Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -382,10 +382,16 @@ test('daemon acquisition reclaims a proven reused owner before publication', asy
const paths = resolveDaemonPaths(stateDir);
const daemon = await startHttpDaemonFixture({ via: 'fresh-daemon' });
vi.stubEnv('AGENT_DEVICE_STATE_DIR', stateDir);
const staleStartTime =
process.platform === 'linux'
? 'linux:00000000-0000-0000-0000-000000000000:0'
: 'stale-start-time';
// A proven reuse needs a stale value in the same verified format as the live read of this pid;
// a legacy-format token would be unverified, not proof.
const liveStartTime = readProcessStartTime(process.pid);
const staleStartTime = liveStartTime?.startsWith('linux:')
? 'linux:00000000-0000-0000-0000-000000000000:0'
: liveStartTime?.startsWith('posix:')
? 'posix:1'
: liveStartTime !== null && /^\d{21}$/.test(liveStartTime)
? '00000000000000000000'
: 'posix:1';
const stale = tryAcquireProcessLock({
lockDirPath: paths.lockPath,
owner: { pid: process.pid, startTime: staleStartTime, acquiredAtMs: Date.now() },
Expand Down
86 changes: 81 additions & 5 deletions packages/daemon-contracts/src/daemon-process-takeover.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -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 });
Expand All @@ -56,6 +60,19 @@ function spawnFakeDaemonFromBranchNamedCheckout(): { pid: number; entryPath: str
return { pid, entryPath };
}

/** A daemon entry from a branch-named checkout, whose path has no project-name marker. */
function spawnFakeDaemonFromBranchNamedCheckout(): { pid: number; entryPath: string } {
return spawnFakeDaemon('repair-evidence-');
}

/** A start time in the same provenanced format as `live` but naming a different lifetime. */
function staleStartTimeLike(live: string): string {
if (live.startsWith('linux:')) return 'linux:00000000-0000-4000-8000-000000000000:999999999';
if (live.startsWith('posix:')) return 'posix:1';
if (/^\d{21}$/.test(live)) return '00000000000000000000';
return 'posix:1';
}

// #1545: a reachable daemon with a code-signature mismatch is replaced. If a
// branch-named worktree is rejected as "not ours", replacement leaves the old
// daemon alive and the next request reaches a fresh empty session store.
Expand Down Expand Up @@ -96,7 +113,9 @@ test('does not stop a branch-named daemon when the pid belongs to a different pr

const actualStartTime = readProcessStartTime(pid);
assert.ok(actualStartTime, 'expected the spawned daemon to report a start time');
const staleStartTime = `${actualStartTime}-previous-lifetime`;
// A proven reuse needs a stale value in the same verified format as the live read; a legacy
// token would be unverified rather than proof.
const staleStartTime = staleStartTimeLike(actualStartTime);
assert.equal(isAgentDeviceDaemonProcess(pid, staleStartTime), false);

const result = await stopDaemonProcess(
Expand All @@ -110,3 +129,60 @@ test('does not stop a branch-named daemon when the pid belongs to a different pr
});
assert.equal(isProcessAlive(pid), true);
});

// #4656: a record written before the provenance pin holds a raw `lstart` rendering — fr_FR prints
// `mar. 17 nov. 19:42:27 2026`, locales that omit HH:mm:ss print no clock, and an earlier pinned
// build stored the raw C form. All are unqualified, so at the daemon stop boundary they yield
// unverified identity — never `already-exited`, and never a signal — so a live daemon is not
// retired while it still runs.
test.skipIf(process.platform !== 'darwin')(
'a legacy raw record yields unverified identity at daemon stop, not an exited daemon',
async () => {
const { pid } = spawnFakeDaemonFromBranchNamedCheckout();
const startTime = readProcessStartTime(pid);
assert.ok(startTime, 'expected the spawned daemon to report a start time');
assert.ok(startTime.startsWith('posix:'), `expected a posix birth token, got ${startTime}`);

for (const legacy of [
'mar. 17 nov. 19:42:27 2026',
'17 nov. 2026',
'Tue Nov 17 19:42:27 2026',
]) {
const result = await stopDaemonProcess(
{ pid, startTime: legacy },
{ mode: 'graceful', termTimeoutMs: 200, killTimeoutMs: 100 },
);
assert.equal(result.status, 'retained', `legacy record ${legacy} must not retire the daemon`);
if (result.status === 'retained') {
assert.equal(result.reason, 'identity-unverified');
}
assert.equal(
isProcessAlive(pid),
true,
'no signal may reach a daemon the legacy record cannot verify',
);
}
},
);

