Skip to content

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

Merged
admarble merged 3 commits into
mainfrom
feature/804-feat-run-auto-wait-continue-a-rate-limited-run
Jul 27, 2026
Merged

admarble merged 3 commits into
mainfrom
feature/804-feat-run-auto-wait-continue-a-rate-limited-run

Conversation

@admarble

Copy link
Copy Markdown
Contributor

Summary

Adds sequant run --auto-wait <minutes>: when a phase fails on a rate-limit window that is hours out, wait for the window to reopen and continue, instead of halting for a manual restart.

Default 0 (off). With no flag, the #761/#799 halt path is unchanged — phase-executor.test.ts and batch-executor.test.ts are untouched by this PR (git diff on those two paths is empty), which is AC-2's regression contract stated as evidence rather than assertion.

Blocker #782 is closed, and its finding drove the central design call: the real 2026-07-18 capture shows out-of-credits rejections do carry resetsAt and rateLimitType: "five_hour". So auto-wait gates on the error type, not the presence of a timestamp — otherwise it would wait out a credits failure that no amount of waiting can heal.

AC Verification

AC Status Evidence
AC-1 ✅ MET --auto-wait <minutes> 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, not just registered — see the bug below
AC-2 ✅ MET Both pinned test files have an empty diff; 201 tests in them pass unmodified
AC-3 ✅ MET RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS and isWindowExhaustedRateLimit unchanged; shouldAutoWaitForReset is separate and fires only once the classifier is already true
AC-4 ✅ MET Gated on instanceof RateLimitError (BillingError is a sibling class, not a subclass). Pinned against the real #782 capture, plus the counterfactual
AC-5 ✅ MET resetsAtToMs() first, +60s buffer after, all epoch ms; display reuses formatRateLimitMessage/formatResetTime; test asserts no resets at … resets at doubling
AC-6 ✅ MET Max 2 waits/issue; budget is a total, ledger created per-issue in runIssueWithLogging; boundary, bound, and cross-wait-budget tests
AC-7 ✅ MET Phase renders waiting <wake>; heartbeat reports the wait instead of a false stall; Ctrl-C aborts via a ShutdownManager-registered AbortController; 15s ticks double as the refresh
AC-8 ✅ MET Split into isBillingHalt/isWindowHalt. Needed no behavioral change — see note below
AC-9 ✅ MET 39 tests in auto-wait.test.ts + 7 in auto-wait-display.test.ts
AC-10 ✅ MET Main README.md, marketplace README (scripts/prepare-marketplace.ts README_CONTENT), docs/reference/run-command.md + cheat-sheet.md, CHANGELOG.md

Bug found and fixed during QA

--auto-wait was inert in the first commit. 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, showed up in --help, and did nothing — the #305 failure mode.

Checking --help proved only that it parses; that's what the first pass did and why it missed. Fixed in normalizeCommanderOptions (the adapter that already exists for this mismatch class), guarded on !== undefined so an explicit --auto-wait 0 still overrides a non-zero setting, and pinned by a test driving the resolver with Commander's actual key shape.

Two more defects were surfaced by writing the tests:

  • The wait loop recomputed remaining time from the wall clock, so an instantly-resolving injected delayFn busy-spun until real time caught up (one 8195-second test run). Now driven by slice accounting, with the clock only able to shorten the wait.
  • Promise.race registered an abort listener per tick — ~1200 listeners on one signal for a 5-hour wait. Now one listener for the whole wait, with a regression test.

AC-8 note

AC-8 anticipated that a phase which waits and then succeeds would still halt the -Q loop. It cannot: all four isBillingOrWindowHalt call sites sit inside else branches of if (result.success), so a successful post-wait result never reaches the predicate. The separability refactor is still done as the AC requires, and the short-circuit is now pinned by test rather than left as an assumption. Reporting this as a finding rather than silently claiming a behavioral fix.

Beyond the literal ACs

  • loop-phase coverage. The skipColdStartRetry arm (maxRetries: 0, used by loop) had no window handling at all, so --auto-wait would have silently skipped it. Flagged in the plan as an open question, defaulted to including it.
  • Env layer. The issue's design note said env resolution came free via ConfigResolver with numeric coercion. It does not — resolveRunOptions uses ?? chains plus getEnvConfig(), so SEQUANT_AUTO_WAIT_MINUTES is wired explicitly (non-numeric and negative values ignored, so a typo can't enable an unbounded wait).

Test plan

  • npm run build — clean
  • npm run lint — clean
  • npm test — 200 files, 4178 passed, 1 expected fail, 2 skipped
  • npx sequant run --help shows the flag
  • End-to-end trace: Commander {autoWait: 90} → resolveRunOptions → ExecutionConfig.autoWaitMinutes === 90
  • AC-2 gate: git diff empty on both pinned test files

Known limitations (documented, by design)

  • In-process only — the wait does not survive closing the terminal. Durable out-of-process resume is out of scope per the issue.
  • Locks held across the wait — deliberate: Claude rate limits are account-wide, so no other run could progress during that window anyway.
  • Auto-wait is not emitted on the SEQUANT_PROGRESS stderr channel (whose event union is start|complete|failed); MCP consumers see the wait through the orchestrator's event emitter instead.

Closes #804

admarble added 2 commits July 26, 2026 23:40
… resets

#761 classified window exhaustion and #799 made it fail fast, so a five-hour
window reset turned a multi-hour run into a manual restart even though the SDK
told us exactly when the window reopens. This makes the wait opt-in and bounded.

