Repository navigation
Description
The defect
isBillingFailure (src/lib/errors.ts:260-265) classifies on the presence of a marker alone:
export function isBillingFailure(info: RateLimitInfoLike): boolean {
return info.errorCode === "credits_required" ||
info.overageDisabledReason === "out_of_credits";
}It ignores rateLimitType and ignores whether a live resetsAt is present.
On a subscription plan, hitting the five-hour cap with overage disabled produces exactly this payload. All 26 real rate-limit failures captured across ad-motion and matcha-maps (five separate days) are structurally identical:
"errorMetadata": {
"resetsAt": 1784478600,
"rateLimitType": "five_hour",
"overageDisabledReason": "out_of_credits"
}That is a window that will reopen at a known time, not a wallet needing a top-up. But it becomes a BillingError, and:
BillingErrorandRateLimitErrorare sibling classes (errors.ts:207and:227, both extendingSequantErrordirectly)shouldAutoWaitForReset(phase-executor.ts:287) returns null unlesserror instanceof RateLimitError
So --auto-wait (#804) cannot fire on any real limit event this project has ever recorded, even though the payload carries the exact wake time it needs. #799 then fail-fasts the quality loop and the run halts.
Net effect: the feature built for unattended runs is inert for the plan most likely to want it.
Design critique — the obvious fix is wrong
Do not simply invert the classification. On a pay-as-you-go/API account, out_of_credits genuinely is terminal; waiting is useless and the current halt-immediately behavior is correct. A naive change strands those users in a silent multi-hour sleep instead of telling them to add credits. The change must narrow the billing class, not flip it.
The natural discriminator is not available in practice. RateLimitInfoLike (errors.ts:250-253) already declares canUserPurchaseCredits and hasChargeableSavedPaymentMethod — exactly the fields that would separate "subscription window" from "needs purchase". All 26 captured payloads omit both. So a correct implementation cannot depend on them; it must degrade to a proxy and treat their absence as unknown.
The proxy is an inference about someone else's billing semantics. rateLimitType: "five_hour" + a future resetsAt is good evidence of a subscription window, but it encodes an assumption about Anthropic's payload vocabulary that can drift silently. Whatever is built should fail closed — if the shape is unrecognized, keep today's terminal behavior.
The larger critique: in-process sleeping may be the wrong shape
Even with correct classification, --auto-wait holds a live process for up to five hours. That has costs the current design does not address:
- It holds the per-issue lock for the entire wait. Nothing else can touch that issue, and
sequant statusshows it as in-progress. - It does not survive a reboot. A laptop restart mid-wait loses the run and leaves a stale lock — and per Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856, a stale lock whose PID is later recycled reads as fresh, silently blocking that issue indefinitely.
- Observability is thin in exactly the case that matters.
LivenessHeartbeat.writeWaitHeartbeatis TTY-gated (heartbeat.ts,if (this.tty)), and the waiting branchcontinues past the stall warning. There is anonAutoWaitprogress channel (batch-executor.ts:116) — whether it actually reaches stdout for a background, non-TTY run needs verifying. If it does not, an unattended run emits nothing for five hours, which is indistinguishable from the hang in Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856.
Alternative worth costing before building: halt cleanly, record a machine-readable resumeAt in state, and exit. Re-entry is already cheap because #837 makes a resumed run skip completed issues. That design holds no lock, survives reboots and laptop sleep for free, is trivially observable, and needs no in-process timer. The scheduling then lives in ~20 lines of launchd/cron rather than inside a long-lived agent process.
The counter-argument for keeping the in-process wait is that it preserves worktree and chain state across the pause without re-deriving it, and avoids a cold start. That may well win — but it should be an argued choice, not a default.
Credit where due: waitForWindowReset (phase-executor.ts:321) is wall-clock tick-based, taking an injectable now() rather than a single setTimeout, so it already survives machine sleep. AUTO_WAIT_MAX_WAITS = 2 bounds runaway pause loops, and a registered AbortController lets Ctrl-C end a wait. The existing implementation is careful; the problem is that classification prevents it from ever running.
Real-world scenario
An overnight chain starts at 23:00 and exhausts the five-hour window at 02:00, with resetsAt at 07:00.
Today: BillingError → #799 fail-fasts → the run halts at 02:00. Seven hours of wall clock wasted; the user finds a dead run at breakfast.
With classification fixed, in-process wait: the run sleeps five hours holding the lock. If the laptop sleeps, the tick loop re-reads the clock and is fine. If it reboots, the run is gone and a stale lock remains. On wake the phase restarts from scratch anyway, because the claude subprocess died at 02:00 — so the wait bought resumption, not continuity.
With halt-and-resume: the run exits at 02:00 recording resumeAt: 07:00. A scheduled re-invocation at 07:05 skips the completed issues (#837) and continues. Survives reboot, holds no lock, and the state file says plainly what is happening.
Acceptance Criteria
- AC-1: A rate-limit failure carrying
rateLimitType: "five_hour"(or another window type) together with a futureresetsAtis classified as a waitable window rather than a terminal billing failure, even whenoverageDisabledReason: "out_of_credits"is present. - AC-2: A failure with
errorCode: "credits_required", or with no futureresetsAt, remains terminal and halts immediately with the existing message. - AC-3: An unrecognized payload shape fails closed — treated as terminal, never as an indefinite wait.
- AC-4: All 26 captured payloads are committed as fixtures and assert the waitable classification; the existing terminal-billing fixtures continue to assert terminal.
- AC-5:
--auto-waitfires end-to-end on a replayed five-hour-window payload, and does not fire on a replayed terminal-credits payload. - AC-6: A waiting run emits periodic progress to non-TTY stdout naming the wake time, so an unattended wait is distinguishable from a hang.
- AC-7: The in-process-wait versus halt-and-resume tradeoff is decided explicitly and the rationale recorded, covering lock-holding and reboot survival.
Evidence
Captured payloads: docs/incidents/782/captures/ (the committed #782 sample from 2026-07-18) plus 26 further occurrences in the ad-motion and matcha-maps .sequant/logs/ from 2026-07-19, 07-24 and 07-26. Note .sequant/ is gitignored and rotates at ~100 files — copy before they age out.
Related: #804 (auto-wait), #799 (fail-fast on billing/window), #820 (infra-blocked CI), #856 (a silent run is indistinguishable from a hang).
Activity
admarble commentedon Jul 29, 2026
#860 — Five-hour window exhaustion is misclassified as terminal billing, so --auto-wait is inert on subscription plans
Open
────────────────────────────────────────────────────────────────
→ PROCEED — Verified against main — isBillingFailure (errors.ts:260-265) classifies on marker presence alone, checking neither rateLimitType nor resetsAt
Commands:
sequant run 860 -Q
spec → exec → qa · 7 ACs
Flags:
-Q classification, wait plumbing and non-TTY observability span several files
Considered:
--testgen AC-4 pins specific captured payloads as fixtures — generated stubs would not match them
────────────────────────────────────────────────────────────────
⚠ AC-4 needs the 26 payloads copied out of ad-motion/matcha-maps .sequant/logs/ before the 100-file rotation ages them out — capture first or the AC becomes unmeetable
⚠ AC-7 is a design decision (in-process wait vs halt-and-resume), not implementation — expect spec to surface it for a call
────────────────────────────────────────────────────────────────
admarble commentedon Jul 29, 2026
#860 — Five-hour window exhaustion is misclassified as terminal billing, so --auto-wait is inert on subscription plans
Open
────────────────────────────────────────────────────────────────
Supersedes prior assess from 2026-07-29 (PROCEED)
→ PROCEED — Re-verified against main — isBillingFailure (errors.ts:259-264) still classifies on marker presence alone, checking neither rateLimitType nor resetsAt
Commands:
sequant run 860 -Q # after PR #858 merges
spec → exec → qa · 7 ACs
Flags:
-Q classification, wait plumbing and non-TTY observability span several files
Considered:
--testgen AC-4 pins 26 specific captured payloads as fixtures — generated stubs would not match them
────────────────────────────────────────────────────────────────
⚠ New since the last assess: open PR #858 (issue #853) rewrites src/lib/workflow/phase-executor.ts, the same file shouldAutoWaitForReset (:287) and waitForWindowReset (:321) live in — land #858 first or expect a conflict
⚠ AC-4 needs the 26 payloads copied out of ad-motion/matcha-maps .sequant/logs/ before the 100-file rotation ages them out — capture first or the AC becomes unmeetable
⚠ AC-7 is a design decision (in-process wait vs halt-and-resume), not implementation — expect spec to surface it for a call
────────────────────────────────────────────────────────────────
admarble commentedon Aug 4, 2026
Plan (spec)
Complexity: Standard (7 ACs, ~4 directories)
Scope note
Automated scope assessment says
SCOPE_SPLIT_RECOMMENDED(feature-count heuristic counts classification + observability + decision-record as 3 features). Proceeding as one change: AC-1..5 are one cohesive classification fix with its evidence, AC-6 is a ~15-line heartbeat gap in the same feature, AC-7 is a document. Quality loop enabled to compensate.Evidence secured
All 26 payloads (22 ad-motion + 4 matcha-maps, 6 distinct
resetsAtvalues, allfive_hour+out_of_credits, none carryingerrorCode/canUserPurchaseCredits/hasChargeableSavedPaymentMethod) copied out of the rotating.sequant/logsbefore they age out. They will be committed underdocs/incidents/860/captures/plus a distilled test-fixture JSON.AC checklist & verification
createRateLimitError→RateLimitError)credits_required/ no-future-resetsAtstays terminal — Unit--auto-waitfires end-to-end on replayed window payload, not on terminal payload — Integration (replay throughbuildStructuredError→shouldAutoWaitForReset/performAutoWait)isTTY: false)docs/investigations/)Design
Narrow
isBillingFailureat the source (src/lib/errors.ts) — do not invert it:errorCode === "credits_required"→ always terminal (explicit purchase signal wins).overageDisabledReason === "out_of_credits"→ terminal unless the payload also carries a recognized window type (five_hour/seven_day*prefix allowlist) and a futureresetsAt(viaresetsAtToMs, injectablenow). Then it is a waitable window →RateLimitError.rateLimitType: "overage", missing/pastresetsAt) → fails closed, terminal.canUserPurchaseCredits/hasChargeableSavedPaymentMethodstay out of classification (absent in all 26 real payloads); they continue to enrich messaging only.All consumers inherit the narrowing:
createRateLimitError,formatRateLimitMessage(window payloads now say "Rate limited — resets at …" instead of the misleading "Out of credits"),isRateLimitFailureInfo,run-display.ts.Critical second touchpoint:
claude-code.ts:366downgradesRateLimitError→ bareBillingErrorwhen the assistant separately reportsbilling_error. After narrowing, that guard would re-kill auto-wait for exactly the payloads we are fixing. The downgrade must not fire when the rate-limit event itself carries waitable-window evidence (richer signal wins — same precedence philosophy already documented there).AC-6:
LivenessHeartbeat.tick()currentlycontinues past non-TTY output while waiting (heartbeat.ts:223-228). Add a throttled non-TTY branch (~every 5 min, plain newline-terminated line naming wake time + remaining). TUI renderer path unaffected.AC-7 decision (to be recorded in
docs/investigations/auto-wait-vs-halt-resume-860.md): keep the in-process wait now — classification is the actual defect; the wait machinery (#804) is tick-based, sleep-safe, abortable, and bounded (AUTO_WAIT_MAX_WAITS=2). Record lock-holding and reboot-survival costs honestly; file a follow-up issue for halt-and-resume +resumeAtstate (builds on #837) rather than expanding this change.Implementation plan
docs/incidents/860/captures/+ distilled__tests__/fixtures/rate-limit-payloads-860.json(26 entries with source refs).errors.ts: addisWaitableWindow(info, now?), narrowisBillingFailure(info, now?); unit tests incl. all 26 fixtures (AC-1..4).claude-code.ts: guard thebilling_errordowngrade with the waitable-window check; driver-level tests.heartbeat.ts: non-TTY throttled wait line (AC-6) + tests.shouldAutoWaitForReset/auto-wait path (AC-5).Open questions (proceeding with defaults)
five_hourexact +seven_dayprefix (matches documented SDK vocabulary). Impact if wrong: an unlisted future window type stays terminal (fail-closed, safe).seven_day+out_of_creditsoccur in practice? No captures show it; allowlisting is a judgment call consistent with AC-1 "(or another window type)".Phases: spec → exec → qa (no UI labels → no browser test; testgen skipped — tests are themselves ACs and written alongside implementation)
admarble commentedon Aug 4, 2026
Exec complete
Commit
a910520donfeature/860-waitable-window-classification(13 files, +1397/−21).AC status after implementation
isBillingFailurenarrowed via newisWaitableWindow(five_hour/seven_day*+ futureresetsAt, injectablenow); live windows → retryableRateLimitError, metadata intactcredits_requiredterminal even beside window evidence; past/missingresetsAtterminal; existing "Out of credits" messages unchangedrateLimitType: "overage")__tests__/fixtures/rate-limit-payloads-860.json+docs/incidents/860/captures/README.md); rawstdoutTailtranscripts deliberately excluded (unrelated-project content — noted in the README)executePhaseWithRetryreplay waits-and-retries on the window payload, halts without waiting oncredits_required-qheartbeat: append-only non-TTY line naming wake time every 5 min; default-mode NonTTYRenderer: announces wait once, 60s heartbeat names wake time — and two latent bugs fixed (waiting events printed a spurious✘per 15s tick and held the heartbeat idle clock fresh, silencing it for the whole wait)docs/investigations/auto-wait-vs-halt-resume-860.md(keep in-process wait; halt-and-resume filed as follow-up)Extra touchpoint found during implementation
claude-code.tsbuildStructuredErrordowngraded anyRateLimitErrorto a metadata-lessBillingErrorwhen the assistant separately reportedbilling_error— which would have re-inerted auto-wait for exactly the payloads being fixed. The downgrade now yields to waitable-window evidence in therate_limit_event.Gates
five_hourremoved from allowlist → 10 tests fail across errors/auto-wait/driver suites ✅✘-suppression guard) ✅admarble commentedon Aug 4, 2026
QA Review for Issue #860
AC Coverage
isWaitableWindow+ narrowedisBillingFailure(errors.ts); all 26 captured payloads →RateLimitErrorwith metadata intact; message names the reset, not "Out of credits"credits_requiredshort-circuits before the window check; past/missing resetsAt terminal; "Out of credits" message tests unchanged; end-to-end replay halts in 1 attempt, delayFn never called/^(five_hour|seven_day)/+ full-shape requirement; tested withrateLimitType: "overage", missing type, missing/past resetsAt — all terminal. Wait is additionally double-bounded (AUTO_WAIT_MAX_WAITS, minutes budget), so "indefinite wait" is impossible even on misclassification__tests__/fixtures/rate-limit-payloads-860.json(26 entries, 22 ad-motion + 4 matcha-maps, with provenance); count + shape + classification gated by tests, mutation-verified. Untouched terminal fixtures (credits_required, markerless out_of_credits) still assert terminal. The #782 capture tests were retitled honestly: same payload class, terminal once aged, waitable at the captured instantshouldAutoWaitForResetat their captured instant;executePhaseWithRetryreplay (payload shape verbatim, reset re-based) waits and retries to success; credits_required replay halts without waiting; driver test proves therate_limit_event→RateLimitErrorlink survives a concurrentbilling_errorenum-qLivenessHeartbeat (append-only line, 5-min throttle, wake + remaining) and default-mode NonTTYRenderer (announce-once + 60s heartbeat naming wake). Two latent bugs fixed on the way: waiting events printed a spurious✘per 15s tick and heldlastEventAtfresh, silencing the heartbeat for the whole waitdocs/investigations/auto-wait-vs-halt-resume-860.md— argued table covering lock-holding and reboot loss explicitly; decision: keep in-process wait, file halt-and-resume follow-upCoverage: 7/7 ACs fully met
Quality Metrics & Checks
any/@ts-ignore: none added).skip)phase-executor.tscomment-onlyPrecheck Findings
isBillingFailuresnippet (now replaced) and theresetsAt: 1784478600payload (present in the committed 26, asserted waitable)Test Coverage Analysis
All behavioral source changes have direct tests:
errors.ts→rate-limit-errors.test.ts(36),claude-code.ts→ driver suite,heartbeat.ts/run-renderer.ts→auto-wait-display.test.ts(16), executor path →auto-wait.test.ts(46).phase-executor.tschange is comment-only.Risk Assessment
sequant_status/run logs remain the liveness source there).isBillingFailureconsumers traced (createRateLimitError,formatRateLimitMessage,isRateLimitFailureInfo— deliberately kept on raw markers,run-display.tslabel fallback — correct with defaultnow). Precheck sibling-grep: 0 unaddressed.billing_errordowngrade atclaude-code.ts:366was found and guarded during exec — the one adjacent site that would have re-inerted the fix.Trust-Boundary Check
Finding: Clean — diff implements only product requirements; the issue body's process guidance ("copy captures before they age out") was followed as benign maintainer instruction; no agent-directed execute/fetch/exfiltrate content present or acted on.
Status: Clean
Behavior-Rule Survival Check
Detector run on all 7 ACs: not triggered (AC-3's single "never" is below the 2-keyword threshold; no
always X unless Ypatterns). Status: N/ACHANGELOG Verification
Adversarial Re-Read
Findings: No gaps found because: (1) both verbatim issue-body fixtures were run — the quoted payload is entry #2 of the committed 26 and asserts waitable; (2) evidence claims are post-fix validations (fixture-driven classification tests + end-to-end replay), not pre-fix repros; (3) process state inspected — single clean commit, 0 behind origin/main, lockfile churn reverted before commit; (4) sibling sites cited above, including the driver downgrade that static AC reading would have missed; (5) the issue's explicit non-goal ("do not simply invert") honored —
credits_requiredand aged windows remain terminal, asserted by tests; classification-time vs wait-decision-time drift traced (window expiring between error creation and wait decision degrades to transient backoff, not a hang).Status: Clean
Verdict: READY_FOR_MERGE
All 7 ACs met with fixture-backed, mutation-verified tests; full suite green; the change narrows rather than inverts the classification and fails closed on unknown shapes. One observation recorded (MCP-mode wait visibility) — pre-existing, by-design, out of scope.
Documentation: CHANGELOG ✅ · incident captures README ✅ · decision record ✅ · README unchanged (no new flags —
--auto-waitalready documented by #804)admarble commentedon Aug 4, 2026
/fullsolve Complete
Issue: #860
Status: READY_FOR_MERGE
PR: #893 (CI: 5/5 checks green — build, typecheck, node-floor-guard, validate-skills, validate-plugin)
Summary
billing_errordowngrade would have re-inerted auto-wait; NonTTY renderer printed a spurious✘per 15s waiting tick and its heartbeat was silenced during waitsresumeAtstate, lock release at halt, reboot survival), per the AC-7 decision recordIterations
Ready for human review and merge.
fix(#860): close the residual gaps — status guard, drift telemetry, M…
fix(#860): classify live five-hour windows as waitable, not terminal …
feat(#892): durable halt-and-resume for waitable rate-limit windows (#…