diff --git a/apps/gateway/src/local-dev.spec.ts b/apps/gateway/src/local-dev.spec.ts index 5ad753540..c2602db62 100644 --- a/apps/gateway/src/local-dev.spec.ts +++ b/apps/gateway/src/local-dev.spec.ts @@ -4,6 +4,44 @@ * Covers mutation->guard row 9 (one-shot freeze + dynamic import) and the * zero-side-effect bars Z1-Z5. * + * Containment gate register: + * + * - G1 requires a safe positive child pid. + * - G2 excludes the verifier pid and process group. + * - G3-S requires pgid === sid === child pid. Its subordinate spawn-boundary + * floor rejects older identities. + * - G4 rejects unreadable member identity. + * - G5 revalidates identity after every settle. + * - G6 tracks pid and starttime pairs across rounds. + * - G7 permits a negative signal only immediately after at least one fully + * verified member. + * - G8 proves emptiness only through ESRCH from the kernel, while enumeration is + * retained for identity rather than for existence. + * + * Residual risks, ranked, stated as accepted rather than engineered around: + * + * 1. **A member that calls `setsid()` leaves the group and is unreachable by any + * group-directed signal.** Unbounded, accepted: no group-based containment + * can follow it, and the alternative would be a broader kill than this design + * is willing to issue. + * 2. **PID reuse between enumeration and signal.** False emptiness is closed + * structurally, not by arithmetic: ESRCH means no process is in the group, + * while any surviving original member remains in that group by definition. + * Reuse of the group number can therefore produce only EXISTS, withholding + * proof and retaining the sandbox. Per-round identity re-verification narrows + * and detects mis-signal by reducing exposure to one enumeration-to-signal + * gap per round and by treating a pid acquired between rounds as newly + * observed, not as a survivor. It does not make that gap atomic. An exact + * identity impostor inside it (a recycled pid equal to `childPid` whose new + * owner calls `setsid()`, so pid, pgid, and sid all equal `childPid`) passes + * every field read here and would be mis-killed. That is an accepted + * operational residual. The `pid_max` margin (4,194,304, above 10^3 for these + * windows) bounds only the likelihood of this mis-signal; it is not an input + * to the emptiness proof. + * 3. **An unreaped zombie leader makes `kill(-pgid, 0)` report EXISTS.** Bounded + * and fails closed: the sandbox is retained and the bound is exhausted loudly + * rather than emptiness being claimed. + * * `@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 @@ -11,9 +49,10 @@ */ import { spawnSync } from 'node:child_process'; +import type { SpawnSyncOptionsWithStringEncoding } from 'node:child_process'; import { accessSync, - constants as fsConstants, + constants, existsSync, mkdirSync, mkdtempSync, @@ -25,17 +64,484 @@ import { } from 'node:fs'; import { readFile, mkdtemp, realpath, rm } from 'node:fs/promises'; import { homedir, tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { basename, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { types as utilTypes } from 'node:util'; +import { types } from 'node:util'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type * as LocalDevNamespace from './local-dev.js'; +import type { + LOCAL_DEV_QUEUE_VAR, + LOCAL_DEV_STATE_ROOT_VAR, + LOCAL_DEV_STORAGE_VAR, + LOCAL_DEV_TIER_VAR, + runLocalDev, +} from './local-dev.js'; + +type LocalDevModule = Readonly<{ + LOCAL_DEV_QUEUE_VAR: typeof LOCAL_DEV_QUEUE_VAR; + LOCAL_DEV_STATE_ROOT_VAR: typeof LOCAL_DEV_STATE_ROOT_VAR; + LOCAL_DEV_STORAGE_VAR: typeof LOCAL_DEV_STORAGE_VAR; + LOCAL_DEV_TIER_VAR: typeof LOCAL_DEV_TIER_VAR; + runLocalDev: typeof runLocalDev; +}>; + +type DetachedSpawnSyncOptions = SpawnSyncOptionsWithStringEncoding & Readonly<{ detached: true }>; 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'; +const REAL_PROCESS_KILL = process.kill; + +/** + * Owns signal-path absence and restoration, while each callback owns its own + * typed refusal and message assertions. + * + * The restoration throw from `finally` deliberately supersedes any primary + * failure already in flight from the callback. A restoration-identity failure + * invalidates every later signal-path result in this file, so it must be the + * fault that reports. Fixing restoration and re-running is how the masked local + * failure is then recovered. + */ +function withBlockedProcessKill(run: () => T): T { + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true); + try { + const value = run(); + expect(killSpy, 'precondition failure reached process.kill').not.toHaveBeenCalled(); + return value; + } finally { + killSpy.mockRestore(); + if (process.kill !== REAL_PROCESS_KILL) { + throw new Error('KBN02A_KILL_SPY_RESTORE_FAILED'); + } + } +} + +type ProcStat = { pid: number; pgid: number; sid: number; starttime: number }; + +type ProcStatUnknownReason = + | Readonly<{ kind: 'errno'; errno: string }> + | Readonly<{ kind: 'parse'; condition: string }> + | Readonly<{ kind: 'exception'; name: string }>; + +type ProcStatReadResult = + | Readonly<{ kind: 'present'; stat: ProcStat }> + | Readonly<{ kind: 'absent'; errno: 'ENOENT' | 'ESRCH' }> + | Readonly<{ kind: 'unknown'; reason: ProcStatUnknownReason }>; + +type GroupEnumerationResult = + | Readonly<{ kind: 'complete'; members: readonly ProcStat[] }> + | Readonly<{ + kind: 'unknown'; + failures: readonly Readonly<{ pid: number; reason: ProcStatUnknownReason }>[]; + }>; + +type GroupExistence = + | Readonly<{ kind: 'exists'; signalable: true }> + | Readonly<{ kind: 'exists'; signalable: false; errno: 'EPERM' }> + | Readonly<{ kind: 'absent'; errno: 'ESRCH' }> + | Readonly<{ kind: 'unknown'; errno: string }>; + +type ContainmentErrorCode = + | 'KBN02A_VERIFIER_IDENTITY_UNREADABLE' + | 'KBN02A_VERIFIER_PGID_UNSAFE' + | 'KBN02A_VERIFIER_PGID_NON_POSITIVE' + | 'KBN02A_VERIFIER_SID_NON_POSITIVE' + | 'KBN02A_CHILD_PID_UNSAFE' + | 'KBN02A_CHILD_PID_NON_POSITIVE' + | 'KBN02A_CHILD_PID_IS_VERIFIER' + | 'KBN02A_CHILD_PID_IS_VERIFIER_PGID' + | 'KBN02A_MEMBER_IDENTITY_UNREADABLE' + | 'KBN02A_GROUP_SESSION_IDENTITY_ANOMALY' + | 'KBN02A_SPAWN_BOUNDARY_FLOOR_ANOMALY' + | 'KBN02A_GROUP_EXISTENCE_EPERM' + | 'KBN02A_GROUP_EXISTENCE_UNKNOWN' + | 'KBN02A_SIGNAL_UNEXPECTED_ERRNO' + | 'KBN02A_GROUP_BOUND_EXHAUSTED' + | 'KBN02A_GROUP_UNOBSERVED_BOUND_EXHAUSTED' + | 'KBN02A_CONTAINMENT_DEPENDENCY_EXCEPTION' + | 'KBN02A_SANDBOX_RETAINED_UNPROVEN' + | 'KBN02A_PRIMARY_CONTAINMENT_FAILURE_UNRECORDED'; + +class ContainmentError extends Error { + readonly code: ContainmentErrorCode; + + constructor(code: ContainmentErrorCode, detail: string) { + super(`${code}: ${detail}`); + this.name = 'ContainmentError'; + this.code = code; + } +} + +function containmentFailure(code: ContainmentErrorCode, detail: string): ContainmentError { + return new ContainmentError(code, detail); +} + +function sanitizedErrno(error: unknown): string { + if (error instanceof Error && 'code' in error) { + const code = error.code; + if ( + (typeof code === 'string' || typeof code === 'number') && + /^[A-Z0-9_]+$/.test(String(code)) + ) { + return String(code); + } + } + return 'UNKNOWN'; +} + +function sanitizedExceptionName(error: unknown): string { + if (typeof error === 'object' && error !== null) { + const name = error.constructor?.name; + if (typeof name === 'string' && /^[A-Za-z][A-Za-z0-9_]*$/.test(name)) { + return name; + } + } + return 'UNKNOWN'; +} + +function parseProcStat(pid: number, stat: string): ProcStatReadResult { + const commStart = stat.indexOf('('); + const commEnd = stat.lastIndexOf(')'); + if (commStart < 0 || commEnd < commStart) { + return { kind: 'unknown', reason: { kind: 'parse', condition: 'missing-comm-delimiter' } }; + } + + const statPid = Number(stat.slice(0, commStart).trim()); + const fieldsAfterComm = stat + .slice(commEnd + 1) + .trim() + .split(/\s+/); + const pgid = Number(fieldsAfterComm[2]); + const sid = Number(fieldsAfterComm[3]); + const starttime = Number(fieldsAfterComm[19]); + const rejection = ( + condition: string, + ): Readonly<{ kind: 'unknown'; reason: ProcStatUnknownReason }> => ({ + kind: 'unknown', + reason: { kind: 'parse', condition }, + }); + + if (!Number.isSafeInteger(statPid)) return rejection('pid-not-safe-integer'); + if (statPid <= 0) return rejection('pid-non-positive'); + if (statPid !== pid) return rejection('pid-mismatch'); + if (!Number.isSafeInteger(pgid)) return rejection('pgid-not-safe-integer'); + if (!Number.isSafeInteger(sid)) return rejection('sid-not-safe-integer'); + if (pgid < 0) return rejection('pgid-negative'); + if (sid < 0) return rejection('sid-negative'); + if ((pgid === 0) !== (sid === 0)) return rejection('pgid-sid-mixed-zero-positive'); + if (!Number.isSafeInteger(starttime)) return rejection('starttime-not-safe-integer'); + if (starttime < 0) return rejection('starttime-negative'); + + return { kind: 'present', stat: { pid: statPid, pgid, sid, starttime } }; +} + +function readProcStat( + pid: number, + readStat: (path: string, encoding: 'utf8') => string = readFileSync, +): ProcStatReadResult { + try { + return parseProcStat(pid, readStat(join('/proc', String(pid), 'stat'), 'utf8')); + } catch (error) { + const errno = sanitizedErrno(error); + if (errno === 'ENOENT' || errno === 'ESRCH') { + return { kind: 'absent', errno }; + } + if (error instanceof Error && 'code' in error) { + return { kind: 'unknown', reason: { kind: 'errno', errno } }; + } + return { + kind: 'unknown', + reason: { kind: 'exception', name: sanitizedExceptionName(error) }, + }; + } +} + +const verifierProcStatRead = readProcStat(process.pid); +if (verifierProcStatRead.kind !== 'present') { + const condition = + verifierProcStatRead.kind === 'absent' + ? verifierProcStatRead.errno + : verifierProcStatRead.reason.kind === 'errno' + ? verifierProcStatRead.reason.errno + : verifierProcStatRead.reason.kind === 'parse' + ? verifierProcStatRead.reason.condition + : verifierProcStatRead.reason.name; + throw containmentFailure( + 'KBN02A_VERIFIER_IDENTITY_UNREADABLE', + `could not read verifier identity for pid ${process.pid}; reason ${condition}`, + ); +} +const verifierProcStat = verifierProcStatRead.stat; +const VERIFIER_PGID = verifierProcStat.pgid; +if (!Number.isSafeInteger(VERIFIER_PGID)) { + throw containmentFailure( + 'KBN02A_VERIFIER_PGID_UNSAFE', + `verifier pid ${process.pid} has an unsafe pgid`, + ); +} +if (VERIFIER_PGID <= 0) { + throw containmentFailure( + 'KBN02A_VERIFIER_PGID_NON_POSITIVE', + `verifier pid ${process.pid} has non-positive pgid ${VERIFIER_PGID}`, + ); +} +const VERIFIER_SID = verifierProcStat.sid; +if (VERIFIER_SID <= 0) { + throw containmentFailure( + 'KBN02A_VERIFIER_SID_NON_POSITIVE', + `verifier pid ${process.pid} has non-positive sid ${VERIFIER_SID}`, + ); +} +const SPAWN_BOUNDARY_FLOOR = verifierProcStat.starttime; + +function enumerateGroupMembers( + pgid: number, + listProc: () => string[] = () => readdirSync('/proc'), + readStat: (pid: number) => ProcStatReadResult = readProcStat, +): GroupEnumerationResult { + let entries: string[]; + try { + entries = listProc(); + } catch (error) { + const errno = sanitizedErrno(error); + const reason: ProcStatUnknownReason = + error instanceof Error && 'code' in error + ? { kind: 'errno', errno } + : { kind: 'exception', name: sanitizedExceptionName(error) }; + return { kind: 'unknown', failures: [{ pid: 0, reason }] }; + } + + const members: ProcStat[] = []; + const failures: Array> = []; + for (const entry of entries) { + if (!/^\d+$/.test(entry)) { + continue; + } + const pid = Number(entry); + const result = readStat(pid); + if (result.kind === 'unknown') { + failures.push({ pid, reason: result.reason }); + } else if ( + result.kind === 'present' && + result.stat.pid !== process.pid && + result.stat.pgid === pgid + ) { + members.push(result.stat); + } + } + return failures.length > 0 ? { kind: 'unknown', failures } : { kind: 'complete', members }; +} + +function formatMemberIdentities(members: readonly ProcStat[]): string { + return members + .map( + ({ pid, pgid, sid, starttime }) => + `pid ${pid}, pgid ${pgid}, sid ${sid}, starttime ${starttime}`, + ) + .join('; '); +} + +function assertGroupAndSessionIdentity(members: readonly ProcStat[], childPid: number): void { + // detached: true performs setsid(), so an expected member has both pgid and + // sid equal to the spawned leader pid. Any other observed identity is a + // refusal, not eligibility to signal. + const anomalous = members.filter(({ pgid, sid }) => pgid !== childPid || sid !== childPid); + if (anomalous.length > 0) { + throw containmentFailure( + 'KBN02A_GROUP_SESSION_IDENTITY_ANOMALY', + `child pid ${childPid} has anomalous member identities: ${formatMemberIdentities(anomalous)}`, + ); + } +} + +function assertNoGroupReuseAnomaly(members: readonly ProcStat[]): void { + const anomalous = members.filter(({ starttime }) => starttime < SPAWN_BOUNDARY_FLOOR); + if (anomalous.length > 0) { + throw containmentFailure( + 'KBN02A_SPAWN_BOUNDARY_FLOOR_ANOMALY', + `members precede spawn boundary floor ${SPAWN_BOUNDARY_FLOOR}: ${formatMemberIdentities(anomalous)}`, + ); + } +} + +const GROUP_KILL_ROUNDS = 5; +const GROUP_SETTLE_MS = 25; +const GROUP_SETTLE_WORD = new Int32Array(new SharedArrayBuffer(4)); + +type ContainmentDependencies = Readonly<{ + enumerate: (pgid: number) => GroupEnumerationResult; + groupExists: (pgid: number) => GroupExistence; + signal: (pgid: number, verifiedMembers: readonly ProcStat[]) => void; + settle: () => void; +}>; + +const REAL_CONTAINMENT_DEPENDENCIES: ContainmentDependencies = { + enumerate: enumerateGroupMembers, + groupExists: (pgid) => { + try { + process.kill(-pgid, 0); + return { kind: 'exists', signalable: true }; + } catch (error) { + const errno = sanitizedErrno(error); + if (errno === 'ESRCH') return { kind: 'absent', errno }; + if (errno === 'EPERM') return { kind: 'exists', signalable: false, errno }; + return { kind: 'unknown', errno }; + } + }, + signal: (pgid) => { + process.kill(-pgid, 'SIGKILL'); + }, + settle: () => { + Atomics.wait(GROUP_SETTLE_WORD, 0, 0, GROUP_SETTLE_MS); + }, +}; + +function memberIdentityFailure( + result: Extract, +): never { + const counts = new Map(); + for (const { reason } of result.failures) { + const name = + reason.kind === 'errno' + ? reason.errno + : reason.kind === 'parse' + ? reason.condition + : reason.name; + counts.set(name, (counts.get(name) ?? 0) + 1); + } + const summary = [...counts].map(([name, count]) => `${name} × ${count}`).join('; '); + throw containmentFailure( + 'KBN02A_MEMBER_IDENTITY_UNREADABLE', + `${result.failures.length} member identity reads are unknown; reasons ${summary}`, + ); +} + +function assertGroupExistenceKnown(existence: GroupExistence, childPid: number): void { + if (existence.kind === 'exists' && !existence.signalable) { + throw containmentFailure( + 'KBN02A_GROUP_EXISTENCE_EPERM', + `signal-zero for child pgid ${childPid} failed with errno ${existence.errno}`, + ); + } + if (existence.kind === 'unknown') { + throw containmentFailure( + 'KBN02A_GROUP_EXISTENCE_UNKNOWN', + `signal-zero for child pgid ${childPid} failed with errno ${existence.errno}`, + ); + } +} + +/** Kills and verifies the detached child's process group synchronously. */ +function proveProcessGroupEmpty( + childPid: number | undefined, + dependencies: ContainmentDependencies = REAL_CONTAINMENT_DEPENDENCIES, +): true { + if (typeof childPid !== 'number' || !Number.isSafeInteger(childPid)) { + throw containmentFailure( + 'KBN02A_CHILD_PID_UNSAFE', + 'process-group guard received a child pid that is not a safe integer', + ); + } + if (childPid <= 0) { + throw containmentFailure( + 'KBN02A_CHILD_PID_NON_POSITIVE', + `process-group guard received non-positive child pid ${childPid}`, + ); + } + if (childPid === process.pid) { + throw containmentFailure( + 'KBN02A_CHILD_PID_IS_VERIFIER', + `child pid ${childPid} equals verifier pid ${process.pid}`, + ); + } + if (childPid === VERIFIER_PGID) { + throw containmentFailure( + 'KBN02A_CHILD_PID_IS_VERIFIER_PGID', + `child pid ${childPid} equals verifier pgid ${VERIFIER_PGID}`, + ); + } + + let enumeration = dependencies.enumerate(childPid); + if (enumeration.kind === 'unknown') memberIdentityFailure(enumeration); + let members = enumeration.members; + assertGroupAndSessionIdentity(members, childPid); + assertNoGroupReuseAnomaly(members); + let observedMember = members.length > 0; + let lastObservedMembers = members; + + let existence = dependencies.groupExists(childPid); + if (existence.kind === 'absent') return true; + assertGroupExistenceKnown(existence, childPid); + + for (let round = 0; round < GROUP_KILL_ROUNDS; round += 1) { + if (members.length > 0) { + try { + // Each signal follows an enumeration whose members passed group, session, and + // anomaly verification. Round zero uses the pre-loop enumeration; later rounds + // use the fresh enumeration from the end of the preceding round. False emptiness + // is closed structurally, not by the `pid_max` margin: ESRCH requires no process + // in the group, so any surviving original member makes ESRCH impossible, while a + // reused group number can only return EXISTS and retain the sandbox. The in-loop + // checks narrow and detect mis-signal by limiting exposure to one + // enumeration-to-signal gap per round and by preventing a pid acquired between + // rounds from being counted as a survivor. They do not make the gap atomic. An + // exact impostor inside it (a recycled pid equal to `childPid` whose new owner + // calls `setsid()`, presenting pid === pgid === sid === `childPid`) passes every + // field read here and would be mis-killed. That is an accepted operational + // residual. The `pid_max` margin bounds only its likelihood. Keep the identity + // and anomaly checks inside the loop, and never reuse members across a settle + // boundary. + dependencies.signal(childPid, members); + } catch (error) { + const errno = sanitizedErrno(error); + if (errno !== 'ESRCH') { + throw containmentFailure( + 'KBN02A_SIGNAL_UNEXPECTED_ERRNO', + `SIGKILL for child pgid ${childPid} failed with errno ${errno}; verified members: ${formatMemberIdentities(members)}`, + ); + } + } + } + + dependencies.settle(); + enumeration = dependencies.enumerate(childPid); + if (enumeration.kind === 'unknown') memberIdentityFailure(enumeration); + const freshMembers = enumeration.members; + assertGroupAndSessionIdentity(freshMembers, childPid); + assertNoGroupReuseAnomaly(freshMembers); + observedMember ||= freshMembers.length > 0; + if (freshMembers.length > 0) lastObservedMembers = freshMembers; + + existence = dependencies.groupExists(childPid); + if (existence.kind === 'absent') return true; + assertGroupExistenceKnown(existence, childPid); + + const recordedIdentities = new Map(members.map(({ pid, starttime }) => [pid, starttime])); + const matchingSurvivors = freshMembers.filter( + ({ pid, starttime }) => recordedIdentities.get(pid) === starttime, + ); + const newlyObserved = freshMembers.filter( + ({ pid, starttime }) => + !recordedIdentities.has(pid) || recordedIdentities.get(pid) !== starttime, + ); + // A reused pid is a newly observed identity, not a matching survivor. Both + // sets remain verified live members and become the recorded pairs for the + // next eligibility decision. + members = [...matchingSurvivors, ...newlyObserved]; + } + + if (!observedMember) { + throw containmentFailure( + 'KBN02A_GROUP_UNOBSERVED_BOUND_EXHAUSTED', + `child pgid ${childPid} existed without observable identities for ${GROUP_KILL_ROUNDS} rounds`, + ); + } + throw containmentFailure( + 'KBN02A_GROUP_BOUND_EXHAUSTED', + `child pgid ${childPid} still exists after ${GROUP_KILL_ROUNDS} rounds; verified identities: ${formatMemberIdentities(lastObservedMembers)}`, + ); +} // --- Z1-Z5 instruments. Nothing real is reachable through these. ------------- const bootstrapMock = vi.fn(async () => {}); @@ -85,14 +591,46 @@ function expectZeroSideEffects(): void { 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[] = []; +type TempRoot = { + path: string; + containment: 'not-applicable' | 'unproven' | 'proven-empty'; + primaryContainmentFailure?: Readonly<{ code: ContainmentErrorCode }>; +}; + +/** Every temp root this file creates, with child containment state attached. */ +const tempRoots: TempRoot[] = []; + +function registerTempRoot( + path: string, + containment: TempRoot['containment'] = 'not-applicable', +): TempRoot { + const root = { path, containment }; + tempRoots.push(root); + return root; +} + +async function teardownTempRoots( + roots: TempRoot[], + remove: (path: string) => Promise = async (path) => + rm(path, { recursive: true, force: true }), +): Promise { + const retained: string[] = []; + for (const root of roots) { + if (root.containment === 'unproven') { + const primaryCode = + root.primaryContainmentFailure?.code ?? 'KBN02A_PRIMARY_CONTAINMENT_FAILURE_UNRECORDED'; + retained.push(`${primaryCode} at ${root.path}`); + } else { + await remove(root.path); + } + } + if (retained.length > 0) { + throw containmentFailure( + 'KBN02A_SANDBOX_RETAINED_UNPROVEN', + `group emptiness is unproven; retained sandboxes: ${retained.join(', ')}`, + ); + } +} beforeEach(() => { envSnapshot = Object.assign({}, process.env); @@ -101,18 +639,591 @@ beforeEach(() => { afterEach(async () => { process.env = { ...envSnapshot }; - for (const root of tempRoots.splice(0)) { - await rm(root, { recursive: true, force: true }); + const roots = tempRoots.splice(0); + try { + await teardownTempRoots(roots); + } finally { + vi.resetModules(); } - vi.resetModules(); }); -type LocalDevModule = typeof LocalDevNamespace; +function captureContainmentFailure(run: () => unknown): ContainmentError { + let thrown: unknown; + try { + run(); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(ContainmentError); + if (!(thrown instanceof ContainmentError)) { + throw new Error('expected a typed containment failure'); + } + return thrown; +} + +function requireProcFixtureRecord(records: Readonly>, pid: number): string { + const stat = records[pid]; + if (stat === undefined) { + throw new Error(`missing /proc fixture record for pid ${pid}`); + } + return stat; +} + +describe('/proc identity reads preserve uncertainty', () => { + const procRecord = ( + pid: number, + fields: Readonly>> = {}, + ): string => { + const tail = Array(20).fill('1'); + tail[0] = 'S'; + tail[2] = fields.pgid ?? '17'; + tail[3] = fields.sid ?? '17'; + tail[19] = fields.starttime ?? '23'; + return `${fields.pid ?? String(pid)} (command name) ${tail.join(' ')}`; + }; + const codedError = (code: string): Error => Object.assign(new Error('hidden'), { code }); + + it('classifies ENOENT after enumeration and ESRCH during a stat read as absent', () => { + const enumeration = enumerateGroupMembers( + 17, + () => ['91'], + () => ({ kind: 'absent', errno: 'ENOENT' }), + ); + const read = readProcStat(91, () => { + throw codedError('ESRCH'); + }); + + expect(enumeration).toEqual({ kind: 'complete', members: [] }); + expect(read).toEqual({ kind: 'absent', errno: 'ESRCH' }); + }); + + it('classifies every non-absence stat errno and non-errno exception as unknown', () => { + for (const errno of ['EACCES', 'EPERM', 'EIO', 'EUNEXPECTED']) { + const result = readProcStat(91, () => { + throw codedError(errno); + }); + expect(result).toEqual({ kind: 'unknown', reason: { kind: 'errno', errno } }); + } + const exception = readProcStat(91, () => { + throw new TypeError('hidden'); + }); + expect(exception).toEqual({ + kind: 'unknown', + reason: { kind: 'exception', name: 'TypeError' }, + }); + }); + + it('classifies malformed stat grammar and every invalid identity field as unknown', () => { + const cases: ReadonlyArray = [ + ['missing-comm-delimiter', '91 command S 1 17 17'], + ['pid-not-safe-integer', procRecord(91, { pid: 'NaN' })], + ['pid-non-positive', procRecord(91, { pid: '0' })], + ['pid-mismatch', procRecord(91, { pid: '92' })], + ['pgid-not-safe-integer', procRecord(91, { pgid: 'NaN' })], + ['pgid-sid-mixed-zero-positive', procRecord(91, { pgid: '0' })], + ['pgid-negative', procRecord(91, { pgid: '-1' })], + ['sid-not-safe-integer', procRecord(91, { sid: 'NaN' })], + ['pgid-sid-mixed-zero-positive', procRecord(91, { sid: '0' })], + ['sid-negative', procRecord(91, { sid: '-1' })], + ['starttime-not-safe-integer', procRecord(91, { starttime: 'NaN' })], + ['starttime-negative', procRecord(91, { starttime: '-1' })], + ]; + for (const [condition, stat, pid = 91] of cases) { + expect(parseProcStat(pid, stat)).toEqual({ + kind: 'unknown', + reason: { kind: 'parse', condition }, + }); + } + }); + + it('classifies a safe zero/zero process identity as present', () => { + expect(parseProcStat(91, procRecord(91, { pgid: '0', sid: '0' }))).toEqual({ + kind: 'present', + stat: { pid: 91, pgid: 0, sid: 0, starttime: 23 }, + }); + }); + + it('keeps zero/zero nonmembers out of a complete positive-group enumeration', () => { + const records: Readonly> = { + 91: procRecord(91, { pgid: '0', sid: '0' }), + 92: procRecord(92, { pgid: '0', sid: '0' }), + 93: procRecord(93), + }; + const result = enumerateGroupMembers( + 17, + () => Object.keys(records), + (pid) => parseProcStat(pid, requireProcFixtureRecord(records, pid)), + ); + + expect(result).toEqual({ + kind: 'complete', + members: [{ pid: 93, pgid: 17, sid: 17, starttime: 23 }], + }); + }); + + it('keeps absent reads complete and makes one unknown read poison the enumeration', () => { + const absent = enumerateGroupMembers( + 17, + () => ['91'], + () => ({ kind: 'absent', errno: 'ENOENT' }), + ); + const unknown = enumerateGroupMembers( + 17, + () => ['91', '92'], + (pid) => + pid === 91 + ? { kind: 'present', stat: { pid, pgid: 99, sid: 99, starttime: 1 } } + : { kind: 'unknown', reason: { kind: 'errno', errno: 'EACCES' } }, + ); + + expect(absent).toEqual({ kind: 'complete', members: [] }); + expect(unknown).toEqual({ + kind: 'unknown', + failures: [{ pid: 92, reason: { kind: 'errno', errno: 'EACCES' } }], + }); + }); + + it('turns a proc-directory read failure into an unknown enumeration', () => { + const result = enumerateGroupMembers(17, () => { + throw codedError('EIO'); + }); + expect(result).toEqual({ + kind: 'unknown', + failures: [{ pid: 0, reason: { kind: 'errno', errno: 'EIO' } }], + }); + }); +}); + +describe('process-group guard refuses unsafe child identities before signaling', () => { + const refusalCases: ReadonlyArray = [ + ['undefined', undefined, 'KBN02A_CHILD_PID_UNSAFE'], + ['NaN', Number.NaN, 'KBN02A_CHILD_PID_UNSAFE'], + ['Infinity', Number.POSITIVE_INFINITY, 'KBN02A_CHILD_PID_UNSAFE'], + ['-Infinity', Number.NEGATIVE_INFINITY, 'KBN02A_CHILD_PID_UNSAFE'], + ['zero', 0, 'KBN02A_CHILD_PID_NON_POSITIVE'], + ['negative zero', -0, 'KBN02A_CHILD_PID_NON_POSITIVE'], + ['a negative pid', -1, 'KBN02A_CHILD_PID_NON_POSITIVE'], + ['a fractional pid', 1.5, 'KBN02A_CHILD_PID_UNSAFE'], + ['the verifier pid', process.pid, 'KBN02A_CHILD_PID_IS_VERIFIER'], + ['the verifier process group', VERIFIER_PGID, 'KBN02A_CHILD_PID_IS_VERIFIER_PGID'], + ]; + + it.each(refusalCases)('refuses %s', (_label, childPid, expectedCode) => { + withBlockedProcessKill(() => { + const failure = captureContainmentFailure(() => proveProcessGroupEmpty(childPid)); + expect(failure.code).toBe(expectedCode); + }); + }); +}); + +describe('process-group containment negative controls', () => { + const childPid = process.pid !== 424_242 && VERIFIER_PGID !== 424_242 ? 424_242 : 424_243; + const member = (starttime = SPAWN_BOUNDARY_FLOOR): ProcStat => ({ + pid: childPid + 1, + pgid: childPid, + sid: childPid, + starttime, + }); + const complete = (members: readonly ProcStat[]): GroupEnumerationResult => ({ + kind: 'complete', + members, + }); + const exists = (): GroupExistence => ({ kind: 'exists', signalable: true }); + const absent = (): GroupExistence => ({ kind: 'absent', errno: 'ESRCH' }); + const fakeDependencies = ( + enumerate: (pgid: number) => GroupEnumerationResult, + groupExists: (pgid: number) => GroupExistence, + signal: (pgid: number, verifiedMembers: readonly ProcStat[]) => void = () => {}, + ): ContainmentDependencies => ({ enumerate, groupExists, signal, settle: () => {} }); + + it('classifies real signal-zero outcomes without calling through', () => { + let errno = 'ESRCH'; + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { + throw Object.assign(new Error('hidden'), { code: errno }); + }); + try { + const cases: ReadonlyArray = [ + ['ESRCH', { kind: 'absent', errno: 'ESRCH' }], + ['EPERM', { kind: 'exists', signalable: false, errno: 'EPERM' }], + ['EIO', { kind: 'unknown', errno: 'EIO' }], + ['ENOENT', { kind: 'unknown', errno: 'ENOENT' }], + ]; + for (const [input, expected] of cases) { + errno = input; + expect(REAL_CONTAINMENT_DEPENDENCIES.groupExists(childPid)).toEqual(expected); + } + expect(killSpy.mock.calls).toEqual(cases.map(() => [-childPid, 0])); + } finally { + killSpy.mockRestore(); + if (process.kill !== REAL_PROCESS_KILL) { + throw new Error('KBN02A_KILL_SPY_RESTORE_FAILED'); + } + } + }); + + it('uses only the validated child pid for every negative group argument', () => { + const otherPgid = childPid + 20; + const statRecord = (pid: number, pgid: number, sid: number): string => { + const tail = Array(20).fill('1'); + tail[0] = 'S'; + tail[2] = String(pgid); + tail[3] = String(sid); + tail[19] = String(SPAWN_BOUNDARY_FLOOR); + return `${pid} (fixture) ${tail.join(' ')}`; + }; + const records: Readonly> = { + [childPid + 1]: statRecord(childPid + 1, childPid, childPid), + [childPid + 2]: statRecord(childPid + 2, 0, 0), + [childPid + 3]: statRecord(childPid + 3, otherPgid, otherPgid), + }; + const negativeGroupArguments: number[] = []; + let probes = 0; + const dependencies: ContainmentDependencies = { + enumerate: (pgid) => + enumerateGroupMembers( + pgid, + () => Object.keys(records), + (pid) => parseProcStat(pid, requireProcFixtureRecord(records, pid)), + ), + groupExists: (pgid) => { + negativeGroupArguments.push(-pgid); + probes += 1; + return probes === 1 ? exists() : absent(); + }, + signal: (pgid) => { + negativeGroupArguments.push(-pgid); + }, + settle: () => {}, + }; + + expect(proveProcessGroupEmpty(childPid, dependencies)).toBe(true); + expect(negativeGroupArguments).toEqual([-childPid, -childPid, -childPid]); + expect(negativeGroupArguments).not.toContain(-otherPgid); + }); + + it('enumerates and verifies a member before the first kill', () => { + const events: string[] = []; + let enumeration = 0; + let observation = 0; + const dependencies = fakeDependencies( + () => { + events.push('enumerate'); + enumeration += 1; + return complete(enumeration === 1 ? [member()] : []); + }, + () => { + events.push('groupExists'); + observation += 1; + return observation === 1 ? exists() : absent(); + }, + (_pgid, verifiedMembers) => { + events.push('signal'); + expect(verifiedMembers).toEqual([member()]); + }, + ); + + expect(proveProcessGroupEmpty(childPid, dependencies)).toBe(true); + expect(events).toEqual(['enumerate', 'groupExists', 'signal', 'enumerate', 'groupExists']); + }); + + it('refuses a member outside the child session before consulting the kernel', () => { + const anomalous = { ...member(), sid: childPid + 2 }; + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => complete([anomalous]), + () => { + throw new Error('groupExists must follow identity validation'); + }, + ), + ), + ); + + expect(failure.code).toBe('KBN02A_GROUP_SESSION_IDENTITY_ANOMALY'); + expect(failure.message).toContain(`sid ${anomalous.sid}`); + }); + + it('refuses a member predating the spawn boundary before consulting the kernel', () => { + const anomalous = member(SPAWN_BOUNDARY_FLOOR - 1); + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => complete([anomalous]), + () => { + throw new Error('groupExists must follow identity validation'); + }, + ), + ), + ); + + expect(failure.code).toBe('KBN02A_SPAWN_BOUNDARY_FLOOR_ANOMALY'); + expect(failure.message).toContain(`starttime ${anomalous.starttime}`); + }); + + it('does not kill on an empty scan while the kernel reports that the group exists', () => { + let enumerations = 0; + let signals = 0; + const enumerationScript = [complete([]), complete([member()]), complete([])]; + const existenceScript = [exists(), exists(), absent()]; + const dependencies = fakeDependencies( + () => { + enumerations += 1; + return enumerationScript.shift() ?? complete([]); + }, + () => existenceScript.shift() ?? absent(), + () => { + signals += 1; + }, + ); + + expect(proveProcessGroupEmpty(childPid, dependencies)).toBe(true); + expect(enumerations).toBe(3); + expect(signals).toBe(1); + }); + + it('accepts initial ESRCH from signal-zero without issuing SIGKILL', () => { + let signals = 0; + const dependencies = fakeDependencies( + () => complete([member()]), + absent, + () => { + signals += 1; + }, + ); + + expect(proveProcessGroupEmpty(childPid, dependencies)).toBe(true); + expect(signals).toBe(0); + }); + + it('accepts post-round ESRCH only after fresh enumeration and signal-zero', () => { + const events: string[] = []; + let observation = 0; + const dependencies = fakeDependencies( + () => { + events.push('enumerate'); + return complete([member()]); + }, + () => { + events.push('groupExists'); + observation += 1; + return observation === 1 ? exists() : absent(); + }, + () => events.push('signal'), + ); + + expect(proveProcessGroupEmpty(childPid, dependencies)).toBe(true); + expect(events).toEqual(['enumerate', 'groupExists', 'signal', 'enumerate', 'groupExists']); + }); + + it('freshly enumerates after ESRCH from SIGKILL rather than trusting it', () => { + let enumerations = 0; + let observations = 0; + const dependencies = fakeDependencies( + () => { + enumerations += 1; + return complete(enumerations === 1 ? [member()] : []); + }, + () => { + observations += 1; + return observations === 1 ? exists() : absent(); + }, + () => { + throw Object.assign(new Error('hidden'), { code: 'ESRCH' }); + }, + ); + + expect(proveProcessGroupEmpty(childPid, dependencies)).toBe(true); + expect(enumerations).toBe(2); + }); + + it('turns EPERM from signal-zero into an exact typed refusal', () => { + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => complete([]), + () => ({ kind: 'exists', signalable: false, errno: 'EPERM' }), + ), + ), + ); + + expect(failure.code).toBe('KBN02A_GROUP_EXISTENCE_EPERM'); + }); + + it('sanitizes an unexpected signal-zero errno in a typed refusal', () => { + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => complete([]), + () => ({ kind: 'unknown', errno: 'EWEIRD' }), + ), + ), + ); + + expect(failure.code).toBe('KBN02A_GROUP_EXISTENCE_UNKNOWN'); + expect(failure.message).toContain('EWEIRD'); + }); + + it('turns a non-ESRCH SIGKILL errno into a typed failure', () => { + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => complete([member()]), + exists, + () => { + throw Object.assign(new Error('hidden'), { code: 'EPERM' }); + }, + ), + ), + ); + + expect(failure.code).toBe('KBN02A_SIGNAL_UNEXPECTED_ERRNO'); + expect(failure.message).toContain('errno EPERM'); + }); + + it('updates pid and starttime identity pairs across rounds', () => { + const first = member(SPAWN_BOUNDARY_FLOOR); + const second = member(SPAWN_BOUNDARY_FLOOR + 1); + const enumerations = [complete([first]), complete([second]), complete([])]; + const existences = [exists(), exists(), absent()]; + const signaledPairs: string[][] = []; + const dependencies = fakeDependencies( + () => enumerations.shift() ?? complete([]), + () => existences.shift() ?? absent(), + (_pgid, verifiedMembers) => { + signaledPairs.push(verifiedMembers.map(({ pid, starttime }) => `${pid}:${starttime}`)); + }, + ); + + expect(proveProcessGroupEmpty(childPid, dependencies)).toBe(true); + expect(signaledPairs).toEqual([ + [`${first.pid}:${first.starttime}`], + [`${second.pid}:${second.starttime}`], + ]); + }); + + it('consults signal-zero after every round even while members remain visible', () => { + let observations = 0; + let signals = 0; + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => complete([member()]), + () => { + observations += 1; + return exists(); + }, + () => { + signals += 1; + }, + ), + ), + ); + + expect(failure.code).toBe('KBN02A_GROUP_BOUND_EXHAUSTED'); + expect(observations).toBe(GROUP_KILL_ROUNDS + 1); + expect(signals).toBe(GROUP_KILL_ROUNDS); + }); + + it('distinguishes a persistently existing group whose members stay unobservable', () => { + let signals = 0; + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => complete([]), + exists, + () => { + signals += 1; + }, + ), + ), + ); + + expect(failure.code).toBe('KBN02A_GROUP_UNOBSERVED_BOUND_EXHAUSTED'); + expect(signals).toBe(0); + }); + + it('refuses an unknown initial enumeration before signal-zero', () => { + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies( + () => ({ + kind: 'unknown', + failures: [ + { pid: childPid + 3, reason: { kind: 'errno', errno: 'EACCES' } }, + { pid: childPid + 4, reason: { kind: 'parse', condition: 'pgid-negative' } }, + { pid: childPid + 5, reason: { kind: 'errno', errno: 'EACCES' } }, + ], + }), + () => { + throw new Error('groupExists must not follow an unknown enumeration'); + }, + ), + ), + ); + + expect(failure.code).toBe('KBN02A_MEMBER_IDENTITY_UNREADABLE'); + expect(failure.message).toContain('3 member identity reads'); + expect(failure.message).toContain('reasons EACCES × 2; pgid-negative × 1'); + }); + + it('refuses an unknown post-signal enumeration', () => { + const enumerations: GroupEnumerationResult[] = [ + complete([member()]), + { + kind: 'unknown', + failures: [ + { + pid: childPid + 4, + reason: { kind: 'parse', condition: 'sid-not-safe-integer' }, + }, + ], + }, + ]; + const failure = captureContainmentFailure(() => + proveProcessGroupEmpty( + childPid, + fakeDependencies(() => enumerations.shift() ?? complete([]), exists), + ), + ); + + expect(failure.code).toBe('KBN02A_MEMBER_IDENTITY_UNREADABLE'); + expect(failure.message).toContain('sid-not-safe-integer'); + }); + + it('retains an unproven sandbox with an explicit missing-primary placeholder', async () => { + const retainedPath = mkdtempSync(join(tmpdir(), 'kbn-02a-negative-control-retained-')); + const root = registerTempRoot(retainedPath, 'unproven'); + let thrown: unknown; + try { + await teardownTempRoots([root]); + } catch (error) { + thrown = error; + } + + expect(thrown).toBeInstanceOf(ContainmentError); + if (!(thrown instanceof ContainmentError)) { + throw new Error('expected a typed teardown retention failure'); + } + expect(thrown.code).toBe('KBN02A_SANDBOX_RETAINED_UNPROVEN'); + expect(thrown.message).toContain('KBN02A_PRIMARY_CONTAINMENT_FAILURE_UNRECORDED'); + expect(thrown.message).toContain(retainedPath); + expect(existsSync(retainedPath)).toBe(true); + root.containment = 'proven-empty'; + }); +}); /** 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); + registerTempRoot(root); return root; } @@ -124,7 +1235,7 @@ async function freshLocalDev(): Promise { /** A well-formed local declaration, planted in the ambient environment. */ async function declareAdmissibleLocalStart(mod: LocalDevModule): Promise { const stateRoot = await realpath(await mkdtemp(join(tmpdir(), 'kbn-02a-localdev-'))); - tempRoots.push(stateRoot); + registerTempRoot(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'; @@ -139,7 +1250,7 @@ describe('KBN-101-02a local-dev — row 9, import order is structural', () => { // 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 + // which loads the module graph equally 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; @@ -258,16 +1369,22 @@ describe('KBN-101-02a local-dev — refusal reaches nothing', () => { } 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'); + if (thrown instanceof Error) { + expect(thrown.message.includes(FORBIDDEN_DSN), 'the refusal echoed the DSN value').toBe( + false, + ); + expect(thrown.message.includes('mosaic:mosaic'), 'the refusal echoed DSN credentials').toBe( + false, + ); + } }); }); 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; - }; + const manifest: { scripts?: Record } = JSON.parse( + await readFile(join(HERE, '..', 'package.json'), 'utf8'), + ); // The discriminator is the entrypoint itself, so it needs its own command. // Without one, "start locally" remains a flag on the shared command, which @@ -278,9 +1395,9 @@ describe('KBN-101-02a local-dev — the channel has its own command', () => { }); it('leaves the production-like dev script untouched', async () => { - const manifest = JSON.parse(await readFile(join(HERE, '..', 'package.json'), 'utf8')) as { - scripts?: Record; - }; + const manifest: { scripts?: Record } = JSON.parse( + await readFile(join(HERE, '..', 'package.json'), 'utf8'), + ); expect(manifest.scripts?.['dev']).toBe('tsx watch src/main.ts'); }); @@ -303,7 +1420,7 @@ describe('KBN-101-02a local-dev — the channel has its own command', () => { * 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 + * treat that path like 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. @@ -315,7 +1432,7 @@ describe('KBN-101-02a local-dev — the channel has its own command', () => { * 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 + * denylist depends on enumerating 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', () => { @@ -325,7 +1442,7 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo const REPO_ROOT = join(GATEWAY_DIR, '..', '..'); /** - * The POSIX shell the packaged route is executed through, as a validated + * The POSIX shell the packaged route is executed through, using a validated * absolute path. * * The shell is not resolved through `PATH`. It is invoked by this validated @@ -354,18 +1471,22 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo return candidate; } } - throw new Error(`tsx CLI was not found at either candidate: ${candidates.join(', ')}`); + throw new Error( + `tsx CLI was not found; candidate count ${candidates.length}; basenames ${candidates.map((candidate) => basename(candidate)).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}`); + throw new Error( + `${name} PATH target does not exist after realpath; basename ${basename(resolved)}`, + ); } if (!statSync(resolved).isFile()) { - throw new Error(`${name} PATH target is not a file: ${resolved}`); + throw new Error(`${name} PATH target is not a file; basename ${basename(resolved)}`); } - accessSync(resolved, fsConstants.X_OK); + accessSync(resolved, constants.X_OK); return resolved; } @@ -456,9 +1577,9 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo } /** A private root for one child run: home, XDG trees, tmp, runtime dir, bin. */ - function makeChildSandbox(): string { + function makeChildSandbox(): TempRoot { const sandbox = mkdtempSync(join(tmpdir(), 'kbn-02a-child-')); - tempRoots.push(sandbox); + const root = registerTempRoot(sandbox, 'unproven'); for (const relative of [ join('home', '.config'), join('home', '.local', 'share'), @@ -478,9 +1599,38 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo symlinkSync(target, join(sandboxBin, name)); } - return sandbox; + return root; } + it("registers a fresh child sandbox as 'unproven' before containment is proven", () => { + const root = makeChildSandbox(); + expect(root.containment, 'fresh child sandbox containment state').toBe('unproven'); + expect(tempRoots.includes(root), 'fresh child sandbox was not registered').toBe(true); + root.containment = 'proven-empty'; + }); + + it("guards the 'proven-empty' flip after the process-group proof in source order", () => { + const ownSource = readFileSync(fileURLToPath(import.meta.url), 'utf8'); + const spawnFunction = ['function spawn', 'Hermetic('].join(''); + const spawnSiteStart = ownSource.indexOf(spawnFunction); + const spawnSiteEnd = ownSource.indexOf('/** A child that reports', spawnSiteStart); + const spawnSite = ownSource.slice(spawnSiteStart, spawnSiteEnd); + const proofCall = spawnSite.indexOf('proveProcessGroupEmpty(result.pid, dependencies)'); + const provenEmptyFlip = spawnSite.indexOf("sandboxRoot.containment = 'proven-empty'"); + + // Source-text heuristic, like the child-process import assertions below: + // this is a guard against moving the flip, not proof of runtime ordering. + expect(spawnSiteStart, 'no spawnHermetic source to inspect').toBeGreaterThan(-1); + expect(spawnSiteEnd, 'no end of spawnHermetic source to inspect').toBeGreaterThan( + spawnSiteStart, + ); + expect(proofCall, 'no process-group proof call at the spawn site').toBeGreaterThan(-1); + expect(provenEmptyFlip, "no 'proven-empty' flip at the spawn site").toBeGreaterThan(-1); + expect(proofCall, "the 'proven-empty' flip precedes the process-group proof call").toBeLessThan( + provenEmptyFlip, + ); + }); + function enumerateExecutablePathEntries(pathValue: string): Array<{ directory: string; name: string; @@ -491,12 +1641,12 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo for (const name of readdirSync(directory)) { const path = join(directory, name); try { - accessSync(path, fsConstants.X_OK); + accessSync(path, constants.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. + // A directory entry that cannot be executed is not reachable via a command. } } } @@ -514,7 +1664,7 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo * enforced mechanically, not a sandbox. `isProxy` is secondary defense. */ function snapshotCaseEnv(extraEnv: Record): Record { - const inputIsProxy = utilTypes.isProxy(extraEnv); + const inputIsProxy = types.isProxy(extraEnv); const entries = Object.entries(extraEnv); const snapshot = Object.fromEntries(entries); expect( @@ -547,7 +1697,7 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo * 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 + * rejects an ambient copy passed for a declaration, which is the mistake a * maintainer actually makes. */ function spawnHermetic( @@ -555,48 +1705,309 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo args: string[], extraEnv: Record = {}, timeout = CHILD_TIMEOUT_MS, + dependencies: ContainmentDependencies = REAL_CONTAINMENT_DEPENDENCIES, ): { status: number | null; signal: NodeJS.Signals | null; + stdout: string; + stderr: string; output: string; sandbox: string; + groupProvenEmpty: true; } { const extraEnvSnapshot = snapshotCaseEnv(extraEnv); - const sandbox = makeChildSandbox(); - const result = spawnSync(command, args, { + const sandboxRoot = makeChildSandbox(); + const sandbox = sandboxRoot.path; + // `detached` is declared on `SpawnOptions` and omitted from + // `SpawnSyncOptions` in @types/node 22.19.15. The Node runtime honours it on + // `spawnSync` regardless, measured on this host: pid === pgid === sid. The + // local named extension reconciles the two without a cast or global declaration. + const options = { cwd: GATEWAY_DIR, env: buildHermeticChildEnv(sandbox, extraEnvSnapshot), encoding: 'utf8', timeout, killSignal: 'SIGKILL', - }); + detached: true, + } satisfies DetachedSpawnSyncOptions; + + const result = spawnSync(command, args, options); + let groupProvenEmpty: true; + try { + groupProvenEmpty = proveProcessGroupEmpty(result.pid, dependencies); + } catch (error) { + const failure = + error instanceof ContainmentError + ? error + : containmentFailure( + 'KBN02A_CONTAINMENT_DEPENDENCY_EXCEPTION', + `containment dependency threw ${sanitizedExceptionName(error)}`, + ); + sandboxRoot.primaryContainmentFailure = { code: failure.code }; + throw failure; + } + sandboxRoot.containment = 'proven-empty'; return { status: result.status, signal: result.signal, + stdout: result.stdout ?? '', + stderr: result.stderr ?? '', output: `${result.stdout ?? ''}${result.stderr ?? ''}`, sandbox, + groupProvenEmpty, }; } + it('keeps a newly registered sandbox unproven after an unknown initial enumeration', () => { + const registryStart = tempRoots.length; + const dependencies: ContainmentDependencies = { + enumerate: (pgid) => ({ + kind: 'unknown', + failures: [{ pid: pgid, reason: { kind: 'errno', errno: 'EACCES' } }], + }), + groupExists: () => { + throw new Error('groupExists must not follow an unknown enumeration'); + }, + signal: () => { + throw new Error('signal must not follow an unknown enumeration'); + }, + settle: () => {}, + }; + + const failure = captureContainmentFailure(() => + spawnHermetic(process.execPath, ['-e', ''], {}, CHILD_TIMEOUT_MS, dependencies), + ); + const [root] = tempRoots.slice(registryStart); + + expect(failure.code).toBe('KBN02A_MEMBER_IDENTITY_UNREADABLE'); + expect(root?.containment).toBe('unproven'); + expect(root?.primaryContainmentFailure?.code).toBe('KBN02A_MEMBER_IDENTITY_UNREADABLE'); + if (root !== undefined) root.containment = 'proven-empty'; + }); + + it('converts an untyped containment dependency exception before recording it', () => { + const registryStart = tempRoots.length; + const dependencies: ContainmentDependencies = { + enumerate: () => { + throw new TypeError('hidden dependency text'); + }, + groupExists: () => { + throw new Error('groupExists must not follow an enumeration exception'); + }, + signal: () => {}, + settle: () => {}, + }; + + const failure = captureContainmentFailure(() => + spawnHermetic(process.execPath, ['-e', ''], {}, CHILD_TIMEOUT_MS, dependencies), + ); + const [root] = tempRoots.slice(registryStart); + + expect(failure.code).toBe('KBN02A_CONTAINMENT_DEPENDENCY_EXCEPTION'); + expect(failure.message).toContain('TypeError'); + expect(failure.message).not.toContain('hidden dependency text'); + expect(root?.primaryContainmentFailure?.code).toBe('KBN02A_CONTAINMENT_DEPENDENCY_EXCEPTION'); + if (root !== undefined) root.containment = 'proven-empty'; + }); + + it('retains the sandbox when signal-zero reports EPERM with the exact primary code', () => { + const registryStart = tempRoots.length; + const dependencies: ContainmentDependencies = { + enumerate: () => ({ kind: 'complete', members: [] }), + groupExists: () => ({ kind: 'exists', signalable: false, errno: 'EPERM' }), + signal: () => { + throw new Error('signal must not follow EPERM from signal-zero'); + }, + settle: () => {}, + }; + + const failure = captureContainmentFailure(() => + spawnHermetic(process.execPath, ['-e', ''], {}, CHILD_TIMEOUT_MS, dependencies), + ); + const [root] = tempRoots.slice(registryStart); + + expect(failure.code).toBe('KBN02A_GROUP_EXISTENCE_EPERM'); + expect(root?.containment).toBe('unproven'); + expect(root?.primaryContainmentFailure?.code).toBe('KBN02A_GROUP_EXISTENCE_EPERM'); + if (root !== undefined) root.containment = 'proven-empty'; + }); + + it('retains the sandbox for an unexpected signal-zero errno without free text', () => { + const registryStart = tempRoots.length; + const dependencies: ContainmentDependencies = { + enumerate: () => ({ kind: 'complete', members: [] }), + groupExists: () => ({ kind: 'unknown', errno: 'EUNEXPECTED' }), + signal: () => { + throw new Error('signal must not follow unknown signal-zero'); + }, + settle: () => {}, + }; + + const failure = captureContainmentFailure(() => + spawnHermetic(process.execPath, ['-e', ''], {}, CHILD_TIMEOUT_MS, dependencies), + ); + const [root] = tempRoots.slice(registryStart); + + expect(failure.code).toBe('KBN02A_GROUP_EXISTENCE_UNKNOWN'); + expect(failure.message).toContain('EUNEXPECTED'); + expect(root?.primaryContainmentFailure?.code).toBe('KBN02A_GROUP_EXISTENCE_UNKNOWN'); + if (root !== undefined) root.containment = 'proven-empty'; + }); + + it('retains the sandbox when an unobserved existing group exhausts the bound', () => { + const registryStart = tempRoots.length; + const dependencies: ContainmentDependencies = { + enumerate: () => ({ kind: 'complete', members: [] }), + groupExists: () => ({ kind: 'exists', signalable: true }), + signal: () => { + throw new Error('zero-member enumeration must never become kill-eligible'); + }, + settle: () => {}, + }; + + const failure = captureContainmentFailure(() => + spawnHermetic(process.execPath, ['-e', ''], {}, CHILD_TIMEOUT_MS, dependencies), + ); + const [root] = tempRoots.slice(registryStart); + + expect(failure.code).toBe('KBN02A_GROUP_UNOBSERVED_BOUND_EXHAUSTED'); + expect(root?.containment).toBe('unproven'); + expect(root?.primaryContainmentFailure?.code).toBe('KBN02A_GROUP_UNOBSERVED_BOUND_EXHAUSTED'); + if (root !== undefined) root.containment = 'proven-empty'; + }); + + it('retains the sandbox after an unknown post-signal enumeration without calling removal', async () => { + const registryStart = tempRoots.length; + let enumeration = 0; + let signals = 0; + const dependencies: ContainmentDependencies = { + enumerate: (pgid) => { + enumeration += 1; + return enumeration === 1 + ? { + kind: 'complete', + members: [{ pid: pgid + 1, pgid, sid: pgid, starttime: SPAWN_BOUNDARY_FLOOR }], + } + : { + kind: 'unknown', + failures: [{ pid: pgid + 2, reason: { kind: 'parse', condition: 'pid-mismatch' } }], + }; + }, + groupExists: () => ({ kind: 'exists', signalable: true }), + signal: () => { + signals += 1; + }, + settle: () => {}, + }; + const failure = captureContainmentFailure(() => + spawnHermetic(process.execPath, ['-e', ''], {}, CHILD_TIMEOUT_MS, dependencies), + ); + const [root] = tempRoots.slice(registryStart); + const remove = vi.fn(async () => {}); + let retention: unknown; + try { + await teardownTempRoots(root === undefined ? [] : [root], remove); + } catch (error) { + retention = error; + } + + expect(failure.code).toBe('KBN02A_MEMBER_IDENTITY_UNREADABLE'); + expect(signals).toBe(1); + expect(retention).toBeInstanceOf(ContainmentError); + expect(remove.mock.calls.length, 'sandbox removal call count').toBe(0); + if (root !== undefined) root.containment = 'proven-empty'; + }); + + it('carries the primary containment code and retained path through the real spawn wiring', async () => { + const registryStart = tempRoots.length; + const dependencies: ContainmentDependencies = { + enumerate: (pgid) => ({ + kind: 'complete', + members: [{ pid: pgid + 1, pgid, sid: pgid, starttime: SPAWN_BOUNDARY_FLOOR }], + }), + groupExists: () => ({ kind: 'exists', signalable: true }), + signal: () => { + throw Object.assign(new Error('hidden dependency detail'), { code: 'EPERM' }); + }, + settle: () => {}, + }; + const primary = captureContainmentFailure(() => + spawnHermetic(process.execPath, ['-e', ''], {}, CHILD_TIMEOUT_MS, dependencies), + ); + const [root] = tempRoots.slice(registryStart); + const remove = vi.fn(async () => {}); + let retention: unknown; + try { + await teardownTempRoots(root === undefined ? [] : [root], remove); + } catch (error) { + retention = error; + } + + expect(primary.code).toBe('KBN02A_SIGNAL_UNEXPECTED_ERRNO'); + expect(retention).toBeInstanceOf(ContainmentError); + if (!(retention instanceof ContainmentError) || root === undefined) { + throw new Error('expected the registered root to produce a typed retention failure'); + } + expect(retention.message).toContain(primary.code); + expect(retention.message).toContain(root.path); + expect(remove.mock.calls.length, 'retained sandbox removal call count').toBe(0); + root.containment = 'proven-empty'; + }); + /** 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));`; + const TSX_DEP0205_FIRST_LINE = + /^\(node:\d+\) \[DEP0205\] DeprecationWarning: `module\.register\(\)` is deprecated\. Use `module\.registerHooks\(\)` instead\.\n/; + const TSX_DEP0205_WARNING = + /^\(node:\d+\) \[DEP0205\] DeprecationWarning: `module\.register\(\)` is deprecated\. Use `module\.registerHooks\(\)` instead\.\n\(Use `node --trace-deprecation \.\.\.` to show where the warning was created\)\n/; + const TSX_DEP0205_STDERR = + /^(?:\(node:\d+\) \[DEP0205\] DeprecationWarning: `module\.register\(\)` is deprecated\. Use `module\.registerHooks\(\)` instead\.\n\(Use `node --trace-deprecation \.\.\.` to show where the warning was created\)\n)?$/; function hasOnlyStringValues(value: object): value is Record { return Object.values(value).every((entry) => typeof entry === 'string'); } function parseObservedEnv(output: string): Record { - const at = output.indexOf(ENV_MARKER); - expect(at, `the marker child printed no environment: ${output}`).toBeGreaterThanOrEqual(0); + const markerAt = output.indexOf(ENV_MARKER); + const prefixLength = markerAt < 0 ? output.length : markerAt; + expect( + markerAt === 0, + `marker channel has ${prefixLength} unconsumed bytes before the marker at position ${markerAt}`, + ).toBe(true); - const parsed: unknown = JSON.parse(output.slice(at + ENV_MARKER.length)); + const payloadStart = ENV_MARKER.length; + const recordEnd = completeJsonObjectEnd(output, payloadStart); + expect( + recordEnd >= payloadStart, + `marker channel has no complete JSON object after the marker at position ${payloadStart}`, + ).toBe(true); + + const secondMarkerAt = output.indexOf(ENV_MARKER, payloadStart); + expect( + secondMarkerAt === -1, + `marker channel contains a duplicate marker at position ${secondMarkerAt}`, + ).toBe(true); + + const suffixLength = recordEnd < 0 ? output.length - payloadStart : output.length - recordEnd; + expect( + suffixLength === 0, + `marker channel has ${suffixLength} unconsumed bytes after the complete record at position ${recordEnd}`, + ).toBe(true); + + let parsed: unknown; + try { + parsed = JSON.parse(output.slice(payloadStart, recordEnd)); + } catch { + expect.fail('marker channel payload is not valid JSON'); + return {}; + } 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) { + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { return {}; } @@ -614,44 +2025,156 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo return parsed; } + function completeJsonObjectEnd(channel: string, start: number): number { + if (channel[start] !== '{') { + return -1; + } + + let depth = 0; + let inString = false; + let escaped = false; + for (let index = start; index < channel.length; index += 1) { + const character = channel[index]; + if (inString) { + if (escaped) { + escaped = false; + } else if (character === '\\') { + escaped = true; + } else if (character === '"') { + inString = false; + } + continue; + } + + if (character === '"') { + inString = true; + } else if (character === '{' || character === '[') { + depth += 1; + } else if (character === '}' || character === ']') { + depth -= 1; + if (depth === 0) { + return index + 1; + } + if (depth < 0) { + return -1; + } + } + } + return -1; + } + + function consumeTsxStderr(stderr: string): void { + if (TSX_DEP0205_STDERR.test(stderr)) { + return; + } + + const completeWarning = TSX_DEP0205_WARNING.exec(stderr); + const firstLine = TSX_DEP0205_FIRST_LINE.exec(stderr); + const consumed = completeWarning?.[0].length ?? firstLine?.[0].length ?? 0; + expect( + false, + `stderr DEP0205 grammar consumed ${consumed} of ${stderr.length} bytes; ${stderr.length - consumed} bytes remain at position ${consumed}`, + ).toBe(true); + } + + function consumeTsxStdout(stdout: string): Record { + const markerAt = stdout.indexOf(ENV_MARKER); + const prefixLength = markerAt < 0 ? stdout.length : markerAt; + expect( + markerAt === 0, + `stdout has ${prefixLength} unconsumed bytes before the marker at position ${markerAt}`, + ).toBe(true); + + const payloadStart = ENV_MARKER.length; + const recordEnd = completeJsonObjectEnd(stdout, payloadStart); + expect( + recordEnd >= payloadStart, + `stdout has no complete JSON object after the marker at position ${payloadStart}`, + ).toBe(true); + + const suffixLength = recordEnd < 0 ? stdout.length - payloadStart : stdout.length - recordEnd; + const secondMarkerAt = recordEnd < 0 ? -1 : stdout.indexOf(ENV_MARKER, recordEnd); + + // Chosen terminal-newline policy: process.stdout.write emits no newline, so + // the complete JSON object must be the final byte of the channel. + expect( + stdout.endsWith('\n'), + `stdout has ${suffixLength} unconsumed terminal-newline-terminated bytes at position ${recordEnd}`, + ).toBe(false); + + expect( + suffixLength === 0, + `stdout has ${suffixLength} unconsumed bytes after the complete marker record at position ${recordEnd}; second marker position ${secondMarkerAt}`, + ).toBe(true); + + let parsed: unknown; + try { + parsed = JSON.parse(stdout.slice(payloadStart, recordEnd)); + } catch { + expect.fail('stdout marker payload is not valid JSON'); + } + expect( + typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed), + 'stdout marker payload must be a non-null, non-array object', + ).toBe(true); + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return {}; + } + + const nonStringKeys = Object.entries(parsed) + .filter(([, value]) => typeof value !== 'string') + .map(([key]) => key); + expect( + nonStringKeys, + `stdout marker payload has non-string environment names: ${nonStringKeys.join(', ')}`, + ).toEqual([]); + if (!hasOnlyStringValues(parsed)) { + return {}; + } + return parsed; + } + function runDevLocal(extraEnv: Record = {}): { status: number | null; signal: NodeJS.Signals | null; output: string; + groupProvenEmpty: true; } { - const manifest = JSON.parse(readFileSync(join(GATEWAY_DIR, 'package.json'), 'utf8')) as { - scripts?: Record; - }; + const manifest: { scripts?: Record } = JSON.parse( + readFileSync(join(GATEWAY_DIR, 'package.json'), 'utf8'), + ); 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); + expect(script, 'dev:local must be the exact required route').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(); + const { status, signal, output, groupProvenEmpty } = runDevLocal(); + expect(groupProvenEmpty).toBe(true); 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', - ); + expect( + output.includes('LOCAL_START_TIER_NOT_EXPLICIT'), + 'the route did not emit the undeclared-tier refusal code', + ).toBe(true); + expect( + output.includes('BETTER_AUTH_SECRET'), + 'exited via bootstrap rather than refusing before it', + ).toBe(false); }); 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', + const { status, signal, output, groupProvenEmpty } = runDevLocal({ + DATABASE_URL: FORBIDDEN_DSN, MOSAIC_LOCAL_DEV_TIER: 'local', MOSAIC_LOCAL_DEV_STORAGE: 'pglite', MOSAIC_LOCAL_DEV_QUEUE: 'local', @@ -660,10 +2183,14 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo // MOSAIC_* variable this case does not name. }); + expect(groupProvenEmpty).toBe(true); 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'); + expect( + output.includes('LOCAL_START_POSTGRES_DSN_PRESENT'), + 'the route did not emit the DSN refusal code', + ).toBe(true); + expect(output.includes('mosaic:mosaic'), 'the refusal echoed DSN credentials').toBe(false); }); /** @@ -690,18 +2217,21 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo 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); + 'the child-process module must appear only in its value and type imports', + ).toBe(2); 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}';`]); + 'the child-process module must have one named value import and one named type import', + ).toEqual([ + `import { ${spawnIdentifier} } from '${childProcessModule}';`, + `import type { SpawnSyncOptionsWithStringEncoding } 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); + 'the synchronous spawn identifier must appear only in its import, options comment, and single call site', + ).toBe(3); expect( /\.\.\.process\.env/.test(ownSource), 'a child environment is being built by copying the ambient environment', @@ -711,19 +2241,34 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo // 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); + expect( + direct.status, + `the marker child failed with status ${direct.status}, signal ${direct.signal}, stdout length ${direct.stdout.length}, stderr length ${direct.stderr.length}`, + ).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'), - ); + const observedHome = observed['HOME']; + expect(typeof observedHome === 'string', 'the marker child had no HOME').toBe(true); + if (observedHome === undefined) { + expect.fail('the marker child had no HOME'); + } + expect(observedHome === homedir(), 'the marker child received the real HOME').toBe(false); + expect( + observedHome.startsWith(direct.sandbox), + 'the marker child HOME is outside its sandbox', + ).toBe(true); + expect( + homedir().startsWith(observedHome), + 'the real HOME is nested under the observed HOME', + ).toBe(false); + for (const [name, value] of Object.entries(observed)) { + expect( + value.includes(join(homedir(), '.config', 'mosaic')), + `allowlisted environment name ${name} points at the real home`, + ).toBe(false); } // The XDG directory lists name private empty directories. An unset list @@ -732,8 +2277,8 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo 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(); + expect(value?.startsWith(direct.sandbox) === true, isolationReason).toBe(true); + expect(typeof value === 'string', isolationReason).toBe(true); if (value === undefined) { continue; } @@ -743,9 +2288,20 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo } // PATH is the fixture-owned directory, in order, and nothing else. - expect(observed['PATH']?.split(':')).toEqual([join(direct.sandbox, 'bin')]); + const observedPathEntries = observed['PATH']?.split(':') ?? []; + expect(observedPathEntries.length, 'fixture PATH entry count').toBe(1); + expect( + observedPathEntries.map((entry) => basename(entry)), + 'fixture PATH entry basenames', + ).toEqual(['bin']); + expect( + observedPathEntries[0] === join(direct.sandbox, 'bin'), + 'fixture PATH does not name the sandbox bin directory', + ).toBe(true); const observedPath = observed['PATH']; - expect(observedPath, 'the marker child had no PATH to enumerate').toBeDefined(); + expect(typeof observedPath === 'string', 'the marker child had no PATH to enumerate').toBe( + true, + ); if (observedPath === undefined) { return; } @@ -766,17 +2322,17 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo ]) { const offenders = reachable.filter(({ name }) => name === harness); expect( - offenders, - `${harness} is resolvable from fixture PATH in: ${offenders.map(({ directory }) => directory).join(', ')}`, - ).toEqual([]); + offenders.length, + `${harness} is resolvable from ${offenders.length} fixture PATH directories; basenames ${offenders.map(({ directory }) => basename(directory)).join(', ')}`, + ).toBe(0); } 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)); + realpathSync(fixtureCommand) === realpathSync(expectedTarget), + `${name} did not resolve to the expected binary basename ${basename(expectedTarget)}`, + ).toBe(true); } // Executed through the trusted shell, which is the route arm's own shape. @@ -788,16 +2344,19 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo `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); + expect( + viaShell.status, + `the shell-mediated marker child failed with status ${viaShell.status}, signal ${viaShell.signal}, stdout length ${viaShell.stdout.length}, stderr length ${viaShell.stderr.length}`, + ).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], + shellObserved[key] === expectedShellBase[key], `the shell-mediated child changed the builder's value for ${key}`, - ).toBe(expectedShellBase[key]); + ).toBe(true); } const added = Object.keys(shellObserved).filter((key) => !ALLOWED_CHILD_ENV.includes(key)); expect( @@ -806,45 +2365,91 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo ).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')); + shellObserved[key]?.includes(join(homedir(), '.config', 'mosaic')), + `shell-added environment name ${key} points at the real home`, + ).toBe(false); + } + }); + + it('fixture control: the TSX launcher delivers exactly the allowlist to its loader process', () => { + const viaTsx = spawnHermetic(PATH_COMMAND_TARGETS.tsx, ['--eval', ENV_MARKER_SCRIPT]); + expect(viaTsx.signal, 'the TSX marker child was signaled').toBeNull(); + expect(viaTsx.status, 'the TSX marker child exited unsuccessfully').toBe(0); + + // These are hard channel-integrity assertions. Environment diagnostics are + // meaningful only after both observed channels have been consumed whole. + consumeTsxStderr(viaTsx.stderr); + const tsxObserved = consumeTsxStdout(viaTsx.stdout); + + const missing = ALLOWED_CHILD_ENV.filter((key) => !(key in tsxObserved)); + expect + .soft(missing, `the TSX loader omitted allowlisted names: ${missing.join(', ')}`) + .toEqual([]); + const expectedTsxBase = buildHermeticChildEnv(viaTsx.sandbox); + for (const key of ALLOWED_CHILD_ENV) { + expect + .soft( + tsxObserved[key] === expectedTsxBase[key], + `the TSX loader rewrote allowlisted name ${key}`, + ) + .toBe(true); + } + + const added = Object.keys(tsxObserved).filter((key) => !ALLOWED_CHILD_ENV.includes(key)); + expect.soft(added, `the TSX loader added unaccounted names: ${added.join(', ')}`).toEqual([]); + + const loaderControls = Object.keys(tsxObserved).filter((key) => key.startsWith('NODE_')); + expect + .soft( + loaderControls, + `the TSX loader inherited or injected NODE_* names: ${loaderControls.join(', ')}`, + ) + .toEqual([]); + + for (const [key, value] of Object.entries(tsxObserved)) { + expect + .soft(!value.includes(homedir()), `TSX environment name ${key} points at the real home`) + .toBe(true); } }); /** - * 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. + * This control exercises the real, unmocked group-kill launcher/CLI through + * TSX. TSX spawns an esbuild service child and a loader/eval child, where the + * script 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 unless the process group is contained. 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. The containment step runs at + * the spawn site, and this case asserts both marker absence and proven + * process-group emptiness. Containment is not total: a descendant that calls + * setsid() for itself leaves both the group and session and is unreachable by + * group kill. */ - it('fixture control: timeout SIGKILLs the single-process arm and it writes no marker afterward', async () => { + it('fixture control: timeout SIGKILLs a TSX --eval launcher and observes ESRCH for its process group', async () => { + expect( + process.kill, + 'the kill stub is still installed; this containment result would be meaningless', + ).toBe(REAL_PROCESS_KILL); 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 result = spawnHermetic(PATH_COMMAND_TARGETS.tsx, ['--eval', markerScript], {}, timeoutMs); const marker = join(result.sandbox, 'tmp', markerName); - expect(result.signal, `the timeout did not send SIGKILL: ${result.output}`).toBe('SIGKILL'); + expect( + result.signal, + `the timeout result had status ${result.status}, signal ${result.signal}, stdout length ${result.stdout.length}, stderr length ${result.stderr.length}`, + ).toBe('SIGKILL'); await new Promise((resolve) => setTimeout(resolve, writeDelayMs + 250)); expect(existsSync(marker), 'the killed route process survived long enough to write').toBe( false, ); + expect(result.groupProvenEmpty).toBe(true); }); /** @@ -854,7 +2459,7 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo * 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 + * 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 @@ -879,21 +2484,29 @@ describe('KBN-101-02a local-dev — the package route refuses, not merely the mo } try { - const { status, signal, output } = runDevLocal(); + const { status, signal, output, groupProvenEmpty } = runDevLocal(); + expect(groupProvenEmpty).toBe(true); 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'); + expect( + output.includes('LOCAL_START_TIER_NOT_EXPLICIT'), + 'the route did not emit the undeclared-tier refusal code', + ).toBe(true); // 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', + expect( + output.includes('LOCAL_START_POSTGRES_DSN_PRESENT'), + 'the child inherited the parent DSN', + ).toBe(false); + expect(output.includes('mosaic:mosaic'), 'the child emitted parent DSN credentials').toBe( + false, ); + expect( + output.includes('BETTER_AUTH_SECRET'), + 'exited via bootstrap rather than refusing before it', + ).toBe(false); } finally { for (const [key, value] of restore) { if (value === undefined) { diff --git a/docs/native-kanban-sot/KBN-101-DB-ROLE-SPLIT.md b/docs/native-kanban-sot/KBN-101-DB-ROLE-SPLIT.md index 45e4c79fc..15b04aae7 100644 --- a/docs/native-kanban-sot/KBN-101-DB-ROLE-SPLIT.md +++ b/docs/native-kanban-sot/KBN-101-DB-ROLE-SPLIT.md @@ -442,7 +442,7 @@ its stated reason is the same defect class as the span gap that created this ite ### RED phase result -Focused matrix, gateway package: **83 failing / 17 passing (100 cases, 6 files)**, and the terminal +Focused matrix, gateway package: **83 failing / 40 passing (123 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 @@ -632,10 +632,21 @@ What follows is stated plainly because the temptation to round it off is exactly 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. +being torn down. + +**Historical, and superseded — recorded because the sequence is the point.** At the time this +paragraph was first written, the fixture's timeout control asserted only what it actually measured: +a single-process `exec node -e` sleeper was killed and wrote nothing, and the control was named for +that property alone. No assertion in the file established descendant containment, and the control +was explicitly not offered as evidence of it. **Current disposition:** that gap is closed. The +control now runs the real TSX **CLI/launcher** — `tsx --eval`, which loads the same loader and +esbuild children as the route without executing the absent packaged `dev:local` route — and +containment is asserted rather than assumed. An earlier revision of this sentence, and the control's +own name, said "the real TSX route"; the invocation says `--eval`, so the name claimed a subject the +call does not exercise and both have been corrected. See +_Timeout containment_ below for the mechanism, the ruling that governs it, and the residuals it does +not close. The earlier wording is kept because a document that silently overwrites the state it was +wrong about teaches nothing about how the error was found. 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 @@ -644,10 +655,19 @@ the test runner's `pgid` and `sid`, because a spawn inherits both by default. Th 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. +signal is safe to send. + +Which design does that, and whether the resulting emptiness proof is reuse-safe, **was under +architecture adjudication and is now settled** — the author did not settle it, which was the point +of routing it. The ruling is Design A with the gate set `G1, G2, G3-S (+ subordinate floor), G4, G5, +G6, G7, G8`, behind an independent verification gate. Its two most consequential parts are that a +negative kill is issued **only immediately after an enumeration that just proved at least one fully +identity-verified live member** (G7), and that unproven emptiness **retains** the sandbox rather than +removing it (G8). A subsequent ruling on the same gate settled what counts as proof: **ESRCH from +`kill(-pgid, 0)`**, not a zero-member scan, with enumeration retained for identity rather than for +existence. The mechanism, the accepted residual and its quantitative bound are recorded under +_Timeout containment_ below, including the one no group-based design closes: a descendant that calls +`setsid()` for itself leaves the group and the session. **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 @@ -712,28 +732,47 @@ the callback happened to throw first. How a proof reads is not a property of 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 +source that `node:child_process` is named exactly twice, once as the value import `{ spawnSync }` +and once as the type import `{ SpawnSyncOptionsWithStringEncoding }`, and matches both import lines +literally rather than counting them; that the `spawnSync` identifier occurs exactly three times — +its import, one occurrence in the comment above the options object, and its single call site; 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. +`fixture control: the spawn site delivers exactly the allowlist to a real child` 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. + +An earlier version of that paragraph opened by calling this the only case in the package-route arm +that runs a child at RED head. It is not, and the uniqueness was doing no work in the argument, so +it has been dropped rather than rescoped: the timeout containment control runs a real child at RED +head too, and a third environment measurement has since been added beside this one. + +That third measurement is `fixture control: the TSX launcher delivers exactly the allowlist to its +loader process`, and it exists because the two arms above prove the _fixture's_ hermeticity through +`node` and through the trusted shell, while the route's actual launcher is TSX — a loader that +registers module hooks and therefore has both reason and opportunity to add environment of its own. +Measured through the real TSX CLI, through the same one spawn site and the same two-command `PATH`, +the loader's child receives exactly the ten allowlisted names, each carrying the builder's own value +for that run's sandbox, with no added name and **no `NODE_*` variable of any kind** — no +`NODE_PATH`, no `NODE_OPTIONS`, no loader control. TSX writes one deprecation warning to stderr and +nothing else. That is the result the measurement was built to be able to contradict; it came back +clean, which is a finding and not a reassurance, and the case is retained so that a future TSX which +does inject a loader control reddens rather than passes silently. Like its siblings it is a harness +control and asserts nothing about the code under test. `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 @@ -798,40 +837,115 @@ 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: +The forty 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. They +divide into two populations that must never be summed as though they measured the same thing: +sixteen that make a claim about the code under test, and twenty-four that make a claim about +this spec's own harness. The sixteen: -| 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 | +| 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" | -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. +The other twenty-four greens are **harness self-verification, not coverage of `-02a` at all**. +They assert that this file's own containment machinery, identity guards and channel accounting +behave as specified — code that lives inside the spec file. Every one of them would still be green +if `local-dev.ts` were never written, because none of them touch it: + +| Passing control | What it establishes | +| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ten identity guards (`refuses undefined` … `refuses the verifier process group`) | a negative kill is refused before it is issued, for every unsafe child-identity shape | +| nine containment negative controls | G7 and G8 hold: enumeration precedes every signal, an empty group is never signaled, ESRCH forces re-enumeration, a non-ESRCH errno becomes a typed failure, identity pairs update across rounds, the bound failure is typed, and an unproven sandbox is retained with its absolute path named | +| two G8 wiring controls | the `'unproven'` flag arrives set from `makeChildSandbox`, and the flip to `'proven-empty'` still follows the proof in source order | +| fixture control: the TSX launcher delivers the allowlist | the launcher passes exactly the allowlist, with both output channels consumed byte-for-byte rather than merely matched | +| fixture control: timeout SIGKILLs TSX and proves its process group empty | the unmocked group-kill route contains a loader child that outlives SIGKILL to its TSX parent | + +| fixture control: the spawn site delivers the allowlist | green by construction; the guard on the instrument the environment cases depend on. An earlier revision listed this row in the subject table above, while its own cell there called it "harness control, not coverage" — it was counted on the side it explicitly disclaimed | + +Counting those twenty-four as coverage would be precisely the error this section exists to +prevent. The passing total grew from seventeen to forty while the module under test was still +unimplemented, and every added green is a statement about the instrument rather than about the +subject. The failing total did not move — 83 before and after — which is the measurement that says +no case changed sides while the instrument was being hardened. + +Two corrections to the paragraph above, both of which were wrong in an earlier revision in the +same direction — toward reading better than the evidence supports. + +The first is the split itself. It read seventeen subject to twenty-three harness; it is sixteen to +twenty-four. The `local-dev` spawn-site fixture control was tabled among the subject cases while +its own cell described it as "harness control, not coverage", so the document contradicted itself +within one row and the contradiction inflated the side that flatters the work. + +The second is the word "absent". `apps/gateway/src/local-dev.ts` is not absent and has not been +since the RED commit that introduced this spec — it is a tracked forty-three-line stub whose own +header says it "establishes nothing correctly and performs no dynamic import". What is absent is +the implementation, not the module. The distinction is load-bearing rather than pedantic: an +absent module makes a case fail, while a stub can make one pass for a reason that has nothing to +do with the contract, which is exactly the vacuous-green population this section itemizes. The +rest of the section had it right — every vacuous row already explains itself by what "the stub" +does — so the defect was confined to the summary sentence, which is the sentence most likely to be +quoted on its own. + +**Every pass/fail total in this section — forty passing, 83 failing — is the measurement taken +before the K1/K2/K3/K6 amendment, and has not been retaken.** The amendment added twenty controls +to `local-dev.spec.ts`, all of them harness self-verification, which moved the file to sixteen +subject claims and forty-four harness controls across sixty runtime cases (fifty-one literal +declarations, one of which is an `it.each` expanding to ten). Those sixty are declared counts, +obtained by reading the file; they are not results. Whether the twenty new controls pass is a +question for the independent gate, and stating a passing total here on the strength of having +written the cases would be the same overclaim the section exists to prevent. The subject count did +not move, which is the property worth checking: an amendment that hardened the instrument added no +claim about the subject. + +**The r3 amendment adds three further controls, and the same property holds.** The file is now +**sixteen subject claims and forty-seven harness controls across sixty-three runtime cases** +(fifty-four literal declarations, the same single `it.each` expanding to ten). The three additions +are `classifies a safe zero/zero process identity as present`, `keeps zero/zero nonmembers out of a +complete positive-group enumeration`, and `uses only the validated child pid for every negative +group argument` — a parse class, an enumeration outcome, and a signal-argument boundary, all three +claims about this spec's own instrument rather than about the code under test. + +The derivation is stated because the number is the kind of thing that gets carried forward rather +than recomputed. The r2 bytes were reconstructed from the published r2 patch, the reconstruction +was confirmed against that patch's own recorded digest, and the two declaration lists were compared +by name: three present now, none removed. That is why the harness figure is forty-seven rather than +forty-four held over, and why the subject figure is asserted as unmoved rather than assumed to be. +These remain declared counts obtained by reading the file. **No runtime case in this file has been +executed by its author, at r2 or at r3.** + +One coincidence is worth disarming explicitly, because it invites a false inference. An independent +run reported sixteen failing and forty-four passing cases, and this document declares sixteen +subject and forty-four harness. The numbers coincide on different axes and neither corroborates the +other; the reported failures were thirteen subject and three harness. Reading agreement into the +pair would be reading a coincidence as a measurement. The r3 counts break the coincidence, which is +convenient rather than meaningful. + +Seven of those sixteen 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 is not implemented yet — it is recorded here +so it cannot later be read as coverage. Of the nine non-vacuous greens, 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 @@ -842,6 +956,275 @@ clean", collapsing the exact distinction the refusal path is built on. The invar `present === false` if and only if `readability === 'absent'` is asserted directly, per state and across all seven rows at once. +### Timeout containment: what the fixture kills, and what it does not + +Node's `spawnSync` timeout kills exactly one process — the direct child. That is the whole of what +the built-in does, and for a single-process child it is sufficient. The required `dev:local` route +is not a single process. TSX spawns an esbuild service child and a `node --require .../preflight.cjs +--import .../loader.mjs --eval