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 d2ad20bbf3..13786ca48a 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts @@ -382,10 +382,16 @@ test('daemon acquisition reclaims a proven reused owner before publication', asy const paths = resolveDaemonPaths(stateDir); const daemon = await startHttpDaemonFixture({ via: 'fresh-daemon' }); vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir); - const staleStartTime = - process.platform === 'linux' - ? 'linux:00000000-0000-0000-0000-000000000000:0' - : 'stale-start-time'; + // A proven reuse needs a stale value in the same verified format as the live read of this pid; + // a legacy-format token would be unverified, not proof. + const liveStartTime = readProcessStartTime(process.pid); + const staleStartTime = liveStartTime?.startsWith('linux:') + ? 'linux:00000000-0000-0000-0000-000000000000:0' + : liveStartTime?.startsWith('posix:') + ? 'posix:1' + : liveStartTime !== null && /^\d{21}$/.test(liveStartTime) + ? '00000000000000000000' + : 'posix:1'; const stale = tryAcquireProcessLock({ lockDirPath: paths.lockPath, owner: { pid: process.pid, startTime: staleStartTime, acquiredAtMs: Date.now() }, diff --git a/packages/daemon-contracts/src/daemon-process-takeover.test.ts b/packages/daemon-contracts/src/daemon-process-takeover.test.ts index bc7a33e55a..fbdd21af2f 100644 --- a/packages/daemon-contracts/src/daemon-process-takeover.test.ts +++ b/packages/daemon-contracts/src/daemon-process-takeover.test.ts @@ -5,7 +5,11 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, test } from 'vitest'; -import { isProcessAlive, readProcessStartTime } from '@agent-device/host-kit/process'; +import { + isProcessAlive, + readProcessCommand, + readProcessStartTime, +} from '@agent-device/host-kit/process'; import { isAgentDeviceDaemonProcess, stopDaemonProcess } from './daemon-process.ts'; const TAKEOVER_TIMEOUTS = { termTimeoutMs: 5_000, killTimeoutMs: 2_000 }; @@ -35,13 +39,13 @@ afterEach(async () => { } }); -/** A daemon entry from a branch-named checkout, whose path has no project-name marker. */ -function spawnFakeDaemonFromBranchNamedCheckout(): { pid: number; entryPath: string } { +/** A daemon entry from a checkout under `prefix`, whose path has no project-name marker. */ +function spawnFakeDaemon(prefix: string): { pid: number; entryPath: string } { // Vitest redirects `os.tmpdir()` under a worktree-named run directory. Use // the host temp root so this path itself cannot accidentally contain the // project name and mask the worktree identity regression. const tempRoot = process.platform === 'win32' ? os.tmpdir() : '/tmp'; - const root = fs.realpathSync.native(fs.mkdtempSync(path.join(tempRoot, 'repair-evidence-'))); + const root = fs.realpathSync.native(fs.mkdtempSync(path.join(tempRoot, prefix))); spawnedRoots.push(root); const entryPath = path.join(root, 'dist', 'src', 'internal', 'daemon.js'); fs.mkdirSync(path.dirname(entryPath), { recursive: true }); @@ -56,6 +60,19 @@ function spawnFakeDaemonFromBranchNamedCheckout(): { pid: number; entryPath: str return { pid, entryPath }; } +/** A daemon entry from a branch-named checkout, whose path has no project-name marker. */ +function spawnFakeDaemonFromBranchNamedCheckout(): { pid: number; entryPath: string } { + return spawnFakeDaemon('repair-evidence-'); +} + +/** A start time in the same provenanced format as `live` but naming a different lifetime. */ +function staleStartTimeLike(live: string): string { + if (live.startsWith('linux:')) return 'linux:00000000-0000-4000-8000-000000000000:999999999'; + if (live.startsWith('posix:')) return 'posix:1'; + if (/^\d{21}$/.test(live)) return '00000000000000000000'; + return 'posix:1'; +} + // #1545: a reachable daemon with a code-signature mismatch is replaced. If a // branch-named worktree is rejected as "not ours", replacement leaves the old // daemon alive and the next request reaches a fresh empty session store. @@ -96,7 +113,9 @@ test('does not stop a branch-named daemon when the pid belongs to a different pr const actualStartTime = readProcessStartTime(pid); assert.ok(actualStartTime, 'expected the spawned daemon to report a start time'); - const staleStartTime = `${actualStartTime}-previous-lifetime`; + // A proven reuse needs a stale value in the same verified format as the live read; a legacy + // token would be unverified rather than proof. + const staleStartTime = staleStartTimeLike(actualStartTime); assert.equal(isAgentDeviceDaemonProcess(pid, staleStartTime), false); const result = await stopDaemonProcess( @@ -110,3 +129,60 @@ test('does not stop a branch-named daemon when the pid belongs to a different pr }); assert.equal(isProcessAlive(pid), true); }); + +// #4656: a record written before the provenance pin holds a raw `lstart` rendering — fr_FR prints +// `mar. 17 nov. 19:42:27 2026`, locales that omit HH:mm:ss print no clock, and an earlier pinned +// build stored the raw C form. All are unqualified, so at the daemon stop boundary they yield +// unverified identity — never `already-exited`, and never a signal — so a live daemon is not +// retired while it still runs. +test.skipIf(process.platform !== 'darwin')( + 'a legacy raw record yields unverified identity at daemon stop, not an exited daemon', + async () => { + const { pid } = spawnFakeDaemonFromBranchNamedCheckout(); + const startTime = readProcessStartTime(pid); + assert.ok(startTime, 'expected the spawned daemon to report a start time'); + assert.ok(startTime.startsWith('posix:'), `expected a posix birth token, got ${startTime}`); + + for (const legacy of [ + 'mar. 17 nov. 19:42:27 2026', + '17 nov. 2026', + 'Tue Nov 17 19:42:27 2026', + ]) { + const result = await stopDaemonProcess( + { pid, startTime: legacy }, + { mode: 'graceful', termTimeoutMs: 200, killTimeoutMs: 100 }, + ); + assert.equal(result.status, 'retained', `legacy record ${legacy} must not retire the daemon`); + if (result.status === 'retained') { + assert.equal(result.reason, 'identity-unverified'); + } + assert.equal( + isProcessAlive(pid), + true, + 'no signal may reach a daemon the legacy record cannot verify', + ); + } + }, +); + +test.skipIf(process.platform === 'win32')( + 'the stop route reads a non-ASCII daemon argv as UTF-8, not as C-locale escapes', + async () => { + const { pid, entryPath } = spawnFakeDaemon('utf8-é-ü-'); + assert.ok(entryPath.includes('é-ü')); + + const command = readProcessCommand(pid); + assert.ok(command?.includes('é-ü'), `expected the UTF-8 argv, got ${JSON.stringify(command)}`); + const startTime = readProcessStartTime(pid); + assert.ok(startTime, 'expected the spawned daemon to report a start time'); + assert.equal(isAgentDeviceDaemonProcess(pid, startTime), true); + + const result = await stopDaemonProcess( + { pid, startTime }, + { mode: 'graceful', ...TAKEOVER_TIMEOUTS }, + ); + assert.equal(result.status, 'exited'); + await spawnedChildren.at(-1)!.exited; + assert.equal(isProcessAlive(pid), false); + }, +); diff --git a/packages/daemon-contracts/src/daemon-process.ts b/packages/daemon-contracts/src/daemon-process.ts index ab14469089..401f376b83 100644 --- a/packages/daemon-contracts/src/daemon-process.ts +++ b/packages/daemon-contracts/src/daemon-process.ts @@ -1,5 +1,6 @@ import { isProcessAlive, + isProvenancedBirthToken, processStartTimesDiffer, isProcessPid, readHostProcessIdentityObservations, @@ -33,6 +34,9 @@ export function isAgentDeviceDaemonProcess( expectedStartTime: string | undefined, ): boolean { if (!expectedStartTime) return false; + // A raw historical rendering (pre-canonicalization lstart) has no comparable provenance, so it + // can neither be confirmed against a canonical read nor authorize a signal on its own. + if (!isProvenancedBirthToken(expectedStartTime)) return false; if (!isProcessAlive(pid)) return false; const actualStartTime = readProcessStartTime(pid); if (!actualStartTime || actualStartTime !== expectedStartTime) return false; diff --git a/packages/daemon-contracts/src/daemon-registration-status.test.ts b/packages/daemon-contracts/src/daemon-registration-status.test.ts index 41b4fdf9e5..897a6be76d 100644 --- a/packages/daemon-contracts/src/daemon-registration-status.test.ts +++ b/packages/daemon-contracts/src/daemon-registration-status.test.ts @@ -119,7 +119,9 @@ test('a record whose process is gone or was replaced is not a running daemon', ( processStartTime: process.platform === 'linux' ? 'linux:00000000-0000-0000-0000-000000000000:0' - : 'Thu Jan 1 00:00:00 1970', + : process.platform === 'win32' + ? '00000000000000000000' + : 'posix:1', plugins: [ACTIVE], }); expect(readDaemonStatus(resolveDaemonPaths(stateDir)).state).toBe('stopped'); diff --git a/packages/daemon-contracts/src/daemon-registration.test.ts b/packages/daemon-contracts/src/daemon-registration.test.ts index f4ba3894d0..649e6b05db 100644 --- a/packages/daemon-contracts/src/daemon-registration.test.ts +++ b/packages/daemon-contracts/src/daemon-registration.test.ts @@ -55,14 +55,32 @@ test('a different published pid proves the owner no longer serves its state dir' assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4141, startTime: 'owner-start' }), true); }); -test('a published start time proves supersession only when both sides are readable', () => { +test('a published start time proves supersession only when both sides are provenanced', () => { const stateDir = useStateDir(); - publishDaemonRegistration(stateDir, { pid: 4242, startTime: 'successor-start' }); - assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'owner-start' }), true); + // Two `posix:` tokens with different values are the same provenanced format, so the difference + // proves the pid changed hands. + publishDaemonRegistration(stateDir, { pid: 4242, startTime: 'posix:1763493001000' }); + assert.equal( + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'posix:1763493000000' }), + true, + ); + // Raw historical renderings — a localized one, and even the C form — are unqualified, so they + // are unverified, never a proved supersession. + assert.equal( + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'mar. 17 nov. 19:42:28 2026' }), + false, + ); + assert.equal( + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'Tue Nov 17 19:42:27 2026' }), + false, + ); // An unreadable start time on either side leaves the identity unproven. assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: null }), false); publishDaemonRegistration(stateDir, { pid: 4242, startTime: null }); - assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'owner-start' }), false); + assert.equal( + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'posix:1763493000000' }), + false, + ); }); test('the published owner itself is never superseded, and absence is not proof', () => { diff --git a/packages/daemon-contracts/src/device-claim-settlement.test.ts b/packages/daemon-contracts/src/device-claim-settlement.test.ts index 4db353567b..3e4a16dd47 100644 --- a/packages/daemon-contracts/src/device-claim-settlement.test.ts +++ b/packages/daemon-contracts/src/device-claim-settlement.test.ts @@ -246,7 +246,7 @@ test('a renewal through a migrated record’s own token writes back the shape th workspace: '/worktrees/legacy', stateDir: root, ownerPid: process.pid, - ownerStartTime: 'test-process-start-time', + ownerStartTime: 'Tue Nov 17 19:42:27 2026', ownerToken: 'legacy-token', createdAtMs: 1, updatedAtMs: 1, @@ -258,7 +258,7 @@ test('a renewal through a migrated record’s own token writes back the shape th deviceKey: canonicalLocalDeviceKey(device), ownerToken: 'legacy-token', ownerPid: process.pid, - ownerStartTime: 'test-process-start-time', + ownerStartTime: 'Tue Nov 17 19:42:27 2026', }, process.env, ); @@ -380,7 +380,10 @@ test('PID reuse is uncertain ownership and never authorizes reconciliation', asy stateDir: root, }); const stored = JSON.parse(fs.readFileSync(claimPath(root), 'utf8')) as Record; - fs.writeFileSync(claimPath(root), JSON.stringify({ ...stored, ownerStartTime: 'other-start' })); + fs.writeFileSync( + claimPath(root), + JSON.stringify({ ...stored, ownerStartTime: 'posix:1763493001000' }), + ); const reconcile = vi.fn(async () => ({ status: 'reconciled' as const })); const result = await acquireDeviceClaim({ diff --git a/packages/daemon/src/resources/device/__tests__/device-claims.test.ts b/packages/daemon/src/resources/device/__tests__/device-claims.test.ts index a3e5451874..781e94b29b 100644 --- a/packages/daemon/src/resources/device/__tests__/device-claims.test.ts +++ b/packages/daemon/src/resources/device/__tests__/device-claims.test.ts @@ -681,8 +681,12 @@ test('release names the exact refusal for uncertain owners and misnamed claim fi }); assert.equal(acquired.status, 'acquired'); const stored = JSON.parse(fs.readFileSync(claimPath(root), 'utf8')) as Record; - // Same PID, different recorded start time: PID reuse, uncertain ownership. - fs.writeFileSync(claimPath(root), JSON.stringify({ ...stored, ownerStartTime: 'other-start' })); + // Same PID, different recorded start time in the same provenanced format: PID reuse, + // uncertain ownership. A raw legacy rendering would be unverified, not reuse. + fs.writeFileSync( + claimPath(root), + JSON.stringify({ ...stored, ownerStartTime: 'posix:1763493001000' }), + ); // A dead-owner claim stored under a name that is not the hash of its own // device key: the claim lock protects a different path, so release refuses. fs.writeFileSync( diff --git a/packages/daemon/src/server/http/daemon-metadata-loss.test.ts b/packages/daemon/src/server/http/daemon-metadata-loss.test.ts index 2075ae8dde..3c7556fe7b 100644 --- a/packages/daemon/src/server/http/daemon-metadata-loss.test.ts +++ b/packages/daemon/src/server/http/daemon-metadata-loss.test.ts @@ -11,7 +11,8 @@ import { const OWN_PID = process.pid; const FOREIGN_PID = 999_999_999; -const OWN = { pid: OWN_PID, startTime: 'own-start' } as const; +// A provenanced POSIX birth token: the verified format, so a different token proves a recycle. +const OWN = { pid: OWN_PID, startTime: 'posix:1763493000000' } as const; function scratch(): { stateDir: string; infoPath: string } { const stateDir = mkdtempForTestSync('agent-device-daemon-metadata-loss-'); @@ -25,7 +26,7 @@ function publish(stateDir: string, pid: number, startTime: string | null): void describe('readDaemonMetadataLoss', () => { test('a registration naming this daemon is not a loss', () => { const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'own-start'); + publish(stateDir, OWN_PID, OWN.startTime); assert.equal(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), undefined); }); @@ -42,7 +43,7 @@ describe('readDaemonMetadataLoss', () => { test('a record recycling this pid under a different start time is a loss', () => { const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'recycled-start'); + publish(stateDir, OWN_PID, 'posix:1763493001000'); assert.deepEqual(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), { state: 'replaced', @@ -52,7 +53,7 @@ describe('readDaemonMetadataLoss', () => { test('a registration deleted while the state dir stands is an absent loss', () => { const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'own-start'); + publish(stateDir, OWN_PID, OWN.startTime); fs.rmSync(infoPath); assert.deepEqual(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), { @@ -63,7 +64,7 @@ describe('readDaemonMetadataLoss', () => { test('a state dir that was pruned away entirely is not a loss this daemon should report', () => { // Reporting one would write a `daemon.log` back into the directory the operator just removed. const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'own-start'); + publish(stateDir, OWN_PID, OWN.startTime); fs.rmSync(stateDir, { recursive: true, force: true }); assert.equal(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), undefined); @@ -74,7 +75,7 @@ describe('readDaemonMetadataLoss', () => { () => { // A root-owned CI host reads mode 000 anyway, so the case only binds as a non-root process. const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'own-start'); + publish(stateDir, OWN_PID, OWN.startTime); fs.chmodSync(infoPath, 0o000); try { assert.equal(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), undefined); @@ -94,6 +95,15 @@ describe('readDaemonMetadataLoss', () => { assert.equal(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), undefined); }); + test('a legacy raw record under this pid is unverified, not a reported loss', () => { + // A record written before the provenance pin holds a raw `lstart` rendering, which cannot + // prove a different lifetime, so the daemon does not announce a takeover on it. + const { stateDir, infoPath } = scratch(); + publish(stateDir, OWN_PID, 'Tue Nov 17 19:42:27 2026'); + + assert.equal(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), undefined); + }); + test('a corrupt record is not evidence that the registration was taken', () => { const { stateDir, infoPath } = scratch(); fs.writeFileSync(infoPath, '{not json'); @@ -123,7 +133,7 @@ describe('watchDaemonMetadataLoss', () => { vi.useFakeTimers(); try { const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'own-start'); + publish(stateDir, OWN_PID, OWN.startTime); const watch = startWatch(stateDir, infoPath); try { watch.advance(); @@ -145,7 +155,7 @@ describe('watchDaemonMetadataLoss', () => { vi.useFakeTimers(); try { const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'own-start'); + publish(stateDir, OWN_PID, OWN.startTime); const watch = startWatch(stateDir, infoPath); fs.rmSync(stateDir, { recursive: true, force: true }); @@ -167,7 +177,7 @@ describe('watchDaemonMetadataLoss', () => { vi.useFakeTimers(); try { const { stateDir, infoPath } = scratch(); - publish(stateDir, OWN_PID, 'own-start'); + publish(stateDir, OWN_PID, OWN.startTime); const watch = startWatch(stateDir, infoPath); watch.cancel(); watch.cancel(); diff --git a/packages/host-kit/src/internal/exec.test.ts b/packages/host-kit/src/internal/exec.test.ts index 6009a3f6a9..c0fe93a7d4 100644 --- a/packages/host-kit/src/internal/exec.test.ts +++ b/packages/host-kit/src/internal/exec.test.ts @@ -319,6 +319,31 @@ test('a request command env reaches spawned commands; outside it they inherit th assert.equal(hostOnly.stdout, '/daemon/Developer'); }); +const PRINT_TZ_AND_LOCALE = [ + '-e', + 'process.stdout.write(`${process.env.TZ ?? ""}|${process.env.LC_ALL ?? ""}`)', +]; + +test('envOverrides are the final word over the bound host environment, keeping TZ under a locale pin', async () => { + // Overrides merge over the effective child env instead of replacing it, so an `LC_ALL=C` pin + // alone still lets `TZ` through; the lstart probe itself pins `TZ=UTC` on top (host-process). + const host = hostWith({ TZ: 'Pacific/Kiritimati' }); + const [pinned, requestEnvOverridden] = await Promise.all([ + withCommandHost({ host, requestEnv: undefined }, async () => + runCmd(process.execPath, PRINT_TZ_AND_LOCALE, { envOverrides: { LC_ALL: 'C' } }), + ), + withCommandHost({ host, requestEnv: { LC_ALL: 'fr_FR.UTF-8' } }, async () => + runCmd(process.execPath, PRINT_TZ_AND_LOCALE, { envOverrides: { LC_ALL: 'C' } }), + ), + ]); + assert.equal(pinned.stdout, 'Pacific/Kiritimati|C'); + assert.equal( + requestEnvOverridden.stdout, + 'Pacific/Kiritimati|C', + 'the override is the final word, ahead of the request env too', + ); +}); + test.runIf(process.platform !== 'win32')( 'xcrun tool-not-found failures name the developer dir and how to change it', async () => { diff --git a/packages/host-kit/src/internal/exec.ts b/packages/host-kit/src/internal/exec.ts index e9611933a6..9c00f531e2 100644 --- a/packages/host-kit/src/internal/exec.ts +++ b/packages/host-kit/src/internal/exec.ts @@ -21,6 +21,12 @@ export type ExecResult = { export type ExecOptions = { cwd?: string; env?: NodeJS.ProcessEnv; + /** + * Applied as the final word over the resolved spawn environment, so one child variable can be + * pinned without dropping the rest of the effective environment — `TZ` picks the zone a + * `ps -o lstart` read renders in, so replacing the whole `env` would move the identity clock. + */ + envOverrides?: NodeJS.ProcessEnv; allowFailure?: boolean; binaryStdout?: boolean; stdin?: string | Buffer; @@ -154,10 +160,18 @@ export function commandDeveloperDir(): string | undefined { return scope?.host.env.DEVELOPER_DIR || undefined; } -function resolveSpawnEnv(env: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv | undefined { +function resolveSpawnEnv( + env: NodeJS.ProcessEnv | undefined, + overrides: NodeJS.ProcessEnv | undefined, +): NodeJS.ProcessEnv | undefined { const scope = commandHostScope.getStore(); - if (!scope) return env; - return { ...(env ?? scope.host.env), ...scope.requestEnv }; + if (!scope) { + // Outside a host scope there is no captured environment to merge into: an explicit `env` is + // still honored with the overrides on top, and with neither the child inherits natively. + if (env === undefined) return overrides; + return { ...env, ...overrides }; + } + return { ...(env ?? scope.host.env), ...scope.requestEnv, ...overrides }; } export async function runCmd( @@ -214,7 +228,7 @@ function runSpawnedCommand( return new Promise((resolve, reject) => { const child = spawn(executable, args, { cwd: options.cwd, - env: resolveSpawnEnv(options.env), + env: resolveSpawnEnv(options.env, options.envOverrides), stdio: ['pipe', 'pipe', 'pipe'], detached: options.detached, windowsHide: true, @@ -411,7 +425,7 @@ export function runCmdSync( const executable = normalizeExecutableCommand(cmd); const result = spawnSync(executable, args, { cwd: options.cwd, - env: resolveSpawnEnv(options.env), + env: resolveSpawnEnv(options.env, options.envOverrides), stdio: ['pipe', 'pipe', 'pipe'], encoding: options.binaryStdout ? undefined : 'utf8', input: options.stdin, @@ -478,7 +492,7 @@ export function runCmdDetachedMonitored( const executable = normalizeExecutableCommand(cmd); const child = spawn(executable, args, { cwd: options.cwd, - env: resolveSpawnEnv(options.env), + env: resolveSpawnEnv(options.env, options.envOverrides), stdio: options.stdio ?? 'ignore', detached: true, windowsHide: true, @@ -510,7 +524,7 @@ export function runCmdBackground( const execTrace = createExecTraceContext(cmd, undefined, commandHostScope.getStore()?.host.env); const child = spawn(executable, args, { cwd: options.cwd, - env: resolveSpawnEnv(options.env), + env: resolveSpawnEnv(options.env, options.envOverrides), stdio: options.stdio ?? ['ignore', 'pipe', 'pipe'], detached: options.detached, windowsHide: true, diff --git a/packages/host-kit/src/internal/host-process-liveness.test.ts b/packages/host-kit/src/internal/host-process-liveness.test.ts index b36030f441..cd6e3306bf 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -14,11 +14,14 @@ vi.mock('./exec.ts', async () => { import { isProcessZombie, + listHostProcesses, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, + readProcessCommand, readProcessStartTime, readProcessIdentities, readProcessIdentityFacts, + processStartTimesDiffer, } from './host-process.ts'; import { mockLinuxProcessStatAbsent } from './host-proc.fixtures.ts'; @@ -26,6 +29,11 @@ function psReturns(stdout: string, exitCode = 0): void { mockRunCmdSync.mockReturnValue({ stdout, stderr: '', exitCode }); } +/** The canonical token a pinned C-form lstart parses to: the probe pins TZ=UTC, so parse as UTC. */ +function posixToken(y: number, mo: number, d: number, h: number, mi: number, s: number): string { + return `posix:${Date.UTC(y, mo, d, h, mi, s)}`; +} + /** Answers the two batched identity reads: state and start time, and the command line. */ function psAnswersIdentity(rows: { identity?: string; command?: string }): void { mockRunCmd.mockImplementation(async (_cmd: string, args: string[]) => { @@ -82,11 +90,11 @@ test('reads many process identities from one ps snapshot', () => { assert.deepEqual(observations.get(4242), { state: 'Ss', - startTime: 'Mon Aug 10 20:00:00 2026', + startTime: posixToken(2026, 7, 10, 20, 0, 0), }); assert.deepEqual(observations.get(4343), { state: 'ZN', - startTime: 'Mon Aug 10 20:01:00 2026', + startTime: posixToken(2026, 7, 10, 20, 1, 0), }); assert.equal(mockRunCmdSync.mock.calls.length, 1); assert.ok(PINNED_PS_COMMANDS.includes(mockRunCmdSync.mock.calls[0]?.[0])); @@ -114,11 +122,11 @@ test('the async snapshot answers the same observations from one awaited ps run', assert.deepEqual(observations.get(4242), { state: 'Ss', - startTime: 'Mon Aug 10 20:00:00 2026', + startTime: posixToken(2026, 7, 10, 20, 0, 0), }); assert.deepEqual(observations.get(4343), { state: 'ZN', - startTime: 'Mon Aug 10 20:01:00 2026', + startTime: posixToken(2026, 7, 10, 20, 1, 0), }); assert.equal(mockRunCmd.mock.calls.length, 1); assert.equal(mockRunCmdSync.mock.calls.length, 0, 'the async probe never blocks the loop'); @@ -147,7 +155,7 @@ test('the ownership read spends the budget its caller names on both batched read const facts = await readProcessIdentityFacts(4242, 5_000); assert.deepEqual(facts, { - startTime: 'Mon Aug 10 20:00:00 2026', + startTime: posixToken(2026, 7, 10, 20, 0, 0), command: '/bin/simctl io recordVideo out.mp4', zombie: false, }); @@ -187,12 +195,19 @@ test('one identity read answers a whole fleet from two ps runs, on Linux and mac [ 101, { - startTime: 'Mon Nov 9 10:00:00 2026', + startTime: posixToken(2026, 10, 9, 10, 0, 0), command: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --headless', zombie: false, }, ], - [202, { startTime: 'Tue Nov 10 08:30:00 2026', command: '[chrome] ', zombie: true }], + [ + 202, + { + startTime: posixToken(2026, 10, 10, 8, 30, 0), + command: '[chrome] ', + zombie: true, + }, + ], [303, { startTime: null, command: null, zombie: null }], ], ); @@ -245,7 +260,7 @@ test('a host without /bin/ps reads identity through the NixOS system profile pro assert.equal( readHostProcessIdentityObservations([4242]).get(4242)?.startTime, - 'Mon Aug 10 20:00:00 2026', + posixToken(2026, 7, 10, 20, 0, 0), ); assert.equal((await readProcessIdentityFacts(4242)).startTime, 'x'); assert.equal(mockRunCmdSync.mock.calls[0]?.[0], '/run/current-system/sw/bin/ps'); @@ -363,3 +378,136 @@ test.skipIf(process.platform !== 'linux')( } }, ); + +/** The `-o` value of a ps call: `lstart=`-bearing reads pin locale and clock, the others must not. */ +function psFieldOf(args: readonly string[]): string { + return args.find((arg) => arg.endsWith('=')) ?? ''; +} + +test('only lstart-bearing ps reads pin LC_ALL=C and TZ=UTC; command and state reads keep the caller env', async () => { + // BSD/macOS ps escapes non-ASCII argv bytes under LC_ALL=C, so a pinned command read would + // disagree byte-for-byte with the unpinned listHostProcesses scan and break managed-process + // ownership for non-ASCII paths. The rule: every read whose output carries lstart pins the C + // locale and the UTC clock (so the output never depends on the zone the ps child inherited), + // and no command-text read is pinned. + const utf8Command = '/Users/mich/é/ü/agent-device/dist/src/internal/daemon.js'; + const escapeLikeCLocalePs = (text: string) => + text.replaceAll(/[^\u0020-\u007E]/g, (ch) => `M-C${ch}`); + const commandFor = (options?: { envOverrides?: NodeJS.ProcessEnv }) => + options?.envOverrides?.LC_ALL === 'C' ? escapeLikeCLocalePs(utf8Command) : utf8Command; + mockRunCmdSync.mockImplementation( + (_cmd: string, args: readonly string[], options?: { envOverrides?: NodeJS.ProcessEnv }) => { + const field = psFieldOf(args); + if (field === 'pid=,state=,lstart=') + return { stdout: '4242 Ss Mon Aug 10 20:00:00 2026\n', stderr: '', exitCode: 0 }; + if (field === 'lstart=') + return { stdout: 'Mon Aug 10 20:00:00 2026\n', stderr: '', exitCode: 0 }; + if (field === 'command=') + return { stdout: `${commandFor(options)}\n`, stderr: '', exitCode: 0 }; + return { stdout: 'Ss\n', stderr: '', exitCode: 0 }; + }, + ); + mockRunCmd.mockImplementation( + async ( + _cmd: string, + args: readonly string[], + options?: { envOverrides?: NodeJS.ProcessEnv }, + ) => { + const field = psFieldOf(args); + if (field.includes('command=')) + return { stdout: `4242 ${commandFor(options)}\n`, stderr: '', exitCode: 0 }; + return { stdout: '4242 Ss Mon Aug 10 20:00:00 2026\n', stderr: '', exitCode: 0 }; + }, + ); + + readHostProcessIdentityObservations([4242]); + await readHostProcessIdentityObservationsAsync([4242]); + await readProcessIdentityFacts(4242); + assert.equal(readProcessStartTime(4242), posixToken(2026, 7, 10, 20, 0, 0)); + assert.equal( + readProcessCommand(4242), + utf8Command, + 'command text must read as UTF-8, not as C-locale escapes', + ); + isProcessZombie(4242); + await listHostProcesses({ timeoutMs: 1_000 }); + + const calls = [...mockRunCmdSync.mock.calls, ...mockRunCmd.mock.calls]; + assert.ok(calls.length > 0); + let sawCommandRead = false; + for (const call of calls) { + const field = psFieldOf(call[1] ?? []); + if (field.includes('lstart=')) { + assert.deepEqual( + call[2]?.envOverrides, + { LC_ALL: 'C', TZ: 'UTC' }, + `lstart-bearing read (${field}) must pin LC_ALL=C and TZ=UTC over the inherited env`, + ); + assert.equal(call[2]?.env, undefined, 'the pin must be an override, not a whole env'); + } else { + sawCommandRead ||= field.includes('command='); + assert.equal( + call[2]?.env, + undefined, + `non-lstart read (${field}) must carry no env, so command text keeps one encoding`, + ); + assert.equal( + call[2]?.envOverrides, + undefined, + `non-lstart read (${field}) must carry no locale pin, so command text keeps one encoding`, + ); + } + } + assert.ok(sawCommandRead, 'the pid=,command= batch read must have run'); +}); + +test.runIf(process.platform !== 'win32')( + 'a C-form lstart read canonicalizes on the UTC clock whatever zone the reader process runs in', + () => { + mockRunCmdSync.mockImplementation((_cmd: string, args: readonly string[]) => ({ + stdout: + String(args[3]) === 'lstart=' + ? 'Mon Aug 10 20:00:00 2026\n' + : '4242 Ss Mon Aug 10 20:00:00 2026\n', + stderr: '', + exitCode: 0, + })); + const baseline = readHostProcessIdentityObservations([4242]).get(4242)?.startTime; + assert.equal(baseline, posixToken(2026, 7, 10, 20, 0, 0)); + const originalTz = process.env.TZ; + process.env.TZ = 'Pacific/Kiritimati'; + try { + // The probe pins TZ=UTC for the ps child and the parser reads the fields as UTC, so the + // reader's own zone must not move the token. + assert.equal(readHostProcessIdentityObservations([4242]).get(4242)?.startTime, baseline); + assert.equal(readProcessStartTime(4242), baseline); + } finally { + if (originalTz === undefined) delete process.env.TZ; + else process.env.TZ = originalTz; + } + }, +); + +test('only two start times in the same provenanced format prove different lifetimes', () => { + const cForm = 'Tue Nov 17 19:42:27 2026'; + const french = 'mar. 17 nov. 19:42:27 2026'; // fr_FR rendering, with a clock + const frenchNoClock = '17 nov. 2026'; // locales that omit HH:mm:ss entirely + const norwegian = 'tir. 17. nov. 19:42:27 2026'; // nb_NO renders the clock with dots + // Raw historical renderings are unqualified: none proves a different lifetime, not even two + // raw C-form values one second apart. + assert.equal(processStartTimesDiffer(cForm, 'Tue Nov 17 19:42:28 2026'), false); + assert.equal(processStartTimesDiffer(french, cForm), false); + assert.equal(processStartTimesDiffer(cForm, frenchNoClock), false); + assert.equal(processStartTimesDiffer(french, norwegian), false); + assert.equal(processStartTimesDiffer(french, frenchNoClock), false); + // Two tokens in one provenanced format still prove a difference. + assert.equal(processStartTimesDiffer('posix:1763493000000', 'posix:1763493001000'), true); + assert.equal(processStartTimesDiffer('linux:boot:1', 'linux:boot:2'), true); + assert.equal(processStartTimesDiffer('202610081234567890129', '202701010000000000009'), true); + // Mixed formats and unreadable values prove nothing. + assert.equal(processStartTimesDiffer(cForm, 'posix:1763493000000'), false); + assert.equal(processStartTimesDiffer('posix:1763493000000', cForm), false); + assert.equal(processStartTimesDiffer(cForm, 'linux:boot:1'), false); + assert.equal(processStartTimesDiffer('posix:1763493000000', null), false); + assert.equal(processStartTimesDiffer('posix:1763493000000', 'posix:1763493000000'), false); +}); diff --git a/packages/host-kit/src/internal/host-process-stop-confirm.test.ts b/packages/host-kit/src/internal/host-process-stop-confirm.test.ts index 9352a994ee..04e9a28788 100644 --- a/packages/host-kit/src/internal/host-process-stop-confirm.test.ts +++ b/packages/host-kit/src/internal/host-process-stop-confirm.test.ts @@ -21,8 +21,10 @@ const PID = 4242; const BUDGET = { termTimeoutMs: 1_000, killTimeoutMs: 500 }; type Signal = 'SIGTERM' | 'SIGINT' | 'SIGKILL'; -const START = 'Mon Oct 12 00:00:00 2026'; -const OTHER_START = 'Tue Oct 13 09:00:00 2026'; +const START = 'posix:1760774400000'; +const OTHER_START = 'posix:1760904000000'; +/** A raw C-form lstart as a pre-pin build would have recorded it: unqualified, never comparable. */ +const LEGACY_START = 'Mon Oct 12 00:00:00 2026'; const COMMAND = '/usr/bin/node /app/dist/src/client/companion-tunnel.js --run-metro-companion'; const STOPPED: ConfirmedProcessStop = { status: 'stopped' }; @@ -63,6 +65,8 @@ type HostCase = Readonly<{ */ afterExit?: 'zombie' | 'held'; identity?: HostIdentity; + /** Overrides the recorded start time, for records a pre-pin build wrote. */ + recordedStartTime?: string; /** A `ps` the host refuses outright, so identity cannot be read at all. */ psFails?: boolean; /** The command line the process shows once it has received this signal, as after an `exec`. */ @@ -226,6 +230,15 @@ const STOP_CASES: HostCase[] = [ identity: { startTime: OTHER_START }, expect: REASSIGNED, }, + { + // A record written before the provenance pin holds a raw C-form lstart, which is unqualified: + // the stop neither declares the live process exited nor authorizes a signal to it. + name: 'legacy raw start-time record beside a pinned read', + claims: 'startTime', + recordedStartTime: LEGACY_START, + ...HELD, + expect: UNVERIFIED, + }, { // A confirmed start time with another command line is the same lifetime, as after an argv // rewrite: never signaled, and never reported gone. @@ -312,7 +325,10 @@ function targetOf(model: HostCase): ProcessStopTarget { return { pid: PID, identity: { - startTime: claims === 'startTime' || claims === 'both' ? START : undefined, + startTime: + claims === 'startTime' || claims === 'both' + ? (model.recordedStartTime ?? START) + : undefined, matches: claims === 'matches' || claims === 'both' ? (c) => c === COMMAND : undefined, }, }; diff --git a/packages/host-kit/src/internal/host-process-windows.test.ts b/packages/host-kit/src/internal/host-process-windows.test.ts index d4fa9bc79a..47ae75d301 100644 --- a/packages/host-kit/src/internal/host-process-windows.test.ts +++ b/packages/host-kit/src/internal/host-process-windows.test.ts @@ -22,7 +22,7 @@ import { } from './host-process.ts'; import { classifyOwnerLiveness } from './owner-identity.ts'; -const DAEMON_START = '20261008123456789012'; +const DAEMON_START = '202610081234567890129'; const DAEMON_PID = 4242; // One CIM row as a Windows host answers it: pid|ppid|creation|command. const DAEMON_ROW = `${DAEMON_PID}|4321|${DAEMON_START}|C:\\Program Files\\node.exe C:\\app\\dist\\src\\internal\\daemon.js`; @@ -143,14 +143,14 @@ test('the CIM row body never lets one null field raise, and pins the invariant c test('the Windows batch snapshot answers one observation query for every selected pid', () => { windowsPlatform(() => { cimAnswers( - `${DAEMON_ROW}\r\n4343|4321|20261008123500000000|C:\\Windows\\System32\\cmd.exe\r\n`, + `${DAEMON_ROW}\r\n4343|4321|202610081235000000009|C:\\Windows\\System32\\cmd.exe\r\n`, ); const observations = readHostProcessIdentityObservations([DAEMON_PID, 4343, DAEMON_PID]); assert.deepEqual(observations.get(DAEMON_PID), { state: 'R', startTime: DAEMON_START, }); - assert.equal(observations.get(4343)?.startTime, '20261008123500000000'); + assert.equal(observations.get(4343)?.startTime, '202610081235000000009'); }); assert.equal(mockRunCmdSync.mock.calls.length, 1); assert.match(String(mockRunCmdSync.mock.calls[0]![1][3]), /ProcessId=4242 OR ProcessId=4343/); @@ -247,7 +247,7 @@ test('a live Windows owner matches its recorded CIM birth instead of staying unp ); // The same pid answering a different birth proves PID reuse, which the // null-start Windows failure could never report. - cimAnswers(`${process.pid}|4321|20270101000000000000|\r\n`); + cimAnswers(`${process.pid}|4321|202701010000000000009|\r\n`); assert.equal( classifyOwnerLiveness({ owner: { pid: process.pid, startTime: DAEMON_START } }), 'owner-process-reused', diff --git a/packages/host-kit/src/internal/host-process.test.ts b/packages/host-kit/src/internal/host-process.test.ts index 6d43b22152..cccc5d798d 100644 --- a/packages/host-kit/src/internal/host-process.test.ts +++ b/packages/host-kit/src/internal/host-process.test.ts @@ -170,9 +170,9 @@ test.each([ 'unverified', ], [ - 'a contradicted start time', - { startTime: 'S1', matches: true }, - ['S2', 'recorded'], + 'a contradicted start time in the same provenanced format', + { startTime: 'posix:1763493000000', matches: true }, + ['posix:1763493001000', 'recorded'], 'reassigned', ], [ @@ -195,3 +195,24 @@ test('judgeProcessIdentity reads a zombie as exited whatever else the host says' 'exited', ); }); + +test('judgeProcessIdentity treats a legacy raw record against a provenanced read as unverified', () => { + // Records written before the provenance pin hold a raw `ps -o lstart` rendering: fr_FR prints + // `mar. 17 nov. 19:42:27 2026`, locales that omit HH:mm:ss print no clock at all, and even the + // C-locale C form carries no comparable provenance. None proves a different lifetime, so the + // verdict is unverified — never reassigned, and never permission to signal. + const facts = { startTime: 'posix:1763493000000', command: null, zombie: false }; + assert.equal( + judgeProcessIdentity({ startTime: 'mar. 17 nov. 19:42:27 2026' }, facts), + 'unverified', + ); + assert.equal(judgeProcessIdentity({ startTime: '17 nov. 2026' }, facts), 'unverified'); + assert.equal( + judgeProcessIdentity({ startTime: 'tir. 17. nov. 19:42:27 2026' }, facts), + 'unverified', + ); + assert.equal( + judgeProcessIdentity({ startTime: 'Tue Nov 17 19:42:27 2026' }, facts), + 'unverified', + ); +}); diff --git a/packages/host-kit/src/internal/host-process.ts b/packages/host-kit/src/internal/host-process.ts index f7533107ae..6101aebaa6 100644 --- a/packages/host-kit/src/internal/host-process.ts +++ b/packages/host-kit/src/internal/host-process.ts @@ -25,13 +25,7 @@ export type HostProcessIdentityObservation = Readonly<{ startTime: string; }>; -/** - * What the host says about one pid when a caller is about to signal it. Each field is `null` - * when the host did not answer, which is unknown evidence rather than absence: only a `ps` - * that names a different process proves the pid changed hands. `zombie` is `null` together - * with an unreadable process state, since a zombie passes `kill(pid, 0)` and still reports - * its original start time, so nothing else exposes that it already terminated. - */ +/** What the host says about one pid before a signal; `null` fields are unknown evidence, never absence. */ export type HostProcessIdentityFacts = Readonly<{ startTime: string | null; command: string | null; @@ -50,10 +44,7 @@ export type HostEnvironmentSource = Readonly<{ cwd(): string; }>; -/** - * Snapshots the environment and working directory of `source`, which an entry point passes as - * `process`. The environment is copied, so later changes to the source never reach the capture. - */ +/** Copies `source` (an entry point passes `process`) so later changes never reach the capture. */ export function captureHostEnvironment(source: HostEnvironmentSource): HostEnvironment { return { env: { ...source.env }, cwd: source.cwd() }; } @@ -113,11 +104,7 @@ export function isProcessGroupAlive(pid: number): boolean { } } -/** - * Reads who owns a pid, off the event loop, with a budget the caller names. Use this rather than - * the synchronous probes when the answer decides whether a process is signaled: waiting is - * reversible and signaling the wrong process is not. See {@link readProcessIdentities}. - */ +/** Off-loop ownership read for answers that decide a signal; see {@link readProcessIdentities}. */ export async function readProcessIdentityFacts( pid: number, timeoutMs = PS_TIMEOUT_MS, @@ -132,14 +119,8 @@ const UNANSWERED_IDENTITY: HostProcessIdentityFacts = Object.freeze({ }); /** - * What the host says about each pid named, off the event loop. Every pid shares the same process - * table reads: on POSIX one `ps` for state and start time and one for the command, run - * concurrently so a loaded host pays one budget for the set; on Windows one CIM query. A pid the - * host did not answer for maps to all-`null` facts, which is unknown evidence, never absence. - * - * Nothing about another process is cached: its identity is the fact a caller is about to act on, - * and a pid can change hands between two reads. Only this process's own identity is reused, by - * `readCurrentOwnerIdentity`, because a process's own start time never changes. + * Off-loop facts for many pids from one shared process-table read set (POSIX ps pairs, Windows + * CIM); unanswered pids map to all-`null` facts. Nothing about another process is cached. */ export async function readProcessIdentities( pids: Iterable, @@ -171,8 +152,16 @@ async function readProcessIdentityRows( ); } const [identityRows, commandRows] = await Promise.all([ - runHostPsAsync(HOST_PROCESS_IDENTITY_PS_ARGS(pids), timeoutMs, parseHostProcessIdentityRows), - runHostPsAsync(HOST_PROCESS_COMMAND_PS_ARGS(pids), timeoutMs, parseHostProcessCommandRows), + runHostPsAsync( + HOST_PROCESS_IDENTITY_PS_ARGS(pids), + psLstartReadOptions(timeoutMs), + parseHostProcessIdentityRows, + ), + runHostPsAsync( + HOST_PROCESS_COMMAND_PS_ARGS(pids), + psReadOptions(timeoutMs), + parseHostProcessCommandRows, + ), ]); const identities = new Map(identityRows.map((row) => [row.pid, row])); const commands = new Map(commandRows.map((row) => [row.pid, row.command])); @@ -192,11 +181,11 @@ async function readProcessIdentityRows( async function runHostPsAsync( args: string[], - timeoutMs: number, + options: ExecOptions, parse: (stdout: string) => Row[], ): Promise { try { - const result = await runCmd(hostPsCommand(), args, { allowFailure: true, timeoutMs }); + const result = await runCmd(hostPsCommand(), args, options); return result.exitCode !== 0 ? [] : parse(result.stdout); } catch { // A failed ps read is unknown evidence; callers remain fail-closed. @@ -240,16 +229,77 @@ function readLinuxProcessStat(pid: number): { state: string; startTime: string } } } -/** Positive proof of different lifetimes; unreadable or mixed-format records prove nothing. */ +/** + * Locale and clock pin for lstart-bearing ps reads, applied as a final `envOverrides` word so it + * wins over any captured host or request `TZ` without replacing the rest of the child env. With + * `TZ=UTC` the ps child renders lstart on the UTC clock no matter which zone the reader or the + * bound request inherited, so the output is parsed as UTC and the token has no local-zone or DST + * dependence. + */ +const PS_LSTART_ENV_OVERRIDES: NodeJS.ProcessEnv = { LC_ALL: 'C', TZ: 'UTC' }; + +/** ps read options without lstart: failure is unknown evidence; the caller's locale stays in charge. */ +const psReadOptions = (timeoutMs: number): ExecOptions => ({ allowFailure: true, timeoutMs }); + +/** ps read options carrying lstart: C locale and UTC clock pinned over the effective child env. */ +const psLstartReadOptions = (timeoutMs: number): ExecOptions => ({ + allowFailure: true, + timeoutMs, + envOverrides: PS_LSTART_ENV_OVERRIDES, +}); + +const WINDOWS_START_TIME = /^\d{21}$/; // Windows CIM stamp yyyyMMddHHmmssfffffff +const POSIX_BIRTH_TOKEN_PREFIX = 'posix:'; // canonical POSIX birth token: UTC epoch ms +// Raw C-form `ps -o lstart=` (historical records) is unqualified: no comparable provenance. +const PS_START_TIME_FIELDS = + /^([A-Za-z]{3}) ([A-Za-z]{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/; +const PS_MONTHS = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '); + +type BirthTokenFormat = 'linux' | 'posix' | 'windows' | 'unqualified'; + +function psStartTimeFormat(value: string): BirthTokenFormat { + if (value.startsWith('linux:')) return 'linux'; + if (value.startsWith(POSIX_BIRTH_TOKEN_PREFIX)) return 'posix'; + if (WINDOWS_START_TIME.test(value)) return 'windows'; + return 'unqualified'; +} + +/** A birth token with comparable provenance can prove or authorize a lifetime; a raw one cannot. */ +export function isProvenancedBirthToken(value: string): boolean { + return psStartTimeFormat(value) !== 'unqualified'; +} + +// Differ proves exit only when both sides share one provenanced format; raw renderings stay unknown. export function processStartTimesDiffer( left: string | null | undefined, right: string | null | undefined, ): boolean { if (!left || !right) return false; - if (left.startsWith('linux:') !== right.startsWith('linux:')) return false; + const format = psStartTimeFormat(left); + if (format !== psStartTimeFormat(right) || format === 'unqualified') return false; return left !== right; } +/** + * Canonicalize a pinned C-form lstart to a zone-independent token. The probe pins `TZ=UTC`, so the + * wall-clock fields are UTC and are parsed with `Date.UTC` — never the reader's local zone, which + * could differ from the zone the ps child inherited and which folds ambiguous times at DST. + */ +function canonicalPosixBirthToken(lstart: string): string | null { + const match = PS_START_TIME_FIELDS.exec(lstart.trim()); + const month = match === null ? -1 : PS_MONTHS.indexOf(match[2]!); + if (match === null || month < 0) return null; + const startedAtMs = Date.UTC( + Number(match[7]), + month, + Number(match[3]), + Number(match[4]), + Number(match[5]), + Number(match[6]), + ); + return Number.isFinite(startedAtMs) ? `${POSIX_BIRTH_TOKEN_PREFIX}${startedAtMs}` : null; +} + export function readProcessStartTime(pid: number): string | null { return readProcessField(pid, 'lstart='); } @@ -266,12 +316,7 @@ export function isProcessZombie(pid: number): boolean { return readProcessField(pid, 'state=')?.startsWith('Z') ?? false; } -/** - * What the host says about each pid named, from one process-tool snapshot. An unanswered pid is - * missing from the map, which is unknown evidence rather than absence: a caller that signals on - * the answer must stay fail-closed. Use {@link readHostProcessIdentityObservationsAsync} from a - * path that is already waiting; this one blocks the event loop for the whole snapshot. - */ +/** One blocking process-tool snapshot; unanswered pids are unknown, never absence. Use the async variant from waiting paths. */ export function readHostProcessIdentityObservations( pids: Iterable, ): ReadonlyMap { @@ -280,12 +325,7 @@ export function readHostProcessIdentityObservations( return readHostProcessIdentitySnapshot(selected, readHostProcessIdentityRowsSync(selected)); } -/** - * {@link readHostProcessIdentityObservations} off the event loop, with the same one-snapshot - * guarantee and the same fail-closed answer. A daemon request path that only decides whether to - * pay a cost must not stall every other request, timer, and abort handler behind a - * `spawnSync` of the host process tool. - */ +/** {@link readHostProcessIdentityObservations} off the event loop: same snapshot, same fail-closed answer. */ export async function readHostProcessIdentityObservationsAsync( pids: Iterable, ): Promise> { @@ -332,10 +372,11 @@ function readHostProcessIdentityRowsSync( return windowsProcessIdentityRows(readWindowsProcessRows(pids, WINDOWS_PS_TIMEOUT_MS)); } try { - const result = runCmdSync(hostPsCommand(), HOST_PROCESS_IDENTITY_PS_ARGS(pids), { - allowFailure: true, - timeoutMs: PS_TIMEOUT_MS, - }); + const result = runCmdSync( + hostPsCommand(), + HOST_PROCESS_IDENTITY_PS_ARGS(pids), + psLstartReadOptions(PS_TIMEOUT_MS), + ); return result.exitCode !== 0 ? [] : parseHostProcessIdentityRows(result.stdout); } catch { // A failed ps snapshot is unknown evidence; callers remain fail-closed. @@ -353,7 +394,7 @@ async function readHostProcessIdentityRowsAsync( } return await runHostPsAsync( HOST_PROCESS_IDENTITY_PS_ARGS(pids), - PS_TIMEOUT_MS, + psLstartReadOptions(PS_TIMEOUT_MS), parseHostProcessIdentityRows, ); } @@ -367,7 +408,10 @@ function parseHostProcessIdentityRows(stdout: string): HostProcessIdentityRow[] if (!Number.isInteger(pid) || pid <= 0) continue; // On Linux both facts come from one /proc read; the ps row is the fallback when /proc is unreadable. const linux = readLinuxProcessStat(pid); - rows.push(linux ? { pid, ...linux } : { pid, state: match[2]!, startTime: match[3]! }); + // A ps lstart row canonicalizes to a zone-independent posix: token; an unparseable raw value + // stays unqualified and is later treated as unverified evidence. + const startTime = linux ? linux.startTime : (canonicalPosixBirthToken(match[3]!) ?? match[3]!); + rows.push(linux ? { pid, ...linux } : { pid, state: match[2]!, startTime }); } return rows; } @@ -392,11 +436,14 @@ function readProcessField(pid: number, field: HostProcessField): string | null { if (token !== undefined) return token; } try { - const result = runCmdSync(hostPsCommand(), ['-p', String(pid), '-o', field], { - allowFailure: true, - timeoutMs: PS_TIMEOUT_MS, - }); - return processFieldValue(result); + const result = runCmdSync( + hostPsCommand(), + ['-p', String(pid), '-o', field], + // Only the lstart-bearing read is locale-pinned; command/state keep the caller's locale. + field === 'lstart=' ? psLstartReadOptions(PS_TIMEOUT_MS) : psReadOptions(PS_TIMEOUT_MS), + ); + const value = processFieldValue(result); + return field === 'lstart=' ? (canonicalPosixBirthToken(value ?? '') ?? value) : value; } catch { return null; } @@ -408,12 +455,7 @@ function processFieldValue(result: ExecResult): string | null { return value.length > 0 ? value : null; } -/** - * Walks process-table stdout line by line, keeping rows whose first two - * capture groups are a positive pid and an optional positive ppid. Every - * process-table format (POSIX `ps`, Windows CIM) feeds its own row pattern - * and row builder through this single walk. - */ +/** Walks process-table stdout, keeping rows whose first groups are a positive pid (and optional ppid). */ function parseProcessTableRows( stdout: string, rowPattern: RegExp, @@ -439,17 +481,9 @@ export function parseHostProcessList(stdout: string): HostProcessInfo[] { })); } -/* -------------------------------------------------------------------------- */ -/* Windows process-identity branch (#3291) */ -/* */ -/* Windows hosts have no `ps`. The same identity facts come from one */ -/* CIM (`Win32_Process`) query through PowerShell: `CreationDate` is the */ -/* birth time proven against PID reuse, `CommandLine` is the command the */ -/* daemon-identity patterns match, and a terminated process leaves the table */ -/* entirely instead of lingering as a zombie, so a live row is never `Z`. */ -/* A failed or unanswered query is unknown evidence, exactly like a failed */ -/* `ps`, and every caller stays fail-closed on it. */ -/* -------------------------------------------------------------------------- */ +/* Windows branch (#3291): no `ps`; one CIM query gives CreationDate (PID-reuse proof) and + CommandLine (daemon-identity match), and a terminated process leaves the table, so no live + row is a zombie. A failed query is unknown evidence, exactly like a failed `ps`. */ type WindowsProcessRow = Readonly<{ pid: number; @@ -647,18 +681,10 @@ export type GracefulStopSignal = 'SIGTERM' | 'SIGINT'; type StopSignal = GracefulStopSignal | 'SIGKILL'; /** - * The outcome of a stop that a caller may act on. A process tracked elsewhere (a state file, a - * registration) may be forgotten only on `stopped`. - * - * - `stopped`: the host released the pid, or proved the pid now names a different process. - * `signal` is the last signal this stop sent before that proof, and is absent when the recorded - * process was already gone before anything was signaled. `reassigned` says the proof was a pid - * that now names a different process: the recorded process is gone, but nobody watched it leave. - * - `retained` + `signal-failed`: `signal` was refused by `errno` while the process was there. - * `EPERM` usually means another owner holds it, and later signals are refused by the same check. - * - `retained` + `exit-timeout`: SIGKILL was accepted and the process outlived its budget. - * - `retained` + `identity-unverified`: no recorded claim could be confirmed against a readable fact, - * so nothing proves which process a signal would reach. + * The outcome of a stop a caller may act on; a tracked process may be forgotten only on `stopped`. + * - `stopped`: pid released or proven reassigned; `signal` is the last one sent, if any. + * - `retained` + `signal-failed` / `exit-timeout` / `identity-unverified`: the pid stayed; the + * reason says why nothing may be forgotten or signaled further. */ export type ConfirmedProcessStop = | Readonly<{ status: 'stopped'; signal?: StopSignal; reassigned?: true }> @@ -674,11 +700,7 @@ export type ConfirmedProcessStopDetails = Readonly<{ pid: number; }>; -/** - * Projects a retained verdict onto the keys a caller may publish. A caller adds its own artifact - * paths beside these; a layer that forwards the verdict forwards only these, so an inner surface's - * file paths and advice cannot ride along under an outer surface's message. - */ +/** Projects a retained verdict onto the publishable `details` keys, and nothing else. */ export function confirmedProcessStopDetails( retained: Extract, pid: number, @@ -691,10 +713,7 @@ export function confirmedProcessStopDetails( }; } -/** - * Names a pid the stop left alone. This is the one verdict that must not say the process is still - * running: the host refused to describe it, so nothing was ever signaled to it. - */ +/** Names a pid the stop left alone; it must never read as "still running". */ export function describeUnconfirmedProcessStop(pid: number, claimedAs: string): string { return `pid ${pid} could not be confirmed as ${claimedAs}, so no signal was sent to it`; } @@ -732,11 +751,7 @@ export function readConfirmedProcessStopDetails( }; } -/** - * The process to stop, and what the caller recorded about it. A stop signals only a process it can - * name: an `identity` that claims nothing is unverifiable, and so is one whose claims the host will - * not confirm. - */ +/** The pid to stop and the caller's recorded claims; a stop signals only a process it can name. */ export type ProcessStopTarget = Readonly<{ pid: number; identity: ProcessStopIdentity; @@ -761,18 +776,9 @@ export type ProcessStopBudget = Readonly<{ }>; /** - * What the host's facts say about the process a caller recorded. One rule answers every identity - * question before a signal: - * - * - `exited`: the host shows the pid as a zombie, so the recorded process already terminated. - * - `reassigned`: a readable start time contradicts the record, or, when no start time was - * recorded, a readable command does: the pid now names a different process and the recorded one - * is gone. - * - `ours`: every recorded claim was read and matches. One confirmed claim beside an unread one is - * not enough, because the start-time and command reads can fail independently. - * - `unverified`: everything else. A claim the host did not answer, no claim at all, or a recorded - * start time beside a command that does not match (the same lifetime may have exec'd or rewritten - * its argv) is neither proof the recorded process is gone nor permission to signal. + * The one identity rule before a signal: `exited` (zombie), `reassigned` (a readable fact + * contradicts the record), `ours` (every recorded claim read and matching), or `unverified` + * (everything else — never proof of exit, never permission to signal). */ export type ProcessIdentityVerdict = 'ours' | 'exited' | 'reassigned' | 'unverified'; @@ -792,11 +798,8 @@ export function judgeProcessIdentity( } /** - * The one TERM-then-KILL escalation in host-kit. Signals one process gracefully, waits the grace - * period, re-proves identity, then sends SIGKILL, and proves which way the recorded process ended - * so a caller only forgets one it watched leave. Every signal needs a host-confirmed identity - * ({@link judgeProcessIdentity}): an unreadable identity before either signal retains rather than - * signaling a process this caller cannot name. A refusal is not absence, so each stage waits. + * The one TERM-then-KILL escalation: every signal needs a host-confirmed identity + * ({@link judgeProcessIdentity}); unreadable identity retains rather than signaling. */ export async function stopProcessAndConfirmExit( target: ProcessStopTarget, @@ -831,10 +834,7 @@ function stageVerdict( return { status: 'retained', reason: 'identity-unverified' }; } -/** - * Whether the live pid still names the process the caller recorded, read once before anything is - * signaled. `released` is a pid `kill(pid, 0)` no longer finds; the rest is {@link judgeProcessIdentity}. - */ +/** Pre-signal identity proof: `released` when `kill(pid, 0)` fails, else {@link judgeProcessIdentity}. */ async function proveStopTargetIdentity( target: ProcessStopTarget, ): Promise { diff --git a/packages/host-kit/src/internal/owned-process-record.test.ts b/packages/host-kit/src/internal/owned-process-record.test.ts index 5ca396f9ac..8b60e5e5bf 100644 --- a/packages/host-kit/src/internal/owned-process-record.test.ts +++ b/packages/host-kit/src/internal/owned-process-record.test.ts @@ -146,7 +146,7 @@ function hostRuns(record: { pid: number; startTime: string; command: string }): const BROWSER = { pid: 101, - startTime: 'Mon Nov 9 10:00:00 2026', + startTime: 'posix:1000', command: '/opt/chrome --user-data-dir=/tmp/agent-device-browser', purpose: 'managed-web-browser', }; @@ -174,7 +174,7 @@ test('startup interrupts an exact simctl recorder before clearing its record', a const { store, cleanup } = reapFixture('simctl-reap'); const record = { pid: 111, - startTime: 'Mon Nov 9 10:00:00 2026', + startTime: 'posix:1000', command: 'xcrun simctl io simulator recordVideo /tmp/recording.mp4', purpose: 'simctl-screen-recording', }; @@ -211,7 +211,7 @@ test('startup treats a zombie identity as missing without signaling it', async ( test('startup forgets a record whose pid the host shows in another lifetime, without signaling it', async () => { const { store, cleanup } = reapFixture('reuse'); - hostRuns({ ...BROWSER, startTime: 'Tue Nov 10 08:00:00 2026', command: '/usr/bin/other' }); + hostRuns({ ...BROWSER, startTime: 'posix:2000', command: '/usr/bin/other' }); try { store.replace({ kind: 'daemon' }, [BROWSER]); @@ -306,7 +306,7 @@ test('startup counts a pid reassigned after SIGTERM as missing, not terminated', const { store, cleanup } = reapFixture('reassigned-after-term'); hostRuns(BROWSER); processState.exitsOnSignal = false; - processState.startAfterSignal = 'Tue Nov 10 09:00:00 2026'; + processState.startAfterSignal = 'posix:3000'; try { store.replace({ kind: 'daemon' }, [BROWSER]); diff --git a/packages/host-kit/src/internal/owner-identity-liveness.test.ts b/packages/host-kit/src/internal/owner-identity-liveness.test.ts index ef97f9f5e3..744bbb3055 100644 --- a/packages/host-kit/src/internal/owner-identity-liveness.test.ts +++ b/packages/host-kit/src/internal/owner-identity-liveness.test.ts @@ -53,15 +53,26 @@ test('a failed start-time read is not proof of death for an alive pid', () => { }); test('a definite start-time mismatch classifies as owner-process-reused', () => { - mockReadProcessStartTime.mockReturnValue('start-b'); + // The mismatch must be proven in one provenanced format: two `posix:` tokens one second apart. + mockReadProcessStartTime.mockReturnValue('posix:1763493001000'); assert.equal( - classifyOwnerLiveness({ owner: { pid: OWNER_PID, startTime: 'start-a' } }), + classifyOwnerLiveness({ owner: { pid: OWNER_PID, startTime: 'posix:1763493000000' } }), 'owner-process-reused', ); }); +test('a legacy raw record beside a provenanced read stays live, never reused', () => { + // `mar. 17 nov. 19:42:27 2026` (fr_FR), `17 nov. 2026` (no colon-separated clock), and the raw + // C form are renderings an older build could have recorded; none proves the pid changed hands. + for (const legacy of ['mar. 17 nov. 19:42:27 2026', '17 nov. 2026', 'Tue Nov 17 19:42:27 2026']) { + mockReadProcessStartTime.mockReturnValue('posix:1763493000000'); + assert.equal(classifyOwnerLiveness({ owner: { pid: OWNER_PID, startTime: legacy } }), 'live'); + } +}); + test.each([ ['Mon Aug 10 20:00:00 2026', 'linux:11111111-1111-4111-8111-111111111111:12345'], + ['posix:1763493000000', 'linux:11111111-1111-4111-8111-111111111111:12345'], ['linux:11111111-1111-4111-8111-111111111111:12345', 'Mon Aug 10 20:00:00 2026'], ])('an owner with an incomparable start-time format retains its resource', (recorded, observed) => { mockReadProcessStartTime.mockReturnValue(observed); diff --git a/packages/host-kit/src/internal/owner-identity.test.ts b/packages/host-kit/src/internal/owner-identity.test.ts index 14ff2450a3..51778c24ae 100644 --- a/packages/host-kit/src/internal/owner-identity.test.ts +++ b/packages/host-kit/src/internal/owner-identity.test.ts @@ -26,13 +26,20 @@ test('distinguishes dead and PID-reused owners', () => { classifyOwnerLiveness({ owner: { pid: 999_999_999, startTime: 'old-start' } }), 'owner-process-dead', ); + // A proved reuse needs a recorded start time in the same provenanced format as the live read + // but with a different value: the `linux:` token on Linux, the CIM stamp on Windows, the + // `posix:` canonical token on macOS. + const liveStartTime = readProcessStartTime(process.pid); + const staleStartTime = liveStartTime?.startsWith('linux:') + ? 'linux:other-boot:1' + : liveStartTime !== null && /^\d{21}$/.test(liveStartTime) + ? '00000000000000000000' + : 'posix:1'; assert.equal( classifyOwnerLiveness({ owner: { pid: process.pid, - startTime: readProcessStartTime(process.pid)?.startsWith('linux:') - ? 'linux:other-boot:1' - : 'not-this-process', + startTime: staleStartTime, }, }), 'owner-process-reused', @@ -64,7 +71,26 @@ test('distinguishes a gone state directory from permission and transient I/O fai test('proves two owners differ only when the evidence is there', () => { const differs = (left: OwnerIdentity, right: OwnerIdentity) => ownerIdentityDiffers(left, right); assert.equal(differs({ pid: 1, startTime: 'a' }, { pid: 2, startTime: 'a' }), true); - assert.equal(differs({ pid: 1, startTime: 'a' }, { pid: 1, startTime: 'b' }), true); + // Two records in the same provenanced format with different values prove a reuse. + assert.equal( + differs( + { pid: 1, startTime: 'posix:1763493000000' }, + { pid: 1, startTime: 'posix:1763493001000' }, + ), + true, + ); + // Two raw C-form renderings one second apart are unqualified: a legacy record never proves + // a reuse, not even against another raw rendering. + assert.equal( + differs( + { pid: 1, startTime: 'Mon Aug 10 20:00:00 2026' }, + { pid: 1, startTime: 'Mon Aug 10 20:00:01 2026' }, + ), + false, + ); + // Two legacy-format records are not comparable: neither rendering was read by this build, so + // a difference between them proves nothing about the lifetime. + assert.equal(differs({ pid: 1, startTime: 'a' }, { pid: 1, startTime: 'b' }), false); assert.equal(differs({ pid: 1, startTime: 'a' }, { pid: 1, startTime: 'a' }), false); assert.equal( differs( @@ -73,6 +99,14 @@ test('proves two owners differ only when the evidence is there', () => { ), false, ); + // A legacy localized rendering beside a C-form read is unverified, never a proved reuse. + assert.equal( + differs( + { pid: 1, startTime: 'mar. 10 août 20:00:00 2026' }, + { pid: 1, startTime: 'Mon Aug 10 20:00:00 2026' }, + ), + false, + ); assert.equal( differs({ pid: 1, startTime: 'linux:boot:1' }, { pid: 1, startTime: 'linux:boot:2' }), true, diff --git a/packages/host-kit/src/internal/owner-identity.ts b/packages/host-kit/src/internal/owner-identity.ts index c5c16e08ea..1219e2eb2f 100644 --- a/packages/host-kit/src/internal/owner-identity.ts +++ b/packages/host-kit/src/internal/owner-identity.ts @@ -1,8 +1,8 @@ import fs from 'node:fs'; import { isProcessAlive, - processStartTimesDiffer, isProcessZombie, + processStartTimesDiffer, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, readProcessIdentityFacts, diff --git a/packages/host-kit/src/internal/process-lock-guard.test.ts b/packages/host-kit/src/internal/process-lock-guard.test.ts index 09bcea3bf6..898fe29096 100644 --- a/packages/host-kit/src/internal/process-lock-guard.test.ts +++ b/packages/host-kit/src/internal/process-lock-guard.test.ts @@ -78,7 +78,9 @@ test('a long-standing guard whose holder pid now has another start time is recla startTime: process.platform === 'linux' ? 'linux:00000000-0000-0000-0000-000000000000:0' - : 'Thu Jan 1 00:00:00 1970', + : process.platform === 'win32' + ? '00000000000000000000' + : 'posix:1', }; fs.writeFileSync(mutexPath, JSON.stringify(reusedHolder)); stampDirectoryAbandoned(mutexPath); diff --git a/packages/host-kit/src/process.ts b/packages/host-kit/src/process.ts index 9a8eedfae2..23f4b04c83 100644 --- a/packages/host-kit/src/process.ts +++ b/packages/host-kit/src/process.ts @@ -19,8 +19,10 @@ export { isProcessAlive, isProcessGroupAlive, isProcessZombie, + isProvenancedBirthToken, judgeProcessIdentity, listHostProcesses, + processStartTimesDiffer, type ProcessIdentityVerdict, type ProcessStopBudget, type ProcessStopIdentity, @@ -34,7 +36,6 @@ export { readProcessIdentities, readProcessIdentityFacts, readProcessStartTime, - processStartTimesDiffer, signalPidsBestEffort, stopProcessAndConfirmExit, uniquePositivePids, diff --git a/packages/platform-web/src/__tests__/agent-browser-process-record.test.ts b/packages/platform-web/src/__tests__/agent-browser-process-record.test.ts index 965553cfe2..41befbb7c5 100644 --- a/packages/platform-web/src/__tests__/agent-browser-process-record.test.ts +++ b/packages/platform-web/src/__tests__/agent-browser-process-record.test.ts @@ -27,7 +27,14 @@ vi.mock('@agent-device/host-kit/process', async (importOriginal) => ({ const mockObservations = vi.mocked(observationsMock); const mockIsProcessAlive = vi.mocked(isProcessAliveMock); -function record(pid: number, startTime = `start-${pid}`): OwnedProcessRecord { +/** Canonical POSIX birth token per pid: provenanced, so a differing token proves a different lifetime. */ +function startToken(pid: number): string { + return `posix:${1000 + pid}`; +} +/** A birth token naming a different lifetime than any `startToken`. */ +const LATER_LIFETIME = 'posix:999999999'; + +function record(pid: number, startTime = startToken(pid)): OwnedProcessRecord { return { pid, startTime, @@ -78,7 +85,7 @@ function undecodableDaemonEntry() { function hostNamesEveryRequestedPid(): void { mockObservations.mockImplementation(async (pidsArg: Iterable) => { const observations = new Map(); - for (const pid of pidsArg) observations.set(pid, { state: 'Ss', startTime: `start-${pid}` }); + for (const pid of pidsArg) observations.set(pid, { state: 'Ss', startTime: startToken(pid) }); return observations; }); } @@ -110,7 +117,7 @@ test('a record whose every managed process is alive under its recorded identity test('a process the host cannot name makes the record not-live', async () => { hostAnswers( new Map([ - [11, { state: 'Ss', startTime: 'start-11' } satisfies HostProcessIdentityObservation], + [11, { state: 'Ss', startTime: startToken(11) } satisfies HostProcessIdentityObservation], ]), ); assert.equal( @@ -124,7 +131,7 @@ test('a process the host cannot name makes the record not-live', async () => { test('a pid answering under a different start time is pid reuse, not the recorded fleet', async () => { hostAnswers( new Map([ - [11, { state: 'Ss', startTime: 'a-later-boot' } satisfies HostProcessIdentityObservation], + [11, { state: 'Ss', startTime: LATER_LIFETIME } satisfies HostProcessIdentityObservation], ]), ); assert.equal( @@ -136,7 +143,7 @@ test('a pid answering under a different start time is pid reuse, not the recorde test('a recorded zombie is not a live fleet even with its start time intact', async () => { hostAnswers( new Map([ - [11, { state: 'ZN', startTime: 'start-11' } satisfies HostProcessIdentityObservation], + [11, { state: 'ZN', startTime: startToken(11) } satisfies HostProcessIdentityObservation], ]), ); assert.equal( @@ -173,7 +180,12 @@ test('a session-scoped record is not the daemon-scoped managed fleet', async () test('a record of another purpose is not the managed fleet', async () => { const store = storeReturning([ daemonEntry([ - { pid: 11, startTime: 'start-11', command: 'command-11', purpose: 'simctl-screen-recording' }, + { + pid: 11, + startTime: startToken(11), + command: 'command-11', + purpose: 'simctl-screen-recording', + }, ]), ]); assert.equal(await managedWebBrowserProcessRecordIsLive(store), false); @@ -199,8 +211,8 @@ test('a store that cannot answer reads as not-live, which sends the caller back test('a record is dead only when every recorded process was observed not alive', async () => { hostAnswers( new Map([ - [11, { state: 'ZN', startTime: 'start-11' } satisfies HostProcessIdentityObservation], - [12, { state: 'Ss', startTime: 'a-later-boot' } satisfies HostProcessIdentityObservation], + [11, { state: 'ZN', startTime: startToken(11) } satisfies HostProcessIdentityObservation], + [12, { state: 'Ss', startTime: LATER_LIFETIME } satisfies HostProcessIdentityObservation], ]), ); assert.equal( @@ -214,8 +226,8 @@ test('a record is dead only when every recorded process was observed not alive', test('a recorded process still answering alive keeps the record from being dead', async () => { hostAnswers( new Map([ - [11, { state: 'ZN', startTime: 'start-11' } satisfies HostProcessIdentityObservation], - [12, { state: 'Ss', startTime: 'start-12' } satisfies HostProcessIdentityObservation], + [11, { state: 'ZN', startTime: startToken(11) } satisfies HostProcessIdentityObservation], + [12, { state: 'Ss', startTime: startToken(12) } satisfies HostProcessIdentityObservation], ]), ); assert.equal( diff --git a/packages/platform-web/src/agent-browser-lifecycle.test.ts b/packages/platform-web/src/agent-browser-lifecycle.test.ts index 2e69acd2f1..ab687b08d2 100644 --- a/packages/platform-web/src/agent-browser-lifecycle.test.ts +++ b/packages/platform-web/src/agent-browser-lifecycle.test.ts @@ -12,6 +12,13 @@ import { PassThrough } from 'node:stream'; import { afterEach, beforeEach, expect, test, vi } from 'vitest'; import { mkdtempForTestSync } from './__tests__/test-utils.ts'; +/** C-form `lstart` token per pid: the verified format, so a differing token proves a different lifetime. */ +function startToken(pid: number): string { + return `posix:${1000 + pid}`; +} +/** A birth token naming a different lifetime than any `startToken`. */ +const LATER_LIFETIME = 'posix:999999999'; + const { runCmdMock, spawnMock, probe } = vi.hoisted(() => ({ runCmdMock: vi.fn(), spawnMock: vi.fn(), @@ -38,7 +45,7 @@ const identitiesMock = vi.hoisted(() => new Map( [...pids].map((pid) => [ pid, - { startTime: `start-${pid}`, command: `command-${pid}`, zombie: false }, + { startTime: startToken(pid), command: `command-${pid}`, zombie: false }, ]), ), ), @@ -226,7 +233,7 @@ function recordedBrowserStore(stateDir: string, pid = NEVER_A_PID) { records: [ { pid, - startTime: `start-${pid}`, + startTime: startToken(pid), command: `command-${pid}`, purpose: 'verified-managed-web-browser', }, @@ -420,7 +427,7 @@ test('cleanup reads recorded browser identities without reconstructing a process records: [ { pid: NEVER_A_PID, - startTime: `start-${NEVER_A_PID}`, + startTime: startToken(NEVER_A_PID), command: `command-${NEVER_A_PID}`, purpose: 'verified-managed-web-browser', }, @@ -513,7 +520,7 @@ function observeProcesses(processes: ProcessFixture[]) { [...pids].flatMap((pid) => { const row = processes.find((item) => item.pid === pid); return row - ? [[pid, { startTime: `start-${pid}`, command: row.command, zombie: false }]] + ? [[pid, { startTime: startToken(pid), command: row.command, zombie: false }]] : []; }), ), @@ -632,7 +639,7 @@ test('records verified current and retained native roots and stable descendants' rows.slice(0, 4).map(({ pid, command }) => ({ pid, command, - startTime: `start-${pid}`, + startTime: startToken(pid), purpose: 'verified-managed-web-browser', })), ); @@ -740,7 +747,7 @@ test('an unstable root or intermediate process cannot authorize its descendants' [...pids].map((pid) => [ pid, { - startTime: `start-${pid}`, + startTime: startToken(pid), command: rows.find((row) => row.pid === pid)!.command, zombie: false, }, @@ -753,7 +760,7 @@ test('an unstable root or intermediate process cannot authorize its descendants' [...pids].map((pid) => [ pid, { - startTime: pid === 102 || pid === 104 ? 'changed' : `start-${pid}`, + startTime: pid === 102 || pid === 104 ? LATER_LIFETIME : startToken(pid), command: rows.find((row) => row.pid === pid)!.command, zombie: false, }, @@ -780,7 +787,9 @@ test('recording refuses a scanned command that differs from the bracketed identi observeProcesses([{ pid: 101, command: `${binary} daemon`, executable: binary }]); identitiesMock.mockImplementation( async () => - new Map([[101, { startTime: 'start-101', command: 'different command', zombie: false }]]), + new Map([ + [101, { startTime: startToken(101), command: 'different command', zombie: false }], + ]), ); const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) }; expect((await recordManagedAgentBrowserProcesses(status, store, testHost)).pids).toEqual([]); @@ -844,7 +853,7 @@ test('recording and reaping require executable provenance and matching identity' (_command: string, args: readonly string[]) => { const pid = Number(args[1]); const command = rows.find((row) => row.pid === pid)?.command; - const start = pid === 11003 ? 'changed-start' : `start-${pid}`; + const start = pid === 11003 ? LATER_LIFETIME : startToken(pid); const stdout = args[3] === 'pid=,command=' ? `${pid} ${command}\n` : `${pid} S ${start}\n`; const child = Object.assign(new ChildProcess(), { stdin: new PassThrough(), diff --git a/packages/test-kit/src/host-process-mock.ts b/packages/test-kit/src/host-process-mock.ts index 71dbe0a247..72a2e76c70 100644 --- a/packages/test-kit/src/host-process-mock.ts +++ b/packages/test-kit/src/host-process-mock.ts @@ -17,7 +17,9 @@ export function pinOwnProcessStartTime(hostProcess: HostProcessModule): void { } function installPin(hostProcess: HostProcessModule): void { - const ownStartTime = 'test-process-start-time'; + // A canonical POSIX birth token: the provenanced format host-kit reads on macOS, so a + // different `posix:` token in a record still proves PID reuse while raw renderings do not. + const ownStartTime = 'posix:1763493000000'; vi.spyOn(hostProcess, 'readCurrentOwnerIdentity').mockImplementation(() => ({ pid: process.pid, startTime: ownStartTime, diff --git a/src/__tests__/cli-device-status.test.ts b/src/__tests__/cli-device-status.test.ts index ed1e32800b..a2d178a6df 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -18,6 +18,15 @@ import { pinOwnProcessStartTime(hostProcess); +/** A start time in the same provenanced format as `live` but naming a different lifetime. */ +function staleStartTimeLike(live: string | null): string { + if (live === null) return 'posix:1'; + if (live.startsWith('linux:')) return 'linux:00000000-0000-4000-8000-000000000000:999999999'; + if (live.startsWith('posix:')) return 'posix:1'; + if (/^\d{21}$/.test(live)) return '00000000000000000000'; + return 'posix:1'; +} + test('device status is daemonless and does not send a daemon request', async () => { const result = await runCliCapture(['device', 'status', '--json']); assert.equal(result.code, null); @@ -467,7 +476,9 @@ test('keeps corrupt claims visible and requires --stale for uncertain reclaimabl workspace: '/worktrees/pid-reused', stateDir: process.cwd(), ownerPid: owner.pid, - ownerStartTime: 'different-readable-start-time', + // Same verified format as the live read but a different value, so the pid proves reuse; + // a legacy-format token would be unverified rather than proof. + ownerStartTime: staleStartTimeLike(owner.startTime), ownerToken: 'pid-reused-token', createdAtMs: 1, updatedAtMs: 1, diff --git a/src/__tests__/daemon-exit-wait.test.ts b/src/__tests__/daemon-exit-wait.test.ts index d2bc489a0a..660a9d6940 100644 --- a/src/__tests__/daemon-exit-wait.test.ts +++ b/src/__tests__/daemon-exit-wait.test.ts @@ -5,8 +5,8 @@ import { } from '@agent-device/daemon-contracts/daemon-process'; const DAEMON_COMMAND = '/opt/checkout/dist/src/internal/daemon.js'; -const OURS = 'Mon Aug 24 10:00:00 2026'; -const RECYCLED = 'Mon Aug 24 10:00:07 2026'; +const OURS = 'posix:1000'; +const RECYCLED = 'posix:2000'; const PID = 4242; const TIMEOUT_MS = 1_000; const POLL_MS = 5; diff --git a/src/__tests__/daemon-registration-owner.test.ts b/src/__tests__/daemon-registration-owner.test.ts index fd44acff7b..154869d9de 100644 --- a/src/__tests__/daemon-registration-owner.test.ts +++ b/src/__tests__/daemon-registration-owner.test.ts @@ -230,15 +230,19 @@ test('a log removed between creation and the write-handle reopen fails startup l await owner.finish(report); }); +// A start time in the same provenanced format as the live owner's but a different value, so the +// registration proves replacement; a raw legacy rendering would be unverified, not proof. +const recycledStartTime = ownIdentity.startTime?.startsWith('linux:') + ? 'linux:00000000-0000-0000-0000-000000000000:0' + : ownIdentity.startTime?.startsWith('posix:') + ? 'posix:1' + : ownIdentity.startTime !== null && /^\d{21}$/.test(ownIdentity.startTime) + ? '00000000000000000000' + : 'posix:1'; + for (const [pid, startTime, reason] of [ [999_999_999, 'successor-start', 'replaced'], - [ - process.pid, - process.platform === 'linux' - ? 'linux:00000000-0000-0000-0000-000000000000:0' - : 'recycled-start', - 'replaced', - ], + [process.pid, recycledStartTime, 'replaced'], [process.pid, undefined, 'unproven'], [null, undefined, 'ownerless'], ] as const) { diff --git a/src/platform-runtime-screen-recording-apple-simulator-host.test.ts b/src/platform-runtime-screen-recording-apple-simulator-host.test.ts index 9ddae081a6..5213d87e8c 100644 --- a/src/platform-runtime-screen-recording-apple-simulator-host.test.ts +++ b/src/platform-runtime-screen-recording-apple-simulator-host.test.ts @@ -7,6 +7,13 @@ import { createAppleScreenRecordingHost } from './platform-runtime-screen-record import { startAppleSimulatorRecording } from './platform-runtime-screen-recording-apple-simulator-host.ts'; import { withAppleSimulatorScreenRecordingTransport } from './platform-runtime-screen-recording-apple-transport.ts'; +/** C-form `lstart` token per pid: the verified format, so a differing token proves a different lifetime. */ +function startToken(pid: number): string { + return `Tue Nov 17 19:${String(40 + (pid % 20)).padStart(2, '0')}:${String(pid % 60).padStart(2, '0')} 2026`; +} +/** A C-form start time naming a different lifetime than any `startToken`. */ +const LATER_LIFETIME = 'Wed Nov 18 08:00:00 2026'; + const processes = vi.hoisted(() => ({ alive: new Map(), starts: new Map(), @@ -391,11 +398,11 @@ test('a recorder whose stop was refused can be stopped by the next stop', async // A refused attempt stays refused for that attempt only. Whatever made this one refuse, // the next `record stop` must be able to end the same recorder rather than replay the // rejection for the rest of the session. - processes.starts.set(50, 'start-of-a-different-process'); + processes.starts.set(50, LATER_LIFETIME); await expect(process.terminate()).rejects.toThrow('process ownership changed'); expect(running.kill).not.toHaveBeenCalled(); - processes.starts.set(50, 'start-50'); + processes.starts.set(50, startToken(50)); await expect(process.terminate()).resolves.toBeUndefined(); expect(running.kill).toHaveBeenCalledWith('SIGINT'); }); @@ -462,7 +469,7 @@ function background(pid: number | undefined, command?: string) { }); if (pid !== undefined) { processes.alive.set(pid, true); - processes.starts.set(pid, `start-${pid}`); + processes.starts.set(pid, startToken(pid)); processes.commands.set(pid, command ?? `xcrun simctl io ${simulator.id} recordVideo`); } const kill = vi.fn((_signal: NodeJS.Signals) => {