Repository navigation
Description
Blocked by #782
Context
#761 built the classification and #799 built the fail-fast: a rate limit whose resetsAt is more than RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS (5 min) out is treated as window exhaustion, skips the retry ladder and the MCP fallback (phase-executor.ts:965), and halts the outer -Q loop (isBillingOrWindowHalt, batch-executor.ts:474). That was the right call at the time — #761 listed "scheduling runs around limit windows" as explicitly out of scope.
The consequence is that a 5-hour window reset turns a multi-hour run into a manual restart, even though the SDK told us exactly when the window reopens. Sequant already waits-and-retries for the sub-5-minute case (phase-executor.ts:981-996, exponential backoff via the injected delayFn), so the machinery exists; only the threshold and the durability story differ.
This issue makes that wait opt-in and bounded: if the user says they are willing to wait up to N minutes, wait until resetsAt and continue the run instead of halting.
Proposal
A single user-facing dial — a wait budget in minutes, default 0 (off, i.e. today's behavior byte-for-byte):
- Flag:
--auto-wait <minutes>onsequant run - Setting:
run.autoWaitMinutes - Env: resolved for free by
ConfigResolver(defaults < settings < env < explicit), including numeric coercion viacoerceEnvValue
When a phase fails with a window-exhausted RateLimitError and resetsAt - now <= autoWaitMinutes, sleep until resetsAt (plus a small buffer) and retry the phase rather than returning the failure.
Naming rationale (settled during design): auto-wait names the behavior, not the mechanism, so the name survives a future move from in-process sleep to out-of-process rescheduling. Rejected alternatives: auto-persist (the token persist already means disk writes in 25 non-test sites, notably batch-executor.ts:642 "Persist resume token + originCwd for cross-process resume" — it would read as a state-retention knob next to state --max-age); a bare --wait (already exists on sequant prompt at bin/cli.ts:374 and takes seconds, so a minutes-valued twin invites unit confusion). The unit lives in the setting name per house style (maxSizeMB, durationSeconds, COLD_START_THRESHOLD_SECONDS).
Scope is in-process sleep only. Durable out-of-process resume (persist a wake time, exit, let a scheduler re-enter) is deliberately deferred — see Out of scope. In-process is the smallest change that delivers the behavior and is a direct generalization of the existing transient-throttle branch. Holding the worktree lock across the wait is acceptable because the limit is account-wide: no other run could make progress during that window anyway.
Acceptance Criteria
- AC-1:
--auto-wait <minutes>exists end-to-end:.option()inbin/cli.ts(without it the flag silently does not exist),RunOptions+ExecutionConfig+DEFAULT_CONFIGinworkflow/types.ts,run.autoWaitMinutesonRunSettingsandRunSettingsSchema(settings.ts:275,314), reaching the decision site inphase-executor.ts. Default0. Not inlib/config.ts— that is the setup config (tokens/stack), unrelated to run behavior. - AC-2: With the default (
0), behavior is unchanged: the existing window-exhaustion tests (phase-executor.test.ts:771and:806) pass unmodified, as do the-Qhalt tests (batch-executor.test.ts:807). This AC is the regression contract for the whole change. - AC-3:
RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS(phase-executor.ts:139) andisWindowExhaustedRateLimit(:161) are not repurposed as the budget — they answer "transient or exhausted?" while the budget answers "am I willing to wait that long?", which are different questions. Add the budget as a separate, purely-internal decision (e.g.shouldAutoWaitForReset(error, budgetMs, now)) that fires only whenisWindowExhaustedRateLimitis already true, keepingautoWaitMinutesthe only user-facing dial for the wait-vs-halt outcome. - AC-4: Auto-wait fires for
RateLimitErroronly. ABillingError(out of credits) must never wait — it carries noresetsAtby design because credits are purchased, not waited out, so a wait would hang on a condition that cannot self-heal. A rate limit with noresetsAt(the assistant-error channel,claude-code.ts:376-399) must not wait either: it falls through to the existing transient backoff per feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761 AC-9. - AC-5: The wake fires at
resetsAtToMs(resetsAt)plus a ~60s buffer, not exactly atresetsAt— the reset is a floor, and clock skew or server-side rounding otherwise produces an immediate second rejection. All arithmetic stays in epoch ms and formatting happens only for display, reusingformatRateLimitMessage; do not re-derive or re-appendresetsAtonto an already-formatted message (the fix(run): -Q quality loop retries after an "Out of credits" exec instead of failing fast (billing cascades into "unparseable verdict") #799 doubled-string trap). - AC-6: Auto-waits are bounded: at most 2 per issue, and the cumulative wait respects
autoWaitMinutesas a total budget rather than a per-occurrence allowance. A window still closed on wake must not produce an unbounded pause loop; once the bound or budget is spent, halt with today's labeled message. - AC-7: The wait is visibly live and interruptible: the renderer and heartbeat show the wait and its wake time, and Ctrl-C aborts promptly via the existing shutdown manager rather than blocking until the wake. A multi-hour silent sleep is the feat(run): -q mode silent for entire phase duration — no liveness or stall signal #574 complaint ("no liveness or stall signal") at 60x the scale. Reuse the injected
delayFn(phase-executor.ts:872) so the wait stays test-injectable. - AC-8:
isBillingOrWindowHalt(batch-executor.ts:474) no longer halts the-Qloop for a window-exhausted rate limit that auto-wait handled — otherwise the phase waits, succeeds, and the outer loop halts anyway. Billing and window must be separable at this predicate, with current behavior preserved whenever auto-wait did not fire (default, budget exhausted, or bound hit). - AC-9: Tests cover the budget boundary (reset just inside vs just outside
autoWaitMinutes),BillingErrornever waiting, missing-resetsAttaking the transient path, the wake buffer, the re-wait bound, the total budget honored across two waits, anddelayFncalled with the computed duration (mirror the existing assertions atphase-executor.test.ts:888,920). - AC-10: Documented in all three locations — main
README.md, the marketplace README, anddocs/— stating the default (off), the account-wide-limit rationale for holding locks during the wait, and the in-process limitation that the wait does not survive closing the terminal.
Notes for the implementer
- validate(#761 AC-9): confirm real window-exhaustion rejections carry rateLimitType/resetsAt (post-hoc capture) #782 is load-bearing. It validates whether real window-exhaustion rejections actually arrive with
resetsAtpopulated. If they usually land on the assistant-error channel instead, auto-wait fires rarely and AC-4's fall-through is the common path rather than the edge case. Do not build on mockedrate_limit_eventpayloads alone. - The sleep belongs between phase attempts in
executePhaseWithRetry, not inside a phase spawn, sophaseTimeoutis not implicated. Confirm the heartbeat and stall detection agree.
Out of scope
- Durable out-of-process resume (persist a wake time, exit cleanly, let cron/launchd/a supervisor re-enter). This is the robustness follow-up and carries its own surface: cross-platform scheduling, a paused lock state, and unattended-safety review for commits/pushes/PRs landing with nobody watching. File separately once auto-wait has real usage behind it.
- Waiting on billing / out-of-credits failures (AC-4).
- Token budgeting, or staggering wake times across several halted runs.
References
- feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761 — window-exhaustion classification; listed limit-window scheduling as out of scope
- fix(run): -Q quality loop retries after an "Out of credits" exec instead of failing fast (billing cascades into "unparseable verdict") #799 / fix(#799): fail-fast the -Q quality loop on billing / rate-limit-window failures #800 —
-Qfail-fast on billing / window failures (isBillingOrWindowHalt) - feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732 — structured SDK rate-limit signals (
RateLimitError/RateLimitMetadata) - feat(run): -q mode silent for entire phase duration — no liveness or stall signal #574 — prior art on silent phases lacking a liveness signal (AC-7)
Activity
admarble commentedon Jul 26, 2026
Field evidence for this from session-history mining (2026-07-26):
On 2026-07-18 at 16:05 UTC, a batch run of #783 + #784 spawned eight phase-executor sessions in the same minute — four identical
/spec 783and four identical/spec 784, every transcript exactly 16,998 bytes. Each one ends with the same assistant message:So the cold-start retry ladder burned its full retry budget per issue into an already-exhausted rate-limit window, duplicating spec spawns 4× with zero chance of success — exactly the class
--auto-waitaddresses (wait for the stated reset instead of retrying/halting).Two notes:
PhaseResult.erroralready formatting the reset timestamp — so--auto-waithas the data it needs without new plumbing.Transcript IDs for reference (local
~/.claude/projects/-Users-tony-Projects-sequant/): 573ffc3b, 2161f81d, 426e570c, 62047a32 (#783); 1078e8a4, a0bc628a, 5ef2826a, c8d9e0c1 (#784).admarble commentedon Jul 27, 2026
#804 — feat(run): --auto-wait — continue a rate-limited run when the window resets instead of halting
Open · no labels
────────────────────────────────────────────────────────────────
→ PROCEED — Blocker #782 closed COMPLETED (validation READY_FOR_MERGE); design settled, codebase matches
Commands:
sequant run 804 -Q
spec → exec → qa · 10 ACs
Flags:
-Q 10 ACs across bin/cli.ts, workflow/types.ts, settings.ts, phase-executor, batch-executor
────────────────────────────────────────────────────────────────
⚠ Body still says "Blocked by #782" — #782 closed COMPLETED (validation READY_FOR_MERGE), blocker cleared
⚠ 10 ACs across cli.ts, types.ts, settings.ts, phase-executor, batch-executor — largest scope in batch
⚠ No labels — suggest
gh issue edit 804 --add-label enhancement,cli(siblings #817/#818 carry both)────────────────────────────────────────────────────────────────
admarble commentedon Jul 27, 2026
Plan (
/spec) — #804--auto-waitComplexity: Complex (10 ACs, ~7 directories)
Blocker #782 is closed (PR #805). Its finding is load-bearing and confirms AC-4's design: the real 2026-07-18 capture carries
resetsAt: 1784392200+rateLimitType: "five_hour"on aBillingError(overageDisabledReason: "out_of_credits"). SoresetsAtis present on the structured channel — auto-wait can compute a real wake target — but gating on "hasresetsAt" would wait on an unwaitable credits failure. Gate onerror instanceof RateLimitError, exactly as AC-4 says.AC Quality Check
✅ All 10 AC parse cleanly and are testable. Two corrections to statements in the issue body, both found by reading the code rather than assumed:
The Proposal's env claim is wrong. "Env: resolved for free by
ConfigResolver… including numeric coercion viacoerceEnvValue" —resolveRunOptions(src/lib/workflow/config-resolver.ts:155) does not use theConfigResolverclass. It uses??chains plusgetEnvConfig()(batch-executor.ts:334), which reads a hardcoded list of env vars.SEQUANT_AUTO_WAIT_MINUTESneeds ~5 explicit lines there. Not an AC requirement (AC-1 doesn't list env), but the issue advertises it — see Open Question 1.AC-8's stated failure mode cannot occur. AC-8 says "otherwise the phase waits, succeeds, and the outer loop halts anyway." All four
isBillingOrWindowHaltcall sites (batch-executor.ts:681, 995, 1110, and the:474definition) sit insideelsebranches ofif (result.success). A phase that auto-waits and then succeeds never reaches the predicate. The AC's requirement (billing/window separable, current behavior preserved when auto-wait did not fire) is still worth implementing and pinning — see AC-8 below. Flagging rather than quietly "satisfying" it.Scope Assessment
Non-Goals (from issue): durable out-of-process resume; waiting on billing/out-of-credits; token budgeting / staggered wakes.
Tool verdict: ❌ SCOPE_SPLIT_RECOMMENDED (suggested splits:
test= AC-2/6/9,error= AC-3/4/8,ui= AC-5/7).Assessment: do not split — the suggested split is an artifact of keyword clustering. These are not four features; they are one flag, one decision site, and its tests/docs. You cannot ship "the error part" of a flag without the flag, and AC-2 (the regression contract) is meaningless split away from the behavior it constrains. The metrics are still a real signal about size, so: quality loop enabled, and the plan front-loads the one genuinely underestimated area (AC-7, below).
Acceptance Criteria
AC-1:
--auto-wait <minutes>end-to-end, default0Verification: Integration Test
Scenario: Given
sequant run 42 --auto-wait 90→ When options resolve → ThenExecutionConfig.autoWaitMinutes === 90; omitted →0.Sites:
bin/cli.ts.option("--auto-wait <minutes>", …, parseInt)on theruncommand ·RunOptions(workflow/types.ts:292) ·ExecutionConfig+DEFAULT_CONFIG(:187, addautoWaitMinutes: 0) ·RunSettings(settings.ts:83) +RunSettingsSchema(:312,z.number().default(0)) · resolution inresolveRunOptions/buildExecutionConfig. Notlib/config.ts.AC-2: Default
0⇒ byte-for-byte unchanged (regression contract)Verification: Unit Test (existing, unmodified)
Scenario: Given
baseConfigwith noautoWaitMinutes→ When the window-exhaustion tests atphase-executor.test.ts:771/:806and the halt test atbatch-executor.test.ts:807run → Then they pass with zero edits.Hard constraint this imposes: those tests call
executePhaseWithRetry(...)positionally withexecutePhaseFnas arg 8 anddelayFnas arg 9. Any new parameter must land at position 10 or later. This is the single biggest implementation trap in the change.AC-3: Budget is a separate decision from the classifier
Verification: Unit Test
Scenario: Given a window-exhausted
RateLimitError→ When deciding → ThenRATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS(:139) andisWindowExhaustedRateLimit(:161) are untouched, and a new internalshouldAutoWaitForReset(error, budgetMs, now)fires only whenisWindowExhaustedRateLimitis already true.autoWaitMinutesstays the only user-facing dial.AC-4:
RateLimitErroronly — neverBillingError, never missing-resetsAtVerification: Unit Test
Scenario: Given the real #782 capture (
BillingError,resetsAtpresent,out_of_credits) → When the ladder runs with--auto-wait 600→ ThendelayFnis never called for a wait and today's halt happens. Given aRateLimitErrorwith noresetsAt→ Then the existing transient backoff path runs (#761 AC-9), not a wait.Note: reuse the committed capture at
docs/incidents/782/captures/— #782's tests already read it, so the fixture cannot drift.AC-5: Wake at
resetsAtToMs(resetsAt) + ~60s, epoch-ms arithmetic onlyVerification: Unit Test
Scenario: Given
resetsAtin seconds (1784392200, the real capture's unit) → When computing the wait → ThenresetsAtToMs()normalizes first, buffer added after, and the delay iswakeMs - now. Display reusesformatRateLimitMessage; never re-appendresetsAtto an already-formatted message (the #799 doubled-string trap, documented atbatch-executor.ts:491).AC-6: Bounded — max 2 waits per issue,
autoWaitMinutesas a total budgetVerification: Unit Test
Scenario: Given
--auto-wait 60and two successive window rejections 25 min out → When both waits fire → Then the second is granted only ifspent + needed <= 60min; a third rejection halts. Given a window still closed on wake → Then no unbounded re-pause.Design: a small mutable
AutoWaitLedger { waits, spentMs, budgetMs }created once per issue inrunIssueWithLoggingand threaded to all threeexecutePhaseWithRetrycall sites (:629spec,:945main,:1148loop). Per-issue is only achievable at that level — the ledger cannot live insideexecutePhaseWithRetry, which is per-phase.AC-7: Visibly live and interruptible
Verification: Unit Test (+ Manual smoke)
⚠️ This is the largest and most understated AC. Both display paths currently drop the only sub-phase channel that exists:
Scenario: Given an active wait → When 15s elapse → Then the display shows the wait and its wake time. When Ctrl-C → Then the run aborts promptly, not at wake.
run-progress.ts:107— renderer path:if (event === "activity") return;run-progress.ts:121— heartbeat path: same.So
config.onActivityreaches neither. Real work needed:PhaseState.status: "waiting"+ wake time, plumbedProgressCallback→run-progress.ts→renderer.onEvent→ live-zone status cell (run-renderer-types.ts:8,27).LivenessHeartbeatstall detection is mtime-based on.sequant/state.json. A multi-hour wait produces no mtime change, so today it would fire a false stall warning during an entirely expected pause. Needs a wait-aware pause API that both relabels the line and suppresses the stall warning. This is precisely what the issue's implementer note ("confirm the heartbeat and stall detection agree") is pointing at.AbortControllerwithShutdownManager(shutdown.ts:107addAbortController— it aborts all registered controllers on SIGINT), then sleep in ~15s ticks via the injecteddelayFn(AC-7 requires reuse for test-injectability), racing each tick against abort. Ticks double as the display refresh. Residual: the final in-flight ≤15s timer cannot be cleared (the injecteddelayFnexposes no handle);ShutdownManager's 10s force-exit covers it.AC-8:
isBillingOrWindowHaltseparable; behavior preserved when auto-wait did not fireVerification: Unit Test
Scenario: Given auto-wait fired and the retry succeeded → Then no halt (pin the short-circuit explicitly rather than assuming it). Given default / budget spent / bound hit → Then today's halt and today's
billingHaltReasonmessage, unchanged.Approach: split
:474intoisBillingHalt+isWindowHaltwithisBillingOrWindowHaltretained as their union, so the two are separable at the predicate per the AC's literal text — while stating plainly in QA that no behavioral change was required, with the four call-site line numbers as evidence.AC-9: Test matrix
Verification: Unit Test — budget boundary (reset just inside vs just outside),
BillingErrornever waits, missing-resetsAt→ transient path, wake buffer, re-wait bound, total budget across two waits,delayFncalled with the computed duration (mirroringphase-executor.test.ts:888,920).AC-10: Docs in all three locations
Verification: Manual Test — (1) main
README.md; (2) marketplace README = theREADME_CONTENTtemplate literal inscripts/prepare-marketplace.ts:287(thedist/marketplace/**copy is generated and gitignored — editing it is a no-op); (3)docs/—docs/reference/run-command.md:59(flag table) and:202, the paragraph that currently states the halt-on-window behavior this change makes conditional. Must state: default off · account-wide-limit rationale for holding locks during the wait · in-process limitation (does not survive closing the terminal).Implementation Plan
Phase 1 — Config plumbing (AC-1)
bin/cli.ts.option("--auto-wait <minutes>", …, parseInt);RunOptions.autoWaitMinutes?;ExecutionConfig.autoWaitMinutes+DEFAULT_CONFIG: 0;RunSettings.autoWaitMinutes+ schema.default(0); wire throughresolveRunOptions+buildExecutionConfig; addSEQUANT_AUTO_WAIT_MINUTEStogetEnvConfig()(Open Question 1).Phase 2 — Decision + wait mechanics (AC-3, AC-4, AC-5, AC-6)
shouldAutoWaitForReset(error, budgetMs, now)inphase-executor.ts— guarded byisWindowExhaustedRateLimit,instanceof RateLimitError,typeof resetsAt === "number". Leave:139/:161untouched.AutoWaitLedger+waitForWindowReset(waitMs, {delayFn, signal, onTick}), ticked at 15s, abort-raced.phase-executor.ts:965), beforereturn lastResult. On a granted wait, do not consume a cold-start attempt (decrementattemptbeforecontinue) — a wait is not a cold-start retry; the ledger bound is what makes that safe from looping.runIssueWithLoggingto all three call sites — as parameter 10+ (AC-2 constraint).Phase 3 — Liveness (AC-7)
waitingstatus + wake time throughrun-progress.ts;LivenessHeartbeatwait-aware pause that suppresses the false stall warning;AbortControllerregistered withShutdownManager.Phase 4 — Predicate + tests + docs (AC-8, AC-9, AC-10)
isBillingHalt/isWindowHalt; add the "auto-wait success ⇒ no halt" pin.phase-executor.test.ts/batch-executor.test.tsunmodified as the AC-2 gate.Rule Touchpoints
The behavior-rule detector fired on AC-1, AC-2, AC-8. Curated to the sites that actually matter (raw output was keyword noise):
src/lib/workflow/batch-executor.ts:474export function isBillingOrWindowHalt(result: PhaseResult): boolean {src/lib/workflow/batch-executor.ts:681: isBillingOrWindowHalt(specResult)— spec pathsrc/lib/workflow/batch-executor.ts:995: isBillingOrWindowHalt(result)— progress labelsrc/lib/workflow/batch-executor.ts:1110if (isBillingOrWindowHalt(result)) { haltedByBilling = true; }bin/cli.tsrun.option()chainscripts/prepare-marketplace.ts:287const README_CONTENT = ...— the real marketplace README sourceDesign Review
phase-executor.ts, at the existing window-exhaustion branch — the one place that already owns "transient or exhausted?". The ledger belongs one level up inbatch-executor'srunIssueWithLogging, because "per issue" is only expressible there.:981-996) — same injecteddelayFn, samebracketedConsoleLognotice, samecontinue. Auto-wait is a direct generalization of it.setTimeout. (c) "Does the stall warning fire during the wait?" — it would today; AC-7 fixes it.Feature Quality Planning
loop-phase gap: theskipColdStartRetrybranch (:905-930, used byloop, registeredmaxRetries: 0) has no window-exhaustion check today, so auto-wait would not cover it. See Open Question 2.feedback_synthetic_test_fixture_trap.Open Questions
SEQUANT_AUTO_WAIT_MINUTEStogetEnvConfig()? — Recommendation: yes (~5 lines). The issue advertises env support as free; it is not. Impact if skipped: the documented env layer silently does not exist. Not AC-required, so it is called out rather than assumed.loopphase (skipColdStartRetrybranch)? — Recommendation: yes, symmetric ~6 lines, and the per-issue ledger already bounds it. Impact if skipped: a window limit hitting/loopstill hard-halts even with--auto-waitset, which reads as a bug. Flagged rather than silently widened — say the word if you want it deferred.Recommended Workflow
Phases: spec → exec → qa · Quality Loop: enabled (scope metrics red)
Reasoning: No
ui/frontend/adminlabels and the change is CLI/runtime only → no/testphase.testgendeliberately skipped (overriding the "unit-test ACs ⇒ testgen" default, documented per the skill's override rule): AC-9's tests must be added to existing suites (phase-executor.test.ts,batch-executor.test.ts) alongside the AC-2 tests that must stay unmodified. Generated stubs in new files would fight that contract and leave untracked stubs to clean up.Label Review
Current: none · Recommended:
enhancement,no-browser-testReason: No UI surface;
no-browser-testmakes the/testskip explicit rather than incidental.enhancementmatches thefeat(run):title.admarble commentedon Jul 27, 2026
QA Review for Issue #804
Reviewed at:
13aa6ff· PR #825 · CI 5/5 pass · branch 0 commits behindorigin/mainQuality checks were run inline rather than via sub-agents (operator instruction for this session). Given
feedback_qa_agent_worktree_verification, inline review is also the more accurate mode on worktree code.AC Coverage
bin/cli.ts;RunOptions/ExecutionConfig/DEFAULT_CONFIGinworkflow/types.ts;run.autoWaitMinutesonRunSettings+RunSettingsSchema; reachesphase-executor. Default0.lib/config.tsuntouched. Traced end-to-end — a bug here was caught during this QA, see belowgit diffis empty onphase-executor.test.tsandbatch-executor.test.ts; their 201 tests pass unmodified. The regression contract is demonstrated, not assertedRATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS(:139) andisWindowExhaustedRateLimit(:161) unchanged.shouldAutoWaitForResetis a separate internal decision, guarded so it fires only once the classifier is already trueinstanceof RateLimitError;BillingErroris a sibling ofRateLimitError, not a subclass (verified inerrors.ts:207/227), so the exclusion is structural. Pinned against the real #782 capture and its counterfactual. Missing-resetsAtfalls to transient backoff — asserted as[5000, 10000], the actual ladder delaysresetsAtToMs()then+60s, all epoch ms; seconds-unit test uses the real capture's unit. Display reusesformatRateLimitMessage/formatResetTime; explicit assertion that the message does not match/resets at .*resets at/(#799 trap)runIssueWithLogging, since a per-phase ledger would grant every phase its own budget. Boundary tests at just-inside/just-outside, plus bound and cross-wait-budgetwaiting <wake>phase cell; heartbeat reports the wait instead of a false stall; Ctrl-C aborts viaShutdownManager-registeredAbortController; 15s ticks double as refresh. Now covered byauto-wait-display.test.tsisBillingHalt/isWindowHalt. No behavioral change was required — see finding 4auto-wait.test.ts, 7 inauto-wait-display.test.ts— every listed case plus the wake buffer anddelayFndurationREADME.md; marketplace README (scripts/prepare-marketplace.tsREADME_CONTENT— thedist/marketplace/**copy is generated and gitignored, so editing it would be a no-op);docs/reference/run-command.md(flag table, settings block, new section) +cheat-sheet.md;CHANGELOG.md. All three state the default, the account-wide-lock rationale, and the in-process limitationCoverage: 10/10 MET.
Findings
1.
--auto-waitwas inert (fixed,13aa6ff). Commander derives the option key from the flag name, so--auto-wait <minutes>arrives asoptions.autoWait, whileresolveRunOptionsreaddefined.autoWaitMinutes. The flag parsed, appeared in--help, and did nothing — the #305 failure mode, which AC-1's "end-to-end" wording exists to prevent.The first pass verified
npx tsx bin/cli.ts run --helpand treated the flag as wired. That proves only that it parses. The defect surfaced from §2h's CLI-registration check, then confirmed by probing Commander directly and tracing Commander's key shape throughresolveRunOptionstoExecutionConfig. Fixed innormalizeCommanderOptions— the CLI-boundary adapter that already exists for--no-Xmismatches — guarded on!== undefinedso an explicit--auto-wait 0still overrides a non-zero setting.2. Wait loop busy-spun against the wall clock (fixed).
waitForWindowResetrecomputed remaining time fromnow()each iteration. With an injecteddelayFnthat resolves instantly — i.e. every test — it spun until real time reached the deadline: one test run took 8195 seconds. Now driven by slice accounting, with the clock only able to shorten the wait (a laptop resumed from sleep).3. Abort-listener leak (fixed).
Promise.raceregistered a newabortlistener per tick — ~1200 listeners and as many pending promises on a single signal for a 5-hour wait. One listener now covers the whole wait; pinned by a test asserting exactly 1 registration across 100 ticks.4. AC-8's premise does not hold — reported, not papered over. AC-8 says "otherwise the phase waits, succeeds, and the outer loop halts anyway." It cannot: all four
isBillingOrWindowHaltcall sites (batch-executor.ts:474definition;:681spec,:995progress label,:1110halt flag) sit insideelsebranches ofif (result.success), so a successful post-wait result never reaches the predicate. The separability refactor the AC requires is done, and the short-circuit is pinned by test rather than assumed — but no behavioral change was needed, and claiming one would be false.5. Type assertions removed. The first pass had
(error as RateLimitError).metadata.resetsAt as numberin the decision function andas RateLimitErrorat both call sites. Replaced with real narrowing;shouldAutoWaitForResetnow returns the narrowed error in anAutoWaitDecision. A silent cast in the one function that decides whether to pause a run for hours is not worth the two saved lines.Scope decisions surfaced (not silently taken)
loop-phase coverage. TheskipColdStartRetryarm (maxRetries: 0, used byloop) had no window-exhaustion handling at all, so--auto-waitwould have silently skipped it. Raised as an open question in the plan and defaulted to including it — a flag that doesn't cover a phase reads as a bug.ConfigResolverwithcoerceEnvValue. It does not:resolveRunOptionsuses??chains plusgetEnvConfig()'s hardcoded list.SEQUANT_AUTO_WAIT_MINUTESis wired explicitly; non-numeric and negative values are ignored so a typo can't enable an unbounded wait.Quality Metrics
any) in added linesTest Coverage
workflow/phase-executor.tsauto-wait.test.ts(39)workflow/batch-executor.tsbatch-executor.test.ts+auto-wait.test.tsworkflow/config-resolver.tsauto-wait.test.ts(incl. the Commander-key regression)workflow/heartbeat.tsheartbeat.test.ts+auto-wait-display.test.tscli-ui/run-renderer.tsrun-renderer*.test.ts+auto-wait-display.test.tscommands/run-progress.tsrun-progress.test.ts—waitingrouting branch is not directly coveredworkflow/run-orchestrator.tswaitingbranch not directly coveredcommands/ready-tui-adapter.tsready-tui-adapter.test.ts— new case shares theactivitybodyerrors.ts,settings.ts,types.ts,bin/cli.tsFull suite: 200 files, 4178 passed, 1 expected fail, 2 skipped.
Risk Assessment
waiting-routing branches (run-progress.ts,run-orchestrator.ts). A regression there would strand awaitingcell or drop the liveness signal — cosmetic, not correctness, and the state machine underneath is tested. The genuinely dangerous paths (decide-to-wait, budget, abort) are covered.delayFnthroughout. The final in-flight ≤15s timer cannot be cleared on abort (the injecteddelayFnexposes no handle);ShutdownManager's 10s force-exit covers it, and this is documented at the call site.isWindowExhaustedRateLimithas exactly two consumers —phase-executor's ladder andbatch-executor's halt predicate. Both were reviewed; the second needed no change (finding 4). No third consumer exists.skipColdStartRetryarm was audited, found to have the same gap, and fixed — that is theloop-phase item above.Adversarial Re-Read
Findings: Re-read the decision path and both ladder arms after the structured pass. Surfaced findings 1, 2, 3 and 5 above — finding 1 in particular is the class the pipeline is meant to catch and the first pass had wrongly cleared. Verified: no Non-Goal has crept into scope (no durable out-of-process resume, no billing wait, no token budgeting, no wake staggering); the
attempt--in the cold-start arm cannot loop unbounded becauseAUTO_WAIT_MAX_WAITSbounds grants; thefor(;;)in theskipColdStartRetryarm is bounded by the same counter, whichperformAutoWaitincrements before sleeping so an exception on the sleep path cannot hand back a free retry; heartbeat suppression is confirmed non-sticky, so auto-wait cannot permanently disable the #574 alarm.Status: Gaps Found — the two uncovered display-routing branches noted above. All are non-blocking and named rather than waved off.
Out-of-scope observation (not fixed here)
scripts/new-feature.shstill usesnpm install --silentat three sites (lines 203/210/219). #816 switched the TypeScript worktree-manager path to frozen installs, but not this shell script — this worktree's provisioning dirtiedpackage-lock.jsonby strippinglibcfields, the exact #816 signature. Reverted locally and not included in this PR. Worth its own issue; deliberately not widened into #804.Verdict: AC_MET_BUT_NOT_A_PLUS
All 10 ACs are MET, CI is green, and the three defects found during QA are fixed and regression-pinned. Held back from
READY_FOR_MERGEon the adversarial re-read's "Gaps Found" status: twowaiting-routing branches ship without direct tests. That is a deliberate, disclosed gap rather than a discovered one — but the gate is the gate, and given this QA already caught an inert flag that a--helpcheck had cleared, understating residual risk would be the wrong call.Ready for human review and merge at your discretion — the uncovered branches are display-only.
PR: #825
test(#804): cover the two waiting-routing branches QA flagged as unte…
admarble commentedon Jul 27, 2026
QA Addendum — gaps closed (#804)
Reviewed at:
ae631a7· PR #825 · CI 5/5 pass · Verdict upgraded: AC_MET_BUT_NOT_A_PLUS → READY_FOR_MERGEThe prior pass held at
AC_MET_BUT_NOT_A_PLUSsolely on the adversarial re-read's "Gaps Found" — twowaiting-routing branches shipping without direct tests. Both are now covered, and closing them corrected a claim I made in that review.I understated the orchestrator gap
I called both branches "display-only". That was wrong for
run-orchestrator.ts.applyProgressEventhandleswaitingbefore the complete/failed fall-through. If that ordering regresses, the fall-through runsp.status = event === "complete" ? "done" : "failed"and emitsphase_failed— so a phase merely paused on a rate-limit window is reported as a failure, andpipelineHasFailedcan then mark the whole issue failed. That is a correctness defect on the MCP/TUI path, not cosmetics. Calling it cosmetic was the kind of rounding-down that the gate exists to prevent.Coverage added
auto-wait-routing.test.ts(new, 6 tests) — orchestrator: phase staysrunning; nophase_failed/phase_completed; wait text reachesnowLine; forwards to an externalonProgress; a late notice for a non-current phase is ignored; normal completion still works afterwards.run-progress.test.ts(+4 tests) — renderer branch forwardswaitingboth with and withoutwakeAtMs(its absence is the clear-state signal); heartbeat branch callspauseForWait/resumeFromWaitand, load-bearingly, does not callstop()— which would delete the phase entry and leave a multi-hour wait with no liveness signal at all.RunOrchestrator.getProgressCallback()is a new@internalaccessor.applyProgressEventis private and depends onissueStates/phaseStartTimes/emitter, so without a seam the branch is unreachable short of a fullrun().Both guards mutation-tested, not assumed
waitingbranchwaitinghandlerThis mattered: my first draft of the orchestrator tests was tautological.
WorkflowEventEmitter.emitdispatches throughPromise.allSettled, so listeners run on a later tick and everynot.toHaveBeenCalled()passed regardless of the branch's presence — including the one assertion the whole test existed for. Adding an explicit flush is what made the mutation run meaningful. Worth recording, because a green tautological test here would have read exactly like closed coverage.Updated metrics
phase-executor.test.ts,batch-executor.test.tsuntouched across all three commitsRe-run gate statuses
Out-of-scope item now handled separately
The
scripts/new-feature.shlockfile bug I flagged is filed as #826 and fixed in PR #827 — deliberately not folded into this PR. It reproduced live while provisioning the #826 worktree, and the fix is verified by an A/B execution (npm install→ 1 dirty file / 12 deletions;npm ci→ 0 dirty files) plus an exercised failure path, rather than by inspection.Verdict: READY_FOR_MERGE
10/10 ACs MET, all gates clean, CI green, both new guards mutation-verified.
fix(#817): close the AC-3 wiring guard and stop a crashed ready gate …
feat(#817): --ready-gate — run the post-QA ready gate inside `sequant…
fix(#860): classify live five-hour windows as waitable, not terminal …
docs: 2.10 release-notes section + coverage gaps found by release audit
fix(ready-gate): collapse the second ExecutionConfig producer so driv…
fix(#817): close the AC-3 wiring guard and stop a crashed ready gate …