Skip to content

fix(#833): reject malformed numeric CLI flags instead of coercing them to NaN - #836

Merged
admarble merged 6 commits into
mainfrom
feature/833-fix-cli-bare-parseint-on-run-timeout-lets-a-ma
Jul 29, 2026
Merged

admarble merged 6 commits into
mainfrom
feature/833-fix-cli-bare-parseint-on-run-timeout-lets-a-ma

Conversation

@admarble

@admarble admarble commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

--timeout on run and ready was coerced with a bare parseInt. parseInt("abc", 10) is NaN, which is not nullish, so it survived phaseTimeout: mergedOptions.timeout ?? DEFAULT_CONFIG.phaseTimeout (config-resolver.ts:242) and reached setTimeout(abort, config.phaseTimeout * 1000) (phase-executor.ts:982). A NaN delay clamps to 0, so every phase aborted on its first tick — and because it surfaced as a phase timeout, the run read as a phase/agent fault rather than a typo in a flag.

Sibling of #818/#831, found by that PR's cross-file scan and deliberately deferred out of it.

AC-1 — reproduced before fixing

Ran the real resolution path plus the actual timer:

parseInt("abc",10)                      = NaN
resolveRunOptions().timeout             = NaN
buildExecutionConfig().phaseTimeout     = NaN
setTimeout delay would be               = NaN
timer fired after ms                    = 2.4      <-- clamped to 0
parseInt("30m",10)                      = 30

And the CLI accepted it silently: sequant run 999999 --timeout abc --dry-run exited 0 with no warning.

The issue's read was correct — nothing downstream normalizes it. (Stated plainly: the abort was demonstrated at the config + timer layer, not by spawning a live agent run. --dry-run never reaches setTimeout, and a non-dry run spawns a real Claude session. The three call sites in between are a straight pass-through with no guard.)

AC-2 — --timeout 0 has no existing meaning, so it is rejected

Command --timeout 0 before this PR
run 0 is not nullish, so it won both ?? chains → setTimeout(fn, 0) → aborts every phase instantly. The same failure as NaN, not "no timeout".
ready src/commands/ready.ts:111-114 already guards typeof options.timeout === "number" && options.timeout > 0, so 0 was discarded and settings.run.timeout won.

Nothing in phase-executor.ts, heartbeat.ts, or run-progress.ts treats 0 as a "disabled" sentinel — run-progress.ts:77's phaseTimeoutSeconds > 0 only gates a stall-threshold display, and it reads settings.run.timeout, not the flag. No working behavior is removed.

Changes

1. Flag boundary (bin/cli.ts) — the user-facing fix. run --timeout and ready --timeout now use the whole-string-digits validator #831 introduced, which rejects both abc and 30m and names the flag.

2. Resolver backstop (config-resolver.ts) — buildExecutionConfig no longer resolves phaseTimeout and maxIterations through a bare ??. Non-finite and non-positive values fall back to the default instead of through it. AC-5 asks that the ?? default gap "cannot silently return"; a CLI-only fix removes today's caller but leaves the gap for the next one, and this class has already recurred once (#818 → #833).

3. Testability (src/lib/cli-flags.ts) — the validator moved out of bin/cli.ts, which calls program.parse() at import time and so cannot be imported from a test. parsePositiveSeconds is preserved as a named wrapper, so #831's merge --watch messages are byte-identical.

AC-6 — inventory of every bare parseInt CLI coercion

All Commander registrations live in bin/cli.ts; nothing under src/ registers CLI options, so the inventory is closed at 16 sites.

Fixed (8) — a malformed value was load-bearing

Line Flag What NaN (or the misparse) actually did
286 run --timeout setTimeout clamps to 0 → every phase aborts instantly. 30m → 30s.
527 ready --timeout NaN was caught by a > 0 guard, but 30m silently became 30 seconds.
304 run --max-iterations while (iteration < NaN) is false on entry → the issue runs zero phases (batch-executor.ts:967).
459 abort --grace Math.max(0, NaN * 1000) is NaN → the SIGINT grace period is skipped entirely and SIGTERM follows at once (abort.ts:135).
379 run --concurrency run.ts:76-81 rejects non-integers — but only after parseInt turned 3x into a valid 3.
354 run --auto-wait createAutoWaitLedger's Number.isFinite guard caught NaN, but 30m quietly bought 30 minutes.
520 ready --max-iterations > 0 guard caught NaN; misparse survived.
525 ready --budget > 0 guard caught NaN; 10k silently became 10.

--auto-wait and --grace are validated with min 0, not min 1 — 0 is meaningful for both (#804 defines --auto-wait 0 as "off"; --grace 0 means escalate immediately).

Justified as safe (8) — left as bare parseInt

Line Flag Why NaN is harmless
254 status [issue] getIssueState(NaN) misses → prints "not found in state". Read-only, clear outcome.
260 status --max-age state-cleanup.ts:181 is options.maxAgeDays && ageDays > options.maxAgeDays; NaN is falsy, so the age rule is skipped and cleanup removes fewer entries. Fails closed.
642 state clean --max-age Same consumer, same fail-closed behavior.
417 prompt --wait prompt.ts:259-260 guards typeof === "number" && > 0.
558 logs --last slice(0, NaN) → slice(0, 0) → empty list. Read-only display.
560 logs --issue === NaN is always false → empty list. Read-only display.
587 dashboard --port server.listen(NaN) throws options.port should be >= 0 and < 65536. Received type number (NaN). — fails loudly, naming the problem.
600 serve --port Same.

(merge --interval / merge --timeout were already fixed in #831 and are out of scope per the issue.)

The safe cases divide cleanly: every one is either a read-only display filter that degrades to "nothing matched", or a fail-closed guard, or a loud crash naming the bad value. None can silently do the wrong work.

Test plan

Suite Covers
src/lib/cli-flags.test.ts AC-3/AC-4 — the validator itself: abc, 30m, 1.5, 1e3, 0x10, -5, 0, oversized, whitespace, per-flag naming, value echo, min: 0 variants
src/lib/workflow/config-resolver.numeric-guards.test.ts AC-5 — NaN/0/negative/±Infinity reaching phaseTimeout and maxIterations, asserted on the properties that matter (setTimeout delay is finite and > 0; 0 < maxIterations is true)
src/commands/numeric-flags.integration.test.ts AC-3/AC-4/AC-6 wiring — real built CLI as a subprocess, per command and flag

Vacuity guards. Every rejection assertion pins the specific error text, not merely a non-zero exit. The integration suite carries a positive control (valid values get past coercion), and a further test that the positive control itself really exits during parsing — otherwise a regression in --phases validation would silently turn those cases into real workflow runs.

Mutation-verified, both layers:

  • Reverting the resolver guard to ?? → 20 of 25 guard tests fail.
  • Reverting run --timeout alone to parseInt → exactly its 4 assertions fail; ready --timeout stays green, confirming the tests are per-site and not blanket.

Gates: npm run build ✅ · npm run lint ✅ (0 warnings) · npm test ✅ 4417 passed, 212 files, 1 expected fail, 2 skipped.

Risk

  • Likely failure mode: a user or CI script currently passing a value that parsed leniently (--timeout 30m, --concurrency 3x, --budget 10k) now gets a hard error instead of silently-wrong behavior. That is the intent, but it is a user-visible break — hence the CHANGELOG entry and the doc-table notes on run/ready.
  • Not covered: no test spawns a real agent run to observe the instant-abort end to end (AC-1's caveat). The chain from phaseTimeout to setTimeout is asserted as a property rather than executed against a live phase.
  • --grace no longer accepts fractional seconds from the CLI. Nothing is lost: parseInt("0.5") was already 0. The programmatic API still takes fractions, and abort.test.ts's graceSeconds: 0.05 calls it directly — unaffected.

Conflict note

feature/817-* is in flight and touches both bin/cli.ts (adds --ready-gate near line 339) and config-resolver.ts (adds readyGate: at the end of the same return object). Hunks are >3 lines apart in both files, so no textual conflict is expected. origin/main was re-fetched immediately before push — 0 commits behind.

Closes #833


Follow-up: gaps found reviewing this PR's own fix

The first pass closed the flag boundary and buildExecutionConfig. Reviewing that fix surfaced that it covered one of the two producers of phaseTimeout, plus an unguarded entry point feeding both.

1. sequant ready was still exposed (real defect)

ready never passes through buildExecutionConfig — ready-gate.ts's buildPhaseConfig assembles its own ExecutionConfig. Its typeof x === "number" && x > 0 checks stopped a bad flag but fell through unchecked to settings.run.*. Reproduced before fixing:

settings.json { "run": { "timeout": 0 } }
  -> validateSettings: run.timeout parsed as 0, warnings: []
  -> ready phaseTimeout = 0  ->  setTimeout delay = 0    <-- instant abort, silent

That is the #833 defect, on the path the original fix did not reach. Both producers now chain the same guard CLI → settings → default, so no layer is unchecked and the two cannot drift apart again. ready's resolution is extracted to resolveReadyLimits so it is testable rather than buried in the command body.

2. settings.json was an unguarded entry point

run.timeout / concurrency / maxIterations were z.number() with no constraint. All three are now .positive(), so a bad key is named at load instead of silently swapped for a default. Deliberately left unconstrained where 0 is meaningful: staleBranchThreshold (0 = warn on any drift), resolvedIssueTTL (0 = expire immediately), autoWaitMinutes (0 = off, per #804).

3. One bad key discarded the entire settings file (latent bug, surfaced by 2)

validateSettings re-parsed {} on any Zod failure, so a single bad value reverted every unrelated key to its default:

{ "run": { "timeout": "fast", "logPath": "custom/logs", "pmRun": "pnpm run" } }
  before:  logPath -> ".sequant/logs"   pmRun -> undefined     (both silently lost)
  after:   logPath -> "custom/logs"     pmRun -> "pnpm run"    (only timeout reset)

Its comment claimed it worked "by stripping invalid fields and re-parsing" — it never stripped anything. It now drops only the rejected paths and re-parses. An array index in a rejected path drops the whole array, since deleting by index leaves a hole that re-parses as undefined and fails again. Fixing this was a prerequisite: without it, adding the constraints in (2) would have widened that blast radius rather than improving diagnostics.

Deliberate behavior changes

Change Why
__tests__/settings-schema.test.ts no longer asserts run.timeout: 0 parses It pinned the permissiveness AC-2 proved is a defect. The zero-value case moves to staleBranchThreshold, where 0 is genuinely meaningful, plus a new case asserting the three guarded fields reject it.
buildExecutionConfig falls back to settings.run.* before DEFAULT_CONFIG Removes the layering asymmetry between the two producers — that asymmetry is what let gap (1) hide.

Test-quality gate

The tautology detector flagged 10 blocks (52.6%, over its blocking threshold) as having no production calls — all of them mine. The calls were real but hidden behind describe-scope aliases and local helpers, so neither a reader nor the detector could see the coupling. Fixed by making the calls visible in each block, not by @tautology-skip. Gate now reports ✅ OK — All tests call production code.

Verification

Check Result
Full suite 4500 passed, 215 files, 1 expected fail, 2 skipped
Build / lint pass / pass (0 warnings)
Tautology gate ✅ OK
Merge with origin/main #817 (--ready-gate) merged cleanly; its in-run gate uses the already-guarded config.phaseTimeout, so it adds no third producer

Mutation-verified, all three new guards:

Mutation Result
Revert ready.ts chaining to the old CLI-only guard 17 of 30 fail
Revert schema .positive() 10 of 50 fail
Revert salvage to the old parse({}) 5 of 19 fail

admarble added 2 commits July 28, 2026 00:30
…m to NaN

`--timeout` on `run` and `ready` was coerced with a bare `parseInt`.
`parseInt("abc", 10)` is `NaN`, which is not nullish, so it survived
`phaseTimeout: mergedOptions.timeout ?? DEFAULT_CONFIG.phaseTimeout` and
reached `setTimeout(abort, phaseTimeout * 1000)` — a `NaN` delay clamps to
0, so every phase aborted on its first tick and the run read as a phase
fault rather than a bad flag. `--timeout 30m` was the quiet half: the user
asked for 30 minutes and got 30 seconds.

Sibling of #818/#831, deferred out of that PR because narrowing `run`/`ready`
input is user-visible and deserved its own check on whether `--timeout 0`
meant anything. It does not: on `run` it reached `setTimeout` as a 0ms delay
(the same instant-abort), and on `ready` an existing `> 0` guard already
discarded it. So it is now rejected, per #831.

The AC-6 audit found three more flags whose malformed value was load-bearing:
  --max-iterations  `while (iteration < NaN)` is false on entry → zero phases
  --grace           `Math.max(0, NaN * 1000)` is NaN → grace period skipped
  --concurrency / --auto-wait / ready --budget / ready --max-iterations
                    guarded against NaN downstream, but each silently
                    misparsed `3x` → 3 and `10k` → 10

`buildExecutionConfig` also no longer resolves `phaseTimeout`/`maxIterations`
through a bare `??` — non-finite and non-positive values fall back *to* the
default rather than through it, closing the gap for programmatic callers and
settings.json, not just today's CLI.

The validator moves to src/lib/cli-flags.ts so it can be unit-tested directly
(bin/cli.ts calls program.parse() at import time). Subprocess tests pin that
it is actually wired to each command — the #305 inert-flag failure mode.

Both guards mutation-verified: reverting the resolver guard fails 20/25 of its
tests; reverting `run --timeout` alone fails exactly its 4 assertions and
leaves `ready` green.
The `ready` / `abort` positive controls asserted only the *absence* of a
coercion error. That stays green if the command starts failing before the
flag is ever parsed — the test would report success having proven nothing.
Each case now also pins the specific downstream message it should reach
("No worktree found", "No relay PID found", "Unknown phase 'bogus'"), which
is only reachable if argument coercion accepted the value.

Replaces the separate exit-during-parsing guard, which covered only the
`run` cases and is now subsumed per-case.
admarble added 4 commits July 28, 2026 01:42
QA's own follow-up review found the first fix covered only one of the two
producers of `phaseTimeout`.

`sequant ready` never passes through `buildExecutionConfig` — `ready-gate.ts`'s
`buildPhaseConfig` assembles its own ExecutionConfig — so the resolver guard
did not protect it. Its `typeof x === "number" && x > 0` checks stopped a bad
CLI value but fell through unchecked to `settings.run.*`, which was itself
`z.number()` with no constraint. A `"timeout": 0` in settings.json therefore
reached `setTimeout` as a 0ms delay and aborted every ready-gate phase on its
first tick, with no warning: the #833 defect, on the uncovered path.

- Export `positiveOr` and chain it CLI -> settings -> default in BOTH
  producers, so neither layer is unchecked and the two cannot drift again.
  `ready.ts`'s resolution moves into `resolveReadyLimits` so it is testable.
- Constrain `run.timeout` / `concurrency` / `maxIterations` with `.positive()`
  so a bad key is NAMED at load instead of silently swapped for a default.
  Left unconstrained where 0 is meaningful (staleBranchThreshold,
  resolvedIssueTTL, autoWaitMinutes).
- Fix `validateSettings` salvage. It re-parsed `{}` on any Zod failure, so one
  bad value discarded the user's ENTIRE settings.json and reverted every
  unrelated key to its default — while its comment claimed it stripped invalid
  fields. It now drops only the rejected paths (whole arrays on a bad index,
  since deleting by index leaves a hole that re-fails) and re-parses.
  Without this, adding constraints above would have widened that blast radius.

`__tests__/settings-schema.test.ts` asserted `run.timeout: 0` parses. That
pinned the permissiveness AC-2 proved is a defect, so the case moves to
`staleBranchThreshold`, where 0 is genuinely meaningful, plus a new case
asserting the three guarded fields reject it.

Also restructured the new tests to call production functions directly instead
of through describe-scope aliases. The tautology detector counted 10 blocks as
vacuous (52.6%, over its blocking threshold) because the calls were hidden
behind local helpers. Fixed by making the coupling visible, not by
@tautology-skip.
…erence

The `run.timeout` / `concurrency` / `maxIterations` rows now state the positive
constraint and what happens on a bad value, and the CHANGELOG covers the ready
path and the settings entry point alongside the original flag fix.
CHANGELOG conflict was purely additive — #837's Fixed entry and #833's two
entries both landed at the top of the same section. Kept both.

No source-file overlap: #837 touched batch-executor / chain-resume /
state-cleanup / run-orchestrator; #833 touches cli-flags / config-resolver /
ready / settings.
@admarble
admarble merged commit 745e996 into main Jul 29, 2026
5 checks passed
@admarble
admarble deleted the feature/833-fix-cli-bare-parseint-on-run-timeout-lets-a-ma branch July 29, 2026 01:02
admarble added a commit that referenced this pull request Jul 29, 2026
…seInt (#855)

* fix(#846): ensureWorktree surfaces failed provisioning install instead of swallowing it

Extract the frozen provisioning install into installWorktreeDeps, which
mirrors reinstallIfLockfileChanged's status check: on a non-zero exit it
warns (chalk.yellow) naming the resolved command so the user can rerun it,
and warn-and-continues rather than aborting. Previously ensureWorktree ran
the install and discarded the result, so after #816/#826 switched to a
frozen npm ci a repo with no/stale lockfile yielded a silently
dependency-less worktree whose breakage only surfaced later as a confusing
phase error.

Adds a mocked unit test (no lockfile => npm ci exit 1) asserting the
failure is reported, the stderr is surfaced, and the command is named even
when stderr is empty.

Entire-Checkpoint: 8e84f0faf466

* fix(#845): harden the eight numeric CLI options #833 left on bare parseInt

#833 hardened 10 numeric flags with parseWholeNumber but left eight on a
bare parseInt, justified in PR #836's AC-6 table by reasoning only about
NaN. The unit-suffix misparse the guard exists for (parseInt("30m",10) is
30) was never addressed, so `logs --last 30m` read 30, the two --port flags
bound the truncated port silently, and `--max-age 1w` failed *open* —
state-cleanup.ts:181 gates on a truthy value, so 1w narrowed a 7-day
retention to 1 day and deleted more than asked.

All eight sites (status [issue], status --max-age, prompt --wait,
logs --last, logs --issue, dashboard --port, serve --port,
state clean --max-age) now use the same parseWholeNumber guard, coerced
during commander's parse phase so a rejection exits before any server
binds or cleanup runs. --wait uses min:0 (prompt.ts:259 reads 0 as
"don't block"); the rest use min:1.

Tests: extend numeric-flags.integration.test.ts with the issue's eight
end-to-end reproductions (proves wiring, not just the coercion) plus the
--wait 0 boundary; add a data-driven per-flag table in cli-flags.test.ts
pinning reject-suffix (AC-1) and preserve-boundary (AC-4). Mutation-checked
the --max-age case: reverting the coercion reaches the fail-open cleanup
and the test fails.

Entire-Checkpoint: 8a29dcd37f14
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.

fix(cli): bare parseInt on run --timeout lets a malformed value abort every phase instantly (sibling of #818)

1 participant