Skip to content

feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732

Closed

Description

@admarble

Summary

Bumping @anthropic-ai/claude-agent-sdk to 0.3.181 (PR #731) prompted a fan-out review of how sequant consumes the SDK message stream. The review surfaced one high-value gap unrelated to the bump itself: sequant silently discards the structured rate-limit / billing signals the SDK already emits, and instead guesses rate limits via regex-on-stderr. This directly worsens the known #592 fallback-noise problem.

This issue scopes that fix (primary), records a deliberately-deferred UX idea (tool_use_meta), and captures a housekeeping flag (local SDK drift).


Part 1 — Structured rate-limit / credits error handling (PRIMARY)

Problem

Today sequant infers rate limits by regex-matching stderr text:

Meanwhile, the SDK message stream — consumed at a single clean chokepoint, src/lib/workflow/drivers/claude-code.ts:122 (for await (const message of queryInstance)) — already emits, and sequant drops on the floor:

  • rate_limit_event → SDKRateLimitInfo (status, resetsAt, overageDisabledReason: 'out_of_credits' | ...)
  • assistant.error: 'rate_limit' | 'billing_error' | ...
  • api_retry messages (error_status, error)

The assistant handler (claude-code.ts:127-144) filters content to type === "text" only; every other message type falls through silently.

Important: these three message types exist in the currently installed 0.3.158 — this fix is viable today and does not depend on the 0.3.181 bump. The 0.3.181 additions (errorCode, canUserPurchaseCredits, hasChargeableSavedPaymentMethod on SDKRateLimitInfo) are incremental polish layered on top once we're on 0.3.181.

Proposed approach

  1. In the claude-code.ts:122 stream loop, handle message.type === 'rate_limit_event' and the assistant.error field (and optionally api_retry), extracting the structured info.
  2. Add a RateLimitError (and/or BillingError) subclass in src/lib/errors.ts (alongside the existing ApiError) carrying resetsAt, overageDisabledReason, and — when on ≥0.3.181 — canUserPurchaseCredits / hasChargeableSavedPaymentMethod.
  3. Propagate it through AgentPhaseResult so phase-executor surfaces an accurate message ("Out of credits" / "Rate limited — resets at HH:MM") instead of the generic fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592 fallback noise, and skips the pointless MCP-disabled retry when the failure is billing/credits (a no-MCP retry won't fix being out of credits).
  4. Keep the existing stderr-regex classifier as a fallback for non-SDK error paths (subprocess runs via src/mcp/tools/run.ts).

Acceptance Criteria

  • The claude-code.ts stream loop reads rate_limit_event and assistant error fields rather than discarding them.
  • A dedicated error type (RateLimitError / BillingError) exists in src/lib/errors.ts and carries at minimum resetsAt and overageDisabledReason.
  • When a phase fails due to rate-limit/credits, the user-facing message names the real cause (e.g. "Out of credits" or "Rate limited, resets at ") — verified against a captured/mocked rate_limit_event.
  • A credits/billing failure does not trigger the misleading "retrying without MCP" fallback path (fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592).
  • Existing stderr-regex classification still works for the subprocess path (run.ts) — no regression in error-classifier tests.
  • Unit coverage in src/lib/workflow/drivers/claude-code.test.ts (or a sibling) drives the new message types through the loop.
  • When the codebase is on ≥0.3.181, the message is enriched with canUserPurchaseCredits / hasChargeableSavedPaymentMethod (e.g. "Out of credits — purchasable" vs "hard limit"). Gate gracefully if the field is absent.

Evidence / references

  • Chokepoint & dropped messages: claude-code.ts:122, :127-144
  • SDK types already present in 0.3.158: node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts — SDKRateLimitEvent/SDKRateLimitInfo (:3432-3455), SDKAssistantMessage.error (:2604), SDKAPIRetryMessage (~:2590)
  • Regex fallback: error-classifier.ts:84-99; consumer phase-executor.ts:863, fallback noise :912
  • Related: fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592 (fallback-noise / pre-flight miss)

Part 2 — tool_use_meta human-readable tool labels (DEFERRED — out of scope here)

The 0.3.181 bump also added a tool_use_meta sidecar (display-friendly tool names + icon_url). Investigated and deliberately deferred — recorded here so it isn't re-discovered cold:

  • Sequant never renders tool calls. The driver (claude-code.ts:132) filters assistant content to type:"text" and discards tool_use blocks; the renderer (src/lib/cli-ui/run-renderer.ts) shows phase status only; the TUI activity row (src/ui/tui/IssueBox.tsx) surfaces agent prose, not tool calls.
  • So there is no raw-wire-name UX problem to fix — this would be a new tool-activity rendering path, not a label swap. icon_url is unusable in a terminal TUI.
  • Benefit: LOW. Revisit only if a per-tool activity surface is independently wanted (cf. closed feat(tui): enrich nowLine with per-file / log-tail activity #543 "enrich nowLine"). Requires ≥0.3.181 first.

No ACs — tracked as a note, not a deliverable. Split into its own issue if/when prioritized.


Part 3 — Housekeeping flag: local SDK / lockfile drift

During the review, the local working tree was found 3 commits behind origin/main (the just-merged dependabot PRs #728/#730/#731). Consequently:

  • Local package-lock.json and node_modules/@anthropic-ai/claude-agent-sdk are both still 0.3.158, while origin/main pins 0.3.181.
  • This is not a code bug — just stale local state. Anyone picking up Part 1 (or testing the 0.3.181 fields) must first:
git pull origin main && npm ci
  • engines.node is >=22.12.0 on origin/main; all bumps were in-range patch/minor — no engine-floor conflict.

Acceptance Criteria

  • Working tree synced to origin/main and npm ci run so node_modules reflects 0.3.181 before validating the ≥0.3.181 enrichment AC in Part 1.

Scope note

The behavioral background/remote/-p fixes in the 0.3.158→0.3.181 range (print-mode background-notification timing, stream-json idle reporting, remote-control file_attachments) were checked and are behavior-neutral for sequant — it embeds the SDK in-process as a foreground query() with a string prompt, with no -p/headless CLI, stream-json, remote control, or file_attachments. No action needed; documented so it isn't re-investigated.

Activity

  1. added
    enhancement
    cli
    dependencies
    on Jun 20, 2026
  2. admarble commented on Jun 20, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (8 ACs, 2 directories)

    AC Quality Check

    All ACs are measurable with concrete verification targets. Notes:

    • Part 3 AC is already satisfied — the local tree is synced to origin/main and node_modules/@anthropic-ai/claude-agent-sdk is already 0.3.181. No work required; AC-8 should be checked as a precondition, not implemented.
    • AC-7 (≥0.3.181 enrichment) is testable now since 0.3.181 is installed — no longer "deferred polish."
    • No vague/unmeasurable/open-ended patterns found. No title/body verb tension.

    Scope Assessment

    Non-Goals: Present and explicit — Part 2 (tool_use_meta tool-label rendering) is deliberately deferred (no ACs); the 0.3.158→0.3.181 background/remote/-p behaviors are documented as behavior-neutral for sequant.

    Metric Value Status
    Feature count 1 ✅
    AC items 8 (7 active + 1 already-met) ⚠️
    Directory spread 2 (src/lib/workflow/*, src/lib) ✅

    Verdict: ⚠️ SCOPE_WARNING (AC count ≥6) → auto-enables quality loop. Cohesive single feature; no split recommended.


    Acceptance Criteria

    AC-1: Stream loop reads rate_limit_event + assistant error instead of discarding

    Verification: Unit Test — claude-code.test.ts
    Scenario: Given a mocked queryInstance async-iterable emitting a rate_limit_event and an assistant message with error: 'rate_limit' → When the driver consumes the stream → Then both are captured (not silently dropped at the type === "text" filter, claude-code.ts:127-144).
    Assumptions: rate_limit_info lives on message.rate_limit_info; assistant error on message.message.error.

    AC-2: RateLimitError / BillingError in src/lib/errors.ts

    Verification: Unit Test
    Scenario: Given the new subclasses → When constructed → Then they extend SequantError, carry resetsAt + overageDisabledReason in metadata, and set isRetryable correctly (rate-limit retryable; billing/credits NOT retryable).
    Assumptions: Follows the existing ApiError subclass pattern.

    AC-3: User-facing message names the real cause

    Verification: Integration Test (phase-executor) + Unit Test (formatter)
    Scenario: Given a captured/mocked rate_limit_event → When a phase fails → Then the message reads e.g. "Out of credits" or "Rate limited — resets at HH:MM", not the generic #592 fallback.

    AC-4: Credits/billing failure does NOT trigger "retrying without MCP" (#592)

    Verification: Integration Test — phase-executor.test.ts
    Scenario: Given a phase fails with a BillingError (out_of_credits) → When the executor reaches the MCP-fallback guard (phase-executor.ts:912) → Then the no-MCP retry is skipped (it cannot fix being out of credits).

    AC-5: stderr-regex classifier still works for subprocess path — no regression

    Verification: Unit Test — error-classifier.test.ts
    Scenario: Given run.ts subprocess stderr (no structured SDK data) → When classifyError runs → Then api_error/429/overloaded patterns classify as before. Existing tests unchanged + green.

    AC-6: Unit coverage drives the new message types through the loop

    Verification: Unit Test
    Scenario: Given mock messages for rate_limit_event, assistant.error, and (optionally) api_retry → When fed through the driver loop → Then each path is asserted.

    AC-7: ≥0.3.181 enrichment (canUserPurchaseCredits / hasChargeableSavedPaymentMethod)

    Verification: Unit Test
    Scenario: Given rate_limit_info with the 0.3.181 fields → Then message distinguishes "Out of credits — purchasable" vs "hard limit". Given the fields absent → Then gate gracefully (no crash, generic billing message).
    Assumptions: Fields are optional on SDKRateLimitInfo (confirmed present in installed 0.3.181 sdk.d.ts:3832-3834).

    AC-8: Working tree synced to origin/main, npm ci run (Part 3)

    Verification: Manual / precondition — ALREADY MET (tree at origin/main 0/0; SDK 0.3.181 installed).


    Implementation Plan

    Phase 1: Error types (src/lib/errors.ts)

    1. Add RateLimitError extends SequantError (isRetryable: true) and BillingError extends SequantError (isRetryable: false), each declaring a typed metadata (resetsAt?, overageDisabledReason?, rateLimitType?, canUserPurchaseCredits?, hasChargeableSavedPaymentMethod?).
    2. Add a small formatRateLimitMessage(info) helper that maps overageDisabledReason === 'out_of_credits' / errorCode === 'credits_required' → BillingError text, else rate-limit-with-reset text; enrich with purchasable flag when present.

    Phase 2: Capture in driver (drivers/claude-code.ts:122 loop)

    1. In the stream loop, capture message.type === 'rate_limit_event' → latest rate_limit_info; in the existing assistant branch, read message.message.error (and optionally handle api_retry). Keep these in loop-scoped vars.
    2. On non-success, construct the appropriate typed error from captured signals and attach it to the result (see Phase 3 field).

    Phase 3: Propagate via AgentPhaseResult (drivers/agent-driver.ts:58)

    1. Add optional structuredError?: SequantError to AgentPhaseResult. Driver populates it; other drivers (aider) leave it undefined.
    2. In phase-executor.ts: prefer lastResult.structuredError over re-classifyError(stderrTail) for the user-facing message; guard the MCP fallback (:912) so a BillingError (and non-retryable credits case) skips the no-MCP retry. Retain the stderr-regex classifier as the fallback when structuredError is absent (subprocess/run.ts path → AC-5).

    Phase 4: Tests

    1. claude-code.test.ts (AC-1/6/7), phase-executor.test.ts (AC-3/4), confirm error-classifier.test.ts unchanged + green (AC-5).

    Design Review

    1. Where does this logic belong? Capture in the driver (only it sees the raw SDK message stream); error types + formatting in errors.ts; the retry/message decision in phase-executor. Clean separation matching the existing "driver captures, executor decides" contract (agent-driver.ts:81-83).
    2. Simplest correct approach? Two loop-scoped vars + one new optional result field + a guard on the existing MCP-fallback if. Rejected: a new event-bus or refactoring the message loop into a typed dispatcher — overkill for 2-3 message types.
    3. Existing pattern? Mirrors ApiError subclassing of SequantError; reuses the classifyError → isRetryable decision flow already wired at phase-executor.ts:861-880.
    4. What would a senior reviewer challenge? "Why a new structuredError field instead of reusing error: string?" — because the executor needs the type (billing vs rate-limit) to gate the MCP retry, not just text. "Is billing non-retryable correct?" — yes; a no-MCP retry can't refill credits.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • No security-review needed — this reads billing/credit signals for display; it does not process payments or handle secrets.
    • Backward-compat: new AgentPhaseResult field is optional; aider driver and subprocess path unaffected.
    • Sibling check: error-classifier.ts:84-99 regex stays as the subprocess fallback by design (AC-5) — not a duplicate to consolidate.

    Open Questions

    1. Construct the typed error in the driver or executor? — Recommendation: driver (it owns the structured SDK data; executor only sees AgentPhaseResult). Impact if wrong: executor would have to re-parse text, defeating the purpose.
    2. Split RateLimitError vs BillingError? — Recommendation: yes, two types. out_of_credits/credits_required → BillingError (non-retryable, drives the fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592 skip); transient rate_limit/overloaded → RateLimitError (retryable). Impact if collapsed to one: harder to gate the MCP-fallback skip cleanly (AC-4).
    3. Handle api_retry now or defer? — Recommendation: capture it opportunistically for diagnostics but don't block AC on it (issue marks it "optionally"). Low impact.

    Recommended Workflow

    Phases: spec → testgen → exec → qa
    Quality Loop: enabled (SCOPE_WARNING auto-enable; touches retry/error control flow)
    Reasoning: ACs are Unit/Integration with clear input/output → testgen stubs first. No UI → no test phase. Not security-sensitive → no security-review.


    Label Review

    Current: enhancement, cli, dependencies
    Recommended: keep enhancement, cli; add planned. dependencies is borderline — the actual SDK bump already merged (#731); this is feature work consuming the SDK, not a dep bump. Keep only if you want the SDK-coupling traceable, otherwise drop.
    Quality Loop: Will auto-enable (SCOPE_WARNING).

    → gh issue edit 732 --add-label planned

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

    @admarble
    ContributorAuthor

    Implementation Update (/exec)

    All 8 ACs satisfied. PR: #735

    AC Coverage

    AC Status Evidence
    AC-1 stream loop reads rate_limit_event + assistant error ✅ drivers/claude-code.ts capture vars
    AC-2 RateLimitError/BillingError typed subclasses ✅ src/lib/errors.ts
    AC-3 message names real cause ✅ driver sets error: structuredError.message
    AC-4 billing failure skips no-MCP retry (#592) ✅ BillingError guard in phase-executor.ts
    AC-5 stderr-regex classifier no regression ✅ error-types/error-capture tests unchanged & green
    AC-6 unit coverage drives new message types ✅ claude-code.test.ts
    AC-7 ≥0.3.181 enrichment + graceful gating ✅ formatRateLimitMessage + tests
    AC-8 tree synced, SDK 0.3.181 ✅ Precondition already met

    Key files changed

    • src/lib/errors.ts — RateLimitError, BillingError, formatRateLimitMessage, createRateLimitError, predicates
    • src/lib/workflow/drivers/claude-code.ts — capture rate_limit_event/assistant.error/api_retry, build typed error
    • src/lib/workflow/drivers/agent-driver.ts + types.ts — structuredError? on AgentPhaseResult/PhaseResult
    • src/lib/workflow/phase-executor.ts — prefer structuredError; guard MCP fallback against BillingError
    • Tests: __tests__/rate-limit-errors.test.ts (new), claude-code.test.ts, phase-executor.test.ts

    Quality Plan Alignment

    Quality Dimension Items Addressed Notes
    Error Handling ✅ Billing vs rate-limit split; graceful gating when 0.3.181 fields absent
    Test Coverage ✅ New message types driven through loop; MCP-skip integration tests
    Code Quality ✅ errors.ts stays SDK-free (structural RateLimitInfoLike); driver owns SDK import
    Backward-compat ✅ New structuredError field optional; aider/subprocess paths unaffected

    Checks

    • npm run build ✅ · npm run lint ✅ (0 warnings) · targeted tests 218 ✅ · workflow sweep 1003 ✅

    Note: Restored an unrelated pre-existing package-lock.json drift (npm dropping libc metadata) to keep the commit focused.

  5. admarble commented on Jun 20, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #732

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Stream loop reads rate_limit_event + assistant error instead of discarding MET claude-code.ts:148-165 captures both (guarded by isRateLimitFailureInfo); driven through the loop in claude-code.test.ts
    AC-2 Original RateLimitError/BillingError extend SequantError, carry resetsAt+overageDisabledReason, correct isRetryable MET errors.ts: RateLimit retryable=true, Billing retryable=false; metadata verified in rate-limit-errors.test.ts
    AC-3 Original User-facing message names the real cause MET Driver sets error: structuredError?.message ?? error; phase-executor.test.ts asserts result.error === "Out of credits"; formatter unit-tested
    AC-4 Original Billing/credits failure does NOT trigger "retrying without MCP" (#592) MET instanceof BillingError guard at phase-executor.ts:918-924; two integration tests (genuine-failure + cold-start range) assert no mcp-disabled call
    AC-5 Original stderr-regex classifier still works for subprocess path — no regression MET error-classifier.ts untouched; error-types.test.ts + error-capture.test.ts unchanged & green
    AC-6 Original Unit coverage drives new message types through the loop MET claude-code.test.ts covers rate_limit_event, assistant.error, api_retry, allowed_warning (no false positive), success
    AC-7 Original ≥0.3.181 enrichment + graceful gating MET formatRateLimitMessage handles canUserPurchaseCredits true/false/undefined → "purchasable"/"hard limit"/generic; tested
    AC-8 Part 3 Tree synced to origin/main, SDK 0.3.181 installed MET Precondition — SDK sdk.d.ts exposes the 0.3.181 fields; build consumes them

    Coverage: 8/8 AC items met (8 original, 0 derived)


    CI Status

    Check State Bucket
    build (22.x) SUCCESS pass
    typecheck SUCCESS pass
    validate-skills SUCCESS pass
    validate-plugin SUCCESS pass

    CI Summary: 4 passed, 0 pending, 0 failed


    Quality Metrics

    Metric Value Status
    Type issues (new any) 0 OK
    Deleted tests 0 OK
    Files changed 9 OK
    Lines added +792 -
    Lines deleted -10 -

    Local gates: npm run build ✅ · npm run lint ✅ (0 warnings) · affected suites 218 ✅ · workflow sweep (exec) 1003 ✅


    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/errors.ts Standard ✅ Yes __tests__/rate-limit-errors.test.ts
    src/lib/workflow/drivers/claude-code.ts Standard ✅ Yes drivers/claude-code.test.ts
    src/lib/workflow/phase-executor.ts Critical (retry control flow) ✅ Yes phase-executor.test.ts
    src/lib/workflow/drivers/agent-driver.ts Optional (type-only) – interface field
    src/lib/workflow/types.ts Optional (type-only) – interface field

    Coverage: 3/3 changed logic files have corresponding tests. Critical path (retry/MCP-fallback control flow) covered.


    Code Review

    Strengths:

    • Clean layering: errors.ts stays SDK-free via the structural RateLimitInfoLike type; only the driver imports the SDK. Matches the existing "driver captures, executor decides" contract.
    • Failure-grade gating (isRateLimitFailureInfo) correctly prevents a benign allowed_warning event from being mis-attributed to an unrelated phase failure — explicitly tested.
    • Structured message preserved across all return paths: genuine-failure early return, cold-start-range path (final return lastResult!), and the no-result path. Traced manually; originalError overwrite only happens inside the now-skipped MCP-fallback block.
    • instanceof BillingError is safe here — single internal errors.js module, no dual-package hazard.
    • Mirrors the existing ApiError/SequantError subclass pattern; isRetryable drives the existing retry decision flow.

    Issues: None blocking.

    Suggestions (non-blocking):

    • Catch-path does not attach structuredError (claude-code.ts:263-290). The captured rateLimitInfo/assistantError are function-scoped and available, but the catch returns without building the typed error. Low-probability — rate-limit/billing failures arrive as result/assistant-error messages, not thrown exceptions (the catch is for timeout/abort/unexpected SDK throws). Could call buildStructuredError in the catch for completeness as a follow-up.
    • resetsAt unit heuristic (<1e12 → seconds, else ms): the SDK type doesn't document the unit. The heuristic is reasonable and documented, but if the SDK ever emits a small ms value the time would be wrong. Acceptable given the constraint.
    • Minor: the local const isBillingFailure in phase-executor.ts:918 shares a name with the exported isBillingFailure(info) predicate (not imported here, so no compiler collision) — a different local name would read slightly clearer.

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Asserts on outputs (error type, isRetryable, surfaced message string), not internals
    Coverage Depth ✅ OK Billing + transient + assistant-error + api_retry + allowed_warning(no-FP) + success; ms-vs-seconds equivalence; absent-field gating
    Mock Hygiene ✅ OK Only the SDK query is mocked (external dep) via a clean async-iterable helper
    Test Reliability ✅ OK Deterministic; reset-time asserted via /\d{2}:\d{2}/ regex so TZ-independent

    Anti-Pattern Detection

    No N+1 loops, empty catches, hardcoded secrets, or uncleared timers introduced. package.json unchanged → no dependency audit. Call-site review: all 6 new exports (RateLimitError, BillingError, createRateLimitError, isRateLimitFailureInfo, isBillingFailure, formatRateLimitMessage) have live call sites — no dead exports.


    Risk Assessment

    • Likely failure mode: SDK throws mid-stream after a rate_limit_event → catch path loses the structured cause and falls back to the raw error string (see suggestion feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1). Or the SDK changes resetsAt units (heuristic could misformat).
    • Not tested: The catch-path-with-prior-rate-limit-signal scenario (the structured error is only built on the post-loop result paths, not in catch).
    • Sibling sites considered: Cross-file — the aider driver does not consume the SDK message stream, and the subprocess path (run.ts) is intentionally left on the stderr-regex classifier per AC-5. No cross-file sibling requires action.
    • Sibling-line audit: Intra-file — the three post-loop failure returns (error-result, no-result) both attach structuredError; the catch return is the one sibling that does not (flagged above as a non-blocking follow-up).

    Adversarial Re-Read

    Findings: Traced every failure return path for message preservation (genuine-failure, cold-start exhaustion, no-result) — structured message survives in all three; originalError overwrite is confined to the MCP-fallback block that billing now skips. Ran the build/lint/affected-suite gates fresh (all green) rather than trusting exec's claims. Verified instanceof works across the AgentPhaseResult→PhaseResult boundary (single module). Confirmed no Non-Goal expansion: Part 2 (tool_use_meta rendering) is untouched; subprocess regex path retained per AC-5. One genuine gap surfaced: the catch path does not propagate structuredError (low-probability, non-blocking).

    Status: Gaps Found


    Verdict: AC_MET_BUT_NOT_A_PLUS

    All 8 acceptance criteria are MET with strong test coverage, clean layering, and green CI. Downgraded from READY_FOR_MERGE only by the adversarial re-read surfacing one non-blocking gap (catch-path structuredError propagation) plus two minor suggestions. None block merge — these are follow-up polish items. Safe to merge; optionally address suggestion #1 first.

    Documentation

    Documentation: Before merging, optionally run /docs 732 (low value here — no user-facing config/CLI surface).

    Next Steps

    1. (Optional) Propagate structuredError in the catch block of claude-code.ts for completeness, or file as a follow-up.
    2. Merge PR feat(driver): surface structured rate-limit/credits errors from SDK message stream (#732) #735 (branch is 1 commit behind origin/main — a clean merge or quick git merge origin/main before merging is fine).
  6. added
    needs-improvement
    on Jun 20, 2026
  7. admarble commented on Jun 20, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #732 (re-run on 1dc6e15)

    Incremental review of commit 1dc6e15 (the QA-suggestion follow-up) on top of the previously-reviewed d98061b. Delta: +69 lines across claude-code.ts (catch-path), phase-executor.ts (rename), claude-code.test.ts (+2 tests).

    AC Coverage

    AC Description Status
    AC-1 Stream loop reads rate_limit_event + assistant error MET (now also surfaced on the catch/throw path)
    AC-2 RateLimitError/BillingError typed subclasses, correct isRetryable MET
    AC-3 User-facing message names the real cause MET (extended to mid-stream throws)
    AC-4 Billing failure does NOT trigger "retrying without MCP" (#592) MET
    AC-5 stderr-regex classifier no regression MET
    AC-6 Unit coverage drives new message types through the loop MET (+2 catch-path tests)
    AC-7 ≥0.3.181 enrichment + graceful gating MET
    AC-8 Tree synced, SDK 0.3.181 MET

    Coverage: 8/8 AC items MET.

    Prior-round findings — resolution

    Prior finding Status
    Catch-path didn't attach structuredError ✅ Fixed — claude-code.ts:277-303 builds the typed error from captured signals; abort/timeout still returns first (tested both branches)
    Local isBillingFailure var overlapped exported predicate ✅ Fixed — renamed to failureIsBilling
    resetsAt seconds/ms heuristic Accepted as-is — documented, handles both units; not a defect

    CI Status (commit 1dc6e15)

    Check State Bucket
    typecheck SUCCESS pass
    build (22.x) SUCCESS pass
    validate-skills SUCCESS pass
    validate-plugin SUCCESS pass

    CI Summary: 4 passed, 0 pending, 0 failed (waited for build (22.x) to settle before verdict).

    Quality Metrics

    Metric Value Status
    New any types 0 OK
    Deleted tests 0 OK
    Files changed (delta) 3 OK
    Lines added/deleted (delta) +69 / -3 -

    Local gates (on 1dc6e15): build ✅ · lint ✅ (0 warnings) · affected suites 220/220 ✅ · workflow sweep 934 passed / 2 skipped ✅

    Code Review (delta)

    • Catch-path fix ordering is correct: the abort/timeout early-return precedes buildStructuredError, so a genuine timeout is never masked by a stale rate-limit signal — explicitly covered by the "abort-wins" test.
    • Operator precedence verified: structuredError?.message ?? error + stderrSuffix parses as ?? (error + stderrSuffix) — correct fallback.
    • buildStructuredError only attaches a cause when a failure-grade (rejected/billing) event was captured (isRateLimitFailureInfo guard), so an unrelated throw isn't mislabelled.
    • Rename is cosmetic; no behavior change.

    Risk Assessment

    • Likely failure mode: resetsAt unit drift if the SDK emits an unexpected magnitude (mitigated by the <1e12 heuristic).
    • Not tested: none new — both catch-path branches (structured cause / abort) are now covered.
    • Sibling sites considered: cross-file — aider driver doesn't consume the SDK stream; subprocess path stays on the regex classifier per AC-5. No action.
    • Sibling-line audit: intra-file — all four failure returns (success-error, no-result, error-result, and now catch) attach structuredError; the abort early-return intentionally does not (timeout is the real cause).

    Adversarial Re-Read

    Findings: Traced the new catch-path against both branches (throw-after-rejection → typed cause surfaced; abort → timeout preserved); re-ran build/lint/tests fresh on 1dc6e15 and waited for CI build (22.x) to go green rather than assuming; verified ??/+ precedence; confirmed no Non-Goal expansion (Part 2 untouched, subprocess regex path retained). No remaining gaps — the prior round's actionable items are resolved and the one accepted item is a documented engineering choice.

    Status: Clean

    Verdict: READY_FOR_MERGE

    All 8 ACs MET, all gates and CI green, prior-round suggestions resolved, adversarial re-read clean. This is an A+ implementation. Ready to merge PR #735.

    Documentation

    Documentation: Optionally run /docs 732 before merge (low value — no user-facing CLI/config surface).

    Next Steps

    1. Merge PR feat(driver): surface structured rate-limit/credits errors from SDK message stream (#732) #735 (branch is behind origin/main by the dependabot commit — a clean git merge origin/main before merge keeps it tidy).
  8. added
    ready-for-review
    and removed
    needs-improvement
    on Jun 20, 2026
  9. admarble commented on Jun 20, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #732 (re-review @ d404ca4)

    Re-QA after the follow-up commit d404ca4 (catch-path structuredError propagation + billing-guard rename) landed on top of the previously-approved 1dc6e15. PR #735.

    AC Coverage

    AC Description Status Notes
    AC-1 Stream loop reads rate_limit_event + assistant error MET claude-code.ts:149-172 captures both; api_retry also captured. Discriminants verified against SDK sdk.d.ts (type:'system'/subtype:'api_retry', assistant.error?).
    AC-2 RateLimitError/BillingError in errors.ts w/ resetsAt + overageDisabledReason MET Both subclass SequantError; RateLimitMetadata carries both fields. BillingError.isRetryable=false, RateLimitError=true.
    AC-3 User-facing message names real cause, verified vs mocked event MET formatRateLimitMessage → "Out of credits…" / "Rate limited — resets at HH:MM"; driven by mocked rate_limit_event in claude-code.test.ts.
    AC-4 Billing failure does NOT trigger "retrying without MCP" (#592) MET failureIsBilling gate at phase-executor.ts:913; tested incl. cold-start-window edge case (no 4th mcp-disabled call).
    AC-5 stderr-regex classifier still works for subprocess path MET error-classifier.ts and run.ts untouched; still invoked via structuredError ?? classifyError(...). No regression.
    AC-6 Unit coverage drives new message types through the loop MET 8 new driver tests: billing, transient, assistant-error fallback, api_retry, allowed_warning ignored, throw-after-reject, abort-not-masked, success.
    AC-7 ≥0.3.181 enrichment (canUserPurchaseCredits …) w/ graceful gating MET SDK installed is 0.3.181; "purchasable" vs "hard limit" vs generic, gated on field presence. Tested.
    Part 3 Working tree synced to origin/main + npm ci (0.3.181) MET Worktree 0 commits behind main; installed SDK 0.3.181.

    Coverage: 8/8 met.

    CI Status (PR #735)

    Check State Impact
    typecheck SUCCESS ✅ MET
    build (22.x) SUCCESS ✅ MET
    validate-skills SUCCESS ✅ MET
    validate-plugin SUCCESS ✅ MET

    mergeable: CLEAN. 149/149 relevant unit tests pass locally (rate-limit-errors, claude-code, phase-executor).

    Quality Metrics

    Metric Value Status
    Type issues (any) 0 new OK
    Deleted tests 0 OK
    Files changed 9 OK
    Lines +859 / -11 OK (mostly tests + errors module)

    Code Review

    Strengths:

    • Clean layering: errors.ts stays SDK-free via the RateLimitInfoLike subset; only the driver imports the SDK.
    • Wire-correct — every discriminant/field name (status, resetsAt, overageDisabledReason, errorCode:'credits_required', canUserPurchaseCredits) matches SDKRateLimitInfo exactly (camelCase confirmed, not snake_case).
    • isRateLimitFailureInfo correctly excludes allowed/allowed_warning so a benign warning event can't poison an unrelated failure.
    • Abort/timeout path returns before the structured-error build in the catch handler, so a real timeout is never masked by a stale rate-limit signal (explicitly tested).
    • Follow-up d404ca4 closed the one gap from the prior pass — catch-path now propagates structuredError too, so all three error return sites are consistent while success correctly omits it.

    Issues: None blocking.

    Suggestions (non-blocking, follow-up at most):

    • apiRetryError is the lowest-precedence fallback; if the SDK does an api_retry (e.g. overloaded) and then fails for an unrelated reason, "API overloaded" could be surfaced as the cause. Low risk — rate_limit_event/assistant.error take precedence and an api_retry-then-fail is usually genuinely rate-limit-adjacent.
    • RateLimitInfoLike is a hand-maintained subset of SDKRateLimitInfo; a future SDK field rename would silently stop populating (no compile error, since the driver passes the raw SDK object). Inherent to the deliberate decoupling; acceptable.

    Risk Assessment

    • Likely failure mode: SDK changes the shape/field names of SDKRateLimitInfo in a future bump → structured capture silently no-ops and behavior reverts to the stderr-regex fallback (safe degradation, not a crash).
    • Not tested: Live end-to-end against a real out-of-credits account (mocked streams only — appropriate for unit scope).
    • Sibling sites considered (cross-file §5): aider.ts (other AgentDriver) and run.ts (subprocess) — both correctly leave the optional structuredError undefined and use the unchanged stderr-regex classifier, exactly as the issue scopes. No sibling fix needed.
    • Sibling-line audit (intra-file §4): All three driver error return sites (result-error, no-result, catch) propagate structuredError; the success site correctly omits it. Consistent.

    Adversarial Re-Read

    Findings: No gaps found because: ran all 8 driver + 3 executor + AC-2/3/7 error tests (149 pass); verified every SDK discriminant and field name against node_modules/.../sdk.d.ts (not just code review); confirmed the formatResetTime seconds-vs-ms heuristic boundary (1e12) holds for realistic epochs; confirmed abort-masking guard ordering; confirmed both fallback paths (error-classifier.ts, run.ts) are untouched so AC-5 has no regression surface; Part 2 (tool_use_meta) is explicitly a Non-Goal and correctly not implemented; no any introduced.

    Status: Clean

    Verdict: READY_FOR_MERGE

    A+ implementation. All 8 ACs met, CI green, mergeable CLEAN, comprehensive edge-case test coverage, clean SDK/error-module decoupling, and the follow-up commit closed the only prior gap.

    Documentation

    Next Steps

    1. Merge PR feat(driver): surface structured rate-limit/credits errors from SDK message stream (#732) #735.
    2. (Optional follow-up) Reconsider api_retry-as-cause precedence if false attributions are observed in the wild.
  10. admarble commented on Jun 20, 2026

    @admarble
    ContributorAuthor

    Gap-fill follow-up (commit 0af8872, PR #735)

    Filled the two concrete gaps surfaced in the re-review, directly on the PR:

    1. Multi-day reset times were misleading. SDKRateLimitInfo.rateLimitType can be seven_day*, where resetsAt is days out — but formatResetTime rendered only bare local HH:MM, which reads as "later today." Now: bare HH:MM when the reset is on the current calendar day, date-qualified MM-DD HH:MM otherwise. Added same-day and multi-day tests.

    2. Billing could be downgraded to retryable. If a transient rate_limit_event (no billing reason) co-occurred with assistant.error: "billing_error", buildStructuredError returned a retryable RateLimitError — which would wrongly re-enable the retry / MCP-fallback path for a non-retryable billing failure. The billing_error signal now wins over a transient throttle event; when the rate_limit_event is itself billing, its richer canUserPurchaseCredits metadata is preserved. Added a billing-precedence driver test.

    Not changed (deliberate):

    • api_retry as lowest-precedence diagnostic — kept; rate_limit_event/assistant.error take precedence and an api_retry-then-fail is usually genuinely rate-limit-adjacent.
    • RateLimitInfoLike hand-maintained SDK subset — kept; importing the SDK type into errors.ts to guard against drift would defeat the SDK-free decoupling that module was written to preserve. Drift degrades safely to the stderr-regex fallback.

    Local: typecheck clean, 151/151 unit tests pass (rate-limit-errors, claude-code, phase-executor). CI re-running on 0af8872.

  11. added a commit that references this issue on Jun 23, 2026
  12. added 2 commits that reference this issue on Aug 4, 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

    clidependenciesenhancementplannedready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions