Compare commits

...
Author SHA1 Message Date
shaggyandClaude Opus 5 517e1adad3 test(kbn-101-02a): resolve tsx CLI directly, exact dev:local contract, honest timeout bound
Three reviewer blockers, all verified against source and by measurement before
acting on them.

C1 — the fixture's `tsx` was `apps/gateway/node_modules/.bin/tsx`, which is not
the TSX CLI but a pnpm-generated /bin/sh launcher that **exports NODE_PATH**
naming four repository module roots into the process it starts. A fixture whose
stated invariant is that the child receives no Node loader controls was shipping
a `tsx` that reinstated one. Resolving `tsx/dist/cli.mjs` directly deletes the
wrapper, the NODE_PATH injection, three coreutils symlinks and an off-PATH
package-layout symlink at once: PATH is now two names, `node` and `tsx`. Targets
are realpath-resolved and asserted to be executable files at module scope,
before the first child, and the symlinks derive from those checked values.
Observed child key set carries neither NODE_PATH nor NODE_OPTIONS.

C3 — the dev:local contract was a substring check followed by arbitrary shell
execution: the manifest case asserted the script *contained* src/local-dev.ts,
and the helper then handed the whole string to `sh -c`. "curl … | sh; tsx
src/local-dev.ts" satisfied it and ran. Now one module constant spelled once,
asserted with equality in the manifest case and re-asserted in the executing
helper against the value about to run. No metacharacter denylist — equality
already excludes them, and a denylist here would repeat the mistake the PATH
allowlist was built to correct.

C2 — the timeout bound is corrected rather than closed. `exec` removes the outer
shell, but the required route is itself multi-process: TSX spawns an esbuild
service child and a loader/eval child, and the latter is where route code runs.
Measured six out of six times under this exact spawn shape, that child survives
SIGKILL to its TSX parent, is reparented, and completes its work afterward —
while sandbox teardown removes directories it still holds. So exact equality
plus `exec` prohibits *injected* shell content and does not close the gap; the
launcher the contract *permits* is the one that leaks. The timeout control is
named and commented for the single-process property it actually measures and is
not offered as containment evidence.

Containment design is at architecture adjudication and is deliberately not
implemented here: every process in the TSX tree runs in the verifier's own
process group and session, so the obvious repair would signal the test runner.

RED unchanged: 83 failed | 17 passed -> 83 failed | 18 passed (101), the one
added case being the timeout control passing as a harness control. Prettier,
tsc and ESLint clean; zero /tmp/kbn-02a-* residue; casts unchanged at six.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ESFAnh2t9HmLwng8oW95St
2026-08-13 00:57:05 -05:00
shaggy a266c88b7f test(gateway): make the KBN-101-02a child PATH an allowlist and enumerate it
PATH was the last part of the child environment still built as a denylist:
the two workspace node_modules/.bin directories, dirname(process.execPath)
and the shell's directory. Measured on this host that is 4,093 distinct
executable names, and apps/gateway/node_modules/.bin carries real agent
runtimes this repo depends on directly — pi (@mariozechner/pi-coding-agent),
pi-ai, openai, anthropic-ai-sdk. The comment on that construction claimed it
prevented an unrelated same-name executable from answering, which is the
resolution it permitted.

PATH is now one fixture-owned directory in the per-run sandbox holding only
symlinks: node, tsx, and dirname/sed/uname (the pnpm tsx launcher is a
/bin/sh script that calls all three to locate its own entrypoint). The
launcher's relative ../tsx/dist/cli.mjs lookup is served by one directory
symlink inside the sandbox, off PATH. The shell is invoked absolutely and
needs no entry; env needs none because the shebang invokes it absolutely.

The fixture control now enumerates the directories on the child's observed
PATH and asserts the reachable executable names EQUAL the allowlist. The
seven harness-name assertions are kept and commented redundant-by-design: a
name enumeration finds pi and misses the other three actually present, which
is the empirical argument against the denylist shape. Symlink targets are
asserted to resolve to the exact expected binaries.

Measured: 4,093 -> 5 reachable names; `command -v pi` resolves the real
.bin/pi under the old construction and is not-found under the new one;
`tsx --version` still succeeds on the narrowed PATH.

Bounds recorded rather than overclaimed: this narrows command resolution,
not module resolution — the tsx launcher exports NODE_PATH naming four real
repository module roots, the last exposing 775 packages including the same
agent runtimes. And the shell-arm key-set measurement describes the
control's own arm, not the GREEN route.

RED unchanged: 83 failing / 17 passing (100 cases, 6 files), no Errors row,
zero /tmp/kbn-02a-* residue, dev:local still absent.
2026-08-13 00:17:39 -05:00
shaggy 3d348772ad test(gateway): bound the KBN-101-02a child-env guard's claim instead of escalating it
Three review rounds found the same defect in this guard: the value validated
and the value used came from two different reads. Each repair narrowed the
window and the next round reopened it -- a Proxy, then a getter replacing
Object.keys mid-enumeration. The single-entries-array form closes both, and a
fourth round showed it still is not a proof: the helper calls Object.fromEntries,
map and filter after the enumeration, and a getter can replace any of them.

That is not closable here. These cases share a closure with the guard, so an
author who can patch a global can patch the guard. The escalation is what was
wrong -- the previous round added a caller-supplied callback to the one spawn
site purely to make a mutation proof read better, and it had to be reverted.

So the claim is bounded rather than narrowed again:

- Freeze ALLOWED_CHILD_ENV, DECLARABLE_CASE_ENV_NAMES and SHELL_GENERATED_ENV.
  The name list was mutable; a case could push a forbidden name before
  declaring it. Verified: the push now throws and the spawn is still rejected.
- Say what the guard does. It rejects an ambient copy or a stray name passed
  as a declaration, which is the mistake a maintainer makes by accident. The
  comments claimed it closed the accessor gap; they no longer do.
- Correct the bootstrap() comment: main.ts constructs a logger before the
  secret check. The load-bearing claim -- the throw precedes any config read --
  is unchanged.

Document corrections, all found by review of claims written in earlier rounds:

- Withdraw "no second call to any replaceable global stands between the check
  and the use". False, and stated while correcting a different overclaim.
- Both exploits are rejected, but by different assertions. The ambient copy is
  named by the offending-keys message; the Proxy is stopped one assertion
  earlier by isProxy, whose message names no keys.
- The sandbox is created in spawnHermetic before the spawn call, not inside
  the spawn arguments. main.spec.ts:58 cleans up in a finally rather than by
  registration, outside the kbn-02a- prefix the residue count measures.
- The package.json RED does not execute the route yet: the script is absent, so
  the case stops on the missing manifest entry before any child is created.
- Three route cases, not two. Four XDG_*_HOME roots plus XDG_RUNTIME_DIR, not
  "five XDG home roots". Not every failure is behavioral -- the structural
  source guards are counted in the same 83.

RED unchanged: 83 failing / 17 passing (100 cases, 6 files), no Errors row,
zero /tmp/kbn-02a-* residue, fixture control green. Typecheck, lint, Prettier
clean.
2026-08-12 23:52:40 -05:00
shaggy ccb5913620 test(gateway): make the KBN-101-02a child-process fixture hermetic by allowlist
The dev:local route case built its child environment as a denylist — copy the
ambient process.env, delete three keys — leaving the real HOME, every XDG root,
MOSAIC_GATEWAY_HOME, service endpoints, auth/credential families, the Node
loader controls and an ambient PATH in place. A faulty GREEN could read real
host state before an assertion caught it, and a refusal could be produced by
the host's own configuration rather than by the route, so the case would pass
while proving nothing about the code under test. The hard timeout bounds how
long a leak runs; it does not prevent one.

The child now receives exactly eight variables built from scratch — a private
HOME under a per-run temporary sandbox, all five XDG roots and TMPDIR beneath
it, and a PATH built from the two workspace .bin directories and the directory
of the running Node binary — plus the per-case declarations. Nothing is
inherited.

Two cases hold that rather than assume it: a fixture control asserting the
constructed key set, that HOME is neither the real home nor an ancestor of it,
and that PATH is the three intended directories (green by construction, a
harness negative control, not coverage); and an executed case that plants a
complete valid local declaration and a forbidden DSN in the parent environment
and requires the undeclared refusal — a leaky fixture would fire the DSN
refusal instead.

RED only. 83 failing / 17 passing (100 cases, 6 files), Errors 0, zero
/tmp/kbn-02a-* residue. No GREEN, no push, no 17th fenced path.
2026-08-12 22:03:03 -05:00
shaggy bdcdff5e31 test(gateway): KBN-101-02a RED — positive anchors, owned exit, classified readability
Second AMEND from the verifier. Five blockers, all inside the 16-path fence; no
new path taken and no GREEN implemented.

1. The run carried an out-of-band `process.exit unexpectedly called with "1"`,
   raised by main.ts:71 self-invoking on import and rejecting after the importing
   case had returned. Vitest attributes that to no case and warns it can produce
   false positives; it also falsified the document's "zero non-assertion
   failures". The import is now wrapped so `process.exit` is stubbed
   non-throwing and the case awaits a settle turn — the behavioral red is
   unchanged, the error is owned, and the run reports `Errors 0`.

2. Two inventory cases demanded the raw values 'standalone' and 'postgres',
   which the value-free classification unions cannot represent, so no compliant
   implementation could have turned them green. They assert 'non-local' and
   'non-pglite'.

3. SourceReadability gained `absent`. Without it an absent source has to be
   reported `readable` — the one value meaning "read, and clean" — collapsing
   the distinction the refusal path is built on. The invariant
   `present === false` iff `readability === 'absent'` is now asserted per state
   and across all seven rows at once.

4. Acceptance #6 had no positive anchor: an empty `bootstrap()` and an
   always-refusing `onModuleInit()` satisfied every case, so "safe" could have
   meant "does not work". Two cases now fail against that — bootstrap must reach
   NestFactory.create and listen under the frozen policy with zero independent
   read, and the sterile local lifecycle must actually run both migrations with
   no Postgres handle. Both in-process and substituted at their seams; no port
   is bound and nothing connects.

5. Every mkdtemp site in the six files now registers teardown at the point of
   creation, including the child route's root created inside the spawn
   arguments. The matrix leaves zero /tmp/kbn-02a-* residue, measured.

Focused matrix: 82 failing / 16 passing (98 cases, 6 files), Errors 0.
Typecheck, lint, Prettier, diff --check clean.
2026-08-12 21:39:20 -05:00
shaggy 1a77739410 test(gateway): KBN-101-02a RED supplement — close the verifier's twelve findings
Author phase only; still no implementation. Kept as a distinct fifth commit so
the RED baseline, the contract restoration, the span audit and this supplement
remain separately reviewable.

The finding that mattered: every frozen-policy case mocked ./main.js wholesale,
so nothing executed main.ts, AppModule or the ConfigModule provider, and the
three independent reads at main.ts:28, app.module.ts:39 and config.module.ts:12
could all have survived a fully green matrix. Fence revision 15 -> 16 (granted
solely for apps/gateway/src/main.spec.ts) is used to import the real modules
with no ./main.js mock and assert no independent loadConfig, no tier probe and
no NestFactory.create. The existing anchoring case is left red-in-place rather
than deleted: its import-time-exit premise is the opposite of the new contract,
so it must be migrated by whoever implements GREEN.

Also closes: the executed dev:local child-process route, which requires a
LOCAL_START_* code AND the absence of the BETTER_AUTH_SECRET throw, since a
nonzero exit alone is satisfied by a crash; the real database onModuleInit
lifecycle, asserting migrations never run; the full disposable state-root
contract (absent, not-a-directory, symlink, non-private, foreign-owner), with
ownership substituted at lstat because a filesystem-built case passes trivially
wherever CI runs as root; unreadable and malformed sources, which refuse rather
than being skipped, built as EISDIR so they cannot be vacuous under any uid;
per-source non-local tier detection for all seven labels; canary retention and
console cases; post-freeze source-mutation cases; and a three-form static-import
guard.

Two defects of my own are fixed rather than papered over. The non-canonical
state-root case normalized to the valid path before the policy saw it, so it
demanded a refusal on input identical to the accepted one — a red that could
never go green for its stated reason. And the first substitution of @nestjs/core
was wholesale, which dropped APP_GUARD and killed app.module.ts at import, so
two cases failed for a reason they did not state.

Classification types are unions, not strings: a declaredTier?: string is
value-free only by convention, and a two-member union cannot carry a canary.

77 failing / 15 passing (92 cases, 6 files). Typecheck, lint and Prettier clean.
Zero non-assertion failures. Seven of the fifteen greens are vacuous against the
stub, up from three; that rise is recorded in the document so it cannot later be
read as coverage. The first RED report's implication that the GREEN targets were
covered behaviorally is corrected there too.

Refs: KBN-101-02a (Stack #1178)
2026-08-12 21:05:24 -05:00
shaggy 09c75f3b10 docs(kbn): downgrade the -05 Dockerfile finding to unresolved planned-vs-current
Scrappy's ruling, verified independently at
docs/scratchpads/771-kbn101-db-role-split.md:98, which records
apps/gateway/Dockerfile explicitly as 'a planned KBN-101-05 artifact'.
The row names something intended to exist, not a mis-naming of
docker/gateway.Dockerfile, so it is not the inverse defect I filed it as.

The correction sharpens the proposed control: a link check failing on any
absent ownership path would have flagged this row and been wrong. The
check needs a planned marker, and an unmarked absent path is the failure.

Negative existence evidence retained; classification corrected.
2026-08-12 20:23:38 -05:00
shaggy 93b81fac96 docs(kbn): file the -02a span audit of every held-until claim
Commissioned with -02a on the board ruling. Four findings: the -02
local-start hold is carried by eight files not five (AGENTS.md and
README.md among them, so -02a's completion surface is wider than its
record); a candidate defect of the same shape at -05, whose scope row
contains neither 'process-exec' nor 'LoadCredential' though three guides
condition deployment on that interface; a negative result confirming the
-00/-03/-05 activation hold spans correctly; and the structural hole that
makes all of them unverifiable, whose inverse form is the -05 rows naming
apps/gateway/Dockerfile, a path that does not exist.

Additive to section 10 only. No other item's rows altered; the Dockerfile
discrepancy is reported, not corrected — that row is -05's.
2026-08-12 20:04:46 -05:00
shaggy a4809d8c52 docs(kbn): restore KBN-101 family contract clobbered by the -02a manifest
b4c468b3 wrote the -02a path-ownership manifest OVER the frozen KBN-101
contract (#774, #902) rather than appending to it, deleting 272 lines
including the KBN-101-05 exclusive-ownership row, the K101-REQ-04
traceability row and the -03 runner/manifest contract.

Sections 1-9 are restored byte-identical to 216cd722. The -02a amendment
is re-added as additive section 10 with its headings demoted. No other
item's ownership rows are altered.

Self-reported to the verifier; the defect class is the same span/scope
failure -02a exists to close.
2026-08-12 20:00:32 -05:00
shaggy b4c468b3e7 test(gateway): KBN-101-02a RED — fail-closed local-start refusal
Author phase only. No implementation: the scaffolding is deliberately
permissive so every refusal assertion fails behaviorally rather than on a
missing module. A `not implemented` throw would have satisfied `.toThrow()`
and produced a green matrix that proved nothing.

Adds the path-ownership manifest and 60 behavioral cases across the nine
mutation->guard rows: inherited env, shared dotenv, daemon JSON, app JSON,
root JSON, MOSAIC_GATEWAY_HOME redirect, exact local tier, exact PGlite plus
disposable state root, and one-shot freeze with dynamic import.

50 red / 10 green. Zero non-assertion failures. The ten greens are itemized
in the manifest, including three that are vacuous until the implementation
exists.

Enforcement sits at the apps/gateway seam. Nothing in packages/db or
packages/config is touched: -02a proves the local entrypoint never reaches
those paths rather than modifying code owned by -01, -03 and -10.

Refs: KBN-101-02a (Stack #1178)
2026-08-12 19:54:24 -05:00
10 changed files with 3887 additions and 1 deletions

No files matched your search

@@ -0,0 +1,305 @@
/**
* KBN-101-02a — DatabaseModule REDs.
*
* This module has no spec today, and it is where the cross-field hazard lands:
* `detectAndAssertTier` early-returns on `tier === 'local'` without inspecting
* `storage.type`, and DatabaseModule then builds a storage adapter from
* `config.storage` independently and migrates it in `onModuleInit`. So
* `tier: local` + `storage.type: postgres` skips the probe and still reaches
* real Postgres DDL.
*
* `@mosaicstack/db` and `@mosaicstack/storage` are mocked, so no real
* PostgreSQL connection can be constructed here even if a guard is missing.
* The mocks are also the instrument.
*
* The providers are exercised through the module's own metadata rather than a
* full Nest bootstrap: the factories are the unit under test, and booting Nest
* would itself be a side effect these cases must prove does not happen.
*/
import 'reflect-metadata';
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const createDbMock = vi.fn(() => ({ db: {}, close: vi.fn() }));
const createPgliteDbMock = vi.fn((dataDir: string) => ({ db: { dataDir }, close: vi.fn() }));
const runPgliteMigrationsMock = vi.fn(async () => {});
const createStorageAdapterMock = vi.fn((_storage?: unknown) => ({
name: 'mock',
migrate: vi.fn(async () => {}),
close: vi.fn(async () => {}),
}));
vi.mock('@mosaicstack/db', () => ({
createDb: createDbMock,
createPgliteDb: createPgliteDbMock,
runPgliteMigrations: runPgliteMigrationsMock,
runMigrations: vi.fn(async () => {}),
}));
vi.mock('@mosaicstack/storage', () => ({
createStorageAdapter: createStorageAdapterMock,
detectAndAssertTier: vi.fn(async () => {}),
TierDetectionError: class TierDetectionError extends Error {},
}));
// Keep the transitive `../env.js` import inert: it calls loadGatewayEnv() as a
// top-level side effect today.
vi.mock('dotenv', () => {
const config = vi.fn(() => ({ parsed: {} }));
return { config, default: { config } };
});
vi.mock('@mosaicstack/config', () => ({
loadConfig: vi.fn(() => ({ tier: 'local', storage: { type: 'pglite' } })),
// env.ts reads `detectFromEnv().tier` at import time, so this must be an
// object — returning undefined turns every case in this file into a setup
// error rather than a behavioral red.
detectFromEnv: vi.fn(() => ({ tier: undefined })),
}));
type AnyProvider = { provide?: unknown; useFactory?: (...args: unknown[]) => unknown };
let envSnapshot: NodeJS.ProcessEnv;
beforeEach(() => {
envSnapshot = { ...process.env };
vi.clearAllMocks();
});
/**
* Disposable fixture roots are removed, not merely created.
*
* A spec that mkdtemps per case and never unlinks leaks one directory per run
* forever; verification runs of this suite left 166 of them on the verifier's
* host. A suite that litters the machine it runs on is not a suite that can
* claim to prove disposability of anything.
*/
const tempRoots: string[] = [];
async function trackTempRoot(path: string): Promise<string> {
tempRoots.push(path);
return path;
}
afterEach(async () => {
process.env = { ...envSnapshot };
vi.resetModules();
while (tempRoots.length > 0) {
const root = tempRoots.pop();
if (root !== undefined) {
await rm(root, { recursive: true, force: true });
}
}
});
async function loadModuleUnderTest(): Promise<{
factoryFor: (token: unknown) => (...args: unknown[]) => unknown;
tokens: { DB_HANDLE: unknown; STORAGE_ADAPTER: unknown };
}> {
const mod = await import('./database.module.js');
const providers = (Reflect.getMetadata('providers', mod.DatabaseModule) ?? []) as AnyProvider[];
return {
tokens: { DB_HANDLE: mod.DB_HANDLE, STORAGE_ADAPTER: mod.STORAGE_ADAPTER },
factoryFor: (token: unknown) => {
const provider = providers.find((candidate) => candidate.provide === token);
expect(provider?.useFactory, 'provider factory not found').toBeDefined();
return provider!.useFactory!;
},
};
}
/** Establish a valid frozen local policy and return its state root. */
async function establishLocalChannel(): Promise<string> {
const tempRoot = await trackTempRoot(await mkdtemp(join(tmpdir(), 'kbn-02a-dbmod-')));
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
const homeBase = join(tempRoot, 'home');
const stateRoot = join(tempRoot, 'session-state');
await mkdir(anchor, { recursive: true });
await mkdir(homeBase, { recursive: true });
await mkdir(stateRoot, { recursive: true });
const { establishFrozenLocalPolicy } = await import('../local-start/local-start-policy.js');
establishFrozenLocalPolicy({
declaration: { tier: 'local', storageType: 'pglite', queueType: 'local', stateRoot },
anchor,
homeBase,
env: {},
});
return stateRoot;
}
describe('KBN-101-02a DatabaseModule — the cross-field hazard', () => {
it('refuses tier local + storage postgres instead of constructing a Postgres adapter', async () => {
vi.resetModules();
await establishLocalChannel();
const { factoryFor, tokens } = await loadModuleUnderTest();
const hazardConfig = {
tier: 'local',
storage: { type: 'postgres', url: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
};
// detectAndAssertTier never sees this shape: it early-returns on tier alone.
expect(() => factoryFor(tokens.STORAGE_ADAPTER)(hazardConfig)).toThrow();
expect(createStorageAdapterMock).not.toHaveBeenCalled();
});
it('refuses tier local + storage postgres in the DB handle factory as well', async () => {
vi.resetModules();
await establishLocalChannel();
const { factoryFor, tokens } = await loadModuleUnderTest();
const hazardConfig = {
tier: 'local',
storage: { type: 'postgres', url: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
};
expect(() => factoryFor(tokens.DB_HANDLE)(hazardConfig)).toThrow();
expect(createDbMock).not.toHaveBeenCalled();
});
it('never calls createDb while the local policy is established', async () => {
vi.resetModules();
await establishLocalChannel();
const { factoryFor, tokens } = await loadModuleUnderTest();
const nonLocal = { tier: 'standalone', storage: { type: 'postgres', url: 'postgresql://x/y' } };
expect(() => factoryFor(tokens.DB_HANDLE)(nonLocal)).toThrow();
expect(createDbMock).not.toHaveBeenCalled();
});
});
describe('KBN-101-02a DatabaseModule — state lives under the declared root', () => {
it('derives the PGlite data dir from the frozen policy, not from homedir()', async () => {
vi.resetModules();
const stateRoot = await establishLocalChannel();
const { factoryFor, tokens } = await loadModuleUnderTest();
factoryFor(tokens.DB_HANDLE)({ tier: 'local', storage: { type: 'pglite' } });
expect(createPgliteDbMock).toHaveBeenCalledTimes(1);
const dataDir = createPgliteDbMock.mock.calls[0]?.[0] as string;
// A homedir()-derived path is neither declared, session-created, nor
// disposable, and it is shared with the daemon install.
expect(dataDir.startsWith(`${stateRoot}/`)).toBe(true);
expect(dataDir).not.toContain('.config/mosaic/gateway/pglite');
});
it('derives the storage adapter data dir from the frozen policy', async () => {
vi.resetModules();
const stateRoot = await establishLocalChannel();
const { factoryFor, tokens } = await loadModuleUnderTest();
factoryFor(tokens.STORAGE_ADAPTER)({ tier: 'local', storage: { type: 'pglite' } });
expect(createStorageAdapterMock).toHaveBeenCalledTimes(1);
const passed = JSON.stringify(createStorageAdapterMock.mock.calls[0]?.[0] ?? {});
expect(passed).toContain(stateRoot);
});
it('reads the frozen policy rather than the injected config in the local channel', async () => {
vi.resetModules();
const stateRoot = await establishLocalChannel();
const { factoryFor, tokens } = await loadModuleUnderTest();
// A config object that disagrees with the frozen policy must not win: the
// policy is the single read, and there is no fallback to an independent one.
factoryFor(tokens.DB_HANDLE)({
tier: 'local',
storage: { type: 'pglite', dataDir: '/somewhere/else' },
});
const dataDir = createPgliteDbMock.mock.calls[0]?.[0] as string;
expect(dataDir.startsWith(`${stateRoot}/`)).toBe(true);
});
});
/**
* The lifecycle, not just the factories.
*
* Provider factories construct handles; `onModuleInit()` is what actually runs
* DDL — `runPgliteMigrations(handle)` and `storageAdapter.migrate()`. A guard
* placed only in the factories leaves that path reachable whenever a handle is
* obtained by any other route, and every case above would stay green. These
* cases drive the lifecycle hook directly.
*/
describe('KBN-101-02a DatabaseModule — migrations are a lifecycle effect, not a factory effect', () => {
interface Handle {
db: unknown;
close: () => void;
}
async function instantiate(config: unknown): Promise<{
instance: { onModuleInit: () => Promise<void> };
adapterMigrate: ReturnType<typeof vi.fn>;
}> {
const mod = await import('./database.module.js');
const adapterMigrate = vi.fn(async () => {});
const handle: Handle = { db: {}, close: vi.fn() };
const adapter = { name: 'mock', migrate: adapterMigrate, close: vi.fn(async () => {}) };
const instance = new mod.DatabaseModule(
handle as never,
adapter as never,
config as never,
) as unknown as { onModuleInit: () => Promise<void> };
return { instance, adapterMigrate };
}
it('refuses to migrate a postgres storage shape while the local policy is established', async () => {
vi.resetModules();
await establishLocalChannel();
const { instance, adapterMigrate } = await instantiate({
tier: 'local',
storage: { type: 'postgres', url: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
});
await expect(instance.onModuleInit()).rejects.toThrow(/LOCAL_START_/);
expect(adapterMigrate, 'storage migrate() ran on a refusing start').not.toHaveBeenCalled();
expect(runPgliteMigrationsMock).not.toHaveBeenCalled();
});
it('refuses to migrate a non-local tier while the local policy is established', async () => {
vi.resetModules();
await establishLocalChannel();
const { instance, adapterMigrate } = await instantiate({
tier: 'standalone',
storage: { type: 'pglite' },
});
await expect(instance.onModuleInit()).rejects.toThrow(/LOCAL_START_/);
expect(adapterMigrate).not.toHaveBeenCalled();
expect(runPgliteMigrationsMock).not.toHaveBeenCalled();
});
// Acceptance #6 — the positive anchor, and the only case in this file that is
// not a refusal.
//
// A refusal-only matrix is fully satisfied by an onModuleInit() that always
// throws. Dead production behavior and correct fail-closed behavior would be
// indistinguishable, and the item would ship having made local start safe by
// making it not work. The previous case here swallowed the error
// (`.catch(() => undefined)`) and then asserted zero migration, so it was
// satisfied by the same dead implementation it was supposed to exclude.
//
// This is the case that fails if the sterile local route stops working.
it('completes the sterile local lifecycle: PGlite and adapter migrations both run, no Postgres seam', async () => {
vi.resetModules();
await establishLocalChannel();
const { instance, adapterMigrate } = await instantiate({
tier: 'local',
storage: { type: 'pglite' },
});
await expect(instance.onModuleInit()).resolves.toBeUndefined();
expect(runPgliteMigrationsMock, 'the sterile local route never migrated').toHaveBeenCalled();
expect(adapterMigrate, 'the local storage adapter was never migrated').toHaveBeenCalled();
expect(
createDbMock,
'a Postgres handle was constructed on the sterile local route',
).not.toHaveBeenCalled();
});
});
+173
View File
@@ -0,0 +1,173 @@
/**
* KBN-101-02a — env.ts REDs.
*
* `loadGatewayEnv()` runs today as an unconditional top-level module side
* effect (`env.ts` last line), so merely importing this module loads dotenv
* files and re-reads configuration. Inside the local channel that is a second,
* independent read behind the frozen policy's back.
*
* Two signals are distinguished deliberately, because they fire under different
* conditions and a case that asserts the wrong one cannot fail for its stated
* reason:
* - `dotenv.config()` fires ONLY when the dotenv file exists, so any case
* about it plants a real fixture under a temp anchor;
* - `loadConfig()` fires unconditionally, so it is the signal for the
* import-time side effect at the real anchors.
*
* The final describe block is a legacy-channel regression guard and passes
* before implementation. It is not claimed as a RED.
*/
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const FORBIDDEN_DSN = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
const dotenvConfigMock = vi.fn((_options?: unknown) => ({ parsed: {} }));
const loadConfigMock = vi.fn(() => ({
tier: 'local',
storage: { type: 'pglite' },
queue: { type: 'local' },
}));
const detectFromEnvMock = vi.fn(() => ({ tier: undefined }));
vi.mock('dotenv', () => ({ config: dotenvConfigMock, default: { config: dotenvConfigMock } }));
vi.mock('@mosaicstack/config', () => ({
loadConfig: loadConfigMock,
detectFromEnv: detectFromEnvMock,
}));
let envSnapshot: NodeJS.ProcessEnv;
beforeEach(() => {
envSnapshot = { ...process.env };
vi.clearAllMocks();
});
/** Temp roots created by makeBed, removed after every case. */
const tempRoots: string[] = [];
afterEach(async () => {
process.env = { ...envSnapshot };
for (const root of tempRoots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
vi.resetModules();
});
interface Bed {
anchor: string;
homeBase: string;
stateRoot: string;
}
async function makeBed(): Promise<Bed> {
const tempRoot = await mkdtemp(join(tmpdir(), 'kbn-02a-env-'));
tempRoots.push(tempRoot);
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
const homeBase = join(tempRoot, 'home');
const stateRoot = join(tempRoot, 'session-state');
await mkdir(anchor, { recursive: true });
await mkdir(homeBase, { recursive: true });
await mkdir(stateRoot, { recursive: true });
return { anchor, homeBase, stateRoot };
}
/** Plant a dotenv the loader would find, so `config()` can actually fire. */
async function plantDotenv(bed: Bed): Promise<void> {
await writeFile(
join(bed.anchor, '..', '.env'),
`MOSAIC_STORAGE_TIER=standalone\nDATABASE_URL=${FORBIDDEN_DSN}\n`,
'utf8',
);
}
async function establishLocalChannel(bed: Bed): Promise<void> {
const { establishFrozenLocalPolicy } = await import('./local-start/local-start-policy.js');
establishFrozenLocalPolicy({
declaration: {
tier: 'local',
storageType: 'pglite',
queueType: 'local',
stateRoot: bed.stateRoot,
},
anchor: bed.anchor,
homeBase: bed.homeBase,
env: {},
});
}
describe('KBN-101-02a env.ts — inert inside the local channel', () => {
it('performs no configuration re-read on import when the frozen local policy is established', async () => {
vi.resetModules();
const bed = await makeBed();
await establishLocalChannel(bed);
await import('./env.js');
// The frozen policy is the only read in the local channel. This one fires
// unconditionally today, from the module's top-level side effect.
expect(loadConfigMock).not.toHaveBeenCalled();
});
it('loads no dotenv file when called under the frozen local policy', async () => {
vi.resetModules();
const bed = await makeBed();
await plantDotenv(bed);
await establishLocalChannel(bed);
const mod = await import('./env.js');
dotenvConfigMock.mockClear();
loadConfigMock.mockClear();
mod.loadGatewayEnv(bed.anchor, bed.homeBase);
// The guard lives inside loadGatewayEnv, not at its call site: a caller
// anywhere in the local channel must not be able to reintroduce the load.
expect(dotenvConfigMock).not.toHaveBeenCalled();
expect(loadConfigMock).not.toHaveBeenCalled();
});
it('does not repopulate the ambient environment from a planted dotenv under the local policy', async () => {
vi.resetModules();
const bed = await makeBed();
await plantDotenv(bed);
await establishLocalChannel(bed);
const mod = await import('./env.js');
dotenvConfigMock.mockClear();
mod.loadGatewayEnv(bed.anchor, bed.homeBase);
// A dotenv load here would repopulate process.env from files the policy
// already inspected and refused to be governed by.
const loadedPaths = dotenvConfigMock.mock.calls.map((call) => JSON.stringify(call[0] ?? null));
expect(loadedPaths).toEqual([]);
});
});
describe('KBN-101-02a env.ts — legacy channel unchanged (regression guard, not a RED)', () => {
it('still performs its configuration read on import when no local policy is established', async () => {
vi.resetModules();
await import('./env.js');
expect(loadConfigMock).toHaveBeenCalled();
});
it('still loads a planted dotenv when no local policy is established', async () => {
vi.resetModules();
const bed = await makeBed();
await plantDotenv(bed);
const mod = await import('./env.js');
dotenvConfigMock.mockClear();
mod.loadGatewayEnv(bed.anchor, bed.homeBase);
expect(dotenvConfigMock).toHaveBeenCalled();
});
});
+907
View File
@@ -0,0 +1,907 @@
/**
* KBN-101-02a — local-dev entrypoint REDs.
*
* Covers mutation->guard row 9 (one-shot freeze + dynamic import) and the
* zero-side-effect bars Z1-Z5.
*
* `@mosaicstack/db`, `@mosaicstack/storage` and `@nestjs/core` are mocked here,
* so no real PostgreSQL connection can be constructed by this file even if a
* guard is missing. The mocks are also the instrument: a refusing case proves
* zero calls to each.
*/
import { spawnSync } from 'node:child_process';
import {
accessSync,
constants as fsConstants,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
realpathSync,
statSync,
symlinkSync,
} from 'node:fs';
import { readFile, mkdtemp, realpath, rm } from 'node:fs/promises';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { types as utilTypes } from 'node:util';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as LocalDevNamespace from './local-dev.js';
const FORBIDDEN_DSN = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
const HERE = fileURLToPath(new URL('.', import.meta.url));
const REQUIRED_DEV_LOCAL_SCRIPT = 'exec tsx src/local-dev.ts';
// --- Z1-Z5 instruments. Nothing real is reachable through these. -------------
const bootstrapMock = vi.fn(async () => {});
const detectAndAssertTierMock = vi.fn(async () => {});
const createDbMock = vi.fn(() => {
throw new Error('createDb must not be reached from the local channel');
});
const createStorageAdapterMock = vi.fn(() => {
throw new Error('createStorageAdapter must not be reached from the local channel');
});
const runMigrationsMock = vi.fn(async () => {});
const nestFactoryCreateMock = vi.fn(async () => ({ listen: vi.fn() }));
vi.mock('./main.js', () => ({ bootstrap: bootstrapMock }));
vi.mock('@mosaicstack/db', () => ({
createDb: createDbMock,
createPgliteDb: vi.fn(() => ({ db: {}, close: vi.fn() })),
runMigrations: runMigrationsMock,
runPgliteMigrations: vi.fn(async () => {}),
}));
vi.mock('@mosaicstack/storage', () => ({
createStorageAdapter: createStorageAdapterMock,
detectAndAssertTier: detectAndAssertTierMock,
TierDetectionError: class TierDetectionError extends Error {},
}));
vi.mock('@nestjs/core', () => ({
NestFactory: { create: nestFactoryCreateMock },
}));
const SIDE_EFFECT_MOCKS = {
'detectAndAssertTier (tier probe)': detectAndAssertTierMock,
createDb: createDbMock,
'createStorageAdapter (PostgresAdapter construction)': createStorageAdapterMock,
runMigrations: runMigrationsMock,
'NestFactory.create': nestFactoryCreateMock,
};
/** Z1-Z5: a refusing case reaches none of these. */
function expectZeroSideEffects(): void {
for (const [name, mock] of Object.entries(SIDE_EFFECT_MOCKS)) {
expect(mock, `${name} was reached on a refusing start`).not.toHaveBeenCalled();
}
}
let envSnapshot: NodeJS.ProcessEnv;
/**
* Every temp root this file creates, removed after the case that made it.
*
* Both the in-process beds and the child-process route beds register here. The
* child route's sandbox is created synchronously in `spawnHermetic`, immediately
* before the child is spawned.
*/
const tempRoots: string[] = [];
beforeEach(() => {
envSnapshot = Object.assign({}, process.env);
vi.clearAllMocks();
});
afterEach(async () => {
process.env = { ...envSnapshot };
for (const root of tempRoots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
vi.resetModules();
});
type LocalDevModule = typeof LocalDevNamespace;
/** A state root for the executed child route, registered for teardown. */
function makeRouteStateRoot(): string {
const root = mkdtempSync(join(tmpdir(), 'kbn-02a-route-'));
tempRoots.push(root);
return root;
}
async function freshLocalDev(): Promise<LocalDevModule> {
vi.resetModules();
return import('./local-dev.js');
}
/** A well-formed local declaration, planted in the ambient environment. */
async function declareAdmissibleLocalStart(mod: LocalDevModule): Promise<string> {
const stateRoot = await realpath(await mkdtemp(join(tmpdir(), 'kbn-02a-localdev-')));
tempRoots.push(stateRoot);
process.env[mod.LOCAL_DEV_TIER_VAR] = 'local';
process.env[mod.LOCAL_DEV_STORAGE_VAR] = 'pglite';
process.env[mod.LOCAL_DEV_QUEUE_VAR] = 'local';
process.env[mod.LOCAL_DEV_STATE_ROOT_VAR] = stateRoot;
return stateRoot;
}
describe('KBN-101-02a local-dev — row 9, import order is structural', () => {
it('does not statically import main.js: the module able to start must not load first', async () => {
const source = await readFile(join(HERE, 'local-dev.ts'), 'utf8');
// Both static forms, because they have identical effect and only one of them
// has a `from` clause. A guard written against `import … from './main.js'`
// alone is satisfied by the bare side-effect form `import './main.js'`,
// which loads the module graph just as eagerly — the guard would be green
// while the property it names is false.
const staticBindingImport = /^\s*import\s[^\n]*from\s+['"]\.\/main\.js['"]/m;
const staticSideEffectImport = /^\s*import\s+['"]\.\/main\.js['"]/m;
const staticRequire = /require\(\s*['"]\.\/main\.js['"]\s*\)/;
// A static import would load main.js — and everything it pulls in, up to and
// including the DB client — before the policy exists. "Refused before
// connection" then becomes an assertion rather than a structural property.
expect(staticBindingImport.test(source), 'static binding import of main.js').toBe(false);
expect(staticSideEffectImport.test(source), 'static side-effect import of main.js').toBe(false);
expect(staticRequire.test(source), 'static require of main.js').toBe(false);
});
// The negative guards above are satisfied by a module that never references
// main.js at all. This is the positive half: the dynamic import must exist and
// must sit after the establish call, so removing the establish line cannot
// leave the file passing.
it('places the dynamic import of main.js after the establish call, in source order', async () => {
const source = await readFile(join(HERE, 'local-dev.ts'), 'utf8');
const dynamicImport = source.search(/await\s+import\(\s*['"]\.\/main\.js['"]\s*\)/);
const establish = source.search(/establishFrozenLocalPolicy\s*\(/);
expect(dynamicImport, 'no dynamic import of main.js').toBeGreaterThan(-1);
expect(establish, 'no establishFrozenLocalPolicy call').toBeGreaterThan(-1);
expect(establish).toBeLessThan(dynamicImport);
});
it('dynamically imports main.js', async () => {
const source = await readFile(join(HERE, 'local-dev.ts'), 'utf8');
expect(/await\s+import\(\s*['"]\.\/main\.js['"]\s*\)/.test(source)).toBe(true);
});
it('starts nothing merely by being imported', async () => {
await freshLocalDev();
expect(bootstrapMock).not.toHaveBeenCalled();
expectZeroSideEffects();
});
it('establishes the frozen policy BEFORE bootstrap is imported and called', async () => {
const mod = await freshLocalDev();
await declareAdmissibleLocalStart(mod);
const { getFrozenLocalPolicy } = await import('./local-start/local-start-policy.js');
let policyAtBootstrap: unknown;
bootstrapMock.mockImplementationOnce(async () => {
policyAtBootstrap = getFrozenLocalPolicy();
});
await mod.runLocalDev();
expect(bootstrapMock).toHaveBeenCalledTimes(1);
expect(policyAtBootstrap, 'bootstrap ran before the policy was established').toBeDefined();
});
});
describe('KBN-101-02a local-dev — refusal reaches nothing', () => {
it('refuses an inherited PostgreSQL DSN and never calls bootstrap', async () => {
const mod = await freshLocalDev();
await declareAdmissibleLocalStart(mod);
process.env['DATABASE_URL'] = FORBIDDEN_DSN;
await expect(mod.runLocalDev()).rejects.toThrow(/LOCAL_START_POSTGRES_DSN_PRESENT/);
expect(bootstrapMock).not.toHaveBeenCalled();
expectZeroSideEffects();
});
it('refuses a non-local tier declared to the local entrypoint', async () => {
const mod = await freshLocalDev();
await declareAdmissibleLocalStart(mod);
process.env[mod.LOCAL_DEV_TIER_VAR] = 'standalone';
await expect(mod.runLocalDev()).rejects.toThrow(/LOCAL_START_NON_LOCAL_TIER/);
expect(bootstrapMock).not.toHaveBeenCalled();
expectZeroSideEffects();
});
it('refuses a non-pglite storage declared to the local entrypoint', async () => {
const mod = await freshLocalDev();
await declareAdmissibleLocalStart(mod);
process.env[mod.LOCAL_DEV_STORAGE_VAR] = 'postgres';
await expect(mod.runLocalDev()).rejects.toThrow(/LOCAL_START_STORAGE_NOT_PGLITE/);
expect(bootstrapMock).not.toHaveBeenCalled();
expectZeroSideEffects();
});
it('refuses when no state root is declared rather than defaulting to HOME', async () => {
const mod = await freshLocalDev();
await declareAdmissibleLocalStart(mod);
delete process.env[mod.LOCAL_DEV_STATE_ROOT_VAR];
await expect(mod.runLocalDev()).rejects.toThrow(/LOCAL_START_STATE_ROOT_MISSING/);
expect(bootstrapMock).not.toHaveBeenCalled();
expectZeroSideEffects();
});
it('refuses a second run in the same process: the freeze is one-shot', async () => {
const mod = await freshLocalDev();
await declareAdmissibleLocalStart(mod);
await mod.runLocalDev();
await expect(mod.runLocalDev()).rejects.toThrow(/LOCAL_START_ALREADY_ESTABLISHED/);
expect(bootstrapMock).toHaveBeenCalledTimes(1);
});
it('does not leak the offending value in the refusal', async () => {
const mod = await freshLocalDev();
await declareAdmissibleLocalStart(mod);
process.env['DATABASE_URL'] = FORBIDDEN_DSN;
let thrown: unknown;
try {
await mod.runLocalDev();
} catch (error) {
thrown = error;
}
expect(thrown, 'the start was admitted with a DSN present').toBeInstanceOf(Error);
expect((thrown as Error).message).not.toContain(FORBIDDEN_DSN);
expect((thrown as Error).message).not.toContain('mosaic:mosaic');
});
});
describe('KBN-101-02a local-dev — the channel has its own command', () => {
it('exposes a dev:local package script pointed at the local entrypoint', async () => {
const manifest = JSON.parse(await readFile(join(HERE, '..', 'package.json'), 'utf8')) as {
scripts?: Record<string, string>;
};
// The discriminator is the entrypoint itself, so it needs its own command.
// Without one, "start locally" remains a flag on the shared command, which
// is the shape this item exists to remove.
const devLocal = manifest.scripts?.['dev:local'];
expect(devLocal, 'no dev:local script').toBeDefined();
expect(devLocal).toBe(REQUIRED_DEV_LOCAL_SCRIPT);
});
it('leaves the production-like dev script untouched', async () => {
const manifest = JSON.parse(await readFile(join(HERE, '..', 'package.json'), 'utf8')) as {
scripts?: Record<string, string>;
};
expect(manifest.scripts?.['dev']).toBe('tsx watch src/main.ts');
});
});
/**
* The package script, executed rather than read.
*
* The exact script assertion above is satisfied by a `dev:local` route using the
* required exec form pointed at a module that exports `runLocalDev()` and never
* calls it - which is exactly what this file is today: running that command
* right now exits 0 having started nothing and refused nothing. A route that
* silently succeeds is worse than one that is missing, because the operator's
* shell says it worked.
*
* Safety of running the real route in-band: the child inherits nothing and
* receives only the base allowlist plus names a case explicitly declares. No
* case declares BETTER_AUTH_SECRET; the DSN route case deliberately declares
* DATABASE_URL. If a future GREEN wrongly reached `main.ts`, `bootstrap()`
* constructs its logger, then throws on the missing secret before `loadConfig()`
* and before `detectAndAssertTier()` — so no configuration
* is read, no connection is attempted, and nothing listens. The assertions below
* treat that path as a FAILURE rather than a pass, so it cannot be mistaken for
* a refusal.
*
* The child's environment is an ALLOWLIST, and that is the load-bearing part.
* It was a denylist — copy `process.env`, drop three keys — which left the real
* `HOME`, every XDG root, `MOSAIC_GATEWAY_HOME`, service endpoints, auth and
* credential families, and the Node loader controls in place. Two things follow
* from that, and both are worse than a missing case. A faulty GREEN could read
* real host state before any assertion caught it, which is the same defect that
* makes an unhermetic fixture unable to certify what it claims. And a refusal
* could be produced by the host's own configuration rather than by the route,
* so the case would pass while proving nothing about the code under test. A
* denylist is only as good as the enumeration of what is dangerous, which is
* unbounded; an allowlist is bounded by what the route actually needs.
*/
describe('KBN-101-02a local-dev — the package route refuses, not merely the module', () => {
const GATEWAY_DIR = join(HERE, '..');
const CHILD_TIMEOUT_MS = 120_000;
const REPO_ROOT = join(GATEWAY_DIR, '..', '..');
/**
* The POSIX shell the packaged route is executed through, as a validated
* absolute path.
*
* The shell is not resolved through `PATH`. It is invoked by this validated
* absolute path, so it does not need an entry in the fixture-owned command
* directory. Widening `PATH` to find a shell would reopen the executable-
* resolution hole the allowlist exists to close.
*/
function resolveTrustedShell(): string {
for (const candidate of ['/bin/sh', '/usr/bin/sh']) {
if (existsSync(candidate) && statSync(candidate).isFile()) {
return candidate;
}
}
throw new Error('no trusted POSIX shell found at /bin/sh or /usr/bin/sh');
}
const TRUSTED_SHELL = resolveTrustedShell();
function resolveTsxExecutable(): string {
const candidates = [
join(GATEWAY_DIR, 'node_modules', 'tsx', 'dist', 'cli.mjs'),
join(REPO_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs'),
];
for (const candidate of candidates) {
if (existsSync(candidate)) {
return candidate;
}
}
throw new Error(`tsx CLI was not found at either candidate: ${candidates.join(', ')}`);
}
function validatePathCommandTarget(name: string, target: string): string {
const resolved = realpathSync(target);
if (!existsSync(resolved)) {
throw new Error(`${name} PATH target does not exist after realpath: ${resolved}`);
}
if (!statSync(resolved).isFile()) {
throw new Error(`${name} PATH target is not a file: ${resolved}`);
}
accessSync(resolved, fsConstants.X_OK);
return resolved;
}
const PATH_COMMAND_TARGETS = Object.freeze({
node: validatePathCommandTarget('node', process.execPath),
tsx: validatePathCommandTarget('tsx', resolveTsxExecutable()),
});
const PATH_COMMAND_NAMES = Object.freeze(Object.keys(PATH_COMMAND_TARGETS).sort());
/**
* Every variable name the child is permitted to receive, before the per-case
* declarations are layered on.
*/
const ALLOWED_CHILD_ENV = Object.freeze([
'HOME',
'PATH',
'TMPDIR',
'XDG_CACHE_HOME',
'XDG_CONFIG_DIRS',
'XDG_CONFIG_HOME',
'XDG_DATA_DIRS',
'XDG_DATA_HOME',
'XDG_RUNTIME_DIR',
'XDG_STATE_HOME',
]);
/**
* Names a POSIX shell sets for itself. They are derived from the invocation —
* `PWD` from `cwd`, `SHLVL` from a counter, `_` from the last word of the
* command — not inherited from this process, so they carry no host state. They
* are enumerated rather than tolerated: an unexpected name appearing in a
* shell-mediated child is a leak, and the only way to say that is to say which
* names are not.
*/
const SHELL_GENERATED_ENV = Object.freeze(['IFS', 'OLDPWD', 'PWD', 'SHLVL', '_']);
/**
* The exact route inputs cases may add to the child environment. Adding a new
* name is a deliberate change to this list, not an open-ended prefix match.
*/
const DECLARABLE_CASE_ENV_NAMES = Object.freeze([
'MOSAIC_LOCAL_DEV_TIER',
'MOSAIC_LOCAL_DEV_STORAGE',
'MOSAIC_LOCAL_DEV_QUEUE',
'MOSAIC_LOCAL_DEV_STATE_ROOT',
'DATABASE_URL',
]);
/**
* The complete base environment for one child. Built from nothing; nothing is
* inherited. A case may add only the explicitly declarable route inputs.
*
* `PATH` names one fixture-owned directory containing only `node` and the
* real TSX CLI. The pnpm-generated `.bin/tsx` wrapper is deliberately rejected:
* it injects a Node loader control, and wrapper parity is not a fixture goal.
* This fixture-owned command boundary executes the same TSX CLI directly. Its
* `#!/usr/bin/env node` shebang needs `node` on `PATH`, but `env` needs no entry
* because the shebang invokes it by absolute path.
*
* `XDG_CONFIG_DIRS` and `XDG_DATA_DIRS` are set to private empty directories
* rather than left unset. Unset is not neutral for the XDG directory *lists*:
* they default to `/etc/xdg` and `/usr/local/share:/usr/share`, so leaving
* them out would have left two real system config/data roots readable while
* the eight-key set claimed full isolation. Empty *strings* would not do
* either — the specification says a set-but-empty list falls back to the same
* defaults, so the value has to be a real directory that happens to be empty.
*/
function buildHermeticChildEnv(
sandbox: string,
extraEnv: Record<string, string> = {},
): Record<string, string> {
const home = join(sandbox, 'home');
const base: Record<string, string> = {
HOME: home,
// Every XDG root, not only the config one. Leaving any of them ambient
// leaves a real directory the child can read or write.
XDG_CONFIG_HOME: join(home, '.config'),
XDG_DATA_HOME: join(home, '.local', 'share'),
XDG_STATE_HOME: join(home, '.local', 'state'),
XDG_CACHE_HOME: join(home, '.cache'),
XDG_RUNTIME_DIR: join(sandbox, 'run'),
XDG_CONFIG_DIRS: join(sandbox, 'xdg', 'config-dirs'),
XDG_DATA_DIRS: join(sandbox, 'xdg', 'data-dirs'),
TMPDIR: join(sandbox, 'tmp'),
PATH: join(sandbox, 'bin'),
};
return { ...base, ...extraEnv };
}
/** A private root for one child run: home, XDG trees, tmp, runtime dir, bin. */
function makeChildSandbox(): string {
const sandbox = mkdtempSync(join(tmpdir(), 'kbn-02a-child-'));
tempRoots.push(sandbox);
for (const relative of [
join('home', '.config'),
join('home', '.local', 'share'),
join('home', '.local', 'state'),
join('home', '.cache'),
'run',
'tmp',
join('xdg', 'config-dirs'),
join('xdg', 'data-dirs'),
'bin',
]) {
mkdirSync(join(sandbox, relative), { recursive: true });
}
const sandboxBin = join(sandbox, 'bin');
for (const [name, target] of Object.entries(PATH_COMMAND_TARGETS)) {
symlinkSync(target, join(sandboxBin, name));
}
return sandbox;
}
function enumerateExecutablePathEntries(pathValue: string): Array<{
directory: string;
name: string;
path: string;
}> {
const entries: Array<{ directory: string; name: string; path: string }> = [];
for (const directory of pathValue.split(':')) {
for (const name of readdirSync(directory)) {
const path = join(directory, name);
try {
accessSync(path, fsConstants.X_OK);
if (statSync(path).isFile()) {
entries.push({ directory, name, path });
}
} catch {
// A directory entry that cannot be executed is not reachable as a command.
}
}
}
return entries;
}
/**
* Enumerates a case's declarations once, then validates and snapshots that
* same entry array. The single enumeration removes the double-read that two
* earlier versions had; the exact-name and string-value checks reject ambient
* copies and malformed declarations. A case that patches the globals this
* helper calls, or that writes `process.execPath`, can still make the checked
* value differ from the used value, and nothing here detects that. These cases
* share a closure with the guard, so the guard is maintainer discipline
* enforced mechanically, not a sandbox. `isProxy` is secondary defense.
*/
function snapshotCaseEnv(extraEnv: Record<string, string>): Record<string, string> {
const inputIsProxy = utilTypes.isProxy(extraEnv);
const entries = Object.entries(extraEnv);
const snapshot = Object.fromEntries(entries);
expect(
inputIsProxy,
'extraEnv must not be a Proxy; use a plain record so its validated snapshot is stable',
).toBe(false);
const offendingKeys = entries
.map(([key]) => key)
.filter((key) => !DECLARABLE_CASE_ENV_NAMES.includes(key));
expect(
offendingKeys,
`extraEnv contains undeclarable keys (${offendingKeys.join(', ')}); accepted names are exactly: ${DECLARABLE_CASE_ENV_NAMES.join(', ')}`,
).toEqual([]);
const nonStringKeys = entries
.filter(([, value]) => typeof value !== 'string')
.map(([key]) => key);
expect(
nonStringKeys,
`extraEnv must contain only string values; non-string keys: ${nonStringKeys.join(', ')}`,
).toEqual([]);
return snapshot;
}
/**
* The ONE place a child process is created in this file, and the only place
* its environment is chosen.
*
* That is the point, not tidiness. A control that exercised its own spawn
* would leave the route's spawn free to be reverted to an ambient copy without
* reddening anything, while real host state leaked alongside the expected
* refusal. The single site keeps both arms on one environment builder, and the
* single-enumeration validation of per-case inputs against an exact name list
* rejects an ambient copy passed as a declaration, which is the mistake a
* maintainer actually makes.
*/
function spawnHermetic(
command: string,
args: string[],
extraEnv: Record<string, string> = {},
timeout = CHILD_TIMEOUT_MS,
): {
status: number | null;
signal: NodeJS.Signals | null;
output: string;
sandbox: string;
} {
const extraEnvSnapshot = snapshotCaseEnv(extraEnv);
const sandbox = makeChildSandbox();
const result = spawnSync(command, args, {
cwd: GATEWAY_DIR,
env: buildHermeticChildEnv(sandbox, extraEnvSnapshot),
encoding: 'utf8',
timeout,
killSignal: 'SIGKILL',
});
return {
status: result.status,
signal: result.signal,
output: `${result.stdout ?? ''}${result.stderr ?? ''}`,
sandbox,
};
}
/** A child that reports the environment it was actually given, and exits. */
const ENV_MARKER = 'KBN02A_ENV:';
const ENV_MARKER_SCRIPT = `process.stdout.write(${JSON.stringify(ENV_MARKER)} + JSON.stringify(process.env));`;
function hasOnlyStringValues(value: object): value is Record<string, string> {
return Object.values(value).every((entry) => typeof entry === 'string');
}
function parseObservedEnv(output: string): Record<string, string> {
const at = output.indexOf(ENV_MARKER);
expect(at, `the marker child printed no environment: ${output}`).toBeGreaterThanOrEqual(0);
const parsed: unknown = JSON.parse(output.slice(at + ENV_MARKER.length));
const isRecord = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed);
expect(isRecord, 'the marker child environment must be a non-null, non-array object').toBe(
true,
);
if (!isRecord) {
return {};
}
const nonStringKeys = Object.entries(parsed)
.filter(([, value]) => typeof value !== 'string')
.map(([key]) => key);
expect(
nonStringKeys,
`the marker child environment must contain only string values; non-string keys: ${nonStringKeys.join(', ')}`,
).toEqual([]);
if (!hasOnlyStringValues(parsed)) {
return {};
}
return parsed;
}
function runDevLocal(extraEnv: Record<string, string> = {}): {
status: number | null;
signal: NodeJS.Signals | null;
output: string;
} {
const manifest = JSON.parse(readFileSync(join(GATEWAY_DIR, 'package.json'), 'utf8')) as {
scripts?: Record<string, string>;
};
const script = manifest.scripts?.['dev:local'];
if (typeof script !== 'string') {
expect.fail('the package manifest has no dev:local script yet');
}
expect(
script,
`dev:local must be the exact required route; found ${JSON.stringify(script)}`,
).toBe(REQUIRED_DEV_LOCAL_SCRIPT);
return spawnHermetic(TRUSTED_SHELL, ['-c', script], extraEnv);
}
it('exits nonzero with a refusal code when nothing is declared', () => {
const { status, signal, output } = runDevLocal();
expect(signal, 'the route hung and had to be killed').toBeNull();
expect(status, 'the route exited 0 with nothing declared').not.toBe(0);
// Nonzero alone would be satisfied by a crash, a missing dependency, or the
// BETTER_AUTH_SECRET throw inside bootstrap — all of which mean the refusal
// did NOT happen and the start was merely broken. The code is named exactly:
// any LOCAL_START_* would let an unrelated refusal stand in for this one.
expect(output).toContain('LOCAL_START_TIER_NOT_EXPLICIT');
expect(output, 'exited via bootstrap rather than refusing before it').not.toContain(
'BETTER_AUTH_SECRET',
);
});
it('exits nonzero with a DSN refusal, and echoes no DSN, when one is inherited', () => {
const { status, signal, output } = runDevLocal({
DATABASE_URL: 'postgresql://mosaic:mosaic@localhost:5433/mosaic',
MOSAIC_LOCAL_DEV_TIER: 'local',
MOSAIC_LOCAL_DEV_STORAGE: 'pglite',
MOSAIC_LOCAL_DEV_QUEUE: 'local',
MOSAIC_LOCAL_DEV_STATE_ROOT: makeRouteStateRoot(),
// Declared explicitly rather than inherited: the child receives no
// MOSAIC_* variable this case does not name.
});
expect(signal, 'the route hung and had to be killed').toBeNull();
expect(status).not.toBe(0);
expect(output).toContain('LOCAL_START_POSTGRES_DSN_PRESENT');
expect(output, 'the refusal echoed the DSN it refused').not.toContain('mosaic:mosaic');
});
/**
* A harness control, and the only case in this describe that runs a child at
* RED head. It asserts nothing about the code under test: it asserts that the
* spawn site the route arm depends on delivers the allowlist, measured from
* inside a real child rather than from the object handed to the spawn site.
*
* Measuring the object would not have been enough. Reverting only the route's
* spawn to an ambient copy leaves an assertion on the builder green, and that
* revert is invisible from the outside — the ambient copy strips the planted
* declarations, so the canary below still sees the refusal it expects while
* real host state leaks alongside it. Both observations here go through the
* same single spawn site the route goes through, so no such divergence exists
* to be measured.
*/
it('fixture control: the spawn site delivers exactly the allowlist to a real child', () => {
// Source-text heuristics guard the named import, direct call count, and
// ambient-copy spelling. They cannot see a child created through an
// indirection that this source does not name, so this is not a proof that
// every possible child-process path is covered.
const ownSource = readFileSync(fileURLToPath(import.meta.url), 'utf8');
const spawnIdentifier = ['spawn', 'Sync'].join('');
const childProcessModule = ['node', 'child_process'].join(':');
expect(
ownSource.match(new RegExp(childProcessModule, 'g'))?.length ?? 0,
'the child-process module must appear as exactly one import source',
).toBe(1);
const childProcessImports =
ownSource.match(new RegExp(`^import[^\\n]*['"]${childProcessModule}['"];?$`, 'gm')) ?? [];
expect(
childProcessImports,
'the child-process module must be imported exactly once, using only its named synchronous spawn',
).toEqual([`import { ${spawnIdentifier} } from '${childProcessModule}';`]);
expect(
ownSource.match(new RegExp(`\\b${spawnIdentifier}\\b`, 'g'))?.length ?? 0,
'the synchronous spawn identifier must appear only in its import and single call site',
).toBe(2);
expect(
/\.\.\.process\.env/.test(ownSource),
'a child environment is being built by copying the ambient environment',
).toBe(false);
// Executed directly: no shell, so the child's environment is the builder's
// set exactly.
const direct = spawnHermetic(process.execPath, ['-e', ENV_MARKER_SCRIPT]);
expect(direct.signal, 'the marker child hung').toBeNull();
expect(direct.status, `the marker child failed: ${direct.output}`).toBe(0);
const observed = parseObservedEnv(direct.output);
expect(Object.keys(observed).sort()).toEqual(ALLOWED_CHILD_ENV);
// The real home and the real Mosaic config root are unreachable.
expect(observed['HOME']).not.toBe(homedir());
expect(observed['HOME']?.startsWith(direct.sandbox)).toBe(true);
expect(homedir().startsWith(observed['HOME'] as string)).toBe(false);
for (const value of Object.values(observed)) {
expect(value, `an allowlisted value still points at the real home: ${value}`).not.toContain(
join(homedir(), '.config', 'mosaic'),
);
}
// The XDG directory lists name private empty directories. An unset list
// falls back to system roots, while a non-empty directory can expose
// prepopulated state, so either condition would defeat the isolation.
for (const key of ['XDG_CONFIG_DIRS', 'XDG_DATA_DIRS']) {
const value = observed[key];
const isolationReason = `${key} must name a private empty directory because an unset list or a non-empty directory would expose external state and defeat isolation`;
expect(value?.startsWith(direct.sandbox), isolationReason).toBe(true);
expect(value, isolationReason).toBeDefined();
if (value === undefined) {
continue;
}
expect(existsSync(value), isolationReason).toBe(true);
expect(statSync(value).isDirectory(), isolationReason).toBe(true);
expect(readdirSync(value), isolationReason).toEqual([]);
}
// PATH is the fixture-owned directory, in order, and nothing else.
expect(observed['PATH']?.split(':')).toEqual([join(direct.sandbox, 'bin')]);
const observedPath = observed['PATH'];
expect(observedPath, 'the marker child had no PATH to enumerate').toBeDefined();
if (observedPath === undefined) {
return;
}
const reachable = enumerateExecutablePathEntries(observedPath);
expect([...new Set(reachable.map(({ name }) => name))].sort()).toEqual(PATH_COMMAND_NAMES);
// Redundant by design: exact set equality above catches every added command,
// while these messages identify the agent-runtime hazard that prompted it.
for (const harness of [
'pi',
'pi-ai',
'openai',
'anthropic-ai-sdk',
'claude',
'opencode',
'codex',
]) {
const offenders = reachable.filter(({ name }) => name === harness);
expect(
offenders,
`${harness} is resolvable from fixture PATH in: ${offenders.map(({ directory }) => directory).join(', ')}`,
).toEqual([]);
}
for (const [name, expectedTarget] of Object.entries(PATH_COMMAND_TARGETS)) {
const fixtureCommand = join(direct.sandbox, 'bin', name);
expect(
realpathSync(fixtureCommand),
`${name} did not resolve to the exact expected binary ${expectedTarget}`,
).toBe(realpathSync(expectedTarget));
}
// Executed through the trusted shell, which is the route arm's own shape.
// The shell adds names of its own; the claim is not that the final process
// receives the builder's set exactly, it is that every difference is the
// shell's own bookkeeping and none of it is inherited.
const viaShell = spawnHermetic(TRUSTED_SHELL, [
'-c',
`exec ${JSON.stringify(process.execPath)} -e ${JSON.stringify(ENV_MARKER_SCRIPT)}`,
]);
expect(viaShell.signal, 'the shell-mediated marker child hung').toBeNull();
expect(viaShell.status, `the shell-mediated marker child failed: ${viaShell.output}`).toBe(0);
const shellObserved = parseObservedEnv(viaShell.output);
expect(ALLOWED_CHILD_ENV.filter((key) => !(key in shellObserved))).toEqual([]);
const expectedShellBase = buildHermeticChildEnv(viaShell.sandbox);
for (const key of ALLOWED_CHILD_ENV) {
expect(
shellObserved[key],
`the shell-mediated child changed the builder's value for ${key}`,
).toBe(expectedShellBase[key]);
}
const added = Object.keys(shellObserved).filter((key) => !ALLOWED_CHILD_ENV.includes(key));
expect(
added.filter((key) => !SHELL_GENERATED_ENV.includes(key)),
"the shell-mediated child received a variable that is not the shell's own bookkeeping",
).toEqual([]);
for (const key of added) {
expect(
shellObserved[key],
`a shell-added value points at the real home: ${key}=${shellObserved[key]}`,
).not.toContain(join(homedir(), '.config', 'mosaic'));
}
});
/**
* This control's arm is a single-process `exec node -e` sleeper. For that arm,
* SIGKILL reaches the process that matters and nothing survives to write; the
* two assertions below measure only that. The required route is itself
* multi-process: TSX spawns an esbuild service child and a loader/eval child,
* where the route code runs. Measured six out of six times under this exact
* spawn shape, that loader/eval child survives SIGKILL to its TSX parent, is
* reparented, and completes its work afterward. The exact `dev:local` script
* contract blocks injected shell content, but does not close this gap:
* the permitted launcher can leave a live process holding paths inside a
* sandbox the fixture is removing. Descendant containment is an open question
* deferred to the reviewer; no assertion in this file currently proves it.
*/
it('fixture control: timeout SIGKILLs the single-process arm and it writes no marker afterward', async () => {
const timeoutMs = 200;
const writeDelayMs = 1_000;
const markerName = 'timeout-survivor';
const markerScript =
`const { writeFileSync } = require('node:fs');` +
`setTimeout(() => writeFileSync(process.env.TMPDIR + '/${markerName}', 'SURVIVED'), ${writeDelayMs});`;
const result = spawnHermetic(
TRUSTED_SHELL,
['-c', `exec ${JSON.stringify(process.execPath)} -e ${JSON.stringify(markerScript)}`],
{},
timeoutMs,
);
const marker = join(result.sandbox, 'tmp', markerName);
expect(result.signal, `the timeout did not send SIGKILL: ${result.output}`).toBe('SIGKILL');
await new Promise((resolve) => setTimeout(resolve, writeDelayMs + 250));
expect(existsSync(marker), 'the killed route process survived long enough to write').toBe(
false,
);
});
/**
* The route-arm half of the same obligation, and it is PENDING EXECUTION until
* GREEN. At RED head there is no `dev:local` script, so `runDevLocal` fails on
* the manifest assertion before any child is created — this case is red for
* that reason and its hermeticity claim is not yet measured by it. The control
* above is what is measured today; this is what will measure the route once
* the route exists. Saying otherwise would classify a case that never spawned
* as evidence about a subprocess, which is the same overclaim the vacuous
* greens are itemized to prevent.
*
* What it will then assert: the parent declares a complete, valid local start
* AND a forbidden DSN in its own ambient environment, then runs the route with
* nothing passed in. A leaky fixture would hand the child a valid declaration,
* so the undeclared refusal would not fire — and the DSN would refuse instead,
* which is the discriminator.
*/
it('does not leak the parent ambient environment into the child', () => {
const canaries: Record<string, string> = {
MOSAIC_LOCAL_DEV_TIER: 'local',
MOSAIC_LOCAL_DEV_STORAGE: 'pglite',
MOSAIC_LOCAL_DEV_QUEUE: 'local',
MOSAIC_LOCAL_DEV_STATE_ROOT: makeRouteStateRoot(),
MOSAIC_GATEWAY_HOME: makeRouteStateRoot(),
DATABASE_URL: FORBIDDEN_DSN,
};
const restore = new Map<string, string | undefined>();
for (const [key, value] of Object.entries(canaries)) {
restore.set(key, process.env[key]);
process.env[key] = value;
}
try {
const { status, signal, output } = runDevLocal();
expect(signal, 'the route hung and had to be killed').toBeNull();
expect(status, 'the route exited 0 — it saw the parent declaration').not.toBe(0);
// The exact code, not the family: an unrelated refusal would otherwise
// satisfy a canary whose whole claim is that THIS refusal fired.
expect(output).toContain('LOCAL_START_TIER_NOT_EXPLICIT');
// If either of these fires, the child read the parent's environment.
expect(output, 'the child inherited the parent DSN').not.toContain(
'LOCAL_START_POSTGRES_DSN_PRESENT',
);
expect(output, 'the child inherited the parent DSN').not.toContain('mosaic:mosaic');
expect(output, 'exited via bootstrap rather than refusing before it').not.toContain(
'BETTER_AUTH_SECRET',
);
} finally {
for (const [key, value] of restore) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
}
});
});
+43
View File
@@ -0,0 +1,43 @@
/**
* Local-development entrypoint — KBN-101-02a.
*
* THE channel discriminator. Being this entrypoint is what makes a start a
* local-development start; it is never inferred from tier value or from
* configuration provenance. Its sole contract is local + PGlite, in an
* explicitly declared, session-created, disposable state root.
*
* Import order here is load-bearing. This module statically imports ONLY the
* policy and inventory modules, establishes the frozen policy, and only then
* dynamically imports `bootstrap()` from `main.js`. The modules that are able
* to open a connection are not loaded until the policy has been established —
* which is what makes "refused before connection" a structural property rather
* than an assertion.
*
* RED PHASE SCAFFOLDING. This stub establishes nothing correctly and performs
* no dynamic import, so the behavioral and structural specs fail. Do not read
* this file as the implementation — there is none yet.
*/
import { establishFrozenLocalPolicy } from './local-start/local-start-policy.js';
/** Explicit, session-scoped declarations for this invocation. Nothing defaults. */
export const LOCAL_DEV_TIER_VAR = 'MOSAIC_LOCAL_DEV_TIER';
export const LOCAL_DEV_STORAGE_VAR = 'MOSAIC_LOCAL_DEV_STORAGE';
export const LOCAL_DEV_QUEUE_VAR = 'MOSAIC_LOCAL_DEV_QUEUE';
export const LOCAL_DEV_STATE_ROOT_VAR = 'MOSAIC_LOCAL_DEV_STATE_ROOT';
export async function runLocalDev(): Promise<void> {
// RED-phase stub: establishes via the permissive policy stub and stops. It
// performs no dynamic import of bootstrap, so nothing starts. See header.
establishFrozenLocalPolicy({
declaration: {
tier: process.env[LOCAL_DEV_TIER_VAR],
storageType: process.env[LOCAL_DEV_STORAGE_VAR],
queueType: process.env[LOCAL_DEV_QUEUE_VAR],
stateRoot: process.env[LOCAL_DEV_STATE_ROOT_VAR],
},
anchor: import.meta.dirname,
homeBase: '',
env: process.env,
});
}
@@ -0,0 +1,642 @@
/**
* KBN-101-02a — local-start policy REDs.
*
* Covers mutation->guard rows 7 (exact local tier), 8 (exact PGlite + disposable
* state root), and the freeze half of row 9 (one-shot freeze).
*
* The policy module holds one-shot module state, so every case re-imports it
* through `vi.resetModules()` rather than sharing an established policy.
*
* Nothing here connects to anything. DSN strings are fixture text.
*/
import type * as NodeFs from 'node:fs';
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type * as PolicyNamespace from './local-start-policy.js';
import type {
EstablishInput,
LocalStartDeclaration,
LocalStartRefusalCode,
} from './local-start-policy.js';
import type { LocalStartSourceLabel } from './source-inventory.js';
const FORBIDDEN_DSN = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
type PolicyModule = typeof PolicyNamespace;
/** Fresh module state per case — the freeze is one-shot and has no reset API. */
async function freshPolicy(): Promise<PolicyModule> {
vi.resetModules();
return import('./local-start-policy.js');
}
/** Undo module substitutions so one case's mock cannot leak into the next. */
const mockedFsCases: (() => void)[] = [];
/** Temp roots created by makeBed, removed after every case. */
const tempRoots: string[] = [];
afterEach(async () => {
while (mockedFsCases.length > 0) {
mockedFsCases.pop()?.();
}
for (const root of tempRoots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
vi.resetModules();
});
interface Bed {
tempRoot: string;
anchor: string;
homeBase: string;
stateRoot: string;
}
/** A clean layout: no source carries anything forbidden. */
async function makeBed(): Promise<Bed> {
const tempRoot = await mkdtemp(join(tmpdir(), 'kbn-02a-policy-'));
tempRoots.push(tempRoot);
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
const homeBase = join(tempRoot, 'home');
const stateRoot = join(tempRoot, 'session-state');
await mkdir(anchor, { recursive: true });
await mkdir(homeBase, { recursive: true });
await mkdir(stateRoot, { recursive: true });
return { tempRoot, anchor, homeBase, stateRoot };
}
function validDeclaration(stateRoot: string): LocalStartDeclaration {
return { tier: 'local', storageType: 'pglite', queueType: 'local', stateRoot };
}
function establishInput(bed: Bed, overrides: Partial<EstablishInput> = {}): EstablishInput {
return {
declaration: validDeclaration(bed.stateRoot),
anchor: bed.anchor,
homeBase: bed.homeBase,
env: {},
...overrides,
};
}
/** Assert the call refused, with the exact code, carrying no value. */
async function expectRefusal(
policy: PolicyModule,
input: EstablishInput,
code: LocalStartRefusalCode,
): Promise<void> {
let thrown: unknown;
try {
policy.establishFrozenLocalPolicy(input);
} catch (error) {
thrown = error;
}
expect(thrown, `expected a refusal with code ${code}, got none`).toBeInstanceOf(
policy.LocalStartRefusal,
);
const refusal = thrown as InstanceType<PolicyModule['LocalStartRefusal']>;
expect(refusal.code).toBe(code);
// A refusal that echoed the offending value would move the secret into the
// log, which is the failure this item exists to prevent.
const serialized = `${refusal.message} ${JSON.stringify(refusal.sourceLabels)}`;
expect(serialized).not.toContain(FORBIDDEN_DSN);
expect(serialized).not.toContain('mosaic:mosaic');
}
describe('KBN-101-02a establishFrozenLocalPolicy — row 7, exact local tier', () => {
it('refuses when no tier is declared: absent is not local', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), tier: undefined },
}),
'LOCAL_START_TIER_NOT_EXPLICIT',
);
});
it('refuses an empty tier: empty is not local', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), tier: '' },
}),
'LOCAL_START_TIER_NOT_EXPLICIT',
);
});
it('refuses a declared non-local tier inside the local channel', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), tier: 'standalone' },
}),
'LOCAL_START_NON_LOCAL_TIER',
);
});
it('refuses a near-miss tier: matching is exact, not normalized', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), tier: ' Local ' },
}),
'LOCAL_START_NON_LOCAL_TIER',
);
});
it('refuses a non-local tier found in a source even when the declaration is local', async () => {
const bed = await makeBed();
await writeFile(join(bed.anchor, '..', '.env'), 'MOSAIC_STORAGE_TIER=federated\n', 'utf8');
const policy = await freshPolicy();
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_NON_LOCAL_TIER');
});
it('refuses a PostgreSQL DSN found in a source, naming the source label but not the value', async () => {
const bed = await makeBed();
await writeFile(join(bed.anchor, '..', '.env'), `DATABASE_URL=${FORBIDDEN_DSN}\n`, 'utf8');
const policy = await freshPolicy();
let thrown: unknown;
try {
policy.establishFrozenLocalPolicy(establishInput(bed));
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(policy.LocalStartRefusal);
const refusal = thrown as InstanceType<PolicyModule['LocalStartRefusal']>;
expect(refusal.code).toBe('LOCAL_START_POSTGRES_DSN_PRESENT');
expect(refusal.sourceLabels).toContain('gateway-local-dotenv');
expect(refusal.message).not.toContain(FORBIDDEN_DSN);
});
it('refuses an inherited-environment DSN that precedence would have discarded', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, { env: { DATABASE_URL: FORBIDDEN_DSN } }),
'LOCAL_START_POSTGRES_DSN_PRESENT',
);
});
it('refuses the default DSN constant, which is itself a PostgreSQL DSN', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
// No role classification is attempted: proving a DSN non-superuser requires
// connecting, and connecting is the thing being prevented.
await expectRefusal(
policy,
establishInput(bed, {
env: { DATABASE_URL: 'postgresql://mosaic:mosaic@localhost:5433/mosaic' },
}),
'LOCAL_START_POSTGRES_DSN_PRESENT',
);
});
});
describe('KBN-101-02a establishFrozenLocalPolicy — row 8, PGlite and disposable state root', () => {
it('refuses a non-pglite storage type', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), storageType: 'postgres' },
}),
'LOCAL_START_STORAGE_NOT_PGLITE',
);
});
it('refuses a files storage type: only pglite is admitted, not merely "not postgres"', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), storageType: 'files' },
}),
'LOCAL_START_STORAGE_NOT_PGLITE',
);
});
it('refuses an undeclared storage type rather than defaulting it', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), storageType: undefined },
}),
'LOCAL_START_STORAGE_NOT_PGLITE',
);
});
it('refuses a non-local queue', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), queueType: 'bullmq' },
}),
'LOCAL_START_QUEUE_NOT_LOCAL',
);
});
it('refuses an undeclared state root rather than falling back to HOME or CWD', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: undefined },
}),
'LOCAL_START_STATE_ROOT_MISSING',
);
});
it('refuses an empty state root', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: '' },
}),
'LOCAL_START_STATE_ROOT_MISSING',
);
});
it('refuses a relative state root', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: './local-state' },
}),
'LOCAL_START_STATE_ROOT_NOT_ABSOLUTE',
);
});
// The traversal segment is concatenated, NOT built with join(). `join()`
// normalizes `a/../a` to `a` before the policy is ever called, so a case built
// that way asserts a refusal on a string identical to the valid one — it can
// only be made green by also refusing the valid declaration. A red that cannot
// go green for its stated reason is the same defect class as a green that
// cannot go red.
it('refuses a state root that is not its own canonical form', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
const noncanonical = `${bed.tempRoot}/session-state/../session-state`;
expect(noncanonical).not.toBe(bed.stateRoot);
expect(noncanonical).toContain('/../');
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: noncanonical },
}),
'LOCAL_START_STATE_ROOT_ESCAPES',
);
});
it('refuses a state root that does not exist rather than creating it', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
const absent = join(bed.tempRoot, 'never-created');
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: absent },
}),
'LOCAL_START_STATE_ROOT_ABSENT',
);
});
it('refuses a state root that exists but is a file', async () => {
const bed = await makeBed();
const notADir = join(bed.tempRoot, 'a-file');
await writeFile(notADir, 'not a directory\n', 'utf8');
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: notADir },
}),
'LOCAL_START_STATE_ROOT_NOT_DIRECTORY',
);
});
// lstat, not stat: a stat on a symlinked root reports the TARGET, so every
// later bar would describe a directory the operator never named.
it('refuses a state root that is itself a symlink, even to a valid directory', async () => {
const bed = await makeBed();
const realRoot = join(bed.tempRoot, 'real-root');
await mkdir(realRoot, { recursive: true, mode: 0o700 });
const linkedRoot = join(bed.tempRoot, 'linked-root');
await symlink(realRoot, linkedRoot, 'dir');
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: linkedRoot },
}),
'LOCAL_START_STATE_ROOT_IS_SYMLINK',
);
});
it('refuses a state root readable by group or other', async () => {
const bed = await makeBed();
const shared = join(bed.tempRoot, 'shared-root');
await mkdir(shared, { recursive: true });
await chmod(shared, 0o755);
const policy = await freshPolicy();
await expectRefusal(
policy,
establishInput(bed, {
declaration: { ...validDeclaration(bed.stateRoot), stateRoot: shared },
}),
'LOCAL_START_STATE_ROOT_NOT_PRIVATE',
);
});
// Ownership is the one bar that cannot be built on the filesystem without
// privileges: an unprivileged process cannot chown, and a privileged one owns
// everything it creates, so a filesystem-built case would pass trivially
// wherever CI runs as root. That is a vacuous case, not a cheap one. The stat
// result is therefore substituted directly. This couples the case to the
// mechanism (the implementation must learn ownership from an lstat), which is
// inherent to the bar rather than an accident of this test.
it('refuses a state root owned by another user', async () => {
const bed = await makeBed();
const foreignUid = (process.getuid?.() ?? 0) + 1;
vi.resetModules();
vi.doMock('node:fs', async () => {
const actual = await vi.importActual<typeof NodeFs>('node:fs');
return {
...actual,
lstatSync: (target: string, ...rest: unknown[]) => {
const stats = (
actual.lstatSync as unknown as (...args: unknown[]) => Record<string, unknown>
)(target, ...rest);
if (target === bed.stateRoot) {
return {
...stats,
uid: foreignUid,
isDirectory: () => true,
isSymbolicLink: () => false,
};
}
return stats;
},
};
});
mockedFsCases.push(() => {
vi.doUnmock('node:fs');
});
const policy = await import('./local-start-policy.js');
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_STATE_ROOT_NOT_OWNED');
});
it('refuses when a derived child escapes the state root through a symlink', async () => {
const bed = await makeBed();
const escapeTarget = join(bed.tempRoot, 'outside');
await mkdir(escapeTarget, { recursive: true });
// The DB child is a symlink pointing out of the disposable root: state
// written "under" the root would land outside it.
await symlink(escapeTarget, join(bed.stateRoot, 'db'), 'dir');
const policy = await freshPolicy();
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_STATE_ROOT_ESCAPES');
});
it('refuses the cross-field local+postgres shape that the tier probe does not catch', async () => {
const bed = await makeBed();
await writeFile(
join(bed.anchor, '..', 'mosaic.config.json'),
JSON.stringify({ tier: 'local', storage: { type: 'postgres', url: FORBIDDEN_DSN } }),
'utf8',
);
const policy = await freshPolicy();
// detectAndAssertTier early-returns on tier === 'local' without inspecting
// storage.type, so this shape reaches real Postgres DDL today.
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_CROSS_FIELD_MISMATCH');
});
});
describe('KBN-101-02a establishFrozenLocalPolicy — row 9, one-shot freeze', () => {
it('returns a deep-frozen allowed-only policy', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
const frozen = policy.establishFrozenLocalPolicy(establishInput(bed));
expect(Object.isFrozen(frozen)).toBe(true);
expect(Object.isFrozen(frozen.storage)).toBe(true);
expect(Object.isFrozen(frozen.queue)).toBe(true);
expect(frozen.tier).toBe('local');
expect(frozen.storage.type).toBe('pglite');
expect(frozen.queue.type).toBe('local');
});
it('resolves every derived child beneath the declared state root', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
const frozen = policy.establishFrozenLocalPolicy(establishInput(bed));
expect(frozen.stateRoot).toBe(bed.stateRoot);
expect(frozen.storage.dataDir.startsWith(`${bed.stateRoot}/`)).toBe(true);
expect(frozen.queue.dataDir.startsWith(`${bed.stateRoot}/`)).toBe(true);
});
it('refuses a second establish: the policy is one-shot and there is no reset API', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
policy.establishFrozenLocalPolicy(establishInput(bed));
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_ALREADY_ESTABLISHED');
expect(Object.keys(policy)).not.toContain('resetFrozenLocalPolicy');
});
it('is unaffected by mutating the inputs after establish: the policy is a deep clone', async () => {
const bed = await makeBed();
const policy = await freshPolicy();
const env: Record<string, string | undefined> = {};
const frozen = policy.establishFrozenLocalPolicy(establishInput(bed, { env }));
const dataDirBefore = frozen.storage.dataDir;
env['DATABASE_URL'] = FORBIDDEN_DSN;
env['MOSAIC_STORAGE_TIER'] = 'standalone';
const observed = policy.getFrozenLocalPolicy();
expect(observed?.storage.dataDir).toBe(dataDirBefore);
expect(observed?.tier).toBe('local');
expect(observed?.storage.type).toBe('pglite');
});
it('refuses to serve a policy when the local channel was never established', async () => {
const policy = await freshPolicy();
expect(policy.getFrozenLocalPolicy()).toBeUndefined();
expect(() => policy.requireFrozenLocalPolicy()).toThrow(policy.LocalStartRefusal);
});
it('does not fall back to an independent config read when unestablished', async () => {
const policy = await freshPolicy();
// No `getFrozen() ?? loadConfig()` masking: the local and legacy channels
// must not fall through to one another.
let thrown: unknown;
try {
policy.requireFrozenLocalPolicy();
} catch (error) {
thrown = error;
}
expect((thrown as { code?: string }).code).toBe('LOCAL_START_POLICY_NOT_ESTABLISHED');
});
});
/** Where each file source lives, relative to the bed's anchor and home base. */
function sourcePath(
bed: Bed,
label: Exclude<LocalStartSourceLabel, 'process-environment'>,
): string {
const repo = join(bed.anchor, '..', '..', '..');
const daemonDir = join(bed.homeBase, '.config', 'mosaic', 'gateway');
const paths: Record<Exclude<LocalStartSourceLabel, 'process-environment'>, string> = {
'daemon-dotenv': join(daemonDir, '.env'),
'monorepo-root-dotenv': join(repo, '.env'),
'gateway-local-dotenv': join(repo, 'apps', 'gateway', '.env'),
'daemon-json': join(daemonDir, 'mosaic.config.json'),
'app-json': join(repo, 'apps', 'gateway', 'mosaic.config.json'),
'monorepo-root-json': join(repo, 'mosaic.config.json'),
};
return paths[label];
}
const CLEAN_LOCAL_JSON = JSON.stringify({
tier: 'local',
storage: { type: 'pglite' },
queue: { type: 'local' },
memory: { type: 'none' },
});
async function writeSource(bed: Bed, label: Parameters<typeof sourcePath>[1], body: string) {
const path = sourcePath(bed, label);
await mkdir(join(path, '..'), { recursive: true });
await writeFile(path, body, 'utf8');
return path;
}
/**
* A source that cannot be read or parsed has UNKNOWN contents, and an unknown
* source has not been shown to be free of a forbidden value. Skipping it — or
* letting a clean higher-precedence source stand in for it — is precisely the
* "a forbidden value refuses even when shadowed" rule failing in its other
* direction: here the forbidden value is not absent, it is unreadable.
*/
describe('KBN-101-02a establishFrozenLocalPolicy — unreadable and malformed sources', () => {
it('refuses malformed JSON in a LOSING source even when the winning source is clean', async () => {
const bed = await makeBed();
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
await writeSource(bed, 'app-json', '{ "tier": "local", ');
const policy = await freshPolicy();
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_SOURCE_MALFORMED');
});
it('refuses malformed JSON in the daemon config specifically', async () => {
const bed = await makeBed();
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
await writeSource(bed, 'daemon-json', 'not json at all');
const policy = await freshPolicy();
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_SOURCE_MALFORMED');
});
// A directory where a file is expected fails the read with EISDIR for every
// uid. Mode 0o000 would not: a process running as root reads it anyway, so
// that case would pass trivially in exactly the environments CI uses.
it('refuses a source that cannot be read at all', async () => {
const bed = await makeBed();
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
await mkdir(sourcePath(bed, 'gateway-local-dotenv'), { recursive: true });
const policy = await freshPolicy();
await expectRefusal(policy, establishInput(bed), 'LOCAL_START_SOURCE_UNREADABLE');
});
it('names the offending source label without quoting its contents', async () => {
const bed = await makeBed();
await writeSource(bed, 'app-json', `{ "tier": "local", "note": "${FORBIDDEN_DSN}"`);
const policy = await freshPolicy();
let thrown: unknown;
try {
policy.establishFrozenLocalPolicy(establishInput(bed));
} catch (error) {
thrown = error;
}
const refusal = thrown as InstanceType<PolicyModule['LocalStartRefusal']>;
expect(refusal?.code).toBe('LOCAL_START_SOURCE_MALFORMED');
expect(refusal.sourceLabels).toContain('app-json');
expect(`${refusal.message} ${JSON.stringify(refusal.sourceLabels)}`).not.toContain(
FORBIDDEN_DSN,
);
});
});
/**
* The freeze is a promise about the FUTURE, and a snapshot taken at establish
* time proves nothing about it. These cases mutate the underlying sources after
* establish and then read the policy back: a consumer that re-reads a file on
* demand, or holds a live reference into one, fails here and passes every case
* that only inspects the object returned at establish time.
*/
describe('KBN-101-02a establishFrozenLocalPolicy — the freeze survives source mutation', () => {
it('retains the frozen policy after a source file is rewritten to carry a DSN', async () => {
const bed = await makeBed();
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
const policy = await freshPolicy();
const established = policy.establishFrozenLocalPolicy(establishInput(bed));
await writeSource(
bed,
'monorepo-root-json',
JSON.stringify({
tier: 'standalone',
storage: { type: 'postgres', url: FORBIDDEN_DSN },
queue: { type: 'bullmq' },
memory: { type: 'none' },
}),
);
const after = policy.requireFrozenLocalPolicy();
expect(after).toBe(established);
expect(after.tier).toBe('local');
expect(after.storage.type).toBe('pglite');
expect(JSON.stringify(after)).not.toContain(FORBIDDEN_DSN);
});
it('retains the frozen policy after the ambient environment gains a DSN', async () => {
const bed = await makeBed();
await writeSource(bed, 'monorepo-root-json', CLEAN_LOCAL_JSON);
const policy = await freshPolicy();
const env: Record<string, string | undefined> = {};
const established = policy.establishFrozenLocalPolicy(establishInput(bed, { env }));
env['DATABASE_URL'] = FORBIDDEN_DSN;
const after = policy.requireFrozenLocalPolicy();
expect(after).toBe(established);
expect(after.storage.type).toBe('pglite');
expect(JSON.stringify(after)).not.toContain(FORBIDDEN_DSN);
});
});
@@ -0,0 +1,156 @@
/**
* Local-start policy — KBN-101-02a.
*
* The fail-closed refusal, and the single frozen policy the whole local channel
* consumes. Refusal happens before any connection is opened and before any DDL
* is executed; the modules that are able to connect are not loaded until this
* has run.
*
* RED PHASE SCAFFOLDING. The signatures and codes below are the contract; the
* bodies are deliberately permissive stubs that admit everything and freeze
* nothing, so the behavioral specs fail on their assertions rather than on a
* missing module. Do not read this file as the implementation — there is none
* yet.
*/
import type { LocalStartSourceLabel } from './source-inventory.js';
/** Stable refusal codes. Errors expose labels and codes only — never values. */
export type LocalStartRefusalCode =
| 'LOCAL_START_POSTGRES_DSN_PRESENT'
| 'LOCAL_START_NON_LOCAL_TIER'
| 'LOCAL_START_TIER_NOT_EXPLICIT'
| 'LOCAL_START_STORAGE_NOT_PGLITE'
| 'LOCAL_START_QUEUE_NOT_LOCAL'
| 'LOCAL_START_STATE_ROOT_MISSING'
| 'LOCAL_START_STATE_ROOT_NOT_ABSOLUTE'
| 'LOCAL_START_STATE_ROOT_ESCAPES'
| 'LOCAL_START_STATE_ROOT_ABSENT'
| 'LOCAL_START_STATE_ROOT_NOT_DIRECTORY'
| 'LOCAL_START_STATE_ROOT_IS_SYMLINK'
| 'LOCAL_START_STATE_ROOT_NOT_PRIVATE'
| 'LOCAL_START_STATE_ROOT_NOT_OWNED'
| 'LOCAL_START_SOURCE_UNREADABLE'
| 'LOCAL_START_SOURCE_MALFORMED'
| 'LOCAL_START_CROSS_FIELD_MISMATCH'
| 'LOCAL_START_ALREADY_ESTABLISHED'
| 'LOCAL_START_POLICY_NOT_ESTABLISHED';
/**
* A refusal. Carries the stable code and the source labels that produced it.
*
* It carries no value: no DSN, no dotenv line, no JSON body. A refusal that
* echoed the offending value would move the secret into the log, which is the
* failure this item exists to prevent.
*/
export class LocalStartRefusal extends Error {
public readonly code: LocalStartRefusalCode;
public readonly sourceLabels: readonly LocalStartSourceLabel[];
constructor(code: LocalStartRefusalCode, sourceLabels: readonly LocalStartSourceLabel[] = []) {
super(`[local-start] refused: ${code}`);
this.name = 'LocalStartRefusal';
this.code = code;
this.sourceLabels = sourceLabels;
}
}
/**
* The disposable state-root contract, stated so it is testable.
*
* "Disposable" is not a property of the path string; it is a property of the
* directory the string names. A declared root is admitted only when ALL of the
* following hold, each with its own refusal code so a removed guard turns
* exactly one case red:
*
* 1. absolute (`LOCAL_START_STATE_ROOT_NOT_ABSOLUTE`);
* 2. already its own canonical form, lexically (`LOCAL_START_STATE_ROOT_ESCAPES`);
* 3. it exists (`LOCAL_START_STATE_ROOT_ABSENT`) — the local channel does not
* create the root, because a channel that creates its own root cannot
* distinguish "session-scoped" from "silently reused";
* 4. it is a directory (`LOCAL_START_STATE_ROOT_NOT_DIRECTORY`);
* 5. the root itself is not a symlink (`LOCAL_START_STATE_ROOT_IS_SYMLINK`) —
* checked with lstat, since a stat on a symlinked root reports the target and
* every subsequent check would describe a directory the operator did not name;
* 6. it is owned by the current user (`LOCAL_START_STATE_ROOT_NOT_OWNED`);
* 7. it is private — no group or other permission bits
* (`LOCAL_START_STATE_ROOT_NOT_PRIVATE`);
* 8. no derived child escapes it through a symlink (`LOCAL_START_STATE_ROOT_ESCAPES`).
*
* Only 1, 2 and 8 were covered by the first RED pass. A derived-child symlink
* check alone admits a root that is missing, is a file, is a symlink into
* someone else's directory, or is world-writable — none of which is disposable
* in any sense that protects the operator's data.
*/
/** Explicit declarations supplied for THIS invocation. Nothing is defaulted. */
export interface LocalStartDeclaration {
readonly tier?: string;
readonly storageType?: string;
readonly queueType?: string;
readonly stateRoot?: string;
}
export interface EstablishInput {
readonly declaration: LocalStartDeclaration;
readonly anchor: string;
readonly homeBase: string;
readonly env: Readonly<Record<string, string | undefined>>;
}
/** The one resolved policy. Allowed-only, deep-cloned, deep-frozen. */
export interface FrozenLocalPolicy {
readonly tier: 'local';
readonly storage: { readonly type: 'pglite'; readonly dataDir: string };
readonly queue: { readonly type: 'local'; readonly dataDir: string };
readonly stateRoot: string;
}
let established: FrozenLocalPolicy | undefined;
/**
* Establish the frozen local policy, once.
*
* Contract (not yet implemented):
* - refuses unless tier/storage/queue/state-root are all explicitly declared;
* - refuses any PostgreSQL DSN or non-local tier found in ANY source, shadowed
* or not;
* - refuses cross-field mismatches (local+postgres, local+files, non-local+pglite);
* - refuses a source it cannot read or parse, EVEN when a clean source would win
* precedence — an unknown source has not been shown to be safe;
* - enforces the full disposable state-root contract above; never uses HOME/CWD
* defaults;
* - deep-clones and deep-freezes an allowed-only object;
* - a second call refuses with LOCAL_START_ALREADY_ESTABLISHED; there is no reset.
*/
export function establishFrozenLocalPolicy(input: EstablishInput): FrozenLocalPolicy {
// RED-phase stub: admits everything, validates nothing, freezes nothing, and
// permits re-establish. See module header.
const stateRoot = input.declaration.stateRoot ?? '';
established = {
tier: 'local',
storage: { type: 'pglite', dataDir: `${stateRoot}/db` },
queue: { type: 'local', dataDir: `${stateRoot}/queue` },
stateRoot,
};
return established;
}
/** The established policy, or undefined when the local channel is not active. */
export function getFrozenLocalPolicy(): FrozenLocalPolicy | undefined {
return established;
}
/**
* The established policy, refusing when the local channel is not active.
*
* Local-channel consumers use this rather than falling back to an independent
* read: there is deliberately no `getFrozen() ?? loadConfig()` masking, because
* a fallback would silently restore the split-config path this item removes.
*/
export function requireFrozenLocalPolicy(): FrozenLocalPolicy {
if (established === undefined) {
throw new LocalStartRefusal('LOCAL_START_POLICY_NOT_ESTABLISHED');
}
return established;
}
@@ -0,0 +1,547 @@
/**
* KBN-101-02a — source inventory REDs.
*
* Covers mutation->guard rows 1-6: inherited env, shared dotenv, daemon JSON,
* app JSON, root JSON, redirect.
*
* Every case here plants a forbidden value in exactly ONE source and leaves the
* others clean, so a guard that is removed for that source alone turns exactly
* one case red. Aggregate coverage would not distinguish them.
*
* These read fixture files under a temp root. Nothing here connects to anything.
*/
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
LOCAL_START_SOURCE_LABELS,
inventoryLocalStartSources,
type InventoriedSource,
type LocalStartSourceLabel,
} from './source-inventory.js';
/** A Postgres DSN used only as fixture text. Never connected to. */
const FORBIDDEN_DSN = 'postgresql://mosaic:mosaic@localhost:5433/mosaic';
interface Layout {
tempRoot: string;
anchor: string;
homeBase: string;
gatewayHome: string;
paths: Record<Exclude<LocalStartSourceLabel, 'process-environment'>, string>;
}
const cleanups: (() => Promise<void>)[] = [];
afterEach(async () => {
while (cleanups.length > 0) {
const fn = cleanups.pop();
if (fn) {
await fn();
}
}
});
async function writeFixture(path: string, contents: string): Promise<void> {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, contents, 'utf8');
}
async function makeLayout(): Promise<Layout> {
const tempRoot = await mkdtemp(join(tmpdir(), 'kbn-02a-inventory-'));
// The stack above is drained in afterEach. It existed before this line did,
// and nothing pushed to it — so every case in this file left its temp root
// behind. Registering at the point of creation is the only placement that
// cannot be forgotten by a case added later.
cleanups.push(async () => {
await rm(tempRoot, { recursive: true, force: true });
});
const repo = join(tempRoot, 'repo');
const anchor = join(repo, 'apps', 'gateway', 'src');
const homeBase = join(tempRoot, 'home');
// Redirect target lives OUTSIDE the default home location on purpose: a
// daemon-json hit here can only mean the redirect was followed.
const gatewayHome = join(tempRoot, 'redirected-gateway-home');
return {
tempRoot,
anchor,
homeBase,
gatewayHome,
paths: {
'daemon-dotenv': join(homeBase, '.config', 'mosaic', 'gateway', '.env'),
'monorepo-root-dotenv': join(repo, '.env'),
'gateway-local-dotenv': join(repo, 'apps', 'gateway', '.env'),
'daemon-json': join(gatewayHome, 'mosaic.config.json'),
'app-json': join(repo, 'apps', 'gateway', 'mosaic.config.json'),
'monorepo-root-json': join(repo, 'mosaic.config.json'),
},
};
}
const CLEAN_LOCAL_JSON = JSON.stringify({
tier: 'local',
storage: { type: 'pglite' },
queue: { type: 'local' },
memory: { type: 'none' },
});
function postgresJson(): string {
return JSON.stringify({
tier: 'standalone',
storage: { type: 'postgres', url: FORBIDDEN_DSN },
queue: { type: 'bullmq' },
memory: { type: 'none' },
});
}
/** Plant a forbidden DSN in exactly one file source; all others written clean. */
async function plantIn(
layout: Layout,
target: Exclude<LocalStartSourceLabel, 'process-environment'>,
): Promise<void> {
for (const [label, path] of Object.entries(layout.paths)) {
const isTarget = label === target;
const isJson = label.endsWith('json');
if (isJson) {
await writeFixture(path, isTarget ? postgresJson() : CLEAN_LOCAL_JSON);
continue;
}
await writeFixture(
path,
isTarget ? `DATABASE_URL=${FORBIDDEN_DSN}\n` : 'MOSAIC_LOG_LEVEL=info\n',
);
}
}
function find(sources: InventoriedSource[], label: LocalStartSourceLabel): InventoriedSource {
const found = sources.find((source) => source.label === label);
expect(found, `no source reported for label "${label}"`).toBeDefined();
return found as InventoriedSource;
}
describe('KBN-101-02a inventoryLocalStartSources', () => {
it('reports every source label, present or not, so no source can be silently skipped', async () => {
const layout = await makeLayout();
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
expect(sources.map((source) => source.label).sort()).toEqual(
[...LOCAL_START_SOURCE_LABELS].sort(),
);
});
// Row 1 — inherited env.
it('row 1: detects a PostgreSQL DSN inherited from the ambient process environment', async () => {
const layout = await makeLayout();
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { DATABASE_URL: FORBIDDEN_DSN },
});
expect(find(sources, 'process-environment').carriesPostgresDsn).toBe(true);
});
it('row 1: detects a non-local tier inherited from the ambient process environment', async () => {
const layout = await makeLayout();
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { MOSAIC_STORAGE_TIER: 'standalone' },
});
// Classification, not quotation: 'standalone' is the planted VALUE, and the
// inventory type cannot carry it. Demanding it here would be a red no
// compliant implementation could turn green.
expect(find(sources, 'process-environment').declaredTier).toBe('non-local');
});
// Row 2 — shared dotenv, one case per file so they fail independently.
it('row 2: detects a DSN in the anchored monorepo-root .env', async () => {
const layout = await makeLayout();
await plantIn(layout, 'monorepo-root-dotenv');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
expect(find(sources, 'monorepo-root-dotenv').carriesPostgresDsn).toBe(true);
});
it('row 2: detects a DSN in the anchored gateway-local .env', async () => {
const layout = await makeLayout();
await plantIn(layout, 'gateway-local-dotenv');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
expect(find(sources, 'gateway-local-dotenv').carriesPostgresDsn).toBe(true);
});
it('row 2: detects a DSN in the daemon .env at $HOME, which the redirect does not move', async () => {
const layout = await makeLayout();
await plantIn(layout, 'daemon-dotenv');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
// Redirect set and pointed elsewhere: the daemon DOTENV must still be
// found at $HOME. Widening the redirect to cover dotenv would break this.
env: { MOSAIC_GATEWAY_HOME: layout.gatewayHome },
});
expect(find(sources, 'daemon-dotenv').carriesPostgresDsn).toBe(true);
});
// Rows 3-5 — the three JSON sources.
it('row 3: detects postgres storage declared in the daemon mosaic.config.json', async () => {
const layout = await makeLayout();
await plantIn(layout, 'daemon-json');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { MOSAIC_GATEWAY_HOME: layout.gatewayHome },
});
const daemonJson = find(sources, 'daemon-json');
expect(daemonJson.carriesPostgresDsn).toBe(true);
expect(daemonJson.declaredStorageType).toBe('non-pglite');
});
it('row 4: detects postgres storage declared in the anchored app mosaic.config.json', async () => {
const layout = await makeLayout();
await plantIn(layout, 'app-json');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
expect(find(sources, 'app-json').carriesPostgresDsn).toBe(true);
});
it('row 5: detects postgres storage declared in the anchored monorepo-root mosaic.config.json', async () => {
const layout = await makeLayout();
await plantIn(layout, 'monorepo-root-json');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
expect(find(sources, 'monorepo-root-json').carriesPostgresDsn).toBe(true);
});
// Row 6 — redirect followed for daemon JSON only.
it('row 6: follows MOSAIC_GATEWAY_HOME when locating the daemon JSON', async () => {
const layout = await makeLayout();
await plantIn(layout, 'daemon-json');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { MOSAIC_GATEWAY_HOME: layout.gatewayHome },
});
const daemonJson = find(sources, 'daemon-json');
expect(daemonJson.present).toBe(true);
expect(daemonJson.path).toBe(layout.paths['daemon-json']);
});
it('row 6: without the redirect, the daemon JSON resolves under $HOME and the redirected file is not read', async () => {
const layout = await makeLayout();
await plantIn(layout, 'daemon-json');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
const daemonJson = find(sources, 'daemon-json');
expect(daemonJson.path).toBe(
join(layout.homeBase, '.config', 'mosaic', 'gateway', 'mosaic.config.json'),
);
expect(daemonJson.carriesPostgresDsn).toBe(false);
});
// Shadowing — the property that makes independent inspection necessary.
it('reports a forbidden value in a LOSING source even when a winning source is clean', async () => {
const layout = await makeLayout();
await plantIn(layout, 'gateway-local-dotenv');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
// Ambient env would win precedence and is clean; the shadowed file value
// must still be reported.
env: { MOSAIC_STORAGE_TIER: 'local' },
});
expect(find(sources, 'gateway-local-dotenv').carriesPostgresDsn).toBe(true);
});
// Non-egress: classification only, never the value.
it('retains no raw DSN text anywhere in the inventory result', async () => {
const layout = await makeLayout();
await plantIn(layout, 'monorepo-root-dotenv');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { DATABASE_URL: FORBIDDEN_DSN },
});
expect(JSON.stringify(sources)).not.toContain(FORBIDDEN_DSN);
expect(JSON.stringify(sources)).not.toContain('mosaic:mosaic');
});
});
/**
* Tier and DSN are separate forbidden classes and must be separately detected.
*
* The DSN cases above would all still pass if the tier check were deleted
* outright, because every DSN fixture also declares a non-local tier. These
* cases plant a non-local tier and NO DSN, in exactly one source at a time, so
* deleting the tier guard for one source turns exactly one case red and the DSN
* cases stay green.
*/
const NON_LOCAL_TIER_JSON = JSON.stringify({
tier: 'standalone',
storage: { type: 'pglite' },
queue: { type: 'local' },
memory: { type: 'none' },
});
async function plantNonLocalTierIn(
layout: Layout,
target: Exclude<LocalStartSourceLabel, 'process-environment'>,
): Promise<void> {
for (const [label, path] of Object.entries(layout.paths)) {
const isTarget = label === target;
if (label.endsWith('json')) {
await writeFixture(path, isTarget ? NON_LOCAL_TIER_JSON : CLEAN_LOCAL_JSON);
continue;
}
await writeFixture(
path,
isTarget ? 'MOSAIC_STORAGE_TIER=standalone\n' : 'MOSAIC_LOG_LEVEL=info\n',
);
}
}
describe('KBN-101-02a inventoryLocalStartSources — non-local tier, per source, without any DSN', () => {
const fileLabels: Exclude<LocalStartSourceLabel, 'process-environment'>[] = [
'daemon-dotenv',
'monorepo-root-dotenv',
'gateway-local-dotenv',
'daemon-json',
'app-json',
'monorepo-root-json',
];
for (const label of fileLabels) {
it(`classifies a non-local tier declared only in ${label}`, async () => {
const layout = await makeLayout();
await plantNonLocalTierIn(layout, label);
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
expect(find(sources, label).declaredTier).toBe('non-local');
expect(find(sources, label).carriesPostgresDsn).toBe(false);
for (const other of fileLabels.filter((candidate) => candidate !== label)) {
expect(find(sources, other).declaredTier).not.toBe('non-local');
}
});
}
it('classifies a non-local tier inherited from the ambient process environment', async () => {
const layout = await makeLayout();
for (const [label, path] of Object.entries(layout.paths)) {
await writeFixture(
path,
label.endsWith('json') ? CLEAN_LOCAL_JSON : 'MOSAIC_LOG_LEVEL=info\n',
);
}
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { MOSAIC_STORAGE_TIER: 'federated' },
});
expect(find(sources, 'process-environment').declaredTier).toBe('non-local');
expect(find(sources, 'process-environment').carriesPostgresDsn).toBe(false);
});
});
/**
* Classification, not quotation.
*
* `declaredTier: string` is value-free only by convention — it holds whatever
* the file said. These cases plant a canary in the value position of every
* source and assert it appears nowhere: not in the result, and not in anything
* written to the console on the way there. The result is serialized whole rather
* than field-by-field, so a field added later is covered without anyone
* remembering to extend this case.
*/
describe('KBN-101-02a inventoryLocalStartSources — no source value is retained or logged', () => {
const CANARY = 'kbn-101-02a-canary-2f7d1c';
it('retains no planted canary anywhere in the result', async () => {
const layout = await makeLayout();
for (const [label, path] of Object.entries(layout.paths)) {
await writeFixture(
path,
label.endsWith('json')
? JSON.stringify({
tier: CANARY,
storage: { type: CANARY, url: `postgresql://${CANARY}@localhost:5432/db` },
queue: { type: CANARY },
})
: `MOSAIC_STORAGE_TIER=${CANARY}\nDATABASE_URL=postgresql://${CANARY}@localhost:5432/db\n`,
);
}
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { MOSAIC_STORAGE_TIER: CANARY },
});
expect(JSON.stringify(sources)).not.toContain(CANARY);
});
it('writes no planted canary to the console while inspecting sources', async () => {
const layout = await makeLayout();
await writeFixture(
layout.paths['monorepo-root-json'],
JSON.stringify({ tier: CANARY, storage: { type: CANARY }, queue: { type: CANARY } }),
);
const written: string[] = [];
const methods = ['log', 'info', 'warn', 'error', 'debug', 'trace'] as const;
const spies = methods.map((method) =>
vi.spyOn(console, method).mockImplementation((...args: unknown[]): void => {
written.push(args.map((arg) => String(arg)).join(' '));
}),
);
try {
inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: { DATABASE_URL: `postgresql://${CANARY}@localhost:5432/db` },
});
} finally {
for (const spy of spies) {
spy.mockRestore();
}
}
expect(written.join('\n')).not.toContain(CANARY);
});
});
/**
* Readability is reported per source, and absence is its own classification.
*
* The refusal path in local-start-policy.ts consumes these rows, and it treats
* "read, and clean" as the opposite of "contents unknown". If an absent source
* has to be described as `readable`, those two collapse into one value and the
* refusal loses the distinction it is built on. So all four states are asserted
* directly here rather than inferred from a refusal downstream.
*
* The unreadable fixture is a DIRECTORY where a file is expected. `chmod 0o000`
* would be the obvious choice and is worthless: root ignores the mode bits, so
* the case would pass vacuously wherever CI runs as root. EISDIR holds for every
* uid.
*/
describe('KBN-101-02a inventoryLocalStartSources — readability is classified per source', () => {
it('classifies an absent source as absent, never as readable', async () => {
const layout = await makeLayout();
// Nothing planted: the anchored app JSON does not exist.
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
const appJson = find(sources, 'app-json');
expect(appJson.present).toBe(false);
expect(appJson.readability).toBe('absent');
});
it('classifies a present, parseable source as readable', async () => {
const layout = await makeLayout();
await writeFixture(layout.paths['app-json'], CLEAN_LOCAL_JSON);
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
const appJson = find(sources, 'app-json');
expect(appJson.present).toBe(true);
expect(appJson.readability).toBe('readable');
});
it('classifies a source that cannot be read as unreadable, not as absent', async () => {
const layout = await makeLayout();
// A directory at the file's path: open() fails with EISDIR for every uid.
await mkdir(layout.paths['app-json'], { recursive: true });
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
const appJson = find(sources, 'app-json');
expect(appJson.readability).toBe('unreadable');
expect(appJson.readability, 'an unreadable source was reported as absent').not.toBe('absent');
});
it('classifies a present but unparseable source as malformed, not as readable', async () => {
const layout = await makeLayout();
await writeFixture(layout.paths['app-json'], '{ "tier": "local", ');
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
const appJson = find(sources, 'app-json');
expect(appJson.present).toBe(true);
expect(appJson.readability).toBe('malformed');
});
it('holds present === false exactly when readability === absent, across every source', async () => {
const layout = await makeLayout();
// A deliberately mixed bed: one readable, one malformed, one unreadable,
// the rest absent. The invariant has to hold for all seven rows at once.
await writeFixture(layout.paths['monorepo-root-json'], CLEAN_LOCAL_JSON);
await writeFixture(layout.paths['app-json'], '{ not json');
await mkdir(layout.paths['gateway-local-dotenv'], { recursive: true });
const sources = inventoryLocalStartSources({
anchor: layout.anchor,
homeBase: layout.homeBase,
env: {},
});
expect(sources.length).toBe(LOCAL_START_SOURCE_LABELS.length);
for (const source of sources) {
expect(
source.readability === 'absent',
`${source.label}: present=${String(source.present)} readability=${source.readability}`,
).toBe(source.present === false);
}
});
});
@@ -0,0 +1,111 @@
/**
* Local-start source inventory — KBN-101-02a.
*
* Enumerates and reads EVERY configuration source independently, BEFORE any
* precedence is applied. A forbidden value refuses even when it is shadowed by
* a higher-precedence source, so precedence must not be consulted here.
*
* RED PHASE SCAFFOLDING. The signatures below are the contract; the body is a
* deliberately permissive stub that discovers nothing, so the behavioral specs
* fail on their assertions rather than on a missing module. Do not read this
* file as the implementation — there is none yet.
*/
/** Every configuration source the local channel must inspect. */
export type LocalStartSourceLabel =
| 'process-environment'
| 'daemon-dotenv'
| 'monorepo-root-dotenv'
| 'gateway-local-dotenv'
| 'daemon-json'
| 'app-json'
| 'monorepo-root-json';
export const LOCAL_START_SOURCE_LABELS: readonly LocalStartSourceLabel[] = [
'process-environment',
'daemon-dotenv',
'monorepo-root-dotenv',
'gateway-local-dotenv',
'daemon-json',
'app-json',
'monorepo-root-json',
];
/**
* Finite classifications, not values.
*
* These are unions rather than `string` on purpose. A `declaredTier?: string`
* field is value-free only by convention: it will hold whatever the source said,
* so a canary planted in a config file survives into the inventory and from
* there into anything that logs it. A union of two members cannot carry a
* canary — the type makes retention unrepresentable rather than discouraged.
*/
export type DeclaredTierClass = 'local' | 'non-local';
export type DeclaredStorageClass = 'pglite' | 'non-pglite';
/**
* Whether the source could be read and parsed at all.
*
* A source that cannot be read is not the same as a source that is absent. An
* unreadable or malformed source is a source whose contents are UNKNOWN, and an
* unknown source cannot be shown to be free of a forbidden value — so it refuses
* rather than being skipped.
*
* `absent` is a member rather than an implication of `present: false`. Without
* it the two fields can disagree — an absent source has to be reported as
* `readable`, which is the one classification that means "read, and clean". A
* reader that stats a path and finds nothing there would then be indistinguishable
* from a reader that opened a file and found it safe, and the refusal path treats
* those two as opposites. The invariant is exact and total:
* `present === false` if and only if `readability === 'absent'`.
*/
export type SourceReadability = 'readable' | 'unreadable' | 'malformed' | 'absent';
/**
* What one source was observed to carry.
*
* Deliberately value-free beyond classification: raw DSNs, dotenv contents and
* JSON bodies are never retained here, because anything retained can later be
* logged. Callers get labels and classifications, never secrets.
*/
export interface InventoriedSource {
readonly label: LocalStartSourceLabel;
/** Filesystem path inspected; absent for the ambient process environment. */
readonly path?: string;
readonly present: boolean;
/** True when this source carries a PostgreSQL DSN in any recognized key. */
readonly carriesPostgresDsn: boolean;
/** Whether this source was readable and parseable. */
readonly readability: SourceReadability;
/** Classification of the tier this source declares, if it declares one. */
readonly declaredTier?: DeclaredTierClass;
/** Classification of the storage type this source declares, if it declares one. */
readonly declaredStorageType?: DeclaredStorageClass;
}
export interface InventoryInput {
/** Module anchor used to resolve the anchored dotenv/JSON locations. */
readonly anchor: string;
/** Home base used to resolve the daemon dotenv location. */
readonly homeBase: string;
/** Ambient environment snapshot. */
readonly env: Readonly<Record<string, string | undefined>>;
}
/**
* Inspect every source independently and report what each one carries.
*
* Contract (not yet implemented):
* - every label in LOCAL_START_SOURCE_LABELS appears in the result, present or not;
* - MOSAIC_GATEWAY_HOME redirects `daemon-json` ONLY — `daemon-dotenv` stays at
* `$HOME/.config/mosaic/gateway/.env` regardless of the redirect;
* - a source that cannot be read or parsed is reported as such, never skipped
* and never treated as clean;
* - `present === false` if and only if `readability === 'absent'`; an absent
* source is never reported as `readable`;
* - no precedence is applied and no value is retained.
*/
export function inventoryLocalStartSources(_input: InventoryInput): InventoriedSource[] {
// RED-phase stub: discovers nothing. See module header.
return [];
}
+362 -1
View File
@@ -3,9 +3,11 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import * as nodeOs from 'node:os';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import * as nodeUrl from 'node:url';
import type * as NestCore from '@nestjs/core';
import type * as MosaicConfigModule from '@mosaicstack/config';
import type { MosaicConfig } from '@mosaicstack/config';
import type * as MosaicStorage from '@mosaicstack/storage';
import { describe, expect, it, vi, type MockInstance } from 'vitest';
import { afterEach, describe, expect, it, vi, type MockInstance } from 'vitest';
// Each case uses vi.resetModules() and re-imports the full gateway graph for distinct ambient FS/env; CI needs headroom, while this still guards genuine hangs.
const MODULE_IMPORT_TIMEOUT_MS = 120_000;
@@ -162,3 +164,362 @@ describe('main bootstrap preflight config anchoring', (): void => {
MODULE_IMPORT_TIMEOUT_MS,
);
});
/**
* KBN-101-02a — the real consumers, executed.
*
* The local-dev REDs mock `./main.js` wholesale, which proves the entrypoint
* refuses before it calls bootstrap and proves nothing at all about what
* bootstrap, AppModule and ConfigModule do when they DO run. Those three each
* perform their own independent `loadConfig(resolveGatewayConfigPath())` —
* `main.ts:28`, `app.module.ts:39`, `config.module.ts:12` — and the frozen
* policy is worth nothing if the modules that actually start the process ignore
* it. Every case below drives the real module.
*
* `@nestjs/core` is substituted so a case that wrongly proceeds cannot listen,
* and `@mosaicstack/storage` so no tier probe can reach a real service. Those
* substitutions are also the instrument: the assertions are that they were never
* called.
*
* While red, this block also emits unhandled rejections ('process.exit
* unexpectedly called with "1"'). They are not flake and must not be silenced:
* they are the self-invocation at `main.ts:71` failing asynchronously after the
* case that imported the module has already returned. An entrypoint that starts
* nothing on import cannot produce them, so they disappear when the defect is
* fixed. If they survive GREEN, the entrypoint is still self-invoking.
*
* NOTE — the case above this block ('main bootstrap preflight config anchoring')
* asserts the CURRENT contract, in which importing `main.ts` self-invokes
* `bootstrap()` and exits the process on failure:
*
* await import('./main.js');
* await vi.waitFor(() => { expect(exitSpy).toHaveBeenCalled(); });
*
* That expectation is the direct opposite of the contract this item introduces,
* so it cannot survive GREEN unchanged. It is deliberately left intact here: it
* is the current behavior's regression guard, it must keep passing until the
* behavior actually changes, and the GREEN author has to migrate it to drive the
* exported `bootstrap()` explicitly rather than delete it. A red left where the
* change has to happen is cheaper than a note in a document.
*/
describe('KBN-101-02a main.ts — importing the entrypoint starts nothing', () => {
// The application double has to be complete enough for bootstrap to run all
// the way through, not merely far enough to observe the config read. A thinner
// double fails inside itself (`app.getHttpAdapter is not a function`), which
// would leave these cases unable to go green for the reason they state even
// after the defect is fixed. The HTTP instance is a permissive proxy so the
// double does not have to track every route the controllers mount.
const listenMock = vi.fn(async () => {});
const nestCreateMock = vi.fn(async () => ({
enableCors: vi.fn(),
register: vi.fn(async () => {}),
useGlobalPipes: vi.fn(),
get: vi.fn(() => ({})),
getHttpAdapter: vi.fn(() => ({
getInstance: () => new Proxy({}, { get: () => vi.fn() }),
})),
listen: listenMock,
}));
const detectAndAssertTierMock = vi.fn(async () => {});
const loadConfigMock = vi.fn(() => ({
tier: 'local' as const,
storage: { type: 'pglite' as const, dataDir: '.mosaic/storage-pglite' },
queue: { type: 'local' as const, dataDir: '.mosaic/queue' },
memory: { type: 'keyword' as const },
}));
const tempRoots: string[] = [];
afterEach(async (): Promise<void> => {
for (const root of tempRoots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
});
/**
* Import `main.js` with the current self-invocation effect captured.
*
* `main.ts:71` invokes bootstrap on import; it rejects, and the tail calls
* `process.exit(1)`. Vitest instruments `process.exit`, so that raised a
* global error attributed to no case at all — which both falsified this
* document's zero-non-assertion-failures claim and is exactly the shape
* Vitest warns can produce false positives.
*
* Stubbing `process.exit` non-throwing for the duration and awaiting a settle
* turn keeps the effect inside the case that provokes it. The behavioral
* assertions stay red — importing an entrypoint must not do this — but the
* error is now owned rather than loose. The spy is returned so callers can
* assert against it.
*/
async function importMainCapturingExit(): Promise<{
mod: Record<string, unknown>;
exitSpy: MockInstance<typeof process.exit>;
}> {
const exitSpy = vi
.spyOn(process, 'exit')
.mockImplementation((() => undefined) as unknown as typeof process.exit);
const mod = (await import('./main.js')) as Record<string, unknown>;
// Two turns: one for the bootstrap rejection, one for its catch handler.
await new Promise((resolve) => setImmediate(resolve));
await new Promise((resolve) => setImmediate(resolve));
return { mod, exitSpy };
}
async function establishLocalChannel(): Promise<string> {
const tempRoot = await mkdtemp(join(nodeOs.tmpdir(), 'kbn-02a-main-'));
tempRoots.push(tempRoot);
const anchor = join(tempRoot, 'repo', 'apps', 'gateway', 'src');
const homeBase = join(tempRoot, 'home');
const stateRoot = join(tempRoot, 'session-state');
await mkdir(anchor, { recursive: true });
await mkdir(homeBase, { recursive: true });
await mkdir(stateRoot, { recursive: true });
const { establishFrozenLocalPolicy } = await import('./local-start/local-start-policy.js');
establishFrozenLocalPolicy({
declaration: { tier: 'local', storageType: 'pglite', queueType: 'local', stateRoot },
anchor,
homeBase,
env: {},
});
return stateRoot;
}
function substituteStartupSurface(): void {
vi.doMock('./tracing.js', () => ({}));
// Partial, never wholesale. A wholesale substitution drops APP_GUARD and
// every other export app.module.ts evaluates at import time, so the module
// throws before reaching the behavior under test — the case would then be
// red for a reason it does not state, and could never go green by fixing
// the defect it names.
vi.doMock('@nestjs/core', async () => {
const actual = await vi.importActual<typeof NestCore>('@nestjs/core');
return { ...actual, NestFactory: { ...actual.NestFactory, create: nestCreateMock } };
});
vi.doMock('@mosaicstack/storage', async () => {
const actual = await vi.importActual<typeof MosaicStorage>('@mosaicstack/storage');
return { ...actual, detectAndAssertTier: detectAndAssertTierMock };
});
}
function undoSubstitutions(): void {
vi.doUnmock('@mosaicstack/storage');
vi.doUnmock('@nestjs/core');
vi.doUnmock('./tracing.js');
vi.doUnmock('@mosaicstack/config');
}
it(
'does not bootstrap, probe, or exit merely by being imported',
async (): Promise<void> => {
const originalEnv = snapshotProcessEnv();
let exitSpy: MockInstance<typeof process.exit> | undefined;
try {
delete process.env['BETTER_AUTH_SECRET'];
vi.resetModules();
vi.clearAllMocks();
substituteStartupSurface();
({ exitSpy } = await importMainCapturingExit());
expect(exitSpy, 'importing main.ts exited the process').not.toHaveBeenCalled();
expect(detectAndAssertTierMock, 'importing main.ts probed the tier').not.toHaveBeenCalled();
expect(nestCreateMock, 'importing main.ts created the Nest app').not.toHaveBeenCalled();
} finally {
exitSpy?.mockRestore();
undoSubstitutions();
vi.resetModules();
restoreProcessEnv(originalEnv);
}
},
MODULE_IMPORT_TIMEOUT_MS,
);
it(
'exports bootstrap so the local entrypoint can call it after establishing the policy',
async (): Promise<void> => {
const originalEnv = snapshotProcessEnv();
try {
vi.resetModules();
substituteStartupSurface();
const { mod, exitSpy } = await importMainCapturingExit();
try {
expect(typeof mod['bootstrap'], 'main.ts does not export bootstrap').toBe('function');
} finally {
exitSpy.mockRestore();
}
} finally {
undoSubstitutions();
vi.resetModules();
restoreProcessEnv(originalEnv);
}
},
MODULE_IMPORT_TIMEOUT_MS,
);
it(
'performs no independent config read or tier probe when the frozen policy is established',
async (): Promise<void> => {
const originalEnv = snapshotProcessEnv();
try {
process.env['BETTER_AUTH_SECRET'] = 'fixture-secret';
vi.resetModules();
vi.clearAllMocks();
substituteStartupSurface();
vi.doMock('@mosaicstack/config', async () => {
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
return { ...actual, loadConfig: loadConfigMock };
});
await establishLocalChannel();
const { mod, exitSpy } = await importMainCapturingExit();
try {
await (mod['bootstrap'] as (() => Promise<void>) | undefined)?.();
expect(
loadConfigMock,
'bootstrap re-read configuration independently',
).not.toHaveBeenCalled();
expect(detectAndAssertTierMock, 'bootstrap probed the tier').not.toHaveBeenCalled();
} finally {
exitSpy.mockRestore();
}
} finally {
undoSubstitutions();
vi.resetModules();
restoreProcessEnv(originalEnv);
}
},
MODULE_IMPORT_TIMEOUT_MS,
);
it(
'evaluates AppModule without an independent config read under the frozen policy',
async (): Promise<void> => {
const originalEnv = snapshotProcessEnv();
try {
vi.resetModules();
vi.clearAllMocks();
substituteStartupSurface();
vi.doMock('@mosaicstack/config', async () => {
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
return { ...actual, loadConfig: loadConfigMock };
});
await establishLocalChannel();
// app.module.ts decides federation at module-evaluation time, so the read
// happens on import — before any provider is constructed.
await import('./app.module.js');
expect(
loadConfigMock,
'AppModule re-read configuration independently',
).not.toHaveBeenCalled();
} finally {
undoSubstitutions();
vi.resetModules();
restoreProcessEnv(originalEnv);
}
},
MODULE_IMPORT_TIMEOUT_MS,
);
it(
'serves MOSAIC_CONFIG from the frozen policy rather than a fresh load',
async (): Promise<void> => {
const originalEnv = snapshotProcessEnv();
try {
vi.resetModules();
vi.clearAllMocks();
substituteStartupSurface();
vi.doMock('@mosaicstack/config', async () => {
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
return { ...actual, loadConfig: loadConfigMock };
});
const stateRoot = await establishLocalChannel();
const configModule = await import('./config/config.module.js');
const providers = (Reflect.getMetadata('providers', configModule.ConfigModule) ?? []) as {
provide?: unknown;
useFactory?: () => unknown;
}[];
const provider = providers.find(
(candidate) => candidate.provide === configModule.MOSAIC_CONFIG,
);
expect(provider?.useFactory, 'MOSAIC_CONFIG provider factory not found').toBeDefined();
const served = provider!.useFactory!() as {
tier?: string;
storage?: { type?: string; dataDir?: string };
};
expect(
loadConfigMock,
'the MOSAIC_CONFIG factory called loadConfig',
).not.toHaveBeenCalled();
expect(served.tier).toBe('local');
expect(served.storage?.type).toBe('pglite');
expect(served.storage?.dataDir).toContain(stateRoot);
} finally {
undoSubstitutions();
vi.resetModules();
restoreProcessEnv(originalEnv);
}
},
MODULE_IMPORT_TIMEOUT_MS,
);
// The positive anchor for acceptance #6. Every other case in this file is a
// refusal or an absence, and a refusal-only matrix is satisfied by production
// code that does nothing at all: an exported `bootstrap()` with an empty body
// passes all of them. This case is the one that fails against that, so "safe"
// cannot come to mean "does not work". It is in-process and substituted at the
// Nest seam — no port is bound, no database is reached, nothing is started for
// real.
it(
'starts the application through the frozen policy: create and listen are reached with no independent read',
async (): Promise<void> => {
const originalEnv = snapshotProcessEnv();
try {
process.env['BETTER_AUTH_SECRET'] = 'fixture-secret';
vi.resetModules();
vi.clearAllMocks();
substituteStartupSurface();
vi.doMock('@mosaicstack/config', async () => {
const actual = await vi.importActual<typeof MosaicConfigModule>('@mosaicstack/config');
return { ...actual, loadConfig: loadConfigMock };
});
await establishLocalChannel();
const { mod, exitSpy } = await importMainCapturingExit();
try {
const bootstrap = mod['bootstrap'] as (() => Promise<void>) | undefined;
expect(typeof bootstrap, 'main.ts does not export bootstrap').toBe('function');
await expect(
bootstrap!(),
'bootstrap rejected on the established local channel',
).resolves.toBeUndefined();
expect(nestCreateMock, 'bootstrap never created the Nest application').toHaveBeenCalled();
expect(listenMock, 'bootstrap never reached listen').toHaveBeenCalled();
expect(
loadConfigMock,
'the started path re-read configuration independently',
).not.toHaveBeenCalled();
expect(
detectAndAssertTierMock,
'the started path probed the tier independently',
).not.toHaveBeenCalled();
expect(exitSpy, 'the started path exited the process').not.toHaveBeenCalled();
} finally {
exitSpy.mockRestore();
}
} finally {
undoSubstitutions();
vi.resetModules();
restoreProcessEnv(originalEnv);
}
},
MODULE_IMPORT_TIMEOUT_MS,
);
});
@@ -279,3 +279,644 @@ The manifests above are the complete ownership universe for KBN-101 implementati
## 9. Non-goals and residual authority
KBN-101 planning does not create roles, certificates, Vault paths, migrations, deployment artifacts, or a deployed certificate. It does not replace KBN-100’s data migration, immutable retention, tenant constraints, or KBN-105 endpoint freeze. A PostgreSQL superuser/break-glass operator—including the deliberately isolated extension owner—remains outside application containment: `GRANT`/`REVOKE` cannot constrain that authority. Separate identity/non-login/zero-membership/external-control/audit controls, independent review, maintenance windows, backup/rollback evidence, and drills are mandatory.
## 10. `KBN-101-02a` — path-ownership amendment (additive)
Status: RED phase. Item `KBN-101-02a` (Stack issue #1178).
Base: `next` @ `216cd72226cd9ee17eea461cfe7cd0e010a22f02`.
This section is additive: it amends nothing above it, and sections 1-9 stand exactly as frozen by
#774 and #902. It exists because the defect that produced `-02a` was a document naming an owner
that did not **span** the deliverable. Five guides said `KBN-101-02` delivers fail-closed
local-tier/DSN isolation; `-02`'s scope row and acceptance criteria contain no startup-time refusal
at all. So the first thing `-02a` does is write its own span down, explicitly, before any code.
### What `-02a` delivers
A **dedicated local-development start channel** that refuses, fail-closed, before any connection
and before any DDL, when the start is not an explicitly-declared, isolated, local PGlite start.
The channel discriminator is **the entrypoint itself** — a distinct command whose sole contract is
local + PGlite. It is never inferred from tier value or from configuration provenance. Inside the
channel, a non-local tier is refused from _any_ source; there is no explicit or session-scoped
admission of a non-local tier in `-02a`. (Explicit session-scoped admission belongs solely to the
separately sanctioned disposable-demo path, which is not this item and certifies nothing.)
### Admission contract — everything below is required, and empty/default refuses
A local start is admitted only when all of the following are explicitly declared for this
invocation:
| Requirement | Rule |
| ----------- | ----------------------------------------------- |
| tier | explicitly `local` |
| storage | explicitly `pglite` |
| queue | explicitly local |
| state root | explicit, absolute, session-created, disposable |
Derived state is canonicalized under the declared state root: the DB, storage, and queue children
all resolve beneath it. A child that escapes the root — by `..` traversal or by symlink — is
refused. `HOME`- and CWD-derived defaults are never used to locate state.
Cross-field consistency is part of the contract, not a separate nicety: `local` + `postgres`,
`local` + `files`, and non-local + `pglite` are all refused, as is any mismatch between the
declared and resolved shape.
### Forbidden in the local channel, from any source
- **Any PostgreSQL DSN.** No role classification is attempted. A DSN cannot be proven
superuser-or-not without connecting, and connecting is the thing being prevented — so the rule is
the simple provable one: every PostgreSQL DSN, including the `DEFAULT_DATABASE_URL` fallback
constant, is forbidden.
- **Any non-local tier value.**
A forbidden value refuses **even when it is shadowed** — that is, even when precedence means it
would not have won. Every source is inspected independently, before precedence is applied.
### Source inventory — the complete set
| Label | Location |
| ---------------------- | ------------------------------------------- |
| `process-environment` | inherited ambient environment |
| `daemon-dotenv` | `$HOME/.config/mosaic/gateway/.env` |
| `monorepo-root-dotenv` | anchored monorepo root `.env` |
| `gateway-local-dotenv` | anchored `apps/gateway/.env` |
| `daemon-json` | `$MOSAIC_GATEWAY_HOME/mosaic.config.json` |
| `app-json` | anchored `apps/gateway/mosaic.config.json` |
| `monorepo-root-json` | anchored monorepo root `mosaic.config.json` |
**`MOSAIC_GATEWAY_HOME` redirects the daemon JSON only.** The daemon dotenv remains at
`$HOME/.config/mosaic/gateway/.env` regardless of the redirect. This is the real distinction in
`apps/gateway/src/env.ts` and it is not widened here.
The CWD-relative bare `loadConfig()` search is **not** part of this inventory: the gateway always
passes `resolveGatewayConfigPath()`, and existing AppModule coverage proves the CWD JSON path is
ignored. No new input is created for it.
### Freeze contract
The channel establishes **one** resolved policy, once:
- allowed-only object, deep-cloned then deep-frozen;
- a second establish attempt **fails**; there is no reset API;
- rejected raw JSON, dotenv contents, DSNs and secrets are **neither retained nor logged**;
- errors expose source **labels** and stable **codes** only — never values.
Every consumer in the local channel reads that frozen policy. No consumer performs a second
independent read, so a post-freeze mutation of the environment or of a config file changes nothing
any consumer sees.
Normal (non-local) startup uses a separate explicit legacy path. There is no
`getFrozen() ?? loadConfig()` masking: the two channels do not fall through to one another.
### Import-order contract — load-bearing
`local-dev.ts` statically imports **only** the policy and inventory modules. It establishes the
frozen policy first, and only then **dynamically** imports the exported `bootstrap()` from
`main.ts`. Importing `main.ts` must not start anything by side effect. The local `env.ts` path
performs no dotenv load and no re-read.
This ordering is what makes "refused before connection" true rather than asserted: the modules that
can connect are not even loaded until the policy has been established.
### Path ownership — the 16-path fence for `-02a`
These paths are assigned to `-02a`. A 17th path is a STOP.
Revision 15 → 16 was granted by the verifier on the AMEND verdict, solely for
`apps/gateway/src/main.spec.ts`, so the frozen policy can be proven against the actual entrypoint
and module graph rather than against a wholesale mock of them. No other path was added, and
`app.module.spec.ts` was explicitly not authorized.
| # | Path |
| --- | --------------------------------------------------------- |
| 1 | `docs/native-kanban-sot/KBN-101-DB-ROLE-SPLIT.md` |
| 2 | `apps/gateway/package.json` |
| 3 | `apps/gateway/src/env.ts` |
| 4 | `apps/gateway/src/app.module.ts` |
| 5 | `apps/gateway/src/config/config.module.ts` |
| 6 | `apps/gateway/src/database/database.module.ts` |
| 7 | `apps/gateway/src/main.ts` |
| 8 | `apps/gateway/src/env.spec.ts` |
| 9 | `apps/gateway/src/database/database.module.spec.ts` |
| 10 | `apps/gateway/src/local-start/source-inventory.ts` |
| 11 | `apps/gateway/src/local-start/source-inventory.spec.ts` |
| 12 | `apps/gateway/src/local-start/local-start-policy.ts` |
| 13 | `apps/gateway/src/local-start/local-start-policy.spec.ts` |
| 14 | `apps/gateway/src/local-dev.ts` |
| 15 | `apps/gateway/src/local-dev.spec.ts` |
| 16 | `apps/gateway/src/main.spec.ts` |
**Not owned by `-02a`, and not touched by it:** `packages/db/src/client.ts` (`-01`),
`packages/db/src/migrate.ts` (`-03`), `packages/db/src/credential-handoff/**` (`-10`),
`packages/config/src/mosaic-config.ts`. `-02a` takes no runner or migration ownership. It proves
the local entrypoint never _reaches_ those paths, from a higher seam, rather than modifying them.
### Zero-side-effect bars
Every refusing case proves zero of each: tier probe (`detectAndAssertTier`), `createDb`,
`createStorageAdapter` / PostgresAdapter construction, `runMigrations`, extension DDL, and
`NestFactory.create`.
A case that connects and then rolls back fails these bars by construction. That is deliberate.
### Mutation → guard mapping
Each row names one guard, one mutation that removes it, and the case that must go red when it is
removed alone. Aggregate reverts do not satisfy this.
| # | Guard | Mutation that removes it |
| --- | --------------------------------------------- | ------------------------------------------------------ |
| 1 | inherited-env source inspected | drop `process-environment` from the inventory |
| 2 | shared dotenv sources inspected | drop the two anchored dotenv sources |
| 3 | daemon JSON source inspected | drop `daemon-json` |
| 4 | app JSON source inspected | drop `app-json` |
| 5 | root JSON source inspected | drop `monorepo-root-json` |
| 6 | redirect followed | ignore `MOSAIC_GATEWAY_HOME` when locating daemon JSON |
| 7 | exact local tier required | accept any tier value |
| 8 | exact PGlite + disposable state root required | accept any storage type / default the state root |
| 9 | one-shot freeze + dynamic import | allow re-establish, or statically import `main.js` |
A guard whose case survives its own removal is reported as such. A green test that cannot fail for
its stated reason is the same defect class as the span gap that created this item.
### RED phase result
Focused matrix, gateway package: **83 failing / 17 passing (100 cases, 6 files)**, and the terminal
summary carries **no `Errors` row at all**. Typecheck, lint and Prettier clean. Every failure is an
assertion that names what it wanted — the matrix output was scanned specifically for `TypeError`,
`ReferenceError`, missing-export and module-resolution text, not merely counted. Most of those
assertions are behavioral, but not all of them: the structural guards over this file's own source
text are assertions too, and they are counted in the same 83. The claim is that nothing failed by
accident, not that every failure describes runtime behavior.
An earlier version of this section reported that figure as "terminal `Errors 0`", which is not a
thing vitest prints. It emits an `Errors` row **only** when an out-of-band error is attributed to
no case; at zero the row is absent. The measured claim is the absence of the row, and the wording
above says so. The distinction matters because "`Errors 0`" reads as an observed zero, and a reader
who went looking for it would find nothing and could not tell whether the run was clean or the
claim was invented.
**Correction to the previous report's error claim.** It said "zero non-assertion failures", and
that was wrong at the time it was written: the run also carried one out-of-band
`process.exit unexpectedly called with "1"`, raised by `main.ts:71` self-invoking on import and
rejecting after the importing case had already returned. Vitest attributes such an error to no
case and warns it can produce false positives. It is now captured inside the case that provokes
it — `process.exit` is stubbed non-throwing for the duration of the import and the case awaits a
settle turn — so the behavioral red is unchanged and the run no longer emits the row. The claim
above is a measurement, not an inference.
**The child-process fixture is an allowlist, and that is what makes the three package-route cases
mean anything.** It was a denylist: copy the whole ambient `process.env`, delete three keys. That
left the real `HOME`, every XDG root, `MOSAIC_GATEWAY_HOME`, service endpoints, the auth and
credential families, the Node loader controls, and an ambient `PATH` in place. Two failure modes
follow, and both are worse than having no case at all. A faulty GREEN could read real host state
before any assertion caught it. And a refusal could be produced by the host's own configuration
rather than by the route, so the case would pass while proving nothing about the code under test.
A denylist is bounded only by the enumeration of what is known to be dangerous, which is open;
an allowlist is bounded by what the route actually needs. The child now receives exactly ten
variables — a private `HOME` under a per-run temporary sandbox, the four `XDG_*_HOME` roots and
`XDG_RUNTIME_DIR` plus both XDG _directory lists_ and `TMPDIR` beneath it, and an explicit
`PATH` — plus whatever the
individual case declares. Nothing is inherited. The hard timeout and `SIGKILL` are unchanged; a
timeout bounds how long a leak can run, it does not prevent one.
Three details in that set are not obvious, and each was a hole before it was closed.
`XDG_CONFIG_DIRS` and `XDG_DATA_DIRS` are set to private empty directories rather than omitted.
Omission is not neutral for the XDG _lists_: unset, they mean `/etc/xdg` and
`/usr/local/share:/usr/share`, so an eight-key allowlist that left them out still exposed two real
system config and data roots while claiming full isolation. Setting them to the empty _string_ is
no better — the specification says a set-but-empty list falls back to the same defaults — so the
value has to be a real directory that happens to be empty.
The shell is resolved to a validated absolute path (`/bin/sh` or `/usr/bin/sh`, checked to exist
and to be a file) instead of the literal `sh`. The literal resolved only because an earlier
construction of `PATH` happened to contain the shell's own directory, which was a property of this
host's layout rather than of the fixture. The shell is now invoked by that validated absolute path
and needs no `PATH` entry at all; widening `PATH` to find one would reopen the
executable-resolution hole the allowlist exists to close.
**`PATH` was the last part of the child environment still built as a denylist, and calling it an
allowlist was false in a way that a measurement settles.** It named the two workspace
`node_modules/.bin` directories, the directory of the running Node binary, and the shell's
directory. Measured on the author's host that is 4,093 distinct executable names, and on the
reviewer's 2,650 — because `dirname(process.execPath)` is `/usr/bin`. Both numbers are stated with
whose run produced them on purpose. A count of what is reachable through `/usr/bin` is a property
of a host and its install state, not of the candidate tree, and presenting either figure bare would
repeat this item's own defect: a number offered as a property of the artifact when it is a property
of the observation. What does not vary between the two runs is the shape — an unbounded system
directory on a fixture `PATH`. Worse than the count: `apps/gateway/node_modules/.bin` carries real agent-runtime
executables this repository depends on directly — `pi` (`@mariozechner/pi-coding-agent`), `pi-ai`,
`openai`, `anthropic-ai-sdk`. At GREEN, any accidental resolution of one of those names from the
package script or its process tree reaches a real agent runtime with real capability. The hard
timeout bounds how long that runs; it does not prevent it. A directory list is not a capability
allowlist, and the comment on that construction claimed it stopped exactly the resolution it
permitted.
`PATH` is now a single fixture-owned directory inside the per-run sandbox, holding two symlinks and
nothing else: `node` to `process.execPath`, and `tsx` to the TSX CLI artifact itself
(`tsx/dist/cli.mjs`). `env` needs no entry, because a `#!/usr/bin/env node` shebang invokes `env` by
absolute path and only `node` is resolved through `PATH`. Both targets are resolved through
`realpath` and asserted to be executable files at module scope — before the first child is created,
not inside a case that may run after other cases have already spawned — and the symlinks are built
from those checked values, so the construction and the control's identity assertions cannot drift
apart. Measured: two reachable executable names; `command -v pi` reports the real `.bin/pi` under
the old construction and not-found under the new one; `tsx --version` still succeeds.
Reaching two rather than five took a second correction, and the intermediate step is worth
recording because it was wrong in an instructive direction. The first narrowing symlinked
`apps/gateway/node_modules/.bin/tsx`, which is not the TSX CLI: it is a pnpm-generated `/bin/sh`
launcher. That forced three coreutils symlinks onto `PATH` (`dirname`, `sed`, `uname`, which the
launcher calls to locate its own entrypoint) and one off-`PATH` directory symlink to restore the
`$0`-relative package layout it expects. Five names and a layout fixture, all of them serving a
wrapper. The wrapper also **exports `NODE_PATH`** naming four real repository module roots into the
process it starts — so a fixture whose stated invariant is that the child receives no Node loader
controls was shipping a `tsx` that reinstated one. That was first recorded here as a bound; the
reviewer ruled it had to be fixed rather than bounded, and the ruling produced the smaller design
rather than a larger one. Executing the CLI directly deletes the wrapper, the `NODE_PATH`
injection, three symlinks and the layout fixture at once. Measured through the two-name `PATH`, the
child's key set is `HOME PATH PWD SHLVL TMPDIR XDG_CACHE_HOME XDG_CONFIG_DIRS XDG_CONFIG_HOME
XDG_DATA_DIRS XDG_DATA_HOME XDG_RUNTIME_DIR XDG_STATE_HOME` — neither `NODE_PATH` nor
`NODE_OPTIONS`. Wrapper parity was never a fixture goal; this is a fixture-owned command boundary
executing the same CLI the route executes.
The control does not assert that in prose. It splits the child's **observed** `PATH`, reads each
directory, collects every entry that is an executable file, and asserts that name set **equals**
the allowlist. Equality is the point: a "does not contain" check is the denylist shape, and the
denylist shape is what failed here — an enumeration of known harness names finds `pi` and misses
`pi-ai`, `openai` and `anthropic-ai-sdk`, three of the four actually present. The seven harness
names are still asserted individually, and that assertion is redundant by design and commented as
such: set equality catches every addition including ones nobody enumerated, while the named
assertion is the one whose failure message a maintainer will understand. Each symlink's target is
also asserted to resolve to the exact expected binary, so a fixture-owned `tsx` cannot quietly
become something else.
Two bounds on that claim, stated because the recurring defect in this item is prose crediting a
mechanism with a property it lacks. First, the claim is about **command resolution**, not about
everything the route can reach. Removing the wrapper removes the `NODE_PATH` the fixture was
injecting, and the two-name child carries no loader control at all — but at GREEN the route runs
repository code against repository `node_modules`, and `node_modules/.pnpm/node_modules` holds 775
packages including `@mariozechner/pi-coding-agent`, `@anthropic-ai` and `openai`. Those runtimes
are not resolvable as _commands_; they remain present as _modules_, and nothing at this layer could
change that without changing what the route is. "Not resolvable as a command" is the whole claim,
and "unreachable" is not a sentence this document gets to write. Second, executable enumeration is
a mechanical coverage check and is separate from reading source: the review that passed this
fixture before the hole was found was bounded by paths whose directory contents it never listed,
which is precisely why the guarantee is now measured by the fixture rather than observed by a
reviewer.
This is the third real-runtime-reachability incident in this window — the FL-09 ambient OpenCode
fall-through, the review command-substitution Claude launch, and now real agent executables on a
fixture `PATH` alongside the system bin directory. Taken together they argue for two standing
properties rather than three separate patches: fail-loud semantics when a real fall-through is
possible, and capability-minimal fixture `PATH`s. Private `HOME`/XDG roots and a hard timeout
reduce exposure; neither proves that no runtime or auth state was read.
The claim is **not** that the final route process receives the builder's key set exactly. The route
is executed through that shell, and a POSIX shell sets some of its own bookkeeping names. The
permitted set is five — `IFS`, `OLDPWD`, `PWD`, `SHLVL`, `_` — and in the observed runs the shell
added exactly two of them, `PWD` and `SHLVL`. The permitted list is deliberately wider than the
observed additions, because which of the five a given `/bin/sh` sets is a property of that shell,
not of this fixture; the assertion requires only that any addition be drawn from the five. Each is
derived from the invocation — `PWD` from `cwd`, `SHLVL` from a counter, `_` from the last word of
the command — so none carries host state, but they are additions and the document says so rather
than rounding them away. The measured claim is: the shell-mediated child receives every allowlisted
name with the value the builder constructed for it, and every name beyond the allowlist is one of
those five. That measurement is of the control's own arm, which runs `sh -c 'exec node -e …'`. It
does not describe the GREEN route. What the route's own process ends up holding is unmeasured until
there is a GREEN to measure.
**The package-script contract was a substring check followed by arbitrary shell execution, and the
two halves were never read together.** The manifest case asserted the script _contained_
`src/local-dev.ts`; the executing helper then handed the whole string to `sh -c`. So
`"curl … | sh; tsx src/local-dev.ts"` satisfied the assertion and was then run — as would anything
carrying `&`, `;`, `|`, a backtick, `$( )`, a redirect, or a second absolute command. Neither line
is wrong in isolation, which is why it survived several readings: a substring check is a reasonable
thing to write about a script you are only inspecting, and `sh -c` is a reasonable thing to write
about a script you have already validated. The defect exists only in the seam between them. The
contract is now a single module-level constant, `exec tsx src/local-dev.ts`, spelled exactly once in
the file, asserted with equality in the manifest case **and** re-asserted inside the executing
helper against the value about to run — the manifest is read twice, so the check that matters is the
one sitting on the string being executed. No metacharacter denylist backs it up: exact equality
already excludes every metacharacter anyone would enumerate, and a denylist here would repeat the
mistake the `PATH` allowlist was built to correct.
**The hard timeout does not contain the route's process tree, and the required script is the reason
— not an attacker's.** `spawnSync`'s `timeout` with `killSignal: 'SIGKILL'` signals the process it
directly invoked and nothing below it. Two measurements bound what that is worth, and both were
produced by probing rather than by reading the documentation.
The first is why the route must `exec`. With a backgrounded job — `node -e '…' & echo started` —
the shell returns 0 **immediately**, so the timeout never fires at all: the case observes a clean
exit, the descendant outlives the run, and sandbox teardown then races a live process still holding
paths inside the directory being removed. That is not merely a containment gap; it is a
**silent-pass** path, a control reporting success in exactly the scenario it exists to catch.
Requiring `exec ` at the head of the contract removes the intermediate shell so the signal reaches
the process that matters.
The second is the one that stops this item from claiming the pair is sufficient. `exec` removes the
outer shell; it does not make TSX one process. The selected CLI spawns an `esbuild --service` child
and a `node --require preflight.cjs --import loader.mjs --eval` child, and the second is where the
route's own code runs. Under the fixture's exact spawn shape, four trials out of four, the parent
received `SIGKILL` and that loader child **survived it**, was reparented away from the dead parent,
and went on to complete its work afterward — writing its marker while the fixture believed the
child was gone. The esbuild child did not survive or accumulate in those runs, so the survivor is
the loader child specifically. An earlier probe of the author's appeared to show the whole tree
dying; it enumerated descendants by the killed parent's PID, and reparenting had already moved them
out of that set, so the survivors were live and the filter structurally could not see them. That
probe is recorded here rather than discarded, because a measurement that cannot observe the
violation it is testing for is the same defect class as a review bounded by paths it never listed.
What follows is stated plainly because the temptation to round it off is exactly the failure mode
this item documents: **exact script equality plus `exec` is not process-tree cleanup.** It prohibits
_injected_ shell content, which is worth having on its own terms. But the launcher the contract
_permits_ is multi-process, so a timed-out route can still leave a live process inside a sandbox
being torn down. The fixture's timeout control asserts what it actually measures — a single-process
`exec node -e` sleeper is killed and writes nothing — and it is named for that property alone. No
assertion in this file establishes descendant containment, and the control is not offered as
evidence of it.
One further measurement decides what any containment design may look like, so it is recorded here
rather than left for whoever writes that design to rediscover: every process in the TSX tree runs in
**the verifier's own process group and session**. Parent, esbuild child and loader child all carry
the test runner's `pgid` and `sid`, because a spawn inherits both by default. The consequence is
sharp — the obvious repair, signalling the negative process-group id, would signal the test runner
itself. Group containment is therefore not a matter of sending a different signal to the tree as it
exists; it requires the child to be given a group of its own at spawn time before any group-directed
signal is safe to send. Which design does that, and whether the resulting emptiness proof is
reuse-safe to the reviewer's standard, is under adjudication and deliberately not settled by the
author. This section will record the ruling and the residual — including the one no group-based
design can close, a descendant that calls `setsid()` for itself and leaves the group.
**There is exactly one place in the file where a child process is created**, and that is the
mechanism, not tidiness. A control that made its own spawn would leave the route's spawn free to be
reverted to an ambient copy while the control stayed green — and that revert is invisible from the
outside, because an ambient copy also strips the planted declarations, so the canary still gets the
refusal it expects while real host state leaks alongside it.
**One site is necessary and was not sufficient, and the gap was a check/use gap.** The first
version of this argument said the control and the route received the same environment _by
construction_, because there was only one place an environment could be built. That was too strong,
and the counterexample is exact rather than theoretical: the site validated the caller's per-case
object and then spread it, which enumerated that object **twice**. A `Proxy` returning one legal
name to the validating enumeration and the whole ambient environment to the spread passes the guard
and reaches the child — verified in a standalone probe, where validation reported no offending keys
while the merge copied ambient names and overrode `HOME`. One spawn site constrains _where_ an
environment is built; it says nothing about _what_ the caller may hand that site.
The first repair of that was itself too weak, and the second counterexample is worth recording
because it is the same defect wearing different clothes. That repair snapshotted the caller's
object and then validated the snapshot with a fresh `Object.keys` call — two calls again. A
**non-Proxy** object defeats it: a getter on a declarable key replaces the global `Object.keys`
while `Object.entries` is still collecting, so the forbidden names land in the snapshot and the
later lookup reports none. Also verified by probe. Detecting `Proxy` did not help, because the
input was not one.
What holds it now is that the site enumerates the caller's object exactly **once**, into an entries
array, and derives **both** the validated name list and the merged object from that same array. The
caller's object is never read again, so neither of the two exploits above works: there is no second
read of caller-controlled data for an accessor to sit between. The snapshot's keys must be drawn
from an exact five-name list — the four the route reads plus `DATABASE_URL` — not an open
`MOSAIC_LOCAL_DEV_*` prefix, because a prefix is wide enough to carry host variables the route
never reads; and its values must all be strings, so a getter cannot place a non-string in the child
environment. The list is frozen, so a case cannot extend it before declaring. Adding a sixth name
is an edit to that list. A `Proxy` is additionally rejected outright, but that is secondary defense
and is documented as such.
**The third statement of this claim was also too strong, and the bound is now stated instead of
narrowed again.** An earlier version of this paragraph said no second call to any replaceable
global stands between the check and the use, so the check and the use could not describe different
values whatever the caller did. That is false. The helper calls `Object.fromEntries`, `map` and
`filter` after the enumeration, `buildHermeticChildEnv` later reads the writable `process.execPath`
and calls `Set` — and a getter firing during the single enumeration can replace any of them. The
guard is therefore not a sandbox and cannot become one at this layer, because the cases share a
closure with it: an author who can patch a global can also patch the guard. What the guard actually
does is reject an ambient copy or a stray name **passed as a declaration**, which is the mistake a
maintainer makes by accident. That is worth having, and it is all that is claimed. Three
consecutive repairs tried to make it more than that; the third one added a callback to the spawn
site and had to be reverted, which is the evidence that the escalation was the wrong move rather
than an incomplete one.
Both exploits above were re-run against the final guard and neither reaches a child. They are
rejected by different assertions, which is worth stating precisely because an earlier version of
this paragraph claimed both were named by the offending-keys message: the ambient copy is, and the
`Proxy` is stopped one assertion earlier by the `isProxy` check, whose message names no keys at
all. That proof runs through the spawn site **directly**, not through the package route, because at
RED head the absent `dev:local` script legitimately stops the route arm before it can spawn. An intermediate version reordered that — it added a `beforeSpawn`
callback to the spawn site so route setup assertions ran _after_ the input guard, purely so the
mutation failed on the guard rather than on the missing script. That was removed. It bought nothing
but a more legible proof, and it cost a caller-supplied function executing inside the one guarded
site, plus an `as string` cast that put `undefined` in the argument array and was safe only because
the callback happened to throw first. How a proof reads is not a property of the artifact, and the
mechanism this whole item rests on is the last place to accept new surface for it.
A structural assertion guards the shape the argument depends on: the spec asserts against its own
source that `node:child_process` is imported exactly once as the named form `{ spawnSync }`, that
the `spawnSync` identifier occurs exactly twice (its import and its one call), and that
`...process.env` occurs nowhere. That is aimed at the one revert behavioral assertions cannot see,
since a behavioral case only ever observes the spawn it makes itself. It is a source-text
heuristic and is documented as one: a child created through an indirection it does not name would
not redden it. It is stated here as a guard, not as a proof.
`fixture control: the spawn site delivers exactly the allowlist to a real child` is the only case
in the package-route arm that runs a child at RED head, and it measures the environment **from
inside the child** rather than from the object handed to `spawnSync`. It spawns twice through that
one site: directly, where the observed key set must equal the allowlist exactly and the child's
`HOME` must be neither the real home nor an ancestor of it; and through the trusted shell, which is
the route's own shape, where every allowlisted name must be present, must still carry the value the
builder constructed for that spawn's own sandbox, and every added name must be one of the shell's
bookkeeping names. Presence alone was not enough: a shell-mediated child that changed `HOME`,
`PATH` or an XDG root would keep every name and stay green. Beyond the key set, it enumerates the
directories on the child's observed `PATH` and asserts the reachable executable names **equal** the
allowlist, asserts the seven known agent-runtime names are absent, and asserts each symlink resolves
to its exact expected binary. It is green by construction and is a **harness control, not
coverage** — it asserts nothing about the code under test. Its purpose is to redden if the fixture
is widened back toward the ambient environment, including by a new executable appearing on `PATH`
that nobody thought to name.
`does not leak the parent ambient environment into the child` is the route-arm half, and it is
**pending execution until GREEN**. At RED head there is no `dev:local` script, so the manifest
assertion fires before any child is created: the case is red for that reason, and its hermeticity
claim is not yet measured by it. Recording it as an executed proof would classify a case that never
spawned as evidence about a subprocess, which is the overclaim the vacuous-green itemization exists
to prevent. What it will assert once the route exists: the parent plants a complete, valid local
declaration **and** a forbidden DSN in its own environment, then runs the route with nothing passed
in, and requires `LOCAL_START_TIER_NOT_EXPLICIT` specifically. A leaky fixture would hand the child
a valid declaration, so that refusal would not fire and the DSN refusal would fire instead — the
discriminator. Both route-arm cases name the exact refusal code rather than matching
`/LOCAL_START_[A-Z_]+/`; the family pattern let an unrelated refusal stand in for the one under
test, which is the same defect as asserting a raw source value against a classification union.
The matrix leaves **zero `/tmp/kbn-02a-*` residue**, measured by removing all matching roots
before the run and counting after it. Every `mkdtemp` site in `local-dev.spec.ts` registers its
root for teardown at the point of creation, including the child sandbox, which is created in
`spawnHermetic` immediately before the spawn call and was the one most easily missed. One root
elsewhere in the matrix — `main.spec.ts:58`, outside the `kbn-02a-` prefix the residue count
measures — is removed by its own `finally` rather than by registration; that is a second cleanup
path, not a leak, and it is named here so the sentence is not read as covering more than it does.
The earlier passes leaked one directory per case.
Ten of the sixteen fenced paths are touched in RED. The six GREEN targets (`package.json`,
`env.ts`, `app.module.ts`, `config/config.module.ts`, `database/database.module.ts`, `main.ts`)
are deliberately unmodified, so their specs are red against the production files as they stand.
**Correction to the first RED report.** That report implied the fenced REDs covered the GREEN
targets behaviorally. They did not. Every frozen-policy case mocked `./main.js` wholesale, so
nothing executed `main.ts`, `AppModule`, or the `ConfigModule` provider, and the three independent
reads at `main.ts:28`, `app.module.ts:39` and `config.module.ts:12` could all have survived a
fully green matrix. The report also claimed the zero-side-effect bars as proven; they were proven
only against scaffolding. This pass closes the first gap and narrows the second:
- `main.ts`, `app.module.ts` and `config/config.module.ts` now have behavior-first REDs that
import the real modules with no `./main.js` mock, and assert no independent `loadConfig`, no
`detectAndAssertTier`, and no `NestFactory.create` (bars Z1 and Z5 through the actual path).
- `database.module.ts` now has REDs that drive the real `onModuleInit()`, asserting that migration
and adapter-migrate never run (bars Z3 and Z4) — still through constructor substitution, not
through a full application boot.
- `package.json` now has a RED that _will_ execute the packaged `dev:local` route as a child
process, requiring a `LOCAL_START_*` code in its output and the absence of the
`BETTER_AUTH_SECRET` throw, so a crash or an unrelated failure cannot satisfy it. At RED head it
does not get that far: the script does not exist yet, so the case stops on the missing manifest
entry before any child is created. It is red for the right reason, and the child-process
behavior it specifies is unmeasured until GREEN adds the script.
- `env.ts` remains covered only by legacy-continuity regression guards, by design.
The bars are therefore proven through the actual entrypoint for the probe and application-create
side effects, and through the real database lifecycle for the migration side effects. They are not
yet proven through a full boot, and this document does not claim they are.
**Positive anchors — added because a refusal-only matrix is satisfiable by dead code.** Every
other case in this item asserts an absence: no read, no probe, no migration, no application. A
`bootstrap()` with an empty body and an `onModuleInit()` that always refuses would satisfy all of
them, and "safe" would come to mean "does not work". Two cases fail against exactly that:
`main.spec.ts` requires the exported `bootstrap()` to reach `NestFactory.create` and `listen`
under an established frozen policy with zero independent read or probe (in-process, substituted at
the Nest seam — no port is bound), and `database.module.spec.ts` requires the sterile local
lifecycle to actually run both PGlite and adapter migrations with no Postgres handle constructed.
The second is green today and must stay green; it replaced a case that awaited
`onModuleInit().catch(() => undefined)` and asserted only an absence, which a total failure
satisfied.
The seventeen passing cases are itemized rather than counted as coverage, because a green that
cannot fail for its stated reason is the same defect class as the span gap that created this item:
| Passing case | Why it is green |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| env: config read on import, no policy | legacy regression guard — expected green |
| env: planted dotenv loads, no policy | legacy regression guard — expected green |
| main: anchored config reaches `detectAndAssertTier` | current-contract regression guard; its import-time-exit premise is superseded and must migrate at GREEN |
| local-dev: production `dev` script untouched | regression guard — expected green |
| local-dev: no static import of `main.js` | structural, three forms (binding, side-effect, `require`); must stay green |
| local-dev: importing starts nothing | structural; green today only because nothing invokes `runLocalDev` |
| policy: refuses to serve when unestablished | scaffolding implements this correctly already |
| policy: no fallback read when unestablished | scaffolding implements this correctly already |
| inventory: retains no raw DSN text | **vacuous today** — the stub returns an empty inventory |
| inventory: retains no planted canary | **vacuous today** — same empty inventory |
| inventory: writes no planted canary to the console | **vacuous today** — the stub reads no source, so it can log none |
| policy: children beneath the state root | **vacuous today** — the stub concatenates the declared root |
| policy: unaffected by post-establish input mutation | **vacuous today** — the stub captured strings, it did not clone |
| policy: frozen policy survives a source file gaining a DSN | **vacuous today** — the stub re-serves the same object it built |
| policy: frozen policy survives the environment gaining a DSN | **vacuous today** — same |
| database: sterile local lifecycle migrates, no Postgres seam | positive anchor — green today, must stay green; the one case that fails if GREEN makes "safe" mean "inert" |
| local-dev: fixture control — spawn site delivers the allowlist | harness control, not coverage — green by construction; the only case that runs a child at RED head, and the guard on the instrument the other three depend on |
Seven greens are vacuous until the implementation exists, up from three, because an earlier pass
added retention and post-freeze-mutation cases that a stub satisfies trivially. They are evidence
of nothing today and are re-checked at GREEN. The count rising is the honest outcome of asserting
more about a module that does not exist yet — it is recorded here so it cannot later be read as
coverage. Of the ten non-vacuous greens, one is the harness control above — it asserts
nothing about the code under test and is never counted as coverage — seven are guards that must
stay green (two legacy continuity, the untouched `dev` script, the structural no-static-import,
the two unestablished-policy refusals, and the database positive anchor) and two are green for a
weaker reason than they read: `local-dev` "starts nothing on import" is green only because nothing yet invokes
`runLocalDev`, and the `main.ts` anchoring case guards a current contract whose import-time-exit
premise `-02a` inverts, so it must be migrated at GREEN rather than deleted.
**Classification is a type obligation, not only a wording one.** Two inventory cases demanded the
raw source values `'standalone'` and `'postgres'`, which the value-free classification unions
cannot represent — a compliant implementation could never have turned them green. They now assert
`'non-local'` and `'non-pglite'`. In the same vein `SourceReadability` gained `absent`: without
it an absent source has to be reported `readable`, which is the one value meaning "read, and
clean", collapsing the exact distinction the refusal path is built on. The invariant
`present === false` if and only if `readability === 'absent'` is asserted directly, per state and
across all seven rows at once.
### Scope discipline
`-02a` neither breaks production-like entrypoints nor authorizes their local use. They resolve
exactly as they do today when no local channel is active, and they remain held.
### Span audit of every "held until \<item\>" claim
Commissioned with `-02a` because the item exists to close one instance of this defect, and one
instance is not evidence about the rest. A claim is defective when a guide conditions a hold on an
item whose scope row and acceptance criteria do not contain the named capability — the item can
land complete and the hold's stated condition still not be met.
**Finding 1 — the `-02` local-start hold has a wider site surface than recorded.** The item record
names five doc sites. The claim is actually carried by **eight files**, two of them repo-root and
operator-facing:
| File | Lines |
| ------------------------------------------- | ------------- |
| `AGENTS.md` | 89 |
| `README.md` | 237, 255 |
| `docs/guides/dev-guide.md` | 116, 136, 301 |
| `docs/guides/deployment.md` | 21 |
| `docs/PRD.md` | 1207 |
| `docs/native-kanban-sot/SHARED-CONTRACT.md` | 34 |
| `docs/federation/SETUP.md` | 34 |
| `docs/guides/migrate-tier.md` | 4, 61 |
Consequence for `-02a`'s own completion: updating only the five recorded sites leaves at least
three stale, including `AGENTS.md` and `README.md` — the two files an operator or a fresh agent
seat reads first. A stale site does not merely lag; it re-asserts the hold `-02a` lifted and points
at the wrong item.
**Finding 2 — candidate defect of the same shape, at `-05`.** `SHARED-CONTRACT.md` §35, `PRD.md`
§1209 and `dev-guide.md` §301 hold production deployment until "the KBN-101-05 renderer-backed
process-exec or `LoadCredential` interface exists". In this contract, `process-exec` and
`LoadCredential` occur four times — in `-02`'s row, `-07`'s docs row, and the documentation
disposition rows, always as a _consumer boundary_ or an explicitly _non-executable schematic_.
**`-05`'s own scope row contains neither term.** Its deliverables are the renderer plus the
Compose/stack/image files, stated entirely in render-and-mount terms. Exec-time credential passing
and rendering files into mounts are different mechanisms, not two descriptions of one. So `-05` can
satisfy every criterion it has while that interface does not exist.
Confidence is lower than for `-02`: `-05` genuinely owns the credential-delivery seam, so this may
be an under-specified scope row rather than an absent owner. It is not provable from the criteria
as written, and the disposition belongs to the integration gate, not to `-02a`.
**Finding 3 — negative result, recorded because a one-sided audit is not an audit.** The
PostgreSQL/federated activation hold spans correctly. External bootstrap resolves to `-00`'s
exclusive `infra/pg-bootstrap/**` ownership; runner `--run`/`--verify` resolves to `-03`'s exact
`mosaic-db-migrator --help|--run|--verify` contract; Gateway/Compose readiness resolves to `-05`'s
Compose/stack ownership. Every named capability lands in a scope row that contains it.
**Finding 4 — structural.** None of these claims is machine-checkable. Nothing links "capability
named in a guide" to "capability present in an item's criteria", which is why the `-02` gap
survived review at eight sites.
A related observation, **downgraded on review and recorded at its corrected strength**: the `-05`
rows name `apps/gateway/Dockerfile`, and no such file exists (the current image source is
`docker/gateway.Dockerfile`, 1996 bytes). An earlier revision of this audit called that the inverse
form of the same defect. That was wrong, and the correction is the more useful finding.
`docs/scratchpads/771-kbn101-db-role-split.md:98` records the path explicitly as "a planned
KBN-101-05 artifact", so the row names something intended to exist rather than mis-naming something
that does. The status is **unresolved planned-versus-current ownership** — which of the two paths
`-05` ultimately owns is a disposition for that item, not a typo for anyone to correct. The
negative existence evidence stands; the defect classification does not.
That correction sharpens the control rather than weakening it. A naive link check that failed on
any ownership row whose path is absent would have flagged this row and been wrong, because a
planning contract legitimately names artifacts that do not exist yet. So the check has to
distinguish the two, and the cheapest way is to make the document say which it means: an ownership
row naming a path that does not exist must mark it **planned**, and an unmarked absent path is the
failure. Without that marker there is no way to tell a forward-looking row from a stale one, which
is precisely the ambiguity this finding walked into.
Suggested control, for every lane rather than this one: resolve each `held until <ITEM>` claim to a
scope row or AC containing the named capability, and each ownership row to either an existing path
or an explicit planned marker; fail CI on an unresolved claim. `-02a` does not implement it; the
finding is filed for the integration gate.