Repository navigation
fix(#833): reject malformed numeric CLI flags instead of coercing them to NaN - #836
Merged
admarble merged 6 commits intoJul 29, 2026
Merged
Conversation
…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.
6 tasks
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.
…are-parseint-on-run-timeout-lets-a-ma
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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
--timeoutonrunandreadywas coerced with a bareparseInt.parseInt("abc", 10)isNaN, which is not nullish, so it survivedphaseTimeout: mergedOptions.timeout ?? DEFAULT_CONFIG.phaseTimeout(config-resolver.ts:242) and reachedsetTimeout(abort, config.phaseTimeout * 1000)(phase-executor.ts:982). ANaNdelay 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:
And the CLI accepted it silently:
sequant run 999999 --timeout abc --dry-runexited 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-runnever reachessetTimeout, 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 0has no existing meaning, so it is rejected--timeout 0before this PRrun0is not nullish, so it won both??chains →setTimeout(fn, 0)→ aborts every phase instantly. The same failure asNaN, not "no timeout".readysrc/commands/ready.ts:111-114already guardstypeof options.timeout === "number" && options.timeout > 0, so0was discarded andsettings.run.timeoutwon.Nothing in
phase-executor.ts,heartbeat.ts, orrun-progress.tstreats0as a "disabled" sentinel —run-progress.ts:77'sphaseTimeoutSeconds > 0only gates a stall-threshold display, and it readssettings.run.timeout, not the flag. No working behavior is removed.Changes
1. Flag boundary (
bin/cli.ts) — the user-facing fix.run --timeoutandready --timeoutnow use the whole-string-digits validator #831 introduced, which rejects bothabcand30mand names the flag.2. Resolver backstop (
config-resolver.ts) —buildExecutionConfigno longer resolvesphaseTimeoutandmaxIterationsthrough a bare??. Non-finite and non-positive values fall back to the default instead of through it. AC-5 asks that the?? defaultgap "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 ofbin/cli.ts, which callsprogram.parse()at import time and so cannot be imported from a test.parsePositiveSecondsis preserved as a named wrapper, so #831'smerge --watchmessages are byte-identical.AC-6 — inventory of every bare
parseIntCLI coercionAll Commander registrations live in
bin/cli.ts; nothing undersrc/registers CLI options, so the inventory is closed at 16 sites.Fixed (8) — a malformed value was load-bearing
NaN(or the misparse) actually didrun --timeoutsetTimeoutclamps to 0 → every phase aborts instantly.30m→ 30s.ready --timeoutNaNwas caught by a> 0guard, but30msilently became 30 seconds.run --max-iterationswhile (iteration < NaN)is false on entry → the issue runs zero phases (batch-executor.ts:967).abort --graceMath.max(0, NaN * 1000)isNaN→ the SIGINT grace period is skipped entirely and SIGTERM follows at once (abort.ts:135).run --concurrencyrun.ts:76-81rejects non-integers — but only afterparseIntturned3xinto a valid3.run --auto-waitcreateAutoWaitLedger'sNumber.isFiniteguard caughtNaN, but30mquietly bought 30 minutes.ready --max-iterations> 0guard caughtNaN; misparse survived.ready --budget> 0guard caughtNaN;10ksilently became 10.--auto-waitand--graceare validated with min 0, not min 1 —0is meaningful for both (#804 defines--auto-wait 0as "off";--grace 0means escalate immediately).Justified as safe (8) — left as bare
parseIntNaNis harmlessstatus [issue]getIssueState(NaN)misses → prints "not found in state". Read-only, clear outcome.status --max-agestate-cleanup.ts:181isoptions.maxAgeDays && ageDays > options.maxAgeDays;NaNis falsy, so the age rule is skipped and cleanup removes fewer entries. Fails closed.state clean --max-ageprompt --waitprompt.ts:259-260guardstypeof === "number" && > 0.logs --lastslice(0, NaN)→slice(0, 0)→ empty list. Read-only display.logs --issue=== NaNis always false → empty list. Read-only display.dashboard --portserver.listen(NaN)throwsoptions.port should be >= 0 and < 65536. Received type number (NaN).— fails loudly, naming the problem.serve --port(
merge --interval/merge --timeoutwere 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
src/lib/cli-flags.test.tsabc,30m,1.5,1e3,0x10,-5,0, oversized, whitespace, per-flag naming, value echo,min: 0variantssrc/lib/workflow/config-resolver.numeric-guards.test.tsNaN/0/negative/±InfinityreachingphaseTimeoutandmaxIterations, asserted on the properties that matter (setTimeoutdelay is finite and > 0;0 < maxIterationsis true)src/commands/numeric-flags.integration.test.tsVacuity 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
--phasesvalidation would silently turn those cases into real workflow runs.Mutation-verified, both layers:
??→ 20 of 25 guard tests fail.run --timeoutalone toparseInt→ exactly its 4 assertions fail;ready --timeoutstays 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
--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 onrun/ready.phaseTimeouttosetTimeoutis asserted as a property rather than executed against a live phase.--graceno longer accepts fractional seconds from the CLI. Nothing is lost:parseInt("0.5")was already0. The programmatic API still takes fractions, andabort.test.ts'sgraceSeconds: 0.05calls it directly — unaffected.Conflict note
feature/817-*is in flight and touches bothbin/cli.ts(adds--ready-gatenear line 339) andconfig-resolver.ts(addsreadyGate:at the end of the same return object). Hunks are >3 lines apart in both files, so no textual conflict is expected.origin/mainwas 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 ofphaseTimeout, plus an unguarded entry point feeding both.1.
sequant readywas still exposed (real defect)readynever passes throughbuildExecutionConfig—ready-gate.ts'sbuildPhaseConfigassembles its ownExecutionConfig. Itstypeof x === "number" && x > 0checks stopped a bad flag but fell through unchecked tosettings.run.*. Reproduced before fixing: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 toresolveReadyLimitsso it is testable rather than buried in the command body.2.
settings.jsonwas an unguarded entry pointrun.timeout/concurrency/maxIterationswerez.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 where0is 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)
validateSettingsre-parsed{}on any Zod failure, so a single bad value reverted every unrelated key to its default: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
undefinedand 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
__tests__/settings-schema.test.tsno longer assertsrun.timeout: 0parsesstaleBranchThreshold, where 0 is genuinely meaningful, plus a new case asserting the three guarded fields reject it.buildExecutionConfigfalls back tosettings.run.*beforeDEFAULT_CONFIGTest-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
origin/main--ready-gate) merged cleanly; its in-run gate uses the already-guardedconfig.phaseTimeout, so it adds no third producerMutation-verified, all three new guards:
ready.tschaining to the old CLI-only guard.positive()parse({})