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.

A /goal Claude Code works on after its hook refuses to stop is a turn of its own, not none (#863)

Dee5f5a652fb7be
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 2b0c9234b..326e5701d 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -20,7 +20,9 @@
// the engine does and runs it only if allowed, `!flood <KiB>` prints that much to the terminal, in
// numbered lines, the way a build log or a long diff does, `!clear` starts a new conversation in the
// same pane as Claude Code's `/clear` and Codex's `/new` do, `!compact` compacts the conversation as
-// `/compact` does (a real `/compact` (Claude Code) is written exactly as Claude Code writes it, with no turn) (and Claude Code then announces the same session again), `!compactmid` compacts in the
+// `/compact` does (a real `/compact` (Claude Code) is written exactly as Claude Code writes it, with no turn) (and Claude Code then announces the same session again), `!goalloop <condition>`
+// (Claude Code) works on after its first stop because the /goal hook refused it (`!goalpause <condition>`:
+// refused, and the goal paused with no further output), `!compactmid` compacts in the
// middle of a turn as an automatic compaction does, `!version` answers with the version this
// process is, `!goal` and `!goal done` (Codex) start and achieve a goal the way Codex 0.160 shows one
// under its composer, `!browse` (Codex) leaves Codex browsing its transcript in its default fullscreen
@@ -1212,6 +1214,52 @@ export async function run(engine, config = {}, { native = false } = {}) {
codex('response_item', { type: 'message', role: 'user', content: [{ type: 'input_text', text: answer }] })
codex('event_msg', { type: 'item_completed', turn_id: open, item: { type: 'UserMessage', id: `${id}-reply`, content: [{ type: 'text', text: answer, text_elements: [] }] } })
}
+ if (engine === 'claude' && directive?.[1] === 'goalpause') {
+ // The same refusal, after which Claude Code pauses the goal instead of working on (real 2.1.283): two
+ // notices and its turn_duration, with no output and no further Stop hook.
+ const condition = directive[2] || 'the work is done'
+ claude({ type: 'assistant', message: { id: `msg_${turn}_p1`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'text', text: `first pass at: ${condition}` }], stop_reason: 'end_turn' } })
+ say(`\r\nfirst pass at: ${condition}\r\n`)
+ await runHooks('Stop', { stop_hook_active: false })
+ claude({ type: 'user', isMeta: true, promptId: randomUUID(), message: { role: 'user', content: `Stop hook feedback:\n[goal]: not met yet: ${condition}` } })
+ claude({ type: 'attachment', attachment: { type: 'goal_status', met: false, condition, reason: 'one check still fails' } })
+ claude({ type: 'system', subtype: 'stop_hook_summary', hookCount: 1, hookInfos: [], hookErrors: [], preventedContinuation: false, stopReason: '', hasOutput: false, level: 'suggestion' })
+ claude({ type: 'system', subtype: 'informational', content: 'A hook blocked the stop again — pausing the goal.', level: 'notice' })
+ claude({ type: 'system', subtype: 'informational', content: 'Goal paused · /goal to resume', level: 'notice' })
+ claude({ type: 'system', subtype: 'turn_duration', durationMs: 5_000, messageCount: 6 })
+ say('Goal paused\r\n')
+ open = null
+ return
+ }
+ if (engine === 'claude' && directive?.[1] === 'goalloop') {
+ // Claude Code's /goal, its condition not met at the first stop, as 2.1.283 writes it: the answer and
+ // its Stop hooks, then the goal hook's refusal (a hidden feedback line, the goal's status and the
+ // hooks' summary) and the next pass in the SAME turn, with no prompt line between; a tool runs in it.
+ // The daemon closed the turn at the first stop and read the next pass as no turn at all.
+ //
+ // The first pass's Stop reaches the daemon only once the next pass is on disk, as a loaded daemon took
+ // it in a full end-to-end run (520 ms after that pass started): the CLI waits for its hook commands,
+ // but the hook's request can be read after it has gone on. So the hooks run once the pass has begun.
+ const condition = directive[2] || 'the work is done'
+ const model = config.claudeModel ?? 'claude-opus-5-5'
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
+ claude({ type: 'assistant', message: { id: `msg_${turn}_g1`, role: 'assistant', model, content: [{ type: 'text', text: `first pass at: ${condition}` }], stop_reason: 'end_turn' } })
+ say(`\r\nfirst pass at: ${condition}\r\n`)
+ claude({ type: 'user', isMeta: true, promptId: randomUUID(), message: { role: 'user', content: `Stop hook feedback:\n[goal]: not met yet: ${condition}` } })
+ claude({ type: 'attachment', attachment: { type: 'goal_status', met: false, condition, reason: 'one check still fails' } })
+ claude({ type: 'system', subtype: 'stop_hook_summary', hookCount: 1, hookInfos: [], hookErrors: [], preventedContinuation: false, stopReason: '', hasOutput: false, level: 'suggestion' })
+ const id = `call_${turn}_g`
+ claude({ type: 'assistant', message: { id: `msg_${turn}_g2`, role: 'assistant', model, content: [{ type: 'tool_use', id, name: 'Bash', input: { command: 'make check' } }], stop_reason: 'tool_use' } })
+ await pause(600)
+ const lateStop = runHooks('Stop', { stop_hook_active: false })
+ await pause(Number(config.goalPassMs) || 4_000)
+ await lateStop
+ claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: 'all checks pass' }] } })
+ await finish(`goal met: ${condition}`)
+ claude({ type: 'attachment', attachment: { type: 'goal_status', met: true, condition, reason: 'all checks pass' } })
+ claude({ type: 'system', subtype: 'turn_duration', durationMs: 6_000, messageCount: 8 })
+ return
+ }
if (directive?.[1] === 'version') { await finish(versionLine); return }
if (engine === 'codex' && directive?.[1] === 'goal') {
bottom = goalBottom(directive[2] === 'done' ? 'Goal achieved (1m)' : 'Pursuing goal (1m)')
diff --git a/cli/e2e/turns.e2e.ts b/cli/e2e/turns.e2e.ts
index 592d23f79..3571a6d3a 100644
--- a/cli/e2e/turns.e2e.ts
+++ b/cli/e2e/turns.e2e.ts
@@ -85,6 +85,53 @@ describe('how turns end', () => {
client.close()
}, 150_000)
+ it('claude: a /goal its hook says is not met yet goes on as a turn of its own, working until it ends', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'claude', 'goal-loop')
+ const since = client.frames.length
+ const label = 'Continuing goal: every check passes'
+ const continued = (frame: Frame) => isTurn('turn_started', agent.id)(frame) && frame.payload?.userMessage === label
+ // The goal hook refuses the first stop and Claude Code works on in the same turn, with no prompt line:
+ // the daemon closed the turn at that stop and the next pass ran with none open, so it never ended,
+ // had no recap, and read idle whenever its tool outlasted the work lease (real 2.1.283 transcripts).
+ client.send('message', { agentId: agent.id, content: '!goalloop every check passes' })
+ const pass = await client.waitFor(continued, 45_000, 'the goal\'s next pass to start', since)
+ const at = client.frames.indexOf(pass)
+ expect(client.frames.slice(since, at).filter(isTurn('turn_ended', agent.id))).toHaveLength(1)
+ await until('the agent to read as working in the next pass', async () => (await row(client, agent.id))?.activity?.state === 'working' || null, 3_000, 100)
+ const end = await client.waitFor(isTurn('turn_ended', agent.id), 45_000, 'the goal\'s next pass to end', at)
+ expect(end.payload?.aborted).toBeUndefined()
+ // Ended by its own answer, after its tool: not by the Stop of the pass before it, which reached the
+ // daemon after this pass had started (as under load) and force-closed it after the grace while its
+ // tool still ran.
+ const tool = client.frames.slice(at).find(isTurn('tool_end', agent.id))
+ expect(tool && client.frames.indexOf(tool) < client.frames.indexOf(end), 'the pass\'s tool to finish before it ends').toBe(true)
+ await settled(client, agent.id)
+ const page = await client.request<{ events?: Array<{ type: string; payload: Record<string, any> }> }>('session_get', { sessionId: agent.sessionId, limit: 200 }, 30_000)
+ expect((page.events ?? []).filter((event) => event.type === 'user_message').map((event) => event.payload.content))
+ .toEqual(['!goalloop every check passes', label])
+ // Its end leaves nothing open: the next message is a fresh turn.
+ await turn(client, agent.id, 'after the goal')
+ client.close()
+ })
+
+ it('claude: a /goal that pauses after its hook refuses to stop ends its turn, and the agent reads idle', async () => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'claude', 'goal-pause')
+ const since = client.frames.length
+ const label = 'Continuing goal: every check passes'
+ client.send('message', { agentId: agent.id, content: '!goalpause every check passes' })
+ const pass = await client.waitFor((frame) => isTurn('turn_started', agent.id)(frame) && frame.payload?.userMessage === label, 45_000, 'the refused stop to continue', since)
+ // Claude Code writes no output and fires no Stop for a pass it pauses: only notices and its own
+ // turn_duration. Nothing else closes the pass that the refusal opened.
+ await client.waitFor(isTurn('turn_ended', agent.id), 20_000, 'the paused pass to end', client.frames.indexOf(pass))
+ await until('the agent to read idle', async () => (await row(client, agent.id))?.activity?.state === 'idle' || null, 15_000, 250)
+ await turn(client, agent.id, 'after the pause')
+ client.close()
+ })
+
it.each(engines)('%s: Ctrl-C typed in the terminal itself ends the turn, and the agent goes on', async (engine) => {
const d = await fresh()
const client = await LocalClient.connect(d)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index d251bf0df..34be5d8ae 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -155,8 +155,11 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
* end-to-end suite's first Linux runs (#843): zsh's new-user menu kept out of an agent's pane
* (lib/engineLaunch.ts), a hook's ancestry read as it arrives (core/engines/hooks.ts), and a relaunch
* that must stay up to count (core/agents/swap.ts).
+ *
+ * Grew by 58 for the turn a blocking Stop hook continues (a Claude /goal loop): it is the turn lifecycle,
+ * which only the core's transcript normalizer and Stop-hook fallback can keep.
*/
-const CORE_CLOSURE_BUDGET = 105_879
+const CORE_CLOSURE_BUDGET = 105_937
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
diff --git a/cli/src/core/turns/turnHooks.spec.ts b/cli/src/core/turns/turnHooks.spec.ts
index 91c91511e..f0b5ff5e7 100644
--- a/cli/src/core/turns/turnHooks.spec.ts
+++ b/cli/src/core/turns/turnHooks.spec.ts
@@ -101,6 +101,32 @@ describe('turn hooks', () => {
expect(run.deps.emit).toHaveBeenCalledTimes(1)
})
+ // A /goal loop: a pass a blocking Stop hook continued is the transcript's to close. The Stop of the pass
+ // before it reached the daemon 520 ms after the next pass had started (end to end, under load), and
+ // force-closed that pass after the grace while it ran.
+ it('leaves a pass a blocking Stop hook continued to the transcript, unless the Stop is a failure', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const run = setup('claude')
+ const state = { turnOpen: true, pendingTools: new Map(), continued: true } as unknown as TurnState
+ run.normalizers.turnStates.set('s1', state)
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(run.deps.mirror.noteEngineStopped).toHaveBeenCalledWith('s1')
+ // The same, when the drain after the grace reads the pass's start.
+ state.continued = false
+ vi.mocked(run.deps.drain).mockImplementationOnce(async () => {}).mockImplementationOnce(async () => { state.continued = true })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(state.turnOpen).toBe(true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ // A StopFailure is the API failing in the pass itself: closed, as any wedged turn is.
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ expect(state.turnOpen).toBe(false)
+ expect(run.deps.emit).toHaveBeenCalledWith('s1', END)
+ expect(String(log.mock.calls[0][0])).toContain('force-closed by StopFailure hook')
+ })
+
it('says Stop for a clean stop', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const run = setup('claude')
diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.ts
index 05666d160..5c23bb083 100644
--- a/cli/src/core/turns/turnHooks.ts
+++ b/cli/src/core/turns/turnHooks.ts
@@ -12,7 +12,7 @@ import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
import type { CursorTaskHookQueue } from '../../engines/cursor/taskHookQueue.js'
import type { CommanderMirror } from '../../lib/commander.js'
import { sid } from '../../lib/log.js'
-import type { LiveEvent } from '../../lib/normalize.js'
+import type { LiveEvent, TurnState } from '../../lib/normalize.js'
import type { RegisteredSession } from '../../lib/registry.js'
import type { SessionNormalizers } from '../transcripts/normalizers.js'
@@ -191,6 +191,10 @@ export function createTurnHooks({
return
}
if (session.engine !== 'claude') return
+ // A pass a blocking Stop hook continued (a /goal loop) is the transcript's to close, by its end_turn or
+ // turn_duration: the Stop of the pass before it reached the daemon 520 ms after it began (end to end,
+ // under load) and force-closed it while it ran. Only a StopFailure still closes one here.
+ const leftToTranscript = (st: TurnState): boolean => st.continued === true && status !== 'error'
void (async () => {
await drain(sessionId)
// A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is
@@ -198,13 +202,14 @@ export function createTurnHooks({
// on disk — without it the recap fires on its settle timer and can beat claude's closing summary
// to the punch (measured: recap at 10:18:41, wrap-up written at 10:18:44).
mirror.noteEngineStopped(sessionId)
- if (!turnStates.get(sessionId)?.turnOpen) return // natural JSONL close already won → nothing to do
+ const open = turnStates.get(sessionId)
+ if (!open?.turnOpen || leftToTranscript(open)) return // natural JSONL close already won → nothing to do
// Still open: the transcript may just be lagging the Stop hook. Wait, re-poll, and only force-close
// if it STILL hasn't closed — a genuinely wedged turn, whose assistant text is on disk by now.
await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
await drain(sessionId)
const st = turnStates.get(sessionId)
- if (st?.turnOpen) {
+ if (st?.turnOpen && !leftToTranscript(st)) {
st.turnOpen = false
st.pendingTools.clear()
console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)
diff --git a/cli/src/lib/normalize.test.ts b/cli/src/lib/normalize.test.ts
index 23b2a43f6..52db0acbf 100644
--- a/cli/src/lib/normalize.test.ts
+++ b/cli/src/lib/normalize.test.ts
@@ -343,3 +343,90 @@ describe('a built-in command Claude Code runs itself, typed plainly', () => {
})
})
+
+// A Stop hook that blocks keeps Claude Code's turn going: `/goal` is built on one. The shapes are real
+// 2.1.282/2.1.283 records with invented text: the feedback as a hidden isMeta user line, then the record
+// saying which hook it was, then the continuation's output with no prompt line between. The iteration's
+// end_turn closed the turn, and the continuation ran with none open: no turn_started, no turn_ended, no
+// recap, and the agent read idle whenever a tool outlasted the work lease.
+describe('a Stop hook that blocks', () => {
+ const user = (content: string) => line({ type: 'user', uuid: `u-${content}`, message: { role: 'user', content } })
+ const feedback = line({ type: 'user', isMeta: true, promptId: 'p1', message: { role: 'user', content: 'Stop hook feedback:\n[goal check]: the condition is not met yet' } })
+ const goal = (met: boolean, extra: Record<string, unknown> = {}) => line({
+ type: 'attachment', uuid: `g-${met}`, attachment: { type: 'goal_status', met, condition: 'every page loads under a second', reason: 'two pages still slow', ...extra },
+ })
+ const blocked = (hookEvent: string, blockingError: unknown) => line({
+ type: 'attachment', uuid: `b-${hookEvent}`, attachment: { type: 'hook_blocking_error', hookName: hookEvent, hookEvent, toolUseID: 'h1', blockingError },
+ })
+ const summary = line({ type: 'system', subtype: 'stop_hook_summary', hookCount: 2, hookInfos: [], hookErrors: [], preventedContinuation: false, stopReason: '', hasOutput: false, level: 'suggestion' })
+ const answer = (text: string) => line({ type: 'assistant', uuid: `a-${text}`, message: { role: 'assistant', content: [{ type: 'text', text }], stop_reason: 'end_turn' } })
+
+ it('opens the goal\'s next iteration as a turn of its own, and closes it at its end', () => {
+ const state = newTurnState()
+ expect(lineToEvents(user('/goal every page loads under a second'), state)).toEqual([{ type: 'turn_started', payload: { userMessage: '/goal every page loads under a second' } }])
+ expect(lineToEvents(answer('made the home page fast'), state).at(-1)).toEqual({ type: 'turn_ended', payload: {} })
+ expect(lineToEvents(feedback, state)).toEqual([])
+ expect(lineToEvents(goal(false), state)).toEqual([{ type: 'turn_started', payload: { userMessage: 'Continuing goal: every page loads under a second' } }])
+ expect(state.turnOpen).toBe(true)
+ expect(state.continued).toBe(true)
+ expect(lineToEvents(summary, state)).toEqual([])
+ expect(lineToEvents(answer('made the rest fast'), state)).toEqual([
+ { type: 'text_delta', payload: { content: 'made the rest fast' } },
+ { type: 'turn_ended', payload: {} },
+ ])
+ // A goal met ends nothing more than the end_turn before it did; a goal restated at start opens nothing.
+ expect(lineToEvents(goal(true), state)).toEqual([])
+ expect(lineToEvents(goal(false, { sentinel: true }), state)).toEqual([])
+ expect(state.turnOpen).toBe(false)
+ })
+
+ it('opens the turn a person\'s own blocking Stop hook continues, labelled with its first line', () => {
+ const state = newTurnState()
+ expect(lineToEvents(blocked('Stop', { blockingError: 'Run the tests before you finish.\nThey are in test/.', command: 'check.sh' }), state))
+ .toEqual([{ type: 'turn_started', payload: { userMessage: 'Continuing: Run the tests before you finish.' } }])
+ const long = newTurnState()
+ expect((lineToEvents(blocked('Stop', { blockingError: 'x'.repeat(300) }), long)[0].payload as { userMessage: string }).userMessage)
+ .toBe(`Continuing: ${'x'.repeat(197)}...`)
+ expect(lineToEvents(blocked('Stop', {}), newTurnState())).toEqual([{ type: 'turn_started', payload: { userMessage: 'Continuing' } }])
+ expect(lineToEvents(goal(false, { condition: undefined }), newTurnState())).toEqual([{ type: 'turn_started', payload: { userMessage: 'Continuing goal' } }])
+ // A sub-agent's Stop is its own business, and a turn still open (its end_turn not read yet) goes on.
+ expect(lineToEvents(blocked('SubagentStop', { blockingError: 'no' }), newTurnState())).toEqual([])
+ const open = newTurnState()
+ lineToEvents(user('fix it'), open)
+ expect(lineToEvents(goal(false), open)).toEqual([])
+ expect(open.continued).toBe(false)
+ })
+
+ it('closes a pass that ends with no output when the goal pauses, and only such a pass', () => {
+ const informational = (content: string) => line({ type: 'system', subtype: 'informational', content, level: 'notice' })
+ const duration = line({ type: 'system', subtype: 'turn_duration', durationMs: 42_000, messageCount: 12 })
+ const state = newTurnState()
+ lineToEvents(user('/goal every page loads under a second'), state)
+ lineToEvents(answer('made the home page fast'), state)
+ lineToEvents(feedback, state)
+ lineToEvents(goal(false), state)
+ for (const record of [summary, informational('A hook blocked the stop twice — pausing.'), informational('Goal paused · resume with /goal')]) {
+ expect(lineToEvents(record, state)).toEqual([])
+ }
+ expect(lineToEvents(duration, state)).toEqual([{ type: 'turn_ended', payload: {} }])
+ expect(state.turnOpen).toBe(false)
+ expect(lineToEvents(duration, state)).toEqual([])
+ // A turn a prompt opened is left to its end_turn and the Stop hook, as before.
+ const prompted = newTurnState()
+ lineToEvents(user('fix it'), prompted)
+ expect(lineToEvents(duration, prompted)).toEqual([])
+ expect(prompted.turnOpen).toBe(true)
+ lineToEvents(feedback, prompted)
+ lineToEvents(answer('fixed'), prompted)
+ lineToEvents(goal(false), prompted)
+ lineToEvents(user('and the rest'), prompted)
+ expect(lineToEvents(duration, prompted)).toEqual([])
+ expect(lineToEvents(duration, { ...newTurnState(), turnOpen: true })).toEqual([])
+ })
+
+ it('shows the continuation in the history once, where the live view started it', () => {
+ const contents = messagesToEvents([user('/goal every page loads under a second'), answer('made the home page fast'), feedback, goal(false), blocked('Stop', { blockingError: 'not yet' }), summary, answer('made the rest fast')])
+ .filter((e) => e.type === 'user_message' || e.type === 'text_delta').map((e) => (e.payload as { content: string }).content)
+ expect(contents).toEqual(['/goal every page loads under a second', 'made the home page fast', 'Continuing goal: every page loads under a second', 'made the rest fast'])
+ })
+})
diff --git a/cli/src/lib/normalize.ts b/cli/src/lib/normalize.ts
index 0e625d48e..72213251c 100644
--- a/cli/src/lib/normalize.ts
+++ b/cli/src/lib/normalize.ts
@@ -693,6 +693,7 @@ export function messagesToEvents(rawLines: string[]): SessionEvent[] {
const toolIdToName = new Map<string, string>()
let thinkingCounter = 0
let inAutoFixSequence = false
+ let continuedAt = -1
for (const line of rawLines) {
if (!line.trim()) continue
@@ -702,6 +703,13 @@ export function messagesToEvents(rawLines: string[]): SessionEvent[] {
if (compact) { events.push(...compact); continue } // compact boundary → indicator; summary/meta → suppressed
const queued = queuedHumanPrompt(raw)
if (queued) { events.push({ type: 'user_message', payload: { content: queued } }); continue }
+ // A pass a blocking Stop hook continued, as the live view starts it (lineToEvents), once per pass.
+ const continued = stopHookContinuation(raw)
+ if (continued !== null) {
+ if (continuedAt !== events.length - 1) events.push({ type: 'user_message', payload: { content: continued } })
+ continuedAt = events.length - 1
+ continue
+ }
const msg = transformLine(raw)
if (!msg?.message) continue
@@ -813,6 +821,33 @@ export interface TurnState {
/** 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
+ /** The open turn is one a blocking Stop hook continued (`stopHookContinuation`), not a prompt's. */
+ continued?: boolean
+}
+
+/**
+ * The turn a Stop hook that blocked keeps going, or null. `/goal` is built on such a hook, and people write
+ * their own. Claude Code writes the hook's feedback as a hidden `isMeta` user line, then one of these, then
+ * works on in the SAME turn with no prompt line between (real 2.1.282/2.1.283):
+ * {"type":"attachment","attachment":{"type":"goal_status","met":false,"condition":"…","reason":"…"}}
+ * {"type":"attachment","attachment":{"type":"hook_blocking_error","hookEvent":"Stop","blockingError":{"blockingError":"…"}}}
+ * The pass's end_turn had closed the turn, so the rest ran with none open: no turn_ended, no recap, and
+ * idle whenever a tool outlasted the work lease. A `sentinel` goal_status restates an active goal at start.
+ * The label matches the Codex normalizer's goal continuations.
+ */
+export function stopHookContinuation(raw: Record<string, unknown>): string | null {
+ if (raw.type !== 'attachment') return null
+ const attachment = raw.attachment as Record<string, unknown> | undefined
+ if (attachment?.type === 'goal_status' && attachment.met === false && attachment.sentinel !== true) {
+ const condition = typeof attachment.condition === 'string' ? attachment.condition.trim() : ''
+ return condition ? `Continuing goal: ${condition}` : 'Continuing goal'
+ }
+ if (attachment?.type === 'hook_blocking_error' && attachment.hookEvent === 'Stop') {
+ const blocking = attachment.blockingError as { blockingError?: unknown } | undefined
+ const reason = typeof blocking?.blockingError === 'string' ? blocking.blockingError.trim().split('\n')[0].trim() : ''
+ return reason ? `Continuing: ${reason.length > 200 ? `${reason.slice(0, 197)}...` : reason}` : 'Continuing'
+ }
+ return null
}
export function newTurnState(): TurnState {
@@ -910,6 +945,24 @@ export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {
// launch ack, and this record is not a prompt.
const finished = taskNotificationEvent(raw)
if (finished) return [finished]
+ // A Stop hook that blocked: the pass's end_turn closed the turn Claude Code works on in. Open it again.
+ const continued = stopHookContinuation(raw)
+ if (continued !== null) {
+ if (state.turnOpen) return []
+ state.turnOpen = true
+ state.pendingTools.clear()
+ state.continued = true
+ return [{ type: 'turn_started', payload: { userMessage: continued } }]
+ }
+ // Claude Code's own record that its turn is over. A continued pass can end with no output: when the hook
+ // refuses again, Claude Code pauses the goal and writes only notices and this (real 2.1.283), with no
+ // end_turn or Stop to close what was opened above. Every other turn is closed as before.
+ if (raw.type === 'system' && raw.subtype === 'turn_duration') {
+ if (!state.turnOpen || !state.continued) return []
+ state.turnOpen = false
+ state.pendingTools.clear()
+ return [{ type: 'turn_ended', payload: {} }]
+ }
const msg = transformLine(raw)
if (!msg?.message) return []
@@ -930,6 +983,7 @@ export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {
if (state.turnOpen) events.push({ type: 'turn_ended', payload: {} })
state.turnOpen = true
state.pendingTools.clear()
+ state.continued = false
events.push({ type: 'turn_started', payload: { userMessage: userText } })
return events
}
diff --git a/docs/research/2026-10-06-real-cli-record-audit.md b/docs/research/2026-10-06-real-cli-record-audit.md
index fb0cba11d..13700116f 100644
--- a/docs/research/2026-10-06-real-cli-record-audit.md
+++ b/docs/research/2026-10-06-real-cli-record-audit.md
@@ -26,9 +26,9 @@ For Codex: `CodexNormalizer` (live and replay), `lastCodexTurnText`, `codexTaskB
| 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` |
+| 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. | #868 |
-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`.
+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 in #865.
## Claude Code