Repository navigation
Description
Problem
When a sequant subagent hits its maxTurns cap, the ClaudeCodeDriver receives error_max_turns and currently treats it as a hard failure — discarding whatever partial work the agent produced and failing the entire phase. With turn caps now live on every agent (shipped in #484), this is a real, reachable failure mode that wastes the work already done.
This is the only live, unblocked slice carved out of #483 (closed). The rest of #483's scope is either done (P0/AC-1–9 shipped in #484) or blocked on upstream model-routing bug anthropics/claude-code#43869 (settings/CLI overrides, tracked via #632).
Acceptance Criteria
- AC-1 (was Add user-configurable agent overrides and graceful maxTurns handling #483 AC-14): When
ClaudeCodeDriverreceiveserror_max_turns, it logs a warning (not error) and returns partial output, e.g.{ status: 'partial', output, capped: true }. - AC-2 (was Add user-configurable agent overrides and graceful maxTurns handling #483 AC-15):
/qatreats a turn-capped check as inconclusive — flags it in the QA summary rather than failing the entire QA phase. - AC-3 (was Add user-configurable agent overrides and graceful maxTurns handling #483 AC-16):
/exectreats a turn-capped implementation as incomplete — reports which tasks finished vs. which were capped.
Design Notes
if (result.subtype === 'error_max_turns') {
logger.warn(`Agent hit turn cap (${maxTurns}). Returning partial results.`);
return { status: 'partial', output: result.output, capped: true };
}Skills check result.capped and adjust their summary accordingly. Defensive code — useful regardless of what maxTurns values are set, and independent of the upstream model-routing bug.
Files Affected
src/lib/workflow/drivers/claude-code.ts— gracefulerror_max_turnshandling.claude/skills/qa/SKILL.md(+templates/skills/,skills/mirrors) — inconclusive handling.claude/skills/exec/SKILL.md(+ mirrors) — incomplete/capped reporting
References
- Supersedes the live slice of Add user-configurable agent overrides and graceful maxTurns handling #483 (closed)
- P0 already shipped: Migrate subagent patterns to declarative .claude/agents/ definitions #484
- Blocked sibling scope (settings/CLI overrides): fix(agents): realign declared model tiers; document upstream routing bug #632 /
anthropics/claude-code#43869
Activity
admarble commentedon Jun 20, 2026
📋 Plan Review — Graceful
error_max_turnshandlingComplexity: Standard (3 ACs, 2 logical targets) · Verdict: ✅ SCOPE_OK
Acceptance Criteria + Verification
error_max_turns, log a warning (not error) and return partial output +capped: true.claude-code.test.ts). Given SDK stream yieldssubtype: 'error_max_turns'with prior assistant text →executePhase()returns partialoutput+capped: true, no harderrorstring./qa: a turn-capped spawned check is flagged inconclusive, not a phase failure.qa/SKILL.mdmirrors./exec: a turn-capped implementation is reported incomplete (finished vs. capped tasks).exec/SKILL.mdmirrors.Key design decision (needs input)
The design-note shape
{ status: 'partial', output, capped: true }does not fit the existingAgentPhaseResultinterface (booleansuccess, nostatus/capped). Recommended adaptation:capped?: booleantoAgentPhaseResult(mirrors the refactor: normalize agent-driver resume semantics (origin-cwd-bound ResumeHandle, driver-owned validation) #674 field-addition pattern).error_max_turnscase out of the error-stringswitch(claude-code.ts:174); warn via the existingconfig.onStderr?.()channel (drivers/ has no logger today); return partialoutput+capped: true.statusenum — collides with the boolean-successcontract used by ~20 consumers.Open question — phase-executor scope:
phase-executor.tsis not in Files Affected. If the driver returnssuccess: false(even withcapped: true),phase-executor.ts:745still hard-fails and discards partial work — so AC-1's "not failing the phase" is only fully achieved for sub-agent caps (AC-2/3, handled in skills), not an orchestrator-level cap. Recommend confining this issue to the driver + skills as scoped, and filing a follow-up if orchestrator-level partial-preservation is wanted. Confirm?Layering note: AC-1 = top-level orchestrator query capping (driver sees
error_max_turns); AC-2/AC-3 = spawned subagents (maxTurns:15) capping, observed by the orchestrating skill via Task results. The SKILL.md edits target the latter.Implementation Plan
agent-driver.ts— addcapped?: booleantoAgentPhaseResult.claude-code.ts:174— warn + return partialoutput+capped: trueforerror_max_turns.claude-code.test.ts— assert capped result shape (no existingerror_max_turnstest).qa/SKILL.md(×3 mirrors) — capped spawned check → inconclusive in summary, don't fail verdict on it alone.exec/SKILL.md(×3 mirrors) — capped implementer → report finished-vs-capped tasks, treat as incomplete..claude/skills/,templates/skills/,skills/(read each before editing; grep-verify after).Scope notes
anthropics/claude-code#43869) andmaxTurnsvalue tuning.feature/733-...) with no commits ahead — no in-flight conflict.Recommended workflow
exec → testgen → qa · Quality loop: disabled (SCOPE_OK) · No browser
test(no UI) · Not security-sensitive.testgenrecommended because AC-1 has a Unit Test verification method.admarble commentedon Jun 21, 2026
✅ Exec Progress Update — Graceful
error_max_turnshandlingPR: #737
AC Coverage
capped: trueclaude-code.ts(error_max_turns branched out of the error switch),agent-driver.ts(additivecapped?: boolean), unit test inclaude-code.test.ts/qacapped check → inconclusive, not phase failureqa/SKILL.mdnew "Turn-Capped Checks → Inconclusive" section (×3 mirrors)/execcapped implementer → incomplete (finished-vs-capped)exec/SKILL.md§4b2 "Detecting Turn-Capped Implementers" (×3 mirrors)Key files changed
src/lib/workflow/drivers/agent-driver.ts— additivecapped?: booleanonAgentPhaseResult(rejected astatusenum to preserve the boolean-successcontract used by ~20 consumers, per spec).src/lib/workflow/drivers/claude-code.ts—error_max_turnsnow warns viaonStderrand returns partial output +capped: true, no harderrorstring.src/lib/workflow/drivers/claude-code.test.ts— mocked-SDK unit test for the capped path..claude/skills/{qa,exec}/SKILL.md(+templates/skills/,skills/mirrors) — inconclusive/incomplete handling.CHANGELOG.md—[Unreleased]entry.Checks
npm run build: ✅ pass ·npm run lint: ✅ 0 warnings · tests (drivers + phase-executor): ✅ 179 passed, 2 skippedcheck-skill-sync.ts: qa/exec mirrors in sync ·lint:skill-calls: no violationsKnown gaps / scope notes
phase-executor.tsstill discards onsuccess: false) is intentionally out of scope per the spec's open-question resolution — confined to driver + skills (sub-agent caps). A follow-up can address orchestrator-level cap recovery if wanted.anthropics/claude-code#43869.package-lock.jsonmodification (present at session start, unrelated to Graceful error_max_turns handling for subagents #733) was deliberately excluded from the commit.test(#733): add failure-path regression for narrow error_max_turns br…
admarble commentedon Jun 21, 2026
Test Stubs Generated (
/testgen)Counts explained — Happy Path = positive/success coverage; Failure Paths = error/edge/negative coverage.
AC-1 — Unit Test (
src/lib/workflow/drivers/claude-code.test.ts)Only AC-1 carries a Unit Test verification method. The happy-path test was already implemented and passing during
/exec, mapping exactly to the spec's Given/When/Then:subtype: 'error_max_turns'after prior assistant text → WhenexecutePhase()runs → Then it returns partialoutput("partial work done") +capped: true, no hard error string. (2 cases: result shape +onStderrwarning.)Rather than overwrite that file or inject red
throw new Error('stub')placeholders into a green suite,/testgenadded the failure path the spec implies but didn't yet cover — a real, passing regression guard:does not flag non-capped error subtypes as capped— proves the newerror_max_turnsbranch is narrow:error_during_executionstill fails hard (success: false, real error string, nocappedflag), so soft-cap handling can't mask a genuine failure. The mocked SDK result is now configurable viavi.hoisted, reset inbeforeEach.Result:
claude-code.test.ts→ 6 passed. Full drivers dir → 62 passed / 2 skipped.AC-2 — Manual Checklist (
/qacapped check → inconclusive)No file generated (doc-content / LLM-interpreted prompt change, 3
qa/SKILL.mdmirrors).error_max_turns/ "Returning partial results".NEEDS_VERIFICATION(negative check: neverAC_NOT_METjustified solely by the cap).qa/SKILL.mdmirrors carry the identical "Turn-Capped Checks → Inconclusive" section.AC-3 — Manual Checklist (
/execcapped implementer → incomplete)No file generated (doc-content, 3
exec/SKILL.mdmirrors).error_max_turns/ "turn cap" / output ends mid-task)./exectreats it as incomplete, distinct from §4b hook-block failures.exec/SKILL.mdmirrors carry the identical §4b2 "Detecting Turn-Capped Implementers" section.Next steps
/qaand/exec; the checklists above are the manual verification script./qa 733.Generated with Claude Code
admarble commentedon Jun 21, 2026
QA Review for Issue #733
AC Coverage
error_max_turns, warn (not error) + return partial output +capped: trueclaude-code.ts:171-191brancheserror_max_turnsout of the error switch, warns viaonStderr, returns{ success:false, capped:true, output }with noerrorstring.capped?: booleanadded additively toAgentPhaseResult. Verified literally against AC text./qa: turn-capped check flagged inconclusive, not a phase failureqa/SKILL.md"Turn-Capped Checks → Inconclusive" section: marks single checkNEEDS_VERIFICATION. Synced 3/3 mirrors./exec: turn-capped implementation reported incomplete (finished vs. capped)exec/SKILL.md§4b2 "Detecting Turn-Capped Implementers": incomplete (≠ §4b failure), keeps partial work, per-task finished-vs-capped report, resume next iteration. Synced 3/3 mirrors.Coverage: 3/3 AC items fully met.
Quality Plan Verification
N/A — spec was tier "standard" with no Feature Quality Planning section / Derived ACs.
CI Status
mergeable: CONFLICTING/mergeStateStatus: DIRTY, so GitHub never queued the checks (0 reported). Diff is not markdown-only (contains.tschanges), so no markdown-only relaxation applies. CI cannot be green until the conflict (below) is resolved.Stale Branch Check
⛔ Merge Blocker: cross-PR conflict with #735
Sibling PR #735 ("surface structured rate-limit/credits errors", commit
27f8106) landed on main and edits the same three files as this PR. The branch isCONFLICTING:agent-driver.tsstructuredError?, this PR addedcapped?; both additive aftererror?:. Keep both.claude-code.tserror_max_turns. Different subtypes; my early-return precedes #735's switch. AC-1 still holds post-merge; #735's path untouched.claude-code.test.tsquerymock configurable. This is the real reconciliation point — the two mocks must be unified into one (cross-PR mock merge, the #547-class trap).CHANGELOG.md### Changed.No AC regression: the implementation satisfies all 3 ACs at HEAD
47a262e87c071f9dba59217693dd0dd6db3ea797. The conflict is mechanical, not a design clash — but it must be resolved (viagit merge origin/main, not rebase — force-push is hook-blocked) and CI must go green before merge.Quality Metrics
any)Test Coverage Analysis
claude-code.tsclaude-code.test.ts(capped shape, onStderr warning, narrow-branch regression)agent-driver.ts*/SKILL.md(×6)Coverage: 1/1 testable source file covered. Regression test (
does not flag non-capped error subtypes as capped) is non-tautological — proves the branch is narrow.Code Review
Strengths:
capped?(nostatusenum), preserving the boolean-successcontract for ~20 consumers."Max turns reached"literal cleanly; no stale consumer references it.error_max_turns, "Returning partial results") that match the driver's actual warning string — detection will work at runtime.Issues: None in the code itself. The only blocker is the external merge conflict.
Skill Command Verification
N/A — skill edits add prose/tables only; no new
gh/npm/gitcommands introduced.Detection Pattern Verification
N/A — §6c precondition false (no
grep/awk/jq/sed/regex literals added to skill markdown).Behavior-Rule Survival Check
N/A — no AC trips the behavior-rule heuristic (≥2 of default/always/never/rule/behavior/skip).
Skill sync (three-directory)
✅
qa/SKILL.md3/3 match ·exec/SKILL.md3/3 match.CHANGELOG Verification
[Unreleased]entry for #733### Changed)Note: the
[Unreleased]block is part of theCHANGELOG.mdconflict — ensure the #733 bullet survives the merge.Risk Assessment
claude-code.test.ts— both PRs restructured the SDK mock. A careless resolve could drop one PR's cases or leave a mock that no longer driveserror_max_turns, silently weakening AC-1's coverage./qaand/execat runtime, not by unit tests (inherent to doc-content ACs).error_max_turnshandling is a single site inclaude-code.ts. (feat(driver): surface structured rate-limit/credits errors from SDK message stream (#732) #735 touches the same file but is a separate concern, not a sibling of the same root cause.)error_during_execution,error_max_budget_usd) are intentionally left on the hard-error path, which the new regression test asserts.Adversarial Re-Read
Findings: Walked the diff against the five checks. (1) No motivating-example fixtures in the issue body to run. (2) The
/execevidence claims are post-fix passing tests, not pre-fix repros. (3) Process-state inspection surfaced the blocker:gh pr viewshowsCONFLICTING/DIRTYwith 0 CI checks — the pipeline would otherwise have normalized this away. Traced the conflict to sibling PR #735 and confirmed it is textual/orthogonal in the two source files (post-merge AC-1 holds; #735's rate-limit path untouched) with the test-mock as the one semantic reconciliation point. (4) Sibling sites cited above. (5) The issue's implicit Non-Goal (orchestrator-level partial preservation inphase-executor.ts) was correctly not expanded into scope.Status: Gaps Found (external merge-conflict blocker — not an AC gap)
Verdict: NEEDS_VERIFICATION
All 3 ACs are MET with clean build/lint/tests and full unit coverage of AC-1 (happy + narrow-branch regression). However, the PR cannot merge: it is
CONFLICTINGagainst main (sibling PR #735 edited the same files) and CI has not dispatched. This is an external gate that code review alone cannot clear, so the verdict isNEEDS_VERIFICATIONrather thanREADY_FOR_MERGE.Documentation
Next Steps
git merge origin/main # NOT rebase — force-push is hook-blockedagent-driver.ts: keep bothcapped?andstructuredError?.claude-code.ts: keep theerror_max_turnsearly-return and feat(driver): surface structured rate-limit/credits errors from SDK message stream (#732) #735's structured-error capture + failure return.claude-code.test.ts: carefully unify the two configurable SDK mocks into one; re-runnpx vitest run src/lib/workflow/drivers/and confirm both feat(driver): surface structured rate-limit/credits errors from SDK message stream (#732) #735's and Graceful error_max_turns handling for subagents #733's cases pass.CHANGELOG.md: keep both### Changedbullets.npm run build && npm run lint && npx vitest run src/lib/workflow/drivers/after resolving.gh pr checks 737)./qa 733(or/qa 733 --force) — with a clean merge + green CI this should reachREADY_FOR_MERGE.admarble commentedon Jun 22, 2026
✅ Verification Complete — Merge Conflict Resolved (
NEEDS_VERIFICATION→READY_FOR_MERGE)The prior QA verdict was
NEEDS_VERIFICATIONsolely due to an external gate: PR #737 wasCONFLICTING/DIRTYagainst main (sibling PR #735 edited the same files) and CI had not dispatched. Both are now resolved.Conflict Resolution (
git merge origin/main, not rebase)agent-driver.tscapped?(#733) andstructuredError?(#732)claude-code.tserror_max_turnsearly-return (capped, no hard error) precedes #732's structured-error switch — both paths intactclaude-code.test.tsvi.mockstrategies into one. Removed #733's hoistedmockResultfactory + redundant secondvi.mock(would have been wiped byqueryMock.mockReset()); rewrote the 3 #733 tests to drive their own stream via the sharedmockStream([...])helper.CHANGELOG.md[Unreleased]### Added, #733 bullet preserved under### ChangedPost-Merge Checks (HEAD
f3c1901)npm run build: ✅ tsc cleannpm run lint: ✅ eslint 0 warningsnpx vitest run src/lib/workflow/drivers/: ✅ 71 passed / 2 skipped (both Graceful error_max_turns handling for subagents #733 capped-path cases and feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732 rate-limit/billing cases pass under the unified mock)lint:skill-calls: ✅ no violations ·qa/execSKILL.md mirrors in syncmergeable: MERGEABLE·mergeStateStatus: CLEANAC Coverage (unchanged — all MET, re-verified at merged HEAD)
capped: trueonerror_max_turnsclaude-code.ts:233)/qacapped check → inconclusive, not phase failure/execcapped implementer → incomplete (finished-vs-capped)Verdict: READY_FOR_MERGE
The semantic test-mock reconciliation (the #547-class trap flagged in QA) was handled deliberately — one mock strategy, both PRs' cases proven green. Left for human merge gate.
admarble commentedon Jun 22, 2026
Follow-ups filed (gaps confirmed out of scope for this PR)
feat(orchestrator): preserve partial output for turn-capped phases inphase-executor(the spec's explicitly-deferred open question — AC-1 holds for sub-agent caps via feat(#733): graceful error_max_turns handling for subagents #737, but orchestrator-level query caps still discard partial work atphase-executor.ts:754).chore: reconcile skill-mirror divergences (8 diverged, 10 missing across the 3 roots) — pre-existing debt unrelated to Graceful error_max_turns handling for subagents #733, surfaced during QA.PR #737 stays focused and
READY_FOR_MERGE.feat(#733): graceful error_max_turns handling for subagents (#737)
feat(#739): preserve partial output for turn-capped phases in phase-e…