Skip to content

feat(run): --auto-wait — continue a rate-limited run when the window resets instead of halting #804

Closed

Description

@admarble

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> on sequant run
  • Setting: run.autoWaitMinutes
  • Env: resolved for free by ConfigResolver (defaults < settings < env < explicit), including numeric coercion via coerceEnvValue

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() in bin/cli.ts (without it the flag silently does not exist), RunOptions + ExecutionConfig + DEFAULT_CONFIG in workflow/types.ts, run.autoWaitMinutes on RunSettings and RunSettingsSchema (settings.ts:275,314), reaching the decision site in phase-executor.ts. Default 0. Not in lib/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:771 and :806) pass unmodified, as do the -Q halt 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) and isWindowExhaustedRateLimit (: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 when isWindowExhaustedRateLimit is already true, keeping autoWaitMinutes the only user-facing dial for the wait-vs-halt outcome.
  • AC-4: Auto-wait fires for RateLimitError only. A BillingError (out of credits) must never wait — it carries no resetsAt by design because credits are purchased, not waited out, so a wait would hang on a condition that cannot self-heal. A rate limit with no resetsAt (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 at resetsAt — 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, reusing formatRateLimitMessage; do not re-derive or re-append resetsAt onto 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 autoWaitMinutes as 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 -Q loop 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), BillingError never waiting, missing-resetsAt taking the transient path, the wake buffer, the re-wait bound, the total budget honored across two waits, and delayFn called with the computed duration (mirror the existing assertions at phase-executor.test.ts:888,920).
  • AC-10: Documented in all three locations — main README.md, the marketplace README, and docs/ — 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 resetsAt populated. 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 mocked rate_limit_event payloads alone.
  • The sleep belongs between phase attempts in executePhaseWithRetry, not inside a phase spawn, so phaseTimeout is 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

Activity

  1. admarble commented on Jul 26, 2026

    @admarble
    ContributorAuthor

    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 783 and four identical /spec 784, every transcript exactly 16,998 bytes. Each one ends with the same assistant message:

    You've hit your session limit · resets 11:30am (America/Chicago)

    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-wait addresses (wait for the stated reset instead of retrying/halting).

    Two notes:

    1. This incident predates the feat: detect rate-limit failures mid-chain and halt cleanly instead of timeout-cascading #761/fix(run): -Q quality loop retries after an "Out of credits" exec instead of failing fast (billing cascades into "unparseable verdict") #799 fixes (merged Jul 17–24), so the fail-fast half may already be covered — but it's worth confirming the phase retry ladder (not just the -Q quality loop, which is what fix(run): -Q quality loop retries after an "Out of credits" exec instead of failing fast (billing cascades into "unparseable verdict") #799 fixed) now classifies session-limit rejections as non-retryable. If it still retries them as cold-start failures, that's a residual Quality loop retries misclassified as cold-start failures, wasting retry budget #488-class gap.
    2. The transcripts carry the reset time in the error surface, consistent with PhaseResult.error already formatting the reset timestamp — so --auto-wait has 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).

  2. admarble commented on Jul 27, 2026

    @admarble
    ContributorAuthor

    #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)
    ────────────────────────────────────────────────────────────────

  3. admarble commented on Jul 27, 2026

    @admarble
    ContributorAuthor

    Plan (/spec) — #804 --auto-wait

    Complexity: 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 a BillingError (overageDisabledReason: "out_of_credits"). So resetsAt is present on the structured channel — auto-wait can compute a real wake target — but gating on "has resetsAt" would wait on an unwaitable credits failure. Gate on error 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:

    1. The Proposal's env claim is wrong. "Env: resolved for free by ConfigResolver … including numeric coercion via coerceEnvValue" — resolveRunOptions (src/lib/workflow/config-resolver.ts:155) does not use the ConfigResolver class. It uses ?? chains plus getEnvConfig() (batch-executor.ts:334), which reads a hardcoded list of env vars. SEQUANT_AUTO_WAIT_MINUTES needs ~5 explicit lines there. Not an AC requirement (AC-1 doesn't list env), but the issue advertises it — see Open Question 1.

    2. AC-8's stated failure mode cannot occur. AC-8 says "otherwise the phase waits, succeeds, and the outer loop halts anyway." All four isBillingOrWindowHalt call sites (batch-executor.ts:681, 995, 1110, and the :474 definition) sit inside else branches of if (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.

    Metric Value Status
    Feature count 4 ❌
    AC items 10 ❌
    Directory spread 7 ❌

    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, default 0

    Verification: Integration Test
    Scenario: Given sequant run 42 --auto-wait 90 → When options resolve → Then ExecutionConfig.autoWaitMinutes === 90; omitted → 0.
    Sites: bin/cli.ts .option("--auto-wait <minutes>", …, parseInt) on the run command · RunOptions (workflow/types.ts:292) · ExecutionConfig + DEFAULT_CONFIG (:187, add autoWaitMinutes: 0) · RunSettings (settings.ts:83) + RunSettingsSchema (:312, z.number().default(0)) · resolution in resolveRunOptions/buildExecutionConfig. Not lib/config.ts.

    AC-2: Default 0 ⇒ byte-for-byte unchanged (regression contract)

    Verification: Unit Test (existing, unmodified)
    Scenario: Given baseConfig with no autoWaitMinutes → When the window-exhaustion tests at phase-executor.test.ts:771/:806 and the halt test at batch-executor.test.ts:807 run → Then they pass with zero edits.
    Hard constraint this imposes: those tests call executePhaseWithRetry(...) positionally with executePhaseFn as arg 8 and delayFn as 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 → Then RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS (:139) and isWindowExhaustedRateLimit (:161) are untouched, and a new internal shouldAutoWaitForReset(error, budgetMs, now) fires only when isWindowExhaustedRateLimit is already true. autoWaitMinutes stays the only user-facing dial.

    AC-4: RateLimitError only — never BillingError, never missing-resetsAt

    Verification: Unit Test
    Scenario: Given the real #782 capture (BillingError, resetsAt present, out_of_credits) → When the ladder runs with --auto-wait 600 → Then delayFn is never called for a wait and today's halt happens. Given a RateLimitError with no resetsAt → 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 only

    Verification: Unit Test
    Scenario: Given resetsAt in seconds (1784392200, the real capture's unit) → When computing the wait → Then resetsAtToMs() normalizes first, buffer added after, and the delay is wakeMs - now. Display reuses formatRateLimitMessage; never re-append resetsAt to an already-formatted message (the #799 doubled-string trap, documented at batch-executor.ts:491).

    AC-6: Bounded — max 2 waits per issue, autoWaitMinutes as a total budget

    Verification: Unit Test
    Scenario: Given --auto-wait 60 and two successive window rejections 25 min out → When both waits fire → Then the second is granted only if spent + 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 in runIssueWithLogging and threaded to all three executePhaseWithRetry call sites (:629 spec, :945 main, :1148 loop). Per-issue is only achievable at that level — the ledger cannot live inside executePhaseWithRetry, which is per-phase.

    AC-7: Visibly live and interruptible

    Verification: Unit Test (+ Manual smoke)
    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.
    ⚠️ This is the largest and most understated AC. Both display paths currently drop the only sub-phase channel that exists:

    • run-progress.ts:107 — renderer path: if (event === "activity") return;
    • run-progress.ts:121 — heartbeat path: same.

    So config.onActivity reaches neither. Real work needed:

    • Renderer: new event kind / PhaseState.status: "waiting" + wake time, plumbed ProgressCallback → run-progress.ts → renderer.onEvent → live-zone status cell (run-renderer-types.ts:8,27).
    • Heartbeat: LivenessHeartbeat stall 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.
    • Interruptibility: register an AbortController with ShutdownManager (shutdown.ts:107 addAbortController — it aborts all registered controllers on SIGINT), then sleep in ~15s ticks via the injected delayFn (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 injected delayFn exposes no handle); ShutdownManager's 10s force-exit covers it.

    AC-8: isBillingOrWindowHalt separable; behavior preserved when auto-wait did not fire

    Verification: 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 billingHaltReason message, unchanged.
    Approach: split :474 into isBillingHalt + isWindowHalt with isBillingOrWindowHalt retained 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), BillingError never waits, missing-resetsAt → transient path, wake buffer, re-wait bound, total budget across two waits, delayFn called with the computed duration (mirroring phase-executor.test.ts:888,920).

    AC-10: Docs in all three locations

    Verification: Manual Test — (1) main README.md; (2) marketplace README = the README_CONTENT template literal in scripts/prepare-marketplace.ts:287 (the dist/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)

    1. bin/cli.ts .option("--auto-wait <minutes>", …, parseInt); RunOptions.autoWaitMinutes?; ExecutionConfig.autoWaitMinutes + DEFAULT_CONFIG: 0; RunSettings.autoWaitMinutes + schema .default(0); wire through resolveRunOptions + buildExecutionConfig; add SEQUANT_AUTO_WAIT_MINUTES to getEnvConfig() (Open Question 1).

    Phase 2 — Decision + wait mechanics (AC-3, AC-4, AC-5, AC-6)

    1. shouldAutoWaitForReset(error, budgetMs, now) in phase-executor.ts — guarded by isWindowExhaustedRateLimit, instanceof RateLimitError, typeof resetsAt === "number". Leave :139/:161 untouched.
    2. AutoWaitLedger + waitForWindowReset(waitMs, {delayFn, signal, onTick}), ticked at 15s, abort-raced.
    3. Insert at the existing window-exhaustion branch (phase-executor.ts:965), before return lastResult. On a granted wait, do not consume a cold-start attempt (decrement attempt before continue) — a wait is not a cold-start retry; the ledger bound is what makes that safe from looping.
    4. Thread the ledger from runIssueWithLogging to all three call sites — as parameter 10+ (AC-2 constraint).

    Phase 3 — Liveness (AC-7)

    1. Renderer waiting status + wake time through run-progress.ts; LivenessHeartbeat wait-aware pause that suppresses the false stall warning; AbortController registered with ShutdownManager.

    Phase 4 — Predicate + tests + docs (AC-8, AC-9, AC-10)

    1. Split isBillingHalt/isWindowHalt; add the "auto-wait success ⇒ no halt" pin.
    2. Full AC-9 matrix; re-run phase-executor.test.ts / batch-executor.test.ts unmodified as the AC-2 gate.
    3. Three doc locations.

    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):

    AC Touchpoint Snippet
    AC-8 src/lib/workflow/batch-executor.ts:474 export function isBillingOrWindowHalt(result: PhaseResult): boolean {
    AC-8 src/lib/workflow/batch-executor.ts:681 : isBillingOrWindowHalt(specResult) — spec path
    AC-8 src/lib/workflow/batch-executor.ts:995 : isBillingOrWindowHalt(result) — progress label
    AC-8 src/lib/workflow/batch-executor.ts:1110 if (isBillingOrWindowHalt(result)) { haltedByBilling = true; }
    AC-1 bin/cli.ts run .option() chain flag must exist here or it silently does not exist
    AC-10 scripts/prepare-marketplace.ts:287 const README_CONTENT = ... — the real marketplace README source

    Design Review

    1. Where does this logic belong? phase-executor.ts, at the existing window-exhaustion branch — the one place that already owns "transient or exhausted?". The ledger belongs one level up in batch-executor's runIssueWithLogging, because "per issue" is only expressible there.
    2. Simplest correct approach? One number on the config, one predicate, one sleep at an existing branch point. Rejected: a new retry-strategy abstraction (over-general for one branch); repurposing the 5-min threshold (AC-3 forbids it, correctly — "is it transient?" and "will I wait?" are different questions).
    3. Existing pattern followed? The transient-throttle branch immediately below (:981-996) — same injected delayFn, same bracketedConsoleLog notice, same continue. Auto-wait is a direct generalization of it.
    4. What would a senior reviewer challenge? (a) "You hold the worktree lock for five hours?" — yes, justified: the limit is account-wide, so no other run could progress anyway; must be stated in the docs (AC-10). (b) "Does Ctrl-C actually work?" — hence the abort-raced ticks, not a single 5h setTimeout. (c) "Does the stall warning fire during the wait?" — it would today; AC-7 fixes it.

    Feature Quality Planning

    • AC-7 is under-specified relative to its cost. "The renderer and heartbeat show the wait" reads like a one-liner; it is two display subsystems plus a false-stall-warning fix, and it is where this change will actually go over.
    • AC-2 is a signature-stability contract, not just a test run. Adding a positional parameter in the wrong slot breaks it silently-looking (type errors, but the AC reads as "tests pass").
    • loop-phase gap: the skipColdStartRetry branch (:905-930, used by loop, registered maxRetries: 0) has no window-exhaustion check today, so auto-wait would not cover it. See Open Question 2.
    • No new mocks. AC-4's fixture is the committed real capture, per feedback_synthetic_test_fixture_trap.

    Open Questions

    1. Add SEQUANT_AUTO_WAIT_MINUTES to getEnvConfig()? — 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.
    2. Extend auto-wait to the loop phase (skipColdStartRetry branch)? — Recommendation: yes, symmetric ~6 lines, and the per-issue ledger already bounds it. Impact if skipped: a window limit hitting /loop still hard-halts even with --auto-wait set, which reads as a bug. Flagged rather than silently widened — say the word if you want it deferred.
    3. Wait tick = 15s? — Recommendation: 15s. Trade-off is Ctrl-C latency floor vs. display churn; abort-racing means the tick bounds only the dangling-timer window, not the abort itself.

    Recommended Workflow

    Phases: spec → exec → qa · Quality Loop: enabled (scope metrics red)
    Reasoning: No ui/frontend/admin labels and the change is CLI/runtime only → no /test phase.
    testgen deliberately 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-test
    Reason: No UI surface; no-browser-test makes the /test skip explicit rather than incidental. enhancement matches the feat(run): title.

  4. added
    enhancement
    no-browser-test
    on Jul 27, 2026
  5. admarble commented on Jul 27, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #804

    Reviewed at: 13aa6ff · PR #825 · CI 5/5 pass · branch 0 commits behind origin/main

    Quality 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

    AC Status Evidence
    AC-1 MET Flag in bin/cli.ts; RunOptions/ExecutionConfig/DEFAULT_CONFIG in workflow/types.ts; run.autoWaitMinutes on RunSettings+RunSettingsSchema; reaches phase-executor. Default 0. lib/config.ts untouched. Traced end-to-end — a bug here was caught during this QA, see below
    AC-2 MET git diff is empty on phase-executor.test.ts and batch-executor.test.ts; their 201 tests pass unmodified. The regression contract is demonstrated, not asserted
    AC-3 MET RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS (:139) and isWindowExhaustedRateLimit (:161) unchanged. shouldAutoWaitForReset is a separate internal decision, guarded so it fires only once the classifier is already true
    AC-4 MET Gated on instanceof RateLimitError; BillingError is a sibling of RateLimitError, not a subclass (verified in errors.ts:207/227), so the exclusion is structural. Pinned against the real #782 capture and its counterfactual. Missing-resetsAt falls to transient backoff — asserted as [5000, 10000], the actual ladder delays
    AC-5 MET resetsAtToMs() then +60s, all epoch ms; seconds-unit test uses the real capture's unit. Display reuses formatRateLimitMessage/formatResetTime; explicit assertion that the message does not match /resets at .*resets at/ (#799 trap)
    AC-6 MET Max 2 waits/issue; budget is a total — ledger created once per issue in 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-budget
    AC-7 MET waiting <wake> phase cell; heartbeat reports the wait instead of a false stall; Ctrl-C aborts via ShutdownManager-registered AbortController; 15s ticks double as refresh. Now covered by auto-wait-display.test.ts
    AC-8 MET Split into isBillingHalt/isWindowHalt. No behavioral change was required — see finding 4
    AC-9 MET 39 tests in auto-wait.test.ts, 7 in auto-wait-display.test.ts — every listed case plus the wake buffer and delayFn duration
    AC-10 MET Main README.md; marketplace README (scripts/prepare-marketplace.ts README_CONTENT — the dist/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 limitation

    Coverage: 10/10 MET.

    Findings

    1. --auto-wait was inert (fixed, 13aa6ff). Commander derives the option key from the flag name, so --auto-wait <minutes> arrives as options.autoWait, while resolveRunOptions read defined.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 --help and 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 through resolveRunOptions to ExecutionConfig. Fixed in normalizeCommanderOptions — the CLI-boundary adapter that already exists for --no-X mismatches — guarded on !== undefined so an explicit --auto-wait 0 still overrides a non-zero setting.

    2. Wait loop busy-spun against the wall clock (fixed). waitForWindowReset recomputed remaining time from now() each iteration. With an injected delayFn that 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.race registered a new abort listener 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 isBillingOrWindowHalt call sites (batch-executor.ts:474 definition; :681 spec, :995 progress label, :1110 halt flag) sit inside else branches of if (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 number in the decision function and as RateLimitError at both call sites. Replaced with real narrowing; shouldAutoWaitForReset now returns the narrowed error in an AutoWaitDecision. 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. The skipColdStartRetry arm (maxRetries: 0, used by loop) had no window-exhaustion handling at all, so --auto-wait would 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.
    • Env layer. The issue's design note claimed env resolution came free via ConfigResolver with coerceEnvValue. It does not: resolveRunOptions uses ?? chains plus getEnvConfig()'s hardcoded list. SEQUANT_AUTO_WAIT_MINUTES is wired explicitly; non-numeric and negative values are ignored so a typo can't enable an unbounded wait.

    Quality Metrics

    Metric Value Status
    Type issues (any) in added lines 0 OK
    Deleted tests 0 OK
    Files changed 20 (+1 new test file) OK
    Lines +1524 / −35 OK for a 10-AC feature
    Security patterns 0 OK
    Empty catch blocks 0 OK (the 3 empty catches are pre-existing "must never disrupt the run" guards, each commented)
    CI 5/5 pass OK

    Test Coverage

    Changed file Tier Tests
    workflow/phase-executor.ts Critical auto-wait.test.ts (39)
    workflow/batch-executor.ts Critical batch-executor.test.ts + auto-wait.test.ts
    workflow/config-resolver.ts Critical auto-wait.test.ts (incl. the Commander-key regression)
    workflow/heartbeat.ts Standard heartbeat.test.ts + auto-wait-display.test.ts
    cli-ui/run-renderer.ts Standard run-renderer*.test.ts + auto-wait-display.test.ts
    commands/run-progress.ts Standard run-progress.test.ts — ⚠️ the new waiting routing branch is not directly covered
    workflow/run-orchestrator.ts Standard ⚠️ new waiting branch not directly covered
    commands/ready-tui-adapter.ts Standard ready-tui-adapter.test.ts — new case shares the activity body
    errors.ts, settings.ts, types.ts, bin/cli.ts Standard/Optional covered indirectly; types-only changes need none

    Full suite: 200 files, 4178 passed, 1 expected fail, 2 skipped.

    Risk Assessment

    • Likely failure mode: the two uncovered waiting-routing branches (run-progress.ts, run-orchestrator.ts). A regression there would strand a waiting cell 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.
    • Not tested: no end-to-end test drives a real multi-hour sleep — inherent to the feature; the wait is exercised via the injected delayFn throughout. The final in-flight ≤15s timer cannot be cleared on abort (the injected delayFn exposes no handle); ShutdownManager's 10s force-exit covers it, and this is documented at the call site.
    • Sibling sites considered: isWindowExhaustedRateLimit has exactly two consumers — phase-executor's ladder and batch-executor's halt predicate. Both were reviewed; the second needed no change (finding 4). No third consumer exists.
    • Sibling-line audit: the retry ladder has two arms. The cold-start arm was the literal target; the skipColdStartRetry arm was audited, found to have the same gap, and fixed — that is the loop-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 because AUTO_WAIT_MAX_WAITS bounds grants; the for(;;) in the skipColdStartRetry arm is bounded by the same counter, which performAutoWait increments 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.sh still uses npm install --silent at 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 dirtied package-lock.json by stripping libc fields, 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_MERGE on the adversarial re-read's "Gaps Found" status: two waiting-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 --help check 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

  6. added
    needs-improvement
    on Jul 27, 2026
  7. added a commit that references this issue on Jul 27, 2026
  8. admarble commented on Jul 27, 2026

    @admarble
    ContributorAuthor

    QA Addendum — gaps closed (#804)

    Reviewed at: ae631a7 · PR #825 · CI 5/5 pass · Verdict upgraded: AC_MET_BUT_NOT_A_PLUS → READY_FOR_MERGE

    The prior pass held at AC_MET_BUT_NOT_A_PLUS solely on the adversarial re-read's "Gaps Found" — two waiting-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.

    applyProgressEvent handles waiting before the complete/failed fall-through. If that ordering regresses, the fall-through runs p.status = event === "complete" ? "done" : "failed" and emits phase_failed — so a phase merely paused on a rate-limit window is reported as a failure, and pipelineHasFailed can 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 stays running; no phase_failed/phase_completed; wait text reaches nowLine; forwards to an external onProgress; a late notice for a non-current phase is ignored; normal completion still works afterwards.

    run-progress.test.ts (+4 tests) — renderer branch forwards waiting both with and without wakeAtMs (its absence is the clear-state signal); heartbeat branch calls pauseForWait/resumeFromWait and, load-bearingly, does not call stop() — which would delete the phase entry and leave a multi-hour wait with no liveness signal at all.

    RunOrchestrator.getProgressCallback() is a new @internal accessor. applyProgressEvent is private and depends on issueStates/phaseStartTimes/emitter, so without a seam the branch is unreachable short of a full run().

    Both guards mutation-tested, not assumed

    Mutation Result
    Delete the orchestrator waiting branch 5/6 new tests fail
    Delete the heartbeat waiting handler 3/3 relevant tests fail

    This mattered: my first draft of the orchestrator tests was tautological. WorkflowEventEmitter.emit dispatches through Promise.allSettled, so listeners run on a later tick and every not.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

    Metric Value
    Test files / tests 201 / 4189 passed (1 expected fail, 2 skipped)
    Build · Lint clean · clean
    CI 5/5 pass
    AC-2 pinned files still zero diff — phase-executor.test.ts, batch-executor.test.ts untouched across all three commits

    Re-run gate statuses

    • Adversarial re-read: Clean (was Gaps Found) — the two named gaps are closed; no new gaps surfaced re-reading the routing branches.
    • All other gates unchanged from the prior pass.

    Out-of-scope item now handled separately

    The scripts/new-feature.sh lockfile 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.

  9. added
    ready-for-review
    and removed
    needs-improvement
    on Jul 27, 2026
  10. added 4 commits that reference this issue on Jul 28, 2026
  11. added 2 commits that reference this issue on Sep 8, 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

    enhancementno-browser-testready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions