Skip to content

Graceful error_max_turns handling for subagents #733

Closed

Description

@admarble

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

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 — graceful error_max_turns handling
  • .claude/skills/qa/SKILL.md (+ templates/skills/, skills/ mirrors) — inconclusive handling
  • .claude/skills/exec/SKILL.md (+ mirrors) — incomplete/capped reporting

References

Activity

  1. added
    enhancement
    multi-agent
    on Jun 20, 2026
  2. admarble commented on Jun 20, 2026

    @admarble
    ContributorAuthor

    📋 Plan Review — Graceful error_max_turns handling

    Complexity: Standard (3 ACs, 2 logical targets) · Verdict: ✅ SCOPE_OK

    Acceptance Criteria + Verification

    • AC-1 — Driver: on error_max_turns, log a warning (not error) and return partial output + capped: true.
      • Verification: Unit Test (claude-code.test.ts). Given SDK stream yields subtype: 'error_max_turns' with prior assistant text → executePhase() returns partial output + capped: true, no hard error string.
    • AC-2 — /qa: a turn-capped spawned check is flagged inconclusive, not a phase failure.
      • Verification: Manual/Doc-content (prompt change, LLM-interpreted) across all 3 qa/SKILL.md mirrors.
    • AC-3 — /exec: a turn-capped implementation is reported incomplete (finished vs. capped tasks).
      • Verification: Manual/Doc-content across all 3 exec/SKILL.md mirrors.

    Key design decision (needs input)

    The design-note shape { status: 'partial', output, capped: true } does not fit the existing AgentPhaseResult interface (boolean success, no status/capped). Recommended adaptation:

    Open question — phase-executor scope: phase-executor.ts is not in Files Affected. If the driver returns success: false (even with capped: true), phase-executor.ts:745 still 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

    1. agent-driver.ts — add capped?: boolean to AgentPhaseResult.
    2. claude-code.ts:174 — warn + return partial output + capped: true for error_max_turns.
    3. claude-code.test.ts — assert capped result shape (no existing error_max_turns test).
    4. qa/SKILL.md (×3 mirrors) — capped spawned check → inconclusive in summary, don't fail verdict on it alone.
    5. exec/SKILL.md (×3 mirrors) — capped implementer → report finished-vs-capped tasks, treat as incomplete.
    6. Sync all three roots: .claude/skills/, templates/skills/, skills/ (read each before editing; grep-verify after).

    Scope notes

    Recommended workflow

    exec → testgen → qa · Quality loop: disabled (SCOPE_OK) · No browser test (no UI) · Not security-sensitive.
    testgen recommended because AC-1 has a Unit Test verification method.

  3. added
    planned
    on Jun 20, 2026
  4. admarble commented on Jun 21, 2026

    @admarble
    ContributorAuthor

    ✅ Exec Progress Update — Graceful error_max_turns handling

    PR: #737

    AC Coverage

    AC Description Status Evidence
    AC-1 Driver warns + returns partial output + capped: true ✅ Implemented claude-code.ts (error_max_turns branched out of the error switch), agent-driver.ts (additive capped?: boolean), unit test in claude-code.test.ts
    AC-2 /qa capped check → inconclusive, not phase failure ✅ Implemented qa/SKILL.md new "Turn-Capped Checks → Inconclusive" section (×3 mirrors)
    AC-3 /exec capped implementer → incomplete (finished-vs-capped) ✅ Implemented exec/SKILL.md §4b2 "Detecting Turn-Capped Implementers" (×3 mirrors)

    Key files changed

    • src/lib/workflow/drivers/agent-driver.ts — additive capped?: boolean on AgentPhaseResult (rejected a status enum to preserve the boolean-success contract used by ~20 consumers, per spec).
    • src/lib/workflow/drivers/claude-code.ts — error_max_turns now warns via onStderr and returns partial output + capped: true, no hard error string.
    • 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 skipped
    • check-skill-sync.ts: qa/exec mirrors in sync · lint:skill-calls: no violations

    Known gaps / scope notes

  5. added a commit that references this issue on Jun 21, 2026
  6. admarble commented on Jun 21, 2026

    @admarble
    ContributorAuthor

    Test Stubs Generated (/testgen)

    AC Verification Happy Path Failure Paths
    AC-1 Unit Test 1 (pre-existing, passing) 1 added (narrow-branch regression)
    AC-2 Manual / Doc-content Checklist below 1 negative check
    AC-3 Manual / Doc-content Checklist below 1 negative check

    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:

    • Given the SDK stream yields subtype: 'error_max_turns' after prior assistant text → When executePhase() runs → Then it returns partial output ("partial work done") + capped: true, no hard error string. (2 cases: result shape + onStderr warning.)

    Rather than overwrite that file or inject red throw new Error('stub') placeholders into a green suite, /testgen added 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 new error_max_turns branch is narrow: error_during_execution still fails hard (success: false, real error string, no capped flag), so soft-cap handling can't mask a genuine failure. The mocked SDK result is now configurable via vi.hoisted, reset in beforeEach.

    Result: claude-code.test.ts → 6 passed. Full drivers dir → 62 passed / 2 skipped.

    AC-2 — Manual Checklist (/qa capped check → inconclusive)

    No file generated (doc-content / LLM-interpreted prompt change, 3 qa/SKILL.md mirrors).

    • Simulate a spawned QA sub-agent whose output is truncated / contains error_max_turns / "Returning partial results".
    • QA marks that check ⚠️ Inconclusive in the summary with a one-line reason — does not fail the whole QA phase on the cap alone.
    • Partial findings from the capped agent are retained, not discarded.
    • Other checks proceed and contribute to the verdict normally.
    • An AC left unverified by a cap → NEEDS_VERIFICATION (negative check: never AC_NOT_MET justified solely by the cap).
    • All three qa/SKILL.md mirrors carry the identical "Turn-Capped Checks → Inconclusive" section.

    AC-3 — Manual Checklist (/exec capped implementer → incomplete)

    No file generated (doc-content, 3 exec/SKILL.md mirrors).

    • Simulate a spawned implementer that hits its turn cap (error_max_turns / "turn cap" / output ends mid-task).
    • /exec treats it as incomplete, distinct from §4b hook-block failures.
    • Partial committed work is kept (group not rolled back).
    • Per-task report shows finished vs. capped tasks; capped task flagged for the next iteration to resume.
    • Negative check: a capped task is not reported as ✅ done / AC fully satisfied (AC table shows ⚠️ Partial).
    • All three exec/SKILL.md mirrors carry the identical §4b2 "Detecting Turn-Capped Implementers" section.

    Next steps

    1. AC-1 unit coverage is complete and green (happy + failure path) — no stubs to fill.
    2. AC-2 / AC-3 are exercised at runtime by /qa and /exec; the checklists above are the manual verification script.
    3. Proceed to /qa 733.

    Generated with Claude Code

  7. admarble commented on Jun 21, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #733

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Driver: on error_max_turns, warn (not error) + return partial output + capped: true ✅ MET claude-code.ts:171-191 branches error_max_turns out of the error switch, warns via onStderr, returns { success:false, capped:true, output } with no error string. capped?: boolean added additively to AgentPhaseResult. Verified literally against AC text.
    AC-2 Original /qa: turn-capped check flagged inconclusive, not a phase failure ✅ MET qa/SKILL.md "Turn-Capped Checks → Inconclusive" section: marks single check ⚠️ Inconclusive, keeps partial findings, never fails phase on cap alone, unverified AC → NEEDS_VERIFICATION. Synced 3/3 mirrors.
    AC-3 Original /exec: turn-capped implementation reported incomplete (finished vs. capped) ✅ MET 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

    ⚠️ CI has not dispatched — PR #737 is mergeable: CONFLICTING / mergeStateStatus: DIRTY, so GitHub never queued the checks (0 reported). Diff is not markdown-only (contains .ts changes), so no markdown-only relaxation applies. CI cannot be green until the conflict (below) is resolved.


    Stale Branch Check

    Check Value
    Commits behind origin/main 2
    Threshold 5
    Status ⚠️ Warning (below block threshold, but see conflict)

    ⛔ 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 is CONFLICTING:

    File Conflict type Assessment
    agent-driver.ts Textual (adjacent) Orthogonal — #735 added structuredError?, this PR added capped?; both additive after error?:. Keep both.
    claude-code.ts Textual (adjacent) Orthogonal — #735 captures structured rate-limit/billing errors; this PR early-returns error_max_turns. Different subtypes; my early-return precedes #735's switch. AC-1 still holds post-merge; #735's path untouched.
    claude-code.test.ts Semantic ⚠️ Both PRs made the SDK query mock 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 Textual Trivial — both add bullets under ### 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 (via git merge origin/main, not rebase — force-push is hook-blocked) and CI must go green before merge.


    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 10 OK
    Lines added / deleted +286 / -4 OK
    Build / Lint / Tests tsc clean · eslint 0 warnings · drivers 62 passed/2 skipped OK

    Test Coverage Analysis

    Changed File Tier Has Tests?
    claude-code.ts Standard ✅ Yes — claude-code.test.ts (capped shape, onStderr warning, narrow-branch regression)
    agent-driver.ts Optional (type-only interface field) N/A
    */SKILL.md (×6) Optional (doc-content) N/A — LLM-interpreted prose

    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:

    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/git commands 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.md 3/3 match · exec/SKILL.md 3/3 match.


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅
    User-facing change (feat commit) ✅
    [Unreleased] entry for #733 ✅ Present (under ### Changed)

    Note: the [Unreleased] block is part of the CHANGELOG.md conflict — ensure the #733 bullet survives the merge.


    Risk Assessment

    • Likely failure mode: A botched test-mock merge in 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 drives error_max_turns, silently weakening AC-1's coverage.
    • Not tested: AC-2/AC-3 are runtime LLM-interpreted skill prose — exercised by /qa and /exec at runtime, not by unit tests (inherent to doc-content ACs).
    • Sibling sites considered: none — no cross-file siblings; the error_max_turns handling is a single site in claude-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.)
    • Sibling-line audit: none — single-call-site change; the adjacent error subtypes (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 /exec evidence claims are post-fix passing tests, not pre-fix repros. (3) Process-state inspection surfaced the blocker: gh pr view shows CONFLICTING/DIRTY with 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 in phase-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 CONFLICTING against 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 is NEEDS_VERIFICATION rather than READY_FOR_MERGE.

    Documentation

    • CHANGELOG entry added (verify it survives the merge)
    • N/A — internal driver + skill-prose change; no README/user-docs surface

    Next Steps

    1. Resolve the conflict (the actual blocker):
      git merge origin/main   # NOT rebase — force-push is hook-blocked
    2. npm run build && npm run lint && npx vitest run src/lib/workflow/drivers/ after resolving.
    3. Push; confirm CI dispatches and goes green (gh pr checks 737).
    4. Re-run /qa 733 (or /qa 733 --force) — with a clean merge + green CI this should reach READY_FOR_MERGE.
  8. added
    needs-verification
    on Jun 21, 2026
  9. admarble commented on Jun 22, 2026

    @admarble
    ContributorAuthor

    ✅ Verification Complete — Merge Conflict Resolved (NEEDS_VERIFICATION → READY_FOR_MERGE)

    The prior QA verdict was NEEDS_VERIFICATION solely due to an external gate: PR #737 was CONFLICTING/DIRTY against 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)

    File Conflict Resolution
    agent-driver.ts Adjacent additive fields Kept both capped? (#733) and structuredError? (#732)
    claude-code.ts Auto-merged error_max_turns early-return (capped, no hard error) precedes #732's structured-error switch — both paths intact
    claude-code.test.ts Semantic (the real reconciliation) Unified the two competing vi.mock strategies into one. Removed #733's hoisted mockResult factory + redundant second vi.mock (would have been wiped by queryMock.mockReset()); rewrote the 3 #733 tests to drive their own stream via the shared mockStream([...]) helper.
    CHANGELOG.md Both add to [Unreleased] #734/#732 under ### Added, #733 bullet preserved under ### Changed

    Post-Merge Checks (HEAD f3c1901)

    AC Coverage (unchanged — all MET, re-verified at merged HEAD)

    AC Status
    AC-1 — Driver warns + returns partial output + capped: true on error_max_turns ✅ MET (claude-code.ts:233)
    AC-2 — /qa capped check → inconclusive, not phase failure ✅ MET (qa/SKILL.md ×3)
    AC-3 — /exec capped implementer → incomplete (finished-vs-capped) ✅ MET (exec/SKILL.md ×3)

    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.

  10. admarble commented on Jun 22, 2026

    @admarble
    ContributorAuthor

    Follow-ups filed (gaps confirmed out of scope for this PR)

    PR #737 stays focused and READY_FOR_MERGE.

  11. added a commit that references this issue on Jun 22, 2026
  12. added a commit that references this issue on Jun 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementmulti-agentneeds-verificationplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions