Skip to content

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

Core boundary, part 3: attach, ingest, turn hooks and the agy backstop become modules (#721)

Deeb8f41dcfcba8
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 3e13d3081..663e57f7e 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -183,6 +183,10 @@ import { createLastTurnReader } from './core/transcripts/lastTurn.js'
import { createRecaps } from './core/turns/recaps.js'
import { createHeartbeats } from './core/turns/heartbeats.js'
import { createEventFunnel } from './core/turns/funnel.js'
+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 { 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'
@@ -291,12 +295,6 @@ import {
prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS,
} from './lib/log.js'
-// Claude's Stop hook fires when the agent finishes, but the transcript can lag a moment behind
-// (docs: "the transcript file may lag behind the in-memory conversation"). Acting immediately races
-// that flush → an empty recap + a premature close. So the Stop hook is a DELAYED fallback: poll, and
-// only if the turn is still open after this grace + a re-poll do we force-close (by then the assistant
-// text is on disk, so the natural close usually wins and the recap isn't empty).
-const STOP_HOOK_GRACE_MS = 1_500
// Daemon stdout/stderr. Capped at LOG_MAX_BYTES — see prepareLogFile/trimLogFile in lib/log.ts.
const LOG_FILE = join(env.ADAPTER_DATA_DIR, 'harness.log')
@@ -2167,29 +2165,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const cursorNormalizers = normalizers.cursorNormalizers
const opencodeReaders = normalizers.opencodeReaders
const kiloReaders = normalizers.kiloReaders
- /**
- * Sessions that attached before their transcript existed, so nothing was folded and nothing has ever
- * been streamed for them.
- *
- * `bornAfterAgent` was supposed to cover this and does not always fire — measured on pi, whose agent is
- * discovered the instant the engine starts but whose session file only materialises once the first
- * answer is written: the re-attach that finally brought the path tailed from the file's END, so the
- * entire first turn — prompt, tools and answer — was read as history and never reached web or device.
- * A session that folded NOTHING can replay its whole file live without double-showing anything, which
- * is the one case where starting at byte 0 is unambiguously right.
- */
- const neverFoldedHistory = new Set<string>()
- /**
- * Sessions whose first turn has already been replayed live by an attach, or whose transcript an attach
- * has already folded.
- *
- * NOT the same question as `neverFoldedHistory` above, which is why they stay two sets: that one asks
- * "where should the watcher start reading?", this one asks "has this session's file already been
- * emitted?". A `reset` attach (`meta.isNew` or a repeat `SessionStart`) re-enters the folding branch for
- * a session that may already have streamed, and without this the whole transcript would go out a second
- * time.
- */
- const replayedFirstTurn = new Set<string>()
const piNormalizers = normalizers.piNormalizers
const museNormalizers = normalizers.museNormalizers
const ampNormalizers = normalizers.ampNormalizers
@@ -2251,336 +2226,30 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
})
- const attachSessionNow = async (
- session: RegisteredSession,
- reset = false,
- replayCursorFromStart = false,
- /**
- * Tail the transcript from byte 0 instead of from its current end.
- *
- * The watcher normally starts at the end, because a session is registered the moment the engine
- * starts and the file is empty — end and start are the same place. That stops being true when an
- * agent exists BEFORE its session: the user types their first message in the terminal, THAT is what
- * makes the engine open a session, and by the time the hook binds it the prompt (and the first of the
- * answer) is already on disk. Starting at the end skipped it, so the web showed neither the message
- * nor the response. Only ever set for a session that was born after its agent — a resumed one keeps
- * tailing from the end, since its history belongs to `session_get`, not to the live stream.
- */
- replayFromStart = false,
- /** A tail being taken over (see `attachSession`): the hold on it, and where the read that replaces
- * its normalizer stopped — the byte the tail resumes from. */
- handover: { hold: TailHold | null; next: number | null } = { hold: null, next: null },
- ): Promise<boolean> => {
- if (!await validateTerminal(session)) return false
- if (!reset && normalizers.hasState(session.sessionId)) {
- if (session.transcriptPath) {
- const unseen = neverFoldedHistory.delete(session.sessionId)
- await watcher.addSession(
- { ...session, transcriptPath: session.transcriptPath },
- { fromStart: replayFromStart || unseen || (session.engine === 'cursor' && replayCursorFromStart) },
- )
- }
- else if (session.engine === 'cursor') await cursorDiscovery.add(session.sessionId)
- console.log(`[agent] ${sid(session.agentId)} re-attached · engine=${session.engine} · terminal=${primaryTerminalLabel(session)} · session=${sid(session.sessionId)}`)
- return true
- }
- const initialEvents: LiveEvent[] = []
- // Folding the transcript in below is deliberately silent — old turns must never replay live. But
- // when the history ENDS mid-turn the turn is still running, and dropping its `turn_started` costs
- // the whole turn: CommanderMirror.onTurnEnded returns early while turnOpen is false, so the close
- // that follows produces no recap and no `done`. Keep the last start and replay exactly that one.
- //
- // The exception is a transcript BORN AFTER its agent — the file is then the live first turn rather
- // than history, and swallowing it loses the whole thing without a trace. `replayLive` routes the same
- // fold to `initialEvents`, which is emitted below. Cursor has always done this for its own discovery
- // path; the flag simply makes it available to every engine.
- const replayLive = (replayFromStart && !replayedFirstTurn.has(session.sessionId))
- || (session.engine === 'cursor' && replayCursorFromStart)
- const historyEvents: LiveEvent[] = []
- let historyTurnOpen = false
- const observe = autonomousDeviceService?.needsTranscript(session.agentId, session.sessionId, session.engine)
- ? (line: string): void => autonomousDeviceService?.observeTranscript(session.agentId, session.sessionId, session.engine, line)
- : undefined
- // Returns `turnOpen` rather than assigning it: every engine folds exactly once, and a second call
- // quietly overwriting the first is the kind of mistake a returned value makes impossible to write.
- const take = (out: { history: LiveEvent[]; live: LiveEvent[]; turnOpen: boolean }): boolean => {
- // One at a time, not `push(...arr)`: spreading passes every element as a separate argument and Node
- // throws RangeError somewhere past 100k of them. Real transcripts are nowhere near that (measured:
- // 1194 events out of a 25.6 MB rollout) — but the per-line spread this replaced had no ceiling at
- // all, and re-introducing one for no gain would be a poor trade.
- for (const event of out.history) historyEvents.push(event)
- for (const event of out.live) initialEvents.push(event)
- return out.turnOpen
- }
- // Claude Code and Codex read their transcript from the END: the last turn, plus the few older records
- // the chips and a continuing /goal still need — never the whole conversation, which on a long session
- // cost the daemon more memory than it has (lib/attachTranscript.ts). Their normalizers exist before
- // the read because they fold as the records stream in. The other engines still fold everything.
- const codexNormalizer = session.engine === 'codex'
- ? new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome))
- : null
- const claudeState = session.engine === 'claude' ? newTurnState() : null
- const fields = (line: string): readonly RuntimeField[] => runtimeProfiles.transcriptFields(session, line)
- const fromEndFold = codexNormalizer
- ? { rules: codexAttachRules(fields), ingest: (line: string) => codexNormalizer.ingest(line), turnOpen: () => codexNormalizer.turnOpen }
- : claudeState
- ? { rules: claudeAttachRules(fields), ingest: (line: string) => lineToEvents(line, claudeState), turnOpen: () => claudeState.turnOpen }
- : null
- let fromEnd: AttachRead | null = null
- // A reset keeps the normalizer it meant to replace when its read failed, or outlasted the hold on the
- // tail — which then let go, and delivery went back to that normalizer: it has seen every record since,
- // this one has not.
- const keepLiveNormalizer = (why: string): boolean => {
- console.warn(`[agent] ${sid(session.agentId)} kept its live normalizer · the re-read ${why}`)
- handover.hold?.release()
- handover.next = null
- return true
- }
- if (session.transcriptPath && fromEndFold) {
- // A session already being tailed — a reset — is re-read while its old normalizer is still the one
- // being fed: hold its tail, so the read stops exactly where delivery stopped and delivery resumes,
- // into the new normalizer, from where the read stopped (released by `attachSession`).
- handover.hold = await watcher.hold(session.sessionId, session.transcriptPath)
- // Lines a held tail already delivered were seen live; replaying them live again would repeat them.
- const live = replayLive && handover.hold === null
- const stream = new TranscriptFold(fromEndFold.ingest, fromEndFold.turnOpen, live)
- const profile = runtimeProfiles.beginHydrate(session)
- const read = await attachTranscript(session.transcriptPath, fromEndFold.rules, {
- // Ids named for this window cannot repeat ones another fold of the session sent.
- start: (span) => {
- const prefix = `${span.turnFrom.toString(36)}-`
- if (codexNormalizer) codexNormalizer.thinkingPrefix = `thinking-codex-${prefix}`
- if (claudeState) claudeState.thinkingPrefix = `thinking-live-${prefix}`
- },
- profile: (line) => profile.ingest(line),
- fold: (line) => stream.push(line),
- observe,
- }, { fromStart: live, end: handover.hold?.offset })
- if (handover.hold && (read.failed || handover.hold.expired)) {
- return keepLiveNormalizer(read.failed ? 'could not read the transcript' : 'outlasted its hold on the tail')
- }
- profile.commit()
- fromEnd = read
- handover.next = read.next
- historyTurnOpen = take(stream.finish())
- console.log(`[agent] ${sid(session.agentId)} read the transcript from its end · turn @${read.turnFrom} · profile @${read.profileFrom} · ${read.end} bytes${handover.hold ? ' · took over its tail' : ''}`)
- }
- const lines = session.transcriptPath && !fromEnd ? await tailFile(session.transcriptPath, Infinity) : []
- if (!fromEnd) {
- if (observe) for (const line of lines) observe(line)
- runtimeProfiles.hydrate(session, lines)
- }
- await runtimeProfiles.ingestConfig(session, true)
- // From here to the release in `attachSession` nothing is awaited for a held tail, so the hold cannot
- // expire between installing the new normalizer and handing it the tail.
- if (handover.hold?.expired) return keepLiveNormalizer('outlasted its hold on the tail')
- const fold = (ingest: (line: string) => LiveEvent[], turnOpenAfter: () => boolean): boolean =>
- take(foldTranscript(ingest, lines, turnOpenAfter, { live: replayLive }))
- if (codexNormalizer) {
- // Hydrate state silently; never replay history live — except a turn left open, below.
- if (!fromEnd) historyTurnOpen = fold((line) => codexNormalizer.ingest(line), () => codexNormalizer.turnOpen)
- codexNormalizers.set(session.sessionId, codexNormalizer)
- } else if (session.engine === 'cursor') {
- const normalizer = new CursorNormalizer('live', session.sessionId)
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- cursorNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTerminal(session.agentId, 100)
- if (capture) runtimeProfiles.ingestPane(session, capture, true)
- } else if (session.engine === 'opencode') {
- // OpenCode has no transcript file — poll its SQLite DB. The reader hydrates silently, then
- // streams new activity into emitSessionEvents (the same funnel the file engines use).
- const reader = new OpencodeReader({
- dbPath: OPENCODE_DB,
- sessionId: session.sessionId,
- onEvents: (events) => emitSessionEvents(session.sessionId, events),
- onFatal: (err) => console.warn(`[opencode] ${sid(session.sessionId)} ${err.message}`),
- })
- opencodeReaders.set(session.sessionId, reader)
- await reader.start()
- // The composer footer is the ONLY place OpenCode names its model and reasoning level, so
- // without this a freshly opened agent showed empty chips until the five-minute reconcile came
- // round — which is exactly how long it looked broken for.
- const ocPane = await captureTerminal(session.agentId, 100)
- if (ocPane) runtimeProfiles.ingestPane(session, ocPane, true)
- } else if (session.engine === 'kilo') {
- // Kilo is opencode's fork and keeps the same store shape, so it is polled the same way — but from
- // its OWN db and through its own reader, so the two can diverge without one breaking the other.
- const reader = new KiloReader({
- dbPath: KILO_DB,
- sessionId: session.sessionId,
- onEvents: (events) => emitSessionEvents(session.sessionId, events),
- onFatal: (err) => console.warn(`[kilo] ${sid(session.sessionId)} ${err.message}`),
- })
- kiloReaders.set(session.sessionId, reader)
- await reader.start()
- } else if (session.engine === 'muse') {
- // Same JSONL tail as claude/pi; only the record shape differs.
- const normalizer = new MuseNormalizer()
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- museNormalizers.set(session.sessionId, normalizer)
- } else if (session.engine === 'amp') {
- // A JSONL tail like claude/muse — except the file is written by the adapter's own Amp plugin,
- // because Amp is the one engine that keeps no conversation on disk.
- const normalizer = new AmpNormalizer()
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- ampNormalizers.set(session.sessionId, normalizer)
- } else if (session.engine === 'grok') {
- const normalizer = new GrokNormalizer()
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- grokNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTerminal(session.agentId, 60)
- if (capture) runtimeProfiles.ingestPane(session, capture, true)
- } else if (session.engine === 'agy') {
- // A JSONL tail like claude/grok. agy announces its model only in the hook payload and its pane
- // footer, so the pane is read once on attach to fill the chip before the first turn.
- const normalizer = new AgyNormalizer()
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- agyNormalizers.set(session.sessionId, normalizer)
- const capture = await captureTerminal(session.agentId, 60)
- if (capture) runtimeProfiles.ingestPane(session, capture, true)
- // agy's transcript has no end-of-turn record - only its Stop hook does - so a fold of a FINISHED
- // conversation still reports the last turn as open, and after a daemon restart nothing is ever
- // coming to close it. The pane is the one place the answer exists; ask it.
- if (historyTurnOpen && capture && agyPaneIdle(capture)) {
- normalizer.closeTurn()
- historyTurnOpen = false
- }
- } else if (session.engine === 'copilot') {
- // A JSONL tail like claude/agy. Its turn lifecycle comes from the agentStop hook, not the file —
- // which is exactly why a fold cannot be trusted on its own: `copilot --resume` replays a finished
- // conversation, the fold opens a turn on its last `user.message`, and no hook is coming to close
- // it. Ask the records where the last activity actually ended.
- const normalizer = new CopilotNormalizer()
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- copilotNormalizers.set(session.sessionId, normalizer)
- if (historyTurnOpen && !copilotHistoryTurnOpen(lines)) {
- normalizer.closeTurn()
- historyTurnOpen = false
- }
- } else if (session.engine === 'pi') {
- const normalizer = new PiNormalizer('live')
- // Hydrate state silently; never replay history live — except a turn left open, below.
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- piNormalizers.set(session.sessionId, normalizer)
- } else if (session.engine === 'hermes') {
- // Hermes has no transcript file — poll its SQLite store, like opencode.
- const reader = new HermesReader({
- dbPath: await hermesDbForSession(session),
- sessionId: session.sessionId,
- onEvents: (events) => emitSessionEvents(session.sessionId, events),
- onFatal: (err) => console.warn(`[hermes] ${sid(session.sessionId)} ${err.message}`),
- })
- hermesReaders.set(session.sessionId, reader)
- await reader.start()
- } else if (session.engine === 'devin') {
- // Devin has no transcript file either — poll its SQLite store, like hermes/opencode.
- const reader = new DevinReader({
- dbPath: DEVIN_DB,
- devinHome: env.DEVIN_HOME,
- sessionId: session.sessionId,
- onEvents: (events) => emitSessionEvents(session.sessionId, events),
- // Devin has no StopFailure: a turn that dies on a provider error writes no assistant row and
- // fires no Stop hook, so surface the failure and close the turn ourselves — otherwise the web
- // sits on the typing indicator forever.
- onTurnAborted: (message) => {
- announceTurnAborted(session.sessionId, 'devin', message)
- emitSessionEvents(session.sessionId, [{ type: 'turn_ended', payload: {} }])
- },
- onFatal: (err) => console.warn(`[devin] ${sid(session.sessionId)} ${err.message}`),
- })
- devinReaders.set(session.sessionId, reader)
- await reader.start()
- // Devin's model/effort exist ONLY in its pane footer, so read it now. Without this the chip stayed
- // on Auto until the 5-minute reconcile happened to run — the attach itself said nothing about it.
- const devinPane = await captureTerminal(session.agentId, 60)
- if (devinPane) runtimeProfiles.ingestPane(session, devinPane, true)
- } else if (session.engine === 'commandcode') {
- const normalizer = new CommandCodeNormalizer('live')
- // Hydrate state silently; never replay history live — except a turn left open, below.
- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
- commandcodeNormalizers.set(session.sessionId, normalizer)
- } else {
- const state = claudeState ?? newTurnState()
- if (!fromEnd) historyTurnOpen = fold((line) => lineToEvents(line, state), () => state.turnOpen)
- turnStates.set(session.sessionId, state)
- }
- if (session.transcriptPath) {
- neverFoldedHistory.delete(session.sessionId)
- // Deliberately NOT `fromStart`, even when the caller asked for it: this branch has just folded the
- // file into the normalizer above, so replaying it from byte 0 emits every line a second time.
- // Measured: a claude turn opened, closed after 44ms and opened again, because the fold replayed the
- // open turn and the watcher then re-read the same bytes. `fromStart` belongs to the re-attach path,
- // which folds nothing. A transcript read from its end hands the tail the exact byte it stopped at.
- // A held tail is already this session's, and resumes from there when the hold is released.
- if (!handover.hold || !watcher.tails(session.sessionId, session.transcriptPath)) {
- await watcher.addSession({ ...session, transcriptPath: session.transcriptPath }, fromEnd ? { fromOffset: fromEnd.next } : {})
- }
- } else if (session.engine === 'cursor') {
- await cursorDiscovery.add(session.sessionId)
- } else {
- // No transcript to fold: whatever this session writes later is its FIRST content, so the re-attach
- // that brings the path must read the file whole rather than from its end.
- neverFoldedHistory.add(session.sessionId)
- }
- // Marked on the FOLD, not on the emission. A live fold that happened to produce nothing — the file
- // was still empty when this attach ran — would otherwise leave the session unmarked, and the next
- // `reset` attach (claude fires `SessionStart` on compact, which resets) would fold the by-then
- // complete transcript and emit it live on top of everything the watcher had already streamed. That
- // is the same duplicate-turn class this whole change exists to remove.
- // Any fold of a transcript with content counts too: the watcher now tails it from the end, so a later
- // replay could only send history out again as if it were live.
- if (replayLive || lines.length || fromEnd?.content) replayedFirstTurn.add(session.sessionId)
- if (initialEvents.length) {
- emitSessionEvents(session.sessionId, initialEvents)
- console.log(`[agent] ${sid(session.agentId)} replayed the first turn its transcript already held · ${initialEvents.length} events`)
- }
- console.log(`[agent] ${sid(session.agentId)} attached · engine=${session.engine} · terminal=${primaryTerminalLabel(session)} · session=${sid(session.sessionId)} · lines=${fromEnd ? fromEnd.records : lines.length}`)
- // A first prompt that lands while this attach is running is already in the transcript we just
- // folded, so its turn_started was consumed as history and the live turn would end up untracked.
- // Replay that one event, after the attach log, so the recovery is visible in order.
- if (historyTurnOpen) {
- const opened = historyEvents.findLast((event) => event.type === 'turn_started')
- if (opened) {
- console.log(`[agent] ${sid(session.agentId)} resumed the turn already open at attach`)
- emitSessionEvents(session.sessionId, [opened], { resumed: true })
- }
- }
- // Watch this pane for a question from ATTACH, not only from the next turn_started.
- //
- // A turn-scoped start assumes the agent exists before its turn does, and for some engines it does not:
- // OpenCode registers itself when its FIRST message creates the session, i.e. the turn is already
- // running by the time the daemon knows the agent — so its question opened and nothing announced it
- // (measured: the dialog sat on the pane, the device saw nothing). Command Code has the mirror problem,
- // asking AFTER the turn ends. The watcher is idempotent, no-ops without a device, and dies with the
- // session, so starting it early costs nothing.
- if (pollsQuestions(session.engine)) questionWatcher.start(session.sessionId)
- return true
- }
-
- /** One attach per session, a few sessions at a time, and a record of what is being read — see lib/attachTracker. */
- const attaches = new AttachTracker<AgentEngine>({
+ // Following a session: its history read into its engine's normalizer, then its tail
+ // (core/transcripts/attach.ts).
+ const attach = createAttach({
+ validateTerminal,
+ normalizers,
+ watcher,
+ cursorDiscovery,
+ device: () => autonomousDeviceService,
+ runtimeProfiles,
+ captureTerminal,
+ emit: (sessionId, events, opts) => emitSessionEvents(sessionId, events, opts),
+ announceTurnAborted,
+ // Built further down: read when an attach starts watching a pane, never now.
+ questionWatcher: { start: (sessionId) => questionWatcher.start(sessionId) },
+ terminalLabel: primaryTerminalLabel,
+ dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },
+ devinHome: env.DEVIN_HOME,
+ hermesDb: (s) => hermesDbForSession(s),
concurrency: ATTACH_CONCURRENCY,
- onSlow: (session, elapsedMs) => console.warn(
- `[agent] ${sid(session.agentId)} attach still running · engine=${session.engine} · session=${sid(session.sessionId)} · ${Math.round(elapsedMs / 1000)}s`,
- ),
})
- const attachSession = (
- session: RegisteredSession,
- reset = false,
- replayCursorFromStart = false,
- replayFromStart = false,
- ): Promise<boolean> =>
- attaches.attach(session, reset, async () => {
- // A tail an attach holds (a Claude Code or Codex reset, see attachSessionNow) is released only
- // here, after the whole attach — the new normalizer installed and any open turn said to be open —
- // so delivery resumes into it, in order. Released on every exit, however the attach ends.
- const handover = { hold: null as TailHold | null, next: null as number | null }
- try {
- return await attachSessionNow(session, reset, replayCursorFromStart, replayFromStart, handover)
- } finally {
- handover.hold?.release(handover.next)
- }
- })
+ const attaches = attach.attaches
+ const attachSession = attach.attachSession
+ const neverFoldedHistory = attach.neverFoldedHistory
+ const replayedFirstTurn = attach.replayedFirstTurn
// Everything the core writes into a pane, and the device's pane lock (core/input.ts).
const inputs = createInput({
resolve: (id) => registry.resolve(id),
@@ -2605,53 +2274,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const input = inputs.input
const deviceInput = inputs.deviceInput
- /**
- * agy only: close a turn whose final `Stop` never came.
- *
- * agy reports `fullyIdle: false` when it pauses for sub-agents, and normally sends one more Stop with
- * `fullyIdle: true` once they report — measured, and that is the path a healthy turn takes. But one
- * measured run completed its sub-agents, wrote its summary, and sent nothing further; the turn stayed
- * open with no recap. The pane is the only other place the answer exists (`? for shortcuts` idle vs
- * `esc to cancel` busy), so a waiting Stop arms a bounded poll of it.
- *
- * Bounded on purpose: it stops after AGY_IDLE_WATCH_MAX checks (~10 min) rather than polling a pane
- * forever, and any real Stop clears it first.
- */
- const AGY_IDLE_WATCH_MS = 15_000
- const AGY_IDLE_WATCH_MAX = 40
- const agyIdleWatch = new Map<string, { timer: NodeJS.Timeout; checks: number }>()
-
- const clearAgyIdleWatch = (sessionId: string): void => {
- const watch = agyIdleWatch.get(sessionId)
- if (!watch) return
- clearTimeout(watch.timer)
- agyIdleWatch.delete(sessionId)
- }
-
- const armAgyIdleWatch = (sessionId: string): void => {
- const checks = agyIdleWatch.get(sessionId)?.checks ?? 0
- clearAgyIdleWatch(sessionId)
- if (checks >= AGY_IDLE_WATCH_MAX) return
- const timer = setTimeout(() => {
- void (async () => {
- agyIdleWatch.delete(sessionId)
- const normalizer = agyNormalizers.get(sessionId)
- if (!normalizer?.turnOpen) return
- const entry = registry.bySession(sessionId)
- if (!entry) return
- const capture = await captureTerminal(entry.agentId, 60)
- if (!capture || !agyPaneIdle(capture)) { armAgyIdleWatch(sessionId); return }
- await watcher.pollSession(sessionId)
- if (!normalizer.turnOpen) return
- console.log(`[turn] ${sid(sessionId)} closed by the agy idle backstop · no final Stop arrived`)
- emitSessionEvents(sessionId, normalizer.closeTurn())
- })().catch((err) => {
- console.error('[agy] idle backstop failed:', err instanceof Error ? err.message : err)
- })
- }, AGY_IDLE_WATCH_MS)
- timer.unref?.()
- agyIdleWatch.set(sessionId, { timer, checks: checks + 1 })
- }
+ // agy's turn closed from its pane when its final Stop never comes (core/turns/agyBackstop.ts).
+ const agyBackstop = createAgyBackstop({
+ agyNormalizers,
+ bySession: (sessionId) => registry.bySession(sessionId),
+ captureTerminal,
+ drain: (sessionId) => watcher.pollSession(sessionId),
+ emit: (sessionId, events) => emitSessionEvents(sessionId, events),
+ })
+ const clearAgyIdleWatch = agyBackstop.clearAgyIdleWatch
+ const armAgyIdleWatch = agyBackstop.armAgyIdleWatch
const acquireTerminalControl = inputs.acquireTerminalControl
// Questions an agent asks the person: shown on the dial and the window, answered from anywhere
@@ -3556,6 +3188,20 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
+ const turnHooks = createTurnHooks({
+ resolve: (id) => registry.resolve(id),
+ normalizers,
+ emit: (sessionId, events) => emitSessionEvents(sessionId, events),
+ drain: (sessionId) => watcher.pollSession(sessionId),
+ onCursorTaskStart,
+ cursorTaskHooks,
+ cursorSubagents,
+ announceTurnAborted,
+ armAgyIdleWatch,
+ clearAgyIdleWatch,
+ mirror,
+ dataDir: env.ADAPTER_DATA_DIR,
+ })
const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {
onCommandBar: commandBarService,
onAutonomousDeviceRequest: async (method, target, body) => {
@@ -3643,176 +3289,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onRegistered: handleRegistered,
onPromptSubmitted: (id, text) => backend.swarmPromptScopes.started(id, text, 'hook', registry.byAgent(id)?.engine),
onSessionEnd,
- // Command Code's PreToolUse — the one live "a turn is running" signal this engine has. Without it the
- // adapter only learned of a turn from Stop, and emitted turn_started+turn_ended in the same
- // millisecond, so the device tile jumped from idle straight to the recap with no working state.
- onTurnStart: ({ sessionId }) => {
- const session = registry.resolve(sessionId)
- if (!session || session.engine !== 'commandcode') return
- const normalizer = commandcodeNormalizers.get(sessionId)
- if (!normalizer) return
- emitSessionEvents(sessionId, normalizer.openTurn()) // no-op after the turn's first tool call
- },
- onToolStart: ({ sessionId, toolUseId, toolName, input: toolInput }) => {
- if (toolName === 'Task') onCursorTaskStart(sessionId, toolUseId, toolInput)
- },
- onTurnStop: ({ sessionId, status }) => {
- const session = registry.resolve(sessionId)
- if (!session) return
- if (session.engine === 'cursor') {
- void (async () => {
- await cursorTaskHooks.wait(sessionId)
- await watcher.pollSession(sessionId)
- const normalizer = cursorNormalizers.get(sessionId)
- if (!normalizer) return
- cursorSubagents.closeParent(sessionId, status === 'error')
- const closing = normalizer.closeTurn()
- emitSessionEvents(sessionId, closing)
- // Cursor can fail a turn BEFORE it writes anything to the transcript — observed as a Stop hook
- // with status=error 2.4s after beforeSubmitPrompt, with no transcript file discovered and no
- // rows to read. The normalizer never opened a turn, so closeTurn() returns nothing, so nothing
- // reaches the device: the tile just sits on the previous recap forever while the user waits.
- //
- // Every other engine already routes its failures through announceTurnAborted (codex, devin,
- // commandcode); cursor was the one that stayed silent. Announce only when the close produced no
- // events — if there WAS output, the `done` event above already tells the device the turn ended.
- if (status === 'error' && closing.length === 0) {
- announceTurnAborted(sessionId, 'cursor', 'Cursor ended the turn with an error before producing any output')
- }
- setTimeout(() => void removeCursorPendingTasks(env.ADAPTER_DATA_DIR, sessionId), 2_500)
- })().catch((err) => {
- console.error('[cursor] stop hook failed:', err instanceof Error ? err.message : err)
- })
- return
- }
- // claude: authoritative turn-close from the Stop/StopFailure hook. Drain any un-read JSONL FIRST
- // (may emit the real turn_ended → st.turnOpen already false); only force-close if still open. A
- // later real end_turn line is then a no-op (lineToEvents guards on state.turnOpen). This closes
- // the B1/B2 cases (max_tokens/refusal/API-error/wedged tool) the JSONL parse would otherwise miss.
- // Command Code has no UserPromptSubmit and commits records per turn, so Stop is its authoritative
- // close: drain the transcript first (the natural close usually wins), then force-close what's left.
- if (session.engine === 'commandcode') {
- void (async () => {
- await watcher.pollSession(sessionId)
- const normalizer = commandcodeNormalizers.get(sessionId)
- if (!normalizer?.turnOpen) return
- await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
- await watcher.pollSession(sessionId)
- if (!normalizer.turnOpen) return
- normalizer.closeTurn()
- console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
- emitSessionEvents(sessionId, [{ type: 'turn_ended', payload: {} }])
- })().catch((err) => {
- console.error('[hooks] commandcode stop hook failed:', err instanceof Error ? err.message : err)
- })
- return
- }
- // Devin: same deal, except the un-read history is in SQLite rather than a file, so the drain is the
- // reader's own poll. Its rows only land once the model round-trip commits, so the grace matters.
- if (session.engine === 'devin') {
- void (async () => {
- const reader = devinReaders.get(sessionId)
- if (!reader?.turnOpen) return
- await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
- if (!reader.turnOpen) return
- reader.closeTurn()
- console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
- emitSessionEvents(sessionId, [{ type: 'turn_ended', payload: {} }])
- })().catch((err) => {
- console.error('[hooks] devin stop hook failed:', err instanceof Error ? err.message : err)
- })
- return
- }
- // Copilot's agentStop hook is the turn boundary: its own `assistant.turn_end` records mark model
- // round-trips, several per exchange. Drain first so the closing text is on the wire, then close.
- if (session.engine === 'copilot') {
- void (async () => {
- await watcher.pollSession(sessionId)
- const normalizer = copilotNormalizers.get(sessionId)
- if (!normalizer?.turnOpen) return
- await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
- await watcher.pollSession(sessionId)
- if (!normalizer.turnOpen) return
- if (status === 'error') {
- announceTurnAborted(sessionId, 'copilot', 'Copilot ended the turn early')
- emitSessionEvents(sessionId, normalizer.abortTurn())
- return
- }
- console.log(`[turn] ${sid(sessionId)} closed by copilot agentStop hook (after grace)`)
- emitSessionEvents(sessionId, normalizer.closeTurn())
- })().catch((err) => {
- console.error('[hooks] copilot stop hook failed:', err instanceof Error ? err.message : err)
- })
- return
- }
- // agy's Stop hook is the ONLY turn boundary it has. Nothing in the transcript says a turn ended:
- // a backgrounded step is written `status: RUNNING` and, the file being append-only, stays that way
- // forever. Drain first so the closing prose is on the wire before turn_ended, then force-close.
- if (session.engine === 'agy') {
- // `waiting` = agy's loop stopped only because it is standing by for its sub-agents. The turn is
- // NOT over, so nothing closes here — but the run that proved this necessary also finished its
- // sub-agents and then never sent another Stop, so a backstop watches the pane instead.
- if (status === 'waiting') {
- armAgyIdleWatch(sessionId)
- return
- }
- clearAgyIdleWatch(sessionId)
- void (async () => {
- await watcher.pollSession(sessionId)
- const normalizer = agyNormalizers.get(sessionId)
- if (!normalizer?.turnOpen) return
- await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
- await watcher.pollSession(sessionId)
- if (!normalizer.turnOpen) return
- if (status === 'error') {
- announceTurnAborted(sessionId, 'agy', 'agy ended the turn early')
- emitSessionEvents(sessionId, normalizer.abortTurn())
- return
- }
- console.log(`[turn] ${sid(sessionId)} closed by agy Stop hook (after grace)`)
- emitSessionEvents(sessionId, normalizer.closeTurn())
- })().catch((err) => {
- console.error('[hooks] agy stop hook failed:', err instanceof Error ? err.message : err)
- })
- return
- }
- if (session.engine === 'grok') {
- void (async () => {
- await watcher.pollSession(sessionId)
- const normalizer = grokNormalizers.get(sessionId)
- if (status === 'error') {
- announceTurnAborted(sessionId, 'grok', 'Grok ended the turn with an error')
- emitSessionEvents(sessionId, normalizer?.abortTurn() ?? [])
- }
- })().catch((err) => {
- console.error('[hooks] grok StopFailure hook failed:', err instanceof Error ? err.message : err)
- })
- return
- }
- if (session.engine !== 'claude') return
- void (async () => {
- await watcher.pollSession(sessionId)
- // A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is
- // HOLDING a turn-end for finished async sub-agents, this is what tells it the wrap-up message is
- // on disk — without it the recap fires on its settle timer and can beat claude's closing summary
- // to the punch (measured: recap at 10:18:41, wrap-up written at 10:18:44).
- mirror.noteEngineStopped(sessionId)
- if (!turnStates.get(sessionId)?.turnOpen) return // natural JSONL close already won → nothing to do
- // Still open: the transcript may just be lagging the Stop hook. Wait, re-poll, and only force-close
- // if it STILL hasn't closed — a genuinely wedged turn, whose assistant text is on disk by now.
- await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
- await watcher.pollSession(sessionId)
- const st = turnStates.get(sessionId)
- if (st?.turnOpen) {
- st.turnOpen = false
- st.pendingTools.clear()
- console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)
- emitSessionEvents(sessionId, [{ type: 'turn_ended', payload: {} }])
- }
- })().catch((err) => {
- console.error('[hooks] claude stop hook failed:', err instanceof Error ? err.message : err)
- })
- },
+ // What the engines' own hooks say about a turn (core/turns/turnHooks.ts).
+ onTurnStart: turnHooks.onTurnStart,
+ onToolStart: turnHooks.onToolStart,
+ onTurnStop: turnHooks.onTurnStop,
// `harness pair <code>` → run CPace toward the waiting browser; map the result to an HTTP outcome.
onPair: async (code) => {
const r = await backend.pair(code)
@@ -4452,116 +3932,19 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approve
console.log(`[cli] local dashboard → http://127.0.0.1:${hookPort}`)
- // JSONL watcher → normalize each appended line → stream up. ONE lineToEvents pass feeds BOTH
- // audiences: web (send, ServerEvents) and device (mirror.ingest → curated commander_event cards).
- /** One transcript line through its engine's normalizer. The events, not yet emitted — the two
- * callers below differ only in what they know about the line's age. */
- const ingestLine = (evt: LineEvent): ReturnType<CursorNormalizer['ingest']> | null => {
- if (!registry.has(evt.sessionId)) return null // scope to terminal-registered sessions
- const session = registry.bySession(evt.sessionId)
- if (!session || session.engine !== evt.engine) return null
- agentTokenUsage.changed(session)
- if (autonomousDeviceService?.needsTranscript(session.agentId, evt.sessionId, session.engine)) {
- autonomousDeviceService.observeTranscript(session.agentId, evt.sessionId, session.engine, evt.text)
- }
- runtimeProfiles.ingest(session, evt.text)
- let events
- if (session.engine === 'codex') {
- let normalizer = codexNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome)); codexNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- // Codex rides its failure ON task_complete, so the turn closes by itself — but with no text and
- // no reason, which reads as "the agent answered nothing". Announce the reason ahead of the
- // turn_ended that `events` carries.
- const taskError = codexTaskError(evt.text)
- if (taskError !== null) announceTurnAborted(evt.sessionId, 'codex', taskError)
- } else if (session.engine === 'cursor') {
- let normalizer = cursorNormalizers.get(evt.sessionId)
- if (!normalizer) {
- normalizer = new CursorNormalizer('live', evt.sessionId)
- cursorNormalizers.set(evt.sessionId, normalizer)
- }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'muse') {
- let normalizer = museNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new MuseNormalizer(); museNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'amp') {
- let normalizer = ampNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new AmpNormalizer(); ampNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'grok') {
- let normalizer = grokNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new GrokNormalizer(); grokNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'agy') {
- let normalizer = agyNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new AgyNormalizer(); agyNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'copilot') {
- let normalizer = copilotNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new CopilotNormalizer(); copilotNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'pi') {
- let normalizer = piNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- } else if (session.engine === 'commandcode') {
- let normalizer = commandcodeNormalizers.get(evt.sessionId)
- if (!normalizer) { normalizer = new CommandCodeNormalizer('live'); commandcodeNormalizers.set(evt.sessionId, normalizer) }
- events = normalizer.ingest(evt.text)
- // Command Code fires no Stop hook for a failed turn: this record IS the notification. `ingest`
- // already closed the turn (its turn_ended is in `events`, emitted just below) — announce the
- // reason first so the web/device show the error ahead of the turn closing.
- const runError = commandCodeRunError(evt.text)
- if (runError !== null) {
- announceTurnAborted(evt.sessionId, 'commandcode', runError, commandCodeRunErrorSummary(runError))
- }
- } else {
- let st = turnStates.get(evt.sessionId)
- if (!st) { st = newTurnState(); turnStates.set(evt.sessionId, st) }
- events = lineToEvents(evt.text, st)
- }
- return events
- return events
- }
- watcher.on('line', (evt: LineEvent) => {
- // This runs from a void-discarded async read, so a throw here would be an unhandledRejection. A
- // single malformed line must never take the daemon down — contain it per line and move on.
- try {
- const events = ingestLine(evt)
- if (events) emitSessionEvents(evt.sessionId, events)
- } catch (err) {
- console.error(`[cli] line handler error (session ${evt.sessionId}):`, err instanceof Error ? err.message : err)
- }
- })
- // A transcript catch-up is history, including an unfinished last turn.
- // Its content still streams, but only fresh events or live inspection can
- // establish Working; replay cannot create a new completion notification.
- // A transcript rewritten in place with too much history to replay: its tail already starts at the new
- // end, and the session is attached again, from that end, so its turn state is rebuilt from the file.
- watcher.on('rewritten', (event: RewrittenEvent) => {
- const session = registry.bySession(event.sessionId)
- if (!session || session.transcriptPath !== event.transcriptPath) return
- console.log(`[watcher] ${sid(event.sessionId)} transcript rewritten in place — attaching it again from its end`)
- void attachSession(session, true).catch((err) => console.error(`[cli] re-attach after rewrite failed (session ${sid(event.sessionId)}):`, err instanceof Error ? err.message : err))
- })
- watcher.on('history', (batch: HistoryEvent) => {
- try {
- type Events = ReturnType<CursorNormalizer['ingest']>
- const all: Events = []
- for (const evt of batch.lines) {
- const events = ingestLine(evt)
- if (events) all.push(...events)
- }
- if (!all.length) return
- // Every line in this batch was already on disk. An unclosed last turn
- // is not a fresh prompt; live runtime inspection can establish activity.
- emitSessionEvents(batch.sessionId, all, { replay: true })
- } catch (err) {
- console.error(`[cli] history handler error (session ${batch.sessionId}):`, err instanceof Error ? err.message : err)
- }
+ // Each transcript line, through its engine's normalizer, into the funnel (core/transcripts/ingest.ts).
+ const ingest = createIngest({
+ has: (sessionId) => registry.has(sessionId),
+ bySession: (sessionId) => registry.bySession(sessionId),
+ tokenUsage: agentTokenUsage,
+ device: () => autonomousDeviceService,
+ runtimeProfiles,
+ normalizers,
+ announceTurnAborted,
+ emit: (sessionId, events, opts) => emitSessionEvents(sessionId, events, opts),
+ attachSession: (session, reset) => attachSession(session, reset),
})
+ ingest.wireWatcher(watcher)
// Nothing re-attaches the registry's agents here. Every one of them is dormant from the moment the
// registry loads (see the `setActive(false)` transaction at the top of this function), and the first
// reconcile pass is what reactivates each one it finds a live process for — and attaches it, in the
diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.ts
new file mode 100644
index 000000000..8b17f848e
--- /dev/null
+++ b/cli/src/core/transcripts/attach.spec.ts
@@ -0,0 +1,372 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { TailHold } from '../../watcher/watcher.js'
+import { createAttach, type AttachDeps } from './attach.js'
+import { createSessionNormalizers } from './normalizers.js'
+
+/**
+ * The engines' own normalizers and readers are tested with each engine. Here each is a fake that
+ * reads JSON lines: `{"events":[…]}` is what a line yields, `{"open":true}` / `{"close":true}` move
+ * its turn. Transcript reading, folding and the attach tracker are the real ones.
+ */
+const fakes = vi.hoisted(() => {
+ const made: Array<{ kind: string; args: unknown[]; instance: Record<string, any> }> = []
+ const normalizer = (kind: string) => class {
+ turnOpen = false
+ thinkingPrefix = ''
+ args: unknown[]
+ constructor(...args: unknown[]) { this.args = args; made.push({ kind, args, instance: this as Record<string, any> }) }
+ ingest(line: string) {
+ const record = JSON.parse(line || '{}') as { events?: unknown[]; open?: boolean; close?: boolean }
+ if (record.open) this.turnOpen = true
+ if (record.close) this.turnOpen = false
+ return record.events ?? []
+ }
+ closeTurn() { this.turnOpen = false; return [] }
+ }
+ const reader = (kind: string) => class {
+ turnOpen = false
+ opts: Record<string, any>
+ start = async () => {}
+ constructor(opts: Record<string, any>) { this.opts = opts; made.push({ kind, args: [opts], instance: this as Record<string, any> }) }
+ }
+ return { made, normalizer, reader, copilotOpen: { value: true } }
+})
+vi.mock('../../engines/codex/normalizer.js', async (real) => ({ ...await real<object>(), CodexNormalizer: fakes.normalizer('codex') }))
+vi.mock('../../engines/cursor/normalizer.js', async (real) => ({ ...await real<object>(), CursorNormalizer: fakes.normalizer('cursor') }))
+vi.mock('../../engines/muse/normalizer.js', async (real) => ({ ...await real<object>(), MuseNormalizer: fakes.normalizer('muse') }))
+vi.mock('../../engines/amp/normalizer.js', async (real) => ({ ...await real<object>(), AmpNormalizer: fakes.normalizer('amp') }))
+vi.mock('../../engines/grok/normalizer.js', async (real) => ({ ...await real<object>(), GrokNormalizer: fakes.normalizer('grok') }))
+vi.mock('../../engines/agy/normalizer.js', async (real) => ({ ...await real<object>(), AgyNormalizer: fakes.normalizer('agy') }))
+vi.mock('../../engines/pi/normalizer.js', async (real) => ({ ...await real<object>(), PiNormalizer: fakes.normalizer('pi') }))
+vi.mock('../../engines/commandcode/normalizer.js', async (real) => ({ ...await real<object>(), CommandCodeNormalizer: fakes.normalizer('commandcode') }))
+vi.mock('../../engines/copilot/normalizer.js', async (real) => ({
+ ...await real<object>(),
+ CopilotNormalizer: fakes.normalizer('copilot'),
+ copilotHistoryTurnOpen: () => fakes.copilotOpen.value,
+}))
+vi.mock('../../engines/opencode/reader.js', async (real) => ({ ...await real<object>(), OpencodeReader: fakes.reader('opencode') }))
+vi.mock('../../engines/kilo/reader.js', async (real) => ({ ...await real<object>(), KiloReader: fakes.reader('kilo') }))
+vi.mock('../../engines/hermes/reader.js', async (real) => ({ ...await real<object>(), HermesReader: fakes.reader('hermes') }))
+vi.mock('../../engines/devin/reader.js', async (real) => ({ ...await real<object>(), DevinReader: fakes.reader('devin') }))
+
+const dirs: string[] = []
+const transcript = (lines: unknown[] = []): string => {
+ const dir = mkdtempSync(join(tmpdir(), 'core-attach-'))
+ dirs.push(dir)
+ const file = join(dir, 'session.jsonl')
+ writeFileSync(file, lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n') + (lines.length ? '\n' : ''))
+ return file
+}
+const session = (engine: string, transcriptPath?: string, over: Partial<RegisteredSession> = {}): RegisteredSession =>
+ ({ agentId: `${engine}-agent`, sessionId: `${engine}-s`, engine, transcriptPath, ...over }) as RegisteredSession
+
+const IDLE_AGY = 'done\n\n ? for shortcuts'
+const started = (userMessage = 'go') => ({ type: 'turn_started', payload: { userMessage } })
+const CLAUDE_PROMPT = { type: 'user', message: { role: 'user', content: 'hello' }, uuid: 'u1' }
+
+function setup(over: Partial<AttachDeps> = {}) {
+ const normalizers = createSessionNormalizers()
+ const service = { needsTranscript: vi.fn(() => false), observeTranscript: vi.fn() }
+ const profile = { ingest: vi.fn(), commit: vi.fn() }
+ const deps: AttachDeps = {
+ validateTerminal: vi.fn(async () => true),
+ normalizers,
+ watcher: { addSession: vi.fn(async () => {}), hold: vi.fn(async () => null), tails: vi.fn(() => false) },
+ cursorDiscovery: { add: vi.fn(async () => {}) },
+ device: () => service,
+ runtimeProfiles: {
+ transcriptFields: vi.fn(() => []),
+ beginHydrate: vi.fn(() => profile),
+ hydrate: vi.fn(),
+ ingestConfig: vi.fn(async () => {}),
+ ingestPane: vi.fn(),
+ } as unknown as AttachDeps['runtimeProfiles'],
+ captureTerminal: vi.fn(async () => 'pane'),
+ emit: vi.fn(),
+ announceTurnAborted: vi.fn(),
+ questionWatcher: { start: vi.fn() },
+ terminalLabel: () => 'tmux:%0',
+ dbs: { opencode: '/db/opencode.db', kilo: '/db/kilo.db', devin: '/db/devin.db' },
+ devinHome: '/devin',
+ hermesDb: async (s) => `/db/hermes-${s.agentId}.db`,
+ concurrency: 2,
+ ...over,
+ }
+ return { deps, normalizers, service, profile, attach: createAttach(deps) }
+}
+
+const made = (kind: string) => fakes.made.filter((entry) => entry.kind === kind).map((entry) => entry.instance)
+
+describe('attaching a session', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ fakes.made.length = 0
+ fakes.copilotOpen.value = true
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ })
+
+ it('refuses a session whose pane is gone', async () => {
+ const { attach, deps } = setup({ validateTerminal: vi.fn(async () => false) })
+ expect(await attach.attachSession(session('pi', transcript()))).toBe(false)
+ expect(deps.watcher.addSession).not.toHaveBeenCalled()
+ })
+
+ describe('a session it already follows', () => {
+ it('only makes sure the tail runs — from the start for one that never folded anything', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const s = session('pi', '/t/pi.jsonl')
+ run.normalizers.piNormalizers.set(s.sessionId, {} as never)
+ expect(await run.attach.attachSession(s)).toBe(true)
+ run.attach.neverFoldedHistory.add(s.sessionId)
+ await run.attach.attachSession(s)
+ await run.attach.attachSession(s, false, false, true)
+ expect(vi.mocked(run.deps.watcher.addSession).mock.calls.map((call) => call[1])).toEqual([
+ { fromStart: false }, { fromStart: true }, { fromStart: true },
+ ])
+ expect(run.attach.neverFoldedHistory.has(s.sessionId)).toBe(false)
+ })
+
+ it('replays Cursor from the start when asked, and asks discovery when Cursor has no transcript yet', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const withFile = session('cursor', '/t/cursor.jsonl')
+ run.normalizers.cursorNormalizers.set(withFile.sessionId, {} as never)
+ await run.attach.attachSession(withFile, false, true)
+ expect(vi.mocked(run.deps.watcher.addSession).mock.calls[0][1]).toEqual({ fromStart: true })
+ const noFile = session('cursor', undefined, { sessionId: 'cursor-2' })
+ run.normalizers.cursorNormalizers.set('cursor-2', {} as never)
+ await run.attach.attachSession(noFile)
+ expect(run.deps.cursorDiscovery.add).toHaveBeenCalledWith('cursor-2')
+ const opencode = session('opencode')
+ run.normalizers.opencodeReaders.set(opencode.sessionId, {} as never)
+ expect(await run.attach.attachSession(opencode)).toBe(true)
+ })
+ })
+
+ describe('a first attach', () => {
+ it('reads Claude Code from the end, hands the tail the byte it stopped at, and replays a turn left open', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const s = session('claude', transcript([CLAUDE_PROMPT]))
+ expect(await run.attach.attachSession(s)).toBe(true)
+ const [, from] = vi.mocked(run.deps.watcher.addSession).mock.calls[0]
+ expect(from).toEqual({ fromOffset: expect.any(Number) })
+ expect(run.normalizers.turnStates.get(s.sessionId)?.turnOpen).toBe(true)
+ expect(run.profile.commit).toHaveBeenCalled()
+ expect(run.deps.emit).toHaveBeenCalledWith(s.sessionId, [expect.objectContaining({ type: 'turn_started' })], { resumed: true })
+ expect(run.attach.replayedFirstTurn.has(s.sessionId)).toBe(true)
+ expect(run.deps.questionWatcher.start).toHaveBeenCalledWith(s.sessionId)
+ expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.includes('read the transcript from its end'))).toBe(true)
+ })
+
+ it('reads Codex from the end through its own normalizer, and lets each window name its thinking ids', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const s = session('codex', transcript([{ type: 'event_msg', payload: { type: 'user_message', message: 'go' } }]))
+ await run.attach.attachSession(s)
+ const [codex] = made('codex')
+ expect(run.normalizers.codexNormalizers.get(s.sessionId)).toBe(codex)
+ expect(codex.thinkingPrefix).toMatch(/^thinking-codex-/)
+ })
+
+ it('attaches a Codex session before its rollout exists, ready for its first line', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ expect(await run.attach.attachSession(session('codex'))).toBe(true)
+ expect(run.normalizers.codexNormalizers.get('codex-s')).toBe(made('codex')[0])
+ expect(run.attach.neverFoldedHistory.has('codex-s')).toBe(true)
+ })
+
+ it('shows the device the raw lines it subscribed to, on either path', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ run.service.needsTranscript.mockReturnValue(true)
+ await run.attach.attachSession(session('claude', transcript([CLAUDE_PROMPT])))
+ await run.attach.attachSession(session('pi', transcript([{ events: [] }])))
+ expect(run.service.observeTranscript).toHaveBeenCalledWith('claude-agent', 'claude-s', 'claude', expect.any(String))
+ expect(run.service.observeTranscript).toHaveBeenCalledWith('pi-agent', 'pi-s', 'pi', '{"events":[]}')
+ const none = setup({ device: () => undefined })
+ expect(await none.attach.attachSession(session('pi', transcript([{}])))).toBe(true)
+ })
+
+ it('takes over a tail it holds for a reset, resuming it where the read stopped', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const s = session('claude', transcript([CLAUDE_PROMPT]))
+ const hold: TailHold = { offset: 1_000_000, expired: false, release: vi.fn() }
+ vi.mocked(run.deps.watcher.hold).mockResolvedValue(hold)
+ vi.mocked(run.deps.watcher.tails).mockReturnValue(true)
+ expect(await run.attach.attachSession(s, true)).toBe(true)
+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()
+ expect(hold.release).toHaveBeenCalledWith(expect.any(Number))
+ // A hold whose tail is gone by then: the tail is started from the read's end instead.
+ vi.mocked(run.deps.watcher.tails).mockReturnValue(false)
+ await run.attach.attachSession(s, true)
+ expect(run.deps.watcher.addSession).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps the live normalizer when the re-read fails or outlasts its hold', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const expired: TailHold = { offset: 10, expired: true, release: vi.fn() }
+ vi.mocked(run.deps.watcher.hold).mockResolvedValueOnce(expired)
+ expect(await run.attach.attachSession(session('claude', transcript([CLAUDE_PROMPT])), true)).toBe(true)
+ expect(expired.release).toHaveBeenCalledWith()
+ // The file is gone under the read: it cannot be read through.
+ const missing: TailHold = { offset: 10, expired: false, release: vi.fn() }
+ vi.mocked(run.deps.watcher.hold).mockResolvedValueOnce(missing)
+ await run.attach.attachSession(session('claude', '/nowhere/session.jsonl', { sessionId: 'gone' }), true)
+ // Expiring after the read, while the profile's config is read.
+ const late = { offset: 1_000_000, expired: false, release: vi.fn() }
+ vi.mocked(run.deps.watcher.hold).mockResolvedValueOnce(late as TailHold)
+ vi.mocked(run.deps.runtimeProfiles.ingestConfig).mockImplementationOnce(async () => { late.expired = true; return true })
+ await run.attach.attachSession(session('claude', transcript([CLAUDE_PROMPT]), { sessionId: 'late' }), true)
+ expect(warn.mock.calls.map(([line]) => String(line)).filter((line) => line.includes('kept its live normalizer'))).toEqual([
+ expect.stringContaining('the re-read outlasted its hold on the tail'),
+ expect.stringContaining('the re-read could not read the transcript'),
+ expect.stringContaining('the re-read outlasted its hold on the tail'),
+ ])
+ expect(run.normalizers.turnStates.has('late')).toBe(false)
+ })
+
+ it('replays a first turn already on disk when the transcript was born after its agent', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const s = session('pi', transcript([{ events: [started('first')] }, { events: [{ type: 'text_delta', payload: { content: 'hi' } }] }]))
+ await run.attach.attachSession(s, false, false, true)
+ expect(run.deps.emit).toHaveBeenCalledWith(s.sessionId, [expect.objectContaining({ type: 'turn_started' }), expect.objectContaining({ type: 'text_delta' })])
+ expect(log.mock.calls.map(([line]) => String(line)).some((line) => line.includes('replayed the first turn'))).toBe(true)
+ // Once replayed, never again.
+ run.normalizers.piNormalizers.delete(s.sessionId)
+ vi.mocked(run.deps.emit).mockClear()
+ await run.attach.attachSession(s, true, false, true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ })
+
+ it('replays a Claude Code first turn live when born after its agent, unless a held tail already delivered it', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ await run.attach.attachSession(session('claude', transcript([CLAUDE_PROMPT])), false, false, true)
+ expect(vi.mocked(run.deps.emit).mock.calls[0][2]).toBeUndefined()
+ const held = setup()
+ vi.mocked(held.deps.watcher.hold).mockResolvedValue({ offset: 1_000_000, expired: false, release: vi.fn() })
+ await held.attach.attachSession(session('claude', transcript([CLAUDE_PROMPT])), true, false, true)
+ expect(vi.mocked(held.deps.emit).mock.calls.every((call) => call[2]?.resumed)).toBe(true)
+ })
+
+ it('marks a session with no transcript yet, so its first content is read whole', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ await run.attach.attachSession(session('pi'))
+ expect(run.attach.neverFoldedHistory.has('pi-s')).toBe(true)
+ await run.attach.attachSession(session('cursor'))
+ expect(run.deps.cursorDiscovery.add).toHaveBeenCalledWith('cursor-s')
+ expect(run.attach.neverFoldedHistory.has('cursor-s')).toBe(false)
+ })
+
+ it('folds each file engine into its own normalizer, reading the pane where the chips live there', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ const maps: Record<string, Map<string, unknown>> = {
+ cursor: run.normalizers.cursorNormalizers, muse: run.normalizers.museNormalizers, amp: run.normalizers.ampNormalizers,
+ grok: run.normalizers.grokNormalizers, agy: run.normalizers.agyNormalizers, copilot: run.normalizers.copilotNormalizers,
+ pi: run.normalizers.piNormalizers, commandcode: run.normalizers.commandcodeNormalizers,
+ }
+ for (const engine of Object.keys(maps)) {
+ await run.attach.attachSession(session(engine, transcript([{}])))
+ expect(maps[engine].get(`${engine}-s`), engine).toBe(made(engine)[0])
+ }
+ expect(vi.mocked(run.deps.captureTerminal).mock.calls).toEqual([['cursor-agent', 100], ['grok-agent', 60], ['agy-agent', 60]])
+ expect(run.deps.runtimeProfiles.ingestPane).toHaveBeenCalledTimes(3)
+ // A pane that cannot be read leaves the chips to the next look.
+ vi.mocked(run.deps.captureTerminal).mockResolvedValue(null)
+ for (const engine of ['cursor', 'grok', 'agy']) await run.attach.attachSession(session(engine, transcript([{}]), { sessionId: `${engine}-2` }))
+ expect(run.deps.runtimeProfiles.ingestPane).toHaveBeenCalledTimes(3)
+ })
+
+ it('closes an agy turn its pane shows finished, and a Copilot turn its records show over', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ vi.mocked(run.deps.captureTerminal).mockResolvedValue(IDLE_AGY)
+ await run.attach.attachSession(session('agy', transcript([{ events: [started()], open: true }])))
+ expect(made('agy')[0].turnOpen).toBe(false)
+ fakes.copilotOpen.value = false
+ await run.attach.attachSession(session('copilot', transcript([{ events: [started()], open: true }])))
+ expect(made('copilot')[0].turnOpen).toBe(false)
+ // Still running by the pane, and by the records: left open, and replayed as a resumed turn.
+ vi.mocked(run.deps.captureTerminal).mockResolvedValue('working\n esc to cancel')
+ await run.attach.attachSession(session('agy', transcript([{ events: [started()], open: true }]), { sessionId: 'agy-2' }))
+ fakes.copilotOpen.value = true
+ await run.attach.attachSession(session('copilot', transcript([{ events: [started()], open: true }]), { sessionId: 'copilot-2' }))
+ expect(made('agy')[1].turnOpen).toBe(true)
+ expect(made('copilot')[1].turnOpen).toBe(true)
+ expect(vi.mocked(run.deps.emit).mock.calls.filter((call) => call[2]?.resumed).map((call) => call[0])).toEqual(['agy-2', 'copilot-2'])
+ })
+
+ it('does not resume a turn left open when its history holds no turn start', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ await run.attach.attachSession(session('pi', transcript([{ open: true }])))
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ })
+
+ it('polls each database engine through its reader, wired to the funnel', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ for (const engine of ['opencode', 'kilo', 'hermes', 'devin']) await run.attach.attachSession(session(engine))
+ const [opencode] = made('opencode')
+ const [kilo] = made('kilo')
+ const [hermes] = made('hermes')
+ const [devin] = made('devin')
+ expect(opencode.opts).toMatchObject({ dbPath: '/db/opencode.db', sessionId: 'opencode-s' })
+ expect(kilo.opts).toMatchObject({ dbPath: '/db/kilo.db', sessionId: 'kilo-s' })
+ expect(hermes.opts).toMatchObject({ dbPath: '/db/hermes-hermes-agent.db', sessionId: 'hermes-s' })
+ expect(devin.opts).toMatchObject({ dbPath: '/db/devin.db', devinHome: '/devin', sessionId: 'devin-s' })
+ expect(run.normalizers.opencodeReaders.get('opencode-s')).toBe(opencode)
+ expect(run.normalizers.kiloReaders.get('kilo-s')).toBe(kilo)
+ expect(run.normalizers.hermesReaders.get('hermes-s')).toBe(hermes)
+ expect(run.normalizers.devinReaders.get('devin-s')).toBe(devin)
+ for (const reader of [opencode, kilo, hermes, devin]) {
+ reader.opts.onEvents([started()])
+ reader.opts.onFatal(new Error('store missing'))
+ }
+ expect(vi.mocked(run.deps.emit).mock.calls.map((call) => call[0])).toEqual(['opencode-s', 'kilo-s', 'hermes-s', 'devin-s'])
+ expect(warn).toHaveBeenCalledTimes(4)
+ devin.opts.onTurnAborted('provider error')
+ expect(run.deps.announceTurnAborted).toHaveBeenCalledWith('devin-s', 'devin', 'provider error')
+ expect(run.deps.emit).toHaveBeenLastCalledWith('devin-s', [{ type: 'turn_ended', payload: {} }])
+ // OpenCode and Devin name their model only in the pane.
+ expect(vi.mocked(run.deps.captureTerminal).mock.calls).toEqual([['opencode-agent', 100], ['devin-agent', 60]])
+ vi.mocked(run.deps.captureTerminal).mockResolvedValue(null)
+ await run.attach.attachSession(session('opencode', undefined, { sessionId: 'opencode-2' }))
+ await run.attach.attachSession(session('devin', undefined, { sessionId: 'devin-2' }))
+ expect(run.deps.runtimeProfiles.ingestPane).toHaveBeenCalledTimes(2)
+ })
+
+ it('folds any other engine with a plain turn state', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup()
+ await run.attach.attachSession(session('terminal', transcript(['{}'])))
+ expect(run.normalizers.turnStates.has('terminal-s')).toBe(true)
+ expect(run.deps.questionWatcher.start).not.toHaveBeenCalled()
+ })
+ })
+
+ it('says when an attach is slow', async () => {
+ vi.useFakeTimers()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const run = setup({ validateTerminal: () => new Promise<boolean>(() => {}) })
+ void run.attach.attachSession(session('pi', '/t/pi.jsonl'))
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(String(warn.mock.calls[0][0])).toMatch(/attach still running · engine=pi · session=.* · 15s/)
+ expect(run.attach.attaches.attaching()).toHaveLength(1)
+ })
+})
diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.ts
new file mode 100644
index 000000000..68a351e6c
--- /dev/null
+++ b/cli/src/core/transcripts/attach.ts
@@ -0,0 +1,425 @@
+/**
+ * Attach: start following a session. The first attach of a session reads its history into its engine's
+ * normalizer — Claude Code and Codex from the end of the transcript (lib/attachTranscript.ts), the other
+ * file engines whole, the database engines through a reader that then polls — replays only a turn still
+ * open, and hands the tail the byte the read stopped at. A later attach of a session it already follows
+ * only makes sure the tail is running. One attach per session at a time, a few sessions at a time.
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 9: docs/design/2026-10-03-harnessd.md).
+ */
+import { AgyNormalizer } from '../../engines/agy/normalizer.js'
+import { agyPaneIdle } from '../../engines/agy/runtimeProfile.js'
+import { AmpNormalizer } from '../../engines/amp/normalizer.js'
+import { CodexNormalizer } from '../../engines/codex/normalizer.js'
+import { codexSubagentResolverFor } from '../../engines/codex/subagent.js'
+import { CommandCodeNormalizer } from '../../engines/commandcode/normalizer.js'
+import { CopilotNormalizer, copilotHistoryTurnOpen } from '../../engines/copilot/normalizer.js'
+import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'
+import { CursorNormalizer } from '../../engines/cursor/normalizer.js'
+import { DevinReader } from '../../engines/devin/reader.js'
+import { GrokNormalizer } from '../../engines/grok/normalizer.js'
+import { HermesReader } from '../../engines/hermes/reader.js'
+import { KiloReader } from '../../engines/kilo/reader.js'
+import { MuseNormalizer } from '../../engines/muse/normalizer.js'
+import { OpencodeReader } from '../../engines/opencode/reader.js'
+import { PiNormalizer } from '../../engines/pi/normalizer.js'
+import type { AgentEngine } from '../../engines/types.js'
+import { pollsQuestions, type QuestionWatcher } from '../../lib/askQuestion.js'
+import { attachTranscript, claudeAttachRules, codexAttachRules, type AttachRead } from '../../lib/attachTranscript.js'
+import { AttachTracker } from '../../lib/attachTracker.js'
+import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'
+import { sid } from '../../lib/log.js'
+import { foldTranscript, lineToEvents, newTurnState, TranscriptFold, type LiveEvent } from '../../lib/normalize.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { RuntimeField, RuntimeProfileManager } from '../../lib/runtimeProfile.js'
+import { tailFile } from '../../lib/transcriptTail.js'
+import type { TailHold, Watcher } from '../../watcher/watcher.js'
+import type { SessionNormalizers } from './normalizers.js'
+
+export interface AttachDeps {
+ validateTerminal: (session: RegisteredSession) => Promise<boolean>
+ normalizers: SessionNormalizers
+ watcher: Pick<Watcher, 'addSession' | 'hold' | 'tails'>
+ cursorDiscovery: Pick<CursorTranscriptDiscovery, 'add'>
+ /** The Harness device service, once it exists: some subscriptions read the raw transcript. */
+ device: () => Pick<AutonomousDeviceService, 'needsTranscript' | 'observeTranscript'> | undefined
+ runtimeProfiles: Pick<RuntimeProfileManager, 'transcriptFields' | 'beginHydrate' | 'hydrate' | 'ingestConfig' | 'ingestPane'>
+ captureTerminal: (target: string, historyLines?: number) => Promise<string | null>
+ emit: (sessionId: string, events: LiveEvent[], opts?: { resumed?: boolean }) => void
+ announceTurnAborted: (sessionId: string, engine: string, message: string) => void
+ questionWatcher: Pick<QuestionWatcher, 'start'>
+ /** How a session's terminal is named in the log. */
+ terminalLabel: (session: RegisteredSession) => string
+ /** The database engines' stores. */
+ dbs: { opencode: string; kilo: string; devin: string }
+ devinHome: string
+ /** Hermes keeps a store per profile: the one this session's lives in. */
+ hermesDb: (session: RegisteredSession) => Promise<string>
+ /** How many sessions attach at once. */
+ concurrency: number
+}
+
+export function createAttach({
+ validateTerminal, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,
+ announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency,
+}: AttachDeps) {
+ const {
+ turnStates, codexNormalizers, cursorNormalizers, opencodeReaders, kiloReaders, museNormalizers, ampNormalizers,
+ grokNormalizers, agyNormalizers, copilotNormalizers, piNormalizers, hermesReaders, devinReaders, commandcodeNormalizers,
+ } = normalizers
+ /**
+ * Sessions that attached before their transcript existed, so nothing was folded and nothing has ever
+ * been streamed for them.
+ *
+ * `bornAfterAgent` was supposed to cover this and does not always fire — measured on pi, whose agent is
+ * discovered the instant the engine starts but whose session file only materialises once the first
+ * answer is written: the re-attach that finally brought the path tailed from the file's END, so the
+ * entire first turn — prompt, tools and answer — was read as history and never reached web or device.
+ * A session that folded NOTHING can replay its whole file live without double-showing anything, which
+ * is the one case where starting at byte 0 is unambiguously right.
+ */
+ const neverFoldedHistory = new Set<string>()
+ /**
+ * Sessions whose first turn has already been replayed live by an attach, or whose transcript an attach
+ * has already folded.
+ *
+ * NOT the same question as `neverFoldedHistory` above, which is why they stay two sets: that one asks
+ * "where should the watcher start reading?", this one asks "has this session's file already been
+ * emitted?". A `reset` attach (`meta.isNew` or a repeat `SessionStart`) re-enters the folding branch for
+ * a session that may already have streamed, and without this the whole transcript would go out a second
+ * time.
+ */
+ const replayedFirstTurn = new Set<string>()
+ const attachSessionNow = async (
+ session: RegisteredSession,
+ reset = false,
+ replayCursorFromStart = false,
+ /**
+ * Tail the transcript from byte 0 instead of from its current end.
+ *
+ * The watcher normally starts at the end, because a session is registered the moment the engine
+ * starts and the file is empty — end and start are the same place. That stops being true when an
+ * agent exists BEFORE its session: the user types their first message in the terminal, THAT is what
+ * makes the engine open a session, and by the time the hook binds it the prompt (and the first of the
+ * answer) is already on disk. Starting at the end skipped it, so the web showed neither the message
+ * nor the response. Only ever set for a session that was born after its agent — a resumed one keeps
+ * tailing from the end, since its history belongs to `session_get`, not to the live stream.
+ */
+ replayFromStart = false,
+ /** A tail being taken over (see `attachSession`): the hold on it, and where the read that replaces
+ * its normalizer stopped — the byte the tail resumes from. */
+ handover: { hold: TailHold | null; next: number | null } = { hold: null, next: null },
+ ): Promise<boolean> => {
+ if (!await validateTerminal(session)) return false
+ if (!reset && normalizers.hasState(session.sessionId)) {
+ if (session.transcriptPath) {
+ const unseen = neverFoldedHistory.delete(session.sessionId)
+ await watcher.addSession(
+ { ...session, transcriptPath: session.transcriptPath },
+ { fromStart: replayFromStart || unseen || (session.engine === 'cursor' && replayCursorFromStart) },
+ )
+ }
+ else if (session.engine === 'cursor') await cursorDiscovery.add(session.sessionId)
+ console.log(`[agent] ${sid(session.agentId)} re-attached · engine=${session.engine} · terminal=${terminalLabel(session)} · session=${sid(session.sessionId)}`)
+ return true
+ }
+ const initialEvents: LiveEvent[] = []
+ // Folding the transcript in below is deliberately silent — old turns must never replay live. But
+ // when the history ENDS mid-turn the turn is still running, and dropping its `turn_started` costs
+ // the whole turn: CommanderMirror.onTurnEnded returns early while turnOpen is false, so the close
+ // that follows produces no recap and no `done`. Keep the last start and replay exactly that one.
+ //
+ // The exception is a transcript BORN AFTER its agent — the file is then the live first turn rather
+ // than history, and swallowing it loses the whole thing without a trace. `replayLive` routes the same
+ // fold to `initialEvents`, which is emitted below. Cursor has always done this for its own discovery
+ // path; the flag simply makes it available to every engine.
+ const replayLive = (replayFromStart && !replayedFirstTurn.has(session.sessionId))
+ || (session.engine === 'cursor' && replayCursorFromStart)
+ const historyEvents: LiveEvent[] = []
+ let historyTurnOpen = false
+ const observe = device()?.needsTranscript(session.agentId, session.sessionId, session.engine)
+ ? (line: string): void => device()?.observeTranscript(session.agentId, session.sessionId, session.engine, line)
+ : undefined
+ // Returns `turnOpen` rather than assigning it: every engine folds exactly once, and a second call
+ // quietly overwriting the first is the kind of mistake a returned value makes impossible to write.
+ const take = (out: { history: LiveEvent[]; live: LiveEvent[]; turnOpen: boolean }): boolean => {
+ // One at a time, not `push(...arr)`: spreading passes every element as a separate argument and Node
+ // throws RangeError somewhere past 100k of them. Real transcripts are nowhere near that (measured:
+ // 1194 events out of a 25.6 MB rollout) — but the per-line spread this replaced had no ceiling at
+ // all, and re-introducing one for no gain would be a poor trade.
+ for (const event of out.history) historyEvents.push(event)
+ for (const event of out.live) initialEvents.push(event)
+ return out.turnOpen
+ }
+ // Claude Code and Codex read their transcript from the END: the last turn, plus the few older records
+ // the chips and a continuing /goal still need — never the whole conversation, which on a long session
+ // cost the daemon more memory than it has (lib/attachTranscript.ts). Their normalizers exist before
+ // the read because they fold as the records stream in. The other engines still fold everything.
+ const codexNormalizer = session.engine === 'codex'
+ ? new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome))
+ : null
+ const claudeState = session.engine === 'claude' ? newTurnState() : null
+ const fields = (line: string): readonly RuntimeField[] => runtimeProfiles.transcriptFields(session, line)
+ const fromEndFold = codexNormalizer
+ ? { rules: codexAttachRules(fields), ingest: (line: string) => codexNormalizer.ingest(line), turnOpen: () => codexNormalizer.turnOpen }
+ : claudeState
+ ? { rules: claudeAttachRules(fields), ingest: (line: string) => lineToEvents(line, claudeState), turnOpen: () => claudeState.turnOpen }
+ : null
+ let fromEnd: AttachRead | null = null
+ // A reset keeps the normalizer it meant to replace when its read failed, or outlasted the hold on the
+ // tail — which then let go, and delivery went back to that normalizer: it has seen every record since,
+ // this one has not.
+ const keepLiveNormalizer = (why: string): boolean => {
+ console.warn(`[agent] ${sid(session.agentId)} kept its live normalizer · the re-read ${why}`)
+ handover.hold?.release()
+ handover.next = null
+ return true
+ }
+ if (session.transcriptPath && fromEndFold) {
+ // A session already being tailed — a reset — is re-read while its old normalizer is still the one
+ // being fed: hold its tail, so the read stops exactly where delivery stopped and delivery resumes,
+ // into the new normalizer, from where the read stopped (released by `attachSession`).
+ handover.hold = await watcher.hold(session.sessionId, session.transcriptPath)
+ // Lines a held tail already delivered were seen live; replaying them live again would repeat them.
+ const live = replayLive && handover.hold === null
+ const stream = new TranscriptFold(fromEndFold.ingest, fromEndFold.turnOpen, live)
+ const profile = runtimeProfiles.beginHydrate(session)
+ const read = await attachTranscript(session.transcriptPath, fromEndFold.rules, {
+ // Ids named for this window cannot repeat ones another fold of the session sent.
+ start: (span) => {
+ const prefix = `${span.turnFrom.toString(36)}-`
+ if (codexNormalizer) codexNormalizer.thinkingPrefix = `thinking-codex-${prefix}`
+ if (claudeState) claudeState.thinkingPrefix = `thinking-live-${prefix}`
+ },
+ profile: (line) => profile.ingest(line),
+ fold: (line) => stream.push(line),
+ observe,
+ }, { fromStart: live, end: handover.hold?.offset })
+ if (handover.hold && (read.failed || handover.hold.expired)) {
+ return keepLiveNormalizer(read.failed ? 'could not read the transcript' : 'outlasted its hold on the tail')
+ }
+ profile.commit()
+ fromEnd = read
+ handover.next = read.next
+ historyTurnOpen = take(stream.finish())
+ console.log(`[agent] ${sid(session.agentId)} read the transcript from its end · turn @${read.turnFrom} · profile @${read.profileFrom} · ${read.end} bytes${handover.hold ? ' · took over its tail' : ''}`)
+ }
+ const lines = session.transcriptPath && !fromEnd ? await tailFile(session.transcriptPath, Infinity) : []
+ if (!fromEnd) {
+ if (observe) for (const line of lines) observe(line)
+ runtimeProfiles.hydrate(session, lines)
+ }
+ await runtimeProfiles.ingestConfig(session, true)
+ // From here to the release in `attachSession` nothing is awaited for a held tail, so the hold cannot
+ // expire between installing the new normalizer and handing it the tail.
+ if (handover.hold?.expired) return keepLiveNormalizer('outlasted its hold on the tail')
+ const fold = (ingest: (line: string) => LiveEvent[], turnOpenAfter: () => boolean): boolean =>
+ take(foldTranscript(ingest, lines, turnOpenAfter, { live: replayLive }))
+ if (codexNormalizer) {
+ // Folded above, from the end, when there is a rollout; without one there is nothing to fold.
+ codexNormalizers.set(session.sessionId, codexNormalizer)
+ } else if (session.engine === 'cursor') {
+ const normalizer = new CursorNormalizer('live', session.sessionId)
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ cursorNormalizers.set(session.sessionId, normalizer)
+ const capture = await captureTerminal(session.agentId, 100)
+ if (capture) runtimeProfiles.ingestPane(session, capture, true)
+ } else if (session.engine === 'opencode') {
+ // OpenCode has no transcript file — poll its SQLite DB. The reader hydrates silently, then
+ // streams new activity into the funnel (the same one the file engines use).
+ const reader = new OpencodeReader({
+ dbPath: dbs.opencode,
+ sessionId: session.sessionId,
+ onEvents: (events) => emit(session.sessionId, events),
+ onFatal: (err) => console.warn(`[opencode] ${sid(session.sessionId)} ${err.message}`),
+ })
+ opencodeReaders.set(session.sessionId, reader)
+ await reader.start()
+ // The composer footer is the ONLY place OpenCode names its model and reasoning level, so
+ // without this a freshly opened agent showed empty chips until the five-minute reconcile came
+ // round — which is exactly how long it looked broken for.
+ const ocPane = await captureTerminal(session.agentId, 100)
+ if (ocPane) runtimeProfiles.ingestPane(session, ocPane, true)
+ } else if (session.engine === 'kilo') {
+ // Kilo is opencode's fork and keeps the same store shape, so it is polled the same way — but from
+ // its OWN db and through its own reader, so the two can diverge without one breaking the other.
+ const reader = new KiloReader({
+ dbPath: dbs.kilo,
+ sessionId: session.sessionId,
+ onEvents: (events) => emit(session.sessionId, events),
+ onFatal: (err) => console.warn(`[kilo] ${sid(session.sessionId)} ${err.message}`),
+ })
+ kiloReaders.set(session.sessionId, reader)
+ await reader.start()
+ } else if (session.engine === 'muse') {
+ // Same JSONL tail as claude/pi; only the record shape differs.
+ const normalizer = new MuseNormalizer()
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ museNormalizers.set(session.sessionId, normalizer)
+ } else if (session.engine === 'amp') {
+ // A JSONL tail like claude/muse — except the file is written by the adapter's own Amp plugin,
+ // because Amp is the one engine that keeps no conversation on disk.
+ const normalizer = new AmpNormalizer()
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ ampNormalizers.set(session.sessionId, normalizer)
+ } else if (session.engine === 'grok') {
+ const normalizer = new GrokNormalizer()
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ grokNormalizers.set(session.sessionId, normalizer)
+ const capture = await captureTerminal(session.agentId, 60)
+ if (capture) runtimeProfiles.ingestPane(session, capture, true)
+ } else if (session.engine === 'agy') {
+ // A JSONL tail like claude/grok. agy announces its model only in the hook payload and its pane
+ // footer, so the pane is read once on attach to fill the chip before the first turn.
+ const normalizer = new AgyNormalizer()
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ agyNormalizers.set(session.sessionId, normalizer)
+ const capture = await captureTerminal(session.agentId, 60)
+ if (capture) runtimeProfiles.ingestPane(session, capture, true)
+ // agy's transcript has no end-of-turn record - only its Stop hook does - so a fold of a FINISHED
+ // conversation still reports the last turn as open, and after a daemon restart nothing is ever
+ // coming to close it. The pane is the one place the answer exists; ask it.
+ if (historyTurnOpen && capture && agyPaneIdle(capture)) {
+ normalizer.closeTurn()
+ historyTurnOpen = false
+ }
+ } else if (session.engine === 'copilot') {
+ // A JSONL tail like claude/agy. Its turn lifecycle comes from the agentStop hook, not the file —
+ // which is exactly why a fold cannot be trusted on its own: `copilot --resume` replays a finished
+ // conversation, the fold opens a turn on its last `user.message`, and no hook is coming to close
+ // it. Ask the records where the last activity actually ended.
+ const normalizer = new CopilotNormalizer()
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ copilotNormalizers.set(session.sessionId, normalizer)
+ if (historyTurnOpen && !copilotHistoryTurnOpen(lines)) {
+ normalizer.closeTurn()
+ historyTurnOpen = false
+ }
+ } else if (session.engine === 'pi') {
+ const normalizer = new PiNormalizer('live')
+ // Hydrate state silently; never replay history live — except a turn left open, below.
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ piNormalizers.set(session.sessionId, normalizer)
+ } else if (session.engine === 'hermes') {
+ // Hermes has no transcript file — poll its SQLite store, like opencode.
+ const reader = new HermesReader({
+ dbPath: await hermesDb(session),
+ sessionId: session.sessionId,
+ onEvents: (events) => emit(session.sessionId, events),
+ onFatal: (err) => console.warn(`[hermes] ${sid(session.sessionId)} ${err.message}`),
+ })
+ hermesReaders.set(session.sessionId, reader)
+ await reader.start()
+ } else if (session.engine === 'devin') {
+ // Devin has no transcript file either — poll its SQLite store, like hermes/opencode.
+ const reader = new DevinReader({
+ dbPath: dbs.devin,
+ devinHome,
+ sessionId: session.sessionId,
+ onEvents: (events) => emit(session.sessionId, events),
+ // Devin has no StopFailure: a turn that dies on a provider error writes no assistant row and
+ // fires no Stop hook, so surface the failure and close the turn ourselves — otherwise the web
+ // sits on the typing indicator forever.
+ onTurnAborted: (message) => {
+ announceTurnAborted(session.sessionId, 'devin', message)
+ emit(session.sessionId, [{ type: 'turn_ended', payload: {} }])
+ },
+ onFatal: (err) => console.warn(`[devin] ${sid(session.sessionId)} ${err.message}`),
+ })
+ devinReaders.set(session.sessionId, reader)
+ await reader.start()
+ // Devin's model/effort exist ONLY in its pane footer, so read it now. Without this the chip stayed
+ // on Auto until the 5-minute reconcile happened to run — the attach itself said nothing about it.
+ const devinPane = await captureTerminal(session.agentId, 60)
+ if (devinPane) runtimeProfiles.ingestPane(session, devinPane, true)
+ } else if (session.engine === 'commandcode') {
+ const normalizer = new CommandCodeNormalizer('live')
+ // Hydrate state silently; never replay history live — except a turn left open, below.
+ historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
+ commandcodeNormalizers.set(session.sessionId, normalizer)
+ } else {
+ const state = claudeState ?? newTurnState()
+ if (!fromEnd) historyTurnOpen = fold((line) => lineToEvents(line, state), () => state.turnOpen)
+ turnStates.set(session.sessionId, state)
+ }
+ if (session.transcriptPath) {
+ neverFoldedHistory.delete(session.sessionId)
+ // Deliberately NOT `fromStart`, even when the caller asked for it: this branch has just folded the
+ // file into the normalizer above, so replaying it from byte 0 emits every line a second time.
+ // Measured: a claude turn opened, closed after 44ms and opened again, because the fold replayed the
+ // open turn and the watcher then re-read the same bytes. `fromStart` belongs to the re-attach path,
+ // which folds nothing. A transcript read from its end hands the tail the exact byte it stopped at.
+ // A held tail is already this session's, and resumes from there when the hold is released.
+ if (!handover.hold || !watcher.tails(session.sessionId, session.transcriptPath)) {
+ await watcher.addSession({ ...session, transcriptPath: session.transcriptPath }, fromEnd ? { fromOffset: fromEnd.next } : {})
+ }
+ } else if (session.engine === 'cursor') {
+ await cursorDiscovery.add(session.sessionId)
+ } else {
+ // No transcript to fold: whatever this session writes later is its FIRST content, so the re-attach
+ // that brings the path must read the file whole rather than from its end.
+ neverFoldedHistory.add(session.sessionId)
+ }
+ // Marked on the FOLD, not on the emission. A live fold that happened to produce nothing — the file
+ // was still empty when this attach ran — would otherwise leave the session unmarked, and the next
+ // `reset` attach (claude fires `SessionStart` on compact, which resets) would fold the by-then
+ // complete transcript and emit it live on top of everything the watcher had already streamed. That
+ // is the same duplicate-turn class this whole change exists to remove.
+ // Any fold of a transcript with content counts too: the watcher now tails it from the end, so a later
+ // replay could only send history out again as if it were live.
+ if (replayLive || lines.length || fromEnd?.content) replayedFirstTurn.add(session.sessionId)
+ if (initialEvents.length) {
+ emit(session.sessionId, initialEvents)
+ console.log(`[agent] ${sid(session.agentId)} replayed the first turn its transcript already held · ${initialEvents.length} events`)
+ }
+ console.log(`[agent] ${sid(session.agentId)} attached · engine=${session.engine} · terminal=${terminalLabel(session)} · session=${sid(session.sessionId)} · lines=${fromEnd ? fromEnd.records : lines.length}`)
+ // A first prompt that lands while this attach is running is already in the transcript we just
+ // folded, so its turn_started was consumed as history and the live turn would end up untracked.
+ // Replay that one event, after the attach log, so the recovery is visible in order.
+ if (historyTurnOpen) {
+ const opened = historyEvents.findLast((event) => event.type === 'turn_started')
+ if (opened) {
+ console.log(`[agent] ${sid(session.agentId)} resumed the turn already open at attach`)
+ emit(session.sessionId, [opened], { resumed: true })
+ }
+ }
+ // Watch this pane for a question from ATTACH, not only from the next turn_started.
+ //
+ // A turn-scoped start assumes the agent exists before its turn does, and for some engines it does not:
+ // OpenCode registers itself when its FIRST message creates the session, i.e. the turn is already
+ // running by the time the daemon knows the agent — so its question opened and nothing announced it
+ // (measured: the dialog sat on the pane, the device saw nothing). Command Code has the mirror problem,
+ // asking AFTER the turn ends. The watcher is idempotent, no-ops without a device, and dies with the
+ // session, so starting it early costs nothing.
+ if (pollsQuestions(session.engine)) questionWatcher.start(session.sessionId)
+ return true
+ }
+
+ /** One attach per session, a few sessions at a time, and a record of what is being read — see lib/attachTracker. */
+ const attaches = new AttachTracker<AgentEngine>({
+ concurrency,
+ onSlow: (session, elapsedMs) => console.warn(
+ `[agent] ${sid(session.agentId)} attach still running · engine=${session.engine} · session=${sid(session.sessionId)} · ${Math.round(elapsedMs / 1000)}s`,
+ ),
+ })
+ const attachSession = (
+ session: RegisteredSession,
+ reset = false,
+ replayCursorFromStart = false,
+ replayFromStart = false,
+ ): Promise<boolean> =>
+ attaches.attach(session, reset, async () => {
+ // A tail an attach holds (a Claude Code or Codex reset, see attachSessionNow) is released only
+ // here, after the whole attach — the new normalizer installed and any open turn said to be open —
+ // so delivery resumes into it, in order. Released on every exit, however the attach ends.
+ const handover = { hold: null as TailHold | null, next: null as number | null }
+ try {
+ return await attachSessionNow(session, reset, replayCursorFromStart, replayFromStart, handover)
+ } finally {
+ handover.hold?.release(handover.next)
+ }
+ })
+ return { attachSession, attaches, neverFoldedHistory, replayedFirstTurn }
+}
+
+export type Attach = ReturnType<typeof createAttach>
diff --git a/cli/src/core/transcripts/ingest.spec.ts b/cli/src/core/transcripts/ingest.spec.ts
new file mode 100644
index 000000000..c487aa512
--- /dev/null
+++ b/cli/src/core/transcripts/ingest.spec.ts
@@ -0,0 +1,174 @@
+import { EventEmitter } from 'node:events'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { AgyNormalizer } from '../../engines/agy/normalizer.js'
+import { AmpNormalizer } from '../../engines/amp/normalizer.js'
+import { CodexNormalizer } from '../../engines/codex/normalizer.js'
+import { CommandCodeNormalizer } from '../../engines/commandcode/normalizer.js'
+import { CopilotNormalizer } from '../../engines/copilot/normalizer.js'
+import { CursorNormalizer } from '../../engines/cursor/normalizer.js'
+import { GrokNormalizer } from '../../engines/grok/normalizer.js'
+import { MuseNormalizer } from '../../engines/muse/normalizer.js'
+import { PiNormalizer } from '../../engines/pi/normalizer.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { HistoryEvent, LineEvent, RewrittenEvent, Watcher } from '../../watcher/watcher.js'
+import { createIngest, type IngestDeps } from './ingest.js'
+import { createSessionNormalizers } from './normalizers.js'
+
+const CODEX_FAILED = JSON.stringify({ type: 'event_msg', payload: { type: 'task_complete', error: { message: 'rate limited' } } })
+const COMMANDCODE_FAILED = JSON.stringify({ type: 'message', message: { role: 'user', content: [{ type: 'text', text: 'Error: 500\nTrace ID: 932a' }] } })
+const CLAUDE_PROMPT = JSON.stringify({ type: 'user', message: { role: 'user', content: 'hello' } })
+
+function setup(engines: Record<string, string>, over: Partial<IngestDeps> = {}) {
+ const sessions = new Map(Object.entries(engines).map(([sessionId, engine]) =>
+ [sessionId, { agentId: `agent-${sessionId}`, sessionId, engine, transcriptPath: `/t/${sessionId}.jsonl` } as RegisteredSession]))
+ const normalizers = createSessionNormalizers()
+ const service = { needsTranscript: vi.fn(() => false), observeTranscript: vi.fn() }
+ const deps: IngestDeps = {
+ has: (sessionId) => sessions.has(sessionId),
+ bySession: (sessionId) => sessions.get(sessionId),
+ tokenUsage: { changed: vi.fn() },
+ device: () => service,
+ runtimeProfiles: { ingest: vi.fn() },
+ normalizers,
+ announceTurnAborted: vi.fn(),
+ emit: vi.fn(),
+ attachSession: vi.fn(async () => true),
+ ...over,
+ }
+ return { deps, sessions, normalizers, service, ingest: createIngest(deps) }
+}
+
+const line = (sessionId: string, engine: string, text = '{}'): LineEvent => ({ sessionId, engine, text } as LineEvent)
+
+describe('ingesting a transcript line', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ it('takes lines only for a registered session of the engine that wrote them', () => {
+ const { ingest, deps } = setup({ s1: 'claude', s2: 'codex' })
+ expect(ingest.ingestLine(line('nobody', 'claude'))).toBeNull()
+ expect(ingest.ingestLine(line('s1', 'codex'))).toBeNull()
+ const ghost = setup({}, { has: () => true })
+ expect(ghost.ingest.ingestLine(line('s9', 'claude'))).toBeNull()
+ expect(deps.tokenUsage.changed).not.toHaveBeenCalled()
+ })
+
+ it('counts tokens, shows the device its raw lines when it asks, and reads the runtime from each line', () => {
+ const { ingest, deps, service, sessions } = setup({ s1: 'claude' })
+ ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))
+ expect(deps.tokenUsage.changed).toHaveBeenCalledWith(sessions.get('s1'))
+ expect(service.observeTranscript).not.toHaveBeenCalled()
+ service.needsTranscript.mockReturnValue(true)
+ ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))
+ expect(service.observeTranscript).toHaveBeenCalledWith('agent-s1', 's1', 'claude', CLAUDE_PROMPT)
+ expect(deps.runtimeProfiles.ingest).toHaveBeenCalledWith(sessions.get('s1'), CLAUDE_PROMPT)
+ const none = setup({ s1: 'claude' }, { device: () => undefined })
+ expect(none.ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))).toEqual(expect.any(Array))
+ })
+
+ it('creates each file engine\'s normalizer on the session\'s first line, and keeps it', () => {
+ const engines = {
+ codex: CodexNormalizer, cursor: CursorNormalizer, muse: MuseNormalizer, amp: AmpNormalizer, grok: GrokNormalizer,
+ agy: AgyNormalizer, copilot: CopilotNormalizer, pi: PiNormalizer, commandcode: CommandCodeNormalizer,
+ } as const
+ const run = setup(Object.fromEntries(Object.keys(engines).map((engine) => [engine, engine])))
+ const maps = {
+ codex: run.normalizers.codexNormalizers, cursor: run.normalizers.cursorNormalizers, muse: run.normalizers.museNormalizers,
+ amp: run.normalizers.ampNormalizers, grok: run.normalizers.grokNormalizers, agy: run.normalizers.agyNormalizers,
+ copilot: run.normalizers.copilotNormalizers, pi: run.normalizers.piNormalizers, commandcode: run.normalizers.commandcodeNormalizers,
+ } as Record<keyof typeof engines, Map<string, unknown>>
+ for (const [engine, Normalizer] of Object.entries(engines) as Array<[keyof typeof engines, new (...args: never[]) => unknown]>) {
+ expect(run.ingest.ingestLine(line(engine, engine)), engine).toEqual(expect.any(Array))
+ const first = maps[engine].get(engine)
+ expect(first, engine).toBeInstanceOf(Normalizer)
+ run.ingest.ingestLine(line(engine, engine))
+ expect(maps[engine].get(engine), `${engine} keeps its normalizer`).toBe(first)
+ }
+ })
+
+ it('reads Claude Code and any other engine with the turn state, created once', () => {
+ const run = setup({ s1: 'claude', s2: 'terminal' })
+ const events = run.ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))!
+ expect(events.map((event) => event.type)).toContain('turn_started')
+ const state = run.normalizers.turnStates.get('s1')
+ run.ingest.ingestLine(line('s1', 'claude', '{}'))
+ expect(run.normalizers.turnStates.get('s1')).toBe(state)
+ run.ingest.ingestLine(line('s2', 'terminal', '{}'))
+ expect(run.normalizers.turnStates.has('s2')).toBe(true)
+ })
+
+ it('announces the reason a Codex or Command Code turn failed', () => {
+ const run = setup({ cx: 'codex', cc: 'commandcode' })
+ run.ingest.ingestLine(line('cx', 'codex', CODEX_FAILED))
+ run.ingest.ingestLine(line('cc', 'commandcode', COMMANDCODE_FAILED))
+ run.ingest.ingestLine(line('cx', 'codex', '{}'))
+ run.ingest.ingestLine(line('cc', 'commandcode', '{}'))
+ expect(vi.mocked(run.deps.announceTurnAborted).mock.calls).toEqual([
+ ['cx', 'codex', 'rate limited'],
+ ['cc', 'commandcode', 'Error: 500\nTrace ID: 932a', 'Error: 500'],
+ ])
+ })
+})
+
+describe('the watcher wiring', () => {
+ afterEach(() => vi.restoreAllMocks())
+
+ function wired(engines: Record<string, string>, over: Partial<IngestDeps> = {}) {
+ const run = setup(engines, over)
+ const watcher = new EventEmitter()
+ run.ingest.wireWatcher(watcher as unknown as Pick<Watcher, 'on'>)
+ return { ...run, watcher }
+ }
+
+ it('streams each live line, and contains a line that throws', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = wired({ s1: 'claude' })
+ run.watcher.emit('line', line('s1', 'claude', CLAUDE_PROMPT))
+ run.watcher.emit('line', line('nobody', 'claude', CLAUDE_PROMPT))
+ expect(vi.mocked(run.deps.emit).mock.calls).toHaveLength(1)
+ expect(vi.mocked(run.deps.emit).mock.calls[0][0]).toBe('s1')
+ vi.mocked(run.deps.runtimeProfiles.ingest).mockImplementationOnce(() => { throw new Error('bad line') })
+ run.watcher.emit('line', line('s1', 'claude', CLAUDE_PROMPT))
+ vi.mocked(run.deps.runtimeProfiles.ingest).mockImplementationOnce(() => { throw 'worse' })
+ run.watcher.emit('line', line('s1', 'claude', CLAUDE_PROMPT))
+ expect(error.mock.calls).toEqual([
+ ['[cli] line handler error (session s1):', 'bad line'],
+ ['[cli] line handler error (session s1):', 'worse'],
+ ])
+ })
+
+ it('emits a catch-up batch as one replay, and nothing when it holds no events', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = wired({ s1: 'claude' })
+ const batch = (lines: LineEvent[]): HistoryEvent => ({ sessionId: 's1', lines } as HistoryEvent)
+ run.watcher.emit('history', batch([line('s1', 'claude', CLAUDE_PROMPT), line('nobody', 'claude'), line('s1', 'claude', '{}')]))
+ run.watcher.emit('history', batch([line('nobody', 'claude')]))
+ expect(vi.mocked(run.deps.emit).mock.calls).toHaveLength(1)
+ expect(vi.mocked(run.deps.emit).mock.calls[0][2]).toEqual({ replay: true })
+ vi.mocked(run.deps.runtimeProfiles.ingest).mockImplementationOnce(() => { throw new Error('bad batch') })
+ run.watcher.emit('history', batch([line('s1', 'claude', CLAUDE_PROMPT)]))
+ vi.mocked(run.deps.runtimeProfiles.ingest).mockImplementationOnce(() => { throw 'worse' })
+ run.watcher.emit('history', batch([line('s1', 'claude', CLAUDE_PROMPT)]))
+ expect(error.mock.calls).toEqual([
+ ['[cli] history handler error (session s1):', 'bad batch'],
+ ['[cli] history handler error (session s1):', 'worse'],
+ ])
+ })
+
+ it('attaches a transcript rewritten in place again, from its end, and only the session\'s own', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = wired({ s1: 'claude' })
+ const rewritten = (sessionId: string, transcriptPath: string) => ({ sessionId, transcriptPath } as RewrittenEvent)
+ run.watcher.emit('rewritten', rewritten('nobody', '/t/nobody.jsonl'))
+ run.watcher.emit('rewritten', rewritten('s1', '/t/other.jsonl'))
+ expect(run.deps.attachSession).not.toHaveBeenCalled()
+ run.watcher.emit('rewritten', rewritten('s1', '/t/s1.jsonl'))
+ expect(run.deps.attachSession).toHaveBeenCalledWith(run.sessions.get('s1'), true)
+ expect(String(log.mock.calls[0][0])).toContain('transcript rewritten in place — attaching it again from its end')
+ vi.mocked(run.deps.attachSession).mockRejectedValueOnce(new Error('pane gone')).mockRejectedValueOnce('tmux down')
+ run.watcher.emit('rewritten', rewritten('s1', '/t/s1.jsonl'))
+ run.watcher.emit('rewritten', rewritten('s1', '/t/s1.jsonl'))
+ await new Promise((done) => setTimeout(done, 0))
+ expect(error.mock.calls.map((call) => call[1])).toEqual(['pane gone', 'tmux down'])
+ })
+})
diff --git a/cli/src/core/transcripts/ingest.ts b/cli/src/core/transcripts/ingest.ts
new file mode 100644
index 000000000..9e2732bb3
--- /dev/null
+++ b/cli/src/core/transcripts/ingest.ts
@@ -0,0 +1,163 @@
+/**
+ * Ingest: each transcript line the watcher delivers, through its engine's normalizer, into the funnel.
+ * Lines arrive live, or as a history batch (a catch-up, emitted as a replay); a transcript rewritten in
+ * place with too much history to replay is attached again from its end.
+ *
+ * The file engines' normalizers are created here lazily, on a session's first line; the database
+ * engines' readers never are (they are attached, not tailed).
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 9: docs/design/2026-10-03-harnessd.md).
+ */
+import { AgyNormalizer } from '../../engines/agy/normalizer.js'
+import { AmpNormalizer } from '../../engines/amp/normalizer.js'
+import { CodexNormalizer, codexTaskError } from '../../engines/codex/normalizer.js'
+import { codexSubagentResolverFor } from '../../engines/codex/subagent.js'
+import { CommandCodeNormalizer, commandCodeRunError, commandCodeRunErrorSummary } from '../../engines/commandcode/normalizer.js'
+import { CopilotNormalizer } from '../../engines/copilot/normalizer.js'
+import { CursorNormalizer } from '../../engines/cursor/normalizer.js'
+import { GrokNormalizer } from '../../engines/grok/normalizer.js'
+import { MuseNormalizer } from '../../engines/muse/normalizer.js'
+import { PiNormalizer } from '../../engines/pi/normalizer.js'
+import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'
+import { sid } from '../../lib/log.js'
+import { lineToEvents, newTurnState, type LiveEvent } from '../../lib/normalize.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'
+import type { HistoryEvent, LineEvent, RewrittenEvent, Watcher } from '../../watcher/watcher.js'
+import type { SessionNormalizers } from './normalizers.js'
+
+export interface IngestDeps {
+ has: (sessionId: string) => boolean
+ bySession: (sessionId: string) => RegisteredSession | undefined
+ tokenUsage: { changed(session: RegisteredSession): void }
+ /** The Harness device service, once it exists: some subscriptions read the raw transcript. */
+ device: () => Pick<AutonomousDeviceService, 'needsTranscript' | 'observeTranscript'> | undefined
+ runtimeProfiles: Pick<RuntimeProfileManager, 'ingest'>
+ normalizers: SessionNormalizers
+ announceTurnAborted: (sessionId: string, engine: string, message: string, deviceMessage?: string) => void
+ emit: (sessionId: string, events: LiveEvent[], opts?: { replay?: boolean }) => void
+ attachSession: (session: RegisteredSession, reset: boolean) => Promise<boolean>
+}
+
+export function createIngest({
+ has, bySession, tokenUsage, device, runtimeProfiles, normalizers, announceTurnAborted, emit, attachSession,
+}: IngestDeps) {
+ const {
+ turnStates, codexNormalizers, cursorNormalizers, museNormalizers, ampNormalizers, grokNormalizers, agyNormalizers,
+ copilotNormalizers, piNormalizers, commandcodeNormalizers,
+ } = normalizers
+ // JSONL watcher → normalize each appended line → stream up. ONE lineToEvents pass feeds BOTH
+ // audiences: web (send, ServerEvents) and device (mirror.ingest → curated commander_event cards).
+ /** One transcript line through its engine's normalizer. The events, not yet emitted — the two
+ * callers below differ only in what they know about the line's age. */
+ const ingestLine = (evt: LineEvent): ReturnType<CursorNormalizer['ingest']> | null => {
+ if (!has(evt.sessionId)) return null // scope to terminal-registered sessions
+ const session = bySession(evt.sessionId)
+ if (!session || session.engine !== evt.engine) return null
+ tokenUsage.changed(session)
+ const service = device()
+ if (service?.needsTranscript(session.agentId, evt.sessionId, session.engine)) {
+ service.observeTranscript(session.agentId, evt.sessionId, session.engine, evt.text)
+ }
+ runtimeProfiles.ingest(session, evt.text)
+ let events
+ if (session.engine === 'codex') {
+ let normalizer = codexNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome)); codexNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ // Codex rides its failure ON task_complete, so the turn closes by itself — but with no text and
+ // no reason, which reads as "the agent answered nothing". Announce the reason ahead of the
+ // turn_ended that `events` carries.
+ const taskError = codexTaskError(evt.text)
+ if (taskError !== null) announceTurnAborted(evt.sessionId, 'codex', taskError)
+ } else if (session.engine === 'cursor') {
+ let normalizer = cursorNormalizers.get(evt.sessionId)
+ if (!normalizer) {
+ normalizer = new CursorNormalizer('live', evt.sessionId)
+ cursorNormalizers.set(evt.sessionId, normalizer)
+ }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'muse') {
+ let normalizer = museNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new MuseNormalizer(); museNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'amp') {
+ let normalizer = ampNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new AmpNormalizer(); ampNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'grok') {
+ let normalizer = grokNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new GrokNormalizer(); grokNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'agy') {
+ let normalizer = agyNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new AgyNormalizer(); agyNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'copilot') {
+ let normalizer = copilotNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CopilotNormalizer(); copilotNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'pi') {
+ let normalizer = piNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new PiNormalizer('live'); piNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ } else if (session.engine === 'commandcode') {
+ let normalizer = commandcodeNormalizers.get(evt.sessionId)
+ if (!normalizer) { normalizer = new CommandCodeNormalizer('live'); commandcodeNormalizers.set(evt.sessionId, normalizer) }
+ events = normalizer.ingest(evt.text)
+ // Command Code fires no Stop hook for a failed turn: this record IS the notification. `ingest`
+ // already closed the turn (its turn_ended is in `events`, emitted just below) — announce the
+ // reason first so the web/device show the error ahead of the turn closing.
+ const runError = commandCodeRunError(evt.text)
+ if (runError !== null) {
+ announceTurnAborted(evt.sessionId, 'commandcode', runError, commandCodeRunErrorSummary(runError))
+ }
+ } else {
+ let st = turnStates.get(evt.sessionId)
+ if (!st) { st = newTurnState(); turnStates.set(evt.sessionId, st) }
+ events = lineToEvents(evt.text, st)
+ }
+ return events
+ }
+ /** Feed what the watcher delivers through `ingestLine` into the funnel. */
+ const wireWatcher = (watcher: Pick<Watcher, 'on'>): void => {
+ watcher.on('line', (evt: LineEvent) => {
+ // This runs from a void-discarded async read, so a throw here would be an unhandledRejection. A
+ // single malformed line must never take the daemon down — contain it per line and move on.
+ try {
+ const events = ingestLine(evt)
+ if (events) emit(evt.sessionId, events)
+ } catch (err) {
+ console.error(`[cli] line handler error (session ${evt.sessionId}):`, err instanceof Error ? err.message : err)
+ }
+ })
+ // A transcript catch-up is history, including an unfinished last turn.
+ // Its content still streams, but only fresh events or live inspection can
+ // establish Working; replay cannot create a new completion notification.
+ // A transcript rewritten in place with too much history to replay: its tail already starts at the new
+ // end, and the session is attached again, from that end, so its turn state is rebuilt from the file.
+ watcher.on('rewritten', (event: RewrittenEvent) => {
+ const session = bySession(event.sessionId)
+ if (!session || session.transcriptPath !== event.transcriptPath) return
+ console.log(`[watcher] ${sid(event.sessionId)} transcript rewritten in place — attaching it again from its end`)
+ void attachSession(session, true).catch((err) => console.error(`[cli] re-attach after rewrite failed (session ${sid(event.sessionId)}):`, err instanceof Error ? err.message : err))
+ })
+ watcher.on('history', (batch: HistoryEvent) => {
+ try {
+ type Events = ReturnType<CursorNormalizer['ingest']>
+ const all: Events = []
+ for (const evt of batch.lines) {
+ const events = ingestLine(evt)
+ if (events) all.push(...events)
+ }
+ if (!all.length) return
+ // Every line in this batch was already on disk. An unclosed last turn
+ // is not a fresh prompt; live runtime inspection can establish activity.
+ emit(batch.sessionId, all, { replay: true })
+ } catch (err) {
+ console.error(`[cli] history handler error (session ${batch.sessionId}):`, err instanceof Error ? err.message : err)
+ }
+ })
+ }
+ return { ingestLine, wireWatcher }
+}
diff --git a/cli/src/core/turns/agyBackstop.spec.ts b/cli/src/core/turns/agyBackstop.spec.ts
new file mode 100644
index 000000000..1bc6b1236
--- /dev/null
+++ b/cli/src/core/turns/agyBackstop.spec.ts
@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { AgyNormalizer } from '../../engines/agy/normalizer.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { createAgyBackstop, type AgyBackstopDeps } from './agyBackstop.js'
+
+const IDLE = 'done.\n\n ? for shortcuts'
+const BUSY = 'thinking…\n\n esc to cancel'
+
+function setup(over: Partial<AgyBackstopDeps> = {}) {
+ const normalizer = { turnOpen: true, closeTurn: vi.fn(() => { normalizer.turnOpen = false; return [{ type: 'turn_ended', payload: {} }] }) }
+ const deps: AgyBackstopDeps = {
+ agyNormalizers: new Map([['s1', normalizer as unknown as AgyNormalizer]]),
+ bySession: (sessionId) => sessionId === 's1' ? ({ agentId: 'a1', sessionId: 's1' } as RegisteredSession) : undefined,
+ captureTerminal: vi.fn(async () => IDLE),
+ drain: vi.fn(async () => {}),
+ emit: vi.fn(),
+ ...over,
+ }
+ return { deps, normalizer, backstop: createAgyBackstop(deps) }
+}
+
+describe('the agy idle backstop', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+
+ it('closes a turn whose pane is idle 15 s after the Stop that left it open', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const { deps, backstop } = setup()
+ backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(14_999)
+ expect(deps.captureTerminal).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(deps.captureTerminal).toHaveBeenCalledWith('a1', 60)
+ expect(deps.drain).toHaveBeenCalledWith('s1')
+ expect(deps.emit).toHaveBeenCalledWith('s1', [{ type: 'turn_ended', payload: {} }])
+ expect(String(log.mock.calls[0][0])).toContain('closed by the agy idle backstop')
+ })
+
+ it('keeps watching a busy or unreadable pane, up to forty checks, then stops', async () => {
+ const { deps, backstop } = setup()
+ vi.mocked(deps.captureTerminal).mockResolvedValueOnce(null).mockResolvedValue(BUSY)
+ backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(15_000 * 45)
+ expect(deps.captureTerminal).toHaveBeenCalledTimes(40)
+ expect(deps.emit).not.toHaveBeenCalled()
+ })
+
+ it('leaves alone a turn that closed, a session that is gone, and a turn the drain closed', async () => {
+ const closed = setup()
+ closed.normalizer.turnOpen = false
+ closed.backstop.armAgyIdleWatch('s1')
+ const gone = setup({ bySession: () => undefined })
+ gone.backstop.armAgyIdleWatch('s1')
+ const none = setup()
+ none.backstop.armAgyIdleWatch('no-normalizer')
+ const drained = setup()
+ vi.mocked(drained.deps.drain).mockImplementation(async () => { drained.normalizer.turnOpen = false })
+ drained.backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(closed.deps.captureTerminal).not.toHaveBeenCalled()
+ expect(gone.deps.captureTerminal).not.toHaveBeenCalled()
+ expect(none.deps.captureTerminal).not.toHaveBeenCalled()
+ expect(drained.deps.emit).not.toHaveBeenCalled()
+ })
+
+ it('counts a run of waiting Stops toward the same forty checks', async () => {
+ const { deps, backstop } = setup()
+ for (let stop = 0; stop < 41; stop++) backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(deps.captureTerminal).not.toHaveBeenCalled()
+ })
+
+ it('is cleared by a real Stop, and a new arm replaces the one waiting', async () => {
+ const { deps, backstop } = setup()
+ backstop.armAgyIdleWatch('s1')
+ backstop.clearAgyIdleWatch('s1')
+ backstop.clearAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(deps.captureTerminal).not.toHaveBeenCalled()
+ backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(10_000)
+ backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(deps.captureTerminal).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(deps.captureTerminal).toHaveBeenCalledTimes(1)
+ })
+
+ it('reports a check that fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { deps, backstop } = setup()
+ vi.mocked(deps.captureTerminal).mockRejectedValueOnce(new Error('pane gone')).mockRejectedValueOnce('tmux down')
+ backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(15_000)
+ backstop.armAgyIdleWatch('s1')
+ await vi.advanceTimersByTimeAsync(15_000)
+ expect(error.mock.calls).toEqual([['[agy] idle backstop failed:', 'pane gone'], ['[agy] idle backstop failed:', 'tmux down']])
+ })
+})
diff --git a/cli/src/core/turns/agyBackstop.ts b/cli/src/core/turns/agyBackstop.ts
new file mode 100644
index 000000000..29d776d2e
--- /dev/null
+++ b/cli/src/core/turns/agyBackstop.ts
@@ -0,0 +1,68 @@
+/**
+ * agy only: close a turn whose final `Stop` never came.
+ *
+ * agy reports `fullyIdle: false` when it pauses for sub-agents, and normally sends one more Stop with
+ * `fullyIdle: true` once they report — measured, and that is the path a healthy turn takes. But one
+ * measured run completed its sub-agents, wrote its summary, and sent nothing further; the turn stayed
+ * open with no recap. The pane is the only other place the answer exists (`? for shortcuts` idle vs
+ * `esc to cancel` busy), so a waiting Stop arms a bounded poll of it.
+ *
+ * Bounded on purpose: it stops after AGY_IDLE_WATCH_MAX checks (~10 min) rather than polling a pane
+ * forever, and any real Stop clears it first.
+ *
+ * Moved verbatim out of `runForeground` (the core boundary, step 9: docs/design/2026-10-03-harnessd.md).
+ */
+import type { AgyNormalizer } from '../../engines/agy/normalizer.js'
+import { agyPaneIdle } from '../../engines/agy/runtimeProfile.js'
+import { sid } from '../../lib/log.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+
+export interface AgyBackstopDeps {
+ agyNormalizers: Map<string, AgyNormalizer>
+ bySession: (sessionId: string) => RegisteredSession | undefined
+ captureTerminal: (target: string, historyLines?: number) => Promise<string | null>
+ /** Read what the transcript has that the tail has not delivered yet (Watcher.pollSession). */
+ drain: (sessionId: string) => Promise<void>
+ emit: (sessionId: string, events: LiveEvent[]) => void
+}
+
+export function createAgyBackstop({ agyNormalizers, bySession, captureTerminal, drain, emit }: AgyBackstopDeps) {
+ const AGY_IDLE_WATCH_MS = 15_000
+ const AGY_IDLE_WATCH_MAX = 40
+ const agyIdleWatch = new Map<string, { timer: NodeJS.Timeout; checks: number }>()
+
+ const clearAgyIdleWatch = (sessionId: string): void => {
+ const watch = agyIdleWatch.get(sessionId)
+ if (!watch) return
+ clearTimeout(watch.timer)
+ agyIdleWatch.delete(sessionId)
+ }
+
+ // `checks` carries the count into the re-arm a check makes: the check deletes its own entry first,
+ // so reading the count back from the map started it over every time and the poll never stopped.
+ const armAgyIdleWatch = (sessionId: string, checks = agyIdleWatch.get(sessionId)?.checks ?? 0): void => {
+ clearAgyIdleWatch(sessionId)
+ if (checks >= AGY_IDLE_WATCH_MAX) return
+ const timer = setTimeout(() => {
+ void (async () => {
+ agyIdleWatch.delete(sessionId)
+ const normalizer = agyNormalizers.get(sessionId)
+ if (!normalizer?.turnOpen) return
+ const entry = bySession(sessionId)
+ if (!entry) return
+ const capture = await captureTerminal(entry.agentId, 60)
+ if (!capture || !agyPaneIdle(capture)) { armAgyIdleWatch(sessionId, checks + 1); return }
+ await drain(sessionId)
+ if (!normalizer.turnOpen) return
+ console.log(`[turn] ${sid(sessionId)} closed by the agy idle backstop · no final Stop arrived`)
+ emit(sessionId, normalizer.closeTurn())
+ })().catch((err) => {
+ console.error('[agy] idle backstop failed:', err instanceof Error ? err.message : err)
+ })
+ }, AGY_IDLE_WATCH_MS)
+ timer.unref?.()
+ agyIdleWatch.set(sessionId, { timer, checks: checks + 1 })
+ }
+ return { clearAgyIdleWatch, armAgyIdleWatch }
+}
diff --git a/cli/src/core/turns/turnHooks.spec.ts b/cli/src/core/turns/turnHooks.spec.ts
new file mode 100644
index 000000000..91c91511e
--- /dev/null
+++ b/cli/src/core/turns/turnHooks.spec.ts
@@ -0,0 +1,302 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'
+import type { TurnState } from '../../lib/normalize.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { createSessionNormalizers } from '../transcripts/normalizers.js'
+import { createTurnHooks, STOP_HOOK_GRACE_MS, type TurnHookDeps } from './turnHooks.js'
+
+vi.mock('../../engines/cursor/pendingTasks.js', () => ({ removeCursorPendingTasks: vi.fn(async () => {}) }))
+
+const END = [{ type: 'turn_ended', payload: {} }]
+const ABORT = [{ type: 'turn_ended', payload: { aborted: true } }]
+
+/** A normalizer or reader with the turn calls the hooks make. */
+const engineState = (turnOpen = true) => {
+ const state = {
+ turnOpen,
+ openTurn: vi.fn(() => [{ type: 'turn_started', payload: { userMessage: '' } }]),
+ closeTurn: vi.fn(() => { state.turnOpen = false; return END }),
+ abortTurn: vi.fn(() => { state.turnOpen = false; return ABORT }),
+ }
+ return state
+}
+
+function setup(engine: string, over: Partial<TurnHookDeps> = {}) {
+ const normalizers = createSessionNormalizers()
+ const deps: TurnHookDeps = {
+ resolve: (id) => id === 's1' ? ({ agentId: 'a1', sessionId: 's1', engine } as RegisteredSession) : undefined,
+ normalizers,
+ emit: vi.fn(),
+ drain: vi.fn(async () => {}),
+ onCursorTaskStart: vi.fn(),
+ cursorTaskHooks: { wait: vi.fn(async () => {}) },
+ cursorSubagents: { closeParent: vi.fn() },
+ announceTurnAborted: vi.fn(),
+ armAgyIdleWatch: vi.fn(),
+ clearAgyIdleWatch: vi.fn(),
+ mirror: { noteEngineStopped: vi.fn() },
+ dataDir: '/data',
+ ...over,
+ }
+ return { deps, normalizers, hooks: createTurnHooks(deps) }
+}
+
+const put = (map: Map<string, unknown>, state: unknown) => map.set('s1', state)
+
+describe('turn hooks', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+
+ it('opens Command Code\'s turn on its first tool call, and nothing else\'s', () => {
+ const cc = setup('commandcode')
+ const normalizer = engineState(false)
+ cc.hooks.onTurnStart({ sessionId: 's1' })
+ put(cc.normalizers.commandcodeNormalizers, normalizer)
+ cc.hooks.onTurnStart({ sessionId: 's1' })
+ cc.hooks.onTurnStart({ sessionId: 'nobody' })
+ setup('claude').hooks.onTurnStart({ sessionId: 's1' })
+ expect(cc.deps.emit).toHaveBeenCalledTimes(1)
+ expect(cc.deps.emit).toHaveBeenCalledWith('s1', normalizer.openTurn.mock.results[0].value)
+ })
+
+ it('registers a Cursor sub-agent when its Task tool starts', () => {
+ const { deps, hooks } = setup('cursor')
+ hooks.onToolStart({ sessionId: 's1', toolUseId: 't1', toolName: 'Task', input: { prompt: 'x' } })
+ hooks.onToolStart({ sessionId: 's1', toolUseId: 't2', toolName: 'Read', input: {} })
+ expect(deps.onCursorTaskStart).toHaveBeenCalledTimes(1)
+ expect(deps.onCursorTaskStart).toHaveBeenCalledWith('s1', 't1', { prompt: 'x' })
+ })
+
+ it('does nothing for a Stop from a session it does not know, or an engine with no Stop rule', async () => {
+ const unknown = setup('claude')
+ unknown.hooks.onTurnStop({ sessionId: 'nobody' })
+ const pi = setup('pi')
+ pi.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.runAllTimersAsync()
+ expect(unknown.deps.drain).not.toHaveBeenCalled()
+ expect(pi.deps.drain).not.toHaveBeenCalled()
+ })
+
+ describe('Claude Code', () => {
+ it('lets the transcript close the turn when it can, and closes a wedged one after the grace', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup('claude')
+ const state = { turnOpen: true, pendingTools: new Map([['t', {}]]) } as unknown as TurnState
+ run.normalizers.turnStates.set('s1', state)
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(run.deps.mirror.noteEngineStopped).toHaveBeenCalledWith('s1')
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(state.turnOpen).toBe(false)
+ expect(state.pendingTools.size).toBe(0)
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
+ expect(String(log.mock.calls[0][0])).toContain('force-closed by StopFailure hook')
+ // Closed by the transcript before the grace ran out, or never open: nothing more to do.
+ state.turnOpen = true
+ vi.mocked(run.deps.drain).mockImplementation(async () => { if (vi.mocked(run.deps.drain).mock.calls.length > 3) state.turnOpen = false })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(run.deps.emit).toHaveBeenCalledTimes(1)
+ })
+
+ it('says Stop for a clean stop', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup('claude')
+ run.normalizers.turnStates.set('s1', { turnOpen: true, pendingTools: new Map() } as unknown as TurnState)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(String(log.mock.calls[0][0])).toContain('force-closed by Stop hook')
+ })
+ })
+
+ describe('engines whose Stop hook is their turn boundary', () => {
+ for (const engine of ['commandcode', 'copilot', 'agy'] as const) {
+ const map = (run: ReturnType<typeof setup>) => engine === 'commandcode' ? run.normalizers.commandcodeNormalizers
+ : engine === 'copilot' ? run.normalizers.copilotNormalizers : run.normalizers.agyNormalizers
+
+ it(`${engine}: drains, waits the grace, then closes what is still open`, async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup(engine)
+ const normalizer = engineState()
+ put(map(run), normalizer)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS - 1)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(run.deps.drain).toHaveBeenCalledTimes(2)
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
+ expect(log).toHaveBeenCalledTimes(1)
+ })
+
+ it(`${engine}: leaves a turn the transcript closed, before the grace or after it`, async () => {
+ const run = setup(engine)
+ run.hooks.onTurnStop({ sessionId: 's1' }) // no normalizer at all
+ const normalizer = engineState(false)
+ put(map(run), normalizer)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ normalizer.turnOpen = true
+ vi.mocked(run.deps.drain).mockImplementationOnce(async () => {}).mockImplementationOnce(async () => { normalizer.turnOpen = false })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ })
+
+ it(`${engine}: reports a Stop hook that fails`, async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = setup(engine)
+ put(map(run), engineState())
+ vi.mocked(run.deps.drain).mockRejectedValueOnce(new Error('tail gone')).mockRejectedValueOnce('worse')
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(error.mock.calls.map((call) => call[1])).toEqual(['tail gone', 'worse'])
+ })
+ }
+
+ for (const engine of ['copilot', 'agy'] as const) {
+ it(`${engine}: says why a turn ended early, and aborts it`, async () => {
+ const run = setup(engine)
+ const normalizer = engineState()
+ put(engine === 'copilot' ? run.normalizers.copilotNormalizers : run.normalizers.agyNormalizers, normalizer)
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(run.deps.announceTurnAborted).toHaveBeenCalledWith('s1', engine, expect.stringContaining('ended the turn early'))
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', ABORT)
+ })
+ }
+
+ it('agy: a Stop that waits for sub-agents arms the backstop and closes nothing; any other clears it', async () => {
+ const run = setup('agy')
+ put(run.normalizers.agyNormalizers, engineState())
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'waiting' })
+ expect(run.deps.armAgyIdleWatch).toHaveBeenCalledWith('s1')
+ expect(run.deps.drain).not.toHaveBeenCalled()
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ expect(run.deps.clearAgyIdleWatch).toHaveBeenCalledWith('s1')
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
+ })
+ })
+
+ describe('Devin', () => {
+ it('closes an open turn after the grace, from its reader', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup('devin')
+ const reader = engineState()
+ put(run.normalizers.devinReaders, reader)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(reader.closeTurn).toHaveBeenCalled()
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
+ expect(String(log.mock.calls[0][0])).toContain('force-closed by Stop hook')
+ })
+
+ it('leaves a turn that is closed, or closes during the grace, and survives no reader', async () => {
+ const run = setup('devin')
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ const reader = engineState(false)
+ put(run.normalizers.devinReaders, reader)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ reader.turnOpen = true
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ reader.turnOpen = false
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ })
+
+ it('reports a Stop hook that fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = setup('devin')
+ const broken = { get turnOpen(): boolean { throw new Error('store gone') } }
+ put(run.normalizers.devinReaders, broken)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ const worse = { get turnOpen(): boolean { throw 'worse' } }
+ put(run.normalizers.devinReaders, worse)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(error.mock.calls).toEqual([['[hooks] devin stop hook failed:', 'store gone'], ['[hooks] devin stop hook failed:', 'worse']])
+ })
+ })
+
+ describe('Grok', () => {
+ it('announces and aborts a turn that ended in error, and leaves a clean stop to the transcript', async () => {
+ const run = setup('grok')
+ const normalizer = engineState()
+ put(run.normalizers.grokNormalizers, normalizer)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(run.deps.announceTurnAborted).toHaveBeenCalledWith('s1', 'grok', 'Grok ended the turn with an error')
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', ABORT)
+ run.normalizers.grokNormalizers.delete('s1')
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(run.deps.emit).toHaveBeenLastCalledWith('s1', [])
+ })
+
+ it('reports a StopFailure hook that fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = setup('grok')
+ vi.mocked(run.deps.drain).mockRejectedValueOnce(new Error('tail gone')).mockRejectedValueOnce('worse')
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(error.mock.calls).toEqual([['[hooks] grok StopFailure hook failed:', 'tail gone'], ['[hooks] grok StopFailure hook failed:', 'worse']])
+ })
+ })
+
+ describe('Cursor', () => {
+ it('closes the turn once its sub-agent hooks and transcript are in, then clears its pending tasks', async () => {
+ const run = setup('cursor')
+ const normalizer = engineState()
+ put(run.normalizers.cursorNormalizers, normalizer)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(run.deps.cursorTaskHooks.wait).toHaveBeenCalledWith('s1')
+ expect(run.deps.cursorSubagents.closeParent).toHaveBeenCalledWith('s1', false)
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
+ expect(run.deps.announceTurnAborted).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(2_500)
+ expect(removeCursorPendingTasks).toHaveBeenCalledWith('/data', 's1')
+ })
+
+ it('announces a turn that failed before writing anything, and leaves a session with no normalizer', async () => {
+ const run = setup('cursor')
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ const silent = { ...engineState(false), closeTurn: vi.fn(() => []) }
+ put(run.normalizers.cursorNormalizers, silent)
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(run.deps.cursorSubagents.closeParent).toHaveBeenCalledWith('s1', true)
+ expect(run.deps.announceTurnAborted).toHaveBeenCalledWith('s1', 'cursor', expect.stringContaining('before producing any output'))
+ })
+
+ it('reports a stop hook that fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = setup('cursor')
+ vi.mocked(run.deps.cursorTaskHooks.wait).mockRejectedValueOnce(new Error('queue gone')).mockRejectedValueOnce('worse')
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(error.mock.calls).toEqual([['[cursor] stop hook failed:', 'queue gone'], ['[cursor] stop hook failed:', 'worse']])
+ })
+ })
+
+ it('Claude Code: reports a stop hook that fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const run = setup('claude')
+ vi.mocked(run.deps.drain).mockRejectedValueOnce(new Error('tail gone')).mockRejectedValueOnce('worse')
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(error.mock.calls).toEqual([['[hooks] claude stop hook failed:', 'tail gone'], ['[hooks] claude stop hook failed:', 'worse']])
+ })
+})
diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.ts
new file mode 100644
index 000000000..05666d160
--- /dev/null
+++ b/cli/src/core/turns/turnHooks.ts
@@ -0,0 +1,218 @@
+/**
+ * Turn hooks: what the engines' own hooks say about a turn. Command Code's PreToolUse opens its turn;
+ * Cursor's Task tool start registers a sub-agent; and the Stop hooks close turns the transcript alone
+ * would leave open: each engine drains what is unread first, waits a grace, and closes only what is
+ * still open — or, for an error, announces why.
+ *
+ * Moved verbatim out of the hook server's options in `runForeground` (the core boundary, step 9:
+ * docs/design/2026-10-03-harnessd.md).
+ */
+import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'
+import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
+import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'
+import type { CommanderMirror } from '../../lib/commander.js'
+import { sid } from '../../lib/log.js'
+import type { LiveEvent } from '../../lib/normalize.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { SessionNormalizers } from '../transcripts/normalizers.js'
+
+// Claude's Stop hook fires when the agent finishes, but the transcript can lag a moment behind
+// (docs: "the transcript file may lag behind the in-memory conversation"). Acting immediately races
+// that flush → an empty recap + a premature close. So the Stop hook is a DELAYED fallback: poll, and
+// only if the turn is still open after this grace + a re-poll do we force-close (by then the assistant
+// text is on disk, so the natural close usually wins and the recap isn't empty).
+export const STOP_HOOK_GRACE_MS = 1_500
+
+export interface TurnHookDeps {
+ resolve: (id: string) => RegisteredSession | undefined
+ normalizers: SessionNormalizers
+ emit: (sessionId: string, events: LiveEvent[]) => void
+ /** Read what the transcript has that the tail has not delivered yet (Watcher.pollSession). */
+ drain: (sessionId: string) => Promise<void>
+ onCursorTaskStart: (sessionId: string, toolUseId: string, toolInput: unknown) => void
+ cursorTaskHooks: Pick<CursorTaskHookQueue, 'wait'>
+ cursorSubagents: Pick<CursorSubagentManager, 'closeParent'>
+ announceTurnAborted: (sessionId: string, engine: string, message: string) => void
+ armAgyIdleWatch: (sessionId: string) => void
+ clearAgyIdleWatch: (sessionId: string) => void
+ mirror: Pick<CommanderMirror, 'noteEngineStopped'>
+ dataDir: string
+}
+
+export function createTurnHooks({
+ resolve, normalizers, emit, drain, onCursorTaskStart, cursorTaskHooks, cursorSubagents, announceTurnAborted,
+ armAgyIdleWatch, clearAgyIdleWatch, mirror, dataDir,
+}: TurnHookDeps) {
+ const { turnStates, commandcodeNormalizers, cursorNormalizers, devinReaders, copilotNormalizers, agyNormalizers, grokNormalizers } = normalizers
+ // Command Code's PreToolUse — the one live "a turn is running" signal this engine has. Without it the
+ // adapter only learned of a turn from Stop, and emitted turn_started+turn_ended in the same
+ // millisecond, so the device tile jumped from idle straight to the recap with no working state.
+ const onTurnStart = ({ sessionId }: { sessionId: string }): void => {
+ const session = resolve(sessionId)
+ if (!session || session.engine !== 'commandcode') return
+ const normalizer = commandcodeNormalizers.get(sessionId)
+ if (!normalizer) return
+ emit(sessionId, normalizer.openTurn()) // no-op after the turn's first tool call
+ }
+ const onToolStart = ({ sessionId, toolUseId, toolName, input: toolInput }: { sessionId: string; toolUseId: string; toolName: string; input: unknown }): void => {
+ if (toolName === 'Task') onCursorTaskStart(sessionId, toolUseId, toolInput)
+ }
+ const onTurnStop = ({ sessionId, status }: { sessionId: string; status?: string }): void => {
+ const session = resolve(sessionId)
+ if (!session) return
+ if (session.engine === 'cursor') {
+ void (async () => {
+ await cursorTaskHooks.wait(sessionId)
+ await drain(sessionId)
+ const normalizer = cursorNormalizers.get(sessionId)
+ if (!normalizer) return
+ cursorSubagents.closeParent(sessionId, status === 'error')
+ const closing = normalizer.closeTurn()
+ emit(sessionId, closing)
+ // Cursor can fail a turn BEFORE it writes anything to the transcript — observed as a Stop hook
+ // with status=error 2.4s after beforeSubmitPrompt, with no transcript file discovered and no
+ // rows to read. The normalizer never opened a turn, so closeTurn() returns nothing, so nothing
+ // reaches the device: the tile just sits on the previous recap forever while the user waits.
+ //
+ // Every other engine already routes its failures through announceTurnAborted (codex, devin,
+ // commandcode); cursor was the one that stayed silent. Announce only when the close produced no
+ // events — if there WAS output, the `done` event above already tells the device the turn ended.
+ if (status === 'error' && closing.length === 0) {
+ announceTurnAborted(sessionId, 'cursor', 'Cursor ended the turn with an error before producing any output')
+ }
+ setTimeout(() => void removeCursorPendingTasks(dataDir, sessionId), 2_500)
+ })().catch((err) => {
+ console.error('[cursor] stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ // claude: authoritative turn-close from the Stop/StopFailure hook. Drain any un-read JSONL FIRST
+ // (may emit the real turn_ended → st.turnOpen already false); only force-close if still open. A
+ // later real end_turn line is then a no-op (lineToEvents guards on state.turnOpen). This closes
+ // the B1/B2 cases (max_tokens/refusal/API-error/wedged tool) the JSONL parse would otherwise miss.
+ // Command Code has no UserPromptSubmit and commits records per turn, so Stop is its authoritative
+ // close: drain the transcript first (the natural close usually wins), then force-close what's left.
+ if (session.engine === 'commandcode') {
+ void (async () => {
+ await drain(sessionId)
+ const normalizer = commandcodeNormalizers.get(sessionId)
+ if (!normalizer?.turnOpen) return
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ await drain(sessionId)
+ if (!normalizer.turnOpen) return
+ normalizer.closeTurn()
+ console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
+ emit(sessionId, [{ type: 'turn_ended', payload: {} }])
+ })().catch((err) => {
+ console.error('[hooks] commandcode stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ // Devin: same deal, except the un-read history is in SQLite rather than a file, so the drain is the
+ // reader's own poll. Its rows only land once the model round-trip commits, so the grace matters.
+ if (session.engine === 'devin') {
+ void (async () => {
+ const reader = devinReaders.get(sessionId)
+ if (!reader?.turnOpen) return
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ if (!reader.turnOpen) return
+ reader.closeTurn()
+ console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
+ emit(sessionId, [{ type: 'turn_ended', payload: {} }])
+ })().catch((err) => {
+ console.error('[hooks] devin stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ // Copilot's agentStop hook is the turn boundary: its own `assistant.turn_end` records mark model
+ // round-trips, several per exchange. Drain first so the closing text is on the wire, then close.
+ if (session.engine === 'copilot') {
+ void (async () => {
+ await drain(sessionId)
+ const normalizer = copilotNormalizers.get(sessionId)
+ if (!normalizer?.turnOpen) return
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ await drain(sessionId)
+ if (!normalizer.turnOpen) return
+ if (status === 'error') {
+ announceTurnAborted(sessionId, 'copilot', 'Copilot ended the turn early')
+ emit(sessionId, normalizer.abortTurn())
+ return
+ }
+ console.log(`[turn] ${sid(sessionId)} closed by copilot agentStop hook (after grace)`)
+ emit(sessionId, normalizer.closeTurn())
+ })().catch((err) => {
+ console.error('[hooks] copilot stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ // agy's Stop hook is the ONLY turn boundary it has. Nothing in the transcript says a turn ended:
+ // a backgrounded step is written `status: RUNNING` and, the file being append-only, stays that way
+ // forever. Drain first so the closing prose is on the wire before turn_ended, then force-close.
+ if (session.engine === 'agy') {
+ // `waiting` = agy's loop stopped only because it is standing by for its sub-agents. The turn is
+ // NOT over, so nothing closes here — but the run that proved this necessary also finished its
+ // sub-agents and then never sent another Stop, so a backstop watches the pane instead.
+ if (status === 'waiting') {
+ armAgyIdleWatch(sessionId)
+ return
+ }
+ clearAgyIdleWatch(sessionId)
+ void (async () => {
+ await drain(sessionId)
+ const normalizer = agyNormalizers.get(sessionId)
+ if (!normalizer?.turnOpen) return
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ await drain(sessionId)
+ if (!normalizer.turnOpen) return
+ if (status === 'error') {
+ announceTurnAborted(sessionId, 'agy', 'agy ended the turn early')
+ emit(sessionId, normalizer.abortTurn())
+ return
+ }
+ console.log(`[turn] ${sid(sessionId)} closed by agy Stop hook (after grace)`)
+ emit(sessionId, normalizer.closeTurn())
+ })().catch((err) => {
+ console.error('[hooks] agy stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ if (session.engine === 'grok') {
+ void (async () => {
+ await drain(sessionId)
+ const normalizer = grokNormalizers.get(sessionId)
+ if (status === 'error') {
+ announceTurnAborted(sessionId, 'grok', 'Grok ended the turn with an error')
+ emit(sessionId, normalizer?.abortTurn() ?? [])
+ }
+ })().catch((err) => {
+ console.error('[hooks] grok StopFailure hook failed:', err instanceof Error ? err.message : err)
+ })
+ return
+ }
+ if (session.engine !== 'claude') return
+ void (async () => {
+ await drain(sessionId)
+ // A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is
+ // HOLDING a turn-end for finished async sub-agents, this is what tells it the wrap-up message is
+ // on disk — without it the recap fires on its settle timer and can beat claude's closing summary
+ // to the punch (measured: recap at 10:18:41, wrap-up written at 10:18:44).
+ mirror.noteEngineStopped(sessionId)
+ if (!turnStates.get(sessionId)?.turnOpen) return // natural JSONL close already won → nothing to do
+ // Still open: the transcript may just be lagging the Stop hook. Wait, re-poll, and only force-close
+ // if it STILL hasn't closed — a genuinely wedged turn, whose assistant text is on disk by now.
+ await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ await drain(sessionId)
+ const st = turnStates.get(sessionId)
+ if (st?.turnOpen) {
+ st.turnOpen = false
+ st.pendingTools.clear()
+ console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)
+ emit(sessionId, [{ type: 'turn_ended', payload: {} }])
+ }
+ })().catch((err) => {
+ console.error('[hooks] claude stop hook failed:', err instanceof Error ? err.message : err)
+ })
+ }
+ return { onTurnStart, onToolStart, onTurnStop }
+}