test.skipIf(process.platform === 'win32')(
'the stop route reads a non-ASCII daemon argv as UTF-8, not as C-locale escapes',
async () => {
const { pid, entryPath } = spawnFakeDaemon('utf8-é-ü-');
assert.ok(entryPath.includes('é-ü'));

const command = readProcessCommand(pid);
assert.ok(command?.includes('é-ü'), `expected the UTF-8 argv, got ${JSON.stringify(command)}`);
const startTime = readProcessStartTime(pid);
assert.ok(startTime, 'expected the spawned daemon to report a start time');
assert.equal(isAgentDeviceDaemonProcess(pid, startTime), true);

const result = await stopDaemonProcess(
{ pid, startTime },
{ mode: 'graceful', ...TAKEOVER_TIMEOUTS },
);
assert.equal(result.status, 'exited');
await spawnedChildren.at(-1)!.exited;
assert.equal(isProcessAlive(pid), false);
},
);
4 changes: 4 additions & 0 deletions packages/daemon-contracts/src/daemon-process.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
isProcessAlive,
isProvenancedBirthToken,
processStartTimesDiffer,
isProcessPid,
readHostProcessIdentityObservations,
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
26 changes: 22 additions & 4 deletions packages/daemon-contracts/src/daemon-registration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,32 @@ test('a different published pid proves the owner no longer serves its state dir'
assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4141, startTime: 'owner-start' }), true);
});

test('a published start time proves supersession only when both sides are readable', () => {
test('a published start time proves supersession only when both sides are provenanced', () => {
const stateDir = useStateDir();
publishDaemonRegistration(stateDir, { pid: 4242, startTime: 'successor-start' });
assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'owner-start' }), true);
// Two `posix:` tokens with different values are the same provenanced format, so the difference
// proves the pid changed hands.
publishDaemonRegistration(stateDir, { pid: 4242, startTime: 'posix:1763493001000' });
assert.equal(
isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'posix:1763493000000' }),
true,
);
// Raw historical renderings — a localized one, and even the C form — are unqualified, so they
// are unverified, never a proved supersession.
assert.equal(
isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'mar. 17 nov. 19:42:28 2026' }),
false,
);
assert.equal(
isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'Tue Nov 17 19:42:27 2026' }),
false,
);
// An unreadable start time on either side leaves the identity unproven.
assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: null }), false);
publishDaemonRegistration(stateDir, { pid: 4242, startTime: null });
assert.equal(isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'owner-start' }), false);
assert.equal(
isSupersededDaemonOwner({ stateDir, pid: 4242, startTime: 'posix:1763493000000' }),
false,
);
});