Default 0 (off): with no flag the halt path is byte-for-byte unchanged, which
phase-executor.test.ts and batch-executor.test.ts pin — both files are
untouched by this commit, which is the AC-2 regression contract.

- Flag/setting/env: --auto-wait <minutes>, run.autoWaitMinutes,
  SEQUANT_AUTO_WAIT_MINUTES. The env layer is explicit in getEnvConfig because
  resolveRunOptions does not route through ConfigResolver, contrary to the
  design note that assumed numeric coercion came for free.
- shouldAutoWaitForReset is a separate decision from
  isWindowExhaustedRateLimit / RATE_LIMIT_WINDOW_SKIP_THRESHOLD_MS, which are
  untouched: those answer "transient or exhausted?", this answers "am I willing
  to wait that long?".
- Billing never waits, gated on error type rather than the presence of
  resetsAt: the real #782 capture shows out-of-credits rejections DO carry
  resetsAt/rateLimitType, so a timestamp gate would wait out a condition that
  cannot self-heal. Regression-tested against the committed capture, including
  the counterfactual.
- Bounded: max 2 waits per issue, and the minutes value is a TOTAL budget, not
  a per-occurrence allowance. Ledger is per-issue (created in
  runIssueWithLogging), since a per-phase ledger would grant every phase its
  own full budget.
- Wake at resetsAt + ~60s buffer, all arithmetic in epoch ms, display via the
  existing formatRateLimitMessage/formatResetTime — never re-appending a raw
  resetsAt onto a formatted message (#799 doubled-string trap).
- Liveness: phase renders as `waiting <wake>`, and the -q heartbeat reports the
  wait instead of firing its mtime-based stall warning, which a multi-hour
  sleep would otherwise trip within minutes. Ctrl-C aborts promptly via a
  ShutdownManager-registered AbortController; the sleep is chunked into 15s
  ticks that double as the display refresh.
- Also covers the loop phase, whose maxRetries:0 path had no window handling at
  all, so --auto-wait would have silently skipped it.

AC-8 note: isBillingOrWindowHalt is split into isBillingHalt/isWindowHalt for
separability, but needed no behavioral change. The AC anticipated that a phase
which waits then succeeds would still halt the -Q loop; it cannot, because all
four call sites sit inside `else` branches of `if (result.success)`. Pinned by
test rather than left as an assumption.

Two defects found by the tests and fixed here: the wait loop polled the wall
clock for its remaining time, so an instantly-resolving injected delayFn
busy-spun until real time caught up (8195s test run); and Promise.race
registered an abort listener per tick, which on a 5h wait would have piled up
~1200 listeners on one signal.

Closes #804
…erage

QA of the previous commit found the flag was inert. 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 silently did nothing — the #305
failure mode, and exactly what AC-1's "end-to-end" wording exists to prevent.
Checking `--help` proved only that it parses, which is why the first pass
missed it.

Mapped in `normalizeCommanderOptions`, the CLI-boundary adapter that already
exists for this class of mismatch. Guarded on `!== undefined` rather than
truthiness so an explicit `--auto-wait 0` still overrides a non-zero setting.
Pinned by a test that drives the resolver with Commander's actual key shape.

Also from QA:

- Removed the `as RateLimitError` / `as number` casts from the decision path by
  narrowing for real; `shouldAutoWaitForReset` now returns the narrowed error
  in an `AutoWaitDecision`, so neither call site casts either.
- Added `auto-wait-display.test.ts` covering the AC-7 plumbing, which had no
  direct tests: the renderer's waiting↔running transition (a stranded
  `waiting` cell is invisible to every other test) and the heartbeat's
  stall-warning suppression, including that suppression is not sticky — a
  genuine stall after the wait must still warn, or auto-wait would permanently
  disable the #574 alarm.

Full suite: 200 files, 4178 passed.
…sted

These were the gaps that held the QA verdict at AC_MET_BUT_NOT_A_PLUS.

The orchestrator branch turned out to be worse than "display-only", which is
how I characterized it. `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 gets reported as a failure, and
the issue can be marked failed via pipelineHasFailed. That is a correctness bug
in the MCP/TUI path, not cosmetics.

- `auto-wait-routing.test.ts` (new): orchestrator keeps the phase running,
  emits no phase_failed/phase_completed, surfaces the wait on nowLine, forwards
  to an external onProgress, ignores a late notice for a non-current phase, and
  still completes normally afterwards.
- `run-progress.test.ts`: renderer branch forwards waiting (with and without
  wakeAtMs — its absence is what clears the state); heartbeat branch calls
  pauseForWait/resumeFromWait and, critically, 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. Without
it the branch is unreachable short of a full `run()`: `applyProgressEvent` is
private and depends on issueStates/phaseStartTimes/emitter.

Both guards mutation-tested rather than assumed: deleting the orchestrator
branch fails 5/6 of the new tests, deleting the heartbeat handler fails 3/3.
The first draft of the orchestrator tests was tautological — `emit()` dispatches
via Promise.allSettled, so every `not.toHaveBeenCalled()` passed regardless.
Fixed with an explicit flush, which is what made the mutation run meaningful.

Full suite: 201 files, 4189 passed.
@admarble
admarble merged commit c698b86 into main Jul 27, 2026
5 checks passed
@admarble
admarble deleted the feature/804-feat-run-auto-wait-continue-a-rate-limited-run branch July 27, 2026 09:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant