From 70f0b17800b063caacd56e04fff569a58d9d429b Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Wed, 18 Nov 2026 06:45:15 -0400 Subject: [PATCH 1/6] fix(host-kit): pin ps lstart reads to the C locale ps -o lstart prints weekday and month names in the caller's locale, so a daemon and a client under different LC_TIME compared one start time as different lifetimes and daemon stop orphaned a live daemon on macOS. Run the ps identity reads with LC_ALL=C and treat a C-form start time against a localized one as unknown instead of reassigned. Fixes #4656 --- .../internal/host-process-liveness.test.ts | 34 +++++++++++++++++++ .../host-kit/src/internal/host-process.ts | 22 +++++++----- .../host-kit/src/internal/ps-start-time.ts | 27 +++++++++++++++ 3 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 packages/host-kit/src/internal/ps-start-time.ts 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..4a5941bc83 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -19,6 +19,7 @@ import { readProcessStartTime, readProcessIdentities, readProcessIdentityFacts, + processStartTimesDiffer, } from './host-process.ts'; import { mockLinuxProcessStatAbsent } from './host-proc.fixtures.ts'; @@ -363,3 +364,36 @@ test.skipIf(process.platform !== 'linux')( } }, ); + +test('every ps start-time read pins the C locale so one process reads the same from any caller', async () => { + psReturns('4242 Ss Mon Aug 10 20:00:00 2026\n'); + mockRunCmd.mockResolvedValue({ + stdout: '4242 Ss Mon Aug 10 20:00:00 2026\n', + stderr: '', + exitCode: 0, + }); + + readHostProcessIdentityObservations([4242]); + await readHostProcessIdentityObservationsAsync([4242]); + psReturns('Mon Aug 10 20:00:00 2026\n'); + readProcessStartTime(4242); + + const calls = [...mockRunCmdSync.mock.calls, ...mockRunCmd.mock.calls]; + assert.equal(calls.length, 3); + for (const call of calls) assert.equal(call[2]?.env?.LC_ALL, 'C'); +}); + +test('a localized start time against its C-locale rendering is unknown, not a different lifetime', () => { + assert.equal( + processStartTimesDiffer('mar. 17 nov. 19:42:27 2026', 'Tue Nov 17 19:42:27 2026'), + false, + ); + assert.equal( + processStartTimesDiffer('Tue Nov 17 19:42:27 2026', 'mar. 17 nov. 19:42:27 2026'), + false, + ); + assert.equal( + processStartTimesDiffer('Tue Nov 17 19:42:27 2026', 'Tue Nov 17 19:42:28 2026'), + true, + ); +}); diff --git a/packages/host-kit/src/internal/host-process.ts b/packages/host-kit/src/internal/host-process.ts index f7533107ae..d5028f5383 100644 --- a/packages/host-kit/src/internal/host-process.ts +++ b/packages/host-kit/src/internal/host-process.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import type { ExecOptions, ExecResult } from './exec.ts'; import { runCmd, runCmdSync, withoutCommandExecutorOverride } from './exec.ts'; +import { psReadOptions, psStartTimesLocaleMismatch } from './ps-start-time.ts'; import { sleep } from './retry.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; @@ -196,7 +197,7 @@ async function runHostPsAsync( parse: (stdout: string) => Row[], ): Promise { try { - const result = await runCmd(hostPsCommand(), args, { allowFailure: true, timeoutMs }); + const result = await runCmd(hostPsCommand(), args, psReadOptions(timeoutMs)); return result.exitCode !== 0 ? [] : parse(result.stdout); } catch { // A failed ps read is unknown evidence; callers remain fail-closed. @@ -247,6 +248,7 @@ export function processStartTimesDiffer( ): boolean { if (!left || !right) return false; if (left.startsWith('linux:') !== right.startsWith('linux:')) return false; + if (psStartTimesLocaleMismatch(left, right)) return false; return left !== right; } @@ -332,10 +334,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), + psReadOptions(PS_TIMEOUT_MS), + ); return result.exitCode !== 0 ? [] : parseHostProcessIdentityRows(result.stdout); } catch { // A failed ps snapshot is unknown evidence; callers remain fail-closed. @@ -392,10 +395,11 @@ 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, - }); + const result = runCmdSync( + hostPsCommand(), + ['-p', String(pid), '-o', field], + psReadOptions(PS_TIMEOUT_MS), + ); return processFieldValue(result); } catch { return null; diff --git a/packages/host-kit/src/internal/ps-start-time.ts b/packages/host-kit/src/internal/ps-start-time.ts new file mode 100644 index 0000000000..f16e4fe5c9 --- /dev/null +++ b/packages/host-kit/src/internal/ps-start-time.ts @@ -0,0 +1,27 @@ +import type { ExecOptions } from './exec.ts'; + +/** + * `ps -o lstart` spells weekday and month names in the caller's locale, so one start time reads + * differently from a daemon and a client run under different `LANG`/`LC_TIME`. Pin the C form. + */ +const PS_C_LOCALE_ENV: NodeJS.ProcessEnv = { LC_ALL: 'C' }; + +/** Options for a `ps` read: failure is unknown evidence, and the output is locale-free. */ +export function psReadOptions(timeoutMs: number): ExecOptions { + return { allowFailure: true, timeoutMs, env: PS_C_LOCALE_ENV }; +} + +const PS_START_TIME_C_FORM = /^[A-Za-z]{3} [A-Za-z]{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/; +const CLOCK_TIME = /\d{2}:\d{2}:\d{2}/; + +/** + * A record written before `ps` was pinned to the C locale may hold a localized rendering of the + * same start time. A C-form string against a localized one proves nothing about the lifetime. + */ +export function psStartTimesLocaleMismatch(left: string, right: string): boolean { + return ( + PS_START_TIME_C_FORM.test(left) !== PS_START_TIME_C_FORM.test(right) && + CLOCK_TIME.test(left) && + CLOCK_TIME.test(right) + ); +} From 1a9d35837d275047044e1cadeb50d1795bd421b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 20:31:18 +0100 Subject: [PATCH 2/6] fix(host-kit): pin only lstart-bearing ps reads and keep legacy timestamps unverified MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the blocking review on #4682: - The LC_ALL=C pin now applies only to ps reads whose output carries lstart (HOST_PROCESS_IDENTITY_PS_ARGS sync/async and readProcessField('lstart=')). The pid=,command= batch read and readProcessField('command='/'state=') keep the caller's locale, so command text reads with one encoding from every host-kit caller, matching the unpinned listHostProcesses scan. BSD/macOS ps escapes non-ASCII argv bytes under LC_ALL=C (/tmp/é-ü -> /tmp/M-CM-)-M-CM-<), which broke managed-process ownership for non-ASCII paths. - The pin is a final override on top of the effective child environment (new effectiveChildEnv in exec.ts), so TZ and the rest of the child env survive: replacing the whole env dropped TZ and rendered lstart in the host zone under the pin (verified live: TZ=Pacific/Kiritimati record Thu Nov 19 09:29:21 2026 vs no-TZ read Wed Nov 18 20:29:21). - processStartTimesDiffer proves a different lifetime only when both sides share one verified format (linux: token, C-form lstart, Windows invariant stamp). A legacy localized record — with or without a colon-separated clock, e.g. mer. 18 nov. 20:29:43 2026 or 18 nov. 2026 — is unverified: never declared exited at daemon stop, never a signal authorization. Regressions: pin scope + UTF-8 command reads + TZ retention in host-process-liveness.test.ts, legacy verdicts in host-process.test.ts and owner-identity*.test.ts, and at the daemon stop boundary in daemon-process-takeover.test.ts (legacy record -> retained identity-unverified with the daemon alive; non-ASCII argv reads as UTF-8). Token-based reuse tests now use verified-format tokens. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .../__tests__/daemon-client-lifecycle.test.ts | 12 +- .../src/daemon-process-takeover.test.ts | 120 ++++++++++++++++- .../src/daemon-registration.test.ts | 19 ++- .../src/device-claim-settlement.test.ts | 9 +- .../device/__tests__/device-claims.test.ts | 8 +- .../server/http/daemon-metadata-loss.test.ts | 19 +-- packages/host-kit/src/internal/exec.ts | 13 ++ .../internal/host-process-liveness.test.ts | 127 ++++++++++++++---- .../src/internal/host-process-windows.test.ts | 8 +- .../src/internal/host-process.test.ts | 44 +++++- .../host-kit/src/internal/host-process.ts | 59 ++++++-- .../internal/owner-identity-liveness.test.ts | 14 +- .../src/internal/owner-identity.test.ts | 33 ++++- .../host-kit/src/internal/ps-start-time.ts | 32 ++--- .../agent-browser-process-record.test.ts | 32 +++-- .../src/agent-browser-lifecycle.test.ts | 27 ++-- packages/test-kit/src/host-process-mock.ts | 4 +- src/__tests__/cli-device-status.test.ts | 12 +- .../daemon-registration-owner.test.ts | 16 ++- ...een-recording-apple-simulator-host.test.ts | 13 +- 20 files changed, 500 insertions(+), 121 deletions(-) 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..2185cb10f5 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,14 @@ 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 !== null && /^\d{21}$/.test(liveStartTime) + ? '00000000000000000000' + : 'Thu Jan 1 00:00:00 1970'; 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..dfee61e205 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,59 @@ 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 verified 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 (/^\d{21}$/.test(live)) return '00000000000000000000'; + return live.replace(/\d{4}$/, '1970'); +} + +const FRENCH_MONTHS: Record = { + Jan: 'janv.', + Feb: 'févr.', + Mar: 'mars', + Apr: 'avr.', + May: 'mai', + Jun: 'juin', + Jul: 'juil.', + Aug: 'août', + Sep: 'sept.', + Oct: 'oct.', + Nov: 'nov.', + Dec: 'déc.', +}; +const FRENCH_WEEKDAYS: Record = { + Mon: 'lun.', + Tue: 'mar.', + Wed: 'mer.', + Thu: 'jeu.', + Fri: 'ven.', + Sat: 'sam.', + Sun: 'dim.', +}; +const C_FORM_LSTART = /^(\w{3}) (\w{3}) +(\d{1,2}) (\d{2}:\d{2}:\d{2}) (\d{4})$/; + +/** The fr_FR `ps -o lstart` rendering of a C-form start time, clock included. */ +function frenchLstart(cForm: string): string { + const match = C_FORM_LSTART.exec(cForm); + assert.ok(match, `expected a C-form lstart, got ${cForm}`); + const [, weekday, month, day, clock, year] = match; + return `${FRENCH_WEEKDAYS[weekday] ?? weekday} ${day} ${FRENCH_MONTHS[month] ?? month} ${clock} ${year}`; +} + +/** A localized rendering with no colon-separated clock, as locales that omit HH:mm:ss print. */ +function frenchDateOnlyLstart(cForm: string): string { + const match = C_FORM_LSTART.exec(cForm); + assert.ok(match, `expected a C-form lstart, got ${cForm}`); + const [, , month, day, , year] = match; + return `${day} ${FRENCH_MONTHS[month] ?? month} ${year}`; +} + // #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 +153,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 +169,54 @@ 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 C-locale pin may hold a localized `lstart` rendering. At +// the daemon stop boundary it must 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-locale 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(C_FORM_LSTART.test(startTime), `expected a C-form lstart, got ${startTime}`); + + for (const legacy of [frenchLstart(startTime), frenchDateOnlyLstart(startTime)]) { + 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-registration.test.ts b/packages/daemon-contracts/src/daemon-registration.test.ts index f4ba3894d0..8009e989f9 100644 --- a/packages/daemon-contracts/src/daemon-registration.test.ts +++ b/packages/daemon-contracts/src/daemon-registration.test.ts @@ -57,12 +57,25 @@ test('a different published pid proves the owner no longer serves its state dir' test('a published start time proves supersession only when both sides are readable', () => { const stateDir = useStateDir(); - publishDaemonRegistration(stateDir, { pid: 4242, startTime: 'successor-start' }); - assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'owner-start' }), true); + // Two C-form renderings one second apart are the same verified format with different values, + // so the difference proves the pid changed hands. + publishDaemonRegistration(stateDir, { pid: 4242, startTime: 'Tue Nov 17 19:42:28 2026' }); + assert.equal( + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'Tue Nov 17 19:42:27 2026' }), + true, + ); + // A legacy localized rendering beside a C-form read is unverified, not a proved supersession. + assert.equal( + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'mar. 17 nov. 19:42:28 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: 'Tue Nov 17 19:42:27 2026' }), + 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..9a5a937f36 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: 'Tue Nov 17 19:42:28 2026' }), + ); 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..c73820078d 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 verified C-locale format: PID reuse, + // uncertain ownership. A legacy-format token would be unverified, not reuse. + fs.writeFileSync( + claimPath(root), + JSON.stringify({ ...stored, ownerStartTime: 'Tue Nov 17 19:42:28 2026' }), + ); // 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..6f99cc30b6 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 C-form `lstart` rendering: the verified format, so a different C-form token proves a recycle. +const OWN = { pid: OWN_PID, startTime: 'Tue Nov 17 19:42:27 2026' } 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, 'Tue Nov 17 19:42:28 2026'); 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); @@ -123,7 +124,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 +146,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 +168,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.ts b/packages/host-kit/src/internal/exec.ts index e9611933a6..2905babada 100644 --- a/packages/host-kit/src/internal/exec.ts +++ b/packages/host-kit/src/internal/exec.ts @@ -160,6 +160,19 @@ function resolveSpawnEnv(env: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv return { ...(env ?? scope.host.env), ...scope.requestEnv }; } +/** + * The environment a command spawned without an explicit `env` receives — the bound host scope's + * environment with the request's values on top, or the process's own outside a scope — with + * `overrides` applied as the final word. Use this to pin one child variable, such as the C locale + * of a `ps -o lstart` read, without dropping the rest: `TZ` picks the zone `lstart` renders in, so + * replacing the whole environment would move the identity clock under the pin. + */ +export function effectiveChildEnv(overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { + const scope = commandHostScope.getStore(); + if (!scope) return { ...process.env, ...overrides }; + return { ...scope.host.env, ...scope.requestEnv, ...overrides }; +} + export async function runCmd( cmd: string, args: readonly string[], 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 4a5941bc83..37f8648354 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -14,8 +14,10 @@ vi.mock('./exec.ts', async () => { import { isProcessZombie, + listHostProcesses, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, + readProcessCommand, readProcessStartTime, readProcessIdentities, readProcessIdentityFacts, @@ -365,35 +367,112 @@ test.skipIf(process.platform !== 'linux')( }, ); -test('every ps start-time read pins the C locale so one process reads the same from any caller', async () => { - psReturns('4242 Ss Mon Aug 10 20:00:00 2026\n'); - mockRunCmd.mockResolvedValue({ - stdout: '4242 Ss Mon Aug 10 20:00:00 2026\n', - stderr: '', - exitCode: 0, - }); +/** The `-o` value of a ps call: `lstart=`-bearing reads pin the locale, 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; command and state reads keep the caller locale', 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 is pinned, + // and no command-text read is. + const utf8Command = '/Users/mich/é/ü/agent-device/dist/src/internal/daemon.js'; + const escapeLikeCLocalePs = (text: string) => + text.replaceAll(/[^\x20-\x7E]/g, (ch) => `M-C${ch}`); + const commandFor = (options?: { env?: NodeJS.ProcessEnv }) => + options?.env?.LC_ALL === 'C' ? escapeLikeCLocalePs(utf8Command) : utf8Command; + mockRunCmdSync.mockImplementation( + (_cmd: string, args: readonly string[], options?: { env?: 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?: { env?: 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]); - psReturns('Mon Aug 10 20:00:00 2026\n'); - readProcessStartTime(4242); + await readProcessIdentityFacts(4242); + assert.equal(readProcessStartTime(4242), 'Mon Aug 10 20:00:00 2026'); + 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.equal(calls.length, 3); - for (const call of calls) assert.equal(call[2]?.env?.LC_ALL, 'C'); + assert.ok(calls.length > 0); + let sawCommandRead = false; + for (const call of calls) { + const field = psFieldOf(call[1] ?? []); + if (field.includes('lstart=')) { + assert.equal(call[2]?.env?.LC_ALL, 'C', `lstart-bearing read (${field}) must pin LC_ALL=C`); + } else { + sawCommandRead ||= field.includes('command='); + assert.equal( + call[2]?.env, + undefined, + `non-lstart read (${field}) must carry no env pin, so command text keeps one encoding`, + ); + } + } + assert.ok(sawCommandRead, 'the pid=,command= batch read must have run'); }); -test('a localized start time against its C-locale rendering is unknown, not a different lifetime', () => { - assert.equal( - processStartTimesDiffer('mar. 17 nov. 19:42:27 2026', 'Tue Nov 17 19:42:27 2026'), - false, - ); - assert.equal( - processStartTimesDiffer('Tue Nov 17 19:42:27 2026', 'mar. 17 nov. 19:42:27 2026'), - false, - ); - assert.equal( - processStartTimesDiffer('Tue Nov 17 19:42:27 2026', 'Tue Nov 17 19:42:28 2026'), - true, - ); +test('the pinned lstart read overrides only LC_ALL on top of the effective child environment', () => { + vi.stubEnv('TZ', 'Pacific/Kiritimati'); + try { + psReturns('Mon Aug 10 20:00:00 2026\n'); + readProcessStartTime(4242); + + const env = mockRunCmdSync.mock.calls[0]?.[2]?.env; + assert.equal(env?.LC_ALL, 'C'); + assert.equal( + env?.TZ, + 'Pacific/Kiritimati', + 'dropping TZ would render lstart in the wrong zone under the pin', + ); + assert.deepEqual(env, { ...process.env, LC_ALL: 'C' }); + } finally { + vi.unstubAllEnvs(); + } +}); + +test('only two start times in the same verified 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 + // A legacy rendering beside a C-form read is unverified, never a different lifetime. + assert.equal(processStartTimesDiffer(french, cForm), false); + assert.equal(processStartTimesDiffer(cForm, french), false); + assert.equal(processStartTimesDiffer(frenchNoClock, cForm), false); + assert.equal(processStartTimesDiffer(cForm, frenchNoClock), false); + // Two different legacy renderings are not comparable either. + assert.equal(processStartTimesDiffer(french, norwegian), false); + assert.equal(processStartTimesDiffer(french, frenchNoClock), false); + // Two values in one verified format still prove a difference. + assert.equal(processStartTimesDiffer(cForm, 'Tue Nov 17 19:42:28 2026'), 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, 'linux:boot:1'), false); + assert.equal(processStartTimesDiffer(french, 'linux:boot:1'), false); + assert.equal(processStartTimesDiffer(cForm, null), false); + assert.equal(processStartTimesDiffer(cForm, cForm), false); }); 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..d1e3cb4a52 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 verified C-locale format', + { startTime: 'Tue Nov 17 19:42:27 2026', matches: true }, + ['Tue Nov 17 19:42:28 2026', 'recorded'], 'reassigned', ], [ @@ -195,3 +195,41 @@ test('judgeProcessIdentity reads a zombie as exited whatever else the host says' 'exited', ); }); + +test('judgeProcessIdentity treats a legacy-locale record against a C-locale read as unverified', () => { + // Records written before the C-locale pin hold a localized `ps -o lstart` rendering: fr_FR + // prints `mar. 17 nov. 19:42:27 2026`, and locales that omit HH:mm:ss print no clock at all. + // Neither proves a different lifetime, so the verdict is unverified — never reassigned, and + // never permission to signal. + const facts = { startTime: 'Tue Nov 17 19:42:27 2026', 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', + ); +}); + +test('judgeProcessIdentity still proves reuse between two C-locale reads', () => { + assert.equal( + judgeProcessIdentity( + { startTime: 'Tue Nov 17 19:42:27 2026' }, + { startTime: 'Tue Nov 17 19:42:28 2026', command: null, zombie: false }, + ), + 'reassigned', + ); +}); + +test('judgeProcessIdentity matches a non-ASCII command read byte for byte', () => { + const command = '/Users/mich/é/ü/agent-device/dist/src/internal/daemon.js'; + assert.equal( + judgeProcessIdentity( + { startTime: 'Tue Nov 17 19:42:27 2026', matches: (observed) => observed === command }, + { startTime: 'Tue Nov 17 19:42:27 2026', command, zombie: false }, + ), + 'ours', + ); +}); diff --git a/packages/host-kit/src/internal/host-process.ts b/packages/host-kit/src/internal/host-process.ts index d5028f5383..b1448fc5d3 100644 --- a/packages/host-kit/src/internal/host-process.ts +++ b/packages/host-kit/src/internal/host-process.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import type { ExecOptions, ExecResult } from './exec.ts'; import { runCmd, runCmdSync, withoutCommandExecutorOverride } from './exec.ts'; -import { psReadOptions, psStartTimesLocaleMismatch } from './ps-start-time.ts'; +import { psLstartReadOptions, psReadOptions } from './ps-start-time.ts'; import { sleep } from './retry.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; @@ -172,8 +172,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])); @@ -193,11 +201,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, psReadOptions(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. @@ -241,14 +249,41 @@ function readLinuxProcessStat(pid: number): { state: string; startTime: string } } } -/** Positive proof of different lifetimes; unreadable or mixed-format records prove nothing. */ +/** + * The `ps -o lstart=` rendering printed under the pinned C locale, e.g. `Tue Nov 17 19:42:27 2026`. + */ +const PS_START_TIME_C_FORM = /^[A-Za-z]{3} [A-Za-z]{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/; +/** The invariant-culture CIM birth stamp a Windows host reads: `yyyyMMddHHmmssfffffff`. */ +const WINDOWS_START_TIME = /^\d{21}$/; + +/** + * The format of a recorded start time. Only the formats host-kit itself reads are verified: the + * `linux:` token of one /proc read, the pinned C-form `lstart`, and the Windows invariant stamp. + * Anything else is a legacy record — written by an older build whose `ps` ran under another + * locale, such as `mar. 17 nov. 19:42:27 2026` or a rendering with no colon-separated clock — and + * its text cannot be compared against another format. + */ +function psStartTimeFormat(value: string): 'linux' | 'c-lstart' | 'windows' | 'legacy' { + if (value.startsWith('linux:')) return 'linux'; + if (PS_START_TIME_C_FORM.test(value)) return 'c-lstart'; + if (WINDOWS_START_TIME.test(value)) return 'windows'; + return 'legacy'; +} + +/** + * Positive proof of different lifetimes. Unreadable values prove nothing, and a difference proves + * exit only when both sides share one verified format: a legacy localized rendering beside a + * C-form read, or beside another legacy rendering, is unverified evidence, never proof that the + * recorded process is gone. + */ 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; - if (psStartTimesLocaleMismatch(left, right)) return false; + const leftFormat = psStartTimeFormat(left); + if (leftFormat !== psStartTimeFormat(right)) return false; + if (leftFormat === 'legacy') return false; return left !== right; } @@ -337,7 +372,7 @@ function readHostProcessIdentityRowsSync( const result = runCmdSync( hostPsCommand(), HOST_PROCESS_IDENTITY_PS_ARGS(pids), - psReadOptions(PS_TIMEOUT_MS), + psLstartReadOptions(PS_TIMEOUT_MS), ); return result.exitCode !== 0 ? [] : parseHostProcessIdentityRows(result.stdout); } catch { @@ -356,7 +391,7 @@ async function readHostProcessIdentityRowsAsync( } return await runHostPsAsync( HOST_PROCESS_IDENTITY_PS_ARGS(pids), - PS_TIMEOUT_MS, + psLstartReadOptions(PS_TIMEOUT_MS), parseHostProcessIdentityRows, ); } @@ -398,7 +433,9 @@ function readProcessField(pid: number, field: HostProcessField): string | null { const result = runCmdSync( hostPsCommand(), ['-p', String(pid), '-o', field], - psReadOptions(PS_TIMEOUT_MS), + // Only the lstart-bearing read is locale-pinned; command and state keep the caller's + // locale so their text matches the unpinned listHostProcesses read byte for byte. + field === 'lstart=' ? psLstartReadOptions(PS_TIMEOUT_MS) : psReadOptions(PS_TIMEOUT_MS), ); return processFieldValue(result); } catch { 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..151e5aaa8d 100644 --- a/packages/host-kit/src/internal/owner-identity-liveness.test.ts +++ b/packages/host-kit/src/internal/owner-identity-liveness.test.ts @@ -53,13 +53,23 @@ 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 verified format: two C-form renderings one second apart. + mockReadProcessStartTime.mockReturnValue('Tue Nov 17 19:42:28 2026'); assert.equal( - classifyOwnerLiveness({ owner: { pid: OWNER_PID, startTime: 'start-a' } }), + classifyOwnerLiveness({ owner: { pid: OWNER_PID, startTime: 'Tue Nov 17 19:42:27 2026' } }), 'owner-process-reused', ); }); +test('a legacy-locale record beside a C-locale read stays live, never reused', () => { + // `mar. 17 nov. 19:42:27 2026` (fr_FR) and `17 nov. 2026` (no colon-separated clock) are + // renderings an older build could have recorded; neither proves the pid changed hands. + for (const legacy of ['mar. 17 nov. 19:42:27 2026', '17 nov. 2026']) { + mockReadProcessStartTime.mockReturnValue('Tue Nov 17 19:42:27 2026'); + 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'], ['linux:11111111-1111-4111-8111-111111111111:12345', 'Mon Aug 10 20:00:00 2026'], diff --git a/packages/host-kit/src/internal/owner-identity.test.ts b/packages/host-kit/src/internal/owner-identity.test.ts index 14ff2450a3..ed18b86590 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 verified format as the live read but + // with a different value: the `linux:` token on Linux, the CIM stamp on Windows, the pinned + // C-form `lstart` on macOS. + const liveStartTime = readProcessStartTime(process.pid); + const staleStartTime = liveStartTime?.startsWith('linux:') + ? 'linux:other-boot:1' + : liveStartTime !== null && /^\d{21}$/.test(liveStartTime) + ? '00000000000000000000' + : 'Thu Jan 1 00:00:00 1970'; 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,17 @@ 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 verified C-locale format with different values prove a reuse. + assert.equal( + differs( + { pid: 1, startTime: 'Mon Aug 10 20:00:00 2026' }, + { pid: 1, startTime: 'Mon Aug 10 20:00:01 2026' }, + ), + true, + ); + // 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 +90,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/ps-start-time.ts b/packages/host-kit/src/internal/ps-start-time.ts index f16e4fe5c9..3c7ac3f219 100644 --- a/packages/host-kit/src/internal/ps-start-time.ts +++ b/packages/host-kit/src/internal/ps-start-time.ts @@ -1,27 +1,27 @@ -import type { ExecOptions } from './exec.ts'; +import { effectiveChildEnv, type ExecOptions } from './exec.ts'; /** * `ps -o lstart` spells weekday and month names in the caller's locale, so one start time reads - * differently from a daemon and a client run under different `LANG`/`LC_TIME`. Pin the C form. + * differently from a daemon and a client run under different `LANG`/`LC_TIME`. Every `ps` read + * whose output carries `lstart` runs with this pin. */ -const PS_C_LOCALE_ENV: NodeJS.ProcessEnv = { LC_ALL: 'C' }; +const PS_LSTART_LOCALE_PIN: NodeJS.ProcessEnv = { LC_ALL: 'C' }; -/** Options for a `ps` read: failure is unknown evidence, and the output is locale-free. */ +/** + * Options for a `ps` read whose output does not carry `lstart`: failure is unknown evidence, and + * the caller's locale stays in charge of the output. + */ export function psReadOptions(timeoutMs: number): ExecOptions { - return { allowFailure: true, timeoutMs, env: PS_C_LOCALE_ENV }; + return { allowFailure: true, timeoutMs }; } -const PS_START_TIME_C_FORM = /^[A-Za-z]{3} [A-Za-z]{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/; -const CLOCK_TIME = /\d{2}:\d{2}:\d{2}/; - /** - * A record written before `ps` was pinned to the C locale may hold a localized rendering of the - * same start time. A C-form string against a localized one proves nothing about the lifetime. + * Options for a `ps` read whose output carries `lstart`: failure is unknown evidence, and the C + * locale is pinned as the final override on top of the effective child environment, so `TZ` and + * the rest of the environment survive the pin. Command-text reads must not use this: BSD/macOS + * `ps` escapes non-ASCII argv bytes under `LC_ALL=C`, and every command read in host-kit has to + * keep the same encoding as `listHostProcesses`, which runs unpinned. */ -export function psStartTimesLocaleMismatch(left: string, right: string): boolean { - return ( - PS_START_TIME_C_FORM.test(left) !== PS_START_TIME_C_FORM.test(right) && - CLOCK_TIME.test(left) && - CLOCK_TIME.test(right) - ); +export function psLstartReadOptions(timeoutMs: number): ExecOptions { + return { allowFailure: true, timeoutMs, env: effectiveChildEnv(PS_LSTART_LOCALE_PIN) }; } 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..5ff05ead6c 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 { +/** 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'; + +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..4da6412dac 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 `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 { 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..2121a285ad 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 C-form `ps -o lstart` rendering: the one verified format host-kit reads on macOS, so a + // different C-form token in a record still proves PID reuse while legacy renderings do not. + const ownStartTime = 'Tue Nov 17 19:42:27 2026'; 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..8cf6b86a23 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -18,6 +18,14 @@ import { pinOwnProcessStartTime(hostProcess); +/** A start time in the same verified format as `live` but naming a different lifetime. */ +function staleStartTimeLike(live: string | null): string { + if (live === null) return 'Thu Jan 1 00:00:00 1970'; + if (live.startsWith('linux:')) return 'linux:00000000-0000-4000-8000-000000000000:999999999'; + if (/^\d{21}$/.test(live)) return '00000000000000000000'; + return live.replace(/\d{4}$/, '1970'); +} + 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 +475,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-registration-owner.test.ts b/src/__tests__/daemon-registration-owner.test.ts index fd44acff7b..de46407690 100644 --- a/src/__tests__/daemon-registration-owner.test.ts +++ b/src/__tests__/daemon-registration-owner.test.ts @@ -230,15 +230,17 @@ test('a log removed between creation and the write-handle reopen fails startup l await owner.finish(report); }); +// A start time in the same verified format as the live owner's but a different value, so the +// registration proves replacement; a legacy-format token would be unverified, not proof. +const recycledStartTime = ownIdentity.startTime?.startsWith('linux:') + ? 'linux:00000000-0000-0000-0000-000000000000:0' + : ownIdentity.startTime !== null && /^\d{21}$/.test(ownIdentity.startTime) + ? '00000000000000000000' + : 'Thu Jan 1 00:00:00 1970'; + 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) => { From f88ff09be5748fe95e05095c061a89619f56dd65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 20:41:14 +0100 Subject: [PATCH 3/6] fix(host-kit): keep host-process.ts under the max-lines cap and typecheck the lstart helpers Move the start-time format classification and processStartTimesDiffer into ps-start-time.ts (re-exported through the process barrel) so host-process.ts stays under 1000 lines, and use non-null match groups in the takeover test's locale helpers. Also replaces hex escapes with Unicode escapes in the liveness test. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .../src/daemon-process-takeover.test.ts | 10 ++++- .../internal/host-process-liveness.test.ts | 4 +- .../host-kit/src/internal/host-process.ts | 43 +------------------ .../host-kit/src/internal/owner-identity.ts | 2 +- .../host-kit/src/internal/ps-start-time.ts | 38 ++++++++++++++++ packages/host-kit/src/process.ts | 2 +- 6 files changed, 52 insertions(+), 47 deletions(-) diff --git a/packages/daemon-contracts/src/daemon-process-takeover.test.ts b/packages/daemon-contracts/src/daemon-process-takeover.test.ts index dfee61e205..1342cf9fa9 100644 --- a/packages/daemon-contracts/src/daemon-process-takeover.test.ts +++ b/packages/daemon-contracts/src/daemon-process-takeover.test.ts @@ -101,7 +101,11 @@ const C_FORM_LSTART = /^(\w{3}) (\w{3}) +(\d{1,2}) (\d{2}:\d{2}:\d{2}) (\d{4})$/ function frenchLstart(cForm: string): string { const match = C_FORM_LSTART.exec(cForm); assert.ok(match, `expected a C-form lstart, got ${cForm}`); - const [, weekday, month, day, clock, year] = match; + const weekday = match[1]!; + const month = match[2]!; + const day = match[3]!; + const clock = match[4]!; + const year = match[5]!; return `${FRENCH_WEEKDAYS[weekday] ?? weekday} ${day} ${FRENCH_MONTHS[month] ?? month} ${clock} ${year}`; } @@ -109,7 +113,9 @@ function frenchLstart(cForm: string): string { function frenchDateOnlyLstart(cForm: string): string { const match = C_FORM_LSTART.exec(cForm); assert.ok(match, `expected a C-form lstart, got ${cForm}`); - const [, , month, day, , year] = match; + const month = match[2]!; + const day = match[3]!; + const year = match[5]!; return `${day} ${FRENCH_MONTHS[month] ?? month} ${year}`; } 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 37f8648354..24e1129e88 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -21,8 +21,8 @@ import { readProcessStartTime, readProcessIdentities, readProcessIdentityFacts, - processStartTimesDiffer, } from './host-process.ts'; +import { processStartTimesDiffer } from './ps-start-time.ts'; import { mockLinuxProcessStatAbsent } from './host-proc.fixtures.ts'; function psReturns(stdout: string, exitCode = 0): void { @@ -379,7 +379,7 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th // and no command-text read is. const utf8Command = '/Users/mich/é/ü/agent-device/dist/src/internal/daemon.js'; const escapeLikeCLocalePs = (text: string) => - text.replaceAll(/[^\x20-\x7E]/g, (ch) => `M-C${ch}`); + text.replaceAll(/[^\u0020-\u007E]/g, (ch) => `M-C${ch}`); const commandFor = (options?: { env?: NodeJS.ProcessEnv }) => options?.env?.LC_ALL === 'C' ? escapeLikeCLocalePs(utf8Command) : utf8Command; mockRunCmdSync.mockImplementation( diff --git a/packages/host-kit/src/internal/host-process.ts b/packages/host-kit/src/internal/host-process.ts index b1448fc5d3..69abf4a699 100644 --- a/packages/host-kit/src/internal/host-process.ts +++ b/packages/host-kit/src/internal/host-process.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import type { ExecOptions, ExecResult } from './exec.ts'; import { runCmd, runCmdSync, withoutCommandExecutorOverride } from './exec.ts'; -import { psLstartReadOptions, psReadOptions } from './ps-start-time.ts'; +import { psLstartReadOptions, psReadOptions, processStartTimesDiffer } from './ps-start-time.ts'; import { sleep } from './retry.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; @@ -249,44 +249,6 @@ function readLinuxProcessStat(pid: number): { state: string; startTime: string } } } -/** - * The `ps -o lstart=` rendering printed under the pinned C locale, e.g. `Tue Nov 17 19:42:27 2026`. - */ -const PS_START_TIME_C_FORM = /^[A-Za-z]{3} [A-Za-z]{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/; -/** The invariant-culture CIM birth stamp a Windows host reads: `yyyyMMddHHmmssfffffff`. */ -const WINDOWS_START_TIME = /^\d{21}$/; - -/** - * The format of a recorded start time. Only the formats host-kit itself reads are verified: the - * `linux:` token of one /proc read, the pinned C-form `lstart`, and the Windows invariant stamp. - * Anything else is a legacy record — written by an older build whose `ps` ran under another - * locale, such as `mar. 17 nov. 19:42:27 2026` or a rendering with no colon-separated clock — and - * its text cannot be compared against another format. - */ -function psStartTimeFormat(value: string): 'linux' | 'c-lstart' | 'windows' | 'legacy' { - if (value.startsWith('linux:')) return 'linux'; - if (PS_START_TIME_C_FORM.test(value)) return 'c-lstart'; - if (WINDOWS_START_TIME.test(value)) return 'windows'; - return 'legacy'; -} - -/** - * Positive proof of different lifetimes. Unreadable values prove nothing, and a difference proves - * exit only when both sides share one verified format: a legacy localized rendering beside a - * C-form read, or beside another legacy rendering, is unverified evidence, never proof that the - * recorded process is gone. - */ -export function processStartTimesDiffer( - left: string | null | undefined, - right: string | null | undefined, -): boolean { - if (!left || !right) return false; - const leftFormat = psStartTimeFormat(left); - if (leftFormat !== psStartTimeFormat(right)) return false; - if (leftFormat === 'legacy') return false; - return left !== right; -} - export function readProcessStartTime(pid: number): string | null { return readProcessField(pid, 'lstart='); } @@ -433,8 +395,7 @@ function readProcessField(pid: number, field: HostProcessField): string | null { const result = runCmdSync( hostPsCommand(), ['-p', String(pid), '-o', field], - // Only the lstart-bearing read is locale-pinned; command and state keep the caller's - // locale so their text matches the unpinned listHostProcesses read byte for byte. + // 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), ); return processFieldValue(result); diff --git a/packages/host-kit/src/internal/owner-identity.ts b/packages/host-kit/src/internal/owner-identity.ts index c5c16e08ea..e14d6665ba 100644 --- a/packages/host-kit/src/internal/owner-identity.ts +++ b/packages/host-kit/src/internal/owner-identity.ts @@ -1,7 +1,6 @@ import fs from 'node:fs'; import { isProcessAlive, - processStartTimesDiffer, isProcessZombie, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, @@ -9,6 +8,7 @@ import { readProcessStartTime, type HostProcessIdentityObservation, } from './host-process.ts'; +import { processStartTimesDiffer } from './ps-start-time.ts'; export type OwnerIdentity = { pid: number; diff --git a/packages/host-kit/src/internal/ps-start-time.ts b/packages/host-kit/src/internal/ps-start-time.ts index 3c7ac3f219..ae6e42d264 100644 --- a/packages/host-kit/src/internal/ps-start-time.ts +++ b/packages/host-kit/src/internal/ps-start-time.ts @@ -25,3 +25,41 @@ export function psReadOptions(timeoutMs: number): ExecOptions { export function psLstartReadOptions(timeoutMs: number): ExecOptions { return { allowFailure: true, timeoutMs, env: effectiveChildEnv(PS_LSTART_LOCALE_PIN) }; } + +/** + * The `ps -o lstart=` rendering printed under the pinned C locale, e.g. `Tue Nov 17 19:42:27 2026`. + */ +const PS_START_TIME_C_FORM = /^[A-Za-z]{3} [A-Za-z]{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/; +/** The invariant-culture CIM birth stamp a Windows host reads: `yyyyMMddHHmmssfffffff`. */ +const WINDOWS_START_TIME = /^\d{21}$/; + +/** + * The format of a recorded start time. Only the formats host-kit itself reads are verified: the + * `linux:` token of one /proc read, the pinned C-form `lstart`, and the Windows invariant stamp. + * Anything else is a legacy record — written by an older build whose `ps` ran under another + * locale, such as `mar. 17 nov. 19:42:27 2026` or a rendering with no colon-separated clock — and + * its text cannot be compared against another format. + */ +function psStartTimeFormat(value: string): 'linux' | 'c-lstart' | 'windows' | 'legacy' { + if (value.startsWith('linux:')) return 'linux'; + if (PS_START_TIME_C_FORM.test(value)) return 'c-lstart'; + if (WINDOWS_START_TIME.test(value)) return 'windows'; + return 'legacy'; +} + +/** + * Positive proof of different lifetimes. Unreadable values prove nothing, and a difference proves + * exit only when both sides share one verified format: a legacy localized rendering beside a + * C-form read, or beside another legacy rendering, is unverified evidence, never proof that the + * recorded process is gone. + */ +export function processStartTimesDiffer( + left: string | null | undefined, + right: string | null | undefined, +): boolean { + if (!left || !right) return false; + const leftFormat = psStartTimeFormat(left); + if (leftFormat !== psStartTimeFormat(right)) return false; + if (leftFormat === 'legacy') return false; + return left !== right; +} diff --git a/packages/host-kit/src/process.ts b/packages/host-kit/src/process.ts index 9a8eedfae2..cc917cba98 100644 --- a/packages/host-kit/src/process.ts +++ b/packages/host-kit/src/process.ts @@ -34,13 +34,13 @@ export { readProcessIdentities, readProcessIdentityFacts, readProcessStartTime, - processStartTimesDiffer, signalPidsBestEffort, stopProcessAndConfirmExit, uniquePositivePids, waitForProcessExit, writeHostStderr, } from './internal/host-process.ts'; +export { processStartTimesDiffer } from './internal/ps-start-time.ts'; export { signalProcessGroupBestEffort } from './internal/exec.ts'; export { reapOwnedProcessRecordsAtStartup } from './internal/owned-process-reaper.ts'; export { From 7ef7ebb7d4ed2815f9a915fe73d8f6309cdd4693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 20:53:59 +0100 Subject: [PATCH 4/6] fix(host-kit): apply the ps locale pin as envOverrides, the final spawn-env word The layering guard (R86 process-globals) forbids reading process.env outside declared process entries, so the pin cannot be materialized from process.env in exec.ts. ExecOptions gains envOverrides, which resolveSpawnEnv applies as the final word over the bound host scope's environment plus the request env: LC_ALL=C is pinned while TZ and the rest of the effective child environment survive. Outside a scope an explicit env still takes the overrides on top, and with neither the child inherits natively. The TZ regression moves to exec.test.ts, which spawns a real child: withCommandHost(host TZ=Pacific/Kiritimati) + envOverrides LC_ALL=C observes 'Pacific/Kiritimati|C', and the override also wins over a request-env LC_ALL. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- packages/host-kit/src/internal/exec.test.ts | 25 +++++++++++ packages/host-kit/src/internal/exec.ts | 41 ++++++++--------- .../internal/host-process-liveness.test.ts | 45 +++++++++---------- .../host-kit/src/internal/ps-start-time.ts | 4 +- 4 files changed, 68 insertions(+), 47 deletions(-) diff --git a/packages/host-kit/src/internal/exec.test.ts b/packages/host-kit/src/internal/exec.test.ts index 6009a3f6a9..fc0e683aa0 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 () => { + // A `ps -o lstart` read pins LC_ALL=C this way: the pin must not replace the effective child + // environment, because TZ picks the zone lstart renders in. + 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 2905babada..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,23 +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 }; -} - -/** - * The environment a command spawned without an explicit `env` receives — the bound host scope's - * environment with the request's values on top, or the process's own outside a scope — with - * `overrides` applied as the final word. Use this to pin one child variable, such as the C locale - * of a `ps -o lstart` read, without dropping the rest: `TZ` picks the zone `lstart` renders in, so - * replacing the whole environment would move the identity clock under the pin. - */ -export function effectiveChildEnv(overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { - const scope = commandHostScope.getStore(); - if (!scope) return { ...process.env, ...overrides }; - return { ...scope.host.env, ...scope.requestEnv, ...overrides }; + 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( @@ -227,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, @@ -424,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, @@ -491,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, @@ -523,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 24e1129e88..31b175fcb4 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -380,10 +380,10 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th 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?: { env?: NodeJS.ProcessEnv }) => - options?.env?.LC_ALL === 'C' ? escapeLikeCLocalePs(utf8Command) : utf8Command; + const commandFor = (options?: { envOverrides?: NodeJS.ProcessEnv }) => + options?.envOverrides?.LC_ALL === 'C' ? escapeLikeCLocalePs(utf8Command) : utf8Command; mockRunCmdSync.mockImplementation( - (_cmd: string, args: readonly string[], options?: { env?: NodeJS.ProcessEnv }) => { + (_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 }; @@ -395,7 +395,11 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th }, ); mockRunCmd.mockImplementation( - async (_cmd: string, args: readonly string[], options?: { env?: NodeJS.ProcessEnv }) => { + 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 }; @@ -421,38 +425,29 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th for (const call of calls) { const field = psFieldOf(call[1] ?? []); if (field.includes('lstart=')) { - assert.equal(call[2]?.env?.LC_ALL, 'C', `lstart-bearing read (${field}) must pin LC_ALL=C`); + assert.equal( + call[2]?.envOverrides?.LC_ALL, + 'C', + `lstart-bearing read (${field}) must pin LC_ALL=C`, + ); + 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 pin, so command text keeps one encoding`, + `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('the pinned lstart read overrides only LC_ALL on top of the effective child environment', () => { - vi.stubEnv('TZ', 'Pacific/Kiritimati'); - try { - psReturns('Mon Aug 10 20:00:00 2026\n'); - readProcessStartTime(4242); - - const env = mockRunCmdSync.mock.calls[0]?.[2]?.env; - assert.equal(env?.LC_ALL, 'C'); - assert.equal( - env?.TZ, - 'Pacific/Kiritimati', - 'dropping TZ would render lstart in the wrong zone under the pin', - ); - assert.deepEqual(env, { ...process.env, LC_ALL: 'C' }); - } finally { - vi.unstubAllEnvs(); - } -}); - test('only two start times in the same verified 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 diff --git a/packages/host-kit/src/internal/ps-start-time.ts b/packages/host-kit/src/internal/ps-start-time.ts index ae6e42d264..85e540020f 100644 --- a/packages/host-kit/src/internal/ps-start-time.ts +++ b/packages/host-kit/src/internal/ps-start-time.ts @@ -1,4 +1,4 @@ -import { effectiveChildEnv, type ExecOptions } from './exec.ts'; +import type { ExecOptions } from './exec.ts'; /** * `ps -o lstart` spells weekday and month names in the caller's locale, so one start time reads @@ -23,7 +23,7 @@ export function psReadOptions(timeoutMs: number): ExecOptions { * keep the same encoding as `listHostProcesses`, which runs unpinned. */ export function psLstartReadOptions(timeoutMs: number): ExecOptions { - return { allowFailure: true, timeoutMs, env: effectiveChildEnv(PS_LSTART_LOCALE_PIN) }; + return { allowFailure: true, timeoutMs, envOverrides: PS_LSTART_LOCALE_PIN }; } /** From ea5c816b274e7fb88e0b4fabb441df5c164f86b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 21:37:35 +0100 Subject: [PATCH 5/6] fix(host-kit): canonicalize POSIX birth tokens inline in the loaded host-process module Move the ps-start-time logic into the already-loaded host-process.ts so the eager-closure budget is unchanged, and give newly produced POSIX birth tokens explicit comparable provenance: a pinned C-form lstart is parsed in the reader's zone and recorded as posix:, so identity survives a cross-TZ stop. Historical raw renderings stay unqualified: they yield unverified identity and never prove exit or authorize a signal. Linux /proc and Windows CIM routes, unpinned argv reads, and cancellation are unchanged. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .../__tests__/daemon-client-lifecycle.test.ts | 8 +- .../src/daemon-process-takeover.test.ts | 70 ++----- .../daemon-contracts/src/daemon-process.ts | 4 + .../src/daemon-registration-status.test.ts | 4 +- .../src/daemon-registration.test.ts | 19 +- .../src/device-claim-settlement.test.ts | 2 +- .../device/__tests__/device-claims.test.ts | 6 +- .../server/http/daemon-metadata-loss.test.ts | 15 +- .../internal/host-process-liveness.test.ts | 52 +++-- .../host-process-stop-confirm.test.ts | 22 +- .../src/internal/host-process.test.ts | 39 +--- .../host-kit/src/internal/host-process.ts | 194 ++++++++---------- .../src/internal/owned-process-record.test.ts | 8 +- .../internal/owner-identity-liveness.test.ts | 17 +- .../src/internal/owner-identity.test.ts | 21 +- .../host-kit/src/internal/owner-identity.ts | 2 +- .../src/internal/process-lock-guard.test.ts | 4 +- .../host-kit/src/internal/ps-start-time.ts | 65 ------ packages/host-kit/src/process.ts | 3 +- .../agent-browser-process-record.test.ts | 8 +- .../src/agent-browser-lifecycle.test.ts | 6 +- packages/test-kit/src/host-process-mock.ts | 6 +- src/__tests__/cli-device-status.test.ts | 7 +- src/__tests__/daemon-exit-wait.test.ts | 4 +- .../daemon-registration-owner.test.ts | 12 +- 25 files changed, 265 insertions(+), 333 deletions(-) delete mode 100644 packages/host-kit/src/internal/ps-start-time.ts 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 2185cb10f5..13786ca48a 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle.test.ts @@ -387,9 +387,11 @@ test('daemon acquisition reclaims a proven reused owner before publication', asy const liveStartTime = readProcessStartTime(process.pid); const staleStartTime = liveStartTime?.startsWith('linux:') ? 'linux:00000000-0000-0000-0000-000000000000:0' - : liveStartTime !== null && /^\d{21}$/.test(liveStartTime) - ? '00000000000000000000' - : 'Thu Jan 1 00:00:00 1970'; + : 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 1342cf9fa9..fbdd21af2f 100644 --- a/packages/daemon-contracts/src/daemon-process-takeover.test.ts +++ b/packages/daemon-contracts/src/daemon-process-takeover.test.ts @@ -65,58 +65,12 @@ function spawnFakeDaemonFromBranchNamedCheckout(): { pid: number; entryPath: str return spawnFakeDaemon('repair-evidence-'); } -/** A start time in the same verified format as `live` but naming a different lifetime. */ +/** 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 live.replace(/\d{4}$/, '1970'); -} - -const FRENCH_MONTHS: Record = { - Jan: 'janv.', - Feb: 'févr.', - Mar: 'mars', - Apr: 'avr.', - May: 'mai', - Jun: 'juin', - Jul: 'juil.', - Aug: 'août', - Sep: 'sept.', - Oct: 'oct.', - Nov: 'nov.', - Dec: 'déc.', -}; -const FRENCH_WEEKDAYS: Record = { - Mon: 'lun.', - Tue: 'mar.', - Wed: 'mer.', - Thu: 'jeu.', - Fri: 'ven.', - Sat: 'sam.', - Sun: 'dim.', -}; -const C_FORM_LSTART = /^(\w{3}) (\w{3}) +(\d{1,2}) (\d{2}:\d{2}:\d{2}) (\d{4})$/; - -/** The fr_FR `ps -o lstart` rendering of a C-form start time, clock included. */ -function frenchLstart(cForm: string): string { - const match = C_FORM_LSTART.exec(cForm); - assert.ok(match, `expected a C-form lstart, got ${cForm}`); - const weekday = match[1]!; - const month = match[2]!; - const day = match[3]!; - const clock = match[4]!; - const year = match[5]!; - return `${FRENCH_WEEKDAYS[weekday] ?? weekday} ${day} ${FRENCH_MONTHS[month] ?? month} ${clock} ${year}`; -} - -/** A localized rendering with no colon-separated clock, as locales that omit HH:mm:ss print. */ -function frenchDateOnlyLstart(cForm: string): string { - const match = C_FORM_LSTART.exec(cForm); - assert.ok(match, `expected a C-form lstart, got ${cForm}`); - const month = match[2]!; - const day = match[3]!; - const year = match[5]!; - return `${day} ${FRENCH_MONTHS[month] ?? month} ${year}`; + return 'posix:1'; } // #1545: a reachable daemon with a code-signature mismatch is replaced. If a @@ -176,18 +130,24 @@ 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 C-locale pin may hold a localized `lstart` rendering. At -// the daemon stop boundary it must yield unverified identity — never `already-exited`, and -// never a signal — so a live daemon is not retired while it still runs. +// #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-locale record yields unverified identity at daemon stop, not an exited daemon', + '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(C_FORM_LSTART.test(startTime), `expected a C-form lstart, got ${startTime}`); + assert.ok(startTime.startsWith('posix:'), `expected a posix birth token, got ${startTime}`); - for (const legacy of [frenchLstart(startTime), frenchDateOnlyLstart(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 }, 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 8009e989f9..649e6b05db 100644 --- a/packages/daemon-contracts/src/daemon-registration.test.ts +++ b/packages/daemon-contracts/src/daemon-registration.test.ts @@ -55,25 +55,30 @@ 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(); - // Two C-form renderings one second apart are the same verified format with different values, - // so the difference proves the pid changed hands. - publishDaemonRegistration(stateDir, { pid: 4242, startTime: 'Tue Nov 17 19:42:28 2026' }); + // 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: 'Tue Nov 17 19:42:27 2026' }), + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'posix:1763493000000' }), true, ); - // A legacy localized rendering beside a C-form read is unverified, not a proved supersession. + // 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: 'Tue Nov 17 19:42:27 2026' }), + isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'posix:1763493000000' }), false, ); }); diff --git a/packages/daemon-contracts/src/device-claim-settlement.test.ts b/packages/daemon-contracts/src/device-claim-settlement.test.ts index 9a5a937f36..3e4a16dd47 100644 --- a/packages/daemon-contracts/src/device-claim-settlement.test.ts +++ b/packages/daemon-contracts/src/device-claim-settlement.test.ts @@ -382,7 +382,7 @@ test('PID reuse is uncertain ownership and never authorizes reconciliation', asy const stored = JSON.parse(fs.readFileSync(claimPath(root), 'utf8')) as Record; fs.writeFileSync( claimPath(root), - JSON.stringify({ ...stored, ownerStartTime: 'Tue Nov 17 19:42:28 2026' }), + JSON.stringify({ ...stored, ownerStartTime: 'posix:1763493001000' }), ); const reconcile = vi.fn(async () => ({ status: 'reconciled' as const })); 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 c73820078d..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,11 +681,11 @@ 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 in the same verified C-locale format: PID reuse, - // uncertain ownership. A legacy-format token would be unverified, not reuse. + // 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: 'Tue Nov 17 19:42:28 2026' }), + 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. 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 6f99cc30b6..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,8 +11,8 @@ import { const OWN_PID = process.pid; const FOREIGN_PID = 999_999_999; -// A C-form `lstart` rendering: the verified format, so a different C-form token proves a recycle. -const OWN = { pid: OWN_PID, startTime: 'Tue Nov 17 19:42:27 2026' } 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-'); @@ -43,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, 'Tue Nov 17 19:42:28 2026'); + publish(stateDir, OWN_PID, 'posix:1763493001000'); assert.deepEqual(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), { state: 'replaced', @@ -95,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'); 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 31b175fcb4..cc51f3d084 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -21,14 +21,19 @@ import { readProcessStartTime, readProcessIdentities, readProcessIdentityFacts, + processStartTimesDiffer, } from './host-process.ts'; -import { processStartTimesDiffer } from './ps-start-time.ts'; import { mockLinuxProcessStatAbsent } from './host-proc.fixtures.ts'; function psReturns(stdout: string, exitCode = 0): void { mockRunCmdSync.mockReturnValue({ stdout, stderr: '', exitCode }); } +/** The canonical token a pinned C-form lstart parses to, in the reader's zone. */ +function posixToken(y: number, mo: number, d: number, h: number, mi: number, s: number): string { + return `posix:${new Date(y, mo, d, h, mi, s).getTime()}`; +} + /** 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[]) => { @@ -85,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])); @@ -117,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'); @@ -150,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, }); @@ -190,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 }], ], ); @@ -248,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'); @@ -410,7 +422,7 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th readHostProcessIdentityObservations([4242]); await readHostProcessIdentityObservationsAsync([4242]); await readProcessIdentityFacts(4242); - assert.equal(readProcessStartTime(4242), 'Mon Aug 10 20:00:00 2026'); + assert.equal(readProcessStartTime(4242), posixToken(2026, 7, 10, 20, 0, 0)); assert.equal( readProcessCommand(4242), utf8Command, @@ -448,26 +460,26 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th assert.ok(sawCommandRead, 'the pid=,command= batch read must have run'); }); -test('only two start times in the same verified format prove different lifetimes', () => { +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 - // A legacy rendering beside a C-form read is unverified, never a different lifetime. + // 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, french), false); - assert.equal(processStartTimesDiffer(frenchNoClock, cForm), false); assert.equal(processStartTimesDiffer(cForm, frenchNoClock), false); - // Two different legacy renderings are not comparable either. assert.equal(processStartTimesDiffer(french, norwegian), false); assert.equal(processStartTimesDiffer(french, frenchNoClock), false); - // Two values in one verified format still prove a difference. - assert.equal(processStartTimesDiffer(cForm, 'Tue Nov 17 19:42:28 2026'), true); + // 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(french, 'linux:boot:1'), false); - assert.equal(processStartTimesDiffer(cForm, null), false); - assert.equal(processStartTimesDiffer(cForm, cForm), 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.test.ts b/packages/host-kit/src/internal/host-process.test.ts index d1e3cb4a52..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 in the same verified C-locale format', - { startTime: 'Tue Nov 17 19:42:27 2026', matches: true }, - ['Tue Nov 17 19:42:28 2026', 'recorded'], + 'a contradicted start time in the same provenanced format', + { startTime: 'posix:1763493000000', matches: true }, + ['posix:1763493001000', 'recorded'], 'reassigned', ], [ @@ -196,12 +196,12 @@ test('judgeProcessIdentity reads a zombie as exited whatever else the host says' ); }); -test('judgeProcessIdentity treats a legacy-locale record against a C-locale read as unverified', () => { - // Records written before the C-locale pin hold a localized `ps -o lstart` rendering: fr_FR - // prints `mar. 17 nov. 19:42:27 2026`, and locales that omit HH:mm:ss print no clock at all. - // Neither proves a different lifetime, so the verdict is unverified — never reassigned, and - // never permission to signal. - const facts = { startTime: 'Tue Nov 17 19:42:27 2026', command: null, zombie: false }; +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', @@ -211,25 +211,8 @@ test('judgeProcessIdentity treats a legacy-locale record against a C-locale read judgeProcessIdentity({ startTime: 'tir. 17. nov. 19:42:27 2026' }, facts), 'unverified', ); -}); - -test('judgeProcessIdentity still proves reuse between two C-locale reads', () => { - assert.equal( - judgeProcessIdentity( - { startTime: 'Tue Nov 17 19:42:27 2026' }, - { startTime: 'Tue Nov 17 19:42:28 2026', command: null, zombie: false }, - ), - 'reassigned', - ); -}); - -test('judgeProcessIdentity matches a non-ASCII command read byte for byte', () => { - const command = '/Users/mich/é/ü/agent-device/dist/src/internal/daemon.js'; assert.equal( - judgeProcessIdentity( - { startTime: 'Tue Nov 17 19:42:27 2026', matches: (observed) => observed === command }, - { startTime: 'Tue Nov 17 19:42:27 2026', command, zombie: false }, - ), - 'ours', + 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 69abf4a699..501c615462 100644 --- a/packages/host-kit/src/internal/host-process.ts +++ b/packages/host-kit/src/internal/host-process.ts @@ -1,7 +1,6 @@ import fs from 'node:fs'; import type { ExecOptions, ExecResult } from './exec.ts'; import { runCmd, runCmdSync, withoutCommandExecutorOverride } from './exec.ts'; -import { psLstartReadOptions, psReadOptions, processStartTimesDiffer } from './ps-start-time.ts'; import { sleep } from './retry.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; @@ -26,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; @@ -51,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() }; } @@ -114,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, @@ -133,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, @@ -249,6 +229,67 @@ function readLinuxProcessStat(pid: number): { state: string; startTime: string } } } +/** C-locale pin for lstart-bearing ps reads, applied as a final `envOverrides` word so `TZ` survives. */ +const PS_LSTART_ENV_OVERRIDES: NodeJS.ProcessEnv = { LC_ALL: 'C' }; + +/** 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 pinned over the effective child env, never replacing it. */ +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; + const format = psStartTimeFormat(left); + if (format !== psStartTimeFormat(right) || format === 'unqualified') return false; + return left !== right; +} + +/** Canonicalize a pinned C-form lstart, rendered in the reader's zone, to a zone-independent token. */ +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 = new Date( + Number(match[7]), + month, + Number(match[3]), + Number(match[4]), + Number(match[5]), + Number(match[6]), + ).getTime(); + return Number.isFinite(startedAtMs) ? `${POSIX_BIRTH_TOKEN_PREFIX}${startedAtMs}` : null; +} + export function readProcessStartTime(pid: number): string | null { return readProcessField(pid, 'lstart='); } @@ -265,12 +306,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 { @@ -279,12 +315,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> { @@ -367,7 +398,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; } @@ -398,7 +432,8 @@ function readProcessField(pid: number, field: HostProcessField): string | null { // 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), ); - return processFieldValue(result); + const value = processFieldValue(result); + return field === 'lstart=' ? (canonicalPosixBirthToken(value ?? '') ?? value) : value; } catch { return null; } @@ -410,12 +445,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, @@ -441,17 +471,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; @@ -649,18 +671,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 }> @@ -676,11 +690,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, @@ -693,10 +703,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`; } @@ -734,11 +741,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; @@ -763,18 +766,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'; @@ -794,11 +788,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, @@ -833,10 +824,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 151e5aaa8d..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,25 +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', () => { - // The mismatch must be proven in one verified format: two C-form renderings one second apart. - mockReadProcessStartTime.mockReturnValue('Tue Nov 17 19:42:28 2026'); + // 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: 'Tue Nov 17 19:42:27 2026' } }), + classifyOwnerLiveness({ owner: { pid: OWNER_PID, startTime: 'posix:1763493000000' } }), 'owner-process-reused', ); }); -test('a legacy-locale record beside a C-locale read stays live, never reused', () => { - // `mar. 17 nov. 19:42:27 2026` (fr_FR) and `17 nov. 2026` (no colon-separated clock) are - // renderings an older build could have recorded; neither proves the pid changed hands. - for (const legacy of ['mar. 17 nov. 19:42:27 2026', '17 nov. 2026']) { - mockReadProcessStartTime.mockReturnValue('Tue Nov 17 19:42:27 2026'); +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 ed18b86590..51778c24ae 100644 --- a/packages/host-kit/src/internal/owner-identity.test.ts +++ b/packages/host-kit/src/internal/owner-identity.test.ts @@ -26,15 +26,15 @@ 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 verified format as the live read but - // with a different value: the `linux:` token on Linux, the CIM stamp on Windows, the pinned - // C-form `lstart` on macOS. + // 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' - : 'Thu Jan 1 00:00:00 1970'; + : 'posix:1'; assert.equal( classifyOwnerLiveness({ owner: { @@ -71,13 +71,22 @@ 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); - // Two records in the same verified C-locale format with different values prove a reuse. + // 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' }, ), - true, + 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. diff --git a/packages/host-kit/src/internal/owner-identity.ts b/packages/host-kit/src/internal/owner-identity.ts index e14d6665ba..1219e2eb2f 100644 --- a/packages/host-kit/src/internal/owner-identity.ts +++ b/packages/host-kit/src/internal/owner-identity.ts @@ -2,13 +2,13 @@ import fs from 'node:fs'; import { isProcessAlive, isProcessZombie, + processStartTimesDiffer, readHostProcessIdentityObservations, readHostProcessIdentityObservationsAsync, readProcessIdentityFacts, readProcessStartTime, type HostProcessIdentityObservation, } from './host-process.ts'; -import { processStartTimesDiffer } from './ps-start-time.ts'; export type OwnerIdentity = { pid: number; 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/internal/ps-start-time.ts b/packages/host-kit/src/internal/ps-start-time.ts deleted file mode 100644 index 85e540020f..0000000000 --- a/packages/host-kit/src/internal/ps-start-time.ts +++ /dev/null @@ -1,65 +0,0 @@ -import type { ExecOptions } from './exec.ts'; - -/** - * `ps -o lstart` spells weekday and month names in the caller's locale, so one start time reads - * differently from a daemon and a client run under different `LANG`/`LC_TIME`. Every `ps` read - * whose output carries `lstart` runs with this pin. - */ -const PS_LSTART_LOCALE_PIN: NodeJS.ProcessEnv = { LC_ALL: 'C' }; - -/** - * Options for a `ps` read whose output does not carry `lstart`: failure is unknown evidence, and - * the caller's locale stays in charge of the output. - */ -export function psReadOptions(timeoutMs: number): ExecOptions { - return { allowFailure: true, timeoutMs }; -} - -/** - * Options for a `ps` read whose output carries `lstart`: failure is unknown evidence, and the C - * locale is pinned as the final override on top of the effective child environment, so `TZ` and - * the rest of the environment survive the pin. Command-text reads must not use this: BSD/macOS - * `ps` escapes non-ASCII argv bytes under `LC_ALL=C`, and every command read in host-kit has to - * keep the same encoding as `listHostProcesses`, which runs unpinned. - */ -export function psLstartReadOptions(timeoutMs: number): ExecOptions { - return { allowFailure: true, timeoutMs, envOverrides: PS_LSTART_LOCALE_PIN }; -} - -/** - * The `ps -o lstart=` rendering printed under the pinned C locale, e.g. `Tue Nov 17 19:42:27 2026`. - */ -const PS_START_TIME_C_FORM = /^[A-Za-z]{3} [A-Za-z]{3} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/; -/** The invariant-culture CIM birth stamp a Windows host reads: `yyyyMMddHHmmssfffffff`. */ -const WINDOWS_START_TIME = /^\d{21}$/; - -/** - * The format of a recorded start time. Only the formats host-kit itself reads are verified: the - * `linux:` token of one /proc read, the pinned C-form `lstart`, and the Windows invariant stamp. - * Anything else is a legacy record — written by an older build whose `ps` ran under another - * locale, such as `mar. 17 nov. 19:42:27 2026` or a rendering with no colon-separated clock — and - * its text cannot be compared against another format. - */ -function psStartTimeFormat(value: string): 'linux' | 'c-lstart' | 'windows' | 'legacy' { - if (value.startsWith('linux:')) return 'linux'; - if (PS_START_TIME_C_FORM.test(value)) return 'c-lstart'; - if (WINDOWS_START_TIME.test(value)) return 'windows'; - return 'legacy'; -} - -/** - * Positive proof of different lifetimes. Unreadable values prove nothing, and a difference proves - * exit only when both sides share one verified format: a legacy localized rendering beside a - * C-form read, or beside another legacy rendering, is unverified evidence, never proof that the - * recorded process is gone. - */ -export function processStartTimesDiffer( - left: string | null | undefined, - right: string | null | undefined, -): boolean { - if (!left || !right) return false; - const leftFormat = psStartTimeFormat(left); - if (leftFormat !== psStartTimeFormat(right)) return false; - if (leftFormat === 'legacy') return false; - return left !== right; -} diff --git a/packages/host-kit/src/process.ts b/packages/host-kit/src/process.ts index cc917cba98..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, @@ -40,7 +42,6 @@ export { waitForProcessExit, writeHostStderr, } from './internal/host-process.ts'; -export { processStartTimesDiffer } from './internal/ps-start-time.ts'; export { signalProcessGroupBestEffort } from './internal/exec.ts'; export { reapOwnedProcessRecordsAtStartup } from './internal/owned-process-reaper.ts'; export { 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 5ff05ead6c..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,12 +27,12 @@ vi.mock('@agent-device/host-kit/process', async (importOriginal) => ({ const mockObservations = vi.mocked(observationsMock); const mockIsProcessAlive = vi.mocked(isProcessAliveMock); -/** C-form `lstart` token per pid: the verified format, so a differing token proves a different lifetime. */ +/** Canonical POSIX birth token per pid: provenanced, 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`; + return `posix:${1000 + pid}`; } -/** A C-form start time naming a different lifetime than any `startToken`. */ -const LATER_LIFETIME = 'Wed Nov 18 08:00:00 2026'; +/** A birth token naming a different lifetime than any `startToken`. */ +const LATER_LIFETIME = 'posix:999999999'; function record(pid: number, startTime = startToken(pid)): OwnedProcessRecord { return { diff --git a/packages/platform-web/src/agent-browser-lifecycle.test.ts b/packages/platform-web/src/agent-browser-lifecycle.test.ts index 4da6412dac..ab687b08d2 100644 --- a/packages/platform-web/src/agent-browser-lifecycle.test.ts +++ b/packages/platform-web/src/agent-browser-lifecycle.test.ts @@ -14,10 +14,10 @@ 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 `Tue Nov 17 19:${String(40 + (pid % 20)).padStart(2, '0')}:${String(pid % 60).padStart(2, '0')} 2026`; + return `posix:${1000 + pid}`; } -/** A C-form start time naming a different lifetime than any `startToken`. */ -const LATER_LIFETIME = 'Wed Nov 18 08:00:00 2026'; +/** A birth token naming a different lifetime than any `startToken`. */ +const LATER_LIFETIME = 'posix:999999999'; const { runCmdMock, spawnMock, probe } = vi.hoisted(() => ({ runCmdMock: vi.fn(), diff --git a/packages/test-kit/src/host-process-mock.ts b/packages/test-kit/src/host-process-mock.ts index 2121a285ad..72a2e76c70 100644 --- a/packages/test-kit/src/host-process-mock.ts +++ b/packages/test-kit/src/host-process-mock.ts @@ -17,9 +17,9 @@ export function pinOwnProcessStartTime(hostProcess: HostProcessModule): void { } function installPin(hostProcess: HostProcessModule): void { - // A C-form `ps -o lstart` rendering: the one verified format host-kit reads on macOS, so a - // different C-form token in a record still proves PID reuse while legacy renderings do not. - const ownStartTime = 'Tue Nov 17 19:42:27 2026'; + // 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 8cf6b86a23..a2d178a6df 100644 --- a/src/__tests__/cli-device-status.test.ts +++ b/src/__tests__/cli-device-status.test.ts @@ -18,12 +18,13 @@ import { pinOwnProcessStartTime(hostProcess); -/** A start time in the same verified format as `live` but naming a different lifetime. */ +/** 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 'Thu Jan 1 00:00:00 1970'; + 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 live.replace(/\d{4}$/, '1970'); + return 'posix:1'; } test('device status is daemonless and does not send a daemon request', async () => { 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 de46407690..154869d9de 100644 --- a/src/__tests__/daemon-registration-owner.test.ts +++ b/src/__tests__/daemon-registration-owner.test.ts @@ -230,13 +230,15 @@ test('a log removed between creation and the write-handle reopen fails startup l await owner.finish(report); }); -// A start time in the same verified format as the live owner's but a different value, so the -// registration proves replacement; a legacy-format token would be unverified, not proof. +// 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 !== null && /^\d{21}$/.test(ownIdentity.startTime) - ? '00000000000000000000' - : 'Thu Jan 1 00:00:00 1970'; + : 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'], From 0b301eefcaac49c597faab47667f9c2303fe2de1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 22:26:50 +0100 Subject: [PATCH 6/6] fix(host-kit): pin the lstart ps probe to the UTC clock and parse its output as UTC The probe now overrides TZ=UTC alongside LC_ALL=C (as the final envOverrides word, so a captured host or request TZ cannot change the zone ps renders in), and the known UTC output is parsed with Date.UTC. The posix: birth token no longer depends on the JS reader's local zone or on DST folds, so a daemon registered under one TZ is recognized under any other. Linux /proc, Windows CIM, unpinned argv reads, cancellation, and the eager-closure shape are unchanged; legacy raw renderings stay unqualified and unverified. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- packages/host-kit/src/internal/exec.test.ts | 4 +- .../internal/host-process-liveness.test.ts | 48 +++++++++++++++---- .../host-kit/src/internal/host-process.ts | 22 ++++++--- 3 files changed, 56 insertions(+), 18 deletions(-) diff --git a/packages/host-kit/src/internal/exec.test.ts b/packages/host-kit/src/internal/exec.test.ts index fc0e683aa0..c0fe93a7d4 100644 --- a/packages/host-kit/src/internal/exec.test.ts +++ b/packages/host-kit/src/internal/exec.test.ts @@ -325,8 +325,8 @@ const PRINT_TZ_AND_LOCALE = [ ]; test('envOverrides are the final word over the bound host environment, keeping TZ under a locale pin', async () => { - // A `ps -o lstart` read pins LC_ALL=C this way: the pin must not replace the effective child - // environment, because TZ picks the zone lstart renders in. + // 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 () => 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 cc51f3d084..cd6e3306bf 100644 --- a/packages/host-kit/src/internal/host-process-liveness.test.ts +++ b/packages/host-kit/src/internal/host-process-liveness.test.ts @@ -29,9 +29,9 @@ function psReturns(stdout: string, exitCode = 0): void { mockRunCmdSync.mockReturnValue({ stdout, stderr: '', exitCode }); } -/** The canonical token a pinned C-form lstart parses to, in the reader's zone. */ +/** 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:${new Date(y, mo, d, h, mi, s).getTime()}`; + return `posix:${Date.UTC(y, mo, d, h, mi, s)}`; } /** Answers the two batched identity reads: state and start time, and the command line. */ @@ -379,16 +379,17 @@ test.skipIf(process.platform !== 'linux')( }, ); -/** The `-o` value of a ps call: `lstart=`-bearing reads pin the locale, the others must not. */ +/** 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; command and state reads keep the caller locale', async () => { +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 is pinned, - // and no command-text read is. + // 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}`); @@ -437,10 +438,10 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th for (const call of calls) { const field = psFieldOf(call[1] ?? []); if (field.includes('lstart=')) { - assert.equal( - call[2]?.envOverrides?.LC_ALL, - 'C', - `lstart-bearing read (${field}) must pin LC_ALL=C`, + 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 { @@ -460,6 +461,33 @@ test('only lstart-bearing ps reads pin LC_ALL=C; command and state reads keep th 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 diff --git a/packages/host-kit/src/internal/host-process.ts b/packages/host-kit/src/internal/host-process.ts index 501c615462..6101aebaa6 100644 --- a/packages/host-kit/src/internal/host-process.ts +++ b/packages/host-kit/src/internal/host-process.ts @@ -229,13 +229,19 @@ function readLinuxProcessStat(pid: number): { state: string; startTime: string } } } -/** C-locale pin for lstart-bearing ps reads, applied as a final `envOverrides` word so `TZ` survives. */ -const PS_LSTART_ENV_OVERRIDES: NodeJS.ProcessEnv = { LC_ALL: 'C' }; +/** + * 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 pinned over the effective child env, never replacing it. */ +/** ps read options carrying lstart: C locale and UTC clock pinned over the effective child env. */ const psLstartReadOptions = (timeoutMs: number): ExecOptions => ({ allowFailure: true, timeoutMs, @@ -274,19 +280,23 @@ export function processStartTimesDiffer( return left !== right; } -/** Canonicalize a pinned C-form lstart, rendered in the reader's zone, to a zone-independent token. */ +/** + * 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 = new Date( + const startedAtMs = Date.UTC( Number(match[7]), month, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6]), - ).getTime(); + ); return Number.isFinite(startedAtMs) ? `${POSIX_BIRTH_TOKEN_PREFIX}${startedAtMs}` : null; }