test('the published owner itself is never superseded, and absence is not proof', () => {
Expand Down
9 changes: 6 additions & 3 deletions packages/daemon-contracts/src/device-claim-settlement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
);
Expand Down Expand Up @@ -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<string, unknown>;
fs.writeFileSync(claimPath(root), JSON.stringify({ ...stored, ownerStartTime: 'other-start' }));
fs.writeFileSync(
claimPath(root),
JSON.stringify({ ...stored, ownerStartTime: 'posix:1763493001000' }),
);
const reconcile = vi.fn(async () => ({ status: 'reconciled' as const }));

const result = await acquireDeviceClaim({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
// Same PID, different recorded start time: PID reuse, uncertain ownership.
fs.writeFileSync(claimPath(root), JSON.stringify({ ...stored, ownerStartTime: 'other-start' }));
// Same PID, different recorded start time in the same provenanced format: PID reuse,
// uncertain ownership. A raw legacy rendering would be unverified, not reuse.
fs.writeFileSync(
claimPath(root),
JSON.stringify({ ...stored, ownerStartTime: 'posix:1763493001000' }),
);
// A dead-owner claim stored under a name that is not the hash of its own
// device key: the claim lock protects a different path, so release refuses.
fs.writeFileSync(
Expand Down
28 changes: 19 additions & 9 deletions packages/daemon/src/server/http/daemon-metadata-loss.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {

const OWN_PID = process.pid;
const FOREIGN_PID = 999_999_999;
const OWN = { pid: OWN_PID, startTime: 'own-start' } as const;
// A provenanced POSIX birth token: the verified format, so a different token proves a recycle.
const OWN = { pid: OWN_PID, startTime: 'posix:1763493000000' } as const;

function scratch(): { stateDir: string; infoPath: string } {
const stateDir = mkdtempForTestSync('agent-device-daemon-metadata-loss-');
Expand All @@ -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);
});
Expand All @@ -42,7 +43,7 @@ describe('readDaemonMetadataLoss', () => {

test('a record recycling this pid under a different start time is a loss', () => {
const { stateDir, infoPath } = scratch();
publish(stateDir, OWN_PID, 'recycled-start');
publish(stateDir, OWN_PID, 'posix:1763493001000');

assert.deepEqual(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), {
state: 'replaced',
Expand All @@ -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 }), {
Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -94,6 +95,15 @@ describe('readDaemonMetadataLoss', () => {
assert.equal(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), undefined);
});

test('a legacy raw record under this pid is unverified, not a reported loss', () => {
// A record written before the provenance pin holds a raw `lstart` rendering, which cannot
// prove a different lifetime, so the daemon does not announce a takeover on it.
const { stateDir, infoPath } = scratch();
publish(stateDir, OWN_PID, 'Tue Nov 17 19:42:27 2026');

assert.equal(readDaemonMetadataLoss({ infoPath, stateDir, owner: OWN }), undefined);
});

test('a corrupt record is not evidence that the registration was taken', () => {
const { stateDir, infoPath } = scratch();
fs.writeFileSync(infoPath, '{not json');
Expand Down Expand Up @@ -123,7 +133,7 @@ describe('watchDaemonMetadataLoss', () => {
vi.useFakeTimers();
try {
const { stateDir, infoPath } = scratch();
publish(stateDir, OWN_PID, 'own-start');
publish(stateDir, OWN_PID, OWN.startTime);
const watch = startWatch(stateDir, infoPath);
try {
watch.advance();
Expand All @@ -145,7 +155,7 @@ describe('watchDaemonMetadataLoss', () => {
vi.useFakeTimers();
try {
const { stateDir, infoPath } = scratch();
publish(stateDir, OWN_PID, 'own-start');
publish(stateDir, OWN_PID, OWN.startTime);
const watch = startWatch(stateDir, infoPath);

fs.rmSync(stateDir, { recursive: true, force: true });
Expand All @@ -167,7 +177,7 @@ describe('watchDaemonMetadataLoss', () => {
vi.useFakeTimers();
try {
const { stateDir, infoPath } = scratch();
publish(stateDir, OWN_PID, 'own-start');
publish(stateDir, OWN_PID, OWN.startTime);
const watch = startWatch(stateDir, infoPath);
watch.cancel();
watch.cancel();
Expand Down
25 changes: 25 additions & 0 deletions packages/host-kit/src/internal/exec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,31 @@ test('a request command env reaches spawned commands; outside it they inherit th
assert.equal(hostOnly.stdout, '/daemon/Developer');
});

const PRINT_TZ_AND_LOCALE = [
'-e',
'process.stdout.write(`${process.env.TZ ?? ""}|${process.env.LC_ALL ?? ""}`)',
];

test('envOverrides are the final word over the bound host environment, keeping TZ under a locale pin', async () => {
// Overrides merge over the effective child env instead of replacing it, so an `LC_ALL=C` pin
// alone still lets `TZ` through; the lstart probe itself pins `TZ=UTC` on top (host-process).
const host = hostWith({ TZ: 'Pacific/Kiritimati' });
const [pinned, requestEnvOverridden] = await Promise.all([
withCommandHost({ host, requestEnv: undefined }, async () =>
runCmd(process.execPath, PRINT_TZ_AND_LOCALE, { envOverrides: { LC_ALL: 'C' } }),
),
withCommandHost({ host, requestEnv: { LC_ALL: 'fr_FR.UTF-8' } }, async () =>
runCmd(process.execPath, PRINT_TZ_AND_LOCALE, { envOverrides: { LC_ALL: 'C' } }),
),
]);
assert.equal(pinned.stdout, 'Pacific/Kiritimati|C');
assert.equal(
requestEnvOverridden.stdout,
'Pacific/Kiritimati|C',
'the override is the final word, ahead of the request env too',
);
});

test.runIf(process.platform !== 'win32')(
'xcrun tool-not-found failures name the developer dir and how to change it',
async () => {
Expand Down
Loading
Loading