Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

harnessd: a wake no longer unbinds a working agent, and a clock step is not a reboot (round 29) (#795)

Dee45dec052b7db
diff --git a/cli/e2e/clockjump.e2e.ts b/cli/e2e/clockjump.e2e.ts
new file mode 100644
index 000000000..a9af4a57b
--- /dev/null
+++ b/cli/e2e/clockjump.e2e.ts
@@ -0,0 +1,112 @@
+/**
+ * The wall clock jumping while agents work, for Claude Code and Codex. A laptop closed mid-turn sleeps
+ * with every process on it, and wakes with the wall clock hours ahead while the monotonic clocks (on
+ * macOS) never counted the sleep; an NTP correction, a virtual machine resumed or a time zone synced
+ * after travel moves it back. Every Node process here runs with `Date` shifted from a file
+ * (harness/clockShift.mjs): the daemon, and the engines through the person's shell. A turn in flight
+ * must still read as working, end once, and every agent must go on working, in order.
+ */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+type Row = Record<string, any>
+
+const rows = async (client: LocalClient): Promise<Row[]> =>
+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents
+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)
+async function create(d: IsolatedDaemon, client: LocalClient, engine: Engine, folder: string): Promise<Row> {
+ const cwd = join(d.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agent = await row(client, created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
+ const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)
+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)
+ client.send('message', { agentId, content })
+ expect((await started).payload?.userMessage).toBe(content)
+ await ended
+}
+async function said(client: LocalClient, sessionId: string): Promise<string[]> {
+ const page = await client.request('session_get', { sessionId, limit: 50 }, 60_000)
+ expect(page.error, JSON.stringify(page)).toBeUndefined()
+ return (page.events as Row[]).filter((event) => event.type === 'user_message').map((event) => String(event.payload.content))
+}
+const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms))
+const SHIM = resolve(CLI_ROOT, 'e2e/harness/clockShift.mjs')
+
+describe('the wall clock jumping while agents work', () => {
+ let daemon: IsolatedDaemon | undefined
+ let scratch: string | undefined
+ const paused: number[] = []
+ afterEach(async () => {
+ for (const pid of paused.splice(0)) { try { process.kill(pid, 'SIGCONT') } catch { /* gone */ } }
+ await daemon?.close(); daemon = undefined
+ if (scratch) rmSync(scratch, { recursive: true, force: true })
+ scratch = undefined
+ })
+
+ it.each([
+ ['forward three hours, as a laptop closed mid-turn wakes', 3 * 3_600_000],
+ ['back an hour, as an NTP correction does', -3_600_000],
+ ] as const)('%s: the turn in flight reads as working, ends once, and every agent goes on', async (_what, jump) => {
+ scratch = mkdtempSync(join(tmpdir(), 'clock-'))
+ const shiftFile = join(scratch, 'shift')
+ writeFileSync(shiftFile, '0')
+ const clock = { NODE_OPTIONS: `--import ${SHIM}`, E2E_CLOCK_SHIFT_FILE: shiftFile }
+ const d = await IsolatedDaemon.create({ env: clock })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ // The engines run through the person's shell: the same clock reaches them there.
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export NODE_OPTIONS=${JSON.stringify(clock.NODE_OPTIONS)} E2E_CLOCK_SHIFT_FILE=${JSON.stringify(shiftFile)}\n`)
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const claude = await create(d, client, 'claude', 'clock-claude')
+ const codex = await create(d, client, 'codex', 'clock-codex')
+ await turn(client, claude.id, 'before the jump (claude)')
+ await turn(client, codex.id, 'before the jump (codex)')
+
+ // A long turn in flight when everything stops.
+ const from = client.frames.length
+ client.send('message', { agentId: claude.id, content: '!slow 12000' })
+ await client.next(isTurn('turn_started', claude.id), 30_000, 'the long turn to start')
+ // The daemon is paused, not the panes: tmux resumes a stopped pane's shell at once, and an
+ // interactive shell whose engine stays stopped ends and takes it with it. A real sleep stops
+ // everything together; what is under test is the daemon waking to a moved clock.
+ const everything = [d.pid!, d.corePid()!]
+ // A short-lived child seen in the snapshot may be gone by now.
+ for (const pid of everything) { try { process.kill(pid, 'SIGSTOP'); paused.push(pid) } catch { /* gone */ } }
+ await sleep(3_000)
+ writeFileSync(shiftFile, String(jump))
+ for (const pid of paused.splice(0)) { try { process.kill(pid, 'SIGCONT') } catch { /* gone */ } }
+
+ await sleep(2_000)
+ if (process.env.CLOCK_PROBE) {
+ const { appendFileSync } = await import('node:fs')
+ appendFileSync(process.env.CLOCK_PROBE, `--- jump ${jump}\n${JSON.stringify(await row(client, claude.id))}\n`)
+ }
+ expect((await row(client, claude.id))?.activity?.state, 'the turn in flight still reads as working').toBe('working')
+ await client.waitFor((frame) => isTurn('turn_ended', claude.id)(frame) && client.frames.indexOf(frame) >= from, 45_000, 'the long turn to end')
+ await sleep(3_000)
+ expect(client.frames.slice(from).filter(isTurn('turn_ended', claude.id))).toHaveLength(1)
+ expect((await row(client, claude.id))?.activity?.state).not.toBe('working')
+
+ await turn(client, claude.id, 'after the jump (claude)')
+ await turn(client, codex.id, 'after the jump (codex)')
+ expect(await said(client, claude.sessionId)).toEqual(['before the jump (claude)', '!slow 12000', 'after the jump (claude)'])
+ expect(await said(client, codex.sessionId)).toEqual(['before the jump (codex)', 'after the jump (codex)'])
+ for (const agent of [claude, codex]) expect((await row(client, agent.id))?.status).toBe('active')
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ }, 240_000)
+})
diff --git a/cli/e2e/harness/clockShift.mjs b/cli/e2e/harness/clockShift.mjs
new file mode 100644
index 000000000..1c0f2ec68
--- /dev/null
+++ b/cli/e2e/harness/clockShift.mjs
@@ -0,0 +1,38 @@
+// Preloaded (`node --import`) into every Node process of a test that moves the wall clock: the daemon's
+// master and core, and the fake engines, which inherit NODE_OPTIONS through tmux. `Date` reads the
+// offset in E2E_CLOCK_SHIFT_FILE (milliseconds; re-read when the file changes), so a test can jump the
+// wall clock forward, as a laptop's sleep does, or back, as an NTP correction does. The monotonic
+// clocks (`performance.now`, timers) are untouched: on macOS they do not count a sleep either.
+import { readFileSync, statSync } from 'node:fs'
+
+const file = process.env.E2E_CLOCK_SHIFT_FILE
+const RealDate = Date
+const realNow = RealDate.now.bind(RealDate)
+let offset = 0
+let seen = -1
+let checkedAt = 0
+
+function shift() {
+ const now = realNow()
+ if (file && now - checkedAt >= 50) {
+ checkedAt = now
+ try {
+ const changed = statSync(file).mtimeMs
+ if (changed !== seen) { seen = changed; offset = Number(readFileSync(file, 'utf8').trim()) || 0 }
+ } catch { /* no file yet: no shift */ }
+ }
+ return offset
+}
+
+globalThis.Date = new Proxy(RealDate, {
+ construct(target, args, newTarget) {
+ return args.length ? Reflect.construct(target, args, newTarget) : Reflect.construct(target, [realNow() + shift()], newTarget)
+ },
+ apply() {
+ return new RealDate(realNow() + shift()).toString()
+ },
+ get(target, property, receiver) {
+ if (property === 'now') return () => realNow() + shift()
+ return Reflect.get(target, property, receiver)
+ },
+})
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index e27492380..d945eb8f3 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -758,12 +758,24 @@ function bootTimeSec() {
return Math.round(Date.now() / 1000 - uptime())
}
+// Which boot this is, named as src/lib/bootId.ts names it: the two read and write the same boot file, so
+// they must agree. macOS has a per-boot id too; without it a boot was named by the moment it began, which
+// moves with every step of the wall clock, and a hook that fell back to the registry after an NTP step
+// or a long sleep took the step for a reboot and wrote a registry of its one agent (round 29).
+let bootId = null
function currentBootId() {
+ if (bootId) return bootId
try {
const value = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
- if (/^[0-9a-f-]{36}$/i.test(value)) return `linux:${value}`
- } catch { /* non-Linux fallback below */ }
- return `time:${bootTimeSec()}`
+ if (/^[0-9a-f-]{36}$/i.test(value)) return (bootId = `linux:${value}`)
+ } catch { /* not Linux */ }
+ if (process.platform === 'darwin') {
+ try {
+ const value = execFileSync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], { encoding: 'utf8', timeout: 1000 }).trim()
+ if (/^[0-9a-f-]{36}$/i.test(value)) return (bootId = `macos:${value}`)
+ } catch { /* sysctl unavailable: the moment the boot began, below */ }
+ }
+ return (bootId = `time:${bootTimeSec()}`)
}
function readSavedBoot(bootFile) {
@@ -807,6 +819,8 @@ function rebootedSinceSnapshot(bootFile) {
if (saved === null) return false
const current = currentBootId()
if (saved.startsWith('linux:')) return saved !== current
+ // A macOS id that cannot be read now is no evidence of a reboot.
+ if (saved.startsWith('macos:')) return !current.startsWith('time:') && saved !== current
const savedNumber = Number(saved.replace(/^time:/, ''))
const currentNumber = current.startsWith('time:') ? Number(current.slice(5)) : bootTimeSec()
return !Number.isFinite(savedNumber) || Math.abs(currentNumber - savedNumber) > BOOT_TOLERANCE_SEC
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 723c328c3..fb06e307a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2072,7 +2072,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Following a session: its history read into its engine's normalizer, then its tail
// (core/transcripts/attach.ts).
const attach = createAttach({
- validateTerminal,
+ terminalGone: terminalControl.terminalGone,
normalizers,
watcher,
cursorDiscovery,
diff --git a/cli/src/core/terminals/control.spec.ts b/cli/src/core/terminals/control.spec.ts
index 80133d88a..8a9cecef3 100644
--- a/cli/src/core/terminals/control.spec.ts
+++ b/cli/src/core/terminals/control.spec.ts
@@ -210,4 +210,17 @@ describe('terminal control', () => {
fake.alive = false
expect(await control.validateTerminal(session)).toBe(false)
})
+
+ it('calls a terminal gone only when it is known to be, never on a probe that could not answer', async () => {
+ const { fake, terminals } = backend()
+ const control = createTerminalControl({ resolve, terminals })
+ expect(await control.terminalGone(session)).toBe(false)
+ fake.alive = false
+ expect(await control.terminalGone(session)).toBe(true)
+ // A probe that timed out at a wake: no reason to write to the pane, and no evidence it is gone.
+ vi.mocked(terminals.validate).mockResolvedValueOnce({ state: 'unknown', reason: 'tmux runtime probe failed' })
+ expect(await control.terminalGone(session)).toBe(false)
+ vi.mocked(terminals.validate).mockResolvedValueOnce({ state: 'unknown', reason: 'tmux runtime probe failed' })
+ expect(await control.validateTerminal(session)).toBe(false)
+ })
})
diff --git a/cli/src/core/terminals/control.ts b/cli/src/core/terminals/control.ts
index 2a4c62647..f2039ae11 100644
--- a/cli/src/core/terminals/control.ts
+++ b/cli/src/core/terminals/control.ts
@@ -118,9 +118,17 @@ export function createTerminalControl({ resolve, terminals }: TerminalControlDep
}
const validateTerminal = async (session: RegisteredSession): Promise<boolean> =>
(await terminals.validate(session)).state === 'alive'
+ /**
+ * Whether a session's terminal is known to be gone: the agent is dormant, tmux has no such pane, or
+ * another process is in it. Not the same question as `validateTerminal`, which is the one to ask before
+ * writing to a pane: a probe that could not answer (it timed out, or the process table could not be
+ * read) is no reason to write, and no evidence either that the terminal is gone.
+ */
+ const terminalGone = async (session: RegisteredSession): Promise<boolean> =>
+ (await terminals.validate(session)).state === 'gone'
return {
pinnedControls, pinTerminalControl, invalidateTerminalControl, captureTerminal, submitTerminalAction,
- submitTerminal, typeTerminal, keyTerminalAction, keyTerminal, validateTerminal,
+ submitTerminal, typeTerminal, keyTerminalAction, keyTerminal, validateTerminal, terminalGone,
}
}
diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.ts
index 56a141505..a2c0d825d 100644
--- a/cli/src/core/transcripts/attach.spec.ts
+++ b/cli/src/core/transcripts/attach.spec.ts
@@ -73,7 +73,7 @@ function setup(over: Partial<AttachDeps> = {}) {
const service = { needsTranscript: vi.fn(() => false), observeTranscript: vi.fn() }
const profile = { ingest: vi.fn(), commit: vi.fn() }
const deps: AttachDeps = {
- validateTerminal: vi.fn(async () => true),
+ terminalGone: vi.fn(async () => false),
normalizers,
watcher: { addSession: vi.fn(async () => {}), hold: vi.fn(async () => null), tails: vi.fn(() => false) },
cursorDiscovery: { add: vi.fn(async () => {}) },
@@ -111,7 +111,7 @@ describe('attaching a session', () => {
})
it('refuses a session whose pane is gone', async () => {
- const { attach, deps } = setup({ validateTerminal: vi.fn(async () => false) })
+ const { attach, deps } = setup({ terminalGone: vi.fn(async () => true) })
expect(await attach.attachSession(session('pi', transcript()))).toBe(false)
expect(deps.watcher.addSession).not.toHaveBeenCalled()
})
@@ -416,7 +416,7 @@ describe('attaching a session', () => {
it('says when an attach is slow', async () => {
vi.useFakeTimers()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- const run = setup({ validateTerminal: () => new Promise<boolean>(() => {}) })
+ const run = setup({ terminalGone: () => new Promise<boolean>(() => {}) })
void run.attach.attachSession(session('pi', '/t/pi.jsonl'))
await vi.advanceTimersByTimeAsync(15_000)
expect(String(warn.mock.calls[0][0])).toMatch(/attach still running · engine=pi · session=.* · 15s/)
diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.ts
index a26099f4a..089a19c41 100644
--- a/cli/src/core/transcripts/attach.ts
+++ b/cli/src/core/transcripts/attach.ts
@@ -38,7 +38,8 @@ import type { SessionNormalizers } from './normalizers.js'
import type { RelaunchMarks } from './relaunch.js'
export interface AttachDeps {
- validateTerminal: (session: RegisteredSession) => Promise<boolean>
+ /** Whether the session's terminal is known to be gone (core/terminals/control.ts `terminalGone`). */
+ terminalGone: (session: RegisteredSession) => Promise<boolean>
normalizers: SessionNormalizers
watcher: Pick<Watcher, 'addSession' | 'hold' | 'tails'>
cursorDiscovery: Pick<CursorTranscriptDiscovery, 'add'>
@@ -65,7 +66,7 @@ export interface AttachDeps {
}
export function createAttach({
- validateTerminal, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,
+ terminalGone, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,
announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency, relaunchMarks,
wholeReadCapBytes = WHOLE_READ_CAP_BYTES,
}: AttachDeps) {
@@ -116,7 +117,12 @@ export function createAttach({
* its normalizer stopped — the byte the tail resumes from. */
handover: { hold: TailHold | null; next: number | null } = { hold: null, next: null },
): Promise<boolean> => {
- if (!await validateTerminal(session)) return false
+ // Only a terminal known to be gone refuses an attach, never a probe that could not answer. A failed
+ // attach costs the agent its binding (agents/bind.ts) or its place among the active (discovery.ts),
+ // and a probe in flight when the machine slept times out at the wake before its answer is read: the
+ // session of an agent still at work was unbound that way two seconds after a laptop woke (round 29,
+ // e2e/clockjump.e2e.ts). A terminal that really is gone is retired by the reconciler's confirmed scans.
+ if (await terminalGone(session)) return false
// Taken whichever way this attach goes: a mark is for the next attach of the conversation only.
const relaunchedAt = relaunchMarks?.take(session.sessionId)
if (!reset && normalizers.hasState(session.sessionId)) {
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index e7e16e5cc..0315f64e0 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -14,6 +14,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 })
const HOOK = fileURLToPath(new URL('../hook/notify.mjs', import.meta.url))
+/** A preload that moves `Date` by the milliseconds in a file (e2e/harness/clockShift.mjs). */
+const CLOCK_SHIFT = fileURLToPath(new URL('../e2e/harness/clockShift.mjs', import.meta.url))
const servers: ReturnType<typeof createServer>[] = []
const netServers: ReturnType<typeof createNetServer>[] = []
const tmpDirs: string[] = []
@@ -930,6 +932,46 @@ describe('hook notify terminal scope', () => {
{ sessionId: 'fresh', tmuxPane: '%12' },
])
})
+
+ it('does not take a step of the wall clock for a reboot, and keeps every other agent', async () => {
+ // A boot named by the moment it began moved with the clock, and a hook that fell back to the
+ // registry hours after a laptop slept, or after an NTP step, took it for a reboot and wrote a
+ // registry of its one agent (round 29).
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-clock-'))
+ tmpDirs.push(dir)
+ const claudeProjectsDir = join(dir, 'claude-projects')
+ const dataDir = join(dir, 'data')
+ mkdirSync(join(claudeProjectsDir, 'demo'), { recursive: true })
+ mkdirSync(dataDir, { recursive: true })
+ chmodSync(dataDir, 0o755)
+ const otherTranscript = join(claudeProjectsDir, 'demo', 'other.jsonl')
+ writeFileSync(otherTranscript, '{}\n')
+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([{
+ schemaVersion: 2, active: true, agentId: 'agent-other', sessionId: 'other', boundAt: 1, engine: 'claude',
+ gateway: null, grid: null, codexHome: null, transcriptPath: otherTranscript, projectDir: 'demo', cwd: '/tmp/demo',
+ runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux\u0000%1', tmuxPane: '%1',
+ source: null, title: null, model: null, cliVersion: null,
+ processIdentity: { pid: 5001, executable: 'claude', startMarker: 'Mon Aug 10 09:00:00 2026' },
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }]))
+ const register = (sessionId: string, env?: Record<string, string>) => {
+ const transcriptPath = join(claudeProjectsDir, 'demo', `${sessionId}.jsonl`)
+ writeFileSync(transcriptPath, '{}\n')
+ return runHook({
+ port: 9, tmuxPane: '%12', processEngine: 'claude', dataDir, claudeProjectsDir, env,
+ input: { hook_event_name: 'SessionStart', session_id: sessionId, transcript_path: transcriptPath },
+ })
+ }
+ // This boot's mark is written by the first offline write; then the clock moves three hours on, in
+ // the hook as in the engine that runs it.
+ await register('before')
+ expect(statSync(join(dataDir, 'registry-boot')).isFile()).toBe(true)
+ const shift = join(dir, 'shift')
+ writeFileSync(shift, String(3 * 3_600_000))
+ await register('after', { NODE_OPTIONS: `--import ${CLOCK_SHIFT}`, E2E_CLOCK_SHIFT_FILE: shift })
+ const rows = JSON.parse(readFileSync(join(dataDir, 'registry.json'), 'utf-8')) as Array<{ sessionId: string }>
+ expect(rows.map((row) => row.sessionId).sort()).toEqual(['after', 'other'])
+ })
})
describe('hook notify Grok lifecycle', () => {
diff --git a/cli/src/lib/bootId.spec.ts b/cli/src/lib/bootId.spec.ts
new file mode 100644
index 000000000..bd7560862
--- /dev/null
+++ b/cli/src/lib/bootId.spec.ts
@@ -0,0 +1,63 @@
+import { uptime } from 'node:os'
+import { describe, expect, it } from 'vitest'
+import { BOOT_TOLERANCE_SEC, bootChanged, currentBootId, SYSTEM_BOOT_SOURCES, type BootSources } from './bootId.js'
+
+/** Which boot of the machine this is, and whether a saved mark was written in an earlier one. */
+const LINUX = 'd6c8c2f0-3a5e-4b8f-9f3e-1c2d3e4f5a6b'
+const MAC = '901041CC-91D0-439E-9A41-8677710EEDC0'
+const BOOTED = 1_790_000_000
+const sources = (over: Partial<BootSources> = {}): BootSources => ({
+ platform: 'darwin',
+ linuxBootId: () => { throw new Error('ENOENT') },
+ macosBootId: () => `${MAC}\n`,
+ bootTimeSec: () => BOOTED,
+ ...over,
+})
+
+describe('naming this boot', () => {
+ it('by the kernel\'s id on Linux, and by kern.bootsessionuuid on macOS', () => {
+ expect(currentBootId(sources({ platform: 'linux', linuxBootId: () => `${LINUX}\n` }))).toBe(`linux:${LINUX}`)
+ expect(currentBootId(sources())).toBe(`macos:${MAC}`)
+ })
+
+ it('by the moment it began where no id can be read, or what is read is not one', () => {
+ expect(currentBootId(sources({ macosBootId: () => { throw new Error('sysctl: not found') } }))).toBe(`time:${BOOTED}`)
+ expect(currentBootId(sources({ macosBootId: () => 'kern.bootsessionuuid: unknown oid' }))).toBe(`time:${BOOTED}`)
+ expect(currentBootId(sources({ platform: 'linux', linuxBootId: () => 'garbage' }))).toBe(`time:${BOOTED}`)
+ // Never sysctl off macOS, whatever it would say.
+ expect(currentBootId(sources({ platform: 'freebsd' }))).toBe(`time:${BOOTED}`)
+ })
+
+ it('reads this machine for real: an id on Linux and macOS, a moment elsewhere', () => {
+ const mark = currentBootId(SYSTEM_BOOT_SOURCES)
+ expect(mark).toMatch(process.platform === 'linux' ? /^linux:/ : process.platform === 'darwin' ? /^(macos|time):/ : /^time:/)
+ expect(currentBootId()).toBe(mark)
+ expect(Math.abs(SYSTEM_BOOT_SOURCES.bootTimeSec() - (Date.now() / 1000 - uptime()))).toBeLessThan(2)
+ })
+})
+
+describe('whether the machine rebooted', () => {
+ it('not when nothing was saved', () => {
+ expect(bootChanged(null, `macos:${MAC}`, sources())).toBe(false)
+ })
+
+ it('by the ids on Linux and macOS, whatever the wall clock did meanwhile', () => {
+ const stepped = sources({ bootTimeSec: () => BOOTED + 3 * 3600 })
+ expect(bootChanged(`macos:${MAC}`, `macos:${MAC}`, stepped)).toBe(false)
+ expect(bootChanged(`macos:${MAC}`, `macos:${LINUX}`, stepped)).toBe(true)
+ expect(bootChanged(`linux:${LINUX}`, `linux:${LINUX}`, stepped)).toBe(false)
+ expect(bootChanged(`linux:${LINUX}`, `linux:${MAC}`, stepped)).toBe(true)
+ })
+
+ it('not on a macOS id that cannot be read now: that is no evidence of a reboot', () => {
+ expect(bootChanged(`macos:${MAC}`, `time:${BOOTED}`, sources())).toBe(false)
+ })
+
+ it('by the moment the boot began for a mark an older build wrote, once, with two minutes\' grace', () => {
+ expect(bootChanged(`time:${BOOTED}`, `macos:${MAC}`, sources({ bootTimeSec: () => BOOTED + BOOT_TOLERANCE_SEC }))).toBe(false)
+ expect(bootChanged(`time:${BOOTED}`, `macos:${MAC}`, sources({ bootTimeSec: () => BOOTED + BOOT_TOLERANCE_SEC + 1 }))).toBe(true)
+ expect(bootChanged(String(BOOTED), `time:${BOOTED - 30}`, sources())).toBe(false)
+ expect(bootChanged('time:1', `time:${BOOTED}`, sources())).toBe(true)
+ expect(bootChanged('not a mark', `time:${BOOTED}`, sources())).toBe(true)
+ })
+})
diff --git a/cli/src/lib/bootId.ts b/cli/src/lib/bootId.ts
new file mode 100644
index 000000000..31e29549c
--- /dev/null
+++ b/cli/src/lib/bootId.ts
@@ -0,0 +1,67 @@
+/**
+ * Which boot of the machine this is: how the registry knows, at start, that the machine rebooted while
+ * the daemon was down, and so that every process it remembers is gone and every agent is dormant.
+ *
+ * Linux and macOS each give a boot its own id: the kernel's boot_id, and `kern.bootsessionuuid`. Where
+ * neither can be read, the boot is named by the moment it began, the wall clock less the uptime, and
+ * two such marks are the same boot when they are within two minutes of each other. That rule is wrong
+ * after any step of the wall clock: an NTP correction, a virtual machine resumed or a laptop's clock set
+ * after a long sleep moves the boot's moment by the whole step, and a daemon restarted then decided the
+ * machine had rebooted and marked every agent dormant. On macOS that was the only rule there was.
+ *
+ * A mark written by an older build, a number, is compared by time once, against the moment this boot
+ * began; the boot's own id is written after it, so the comparison happens on one migration only.
+ *
+ * hook/notify.mjs reads and writes the same file and keeps its own copy of these rules: change both.
+ */
+import { execFileSync } from 'node:child_process'
+import { readFileSync } from 'node:fs'
+import { uptime } from 'node:os'
+
+/** Clock and NTP drift is seconds; a reboot moves the boot's moment by the whole uptime. */
+export const BOOT_TOLERANCE_SEC = 120
+const BOOT_UUID_RE = /^[0-9a-f-]{36}$/i
+
+export interface BootSources {
+ platform: NodeJS.Platform
+ /** The Linux kernel's id for this boot. */
+ linuxBootId: () => string
+ /** macOS's id for this boot (`sysctl -n kern.bootsessionuuid`). */
+ macosBootId: () => string
+ /** When this boot began, by the wall clock, in seconds. */
+ bootTimeSec: () => number
+}
+
+export const SYSTEM_BOOT_SOURCES: BootSources = {
+ platform: process.platform,
+ linuxBootId: () => readFileSync('/proc/sys/kernel/random/boot_id', 'utf8'),
+ // By its full path: a daemon started from a shell whose PATH lacks /usr/sbin still finds it.
+ macosBootId: () => execFileSync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], { encoding: 'utf8', timeout: 2_000 }),
+ bootTimeSec: () => Math.round(Date.now() / 1000 - uptime()),
+}
+
+/** This boot's mark: `linux:<id>`, `macos:<id>`, or `time:<seconds>` where neither id can be read. */
+export function currentBootId(sources: BootSources = SYSTEM_BOOT_SOURCES): string {
+ try {
+ const value = sources.linuxBootId().trim()
+ if (BOOT_UUID_RE.test(value)) return `linux:${value}`
+ } catch { /* not Linux */ }
+ if (sources.platform === 'darwin') {
+ try {
+ const value = sources.macosBootId().trim()
+ if (BOOT_UUID_RE.test(value)) return `macos:${value}`
+ } catch { /* sysctl unavailable: the moment the boot began, below */ }
+ }
+ return `time:${sources.bootTimeSec()}`
+}
+
+/** Whether `current` is a later boot than the one `saved` was written in. Nothing saved is no reboot. */
+export function bootChanged(saved: string | null, current: string, sources: BootSources = SYSTEM_BOOT_SOURCES): boolean {
+ if (!saved) return false
+ if (saved.startsWith('linux:')) return saved !== current
+ // A macOS id that cannot be read now is no evidence of a reboot.
+ if (saved.startsWith('macos:')) return !current.startsWith('time:') && saved !== current
+ const savedNumber = Number(saved.replace(/^time:/, ''))
+ const currentNumber = current.startsWith('time:') ? Number(current.slice(5)) : sources.bootTimeSec()
+ return !Number.isFinite(savedNumber) || Math.abs(currentNumber - savedNumber) > BOOT_TOLERANCE_SEC
+}
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index ac39156a2..ff7673e05 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1485,6 +1485,30 @@ describe('registry across a reboot and pane loss', () => {
expect(registry.byProcess('claude', processIdentity(4242))?.agentId).toBe('agent-a')
})
+ it('does not take a step of the wall clock for a reboot', async () => {
+ // A boot named by the moment it began moved with the clock: a daemon restarted after an NTP step,
+ // a virtual machine resumed or a long sleep marked every agent dormant (round 29). macOS has a
+ // per-boot id; Linux always used its own.
+ const transcriptPath = join(dataDir, 'session-a.jsonl')
+ writeFileSync(transcriptPath, '{}\n')
+ chmodSync(dataDir, 0o755)
+ writeLegacyStateFile(join(dataDir, 'registry.json'), JSON.stringify([persistedRow(transcriptPath)]))
+ const first = await loadRegistryModule()
+ first.registry.load()
+ expect(first.registry.rebootedSinceLastRun).toBe(false)
+
+ vi.useFakeTimers({ toFake: ['Date'] })
+ try {
+ vi.setSystemTime(Date.now() + 3 * 3_600_000)
+ const again = await loadRegistryModule()
+ again.registry.load()
+ expect(again.registry.rebootedSinceLastRun).toBe(false)
+ expect(again.registry.byAgent('agent-a')?.processIdentity).toEqual(processIdentity(4242))
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('keeps the permission mode from agent_create through a bind and a reload', async () => {
const transcriptPath = join(dataDir, 'session-p.jsonl')
writeFileSync(transcriptPath, '{}\n')
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index e95d41c0c..ca6c64498 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -37,7 +37,7 @@ import {
} from 'fs'
import { randomUUID } from 'crypto'
import { join, basename, dirname, relative, isAbsolute } from 'path'
-import { hostname, uptime } from 'os'
+import { hostname } from 'os'
import { cursorDataDir } from '../engines/cursor/home.js'
import { env } from '../config/env.js'
import { claudeProjectsRoots, codexHomeRoots } from './engineHomes.js'
@@ -48,6 +48,7 @@ import { parseGridLaunchOverride, type GridLaunchOverride, type GridLaunchRecord
import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'
import { agyTranscriptPath } from '../engines/agy/session.js'
import { copilotTranscriptPath } from '../engines/copilot/session.js'
+import { bootChanged, currentBootId } from './bootId.js'
import { lockOwnerAlive, lockStartMarker, processLockIdentity } from './processLiveness.js'
import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from './secureState.js'
import { mergeTerminalRuntimes, processIdentityKey, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
@@ -799,18 +800,7 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string, codex
}
}
-/** Prefer the kernel boot UUID; retain numeric marker compatibility for one migration. */
-const BOOT_TOLERANCE_SEC = 120 // clock/NTP drift is seconds; a reboot shifts boot time by the whole uptime
-function bootTimeSec(): number {
- return Math.round(Date.now() / 1000 - uptime())
-}
-function currentBootId(): string {
- try {
- const value = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim()
- if (/^[0-9a-f-]{36}$/i.test(value)) return `linux:${value}`
- } catch { /* non-Linux fallback below */ }
- return `time:${bootTimeSec()}`
-}
+/** The boot the registry was last loaded in (lib/bootId.ts says how a boot is named). */
function readSavedBoot(): string | null {
try {
const raw = readPrivateStateFile(BOOT_FILE, 256).trim()
@@ -821,13 +811,6 @@ function readSavedBoot(): string | null {
} catch { return raw }
} catch { return null }
}
-function bootChanged(saved: string | null, current: string): boolean {
- if (!saved) return false
- if (saved.startsWith('linux:')) return saved !== current
- const savedNumber = Number(saved.replace(/^time:/, ''))
- const currentNumber = current.startsWith('time:') ? Number(current.slice(5)) : bootTimeSec()
- return !Number.isFinite(savedNumber) || Math.abs(currentNumber - savedNumber) > BOOT_TOLERANCE_SEC
-}
function writeBoot(bootId: string): void {
try {
secureStateDirectory(env.ADAPTER_DATA_DIR)