Skip to content

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

fix(codex): repair stale reasoning-item ids before resuming a session

bitcoinbuilder6929bacbb6ae
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 0b70dffdf..9c70b3525 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -68,6 +68,7 @@ import { TmuxBackend } from './lib/tmuxBackend.js'
import { createAndRegisterPane } from './lib/createAgentPane.js'
import { restoreAgents } from './lib/restoreAgents.js'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
+import { prepareCodexResume } from './engines/codex/portableHistory.js'
import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'
import { basename } from 'node:path'
import {
@@ -3372,6 +3373,17 @@ async function runForeground(session: AuthSession): Promise<void> {
const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> =>
buildLaunchOverrides(launchOverridesDeps, session.engine, source, session.agentId)
+ const prepareSessionResume = (session: RegisteredSession): void => {
+ const repair = prepareCodexResume(session)
+ if (repair.repairedItems) {
+ // The rollout we tail was just shrunk in place. Move the tail to the repaired length now, before
+ // the resumed engine appends, or the watcher would read the whole repaired history as new lines
+ // and the live normalizer would replay the conversation into web/device. See Watcher.setTail.
+ if (repair.repairedBytes !== undefined) watcher.setTail(session.sessionId, repair.repairedBytes)
+ console.log(`[resume] repaired ${repair.repairedItems} Codex reasoning items · backup: ${repair.backupPath}`)
+ }
+ }
+
watcher.start()
await cursorDiscovery.start()
// Panes that died while the daemon was down (a reboot takes the whole tmux server with it) are
@@ -3394,6 +3406,11 @@ async function runForeground(session: AuthSession): Promise<void> {
// own shell.
const built = await relaunchOverrides(entry)
if (!built.ok) return { error: built.error, detail: built.detail }
+ if (opts.resumeSessionId) {
+ try { prepareSessionResume(entry) } catch (error) {
+ return { error: 'RESUME_PREPARATION_FAILED', detail: error instanceof Error ? error.message : String(error) }
+ }
+ }
const { env: launchEnv, extraArgs, clearEnv } = built.overrides
const argv = buildEngineLaunchArgv(entry.engine, {
...opts,
@@ -3734,6 +3751,7 @@ async function runForeground(session: AuthSession): Promise<void> {
runtime: TmuxRuntimeRef,
launch: { env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[] } = {},
): RestartAgentDeps => ({
+ prepareResume: () => prepareSessionResume(session),
holdOpen: async () => {
const result = await tmuxBackend!.holdOpen(runtime)
return result.state === 'succeeded'
diff --git a/cli/src/engines/codex/portableHistory.real.spec.ts b/cli/src/engines/codex/portableHistory.real.spec.ts
new file mode 100644
index 000000000..4c8e0545c
--- /dev/null
+++ b/cli/src/engines/codex/portableHistory.real.spec.ts
@@ -0,0 +1,88 @@
+/** Offline wire regression against the installed Codex CLI (verified with 0.154.0).
+ * RUN_CODEX_RESUME_E2E=1 npm exec vitest run src/engines/codex/portableHistory.real.spec.ts
+ * Only the loopback mock is contacted; no vendor credential or inference is used. */
+import { execFile } from 'node:child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { promisify } from 'node:util'
+import { expect, it } from 'vitest'
+import { prepareCodexResume } from './portableHistory.js'
+
+it.skipIf(process.env.RUN_CODEX_RESUME_E2E !== '1')('resumes the same Codex conversation after a rejected reasoning id is repaired', async () => {
+ const profile = mkdtempSync(join(tmpdir(), 'codex-resume-wire-'))
+ const id = '01a0a3cd-a374-71f2-a11a-1fc1cc41b36d'
+ const badId = 'msg_aY9suLof0GA06VzeKPXLM7rjUhoRRF9d'
+ const timestamp = '2026-09-15T06:42:38.000Z'
+ const record = (type: string, payload: unknown) => JSON.stringify({ timestamp, type, payload })
+ const dir = join(profile, 'sessions', '2026', '09', '15')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, `rollout-2026-09-15T13-42-38-${id}.jsonl`)
+ writeFileSync(file, [
+ record('session_meta', { id, timestamp, cwd: profile, originator: 'codex_cli_rs', cli_version: '0.154.0', source: 'cli', model_provider: 'mock' }),
+ record('response_item', { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'hello' }] }),
+ record('response_item', { type: 'reasoning', id: badId, summary: [{ type: 'summary_text', text: 'Prior local summary.' }], content: [] }),
+ record('response_item', { type: 'message', id: badId, role: 'assistant', content: [{ type: 'output_text', text: 'Hello back.' }] }),
+ ].join('\n') + '\n')
+ const requests: Array<{ input: Array<Record<string, unknown>> }> = []
+ const server = createServer((req, res) => {
+ if (!req.url?.endsWith('/responses')) { res.writeHead(404).end(); return }
+ let body = ''
+ req.on('data', chunk => { body += chunk })
+ req.on('end', () => {
+ const request = JSON.parse(body)
+ requests.push(request)
+ const reasoning = request.input.find((item: Record<string, unknown>) => item.type === 'reasoning')
+ if (reasoning?.id) {
+ res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({
+ error: { type: 'invalid_request_error', code: 'invalid_id_prefix', message: "Expected an ID that begins with 'rs'." },
+ }))
+ return
+ }
+ const item = { type: 'message', id: 'msg_reply', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'Recovered.', annotations: [] }] }
+ const response = { id: 'resp_test', object: 'response', created_at: 1789460000, model: 'gpt-5.6-luna', status: 'completed', output: [item], usage: { input_tokens: 10, output_tokens: 1, total_tokens: 11 } }
+ const events = [
+ { type: 'response.created', response: { ...response, status: 'in_progress', output: [] } },
+ { type: 'response.output_item.added', output_index: 0, item: { ...item, status: 'in_progress', content: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, item_id: item.id, delta: 'Recovered.' },
+ { type: 'response.output_item.done', output_index: 0, item },
+ { type: 'response.completed', response },
+ ]
+ res.writeHead(200, { 'content-type': 'text/event-stream' }).end(events.map((event, sequence_number) =>
+ `event: ${event.type}\ndata: ${JSON.stringify({ ...event, sequence_number })}\n\n`).join(''))
+ })
+ })
+ try {
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('mock did not bind TCP')
+ const args = ['exec', 'resume', '--skip-git-repo-check', '--ignore-user-config', '--ignore-rules', '--json',
+ '-m', 'gpt-5.6-luna', '-c', 'model_provider="mock"', '-c', 'model_providers.mock.name="Mock"',
+ '-c', `model_providers.mock.base_url="http://127.0.0.1:${address.port}/v1"`,
+ '-c', 'model_providers.mock.wire_api="responses"', '-c', 'model_providers.mock.supports_websockets=false',
+ '-c', 'model_providers.mock.requires_openai_auth=false', id, 'continue']
+ const run = () => promisify(execFile)(process.env.CODEX_TEST_BINARY || 'codex', args, {
+ cwd: profile, env: { PATH: process.env.PATH, HOME: process.env.HOME, CODEX_HOME: profile }, timeout: 20_000,
+ }).then(result => ({ code: 0, ...result }), error => ({ code: error.code, stdout: error.stdout, stderr: error.stderr }))
+
+ const failed = await run()
+ expect(failed.code).toBe(1)
+ expect(requests[0].input.find(item => item.type === 'reasoning')?.id).toBe(badId)
+ expect(failed.stdout + failed.stderr).toContain('invalid_id_prefix')
+
+ expect(prepareCodexResume({ engine: 'codex', sessionId: id, transcriptPath: file, codexHome: profile }).repairedItems).toBe(1)
+ const resumed = await run()
+ expect(resumed.code, resumed.stderr).toBe(0)
+ expect(resumed.stdout).toContain(`"thread_id":"${id}"`)
+ expect(resumed.stdout).toContain('Recovered.')
+ const replay = requests.at(-1)!.input
+ expect(replay.find(item => item.type === 'reasoning')).toMatchObject({ summary: [{ type: 'summary_text', text: 'Prior local summary.' }] })
+ expect(replay.find(item => item.type === 'reasoning')).not.toHaveProperty('id')
+ expect(replay.find(item => item.id === badId)).toMatchObject({ type: 'message', content: [{ type: 'output_text', text: 'Hello back.' }] })
+ } finally {
+ server.closeAllConnections()
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ rmSync(profile, { recursive: true, force: true })
+ }
+}, 45_000)
diff --git a/cli/src/engines/codex/portableHistory.spec.ts b/cli/src/engines/codex/portableHistory.spec.ts
new file mode 100644
index 000000000..77a88af7c
--- /dev/null
+++ b/cli/src/engines/codex/portableHistory.spec.ts
@@ -0,0 +1,134 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { portableCodexHistory, prepareCodexResume } from './portableHistory.js'
+
+const SESSION = '01a0a3cd-a374-71f2-a11a-1fc1cc41b36d'
+const BAD_ID = 'msg_aY9suLof0GA06VzeKPXLM7rjUhoRRF9d'
+const summary = [{ type: 'summary_text', text: 'Prior engine summary.' }]
+const record = (type: string, payload: unknown) => JSON.stringify({ timestamp: '2026-09-15T06:43:10.580Z', type, payload })
+const meta = record('session_meta', { id: SESSION, cwd: '/workspace', model_provider: 'openai' })
+const badReasoning = () => ({ type: 'reasoning', id: BAD_ID, summary, content: [] })
+const message = { type: 'message', id: BAD_ID, role: 'assistant', content: [{ type: 'output_text', text: 'Hello.' }] }
+const history = (...items: unknown[]) => [meta, ...items.map(item => record('response_item', item)), ''].join('\n')
+const payloads = (value: string) => value.trim().split('\n').slice(1).map(line => JSON.parse(line).payload)
+
+describe('Codex reasoning history portability', () => {
+ it('repairs the screenshot pair without changing the answer, its id, or the reasoning summary', () => {
+ const original = history(badReasoning(), message)
+ const result = portableCodexHistory(original, SESSION)
+ expect(result.repairedItems).toBe(1)
+ expect(payloads(result.history)).toEqual([{ type: 'reasoning', summary, content: [] }, message])
+ expect(result.history.split('\n')[2]).toBe(original.split('\n')[2])
+ expect(portableCodexHistory(result.history, SESSION)).toEqual({ history: result.history, repairedItems: 0 })
+ })
+
+ it('keeps local reasoning text when repairing legacy content and rs_ ids', () => {
+ const result = portableCodexHistory(history({
+ type: 'reasoning', id: 'rs_local', summary: [], content: [{ text: 'one ' }, { text: 'two' }],
+ }), SESSION)
+ expect(payloads(result.history)).toEqual([{
+ type: 'reasoning', summary: [{ type: 'summary_text', text: 'one two' }], content: [],
+ }])
+ })
+
+ it('keeps an existing summary when content also needs repair', () => {
+ const result = portableCodexHistory(history({ ...badReasoning(), content: [{ text: 'duplicate' }] }), SESSION)
+ expect(payloads(result.history)[0]).toEqual({ type: 'reasoning', summary, content: [] })
+ })
+
+ it('preserves vendor encrypted reasoning and tool relationships byte for byte', () => {
+ const original = history(
+ { type: 'reasoning', id: 'rs_vendor', encrypted_content: 'opaque-vendor-data', summary: [], content: [{ type: 'reasoning_text', text: 'vendor' }] },
+ { type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'exec', arguments: '{"cmd":"pwd"}' },
+ { type: 'function_call_output', call_id: 'call_1', output: 'workspace' },
+ message,
+ ).replaceAll('\n', '\r\n')
+ expect(portableCodexHistory(original, SESSION)).toEqual({ history: original, repairedItems: 0 })
+ })
+
+ it('repairs replacement history that compaction will replay, leaving other nested data alone', () => {
+ const compacted = record('compacted', { message: 'Context summary', replacement_history: [badReasoning(), message] })
+ const event = record('event_msg', { type: 'agent_reasoning', text: 'Visible trace', metadata: badReasoning() })
+ const original = `${meta}\n${compacted}\n${event}\n`
+ const result = portableCodexHistory(original, SESSION)
+ expect(result.repairedItems).toBe(1)
+ expect(payloads(result.history)[0].replacement_history).toEqual([{ type: 'reasoning', summary, content: [] }, message])
+ expect(result.history.split('\n')[2]).toBe(event)
+ })
+})
+
+describe('preparing a stopped Codex session for resume', () => {
+ let profile: string
+ let file: string
+ beforeEach(() => {
+ profile = mkdtempSync(join(tmpdir(), 'codex-portable-history-'))
+ const dir = join(profile, 'sessions', '2026', '09', '15')
+ mkdirSync(dir, { recursive: true })
+ file = join(dir, `rollout-2026-09-15T13-42-38-${SESSION}.jsonl`)
+ })
+ afterEach(() => { rmSync(profile, { recursive: true, force: true }) })
+ const source = () => ({ engine: 'codex', sessionId: SESSION, transcriptPath: file, codexHome: profile })
+
+ it('backs up the exact original, repairs the same session, and is a no-op on the next resume', () => {
+ const original = history(badReasoning(), message)
+ writeFileSync(file, original)
+ const result = prepareCodexResume(source())
+ expect(result.repairedItems).toBe(1)
+ expect(readFileSync(result.backupPath!, 'utf8')).toBe(original)
+ expect(statSync(result.backupPath!).mode & 0o777).toBe(0o600)
+ expect(readFileSync(file, 'utf8')).toBe(portableCodexHistory(original, SESSION).history)
+ // repairedBytes lets a live tailer re-sync its offset to the shrunk file without another stat.
+ expect(result.repairedBytes).toBe(statSync(file).size)
+ expect(result.repairedBytes).toBeLessThan(Buffer.byteLength(original, 'utf8'))
+ const before = statSync(file)
+ expect(prepareCodexResume(source())).toEqual({ repairedItems: 0 })
+ expect(statSync(file).mtimeMs).toBe(before.mtimeMs)
+ expect(statSync(file).ino).toBe(before.ino)
+ expect(readdirSync(join(profile, 'sessions', '2026', '09', '15'))).toHaveLength(2)
+ })
+
+ it('resolves a rollout in the selected profile when the registry has no transcript path', () => {
+ writeFileSync(file, history(badReasoning()))
+ expect(prepareCodexResume({ ...source(), transcriptPath: null }).repairedItems).toBe(1)
+ })
+
+ it('resolves the session again when the registry points at a missing rollout', () => {
+ writeFileSync(file, history(badReasoning()))
+ expect(prepareCodexResume({ ...source(), transcriptPath: join(profile, 'sessions', 'missing.jsonl') }).repairedItems).toBe(1)
+ expect(payloads(readFileSync(file, 'utf8'))[0]).not.toHaveProperty('id')
+ })
+
+ it.each(['invalid JSON', '{"type":"response_item","payload":'])('does not rewrite or back up a partial or invalid rollout (%s)', (invalid) => {
+ const original = history(badReasoning()) + invalid
+ writeFileSync(file, original)
+ expect(() => prepareCodexResume(source())).toThrow()
+ expect(readFileSync(file, 'utf8')).toBe(original)
+ expect(readdirSync(join(profile, 'sessions', '2026', '09', '15'))).toHaveLength(1)
+ })
+
+ it('refuses a different session instead of modifying the wrong history', () => {
+ const original = history(badReasoning())
+ writeFileSync(file, original)
+ expect(() => prepareCodexResume({ ...source(), sessionId: 'another-session' })).toThrow('does not belong')
+ expect(readFileSync(file, 'utf8')).toBe(original)
+ })
+
+ it('refuses symlinks and files outside the profile', () => {
+ const outside = join(profile, 'other.jsonl')
+ const original = history(badReasoning())
+ writeFileSync(outside, original)
+ symlinkSync(outside, file)
+ expect(() => prepareCodexResume(source())).toThrow('outside the session profile')
+ expect(() => prepareCodexResume({ ...source(), transcriptPath: outside })).toThrow('outside the session profile')
+ expect(readFileSync(outside, 'utf8')).toBe(original)
+ })
+
+ it('leaves other engines, fresh sessions, and missing histories to the existing launch path', () => {
+ expect(prepareCodexResume({ ...source(), engine: 'claude' })).toEqual({ repairedItems: 0 })
+ expect(prepareCodexResume({ ...source(), sessionId: '' })).toEqual({ repairedItems: 0 })
+ expect(prepareCodexResume(source())).toEqual({ repairedItems: 0 })
+ expect(prepareCodexResume({ ...source(), transcriptPath: null })).toEqual({ repairedItems: 0 })
+ })
+})
diff --git a/cli/src/engines/codex/portableHistory.ts b/cli/src/engines/codex/portableHistory.ts
new file mode 100644
index 000000000..085d9ed01
--- /dev/null
+++ b/cli/src/engines/codex/portableHistory.ts
@@ -0,0 +1,120 @@
+import { randomUUID } from 'node:crypto'
+import { lstatSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { isAbsolute, join, relative } from 'node:path'
+import { resolveCodexRollout } from './rollout.js'
+
+type JsonObject = Record<string, unknown>
+
+function object(value: unknown): value is JsonObject {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+/** Match the relay's portable_reasoning_item contract. Plaintext engine reasoning has no
+ * vendor-stored id; encrypted vendor reasoning must keep its original fields. */
+function repairReasoning(item: unknown): boolean {
+ if (!object(item) || item.type !== 'reasoning' || item.encrypted_content) return false
+ let changed = false
+ if ('id' in item) {
+ delete item.id
+ changed = true
+ }
+ if (Array.isArray(item.content) && item.content.length) {
+ const text = item.content.map((part) => object(part) && typeof part.text === 'string' ? part.text : '').join('')
+ item.content = []
+ if (text && (!Array.isArray(item.summary) || !item.summary.length)) {
+ item.summary = [{ type: 'summary_text', text }]
+ }
+ changed = true
+ }
+ return changed
+}
+
+/** Only replayed API items are repaired. Other records (including readable event history) and
+ * unchanged lines retain their exact bytes. Invalid JSON aborts the whole repair. */
+export function portableCodexHistory(history: string, sessionId: string): { history: string; repairedItems: number } {
+ let sawMeta = false
+ let repairedItems = 0
+ const lines = history.split('\n').map((line, index) => {
+ if (!line.trim()) return line
+ let record: unknown
+ try { record = JSON.parse(line) } catch {
+ // JSON.parse's own error can quote conversation text; keep it out of daemon logs.
+ throw new Error(`invalid JSON in Codex rollout at line ${index + 1}`)
+ }
+ if (!object(record)) throw new Error('invalid Codex rollout record')
+ if (!sawMeta) {
+ if (record.type !== 'session_meta' || !object(record.payload) || record.payload.id !== sessionId) {
+ throw new Error('Codex rollout does not belong to the session being resumed')
+ }
+ sawMeta = true
+ }
+ const items = record.type === 'response_item' ? [record.payload]
+ : record.type === 'compacted' && object(record.payload) && Array.isArray(record.payload.replacement_history)
+ ? record.payload.replacement_history : []
+ let changed = false
+ for (const item of items) {
+ if (repairReasoning(item)) { repairedItems++; changed = true }
+ }
+ return changed ? JSON.stringify(record) + (line.endsWith('\r') ? '\r' : '') : line
+ })
+ if (!sawMeta) throw new Error('Codex rollout has no session metadata')
+ return { history: lines.join('\n'), repairedItems }
+}
+
+export interface CodexResumeSource {
+ engine: string
+ sessionId: string
+ transcriptPath?: string | null
+ codexHome?: string | null
+}
+
+/** Call only after the session's engine has stopped, before launching `codex resume`.
+ * Retargeting to the native subscription bypasses Grid, so response-side relay cleanup cannot
+ * repair items already persisted here. A private backup precedes an atomic replacement.
+ *
+ * `repairedBytes` (set only when items were repaired) is the on-disk length of the rewritten
+ * rollout. A live tailer of this same file must move its offset there before the engine relaunches:
+ * the repair shrinks the file mid-history, which an append-only byte tail would otherwise mistake
+ * for a truncation and replay in full. */
+export function prepareCodexResume(source: CodexResumeSource): { repairedItems: number; repairedBytes?: number; backupPath?: string } {
+ if (source.engine !== 'codex' || !source.sessionId) return { repairedItems: 0 }
+ const sessions = join(source.codexHome || process.env.CODEX_HOME || join(homedir(), '.codex'), 'sessions')
+ let file = source.transcriptPath || resolveCodexRollout(source.sessionId, sessions)
+ // A missing history still follows the engine's existing resume/fresh fallback.
+ if (!file) return { repairedItems: 0 }
+ let before: ReturnType<typeof lstatSync>
+ try { before = lstatSync(file) } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ // The registry may still point at a rollout that was moved; Codex resolves the session by id.
+ file = resolveCodexRollout(source.sessionId, sessions)
+ if (!file) return { repairedItems: 0 }
+ before = lstatSync(file)
+ }
+ const rel = relative(realpathSync(sessions), realpathSync(file))
+ if (!before.isFile() || before.isSymbolicLink() || isAbsolute(rel) || rel === '..' || rel.startsWith('../')
+ || (typeof process.getuid === 'function' && before.uid !== process.getuid())) {
+ throw new Error('Codex rollout is outside the session profile or is not an owned regular file')
+ }
+ const original = readFileSync(file, 'utf8')
+ const repaired = portableCodexHistory(original, source.sessionId)
+ if (!repaired.repairedItems) return { repairedItems: 0 }
+
+ const suffix = randomUUID()
+ const backupPath = `${file}.reasoning-backup-${suffix}`
+ const temporary = `${file}.reasoning-tmp-${suffix}`
+ // Writing the bytes we inspected avoids copying a concurrent writer's partial record.
+ writeFileSync(backupPath, original, { flag: 'wx', mode: 0o600, flush: true })
+ try {
+ writeFileSync(temporary, repaired.history, { flag: 'wx', mode: 0o600, flush: true })
+ const current = lstatSync(file)
+ if (current.ino !== before.ino || current.dev !== before.dev || current.size !== before.size
+ || current.mtimeMs !== before.mtimeMs || readFileSync(file, 'utf8') !== original) {
+ throw new Error('Codex rollout changed during resume preparation; retry after its writer stops')
+ }
+ renameSync(temporary, file)
+ } finally {
+ rmSync(temporary, { force: true })
+ }
+ return { repairedItems: repaired.repairedItems, repairedBytes: Buffer.byteLength(repaired.history, 'utf8'), backupPath }
+}
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index 9a78bc4aa..ef96f9f35 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -10,6 +10,7 @@ interface Overrides {
respawn?: RestartAgentDeps['respawn']
waitForProcess?: RestartAgentDeps['waitForProcess']
buildArgv?: RestartAgentDeps['buildArgv']
+ prepareResume?: RestartAgentDeps['prepareResume']
}
/** Every primitive records its own call, even when overridden — so `calls` always reflects the real
@@ -23,6 +24,7 @@ function deps(over: Overrides = {}): RestartAgentDeps & { calls: string[] } {
const buildArgvImpl = over.buildArgv ?? (() => ['claude'])
return {
calls,
+ ...(over.prepareResume ? { prepareResume: async () => { calls.push('prepareResume'); await over.prepareResume!() } } : {}),
holdOpen: async () => { calls.push('holdOpen'); return holdOpenImpl() },
terminate: async (checkAfterMs) => { calls.push('terminate'); return terminateImpl(checkAfterMs) },
respawn: async (argv) => { calls.push('respawn'); return respawnImpl(argv) },
@@ -33,6 +35,35 @@ function deps(over: Overrides = {}): RestartAgentDeps & { calls: string[] } {
}
describe('restartAgent', () => {
+ it('prepares history after its writer stops and before the resume launch', async () => {
+ const d = deps({ prepareResume: vi.fn() })
+ await restartAgent({ engine: 'codex', sessionId: 's1' }, false, d)
+ expect(d.calls).toEqual(['holdOpen', 'terminate', 'prepareResume', 'buildArgv', 'respawn', 'waitForProcess'])
+ })
+
+ it('never prepares history while the old writer may still be alive', async () => {
+ const prepareResume = vi.fn()
+ const d = deps({ terminate: async () => 'failed', prepareResume })
+ await restartAgent({ engine: 'codex', sessionId: 's1' }, false, d)
+ expect(prepareResume).not.toHaveBeenCalled()
+ })
+
+ it('does not fall back to a fresh conversation if preparing history fails', async () => {
+ const d = deps({ prepareResume: () => { throw new Error('rollout changed') } })
+ const outcome = await restartAgent({ engine: 'codex', sessionId: 's1' }, false, d)
+ expect(outcome).toEqual({ ok: false, detail: 'could not prepare codex session for resume: rollout changed' })
+ expect(d.calls).toEqual(['holdOpen', 'terminate', 'prepareResume'])
+ })
+
+ it('does not prepare a fresh launch or repeat preparation on the fresh fallback', async () => {
+ const prepareResume = vi.fn()
+ const d = deps({ prepareResume, waitForProcess: async () => null })
+ await restartAgent({ engine: 'codex', sessionId: '' }, false, d)
+ expect(prepareResume).not.toHaveBeenCalled()
+ await restartAgent({ engine: 'codex', sessionId: 's1' }, false, d)
+ expect(prepareResume).toHaveBeenCalledTimes(1)
+ })
+
it('holds the pane open, kills, respawns, and verifies — in that order', async () => {
const d = deps()
const outcome = await restartAgent({ engine: 'claude', sessionId: 's1' }, false, d)
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index fb1601c84..0404a93fe 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -28,6 +28,9 @@ export interface RestartAgentDeps {
respawn: (argv: string[]) => Promise<{ ok: boolean; reason?: string }>
/** Poll the pane for a recognizable engine process, up to an internal budget. Null on timeout. */
waitForProcess: () => Promise<ProcessIdentity | null>
+ /** Prepare persisted history only once the old writer is confirmed stopped. A failure must
+ * preserve the conversation, not enter the fresh-session fallback. */
+ prepareResume?: () => void | Promise<void>
buildArgv: (opts: { bypassPermission: boolean; resumeSessionId?: string }) => string[]
log: (message: string) => void
}
@@ -52,6 +55,11 @@ export async function restartAgent(
}
const resumeSessionId = session.sessionId || undefined
+ if (resumeSessionId && deps.prepareResume) {
+ try { await deps.prepareResume() } catch (error) {
+ return { ok: false, detail: `could not prepare ${session.engine} session for resume: ${error instanceof Error ? error.message : error}` }
+ }
+ }
const spawnAndWait = async (withResume: boolean): Promise<ProcessIdentity | null> => {
const argv = deps.buildArgv({
bypassPermission,
diff --git a/cli/src/watcher/watcher.spec.ts b/cli/src/watcher/watcher.spec.ts
index 46b70dfed..e82ebc961 100644
--- a/cli/src/watcher/watcher.spec.ts
+++ b/cli/src/watcher/watcher.spec.ts
@@ -108,4 +108,41 @@ describe('Watcher.pollAll', () => {
expect(lines).toEqual(['{"new":3}'])
await watcher.stop()
})
+
+ it('does not replay a rollout repaired (shrunk) in place once the tail is re-synced', async () => {
+ // The Codex resume reasoning-id repair rewrites the rollout to a SHORTER file before the engine
+ // relaunches. Without moving the tail, the next read sees size < offset, treats the shrink as a
+ // truncation, resets to 0, and re-emits the whole conversation into the live normalizer. setTail
+ // pins the offset to the repaired length so only the resumed turn is read.
+ const dir = await mkdtemp(join(tmpdir(), 'machine-repair-'))
+ cleanup.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl')
+ await writeFile(transcriptPath, '{"meta":1}\n{"reasoning":"msg_bad_id"}\n{"answer":1}\n')
+ const watcher = new Watcher()
+ const lines: string[] = []
+ watcher.on('line', (event: LineEvent) => lines.push(event.text))
+
+ await watcher.addSession({ sessionId: 'c1', engine: 'codex', transcriptPath })
+ await watcher.pollSession('c1')
+ expect(lines).toEqual([])
+
+ const repaired = '{"meta":1}\n{"reasoning":""}\n{"answer":1}\n' // shorter: the stale id was stripped
+ await writeFile(transcriptPath, repaired)
+ watcher.setTail('c1', Buffer.byteLength(repaired))
+ await watcher.pollSession('c1')
+ expect(lines).toEqual([]) // the repaired history is NOT re-emitted
+
+ await appendFile(transcriptPath, '{"resumed":2}\n')
+ await watcher.pollSession('c1')
+ expect(lines).toEqual(['{"resumed":2}']) // only the resumed engine's new turn
+ await watcher.stop()
+ })
+
+ it('setTail is a harmless no-op for a session that is not registered', async () => {
+ // The post-reboot restore path repairs the rollout before it re-attaches the tail, so there is
+ // nothing to move — this must not throw.
+ const watcher = new Watcher()
+ expect(() => watcher.setTail('never-registered', 123)).not.toThrow()
+ await watcher.stop()
+ })
})
diff --git a/cli/src/watcher/watcher.ts b/cli/src/watcher/watcher.ts
index be4e60ccf..47bdd1c15 100644
--- a/cli/src/watcher/watcher.ts
+++ b/cli/src/watcher/watcher.ts
@@ -91,6 +91,23 @@ export class Watcher extends EventEmitter {
if (opts.fromStart) this.schedule(session.transcriptPath)
}
+ /** Move a byte-tailed session's read cursor to a known length after the file was rewritten in place
+ * by a trusted producer (e.g. the Codex resume reasoning-id repair). The repair shrinks the rollout
+ * mid-history; left alone, the next read would see `size < offset`, treat it as a truncation, reset
+ * to 0 and re-emit the whole conversation into the live normalizer. Pinning the offset to the new
+ * length keeps the invariant that every line is emitted exactly once. No-op when the session is not
+ * registered (the post-reboot restore path repairs before it re-attaches, so there is nothing to
+ * move). Call synchronously in the same tick as the rewrite, before the producer appends again. */
+ setTail(sessionId: string, offset: number): void {
+ const filePath = this.bySession.get(sessionId)
+ if (!filePath) return
+ const state = this.files.get(filePath)
+ if (!state) return
+ if (state.debounce) { clearTimeout(state.debounce); state.debounce = null }
+ state.offset = offset
+ state.partial = ''
+ }
+
async removeSession(sessionId: string): Promise<void> {
const filePath = this.bySession.get(sessionId)
if (!filePath) return