Repository navigation
fix(agents): compact mid-turn overflow while code-mode work is still pending - #129792
Conversation
…pending #128970 let a mid-turn overflow compact and continue only when every lifecycle item was balanced. A code-mode exec that returns status "waiting" has its result persisted, but its nested tool keeps a lifecycle item active, so the gate failed closed: no compaction, a generic "couldn't generate a response" warning, and the waiting run expired before the operator could resume it. Continuation resumes from the persisted tool results and never replays the assistant call, so the transcript is the settlement proof: gate on every requested tool call having a recorded result. Nested code-mode work stays owned by the run registry and resumes through `wait`, exactly as across turns.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 26, 2026, 9:08 AM ET / 13:08 UTC. ClawSweeper reviewWhat this changesThis PR lets mid-turn overflow compaction continue from a persisted Code Mode Merge readinessNo blocking defect was found in the reviewed PR head: it records the parked-run fact at the tool-result producer, permits only that recorded Code Mode case to bypass lifecycle settlement, and preserves the session-bound wait restriction. Keep this PR open for maintainer handling because it has the protected Priority: P1 Review scores
Verification
Live VerificationCommand: Result: FAIL (failed) — step 1 Assertions:
How this fits togetherThe embedded-agent runner recovers when the next model request exceeds its context budget after tools have run. It compacts the persisted transcript and starts a continuation prompt, while Code Mode retains a session-bound suspended run that the model later resumes through flowchart LR
A[Model turn] --> B[Code Mode exec]
B --> C[Tool result recorded]
C --> D{Mid-turn overflow}
D --> E{Recorded parked Code Mode run}
E -->|yes| F[Compact transcript]
E -->|no| G[Require fully settled tools]
F --> H{Same session retained}
H -->|yes| I[Continue from transcript]
H -->|no| J[Show overflow recovery guidance]
G --> I
Before merge
Agent review detailsSecurityNone. PR surfaceSource +165, Tests +43. Total +208 across 15 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain the producer-recorded parked-run distinction, then merge only after exact-head validation confirms the focused regression suite and all required checks on this head. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible: the focused integration support constructs a recorded waiting Is this the best way to solve the issue? Yes: the fact is captured at the tool-completion producer, matched to the current transcript batch, and consumed narrowly by overflow recovery; broadening generic active-tool continuation would violate the existing fail-closed invariant. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 776986f942dc. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (8 earlier review cycles)
|
…compaction A parked code-mode run is bound to the session it started in and `wait` rejects any other session, so a compaction that adopts a successor session cannot redeem it. When nested tool work is still parked, treat a rotating mid-turn compaction as a failed recovery and surface overflow guidance instead of a continuation that would fail on that binding.
Withholding the mid-turn continuation after a rotating compaction must not turn the committed compaction into a failure: maintenance, the after hook, the compaction count, and the post-compaction guard still run. Only the retry and the tool-result truncation retry are skipped before surfacing the overflow guidance.
Generic tools keep the fully-settled predicate; only a run with Code Mode engaged may continue while lifecycle items are active, since that is the one case where the outer exec result is persisted while the parked nested call stays owned by the code-mode run registry. A generic tool with an active item stays fail-closed (new regression).
…spension codeModeEngaged only says Code Mode controls were enabled for the attempt; Code Mode can still run direct tools, so a recorded direct-tool result plus unrelated active lifecycle work could take the weaker branch with no parked exec to resume. Record the fact where it happens instead: the tool completion handler marks an exec result that came back "waiting" as codeModeSuspended, and recovery continues past active items only when the recorded batch carries that fact. Code Mode enabled with a direct tool active stays fail-closed.
isExecToolName matches any tool named exec or bash, but only the marked Code Mode exec owns a resumable run. Carry the marked control-tool identity from the run's tool list (where the tool objects are known) to the subscription as codeModeExecToolNames, and record codeModeSuspended only for those tools. A plain exec returning a waiting-shaped result is no longer marked.
…tool surface uncompactedEffectiveTools is the bundle list before the tool catalog creates the marked Code Mode controls, so the identity set was empty in real Code Mode runs and the parked-run fact was never recorded. Derive it from the post-catalog effectiveTools, where the activity wrapper preserves the marker through copyAgentToolMetadata.
…e run A local yield_control parks the marked exec without creating a nested lifecycle item, so gating the rotation block on activeCount let that case retry in the successor session where wait rejects the original binding. Key the block off the recorded codeModeSuspended fact instead, with a zero-active-item rotation regression.
…pending (openclaw#129792) * fix(agents): compact mid-turn overflow while code-mode work is still pending openclaw#128970 let a mid-turn overflow compact and continue only when every lifecycle item was balanced. A code-mode exec that returns status "waiting" has its result persisted, but its nested tool keeps a lifecycle item active, so the gate failed closed: no compaction, a generic "couldn't generate a response" warning, and the waiting run expired before the operator could resume it. Continuation resumes from the persisted tool results and never replays the assistant call, so the transcript is the settlement proof: gate on every requested tool call having a recorded result. Nested code-mode work stays owned by the run registry and resumes through `wait`, exactly as across turns. * fix(agents): keep parked code-mode work fail-closed across a rotated compaction A parked code-mode run is bound to the session it started in and `wait` rejects any other session, so a compaction that adopts a successor session cannot redeem it. When nested tool work is still parked, treat a rotating mid-turn compaction as a failed recovery and surface overflow guidance instead of a continuation that would fail on that binding. * fix(agents): keep post-compaction hooks when a rotated retry is withheld Withholding the mid-turn continuation after a rotating compaction must not turn the committed compaction into a failure: maintenance, the after hook, the compaction count, and the post-compaction guard still run. Only the retry and the tool-result truncation retry are skipped before surfacing the overflow guidance. * fix(agents): admit active-item continuation only for Code Mode runs Generic tools keep the fully-settled predicate; only a run with Code Mode engaged may continue while lifecycle items are active, since that is the one case where the outer exec result is persisted while the parked nested call stays owned by the code-mode run registry. A generic tool with an active item stays fail-closed (new regression). * fix(agents): gate active-item continuation on a recorded Code Mode suspension codeModeEngaged only says Code Mode controls were enabled for the attempt; Code Mode can still run direct tools, so a recorded direct-tool result plus unrelated active lifecycle work could take the weaker branch with no parked exec to resume. Record the fact where it happens instead: the tool completion handler marks an exec result that came back "waiting" as codeModeSuspended, and recovery continues past active items only when the recorded batch carries that fact. Code Mode enabled with a direct tool active stays fail-closed. * fix(agents): mark a parked run only for the marked Code Mode exec tool isExecToolName matches any tool named exec or bash, but only the marked Code Mode exec owns a resumable run. Carry the marked control-tool identity from the run's tool list (where the tool objects are known) to the subscription as codeModeExecToolNames, and record codeModeSuspended only for those tools. A plain exec returning a waiting-shaped result is no longer marked. * fix(agents): collect the Code Mode exec identity from the registered tool surface uncompactedEffectiveTools is the bundle list before the tool catalog creates the marked Code Mode controls, so the identity set was empty in real Code Mode runs and the parked-run fact was never recorded. Derive it from the post-catalog effectiveTools, where the activity wrapper preserves the marker through copyAgentToolMetadata. * fix(agents): block rotated retries for every recorded parked Code Mode run A local yield_control parks the marked exec without creating a nested lifecycle item, so gating the rotation block on activeCount let that case retry in the successor session where wait rejects the original binding. Key the block off the recorded codeModeSuspended fact instead, with a zero-active-item rotation regression. --------- Co-authored-by: VACInc <[email protected]>
Related: #128963, #128970, #129423
What Problem This Solves
A mid-turn context overflow that lands while a code-mode⚠️ Agent couldn't generate a response. Note: some tool actions may have already been executed — please verify before retrying." The waiting code-mode run is left unresumed; on the reporting session the operator re-prompted 30 minutes later, the model called
execis still waiting on nested tool work never compacts. The run ends in seconds withincomplete turn detected … compactions=0and the user sees "wait(runId), and gotcode mode run is unavailable or expired(defaultsnapshotTtlSecondsis 900). The in-flight work was lost.Observed 2026-08-26 02:01 UTC on a Telegram session (
openai/gpt-5.6-sol):[context-overflow-midturn-precheck] route=compact_only estimatedPromptTokens=297335, the persistedexecresult was{"status":"waiting","reason":"pending_tools","runId":"cm_…"}, thenincomplete turn detected … stopReason=toolUse tools=1 replaySafe=no compactions=0. Two other compactions in the same session minutes earlier succeeded, so this is not the compaction path itself.Why This Change Was Made
#128970 (fixing #128963) separated "may replay the original attempt" from "may compact and continue from the current transcript", but gated the latter on
resolveSettledToolBatchEvidence(attempt).allToolsProvenSettled, which requires the lifecycle counters to be balanced (completedCount === startedCount && activeCount === 0). A code-modeexecsuspended withpending_toolshas its outer result persisted, yet its nested call keeps a lifecycle item active — verified against the real QuickJS bridge harness:started 1 / completed 0 / active 1while waiting. So the gate fails closed andattempt-recovery.tsreturns the generic replay-unsafe outcome.That gate protects the wrong thing. Mid-turn continuation activates
MID_TURN_PRECHECK_CONTINUATION_PROMPT("Continue from the current transcript after the latest tool result… do not rerun completed tools") — it never replays the assistant call. What must hold is that the transcript is complete: every tool call in the batch has a recorded result. Nested code-mode work belongs to the code-mode run registry and resumes throughwait, which is exactly how it works across ordinary turns.Change:
resolveSettledToolBatchEvidencenow also returnsallToolCallsRecorded(transcript-only proof: every requested call has a matching persisted result);allToolsProvenSettledis unchanged (= recorded + balanced lifecycle) for its other consumers (intentionalTermination, terminal continuation).embedded-agent-subscribe.handlers.tools.completion.ts) marks a result that came backstatus: "waiting"ascodeModeSuspendedon its tool meta — but only when the tool is the marked Code Modeexeccontrol tool. That identity comes from the run's post-catalog tool surface (attempt-client-tools.tscollectscodeModeExecToolNamesfromeffectiveToolsviaisCodeModeExecTool, the same WeakSet marker Code Mode uses; the activity wrapper preserves it throughcopyAgentToolMetadata) and travels to the subscription likereplaySafeToolNames;uncompactedEffectiveToolsis the pre-catalog bundle and never contains the controls, so it cannot be the source (catalog-level test); a plainexec/bashreturning a waiting-shaped result is never marked (producer test).attempt-result.tscarries the fact into the attempt.resolveSettledToolBatchEvidenceexposesparkedCodeModeRun(every call recorded and one of this batch's calls carries that fact).attempt-recovery.tsgatescanContinueSettledMidTurnOverflowonallToolsProvenSettledorparkedCodeModeRun. Generic tools keep the fully-settled predicate; a generic tool with an active lifecycle item stays fail-closed, and so does "Code Mode enabled but a direct tool is the active one" (codeModeEngagedalone is not evidence — Code Mode can run direct tools). The!hasAsyncActivitycondition and the ownership/session checks from fix: resume after settled-tool context overflow #128970 are unchanged.waitrejects any other session (code-mode-execution.tsrunWait). If the overflow compaction adopts a successor session while a Code Mode run is parked — keyed off the recordedcodeModeSuspendedfact, not lifecycle counters, since a localyield_controlparks the exec with no nested item —overflow-context-recovery.tswithholds the mid-turn continuation and surfaces the overflow guidance instead of a retry that would fail on that binding. The compaction itself stays committed: context-engine maintenance, theafter_compactionhook, the compaction count, and the post-compaction guard all still run; only the retry (and the tool-result-truncation retry) are skipped. The default safeguard compaction never rotates the session (all observed compactions on the reporting session kept821434f3…), so the reported case still continues; only rotating engines fail closed there.Not changed: async-started tools (
details.async: true, status: "started") still fail closed as #128970 decided; that case was not observed and is a separate product decision.User Impact
Long tool-heavy turns that use code-mode no longer die at the context boundary while a nested call is in flight; compaction runs and the agent continues (typically calling
wait) within the run's TTL instead of stranding the work and showing the generic side-effect warning.Evidence
code-mode.bridge.lifecycleharness confirming{startedCount:1, completedCount:0, activeCount:1}for a waitingexecwithreason: "pending_tools".compacts while a code-mode exec still waits on nested tool work(run.midturn-precheck-retry.test-support.ts): recordedexecresult +activeCount: 1→ compaction runs once and the retry continues from the transcript. Fails on pre-fix code (verified by stashing the two production files), passes after.a tool call without a recorded result,a generic tool with an active lifecycle item, anda direct tool active while Code Mode is merely enabledkeep the generic side-effect warning; each fails without its guard.keeps a parked Code Mode run fail-closed when compaction rotates the session(activeCount: 1andactiveCount: 0/yield_control): recorded parkedexec+ compaction success carryingsessionId: "rotated-session"→ one attempt, "Try /reset (or /new)" guidance. Each fails without its guard (continues into the successor), passes with it.node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run.shared-integration.test.ts— 73 passed; sibling suites (attempt-recovery,incomplete-turn-*,overflow-*,terminal-resolution) — 131 passed.node scripts/check-changed.mjs: all lanes ok excepttypecheck core tests, which fails only onui/vite.config.ts(pakodeclaration missing in this worktree's sharednode_modulesafter chore(deps): refresh dependencies after seven-day cooldown #129187) — unrelated to this change; zero TS errors in touched files.