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.

fix(cli): keep agent ids across a Linux clock step (#1018)

0xken15b6d27eff6ede
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index c38c13f7c..52cc2338b 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -13,6 +13,7 @@ import { AgentRestartCoordinator, type RestartAgentDeps } from '../../lib/restar
import { processRows } from '../../lib/terminalAgentDiscovery.js'
import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'
import { bypassPermissionActive, resolvePaneEngineProcess } from '../../lib/tmux.js'
+import { sameProcessIdentity } from '../../lib/terminalRuntime.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
export interface PaneSwapDeps {
@@ -95,7 +96,7 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
await new Promise((resolve) => setTimeout(resolve, SWAP_SETTLE_MS))
waited += SWAP_SETTLE_MS
const still = await resolvePaneEngineProcess(runtime.paneId, session.engine)
- if (still && still.pid === found.pid && still.startMarker === found.startMarker) return found
+ if (sameProcessIdentity(still, found)) return found
}
delayMs = Math.min(delayMs * 2, 750)
}
@@ -130,8 +131,7 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
const identity = session.processIdentity
if (!identity) return false
const rows = await processRows()
- const row = rows?.find((candidate) =>
- candidate.pid === identity.pid && candidate.startMarker === identity.startMarker)
+ const row = rows?.find((candidate) => sameProcessIdentity(candidate, identity))
return row ? bypassPermissionActive(session.engine, row.args) : false
}
return { restartJobs, sameRestartTarget, paneSwapDeps, liveBypassPermission }
diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.ts
index f4b5a58d4..4d4d9ea5f 100644
--- a/cli/src/core/engines/hooks.ts
+++ b/cli/src/core/engines/hooks.ts
@@ -17,6 +17,7 @@ import { sid } from '../../lib/log.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
import { processRows } from '../../lib/terminalAgentDiscovery.js'
import type { ProcessRow } from '../../lib/tmux.js'
+import { sameProcessIdentity } from '../../lib/terminalRuntime.js'
import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import type { TerminalRuntimeRef } from '../../lib/terminalTypes.js'
@@ -59,7 +60,7 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: En
if (!rows) return null
const recordedAlive = (session: RegisteredSession): boolean => {
const recorded = session.processIdentity
- return !!recorded && rows.some((row) => row.pid === recorded.pid && row.startMarker === recorded.startMarker)
+ return !!recorded && rows.some((row) => sameProcessIdentity(row, recorded))
}
const callerBelongsTo = (session: RegisteredSession): boolean => {
const expectedPid = session.processIdentity?.pid
diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.ts
index babcf11e6..27383a66d 100644
--- a/cli/src/lib/captureResumeIdentity.ts
+++ b/cli/src/lib/captureResumeIdentity.ts
@@ -10,6 +10,7 @@
import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
import { claudeProcessSession, findLiveSession, findResumedTranscript } from './sessionRepair.js'
import { processRows, resumeSessionId } from './tmux.js'
+import { sameProcessIdentity } from './terminalRuntime.js'
import { isTerminalEngine } from '../engines/types.js'
export async function captureResumeIdentity(session: RegisteredSession): Promise<RegisteredSession> {
@@ -28,8 +29,8 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise
}
const expected = session.processIdentity
if (!expected || !session.cwd) return session
- const live = (await processRows())?.find(row => row.pid === expected.pid
- && row.executable === expected.executable && row.startMarker === expected.startMarker)
+ const live = (await processRows())?.find(row => sameProcessIdentity(row, expected)
+ && row.executable === expected.executable)
if (!live) return session
const explicit = resumeSessionId(session.engine, live.args)
const native = session.engine === 'claude'
diff --git a/cli/src/lib/codexSessionLifecycle.ts b/cli/src/lib/codexSessionLifecycle.ts
index fedf67e86..799088e05 100644
--- a/cli/src/lib/codexSessionLifecycle.ts
+++ b/cli/src/lib/codexSessionLifecycle.ts
@@ -10,6 +10,7 @@ import WebSocket from 'ws'
import { sessionCodexHome } from './engineHomes.js'
import { engineBin } from './engineBin.js'
import { argvTokens, processRows, type ProcessRow } from './tmux.js'
+import { sameProcessIdentity } from './terminalRuntime.js'
import type { RegisteredSession } from './registry.js'
export interface CodexControl {
@@ -108,7 +109,7 @@ export async function stopSharedCodexSession(session: RegisteredSession, current
guard()
return
}
- const owner = rows.find(row => row.pid === session.processIdentity?.pid && row.startMarker === session.processIdentity?.startMarker && row.executable === session.processIdentity?.executable)
+ const owner = rows.find(row => sameProcessIdentity(row, session.processIdentity) && row.executable === session.processIdentity?.executable)
if (owner) {
const args = argvTokens(owner.args)
// Harness inserts this as the FIRST option, before resume/fork or prompt
diff --git a/cli/src/lib/deleteAgentFallback.ts b/cli/src/lib/deleteAgentFallback.ts
index de254a08b..20e1e205d 100644
--- a/cli/src/lib/deleteAgentFallback.ts
+++ b/cli/src/lib/deleteAgentFallback.ts
@@ -2,6 +2,7 @@
import type { RegisteredSession } from './registry.js'
import { processRows, type RuntimeCheck } from './tmux.js'
+import { sameProcessIdentity } from './terminalRuntime.js'
/** Delete has already removed the UI entry; signal the saved process immediately. */
export const TERMINATE_CHECK_MS = 0
@@ -24,7 +25,7 @@ export async function checkPidRuntime(
const rows = await processRows()
if (!rows) return { state: 'unknown', reason: 'process table is unavailable' }
const live = rows.find((row) => row.pid === expected.pid)
- return live && live.startMarker === expected.startMarker && live.executable === expected.executable
+ return live && sameProcessIdentity(live, expected) && live.executable === expected.executable
? { state: 'alive' }
: { state: 'gone', reason: 'saved process identity is no longer running' }
}
diff --git a/cli/src/lib/harnessResources.spec.ts b/cli/src/lib/harnessResources.spec.ts
index 551185efa..f8c7aed76 100644
--- a/cli/src/lib/harnessResources.spec.ts
+++ b/cli/src/lib/harnessResources.spec.ts
@@ -51,6 +51,19 @@ not a process`)).toEqual([
}
})
+ it('still attributes a process whose ps start time moved with the clock, by its start ticks', async () => {
+ const ticked = (agentId: string, pid: number, startTicks: number) =>
+ ({ agentId, processIdentity: { ...agent(agentId, pid).processIdentity, startTicks } })
+ const read = createHarnessResourcesReader(() => [ticked('stepped', 10, 500), ticked('reused', 20, 600)], {
+ sample: async () => [{ ...row(10), start: 'Thu Oct 1 01:00:00 2026' }, { ...row(20), start: 'Thu Oct 1 01:00:00 2026' }],
+ now: () => 10_000, startTicks: (pid) => pid === 10 ? 500 : 601,
+ })
+ expect((await read()).agents).toEqual([
+ { agentId: 'stepped', memoryBytes: 100, processCount: 1, cpuPercent: null },
+ { agentId: 'reused', memoryBytes: null, processCount: null, cpuPercent: null },
+ ])
+ })
+
it('coalesces concurrent clients, expires cached data and retries failed reads', async () => {
let now = 10_000
let finish!: (rows: ResourceProcess[]) => void
diff --git a/cli/src/lib/harnessResources.ts b/cli/src/lib/harnessResources.ts
index 777ac5023..c660e16a2 100644
--- a/cli/src/lib/harnessResources.ts
+++ b/cli/src/lib/harnessResources.ts
@@ -6,6 +6,7 @@ import { promisify } from 'node:util'
import type { ProcessIdentity } from './terminalTypes.js'
import { readProcessTelemetry, type ProcessTelemetry } from './harnessTelemetry.js'
import { macProcessGpuPercent } from './macosProcessGpu.js'
+import { processStartTicks } from './processLiveness.js'
const exec = promisify(execFile)
type Agent = { agentId: string; processIdentity?: ProcessIdentity | null; engine?: string; codexHome?: string | null; transcriptPath?: string | null }
@@ -90,6 +91,7 @@ async function sharedCodexRoots(agents: readonly Agent[]): Promise<SharedResourc
export function createHarnessResourcesReader(agents: () => readonly Agent[], deps: {
sample: () => Promise<ResourceProcess[]>; now: () => number
telemetry?: (pids: number[]) => Promise<Map<number, ProcessTelemetry>>
+ startTicks?: (pid: number) => number | null
} = {
sample: sampleProcesses, now: Date.now, telemetry: readProcessTelemetry,
}, sharedRoots: (agents: readonly Agent[]) => Promise<SharedResourceRoot[]> = sharedCodexRoots) {
@@ -111,7 +113,10 @@ export function createHarnessResourcesReader(agents: () => readonly Agent[], dep
const owners = new Map<number, string[]>()
for (const agent of current) {
const identity = agent.processIdentity
- if (!identity || byPid.get(identity.pid)?.start !== identity.startMarker.replace(/\s+/g, ' ')) continue
+ if (!identity || !byPid.has(identity.pid)) continue
+ // A clock step moves `ps lstart` but not the start ticks (ProcessIdentity.startTicks).
+ if (byPid.get(identity.pid)!.start !== identity.startMarker.replace(/\s+/g, ' ')
+ && (identity.startTicks === undefined || (deps.startTicks ?? processStartTicks)(identity.pid) !== identity.startTicks)) continue
owners.set(identity.pid, [...owners.get(identity.pid) ?? [], agent.agentId])
}
const elapsed = previous ? at - previous.at : 0
diff --git a/cli/src/lib/processLiveness.ts b/cli/src/lib/processLiveness.ts
index 788e427ec..5a065f46a 100644
--- a/cli/src/lib/processLiveness.ts
+++ b/cli/src/lib/processLiveness.ts
@@ -20,13 +20,21 @@ export function processExists(pid: number): boolean {
}
}
-export function processStartMarker(pid: number): string | null {
+/** Linux: when `pid` started, in clock ticks since boot; null elsewhere or once it has exited. */
+export function processStartTicks(pid: number): number | null {
if (!Number.isSafeInteger(pid) || pid <= 0) return null
try {
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
- const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/)
- if (fields[19]) return `linux:${fields[19]}`
- } catch { /* non-Linux or exited process; use ps below */ }
+ // `pid (comm) S ...`: comm may hold spaces and parentheses, so fields count from the LAST `)`.
+ const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/)[19])
+ return Number.isSafeInteger(ticks) && ticks >= 0 ? ticks : null
+ } catch { return null }
+}
+
+export function processStartMarker(pid: number): string | null {
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null
+ const ticks = processStartTicks(pid)
+ if (ticks !== null) return `linux:${ticks}`
try {
const started = execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], {
encoding: 'utf8', timeout: 1_000, env: { ...psEnv(), TZ: 'UTC' },
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 652055cfd..c207d54dc 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1022,6 +1022,56 @@ describe('agent identity: the process owns the agent, the session is bound to it
expect(registry.resolve('s1')).toBeUndefined()
})
+ it('keeps a bound agent across a clock step that moved its ps start time but not its start ticks', async () => {
+ // machine-remote-1, 2026-10-07: the Docker VM's clock was resynced after the Mac slept, every
+ // `ps lstart` moved by hours, and each pane's unchanged engine got a new agent id.
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ const before = { ...processIdentity(101), startTicks: 26385008 }
+ registry.openProcessAgent({ agentId: 'bound-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: before })
+ registerProcess(registry, {
+ launcherId: 'bound-agent', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo',
+ })
+
+ const stepped = { ...before, startMarker: 'Tue Aug 11 01:00:41 2026' }
+ const observed = registry.openProcessAgent({ engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: stepped })
+
+ expect(observed).toMatchObject({ isNew: false, evicted: null })
+ expect(observed?.entry.agentId).toBe('bound-agent')
+ expect(observed?.entry.sessionId).toBe('s1')
+ expect(registry.byProcess('claude', stepped)?.agentId).toBe('bound-agent')
+
+ // Same pid, other ticks: a different process that reused the pid, whatever its marker says.
+ const reused = registry.openProcessAgent({
+ agentId: 'replacement-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
+ processIdentity: { ...stepped, startTicks: 26385009 },
+ })
+ expect(reused?.entry.agentId).toBe('replacement-agent')
+ expect(reused?.evicted).toEqual({ agentId: 'bound-agent', sessionId: 's1' })
+ })
+
+ it('matches a row saved without start ticks by its marker once, then keeps the ticks', async () => {
+ const { registry } = await loadRegistryModule()
+ registry.load()
+ registry.openProcessAgent({ agentId: 'bound-agent', engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: processIdentity(101) })
+ registerProcess(registry, {
+ launcherId: 'bound-agent', sessionId: 's1', transcriptPath: transcript('s1'), tmuxPane: '%1', cwd: '/tmp/demo',
+ })
+
+ const upgraded = registry.openProcessAgent({
+ engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo', processIdentity: { ...processIdentity(101), startTicks: 7 },
+ })
+ expect(upgraded).toMatchObject({ isNew: false, evicted: null })
+ expect(registry.byAgent('bound-agent')?.processIdentity?.startTicks).toBe(7)
+
+ const stepped = registry.openProcessAgent({
+ engine: 'claude', tmuxPane: '%1', cwd: '/tmp/demo',
+ processIdentity: { ...processIdentity(101), startMarker: 'Tue Aug 11 01:00:41 2026', startTicks: 7 },
+ })
+ expect(stepped?.entry.agentId).toBe('bound-agent')
+ expect(stepped?.evicted).toBeNull()
+ })
+
it('removes an agent a resume left with no session and no process', async () => {
// `claude --resume` in a second pane after quitting the first: the session
// moves, and the agent it moved from has nothing left to be. Kept, it is a
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 7dd3640d8..478710d68 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -52,7 +52,7 @@ 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'
+import { mergeTerminalRuntimes, processIdentityKey, sameProcessIdentity, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
import type { HookTerminalHint, ProcessIdentity, TerminalRuntimeRef } from './terminalTypes.js'
export type { ProcessIdentity } from './terminalTypes.js'
@@ -1225,10 +1225,7 @@ class Registry {
// place instead of deleting/recreating its tile. Once bound, process identity remains strict.
!agent.sessionId
|| !agent.processIdentity
- || (
- agent.processIdentity.pid === processIdentity.pid
- && agent.processIdentity.startMarker === processIdentity.startMarker
- )
+ || sameProcessIdentity(agent.processIdentity, processIdentity)
))
const existing = processAgent ?? routeAgent
if (existing) {
@@ -2244,9 +2241,7 @@ class Registry {
if (otherId === agentId) continue
const otherRow = strictPersistedRow(other)
if (!otherRow) continue
- const sameProcess = !!process && !!otherRow.processIdentity && otherRow.engine === engine
- && process.pid === otherRow.processIdentity.pid
- && process.startMarker === otherRow.processIdentity.startMarker
+ const sameProcess = otherRow.engine === engine && sameProcessIdentity(process, otherRow.processIdentity)
const sameSession = !!sessionId && otherRow.sessionId === sessionId
const sameRoute = otherRow.runtimes.some((runtime) => routes.has(terminalRouteKey(runtime)))
if (!sameProcess && !sameSession && !sameRoute) continue
diff --git a/cli/src/lib/runtimeActivity.ts b/cli/src/lib/runtimeActivity.ts
index a69c8eac8..e9e6ac8d4 100644
--- a/cli/src/lib/runtimeActivity.ts
+++ b/cli/src/lib/runtimeActivity.ts
@@ -4,6 +4,7 @@ import { terminalActivityReading } from './terminalActivity.js'
import { connectCodexControl, type CodexControl } from './codexSessionLifecycle.js'
import { codexStoppedGoal } from './codexTurnRecovery.js'
import { argvTokens, processRows, type ProcessRow } from './tmux.js'
+import { sameProcessIdentity } from './terminalRuntime.js'
import type { RegisteredSession } from './registry.js'
import type { ActivityState } from './turnActivity.js'
@@ -27,8 +28,8 @@ export class CodexActivityReader {
this.rowsAt = this.deps.now(); this.rows = this.deps.rows()
}
const rows = await this.rows
- const owner = rows?.find(row => row.pid === session.processIdentity!.pid
- && row.startMarker === session.processIdentity!.startMarker && row.executable === session.processIdentity!.executable)
+ const owner = rows?.find(row => sameProcessIdentity(row, session.processIdentity)
+ && row.executable === session.processIdentity!.executable)
if (!owner) return 'unknown'
const args = argvTokens(owner.args)
const option = /^node(?:\.exe)?$/.test(basename(args[0] ?? '')) && /(?:^|\/)codex(?:\.js)?$/.test(args[1] ?? '') ? 2 : 1
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index 5e87e0ab3..27458f638 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -6,6 +6,7 @@ import { env } from '../config/env.js'
import { isTerminalEngine } from '../engines/types.js'
import { atomicWriteJson, projectDisplayName, strictPersistedRow, type RegisteredSession } from './registry.js'
import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
+import { sameProcessIdentity } from './terminalRuntime.js'
const SAFE_ID = /^[a-zA-Z0-9_-]{1,128}$/
const CATALOG_CACHE_RECORDS = 2048
@@ -116,10 +117,8 @@ export class StoppedAgentStore {
// A temporarily unbound observation of the SAME process cannot erase a known conversation.
// A replacement process must earn its own binding; never carry history across PID reuse.
if (!session.sessionId && previous?.sessionId && previous.engine === session.engine
- && session.processIdentity && previous.processIdentity
- && session.processIdentity.pid === previous.processIdentity.pid
- && session.processIdentity.startMarker === previous.processIdentity.startMarker
- && session.processIdentity.executable === previous.processIdentity.executable) {
+ && sameProcessIdentity(session.processIdentity, previous.processIdentity)
+ && session.processIdentity!.executable === previous.processIdentity!.executable) {
session = { ...session, sessionId: previous.sessionId, transcriptPath: previous.transcriptPath,
boundAt: previous.boundAt, source: previous.source }
}
diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.ts
index 0fa099d75..7b5d5fe4f 100644
--- a/cli/src/lib/terminalAgentDiscovery.ts
+++ b/cli/src/lib/terminalAgentDiscovery.ts
@@ -20,7 +20,7 @@ import {
resumeSessionId,
type ProcessRow,
} from './tmux.js'
-import { processIdentityKey, terminalInstanceId, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
+import { processIdentityKey, processIdentityOf, terminalInstanceId, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
import type {
ProcessIdentity,
TerminalInventoryResult,
@@ -164,7 +164,7 @@ function rootOwner(
agent: {
engine,
cwd: root.cwd,
- processIdentity: { pid: row.pid, executable: row.executable, startMarker: row.startMarker },
+ processIdentity: processIdentityOf(row),
args: row.args,
resumeSessionId: resumeSessionId(engine, row.args),
},
diff --git a/cli/src/lib/terminalAgentReconciler.spec.ts b/cli/src/lib/terminalAgentReconciler.spec.ts
index f77f209eb..693001e9f 100644
--- a/cli/src/lib/terminalAgentReconciler.spec.ts
+++ b/cli/src/lib/terminalAgentReconciler.spec.ts
@@ -67,6 +67,25 @@ describe('composite terminal reconciliation', () => {
} finally { reconciler.stop() }
})
+ it('observes a bound agent saved before start ticks as the same process seen with them', async () => {
+ const current = { ...session([tmux]), sessionId: 'saved-conversation' }
+ const live = { ...observed([tmux]), processIdentity: { ...identity, startTicks: 26385008 } }
+ const onDiscovered = vi.fn()
+ const onObserved = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => [current], backends: [], backendOrder: ['tmux'],
+ onDiscovered, onObserved, onDormant: vi.fn(), onRemoved: vi.fn(),
+ probe: async () => probe([
+ { instanceId: 'tmux:default', result: { state: 'available', roots: [{ runtime: tmux, rootPid: 1, cwd: '/work' }] } },
+ ], [live]),
+ })
+ try {
+ await reconciler.start(60_000)
+ expect(onObserved).toHaveBeenCalledWith(live, current)
+ expect(onDiscovered).not.toHaveBeenCalled()
+ } finally { reconciler.stop() }
+ })
+
it('advertises a retained pane even when no engine process is observed', async () => {
const current = { ...session([tmux]), active: false }
const onTerminalAvailability = vi.fn()
diff --git a/cli/src/lib/terminalAgentReconciler.ts b/cli/src/lib/terminalAgentReconciler.ts
index 7e40f9744..7dd86a9db 100644
--- a/cli/src/lib/terminalAgentReconciler.ts
+++ b/cli/src/lib/terminalAgentReconciler.ts
@@ -7,7 +7,7 @@ import {
type TerminalAgentProbe,
} from './terminalAgentDiscovery.js'
import type { TerminalBackend } from './terminalBackend.js'
-import { mergeTerminalRuntimes, processIdentityKey, terminalInstanceId, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
+import { mergeTerminalRuntimes, processIdentityKey, sameProcessIdentity, terminalInstanceId, terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'
import type { TerminalRuntimeRef } from './terminalTypes.js'
const MISS_LIMIT = 2
@@ -326,6 +326,10 @@ export class TerminalAgentReconciler {
if (this.routeHeld(current.runtimes, probeSeq)) continue
const processKey = currentProcessKey(current)
const observed = (processKey ? observedByProcess.get(processKey) : undefined)
+ // A row saved before start ticks is keyed by its marker, the same process observed with them
+ // by its ticks: match it here, or the pass takes it for a new process (ProcessIdentity.startTicks).
+ ?? probe.agents.find((agent) => agent.engine === current.engine
+ && sameProcessIdentity(agent.processIdentity, current.processIdentity))
?? unboundRouteObservation(current, probe.agents)
if (observed) matchedProcesses.add(processIdentityKey(observed.engine, observed.processIdentity))
diff --git a/cli/src/lib/terminalRuntime.spec.ts b/cli/src/lib/terminalRuntime.spec.ts
index 8c403fd62..f22c315e6 100644
--- a/cli/src/lib/terminalRuntime.spec.ts
+++ b/cli/src/lib/terminalRuntime.spec.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
mergeTerminalRuntimes,
processIdentityKey,
+ processIdentityOf,
sameProcessIdentity,
terminalPlacementKey,
terminalRouteKey,
@@ -23,6 +24,23 @@ describe('terminal runtime identity', () => {
expect(processIdentityKey('claude', before)).toBe(processIdentityKey('claude', renamed))
})
+ it('judges a process by its start ticks when both sides have them, else by its ps marker', () => {
+ const saved = { pid: 42, executable: 'node', startMarker: 'Wed Oct 7 09:48:11 2026', startTicks: 26385008 }
+ // The same process after the clock was stepped: lstart moved, the ticks did not.
+ const stepped = { ...saved, startMarker: 'Thu Oct 8 00:46:03 2026' }
+ expect(sameProcessIdentity(saved, stepped)).toBe(true)
+ expect(processIdentityKey('codex', saved)).toBe(processIdentityKey('codex', stepped))
+ expect(sameProcessIdentity(saved, { ...saved, startTicks: 26385009 })).toBe(false)
+ expect(sameProcessIdentity(saved, { ...saved, pid: 43 })).toBe(false)
+ const { startTicks: _, ...legacy } = saved
+ expect(sameProcessIdentity(legacy, saved)).toBe(true)
+ expect(sameProcessIdentity(legacy, stepped)).toBe(false)
+ expect(sameProcessIdentity(undefined, saved)).toBe(false)
+ expect(processIdentityKey('codex', legacy)).not.toBe(processIdentityKey('codex', saved))
+ expect(processIdentityOf({ ...stepped, parentPid: 1, args: 'codex' } as typeof stepped)).toEqual(stepped)
+ expect(processIdentityOf(legacy)).toEqual(legacy)
+ })
+
it('rejects separator injection into stable keys', () => {
expect(() => terminalRouteKey({ backend: 'tmux', paneId: '%1\u0000other' })).toThrow('invalid tmux pane id')
})
diff --git a/cli/src/lib/terminalRuntime.ts b/cli/src/lib/terminalRuntime.ts
index 97baa40c9..ecf421619 100644
--- a/cli/src/lib/terminalRuntime.ts
+++ b/cli/src/lib/terminalRuntime.ts
@@ -26,12 +26,35 @@ export function terminalPlacementKey(runtime: TerminalRuntimeRef): string {
return terminalRouteKey(runtime)
}
+function startTicks(identity: ProcessIdentity): number | undefined {
+ return Number.isSafeInteger(identity.startTicks) && identity.startTicks! >= 0 ? identity.startTicks : undefined
+}
+
+/** Keyed by the start ticks when known: the marker of the same process moves with the wall clock. */
export function processIdentityKey(engine: string, identity: ProcessIdentity): string {
- return `${assertKeyPart(engine, 'engine')}${SEP}${identity.pid}${SEP}${assertKeyPart(identity.startMarker, 'process start marker')}`
+ const ticks = startTicks(identity)
+ const start = ticks === undefined ? assertKeyPart(identity.startMarker, 'process start marker') : `t:${ticks}`
+ return `${assertKeyPart(engine, 'engine')}${SEP}${identity.pid}${SEP}${start}`
+}
+
+/**
+ * pid + start time is a process. The start ticks decide when both sides have them (see
+ * `ProcessIdentity.startTicks`); otherwise the `ps` marker, as before them — which is also how a row
+ * saved before them is matched once, and then saved with them.
+ */
+export function sameProcessIdentity(a: ProcessIdentity | undefined | null, b: ProcessIdentity | undefined | null): boolean {
+ if (!a || !b || a.pid !== b.pid) return false
+ const ticksA = startTicks(a)
+ const ticksB = startTicks(b)
+ return ticksA !== undefined && ticksB !== undefined ? ticksA === ticksB : a.startMarker === b.startMarker
}
-export function sameProcessIdentity(a: ProcessIdentity | undefined, b: ProcessIdentity | undefined): boolean {
- return !!a && !!b && a.pid === b.pid && a.startMarker === b.startMarker
+/** The identity a row stands for, without the rest of the row. */
+export function processIdentityOf(row: ProcessIdentity): ProcessIdentity {
+ return {
+ pid: row.pid, executable: row.executable, startMarker: row.startMarker,
+ ...(row.startTicks !== undefined ? { startTicks: row.startTicks } : {}),
+ }
}
export function sameTerminalPlacement(a: TerminalRuntimeRef, b: TerminalRuntimeRef): boolean {
diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.ts
index e08bfb124..cc24969f3 100644
--- a/cli/src/lib/terminalTypes.ts
+++ b/cli/src/lib/terminalTypes.ts
@@ -7,6 +7,14 @@ export interface ProcessIdentity {
pid: number
executable: string
startMarker: string
+ /**
+ * Linux only: when the process started, in clock ticks since boot (`/proc/<pid>/stat` field 22).
+ * `startMarker` is `ps lstart`, which Linux derives from the boot time, and the boot time moves
+ * every time the wall clock is stepped: a Docker Desktop VM resynced after the Mac slept shifted
+ * every process's lstart by hours, and each agent got a new id for the same process (6 panes, 5
+ * times in 15 hours, machine-remote-1, 2026-10-07). The ticks never change for a process.
+ */
+ startTicks?: number
}
export interface TmuxRuntimeRef {
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index fd2c2e095..c4f810d75 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -20,6 +20,7 @@ import {
sendLiteralToTmux,
sendToTmux,
tmuxCaptureArgs,
+ withStartTicks,
} from './tmux.js'
import { tmuxControlGate } from './tmuxControlGate.js'
import { assumeTmuxVersion, resetTmuxVersionCache } from './tmuxVersion.js'
@@ -72,6 +73,17 @@ describe('tmux process primitives', () => {
})
+ it('adds the start ticks a clock step cannot move on Linux, and nothing elsewhere', () => {
+ const live = parseProcessRow('3998 3992 node Mon Sep 21 08:15:25 2026 node /home/node/.npm-global/bin/codex')!
+ const gone = parseProcessRow('3999 3992 node Mon Sep 21 08:15:25 2026 node codex')!
+ const ticksOf = (pid: number) => pid === 3998 ? 26385008 : null
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
+ expect(withStartTicks([live, gone], ticksOf)).toEqual([{ ...live, startTicks: 26385008 }, gone])
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')
+ expect(withStartTicks([live], ticksOf)).toEqual([live])
+ vi.restoreAllMocks()
+ })
+
it('parses a process whose comm field contains spaces', () => {
expect(parseProcessRow('4242 100 ⌘ Greeting Thu Jul 30 11:00:03 2026 cmd -r abcdef12-3456-7890-abcd-ef1234567890')).toEqual({
pid: 4242,
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 1cb9ed6d7..0f726348d 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -16,11 +16,13 @@ import {
} from './engineBin.js'
import { BYPASS_PERMISSION_FLAGS, PERMISSION_MODES, permissionModeApproves } from './engineLaunch.js'
import { psEnv } from './childLocale.js'
+import { processStartTicks } from './processLiveness.js'
import { nativeProcessImages } from './nativeProcessImages.js'
import { neutralizePasteControls } from './pasteText.js'
import { patientDeadline, patientExec } from './patientExec.js'
import { inTmuxRoom } from './tmuxControlGate.js'
import { tmuxFeatures, type TmuxFeatures } from './tmuxVersion.js'
+import { processIdentityOf, sameProcessIdentity } from './terminalRuntime.js'
export { captureTmuxPane, tmuxCaptureArgs } from './tmuxCapture.js'
// Every tmux and `ps` call here: a held event loop must not turn a timeout into an empty answer
@@ -301,7 +303,7 @@ let processRowsInFlight: Promise<ProcessRow[] | null> | null = null
/** A running process's command line as the process table shows it; '' once it is not that process. */
export async function processArgs(identity: ProcessIdentity): Promise<string> {
const rows = await processRows()
- return rows?.find((row) => row.pid === identity.pid && row.startMarker === identity.startMarker)?.args ?? ''
+ return rows?.find((row) => sameProcessIdentity(row, identity))?.args ?? ''
}
/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
@@ -325,7 +327,19 @@ async function readProcessRows(): Promise<ProcessRow[] | null> {
resolve(rows.length ? rows : null)
})
})
- return rows ? liveProcessRows(repairMangledRows(rows)) : null
+ return rows ? withStartTicks(liveProcessRows(repairMangledRows(rows))) : null
+}
+
+/**
+ * Linux: each row's start ticks, the part of its identity a clock step cannot move (see
+ * `ProcessIdentity.startTicks`). One small /proc read per row, like the mangled-row repair above.
+ */
+export function withStartTicks(rows: ProcessRow[], ticksOf: (pid: number) => number | null = processStartTicks): ProcessRow[] {
+ if (process.platform !== 'linux') return rows
+ return rows.map((row) => {
+ const startTicks = ticksOf(row.pid)
+ return startTicks === null ? row : { ...row, startTicks }
+ })
}
function execText(command: string, args: string[], timeout: number): Promise<string | null> {
@@ -999,7 +1013,7 @@ export async function lookupPaneEngineProcess(
if (!process) return { ok: false, unknown: false, reason: `no ${engine} process under pane ${pane}` }
return {
ok: true,
- identity: { pid: process.pid, executable: process.executable, startMarker: process.startMarker },
+ identity: processIdentityOf(process),
}
}
@@ -1023,7 +1037,7 @@ export async function resolvePaneRootProcess(pane: string): Promise<ProcessIdent
if (!rows) return null
const row = rows.find((candidate) => candidate.pid === rootPid)
if (!row) return null
- return { pid: row.pid, executable: row.executable, startMarker: row.startMarker }
+ return processIdentityOf(row)
}
/**
@@ -1120,7 +1134,7 @@ export async function checkSessionRuntime(session: RegisteredSession): Promise<R
// PID-reuse guard. `executable` is argv-derived and therefore mutable (Command Code rewrites its own
// argv to `⌘ <session title>` and renames the session mid-life), so it is recorded but not compared:
// comparing it evicted live panes for renaming themselves.
- if (saved && (saved.pid !== live.pid || saved.startMarker !== live.startMarker)) {
+ if (saved && !sameProcessIdentity(saved, live)) {
return {
state: 'gone',
reason: `process changed under pane ${session.tmuxPane}`
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index cb18c02d3..58270eb10 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -44,7 +44,7 @@ import { tmuxFeatures, type TmuxFeatures } from './tmuxVersion.js'
import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.js'
import { machineNames } from './machineNames.js'
import { isNoTmuxServerError, listTmuxPanes } from './tmuxAgentDiscovery.js'
-import { terminalRouteKey } from './terminalRuntime.js'
+import { sameProcessIdentity, terminalRouteKey } from './terminalRuntime.js'
// Every tmux call here: a held event loop must not turn a timeout into a failure, or into an empty
// answer that reads as a pane that was never made (patientExec.ts).
@@ -414,8 +414,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
if (expected.processIdentity && !LSTART_MARKER_RE.test(expected.processIdentity.startMarker)) {
return { state: 'alive' }
}
- if (expected.processIdentity
- && (expected.processIdentity.pid !== live.pid || expected.processIdentity.startMarker !== live.startMarker)) {
+ if (expected.processIdentity && !sameProcessIdentity(expected.processIdentity, live)) {
return { state: 'gone', reason: 'process changed under tmux pane', replaced: true }
}
return { state: 'alive' }