The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Read Claude Code and Codex transcripts from the end when attaching (#705)
Deea715126159c9
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 8e62ab0bd..cba739d21 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -170,7 +170,7 @@ import {type TerminalRuntimeRef,type TmuxRuntimeRef,} from './lib/terminalTypes.js'-import { Watcher, type HistoryEvent, type LineEvent } from './watcher/watcher.js'+import { Watcher, type HistoryEvent, type LineEvent, type TailHold } from './watcher/watcher.js'import { chooseHookAgent, startHookServer } from './hookServer.js'import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'import { legacyDaemonStatus, localDaemonStatus, saveDaemonPort } from './lib/daemonEndpoint.js'@@ -186,7 +186,9 @@ import { WindowVisit } from './cable/windowVisit.js'import { WindowForm } from './cable/windowForm.js'import { RemoteRelayPool } from './lib/remoteRelay.js'import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'-import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, type LiveEvent, type TurnState } from './lib/normalize.js'+import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, selectClaudeRecapLine, TranscriptFold, type LiveEvent, type TurnState } from './lib/normalize.js'+import { attachTranscript, claudeAttachRules, codexAttachRules, type AttachRead } from './lib/attachTranscript.js'+import { tailFileUntil } from './lib/transcriptTail.js'import { AskQuestionController, parseEngineQuestionPane, pollsQuestions, QuestionWatcher } from './lib/askQuestion.js'import { teamWriteHold } from './teams/preflight.js'import { TeamError } from './teams/model.js'@@ -269,7 +271,7 @@ import { SessionInputController } from './lib/sessionInput.js'import { DeviceResultJournal } from './lib/autonomous-device/resultJournal.js'import { AutonomousDeviceInput, isDeviceInputBoundary } from './lib/autonomous-device/input.js'import { adaptSlashCommand } from './lib/goalCommand.js'-import { RuntimeProfileManager, parseRuntimeProfile } from './lib/runtimeProfile.js'+import { RuntimeProfileManager, parseRuntimeProfile, type RuntimeField } from './lib/runtimeProfile.js'import { RuntimeProfileController, inspectRuntimePane } from './lib/runtimeProfileController.js'import { deviceErrorText } from './lib/deviceErrors.js'import { correlateAgentEvent, turnHeartbeatFrame } from './lib/agentEvent.js'@@ -2388,6 +2390,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {* 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 falseif (!reset && (@@ -2417,7 +2422,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.log(`[agent] ${sid(session.agentId)} re-attached · engine=${session.engine} · terminal=${primaryTerminalLabel(session)} · session=${sid(session.sessionId)}`)return true}- const lines = session.transcriptPath ? await tailFile(session.transcriptPath, Infinity) : []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@@ -2432,15 +2436,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {|| (session.engine === 'cursor' && replayCursorFromStart)const historyEvents: LiveEvent[] = []let historyTurnOpen = false- if (autonomousDeviceService?.needsTranscript(session.agentId, session.sessionId, session.engine)) {- for (const line of lines) autonomousDeviceService.observeTranscript(session.agentId, session.sessionId, session.engine, line)- }- runtimeProfiles.hydrate(session, lines)- await runtimeProfiles.ingestConfig(session, true)+ 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 fold = (ingest: (line: string) => LiveEvent[], turnOpenAfter: () => boolean): boolean => {- const out = foldTranscript(ingest, lines, turnOpenAfter, { live: replayLive })+ 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@@ -2449,11 +2450,74 @@ async function runForeground(session: AuthSession | null): Promise<void> {for (const event of out.live) initialEvents.push(event)return out.turnOpen}- if (session.engine === 'codex') {- const normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome))+ // 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.- historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)- codexNormalizers.set(session.sessionId, normalizer)+ 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)@@ -2574,8 +2638,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)commandcodeNormalizers.set(session.sessionId, normalizer)} else {- const state = newTurnState()- historyTurnOpen = fold((line) => lineToEvents(line, state), () => state.turnOpen)+ const state = claudeState ?? newTurnState()+ if (!fromEnd) historyTurnOpen = fold((line) => lineToEvents(line, state), () => state.turnOpen)turnStates.set(session.sessionId, state)}if (session.transcriptPath) {@@ -2584,8 +2648,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// 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.- await watcher.addSession({ ...session, transcriptPath: session.transcriptPath })+ // 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 {@@ -2600,12 +2667,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {// 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) replayedFirstTurn.add(session.sessionId)+ 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=${lines.length}`)+ 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.@@ -2641,7 +2708,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {replayCursorFromStart = false,replayFromStart = false,): Promise<boolean> =>- attaches.attach(session, reset, () => attachSessionNow(session, reset, replayCursorFromStart, replayFromStart))+ 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 input: SessionInputController = new SessionInputController({beforeSubmit: (id, text, tabId, deliveryId) => backend.swarmPromptScopes.prepare(id, text, tabId, deliveryId),getSession: (id) => registry.resolve(id),@@ -2931,6 +3008,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (s.engine === 'devin') return lastDevinTurnText(await readDevinMessages(DEVIN_DB, sessionId))if (!s.transcriptPath) return nullif (s.engine === 'codex') return readLastCodexTurnText(s.transcriptPath)+ // Its last turn, read backward — not the whole conversation once per turn end.+ if (s.engine === 'claude') return lastTurnTextFromRawLines(await tailFileUntil(s.transcriptPath, selectClaudeRecapLine))const lines = await tailFile(s.transcriptPath, Infinity)if (s.engine === 'cursor') return lastCursorTurnText(lines)if (s.engine === 'muse') return lastMuseTurnText(lines)diff --git a/cli/src/engines/codex/normalizer.ts b/cli/src/engines/codex/normalizer.tsindex 23fa376bd..b659023c5 100644--- a/cli/src/engines/codex/normalizer.ts+++ b/cli/src/engines/codex/normalizer.ts@@ -268,6 +268,8 @@ export class CodexNormalizer implements EngineNormalizer {private pendingChildResults = new Map<string, ChildResult>()private completedChildren = new Set<string>()private thinkingCounter = 0+ /** See `TurnState.thinkingPrefix`. */+ thinkingPrefix = 'thinking-codex-'private compactJustEmitted = false/** Objective of the active `/goal`, so its re-injection each turn isn't read as a new submission. */private goalObjective: string | null = null@@ -383,7 +385,7 @@ export class CodexNormalizer implements EngineNormalizer {if (!summary) return []return [{type: 'thinking_delta',- payload: { content: clip(summary, MAX_THINKING), thinkingId: `thinking-codex-${this.thinkingCounter++}` },+ payload: { content: clip(summary, MAX_THINKING), thinkingId: `${this.thinkingPrefix}${this.thinkingCounter++}` },}]}@@ -586,6 +588,43 @@ export function selectCodexRecapLine(line: string): 'keep' | 'skip' | 'stop' {return AGENT_TEXT_TYPES.has(itemType) ? 'keep' : 'skip'}+/**+ * The record `CodexNormalizer.ingest` opens a turn on — a user message with text, or a `/goal` context+ * injection — decided from the record alone, as `ingest` decides it whatever came before. Attaching+ * folds from the last one of these (lib/attachTranscript.ts); see `startsClaudeTurn`.+ */+export function startsCodexTurn(line: string): boolean {+ const raw = parse(line)+ if (!raw || raw.type === 'compacted') return false+ const item = payload(raw)+ if (!item) return false+ const type = string(item.type)+ if (raw.type === 'event_msg') return USER_TURN_TYPES.has(type) && !!messageText(item)+ return raw.type === 'response_item' && type === 'message' && goalObjective(item) !== null+}++/**+ * Where a Codex task's work begins (`task_started`, written before the turn's first message) and+ * where one ends (`task_complete`, `turn_aborted`). Everything the normalizer keeps across messages —+ * tool names, sub-agents in flight — belongs to one task and is cleared when it ends, so a fold that+ * starts at the task's beginning keeps all of it, a message sent mid-task included.+ */+export function codexTaskBoundary(line: string): 'begins' | 'ends' | null {+ const raw = parse(line)+ const item = raw && raw.type === 'event_msg' ? payload(raw) : null+ const type = item ? string(item.type) : ''+ return type === 'task_started' ? 'begins' : type === 'task_complete' || type === 'turn_aborted' ? 'ends' : null+}++/** The objective a `/goal` turn opener carries, or null. Whether that turn reads as the submission or a+ * continuation depends on the goal record before it, which is the one older record a fold from the+ * last turn has to be shown. */+export function codexGoalOf(line: string): string | null {+ const raw = parse(line)+ const item = raw && raw.type === 'response_item' ? payload(raw) : null+ return item && string(item.type) === 'message' ? goalObjective(item) : null+}+export function lastCodexTurnText(rawLines: string[]): LastTurnText | null {let userMessage = ''let assistantText = ''diff --git a/cli/src/lib/attachTranscript.real.spec.ts b/cli/src/lib/attachTranscript.real.spec.tsnew file mode 100644index 000000000..b91956582--- /dev/null+++ b/cli/src/lib/attachTranscript.real.spec.ts@@ -0,0 +1,86 @@+/**+ * Opt-in, read-only: the end-first attach against the whole-history fold on THIS computer's own Claude+ * Code and Codex transcripts.+ *+ * ATTACH_REAL_TRANSCRIPTS=1 npx vitest run src/lib/attachTranscript.real.spec.ts+ *+ * `ATTACH_REAL_LIMIT` (default 150) caps the newest transcripts taken per engine. Each one is copied+ * first — live sessions keep writing to theirs — and compared at its end and at a few earlier record+ * boundaries, including the events the rest of the file would then stream. A transcript too large for+ * the oracle to hold is attached end-first only.+ */+import { copyFileSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { homedir, tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, describe, expect, it } from 'vitest'+import { canonical, fromTheEnd, goalForgotten, wholeHistory, type Engine } from '../testing/transcriptOracle.js'++const enabled = process.env.ATTACH_REAL_TRANSCRIPTS === '1'+const limit = Number(process.env.ATTACH_REAL_LIMIT ?? 150)+/** The oracle holds a whole transcript; past this it would be the bug it checks for. */+const ORACLE_BYTES = 48 * 1024 * 1024+/** Earlier cut points are written out as copies, so only for transcripts this small. */+const CUT_BYTES = 8 * 1024 * 1024++function walk(dir: string, depth: number): string[] {+ let entries: string[]+ try { entries = readdirSync(dir) } catch { return [] }+ return entries.flatMap((name) => {+ const path = join(dir, name)+ if (name.endsWith('.jsonl')) return [path]+ return depth > 0 && !name.includes('.') ? walk(path, depth - 1) : []+ })+}++const newest = (files: string[]) => files+ .map((path) => ({ path, mtime: statSync(path).mtimeMs }))+ .sort((a, b) => b.mtime - a.mtime)+ .slice(0, limit)+ .map(({ path }) => path)++const transcripts: Array<[Engine, string]> = enabled+ ? [+ ...newest(walk(join(homedir(), '.claude', 'projects'), 1)).map((path): [Engine, string] => ['claude', path]),+ ...newest(walk(join(homedir(), '.codex', 'sessions'), 3)).map((path): [Engine, string] => ['codex', path]),+ ]+ : []++const scratch = enabled ? mkdtempSync(join(tmpdir(), 'attach-real-')) : ''+afterAll(() => { if (scratch) rmSync(scratch, { recursive: true, force: true }) })++describe.skipIf(!enabled)('end-first attach on this computer’s transcripts', () => {+ it.each(transcripts.map(([engine, path], index) => [index, engine, path.slice(homedir().length)] as const))(+ '#%i %s ~%s',+ async (index, engine, relative) => {+ const copy = join(scratch, `${index}.jsonl`)+ copyFileSync(join(homedir(), relative), copy)+ const size = statSync(copy).size+ const tail = await fromTheEnd(engine, copy, false)+ expect(tail.next).toBeLessThanOrEqual(size)+ if (size > ORACLE_BYTES) return+ const whole = await wholeHistory(engine, copy, false)+ expect(tail.turnOpen).toBe(whole.turnOpen)+ expect(tail.opened).toEqual(whole.opened)+ expect(tail.profile).toEqual(whole.profile)+ expect(tail.content).toBe(whole.content)+ if (size > CUT_BYTES) return++ const records = readFileSync(copy, 'utf8').split('\n').filter((line) => line.trim())+ const cuts = [...new Set([1, Math.floor(records.length / 3), Math.floor((2 * records.length) / 3), records.length - 1])]+ .filter((cut) => cut > 0 && cut < records.length)+ for (const cut of cuts) {+ writeFileSync(copy, records.slice(0, cut).join('\n') + '\n')+ const before = await wholeHistory(engine, copy, false)+ const after = await fromTheEnd(engine, copy, false)+ expect(after.turnOpen, `cut ${cut}`).toBe(before.turnOpen)+ expect(after.opened, `cut ${cut}`).toEqual(before.opened)+ expect(after.profile, `cut ${cut}`).toEqual(before.profile)+ const rest = records.slice(cut)+ const expected = rest.flatMap(before.ingest)+ expect(canonical(rest.flatMap(after.ingest)), `cut ${cut}`)+ .toEqual(canonical(engine === 'codex' ? goalForgotten(records, cut, expected) : expected))+ }+ },+ 300_000,+ )+})diff --git a/cli/src/lib/attachTranscript.spec.ts b/cli/src/lib/attachTranscript.spec.tsnew file mode 100644index 000000000..6f543ac74--- /dev/null+++ b/cli/src/lib/attachTranscript.spec.ts@@ -0,0 +1,712 @@+import { appendFileSync, chmodSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { CodexNormalizer, codexGoalOf, startsCodexTurn } from '../engines/codex/normalizer.js'+import { canonical, fromTheEnd, goalForgotten, newFold, session, wholeHistory } from '../testing/transcriptOracle.js'+import {+ attachTranscript,+ claudeAttachRules,+ codexAttachRules,+ HEAD_RECORD_LIMIT,+ isWholeRecord,+ locateAttachSpan,+ replayAttachSpan,+ type AttachRules,+} from './attachTranscript.js'+import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, selectClaudeRecapLine, startsClaudeTurn, TranscriptFold, type LiveEvent } from './normalize.js'+import { RuntimeProfileManager } from './runtimeProfile.js'+import { tailFile, tailFileUntil } from './transcriptTail.js'+import { Watcher, type LineEvent } from '../watcher/watcher.js'++// ── Codex records, in the shapes a 0.159 rollout writes ──────────────────────────────────────────────+const cx = (type: string, payload: Record<string, unknown>): string =>+ JSON.stringify({ timestamp: '2026-10-03T23:21:44.458Z', type, payload })+const codex = {+ meta: (version = '0.159.0') => cx('session_meta', { id: 'thread-1', cli_version: version, cwd: '/tmp/work' }),+ context: (model: string, effort: string | null, mode: string | null) => cx('turn_context', {+ turn_id: 't', model, ...(effort ? { reasoning_effort: effort } : {}), ...(mode ? { collaboration_mode: { mode } } : {}),+ }),+ settings: (model: string, effort: string, mode: string) => cx('event_msg', {+ type: 'thread_settings_applied', thread_settings: { model, reasoning_effort: effort, collaboration_mode: { mode } },+ }),+ started: (turn: string) => cx('event_msg', { type: 'task_started', turn_id: turn }),+ user: (text: string) => cx('event_msg', { type: 'user_message', message: text }),+ userItem: (text: string) => cx('event_msg', {+ type: 'item_completed', turn_id: 't', item: { type: 'UserMessage', id: 'u', content: [{ type: 'text', text, text_elements: [] }] },+ }),+ goal: (objective: string) => cx('response_item', {+ type: 'message', role: 'user',+ content: [{ type: 'input_text', text: `<codex_internal_context source="goal">\n<objective>${objective}</objective>\n</codex_internal_context>` }],+ }),+ developer: (text: string) => cx('response_item', { type: 'message', role: 'developer', content: [{ type: 'input_text', text }] }),+ agent: (text: string, phase = 'final_answer') => cx('event_msg', {+ type: 'item_completed', item: { type: 'AgentMessage', content: [{ type: 'Text', text }], phase },+ }),+ reasoning: (text: string) => cx('response_item', { type: 'reasoning', summary: [{ type: 'summary_text', text }] }),+ call: (id: string, cmd: string) => cx('response_item', { type: 'function_call', call_id: id, name: 'exec_command', arguments: JSON.stringify({ cmd }) }),+ output: (id: string, output: string) => cx('response_item', { type: 'function_call_output', call_id: id, output }),+ complete: (turn: string) => cx('event_msg', { type: 'task_complete', turn_id: turn, last_agent_message: 'done' }),+ aborted: (turn: string) => cx('event_msg', { type: 'turn_aborted', turn_id: turn }),+ compacted: (bytes: number) => cx('compacted', { message: '📘é'.repeat(bytes / 6), replacement_history: [] }),+ contextCompacted: () => cx('event_msg', { type: 'context_compacted' }),+ tokens: () => cx('event_msg', { type: 'token_count', info: { total_token_usage: { input_tokens: 1 } } }),+}++/** A rollout with every shape attach has to get right, in the order Codex writes them. */+const codexScenario = (): string[] => [+ codex.meta(),+ codex.developer('<permissions instructions>'),+ codex.settings('gpt-5.5', 'high', 'default'),+ codex.started('t1'), codex.context('gpt-5.5', 'high', 'default'), codex.user('first question'),+ codex.reasoning('Planning'), codex.call('c1', 'ls'), codex.output('c1', 'a\nb'), codex.agent('one answer'), codex.complete('t1'),+ codex.started('t2'), codex.context('gpt-6', 'xhigh', 'plan'), codex.userItem('second, in the item shape'),+ codex.reasoning('Thinking 漢字 📘'), codex.agent('looking', 'commentary'),+ codex.compacted(150_000), codex.contextCompacted(), codex.tokens(),+ codex.call('c2', 'npm test'), codex.output('c2', 'ok'), codex.agent('second answer'), codex.complete('t2'),+ codex.settings('gpt-6', 'low', 'default'),+ codex.started('t3'), codex.context('gpt-6', null, 'default'), codex.user('third: effort left out'),+ codex.call('c3', 'sleep 1'),+ codex.user(''), // an empty message opens nothing+ codex.output('c3', 'slept'), codex.complete('t3'),+ codex.started('t4'), codex.context('gpt-6', 'medium', 'default'), codex.user('interrupted one'), codex.aborted('t4'),+ codex.started('t5'), codex.context('gpt-6', 'medium', 'default'), codex.goal('ship the release'), codex.reasoning('goal work'), codex.complete('t5'),+ codex.started('t6'), codex.context('gpt-6', 'medium', 'default'), codex.goal('ship the release'), codex.agent('continuing'), codex.complete('t6'),+ codex.started('t7'), codex.context('gpt-6', 'medium', 'default'), codex.user('a question mid-goal'), codex.complete('t7'),+ codex.started('t8'), codex.context('gpt-6', 'medium', 'default'), codex.goal('ship the release'), codex.reasoning('still the goal'),+ codex.call('c8', 'make'), codex.complete('t8'),+ codex.started('t9'), codex.context('gpt-6', 'max', 'plan'), codex.goal('a different goal'), codex.reasoning('new goal'),+ codex.complete('t9'),+ // A message sent mid-task, with a call still in flight: its output arrives after the new message.+ codex.started('t10'), codex.context('gpt-6', 'max', 'default'), codex.user('start the build'),+ codex.call('c10', 'make all'), codex.user('also run the tests while that builds'),+ codex.output('c10', 'built'), codex.reasoning('now the tests'), codex.call('c11', 'npm test'),+]++// ── Claude Code records ───────────────────────────────────────────────────────────────────────────────+let uuid = 0+const cl = (record: Record<string, unknown>): string => JSON.stringify({+ parentUuid: null, isSidechain: false, userType: 'external', cwd: '/tmp', sessionId: 's', version: '2.1.212',+ timestamp: '2026-10-03T23:21:44.458Z', uuid: `u${++uuid}`, ...record,+})+const claude = {+ user: (content: unknown, extra: Record<string, unknown> = {}) => cl({ type: 'user', message: { role: 'user', content }, ...extra }),+ assistant: (content: unknown[], stop: string | null, model = 'claude-opus-5-5') =>+ cl({ type: 'assistant', message: { id: `m${uuid}`, role: 'assistant', model, content, stop_reason: stop } }),+ text: (text: string) => ({ type: 'text', text }),+ thinking: (thinking: string) => ({ type: 'thinking', thinking }),+ tool: (id: string, command: string) => ({ type: 'tool_use', id, name: 'Bash', input: { command } }),+ result: (id: string, content: string) => cl({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content }] } }),+ compact: () => cl({ type: 'system', subtype: 'compact_boundary', content: 'Conversation compacted', compactMetadata: { trigger: 'auto' } }),+ summary: () => cl({ type: 'user', isCompactSummary: true, message: { role: 'user', content: 'Summary of the earlier conversation' } }),+}++const claudeScenario = (): string[] => [+ JSON.stringify({ type: 'summary', summary: 'Earlier work', leafUuid: 'x' }),+ claude.user('first prompt'),+ claude.assistant([claude.thinking('let me think'), claude.text('First answer.')], 'end_turn'),+ claude.user('second prompt with a tool'),+ claude.assistant([claude.text('Checking.'), claude.tool('toolu_1', 'ls')], 'tool_use'),+ claude.result('toolu_1', 'files'),+ claude.assistant([claude.thinking('found them 漢字'), claude.text('Done: '.repeat(20_000))], 'end_turn', 'claude-fable-5-1'),+ claude.user('<local-command-stdout>Set model to Opus 5.5</local-command-stdout>'),+ claude.user('<bash-input>git status</bash-input><bash-stdout>clean</bash-stdout>'),+ claude.user('third prompt, interrupted'),+ claude.assistant([claude.tool('toolu_2', 'sleep 100')], 'tool_use'),+ claude.user([{ type: 'text', text: '[Request interrupted by user for tool use]' }]),+ claude.user('<task-notification><task-id>a</task-id><tool-use-id>toolu_9</tool-use-id><status>completed</status><summary>bg done</summary></task-notification>'),+ claude.compact(), claude.summary(),+ claude.user('loop iteration', { isMeta: true, promptSource: 'system' }),+ claude.assistant([claude.text('Loop ran.')], 'end_turn', '<synthetic>'),+ claude.user('a bookkeeping line', { isMeta: true }),+ claude.user('fourth prompt'),+ claude.assistant([claude.text('Working on it'), claude.tool('toolu_3', 'make')], 'tool_use'),+ claude.result('toolu_3', 'built'),+ claude.assistant([claude.thinking('almost'), claude.text('Built it.')], 'end_turn'),+ claude.user('fifth prompt, left running'),+ claude.assistant([claude.tool('toolu_4', 'npm test')], 'tool_use'),+ // A prompt that lands while a call is in flight: the result arrives after it, naming its call.+ claude.user('sixth prompt, typed during the tests'),+ claude.result('toolu_4', 'tests passed'),+ claude.assistant([claude.thinking('reading results'), claude.text('All green.')], 'end_turn'),+]++describe('attachTranscript', () => {+ let dir: string, file: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'attach-transcript-')); file = join(dir, 'rollout.jsonl') })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ // The guarantee: at every point a daemon could attach — after any record, mid-record, with either+ // line ending — the end-first read leaves the fold, the chips and the next live events exactly where+ // reading the whole history would.+ describe.each([['codex', codexScenario], ['claude', claudeScenario]] as const)('%s: equals the whole-history attach', (engine, scenario) => {+ const records = scenario()+ const cuts = records.map((_, index) => index + 1)++ it.each(cuts)('after record %i, then streams the rest identically', async (cut) => {+ for (const separator of ['\n', '\r\n']) {+ writeFileSync(file, records.slice(0, cut).join(separator) + separator)+ const whole = await wholeHistory(engine, file, false)+ const tail = await fromTheEnd(engine, file, false)+ expect(tail.turnOpen).toBe(whole.turnOpen)+ expect(tail.opened).toEqual(whole.opened)+ expect(tail.profile).toEqual(whole.profile)+ expect(tail.content).toBe(whole.content)+ expect(tail.next).toBe(Buffer.byteLength(records.slice(0, cut).join(separator) + separator))+ const rest = records.slice(cut)+ const expected = rest.flatMap(whole.ingest)+ expect(canonical(rest.flatMap(tail.ingest))).toEqual(canonical(engine === 'codex' ? goalForgotten(records, cut, expected) : expected))+ }+ })++ it.each(cuts)('with record %i still being written, leaves it to the tail', async (cut) => {+ const done = records.slice(0, cut - 1)+ const prefix = done.length ? done.join('\n') + '\n' : ''+ const half = records[cut - 1].slice(0, Math.floor(records[cut - 1].length / 2))+ writeFileSync(file, prefix + half)+ const whole = await wholeHistory(engine, file, false)+ const tail = await fromTheEnd(engine, file, false)+ expect(tail.turnOpen).toBe(whole.turnOpen)+ expect(tail.opened).toEqual(whole.opened)+ expect(tail.profile).toEqual(whole.profile)+ expect(tail.content).toBe(true)+ // The tail picks the half-written record up whole, where the whole-history attach lost it.+ expect(tail.next).toBe(Buffer.byteLength(prefix))+ const rest = records.slice(cut - 1)+ const expected = rest.flatMap(whole.ingest)+ expect(canonical(rest.flatMap(tail.ingest))).toEqual(canonical(engine === 'codex' ? goalForgotten(records, cut - 1, expected) : expected))+ })++ it.each(cuts)('replays a first-turn transcript of %i records live, whole', async (cut) => {+ writeFileSync(file, records.slice(0, cut).join('\n'))+ const whole = await wholeHistory(engine, file, true)+ const tail = await fromTheEnd(engine, file, true)+ expect(canonical(tail.live)).toEqual(canonical(whole.live))+ expect(tail.turnOpen).toBe(false)+ expect(tail.profile).toEqual(whole.profile)+ })+ })++ it('labels a goal turn after an ordinary opener as the goal submission, and nothing else changes', async () => {+ const records = [codex.goal('ship'), codex.complete('a'), codex.user('a question'), codex.complete('b')]+ writeFileSync(file, records.join('\n') + '\n')+ const whole = await wholeHistory('codex', file, false)+ const tail = await fromTheEnd('codex', file, false)+ const next = [codex.goal('ship'), codex.agent('more'), codex.complete('c'), codex.goal('ship')]+ const opened = (events: LiveEvent[]) => events.filter((event) => event.type === 'turn_started').map((event) => event.payload)+ expect(opened(next.flatMap(whole.ingest))).toEqual([{ userMessage: 'Continuing goal: ship' }, { userMessage: 'Continuing goal: ship' }])+ expect(opened(next.flatMap(tail.ingest))).toEqual([{ userMessage: '/goal ship' }, { userMessage: 'Continuing goal: ship' }])+ })++ it('keeps the continuation label when the open turn is itself a goal turn', async () => {+ writeFileSync(file, [codex.goal('ship'), codex.complete('a'), codex.user('q'), codex.complete('b'), codex.goal('ship'), codex.reasoning('go')].join('\n') + '\n')+ expect((await fromTheEnd('codex', file, false)).opened).toEqual({ type: 'turn_started', payload: { userMessage: 'Continuing goal: ship' } })+ expect((await wholeHistory('codex', file, false)).opened).toEqual({ type: 'turn_started', payload: { userMessage: 'Continuing goal: ship' } })+ })++ it('reports a forked rollout\'s own CLI version, where the whole fold ends on its parent\'s', async () => {+ // A fork opens with its own session_meta, then copies its parent's history, the parent's own included.+ const turn = (id: string, text: string) => [codex.started(id), codex.context('gpt-6', 'high', 'default'), codex.user(text)]+ writeFileSync(file, [codex.meta('0.160.0'), codex.meta('0.159.0'), ...turn('t1', 'go'), codex.complete('t1'), ...turn('t2', 'again')].join('\n') + '\n')+ expect((await wholeHistory('codex', file, false)).profile).toEqual({ model: 'gpt-6', effort: 'high', mode: 'default', cliVersion: '0.159.0' })+ expect((await fromTheEnd('codex', file, false)).profile).toEqual({ model: 'gpt-6', effort: 'high', mode: 'default', cliVersion: '0.160.0' })+ })++ it('reads only the last turn of a long history, never the rest', async () => {+ const history = codexScenario()+ const turn = [codex.started('t-last'), codex.context('gpt-6', 'high', 'default'), codex.user('last'), codex.reasoning('now')]+ writeFileSync(file, [...history, ...Array(200).fill(codex.compacted(30_000)), codex.complete('x'), ...turn].join('\n') + '\n')+ const fields = (line: string) => new RuntimeProfileManager().transcriptFields(session('codex'), line)+ const span = await locateAttachSpan(file, codexAttachRules(fields))+ const full = Buffer.byteLength([...history, ...Array(200).fill(codex.compacted(30_000)), codex.complete('x')].join('\n') + '\n')+ // Codex's turn begins at its task_started; the turn_context after it already sets every field.+ expect(span).toMatchObject({ turnFrom: full, profileFrom: full, seeds: [] })+ expect(span?.head).toBe(history[0])+ })+})++describe('locateAttachSpan', () => {+ let dir: string, file: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'attach-span-')); file = join(dir, 't.jsonl') })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ const opener = (line: string) => line.startsWith('{"open"')+ const rules = (over: Partial<AttachRules> = {}): AttachRules => ({+ startsTurn: opener, turnMarkers: [Buffer.from('open')], fields: () => [], required: [], ...over,+ })++ it('returns the whole file for an empty transcript or a first turn', async () => {+ writeFileSync(file, '')+ expect(await locateAttachSpan(file, rules())).toEqual({ end: 0, turnFrom: 0, profileFrom: 0, head: null, seeds: [] })+ writeFileSync(file, '{"open":1}\n{"x":1}\n')+ expect(await locateAttachSpan(file, rules(), { fromStart: true })).toEqual({ end: 19, turnFrom: 0, profileFrom: 0, head: null, seeds: [] })+ })++ it('never decodes a record without a turn marker to ask whether it opens a turn', async () => {+ writeFileSync(file, ['{"open":1}', '{"open":2}', ...Array(50).fill('{"noise":"x"}')].join('\n'))+ const asked: string[] = []+ const span = await locateAttachSpan(file, rules({ startsTurn: (line) => { asked.push(line); return opener(line) } }))+ expect(asked).toEqual(['{"open":2}'])+ expect(span?.turnFrom).toBe(11)+ })++ it('takes the whole file as the turn when nothing opens one', async () => {+ writeFileSync(file, '{"a":1}\n{"b":2}\n')+ expect(await locateAttachSpan(file, rules())).toEqual({ end: 16, turnFrom: 0, profileFrom: 0, head: null, seeds: [] })+ })++ it('reaches back past the opener only as far as the newest record setting each missing field', async () => {+ const lines = ['{"meta":1}', '{"model":"old","effort":"low"}', '{"effort":"high"}', '{"x":1}', '{"open":1}', '{"model":"new"}']+ writeFileSync(file, lines.join('\n'))+ const fields = (line: string) => {+ const record = JSON.parse(line) as Record<string, unknown>+ return (['model', 'effort'] as const).filter((field) => field in record)+ }+ const span = await locateAttachSpan(file, rules({ fields, required: ['model', 'effort'] }))+ const offset = (index: number) => Buffer.byteLength(lines.slice(0, index).join('\n') + '\n')+ expect(span).toEqual({ end: Buffer.byteLength(lines.join('\n')), turnFrom: offset(4), profileFrom: offset(2), head: '{"meta":1}', seeds: [] })+ })++ it('asks only marked records about fields, and stops at BOF when a field is never set', async () => {+ writeFileSync(file, ['{"settings":1}', '{"x":2}', '{"open":1}'].join('\n'))+ const asked: string[] = []+ const span = await locateAttachSpan(file, rules({+ fields: (line) => { asked.push(line); return [] },+ fieldMarkers: [Buffer.from('settings')],+ required: ['mode'],+ }))+ expect(asked).toEqual(['{"settings":1}'])+ expect(span).toMatchObject({ turnFrom: 23, profileFrom: 23, head: '{"settings":1}' })+ })++ it('finds the seed an opener depends on, and gives up on it at BOF', async () => {+ const lines = ['{"goal":"a"}', '{"x":1}', '{"open":1,"goal":"a"}']+ writeFileSync(file, lines.join('\n'))+ const seeded = rules({+ seedFor: (line) => (line.includes('goal') ? (candidate) => candidate.includes('goal') : null),+ seedMarkers: [Buffer.from('goal')],+ })+ expect((await locateAttachSpan(file, seeded))?.seeds).toEqual(['{"goal":"a"}'])+ writeFileSync(file, lines.slice(1).join('\n'))+ expect((await locateAttachSpan(file, seeded))?.seeds).toEqual([])+ writeFileSync(file, '{"goal":"a"}\n{"open":2}')+ expect((await locateAttachSpan(file, seeded))?.seeds).toEqual([])+ })++ it('stops reaching back for fields and seeds at the reach limit', async () => {+ const lines = ['{"model":"far","goal":1}', ...Array(20).fill('{"pad":"xxxxxxxxxxxxxxxxxxxx"}'), '{"open":1,"goal":1}', '{"x":1}']+ writeFileSync(file, lines.join('\n'))+ const reaching = rules({+ fields: (line) => (line.includes('model') ? ['model'] : []),+ required: ['model'],+ seedFor: () => (line) => line.includes('goal'),+ seedMarkers: [Buffer.from('goal')],+ })+ const opener = Buffer.byteLength(lines.slice(0, 21).join('\n') + '\n')+ expect(await locateAttachSpan(file, reaching, { reach: 100 })).toEqual({+ end: Buffer.byteLength(lines.join('\n')), turnFrom: opener, profileFrom: opener, head: '{"model":"far","goal":1}', seeds: [],+ })+ expect(await locateAttachSpan(file, reaching, { reach: opener })).toMatchObject({ profileFrom: 0, head: null, seeds: ['{"model":"far","goal":1}'] })+ })++ it('leaves the head out when it is the opener itself or too large to be metadata', async () => {+ writeFileSync(file, '{"open":1}\n{"x":1}')+ expect((await locateAttachSpan(file, rules()))?.head).toBeNull()+ writeFileSync(file, `{"big":"${'x'.repeat(HEAD_RECORD_LIMIT)}"}\n{"open":1}\n`)+ expect(await locateAttachSpan(file, rules())).toMatchObject({ turnFrom: HEAD_RECORD_LIMIT + 11, head: null })+ })++ it('reports a file that shrank under the walk', async () => {+ writeFileSync(file, ['{"open":1}', ...Array(10_000).fill('{"noise":"xxxxxxxxxxxxxxxx"}')].join('\n'))+ expect(await locateAttachSpan(file, rules({+ startsTurn: () => false,+ turnMarkers: [Buffer.from('noise')],+ fields: () => { truncateSync(file, 10); return [] },+ required: ['model'],+ }))).toBeNull()+ })+})++describe('replayAttachSpan', () => {+ let dir: string, file: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'attach-replay-')); file = join(dir, 't.jsonl') })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ it('feeds the head and older records to the profile only, the seed to the fold first', async () => {+ writeFileSync(file, '{"a":1}\n{"b":2}\n{"c":3}\n{"d":4}\n')+ const seen: string[] = []+ const read = await replayAttachSpan(file, { end: 32, turnFrom: 16, profileFrom: 8, head: '{"a":1}', seeds: ['{"s":0}'] }, {+ profile: (line) => seen.push(`profile ${line}`),+ fold: (line) => seen.push(`fold ${line}`),+ observe: (line) => seen.push(`observe ${line}`),+ })+ expect(seen).toEqual([+ 'profile {"a":1}', 'fold {"s":0}',+ 'profile {"b":2}',+ 'profile {"c":3}', 'observe {"c":3}', 'fold {"c":3}',+ 'profile {"d":4}', 'observe {"d":4}', 'fold {"d":4}',+ ])+ expect(read).toEqual({ next: 32, records: 2, content: true })+ })++ it('counts a record still being written as content without feeding it', async () => {+ writeFileSync(file, '{"half":')+ const fed: string[] = []+ const read = await replayAttachSpan(file, { end: 8, turnFrom: 0, profileFrom: 0, head: null, seeds: [] }, {+ profile: (line) => fed.push(line), fold: (line) => fed.push(line),+ })+ expect(fed).toEqual([])+ expect(read).toEqual({ next: 0, records: 0, content: true })+ })++ it('says a whitespace-only transcript has no content', async () => {+ writeFileSync(file, ' \n\n')+ expect(await replayAttachSpan(file, { end: 4, turnFrom: 0, profileFrom: 0, head: null, seeds: [] }, { profile: () => {}, fold: () => {} }))+ .toEqual({ next: 4, records: 0, content: false })+ })++ it('hands the tail the span end when the file shrank under the replay', async () => {+ writeFileSync(file, '{"a":1}\n')+ expect(await replayAttachSpan(file, { end: 500, turnFrom: 0, profileFrom: 0, head: null, seeds: [] }, { profile: () => {}, fold: () => {} }))+ .toEqual({ next: 500, records: 0, content: false })+ })+})++describe('attachTranscript retries', () => {+ let dir: string, file: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'attach-retry-')); file = join(dir, 't.jsonl') })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ // 21 bytes a record, each carrying its index, so a rule can tell which walk is looking at it.+ const noise = (count: number) => Array.from({ length: count }, (_, i) => `{"noise":"${String(i).padStart(8, '0')}"}`).join('\n') + '\n'+ const indexOf = (line: string) => Number((JSON.parse(line) as { noise: string }).noise)++ it('walks again after a shrink, then replays the whole of whatever is left', async () => {+ writeFileSync(file, noise(14_000))+ let shrinks = 0+ const folded: string[] = []+ const read = await attachTranscript(file, {+ startsTurn: () => false,+ turnMarkers: [Buffer.from('noise')],+ fields: (line) => {+ // Each walk sees the file cut well below the next chunk it is going to read.+ if (shrinks === 0 && indexOf(line) >= 7_000) { shrinks++; writeFileSync(file, noise(7_000)) }+ else if (shrinks === 1 && indexOf(line) < 7_000) { shrinks++; writeFileSync(file, noise(3)) }+ return []+ },+ required: ['model'],+ }, { profile: () => {}, fold: (line) => folded.push(line) })+ expect(shrinks).toBe(2)+ expect(read).toMatchObject({ turnFrom: 0, profileFrom: 0, records: 3, end: 63, next: 63 })+ expect(folded).toHaveLength(3)+ })++ it('uses the second walk when only the first is disturbed', async () => {+ writeFileSync(file, noise(14_000))+ let shrinks = 0+ const read = await attachTranscript(file, {+ startsTurn: () => false,+ turnMarkers: [Buffer.from('noise')],+ fields: () => { if (!shrinks++) writeFileSync(file, '{"open":1}\n'); return [] },+ required: ['model'],+ }, { profile: () => {}, fold: () => {} })+ expect(read).toMatchObject({ end: 11, records: 1, next: 11 })+ })+})++describe('turn openers match the normalizers exactly', () => {+ const claudeCorpus = [+ ...claudeScenario(), '', ' ', 'not json', 'null', '42', '"text"', '[]',+ claude.user([]), claude.user(null), claude.user([{ type: 'text', text: '' }]),+ claude.user([{ type: 'image', source: {} }, { type: 'text', text: 'look' }]),+ claude.user('[Request interrupted by user]'),+ claude.user('<system-reminder>only a reminder</system-reminder>'),+ JSON.stringify({ type: 'user', message: { role: 'assistant', content: 'odd' } }),+ JSON.stringify({ type: 'user' }),+ ]+ it.each(claudeCorpus.map((line, index) => [index, line] as const))('claude record %i', (_, line) => {+ const opened = lineToEvents(line, newTurnState()).some((event) => event.type === 'turn_started')+ expect(startsClaudeTurn(line)).toBe(opened)+ })++ const codexCorpus = [+ ...codexScenario(), '', 'not json', 'null', cx('event_msg', {}), JSON.stringify({ type: 'event_msg' }),+ cx('event_msg', { type: 'UserMessage', message: 'old vocabulary' }),+ cx('event_msg', { type: 'item_completed', item: { type: 'UserMessage', content: [] } }),+ cx('response_item', { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: '<codex_internal_context source="goal"><objective>x</objective>' }] }),+ cx('response_item', { type: 'message', role: 'user', content: [{ type: 'input_text', text: '<codex_internal_context source="goal">no objective' }] }),+ cx('compacted', { type: 'user_message', message: 'inside a compaction' }),+ ]+ it.each(codexCorpus.map((line, index) => [index, line] as const))('codex record %i', (_, line) => {+ const opened = new CodexNormalizer('live', () => null).ingest(line).some((event) => event.type === 'turn_started')+ expect(startsCodexTurn(line)).toBe(opened)+ })++ it('reads a goal objective only from a goal injection', () => {+ expect(codexGoalOf(codex.goal('ship it'))).toBe('ship it')+ expect(codexGoalOf(codex.user('ship it'))).toBeNull()+ expect(codexGoalOf(codex.developer('<codex_internal_context source="goal"><objective>x</objective>'))).toBeNull()+ expect(codexGoalOf(cx('response_item', { type: 'reasoning' }))).toBeNull()+ expect(codexGoalOf('not json')).toBeNull()+ })+})++describe('rules', () => {+ it('give Codex its markers, fields and goal seed', () => {+ const rules = codexAttachRules(() => [])+ expect(rules.required).toEqual(['model', 'effort', 'mode'])+ expect(rules.seedFor?.(codex.user('x'))).toBeNull()+ const seed = rules.seedFor?.(codex.goal('g'))+ expect(seed?.(codex.goal('other'))).toBe(true)+ expect(seed?.(codex.user('g'))).toBe(false)+ for (const line of codexScenario().filter(startsCodexTurn)) {+ expect(rules.turnMarkers.some((marker) => Buffer.from(line).includes(marker))).toBe(true)+ }+ })++ it('give Claude its marker and the model alone', () => {+ const rules = claudeAttachRules(() => [])+ expect(rules.required).toEqual(['model'])+ expect(rules.fieldMarkers).toBeUndefined()+ expect(rules.seedFor).toBeUndefined()+ for (const line of claudeScenario().filter(startsClaudeTurn)) {+ expect(rules.turnMarkers.some((marker) => Buffer.from(line).includes(marker))).toBe(true)+ }+ })++ it('treat a record without a line ending as whole only when it parses', () => {+ expect(isWholeRecord('{"a":1}')).toBe(true)+ expect(isWholeRecord('{"a":')).toBe(false)+ })+})++describe('TranscriptFold', () => {+ it('matches foldTranscript, keeping only the last turn_started of the history', () => {+ const lines = claudeScenario()+ for (const live of [false, true]) {+ const a = newTurnState(), b = newTurnState()+ const whole = foldTranscript((line) => lineToEvents(line, a), lines, () => a.turnOpen, { live })+ const stream = new TranscriptFold((line) => lineToEvents(line, b), () => b.turnOpen, live)+ for (const line of lines) stream.push(line)+ const out = stream.finish()+ expect(out.turnOpen).toBe(whole.turnOpen)+ expect(out.live).toEqual(whole.live)+ expect(out.history).toEqual(whole.history.filter((event) => event.type === 'turn_started').slice(-1))+ }+ expect(new TranscriptFold(() => [], () => true, false).finish()).toEqual({ history: [], live: [], turnOpen: true })+ })+})++describe('the Claude recap reads only its last turn', () => {+ let dir: string, file: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'claude-recap-')); file = join(dir, 's.jsonl') })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))+ const records = claudeScenario()++ it.each(records.map((_, index) => index + 1))('matches the whole-file recap after record %i', async (cut) => {+ writeFileSync(file, records.slice(0, cut).join('\n') + '\n')+ const whole = lastTurnTextFromRawLines(await tailFile(file, Infinity))+ expect(lastTurnTextFromRawLines(await tailFileUntil(file, selectClaudeRecapLine))).toEqual(whole)+ })++ it('keeps a turn that never reached an answer, and skips records the recap ignores', async () => {+ writeFileSync(file, [claude.user('q'), claude.assistant([claude.text('Let me look'), claude.tool('t', 'ls')], 'tool_use'), claude.result('t', 'x'), 'null', claude.compact()].join('\n'))+ expect(lastTurnTextFromRawLines(await tailFileUntil(file, selectClaudeRecapLine))).toEqual({ userMessage: 'q', assistantText: 'Let me look' })+ expect(selectClaudeRecapLine('not json')).toBe('skip')+ expect(selectClaudeRecapLine(JSON.stringify({ type: 'system' }))).toBe('skip')+ })+})++describe('the review of the first cut', () => {+ let dir: string, file: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'attach-review-')); file = join(dir, 'rollout.jsonl') })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ // A reset (Codex fires SessionStart on every compaction) re-reads a session that is being tailed.+ // The tail is held for the whole attach: the read stops where delivery stopped, a record written+ // meanwhile reaches only the new fold, and nothing is delivered twice.+ it('hands a tailed session over to the new fold without losing or repeating a record', async () => {+ const open = [codex.meta(), codex.started('t1'), codex.context('gpt-6', 'high', 'default'), codex.user('go'), codex.reasoning('working')]+ writeFileSync(file, open.join('\n') + '\n')+ const watcher = new Watcher()+ const seen: Array<{ fold: string; text: string }> = []+ let current = 'old'+ watcher.on('line', (event: LineEvent) => seen.push({ fold: current, text: event.text }))+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath: file })+ appendFileSync(file, codex.agent('still going') + '\n')+ await watcher.pollSession('s1')+ expect(seen.map((line) => line.fold)).toEqual(['old'])++ const hold = (await watcher.hold('s1', file))!+ const heldAt = hold.offset+ expect(heldAt).toBe(Buffer.byteLength([...open, codex.agent('still going')].join('\n') + '\n'))+ const replacement = newFold('codex')+ const stream = new TranscriptFold(replacement.ingest, replacement.turnOpen, false)+ const read = await attachTranscript(file, codexAttachRules(() => []), {+ // Written while the attach reads: the turn ends.+ start: () => { appendFileSync(file, codex.complete('t1') + '\n') },+ profile: () => {},+ fold: (line) => stream.push(line),+ }, { end: heldAt })+ // Held: nothing reaches the old fold, however long it waits (a drain would wait for the release).+ await new Promise((resolve) => setTimeout(resolve, 80))+ expect(seen).toHaveLength(1)+ expect(stream.finish().turnOpen).toBe(true)+ expect(read.next).toBe(heldAt)++ current = 'new'+ hold.release(read.next)+ await watcher.pollSession('s1')+ expect(seen).toEqual([{ fold: 'old', text: codex.agent('still going') }, { fold: 'new', text: codex.complete('t1') }])+ for (const line of seen.filter((entry) => entry.fold === 'new')) replacement.ingest(line.text)+ expect(replacement.turnOpen()).toBe(false)+ await watcher.stop()+ })++ it('shows the device the record Codex writes before the opener, which is the turn\'s input', async () => {+ const input = cx('response_item', {+ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'go' }],+ internal_chat_message_metadata_passthrough: { turn_id: 't1', content_item_kinds: ['user.text'] },+ })+ writeFileSync(file, [codex.meta(), codex.started('t1'), codex.context('gpt-6', 'high', 'default'), input, codex.userItem('go'), codex.reasoning('x')].join('\n') + '\n')+ const observed: string[] = []+ await attachTranscript(file, codexAttachRules(() => []), { profile: () => {}, fold: () => {}, observe: (line) => observed.push(line) })+ expect(observed).toContain(input)+ expect(observed[0]).toBe(codex.started('t1'))+ })++ it('treats a transcript that is missing as an empty history, as the whole read did', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const fed: string[] = []+ const read = await attachTranscript(file, codexAttachRules(() => []), { profile: (line) => fed.push(line), fold: (line) => fed.push(line) })+ expect(read).toMatchObject({ next: 0, records: 0, content: false, turnFrom: 0, seeds: [], failed: true })+ expect(fed).toEqual([])+ expect(warn).toHaveBeenCalledOnce()+ } finally { warn.mockRestore() }+ })++ // A read that fails must not hand the tail byte 0: from there it would deliver every old turn as a+ // new one. It hands it the end it was reading to, and says it failed.+ it.each([+ ['cannot be read at all', () => { chmodSync(file, 0o000) }, () => {}],+ ['stops being readable once its span is found', () => {}, () => { chmodSync(file, 0o000) }],+ ])('resumes the tail at the end of a transcript that %s', async (_, prepare, start) => {+ const content = [codex.started('t1'), codex.user('a'), codex.complete('t1')].join('\n') + '\n'+ writeFileSync(file, content)+ prepare()+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const read = await attachTranscript(file, codexAttachRules(() => []), { start, profile: () => {}, fold: () => {} })+ expect(read).toMatchObject({ next: Buffer.byteLength(content), records: 0, content: true, failed: true })+ chmodSync(file, 0o600)+ prepare()+ const boundary = Buffer.byteLength(codex.started('t1') + '\n' + codex.user('a') + '\n')+ const held = await attachTranscript(file, codexAttachRules(() => []), { start, profile: () => {}, fold: () => {} }, { end: boundary })+ expect(held).toMatchObject({ next: boundary, failed: true })+ expect(warn).toHaveBeenCalledTimes(2)+ } finally {+ warn.mockRestore()+ chmodSync(file, 0o600)+ }+ })++ // A consumer that throws loses that record, not the attach: the read still ends exactly where it+ // stopped, so a record the engine writes meanwhile — whole, or still being written — is tailed.+ it.each([+ ['whole', (record: string) => [record + '\n', '']],+ ['half-written', (record: string) => [record.slice(0, 20), record.slice(20) + '\n']],+ ])('tails a record written %s while a consumer throws', async (_, split) => {+ const content = [codex.started('t1'), codex.user('a'), codex.complete('t1')].join('\n') + '\n'+ writeFileSync(file, content)+ const record = codex.user('a prompt typed while the daemon was attaching')+ const [now, later] = split(record)+ const folded: string[] = []+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const read = await attachTranscript(file, codexAttachRules(() => []), {+ profile: () => { throw new Error('profile') },+ fold: (line) => {+ if (!folded.length) { appendFileSync(file, now); folded.push(line); throw new Error('boom') }+ folded.push(line)+ },+ observe: () => { throw new Error('device') },+ })+ expect(read).toMatchObject({ next: Buffer.byteLength(content), records: 3, failed: false })+ expect(folded).toEqual([codex.started('t1'), codex.user('a'), codex.complete('t1')])+ expect(warn).toHaveBeenCalledOnce()+ expect(warn.mock.calls[0][0]).toContain('7 record(s) could not be taken in: Error: profile')+ const watcher = new Watcher()+ const lines: string[] = []+ watcher.on('line', (event: LineEvent) => lines.push(event.text))+ await watcher.addSession({ sessionId: 's', engine: 'codex', transcriptPath: file }, { fromOffset: read.next })+ appendFileSync(file, later)+ await watcher.pollSession('s')+ await watcher.stop()+ expect(lines).toEqual([record])+ } finally { warn.mockRestore() }+ })++ it('names thinking blocks so no two windows of one session share an id, and one window keeps its names', async () => {+ const records = claudeScenario()+ const ids = async (cut: number) => {+ writeFileSync(file, records.slice(0, cut).join('\n') + '\n')+ const tail = await fromTheEnd('claude', file, false)+ const next = [claude.user('next'), claude.assistant([claude.thinking('a'), claude.thinking('b')], 'end_turn')]+ return next.flatMap(tail.ingest).flatMap((event) => {+ const id = (event.payload as { thinkingId?: string }).thinkingId+ return event.type === 'thinking_delta' && id ? [id] : []+ })+ }+ const early = await ids(10)+ const late = await ids(records.length)+ expect(early).toHaveLength(2)+ expect(new Set([...early, ...late]).size).toBe(4)+ expect(await ids(records.length)).toEqual(late)+ })++ it('reaches back for the call a turn\'s result answers, and only within reach', async () => {+ const call = claude.assistant([claude.tool('toolu_far', 'make')], 'tool_use')+ const lines = [claude.user('first'), call, claude.user('second, mid-call'), claude.result('toolu_far', 'made')]+ writeFileSync(file, lines.join('\n') + '\n')+ expect((await locateAttachSpan(file, claudeAttachRules(() => [])))?.seeds).toEqual([call])+ expect((await locateAttachSpan(file, claudeAttachRules(() => []), { reach: 1 }))?.seeds).toEqual([])+ writeFileSync(file, [claude.user('first'), claude.user('second'), claude.result('', 'no id')].join('\n') + '\n')+ expect((await locateAttachSpan(file, claudeAttachRules(() => [])))?.seeds).toEqual([])+ })++ it('does not look past a finished task for the beginning of a turn that has none', async () => {+ writeFileSync(file, [codex.started('t1'), codex.user('a'), codex.complete('t1'), codex.user('b, no task_started')].join('\n') + '\n')+ const span = await locateAttachSpan(file, codexAttachRules(() => []))+ expect(span?.turnFrom).toBe(Buffer.byteLength([codex.started('t1'), codex.user('a'), codex.complete('t1')].join('\n') + '\n'))+ })+})++describe('the walk, at its edges', () => {+ let dir: string, file: string+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'attach-edges-')); file = join(dir, 't.jsonl') })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ it('keeps looking for a task\'s beginning past a record that only mentions one', async () => {+ const mention = codex.agent('the task_complete event is next')+ const lines = [codex.started('t1'), codex.user('a'), mention, codex.user('b')]+ writeFileSync(file, lines.join('\n') + '\n')+ expect((await locateAttachSpan(file, codexAttachRules(() => [])))?.turnFrom).toBe(0)+ })++ it('feeds several calls still running, oldest first', async () => {+ const first = claude.assistant([claude.tool('toolu_a', 'make')], 'tool_use')+ const second = claude.assistant([claude.tool('toolu_b', 'npm test')], 'tool_use')+ writeFileSync(file, [claude.user('go'), first, second, claude.user('while both run')].join('\n') + '\n')+ expect((await locateAttachSpan(file, claudeAttachRules(() => [])))?.seeds).toEqual([first, second])+ })++ it('counts an answer before the turn as answered, and passes over one without an id', async () => {+ const lines = [+ claude.user('first'), claude.assistant([claude.tool('toolu_done', 'ls')], 'tool_use'),+ claude.result('toolu_done', 'ok'), claude.result('', 'stray'), claude.user('second'),+ ]+ writeFileSync(file, lines.join('\n') + '\n')+ expect((await locateAttachSpan(file, claudeAttachRules(() => [])))?.seeds).toEqual([])+ })+})diff --git a/cli/src/lib/attachTranscript.ts b/cli/src/lib/attachTranscript.tsnew file mode 100644index 000000000..e83b5eb7c--- /dev/null+++ b/cli/src/lib/attachTranscript.ts@@ -0,0 +1,323 @@+/**+ * What a Claude Code or Codex transcript says about where its session stands, read from the END.+ *+ * Attaching to a session — the daemon starting, a pane opening, a reset — asks the transcript three+ * things: is a turn open and what was its prompt (the Working state, the recap and alert its end will+ * bring, the question watcher), which model, effort and mode the chips show, and, while a device+ * delivery is pending, the records that prove it landed. Every answer sits at the end of the file.+ * Reading the whole history for them cost memory in proportion to the conversation: on 2026-10-03 an+ * 803 MB Codex rollout held 1.9 GB of heap on its own, and the daemon died at its 4 GB limit seconds+ * after every start.+ *+ * So the file is walked backward to where the last turn's work began, and further only for the few+ * older records that turn still depends on, then streamed forward from there one record at a time.+ * Resuming the conversation itself stays the engine's job: nothing here loads history to show it.+ *+ * Why folding from there is the whole-history fold: a turn's beginning resets the normalizer's+ * turn-scoped state (for Codex the task's beginning, which also covers messages sent mid-task), so the+ * fold from it ends where the fold from byte 0 does. What outlives a turn is reached for explicitly+ * and bounded (`ATTACH_REACH_BYTES`): the runtime profile (`profileFrom`, `head`), the goal a+ * continuing Codex `/goal` is labelled against, and the earlier Claude tool calls whose results land+ * in the turn — already, or live, for a call still running when it opened (`seeds`). By design, and pinned by the tests:+ * - thinking-block ids carry the window's start offset (`start`), so no two folds of one session can+ * send the same id, and re-folding the same turn names each block as it was named before;+ * - Codex remembers the last `/goal` objective across ordinary turns. Only a goal opener looks back for+ * it, so when the open turn is an ordinary one, the next goal turn reads `/goal x` rather than+ * `Continuing goal: x`. Finding it would mean reading back to BOF on every Codex attach;+ * - a forked Codex rollout reports its own CLI version, from its first record, where the whole fold+ * ended on the copied parent's `session_meta`.+ */+import { stat } from 'node:fs/promises'+import { codexGoalOf, codexTaskBoundary, startsCodexTurn } from '../engines/codex/normalizer.js'+import { claudeToolLinks, startsClaudeTurn } from './normalize.js'+import { scanRecordsBackward, streamRecords } from './transcriptTail.js'+import type { RuntimeField } from './runtimeProfile.js'++export interface AttachRules {+ /** The record the engine's fold opens a turn on, judged from the record alone. */+ startsTurn(line: string): boolean+ /** Byte strings every turn opener contains: a record with none of them is not decoded to ask. */+ turnMarkers: readonly Buffer[]+ /** Where a turn's work begins when that is before its opener (Codex `task_started`), and where the+ * previous turn's ended, past which none is looked for. */+ turnBegin?: { begins(line: string): boolean; ends(line: string): boolean; markers: readonly Buffer[] }+ /** The runtime fields one record sets (`RuntimeProfileManager.transcriptFields`). */+ fields(line: string): readonly RuntimeField[]+ /** Byte strings every field-setting record contains; absent means every record is asked. */+ fieldMarkers?: readonly Buffer[]+ /** The fields the transcript is read for. */+ required: readonly RuntimeField[]+ /** For an opener whose meaning depends on an older record, the test for that record (Codex `/goal`). */+ seedFor?(opener: string): ((line: string) => boolean) | null+ /** Byte strings every seed record contains. */+ seedMarkers?: readonly Buffer[]+ /** Ids a record defines and earlier ids it refers to (a Claude tool call and its result). */+ links?(line: string): { defines: readonly string[]; references: readonly string[] }+ /** Byte strings every record with links contains. */+ linkMarkers?: readonly Buffer[]+}++export interface AttachSpan {+ /** The file length the walk started from. Anything after it is the tail's to read. */+ end: number+ /** Where the last turn's work begins: the fold and the device observer start here. */+ turnFrom: number+ /** Where the runtime profile's replay starts — at or before `turnFrom`. */+ profileFrom: number+ /** The file's first record, for the profile when it lies before `profileFrom` (Codex `session_meta`). */+ head: string | null+ /** Older records the fold needs before the turn, oldest first. */+ seeds: string[]+}++export interface AttachConsumers {+ /** Called once the span is known, before anything is fed. */+ start?(span: AttachSpan): void+ /** The runtime profile — the head, then every record from `profileFrom`. */+ profile(line: string): void+ /** The turn fold — the seeds, then every record from `turnFrom`. */+ fold(line: string): void+ /** The device's transcript observer — every record from `turnFrom`. */+ observe?(line: string): void+}++export interface AttachRead {+ /** Where the transcript's tail picks up: just past the last whole record replayed. */+ next: number+ /** Records replayed from `turnFrom` on. */+ records: number+ /** The file held something past `profileFrom` — a whole record, or one still being written. */+ content: boolean+}++/** What attaching read: the span, the replay, and whether the file could be read through at all. */+export interface AttachResult extends AttachSpan, AttachRead {+ /** The file could not be read through, so the fold holds less than the history: a reset should keep+ * the normalizer it meant to replace, which has seen every record. */+ failed: boolean+}++/** The first record is only ever wanted for its metadata (Codex `session_meta`, a few KB). */+export const HEAD_RECORD_LIMIT = 4 * 1024 * 1024++/** How far before a turn the walk reaches for what the turn depends on. Those records sit just before+ * it in practice (Codex's `turn_context` is two records back); this only caps the rare session where+ * one was never written, which would otherwise be read back to BOF on every attach. */+export const ATTACH_REACH_BYTES = 64 * 1024 * 1024++const hasAny = (bytes: Buffer, markers: readonly Buffer[] | undefined): boolean =>+ !markers || markers.some((marker) => bytes.includes(marker))++/** A record with no line ending yet is whole only if it parses; half a record belongs to the tail. */+export function isWholeRecord(line: string): boolean {+ try { JSON.parse(line); return true } catch { return false }+}++const wholeFile = (end: number): AttachSpan => ({ end, turnFrom: 0, profileFrom: 0, head: null, seeds: [] })++export interface LocateOptions {+ /** A transcript that IS its first turn (born after its agent) is replayed whole. */+ fromStart?: boolean+ /** Read only up to here — where a tail that is being taken over stopped. Defaults to the file size. */+ end?: number+ /** See `ATTACH_REACH_BYTES`. */+ reach?: number+}++/** Walk back from the end to everything an attach needs. Null when the file shrank under the walk. */+export async function locateAttachSpan(filePath: string, rules: AttachRules, options: LocateOptions = {}): Promise<AttachSpan | null> {+ const { size } = await stat(filePath)+ const end = options.end === undefined ? size : Math.min(options.end, size)+ const reach = options.reach ?? ATTACH_REACH_BYTES+ if (options.fromStart || end === 0) return wholeFile(end)+ let opener: number | null = null+ let begin: number | null = null+ let seekingBegin = !!rules.turnBegin+ let profileFrom = end+ let seedTest: ((line: string) => boolean) | null = null+ const seeds: Array<{ offset: number; line: string }> = []+ const missing = new Set(rules.required)+ // Calls the turn's results answer that it does not make itself.+ const unresolved = new Set<string>()+ // Every call answered after the point reached: a call before the turn without an answer is still+ // running, and its result will arrive live, naming it.+ const answered = new Set<string>()+ let seekingCalls = false+ const whole = await scanRecordsBackward(filePath, end, (bytes, offset) => {+ let decoded: string | null = null+ const line = (): string => (decoded ??= bytes.toString('utf8'))+ // Past the reach: what is still sought was not written near enough to matter.+ if (opener !== null && opener - offset > reach) return true+ if (opener === null) {+ // Inside the turn: note the earlier calls its results answer, and the ones it makes itself.+ if (rules.links && hasAny(bytes, rules.linkMarkers)) {+ const { defines, references } = rules.links(line())+ for (const id of defines) unresolved.delete(id)+ // A result with no id cannot be matched to any call; it is not worth a walk.+ for (const id of references) if (id) { unresolved.add(id); answered.add(id) }+ }+ if (hasAny(bytes, rules.turnMarkers) && rules.startsTurn(line())) {+ opener = offset+ seedTest = rules.seedFor?.(line()) ?? null+ // A call still running when the turn opened is in the turn before it.+ seekingCalls = !!rules.links+ }+ } else {+ if (seekingBegin && hasAny(bytes, rules.turnBegin!.markers)) {+ if (rules.turnBegin!.begins(line())) { begin = offset; seekingBegin = false }+ else if (rules.turnBegin!.ends(line())) seekingBegin = false+ }+ if (seedTest && hasAny(bytes, rules.seedMarkers) && seedTest(line())) {+ seeds.push({ offset, line: line() })+ seedTest = null+ }+ const previousOpener = seekingCalls && hasAny(bytes, rules.turnMarkers) && rules.startsTurn(line())+ if ((seekingCalls || unresolved.size) && hasAny(bytes, rules.linkMarkers)) {+ const { defines, references } = rules.links!(line())+ const wanted = defines.filter((id) => unresolved.has(id) || (seekingCalls && !!id && !answered.has(id)))+ if (wanted.length) {+ for (const id of wanted) unresolved.delete(id)+ seeds.push({ offset, line: line() })+ }+ for (const id of references) if (id) answered.add(id)+ }+ if (previousOpener) seekingCalls = false+ }+ if (missing.size && hasAny(bytes, rules.fieldMarkers)) {+ const set = rules.fields(line())+ if (set.some((field) => missing.has(field))) {+ for (const field of set) missing.delete(field)+ profileFrom = offset+ }+ }+ return opener !== null && !seekingBegin && !missing.size && !seedTest && !unresolved.size && !seekingCalls+ })+ if (!whole) return null+ // No opener anywhere: the whole file is the turn, as the whole-history fold would have it.+ const turnFrom = begin ?? opener ?? 0+ const from = Math.min(profileFrom, turnFrom)+ let head: string | null = null+ if (from > 0) {+ await streamRecords(filePath, 0, Math.min(end, HEAD_RECORD_LIMIT), (record) => {+ head = record+ return true+ }, isWholeRecord)+ }+ return {+ end,+ turnFrom,+ profileFrom: from,+ head,+ // A record found while reaching back that the fold reads anyway is not fed twice.+ seeds: seeds.filter((seed) => seed.offset < turnFrom).sort((a, b) => a.offset - b.offset).map((seed) => seed.line),+ }+}++/**+ * Feed the span to its consumers, one record at a time. If the file shrank meanwhile, what it still+ * held was replayed and the tail picks up at the span's end. A consumer that throws on a record loses+ * that record, as a live line it threw on would be lost, and the replay goes on: stopping would leave+ * the tail nowhere exact to start.+ */+export async function replayAttachSpan(+ filePath: string,+ span: AttachSpan,+ consumers: AttachConsumers,+): Promise<AttachRead> {+ let failures = 0+ let firstFailure: unknown = null+ const feed = (consume: (line: string) => void, line: string): void => {+ try { consume(line) } catch (error) { if (failures++ === 0) firstFailure = error }+ }+ const { profile, fold, observe } = consumers+ consumers.start?.(span)+ if (span.head !== null) feed(profile, span.head)+ for (const seed of span.seeds) feed(fold, seed)+ let records = 0+ const read = await streamRecords(filePath, span.profileFrom, span.end, (line, offset) => {+ feed(profile, line)+ if (offset < span.turnFrom) return+ records+++ if (observe) feed(observe, line)+ feed(fold, line)+ }, isWholeRecord)+ if (failures) console.warn(`[attach] ${filePath}: ${failures} record(s) could not be taken in: ${String(firstFailure)}`)+ return { next: read?.next ?? span.end, records, content: records > 0 || !!read?.partial }+}++/** How far a file reaches, up to `end`; 0 for one that is not there. */+async function reach(filePath: string, end: number | undefined): Promise<number> {+ try {+ const { size } = await stat(filePath)+ return end === undefined ? size : Math.min(end, size)+ } catch { return 0 }+}++/**+ * Locate, then replay. A file that shrank under the walk is walked once more and then replayed whole.+ * One that is not there — moved, archived or deleted since it was announced — is an empty history, as+ * it always was. A file that cannot be read through (`failed`) leaves the history unread, not+ * unwritten: the tail resumes where the read was meant to end — never at byte 0, from where it would+ * deliver old turns as new ones, and not at a later end, past a record written while it read. A record+ * the engine was still writing right there, if the read failed before reaching it, is lost to both.+ */+export async function attachTranscript(+ filePath: string,+ rules: AttachRules,+ consumers: AttachConsumers,+ options: Omit<LocateOptions, 'reach'> = {},+): Promise<AttachResult> {+ let span: AttachSpan | null = null+ try {+ span = await locateAttachSpan(filePath, rules, options)+ ?? await locateAttachSpan(filePath, rules, options)+ ?? wholeFile(Math.min(options.end ?? Infinity, (await stat(filePath)).size))+ return { ...span, ...await replayAttachSpan(filePath, span, consumers), failed: false }+ } catch (error) {+ console.warn(`[attach] ${filePath} could not be read: ${String(error)}`)+ const end = span ? span.end : await reach(filePath, options.end)+ return { ...(span ?? wholeFile(end)), next: end, records: 0, content: end > 0, failed: true }+ }+}++const bytes = (...markers: string[]): Buffer[] => markers.map((marker) => Buffer.from(marker))++/**+ * Claude Code: a turn opens on a real user prompt, always a `"type":"user"` record. Its results name+ * their tool from the call that made it, so calls the turn answers are reached for. The chips read+ * only the model from the transcript — the attach takes effort from Claude's settings straight after —+ * and `Set model to` is matched case-insensitively, so field records are asked for without a byte test.+ */+export function claudeAttachRules(fields: (line: string) => readonly RuntimeField[]): AttachRules {+ return {+ startsTurn: startsClaudeTurn,+ turnMarkers: bytes('"user"'),+ fields,+ required: ['model'],+ links: claudeToolLinks,+ linkMarkers: bytes('tool_use', 'tool_result'),+ }+}++/**+ * Codex: a turn opens on a user message (`user_message`, or `UserMessage` inside `item_completed`) or a+ * `/goal` injection, and its task began at the `task_started` before it. Model, effort and mode arrive+ * together in `turn_context` and `thread_settings_applied`, written just before the turn's first+ * message. A continuing goal's label depends on the goal before it.+ */+export function codexAttachRules(fields: (line: string) => readonly RuntimeField[]): AttachRules {+ return {+ startsTurn: startsCodexTurn,+ turnMarkers: bytes('user_message', 'UserMessage', 'codex_internal_context'),+ turnBegin: {+ begins: (line) => codexTaskBoundary(line) === 'begins',+ ends: (line) => codexTaskBoundary(line) === 'ends',+ markers: bytes('task_started', 'task_complete', 'turn_aborted'),+ },+ fields,+ fieldMarkers: bytes('turn_context', 'thread_settings_applied'),+ required: ['model', 'effort', 'mode'],+ seedFor: (opener) => (codexGoalOf(opener) === null ? null : (line) => codexGoalOf(line) !== null),+ seedMarkers: bytes('codex_internal_context'),+ }+}diff --git a/cli/src/lib/normalize.ts b/cli/src/lib/normalize.tsindex f8f1a6e5f..3664c6ca2 100644--- a/cli/src/lib/normalize.ts+++ b/cli/src/lib/normalize.ts@@ -755,6 +755,9 @@ export interface TurnState {/** tool_use ids started but not yet resolved by a tool_result. */pendingTools: Set<string>thinkingCounter: number+ /** Before the counter in a live thinking id. A fold that starts mid-transcript names its window here+ * (lib/attachTranscript.ts), so its ids cannot repeat ones another fold of the same session sent. */+ thinkingPrefix?: string}export function newTurnState(): TurnState {@@ -791,6 +794,37 @@ export function foldTranscript(}}+/**+ * `foldTranscript` one record at a time, for a transcript streamed in rather than loaded+ * (lib/attachTranscript.ts). History keeps only its last `turn_started` — the one event an attach ever+ * replays from it — so folding a long turn holds nothing but that.+ */+export class TranscriptFold {+ private lastStarted: LiveEvent | null = null+ private readonly folded: LiveEvent[] = []++ constructor(+ private readonly ingest: (line: string) => LiveEvent[],+ private readonly turnOpenAfter: () => boolean,+ private readonly live: boolean,+ ) {}++ push(line: string): void {+ for (const event of this.ingest(line)) {+ if (this.live) this.folded.push(event)+ else if (event.type === 'turn_started') this.lastStarted = event+ }+ }++ finish(): { history: LiveEvent[]; live: LiveEvent[]; turnOpen: boolean } {+ return {+ history: this.lastStarted ? [this.lastStarted] : [],+ live: this.folded,+ turnOpen: !this.live && this.turnOpenAfter(),+ }+ }+}+// Terminal assistant stop reasons that close a turn. `tool_use` is deliberately absent (the turn// continues into the tool). `pause_turn` is absent too — it may legitimately resume; the Stop hook// (which only fires when the agent is truly done) is the authoritative catch-all for that case.@@ -855,7 +889,7 @@ export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {// assistantconst before = events.length- events.push(...assistantEvents(msg, state.toolIdToName, 'thinking-live-', state.thinkingCounter))+ events.push(...assistantEvents(msg, state.toolIdToName, state.thinkingPrefix ?? 'thinking-live-', state.thinkingCounter))state.thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').lengthfor (const e of events) {if (e.type === 'tool_start') state.pendingTools.add(e.payload.id)@@ -868,3 +902,55 @@ export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {}return events}++function parseRecord(rawLine: string): Record<string, unknown> | null {+ if (!rawLine.trim()) return null+ try {+ const raw = JSON.parse(rawLine) as unknown+ return raw && typeof raw === 'object' ? raw as Record<string, unknown> : null+ } catch { return null }+}++/**+ * The record `lineToEvents` opens a turn on — a real user prompt — decided from the record alone, as+ * `lineToEvents` decides it whatever came before. Attaching reads a transcript backward to the last+ * one of these and folds only from there (lib/attachTranscript.ts): every turn-scoped piece of+ * `TurnState` is reset by it, so the fold from here ends exactly where the whole-history fold does.+ */+export function startsClaudeTurn(rawLine: string): boolean {+ const raw = parseRecord(rawLine)+ if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return false+ const msg = transformLine(raw)+ if (!msg?.message || msg.type !== 'user' || isInterruptLine(msg)) return false+ return realUserText(msg) !== null+}++/**+ * The tool calls a Claude record makes (`defines`) and the earlier calls whose results it carries+ * (`references`), decided along `lineToEvents`' own branches. A result names its tool from the call+ * `lineToEvents` saw earlier, so an attach that starts mid-transcript reaches back for the calls its+ * turn's results answer (lib/attachTranscript.ts).+ */+export function claudeToolLinks(rawLine: string): { defines: string[]; references: string[] } {+ const raw = parseRecord(rawLine)+ if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return { defines: [], references: [] }+ const msg = transformLine(raw)+ if (!msg?.message) return { defines: [], references: [] }+ if (msg.type === 'assistant') {+ return { defines: msg.message.content.filter((block) => block.type === 'tool_use').map((block) => block.id || ''), references: [] }+ }+ if (isInterruptLine(msg) || realUserText(msg) !== null) return { defines: [], references: [] }+ return { defines: [], references: msg.message.content.filter((block) => block.type === 'tool_result').map((block) => block.tool_use_id || '') }+}++/** `tailFileUntil` selector for `lastTurnTextFromRawLines`: stop on the prompt it resets on, keep the+ * assistant records it reads after that, and drop everything else it ignores — so a recap reads the+ * last turn's text instead of the whole conversation. */+export function selectClaudeRecapLine(line: string): 'keep' | 'skip' | 'stop' {+ const raw = parseRecord(line)+ if (!raw || compactEventFromRaw(raw) !== undefined) return 'skip'+ const msg = transformLine(raw)+ if (!msg?.message) return 'skip'+ if (realUserText(msg) !== null) return 'stop'+ return msg.type === 'assistant' ? 'keep' : 'skip'+}diff --git a/cli/src/lib/runtimeProfile.spec.ts b/cli/src/lib/runtimeProfile.spec.tsindex 64d2cef45..cae2823a9 100644--- a/cli/src/lib/runtimeProfile.spec.ts+++ b/cli/src/lib/runtimeProfile.spec.ts@@ -429,3 +429,79 @@ describe('RuntimeProfileManager', () => {expect(parseRuntimeProfile(manager.selectedModel(value))).toMatchObject({ effort: 'ultra' })})})++describe('RuntimeProfileManager.transcriptFields', () => {+ const codexLine = (type: string, payload: Record<string, unknown>) => JSON.stringify({ type, payload })++ it('names the fields a Codex record sets, through the same reader as ingest', () => {+ const manager = new RuntimeProfileManager()+ const codex = session('codex')+ expect(manager.transcriptFields(codex, codexLine('turn_context', { model: 'gpt-6', reasoning_effort: 'high', collaboration_mode: { mode: 'plan' } })))+ .toEqual(['model', 'effort', 'mode'])+ expect(manager.transcriptFields(codex, codexLine('turn_context', { model: 'gpt-6', collaboration_mode: { mode: 'default' } }))).toEqual(['model', 'mode'])+ expect(manager.transcriptFields(codex, codexLine('event_msg', { type: 'thread_settings_applied', thread_settings: { model: 'gpt-6', reasoning_effort: 'low' } })))+ .toEqual(['model', 'effort'])+ expect(manager.transcriptFields(codex, codexLine('session_meta', { cli_version: '0.159.0' }))).toEqual([])+ expect(manager.transcriptFields(codex, codexLine('event_msg', { type: 'user_message', message: 'hi' }))).toEqual([])+ })++ it('names the fields a Claude record sets', () => {+ const manager = new RuntimeProfileManager()+ const claude = session('claude')+ const assistant = (model: string) => JSON.stringify({ type: 'assistant', version: '2.1.212', message: { role: 'assistant', model, content: [] } })+ expect(manager.transcriptFields(claude, assistant('claude-opus-5-5'))).toEqual(['model'])+ expect(manager.transcriptFields(claude, assistant('<synthetic>'))).toEqual([])+ const local = (text: string) => JSON.stringify({ type: 'user', message: { role: 'user', content: `<local-command-stdout>${text}</local-command-stdout>` } })+ expect(manager.transcriptFields(claude, local('Set effort level to high'))).toEqual(['effort'])+ expect(manager.transcriptFields(claude, JSON.stringify({ type: 'user', message: { role: 'user', content: 'plain' } }))).toEqual([])+ })++ it('leaves the session, its controls and its state untouched', () => {+ const manager = new RuntimeProfileManager()+ const claude = session('claude')+ manager.hydrate(claude, [JSON.stringify({ type: 'assistant', message: { model: 'claude-opus-5-5' } })])+ const before = manager.getState(claude.sessionId)+ expect(manager.transcriptFields(claude, JSON.stringify({ type: 'assistant', version: '9.9.9', message: { model: 'claude-fable-5-1' } }))).toEqual(['model'])+ expect(manager.getState(claude.sessionId)).toEqual(before)+ expect(claude.cliVersion).toBe('2.1.212')+ })++ it('answers nothing for other engines or a record that is not an object', () => {+ const manager = new RuntimeProfileManager()+ expect(manager.transcriptFields(session('grok'), JSON.stringify({ params: { update: { _meta: { modelId: 'grok-5' } } } }))).toEqual([])+ expect(manager.transcriptFields(session('codex'), 'not json')).toEqual([])+ expect(manager.transcriptFields(session('codex'), '[1]')).toEqual([])+ })+})++describe('RuntimeProfileManager.beginHydrate', () => {+ const turnContext = JSON.stringify({ type: 'turn_context', payload: { model: 'gpt-6', reasoning_effort: 'high', collaboration_mode: { mode: 'plan' } } })++ it('changes nothing the session shows until commit, then shows the staged state', () => {+ const manager = new RuntimeProfileManager()+ const codex = session('codex')+ manager.hydrate(codex, [JSON.stringify({ type: 'turn_context', payload: { model: 'gpt-5', reasoning_effort: 'low' } })])+ const before = manager.getState(codex.sessionId)+ const staged = manager.beginHydrate(codex)+ staged.ingest(turnContext)+ staged.ingest('not json')+ staged.ingest('[1]')+ expect(manager.getState(codex.sessionId)).toEqual(before)+ staged.commit()+ expect(manager.getState(codex.sessionId)).toMatchObject({ model: 'gpt-6', effort: 'high', mode: 'plan', cliVersion: '0.144.5' })+ })++ it('reads Claude records too, and keeps an unbound session out of the shared state', () => {+ const manager = new RuntimeProfileManager()+ const claude = session('claude')+ const staged = manager.beginHydrate(claude)+ staged.ingest(JSON.stringify({ type: 'assistant', version: '2.1.270', message: { model: 'claude-opus-5-5' } }))+ staged.commit()+ expect(manager.getState(claude.sessionId)).toMatchObject({ model: 'claude-opus-5-5', cliVersion: '2.1.270' })+ const unbound = { ...session('codex'), sessionId: '' }+ const nothing = manager.beginHydrate(unbound)+ nothing.ingest(turnContext)+ nothing.commit()+ expect(manager.getState('')).toMatchObject({ model: null })+ })+})diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex 9e3694113..6e7e2928e 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -68,6 +68,26 @@ export interface RuntimeState {observedAt: number | null}+/** The runtime axes a transcript record can set — see `RuntimeProfileManager.transcriptFields`. */+export type RuntimeField = 'model' | 'effort' | 'mode'++/** The session `transcriptFields` reads as — never a real one, so no model-switch control applies.+ * No engine session id is empty or starts with NUL. */+const FIELD_PROBE = '\u0000transcript-fields'++const blankState = (): RuntimeState => ({ model: null, effort: null, mode: 'unknown', cliVersion: null, observedAt: null })++/** Where a session's runtime state starts before its transcript is read. */+function freshState(session: RegisteredSession): RuntimeState {+ return {+ ...blankState(),+ // Registries written by older builds can hold a non-string model; treat it as unknown instead of+ // letting it reach claudeAliasForModel and abort startup.+ model: typeof session.model === 'string' ? session.model : null,+ cliVersion: session.cliVersion,+ }+}+export interface CursorModelTarget {rawId: stringmodelKey: string@@ -672,18 +692,34 @@ export class RuntimeProfileManager {hydrate(session: RegisteredSession, rawLines: string[]): void {if (this.unbound(session.sessionId)) return- this.states.set(session.sessionId, {- // Registries written by older builds can hold a non-string model; treat it as unknown instead of- // letting it reach claudeAliasForModel and abort startup.- model: typeof session.model === 'string' ? session.model : null,- effort: null,- mode: 'unknown',- cliVersion: session.cliVersion,- observedAt: null,- })+ this.states.set(session.sessionId, freshState(session))for (const line of rawLines) this.ingest(session, line, true)}+ /**+ * `hydrate`, for a Claude Code or Codex transcript streamed in rather than loaded+ * (lib/attachTranscript.ts): records are read into a staged state, and what the session shows only+ * changes at `commit` — never an empty chip while the read runs, never a live record overwritten by+ * an older one read after it.+ */+ beginHydrate(session: RegisteredSession): { ingest(rawLine: string): void; commit(): void } {+ const staged = freshState(session)+ return {+ ingest: (rawLine) => {+ let raw: Record<string, unknown> | null+ try { raw = record(JSON.parse(rawLine)) } catch { return }+ if (!raw) return+ if (session.engine === 'codex') this.ingestCodex(session, raw, staged)+ else this.ingestClaude(session, raw, staged)+ },+ commit: () => {+ if (this.unbound(session.sessionId)) return+ this.states.set(session.sessionId, staged)+ this.wake(session.sessionId)+ },+ }+ }+ingest(session: RegisteredSession, rawLine: string, silent = false): boolean {let raw: Record<string, unknown> | nulltry { raw = record(JSON.parse(rawLine)) } catch { return false }@@ -708,6 +744,31 @@ export class RuntimeProfileManager {return before !== after}+ /**+ * Which of model, effort and mode one Claude or Codex transcript record sets — asked of the same+ * readers `ingest` uses, on a scratch state, so the two cannot disagree. An attach that reads only the+ * end of a transcript (lib/attachTranscript.ts) reaches back to the newest record that set each one.+ *+ * It can only under-report (the session's own model-switch control is not consulted), and the attach+ * replays every record from the oldest one it reached, so under-reporting costs a longer reach, never+ * a wrong value.+ */+ transcriptFields(session: RegisteredSession, rawLine: string): RuntimeField[] {+ if (session.engine !== 'claude' && session.engine !== 'codex') return []+ let raw: Record<string, unknown> | null+ try { raw = record(JSON.parse(rawLine)) } catch { return [] }+ if (!raw) return []+ const probe: RegisteredSession = { ...session, sessionId: FIELD_PROBE }+ const state = blankState()+ if (session.engine === 'codex') this.ingestCodex(probe, raw, state)+ else this.ingestClaude(probe, raw, state)+ const fields: RuntimeField[] = []+ if (state.model !== null) fields.push('model')+ if (state.effort !== null) fields.push('effort')+ if (state.mode !== 'unknown') fields.push('mode')+ return fields+ }+async ingestConfig(session: RegisteredSession, silent = false): Promise<boolean> {if (session.engine === 'hermes') {// Both axes are scalars in config.yaml and neither is announced, so this poll is the only reader.@@ -1154,18 +1215,16 @@ export class RuntimeProfileManager {}private state(sessionId: string): RuntimeState {- const blank = (): RuntimeState => ({ model: null, effort: null, mode: 'unknown', cliVersion: null, observedAt: null })- if (this.unbound(sessionId)) return blank()+ if (this.unbound(sessionId)) return blankState()let state = this.states.get(sessionId)if (!state) {- state = blank()+ state = blankState()this.states.set(sessionId, state)}return state}- private ingestCodex(session: RegisteredSession, raw: Record<string, unknown>): void {- const state = this.state(session.sessionId)+ private ingestCodex(session: RegisteredSession, raw: Record<string, unknown>, state = this.state(session.sessionId)): void {const payload = record(raw.payload)const cliVersion = raw.type === 'session_meta' ? text(payload?.cli_version) : ''if (parseVersion(cliVersion)) {@@ -1214,8 +1273,7 @@ export class RuntimeProfileManager {}}- private ingestClaude(session: RegisteredSession, raw: Record<string, unknown>): void {- const state = this.state(session.sessionId)+ private ingestClaude(session: RegisteredSession, raw: Record<string, unknown>, state = this.state(session.sessionId)): void {const cliVersion = text(raw.version)if (parseVersion(cliVersion)) {session.cliVersion = cliVersiondiff --git a/cli/src/lib/transcriptTail.spec.ts b/cli/src/lib/transcriptTail.spec.tsindex 27fb0fec6..3d754e45f 100644--- a/cli/src/lib/transcriptTail.spec.ts+++ b/cli/src/lib/transcriptTail.spec.ts@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { appendFileSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { tailFile, tailFileUntil } from './transcriptTail.js'+import { scanRecordsBackward, streamRecords, tailFile, tailFileUntil } from './transcriptTail.js'describe('backward transcript suffix', () => {let directory: string, file: string@@ -84,3 +84,111 @@ describe('backward transcript suffix', () => {expect(await tailFileUntil(file, () => 'stop')).toEqual(['answer'])})})++describe('record walks', () => {+ let directory: string, file: string+ beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'record-walk-')); file = join(directory, 't.jsonl') })+ afterEach(() => rmSync(directory, { recursive: true, force: true }))++ const records = ['first', 'é📘漢字'.repeat(30_000), '{"third":3}', 'x'.repeat(70_000), 'last']+ const offsets = (text: string, separator: string) => {+ const out: number[] = []+ let at = 0+ for (const part of text.split(separator)) { if (part.trim()) out.push(Buffer.byteLength(text.slice(0, at))); at += part.length + separator.length }+ return out+ }+ const backward = async (end?: number, max?: number) => {+ const seen: Array<[string, number]> = []+ const whole = await scanRecordsBackward(file, end ?? (await import('node:fs')).statSync(file).size, (bytes, offset) => { seen.push([bytes.toString('utf8'), offset]) }, max)+ return { whole, seen: seen.reverse() }+ }+ const forward = async (start = 0, end?: number, complete = (_: string) => true, max?: number, stopAt?: string) => {+ const seen: Array<[string, number]> = []+ const read = await streamRecords(file, start, end ?? (await import('node:fs')).statSync(file).size, (line, offset) => {+ seen.push([line, offset])+ return line === stopAt+ }, complete, max)+ return { read, seen }+ }++ it.each(['\n', '\r\n', '\r'])('agree on every record and where it starts with %j separators', async (separator) => {+ const text = records.join(separator) + separator+ writeFileSync(file, text)+ const expected = records.map((record, index) => [record, offsets(text, separator)[index]])+ expect((await backward()).seen).toEqual(expected)+ expect((await forward()).seen).toEqual(expected)+ expect((await forward()).read).toEqual({ next: Buffer.byteLength(text), records: 5, partial: false })+ })++ it('skip blank records by JavaScript trim rules, without dropping invisible but non-blank ones', async () => {+ writeFileSync(file, ['a', ' ', '\u00a0\u2028\ufeff', '\u0001', '\t', 'b'].join('\n'))+ const expected = [['a', 0], ['\u0001', Buffer.byteLength('a\n \n\u00a0\u2028\ufeff\n')], ['b', Buffer.byteLength('a\n \n\u00a0\u2028\ufeff\n\u0001\n\t\n')]]+ expect((await backward()).seen).toEqual(expected)+ expect((await forward()).seen).toEqual(expected)+ })++ it('stop when the visitor says so', async () => {+ writeFileSync(file, 'a\nb\nc\n')+ const seen: string[] = []+ expect(await scanRecordsBackward(file, 6, (bytes) => { seen.push(bytes.toString()); return bytes.toString() === 'b' })).toBe(true)+ expect(seen).toEqual(['c', 'b'])+ expect(await forward(0, undefined, undefined, undefined, 'b')).toEqual({ read: { next: 4, records: 2, partial: false }, seen: [['a', 0], ['b', 2]] })+ })++ it('pass over a record longer than the limit, whether or not it spans chunks', async () => {+ for (const big of ['y'.repeat(100), 'y'.repeat(200_000)]) {+ writeFileSync(file, `a\n${big}\nb\n`)+ const at = Buffer.byteLength(`a\n${big}\n`)+ expect((await backward(undefined, 50)).seen).toEqual([['a', 0], ['b', at]])+ expect((await forward(0, undefined, undefined, 50)).seen).toEqual([['a', 0], ['b', at]])+ writeFileSync(file, `${big}\nb`)+ expect((await backward(undefined, 50)).seen).toEqual([['b', big.length + 1]])+ writeFileSync(file, `a\n${big}`)+ expect((await forward(0, undefined, undefined, 50)).read).toEqual({ next: 2, records: 1, partial: false })+ }+ })++ it('leave a final record without its line ending to the reader after, unless it is complete', async () => {+ writeFileSync(file, '{"a":1}\n{"b":')+ expect(await forward(0, undefined, (line) => { try { JSON.parse(line); return true } catch { return false } }))+ .toEqual({ read: { next: 8, records: 1, partial: true }, seen: [['{"a":1}', 0]] })+ writeFileSync(file, '{"a":1}\n{"b":2}')+ expect((await forward(0, undefined, () => true)).read).toEqual({ next: 15, records: 2, partial: false })+ writeFileSync(file, '{"a":1}\n ')+ expect((await forward(0, undefined, () => false)).read).toEqual({ next: 8, records: 1, partial: false })+ })++ it('start mid-file and keep a CRLF split across the chunk edge together', async () => {+ writeFileSync(file, 'skip\r\n' + 'z'.repeat(65_535) + '\r\nend\r\n')+ expect(await forward(6)).toEqual({+ read: { next: 6 + 65_535 + 2 + 5, records: 2, partial: false },+ seen: [['z'.repeat(65_535), 6], ['end', 6 + 65_535 + 2]],+ })+ })++ it('report a file that shrank under the walk', async () => {+ writeFileSync(file, 'a\nb\n')+ expect(await scanRecordsBackward(file, 500, () => {})).toBe(false)+ expect(await streamRecords(file, 0, 500, () => {}, () => true)).toBeNull()+ })++ it('walk nothing in an empty range', async () => {+ writeFileSync(file, 'a\n')+ expect(await scanRecordsBackward(file, 0, () => { throw new Error('visited') })).toBe(true)+ expect(await streamRecords(file, 2, 2, () => { throw new Error('fed') }, () => true)).toEqual({ next: 2, records: 0, partial: false })+ })+})++describe('tailFile', () => {+ let directory: string, file: string+ beforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'tail-file-')); file = join(directory, 't.jsonl') })+ afterEach(() => rmSync(directory, { recursive: true, force: true }))++ it('returns nothing for a count that is not a positive number', async () => {+ writeFileSync(file, 'a\nb\n')+ expect(await tailFile(file, Number.NaN)).toEqual([])+ expect(await tailFile(file, -Infinity)).toEqual([])+ expect(await tailFile(file, 0)).toEqual([])+ expect(await tailFile(file, 1.9)).toEqual(['b'])+ })+})diff --git a/cli/src/lib/transcriptTail.ts b/cli/src/lib/transcriptTail.tsindex cfc17d740..4831b2ee0 100644--- a/cli/src/lib/transcriptTail.ts+++ b/cli/src/lib/transcriptTail.ts@@ -1,55 +1,178 @@-import { open } from 'node:fs/promises'+import { open, stat, type FileHandle } from 'node:fs/promises'import { createReadStream } from 'node:fs'import { createInterface } from 'node:readline'+const CHUNK_BYTES = 64 * 1024++/** A record longer than this is passed over unread by the walks below. No engine writes one — Codex's+ * compaction snapshots, the largest, are tens of MB — and one over V8's string limit (~512 MiB) could+ * not be decoded anyway. Holding one while looking for its end is the only thing either walk keeps. */+export const MAX_RECORD_BYTES = 256 * 1024 * 1024++/** `line.trim()` is empty — decided without decoding a record that has a visible ASCII character in it,+ * which is every JSONL record (they open with `{`). */+function isBlank(bytes: Buffer): boolean {+ for (const byte of bytes) if (byte > 0x20 && byte < 0x7f) return false+ return !bytes.toString('utf8').trim()+}++async function readFully(handle: FileHandle, chunk: Buffer, position: number): Promise<boolean> {+ let read = 0+ while (read < chunk.length) {+ const { bytesRead } = await handle.read(chunk, read, chunk.length - read, position + read)+ if (!bytesRead) return false+ read += bytesRead+ }+ return true+}++/**+ * Walk a transcript's records from byte `end` back to byte 0, newest first, holding one at a time.+ *+ * `visit` gets each non-blank record's bytes — valid only during the call — and the offset it starts+ * at; returning true stops the walk. LF, CR and CRLF each end a record, readline's rule. A record over+ * `maxRecordBytes` is passed over unvisited. Resolves false when the file shrank under the walk: what+ * was visited may then mix two versions of it.+ */+export async function scanRecordsBackward(+ filePath: string,+ end: number,+ visit: (record: Buffer, offset: number) => boolean | void,+ maxRecordBytes = MAX_RECORD_BYTES,+): Promise<boolean> {+ const handle = await open(filePath, 'r')+ try {+ let position = end+ // Pieces of the record being assembled, newest first; only ever one record's worth.+ let fragments: Buffer[] = []+ let fragmentBytes = 0+ let oversized = false+ const take = (head: Buffer, offset: number): boolean => {+ const skip = oversized || head.length + fragmentBytes > maxRecordBytes+ const bytes = skip || !fragments.length ? head : Buffer.concat([head, ...fragments.reverse()])+ fragments = []+ fragmentBytes = 0+ oversized = false+ if (skip || isBlank(bytes)) return false+ return visit(bytes, offset) === true+ }+ while (position > 0) {+ const length = Math.min(position, CHUNK_BYTES)+ position -= length+ const chunk = Buffer.allocUnsafe(length)+ if (!await readFully(handle, chunk, position)) return false+ let segmentEnd = length+ // Each native search advances independently: CR-free files must not rescan the+ // remaining chunk for CR once per LF. No per-byte JavaScript loop is needed.+ let lf = chunk.lastIndexOf(10), cr = chunk.lastIndexOf(13)+ while (lf >= 0 || cr >= 0) {+ const i = Math.max(lf, cr)+ // Match readline's LF, CRLF and bare-CR handling. The empty CRLF half is blank and skipped.+ if (take(chunk.subarray(i + 1, segmentEnd), position + i + 1)) return true+ segmentEnd = i+ if (lf === i) lf = i > 0 ? chunk.lastIndexOf(10, i - 1) : -1+ if (cr === i) cr = i > 0 ? chunk.lastIndexOf(13, i - 1) : -1+ }+ if (segmentEnd && !oversized) {+ fragmentBytes += segmentEnd+ if (fragmentBytes > maxRecordBytes) { oversized = true; fragments = [] }+ else fragments.push(chunk.subarray(0, segmentEnd))+ }+ }+ if (fragments.length || oversized) take(Buffer.alloc(0), 0)+ return true+ } finally { await handle.close() }+}++/**+ * Feed every non-blank record in [start, end) to `onRecord` with the offset it starts at, oldest first,+ * holding one at a time — the forward half of `scanRecordsBackward`, with the same record rules.+ * Returning true from `onRecord` stops after that record.+ *+ * A final record with no line ending yet is fed only when `complete` accepts it: an engine caught+ * mid-write leaves half a record there, and it belongs to whoever reads the file next (`partial`). `next`+ * is the offset just past the last record fed — exactly where a tail picks up. Null when the file shrank.+ */+export async function streamRecords(+ filePath: string,+ start: number,+ end: number,+ onRecord: (line: string, offset: number) => boolean | void,+ complete: (line: string) => boolean,+ maxRecordBytes = MAX_RECORD_BYTES,+): Promise<{ next: number; records: number; partial: boolean } | null> {+ const handle = await open(filePath, 'r')+ try {+ let position = start+ let next = start+ let records = 0+ let partial = false+ let pending: Buffer[] = []+ let pendingBytes = 0+ let oversized = false+ const emit = (bytes: Buffer): boolean => {+ if (isBlank(bytes)) return false+ records+++ return onRecord(bytes.toString('utf8'), next) === true+ }+ while (position < end) {+ const length = Math.min(end - position, CHUNK_BYTES)+ const chunk = Buffer.allocUnsafe(length)+ if (!await readFully(handle, chunk, position)) return null+ let segmentStart = 0+ let lf = chunk.indexOf(10), cr = chunk.indexOf(13)+ while (lf >= 0 || cr >= 0) {+ const i = lf < 0 ? cr : cr < 0 ? lf : Math.min(lf, cr)+ const piece = chunk.subarray(segmentStart, i)+ const stop = !oversized && pendingBytes + piece.length <= maxRecordBytes+ && emit(pending.length ? Buffer.concat([...pending, piece]) : piece)+ pending = []+ pendingBytes = 0+ oversized = false+ segmentStart = i + 1+ next = position + i + 1+ if (stop) return { next, records, partial }+ if (lf === i) lf = chunk.indexOf(10, i + 1)+ if (cr === i) cr = chunk.indexOf(13, i + 1)+ }+ if (segmentStart < length && !oversized) {+ pendingBytes += length - segmentStart+ if (pendingBytes > maxRecordBytes) { oversized = true; pending = [] }+ else pending.push(chunk.subarray(segmentStart))+ }+ position += length+ }+ if (pending.length) {+ const bytes = Buffer.concat(pending)+ const line = bytes.toString('utf8')+ if (!isBlank(bytes)) {+ if (complete(line)) {+ records+++ onRecord(line, next)+ next = end+ } else partial = true+ }+ }+ return { next, records, partial }+ } finally { await handle.close() }+}+/** Read selected JSONL records backward, then return them in chronological order.* `stop` includes the boundary record; `skip` discards an irrelevant record immediately.* Only complete records are decoded, so UTF-8 may cross any read boundary. The file length is* captured at open: later appends belong to the next read. A missing boundary reads back to BOF. */export async function tailFileUntil(filePath: string, select: (line: string) => 'keep' | 'skip' | 'stop'): Promise<string[]> {try {- const handle = await open(filePath, 'r')- try {- let position = (await handle.stat()).size- const lines: string[] = []- // Fragments of one record, newest first; never concatenate the whole conversation.- let fragments: Buffer[] = []- const take = (head: Buffer): boolean => {- const bytes = fragments.length ? Buffer.concat([head, ...fragments.reverse()]) : head- fragments = []- const line = bytes.toString('utf8')- if (!line.trim()) return false- const action = select(line)- if (action !== 'skip') lines.push(line)- return action === 'stop'- }- while (position > 0) {- const length = Math.min(position, 64 * 1024)- position -= length- const chunk = Buffer.allocUnsafe(length)- let read = 0- while (read < length) {- const { bytesRead } = await handle.read(chunk, read, length - read, position + read)- if (!bytesRead) return [] // Truncated during the read; don't recap a mixed snapshot.- read += bytesRead- }- let end = length- // Each native search advances independently: CR-free files must not rescan the- // remaining chunk for CR once per LF. No per-byte JavaScript loop is needed.- let lf = chunk.lastIndexOf(10), cr = chunk.lastIndexOf(13)- while (lf >= 0 || cr >= 0) {- const i = Math.max(lf, cr)- // Match readline's LF, CRLF and bare-CR handling. The empty CRLF half is ignored.- if (take(chunk.subarray(i + 1, end))) return lines.reverse()- end = i- if (lf === i) lf = i > 0 ? chunk.lastIndexOf(10, i - 1) : -1- if (cr === i) cr = i > 0 ? chunk.lastIndexOf(13, i - 1) : -1- }- if (end) fragments.push(chunk.subarray(0, end))- }- if (fragments.length) take(Buffer.alloc(0))- return lines.reverse()- } finally { await handle.close() }+ const { size } = await stat(filePath)+ const lines: string[] = []+ const whole = await scanRecordsBackward(filePath, size, (record) => {+ const line = record.toString('utf8')+ const action = select(line)+ if (action !== 'skip') lines.push(line)+ return action === 'stop'+ })+ // Truncated during the read; don't recap a mixed snapshot.+ return whole ? lines.reverse() : []} catch {return []}diff --git a/cli/src/testing/transcriptOracle.ts b/cli/src/testing/transcriptOracle.tsnew file mode 100644index 000000000..07e390e4a--- /dev/null+++ b/cli/src/testing/transcriptOracle.ts@@ -0,0 +1,132 @@+/**+ * The whole-history attach that `lib/attachTranscript.ts` replaced, kept as the oracle the end-first+ * read is checked against — by the unit suite on synthetic transcripts and by the opt-in real-data+ * suite on this computer's own (`attachTranscript.real.spec.ts`).+ */+import { CodexNormalizer, codexGoalOf, startsCodexTurn } from '../engines/codex/normalizer.js'+import { attachTranscript, claudeAttachRules, codexAttachRules } from '../lib/attachTranscript.js'+import { foldTranscript, lineToEvents, newTurnState, TranscriptFold, type LiveEvent } from '../lib/normalize.js'+import type { RegisteredSession } from '../lib/registry.js'+import { RuntimeProfileManager } from '../lib/runtimeProfile.js'+import { tailFile } from '../lib/transcriptTail.js'++export type Engine = 'claude' | 'codex'++export function session(engine: Engine): RegisteredSession {+ return {+ schemaVersion: 2,+ active: true,+ sessionId: `session:${engine}`, engine, launcherId: 'h1', agentId: 'h1', boundAt: 0, transcriptPath: '/tmp/t.jsonl', projectDir: 'tmp', cwd: '/tmp',+ tmuxPane: '%1', source: null, title: null, model: null,+ runtimes: [{ backend: 'tmux', paneId: '%1' }], primaryRuntimeKey: 'tmux\u0000%1',+ cliVersion: null, processIdentity: null,+ registeredAt: 1, touchedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,+ }+}++export interface Folded {+ turnOpen: boolean+ opened: LiveEvent | undefined+ live: LiveEvent[]+ profile: { model: string | null; effort: string | null; mode: string; cliVersion: string | null }+ ingest: (line: string) => LiveEvent[]+ content: boolean+}++export function newFold(engine: Engine): { ingest: (line: string) => LiveEvent[]; turnOpen: () => boolean; name(windowStart: number): void } {+ if (engine === 'codex') {+ const normalizer = new CodexNormalizer('live', () => null)+ return {+ ingest: (line) => normalizer.ingest(line),+ turnOpen: () => normalizer.turnOpen,+ name: (windowStart) => { normalizer.thinkingPrefix = `thinking-codex-${windowStart.toString(36)}-` },+ }+ }+ const state = newTurnState()+ return {+ ingest: (line) => lineToEvents(line, state),+ turnOpen: () => state.turnOpen,+ name: (windowStart) => { state.thinkingPrefix = `thinking-live-${windowStart.toString(36)}-` },+ }+}++const profileOf = (profiles: RuntimeProfileManager, s: RegisteredSession): Folded['profile'] => {+ const { model, effort, mode, cliVersion } = profiles.getState(s.sessionId)+ return { model, effort, mode, cliVersion }+}++export async function wholeHistory(engine: Engine, file: string, live: boolean): Promise<Folded> {+ const lines = await tailFile(file, Infinity)+ const s = session(engine)+ const profiles = new RuntimeProfileManager()+ profiles.hydrate(s, lines)+ // As attachSessionNow does next: Claude's effort comes from its settings, whatever the transcript said.+ await profiles.ingestConfig(s, true)+ const fold = newFold(engine)+ const out = foldTranscript(fold.ingest, lines, fold.turnOpen, { live })+ return {+ turnOpen: out.turnOpen,+ opened: out.history.findLast((event) => event.type === 'turn_started'),+ live: out.live,+ profile: profileOf(profiles, s),+ ingest: fold.ingest,+ content: lines.length > 0,+ }+}++export async function fromTheEnd(engine: Engine, file: string, live: boolean, end?: number): Promise<Folded & { next: number }> {+ const s = session(engine)+ const profiles = new RuntimeProfileManager()+ const fold = newFold(engine)+ const stream = new TranscriptFold(fold.ingest, fold.turnOpen, live)+ const fields = (line: string) => profiles.transcriptFields(s, line)+ const profile = profiles.beginHydrate(s)+ // As attachSessionNow does: the staged profile, ids named for the window, then Claude's settings.+ const read = await attachTranscript(file, engine === 'codex' ? codexAttachRules(fields) : claudeAttachRules(fields), {+ start: (span) => fold.name(span.turnFrom),+ profile: (line) => profile.ingest(line),+ fold: (line) => stream.push(line),+ }, { fromStart: live, end })+ profile.commit()+ await profiles.ingestConfig(s, true)+ const out = stream.finish()+ return {+ turnOpen: out.turnOpen,+ opened: out.history.findLast((event) => event.type === 'turn_started'),+ live: out.live,+ profile: profileOf(profiles, s),+ ingest: fold.ingest,+ content: read.content,+ next: read.next,+ }+}++/** Thinking ids number the blocks from wherever a fold starts; everything else must match exactly. */+export function canonical(events: LiveEvent[]): unknown[] {+ const ids = new Map<string, string>()+ return events.map((event) => {+ const payload = event.payload as Record<string, unknown>+ if (typeof payload.thinkingId !== 'string') return event+ if (!ids.has(payload.thinkingId)) ids.set(payload.thinkingId, `thinking#${ids.size}`)+ return { ...event, payload: { ...payload, thinkingId: ids.get(payload.thinkingId) } }+ })+}++/**+ * The one documented divergence beyond thinking ids: an ordinary opener does not look back for the goal+ * before it, so the first goal turn after it reads as that goal's submission. Applied only when the+ * attach-time opener is ordinary and a goal came before it — anywhere else the events must be equal.+ */+export function goalForgotten(records: string[], cut: number, events: LiveEvent[]): LiveEvent[] {+ const before = records.slice(0, cut)+ const opener = before.findLastIndex(startsCodexTurn)+ if (opener < 0 || codexGoalOf(before[opener]) !== null || !before.slice(0, opener).some((line) => codexGoalOf(line) !== null)) return events+ let done = false+ return events.map((event) => {+ if (done || event.type !== 'turn_started') return event+ const message = event.payload.userMessage+ if (!message.startsWith('/goal ') && !message.startsWith('Continuing goal: ')) return event+ done = true+ return { ...event, payload: { userMessage: message.replace(/^Continuing goal: /, '/goal ') } }+ })+}diff --git a/cli/src/watcher/watcher.spec.ts b/cli/src/watcher/watcher.spec.tsindex 21834499c..4d6b9d126 100644--- a/cli/src/watcher/watcher.spec.ts+++ b/cli/src/watcher/watcher.spec.ts@@ -1,11 +1,21 @@+import { chmodSync } from 'fs'import { appendFile, mkdtemp, rm, writeFile } from 'fs/promises'import { tmpdir } from 'os'import { join } from 'path'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { Watcher, type HistoryEvent, type LineEvent } from './watcher.js'const cleanup: string[] = []+/** Waits for what a timer delivers — a released hold's read, an expired hold — however slow the machine. */+const until = async (what: string, test: () => boolean, ms = 10_000): Promise<void> => {+ const deadline = Date.now() + ms+ while (!test()) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`)+ await new Promise((resolve) => setTimeout(resolve, 20))+ }+}+afterEach(async () => {await Promise.all(cleanup.splice(0).map((path) => rm(path, { recursive: true, force: true })))})@@ -209,3 +219,423 @@ describe('Watcher.pollAll', () => {await watcher.stop()})})++describe('Watcher.addSession fromOffset', () => {+ const setup = async () => {+ const dir = await mkdtemp(join(tmpdir(), 'machine-watcher-offset-'))+ cleanup.push(dir)+ const transcriptPath = join(dir, 'session.jsonl')+ const watcher = new Watcher()+ const lines: string[] = []+ const history: string[] = []+ watcher.on('line', (event: LineEvent) => lines.push(event.text))+ watcher.on('history', (event: HistoryEvent) => history.push(...event.lines.map((line) => line.text)))+ return { transcriptPath, watcher, lines, history }+ }++ it('tails from where the attach stopped reading, so a record written meanwhile is streamed live', async () => {+ const { transcriptPath, watcher, lines, history } = await setup()+ await writeFile(transcriptPath, '{"n":1}\n{"n":2}\n')+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath }, { fromOffset: 8 })+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":2}'])+ expect(history).toEqual([])+ await watcher.stop()+ })++ it('starts at the new end when the file shrank since the attach read it', async () => {+ const { transcriptPath, watcher, lines } = await setup()+ await writeFile(transcriptPath, '{"n":1}\n')+ await watcher.addSession({ sessionId: 's1', engine: 'claude', transcriptPath }, { fromOffset: 500 })+ await appendFile(transcriptPath, '{"n":2}\n')+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":2}'])+ await watcher.stop()+ })++ it('lets fromStart win, reading the existing content as history', async () => {+ const { transcriptPath, watcher, lines, history } = await setup()+ await writeFile(transcriptPath, '{"n":1}\n{"n":2}\n')+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath }, { fromStart: true, fromOffset: 8 })+ await watcher.pollSession('s1')+ expect(history).toEqual(['{"n":1}', '{"n":2}'])+ expect(lines).toEqual([])+ await watcher.stop()+ })+})++describe('Watcher.hold and release', () => {+ const tailed = async (content: string | Buffer) => {+ const dir = await mkdtemp(join(tmpdir(), 'machine-watcher-hold-'))+ cleanup.push(dir)+ const transcriptPath = join(dir, 'session.jsonl')+ await writeFile(transcriptPath, content)+ const watcher = new Watcher()+ const lines: string[] = []+ const history: string[] = []+ watcher.on('line', (event: LineEvent) => lines.push(event.text))+ watcher.on('history', (event: HistoryEvent) => history.push(...event.lines.map((line) => line.text)))+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath })+ return { transcriptPath, watcher, lines, history }+ }++ it('stops delivery where the next line starts, a carried partial line included, and resumes from a given byte', async () => {+ const { transcriptPath, watcher, lines } = await tailed('{"n":1}\n')+ await appendFile(transcriptPath, '{"n":2}\n{"n":')+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":2}'])+ const hold = (await watcher.hold('s1', transcriptPath))!+ expect(hold.offset).toBe(16)+ await appendFile(transcriptPath, '3}\n{"n":4}\n')+ await new Promise((resolve) => setTimeout(resolve, 60))+ expect(lines).toEqual(['{"n":2}'])+ hold.release(24)+ hold.release(0)+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":2}', '{"n":4}'])+ await watcher.stop()+ })++ it('counts a partial line in bytes, a character split between two reads included, and decodes it whole', async () => {+ const { transcriptPath, watcher, lines } = await tailed('{"n":1}\n')+ const accented = Buffer.from('{"a":"é漢"}\n')+ await appendFile(transcriptPath, accented.subarray(0, 9))+ await watcher.pollSession('s1')+ expect(lines).toEqual([])+ const hold = (await watcher.hold('s1', transcriptPath))!+ expect(hold.offset).toBe(8)+ hold.release()+ await appendFile(transcriptPath, accented.subarray(9))+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"a":"é漢"}'])+ await watcher.stop()+ })++ it('keeps its own position when released without one, and delivers what arrived while held', async () => {+ const { transcriptPath, watcher, lines } = await tailed('')+ const hold = (await watcher.hold('s1', transcriptPath))!+ await appendFile(transcriptPath, '{"n":1}\n')+ hold.release()+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":1}'])+ await watcher.stop()+ })++ it('stays held until every hold is released, and a drain waits for that', async () => {+ const { transcriptPath, watcher, lines } = await tailed('')+ const first = (await watcher.hold('s1', transcriptPath))!+ const second = (await watcher.hold('s1', transcriptPath))!+ await appendFile(transcriptPath, '{"n":1}\n')+ let drained = false+ const drain = watcher.pollSession('s1').then(() => { drained = true })+ first.release()+ await new Promise((resolve) => setTimeout(resolve, 60))+ expect(drained).toBe(false)+ expect(lines).toEqual([])+ second.release()+ await drain+ expect(lines).toEqual(['{"n":1}'])+ await watcher.stop()+ })++ it('lets go of a hold an attach never releases, says so, and lets a late release change nothing', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const { transcriptPath, watcher, lines } = await tailed('')+ const hold = (await watcher.hold('s1', transcriptPath, 40))!+ expect(hold.expired).toBe(false)+ await appendFile(transcriptPath, '{"n":1}\n')+ await until('the hold to let go and its read to deliver', () => lines.length > 0)+ expect(warn).toHaveBeenCalledOnce()+ expect(hold.expired).toBe(true)+ expect(lines).toEqual(['{"n":1}'])+ // The attach finishing late: where its read stopped is behind what was delivered since.+ hold.release(0)+ await appendFile(transcriptPath, '{"n":2}\n')+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":1}', '{"n":2}'])+ await watcher.stop()+ } finally { warn.mockRestore() }+ })++ it('keeps the position a repair moved the tail to while it was held', async () => {+ const { transcriptPath, watcher, lines, history } = await tailed(`{"n":1,"r":"${'x'.repeat(200)}"}\n{"n":2}\n`)+ const hold = (await watcher.hold('s1', transcriptPath))!+ // The Codex resume repair shrinks the rollout in place and pins the tail to its new end.+ const repaired = '{"n":1}\n{"n":2}\n'+ await writeFile(transcriptPath, repaired)+ watcher.setTail('s1', Buffer.byteLength(repaired))+ await appendFile(transcriptPath, '{"n":3}\n')+ hold.release(hold.offset)+ await watcher.pollSession('s1')+ expect({ lines, history }).toEqual({ lines: ['{"n":3}'], history: [] })+ await watcher.stop()+ })++ it('drains through a hold that lands during its read, once the hold lets go', async () => {+ const { transcriptPath, watcher, lines } = await tailed('')+ await appendFile(transcriptPath, '{"n":1}\n')+ const reading = watcher.pollAll()+ let drained = false+ // A drain asked for while that read runs (the Stop hook's), then a reset attach takes the tail.+ const drain = watcher.pollSession('s1').then(() => { drained = true })+ const held = watcher.hold('s1', transcriptPath)+ await appendFile(transcriptPath, '{"n":2}\n')+ await reading+ const hold = (await held)!+ await new Promise((resolve) => setTimeout(resolve, 60))+ expect(drained).toBe(false)+ hold.release()+ await drain+ expect(lines).toEqual(['{"n":1}', '{"n":2}'])+ await watcher.stop()+ })++ it('ends a drain waiting on a hold when the session is removed, or the watcher stops', async () => {+ for (const end of ['remove', 'stop'] as const) {+ const { transcriptPath, watcher } = await tailed('')+ const hold = (await watcher.hold('s1', transcriptPath))!+ const drain = watcher.pollSession('s1')+ if (end === 'remove') await watcher.removeSession('s1')+ else await watcher.stop()+ await drain+ hold.release()+ await watcher.stop()+ }+ })++ it('says which file it tails for a session', async () => {+ const { transcriptPath, watcher } = await tailed('')+ expect(watcher.tails('s1', transcriptPath)).toBe(true)+ expect(watcher.tails('s1', `${transcriptPath}.other`)).toBe(false)+ expect(watcher.tails('nobody', transcriptPath)).toBe(false)+ await watcher.removeSession('s1')+ expect(watcher.tails('s1', transcriptPath)).toBe(false)+ await watcher.stop()+ })++ it('stops a read in progress that more data would keep going, at the hold', async () => {+ const { transcriptPath, watcher, lines } = await tailed('')+ await appendFile(transcriptPath, '{"n":1}\n')+ const reading = watcher.pollAll()+ const held = watcher.hold('s1', transcriptPath)+ // Asks for another read while the first is running: without the hold the read would loop on.+ const another = watcher.pollAll()+ await appendFile(transcriptPath, '{"n":2}\n')+ await reading+ const hold = (await held)!+ await another+ expect(lines).toEqual(['{"n":1}'])+ hold.release()+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":1}', '{"n":2}'])+ await watcher.stop()+ })++ it('reads again when more is asked for during a read', async () => {+ const { transcriptPath, watcher, lines } = await tailed('')+ await appendFile(transcriptPath, '{"n":1}\n')+ const reading = watcher.pollSession('s1')+ const another = watcher.pollAll()+ await appendFile(transcriptPath, '{"n":2}\n')+ await reading+ await another+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":1}', '{"n":2}'])+ await watcher.stop()+ })++ it('skips blank lines and line endings in a live read', async () => {+ const { transcriptPath, watcher, lines } = await tailed('')+ await appendFile(transcriptPath, '\n \r\n{"n":1}\r\n\n{"n":2}\n')+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":1}', '{"n":2}'])+ await watcher.stop()+ })++ it('waits out a read in progress, and that read stops at the hold', async () => {+ const { transcriptPath, watcher, lines } = await tailed('')+ await appendFile(transcriptPath, '{"n":1}\n')+ const reading = watcher.pollAll()+ const held = watcher.hold('s1', transcriptPath)+ await appendFile(transcriptPath, '{"n":2}\n')+ await reading+ const hold = (await held)!+ expect(hold.offset).toBe(8)+ expect(lines).toEqual(['{"n":1}'])+ hold.release()+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":1}', '{"n":2}'])+ await watcher.stop()+ })++ it('cancels a read that was only scheduled, and reads it after release', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'machine-watcher-hold-'))+ cleanup.push(dir)+ const transcriptPath = join(dir, 'session.jsonl')+ await writeFile(transcriptPath, '{"n":1}\n{"n":2}\n')+ const watcher = new Watcher()+ const lines: string[] = []+ watcher.on('line', (event: LineEvent) => lines.push(event.text))+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath }, { fromOffset: 8 })+ const hold = (await watcher.hold('s1', transcriptPath))!+ expect(hold.offset).toBe(8)+ await new Promise((resolve) => setTimeout(resolve, 80))+ expect(lines).toEqual([])+ hold.release()+ await until('the read the release schedules', () => lines.length > 0)+ expect(lines).toEqual(['{"n":2}'])+ await watcher.stop()+ })++ it('holds nothing for a session it does not tail, or for another file than the one it tails', async () => {+ const { transcriptPath, watcher } = await tailed('')+ expect(await watcher.hold('nobody', transcriptPath)).toBeNull()+ expect(await watcher.hold('s1', `${transcriptPath}.other`)).toBeNull()+ await watcher.stop()+ })++ it('releases quietly after the session was removed', async () => {+ const { transcriptPath, watcher } = await tailed('')+ const hold = (await watcher.hold('s1', transcriptPath))!+ await watcher.removeSession('s1')+ expect(() => hold.release(5)).not.toThrow()+ await watcher.stop()+ })+})++describe('Watcher, at its edges', () => {+ const fresh = async (content = '') => {+ const dir = await mkdtemp(join(tmpdir(), 'machine-watcher-edges-'))+ cleanup.push(dir)+ const transcriptPath = join(dir, 'session.jsonl')+ await writeFile(transcriptPath, content)+ const watcher = new Watcher()+ const lines: string[] = []+ watcher.on('line', (event: LineEvent) => lines.push(event.text))+ return { dir, transcriptPath, watcher, lines }+ }+ // Private state, read only to see what the file system's events did.+ const internals = (watcher: Watcher) => watcher as unknown as {+ watcher: { emit(event: string, ...args: unknown[]): boolean } | null+ files: Map<string, { pending: boolean }>+ readNew(filePath: string): Promise<void>+ }++ it('follows what chokidar reports from start to stop, and logs the changes the turn engines ride on', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ const { dir, transcriptPath, watcher, lines } = await fresh()+ await watcher.addSession({ sessionId: 's1', engine: 'commandcode', transcriptPath })+ watcher.start()+ watcher.start()+ const second = join(dir, 'second.jsonl')+ await writeFile(second, '')+ await watcher.addSession({ sessionId: 's2', engine: 'codex', transcriptPath: second })+ await appendFile(transcriptPath, '{"n":1}\n')+ await until('the change to be read', () => lines.includes('{"n":1}'))+ expect(log.mock.calls.some(([line]) => String(line).startsWith('[watcher] change commandcode s1'))).toBe(true)+ await appendFile(second, '{"n":2}\n')+ await until('the second file to be read', () => lines.includes('{"n":2}'))+ expect(log.mock.calls.some(([line]) => String(line).startsWith('[watcher] change codex'))).toBe(false)+ await rm(transcriptPath)+ await until('the unlink to be noticed', () => internals(watcher).files.get(transcriptPath)?.pending === true)+ // Events for a file no longer tailed are dropped, however often they come.+ internals(watcher).watcher!.emit('change', join(dir, 'gone.jsonl'), undefined)+ internals(watcher).watcher!.emit('change', join(dir, 'gone.jsonl'), undefined)+ internals(watcher).watcher!.emit('unlink', join(dir, 'gone.jsonl'))+ internals(watcher).watcher!.emit('error', new Error('EMFILE'))+ expect(error).toHaveBeenCalledWith('[watcher] error:', expect.any(Error))+ await watcher.stop()+ await watcher.stop()+ // Started before anything is tailed: there is nothing to watch yet.+ const idle = new Watcher()+ idle.start()+ await idle.stop()+ } finally {+ log.mockRestore()+ error.mockRestore()+ }+ })++ it('moves a session to its new file, and starts a missing one from nothing', async () => {+ const { dir, transcriptPath, watcher, lines } = await fresh('{"n":1}\n')+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath })+ const moved = join(dir, 'moved.jsonl')+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath: moved })+ expect(watcher.tails('s1', transcriptPath)).toBe(false)+ expect(watcher.tails('s1', moved)).toBe(true)+ await writeFile(moved, '{"n":2}\n')+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"n":2}'])+ await watcher.stop()+ })++ it('hands a file to the session added last, and lets a session that lost it go quietly', async () => {+ const { transcriptPath, watcher, lines } = await fresh()+ const seen: string[] = []+ watcher.on('line', (event: LineEvent) => seen.push(event.sessionId))+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath })+ await watcher.addSession({ sessionId: 's2', engine: 'codex', transcriptPath })+ await appendFile(transcriptPath, '{"n":1}\n')+ await watcher.pollSession('s2')+ expect(seen).toEqual(['s2'])+ await watcher.removeSession('s2')+ // s1 still names the file, which is no longer tailed.+ watcher.setTail('s1', 0)+ await watcher.pollSession('s1')+ expect(await watcher.hold('s1', transcriptPath)).toBeNull()+ expect(lines).toEqual(['{"n":1}'])+ await watcher.removeSession('nobody')+ await watcher.pollSession('nobody')+ await watcher.stop()+ })++ it('drops a read that was only scheduled when the tail is moved or the session removed', async () => {+ for (const end of ['setTail', 'remove'] as const) {+ const { transcriptPath, watcher, lines } = await fresh('{"n":1}\n{"n":2}\n')+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath }, { fromOffset: 0 })+ if (end === 'setTail') watcher.setTail('s1', 16)+ else await watcher.removeSession('s1')+ await new Promise((resolve) => setTimeout(resolve, 80))+ expect(lines).toEqual([])+ await watcher.stop()+ }+ })++ it('skips a read of a file it does not tail, one that is gone, and one it may not open', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ const { transcriptPath, watcher, lines } = await fresh('{"n":1}\n')+ await internals(watcher).readNew('/nowhere.jsonl')+ await watcher.addSession({ sessionId: 's1', engine: 'codex', transcriptPath })+ await appendFile(transcriptPath, '{"n":2}\n')+ chmodSync(transcriptPath, 0o000)+ await watcher.pollSession('s1')+ expect(error).toHaveBeenCalledOnce()+ expect(String(error.mock.calls[0][0])).toContain('[watcher] read failed (session.jsonl)')+ chmodSync(transcriptPath, 0o600)+ await rm(transcriptPath)+ await watcher.pollSession('s1')+ expect(lines).toEqual([])+ await watcher.stop()+ } finally { error.mockRestore() }+ })++ it('reads Cursor transcripts whole: none to begin with, a last line not yet ended, and one that vanishes', async () => {+ const { transcriptPath, watcher, lines } = await fresh()+ await rm(transcriptPath)+ await watcher.addSession({ sessionId: 's1', engine: 'cursor', transcriptPath })+ await writeFile(transcriptPath, '{"c":1}\n\n{"c":2}\r\n{"c":3')+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"c":1}', '{"c":2}'])+ await appendFile(transcriptPath, '}\n')+ await watcher.pollSession('s1')+ expect(lines).toEqual(['{"c":1}', '{"c":2}', '{"c":3}'])+ await rm(transcriptPath)+ await watcher.pollSession('s1')+ expect(lines).toHaveLength(3)+ await watcher.stop()+ })+})diff --git a/cli/src/watcher/watcher.ts b/cli/src/watcher/watcher.tsindex 6b913260d..de32bd697 100644--- a/cli/src/watcher/watcher.ts+++ b/cli/src/watcher/watcher.ts@@ -36,15 +36,42 @@ export interface HistoryEvent {lines: LineEvent[]}+/** A tailed session's delivery, held by an attach (see `Watcher.hold`). */+export interface TailHold {+ /** The byte the next undelivered line starts at. */+ readonly offset: number+ /** The hold let go on its own after its timeout: delivery resumed into whatever it was feeding, from+ * where it had stopped, and a later `release` changes nothing. */+ readonly expired: boolean+ /** Resume delivery — from `offset` when given (where the caller's own read stopped), unless the tail+ * was moved under the hold (`setTail`), whose position then stands. Idempotent. */+ release(offset?: number | null): void+}++/** The longest a session's live delivery may stay held. An attach still running by then lets it go+ * (`TailHold.expired`) and must keep the normalizer delivery went back to. */+export const HOLD_TIMEOUT_MS = 30_000++const EMPTY = Buffer.alloc(0)+interface FileState extends WatchedSession {offset: number/** Bytes below this were on disk before the current read cursor was placed — history, not live. */historicalUntil: number- partial: string+ /** The end of the file not yet ending in a newline: raw bytes, decoded only once the line is whole,+ * so a character split between two reads is not mangled and positions stay byte-exact. */+ partial: Bufferseq: numberdebounce: NodeJS.Timeout | nullreading: booleanpending: boolean+ /** Attaches holding delivery (see `hold`); nothing is read while any does. */+ holds: Set<TailHold>+ /** Settled when the last hold is released: what a drain waits on. */+ unheld: Promise<void> | null+ settleUnheld: (() => void) | null+ /** How many times `setTail` moved the tail: a hold taken before a move cannot put it back. */+ moves: numbercursorLines: string[]}@@ -69,8 +96,10 @@ export class Watcher extends EventEmitter {if (this.files.size) this.watcher.add([...this.files.keys()])}- /** Attach one trusted transcript. Runtime hydration is handled by cli.ts; the tail starts at EOF. */- async addSession(session: WatchedSession, opts: { fromStart?: boolean } = {}): Promise<void> {+ /** Attach one trusted transcript. Runtime hydration is handled by cli.ts; the tail starts at EOF, or at+ * `fromOffset` — where that hydration stopped reading — so a record written while it read is tailed+ * rather than lost between the two. */+ async addSession(session: WatchedSession, opts: { fromStart?: boolean; fromOffset?: number } = {}): Promise<void> {const oldPath = this.bySession.get(session.sessionId)if (oldPath && oldPath !== session.transcriptPath) await this.removeSession(session.sessionId)@@ -79,7 +108,8 @@ export class Watcher extends EventEmitter {let size = 0try { size = (await stat(session.transcriptPath)).size } catch { size = 0 }if (!opts.fromStart) {- offset = size+ // A file that shrank since is a rewrite; its tail starts at the new end, as without an offset.+ offset = opts.fromOffset !== undefined && opts.fromOffset <= size ? opts.fromOffset : sizeif (session.engine === 'cursor') {try { cursorLines = completeLines(await readFile(session.transcriptPath, 'utf8')) } catch { cursorLines = [] }}@@ -99,16 +129,79 @@ export class Watcher extends EventEmitter {offset,// A `fromStart` tail of a file that already has content reads that content as history.historicalUntil: opts.fromStart ? size : 0,- partial: '',+ partial: EMPTY,seq: 0,debounce: null,reading: false,pending: false,+ holds: new Set(),+ unheld: null,+ settleUnheld: null,+ moves: 0,cursorLines,})this.bySession.set(session.sessionId, session.transcriptPath)this.watcher?.add(session.transcriptPath)- if (opts.fromStart) this.schedule(session.transcriptPath)+ if (opts.fromStart || offset < size) this.schedule(session.transcriptPath)+ }++ /**+ * Stop delivering a tailed session's lines from `transcriptPath`, and say where delivery stopped: the+ * byte its next line starts at. Waits out a read already in progress. Null when that file is not the+ * one being tailed for the session.+ *+ * A re-attach rebuilds the session's normalizer from the transcript while the old one is still the+ * one being fed. Holding the tail is what lets it read exactly up to where the old one stopped and+ * hand everything after that to the new one: a line written meanwhile is neither lost to the+ * normalizer being replaced nor read twice. Every hold must be released. One held past `timeoutMs`+ * lets go on its own and says so (`expired`), so a stream is never frozen for good; the attach that+ * held it must then keep the normalizer delivery resumed into, which has seen every line since.+ */+ async hold(sessionId: string, transcriptPath: string, timeoutMs = HOLD_TIMEOUT_MS): Promise<TailHold | null> {+ const state = this.bySession.get(sessionId) === transcriptPath ? this.files.get(transcriptPath) : undefined+ if (!state) return null+ if (!state.holds.size) state.unheld = new Promise((resolve) => { state.settleUnheld = resolve })+ if (state.debounce) { clearTimeout(state.debounce); state.debounce = null }+ const moves = state.moves+ let offset = 0+ let released = false+ let expired = false+ const release = (to: number | null = null): void => {+ if (released) return+ released = true+ clearTimeout(timer)+ state.holds.delete(hold)+ if (to !== null && state.moves === moves) {+ state.offset = to+ state.partial = EMPTY+ }+ if (state.holds.size) return+ state.settleUnheld?.()+ state.unheld = null+ state.settleUnheld = null+ if (this.files.get(transcriptPath) === state) this.schedule(transcriptPath)+ }+ // Counted from the request: an attach that never lets go is hung however long its read took.+ const timer = setTimeout(() => {+ console.warn(`[watcher] ${sessionId.slice(0, 8)} held for ${timeoutMs} ms — letting its tail go`)+ expired = true+ release()+ }, timeoutMs)+ timer.unref()+ const hold: TailHold = {+ get offset() { return offset },+ get expired() { return expired },+ release,+ }+ state.holds.add(hold)+ while (state.reading) await new Promise((resolve) => setTimeout(resolve, 5))+ offset = state.offset - state.partial.length+ return hold+ }++ /** Whether `transcriptPath` is the file being tailed for the session. */+ tails(sessionId: string, transcriptPath: string): boolean {+ return this.bySession.get(sessionId) === transcriptPath && this.files.has(transcriptPath)}/** Move a byte-tailed session's read cursor to a known length after the file was rewritten in place@@ -125,7 +218,9 @@ export class Watcher extends EventEmitter {if (!state) returnif (state.debounce) { clearTimeout(state.debounce); state.debounce = null }state.offset = offset- state.partial = ''+ state.partial = EMPTY+ // An attach holding the tail read the file as it was; where it stopped is no position in this one.+ state.moves++}async removeSession(sessionId: string): Promise<void> {@@ -134,12 +229,17 @@ export class Watcher extends EventEmitter {this.bySession.delete(sessionId)const state = this.files.get(filePath)if (state?.debounce) clearTimeout(state.debounce)+ // Nothing is left to drain: a drain waiting for a hold here is done.+ state?.settleUnheld?.()this.files.delete(filePath)await this.watcher?.unwatch(filePath)}async stop(): Promise<void> {- for (const state of this.files.values()) if (state.debounce) clearTimeout(state.debounce)+ for (const state of this.files.values()) {+ if (state.debounce) clearTimeout(state.debounce)+ state.settleUnheld?.()+ }this.files.clear()this.bySession.clear()if (this.watcher) await this.watcher.close()@@ -158,11 +258,18 @@ export class Watcher extends EventEmitter {}))}+ /** Deliver everything on disk now. A hold stops delivery where it is until its attach lets go —+ * whether it landed before this drain or during its read — so the drain waits for it and reads on,+ * until nothing holds the tail and no read asked for is left undone. */async pollSession(sessionId: string): Promise<void> {const filePath = this.bySession.get(sessionId)if (!filePath) return- await this.readNew(filePath)- while (this.files.get(filePath)?.reading) await new Promise((resolve) => setTimeout(resolve, 10))+ for (let state = this.files.get(filePath); state; state = this.files.get(filePath)) {+ if (state.unheld) { await state.unheld; continue }+ await this.readNew(filePath)+ while (state.reading) await new Promise((resolve) => setTimeout(resolve, 10))+ if (!state.holds.size && !state.pending) return+ }}/** Chokidar told us the file moved. Logged for commandcode/devin only, whose whole turn lifecycle rides@@ -187,13 +294,14 @@ export class Watcher extends EventEmitter {private async readNew(filePath: string): Promise<void> {const state = this.files.get(filePath)if (!state) return- if (state.reading) { state.pending = true; return }+ if (state.reading || state.holds.size) { state.pending = true; return }state.reading = truetry {do {state.pending = falseawait this.readOnce(filePath, state)- } while (state.pending && this.files.get(filePath) === state)+ // A hold taken during this read stops it here; `release` reads what is left.+ } while (state.pending && !state.holds.size && this.files.get(filePath) === state)} finally {state.reading = false}@@ -210,19 +318,19 @@ export class Watcher extends EventEmitter {// The file shrank: rewritten in place (or recreated). Whatever it holds now is read from byte 0,// and none of it is new to the world — it is history until the write that grows it past this.state.offset = 0- state.partial = ''+ state.partial = EMPTYstate.historicalUntil = size}if (size <= state.offset) returnconst start = state.offset- let chunk = ''+ let fresh: Buffertry {const fh = await open(filePath, 'r')try {const buf = Buffer.alloc(size - start)const { bytesRead } = await fh.read(buf, 0, buf.length, start)- chunk = buf.subarray(0, bytesRead).toString('utf8')+ fresh = buf.subarray(0, bytesRead)state.offset = start + bytesRead} finally {await fh.close()@@ -232,17 +340,17 @@ export class Watcher extends EventEmitter {return}- // Byte position of each line, to tell the historical prefix of this chunk from the live rest: a- // file appended to between the cursor being placed and this read has both in the same chunk. The- // carried partial line began that many bytes before `start`.- let pos = start - Buffer.byteLength(state.partial, 'utf8')- const combined = state.partial + chunk- const lines = combined.split('\n')- state.partial = combined.endsWith('\n') ? '' : (lines.pop() ?? '')+ // Lines are cut on the newline BYTE and decoded only once whole. Each line's byte position tells+ // the historical prefix of this read from the live rest: a file appended to between the cursor+ // being placed and this read has both. The carried partial line began that many bytes before `start`.+ const base = start - state.partial.length+ const combined = state.partial.length ? Buffer.concat([state.partial, fresh]) : fresh+ let lineStart = 0const history: LineEvent[] = []- for (const raw of lines) {- const linePos = pos- pos += Buffer.byteLength(raw, 'utf8') + 1+ for (let newline = combined.indexOf(10); newline >= 0; newline = combined.indexOf(10, lineStart)) {+ const linePos = base + lineStart+ const raw = combined.subarray(lineStart, newline).toString('utf8')+ lineStart = newline + 1const text = raw.replace(/\r$/, '')if (!text.trim()) continueconst evt: LineEvent = {@@ -258,6 +366,8 @@ export class Watcher extends EventEmitter {this.emit('line', evt)}if (history.length) this.flushHistory(state, history)+ // A copy: the read buffer can be large, and only its unfinished last line is kept.+ state.partial = lineStart < combined.length ? Buffer.from(combined.subarray(lineStart)) : EMPTY}private flushHistory(state: FileState, lines: LineEvent[]): void {@@ -271,10 +381,10 @@ export class Watcher extends EventEmitter {while (common < state.cursorLines.length && common < next.length && state.cursorLines[common] === next[common]) common++state.cursorLines = nextstate.offset = 0- state.partial = ''+ state.partial = EMPTYstate.historicalUntil = 0+ // `completeLines` has already dropped blank lines.for (const text of next.slice(common)) {- if (!text.trim()) continuethis.emit('line', {sessionId: state.sessionId,engine: state.engine,