From a69d1e2a562f887d7f5ac100e6d983094e3471cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 11 Nov 2026 12:15:45 +0000 Subject: [PATCH 1/5] test: centralize daemon fixture launches in declared plans --- docs/agents/test-authoring.md | 1 + ...n-client-ensure-explicit-lifecycle.test.ts | 67 +++-- .../__tests__/daemon-client-lifecycle.test.ts | 96 ++++--- .../daemon-client-startup-budget.test.ts | 158 ++++++---- .../daemon-client-startup-race.test.ts | 270 ++++++++++++------ .../__tests__/explicit-lifecycle-fixture.ts | 25 +- .../__tests__/registered-daemon-fixture.ts | 1 + packages/test-kit/src/index.ts | 4 + .../test-kit/src/registered-daemon-fixture.ts | 69 ++++- .../src/registered-daemon-launch-plan.test.ts | 148 ++++++++++ .../src/registered-daemon-launch-plan.ts | 105 +++++++ .../registered-daemon-fixture.test.ts | 28 ++ .../test-utils/registered-daemon-fixture.ts | 1 + .../test-utils/registered-http-daemon.ts | 5 +- 14 files changed, 728 insertions(+), 250 deletions(-) create mode 100644 packages/test-kit/src/registered-daemon-launch-plan.test.ts create mode 100644 packages/test-kit/src/registered-daemon-launch-plan.ts diff --git a/docs/agents/test-authoring.md b/docs/agents/test-authoring.md index 5c0d71175a..fcab24a906 100644 --- a/docs/agents/test-authoring.md +++ b/docs/agents/test-authoring.md @@ -39,6 +39,7 @@ Spy on that seam in place. Use `mkdtempForTest` or `mkdtempForTestSync`. After workers exit, global setup removes the run directory. Mock the seam the subject consumes. +For daemon fixture launch mocks, use `planRegisteredDaemonLaunches`. Daemon handlers receive fake runtime facts and facets, not generic dispatch mocks. When you migrate an ADR 0019 command, move its tests to the runtime seam. diff --git a/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts b/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts index a836c69ac0..94985b11b5 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-ensure-explicit-lifecycle.test.ts @@ -5,12 +5,12 @@ import { afterEach, test, vi } from 'vitest'; import { closeLoopbackServer, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; import { AppError } from '@agent-device/kernel/errors'; import { DAEMON_QUIESCE_COMMAND } from '@agent-device/daemon-contracts/daemon-resolution'; -import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner'; import { isProcessAlive } from '@agent-device/host-kit/process'; import { readVersion } from '@agent-device/host-kit/version'; import { finishRegisteredDaemonFixtures, spawnRegisteredDaemonFixture, + planRegisteredDaemonLaunches, waitForRegisteredDaemonFixture, } from './registered-daemon-fixture.ts'; import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; @@ -45,9 +45,6 @@ import { ensureDaemon } from '../daemon-client-ensure.ts'; // so a kill or a spawn is observable as a dead pid or a call to the launch seam. const spawn = vi.mocked(runCmdDetachedMonitored); -const actualCommand = await vi.importActual( - '@agent-device/host-kit/command', -); const actualRetry = await vi.importActual( '@agent-device/host-kit/retry', ); @@ -618,35 +615,43 @@ test('ensureDaemon quiesces an incompatible daemon that wins a startup race inst fs.mkdirSync(paths.baseDir, { recursive: true }); vi.mocked(sleep).mockImplementation(actualRetry.sleep); let winner: ReturnType | undefined; - spawn.mockImplementationOnce((_command, _args, options) => { - // An incompatible daemon registers just ahead of the one this call launches, which then exits busy. - winner = spawnRegisteredDaemonFixture( - paths, + spawn.mockImplementationOnce( + planRegisteredDaemonLaunches([ { - httpPort: stale.port, - token: 'local-secret', - version: '0.0.0-stale', - codeOrigin: 'checkout', - codeSignature: currentDaemonCodeSignature(), - capabilities: ['quiesce'], + kind: 'registered', + paths, + fields: { + httpPort: fresh.port, + token: 'local-secret', + version: readVersion(), + codeOrigin: 'checkout', + codeSignature: currentDaemonCodeSignature(), + }, + acquisitionBarrier: barrier, + companions: [ + { + kind: 'registered', + paths, + fields: { + httpPort: stale.port, + token: 'local-secret', + version: '0.0.0-stale', + codeOrigin: 'checkout', + codeSignature: currentDaemonCodeSignature(), + capabilities: ['quiesce'], + }, + observe(child) { + winner = child; + leaver.pid = child.pid; + // Released whether or not the winner published, so the launched child never waits forever. + const release = () => fs.writeFileSync(barrier, 'go'); + void waitForRegisteredDaemonFixture(paths, child).then(release, release); + }, + }, + ], }, - undefined, - ); - leaver.pid = winner.pid; - // Released whether or not the winner published, so the launched child never waits forever. - const release = () => fs.writeFileSync(barrier, 'go'); - void waitForRegisteredDaemonFixture(paths, winner).then(release, release); - // Our launch loses the race once the winner is registered: it exits with the busy code. - return actualCommand.runCmdDetachedMonitored( - process.execPath, - [ - '-e', - `const fs=require("fs");setInterval(()=>{if(fs.existsSync(process.argv[1]))process.exit(${DAEMON_STARTUP_EXIT_CODES.busy})},10)`, - barrier, - ], - options, - ); - }); + ]), + ); launchesFreshDaemonAt(paths, fresh.port); try { diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts index 03d38fc4b5..7440725dea 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts @@ -15,7 +15,7 @@ import { skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; import { - spawnRegisteredDaemonFixture, + planRegisteredDaemonLaunches, finishRegisteredDaemonFixture, finishRegisteredDaemonFixtures, } from './registered-daemon-fixture.ts'; @@ -142,40 +142,48 @@ function installSpawnedHttpDaemonAtOwnedStateDir( onStateDir: (stateDir: string) => void, ): void { mockSleep.mockImplementation(actualRetry.sleep); - mockRunCmdDetached.mockImplementation((_command, _args, options) => { - const ownedStateDir = String(options?.env?.AGENT_DEVICE_STATE_DIR); - onStateDir(ownedStateDir); - const ownedPaths = resolveDaemonPaths(ownedStateDir); - return spawnRegisteredDaemonFixture( - ownedPaths, - { - httpPort, - token: 'local-secret', - version: readVersion(), - codeOrigin: 'checkout', - codeSignature: currentDaemonCodeSignature(), + mockRunCmdDetached.mockImplementation( + planRegisteredDaemonLaunches([ + (options) => { + const ownedStateDir = String(options?.env?.AGENT_DEVICE_STATE_DIR); + onStateDir(ownedStateDir); + const ownedPaths = resolveDaemonPaths(ownedStateDir); + return { + kind: 'registered', + paths: ownedPaths, + fields: { + httpPort, + token: 'local-secret', + version: readVersion(), + codeOrigin: 'checkout', + codeSignature: currentDaemonCodeSignature(), + }, + }; }, - options, - ); - }); + ]), + ); } function installSpawnedHttpDaemon(paths: DaemonPaths, httpPort: number): void { mockSleep.mockImplementation(actualRetry.sleep); - mockRunCmdDetached.mockImplementation((_command, _args, options) => { - assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, paths.baseDir); - return spawnRegisteredDaemonFixture( - paths, - { - httpPort, - token: 'local-secret', - version: readVersion(), - codeOrigin: 'checkout', - codeSignature: currentDaemonCodeSignature(), + mockRunCmdDetached.mockImplementation( + planRegisteredDaemonLaunches([ + (options) => { + assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, paths.baseDir); + return { + kind: 'registered', + paths, + fields: { + httpPort, + token: 'local-secret', + version: readVersion(), + codeOrigin: 'checkout', + codeSignature: currentDaemonCodeSignature(), + }, + }; }, - options, - ); - }); + ]), + ); } function mockSocketConnectionFailures(failingPort: number): { @@ -279,14 +287,18 @@ test('sendToDaemon retains unknown metadata after a spawn failure', async () => vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir); let attempts = 0; - mockRunCmdDetached.mockImplementation((_command, _args, options) => { - attempts += 1; - assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, stateDir); - fs.mkdirSync(paths.baseDir, { recursive: true }); - fs.writeFileSync(paths.infoPath, '{"partial":true}\n', 'utf8'); - fs.writeFileSync(paths.lockPath, 'not-json\n', 'utf8'); - throw new Error(`spawn failed ${attempts}`); - }); + mockRunCmdDetached.mockImplementation( + planRegisteredDaemonLaunches([ + (options) => { + attempts += 1; + assert.equal(options?.env?.AGENT_DEVICE_STATE_DIR, stateDir); + fs.mkdirSync(paths.baseDir, { recursive: true }); + fs.writeFileSync(paths.infoPath, '{"partial":true}\n', 'utf8'); + fs.writeFileSync(paths.lockPath, 'not-json\n', 'utf8'); + return { kind: 'refuse', error: new Error(`spawn failed ${attempts}`) }; + }, + ]), + ); try { let thrown: unknown; @@ -326,17 +338,15 @@ test('sendToDaemon reports early daemon exit with log tail and startup paths', a vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir); let attempts = 0; - mockRunCmdDetached.mockImplementation((_command, _args, options) => { + const earlyExit = (options: Parameters[2]) => { attempts += 1; const stderrFd = options?.stdio?.[2]; if (typeof stderrFd === 'number') { fs.writeSync(stderrFd, `early daemon failure ${attempts}\n`); } - return { - pid: 43_200 + attempts, - exited: Promise.resolve({ pid: 43_200 + attempts, exitCode: 1 }), - }; - }); + return { kind: 'exit' as const, exit: { pid: 43_200 + attempts, exitCode: 1 } }; + }; + mockRunCmdDetached.mockImplementation(planRegisteredDaemonLaunches([earlyExit, earlyExit])); try { let thrown: unknown; diff --git a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts index 1146dd1a50..fa6c00285c 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts @@ -25,6 +25,7 @@ import { isProcessAlive } from '@agent-device/host-kit/process'; import { readVersion } from '@agent-device/host-kit/version'; import { spawnRegisteredDaemonFixture, + planRegisteredDaemonLaunches, finishRegisteredDaemonFixtures, waitForFixtureFile, } from './registered-daemon-fixture.ts'; @@ -86,14 +87,15 @@ function fields(httpPort: number) { } /** A deferred-publication fixture that never exits on its own; retirement can still stop it. */ -function spawnUnregisteredDaemonChild( - paths: DaemonPaths, - options: Parameters[2], - emitStartupMarker = false, -): ReturnType { +function unregisteredDaemonLaunch(paths: DaemonPaths, emitStartupMarker = false) { fs.mkdirSync(paths.baseDir, { recursive: true }); fs.writeFileSync(path.join(paths.baseDir, 'defer-publication'), 'wait'); - return spawnRegisteredDaemonFixture(paths, fields(1), options, undefined, { emitStartupMarker }); + return { + kind: 'registered' as const, + paths, + fields: fields(1), + fixtureOptions: { emitStartupMarker }, + }; } function registrationHeldFor(paths: DaemonPaths, pid: number): string { @@ -160,12 +162,19 @@ test('a daemon slower than the retired 15 s budget starts successfully while it const now = virtualClock(); const spawned = { at: 0, child: undefined as { pid: number } | undefined }; const booted = registrationBooted(paths); - spawn.mockImplementation((_command, _args, options) => { - const child = spawnRegisteredDaemonFixture(paths, fields(http.port), options); - spawned.at = now.value; - spawned.child = child; - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: fields(http.port), + observe(child) { + spawned.at = now.value; + spawned.child = child; + }, + }, + ]), + ); fs.writeFileSync(path.join(paths.baseDir, 'defer-publication'), 'wait'); let nextPhase = 0; pause.mockImplementation(async () => { @@ -208,20 +217,21 @@ test('a daemon that exits during startup fails with startup-exited within one se const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-exit-fast-')); let resolveFirstExit: ((exit: ExecDetachedExit) => void) | undefined; let exitObservedAt = 0; - spawn.mockImplementation(() => { - const pid = 998_231 + spawn.mock.calls.length; - if (spawn.mock.calls.length === 1) { - const exited = new Promise((resolve) => { - resolveFirstExit = resolve; - }); - void exited.then(() => { - exitObservedAt = Date.now(); - }); - setTimeout(() => resolveFirstExit?.({ pid, exitCode: 1 }), 400); - return { pid, exited }; - } - return { pid, exited: Promise.resolve({ pid, exitCode: 1 }) }; + const exitGate = new Promise((resolve) => { + resolveFirstExit = () => resolve(); }); + void exitGate.then(() => { + exitObservedAt = Date.now(); + }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + () => { + setTimeout(() => resolveFirstExit?.({ pid: 998_232, exitCode: 1 }), 400); + return { kind: 'exit', exit: { pid: 998_232, exitCode: 1 }, exitGate }; + }, + { kind: 'exit', exit: { pid: 998_233, exitCode: 1 } }, + ]), + ); pause.mockImplementation(async (ms) => { await realPause(Math.min(Number(ms), 50)); }); @@ -238,10 +248,16 @@ test('a live daemon that publishes no startup marker is retired as stalled befor const started = now.value; const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-no-marker-')); let child: ReturnType | undefined; - spawn.mockImplementation((_command, _args, options) => { - child = spawnUnregisteredDaemonChild(paths, options); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + () => ({ + ...unregisteredDaemonLaunch(paths), + observe(launched) { + child = launched; + }, + }), + ]), + ); const booted = registrationBooted(paths); pause.mockImplementation(async () => { if (!booted()) return await realPause(); @@ -278,10 +294,16 @@ test('a live daemon that keeps progressing but never registers fails at the env const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-ceiling-')); let child: ReturnType | undefined; const booted = registrationBooted(paths); - spawn.mockImplementation((_command, _args, options) => { - child = spawnUnregisteredDaemonChild(paths, options, true); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + () => ({ + ...unregisteredDaemonLaunch(paths, true), + observe(launched) { + child = launched; + }, + }), + ]), + ); pause.mockImplementation(async () => { if (!booted()) return await realPause(); if (now.value - started < 30_000) now.value += 1_000; @@ -324,10 +346,16 @@ test("a startup progressed by a fresh launch is not judged stalled by an earlier const started = now.value; let child: ReturnType | undefined; let booted = false; - spawn.mockImplementation((_command, _args, options) => { - child = spawnUnregisteredDaemonChild(paths, options, true); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + () => ({ + ...unregisteredDaemonLaunch(paths, true), + observe(launched) { + child = launched; + }, + }), + ]), + ); pause.mockImplementation(async () => { if (child && !booted) { booted = fs.existsSync(registrationHeldFor(paths, child.pid)); @@ -365,12 +393,19 @@ test('a busy exit while a live lock holder defers publication reaches the ceilin }); await waitForFixtureFile(registrationHeldFor(paths, winner.pid)); let contender: ReturnType | undefined; - spawn.mockImplementation((_command, _args, options) => { - contender = spawnRegisteredDaemonFixture(paths, fields(1), options, undefined, { - emitStartupMarkerBeforeAcquisition: true, - }); - return contender; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: fields(1), + fixtureOptions: { emitStartupMarkerBeforeAcquisition: true }, + observe(child) { + contender = child; + }, + }, + ]), + ); pause.mockImplementation(async () => { await realPause(20); }); @@ -403,11 +438,11 @@ test('a child gone at the deadline without an observed exit and no live startup vi.stubEnv('AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS', '2000'); const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-gone-at-deadline-')); livenessOverrides = new Map([[997_842, false]]); - spawn.mockImplementation(() => ({ - pid: 997_842, - exited: new Promise(() => {}), - readIdentity: () => ({ pid: 997_842, startTime: null }), - })); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { kind: 'exit', exit: { pid: 997_842 }, exitGate: new Promise(() => {}) }, + ]), + ); pause.mockImplementation(async () => { await realPause(50); }); @@ -422,13 +457,17 @@ test('an observed exit on a reused launch pid is not a live startup at the deadl const reusedPid = 997_603; livenessOverrides = new Map([[reusedPid, true]]); let resolveExit: ((exit: ExecDetachedExit) => void) | undefined; - spawn.mockImplementation(() => ({ - pid: reusedPid, - exited: new Promise((resolve) => { - resolveExit = resolve; - }), - readIdentity: () => ({ pid: reusedPid, startTime: null }), - })); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'exit', + exit: { pid: reusedPid, exitCode: DAEMON_STARTUP_EXIT_CODES.busy }, + exitGate: new Promise((resolve) => { + resolveExit = () => resolve(); + }), + }, + ]), + ); const now = virtualClock(); let advanced = false; pause.mockImplementation(async () => { @@ -448,10 +487,11 @@ test('an observed exit on a reused launch pid is not a live startup at the deadl test('an unproven registration exit reports startup-exited even under a short env ceiling', async () => { vi.stubEnv('AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS', '2000'); const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-start-exit-under-ceiling-')); - spawn.mockImplementation(() => ({ - pid: 998_444, - exited: Promise.resolve({ pid: 998_444, exitCode: DAEMON_STARTUP_EXIT_CODES.unproven }), - })); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { kind: 'exit', exit: { pid: 998_444, exitCode: DAEMON_STARTUP_EXIT_CODES.unproven } }, + ]), + ); pause.mockImplementation(async () => { await realPause(); }); diff --git a/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts b/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts index fbede191b6..13f97b6e42 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-startup-race.test.ts @@ -19,6 +19,7 @@ import { } from '@agent-device/test-kit'; import { spawnRegisteredDaemonFixture, + planRegisteredDaemonLaunches, finishRegisteredDaemonFixtures, } from './registered-daemon-fixture.ts'; import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; @@ -149,9 +150,11 @@ test.for([ }), ); const originalInfo = fs.readFileSync(paths.infoPath, 'utf8'); - spawn.mockImplementation(() => { - throw new Error('fixture refuses a replacement launch'); - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { kind: 'refuse', error: new Error('fixture refuses a replacement launch') }, + ]), + ); try { if (expectedAllowed) { assert.equal((await sendToDaemon(request(paths))).ok, true); @@ -176,10 +179,14 @@ test.for([ test('a synchronous private startup failure removes its never-started owned directory', async () => { let paths: DaemonPaths | undefined; - spawn.mockImplementation((_command, _args, options) => { - paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); - throw new Error('cannot launch fixture'); - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + (options) => { + paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); + return { kind: 'refuse', error: new Error('cannot launch fixture') }; + }, + ]), + ); await assert.rejects( sendToDaemon({ session: 'default', command: 'test', positionals: [], flags: {} }), (error: unknown) => { @@ -205,12 +212,22 @@ test.for(['early exit', 'timeout'] as const)( let advanced = false; vi.stubEnv('AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS', '15000'); vi.spyOn(Date, 'now').mockImplementation(() => now); - spawn.mockImplementation((_command, _args, options) => { - paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); - fs.writeFileSync(path.join(paths.baseDir, 'defer-publication'), 'wait'); - child = spawnRegisteredDaemonFixture(paths, fields(1), options); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + (options) => { + paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); + fs.writeFileSync(path.join(paths.baseDir, 'defer-publication'), 'wait'); + return { + kind: 'registered', + paths, + fields: fields(1), + observe(launched) { + child = launched; + }, + }; + }, + ]), + ); pause.mockImplementation(async (ms) => { if (advanced) { now += ms; @@ -264,20 +281,27 @@ for (const command of ['devices', 'test']) { let genuineExit: ExecDetachedExit | undefined; let contender: ReturnType | undefined; let releaseJoin: (exit: ExecDetachedExit) => void = () => {}; - let pauses = 0; - spawn.mockImplementation((_command, _args, options) => { - contender = spawnRegisteredDaemonFixture(paths, fields(http.port), options); - void contender.exited.then((exit) => { - assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); - genuineExit = exit; - }); - return { - ...contender, - exited: new Promise((resolve) => { - releaseJoin = resolve; - }), - }; + const exitGate = new Promise((resolve) => { + releaseJoin = () => resolve(); }); + let pauses = 0; + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: fields(http.port), + exitGate, + observe(child) { + contender = child; + void child.exited.then((exit) => { + assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); + genuineExit = exit; + }); + }, + }, + ]), + ); pause.mockImplementation(async (ms) => { pauses += 1; fs.rmSync(deferred, { force: true }); @@ -317,16 +341,25 @@ test('a client-held claim is waited out before a fresh daemon attempt', async (t if (claim.status !== 'acquired') throw new Error('fixture claim refused'); let loserJoined = false; let released = false; - spawn.mockImplementation((_command, _args, options) => { - const child = spawnRegisteredDaemonFixture(paths, fields(http.port), options); - if (spawn.mock.calls.length === 1) - void child.exited.then((exit) => { - assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); - loserJoined = true; - }); - else assert.equal(loserJoined, true); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: fields(http.port), + observe(child) { + void child.exited.then((exit) => { + assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); + loserJoined = true; + }); + }, + }, + () => { + assert.equal(loserJoined, true); + return { kind: 'registered', paths, fields: fields(http.port) }; + }, + ]), + ); pause.mockImplementation(async (ms) => { if (loserJoined && !released) { await claim.acquisition.release(); @@ -359,10 +392,9 @@ for (const exit of [ fs.writeFileSync(deferred, 'wait'); const winner = spawnRegisteredDaemonFixture(paths, fields(http.port), { stdio: 'ignore' }); await awaitFile(path.join(paths.baseDir, 'registration-held')); - spawn.mockImplementation(() => ({ - pid: 999_999, - exited: Promise.resolve({ pid: 999_999, ...exit }), - })); + spawn.mockImplementation( + planRegisteredDaemonLaunches([{ kind: 'exit', exit: { pid: 999_999, ...exit } }]), + ); pause.mockImplementation(async (ms) => { fs.rmSync(deferred, { force: true }); await actualRetry.sleep(ms); @@ -394,22 +426,32 @@ test('a busy contender that exits sweeps its own pre-lock marker before the retr assert.equal(claim.status, 'acquired'); if (claim.status !== 'acquired') throw new Error('fixture claim refused'); let released = false; - spawn.mockImplementation((_command, _args, options) => { - if (spawn.mock.calls.length !== 1) - throw new Error('no second launch: the retry boundary must be observable without a sweeper'); - const child = spawnRegisteredDaemonFixture(paths, fields(http.port), options, undefined, { - emitStartupMarkerBeforeAcquisition: true, - }); - void child.exited.then((exit) => { - assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); - if (!released) { - void claim.acquisition.release().then(() => { - released = true; - }); - } - }); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: fields(http.port), + fixtureOptions: { emitStartupMarkerBeforeAcquisition: true }, + observe(child) { + void child.exited.then((exit) => { + assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); + if (!released) { + void claim.acquisition.release().then(() => { + released = true; + }); + } + }); + }, + }, + { + kind: 'refuse', + error: new Error( + 'no second launch: the retry boundary must be observable without a sweeper', + ), + }, + ]), + ); pause.mockImplementation((ms) => actualRetry.sleep(Math.min(Number(ms), 50))); try { await assert.rejects( @@ -445,15 +487,21 @@ test('a joined busy contender waits for a published winner to become ready witho const winner = spawnRegisteredDaemonFixture(paths, fields(http.port), { stdio: 'ignore' }); await awaitFile(path.join(paths.baseDir, 'registration-held')); let contenderExit: ExecDetachedExit | undefined; - spawn.mockImplementation((_command, _args, options) => { - const child = spawnRegisteredDaemonFixture(paths, fields(http.port), options, undefined, { - emitStartupMarkerBeforeAcquisition: true, - }); - void child.exited.then((exit) => { - contenderExit = exit; - }); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: fields(http.port), + fixtureOptions: { emitStartupMarkerBeforeAcquisition: true }, + observe(child) { + void child.exited.then((exit) => { + contenderExit = exit; + }); + }, + }, + ]), + ); pause.mockImplementation(async () => { if (contenderExit) fs.rmSync(deferred, { force: true }); await actualRetry.sleep(10); @@ -501,15 +549,18 @@ for (const held of [true, false]) { nativeTimeout(handler, ms === 1_000 ? 0 : ms, ...args), ); vi.spyOn(Date, 'now').mockImplementation(() => now); - spawn.mockImplementation(() => ({ - pid: 999_999, - exited: - spawn.mock.calls.length === 1 - ? Promise.resolve({ pid: 999_999, exitCode: DAEMON_STARTUP_EXIT_CODES.busy }) - : new Promise((resolve) => { - finishPending = () => resolve({ pid: 999_999, exitCode: 1 }); - }), - })); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { kind: 'exit', exit: { pid: 999_999, exitCode: DAEMON_STARTUP_EXIT_CODES.busy } }, + { + kind: 'exit', + exit: { pid: 999_999, exitCode: 1 }, + exitGate: new Promise((resolve) => { + finishPending = resolve; + }), + }, + ]), + ); pause.mockImplementation(async (ms) => { if (!advanced) { if (!held) { @@ -556,16 +607,25 @@ test.for([ let offset = 0; const clock = vi.spyOn(Date, 'now').mockImplementation(() => wallTime() + offset); let joined = false; - spawn.mockImplementation((_command, _args, options) => { - if (spawn.mock.calls.length > 1) assert.equal(joined, true); - const child = spawnRegisteredDaemonFixture(paths, fields(http.port), options); - if (spawn.mock.calls.length === 1) - void child.exited.then((exit) => { - assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); - joined = true; - }); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: fields(http.port), + observe(child) { + void child.exited.then((exit) => { + assert.equal(exit.exitCode, DAEMON_STARTUP_EXIT_CODES.busy); + joined = true; + }); + }, + }, + () => { + assert.equal(joined, true); + return { kind: 'registered', paths, fields: fields(http.port) }; + }, + ]), + ); pause.mockImplementation(async (ms) => { if (joined) { fs.rmSync(deferred, { force: true }); @@ -609,11 +669,21 @@ test('a failed own transport probe retires and joins the private startup before let paths: DaemonPaths | undefined; let child: ReturnType | undefined; let failure: AppError | undefined; - spawn.mockImplementation((_command, _args, options) => { - paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); - child = spawnRegisteredDaemonFixture(paths, fields(http.port), options); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + (options) => { + paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); + return { + kind: 'registered', + paths, + fields: fields(http.port), + observe(launched) { + child = launched; + }, + }; + }, + ]), + ); pause.mockImplementation(actualRetry.sleep); try { await assert.rejects( @@ -660,12 +730,22 @@ test.for(['default', 'private replay'] as const)( let child: ReturnType | undefined; let now = Date.now(); vi.spyOn(Date, 'now').mockImplementation(() => now); - spawn.mockImplementation((_command, _args, options) => { - paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); - child = spawnRegisteredDaemonFixture(paths, fields(http.port), options); - vi.mocked(readProcessStartTime).mockReturnValueOnce(null); - return child; - }); + spawn.mockImplementation( + planRegisteredDaemonLaunches([ + (options) => { + paths = resolveDaemonPaths(String(options?.env?.AGENT_DEVICE_STATE_DIR)); + return { + kind: 'registered', + paths, + fields: fields(http.port), + observe(launched) { + child = launched; + vi.mocked(readProcessStartTime).mockReturnValueOnce(null); + }, + }; + }, + ]), + ); pause.mockImplementation(async () => { assert.ok(paths); if (http.rpcRequests.length === 0) { diff --git a/packages/daemon-client/src/__tests__/explicit-lifecycle-fixture.ts b/packages/daemon-client/src/__tests__/explicit-lifecycle-fixture.ts index ed0c5644ec..952fbd2a1a 100644 --- a/packages/daemon-client/src/__tests__/explicit-lifecycle-fixture.ts +++ b/packages/daemon-client/src/__tests__/explicit-lifecycle-fixture.ts @@ -14,6 +14,7 @@ import type { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; import { readVersion } from '@agent-device/host-kit/version'; import { spawnRegisteredDaemonFixture, + planRegisteredDaemonLaunches, waitForRegisteredDaemonFixture, } from './registered-daemon-fixture.ts'; import { currentDaemonCodeSignature } from './code-signature-fixture.ts'; @@ -172,18 +173,20 @@ export function launchesFreshDaemonAt( paths: DaemonPaths, httpPort: number, ): void { - spawn.mockImplementation((_command, _args, options) => - spawnRegisteredDaemonFixture( - paths, + spawn.mockImplementation( + planRegisteredDaemonLaunches([ { - httpPort, - token: 'local-secret', - version: readVersion(), - codeOrigin: 'checkout', - codeSignature: currentDaemonCodeSignature(), - capabilities: ['quiesce'], + kind: 'registered', + paths, + fields: { + httpPort, + token: 'local-secret', + version: readVersion(), + codeOrigin: 'checkout', + codeSignature: currentDaemonCodeSignature(), + capabilities: ['quiesce'], + }, }, - options, - ), + ]), ); } diff --git a/packages/daemon-client/src/__tests__/registered-daemon-fixture.ts b/packages/daemon-client/src/__tests__/registered-daemon-fixture.ts index e38072c789..e7264f9e4d 100644 --- a/packages/daemon-client/src/__tests__/registered-daemon-fixture.ts +++ b/packages/daemon-client/src/__tests__/registered-daemon-fixture.ts @@ -10,6 +10,7 @@ const actualCommand = await vi.importActual; @@ -43,6 +47,9 @@ export type RegisteredDaemonFixtures< TPaths extends RegisteredDaemonPaths, TFields extends object, > = Readonly<{ + planRegisteredDaemonLaunches: ( + steps: readonly DaemonFixtureLaunchStep[], + ) => typeof runCmdDetachedMonitored; /** A real registration owner, advertising the caller's fields and joining before deletion. */ registeredDaemonFixtureArgs: ( paths: TPaths, @@ -80,6 +87,15 @@ export function createRegisteredDaemonFixtures< string, Array<{ launch: RegisteredDaemonChild; startTime: string | null }> >(); + const planner = createDaemonFixtureLaunchPlanner((step, options) => + spawnRegisteredDaemonFixture( + step.paths, + step.fields, + options, + step.acquisitionBarrier, + step.fixtureOptions, + ), + ); function registeredDaemonFixtureArgs( paths: TPaths, @@ -87,6 +103,7 @@ export function createRegisteredDaemonFixtures< acquisitionBarrier?: string, fixtureOptions?: RegisteredDaemonFixtureOptions, ): string[] { + planner.assertLaunchAllowed(); // One directory per launch so a later build cannot overwrite a script an earlier child has // not loaded; the path still ends in the real daemon entry name for the identity checks. const launchDir = path.join(paths.baseDir, 'fixture-entries', crypto.randomUUID()); @@ -138,6 +155,7 @@ setInterval(() => {}, 1000); args: string[], options: Parameters[2], ): RegisteredDaemonChild { + planner.assertLaunchAllowed(); const child = composition.launch(process.execPath, args, options); const owned = children.get(paths.baseDir) ?? []; owned.push({ launch: child, startTime: readProcessStartTime(child.pid) }); @@ -186,24 +204,59 @@ setInterval(() => {}, 1000); } async function finishRegisteredDaemonFixture(stateDir: string): Promise { + const errors: unknown[] = []; for (const owned of children.get(stateDir) ?? []) { - const child = owned.launch; - const termination = await composition.stopDaemonProcess( - { pid: child.pid, startTime: owned.startTime }, - { mode: 'force', termTimeoutMs: 0, killTimeoutMs: 2_000 }, - ); - assert.notEqual(termination.status, 'retained', JSON.stringify(termination)); - await child.exited; + try { + const child = owned.launch; + const termination = await composition.stopDaemonProcess( + { pid: child.pid, startTime: owned.startTime }, + { mode: 'force', termTimeoutMs: 0, killTimeoutMs: 2_000 }, + ); + assert.notEqual(termination.status, 'retained', JSON.stringify(termination)); + let timer: ReturnType | undefined; + try { + await Promise.race([ + child.exited, + new Promise((_resolve, reject) => { + timer = setTimeout( + () => + reject( + new Error(`Daemon fixture child ${child.pid} was not joined after termination`), + ), + 1_000, + ); + }), + ]); + } finally { + clearTimeout(timer); + } + } catch (error) { + errors.push(error); + } } + if (errors.length) throw new AggregateError(errors, 'Daemon fixture children did not finish'); children.delete(stateDir); fs.rmSync(stateDir, { recursive: true, force: true }); + planner.assertPlans(); } async function finishRegisteredDaemonFixtures(): Promise { - for (const stateDir of children.keys()) await finishRegisteredDaemonFixture(stateDir); + const results = await Promise.allSettled( + [...children.keys()].map(finishRegisteredDaemonFixture), + ); + const errors = results + .filter((result) => result.status === 'rejected') + .map((result) => result.reason); + try { + planner.assertPlans(); + } catch (error) { + errors.push(error); + } + if (errors.length) throw new AggregateError(errors, 'Daemon fixture teardown failed'); } return { + planRegisteredDaemonLaunches: planner.planRegisteredDaemonLaunches, registeredDaemonFixtureArgs, launchRegisteredDaemonFixtureArgs, spawnRegisteredDaemonFixture, diff --git a/packages/test-kit/src/registered-daemon-launch-plan.test.ts b/packages/test-kit/src/registered-daemon-launch-plan.test.ts new file mode 100644 index 0000000000..1a1c2e559a --- /dev/null +++ b/packages/test-kit/src/registered-daemon-launch-plan.test.ts @@ -0,0 +1,148 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import { + createRegisteredDaemonFixtures, + type RegisteredDaemonChild, +} from './registered-daemon-fixture.ts'; +import { mkdtempForTestSync } from './tmp-dir.ts'; + +afterEach(() => vi.useRealTimers()); + +function diagnostic(error: unknown): string { + if (!(error instanceof Error)) return String(error); + return [ + error.message, + diagnostic(error.cause), + ...(error instanceof AggregateError ? error.errors.map(diagnostic) : []), + ].join('\n'); +} + +function rejectsContract(pending: Promise, pattern: RegExp): Promise { + return assert.rejects(pending, (error: unknown) => { + assert.match(diagnostic(error), pattern); + return true; + }); +} + +function fixture(exited = Promise.resolve({ pid: process.pid, exitCode: 0 })) { + const baseDir = mkdtempForTestSync('daemon-launch-plan-'); + const paths = { + baseDir, + sessionsDir: path.join(baseDir, 'sessions'), + infoPath: path.join(baseDir, 'daemon.json'), + }; + const child: RegisteredDaemonChild = { pid: process.pid, exited }; + let launches = 0; + let stops = 0; + const fixtures = createRegisteredDaemonFixtures({ + registrationOwnerUrl: 'file:///unused-registration.ts', + startupPhasesUrl: 'file:///unused-phases.ts', + launch: () => { + launches++; + return child; + }, + stopDaemonProcess: async () => { + stops++; + return { status: 'exited' }; + }, + readDaemonInfo: () => null, + }); + return { fixtures, paths, child, launches: () => launches, stops: () => stops }; +} + +test('refusal and an unexpected second launch start no extra writer even when their errors are caught', async () => { + const f = fixture(); + const refusal = new Error('launch refused'); + const refuse = f.fixtures.planRegisteredDaemonLaunches([{ kind: 'refuse', error: refusal }]); + assert.throws( + () => refuse('node', []), + (error) => error === refusal, + ); + assert.equal(fs.existsSync(path.join(f.paths.baseDir, 'fixture-entries')), false); + const launch = f.fixtures.planRegisteredDaemonLaunches([ + { kind: 'registered', paths: f.paths, fields: {} }, + ]); + assert.equal(launch('node', []), f.child); + assert.throws(() => launch('node', []), /unexpected launch 2/); + assert.equal(f.launches(), 1); + await rejectsContract(f.fixtures.finishRegisteredDaemonFixtures(), /unexpected launch 2/); +}); + +test('a refusal builder cannot secretly launch a child before returning its refusal', async () => { + const f = fixture(); + const launch = f.fixtures.planRegisteredDaemonLaunches([ + () => { + f.fixtures.spawnRegisteredDaemonFixture(f.paths, {}, undefined); + return { kind: 'refuse', error: new Error('refused after spawning') }; + }, + ]); + assert.throws(() => launch('node', []), /plan callback attempted to start a child/); + assert.equal(f.launches(), 0); + assert.equal(fs.existsSync(path.join(f.paths.baseDir, 'fixture-entries')), false); + await rejectsContract( + f.fixtures.finishRegisteredDaemonFixtures(), + /plan callback attempted to start a child/, + ); +}); + +test('an observer cannot replace the returned child handle and its violation survives caught errors', async () => { + const f = fixture(); + const launch = f.fixtures.planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths: f.paths, + fields: {}, + observe: () => ({ pid: 1234, exited: Promise.resolve({ pid: 1234, exitCode: 0 }) }), + }, + ]); + assert.equal(launch('node', []), f.child); + await rejectsContract( + f.fixtures.finishRegisteredDaemonFixtures(), + /observer returned a replacement handle/, + ); +}); + +test('teardown fails when termination reports success but the exact child exit never joins', async () => { + vi.useFakeTimers(); + const f = fixture(new Promise(() => {})); + f.fixtures.spawnRegisteredDaemonFixture(f.paths, {}, undefined); + const rejected = rejectsContract( + f.fixtures.finishRegisteredDaemonFixtures(), + /was not joined after termination/, + ); + await vi.advanceTimersByTimeAsync(1_000); + await rejected; +}); + +test('a declared launch returns its exact child and teardown joins it before deleting state', async () => { + const f = fixture(); + const launch = f.fixtures.planRegisteredDaemonLaunches([ + { kind: 'registered', paths: f.paths, fields: {} }, + ]); + const child = launch('node', []); + assert.equal(child.pid, process.pid); + assert.equal(child.exited, f.child.exited); + await f.fixtures.finishRegisteredDaemonFixtures(); + assert.equal(fs.existsSync(f.paths.baseDir), false); +}); + +test('a failed child join does not prevent teardown from stopping the remaining children', async () => { + vi.useFakeTimers(); + const f = fixture(new Promise(() => {})); + f.fixtures.spawnRegisteredDaemonFixture(f.paths, {}, undefined); + f.fixtures.spawnRegisteredDaemonFixture(f.paths, {}, undefined); + const rejected = rejectsContract( + f.fixtures.finishRegisteredDaemonFixtures(), + /was not joined after termination/, + ); + await vi.runAllTimersAsync(); + await rejected; + assert.equal(f.stops(), 2); + assert.equal( + fs.existsSync(f.paths.baseDir), + true, + 'failed cleanup must retain state for diagnosis', + ); +}); diff --git a/packages/test-kit/src/registered-daemon-launch-plan.ts b/packages/test-kit/src/registered-daemon-launch-plan.ts new file mode 100644 index 0000000000..b5f163fb3b --- /dev/null +++ b/packages/test-kit/src/registered-daemon-launch-plan.ts @@ -0,0 +1,105 @@ +import type { runCmdDetachedMonitored, ExecDetachedExit } from '@agent-device/host-kit/command'; +import type { RegisteredDaemonChild } from './registered-daemon-fixture.ts'; + +type LaunchOptions = Parameters[2]; + +export type DaemonFixtureLaunch = + | { kind: 'refuse'; error: Error } + | { kind: 'exit'; exit: ExecDetachedExit; exitGate?: Promise } + | { + kind: 'registered'; + paths: P; + fields: F; + acquisitionBarrier?: string; + fixtureOptions?: { + emitStartupMarker?: boolean; + emitStartupMarkerBeforeAcquisition?: boolean; + }; + exitGate?: Promise; + observe?: (child: RegisteredDaemonChild) => void; + companions?: readonly Extract, { kind: 'registered' }>[]; + }; + +export type DaemonFixtureLaunchStep = + | DaemonFixtureLaunch + | ((options: LaunchOptions) => DaemonFixtureLaunch); + +/** Owns the launch decision and handle; callbacks may describe or observe, but never launch. */ +export function createDaemonFixtureLaunchPlanner( + launch: ( + step: Extract, { kind: 'registered' }>, + options: LaunchOptions, + ) => RegisteredDaemonChild, +) { + let describing = false; + const violations: Error[] = []; + const refuse = (message: string): never => { + const error = new Error(`Daemon fixture launch contract: ${message}`); + violations.push(error); + throw error; + }; + function start( + step: Extract, { kind: 'registered' }>, + options: LaunchOptions, + ): RegisteredDaemonChild { + for (const companion of step.companions ?? []) start(companion, options); + const child = Object.freeze(launch(step, options)); + describing = true; + try { + const result: unknown = step.observe?.(child); + if (result !== undefined) refuse('an observer returned a replacement handle or value'); + } catch (error) { + violations.push( + new Error('Daemon fixture launch observer failed after starting a child', { cause: error }), + ); + } finally { + describing = false; + } + return child; + } + return { + assertLaunchAllowed() { + if (describing) refuse('a plan callback attempted to start a child'); + }, + assertPlans() { + if (violations.length) + throw new AggregateError(violations.splice(0), 'Daemon fixture launch contract violated'); + }, + planRegisteredDaemonLaunches( + steps: readonly DaemonFixtureLaunchStep[], + ): typeof runCmdDetachedMonitored { + let index = 0; + return (_command, _args, options) => { + if (describing) return refuse('a plan callback attempted a nested launch'); + const next = steps[index++]; + if (!next) return refuse(`unexpected launch ${index}; planned ${steps.length}`); + let step: DaemonFixtureLaunch; + describing = true; + try { + step = typeof next === 'function' ? next(options) : next; + } finally { + describing = false; + } + if (step.kind === 'refuse') throw step.error; + if (step.kind === 'exit') + return { + pid: step.exit.pid, + exited: Promise.resolve(step.exit).then(async (exit) => { + await step.exitGate; + return exit; + }), + }; + const child = start(step, options); + return step.exitGate + ? { + pid: child.pid, + exited: child.exited.then(async (exit) => { + await step.exitGate; + return exit; + }), + } + : child; + }; + }, + }; +} diff --git a/src/__tests__/test-utils/registered-daemon-fixture.test.ts b/src/__tests__/test-utils/registered-daemon-fixture.test.ts index d179429605..edaf963524 100644 --- a/src/__tests__/test-utils/registered-daemon-fixture.test.ts +++ b/src/__tests__/test-utils/registered-daemon-fixture.test.ts @@ -11,11 +11,39 @@ import { launchRegisteredDaemonFixtureArgs, registeredDaemonFixtureArgs, spawnRegisteredDaemonFixture, + planRegisteredDaemonLaunches, waitForFixtureFile, waitForRegisteredDaemonFixture, finishRegisteredDaemonFixture, } from './registered-daemon-fixture.ts'; +test('a launch plan returns the registered child identity and joins that child at teardown', async () => { + const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-planned-identity-')); + const launch = planRegisteredDaemonLaunches([ + { + kind: 'registered', + paths, + fields: { + httpPort: 4210, + token: 'fixture', + version: 'test', + codeOrigin: 'checkout', + codeSignature: 'fixture', + }, + }, + ]); + const child = launch('node', [], { stdio: 'ignore' }); + try { + const observed = await waitForRegisteredDaemonFixture(paths, child); + assert.equal(observed.pid, child.pid); + assert.notEqual(child.pid, process.pid); + } finally { + await finishRegisteredDaemonFixture(paths.baseDir); + } + assert.equal((await child.exited).pid, child.pid); + assert.equal(fs.existsSync(paths.baseDir), false); +}); + test('args built before any launch keep their own entry script under a concurrent second build', async () => { // Under a shared entry path child 1 would run child 2's switches and carry the wrong marker. const paths = resolveDaemonPaths(mkdtempForTestSync('daemon-fixture-entry-isolation-')); diff --git a/src/__tests__/test-utils/registered-daemon-fixture.ts b/src/__tests__/test-utils/registered-daemon-fixture.ts index 4d6b98f1b4..98701d1ebb 100644 --- a/src/__tests__/test-utils/registered-daemon-fixture.ts +++ b/src/__tests__/test-utils/registered-daemon-fixture.ts @@ -21,6 +21,7 @@ function readPublishedDaemonRecord(infoPath: string): PublishedDaemonRecord | nu } export const { + planRegisteredDaemonLaunches, registeredDaemonFixtureArgs, launchRegisteredDaemonFixtureArgs, spawnRegisteredDaemonFixture, diff --git a/src/__tests__/test-utils/registered-http-daemon.ts b/src/__tests__/test-utils/registered-http-daemon.ts index 7853c0c4a3..e31edcca80 100644 --- a/src/__tests__/test-utils/registered-http-daemon.ts +++ b/src/__tests__/test-utils/registered-http-daemon.ts @@ -16,6 +16,7 @@ import { import { finishRegisteredDaemonFixture, spawnRegisteredDaemonFixture, + planRegisteredDaemonLaunches, waitForRegisteredDaemonFixture, } from './registered-daemon-fixture.ts'; @@ -93,9 +94,7 @@ export async function launchesFreshHttpDaemon( await Promise.allSettled([closeLoopbackServer(stub.server)]); throw error; } - spawn.mockImplementation((_command, _args, options) => - spawnRegisteredDaemonFixture(paths, fields, options), - ); + spawn.mockImplementation(planRegisteredDaemonLaunches([{ kind: 'registered', paths, fields }])); return { stub, commands: () => stub.rpcRequests.map((rpc) => String(rpc.params?.command)), From a2dc6558ade4598585d1dd6d8dc56ac6a4ccfb60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 11 Nov 2026 12:15:49 +0000 Subject: [PATCH 2/5] chore(gates): require launch plans for daemon fixture mocks --- docs/agents/test-authoring.md | 1 - scripts/lib/daemon-fixture-launch-guard.ts | 169 ++++++++++++++++++ .../daemon-fixture-launch-guard.test.ts | 89 +++++++++ src/__tests__/daemon-client-host.test.ts | 18 +- .../daemon-fixture-launches.test.ts | 31 ++++ 5 files changed, 303 insertions(+), 5 deletions(-) create mode 100644 scripts/lib/daemon-fixture-launch-guard.ts create mode 100644 scripts/mutation/daemon-fixture-launch-guard.test.ts create mode 100644 test/repo-guards/daemon-fixture-launches.test.ts diff --git a/docs/agents/test-authoring.md b/docs/agents/test-authoring.md index fcab24a906..5c0d71175a 100644 --- a/docs/agents/test-authoring.md +++ b/docs/agents/test-authoring.md @@ -39,7 +39,6 @@ Spy on that seam in place. Use `mkdtempForTest` or `mkdtempForTestSync`. After workers exit, global setup removes the run directory. Mock the seam the subject consumes. -For daemon fixture launch mocks, use `planRegisteredDaemonLaunches`. Daemon handlers receive fake runtime facts and facets, not generic dispatch mocks. When you migrate an ADR 0019 command, move its tests to the runtime seam. diff --git a/scripts/lib/daemon-fixture-launch-guard.ts b/scripts/lib/daemon-fixture-launch-guard.ts new file mode 100644 index 0000000000..f9edf5033c --- /dev/null +++ b/scripts/lib/daemon-fixture-launch-guard.ts @@ -0,0 +1,169 @@ +import { parseSync } from 'oxc-parser'; +import path from 'node:path'; +import { + asNode, + memberName, + nodeList, + propertyName, + visitAst, + type AstNode, +} from '../layering/layering-ast.ts'; + +type FixtureSource = Readonly<{ file: string; source: string }>; + +/** Follows local fixture imports so a renamed helper or a new consumer cannot leave the guard. */ +export function scanDaemonFixtureLaunches(files: readonly FixtureSource[]): string[] { + const family = new Set(); + const imports = new Map(); + for (const { file, source } of files) { + const parsed = parseSync(file, source); + if (parsed.errors.length) + throw new Error(`Cannot scan daemon fixtures in ${file}: ${parsed.errors[0]!.message}`); + const dependencies: string[] = []; + visitAst(parsed.program, (node) => { + if ( + node.type === 'CallExpression' && + memberName(asNode(node.callee) ?? {}) === 'createRegisteredDaemonFixtures' + ) + family.add(file); + if ( + node.type !== 'ImportDeclaration' && + node.type !== 'ExportNamedDeclaration' && + node.type !== 'ExportAllDeclaration' + ) + return; + const specifier = asNode(node.source)?.value; + if (typeof specifier !== 'string') return; + if ( + nodeList(node.specifiers).some( + (entry) => propertyName(asNode(entry)?.imported) === 'createRegisteredDaemonFixtures', + ) + ) + family.add(file); + if (specifier.startsWith('.')) { + const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(file), specifier)); + dependencies.push(resolved.endsWith('.ts') ? resolved : `${resolved}.ts`); + } + }); + imports.set(file, dependencies); + } + let changed = true; + while (changed) { + changed = false; + for (const [file, dependencies] of imports) { + if (!family.has(file) && dependencies.some((dependency) => family.has(dependency))) { + family.add(file); + changed = true; + } + } + } + return files + .filter(({ file }) => family.has(file)) + .flatMap(({ file, source }) => daemonFixtureLaunchViolations(source, file)); +} + +/** Checks mocked monitored launches in a daemon-fixture family module. */ +export function daemonFixtureLaunchViolations(source: string, file: string): string[] { + const parsed = parseSync(file, source); + if (parsed.errors.length) + return [`${file}: cannot parse daemon-fixture module: ${parsed.errors[0]!.message}`]; + const launchers = new Set(); + const planners = new Set(); + const bindings = new Map(); + visitAst(parsed.program, (node) => { + if (node.type === 'ImportSpecifier') { + const imported = propertyName(node.imported); + const name = propertyName(node.local); + if (name && imported === 'runCmdDetachedMonitored') launchers.add(name); + if (name && imported === 'planRegisteredDaemonLaunches') planners.add(name); + } + if ( + node.type === 'VariableDeclarator' && + asNode(node.id)?.type === 'Identifier' && + asNode(node.init) + ) + bindings.set(String(asNode(node.id)!.name), asNode(node.init)!); + if (node.type === 'Identifier' && asNode(node.typeAnnotation)) { + const annotation = asNode(node.typeAnnotation)!; + const text = source.slice(Number(annotation.start), Number(annotation.end)); + if (text.includes('Mock<') && [...launchers].some((name) => text.includes(`typeof ${name}`))) + launchers.add(String(node.name)); + } + }); + function resolves(node: unknown, names: Set, seen = new Set()): boolean { + const value = asNode(node); + if (!value) return false; + if (value.type === 'Identifier') { + const name = String(value.name); + if (names.has(name)) return true; + if (seen.has(name)) return false; + seen.add(name); + return resolves(bindings.get(name), names, seen); + } + if (value.type === 'CallExpression' && memberName(asNode(value.callee) ?? {}) === 'mocked') + return resolves(nodeList(value.arguments)[0], names, seen); + if (value.type === 'MemberExpression' && memberName(value) === 'runCmdDetachedMonitored') + return names === launchers; + if (value.type === 'CallExpression' && memberName(asNode(value.callee) ?? {}) === 'spyOn') + return ( + names === launchers && + asNode(nodeList(value.arguments)[1])?.value === 'runCmdDetachedMonitored' + ); + return false; + } + function initializationViolation(node: AstNode): string | undefined { + if (node.type !== 'Property' || propertyName(node.key) !== 'runCmdDetachedMonitored') return; + const value = asNode(node.value); + if ( + value?.type === 'CallExpression' && + memberName(asNode(value.callee) ?? {}) === 'fn' && + nodeList(value.arguments).length === 0 + ) + return; + return 'initialize daemon launcher mocks with vi.fn() and install a shared launch plan'; + } + function detachedMethodViolation(node: AstNode): string | undefined { + if ( + node.type === 'VariableDeclarator' && + asNode(node.id)?.type === 'ObjectPattern' && + resolves(node.init, launchers) + ) { + return 'do not detach daemon launcher mock methods from their guarded receiver'; + } + } + function launchCallViolation(node: AstNode): string | undefined { + if (node.type !== 'CallExpression') return; + const callee = asNode(node.callee); + if (resolves(callee, launchers)) + return 'do not invoke a raw monitored launcher in the daemon fixture family'; + if (callee?.type !== 'MemberExpression' || !resolves(callee.object, launchers)) return; + const method = memberName(callee); + if (!method || (callee.computed === true && asNode(callee.property)?.type !== 'Literal')) { + return 'dynamic daemon launcher mock methods are not supported'; + } + if ( + !/^(mockImplementation|mockReturnValue|mockResolvedValue|mockRejectedValue)(Once)?$/.test( + method, + ) + ) + return; + const argument = asNode(nodeList(node.arguments)[0]); + if ( + method.startsWith('mockImplementation') && + argument?.type === 'CallExpression' && + resolves(argument.callee, planners) + ) + return; + return 'mocked daemon launch must use planRegisteredDaemonLaunches'; + } + const violations: string[] = []; + visitAst(parsed.program, (node) => { + const message = + initializationViolation(node) ?? detachedMethodViolation(node) ?? launchCallViolation(node); + if (message) + violations.push( + `${file}:${source.slice(0, Number(node.start)).split('\n').length}: ${message}`, + ); + }); + return violations; +} diff --git a/scripts/mutation/daemon-fixture-launch-guard.test.ts b/scripts/mutation/daemon-fixture-launch-guard.test.ts new file mode 100644 index 0000000000..74490409a0 --- /dev/null +++ b/scripts/mutation/daemon-fixture-launch-guard.test.ts @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { + daemonFixtureLaunchViolations, + scanDaemonFixtureLaunches, +} from '../lib/daemon-fixture-launch-guard.ts'; + +const imports = `import { runCmdDetachedMonitored as launch } from '@agent-device/host-kit/command'; +import { planRegisteredDaemonLaunches as plan, spawnRegisteredDaemonFixture } from './registered-daemon-fixture.ts'; +const spawn = vi.mocked(launch);`; + +for (const body of [ + `spawn.mockImplementation(() => { const child = spawnRegisteredDaemonFixture(); throw new Error('refused'); });`, + `spawn['mockImplementationOnce'](() => { const child = spawnRegisteredDaemonFixture(); return { pid: 999, exited: child.exited }; });`, + `const alias = spawn; alias.mockReturnValue({ pid: 123 });`, + `vi.mocked(launch).mockImplementation(() => spawnRegisteredDaemonFixture());`, + `vi.spyOn(command, 'runCmdDetachedMonitored').mockImplementation(() => spawnRegisteredDaemonFixture());`, + `command.runCmdDetachedMonitored('node', []);`, + `spawn[method](() => spawnRegisteredDaemonFixture());`, + `const { mockImplementation: install } = spawn; install(() => spawnRegisteredDaemonFixture());`, + `vi.mock('@agent-device/host-kit/command', () => ({ runCmdDetachedMonitored: vi.fn(() => { const child = spawnRegisteredDaemonFixture(); return { pid: 123, exited: child.exited }; }) }));`, +]) { + test(`rejects a raw daemon launcher: ${body}`, () => { + assert.equal(daemonFixtureLaunchViolations(imports + body, 'fixture.test.ts').length, 1); + }); +} + +test('accepts the shared plan, including an imported alias', () => { + assert.deepEqual( + daemonFixtureLaunchViolations( + imports + `spawn.mockImplementation(plan([{ kind: 'refuse', error: new Error('no') }]));`, + 'fixture.test.ts', + ), + [], + ); +}); + +test('namespace-created fixture families remain guarded', () => { + const violations = scanDaemonFixtureLaunches([ + { + file: 'src/support.ts', + source: `import * as testKit from '@agent-device/test-kit'; export const fixtures = testKit.createRegisteredDaemonFixtures({});`, + }, + { + file: 'src/consumer.test.ts', + source: `import { fixtures } from './support.ts'; import { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; const launch = vi.mocked(runCmdDetachedMonitored); launch.mockImplementation(() => fixtures.spawnRegisteredDaemonFixture());`, + }, + ]); + assert.equal(violations.length, 1); +}); + +test('does not restrict unrelated sleep mocks or ordinary command tests outside the family', () => { + assert.deepEqual( + daemonFixtureLaunchViolations( + imports + `pause.mockImplementation(() => {});`, + 'fixture.test.ts', + ), + [], + ); +}); + +test('a typed launcher parameter cannot bypass the plan', () => { + assert.equal( + daemonFixtureLaunchViolations( + imports + + `function install(other: Mock) { other.mockImplementation(() => spawnRegisteredDaemonFixture()); }`, + 'fixture.ts', + ).length, + 1, + ); +}); + +test('the repo scan follows renamed and re-exported fixture helpers but leaves other command tests alone', () => { + const bad = `import { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; const spawn = vi.mocked(runCmdDetachedMonitored); spawn.mockImplementation(() => { throw new Error('raw'); });`; + const violations = scanDaemonFixtureLaunches([ + { + file: 'src/support/renamed.ts', + source: `import { createRegisteredDaemonFixtures as create } from '@agent-device/test-kit'; export const fixtures = create({});`, + }, + { file: 'src/support/barrel.ts', source: `export * from './renamed.ts';` }, + { + file: 'src/consumer.test.ts', + source: `import { fixtures } from './support/barrel.ts'; ${bad}`, + }, + { file: 'src/unrelated.test.ts', source: bad }, + ]); + assert.equal(violations.length, 1); + assert.match(violations[0]!, /src\/consumer.test.ts/); +}); diff --git a/src/__tests__/daemon-client-host.test.ts b/src/__tests__/daemon-client-host.test.ts index 3ef62e0d7a..9c152c419f 100644 --- a/src/__tests__/daemon-client-host.test.ts +++ b/src/__tests__/daemon-client-host.test.ts @@ -1,5 +1,5 @@ import fs from 'node:fs'; -import { afterEach, expect, test, vi } from 'vitest'; +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; import { createTestHostEnvironment, skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; import { runCli } from '../cli.ts'; import { createAgentDeviceClient } from '@agent-device/client'; @@ -8,20 +8,30 @@ import { stateDirAndPaths, type RegisteredHttpDaemon, } from './test-utils/registered-http-daemon.ts'; +import { planRegisteredDaemonLaunches } from './test-utils/registered-daemon-fixture.ts'; // A client or a CLI run takes the host it is given. These tests run the real client and the real // default CLI against a real registered daemon on the host's state directory, while the process // names another one: a daemon resolved from the process would be started, so launching is refused. vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({ ...(await importOriginal()), - runCmdDetachedMonitored: vi.fn(() => { - throw new Error('A daemon was launched: the host state directory was not used.'); - }), + runCmdDetachedMonitored: vi.fn(), })); import { runCmdDetachedMonitored } from '@agent-device/host-kit/command'; let daemon: RegisteredHttpDaemon | undefined; +beforeEach(() => { + vi.mocked(runCmdDetachedMonitored).mockImplementation( + planRegisteredDaemonLaunches([ + { + kind: 'refuse', + error: new Error('A daemon was launched: the host state directory was not used.'), + }, + ]), + ); +}); + afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); diff --git a/test/repo-guards/daemon-fixture-launches.test.ts b/test/repo-guards/daemon-fixture-launches.test.ts new file mode 100644 index 0000000000..d419f50716 --- /dev/null +++ b/test/repo-guards/daemon-fixture-launches.test.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from 'vitest'; +import { REPO_ROOT } from '@agent-device/test-kit'; +import { scanDaemonFixtureLaunches } from '../../scripts/lib/daemon-fixture-launch-guard.ts'; + +test('daemon fixture family mocks use declared launch plans', () => { + const files = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { + cwd: REPO_ROOT, + encoding: 'utf8', + }) + .trim() + .split('\n') + .filter((file) => /^(src\/|packages\/[^/]+\/src\/).*\.ts$/.test(file)) + .map((file) => ({ file, source: fs.readFileSync(path.join(REPO_ROOT, file), 'utf8') })); + assert.deepEqual(scanDaemonFixtureLaunches(files), []); +}); + +test('daemon fixture guard rejects its adversarial cases in the PR unit lane', () => { + execFileSync( + process.execPath, + [ + '--experimental-strip-types', + '--test', + 'scripts/mutation/daemon-fixture-launch-guard.test.ts', + ], + { cwd: REPO_ROOT, stdio: 'pipe' }, + ); +}); From 1ecf501488b65412a384b7310a5cbbf8e7602f04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 12 Nov 2026 11:56:01 +0100 Subject: [PATCH 3/5] fix(test): address daemon fixture launch review findings --- .../src/registered-daemon-launch-plan.test.ts | 17 +++- .../src/registered-daemon-launch-plan.ts | 7 +- .../daemon-fixture-launch-guard.test.ts | 85 ++++++++++++++++++- scripts/lib/daemon-fixture-launch-guard.ts | 64 ++++++++++++-- src/__tests__/daemon-client-host.test.ts | 13 ++- .../test-utils/registered-daemon-fixture.ts | 1 + .../daemon-fixture-launches.test.ts | 12 --- vitest.config.ts | 1 + 8 files changed, 170 insertions(+), 30 deletions(-) rename scripts/{mutation => __tests__}/daemon-fixture-launch-guard.test.ts (56%) diff --git a/packages/test-kit/src/registered-daemon-launch-plan.test.ts b/packages/test-kit/src/registered-daemon-launch-plan.test.ts index 1a1c2e559a..ab4a511bd8 100644 --- a/packages/test-kit/src/registered-daemon-launch-plan.test.ts +++ b/packages/test-kit/src/registered-daemon-launch-plan.test.ts @@ -98,10 +98,19 @@ test('an observer cannot replace the returned child handle and its violation sur }, ]); assert.equal(launch('node', []), f.child); - await rejectsContract( - f.fixtures.finishRegisteredDaemonFixtures(), - /observer returned a replacement handle/, - ); + await assert.rejects(f.fixtures.finishRegisteredDaemonFixtures(), (error: unknown) => { + function leafErrors(value: unknown): Error[] { + return value instanceof AggregateError + ? value.errors.flatMap(leafErrors) + : value instanceof Error + ? [value] + : []; + } + const errors = leafErrors(error); + assert.equal(errors.length, 1, 'one replacement handle must produce exactly one violation'); + assert.match(errors[0]!.message, /observer returned a replacement handle/); + return true; + }); }); test('teardown fails when termination reports success but the exact child exit never joins', async () => { diff --git a/packages/test-kit/src/registered-daemon-launch-plan.ts b/packages/test-kit/src/registered-daemon-launch-plan.ts index b5f163fb3b..2437d1b7b8 100644 --- a/packages/test-kit/src/registered-daemon-launch-plan.ts +++ b/packages/test-kit/src/registered-daemon-launch-plan.ts @@ -47,7 +47,12 @@ export function createDaemonFixtureLaunchPlanner( describing = true; try { const result: unknown = step.observe?.(child); - if (result !== undefined) refuse('an observer returned a replacement handle or value'); + if (result !== undefined) + violations.push( + new Error( + 'Daemon fixture launch contract: an observer returned a replacement handle or value', + ), + ); } catch (error) { violations.push( new Error('Daemon fixture launch observer failed after starting a child', { cause: error }), diff --git a/scripts/mutation/daemon-fixture-launch-guard.test.ts b/scripts/__tests__/daemon-fixture-launch-guard.test.ts similarity index 56% rename from scripts/mutation/daemon-fixture-launch-guard.test.ts rename to scripts/__tests__/daemon-fixture-launch-guard.test.ts index 74490409a0..3e6045fdb0 100644 --- a/scripts/mutation/daemon-fixture-launch-guard.test.ts +++ b/scripts/__tests__/daemon-fixture-launch-guard.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { test } from 'node:test'; +import { test } from 'vitest'; import { daemonFixtureLaunchViolations, scanDaemonFixtureLaunches, @@ -87,3 +87,86 @@ test('the repo scan follows renamed and re-exported fixture helpers but leaves o assert.equal(violations.length, 1); assert.match(violations[0]!, /src\/consumer.test.ts/); }); + +for (const expression of [ + '(spawn as any)', + 'spawn!', + '(spawn satisfies unknown)', + '(spawn)', + 'vi.mocked(launch as any)', +]) { + test(`rejects a wrapped launcher: ${expression}`, () => { + assert.equal( + daemonFixtureLaunchViolations( + imports + `${expression}.mockImplementation(() => spawnRegisteredDaemonFixture());`, + 'fixture.test.ts', + ).length, + 1, + ); + }); +} + +for (const annotation of ['MockedFunction', 'MockInstance']) { + test(`rejects a launcher parameter typed as ${annotation}`, () => { + assert.equal( + daemonFixtureLaunchViolations( + imports + + `function install(other: ${annotation}) { other.mockImplementation(() => spawnRegisteredDaemonFixture()); }`, + 'fixture.ts', + ).length, + 1, + ); + }); +} + +for (const binding of ['runCmdDetachedMonitored', 'runCmdDetachedMonitored: detached']) { + test(`rejects a launcher destructured from a namespace: ${binding}`, () => { + const local = binding.includes(':') ? 'detached' : 'runCmdDetachedMonitored'; + const violations = daemonFixtureLaunchViolations( + `import * as command from '@agent-device/host-kit/command'; const { ${binding} } = command; ${local}.mockImplementation(() => ({}));`, + 'fixture.ts', + ); + assert.equal(violations.length, 1); + assert.match(violations[0]!, /mocked daemon launch must use/); + }); +} + +test('accepts a shared launch plan held in a local binding', () => { + assert.deepEqual( + daemonFixtureLaunchViolations( + imports + + `const next = plan([{kind: 'refuse', error: new Error('no')}]); const alias = next; spawn.mockImplementation(alias);`, + 'fixture.ts', + ), + [], + ); +}); + +for (const specifier of ['./support', './support/index.js', './support/renamed.js']) { + test(`follows a fixture family through ${specifier}`, () => { + const violations = scanDaemonFixtureLaunches([ + { + file: 'src/support/renamed.ts', + source: `import {createRegisteredDaemonFixtures} from '@agent-device/test-kit'; export const fixtures = createRegisteredDaemonFixtures({});`, + }, + { file: 'src/support/index.ts', source: `export * from './renamed.js';` }, + { + file: 'src/consumer.test.ts', + source: `import {fixtures} from '${specifier}'; import {runCmdDetachedMonitored} from '@agent-device/host-kit/command'; vi.mocked(runCmdDetachedMonitored).mockImplementation(() => fixtures.spawnRegisteredDaemonFixture());`, + }, + ]); + assert.equal(violations.length, 1); + assert.match(violations[0]!, /src\/consumer.test.ts/); + }); +} + +test('accepts a namespace-destructured launcher using the shared plan', () => { + assert.deepEqual( + daemonFixtureLaunchViolations( + imports + + `import * as command from '@agent-device/host-kit/command'; const { runCmdDetachedMonitored: detached } = command; vi.mocked(detached).mockImplementation(plan([]));`, + 'fixture.ts', + ), + [], + ); +}); diff --git a/scripts/lib/daemon-fixture-launch-guard.ts b/scripts/lib/daemon-fixture-launch-guard.ts index f9edf5033c..e9b776426e 100644 --- a/scripts/lib/daemon-fixture-launch-guard.ts +++ b/scripts/lib/daemon-fixture-launch-guard.ts @@ -15,6 +15,7 @@ type FixtureSource = Readonly<{ file: string; source: string }>; export function scanDaemonFixtureLaunches(files: readonly FixtureSource[]): string[] { const family = new Set(); const imports = new Map(); + const paths = new Set(files.map(({ file }) => file)); for (const { file, source } of files) { const parsed = parseSync(file, source); if (parsed.errors.length) @@ -42,7 +43,13 @@ export function scanDaemonFixtureLaunches(files: readonly FixtureSource[]): stri family.add(file); if (specifier.startsWith('.')) { const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(file), specifier)); - dependencies.push(resolved.endsWith('.ts') ? resolved : `${resolved}.ts`); + const dependency = [ + resolved, + resolved.replace(/\.js$/, '.ts'), + `${resolved}.ts`, + `${resolved}/index.ts`, + ].find((candidate) => paths.has(candidate)); + if (dependency) dependencies.push(dependency); } }); imports.set(file, dependencies); @@ -70,6 +77,7 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str const launchers = new Set(); const planners = new Set(); const bindings = new Map(); + const destructuredProperties = new Set(); visitAst(parsed.program, (node) => { if (node.type === 'ImportSpecifier') { const imported = propertyName(node.imported); @@ -83,15 +91,29 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str asNode(node.init) ) bindings.set(String(asNode(node.id)!.name), asNode(node.init)!); + if (node.type === 'ObjectPattern') { + for (const property of nodeList(node.properties)) { + const entry = asNode(property); + if (!entry) continue; + destructuredProperties.add(entry); + if (propertyName(entry.key) === 'runCmdDetachedMonitored') { + const name = propertyName(entry.value); + if (name) launchers.add(name); + } + } + } if (node.type === 'Identifier' && asNode(node.typeAnnotation)) { const annotation = asNode(node.typeAnnotation)!; const text = source.slice(Number(annotation.start), Number(annotation.end)); - if (text.includes('Mock<') && [...launchers].some((name) => text.includes(`typeof ${name}`))) + if ( + /\bMock\w*\s* text.includes(`typeof ${name}`)) + ) launchers.add(String(node.name)); } }); function resolves(node: unknown, names: Set, seen = new Set()): boolean { - const value = asNode(node); + const value = unwrap(node); if (!value) return false; if (value.type === 'Identifier') { const name = String(value.name); @@ -111,7 +133,19 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str ); return false; } + function isLaunchPlan(node: unknown, seen = new Set()): boolean { + const value = unwrap(node); + if (!value) return false; + if (value.type === 'Identifier') { + const name = String(value.name); + if (seen.has(name)) return false; + seen.add(name); + return isLaunchPlan(bindings.get(name), seen); + } + return value.type === 'CallExpression' && resolves(value.callee, planners); + } function initializationViolation(node: AstNode): string | undefined { + if (destructuredProperties.has(node)) return; if (node.type !== 'Property' || propertyName(node.key) !== 'runCmdDetachedMonitored') return; const value = asNode(node.value); if ( @@ -147,12 +181,7 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str ) ) return; - const argument = asNode(nodeList(node.arguments)[0]); - if ( - method.startsWith('mockImplementation') && - argument?.type === 'CallExpression' && - resolves(argument.callee, planners) - ) + if (method.startsWith('mockImplementation') && isLaunchPlan(nodeList(node.arguments)[0])) return; return 'mocked daemon launch must use planRegisteredDaemonLaunches'; } @@ -167,3 +196,20 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str }); return violations; } + +function unwrap(node: unknown): AstNode | undefined { + let value = asNode(node); + while ( + value && + [ + 'ParenthesizedExpression', + 'TSAsExpression', + 'TSSatisfiesExpression', + 'TSNonNullExpression', + 'TSTypeAssertion', + ].includes(String(value.type)) + ) { + value = asNode(value.expression); + } + return value; +} diff --git a/src/__tests__/daemon-client-host.test.ts b/src/__tests__/daemon-client-host.test.ts index 9c152c419f..96518e624b 100644 --- a/src/__tests__/daemon-client-host.test.ts +++ b/src/__tests__/daemon-client-host.test.ts @@ -8,7 +8,10 @@ import { stateDirAndPaths, type RegisteredHttpDaemon, } from './test-utils/registered-http-daemon.ts'; -import { planRegisteredDaemonLaunches } from './test-utils/registered-daemon-fixture.ts'; +import { + planRegisteredDaemonLaunches, + finishRegisteredDaemonFixtures, +} from './test-utils/registered-daemon-fixture.ts'; // A client or a CLI run takes the host it is given. These tests run the real client and the real // default CLI against a real registered daemon on the host's state directory, while the process @@ -36,8 +39,12 @@ afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.mocked(runCmdDetachedMonitored).mockClear(); - await daemon?.close(); - daemon = undefined; + try { + await daemon?.close(); + } finally { + daemon = undefined; + await finishRegisteredDaemonFixtures(); + } }); async function bootHostAndProcess() { diff --git a/src/__tests__/test-utils/registered-daemon-fixture.ts b/src/__tests__/test-utils/registered-daemon-fixture.ts index 98701d1ebb..51019689b4 100644 --- a/src/__tests__/test-utils/registered-daemon-fixture.ts +++ b/src/__tests__/test-utils/registered-daemon-fixture.ts @@ -28,6 +28,7 @@ export const { waitForFixtureFile, waitForRegisteredDaemonFixture, finishRegisteredDaemonFixture, + finishRegisteredDaemonFixtures, } = createRegisteredDaemonFixtures({ registrationOwnerUrl: import.meta .resolve('@agent-device/daemon-contracts/daemon-registration-owner'), diff --git a/test/repo-guards/daemon-fixture-launches.test.ts b/test/repo-guards/daemon-fixture-launches.test.ts index d419f50716..84ff915cef 100644 --- a/test/repo-guards/daemon-fixture-launches.test.ts +++ b/test/repo-guards/daemon-fixture-launches.test.ts @@ -17,15 +17,3 @@ test('daemon fixture family mocks use declared launch plans', () => { .map((file) => ({ file, source: fs.readFileSync(path.join(REPO_ROOT, file), 'utf8') })); assert.deepEqual(scanDaemonFixtureLaunches(files), []); }); - -test('daemon fixture guard rejects its adversarial cases in the PR unit lane', () => { - execFileSync( - process.execPath, - [ - '--experimental-strip-types', - '--test', - 'scripts/mutation/daemon-fixture-launch-guard.test.ts', - ], - { cwd: REPO_ROOT, stdio: 'pipe' }, - ); -}); diff --git a/vitest.config.ts b/vitest.config.ts index 4a1fda648c..2c3a895974 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -161,6 +161,7 @@ export default defineConfig({ 'scripts/__tests__/help-conformance-topic-coverage.test.ts', 'scripts/__tests__/eager-closure-budgets.test.ts', 'scripts/__tests__/committed-source-tree.test.ts', + 'scripts/__tests__/daemon-fixture-launch-guard.test.ts', 'scripts/__tests__/mutation-scope-budget.test.ts', 'scripts/__tests__/closure-growth-rule.test.ts', 'scripts/__tests__/agent-setup-startup-contract.test.ts', From c4ba09dc41589e916a0c18f9fabdece9300745a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 12 Nov 2026 12:00:55 +0100 Subject: [PATCH 4/5] refactor(test): flatten fixture binding classification --- scripts/lib/daemon-fixture-launch-guard.ts | 57 ++++++++++++---------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/scripts/lib/daemon-fixture-launch-guard.ts b/scripts/lib/daemon-fixture-launch-guard.ts index e9b776426e..bdbcbc93f6 100644 --- a/scripts/lib/daemon-fixture-launch-guard.ts +++ b/scripts/lib/daemon-fixture-launch-guard.ts @@ -79,38 +79,41 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str const bindings = new Map(); const destructuredProperties = new Set(); visitAst(parsed.program, (node) => { - if (node.type === 'ImportSpecifier') { - const imported = propertyName(node.imported); - const name = propertyName(node.local); - if (name && imported === 'runCmdDetachedMonitored') launchers.add(name); - if (name && imported === 'planRegisteredDaemonLaunches') planners.add(name); - } - if ( - node.type === 'VariableDeclarator' && - asNode(node.id)?.type === 'Identifier' && - asNode(node.init) - ) - bindings.set(String(asNode(node.id)!.name), asNode(node.init)!); - if (node.type === 'ObjectPattern') { - for (const property of nodeList(node.properties)) { - const entry = asNode(property); - if (!entry) continue; - destructuredProperties.add(entry); - if (propertyName(entry.key) === 'runCmdDetachedMonitored') { + switch (node.type) { + case 'ImportSpecifier': { + const imported = propertyName(node.imported); + const name = propertyName(node.local); + if (name && imported === 'runCmdDetachedMonitored') launchers.add(name); + if (name && imported === 'planRegisteredDaemonLaunches') planners.add(name); + return; + } + case 'VariableDeclarator': { + const name = propertyName(node.id); + const value = asNode(node.init); + if (name && value) bindings.set(name, value); + return; + } + case 'ObjectPattern': + for (const property of nodeList(node.properties)) { + const entry = asNode(property); + if (!entry) continue; + destructuredProperties.add(entry); + if (propertyName(entry.key) !== 'runCmdDetachedMonitored') continue; const name = propertyName(entry.value); if (name) launchers.add(name); } + return; + case 'Identifier': { + const annotation = asNode(node.typeAnnotation); + if (!annotation) return; + const text = source.slice(Number(annotation.start), Number(annotation.end)); + if ( + /\bMock\w*\s* text.includes(`typeof ${name}`)) + ) + launchers.add(String(node.name)); } } - if (node.type === 'Identifier' && asNode(node.typeAnnotation)) { - const annotation = asNode(node.typeAnnotation)!; - const text = source.slice(Number(annotation.start), Number(annotation.end)); - if ( - /\bMock\w*\s* text.includes(`typeof ${name}`)) - ) - launchers.add(String(node.name)); - } }); function resolves(node: unknown, names: Set, seen = new Set()): boolean { const value = unwrap(node); From 18fad61f628ce7744b672b880d94a8da5d3d6002 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 12 Nov 2026 12:03:36 +0100 Subject: [PATCH 5/5] refactor(test): isolate destructured launcher binding rules --- scripts/lib/daemon-fixture-launch-guard.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/scripts/lib/daemon-fixture-launch-guard.ts b/scripts/lib/daemon-fixture-launch-guard.ts index bdbcbc93f6..13662524d4 100644 --- a/scripts/lib/daemon-fixture-launch-guard.ts +++ b/scripts/lib/daemon-fixture-launch-guard.ts @@ -94,14 +94,7 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str return; } case 'ObjectPattern': - for (const property of nodeList(node.properties)) { - const entry = asNode(property); - if (!entry) continue; - destructuredProperties.add(entry); - if (propertyName(entry.key) !== 'runCmdDetachedMonitored') continue; - const name = propertyName(entry.value); - if (name) launchers.add(name); - } + recordDestructuredLaunchers(node); return; case 'Identifier': { const annotation = asNode(node.typeAnnotation); @@ -115,6 +108,16 @@ export function daemonFixtureLaunchViolations(source: string, file: string): str } } }); + function recordDestructuredLaunchers(node: AstNode): void { + for (const property of nodeList(node.properties)) { + const entry = asNode(property); + if (!entry) continue; + destructuredProperties.add(entry); + if (propertyName(entry.key) !== 'runCmdDetachedMonitored') continue; + const name = propertyName(entry.value); + if (name) launchers.add(name); + } + } function resolves(node: unknown, names: Set, seen = new Set()): boolean { const value = unwrap(node); if (!value) return false;