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.

Sub-agents as Codex 0.160 and Claude Code record them, and an audit of every record type the CLIs write (#864)

Deee33ffc307b47
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index a3b742bb1..e770a9eb6 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -1085,6 +1085,49 @@ export async function run(engine, config = {}, { native = false } = {}) {
codex('response_item', { type: 'function_call_output', call_id: id, output: `ran ${directive[2]}` })
}
}
+ if (engine === 'claude' && directive?.[1] === 'bgagent') {
+ // A background sub-agent that finishes while its parent still works, as Claude Code 2.1.287 records
+ // it: the Agent call, its launch ack, the parent's own next tool, then the sub-agent's
+ // `<task-notification>` handed back INTO the running turn as a queued_command attachment, not as the
+ // user record Claude Code writes when the parent is idle.
+ const name = directive[2] || 'scout'
+ const id = `toolu_${turn}_bg`
+ claude({ type: 'assistant', message: { id: `msg_${turn}_bg`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'Agent', input: { description: `Count for ${name}`, prompt: `Count the files for ${name}.`, run_in_background: true } }], stop_reason: 'tool_use' } })
+ claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: 'Async agent launched successfully.\nagentId: a0f1e2d3c4b5a6978' }] }, toolUseResult: { isAsync: true, status: 'async_launched', agentId: 'a0f1e2d3c4b5a6978' } })
+ const edit = `toolu_${turn}_ed`
+ claude({ type: 'assistant', message: { id: `msg_${turn}_ed`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id: edit, name: 'Bash', input: { command: 'true' } }], stop_reason: 'tool_use' } })
+ claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: edit, content: 'ran true' }] } })
+ const notification = `<task-notification>\n<task-id>a0f1e2d3c4b5a6978</task-id>\n<tool-use-id>${id}</tool-use-id>\n<output-file>${join(cwd, '.tasks', 'a0f1e2d3c4b5a6978.output')}</output-file>\n<status>completed</status>\n<summary>Agent "Count for ${name}" finished</summary>\n<result>${name} found 3 files</result>\n</task-notification>`
+ claude({ type: 'attachment', attachment: { type: 'queued_command', prompt: notification, commandMode: 'task-notification', origin: { kind: 'task-notification', producer: 'session-task' } } })
+ }
+ if (engine === 'codex' && directive?.[1] === 'spawn') {
+ // A sub-agent, recorded as Codex 0.160 records one (multi-agent v2, measured on real rollouts): the
+ // spawn call; a SubAgentActivity naming the child's thread, written before the spawn's output; an output
+ // that names the child only by its path; the child's report to its parent; and its completion. No
+ // `<subagent_notification>`, which is what 0.160's parent never writes. The child keeps a rollout of
+ // its own, as Codex does, that the Task card reads its work from.
+ const name = directive[2] || 'scout'
+ const id = `call_${turn}_spawn`
+ const thread = randomUUID()
+ const path = `/root/${name}`
+ const childFile = join(codexHome, 'sessions', '2026', '10', '03', `rollout-2026-10-03T00-00-01-${thread}.jsonl`)
+ const child = (type, payload) => appendFileSync(childFile, JSON.stringify({ timestamp: now(), type, payload }) + '\n')
+ codex('response_item', { type: 'function_call', namespace: 'collaboration', name: 'spawn_agent', call_id: id, arguments: JSON.stringify({ task_name: name, agent_type: 'explorer', message: `Count the files for ${name}.` }) })
+ child('session_meta', { id: thread, cli_version: version, cwd, agent_nickname: 'Goodall', agent_role: 'explorer', agent_path: path, multi_agent_version: 'v2',
+ source: { subagent: { thread_spawn: { parent_thread_id: sessionId, depth: 1, agent_path: path, agent_nickname: 'Goodall', agent_role: 'explorer' } } } })
+ codex('event_msg', { type: 'item_completed', turn_id: open, item: { type: 'SubAgentActivity', id, kind: 'started', agent_thread_id: thread, agent_path: path } })
+ codex('response_item', { type: 'function_call_output', call_id: id, output: JSON.stringify({ task_name: path }) })
+ child('event_msg', { type: 'task_started', turn_id: `${thread}-1` })
+ child('response_item', { type: 'function_call', call_id: `${thread}-ls`, name: 'exec_command', arguments: JSON.stringify({ cmd: 'ls' }) })
+ child('response_item', { type: 'function_call_output', call_id: `${thread}-ls`, output: 'one\ntwo\nthree' })
+ child('event_msg', { type: 'task_complete', turn_id: `${thread}-1`, last_agent_message: `${name} found 3 files` })
+ codex('inter_agent_communication_metadata', { trigger_turn: false })
+ codex('response_item', { type: 'agent_message', author: path, recipient: '/root', content: [
+ { type: 'input_text', text: `Message Type: FINAL_ANSWER\nTask name: /root\nSender: ${path}\nPayload:\n${name} found 3 files` },
+ { type: 'encrypted_content', encrypted_content: 'gAAAA' },
+ ] })
+ codex('event_msg', { type: 'item_completed', turn_id: open, item: { type: 'SubAgentActivity', id: `subagent-completed-${thread}`, kind: 'completed', agent_thread_id: thread, agent_path: path } })
+ }
if (directive?.[1] === 'flood') {
// Numbered, so whoever reads the terminal can tell a lost, repeated or reordered line.
const kib = Number(directive[2]) || 256
diff --git a/cli/e2e/subagents.e2e.ts b/cli/e2e/subagents.e2e.ts
new file mode 100644
index 000000000..cf5a67a03
--- /dev/null
+++ b/cli/e2e/subagents.e2e.ts
@@ -0,0 +1,97 @@
+/**
+ * Sub-agents as the real CLIs record them, on the real daemon (found auditing the daemon's readers against
+ * real transcripts, docs/research/2026-10-06-real-cli-record-audit.md).
+ *
+ * - Codex 0.160 runs its sub-agents as "multi-agent v2": the spawn's output names the child only by its
+ * path, a SubAgentActivity record names its thread, and its completion is another SubAgentActivity, with
+ * the child's report in an agent_message before it. Read with the older vocabulary's rules, every
+ * sub-agent Codex started showed as a Task that failed at once, `{"task_name":"/root/…"}` for its output,
+ * live and in the history.
+ * - Claude Code hands a background sub-agent that finishes while its parent still works back into that
+ * turn as a queued_command attachment. Only the user record it writes for an idle parent was read, so
+ * that sub-agent never finished.
+ */
+import { mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+const row = async (client: LocalClient, agentId: string) =>
+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)
+ .find((agent) => agent.id === agentId)
+const forAgent = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+
+describe('sub-agents', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ it('codex: a sub-agent Codex 0.160 starts runs as a Task and closes with what it reported, live and in the history', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-120).join('\n')}`) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, 'spawn-codex')
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'codex', cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until('the agent to bind its conversation', async () => {
+ const found = await row(client, created.agent.id)
+ return found?.sessionId && found.status === 'active' ? found : null
+ }, 60_000, 500)
+
+ const since = client.frames.length
+ const ended = client.next(forAgent('turn_ended', agent.id), 45_000, 'turn_ended')
+ client.send('message', { agentId: agent.id, content: '!spawn scout' })
+ await ended
+ const live = client.frames.slice(since).filter((frame) => frame.agentId === agent.id)
+ const taskEnds = live.filter((frame) => frame.type === 'tool_end' && frame.payload?.tool === 'Task')
+ expect(live.some((frame) => frame.type === 'tool_start' && frame.payload?.tool === 'Task'), 'a Task card opened').toBe(true)
+ expect(taskEnds, 'the Task closed once').toHaveLength(1)
+ expect(taskEnds[0].payload).toMatchObject({ isError: false, output: 'scout found 3 files', subagent: { agentType: 'Goodall', totalToolUseCount: 1 } })
+ // The child's own work, read from its rollout by the thread its start named, sits under the Task.
+ const spawnId = taskEnds[0].payload?.id
+ expect(live.some((frame) => frame.type === 'tool_start' && frame.payload?.tool === 'Bash' && frame.payload?.parentToolUseId === spawnId)).toBe(true)
+
+ const page = await client.request<{ events?: Array<{ type: string; payload: Record<string, any> }>; error?: string }>(
+ 'session_get', { sessionId: agent.sessionId, limit: 200 }, 30_000)
+ expect(page.error).toBeUndefined()
+ const history = (page.events ?? []).filter((event) => event.type === 'tool_end' && event.payload.tool === 'Task')
+ expect(history).toHaveLength(1)
+ expect(history[0].payload).toMatchObject({ isError: false, output: 'scout found 3 files' })
+ client.close()
+ })
+
+ it('claude: a background sub-agent handed back while its parent still works is finished', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-120).join('\n')}`) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, 'bgagent-claude')
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until('the agent to bind its conversation', async () => {
+ const found = await row(client, created.agent.id)
+ return found?.sessionId && found.status === 'active' ? found : null
+ }, 60_000, 500)
+
+ const since = client.frames.length
+ const ended = client.next(forAgent('turn_ended', agent.id), 45_000, 'turn_ended')
+ client.send('message', { agentId: agent.id, content: '!bgagent scout' })
+ await ended
+ const live = client.frames.slice(since).filter((frame) => frame.agentId === agent.id)
+ const spawn = live.find((frame) => frame.type === 'tool_start' && frame.payload?.tool === 'Agent')
+ expect(spawn, 'the Agent card opened').toBeDefined()
+ // Claude Code 2.1.287 hands a sub-agent that finishes mid-turn back as a queued_command attachment. Only
+ // the user-record delivery was read, so this sub-agent never finished: the dial kept it running and held
+ // the parent's recap until its backstop gave up.
+ const finished = live.filter((frame) => frame.type === 'subagent_finished')
+ expect(finished, 'the sub-agent finished once').toHaveLength(1)
+ expect(finished[0].payload).toMatchObject({ id: spawn?.payload?.id, status: 'completed', summary: 'Agent "Count for scout" finished' })
+ expect(live.filter((frame) => frame.type === 'turn_started'), 'the hand-back opened no turn').toHaveLength(1)
+ client.close()
+ })
+})
diff --git a/cli/src/engines/codex/normalizer.spec.ts b/cli/src/engines/codex/normalizer.spec.ts
index 54bef5dda..3e5e7f594 100644
--- a/cli/src/engines/codex/normalizer.spec.ts
+++ b/cli/src/engines/codex/normalizer.spec.ts
@@ -644,3 +644,115 @@ describe('Codex rollout normalizer — the 0.147 TUI vocabulary', () => {
expect(windowed.hasMore).toBe(true)
})
})
+
+/**
+ * Codex 0.160 runs sub-agents as "multi-agent v2" (`multi_agent_version: "v2"` in turn_context), and records
+ * them in a vocabulary the Task tree never read (shapes measured on real 0.160.0 rollouts; text invented):
+ *
+ * function_call spawn_agent (namespace "collaboration"), args { task_name, agent_type, message }
+ * item_completed SubAgentActivity { id: <spawn call id>, kind: "started", agent_thread_id, agent_path }
+ * function_call_output { "task_name": "/root/<name>" } — no agent_id, no thread_id, no nickname
+ * agent_message { author: "/root/<name>", recipient: "/root", content: [input_text "Message Type: …\n…Payload:\n<text>"] }
+ * item_completed SubAgentActivity { kind: "completed", agent_thread_id, agent_path }
+ *
+ * and never the `<subagent_notification>` the v1 vocabulary closed a Task on. Read with v1's rules, the spawn's
+ * output named no child, so every sub-agent Codex started closed at once as "Task failed: {"task_name":…}".
+ */
+describe('Codex sub-agents — the 0.160 multi-agent v2 vocabulary', () => {
+ const childThread = '01a20000-1111-7222-8333-944445555666'
+ const spawnCall = 'call_spawnScout0001'
+ const message = (text: string, kind = 'FINAL_ANSWER') => line('response_item', {
+ type: 'agent_message',
+ author: '/root/scout',
+ recipient: '/root',
+ content: [
+ { type: 'input_text', text: `Message Type: ${kind}\nTask name: /root\nSender: /root/scout\nPayload:\n${text}` },
+ { type: 'encrypted_content', encrypted_content: 'gAAAA-invented' },
+ ],
+ })
+ const spawned = [
+ line('event_msg', { type: 'task_started', turn_id: 'turn-1' }),
+ line('event_msg', { type: 'item_completed', item: { type: 'UserMessage', id: 'u1', content: [{ type: 'text', text: 'Send a scout to count the fixtures' }] } }),
+ line('response_item', {
+ type: 'function_call',
+ namespace: 'collaboration',
+ name: 'spawn_agent',
+ call_id: spawnCall,
+ arguments: JSON.stringify({ task_name: 'scout', agent_type: 'explorer', message: 'Count the fixtures under test/. Report the number.' }),
+ }),
+ line('event_msg', { type: 'item_completed', item: { type: 'SubAgentActivity', id: spawnCall, kind: 'started', agent_thread_id: childThread, agent_path: '/root/scout' } }),
+ line('response_item', { type: 'function_call_output', call_id: spawnCall, output: JSON.stringify({ task_name: '/root/scout' }) }),
+ ]
+ const finished = [
+ line('inter_agent_communication_metadata', { trigger_turn: false }),
+ message('There are 12 fixtures.'),
+ line('event_msg', { type: 'item_completed', item: { type: 'SubAgentActivity', id: 'subagent-completed-01a2', kind: 'completed', agent_thread_id: childThread, agent_path: '/root/scout' } }),
+ line('event_msg', { type: 'item_completed', item: { type: 'AgentMessage', content: [{ type: 'Text', text: 'The scout counted 12.' }], phase: 'final_answer' } }),
+ line('event_msg', { type: 'task_complete', turn_id: 'turn-1' }),
+ ]
+ // The parent writing to its child mid-task: hidden like the other orchestration calls, and no result.
+ const followUp = [
+ line('response_item', { type: 'function_call', namespace: 'collaboration', name: 'send_message', call_id: 'call_nudge01', arguments: JSON.stringify({ target: 'scout', message: 'Include the snapshots.' }) }),
+ line('event_msg', { type: 'item_completed', item: { type: 'SubAgentActivity', id: 'call_nudge01', kind: 'interacted', agent_thread_id: childThread, agent_path: '/root/scout' } }),
+ line('response_item', { type: 'function_call_output', call_id: 'call_nudge01', output: '' }),
+ ]
+ const resolver: CodexSubagentResolver = () => ({ events: [], agentType: 'Goodall', totalToolUseCount: 2, totalTokens: 900, totalDurationMs: 4_000 })
+
+ it('opens the Task when Codex starts the sub-agent, not a failure', () => {
+ const normalizer = new CodexNormalizer('live', resolver)
+ const events = spawned.flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events.map((event) => event.type)).toEqual(['turn_started', 'tool_start'])
+ expect(events[1]).toEqual({
+ type: 'tool_start',
+ payload: {
+ id: spawnCall,
+ tool: 'Task',
+ input: { subagent_type: 'explorer', name: 'scout', title: 'Count the fixtures under test/', description: 'Count the fixtures under test/. Report the number.' },
+ },
+ })
+ })
+
+ it('closes the Task when the sub-agent completes, with what it reported, keyed by its thread', () => {
+ const resolveSubagent = vi.fn(resolver)
+ const normalizer = new CodexNormalizer('live', resolveSubagent)
+ const events = [...spawned, ...followUp, ...finished].flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events.map((event) => event.type)).toEqual(['turn_started', 'tool_start', 'tool_end', 'text_delta', 'turn_ended'])
+ expect(events[2].payload).toMatchObject({
+ id: spawnCall,
+ tool: 'Task',
+ isError: false,
+ output: 'There are 12 fixtures.',
+ subagent: { agentId: childThread, agentType: 'Goodall', totalToolUseCount: 2, totalTokens: 900, totalDurationMs: 4_000 },
+ })
+ expect(resolveSubagent).toHaveBeenCalledWith(childThread)
+ })
+
+ it('reports a final answer over a later progress message, and says completed when the child sent none', () => {
+ const answered = new CodexNormalizer('live', resolver)
+ const late = [...spawned, message('Final count: 12.'), message('Anything else?', 'MESSAGE'), ...finished.slice(2)]
+ .flatMap((raw) => answered.ingest(raw))
+ expect(late.find((event) => event.type === 'tool_end')?.payload).toMatchObject({ output: 'Final count: 12.', isError: false })
+
+ const silent = new CodexNormalizer('live', resolver)
+ const quiet = [...spawned, ...finished.slice(2)].flatMap((raw) => silent.ingest(raw))
+ expect(quiet.find((event) => event.type === 'tool_end')?.payload).toMatchObject({ output: 'Subagent completed', isError: false })
+ })
+
+ it('replays the same Task to history', () => {
+ const events = codexMessagesToEvents([...spawned, ...finished], resolver)
+ const task = events.filter((event) => (event.type === 'tool_start' || event.type === 'tool_end') && event.payload.tool === 'Task')
+ expect(task.map((event) => event.type)).toEqual(['tool_start', 'tool_end'])
+ expect(task[1].payload).toMatchObject({ isError: false, output: 'There are 12 fixtures.', subagent: { agentId: childThread } })
+ })
+
+ it('still closes a Task by the child\'s path when its start was never read', () => {
+ // An attach can fold from the spawn's output alone. The output names the child by its path, and the
+ // completion carries the same path beside the thread id.
+ const normalizer = new CodexNormalizer('live', resolver)
+ const events = [spawned[2], spawned[4], ...finished.slice(0, 3)].flatMap((raw) => normalizer.ingest(raw))
+ expect(events.map((event) => event.type)).toEqual(['tool_start', 'tool_end'])
+ expect(events[1].payload).toMatchObject({ id: spawnCall, isError: false, output: 'There are 12 fixtures.', subagent: { agentId: '/root/scout' } })
+ })
+})
diff --git a/cli/src/engines/codex/normalizer.ts b/cli/src/engines/codex/normalizer.ts
index b37268835..cae406d40 100644
--- a/cli/src/engines/codex/normalizer.ts
+++ b/cli/src/engines/codex/normalizer.ts
@@ -267,6 +267,9 @@ export class CodexNormalizer implements EngineNormalizer {
private childLaunchers = new Map<string, SpawnState>()
private pendingChildResults = new Map<string, ChildResult>()
private completedChildren = new Set<string>()
+ /** Codex 0.160 (multi-agent v2): spawn call id → child, and child path → its last report (subAgentActivity). */
+ private startedChildren = new Map<string, { threadId: string; path: string }>()
+ private childReports = new Map<string, { text: string; final: boolean }>()
private thinkingCounter = 0
/** See `TurnState.thinkingPrefix`. */
thinkingPrefix = 'thinking-codex-'
@@ -338,6 +341,8 @@ export class CodexNormalizer implements EngineNormalizer {
return message ? [{ type: 'text_delta', payload: { content: message } }] : []
}
+ if (type === 'SubAgentActivity') return this.subAgentActivity(item)
+
if (type === 'task_complete' || type === 'turn_aborted') {
this.pendingTask = false
const events = this.completeOutstanding(type === 'turn_aborted')
@@ -378,6 +383,8 @@ export class CodexNormalizer implements EngineNormalizer {
return notification ? this.completeChild(notification.childId, notification.result) : []
}
+ if (type === 'agent_message') { this.noteChildReport(item); return [] }
+
if (type === 'reasoning') {
const summary = Array.isArray(item.summary)
? item.summary.map((part) => string(object(part)?.text)).filter(Boolean).join('\n')
@@ -446,9 +453,14 @@ export class CodexNormalizer implements EngineNormalizer {
if (!spawn) return []
this.toolNames.delete(id)
const parsed = parseObject(item.output)
- const childId = string(parsed?.agent_id) || string(parsed?.thread_id)
+ // Codex 0.160's output is only `{"task_name":"/root/<name>"}`: the child's thread is in the SubAgentActivity
+ // before it, else its path names it. Without them every sub-agent read as failed (real 0.160 rollouts).
+ const started = this.startedChildren.get(id)
+ this.startedChildren.delete(id)
+ const taskName = string(parsed?.task_name)
+ const childId = string(parsed?.agent_id) || string(parsed?.thread_id) || started?.threadId || started?.path || taskName
if (childId) {
- const nickname = string(parsed?.nickname) || string(parsed?.name)
+ const nickname = string(parsed?.nickname) || string(parsed?.name) || taskName.split('/').pop() || ''
if (nickname) spawn.input.name = nickname
this.pendingSpawns.delete(id)
this.childLaunchers.set(childId, spawn)
@@ -479,6 +491,28 @@ export class CodexNormalizer implements EngineNormalizer {
]
}
+ /** v2's sub-agent life: `started` (keyed by the spawn's call id) names the child's thread, and `completed` is
+ * the only sign it finished: v2 writes no `<subagent_notification>`, and `wait_agent` carries no status. */
+ private subAgentActivity(item: JsonObject): LiveEvent[] {
+ const [kind, threadId, path, callId] = [item.kind, item.agent_thread_id, item.agent_path, item.id].map(string)
+ if (kind === 'started' && callId && (threadId || path)) this.startedChildren.set(callId, { threadId, path })
+ if (kind !== 'completed') return []
+ const childId = [threadId, path].find((id) => id && this.childLaunchers.has(id)) || threadId || path
+ const report = this.childReports.get(path)
+ this.childReports.delete(path)
+ return childId ? this.completeChild(childId, { output: report?.text ?? '', isError: false }) : []
+ }
+
+ /** A v2 child's message to its parent (`Message Type: FINAL_ANSWER|MESSAGE`, …, `Payload:` and the text),
+ * kept by sender as its Task's result; a final answer outranks a later progress message. */
+ private noteChildReport(item: JsonObject): void {
+ const author = string(item.author)
+ const text = textContent(item)
+ const final = /^Message Type:\s*FINAL_ANSWER\b/m.test(text)
+ const body = (/(?:^|\n)Payload:[ \t]*\n?([\s\S]*)$/.exec(text)?.[1] ?? text).trim()
+ if (author && body && !(this.childReports.get(author)?.final && !final)) this.childReports.set(author, { text: body, final })
+ }
+
private completeFromStatus(value: unknown): LiveEvent[] {
const events: LiveEvent[] = []
for (const [childId, result] of childResults(value)) events.push(...this.completeChild(childId, result))
@@ -560,6 +594,8 @@ export class CodexNormalizer implements EngineNormalizer {
this.pendingSpawns.delete(callId)
}
this.pendingChildResults.clear()
+ this.startedChildren.clear()
+ this.childReports.clear()
return events
}
}
diff --git a/cli/src/lib/normalize.ts b/cli/src/lib/normalize.ts
index 28a950d93..0e625d48e 100644
--- a/cli/src/lib/normalize.ts
+++ b/cli/src/lib/normalize.ts
@@ -408,8 +408,11 @@ function userTextRaw(msg: NormalizedMessage): string | null {
* then the text block is empty and there is nothing left to parse.
*/
function taskNotificationEvent(raw: Record<string, unknown>): LiveEvent | null {
- if (raw.type !== 'user') return null
- const content = (raw.message as { content?: unknown } | undefined)?.content ?? raw.content
+ // One that finishes while its parent still works comes as a `queued_command` attachment, the more common
+ // delivery (real 2.1.270–2.1.287). Read from user records alone, it never finished on the dial.
+ const attachment = raw.type === 'attachment' ? raw.attachment as { type?: unknown; prompt?: unknown } | undefined : undefined
+ if (raw.type !== 'user' && attachment?.type !== 'queued_command') return null
+ const content = attachment ? attachment.prompt : (raw.message as { content?: unknown } | undefined)?.content ?? raw.content
let text = ''
if (typeof content === 'string') text = content
else if (Array.isArray(content)) {
diff --git a/cli/src/lib/subagentTurn.spec.ts b/cli/src/lib/subagentTurn.spec.ts
index 5d8b2a282..d7fdbb15d 100644
--- a/cli/src/lib/subagentTurn.spec.ts
+++ b/cli/src/lib/subagentTurn.spec.ts
@@ -171,3 +171,59 @@ describe('async sub-agents (real claude transcript)', () => {
expect(summarize).toHaveBeenCalledTimes(1)
})
})
+
+/**
+ * A background sub-agent that finishes while its parent is still working is handed back INTO the running
+ * turn: Claude Code writes its `<task-notification>` as a `queued_command` attachment (commandMode
+ * `task-notification`), not as the `type:"user"` record it writes when the parent is idle. Across real
+ * 2.1.270–2.1.287 transcripts the attachment is the more common of the two (about 800 against 370). Read only from
+ * user records, that sub-agent never finished: its row stayed running on the dial, and the parent's recap
+ * was held until the backstop gave up on it. Records synthesized in the real shape; the text is invented.
+ */
+describe('async sub-agents handed back mid-turn', () => {
+ const line = (o: Record<string, unknown>) => JSON.stringify(o)
+ const notification = (id: string, status: string) =>
+ `<task-notification>\n<task-id>a1b2c3d4e5f6a7b8c</task-id>\n<tool-use-id>${id}</tool-use-id>\n<output-file>/tmp/tasks/a1b2c3d4e5f6a7b8c.output</output-file>\n<status>${status}</status>\n<summary>Agent "Count the fixtures" finished</summary>\n<result>There are 12 fixtures.</result>\n</task-notification>`
+ const turn = [
+ line({ type: 'user', uuid: 'u1', message: { role: 'user', content: 'count the fixtures in the background, then tidy the README' } }),
+ line({ type: 'assistant', uuid: 'a1', message: { role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_bg1', name: 'Agent', input: { description: 'Count the fixtures', run_in_background: true } }], stop_reason: 'tool_use' } }),
+ line({ type: 'user', uuid: 'r1', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_bg1', content: 'Async agent launched successfully.' }] } }),
+ line({ type: 'assistant', uuid: 'a2', message: { role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_ed1', name: 'Edit', input: { file_path: 'README.md' } }], stop_reason: 'tool_use' } }),
+ line({ type: 'user', uuid: 'r2', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_ed1', content: 'The file README.md has been updated successfully.' }] } }),
+ line({
+ type: 'attachment', uuid: 'q1',
+ attachment: { type: 'queued_command', prompt: notification('toolu_bg1', 'completed'), commandMode: 'task-notification', origin: { kind: 'task-notification', producer: 'session-task' } },
+ }),
+ line({ type: 'assistant', uuid: 'a3', message: { role: 'assistant', content: [{ type: 'text', text: 'README tidied; the scout counted 12 fixtures.' }], stop_reason: 'end_turn' } }),
+ ]
+
+ it('finishes the sub-agent, keyed by its tool-use id, and opens no turn', () => {
+ const state = newTurnState()
+ const events = turn.flatMap((raw) => lineToEvents(raw, state))
+ expect(events.filter((e) => e.type === 'subagent_finished')).toEqual([
+ { type: 'subagent_finished', payload: { id: 'toolu_bg1', status: 'completed', summary: 'Agent "Count the fixtures" finished' } },
+ ])
+ expect(events.filter((e) => e.type === 'turn_started')).toHaveLength(1)
+ expect(events.at(-1)).toEqual({ type: 'turn_ended', payload: {} })
+ })
+
+ it('ticks the row off on the dial, so the recap is not held for it', async () => {
+ vi.useFakeTimers()
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-subagent-'))
+ try {
+ const frames: CommanderFrame[] = []
+ const summarize = vi.fn(async () => 'recap\n\nbody')
+ const mirror = new CommanderMirror({ send: (f) => frames.push(f), sendWeb: () => {}, hasDevice: () => true, summarize, dataDir: dir })
+ const state = newTurnState()
+ for (const raw of turn) mirror.ingest(lineToEvents(raw, state), 'sess-midturn')
+ const rows = frames.filter((f) => (f.payload as { kind?: string }).kind === 'agents')
+ .map((f) => (f.payload as { agents: Array<{ text: string }> }).agents.map((a) => a.text))
+ expect(rows.at(-1)?.every((text) => text.startsWith('✓'))).toBe(true)
+ await vi.advanceTimersByTimeAsync(13_000)
+ expect(summarize).toHaveBeenCalledTimes(1)
+ } finally {
+ vi.useRealTimers()
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/docs/research/2026-10-06-real-cli-record-audit.md b/docs/research/2026-10-06-real-cli-record-audit.md
new file mode 100644
index 000000000..fb0cba11d
--- /dev/null
+++ b/docs/research/2026-10-06-real-cli-record-audit.md
@@ -0,0 +1,89 @@
+# What the real Claude Code and Codex write, and what the daemon reads: 2026-10-06
+
+Daemon QA with the real CLIs (Claude Code 2.1.290, Codex 0.160) found three bugs in one day, all where the e2e fake engines had drifted from what the CLIs write:
+- a tool's aborted output arriving after an interrupt (#850);
+- Claude's mid-turn `queued_command` attachment missing from history (#855);
+- Claude writing `/compact` as a plain user line, which opened a turn nothing closed (#858).
+
+This audit counts every record type in real recent transcripts. Each type the daemon's readers never mention gets one of three verdicts, checked against the code paths:
+- **handled**: some reader acts on it;
+- **irrelevant**: pure metadata, or a duplicate of a record that is handled;
+- **GAP**: missing it changes what a person sees: the turn lifecycle, the history (`session_get`), tool events, questions, compaction, sub-agents, titles, models and effort, token usage, or search.
+
+**Method.** 152 Claude Code transcripts (2.1.270 to 2.1.290, mostly 2.1.283 and 2.1.287) and 200 Codex 0.160.0 rollouts were read on one development machine. Only record types, keys, counts and orderings were recorded, never content. Every test and fixture uses synthesized records with invented text.
+
+**Readers checked.** Claude records:
+- the live turn lifecycle: `lineToEvents`, the Stop hook in `core/turns/turnHooks.ts`, activity in `lib/turnActivity.ts`;
+- the history (`messagesToEvents`), the recap (`lastTurnTextFromRawLines`), paging and attach (`claudePageLine`, `startsClaudeTurn`);
+- models and effort (`runtimeProfile.ts` `ingestClaude`), token usage (`agentTokenUsage.ts`), search (`sessionSearch/`), idle time (`transcriptActivity.ts`), titles (`sessionTitle.ts`, the terminal title), and the dial's sub-agent rows (`commander.ts`).
+
+For Codex: `CodexNormalizer` (live and replay), `lastCodexTurnText`, `codexTaskBoundary`, `subagent.ts`, the model controller, token usage and idle time.
+
+## Gaps found
+
+| # | Engine | Record | What a person saw | Fix |
+|---|---|---|---|---|
+| 1 | Codex 0.160 | `function_call_output` of `spawn_agent` is `{"task_name":"/root/<name>"}`; the child is named by `event_msg/item_completed/SubAgentActivity` (`started`, `completed`) | Every sub-agent Codex started closed at once as a failed Task, with `{"task_name":…}` as its output, live and in the history. Its work and result never showed. | this PR: the spawn's child comes from the `started` activity (or the path), the Task closes on `completed`, and its result is the child's report (`response_item/agent_message`, `Payload:`) |
+| 2 | Claude | `attachment/queued_command` with `commandMode: "task-notification"`: a background sub-agent's `<task-notification>` handed back into a turn still running | That sub-agent never finished: its row stayed running on the dial, and the parent's recap was held until the backstop gave up on it. This is the more common delivery (about 800, against 370 as user records). | this PR: `taskNotificationEvent` reads the attachment as well as the user record |
+| 3 | Claude | `user` (isMeta) `"Stop hook feedback:…"`, then `attachment/goal_status` `{met:false}` (the `/goal` loop) or `attachment/hook_blocking_error` (a Stop hook that blocks); Claude continues in the same turn | The turn closed at the iteration's `end_turn`. The continuation ran with no turn open: no `turn_started`, no `turn_ended`, no recap, and the agent read idle again after each 30 s lease. | #863 |
+| 4 | Codex 0.160 | `item_completed/UserMessage` (and its `response_item/message`) wrapping `<send_user_message_question_reply>[{"answer","question","questionItemId"}]</…>`: the person's answer to `request_user_input_async`, a question that does not stop the turn | The wrapper and its JSON were the person's message, in the live turn, the history, the recap and search. | separate PR, branch `fidelity-codex-question-reply` |
+
+Moved engine homes (`CLAUDE_CONFIG_DIR`, `CODEX_HOME` from the login shell) are the same class of drift but not a record type. They are fixed on branch `fidelity-moved-homes`.
+
+## Claude Code
+
+| Record | Count | Verdict | Evidence |
+|---|---|---|---|
+| `user`, `assistant` | 28,746 / 54,032 | handled | `transformLine` and every reader above |
+| `system/compact_boundary` | 37 | handled | `compactEventFromRaw` emits `context_compact` |
+| `system/turn_duration` | 1,657 | irrelevant | Written after the Stop hooks of a finished turn. The turn already closed on the assistant's terminal `stop_reason` (1,655 of 1,657 turns end `end_turn`/`stop_sequence` with text), and the Stop hook closes the rest. Counted as activity in `transcriptActivity.ts`. |
+| `system/stop_hook_summary` | 1,639 | irrelevant | Bookkeeping for the Stop hooks, which reach the daemon as the hook itself. Counted as activity. |
+| `system/local_command` | 107 | handled, models and effort | `/model`, `/effort`, `/usage`, `/goal` with no args, and dialogs closing, as `<command-name>` or `<local-command-stdout>`. `ingestClaude` reads `raw.content`, so "Set model to …" and "Set effort level to …" land. A local command is not a turn; `transformLine` ignores `system` records. |
+| `system/informational` | 55 | irrelevant | TUI notices: "Usage limit reached/reset", "Goal paused/still active", "A hook blocked", "Remote Control disconnected", "Unknown command". When one ends a turn, the turn's own synthetic assistant record (`<synthetic>`, `stop_sequence`, `isApiErrorMessage`) carries the reason and closes it. |
+| `system/away_summary` | 51 | irrelevant | Claude Code's own "while you were away" summary, written after `turn_duration` when the person comes back. Not part of the conversation. The daemon makes its own recaps. |
+| `system/scheduled_task_fire` | 3 | handled, by the record after it | The `/loop` or cron prompt it fires is the next record, a `user` line with `isMeta` and `promptSource: "system"`, which opens a turn (`compactEventFromRaw`). |
+| `system/bridge_status` | 1 | irrelevant | Remote-control bridge status. |
+| `queue-operation` | 6,361 | irrelevant | The TUI's queue: `enqueue`, `dequeue`, `remove`, `popAll`. What is delivered is written again, as a `user` prompt when the turn has ended or as a `queued_command` attachment mid-turn. `remove` is the person taking it back. |
+| `attachment/queued_command`, `commandMode: "prompt"`, `origin.kind: "human"` | 1,541 (all modes) | handled (#855) | In the history (`queuedHumanPrompt`), search and the device's result evidence. It opens no live turn, by design: it joins the running one. |
+| `attachment/queued_command`, `commandMode: "task-notification"` | (included above) | **GAP 2, fixed here** | See above. |
+| `attachment/queued_command`, `origin.kind: "auto-continuation"` or `"peer"` | rare | irrelevant | Claude's own continuations, and sub-agent hand-backs to the model. Not the person's words (#855). |
+| `attachment/goal_status` | 80 | **GAP 3** (`met: false`, not `sentinel`) | Not met: written after the Stop hook's feedback line, then Claude continues the turn. Met: written after the final `end_turn`. `sentinel: true` restates an active goal in a session's opening attachments and is not a continuation. |
+| `attachment/hook_blocking_error` | 6 | **GAP 3** (`hookEvent: "Stop"`) | A Stop hook that blocked; the same continuation as the goal loop. |
+| `attachment/task_status` | 54 | irrelevant | Restates background tasks (`running`/`completed`) after a compaction, beside `compact_file_reference`. The task's own `<task-notification>` is what finishes it. |
+| `attachment/silent_turn_reminder`, `total_tokens_reminder`, `batching_reminder_sent`, `bash_output_audience_note`, `task_reminder`, `date`, `instructions`, `nested_memory`, `skill_listing`, `agent_listing_delta`, `deferred_tools_*`, `mcp_instructions_delta`, `hook_additional_context`, `hook_success`, `hook_system_message`, `invoked_skills`, `prompt_snapshot`, `session_context`, `environment`, `credential_org`, `remote_session_change`, `command_permissions`, `file`, `directory`, `read_truncation_notice` | — | irrelevant | Context injected for the model, or session plumbing. Nothing a person reads in the conversation. |
+| `attachment/compact_file_reference` | 72 | irrelevant | Files re-attached for the model after a compaction. |
+| `attachment/thinking_drop`, `thinking_stripped` | 26 | irrelevant | Telemetry about thinking blocks the API dropped. |
+| `attachment/hook_non_blocking_error`, `hook_cancelled` | 5 | irrelevant | A hook failed or was cancelled without stopping anything. The turn goes on as written. |
+| `attachment/edited_text_file` | 583 | irrelevant | Tells the model a file changed outside it. |
+| `attachment/auto_mode`, `auto_mode_exit`, `permission-mode`, `mode` | 168 / 1 / 10,217 / 10,220 | irrelevant | The permission mode. The daemon chooses it at launch (`engineLaunch.ts`) and shows no live permission mode. |
+| `attachment/model` | 200 | irrelevant | The model's identity, at session start. The model comes from each assistant record's `message.model`, the startup banner and "Set model to" (`runtimeProfile.ts`), which arrive no later. |
+| `ai-title`, `custom-title` | 10,063 / 1 | handled, search | `sessionSearch/indexer.ts` (a custom title outranks the AI one). The tile is named from the terminal title Claude Code sets from the same title (`sessionTitle.ts`). |
+| `agent-name` | 1,521 | irrelevant | The same title, for Claude Code's own agent views. |
+| `last-prompt`, `pr-link`, `cost-state`, `file-history-snapshot`, `file-history-delta`, `atis-latch`, `worktree-state`, `relocated`, `frame-link`, `bridge-session`, `artifact-*`, `continued-in` | — | irrelevant | Claude Code's own bookkeeping. Token usage is summed from the assistant records' `usage` (`agentTokenUsage.ts`), not `cost-state`. |
+
+## Codex 0.160
+
+| Record | Count | Verdict | Evidence |
+|---|---|---|---|
+| `event_msg/task_started`, `task_complete`, `turn_aborted` | 2,285 / 2,276 / 6 | handled | The turn lifecycle, `codexTaskBoundary`, and the turn error (`codexTaskError`) |
+| `event_msg/item_completed/UserMessage`, `AgentMessage` | 297 / 3,093 | handled, except **GAP 4** | The 0.147+ TUI vocabulary (`USER_TURN_TYPES`, `AGENT_TEXT_TYPES`). A message typed mid-task (75 measured) opens a new turn card while Codex keeps working. That is long-standing behaviour, not drift. A `UserMessage` can be the answer to an async question, wrapped (gap 4). |
+| `event_msg/token_count` | 7,723 | handled | Token usage and context (`agentTokenUsage.ts`) |
+| `token_usage_record` | 7,415 | irrelevant | The same usage, written beside each `token_count`. |
+| `event_msg/thread_settings_applied`, `turn_context` | 2,377 / 2,375 | handled | The model controller's model and effort |
+| `world_state` | 318 | irrelevant | `AGENTS.md`, environment, permissions and model, injected for the model. The model is read from `thread_settings_applied`/`turn_context`. |
+| `event_msg/thread_goal_updated` | 2 | irrelevant | The `/goal` objective and status. The turn is driven by the injected `<codex_internal_context source="goal">` message (still written by 0.160), and the goal's status by the pane. |
+| `response_item/message`, `reasoning`, `function_call(_output)`, `custom_tool_call(_output)` | — | handled | Tool cards, thinking and `/goal` turns |
+| `compacted` | 83 | handled | `context_compact` |
+| `event_msg/item_completed/ContextCompaction` | 73 | irrelevant | Always next to a `compacted` (32 of 32 in main sessions). |
+| `response_item/compaction` | 153 | irrelevant | The encrypted summary. At the head of a forked thread it is inherited history, and in a main session it sits beside `compacted`. |
+| `event_msg/item_completed/Reasoning` | 7,226 | irrelevant | Duplicates `response_item/reasoning`. |
+| `event_msg/item_completed/CommandExecution`, `FileChange`, `McpToolCall`, `ImageView`, `Extension` (`web.search`, `clock.sleep`) | 5,004 / 358 / 378 / 118 / 529 | irrelevant | Details of a tool call already shown as a card. Each sits inside an open `exec`/`js`/`sleep` call: web searches inside `exec` calling `tools.web__run` (240 of 241), which already renders as a WebSearch card. The rest are a background command's completion after its `exec` returned. |
+| `event_msg/item_completed/SubAgentActivity` | 769 | **GAP 1, fixed here** | `started` names the spawned child's thread; `completed` is the only record that it finished; `interacted` follows `send_message`/`followup_task`. |
+| `event_msg/item_completed/CollabAgentToolCall` | 61 | irrelevant | Detail of `wait_agent`, with empty `agents_states` in v2. |
+| `response_item/agent_message` | 1,699 | **part of GAP 1, fixed here** | Inter-agent messages, `Message Type: FINAL_ANSWER/MESSAGE/NEW_TASK`. A child's message to its parent is its report. |
+| `inter_agent_communication_metadata` | 663 | irrelevant | `trigger_turn` for the agent_message after it. |
+
+## Not record types, noted on the way
+
+- `runtimeProfile.ts` `readCodexCache` and `sessionTitle.ts` `codexThreadName` fall back to the daemon's own `CODEX_HOME`. This is the moved-homes class, and it is left to that branch.
+- `request_user_input_async` (11 calls) is Codex 0.160's question tool beside `request_user_input`. It returns `{"accepted":true}` at once, and the answer arrives later as a user message (gap 4). Its card is the plain tool name, as before. The question itself is read from the pane, and how 0.160 draws this one was not recorded, so this audit does not cover it.