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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Core boundary, part 4: forgetting, binding, discovering and relaunching agents become modules (#723)
Dee708e2fceb65f
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 663e57f7e..a2d8dfbbd 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -187,6 +187,11 @@ import { createAgyBackstop } from './core/turns/agyBackstop.js'import { createIngest } from './core/transcripts/ingest.js'import { createTurnHooks } from './core/turns/turnHooks.js'import { createAttach } from './core/transcripts/attach.js'+import { createForgetSession } from './core/agents/forget.js'+import { createBinding } from './core/agents/bind.js'+import { createDiscoveryHandlers } from './core/agents/discovery.js'+import { createLaunchHelpers } from './core/agents/launch.js'+import { createCancel } from './core/turns/cancel.js'import { describeMasterStatus, readStatusFile, runMaster } from './harnessd/master.js'import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'@@ -384,14 +389,6 @@ const GRID_MINT_TIMEOUT_MS = 10_000* Past it the set-up carries on, and the agent's own `harness grid setup` waits for it. */const MODEL_MANAGER_GRID_WAIT_MS = 8_000-/** Between session-binding attempts for a process whose engine store is not resolvable yet. */-const REPAIR_RETRY_MS = 60_000-/** A NEW process is waiting for a session that is about to appear. Muse makes- * this concrete — its session is only claimable once the user has typed, because a file with no turn in- * it cannot be told apart from the ones muse opens for itself. Backing off a full minute there costs the- * FIRST message: the pane answers while web and device show nothing. So keep sweeping for a while first,- * then settle into the slow rhythm for processes that will never resolve. */-const REPAIR_EAGER_ATTEMPTS = 24 // ≈2 min at the 5s sweepfunction usage(exitCode = 0): never {console.log(`harness v${VERSION} — connect this computer to your machine@@ -1610,13 +1607,6 @@ function primaryTerminalLabel(session: RegisteredSession): string {return runtime ? terminalRuntimeLabel(runtime) : 'dormant'}-/** Birth time of a transcript in ms, or 0 when it cannot be read (treated as "not newer than the agent"). */-async function statBirthMs(path: string): Promise<number> {- const st = await stat(path).catch(() => null)- if (!st) return 0- const birth = st.birthtimeMs || st.ctimeMs || st.mtimeMs- return Number.isFinite(birth) ? birth : 0-}/** The daemon body: hooks + watcher + process discovery + backend socket. */async function runForeground(session: AuthSession | null): Promise<void> {@@ -2525,53 +2515,29 @@ async function runForeground(session: AuthSession | null): Promise<void> {cursorTaskHooks.enqueue(sessionId, { toolUseId, input: toolInput }, normalizer)}- /** Release a mutable session binding, or remove the process-owned agent everywhere. */- const forgetSession = (- id: string,- opts: { force?: boolean; keepAgent?: boolean; agentId?: string } = {},- ): void => {- const doomed = registry.resolve(id)- const sessionId = doomed?.sessionId || id- // Clients key on the AGENT id. Normally it is read off the entry, but an- // agent already removed from the registry cannot be looked up — and- // announcing its sessionId instead is silently useless: the app takes- // payload.agentId verbatim, matches nothing, and leaves the dead row on- // screen. Callers who know the id pass it.- const announceId = doomed?.agentId ?? opts.agentId ?? sessionId-- console.log(opts.keepAgent- ? `[agent] ${sid(announceId)} released session ${sid(sessionId)}`- : `[agent] ${sid(announceId)} forgotten`)-- if (!opts.keepAgent && doomed) stoppedAgents.save(doomed)- if (opts.keepAgent) registry.unbindSession(sessionId)- else if (doomed) registry.removeAgent(doomed.agentId)- else registry.remove(sessionId)- syncRecapPool()- normalizers.forget(sessionId)- turnStartedAt.delete(sessionId)- neverFoldedHistory.delete(sessionId)- // Both sets are per-session and must die with it: left behind they grow without bound in a daemon- // that runs for days, and a session forgotten then re-registered under the same id would inherit a- // stale "already replayed" and lose a first turn it was entitled to.- replayedFirstTurn.delete(sessionId)- clearAgyIdleWatch(sessionId)- cursorDiscovery.remove(sessionId)- cursorSubagents.forget(sessionId)- void removeCursorPendingTasks(env.ADAPTER_DATA_DIR, sessionId)- runtimeProfiles.forget(sessionId)- void watcher.removeSession(sessionId)- stopHeartbeat(sessionId)- backend.swarmPromptScopes.forget(doomed?.agentId ?? sessionId)- input.forget(doomed?.agentId ?? sessionId)- deviceInput.forget(doomed?.agentId ?? sessionId)- if (!opts.keepAgent) detachDsh(announceId)- mirror.forget(sessionId) // aborts any in-flight recap + clears busy; KEEPS the persisted summary- if (opts.keepAgent) return- backend.send({ type: 'agent_deleted', payload: { agentId: announceId, retained: !!doomed } }) // web tab- backend.sendCommander({ type: 'agent_deleted', payload: { agentId: announceId } })-- }+ // Release a session's binding, or remove a process-owned agent everywhere (core/agents/forget.ts).+ const forgetSession = createForgetSession({+ registry,+ stoppedAgents,+ syncRecapPool,+ normalizers,+ turnStartedAt,+ neverFoldedHistory,+ replayedFirstTurn,+ clearAgyIdleWatch,+ cursorDiscovery,+ cursorSubagents,+ runtimeProfiles,+ watcher,+ stopHeartbeat,+ teams: backend.swarmPromptScopes,+ input,+ deviceInput,+ detachDsh,+ mirror,+ clients: backend,+ dataDir: env.ADAPTER_DATA_DIR,+ })const retainExitedSession = createRetainExitedSession({stoppedAgents,@@ -2587,255 +2553,46 @@ async function runForeground(session: AuthSession | null): Promise<void> {warn: (message, error) => console.warn(message, error),})- type RegisteredMeta = {- isNew: boolean- evicted: string | null- rebound: string | null- orphaned?: { agentId: string; sessionId: string } | null- hookEvent?: string- }-- /**- * Forks whose engine session has not reported in yet, agentId → the SOURCE's sessionId. A fork's tile- * should open with the source's last recap on it, the way its pane opens with the source's transcript- * — but the mirror keys by session, and the fork's session id is the engine's to name, minutes later- * over a hook. Settled the moment it binds, below.- */- const pendingForkInherit = new Map<string, string>()-- const handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {- const forkSource = pendingForkInherit.get(entry.agentId)- if (forkSource && entry.sessionId) {- pendingForkInherit.delete(entry.agentId)- mirror.inheritSummary(forkSource, entry.sessionId)- }- if (meta.rebound) {- registry.inheritName(meta.rebound, entry.sessionId)- mirror.inheritSummary(meta.rebound, entry.sessionId)- forgetSession(meta.rebound, { force: true, keepAgent: true })- backend.send({ type: 'session_reset', payload: { staleSessionId: meta.rebound } })- console.log(`[agent] ${sid(entry.agentId)} rebound ${sid(meta.rebound)} → ${sid(entry.sessionId)}`)- } else if (meta.evicted) {-- forgetSession(meta.evicted, { force: true })- }- // The agent this bind emptied out — `claude --resume` in a second pane, with- // the first one's engine already gone. The registry dropped it; without this- // the app kept showing it until someone hit Reload machines by hand, and- // opening it landed on TERMINAL FROZEN because it has nothing left to open.- //- // Not part of the chain above: a rebound bind can orphan an agent too, so- // this has to be asked independently of which branch ran.- if (meta.orphaned) {- forgetSession(meta.orphaned.agentId, {- force: true,- agentId: meta.orphaned.agentId,- })- }- // agy is excluded for the same reason as cursor, arriving by a different road: it has no- // session-start event at all. The closest thing is `PreInvocation`, which fires before EVERY model- // round-trip — four to seven times in one measured turn — and each one re-folded the transcript and- // re-emitted `turn_started` for a turn already open (measured: two turn_started, one turn_ended).- // Its first bind is covered by `meta.isNew`, and registry derives the transcript path from the- // conversation id, so nothing here depends on a later announcement carrying it.- // Copilot joins cursor and agy for a third reason: it announces the SAME turn twice. Its- // `userPromptSubmitted` and `sessionStart` hooks both register (measured 2.5s apart, and in that- // order — sessionStart fires AFTER the first prompt), so treating the second as a reset re-folded- // the transcript and emitted a second `turn_started` for one exchange.- const reset = meta.isNew- || (entry.engine !== 'cursor' && entry.engine !== 'agy' && entry.engine !== 'copilot'- && meta.hookEvent === 'SessionStart')- // Deliberately NOT gated on `meta.isNew`. `isNew` is false in exactly the case this is meant to catch:- // a session announced once BEFORE its transcript exists and registered again when the file appears —- // the second announcement is the only one that can carry the path, and it reports `isNew=false`- // (measured: `[hooks] 019fff7f SessionStart · engine=codex · isNew=false`, whose whole first turn was- // then folded away as history and never reached web or device).- //- // `statBirthMs >= registeredAt` is what actually separates the two cases. Measured on one machine,- // same claude session, transcript birth relative to each timestamp:- //- // first turn resumed (`claude --continue`)- // registeredAt +18.1s -81.5s ← separates cleanly- // boundAt -0.5s -81.6s ← negative for BOTH; useless as a test- //- // so the birth-vs-`registeredAt` comparison stays, and comparing against `boundAt` instead — the- // obvious-looking alternative, since `boundAt` is when this session was bound — does not work: the- // transcript is created a moment BEFORE the hook binds it.- //- // And only while the file is new (`transcriptIsFirstTurn`): a long session's transcript was born after- // its agent too, and after a daemon restart its next SessionStart replayed the whole history live.- const bornAfterAgent = transcriptIsFirstTurn(- entry,- entry.transcriptPath ? await statBirthMs(entry.transcriptPath) : 0,- { rebound: !!meta.rebound, now: Date.now() },- )- const attached = await attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent)- if (!attached) {- registry.unbindSession(entry.sessionId)- announceSession(entry)- return- }- const confirmed = registry.byAgent(entry.agentId)- if (confirmed?.sessionId === entry.sessionId) {- stoppedAgents.save(confirmed)- if (confirmed.resumeOnly) stoppedAgents.finishResume(confirmed.agentId)- }- syncRecapPool()- if (!meta.isNew) return- registry.inheritName(entry.agentId, entry.sessionId)- announceSession(entry)- backend.send({- type: 'session_synced',- payload: {- sessionId: entry.sessionId,- agentId: entry.agentId,- title: projectDisplayName(entry),- createdAt: new Date(entry.boundAt ?? Date.now()).toISOString(),- },- })- }-- const lastRepairAttempt = new Map<string, number>()- const repairAttempts = new Map<string, number>()- const bindObservedAgent = async (observed: DiscoveredTerminalAgent): Promise<void> => {- const agent = registry.byProcess(observed.engine, observed.processIdentity)- if (!agent) return-- // Copilot can change session WITHOUT changing process: `/resume` inside the CLI opens another one,- // and the pane then shows a conversation the daemon is not streaming. Every other engine here- // starts a new process for that, which is why this path used to stop at `agent.sessionId`.- //- // The switch leaves exactly one trace — the `inuse.<pid>.lock` Copilot takes on the new session- // directory. It writes nothing to the transcript and fires no hook until the next prompt.- if (agent.resumeOnly && agent.launch && agent.launch.state !== 'ready') return- if (agent.sessionId) {- if (observed.engine === 'copilot') {- const current = await copilotSessionForPid(env.COPILOT_HOME, observed.processIdentity.pid)- if (!current || current === agent.sessionId || isRecentlyDeleted(current)) return- const transcript = await findCopilotTranscript(env.COPILOT_HOME, current)- console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(current)} (/resume)`)- const rotated = registry.register({- engine: 'copilot',- sessionId: current,- transcriptPath: transcript ?? undefined,- cwd: observed.cwd,- source: 'copilot-resume',- runtimes: observed.runtimes,- primaryRuntimeKey: observed.primaryRuntimeKey,- processIdentity: observed.processIdentity,- hookEvent: 'CopilotResume',- })- if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)- return- }- // Claude can also change session WITHOUT any hook firing: a long conversation's transcript- // rolls over to a new file on its own (compaction/a resume chain), and if the turn that follows- // lands on a pooled/"spare" worker process rather than one spawned fresh in the pane, no- // SessionStart/UserPromptSubmit ever reaches us for it — the agent is left bound to a transcript- // that has gone quiet forever while the real conversation continues one file over. Checked on- // the same cadence this reconciler already re-observes every live process, so it costs nothing- // extra to ask.- if (observed.engine === 'claude' && agent.transcriptPath) {- const continuation = await claudeContinuation(agent.transcriptPath)- if (!continuation || continuation.sessionId === agent.sessionId- || registry.has(continuation.sessionId) || isRecentlyDeleted(continuation.sessionId)) return- console.log(`[discovery] ${sid(agent.agentId)} claude session continued ${sid(agent.sessionId)} → ${sid(continuation.sessionId)}`)- const rotated = registry.register({- engine: 'claude',- sessionId: continuation.sessionId,- transcriptPath: continuation.transcriptPath,- cwd: observed.cwd,- source: 'claude-continuation',- runtimes: observed.runtimes,- primaryRuntimeKey: observed.primaryRuntimeKey,- processIdentity: observed.processIdentity,- hookEvent: 'ClaudeContinuation',- })- if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)- return- }- return- }-- let sessionId = observed.resumeSessionId- let transcriptPath: string | undefined- let hermesHome: string | undefined- let source = 'terminal-resume'- if (sessionId) {- if (isRecentlyDeleted(sessionId)) return- const owner = registry.bySession(sessionId)- if (owner && owner.agentId !== agent.agentId) {- const observedStarted = Date.parse(observed.processIdentity.startMarker)- const ownerStarted = Date.parse(owner.processIdentity?.startMarker ?? '')- if (Number.isFinite(ownerStarted) && (!Number.isFinite(observedStarted) || observedStarted <= ownerStarted)) return- }- transcriptPath = observed.engine === 'cursor'- ? await findCursorTranscript(cursorDataDir(), sessionId) ?? undefined- : observed.engine === 'grok'- ? await findGrokTranscript(env.GROK_HOME, observed.cwd, sessionId) ?? undefined- : observed.engine === 'agy'- ? await findAgyTranscript(env.AGY_HOME, sessionId) ?? undefined- : observed.engine === 'copilot'- ? await findCopilotTranscript(env.COPILOT_HOME, sessionId) ?? undefined- : observed.engine === 'claude' || observed.engine === 'codex'- ? await findResumedTranscript(observed.engine, sessionId, { codexHome: agent.codexHome ?? undefined }) ?? undefined- : undefined- // The registry refuses a claude/codex session without its file, so a resume of a transcript this- // machine does not have is not a session — the hook that follows the user's next prompt will say.- if ((observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'claude' || observed.engine === 'codex')- && !transcriptPath) return- } else {- const attempts = repairAttempts.get(agent.agentId) ?? 0- const lastAttempt = lastRepairAttempt.get(agent.agentId) ?? 0- if (attempts >= REPAIR_EAGER_ATTEMPTS && Date.now() - lastAttempt < REPAIR_RETRY_MS) return- lastRepairAttempt.set(agent.agentId, Date.now())- repairAttempts.set(agent.agentId, attempts + 1)- const startedAtMs = Date.parse(observed.processIdentity.startMarker)- if (!Number.isFinite(startedAtMs)) return- // agy cannot be found by directory — its repair reads the presence lock the process holds open.- //- const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, {- bornOnly: true,- pid: observed.processIdentity.pid,- codexHome: agent.codexHome ?? undefined,- })- if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return- sessionId = found.sessionId- transcriptPath = found.transcriptPath- // Which Hermes home the repair found it in, so the row starts life reading the right store- // rather than looking it up again on its first poll.- hermesHome = found.hermesHome- source = 'process-repair'- }-- const previousOwner = registry.bySession(sessionId)- const result = registry.register({- engine: observed.engine,- sessionId,- transcriptPath,- ...(hermesHome ? { hermesHome } : {}),- cwd: observed.cwd,- source,- runtimes: observed.runtimes,- primaryRuntimeKey: observed.primaryRuntimeKey,- processIdentity: observed.processIdentity,- hookEvent: source === 'terminal-resume' ? 'TerminalResumeDiscovery' : 'ProcessRepair',- })- if (!result || !result.isNew) return- if (previousOwner && previousOwner.agentId !== result.entry.agentId) {- backend.swarmPromptScopes.forget(previousOwner.agentId)- input.forget(previousOwner.agentId)- deviceInput.forget(previousOwner.agentId)- announceSession(previousOwner)- }- lastRepairAttempt.delete(agent.agentId)- repairAttempts.delete(agent.agentId)- await handleRegistered(result.entry, result)- console.log(`[discovery] bound ${observed.engine} session ${sid(result.entry.sessionId)} via ${observed.primaryRuntimeKey}`)- }+ // Binding a session to its agent, and a running process to its session (core/agents/bind.ts).+ const binding = createBinding({+ registry,+ mirror,+ forgetSession,+ clients: backend,+ attachSession,+ announceSession,+ stoppedAgents,+ syncRecapPool,+ teams: backend.swarmPromptScopes,+ input,+ deviceInput,+ homes: { copilot: env.COPILOT_HOME, grok: env.GROK_HOME, agy: env.AGY_HOME },+ })+ const pendingForkInherit = binding.pendingForkInherit+ const handleRegistered = binding.handleRegistered+ const bindObservedAgent = binding.bindObservedAgent+ // What the reconciler's scans mean for the registry (core/agents/discovery.ts).+ const discovery = createDiscoveryHandlers({+ registry,+ attachDsh,+ forgetSession,+ announceSession,+ bindObservedAgent,+ syncRecapPool,+ attachSession,+ invalidateTerminalControl,+ teams: backend.swarmPromptScopes,+ input,+ deviceInput,+ questionWatcher,+ stopHeartbeat,+ retainExitedSession,+ stoppedAgents,+ restoreDegraded: () => restoreDegraded,+ })const agentReconciler = new TerminalAgentReconciler({// The hook server starts before restore. Its early SessionStart hints must not run a full// discovery scan over rows whose panes have not been recreated yet (and archive those rows).@@ -2844,179 +2601,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {backends: terminalBackends,backendOrder: terminalConfig.backends,transaction: (apply) => registry.transaction(apply),- onDiscovered: async (observed) => {- const launching = observed.runtimes- .map((runtime) => registry.byRuntimeEngine(runtime, observed.engine))- .find((entry) => entry?.launch?.state !== 'ready')- const opened = registry.openProcessAgent({- engine: observed.engine,- runtimes: observed.runtimes,- primaryRuntimeKey: observed.primaryRuntimeKey,- cwd: observed.cwd,- processIdentity: observed.processIdentity,- gateway: observed.gateway,- grid: observed.grid,- codexHome: observed.codexHome,- dsh: observed.dsh,- })- if (!opened) return- if (opened.entry.dsh) attachDsh(opened.entry)- if (opened.evicted) {- console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted.agentId)}`)- // ⚠️ THE REGISTRY ALREADY DROPPED IT; NOBODY HAD TOLD THE CLIENTS. That- // is the whole bug behind "two sessions, one of them frozen": resuming- // an engine in a pane another agent owned takes the pane away, and an- // agent with no pane can never be opened again — but the app kept the- // row until someone hit Reload machines by hand, and opening it landed- // on TERMINAL FROZEN. This is the same call the hook path already makes- // for the same situation (see onRegistered below).- forgetSession(opened.evicted.sessionId || opened.evicted.agentId, {- force: true,- agentId: opened.evicted.agentId,- })- }-- if (opened.isNew || launching) {- console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · terminal=${observed.primaryRuntimeKey}`)- announceSession(opened.entry)- }- await bindObservedAgent(observed)- },- onObserved: async (observed, current) => {- const wasDormant = !current.active- // Read BEFORE the update, because the update is what overwrites it. `undefined` means the probe- // could not look, which never counts as a move — see `probeGridAssignment`'s three answers.- const gridMoved = observed.grid !== undefined- && !sameGridAssignment(current.grid ?? null, observed.grid)- const wasLaunching = current.launch?.state !== undefined && current.launch.state !== 'ready'- // Somebody typed an engine into a terminal. The row becomes that engine's agent — same id,- // same pane — and from here on is handled exactly like one the app launched: bound by its- // hooks, watched for turns, listed on the dial. `adopted` makes the announce below- // unconditional, since the engine changing is the one fact the app must not miss.- const adopted = isTerminalEngine(current.engine) && !isTerminalEngine(observed.engine)- ? registry.adoptEngine(current.agentId, observed.engine, observed.processIdentity)- : null- if (adopted) console.log(`[discovery] ${sid(current.agentId)} terminal → ${observed.engine} · ${observed.primaryRuntimeKey}`)- registry.updateRuntimes(current.agentId, observed.runtimes, observed.primaryRuntimeKey)- registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway, observed.grid)- // The live argv is the truth about the bypass flag, and this is the one place every running- // agent passes through — so a row written before the flag was persisted at all (or by a build- // that did not yet) learns it here, before any pane recreation ever needs it.- // `observed.engine`, not `current.engine`: for a terminal that just adopted one, the row's- // engine was `terminal` a line ago, which has no bypass flag and would read every launch as "no".- registry.setBypassPermission(current.agentId, bypassPermissionActive(observed.engine, observed.args))- // And the exact MODE, fill-only: a row that recorded one at create is authoritative, and one- // that never did (adopted from a terminal, written by an older build, created by a path that- // passes no mode) learns it from the same argv — so its restart brings back- // `--dangerously-skip-permissions`, not the auto mode `bypassPermission` alone would pick.- if (!current.permissionMode) {- const mode = permissionModeFromArgv(observed.engine, observed.args)- if (mode) registry.setPermissionMode(current.agentId, mode)- }- // Same idea for a Codex profile: a row that never learned which CODEX_HOME its process runs- // under learns it from the process, before the hook path validates a transcript against it.- // Fill-only — a profile the row already knows is never re-derived.- if (observed.codexHome && !current.codexHome) registry.setCodexHome(current.agentId, observed.codexHome)- // …and a Hermes home the same way, when the process names one. A row that learns it here never- // has to look its session up store by store (openharness#191).- if (observed.hermesHome && !current.hermesHome) registry.setHermesHome(current.agentId, observed.hermesHome)- // And the DSH: a row minted by discovery (or written before the field existed) learns it from- // the process's own `HARNESS_DSH`, and gets its viewer and verdict watch from here on.- if (observed.dsh && !current.dsh) registry.setDsh(current.agentId, observed.dsh)- const withDsh = registry.byAgent(current.agentId)- if (withDsh?.dsh) attachDsh(withDsh)- // This live process, in this row's own pane, is what "started" means — for a resumed row as- // much as any other. A resume used to be held back here until its `SessionStart` hook landed,- // on the grounds that only the hook proves WHICH conversation reopened. Two things were wrong- // with that. The hook does not always come: measured on machine-remote-1, both resume-only- // codex rows carried `lastHookAt: 0` while every fresh launch beside them had hooked, and one- // of them sat at "Starting" for 19 hours over a pane its owner could type in — re-attached and- // re-announced every 5s for the whole time, because `wasLaunching` stays true for a row that- // nothing will ever mark ready (openharness#189). And nothing was actually protected by the- // wait: the wrong-conversation guard in `registry.register` keys on `lastHookAt`, not on this- // launch state, so it stays armed until the first hook whatever is written here.- if (wasLaunching) registry.setLaunch(current.agentId, { state: 'ready' })- await bindObservedAgent(observed)- if (wasDormant || wasLaunching || adopted) {- const active = registry.byAgent(current.agentId)- if (!active) return- if (!active.sessionId) {- syncRecapPool()- announceSession(active)- return- }- // Not awaited: the attach reads this agent's whole history, and this callback runs inside the- // reconcile pass whose completion is what publishes `discoveryReady`. One agent's slow store- // must not hold the pass — or, at boot, the app. The tracker runs a few of these at a time.- void attachSession(active).then((attached) => {- if (!attached) {- registry.setActive(active.agentId, false)- return- }- syncRecapPool()- announceSession(active)- }).catch((err) => {- console.error(`[discovery] ${sid(active.agentId)} attach failed:`, err instanceof Error ? err.message : err)- })- return- }- // An agent that was already awake changed grid under us. Nobody was told: this branch wrote the- // new assignment into the registry and stopped, so the app went on drawing the old one until- // its own 60s reconciliation tick happened to notice — a minute of an agent's header naming a- // grid it had left. The retarget path has always announced (it is the same fact, arriving by a- // different door); this is the door an engine's own `exec` comes through, which is what an- // install-then-launch does the moment the install finishes.- if (!gridMoved) return- const refreshed = registry.byAgent(current.agentId)- if (refreshed) announceSession(refreshed)- },- onDormant: async (agent, reason) => {- if (!agent.active) return- invalidateTerminalControl(agent.agentId)- backend.swarmPromptScopes.forget(agent.agentId)- input.forget(agent.agentId)- deviceInput.forget(agent.agentId)- if (agent.sessionId) {- questionWatcher.stop(agent.sessionId)- stopHeartbeat(agent.sessionId)- }- // Preserve the conversation's public identity and give the surviving shell its own row.- // A starting install is not an exited engine; strict uncertain starts keep their reservation.- if (agent.resumeOnly && agent.launch?.state === 'failed') {- const pane = await tmuxPaneState(agent.tmuxPane)- // An unconfirmed install/startup can still be about to launch the engine. Do not- // turn its live shell into permission to start another one.- if (!pane || (!pane.dead && pane.engineExit == null)) return- }- if (agent.launch?.state !== 'starting') {- retainExitedSession(agent, true)- if (agent.resumeOnly) stoppedAgents.finishResume(agent.agentId)- console.log(`[discovery] ${sid(agent.agentId)} retained · ${reason}`)- return- }- registry.setActive(agent.agentId, false)- console.log(`[discovery] ${sid(agent.agentId)} dormant · ${reason}`)- announceSession(agent)- },- onRemoved: (agent, reason) => {- // A pane absent because RESTORE never ran is not a pane the person closed. Retiring it here- // would archive a row whose tmux pane was simply never rebuilt, and the person would have to- // Open each one by hand; keeping it dormant leaves the next daemon — the fixed one — something- // to restore.- if (restoreDegraded) {- console.log(`[discovery] ${sid(agent.agentId)} kept · restore did not run this boot · ${reason}`)- registry.setActive(agent.agentId, false)- announceSession(agent)- return- }- console.log(`[discovery] ${sid(agent.agentId)} removed · ${reason}`)- forgetSession(agent.agentId, { force: true })- },- onTerminalAvailability: (agent, available) => {- const changed = registry.terminalAvailable(agent.agentId) !== available- registry.setTerminalAvailable(agent.agentId, available)- if (available && changed) announceSession(agent)- },+ ...discovery,onProbeStatus: (status) => {discoveryReady = status.readydiscoveryError = status.error@@ -3989,83 +3574,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {return prepareHarnessLaunch(installed, workspace, engine, runtimeKey, { privateGrid: backend.gridName() }, null)},}- // Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH,- // workspace and named agent come from the row: a retarget must not silently drop the harness the- // agent is, or bring a pane opened as `harness-compute` back as a general session.- // An agent on a saved API's model relaunches with that API's endpoint and key as saved now, so a key- // pasted since takes effect, and a removed API is refused rather than kept on its old key.- const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> => {- prepareApiTools(session.cwd, session.engine)- let gridLaunch = source.gridLaunch ?? null- if (gridLaunch && isApiLaunch(gridLaunch)) {- try {- gridLaunch = refreshApiLaunch(savedApis, gridLaunch)- } catch (error) {- return {- ok: false,- error: 'API_UNAVAILABLE',- detail: error instanceof ApiConnectionError ? error.message : `${gridLaunch.networkName} could not be read from saved APIs.`,- }- }- }- return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source, gridLaunch }, session.agentId)- }-- /**- * A restart or a post-reboot restore rebuilds the ROW's own launch, and the machine may decide- * differently about web search this time than it did when the row was written (an administrator- * pinned `/etc/hermes` since, or unpinned it). The override is the row's already; what is- * refreshed is the decision, so the frame describes the pane that actually came up. Retarget- * does not go through here — its override is new, and it records the pair itself once the move- * has succeeded.- */- const refreshGridWebSearch = (agentId: string, overrides: LaunchOverrides): void => {- if (overrides.gridLaunchRecord) registry.setGridLaunch(agentId, overrides.gridLaunchRecord)- }-- /**- * The permission this relaunch can actually ask for. Nobody is waiting on a restart, a retarget, a- * restore or a resume, so an engine that no longer takes the row's flag costs it the mode, not the- * harness — the alternative is a pane of help text, or no pane at all (openharness#285).- *- * The row is NOT rewritten. `permissionMode` is the person's recorded choice and `setPermissionMode`- * is fill-only for that reason; an engine put back the way it was gets Auto again on the next- * relaunch, with nobody having to ask for it twice. The row stops CLAIMING the mode on its own:- * discovery re-derives `bypassPermission` from the live argv on every pass (`setBypassPermission`- * above), so a launch without the flag reads as one within a reconcile.- *- * ⚠️ DECLARED BEFORE THE RESTORE PASS, and it has to stay there. `restoreAgents` runs during- * start-up and calls `buildLaunch` for every pane it rebuilds, which asks this — and a `const`- * declared further down the function is still in its dead zone then, so the daemon died on boot- * with `Cannot access 'downgradedPermission' before initialization` on any machine that had a- * pane to restore. Everything it needs is imported; it closes over nothing local.- */- const downgradedPermission = async (- session: RegisteredSession,- bypassPermission: boolean,- what: string,- ): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }> => {- const { choice, droppedFlag } = await dropPermissionFlagIfUnsupported(session.engine, {- permissionMode: session.permissionMode ?? null,- bypassPermission,- })- if (droppedFlag) {- console.warn(`[agent] ${what} ${sid(session.agentId)} · ${session.engine} does not take ${droppedFlag}`- + ` · starting in Ask · update ${session.engine} to get ${session.permissionMode ?? 'Auto'} back`)- }- return choice- }-- const prepareSessionResume = (session: RegisteredSession): void => {- const repair = prepareCodexResume(session)- if (repair.repairedItems) {- // The rollout we tail was just shrunk in place. Move the tail to the repaired length now, before- // the resumed engine appends, or the watcher would read the whole repaired history as new lines- // and the live normalizer would replay the conversation into web/device. See Watcher.setTail.- if (repair.repairedBytes !== undefined) watcher.setTail(session.sessionId, repair.repairedBytes)- console.log(`[resume] repaired ${repair.repairedItems} Codex reasoning items · backup: ${repair.backupPath}`)- }- }+ // What a relaunch needs to bring a pane back (core/agents/launch.ts). Declared before the restore+ // pass below, which calls these for every pane it rebuilds.+ const launchHelpers = createLaunchHelpers({+ prepareApiTools,+ savedApis,+ launchOverridesDeps,+ setGridLaunch: (agentId, launch) => registry.setGridLaunch(agentId, launch),+ setTail: (sessionId, offset) => watcher.setTail(sessionId, offset),+ })+ const relaunchOverrides = launchHelpers.relaunchOverrides+ const refreshGridWebSearch = launchHelpers.refreshGridWebSearch+ const downgradedPermission = launchHelpers.downgradedPermission+ const prepareSessionResume = launchHelpers.prepareSessionResume// Rows that drifted out of their project folder while `register` still took the hook's cwd on// every prompt are put back BEFORE anything relaunches them: restore below `cd`s into `entry.cwd`,@@ -4284,22 +3805,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {setVoiceRouterDeviceConnected(connected)}- // Web cancel (C-c) interrupts the turn — claude writes no end_turn line to close it, so stop the- // heartbeat and mark the turn closed here (mirrors the hosted runtime stopping its heartbeat on cancel). We do- // NOT emit turn_ended: the web clears its own dots on cancel, and a turn_ended would fire a device- // recap for a killed turn. The next real prompt reopens a fresh turn.- const cancelAgent = (id: string, confirmed = false): Promise<boolean> => {- const record = registry.resolve(id)- const sessionId = record?.sessionId ?? id- normalizers.closeTurns(sessionId)- cursorSubagents.forget(sessionId)- const cancelled = confirmed ? input.cancelConfirmed(record?.agentId ?? sessionId) : (input.cancel(record?.agentId ?? sessionId), Promise.resolve(true))- autonomousDeviceService?.turnEnded(record?.agentId ?? sessionId, true)- stopHeartbeat(sessionId)- questionWatcher.stop(sessionId)- mirror.cancel(sessionId) // close the device's "Working…" tile (bare done, no recap) — a cancel emits no turn_ended- return cancelled- }+ // Cancelling a turn (core/turns/cancel.ts).+ const cancelAgent = createCancel({+ resolve: (id) => registry.resolve(id),+ normalizers,+ cursorSubagents,+ input,+ device: () => autonomousDeviceService,+ stopHeartbeat,+ questionWatcher,+ mirror,+ })backend.onCancel = id => { void cancelAgent(id) }/**diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.tsnew file mode 100644index 000000000..bdc874d92--- /dev/null+++ b/cli/src/core/agents/bind.spec.ts@@ -0,0 +1,384 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { findAgyTranscript } from '../../engines/agy/session.js'+import { copilotSessionForPid, findCopilotTranscript } from '../../engines/copilot/session.js'+import { findCursorTranscript } from '../../engines/cursor/discovery.js'+import { findGrokTranscript } from '../../engines/grok/session.js'+import { isRecentlyDeleted } from '../../lib/deletedSessions.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { claudeContinuation, findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'+import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'+import { createBinding, statBirthMs, type BindDeps, type RegisteredMeta } from './bind.js'++vi.mock('../../engines/agy/session.js', () => ({ findAgyTranscript: vi.fn(async () => '/t/agy.jsonl') }))+vi.mock('../../engines/copilot/session.js', () => ({ copilotSessionForPid: vi.fn(async () => null), findCopilotTranscript: vi.fn(async () => '/t/copilot.jsonl') }))+vi.mock('../../engines/cursor/discovery.js', async (real) => ({ ...await real<object>(), findCursorTranscript: vi.fn(async () => '/t/cursor.jsonl') }))+vi.mock('../../engines/cursor/home.js', async (real) => ({ ...await real<object>(), cursorDataDir: () => '/cursor' }))+vi.mock('../../engines/grok/session.js', () => ({ findGrokTranscript: vi.fn(async () => '/t/grok.jsonl') }))+vi.mock('../../lib/deletedSessions.js', () => ({ isRecentlyDeleted: vi.fn(() => false) }))+vi.mock('../../lib/sessionRepair.js', () => ({+ claudeContinuation: vi.fn(async () => null),+ findLiveSession: vi.fn(async () => null),+ findResumedTranscript: vi.fn(async () => '/t/resumed.jsonl'),+}))++const dirs: string[] = []++/** Every engine lookup back to its default answer, calls forgotten, before each test. */+function resetLookups() {+ vi.mocked(findAgyTranscript).mockReset().mockResolvedValue('/t/agy.jsonl')+ vi.mocked(copilotSessionForPid).mockReset().mockResolvedValue(null)+ vi.mocked(findCopilotTranscript).mockReset().mockResolvedValue('/t/copilot.jsonl')+ vi.mocked(findCursorTranscript).mockReset().mockResolvedValue('/t/cursor.jsonl')+ vi.mocked(findGrokTranscript).mockReset().mockResolvedValue('/t/grok.jsonl')+ vi.mocked(isRecentlyDeleted).mockReset().mockReturnValue(false)+ vi.mocked(claudeContinuation).mockReset().mockResolvedValue(null)+ vi.mocked(findLiveSession).mockReset().mockResolvedValue(null)+ vi.mocked(findResumedTranscript).mockReset().mockResolvedValue('/t/resumed.jsonl')+}+beforeEach(resetLookups)++const agent = (over: Partial<RegisteredSession> = {}): RegisteredSession =>+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', registeredAt: 0, ...over }) as RegisteredSession+const meta = (over: Partial<RegisteredMeta> = {}): RegisteredMeta => ({ isNew: false, evicted: null, rebound: null, ...over })++function setup(over: Partial<BindDeps> = {}) {+ const byAgent = new Map<string, RegisteredSession>()+ const bySession = new Map<string, RegisteredSession>()+ const deps: BindDeps = {+ registry: {+ inheritName: vi.fn(),+ unbindSession: vi.fn(() => true),+ byAgent: vi.fn((agentId: string) => byAgent.get(agentId)),+ byProcess: vi.fn(() => undefined),+ register: vi.fn(() => null),+ has: vi.fn(() => false),+ bySession: vi.fn((sessionId: string) => bySession.get(sessionId)),+ } as unknown as BindDeps['registry'],+ mirror: { inheritSummary: vi.fn() },+ forgetSession: vi.fn(),+ clients: { send: vi.fn() },+ attachSession: vi.fn(async () => true),+ announceSession: vi.fn(),+ stoppedAgents: { save: vi.fn(), finishResume: vi.fn() },+ syncRecapPool: vi.fn(),+ teams: { forget: vi.fn() },+ input: { forget: vi.fn() },+ deviceInput: { forget: vi.fn() },+ homes: { copilot: '/copilot', grok: '/grok', agy: '/agy' },+ ...over,+ }+ return { deps, byAgent, bySession, binding: createBinding(deps) }+}++describe('binding a registered session to its agent', () => {+ beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })+ afterEach(() => {+ vi.restoreAllMocks()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ })++ it('attaches a new session, archives it as the agent\'s, names it and tells the app', async () => {+ const run = setup()+ const entry = agent({ boundAt: Date.parse('2026-10-04T10:00:00Z') })+ run.byAgent.set('a1', entry)+ await run.binding.handleRegistered(entry, meta({ isNew: true }))+ expect(run.deps.attachSession).toHaveBeenCalledWith(entry, true, false, false)+ expect(run.deps.stoppedAgents.save).toHaveBeenCalledWith(entry)+ expect(run.deps.syncRecapPool).toHaveBeenCalled()+ expect(run.deps.registry.inheritName).toHaveBeenCalledWith('a1', 's1')+ expect(run.deps.announceSession).toHaveBeenCalledWith(entry)+ expect(run.deps.clients.send).toHaveBeenCalledWith({+ type: 'session_synced',+ payload: { sessionId: 's1', agentId: 'a1', title: expect.any(String), createdAt: '2026-10-04T10:00:00.000Z' },+ })+ })++ it('stops after the attach for a session it already had, and finishes a resume it was waiting for', async () => {+ const run = setup()+ const entry = agent({ resumeOnly: true } as Partial<RegisteredSession>)+ run.byAgent.set('a1', entry)+ await run.binding.handleRegistered(entry, meta())+ expect(run.deps.stoppedAgents.finishResume).toHaveBeenCalledWith('a1')+ expect(run.deps.announceSession).not.toHaveBeenCalled()+ // Bound elsewhere by the time the attach finished: not this agent's session to archive.+ run.byAgent.set('a1', agent({ sessionId: 'other' }))+ vi.mocked(run.deps.stoppedAgents.save).mockClear()+ await run.binding.handleRegistered(agent(), meta())+ expect(run.deps.stoppedAgents.save).not.toHaveBeenCalled()+ })++ it('unbinds a session whose pane is gone and re-announces its agent', async () => {+ const run = setup({ attachSession: vi.fn(async () => false) })+ const entry = agent()+ await run.binding.handleRegistered(entry, meta({ isNew: true }))+ expect(run.deps.registry.unbindSession).toHaveBeenCalledWith('s1')+ expect(run.deps.announceSession).toHaveBeenCalledWith(entry)+ expect(run.deps.syncRecapPool).not.toHaveBeenCalled()+ })++ it('hands a rebound agent its name and recap, and lets the stale session go', async () => {+ const run = setup()+ await run.binding.handleRegistered(agent({ sessionId: 's2' }), meta({ rebound: 's1' }))+ expect(run.deps.registry.inheritName).toHaveBeenCalledWith('s1', 's2')+ expect(run.deps.mirror.inheritSummary).toHaveBeenCalledWith('s1', 's2')+ expect(run.deps.forgetSession).toHaveBeenCalledWith('s1', { force: true, keepAgent: true })+ expect(run.deps.clients.send).toHaveBeenCalledWith({ type: 'session_reset', payload: { staleSessionId: 's1' } })+ })++ it('forgets an evicted session and an agent the bind emptied out', async () => {+ const run = setup()+ await run.binding.handleRegistered(agent(), meta({ evicted: 's0', orphaned: { agentId: 'a0', sessionId: 's0' } }))+ expect(vi.mocked(run.deps.forgetSession).mock.calls).toEqual([+ ['s0', { force: true }],+ ['a0', { force: true, agentId: 'a0' }],+ ])+ })++ it('gives a fork the recap of its source once its own session reports in', async () => {+ const run = setup()+ run.binding.pendingForkInherit.set('a1', 'source-s')+ await run.binding.handleRegistered(agent({ sessionId: '' }), meta())+ expect(run.deps.mirror.inheritSummary).not.toHaveBeenCalled()+ await run.binding.handleRegistered(agent(), meta())+ expect(run.deps.mirror.inheritSummary).toHaveBeenCalledWith('source-s', 's1')+ expect(run.binding.pendingForkInherit.has('a1')).toBe(false)+ })++ it('resets on a SessionStart, except for engines that announce one turn more than once', async () => {+ const run = setup()+ for (const engine of ['claude', 'cursor', 'agy', 'copilot']) {+ await run.binding.handleRegistered(agent({ engine } as Partial<RegisteredSession>), meta({ hookEvent: 'SessionStart' }))+ }+ expect(vi.mocked(run.deps.attachSession).mock.calls.map((call) => [call[0].engine, call[1], call[2]])).toEqual([+ ['claude', true, false], ['cursor', false, true], ['agy', false, false], ['copilot', false, false],+ ])+ })++ it('replays a transcript born after its agent from the start, judged by the file\'s birth', async () => {+ const run = setup()+ const dir = mkdtempSync(join(tmpdir(), 'core-bind-'))+ dirs.push(dir)+ const born = join(dir, 'session.jsonl')+ writeFileSync(born, '{}\n')+ await run.binding.handleRegistered(agent({ transcriptPath: born, registeredAt: Date.now() - 60_000 }), meta())+ await run.binding.handleRegistered(agent({ transcriptPath: join(dir, 'missing.jsonl'), registeredAt: Date.now() - 60_000 }), meta())+ expect(vi.mocked(run.deps.attachSession).mock.calls.map((call) => call[3])).toEqual([true, false])+ })+})++describe('binding a running process to its session', () => {+ const observed = (over: Partial<DiscoveredTerminalAgent> = {}): DiscoveredTerminalAgent => ({+ engine: 'claude',+ cwd: '/work',+ runtimes: [],+ primaryRuntimeKey: 'tmux:%0',+ processIdentity: { pid: 42, startMarker: '2026-10-04T10:00:00Z' },+ ...over,+ }) as DiscoveredTerminalAgent++ beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })+ afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() })++ it('ignores a process no agent runs, and a resume still launching', async () => {+ const run = setup()+ await run.binding.bindObservedAgent(observed())+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ resumeOnly: true, launch: { state: 'starting' } } as Partial<RegisteredSession>))+ await run.binding.bindObservedAgent(observed())+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ })++ describe('an agent that already has a session', () => {+ it('follows Copilot to the session it /resumed into, and only to a new one', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ engine: 'copilot' } as Partial<RegisteredSession>))+ await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))+ vi.mocked(copilotSessionForPid).mockResolvedValueOnce('s1')+ await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))+ vi.mocked(copilotSessionForPid).mockResolvedValueOnce('deleted')+ vi.mocked(isRecentlyDeleted).mockReturnValueOnce(true)+ await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ vi.mocked(copilotSessionForPid).mockResolvedValue('s2')+ const rotated = agent({ engine: 'copilot', sessionId: 's2' } as Partial<RegisteredSession>)+ vi.mocked(run.deps.registry.register).mockReturnValueOnce({ entry: rotated, ...meta({ isNew: true }) } as never)+ await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))+ expect(copilotSessionForPid).toHaveBeenLastCalledWith('/copilot', 42)+ expect(findCopilotTranscript).toHaveBeenLastCalledWith('/copilot', 's2')+ expect(vi.mocked(run.deps.registry.register).mock.calls[0][0]).toMatchObject({ sessionId: 's2', transcriptPath: '/t/copilot.jsonl', source: 'copilot-resume' })+ expect(run.deps.attachSession).toHaveBeenCalledWith(rotated, true, false, false)+ // Not new to the registry, or no transcript yet: registered as it is, attached by its hook later.+ vi.mocked(findCopilotTranscript).mockResolvedValueOnce(null)+ vi.mocked(run.deps.registry.register).mockReturnValueOnce({ entry: rotated, ...meta() } as never)+ await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))+ expect(vi.mocked(run.deps.registry.register).mock.calls[1][0]).toMatchObject({ transcriptPath: undefined })+ expect(run.deps.attachSession).toHaveBeenCalledTimes(1)+ })++ it('follows Claude Code to the file its transcript rolled over to, when that is new', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ transcriptPath: '/t/s1.jsonl' }))+ await run.binding.bindObservedAgent(observed())+ for (const continuation of [{ sessionId: 's1' }, { sessionId: 'known' }, { sessionId: 'deleted' }]) {+ vi.mocked(claudeContinuation).mockResolvedValueOnce({ ...continuation, transcriptPath: '/t/x.jsonl' } as never)+ }+ vi.mocked(run.deps.registry.has).mockImplementation((sessionId: string) => sessionId === 'known')+ vi.mocked(isRecentlyDeleted).mockImplementation((sessionId?: string) => sessionId === 'deleted')+ for (let i = 0; i < 3; i++) await run.binding.bindObservedAgent(observed())+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ vi.mocked(claudeContinuation).mockResolvedValue({ sessionId: 's2', transcriptPath: '/t/s2.jsonl' } as never)+ vi.mocked(run.deps.registry.register).mockReturnValueOnce({ entry: agent({ sessionId: 's2' }), ...meta({ isNew: true }) } as never)+ await run.binding.bindObservedAgent(observed())+ expect(vi.mocked(run.deps.registry.register).mock.calls[0][0]).toMatchObject({ sessionId: 's2', source: 'claude-continuation' })+ expect(run.deps.attachSession).toHaveBeenCalledTimes(1)+ vi.mocked(run.deps.registry.register).mockReturnValueOnce(null)+ await run.binding.bindObservedAgent(observed())+ expect(run.deps.attachSession).toHaveBeenCalledTimes(1)+ })++ it('leaves any other engine, or Claude Code without a transcript, as it is', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValueOnce(agent({ engine: 'pi' } as Partial<RegisteredSession>)).mockReturnValueOnce(agent())+ await run.binding.bindObservedAgent(observed({ engine: 'pi' }))+ await run.binding.bindObservedAgent(observed())+ expect(claudeContinuation).not.toHaveBeenCalled()+ })+ })++ describe('a resume named on the command line', () => {+ it('finds each engine\'s transcript where that engine keeps it', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))+ const expected: Record<string, string | undefined> = {+ cursor: '/t/cursor.jsonl', grok: '/t/grok.jsonl', agy: '/t/agy.jsonl', copilot: '/t/copilot.jsonl',+ claude: '/t/resumed.jsonl', codex: '/t/resumed.jsonl', pi: undefined,+ }+ for (const engine of Object.keys(expected)) {+ await run.binding.bindObservedAgent(observed({ engine, resumeSessionId: `${engine}-resumed` } as Partial<DiscoveredTerminalAgent>))+ }+ expect(vi.mocked(run.deps.registry.register).mock.calls.map(([input]) => [input.engine, input.transcriptPath, input.source, input.hookEvent])).toEqual(+ Object.entries(expected).map(([engine, path]) => [engine, path, 'terminal-resume', 'TerminalResumeDiscovery']),+ )+ expect(findCursorTranscript).toHaveBeenCalledWith('/cursor', 'cursor-resumed')+ expect(findGrokTranscript).toHaveBeenCalledWith('/grok', '/work', 'grok-resumed')+ expect(findAgyTranscript).toHaveBeenCalledWith('/agy', 'agy-resumed')+ expect(findResumedTranscript).toHaveBeenCalledWith('codex', 'codex-resumed', { codexHome: undefined })+ })++ it('needs a transcript for the engines whose sessions are files, and skips a deleted session', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '', codexHome: '/codex' } as Partial<RegisteredSession>))+ vi.mocked(findCursorTranscript).mockResolvedValueOnce(null)+ vi.mocked(findGrokTranscript).mockResolvedValueOnce(null)+ vi.mocked(findResumedTranscript).mockResolvedValueOnce(null).mockResolvedValueOnce(null)+ for (const engine of ['cursor', 'grok', 'claude', 'codex']) {+ await run.binding.bindObservedAgent(observed({ engine, resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ }+ vi.mocked(findAgyTranscript).mockResolvedValueOnce(null)+ vi.mocked(findCopilotTranscript).mockResolvedValueOnce(null)+ await run.binding.bindObservedAgent(observed({ engine: 'agy', resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ await run.binding.bindObservedAgent(observed({ engine: 'copilot', resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ vi.mocked(isRecentlyDeleted).mockReturnValueOnce(true)+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'gone' } as Partial<DiscoveredTerminalAgent>))+ // agy and Copilot can bind before their file exists; the others cannot.+ expect(vi.mocked(run.deps.registry.register).mock.calls.map(([input]) => input.engine)).toEqual(['agy', 'copilot'])+ expect(findResumedTranscript).toHaveBeenCalledWith('codex', 'r', { codexHome: '/codex' })+ })++ it('gives a resumed session to the newer process, never to an older one or one whose start is unknown', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))+ // The holder started after this process (10:00), or this process's start cannot be read: it stays.+ run.bySession.set('r', agent({ agentId: 'newer', processIdentity: { pid: 1, startMarker: '2026-10-04T11:00:00Z' } } as Partial<RegisteredSession>))+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'r', processIdentity: { pid: 42, startMarker: 'not a time' } } as Partial<DiscoveredTerminalAgent>))+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ // A holder that started earlier, one whose start is unknown, or this very agent: the session moves.+ run.bySession.set('r', agent({ agentId: 'older', processIdentity: { pid: 1, startMarker: '2026-10-04T09:00:00Z' } } as Partial<RegisteredSession>))+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ run.bySession.set('r', agent({ agentId: 'older' }))+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ run.bySession.set('r', agent({ agentId: 'a1' }))+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ expect(run.deps.registry.register).toHaveBeenCalledTimes(3)+ })++ it('moves a session from the agent that had it, telling everything that held it for that agent', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))+ const previous = agent({ agentId: 'old', processIdentity: { pid: 1, startMarker: '2026-10-04T09:00:00Z' } } as Partial<RegisteredSession>)+ run.bySession.set('r', previous)+ vi.mocked(run.deps.registry.register).mockReturnValue({ entry: agent({ sessionId: 'r' }), ...meta({ isNew: true }) } as never)+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))+ expect(run.deps.teams.forget).toHaveBeenCalledWith('old')+ expect(run.deps.input.forget).toHaveBeenCalledWith('old')+ expect(run.deps.deviceInput.forget).toHaveBeenCalledWith('old')+ expect(run.deps.announceSession).toHaveBeenCalledWith(previous)+ expect(run.deps.attachSession).toHaveBeenCalled()+ })+ })++ describe('a repair', () => {+ it('looks for the session a new process opened, sweeping eagerly, then once a minute', async () => {+ vi.useFakeTimers()+ vi.setSystemTime(Date.parse('2026-10-04T10:00:00Z'))+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))+ for (let sweep = 0; sweep < 30; sweep++) await run.binding.bindObservedAgent(observed())+ expect(findLiveSession).toHaveBeenCalledTimes(24)+ vi.advanceTimersByTime(60_000)+ await run.binding.bindObservedAgent(observed())+ expect(findLiveSession).toHaveBeenCalledTimes(25)+ expect(findLiveSession).toHaveBeenLastCalledWith('claude', '/work', Date.parse('2026-10-04T10:00:00Z'), { bornOnly: true, pid: 42, codexHome: undefined })+ })++ it('binds what it finds, with the Hermes home it was found in, and starts the count over', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '', codexHome: '/codex' } as Partial<RegisteredSession>))+ vi.mocked(findLiveSession).mockResolvedValueOnce({ sessionId: 'found', transcriptPath: '/t/found.jsonl', hermesHome: '/hermes' } as never)+ vi.mocked(run.deps.registry.register).mockReturnValue({ entry: agent({ sessionId: 'found' }), ...meta({ isNew: true }) } as never)+ await run.binding.bindObservedAgent(observed({ engine: 'hermes' }))+ expect(vi.mocked(run.deps.registry.register).mock.calls[0][0]).toMatchObject({+ sessionId: 'found', transcriptPath: '/t/found.jsonl', hermesHome: '/hermes', source: 'process-repair', hookEvent: 'ProcessRepair',+ })+ vi.mocked(findLiveSession).mockResolvedValueOnce({ sessionId: 'found2', transcriptPath: '/t/found2.jsonl' } as never)+ await run.binding.bindObservedAgent(observed())+ expect(vi.mocked(run.deps.registry.register).mock.calls[1][0]).not.toHaveProperty('hermesHome')+ expect(run.deps.attachSession).toHaveBeenCalledTimes(2)+ })++ it('finds nothing to bind for an unknown start, nothing found, or a session taken or deleted', async () => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '', agentId: 'repair' }))+ await run.binding.bindObservedAgent(observed({ processIdentity: { pid: 42, startMarker: 'unknown' } } as Partial<DiscoveredTerminalAgent>))+ expect(findLiveSession).not.toHaveBeenCalled()+ await run.binding.bindObservedAgent(observed())+ vi.mocked(findLiveSession).mockResolvedValueOnce({ sessionId: 'taken' } as never).mockResolvedValueOnce({ sessionId: 'deleted' } as never)+ vi.mocked(run.deps.registry.has).mockImplementation((sessionId: string) => sessionId === 'taken')+ vi.mocked(isRecentlyDeleted).mockImplementation((sessionId?: string) => sessionId === 'deleted')+ await run.binding.bindObservedAgent(observed())+ await run.binding.bindObservedAgent(observed())+ // Registered but not new: nothing more to do.+ vi.mocked(findLiveSession).mockResolvedValueOnce({ sessionId: 'same' } as never)+ vi.mocked(run.deps.registry.register).mockReturnValueOnce({ entry: agent({ sessionId: 'same' }), ...meta() } as never)+ await run.binding.bindObservedAgent(observed())+ expect(run.deps.registry.register).toHaveBeenCalledTimes(1)+ expect(run.deps.attachSession).not.toHaveBeenCalled()+ })+ })+})++describe('a transcript\'s birth time', () => {+ const at = (birthtimeMs: number, ctimeMs: number, mtimeMs: number) => async () => ({ birthtimeMs, ctimeMs, mtimeMs })++ it('is its birth time, else its change time, else its write time, and 0 when unreadable or not a time', async () => {+ expect(await statBirthMs('/t', at(3, 2, 1))).toBe(3)+ expect(await statBirthMs('/t', at(0, 2, 1))).toBe(2)+ expect(await statBirthMs('/t', at(0, 0, 1))).toBe(1)+ expect(await statBirthMs('/t', at(Number.POSITIVE_INFINITY, 0, 0))).toBe(0)+ expect(await statBirthMs('/t', at(0, 0, Number.NaN))).toBe(0)+ expect(await statBirthMs('/t', async () => { throw new Error('ENOENT') })).toBe(0)+ })+})diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.tsnew file mode 100644index 000000000..10e25a916--- /dev/null+++ b/cli/src/core/agents/bind.ts@@ -0,0 +1,315 @@+/**+ * Binding: a session to its agent (`handleRegistered`, after the registry took a hook's or a discovery's+ * registration) and a running engine process to the session it is in (`bindObservedAgent`, from the+ * reconciler's scans: a resume named on the command line, a session the process changed to without a+ * hook, or one repaired by looking for it).+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).+ */+import { stat } from 'node:fs/promises'+import { findAgyTranscript } from '../../engines/agy/session.js'+import { copilotSessionForPid, findCopilotTranscript } from '../../engines/copilot/session.js'+import { findCursorTranscript } from '../../engines/cursor/discovery.js'+import { cursorDataDir } from '../../engines/cursor/home.js'+import { findGrokTranscript } from '../../engines/grok/session.js'+import type { CommanderMirror } from '../../lib/commander.js'+import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'+import { isRecentlyDeleted } from '../../lib/deletedSessions.js'+import { transcriptIsFirstTurn } from '../../lib/firstTurnReplay.js'+import { sid } from '../../lib/log.js'+import { projectDisplayName, type registry, type RegisteredSession } from '../../lib/registry.js'+import type { SessionInputController } from '../../lib/sessionInput.js'+import { claudeContinuation, findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'+import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'+import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'+import type { SwarmPromptScopes } from '../../teams/promptScope.js'++/** Between session-binding attempts for a process whose engine store is not resolvable yet. */+const REPAIR_RETRY_MS = 60_000+/** A NEW process is waiting for a session that is about to appear. Muse makes+ * this concrete — its session is only claimable once the user has typed, because a file with no turn in+ * it cannot be told apart from the ones muse opens for itself. Backing off a full minute there costs the+ * FIRST message: the pane answers while web and device show nothing. So keep sweeping for a while first,+ * then settle into the slow rhythm for processes that will never resolve. */+const REPAIR_EAGER_ATTEMPTS = 24 // ≈2 min at the 5s sweep++/** Birth time of a transcript in ms, or 0 when it cannot be read (treated as "not newer than the agent").+ * A filesystem that keeps no birth time reports 0 for it: the change time, then the write time, stand in. */+export async function statBirthMs(path: string, statFile: (path: string) => Promise<{ birthtimeMs: number; ctimeMs: number; mtimeMs: number }> = stat): Promise<number> {+ const st = await statFile(path).catch(() => null)+ if (!st) return 0+ const birth = st.birthtimeMs || st.ctimeMs || st.mtimeMs+ return Number.isFinite(birth) ? birth : 0+}++/** What the registry says about a registration it just took. */+export type RegisteredMeta = {+ isNew: boolean+ evicted: string | null+ rebound: string | null+ orphaned?: { agentId: string; sessionId: string } | null+ hookEvent?: string+}++export interface BindDeps {+ registry: Pick<typeof registry, 'inheritName' | 'unbindSession' | 'byAgent' | 'byProcess' | 'register' | 'has' | 'bySession'>+ mirror: Pick<CommanderMirror, 'inheritSummary'>+ forgetSession: (id: string, opts?: { force?: boolean; keepAgent?: boolean; agentId?: string }) => void+ /** The app. */+ clients: { send(frame: { type: string; payload: Record<string, unknown> }): void }+ attachSession: (session: RegisteredSession, reset?: boolean, replayCursorFromStart?: boolean, replayFromStart?: boolean) => Promise<boolean>+ announceSession: (session: RegisteredSession) => void+ stoppedAgents: Pick<StoppedAgentStore, 'save' | 'finishResume'>+ syncRecapPool: () => void+ teams: Pick<SwarmPromptScopes, 'forget'>+ input: Pick<SessionInputController, 'forget'>+ deviceInput: Pick<AutonomousDeviceInput, 'forget'>+ /** Where Copilot, Grok and agy keep their sessions. */+ homes: { copilot: string; grok: string; agy: string }+}++export function createBinding({+ registry, mirror, forgetSession, clients, attachSession, announceSession, stoppedAgents, syncRecapPool, teams,+ input, deviceInput, homes,+}: BindDeps) {+ /**+ * Forks whose engine session has not reported in yet, agentId → the SOURCE's sessionId. A fork's tile+ * should open with the source's last recap on it, the way its pane opens with the source's transcript+ * — but the mirror keys by session, and the fork's session id is the engine's to name, minutes later+ * over a hook. Settled the moment it binds, below.+ */+ const pendingForkInherit = new Map<string, string>()++ const handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {+ const forkSource = pendingForkInherit.get(entry.agentId)+ if (forkSource && entry.sessionId) {+ pendingForkInherit.delete(entry.agentId)+ mirror.inheritSummary(forkSource, entry.sessionId)+ }+ if (meta.rebound) {+ registry.inheritName(meta.rebound, entry.sessionId)+ mirror.inheritSummary(meta.rebound, entry.sessionId)+ forgetSession(meta.rebound, { force: true, keepAgent: true })+ clients.send({ type: 'session_reset', payload: { staleSessionId: meta.rebound } })+ console.log(`[agent] ${sid(entry.agentId)} rebound ${sid(meta.rebound)} → ${sid(entry.sessionId)}`)+ } else if (meta.evicted) {++ forgetSession(meta.evicted, { force: true })+ }+ // The agent this bind emptied out — `claude --resume` in a second pane, with+ // the first one's engine already gone. The registry dropped it; without this+ // the app kept showing it until someone hit Reload machines by hand, and+ // opening it landed on TERMINAL FROZEN because it has nothing left to open.+ //+ // Not part of the chain above: a rebound bind can orphan an agent too, so+ // this has to be asked independently of which branch ran.+ if (meta.orphaned) {+ forgetSession(meta.orphaned.agentId, {+ force: true,+ agentId: meta.orphaned.agentId,+ })+ }++ // agy is excluded for the same reason as cursor, arriving by a different road: it has no+ // session-start event at all. The closest thing is `PreInvocation`, which fires before EVERY model+ // round-trip — four to seven times in one measured turn — and each one re-folded the transcript and+ // re-emitted `turn_started` for a turn already open (measured: two turn_started, one turn_ended).+ // Its first bind is covered by `meta.isNew`, and registry derives the transcript path from the+ // conversation id, so nothing here depends on a later announcement carrying it.+ // Copilot joins cursor and agy for a third reason: it announces the SAME turn twice. Its+ // `userPromptSubmitted` and `sessionStart` hooks both register (measured 2.5s apart, and in that+ // order — sessionStart fires AFTER the first prompt), so treating the second as a reset re-folded+ // the transcript and emitted a second `turn_started` for one exchange.+ const reset = meta.isNew+ || (entry.engine !== 'cursor' && entry.engine !== 'agy' && entry.engine !== 'copilot'+ && meta.hookEvent === 'SessionStart')+ // Deliberately NOT gated on `meta.isNew`. `isNew` is false in exactly the case this is meant to catch:+ // a session announced once BEFORE its transcript exists and registered again when the file appears —+ // the second announcement is the only one that can carry the path, and it reports `isNew=false`+ // (measured: `[hooks] 019fff7f SessionStart · engine=codex · isNew=false`, whose whole first turn was+ // then folded away as history and never reached web or device).+ //+ // `statBirthMs >= registeredAt` is what actually separates the two cases. Measured on one machine,+ // same claude session, transcript birth relative to each timestamp:+ //+ // first turn resumed (`claude --continue`)+ // registeredAt +18.1s -81.5s ← separates cleanly+ // boundAt -0.5s -81.6s ← negative for BOTH; useless as a test+ //+ // so the birth-vs-`registeredAt` comparison stays, and comparing against `boundAt` instead — the+ // obvious-looking alternative, since `boundAt` is when this session was bound — does not work: the+ // transcript is created a moment BEFORE the hook binds it.+ //+ // And only while the file is new (`transcriptIsFirstTurn`): a long session's transcript was born after+ // its agent too, and after a daemon restart its next SessionStart replayed the whole history live.+ const bornAfterAgent = transcriptIsFirstTurn(+ entry,+ entry.transcriptPath ? await statBirthMs(entry.transcriptPath) : 0,+ { rebound: !!meta.rebound, now: Date.now() },+ )+ const attached = await attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent)+ if (!attached) {+ registry.unbindSession(entry.sessionId)+ announceSession(entry)+ return+ }+ const confirmed = registry.byAgent(entry.agentId)+ if (confirmed?.sessionId === entry.sessionId) {+ stoppedAgents.save(confirmed)+ if (confirmed.resumeOnly) stoppedAgents.finishResume(confirmed.agentId)+ }+ syncRecapPool()+ if (!meta.isNew) return+ registry.inheritName(entry.agentId, entry.sessionId)+ announceSession(entry)+ clients.send({+ type: 'session_synced',+ payload: {+ sessionId: entry.sessionId,+ agentId: entry.agentId,+ title: projectDisplayName(entry),+ createdAt: new Date(entry.boundAt ?? Date.now()).toISOString(),+ },+ })+ }++ const lastRepairAttempt = new Map<string, number>()+ const repairAttempts = new Map<string, number>()+ const bindObservedAgent = async (observed: DiscoveredTerminalAgent): Promise<void> => {+ const agent = registry.byProcess(observed.engine, observed.processIdentity)+ if (!agent) return++ // Copilot can change session WITHOUT changing process: `/resume` inside the CLI opens another one,+ // and the pane then shows a conversation the daemon is not streaming. Every other engine here+ // starts a new process for that, which is why this path used to stop at `agent.sessionId`.+ //+ // The switch leaves exactly one trace — the `inuse.<pid>.lock` Copilot takes on the new session+ // directory. It writes nothing to the transcript and fires no hook until the next prompt.+ if (agent.resumeOnly && agent.launch && agent.launch.state !== 'ready') return+ if (agent.sessionId) {+ if (observed.engine === 'copilot') {+ const current = await copilotSessionForPid(homes.copilot, observed.processIdentity.pid)+ if (!current || current === agent.sessionId || isRecentlyDeleted(current)) return+ const transcript = await findCopilotTranscript(homes.copilot, current)+ console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(current)} (/resume)`)+ const rotated = registry.register({+ engine: 'copilot',+ sessionId: current,+ transcriptPath: transcript ?? undefined,+ cwd: observed.cwd,+ source: 'copilot-resume',+ runtimes: observed.runtimes,+ primaryRuntimeKey: observed.primaryRuntimeKey,+ processIdentity: observed.processIdentity,+ hookEvent: 'CopilotResume',+ })+ if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ return+ }+ // Claude can also change session WITHOUT any hook firing: a long conversation's transcript+ // rolls over to a new file on its own (compaction/a resume chain), and if the turn that follows+ // lands on a pooled/"spare" worker process rather than one spawned fresh in the pane, no+ // SessionStart/UserPromptSubmit ever reaches us for it — the agent is left bound to a transcript+ // that has gone quiet forever while the real conversation continues one file over. Checked on+ // the same cadence this reconciler already re-observes every live process, so it costs nothing+ // extra to ask.+ if (observed.engine === 'claude' && agent.transcriptPath) {+ const continuation = await claudeContinuation(agent.transcriptPath)+ if (!continuation || continuation.sessionId === agent.sessionId+ || registry.has(continuation.sessionId) || isRecentlyDeleted(continuation.sessionId)) return+ console.log(`[discovery] ${sid(agent.agentId)} claude session continued ${sid(agent.sessionId)} → ${sid(continuation.sessionId)}`)+ const rotated = registry.register({+ engine: 'claude',+ sessionId: continuation.sessionId,+ transcriptPath: continuation.transcriptPath,+ cwd: observed.cwd,+ source: 'claude-continuation',+ runtimes: observed.runtimes,+ primaryRuntimeKey: observed.primaryRuntimeKey,+ processIdentity: observed.processIdentity,+ hookEvent: 'ClaudeContinuation',+ })+ if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ return+ }+ return+ }++ let sessionId = observed.resumeSessionId+ let transcriptPath: string | undefined+ let hermesHome: string | undefined+ let source = 'terminal-resume'+ if (sessionId) {+ if (isRecentlyDeleted(sessionId)) return+ const owner = registry.bySession(sessionId)+ if (owner && owner.agentId !== agent.agentId) {+ const observedStarted = Date.parse(observed.processIdentity.startMarker)+ const ownerStarted = Date.parse(owner.processIdentity?.startMarker ?? '')+ if (Number.isFinite(ownerStarted) && (!Number.isFinite(observedStarted) || observedStarted <= ownerStarted)) return+ }+ transcriptPath = observed.engine === 'cursor'+ ? await findCursorTranscript(cursorDataDir(), sessionId) ?? undefined+ : observed.engine === 'grok'+ ? await findGrokTranscript(homes.grok, observed.cwd, sessionId) ?? undefined+ : observed.engine === 'agy'+ ? await findAgyTranscript(homes.agy, sessionId) ?? undefined+ : observed.engine === 'copilot'+ ? await findCopilotTranscript(homes.copilot, sessionId) ?? undefined+ : observed.engine === 'claude' || observed.engine === 'codex'+ ? await findResumedTranscript(observed.engine, sessionId, { codexHome: agent.codexHome ?? undefined }) ?? undefined+ : undefined+ // The registry refuses a claude/codex session without its file, so a resume of a transcript this+ // machine does not have is not a session — the hook that follows the user's next prompt will say.+ if ((observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'claude' || observed.engine === 'codex')+ && !transcriptPath) return+ } else {+ const attempts = repairAttempts.get(agent.agentId) ?? 0+ const lastAttempt = lastRepairAttempt.get(agent.agentId) ?? 0+ if (attempts >= REPAIR_EAGER_ATTEMPTS && Date.now() - lastAttempt < REPAIR_RETRY_MS) return+ lastRepairAttempt.set(agent.agentId, Date.now())+ repairAttempts.set(agent.agentId, attempts + 1)+ const startedAtMs = Date.parse(observed.processIdentity.startMarker)+ if (!Number.isFinite(startedAtMs)) return+ // agy cannot be found by directory — its repair reads the presence lock the process holds open.+ //+ const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, {+ bornOnly: true,+ pid: observed.processIdentity.pid,+ codexHome: agent.codexHome ?? undefined,+ })+ if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return+ sessionId = found.sessionId+ transcriptPath = found.transcriptPath+ // Which Hermes home the repair found it in, so the row starts life reading the right store+ // rather than looking it up again on its first poll.+ hermesHome = found.hermesHome+ source = 'process-repair'+ }++ const previousOwner = registry.bySession(sessionId)+ const result = registry.register({+ engine: observed.engine,+ sessionId,+ transcriptPath,+ ...(hermesHome ? { hermesHome } : {}),+ cwd: observed.cwd,+ source,+ runtimes: observed.runtimes,+ primaryRuntimeKey: observed.primaryRuntimeKey,+ processIdentity: observed.processIdentity,+ hookEvent: source === 'terminal-resume' ? 'TerminalResumeDiscovery' : 'ProcessRepair',+ })+ if (!result || !result.isNew) return+ if (previousOwner && previousOwner.agentId !== result.entry.agentId) {+ teams.forget(previousOwner.agentId)+ input.forget(previousOwner.agentId)+ deviceInput.forget(previousOwner.agentId)+ announceSession(previousOwner)+ }+ lastRepairAttempt.delete(agent.agentId)+ repairAttempts.delete(agent.agentId)+ await handleRegistered(result.entry, result)+ console.log(`[discovery] bound ${observed.engine} session ${sid(result.entry.sessionId)} via ${observed.primaryRuntimeKey}`)+ }+ return { pendingForkInherit, handleRegistered, bindObservedAgent }+}diff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.tsnew file mode 100644index 000000000..9668bab7d--- /dev/null+++ b/cli/src/core/agents/discovery.spec.ts@@ -0,0 +1,269 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'+import { bypassPermissionActive, permissionModeFromArgv, tmuxPaneState } from '../../lib/tmux.js'+import { createDiscoveryHandlers, type DiscoveryDeps } from './discovery.js'++vi.mock('../../lib/tmux.js', async (real) => ({ ...await real<object>(), tmuxPaneState: vi.fn(async () => null) }))++const row = (over: Partial<RegisteredSession> = {}): RegisteredSession =>+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', active: true, ...over }) as RegisteredSession+const seen = (over: Partial<DiscoveredTerminalAgent> = {}): DiscoveredTerminalAgent => ({+ engine: 'claude',+ cwd: '/work',+ runtimes: [{ backend: 'tmux', paneId: '%0' }],+ primaryRuntimeKey: 'tmux:%0',+ processIdentity: { pid: 42, startMarker: 'now' },+ args: 'claude',+ ...over,+}) as unknown as DiscoveredTerminalAgent++function setup(over: Partial<DiscoveryDeps> = {}) {+ const rows = new Map<string, RegisteredSession>()+ let restoreDegraded = false+ const deps: DiscoveryDeps = {+ registry: {+ byRuntimeEngine: vi.fn(() => undefined),+ openProcessAgent: vi.fn(() => null),+ adoptEngine: vi.fn(() => row()),+ updateRuntimes: vi.fn(),+ updateProcessIdentity: vi.fn(),+ setBypassPermission: vi.fn(),+ setPermissionMode: vi.fn(),+ setCodexHome: vi.fn(),+ setHermesHome: vi.fn(),+ setDsh: vi.fn(),+ byAgent: vi.fn((agentId: string) => rows.get(agentId)),+ setLaunch: vi.fn(),+ setActive: vi.fn(),+ terminalAvailable: vi.fn(() => false),+ setTerminalAvailable: vi.fn(),+ } as unknown as DiscoveryDeps['registry'],+ attachDsh: vi.fn(),+ forgetSession: vi.fn(),+ announceSession: vi.fn(),+ bindObservedAgent: vi.fn(async () => {}),+ syncRecapPool: vi.fn(),+ attachSession: vi.fn(async () => true),+ invalidateTerminalControl: vi.fn(),+ teams: { forget: vi.fn() },+ input: { forget: vi.fn() },+ deviceInput: { forget: vi.fn() },+ questionWatcher: { stop: vi.fn() },+ stopHeartbeat: vi.fn(),+ retainExitedSession: vi.fn(),+ stoppedAgents: { finishResume: vi.fn() },+ restoreDegraded: () => restoreDegraded,+ ...over,+ }+ return { deps, rows, handlers: createDiscoveryHandlers(deps), degrade: () => { restoreDegraded = true } }+}++const settle = () => new Promise((done) => setTimeout(done, 0))+const grid = (name: string) => ({ grid: name, baseUrl: `http://${name}.local`, model: 'm' })++describe('discovery', () => {+ beforeEach(() => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.mocked(tmuxPaneState).mockReset().mockResolvedValue(null)+ })+ afterEach(() => vi.restoreAllMocks())++ describe('a process no row owns', () => {+ it('opens an agent for it, announces it and binds its session', async () => {+ const run = setup()+ const opened = row({ agentId: 'new' })+ vi.mocked(run.deps.registry.openProcessAgent).mockReturnValue({ entry: opened, isNew: true, evicted: null } as never)+ await run.handlers.onDiscovered(seen())+ expect(run.deps.registry.openProcessAgent).toHaveBeenCalledWith(expect.objectContaining({ engine: 'claude', primaryRuntimeKey: 'tmux:%0' }))+ expect(run.deps.announceSession).toHaveBeenCalledWith(opened)+ expect(run.deps.bindObservedAgent).toHaveBeenCalled()+ expect(run.deps.attachDsh).not.toHaveBeenCalled()+ })++ it('attaches its DSH, forgets the agent it evicted from the pane, and re-announces a launch still starting', async () => {+ const run = setup()+ const opened = row({ agentId: 'a2', dsh: 'blender' } as Partial<RegisteredSession>)+ vi.mocked(run.deps.registry.byRuntimeEngine).mockReturnValue(row({ launch: { state: 'starting' } } as Partial<RegisteredSession>))+ vi.mocked(run.deps.registry.openProcessAgent).mockReturnValue({ entry: opened, isNew: false, evicted: row({ agentId: 'old', sessionId: '' }) } as never)+ await run.handlers.onDiscovered(seen())+ expect(run.deps.attachDsh).toHaveBeenCalledWith(opened)+ expect(run.deps.forgetSession).toHaveBeenCalledWith('old', { force: true, agentId: 'old' })+ expect(run.deps.announceSession).toHaveBeenCalledWith(opened)+ vi.mocked(run.deps.registry.openProcessAgent).mockReturnValue({ entry: row(), isNew: false, evicted: row({ agentId: 'old', sessionId: 'old-s' }) } as never)+ vi.mocked(run.deps.registry.byRuntimeEngine).mockReturnValue(row({ launch: { state: 'ready' } } as Partial<RegisteredSession>))+ await run.handlers.onDiscovered(seen())+ expect(run.deps.forgetSession).toHaveBeenLastCalledWith('old-s', { force: true, agentId: 'old' })+ expect(run.deps.announceSession).toHaveBeenCalledTimes(1)+ })++ it('does nothing when the registry opens nothing', async () => {+ const run = setup()+ await run.handlers.onDiscovered(seen())+ expect(run.deps.bindObservedAgent).not.toHaveBeenCalled()+ })+ })++ describe('a row\'s own process', () => {+ it('updates the row from the live process, filling only what it does not know', async () => {+ const run = setup()+ const observed = seen({ args: 'claude --dangerously-skip-permissions', codexHome: '/codex', hermesHome: '/hermes', dsh: 'blender' } as Partial<DiscoveredTerminalAgent>)+ run.rows.set('a1', row({ dsh: 'blender' } as Partial<RegisteredSession>))+ await run.handlers.onObserved(observed, row())+ expect(run.deps.registry.updateRuntimes).toHaveBeenCalledWith('a1', observed.runtimes, 'tmux:%0')+ expect(run.deps.registry.updateProcessIdentity).toHaveBeenCalledWith('a1', observed.processIdentity, undefined, undefined)+ expect(run.deps.registry.setBypassPermission).toHaveBeenCalledWith('a1', bypassPermissionActive('claude', observed.args))+ const mode = permissionModeFromArgv('claude', observed.args)+ expect(vi.mocked(run.deps.registry.setPermissionMode).mock.calls).toEqual(mode ? [['a1', mode]] : [])+ expect(run.deps.registry.setCodexHome).toHaveBeenCalledWith('a1', '/codex')+ expect(run.deps.registry.setHermesHome).toHaveBeenCalledWith('a1', '/hermes')+ expect(run.deps.registry.setDsh).toHaveBeenCalledWith('a1', 'blender')+ expect(run.deps.attachDsh).toHaveBeenCalled()+ expect(run.deps.bindObservedAgent).toHaveBeenCalledWith(observed)+ // A row that knows them already keeps its own.+ const known = setup()+ await known.handlers.onObserved(observed, row({ permissionMode: 'plan', codexHome: '/mine', hermesHome: '/mine', dsh: 'mine' } as Partial<RegisteredSession>))+ for (const setter of ['setPermissionMode', 'setCodexHome', 'setHermesHome', 'setDsh'] as const) {+ expect(known.deps.registry[setter], setter).not.toHaveBeenCalled()+ }+ })++ it('learns the permission mode from the command line when the row has none', async () => {+ const run = setup()+ await run.handlers.onObserved(seen({ engine: 'codex', args: 'codex --dangerously-bypass-approvals-and-sandbox' } as Partial<DiscoveredTerminalAgent>), row({ engine: 'codex' } as Partial<RegisteredSession>))+ const mode = permissionModeFromArgv('codex', 'codex --dangerously-bypass-approvals-and-sandbox')+ expect(vi.mocked(run.deps.registry.setPermissionMode).mock.calls).toEqual(mode ? [['a1', mode]] : [])+ expect(mode, 'this fixture must name a mode').not.toBeNull()+ })++ it('adopts the engine someone typed into a terminal, and announces it', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const run = setup()+ const adopted = row({ engine: 'claude', sessionId: '' })+ run.rows.set('a1', adopted)+ await run.handlers.onObserved(seen(), row({ engine: 'terminal' } as Partial<RegisteredSession>))+ expect(run.deps.registry.adoptEngine).toHaveBeenCalledWith('a1', 'claude', expect.anything())+ expect(run.deps.syncRecapPool).toHaveBeenCalled()+ expect(run.deps.announceSession).toHaveBeenCalledWith(adopted)+ expect(String(log.mock.calls[0][0])).toContain('terminal → claude')+ })++ it('wakes a dormant row and attaches it in the background, or puts it back to sleep if its pane is gone', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const run = setup()+ const awake = row()+ run.rows.set('a1', awake)+ await run.handlers.onObserved(seen(), row({ active: false }))+ await settle()+ expect(run.deps.attachSession).toHaveBeenCalledWith(awake)+ expect(run.deps.announceSession).toHaveBeenCalledWith(awake)+ vi.mocked(run.deps.attachSession).mockResolvedValueOnce(false)+ await run.handlers.onObserved(seen(), row({ active: false }))+ await settle()+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', false)+ vi.mocked(run.deps.attachSession).mockRejectedValueOnce(new Error('store locked')).mockRejectedValueOnce('worse')+ await run.handlers.onObserved(seen(), row({ active: false }))+ await run.handlers.onObserved(seen(), row({ active: false }))+ await settle()+ expect(error.mock.calls.map((call) => call[1])).toEqual(['store locked', 'worse'])+ // Gone from the registry by then: nothing to wake.+ run.rows.clear()+ await run.handlers.onObserved(seen(), row({ active: false }))+ expect(run.deps.attachSession).toHaveBeenCalledTimes(4)+ })++ it('marks a launch ready once its process runs, and wakes it', async () => {+ const run = setup()+ run.rows.set('a1', row())+ await run.handlers.onObserved(seen(), row({ launch: { state: 'starting' } } as Partial<RegisteredSession>))+ expect(run.deps.registry.setLaunch).toHaveBeenCalledWith('a1', { state: 'ready' })+ expect(run.deps.attachSession).toHaveBeenCalled()+ await run.handlers.onObserved(seen(), row({ launch: { state: 'ready' } } as Partial<RegisteredSession>))+ expect(run.deps.registry.setLaunch).toHaveBeenCalledTimes(1)+ })++ it('announces an awake agent whose grid moved, and nothing when it did not or could not be read', async () => {+ const run = setup()+ run.rows.set('a1', row())+ await run.handlers.onObserved(seen({ grid: grid('g1') } as Partial<DiscoveredTerminalAgent>), row({ grid: grid('g1') } as Partial<RegisteredSession>))+ await run.handlers.onObserved(seen(), row())+ expect(run.deps.announceSession).not.toHaveBeenCalled()+ await run.handlers.onObserved(seen({ grid: grid('g2') } as Partial<DiscoveredTerminalAgent>), row())+ expect(run.deps.announceSession).toHaveBeenCalledTimes(1)+ run.rows.clear()+ await run.handlers.onObserved(seen({ grid: grid('g3') } as Partial<DiscoveredTerminalAgent>), row())+ expect(run.deps.announceSession).toHaveBeenCalledTimes(1)+ })+ })++ describe('a row whose engine exited', () => {+ it('keeps its conversation, letting go of input, questions and the heartbeat', async () => {+ const run = setup()+ const exited = row({ resumeOnly: true } as Partial<RegisteredSession>)+ await run.handlers.onDormant(exited, 'engine exited')+ expect(run.deps.invalidateTerminalControl).toHaveBeenCalledWith('a1')+ expect(run.deps.teams.forget).toHaveBeenCalledWith('a1')+ expect(run.deps.input.forget).toHaveBeenCalledWith('a1')+ expect(run.deps.deviceInput.forget).toHaveBeenCalledWith('a1')+ expect(run.deps.questionWatcher.stop).toHaveBeenCalledWith('s1')+ expect(run.deps.stopHeartbeat).toHaveBeenCalledWith('s1')+ expect(run.deps.retainExitedSession).toHaveBeenCalledWith(exited, true)+ expect(run.deps.stoppedAgents.finishResume).toHaveBeenCalledWith('a1')+ })++ it('keeps the conversation of an agent that was not a resume, with nothing to finish', async () => {+ const run = setup()+ await run.handlers.onDormant(row(), 'engine exited')+ expect(run.deps.retainExitedSession).toHaveBeenCalledWith(row(), true)+ expect(run.deps.stoppedAgents.finishResume).not.toHaveBeenCalled()+ })++ it('leaves a dormant row alone, and puts a launch that is still starting to sleep instead', async () => {+ const run = setup()+ await run.handlers.onDormant(row({ active: false }), 'x')+ expect(run.deps.invalidateTerminalControl).not.toHaveBeenCalled()+ const starting = row({ sessionId: '', launch: { state: 'starting' } } as Partial<RegisteredSession>)+ await run.handlers.onDormant(starting, 'no process yet')+ expect(run.deps.questionWatcher.stop).not.toHaveBeenCalled()+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', false)+ expect(run.deps.announceSession).toHaveBeenCalledWith(starting)+ expect(run.deps.retainExitedSession).not.toHaveBeenCalled()+ })++ it('holds a failed resume while its pane may still be about to launch the engine', async () => {+ const run = setup()+ const failed = row({ resumeOnly: true, tmuxPane: '%0', launch: { state: 'failed' } } as Partial<RegisteredSession>)+ await run.handlers.onDormant(failed, 'x') // no pane state at all+ vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: false, engineExit: null } as never)+ await run.handlers.onDormant(failed, 'x') // a live shell, no engine exit+ expect(run.deps.retainExitedSession).not.toHaveBeenCalled()+ vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: true, engineExit: null } as never)+ await run.handlers.onDormant(failed, 'pane died')+ vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: false, engineExit: 1 } as never)+ await run.handlers.onDormant(failed, 'engine exited 1')+ expect(run.deps.retainExitedSession).toHaveBeenCalledTimes(2)+ })+ })++ it('removes a row whose pane is gone, unless restore never ran this boot', () => {+ const run = setup()+ run.handlers.onRemoved(row(), 'pane gone')+ expect(run.deps.forgetSession).toHaveBeenCalledWith('a1', { force: true })+ run.degrade()+ run.handlers.onRemoved(row(), 'pane gone')+ expect(run.deps.forgetSession).toHaveBeenCalledTimes(1)+ expect(run.deps.registry.setActive).toHaveBeenCalledWith('a1', false)+ expect(run.deps.announceSession).toHaveBeenCalled()+ })++ it('records whether a row\'s terminal is available, announcing it when it becomes so', () => {+ const run = setup()+ run.handlers.onTerminalAvailability(row(), true)+ expect(run.deps.registry.setTerminalAvailable).toHaveBeenCalledWith('a1', true)+ expect(run.deps.announceSession).toHaveBeenCalledTimes(1)+ vi.mocked(run.deps.registry.terminalAvailable).mockReturnValue(true)+ run.handlers.onTerminalAvailability(row(), true)+ run.handlers.onTerminalAvailability(row(), false)+ expect(run.deps.announceSession).toHaveBeenCalledTimes(1)+ })+})diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.tsnew file mode 100644index 000000000..a8283ba4a--- /dev/null+++ b/cli/src/core/agents/discovery.ts@@ -0,0 +1,224 @@+/**+ * Discovery: what the reconciler's scans of the terminal backends and their processes mean for the+ * registry. A process no row owns opens an agent; a row's own process updates it (runtimes, identity,+ * permissions, profile homes, DSH) and wakes a dormant one; a row whose engine exited keeps its+ * conversation or goes dormant; a row whose pane is gone is removed, unless restore never ran.+ *+ * Moved verbatim out of the reconciler's options in `runForeground` (the core boundary, step 10:+ * docs/design/2026-10-03-harnessd.md). The reconciler itself, with what it scans, stays there.+ */+import { isTerminalEngine } from '../../engines/types.js'+import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'+import type { QuestionWatcher } from '../../lib/askQuestion.js'+import { sameGridAssignment } from '../../lib/gridAssignment.js'+import { sid } from '../../lib/log.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'+import type { SessionInputController } from '../../lib/sessionInput.js'+import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'+import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'+import { bypassPermissionActive, permissionModeFromArgv, tmuxPaneState } from '../../lib/tmux.js'+import type { SwarmPromptScopes } from '../../teams/promptScope.js'++export interface DiscoveryDeps {+ registry: Pick<typeof registry,+ 'byRuntimeEngine' | 'openProcessAgent' | 'adoptEngine' | 'updateRuntimes' | 'updateProcessIdentity' | 'setBypassPermission'+ | 'setPermissionMode' | 'setCodexHome' | 'setHermesHome' | 'setDsh' | 'byAgent' | 'setLaunch' | 'setActive'+ | 'terminalAvailable' | 'setTerminalAvailable'>+ attachDsh: (session: RegisteredSession) => void+ forgetSession: (id: string, opts?: { force?: boolean; agentId?: string }) => void+ announceSession: (session: RegisteredSession) => void+ bindObservedAgent: (observed: DiscoveredTerminalAgent) => Promise<void>+ syncRecapPool: () => void+ attachSession: (session: RegisteredSession) => Promise<boolean>+ invalidateTerminalControl: (agentId: string) => void+ teams: Pick<SwarmPromptScopes, 'forget'>+ input: Pick<SessionInputController, 'forget'>+ deviceInput: Pick<AutonomousDeviceInput, 'forget'>+ questionWatcher: Pick<QuestionWatcher, 'stop'>+ stopHeartbeat: (sessionId: string) => void+ retainExitedSession: (agent: RegisteredSession, announce: boolean) => void+ stoppedAgents: Pick<StoppedAgentStore, 'finishResume'>+ /** Whether restore did not run this boot: a missing pane then is one never rebuilt, not one closed. */+ restoreDegraded: () => boolean+}++export function createDiscoveryHandlers({+ registry, attachDsh, forgetSession, announceSession, bindObservedAgent, syncRecapPool, attachSession,+ invalidateTerminalControl, teams, input, deviceInput, questionWatcher, stopHeartbeat, retainExitedSession,+ stoppedAgents, restoreDegraded,+}: DiscoveryDeps) {+ const onDiscovered = async (observed: DiscoveredTerminalAgent): Promise<void> => {+ const launching = observed.runtimes+ .map((runtime) => registry.byRuntimeEngine(runtime, observed.engine))+ .find((entry) => entry?.launch?.state !== 'ready')+ const opened = registry.openProcessAgent({+ engine: observed.engine,+ runtimes: observed.runtimes,+ primaryRuntimeKey: observed.primaryRuntimeKey,+ cwd: observed.cwd,+ processIdentity: observed.processIdentity,+ gateway: observed.gateway,+ grid: observed.grid,+ codexHome: observed.codexHome,+ dsh: observed.dsh,+ })+ if (!opened) return+ if (opened.entry.dsh) attachDsh(opened.entry)+ if (opened.evicted) {+ console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted.agentId)}`)+ // ⚠️ THE REGISTRY ALREADY DROPPED IT; NOBODY HAD TOLD THE CLIENTS. That+ // is the whole bug behind "two sessions, one of them frozen": resuming+ // an engine in a pane another agent owned takes the pane away, and an+ // agent with no pane can never be opened again — but the app kept the+ // row until someone hit Reload machines by hand, and opening it landed+ // on TERMINAL FROZEN. This is the same call the hook path already makes+ // for the same situation (see onRegistered below).+ forgetSession(opened.evicted.sessionId || opened.evicted.agentId, {+ force: true,+ agentId: opened.evicted.agentId,+ })+ }++ if (opened.isNew || launching) {+ console.log(`[discovery] ${sid(opened.entry.agentId)} opened · engine=${observed.engine} · terminal=${observed.primaryRuntimeKey}`)+ announceSession(opened.entry)+ }+ await bindObservedAgent(observed)+ }+ const onObserved = async (observed: DiscoveredTerminalAgent, current: RegisteredSession): Promise<void> => {+ const wasDormant = !current.active+ // Read BEFORE the update, because the update is what overwrites it. `undefined` means the probe+ // could not look, which never counts as a move — see `probeGridAssignment`'s three answers.+ const gridMoved = observed.grid !== undefined+ && !sameGridAssignment(current.grid ?? null, observed.grid)+ const wasLaunching = current.launch?.state !== undefined && current.launch.state !== 'ready'+ // Somebody typed an engine into a terminal. The row becomes that engine's agent — same id,+ // same pane — and from here on is handled exactly like one the app launched: bound by its+ // hooks, watched for turns, listed on the dial. `adopted` makes the announce below+ // unconditional, since the engine changing is the one fact the app must not miss.+ const adopted = isTerminalEngine(current.engine) && !isTerminalEngine(observed.engine)+ ? registry.adoptEngine(current.agentId, observed.engine, observed.processIdentity)+ : null+ if (adopted) console.log(`[discovery] ${sid(current.agentId)} terminal → ${observed.engine} · ${observed.primaryRuntimeKey}`)+ registry.updateRuntimes(current.agentId, observed.runtimes, observed.primaryRuntimeKey)+ registry.updateProcessIdentity(current.agentId, observed.processIdentity, observed.gateway, observed.grid)+ // The live argv is the truth about the bypass flag, and this is the one place every running+ // agent passes through — so a row written before the flag was persisted at all (or by a build+ // that did not yet) learns it here, before any pane recreation ever needs it.+ // `observed.engine`, not `current.engine`: for a terminal that just adopted one, the row's+ // engine was `terminal` a line ago, which has no bypass flag and would read every launch as "no".+ registry.setBypassPermission(current.agentId, bypassPermissionActive(observed.engine, observed.args))+ // And the exact MODE, fill-only: a row that recorded one at create is authoritative, and one+ // that never did (adopted from a terminal, written by an older build, created by a path that+ // passes no mode) learns it from the same argv — so its restart brings back+ // `--dangerously-skip-permissions`, not the auto mode `bypassPermission` alone would pick.+ if (!current.permissionMode) {+ const mode = permissionModeFromArgv(observed.engine, observed.args)+ if (mode) registry.setPermissionMode(current.agentId, mode)+ }+ // Same idea for a Codex profile: a row that never learned which CODEX_HOME its process runs+ // under learns it from the process, before the hook path validates a transcript against it.+ // Fill-only — a profile the row already knows is never re-derived.+ if (observed.codexHome && !current.codexHome) registry.setCodexHome(current.agentId, observed.codexHome)+ // …and a Hermes home the same way, when the process names one. A row that learns it here never+ // has to look its session up store by store (openharness#191).+ if (observed.hermesHome && !current.hermesHome) registry.setHermesHome(current.agentId, observed.hermesHome)+ // And the DSH: a row minted by discovery (or written before the field existed) learns it from+ // the process's own `HARNESS_DSH`, and gets its viewer and verdict watch from here on.+ if (observed.dsh && !current.dsh) registry.setDsh(current.agentId, observed.dsh)+ const withDsh = registry.byAgent(current.agentId)+ if (withDsh?.dsh) attachDsh(withDsh)+ // This live process, in this row's own pane, is what "started" means — for a resumed row as+ // much as any other. A resume used to be held back here until its `SessionStart` hook landed,+ // on the grounds that only the hook proves WHICH conversation reopened. Two things were wrong+ // with that. The hook does not always come: measured on machine-remote-1, both resume-only+ // codex rows carried `lastHookAt: 0` while every fresh launch beside them had hooked, and one+ // of them sat at "Starting" for 19 hours over a pane its owner could type in — re-attached and+ // re-announced every 5s for the whole time, because `wasLaunching` stays true for a row that+ // nothing will ever mark ready (openharness#189). And nothing was actually protected by the+ // wait: the wrong-conversation guard in `registry.register` keys on `lastHookAt`, not on this+ // launch state, so it stays armed until the first hook whatever is written here.+ if (wasLaunching) registry.setLaunch(current.agentId, { state: 'ready' })+ await bindObservedAgent(observed)+ if (wasDormant || wasLaunching || adopted) {+ const active = registry.byAgent(current.agentId)+ if (!active) return+ if (!active.sessionId) {+ syncRecapPool()+ announceSession(active)+ return+ }+ // Not awaited: the attach reads this agent's whole history, and this callback runs inside the+ // reconcile pass whose completion is what publishes `discoveryReady`. One agent's slow store+ // must not hold the pass — or, at boot, the app. The tracker runs a few of these at a time.+ void attachSession(active).then((attached) => {+ if (!attached) {+ registry.setActive(active.agentId, false)+ return+ }+ syncRecapPool()+ announceSession(active)+ }).catch((err) => {+ console.error(`[discovery] ${sid(active.agentId)} attach failed:`, err instanceof Error ? err.message : err)+ })+ return+ }+ // An agent that was already awake changed grid under us. Nobody was told: this branch wrote the+ // new assignment into the registry and stopped, so the app went on drawing the old one until+ // its own 60s reconciliation tick happened to notice — a minute of an agent's header naming a+ // grid it had left. The retarget path has always announced (it is the same fact, arriving by a+ // different door); this is the door an engine's own `exec` comes through, which is what an+ // install-then-launch does the moment the install finishes.+ if (!gridMoved) return+ const refreshed = registry.byAgent(current.agentId)+ if (refreshed) announceSession(refreshed)+ }+ const onDormant = async (agent: RegisteredSession, reason: string): Promise<void> => {+ if (!agent.active) return+ invalidateTerminalControl(agent.agentId)+ teams.forget(agent.agentId)+ input.forget(agent.agentId)+ deviceInput.forget(agent.agentId)+ if (agent.sessionId) {+ questionWatcher.stop(agent.sessionId)+ stopHeartbeat(agent.sessionId)+ }+ // Preserve the conversation's public identity and give the surviving shell its own row.+ // A starting install is not an exited engine; strict uncertain starts keep their reservation.+ if (agent.resumeOnly && agent.launch?.state === 'failed') {+ const pane = await tmuxPaneState(agent.tmuxPane)+ // An unconfirmed install/startup can still be about to launch the engine. Do not+ // turn its live shell into permission to start another one.+ if (!pane || (!pane.dead && pane.engineExit == null)) return+ }+ if (agent.launch?.state !== 'starting') {+ retainExitedSession(agent, true)+ if (agent.resumeOnly) stoppedAgents.finishResume(agent.agentId)+ console.log(`[discovery] ${sid(agent.agentId)} retained · ${reason}`)+ return+ }+ registry.setActive(agent.agentId, false)+ console.log(`[discovery] ${sid(agent.agentId)} dormant · ${reason}`)+ announceSession(agent)+ }+ const onRemoved = (agent: RegisteredSession, reason: string): void => {+ // A pane absent because RESTORE never ran is not a pane the person closed. Retiring it here+ // would archive a row whose tmux pane was simply never rebuilt, and the person would have to+ // Open each one by hand; keeping it dormant leaves the next daemon — the fixed one — something+ // to restore.+ if (restoreDegraded()) {+ console.log(`[discovery] ${sid(agent.agentId)} kept · restore did not run this boot · ${reason}`)+ registry.setActive(agent.agentId, false)+ announceSession(agent)+ return+ }+ console.log(`[discovery] ${sid(agent.agentId)} removed · ${reason}`)+ forgetSession(agent.agentId, { force: true })+ }+ const onTerminalAvailability = (agent: RegisteredSession, available: boolean): void => {+ const changed = registry.terminalAvailable(agent.agentId) !== available+ registry.setTerminalAvailable(agent.agentId, available)+ if (available && changed) announceSession(agent)+ }+ return { onDiscovered, onObserved, onDormant, onRemoved, onTerminalAvailability }+}diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.tsnew file mode 100644index 000000000..cc7cd7c97--- /dev/null+++ b/cli/src/core/agents/forget.spec.ts@@ -0,0 +1,112 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createForgetSession, type ForgetDeps } from './forget.js'++vi.mock('../../engines/cursor/pendingTasks.js', () => ({ removeCursorPendingTasks: vi.fn(async () => {}) }))++function setup() {+ const agents = new Map<string, RegisteredSession>([+ ['a1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],+ ['s1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],+ ['fresh', { agentId: 'fresh', sessionId: '', engine: 'claude' } as RegisteredSession],+ ])+ const deps: ForgetDeps = {+ registry: { resolve: vi.fn((id: string) => agents.get(id)), unbindSession: vi.fn(() => true), removeAgent: vi.fn(() => true), remove: vi.fn(() => true) },+ stoppedAgents: { save: vi.fn() },+ syncRecapPool: vi.fn(),+ normalizers: { forget: vi.fn() },+ turnStartedAt: new Map([['s1', 1], ['other', 2]]),+ neverFoldedHistory: new Set(['s1', 'other']),+ replayedFirstTurn: new Set(['s1', 'other']),+ clearAgyIdleWatch: vi.fn(),+ cursorDiscovery: { remove: vi.fn() },+ cursorSubagents: { forget: vi.fn() },+ runtimeProfiles: { forget: vi.fn() },+ watcher: { removeSession: vi.fn(async () => {}) },+ stopHeartbeat: vi.fn(),+ teams: { forget: vi.fn() },+ input: { forget: vi.fn() },+ deviceInput: { forget: vi.fn() },+ detachDsh: vi.fn(),+ mirror: { forget: vi.fn() },+ clients: { send: vi.fn(), sendCommander: vi.fn() },+ dataDir: '/data',+ }+ return { deps, forgetSession: createForgetSession(deps) }+}++/** Every per-session store the session must be gone from. */+function expectLetGo(deps: ForgetDeps, sessionId: string, agentId: string) {+ expect(deps.syncRecapPool).toHaveBeenCalled()+ expect(deps.normalizers.forget).toHaveBeenCalledWith(sessionId)+ expect(deps.turnStartedAt.has(sessionId)).toBe(false)+ expect(deps.neverFoldedHistory.has(sessionId)).toBe(false)+ expect(deps.replayedFirstTurn.has(sessionId)).toBe(false)+ expect(deps.turnStartedAt.has('other')).toBe(true)+ expect(deps.clearAgyIdleWatch).toHaveBeenCalledWith(sessionId)+ expect(deps.cursorDiscovery.remove).toHaveBeenCalledWith(sessionId)+ expect(deps.cursorSubagents.forget).toHaveBeenCalledWith(sessionId)+ expect(removeCursorPendingTasks).toHaveBeenCalledWith('/data', sessionId)+ expect(deps.runtimeProfiles.forget).toHaveBeenCalledWith(sessionId)+ expect(deps.watcher.removeSession).toHaveBeenCalledWith(sessionId)+ expect(deps.stopHeartbeat).toHaveBeenCalledWith(sessionId)+ expect(deps.teams.forget).toHaveBeenCalledWith(agentId)+ expect(deps.input.forget).toHaveBeenCalledWith(agentId)+ expect(deps.deviceInput.forget).toHaveBeenCalledWith(agentId)+ expect(deps.mirror.forget).toHaveBeenCalledWith(sessionId)+}++describe('forgetting a session', () => {+ afterEach(() => { vi.restoreAllMocks(); vi.mocked(removeCursorPendingTasks).mockClear() })++ it('releases a session and keeps its agent: everything per-session goes, the agent and its tiles stay', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const { deps, forgetSession } = setup()+ forgetSession('a1', { keepAgent: true })+ expect(deps.registry.unbindSession).toHaveBeenCalledWith('s1')+ expect(deps.registry.removeAgent).not.toHaveBeenCalled()+ expect(deps.stoppedAgents.save).not.toHaveBeenCalled()+ expect(deps.detachDsh).not.toHaveBeenCalled()+ expectLetGo(deps, 's1', 'a1')+ expect(deps.clients.send).not.toHaveBeenCalled()+ expect(deps.clients.sendCommander).not.toHaveBeenCalled()+ expect(String(log.mock.calls[0][0])).toContain('released session')+ })++ it('removes an agent everywhere, archived as stopped, and tells the app and the dial', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const { deps, forgetSession } = setup()+ forgetSession('s1')+ expect(deps.stoppedAgents.save).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1' }))+ expect(deps.registry.removeAgent).toHaveBeenCalledWith('a1')+ expect(deps.detachDsh).toHaveBeenCalledWith('a1')+ expectLetGo(deps, 's1', 'a1')+ expect(deps.clients.send).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 'a1', retained: true } })+ expect(deps.clients.sendCommander).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 'a1' } })+ expect(String(log.mock.calls[0][0])).toContain('forgotten')+ })++ it('removes a session the registry no longer knows, announced by the agent id the caller names', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const named = setup()+ named.forgetSession('s9', { agentId: 'a9' })+ expect(named.deps.registry.remove).toHaveBeenCalledWith('s9')+ expect(named.deps.stoppedAgents.save).not.toHaveBeenCalled()+ expect(named.deps.detachDsh).toHaveBeenCalledWith('a9')+ expect(named.deps.clients.send).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 'a9', retained: false } })+ expect(named.deps.input.forget).toHaveBeenCalledWith('s9')+ // With no agent id at all, the session id is all there is to announce.+ const bare = setup()+ bare.forgetSession('s9')+ expect(bare.deps.clients.sendCommander).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 's9' } })+ })++ it('forgets an agent that has no session yet under the id it was asked by', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { deps, forgetSession } = setup()+ forgetSession('fresh')+ expect(deps.registry.removeAgent).toHaveBeenCalledWith('fresh')+ expect(deps.normalizers.forget).toHaveBeenCalledWith('fresh')+ })+})diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.tsnew file mode 100644index 000000000..f4ddd1caa--- /dev/null+++ b/cli/src/core/agents/forget.ts@@ -0,0 +1,101 @@+/**+ * Forgetting a session: release a mutable session binding (the agent stays, its session goes), or+ * remove a process-owned agent everywhere — archived as stopped, and every per-session store the core+ * keeps let go of, so a daemon that runs for days does not grow with every session it ever saw.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).+ */+import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'+import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'+import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'+import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'+import type { CommanderMirror } from '../../lib/commander.js'+import { sid } from '../../lib/log.js'+import type { registry } from '../../lib/registry.js'+import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'+import type { SessionInputController } from '../../lib/sessionInput.js'+import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'+import type { SwarmPromptScopes } from '../../teams/promptScope.js'+import type { Watcher } from '../../watcher/watcher.js'+import type { SessionNormalizers } from '../transcripts/normalizers.js'++type Frame = { type: string; payload: Record<string, unknown> }++export interface ForgetDeps {+ registry: Pick<typeof registry, 'resolve' | 'unbindSession' | 'removeAgent' | 'remove'>+ stoppedAgents: Pick<StoppedAgentStore, 'save'>+ syncRecapPool: () => void+ normalizers: Pick<SessionNormalizers, 'forget'>+ turnStartedAt: Map<string, number>+ /** Attach's two per-session marks (core/transcripts/attach.ts). */+ neverFoldedHistory: Set<string>+ replayedFirstTurn: Set<string>+ clearAgyIdleWatch: (sessionId: string) => void+ cursorDiscovery: Pick<CursorTranscriptDiscovery, 'remove'>+ cursorSubagents: Pick<CursorSubagentManager, 'forget'>+ runtimeProfiles: Pick<RuntimeProfileManager, 'forget'>+ watcher: Pick<Watcher, 'removeSession'>+ stopHeartbeat: (sessionId: string) => void+ teams: Pick<SwarmPromptScopes, 'forget'>+ input: Pick<SessionInputController, 'forget'>+ deviceInput: Pick<AutonomousDeviceInput, 'forget'>+ detachDsh: (agentId: string) => void+ mirror: Pick<CommanderMirror, 'forget'>+ /** The app (`send`) and the dial (`sendCommander`). */+ clients: { send(frame: Frame): void; sendCommander(frame: Frame): void }+ dataDir: string+}++export function createForgetSession({+ registry, stoppedAgents, syncRecapPool, normalizers, turnStartedAt, neverFoldedHistory, replayedFirstTurn,+ clearAgyIdleWatch, cursorDiscovery, cursorSubagents, runtimeProfiles, watcher, stopHeartbeat, teams, input,+ deviceInput, detachDsh, mirror, clients, dataDir,+}: ForgetDeps) {+ /** Release a mutable session binding, or remove the process-owned agent everywhere. */+ const forgetSession = (+ id: string,+ opts: { force?: boolean; keepAgent?: boolean; agentId?: string } = {},+ ): void => {+ const doomed = registry.resolve(id)+ const sessionId = doomed?.sessionId || id+ // Clients key on the AGENT id. Normally it is read off the entry, but an+ // agent already removed from the registry cannot be looked up — and+ // announcing its sessionId instead is silently useless: the app takes+ // payload.agentId verbatim, matches nothing, and leaves the dead row on+ // screen. Callers who know the id pass it.+ const announceId = doomed?.agentId ?? opts.agentId ?? sessionId++ console.log(opts.keepAgent+ ? `[agent] ${sid(announceId)} released session ${sid(sessionId)}`+ : `[agent] ${sid(announceId)} forgotten`)++ if (!opts.keepAgent && doomed) stoppedAgents.save(doomed)+ if (opts.keepAgent) registry.unbindSession(sessionId)+ else if (doomed) registry.removeAgent(doomed.agentId)+ else registry.remove(sessionId)+ syncRecapPool()+ normalizers.forget(sessionId)+ turnStartedAt.delete(sessionId)+ neverFoldedHistory.delete(sessionId)+ // Both sets are per-session and must die with it: left behind they grow without bound in a daemon+ // that runs for days, and a session forgotten then re-registered under the same id would inherit a+ // stale "already replayed" and lose a first turn it was entitled to.+ replayedFirstTurn.delete(sessionId)+ clearAgyIdleWatch(sessionId)+ cursorDiscovery.remove(sessionId)+ cursorSubagents.forget(sessionId)+ void removeCursorPendingTasks(dataDir, sessionId)+ runtimeProfiles.forget(sessionId)+ void watcher.removeSession(sessionId)+ stopHeartbeat(sessionId)+ teams.forget(doomed?.agentId ?? sessionId)+ input.forget(doomed?.agentId ?? sessionId)+ deviceInput.forget(doomed?.agentId ?? sessionId)+ if (!opts.keepAgent) detachDsh(announceId)+ mirror.forget(sessionId) // aborts any in-flight recap + clears busy; KEEPS the persisted summary+ if (opts.keepAgent) return+ clients.send({ type: 'agent_deleted', payload: { agentId: announceId, retained: !!doomed } }) // web tab+ clients.sendCommander({ type: 'agent_deleted', payload: { agentId: announceId } })+ }+ return forgetSession+}diff --git a/cli/src/core/agents/launch.spec.ts b/cli/src/core/agents/launch.spec.tsnew file mode 100644index 000000000..f373e0b19--- /dev/null+++ b/cli/src/core/agents/launch.spec.ts@@ -0,0 +1,99 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { prepareCodexResume } from '../../engines/codex/portableHistory.js'+import { ApiConnectionError, type ApiConnections } from '../../lib/apiConnections.js'+import { refreshApiLaunch } from '../../lib/apiModels.js'+import { dropPermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'+import { buildLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps } from '../../lib/launchOverrides.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createLaunchHelpers, type LaunchHelperDeps } from './launch.js'++vi.mock('../../engines/codex/portableHistory.js', () => ({ prepareCodexResume: vi.fn(() => ({ repairedItems: 0 })) }))+vi.mock('../../lib/apiModels.js', async (real) => ({ ...await real<object>(), refreshApiLaunch: vi.fn((_apis: unknown, launch: object) => ({ ...launch, refreshed: true })) }))+vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), dropPermissionFlagIfUnsupported: vi.fn() }))+vi.mock('../../lib/launchOverrides.js', async (real) => ({ ...await real<object>(), buildLaunchOverrides: vi.fn(async () => ({ ok: true })) }))++const session = (over: Partial<RegisteredSession> = {}): RegisteredSession =>+ ({ agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work', dsh: 'blender', dshRuntime: null, agent: 'reviewer', ...over }) as RegisteredSession++function setup() {+ const deps: LaunchHelperDeps = {+ prepareApiTools: vi.fn(),+ savedApis: {} as ApiConnections,+ launchOverridesDeps: { marker: 'deps' } as unknown as LaunchOverridesDeps,+ setGridLaunch: vi.fn(() => true),+ setTail: vi.fn(),+ }+ return { deps, helpers: createLaunchHelpers(deps) }+}++describe('relaunch helpers', () => {+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })++ it('rebuilds a launch from the row: its DSH, folder and named agent, whatever the source adds', async () => {+ const { deps, helpers } = setup()+ expect(await helpers.relaunchOverrides(session())).toEqual({ ok: true })+ expect(deps.prepareApiTools).toHaveBeenCalledWith('/work', 'claude')+ expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({+ dsh: 'blender', dshRuntime: null, cwd: '/work', agent: 'reviewer', gridLaunch: null,+ }), 'a1')+ const grid = { networkId: 'grid-1', networkName: 'Home grid' }+ await helpers.relaunchOverrides(session({ dsh: undefined, dshRuntime: undefined, agent: undefined } as Partial<RegisteredSession>), { gridLaunch: grid } as never)+ expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ dsh: null, agent: null, gridLaunch: grid }), 'a1')+ expect(refreshApiLaunch).not.toHaveBeenCalled()+ })++ it('relaunches on a saved API with its key as saved now, and refuses one that is gone', async () => {+ const { deps, helpers } = setup()+ const api = { networkId: 'api:openrouter', networkName: 'OpenRouter' }+ await helpers.relaunchOverrides(session(), { gridLaunch: api } as never)+ expect(refreshApiLaunch).toHaveBeenCalledWith(deps.savedApis, api)+ expect(vi.mocked(buildLaunchOverrides).mock.lastCall?.[2]).toMatchObject({ gridLaunch: { ...api, refreshed: true } })+ vi.mocked(refreshApiLaunch).mockImplementationOnce(() => { throw new ApiConnectionError('OpenRouter was removed.') })+ expect(await helpers.relaunchOverrides(session(), { gridLaunch: api } as never)).toEqual({ ok: false, error: 'API_UNAVAILABLE', detail: 'OpenRouter was removed.' })+ vi.mocked(refreshApiLaunch).mockImplementationOnce(() => { throw new Error('unreadable store') })+ expect(await helpers.relaunchOverrides(session(), { gridLaunch: api } as never)).toEqual({+ ok: false, error: 'API_UNAVAILABLE', detail: 'OpenRouter could not be read from saved APIs.',+ })+ })++ it('records the web-search decision a relaunch made, when it made one', () => {+ const { deps, helpers } = setup()+ helpers.refreshGridWebSearch('a1', {} as LaunchOverrides)+ expect(deps.setGridLaunch).not.toHaveBeenCalled()+ const record = { networkId: 'grid-1' }+ helpers.refreshGridWebSearch('a1', { gridLaunchRecord: record } as unknown as LaunchOverrides)+ expect(deps.setGridLaunch).toHaveBeenCalledWith('a1', record)+ })++ it('drops a permission flag the engine no longer takes, says so, and keeps the pane', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { helpers } = setup()+ vi.mocked(dropPermissionFlagIfUnsupported).mockResolvedValueOnce({ choice: { bypassPermission: false }, droppedFlag: '--permission-mode' } as never)+ expect(await helpers.downgradedPermission(session({ permissionMode: 'plan' } as Partial<RegisteredSession>), true, 'restart')).toEqual({ bypassPermission: false })+ expect(dropPermissionFlagIfUnsupported).toHaveBeenCalledWith('claude', { permissionMode: 'plan', bypassPermission: true })+ expect(String(warn.mock.calls[0][0])).toContain('does not take --permission-mode · starting in Ask · update claude to get plan back')+ vi.mocked(dropPermissionFlagIfUnsupported).mockResolvedValueOnce({ choice: { bypassPermission: true }, droppedFlag: '--dangerously-skip-permissions' } as never)+ await helpers.downgradedPermission(session(), true, 'retarget')+ expect(String(warn.mock.calls[1][0])).toContain('to get Auto back')+ vi.mocked(dropPermissionFlagIfUnsupported).mockResolvedValueOnce({ choice: { permissionMode: 'plan' }, droppedFlag: null } as never)+ expect(await helpers.downgradedPermission(session(), false, 'restore')).toEqual({ permissionMode: 'plan' })+ expect(warn).toHaveBeenCalledTimes(2)+ })++ it('repairs a Codex rollout for resume and moves the tail to its new length', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const { deps, helpers } = setup()+ helpers.prepareSessionResume(session())+ expect(deps.setTail).not.toHaveBeenCalled()+ vi.mocked(prepareCodexResume).mockReturnValueOnce({ repairedItems: 3, repairedBytes: 1_234, backupPath: '/b/rollout.bak' } as never)+ helpers.prepareSessionResume(session())+ expect(deps.setTail).toHaveBeenCalledWith('s1', 1_234)+ vi.mocked(prepareCodexResume).mockReturnValueOnce({ repairedItems: 1, backupPath: '/b/rollout.bak' } as never)+ helpers.prepareSessionResume(session())+ expect(deps.setTail).toHaveBeenCalledTimes(1)+ expect(log.mock.calls.map(([line]) => String(line))).toEqual([+ '[resume] repaired 3 Codex reasoning items · backup: /b/rollout.bak',+ '[resume] repaired 1 Codex reasoning items · backup: /b/rollout.bak',+ ])+ })+})diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.tsnew file mode 100644index 000000000..7442b1894--- /dev/null+++ b/cli/src/core/agents/launch.ts@@ -0,0 +1,104 @@+/**+ * Relaunch helpers: what a restart, a retarget, a restore or a resume needs to bring an agent's pane+ * back. Its launch overrides, rebuilt from the row (an API's key as saved now); the web-search decision+ * refreshed; a permission flag the engine no longer takes dropped, rather than the pane; and a Codex+ * rollout repaired for resume, with the tail moved to its new length.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).+ */+import { prepareCodexResume } from '../../engines/codex/portableHistory.js'+import { ApiConnectionError, type ApiConnections } from '../../lib/apiConnections.js'+import { refreshApiLaunch } from '../../lib/apiModels.js'+import { dropPermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'+import { isApiLaunch } from '../../lib/gridLaunch.js'+import { buildLaunchOverrides, type LaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from '../../lib/launchOverrides.js'+import { sid } from '../../lib/log.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'++export interface LaunchHelperDeps {+ /** Writes the saved APIs' tool instructions into the agent's folder before it launches. */+ prepareApiTools: (cwd: string | null | undefined, engine: string) => void+ savedApis: ApiConnections+ launchOverridesDeps: LaunchOverridesDeps+ setGridLaunch: typeof registry.setGridLaunch+ /** Moves a session's tail to a byte (Watcher.setTail). */+ setTail: (sessionId: string, offset: number) => void+}++export function createLaunchHelpers({ prepareApiTools, savedApis, launchOverridesDeps, setGridLaunch, setTail }: LaunchHelperDeps) {+ // Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH,+ // workspace and named agent come from the row: a retarget must not silently drop the harness the+ // agent is, or bring a pane opened as `harness-compute` back as a general session.+ // An agent on a saved API's model relaunches with that API's endpoint and key as saved now, so a key+ // pasted since takes effect, and a removed API is refused rather than kept on its old key.+ const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> => {+ prepareApiTools(session.cwd, session.engine)+ let gridLaunch = source.gridLaunch ?? null+ if (gridLaunch && isApiLaunch(gridLaunch)) {+ try {+ gridLaunch = refreshApiLaunch(savedApis, gridLaunch)+ } catch (error) {+ return {+ ok: false,+ error: 'API_UNAVAILABLE',+ detail: error instanceof ApiConnectionError ? error.message : `${gridLaunch.networkName} could not be read from saved APIs.`,+ }+ }+ }+ return buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, ...source, gridLaunch }, session.agentId)+ }++ /**+ * A restart or a post-reboot restore rebuilds the ROW's own launch, and the machine may decide+ * differently about web search this time than it did when the row was written (an administrator+ * pinned `/etc/hermes` since, or unpinned it). The override is the row's already; what is+ * refreshed is the decision, so the frame describes the pane that actually came up. Retarget+ * does not go through here — its override is new, and it records the pair itself once the move+ * has succeeded.+ */+ const refreshGridWebSearch = (agentId: string, overrides: LaunchOverrides): void => {+ if (overrides.gridLaunchRecord) setGridLaunch(agentId, overrides.gridLaunchRecord)+ }++ /**+ * The permission this relaunch can actually ask for. Nobody is waiting on a restart, a retarget, a+ * restore or a resume, so an engine that no longer takes the row's flag costs it the mode, not the+ * harness — the alternative is a pane of help text, or no pane at all (openharness#285).+ *+ * The row is NOT rewritten. `permissionMode` is the person's recorded choice and `setPermissionMode`+ * is fill-only for that reason; an engine put back the way it was gets Auto again on the next+ * relaunch, with nobody having to ask for it twice. The row stops CLAIMING the mode on its own:+ * discovery re-derives `bypassPermission` from the live argv on every pass (`setBypassPermission`+ * above), so a launch without the flag reads as one within a reconcile.+ *+ * ⚠️ Its alias in runForeground is DECLARED BEFORE THE RESTORE PASS, and has to stay there:+ * `restoreAgents` calls `buildLaunch` for every pane it rebuilds, which asks this, during start-up.+ */+ const downgradedPermission = async (+ session: RegisteredSession,+ bypassPermission: boolean,+ what: string,+ ): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }> => {+ const { choice, droppedFlag } = await dropPermissionFlagIfUnsupported(session.engine, {+ permissionMode: session.permissionMode ?? null,+ bypassPermission,+ })+ if (droppedFlag) {+ console.warn(`[agent] ${what} ${sid(session.agentId)} · ${session.engine} does not take ${droppedFlag}`+ + ` · starting in Ask · update ${session.engine} to get ${session.permissionMode ?? 'Auto'} back`)+ }+ return choice+ }++ const prepareSessionResume = (session: RegisteredSession): void => {+ const repair = prepareCodexResume(session)+ if (repair.repairedItems) {+ // The rollout we tail was just shrunk in place. Move the tail to the repaired length now, before+ // the resumed engine appends, or the watcher would read the whole repaired history as new lines+ // and the live normalizer would replay the conversation into web/device. See Watcher.setTail.+ if (repair.repairedBytes !== undefined) setTail(session.sessionId, repair.repairedBytes)+ console.log(`[resume] repaired ${repair.repairedItems} Codex reasoning items · backup: ${repair.backupPath}`)+ }+ }+ return { relaunchOverrides, refreshGridWebSearch, downgradedPermission, prepareSessionResume }+}diff --git a/cli/src/core/turns/cancel.spec.ts b/cli/src/core/turns/cancel.spec.tsnew file mode 100644index 000000000..ad3ad8058--- /dev/null+++ b/cli/src/core/turns/cancel.spec.ts@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import { createCancel, type CancelDeps } from './cancel.js'++function setup(over: Partial<CancelDeps> = {}) {+ const calls: string[] = []+ const service = { turnEnded: vi.fn() }+ const deps: CancelDeps = {+ resolve: (id) => id === 'a1' ? ({ agentId: 'a1', sessionId: 's1' } as RegisteredSession) : undefined,+ normalizers: { closeTurns: vi.fn((sessionId: string) => { calls.push(`close ${sessionId}`) }) },+ cursorSubagents: { forget: vi.fn() },+ input: { cancel: vi.fn(), cancelConfirmed: vi.fn(async () => true) },+ device: () => service,+ stopHeartbeat: vi.fn(),+ questionWatcher: { stop: vi.fn() },+ mirror: { cancel: vi.fn() },+ ...over,+ }+ return { deps, service, calls, cancelAgent: createCancel(deps) }+}++describe('cancelling a turn', () => {+ it('closes the turn everywhere and tells input, the device, the heartbeat, questions and the dial', async () => {+ const { deps, service, cancelAgent } = setup()+ expect(await cancelAgent('a1')).toBe(true)+ expect(deps.normalizers.closeTurns).toHaveBeenCalledWith('s1')+ expect(deps.cursorSubagents.forget).toHaveBeenCalledWith('s1')+ expect(deps.input.cancel).toHaveBeenCalledWith('a1')+ expect(deps.input.cancelConfirmed).not.toHaveBeenCalled()+ expect(service.turnEnded).toHaveBeenCalledWith('a1', true)+ expect(deps.stopHeartbeat).toHaveBeenCalledWith('s1')+ expect(deps.questionWatcher.stop).toHaveBeenCalledWith('s1')+ expect(deps.mirror.cancel).toHaveBeenCalledWith('s1')+ })++ it('waits for input to confirm a cancel a stop depends on, and answers with what it said', async () => {+ const { deps, cancelAgent } = setup()+ vi.mocked(deps.input.cancelConfirmed).mockResolvedValueOnce(false)+ expect(await cancelAgent('a1', true)).toBe(false)+ expect(deps.input.cancelConfirmed).toHaveBeenCalledWith('a1')+ expect(deps.input.cancel).not.toHaveBeenCalled()+ await cancelAgent('s9', true)+ expect(deps.input.cancelConfirmed).toHaveBeenLastCalledWith('s9')+ })++ it('cancels by the id it was given when no agent has it, with or without a device', async () => {+ const { deps, service, cancelAgent } = setup()+ await cancelAgent('s9')+ expect(deps.normalizers.closeTurns).toHaveBeenCalledWith('s9')+ expect(deps.input.cancel).toHaveBeenCalledWith('s9')+ expect(service.turnEnded).toHaveBeenCalledWith('s9', true)+ const none = setup({ device: () => undefined })+ expect(await none.cancelAgent('a1')).toBe(true)+ })+})diff --git a/cli/src/core/turns/cancel.ts b/cli/src/core/turns/cancel.tsnew file mode 100644index 000000000..255e1e5bc--- /dev/null+++ b/cli/src/core/turns/cancel.ts@@ -0,0 +1,46 @@+/**+ * Cancelling a turn: the person interrupted it (C-c from the app, or a stop that must not wait). The+ * turn is marked closed in whichever engine holds it, input is told, the heartbeat and the question+ * watcher stop, and the device's tile closes without a recap.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).+ */+import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'+import type { QuestionWatcher } from '../../lib/askQuestion.js'+import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'+import type { CommanderMirror } from '../../lib/commander.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { SessionInputController } from '../../lib/sessionInput.js'+import type { SessionNormalizers } from '../transcripts/normalizers.js'++export interface CancelDeps {+ resolve: (id: string) => RegisteredSession | undefined+ normalizers: Pick<SessionNormalizers, 'closeTurns'>+ cursorSubagents: Pick<CursorSubagentManager, 'forget'>+ input: Pick<SessionInputController, 'cancel' | 'cancelConfirmed'>+ /** The Harness device service, once it exists. */+ device: () => Pick<AutonomousDeviceService, 'turnEnded'> | undefined+ stopHeartbeat: (sessionId: string) => void+ questionWatcher: Pick<QuestionWatcher, 'stop'>+ mirror: Pick<CommanderMirror, 'cancel'>+}++export function createCancel({ resolve, normalizers, cursorSubagents, input, device, stopHeartbeat, questionWatcher, mirror }: CancelDeps) {+ // Web cancel (C-c) interrupts the turn — claude writes no end_turn line to close it, so stop the+ // heartbeat and mark the turn closed here (mirrors the hosted runtime stopping its heartbeat on cancel). We do+ // NOT emit turn_ended: the web clears its own dots on cancel, and a turn_ended would fire a device+ // recap for a killed turn. The next real prompt reopens a fresh turn.+ const cancelAgent = (id: string, confirmed = false): Promise<boolean> => {+ const record = resolve(id)+ const sessionId = record?.sessionId ?? id+ normalizers.closeTurns(sessionId)+ cursorSubagents.forget(sessionId)+ const cancelled = confirmed ? input.cancelConfirmed(record?.agentId ?? sessionId) : (input.cancel(record?.agentId ?? sessionId), Promise.resolve(true))+ device()?.turnEnded(record?.agentId ?? sessionId, true)+ stopHeartbeat(sessionId)+ questionWatcher.stop(sessionId)+ mirror.cancel(sessionId) // close the device's "Working…" tile (bare done, no recap) — a cancel emits no turn_ended+ return cancelled+ }+ return cancelAgent+}