Repository navigation
fix(agents): keep a finished Claude CLI turn that outgrew its stream budget - #160209
zeroaltitude wants to merge 9 commits into
Conversation
…budget `CLI_STREAM_JSON_OUTPUT_LIMITS` uses one 8 MiB constant for two unrelated jobs. `maxPendingLineChars` is a real memory bound: it caps a single un-newlined line held in `lineBuffer.pending`. `maxTurnRawChars` is not — it is an odometer over a stream whose partial-message deltas and tool results are discarded the moment they are assembled. Under `--include-partial-messages --verbose`, 8 MiB of cumulative stream-json is ordinary for a long agentic turn. When that odometer tripped, `accountClaudeJsonlLine()` set `parseErrorText`, `handleJsonlLine()` early-returned for every later line, and the terminal `result` record — which arrives last and carries the finished answer — was never seen. `getOutput()` returned empty text with an `errorText`, and `execute-process.ts` raised a `format` FailoverError, which the gateway classified `status=400` / `chain_exhausted`. A 23-minute run that had already written its report to disk was reported as failed and lost its `completionTarget=parent` completion; ten runs died this way since Sep 1. `maxTurnLines` carried the identical cliff, so capping only characters would have relocated the failure rather than removing it. Cumulative budgets now stop the parser from assembling without abandoning the turn. Past exhaustion the Claude stream-json path retains nothing further and decodes each line only far enough to recognize the terminal result. If that record arrives the run is not failed: the answer and session continuity survive, and a new `getOutputTruncationText()` surfaces the truncation, which `execute-process.ts` logs as `cli stream truncated`. If it never arrives the outcome is genuinely unknowable and the pre-existing error is returned byte-identically, so the guard is not removed. `maxPendingLineChars` is untouched and stays fatal. The budget accounting and the terminal-result watcher live in a new `src/agents/cli-output-stream-budget.ts`, keeping the parser inside the repository's 700-line file budget. Validation from the topic worktree on origin/main 000d039: `pnpm tsgo:core` 0; `pnpm tsgo:core:test` 0 (20 shards); `node scripts/run-vitest.mjs run src/agents/cli-output-*.test.ts` 0 (182 tests, 8 files, 2 shards); `pnpm plugin-sdk:surface:check` 0; `pnpm deadcode:unused-files` 0 on both the production and full-tree scans; `pnpm oxlint` and `pnpm oxfmt --check` clean on every touched file; `git diff --check` clean; `pnpm tsx scripts/proof-cli-stream-turn-budget.ts` 0 — all four scenarios (recovered-raw, recovered-lines, unknowable-raw, retention-flat) asserted, with 32 MiB streamed past a spent budget producing zero new assistant deltas and a negative heap delta. 31 of the 32 `check:changed` lanes pass individually; `check:line-cap-ratchet` fails only because this host runs git 2.34.1 and the lane needs `git cat-file --batch -z` (git 2.37+) — it fails identically on an unmodified worktree, and `check:max-lines-ratchet`, the lane that actually measures line growth, passes. Beads: openclaw-v1et Co-Authored-By: Claude <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR recovers Claude CLI terminal replies after cumulative stream budgets are exhausted while preserving outstanding-tool progress and logging truncation. Example: A Claude turn streams “Before.”, starts a tool, exceeds 20,000 ordinary frames, and finishes with “DONE”.
Review scores
ProductKind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 2 items remain This PR retains useful recovery work absent from current main; the previous finding is fixed, but the changed delivery contract needs an owner decision. Priority: P1 Decision needed
Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe CLI runner feeds subprocess stdout into the shared JSONL parser, which projects text, tool activity, session continuity, and terminal results into agent execution. flowchart LR
A[Claude CLI stdout] --> B[JSONL framing]
B --> C[Turn budget accounting]
C --> D[Normal output assembly]
C --> E[Post budget watcher]
E --> F[Tool progress and settlement]
D --> G[Terminal reply]
E --> G
Technical reviewBest possible solution: Recover verified terminal replies with bounded parsing and an owner-approved policy for preserved prefixes and truncation visibility. Do we have a high-confidence way to reproduce the issue? Current-main source directly shows fatal cumulative-budget exhaustion followed by rejection of later records; no target code or tests were executed during this read-only review. Is this the best way to solve the issue? Terminal recovery addresses the remaining failure without another tuning option, and the prior normalization defect is fixed; accepting incomplete boundary knowledge remains a product decision. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 315e772a1d30. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +365, Tests +343, Docs +6, Other +570. Total +1284 across 8 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (7 earlier review cycles)
Reviewed October 14, 2026, 3:53 AM ET / 07:53 UTC (Revision 8). |
…rminal-result # Conflicts: # src/agents/cli-output-stream.ts
…text (review feedback) ClawSweeper Revision 5 (head bf578b0) raised three [P2] defects, all in `src/agents/cli-output-stream.ts`. All three were reproduced before fixing and measured after; two of them were failing tests already on the branch, including one that exists on `origin/main`. 1. Charge blank and hook-handled Claude frames to the line budget. Moving `chargeLine()` below the blank-line and custom-parser returns exempted ordinary frames from the line odometer, breaking the documented bounded-frame contract (`docs/gateway/cli-backends.md`). `push("\n".repeat(20001))` spent no line budget at all. Both charges now run through one accountant (`createOrdinaryClaudeLineAccountant`) for blank frames, lifecycle frames and custom-parser frames alike; recognized partial-message deltas keep their line exemption and are still charged for characters. Base-fail: `counts actual blank Claude frames without invoking hooks or inventing a finish frame` (an `origin/main` test) and the branch's own `keeps a finished Claude turn that outgrew the line-count budget` both failed at the reviewed head. Both pass now. 2. Track observed output separately from ordinary-frame charges. `getOutput()` used `turnBudget.lines`, which counts only ordinary built-in records, where `origin/main`'s `rawLines` counted every observed frame. A recognized `text_delta` followed by `finish()` with no result envelope assembled its text and then returned null, never reaching the partial-text fallback. Hook-handled text had the same bug. The budget now keeps an independent `observedLines` fact, charged for every frame. 3. Preserve pre-budget text in a tool-split reply. Once a budget is spent the parser stops assembling, so the closing message is never streamed and `preferStreamedClaudeTextOverResult` cannot see it: the envelope's text replaced the reply text already assembled. Reply selection is now `resolveCliTerminalReplyText`, which on a truncated turn keeps the preserved candidate as a bounded prefix while a tool split still connects it to the answer (a tool outstanding, or a split already applied), and joins it to the envelope with the normal message separator. A draft with no tool split stays superseded exactly as on an unbudgeted turn, and the in-flight message is dropped when the envelope restates it, so a budget spent mid-message cannot duplicate text. The `origin/main` contract at `cli-output-stream.test.ts:364` ("Before.\n\nDONE") is unchanged. Proof harness repaired and extended. `overflowRawCharBudget` counted streamed bytes, but after openclaw#153545 the odometer charges retained characters, so the loop stopped ~96 KB short and `recovered-raw` failed its own truncation assertion at the reviewed head. It now streams until the parser reports exhaustion. Four new scenarios: `tool-split-silent`, `tool-split-commentary`, `superseded-draft` and `discounted-output-seen`. 8/8 pass. Two helpers moved into the existing sibling `cli-output-stream-budget.ts` to keep `cli-output-stream.ts` under the 700-line cap; no coverage was trimmed and no `max-lines` suppression was added. No test that exists on `origin/main` was deleted or weakened. Validation: `pnpm check:changed` exit 0, all 36 lanes (linuxbrew git 2.55 for the ratchet lanes). `pnpm deadcode:unused-files` 0 entries on both the production and full-tree scans. `pnpm tsx scripts/proof-cli-stream-turn-budget.ts` all assertions passed. Beads: openclaw-cy3n Co-Authored-By: Claude <[email protected]>
Round 10 — all three [P2] findings fixed, head
|
|
🦞👀 Re-review progress:
|
…tream budget (review feedback)
Exhausting a cumulative turn budget stops text assembly and keeps watching for
the terminal `result` record. That window had no semantic events at all, and
recovery needs two of them.
While a parsed tool is active, `execute-process.ts:145-156` routes every stdout
chunk to `observeOutput(false)` — transport allowance only — and
`diagnostic-owned-activity.ts:97-104` also makes `observeOutput(true)` inert
whenever `activeTools.size > 0`. So the blocked-tool clock can only be advanced
by `observeAttributedAgentProgress`, fed solely from
`onAttributedSubagentProgress`, or by the tool result that clears the active
tool. The post-budget watcher dispatched neither:
- its `line.includes("result")` prefilter dropped an attributed child frame
(`{"type":"assistant","parent_tool_use_id":…}`) before any decode, because
such a frame need not contain the substring `result` at all;
- it routed only `type === "result"` records onward, so the top-level
`tool_result` that settles the foreground `Agent` call never reached
`onToolResult`.
With an Agent tool outstanding at exhaustion, `lastProgressAgeMs` therefore grew
unbounded for the rest of the turn, and past the 15-minute
`BLOCKED_TOOL_CALL_ABORT_FLOOR_MS` floor `diagnostic.ts:327-336` can abort the
still-working run before the terminal result this recovery is waiting for.
The watcher now also admits a non-null `parent_tool_use_id`, dispatches
attributed child progress, and settles outstanding tool calls. The prefilter
tests for a string value rather than the bare key, because 51 of the 65 frames
in `test/fixtures/cli/claude-2.1-subagent-forwarding.jsonl` carry
`"parent_tool_use_id":null` — a bare substring test would hand nearly every
post-budget line to the decoder the prefilter exists to avoid. Settlement is deliberately
bounded: new `dispatchClaudeCliOutstandingToolSettlement` emits a result only
for a call already in `tracker.startedIds` and has no start path at all, so that
set stays frozen after assembly stops and neither the tool-split state nor the
synthetic-no-response condition that terminal reply selection reads can move.
It is a sibling of `dispatchClaudeCliStreamingToolEvent` rather than a mode on
it, for two reasons. The two jobs genuinely differ — the streaming dispatcher
also starts calls and tracks streamed tool input — and `git merge-tree` shows
upstream actively reworking the exact hunks a mode flag would have touched
(`onToolInputDelta`, the `content_block_start` and `content_block_delta`
branches). Appending a sibling in a region upstream has not touched keeps this
PR's conflict set unchanged; a flag added one conflicted file to it.
`createTerminalResultEventDispatcher` moves to the budget module so
`cli-output-stream.ts` stays inside the 700-line file budget.
Validation: `pnpm check:changed` exit 0; focused vitest over the five
`cli-output-*` suites; `pnpm tsx scripts/proof-cli-stream-turn-budget.ts` 9/9.
Controls, each measured on its own: source reverted with the tests kept fails
exactly the two new contracts; routing every admitted record through the full
semantic handler instead leaks a post-budget tool start; dropping the prefilter
as well breaks the branch's own truncation contract.
Beads: openclaw-cy3n
Round 20 — ClawSweeper Revision 6's one finding, fixed and measuredHead is now [P2] Preserve semantic tool progress during post-budget recovery —
|
| Control | Result |
|---|---|
| Round-20 source hunks reverted, tests and proof kept | 2 failed / 29 passed, exit 1 — exactly the two new contracts; proof exits 1 on the new scenario only, 0 of 3 attributed child frames advanced semantic progress |
| Shipped fix | 31 passed, exit 0; proof 9/9, exit 0 |
| Every admitted post-budget record routed through the full semantic handler | 1 failed / 30 passed, exit 1 — a post-budget tool_use starts a new call (['Agent','Grep']); proof fails its first scenario, recovered-raw: 1 assistant delta(s) were assembled after the budget was spent |
| The same, prefilter dropped too ("just resume handling") | 3 failed / 28 passed, exit 1 — both budget kinds assemble a post-budget delta (['dropped']), breaking this PR's own truncation contract |
The last two are why the fix has the shape it has rather than simply re-enabling the handler. Both were re-measured against the shipped structure.
New proof scenario semantic-progress-after-budget wires the exact callbacks execute-process.ts wires and asserts, in order: three attributed child frames each advance semantic progress while the Agent call is outstanding; a result for a call this stream never started does not settle it; the real result does; ordinary output advances progress again afterwards; and the recovered reply is unchanged. Two predicates it cannot run for real are restated with their source lines so the restatement is checkable — activeParsedTools mirrors execute-events.ts:240-277, the progress arithmetic mirrors diagnostic-owned-activity.ts:97-127. The real diagnostic owner needs a live registration; I did not pretend otherwise.
Widening considered and declined, with the check named
- Dispatching post-budget tool starts. Declined:
tracker.startedIdsis read by the synthetic-no-response condition atcli-output-stream.ts:434-440, andsawToolUseSinceTextfeedspreservedTextHasToolSplitat:428-429. Starting new work after assembly stops would move reply selection, which is the contract this PR exists to establish. The third control above is what that costs. - A
settleOutstandingOnlymode on the shared dispatcher (the first revision of this round). Declined on measurement:git merge-tree --write-tree --name-only upstream/main HEADreported a new conflicted file,src/agents/cli-output-events.ts, because upstream is reworking the exact hunks the flag touched (onToolInputDelta, thecontent_block_start/content_block_deltabranches). The appended sibling keeps the conflict set byte-identical to the reviewed base. - Plugin-parsed (
parseJsonlEvent) backends. Left exactly as-is. That path returns before the record decode, mirrors the pre-budgethandleCustomJsonlLineprecedence, and the finding's mechanism is on the native record path. Zero behavior change there. - The other
observeOutput/ stale-threshold call sites. Byte-identical toorigin/mainand outside this diff.
Validation
pnpm check:changed exit 0, LANECOUNT lane headers. All three Knip scans 0 entries. SQLite worker ratchet OK. Focused vitest over the five cli-output-* suites: 116 passed, 0 failed. Proof harness 9/9, exit 0. git diff --check clean.
check:line-cap-ratchet went red mid-round: wiring the tool tracker into the watcher took cli-output-stream.ts to 701 counted lines against its cap of 700. Nothing was trimmed or suppressed — createTerminalResultEventDispatcher, branch-owned code, moved into the existing sibling module.
Mergeability: the conflict set is {src/agents/cli-output-stream.ts} at the reviewed base and at this head — unchanged, neither enlarged nor resolved. The fork-sync decision that would clear it is not mine to take.
PR body audit
Round 20's own fix would have made two body statements false, so they are corrected rather than left standing: "decodes each remaining line only far enough to recognize the terminal result record", and "retention past the budget is flat by construction, because only a terminal result record is ever acted on". The proof output block and the retention-flat heap figure are re-pasted from a run at this head; the round-10 regression table is kept, relabelled as round 10's measurement against bf578b0edd8, and round 20's own table added beside it rather than overwriting it. The round-10 withdrawal of the git-2.34 ratchet excuse stays in place and is still accurate.
Not mine, unchanged
Owner decision: Required/ the P1 headline — whether genuine cumulative-budget exhaustion should become successful truncated delivery, when recovery can retain a superseded pre-budget prefix and report truncation only in operator logs. That is a maintainer call and I have not tried to pre-empt it.- The before-merge real behavior proof — a trace through a real
claudeprocess andexecuteCliProcess. It needs a ~20-minute agentic turn that naturally exceeds 8 MiB of stream-json, which a fork cannot produce on demand. Stated as a limit in the body rather than synthesized. This is also the honest reason a patch-quality rank-up here may move overall readiness by zero: overall follows the weaker of proof and patch quality, and proof is pinned by this item. - The merge conflict and the same-author companion branch
fix/cli-stream-subagent-budget— untouched.
@clawsweeper re-review
Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).
…(review feedback) ClawSweeper Revision 7 flagged a regression introduced by the previous commit, and it is real. `normalizeClaudeCliStreamJsonRecord` (`cli-output-echoed-binary.ts:35-40, 52-56`) strips Claude's echoed base64 **in place** — `node.source = rest; node.omitted = true; node.bytes = …` — and only then returns its serialized line. So the pre-budget path at `cli-output-stream.ts:641-645` hands tool dispatch a record whose payload is already gone, purely as a side effect of char accounting. The post-budget watcher decoded its own records and never called it. A Read or MCP image/PDF call that starts before exhaustion and returns after it settles through that path, so its full payload reached `onToolResult`; from there `prepareToolResult`'s array branch only redacts secrets, and the bytes would go on to tool events and after-tool hooks. The watcher now applies the same normalization to every record it decodes, before any dispatch, which is parity with the pre-budget path rather than a new rule. It is a no-op for anything that is not a `type: "user"` record carrying echoed media, and it only re-serializes when something was actually stripped. Measured: a post-budget `tool_result` carrying 4,300,000 base64 characters now reaches `onToolResult` as a 176-character record with `omitted: true` and the decoded byte count. New regression `omits echoed binary from a tool result that settles after the budget`; removing only the normalizer call fails it alone (1 failed / 31 passed, exit 1) with the raw payload visible in the dispatched delta. New proof scenario `settled-media-normalized` pins the same contract through the harness; 10/10. Validation: `pnpm check:changed` exit 0; focused vitest over the five `cli-output-*` suites 117 passed; proof 10/10. Beads: openclaw-cy3n
Round 20, second commit — Revision 7's [P2], fixedHead is now [P2] Normalize recovered tool-result records before settlement —
|
| Check | Result |
|---|---|
New regression omits echoed binary from a tool result that settles after the budget |
pass at this head; 1 failed / 31 passed, exit 1 with only the one-line normalizer call removed, the raw base64 visible in the dispatched delta |
Focused vitest, five cli-output-* suites |
117 passed, 0 failed |
New proof scenario settled-media-normalized |
4,300,000 base64 chars in, 176-character settled record out, omitted: true plus the decoded byte count; harness 10/10, exit 0 |
pnpm check:changed |
exit 0, 45 lane headers, Knip 0 entries on all three scans — run independently for each of the two round-20 commits |
git merge-tree --write-tree --name-only upstream/main HEAD |
conflict set {src/agents/cli-output-stream.ts}, unchanged from the reviewed base |
PR body updated: the proof block is re-pasted from a run at this head, the regression table carries the new case and its control, and the gate row reflects 117 focused tests and 10/10 scenarios.
Still owner-gated, unchanged
The real-behavior proof through a live claude process and executeCliProcess, the Owner decision: Required delivery-contract question, the merge conflict, and the Tool-result media projection provenance item (#128699) — that last one is now satisfied in direction by this commit, since the recovered path reuses the single stack-safe normalizer rather than adding a second one, but confirming that is the reviewer's call, not mine.
@clawsweeper re-review
Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).
|
🦞👀 Re-review progress:
|
|
Data point from 2026.10.3 (59cb447), which already includes #153545: a The CLI's own on-disk transcript for that run is 2.6 MB in total (tool results incl. Happy to provide more detail if it helps the proof. |
|
We are adopting this terminal-recovery approach for the genuine ordinary-frame exhaustion in #186967, alongside #166127 for discarded tool-result character accounting, rather than opening a competing implementation. Reviewed the latest body and ClawSweeper result at Please keep the maintainer decision on preserved-prefix/truncation semantics explicit. Our operational impact is completed tool work reported as failed with the final reply missing; simply raising the line limit moves that cliff. The distinction from #166127 is material, since each discounted tool-result record there still consumes an ordinary frame. |
|
@zeroaltitude, we've been hitting this cap in long Branch: https://github.com/brandonulrich/openclaw/tree/fix/cli-stream-cap-recovery (3 commits, rebased onto What changed from
Proof (all local, no model calls)
Not done yet
I'm happy to rework it if you'd rather keep your structure. |
# Conflicts: # src/agents/cli-output-events.ts # src/agents/cli-output-stream.ts
|
Closing in favour of #160325, which carries this PR's thesis (a spent stream budget truncates a finished turn instead of discarding it) and has been narrowed to it. The two were siblings, not a stack: #160325 contains this PR's base commit and independently re-fixed its three review follow-ups, so both could not land. #160325 has now been re-scoped to match main's current budget policy (forwarded subagent frames stay charged against the parent turn, and child text deltas stay charged), so it carries recovery of finished turns, the child-text leak fix, and the retention bounds that parsing past a spent budget needs. The branch here is preserved as Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
What Problem This Solves
A Claude CLI run that finished its work is reported as a failed run, and its completion is dropped.
src/agents/cli-output-stream-limits.tsdefines one constant,8 * 1024 * 1024, and uses it for two different jobs:maxPendingLineCharsis a real memory bound — it caps one un-newlined line held inlineBuffer.pending.maxTurnRawCharsis not: it is an odometer over a stream whose partial-message deltas and tool results are discarded the moment they are assembled. Under--include-partial-messages --verbose, 8 MiB of cumulative stream-json is ordinary for a long agentic turn, not pathological.When the odometer trips,
accountClaudeJsonlLine()setsparseErrorText,handleJsonlLine()early-returns for every later line, and the terminalresultrecord — which arrives last, and carries the finished answer — is never seen.getOutput()then returns empty text with anerrorText, andexecute-process.ts:355raises aformatFailoverError, which the gateway classifiesstatus=400/chain_exhausted.Observed on a 23-minute run (
claude-opus-5-5, 1,404,065 ms) that had already written its 81 KB report to disk:The session was marked
failedand itscompletionTarget=parentcompletion never reached the requester. Ten runs have been destroyed this way since Sep 1 across five different lanes.The same cliff exists on
maxTurnLines(20,000): whichever odometer trips first abandons the turn identically, so fixing only the character budget would just move the failure.What Changed
Cumulative turn budgets stop the parser from assembling; they no longer abandon the turn. Once
maxTurnRawCharsormaxTurnLinesis spent on the Claude stream-json path, the parser retains nothing further and decodes each remaining line only far enough to recognize the records that still change the turn's outcome: the terminalresult, attributed progress for an outstanding Agent call, and the tool result that settles one.getErrorText()returnsnull,getOutput()returns the finished answer and session continuity, and a newgetOutputTruncationText()reports the truncation.execute-process.tslogs it ascli stream truncated: provider=…instead of throwing.formatfailover. The guard is not removed.maxPendingLineCharsis untouched and stays fatal. It is the one limit that bounds a single allocation.New module
src/agents/cli-output-stream-budget.tsowns the budget accounting, the ordinary-frame accountant, the post-budget watcher, the terminal-result event dispatcher and terminal reply selection, keepingcli-output-stream.tsinside the repo's 700-line file budget (same reasoncli-output-stream-limits.tsexists).Truncated turns keep the reply text they already assembled. A tool-split reply streams as pre-tool text, a tool call, then a closing message that the terminal envelope restates. Because a spent budget stops assembly before that closing message, the envelope alone would erase the pre-tool half.
resolveCliTerminalReplyTextkeeps the preserved candidate as a bounded prefix while a tool split still connects it to the answer, and joins it to the envelope with the normal message separator. A draft with no tool split stays superseded exactly as on an unbudgeted turn, so recovery never resurrects a superseded draft.A truncated turn keeps its recovery clock alive (review round 20). Waiting for the terminal result is only safe if the run survives long enough to produce it. While a parsed tool is active,
execute-process.ts:145-156routes every stdout chunk toobserveOutput(false)— the transport allowance — anddiagnostic-owned-activity.ts:97-104makes evenobserveOutput(true)inert wheneveractiveTools.size > 0. So the blocked-tool clock can be advanced by exactly two things:observeAttributedAgentProgress, fed only fromonAttributedSubagentProgress, and the tool result that clears the active tool. The first revision of this watcher dispatched neither — itsline.includes("result")prefilter dropped an attributed child frame such as{"type":"assistant","parent_tool_use_id":…}before any decode, and it routed onlytype === "result"records onward, so the top-leveltool_resultthat settles a foregroundAgentcall never reachedonToolResult. With an Agent tool outstanding at exhaustion,lastProgressAgeMsgrew unbounded for the rest of the turn, and past the 15-minuteBLOCKED_TOOL_CALL_ABORT_FLOOR_MSfloordiagnostic.ts:327-336can abort the still-working run before the result this recovery waits for.The watcher now admits a non-null
parent_tool_use_id, dispatches attributed child progress, and settles outstanding tool calls. Settlement is deliberately bounded: newdispatchClaudeCliOutstandingToolSettlementemits a result only for a call already intracker.startedIdsand has no start path at all, so that set stays frozen after assembly stops and neither the tool-split state nor the synthetic-no-response condition that terminal reply selection reads can move.Two details that look incidental and are not:
dispatchClaudeCliStreamingToolEvent, not a mode on it. The first revision of this round added asettleOutstandingOnlyflag to the shared dispatcher.git merge-tree --write-tree --name-only upstream/main HEADthen reported a new conflicted file,src/agents/cli-output-events.ts, because upstream is actively reworking the exact hunks the flag touched (onToolInputDelta, thecontent_block_startandcontent_block_deltabranches). Appending a sibling in a region upstream has not touched keeps this PR's conflict set byte-identical to the reviewed base. The two jobs also genuinely differ — the streaming dispatcher starts calls and tracks streamed tool input; settlement must do neither.test/fixtures/cli/claude-2.1-subagent-forwarding.jsonlcarry"parent_tool_use_id":null, soline.includes("parent_tool_use_id")would hand nearly every post-budget line to the JSON decoder the prefilter exists to avoid./"parent_tool_use_id"\s*:\s*"/admits only real child records. This is a cost refinement, not a behavior change — both forms behave identically, which is why no test pins it; the measurement is below.Why this approach, and not the alternatives
The issue listed four candidate fixes. Three of them do not meet the bar, which is that a run that reached a terminal result must not be reported as failed:
maxTurnLinescliff at all.assistantText,preserveFrom/segmentStartboundary tracking,preferStreamedClaudeTextOverResult) for a defect whose whole cost is a mis-classification at the end of the run.The chosen approach is the smallest change that removes the cliff entirely rather than relocating it, keeps every real memory bound, and leaves the failure path intact for the case where the turn outcome really is unknown.
A fourth alternative was considered and rejected in round 20: simply routing every admitted post-budget record through the parser's full semantic handler. It is the obvious reading of the review finding, and it is measurably wrong — see the controls below.
Evidence
Real behavior proof
scripts/proof-cli-stream-turn-budget.tsdrives the productioncreateCliJsonlStreamingParserexactly asexecute-process.tsdoes — raw chunks throughpush(), thenfinish(), thengetErrorText()/getOutput(). Nothing in the parser, its record decoding, its budget accounting or its output assembly is stubbed; only theclaudesubprocess edge is synthesized, using the stream-json shapes the CLI emits under--include-partial-messages --verbose.The two
tool-splitscenarios are the reply-loss case directly: pre-tool text, a tool call, the budget spent, then the closing message and an envelope that restates only that message. They assert both halves survive.superseded-draftis their guard — the same shape with no tool split, where the envelope must still win.semantic-progress-after-budgetis new in round 20 and covers the recovery clock. It wires the exact callbacksexecute-process.tswires (onToolUseStart,onToolResult,onAttributedSubagentProgress) and asserts, in order, that three attributed child frames each advance semantic progress while the Agent call is outstanding, that a result for a call this stream never started does not settle it, that the real result does, that ordinary output advances progress again afterwards, and that none of it changes the recovered reply. Two predicates it cannot run for real are restated with their source lines so the restatement is checkable:activeParsedToolsmirrorsexecute-events.ts:240-277, and the progress arithmetic mirrorsdiagnostic-owned-activity.ts:97-127(the real diagnostic owner needs a live registration). With the round-20 source hunks reverted and the harness kept, this scenario is the only one that fails, with0 of 3 attributed child frames advanced semantic progress.settled-media-normalizedis new in the second commit of round 20 and closes a regression the first one introduced. A Read or MCP image call can start before exhaustion and return after it, so its result settles through the post-budget path;normalizeClaudeCliStreamJsonRecordstrips Claude's echoed base64 in place, which is why the pre-budget path gets it for free as a side effect of character accounting. The watcher now applies the same normalization to every record it decodes before any dispatch. Atool_resultcarrying 4,300,000 base64 characters reachesonToolResultas a 176-character record withomitted: trueand the decoded byte count.retention-flatalso answers the cost question for round 20's wider record admission. Measured over five runs each on this host, the whole harness takes a median 0.78 s at this head against 0.77 s with the round-20 source reverted — and this head runs one extra scenario. The post-budget path's added work is within measurement noise on a 33 MiB post-budget stream.retention-flatis the answer to the obvious objection, that recovering the run weakens a memory bound. It pushes 32 MiB of realistic frames after the budget is already spent and asserts both that zero new assistant deltas are assembled and that the heap grows by less than a quarter of the bytes streamed. Measured heap delta is negative (the transient frames are collected); retention past the budget stays flat because the only records ever acted on are the terminal result, attributed child progress, and a tool result for a call already started — none of which is retained.The harness is registered in
config/knip.config.tsrepositoryScriptEntries, and the file is present in the tree at the PR head, socheck-dependenciesstays green.Limit of this proof, stated plainly: it does not spawn
claudeand does not go throughexecuteCliProcess. An end-to-end trace through a real Claude CLI process is not something this fork can produce on demand — it needs a ~20-minute agentic turn that naturally exceeds 8 MiB of stream-json, which is not reproducible to order. The 23-minute production failure quoted above is the real-world observation; everything after it is parser-level.Regression tests
All regressions live in
src/agents/cli-output-framing.test.ts. Base-fail/head-pass is measured by reverting only the source files and re-running, with the tests kept in place.Round 20 — source hunks in
cli-output-stream.ts,cli-output-stream-budget.tsandcli-output-events.tsreverted:dispatches attributed Agent progress after the budget stops assembly(new)settles the outstanding tool after the budget stops assembly(new)starts no new tool call and settles no unstarted call after the budget(new guard)keeps post-budget tool-split reply text while the outstanding tool settles(new guard)omits echoed binary from a tool result that settles after the budget(new, second commit)Measured: 2 failed / 29 passed, exit 1 with the first commit's source reverted; 31 passed, exit 0 at that head. The two failures are separate
itblocks, so neither masks the other. The second commit adds the 32nd case; removing only its one-line normalizer call fails that case alone — 1 failed / 31 passed, exit 1, with the raw base64 visible in the dispatched delta.Two further controls say why the shape of the fix matters, not just its presence:
tool_usestarts a new call (['Agent','Grep']), unfreezing thestartedIdsset reply selection reads. The proof also fails its first scenario:recovered-raw: 1 assistant delta(s) were assembled after the budget was spent['dropped']), breaking this PR's own truncation contractEach control was re-measured against the shipped structure, not against the first revision of it.
Round 10 — the earlier round's measurement, reproduced for continuity (it was taken against
bf578b0edd8with two source files reverted, and its counts do not describe the current head):bf578b0edd8counts actual blank Claude frames without invoking hooks or inventing a finish frame(exists onorigin/main)keeps a finished Claude turn that outgrew the line-count budget instead of failing itkeeps pre-budget tool-split text when the budget is spent before the closing messagereports assembled built-in partial deltas when no result envelope arrivesreports assembled hook-handled text when no result envelope arriveslets a post-budget result supersede a draft with no outstanding tool split(guard)Measured then: 5 failed / 22 passed with the source reverted, 0 failed / 27 passed. No test that exists on
origin/mainhas been deleted or weakened in either round.Validation gate
Run from the topic worktree at head
e9d7a0512d7(both round-20 commits were gated independently):pnpm check:changedpnpm deadcode:unused-filesnode scripts/run-vitest.mjs runover the fivecli-output-*suitespnpm tsx scripts/proof-cli-stream-turn-budget.tsgit diff --checkRound 20 hit the
check:line-cap-ratchetlane again: wiring the tool tracker into the watcher tookcli-output-stream.tsto 701 counted lines against its cap of 700. Nothing was trimmed or suppressed —createTerminalResultEventDispatcher, branch-owned code, moved into the existing sibling module, which puts the file back under cap.A previous revision of this body claimed
check:line-cap-ratchetwas blocked by the local toolchain's git 2.34.1. That claim was withdrawn in round 10 and stays withdrawn: the lane runs under git 2.55, and in both rounds it caught real over-cap growth introduced by the round's own work.The PR is
CONFLICTINGagainst currentmain, insrc/agents/cli-output-stream.tsonly — measured withgit merge-tree --write-tree --name-only upstream/main <ref>, which reports the same single-file conflict set at the reviewed base1167f68387band at this head, so round 20 neither added to it nor resolved it. (It did briefly add to it; see the sibling-not-a-flag note above.) The fork'smainis well behind upstream; resolving that is a fork-sync decision and is deliberately not done here.Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).