Repository navigation
Description
Background
sequant run manages an expensive pipeline (spec → exec → qa) where each phase spawns Claude API sessions costing real budget. The system has state tracking (state.json) that records issue lifecycle status (in_progress → ready_for_merge → merged), run logs that record completion history, and worktree isolation that creates persistent git worktrees per issue.
However, none of this tracking is used as a gate before execution. run.ts reads state at line 2719 but only uses it to decide whether to initialize or update — it never asks "should I skip this issue?" This means:
- Completed issues can be re-executed indefinitely
- Stale worktrees (days/weeks behind main) are silently reused
- The merger workflow doesn't close the lifecycle (state stays
ready_for_merge, worktrees persist, GitHub issues stay open)
Incident: 70 Minutes of Wasted Budget (2026-02-19)
Timeline:
| Date | Event | State |
|---|---|---|
| Feb 12 | sequant run 33 34 35 36 37 --sequential — all 5 passed (run 616d176e, 75 min) |
state.json → ready_for_merge |
| Feb 12 | /merger merged all 5 branches into main (direct merge, no PRs) |
state.json still ready_for_merge, worktrees still exist, GitHub issues still open |
| Feb 12–19 | 30+ commits land on main (#44, #50, #57–#72) — worktrees become 39 commits stale | No change to state or worktrees |
| Feb 19 | sequant run 35 33 34 36 37 --sequential --chain — re-runs all 5 |
No guard checked. 70 min wasted on duplicate work |
| Feb 19 | sequant run 33 34 36 37 --sequential --chain --qa-gate — re-runs 4 more |
Another 70 min wasted. Stale worktrees reused (0 created, 4 reused) |
Evidence:
# state.json — still "ready_for_merge" despite being merged a week ago
#33: status=ready_for_merge, merged=false
#34: status=ready_for_merge, merged=false
#35: status=ready_for_merge, merged=false
# Run logs confirm original completion
run-2026-02-12T15-51-31-616d176e: Issues [33,34,35,36,37] → 5 passed, 0 failed
# Worktrees were 39 commits behind main
$ git merge-base main feature/33-... → 62caf93 (39 commits behind 229cde8)
# Main already had all the merge commits
fa25065 Merge #35: standardize dark mode override pattern
a3f94ba Merge #34: extract CopyIcon and CommandBlock components
b463cd3 Merge #36: split WhatIsSequant.astro into sub-components
a62eeee Merge #33: adopt typography and spacing tokens across codebase
c794377 Merge #37: split global.css into focused stylesheets
Impact: ~140 minutes of API budget. One conflicting PR created (#73, now closed). All work was pure duplication.
Why Existing Fixes Didn't Help
- Chain mode silently fails when worktrees pre-exist from earlier runs #289 (chain worktree rebase): Fixed rebase mechanics but doesn't check if work is already done. The rebase fired ("3 rebased") but rebased onto a stale chain base, not current main.
- fix: Rebase worktrees onto main before PR to prevent lockfile drift #295 (pre-PR rebase onto origin/main): Runs after exec, so doesn't prevent wasted execution.
- Exec skill line 157–164 ("check for existing PRs"): This check runs inside the Claude session, which already costs budget. It also only checks for PRs — tonight there were no PRs (direct merge).
sequant state cleanup: Can detect merged PRs and update state, but requires manual invocation. Doesn't run automatically.
Proposed Fix
Three defense layers, each catching what the previous might miss:
Layer 1: Pre-flight state guard in run.ts
Where: After issue info fetch (~line 2232), before worktree creation (~line 2237).
What: Check state.json for each issue. If ready_for_merge or merged, skip it with a warning. --force overrides.
Why this layer: Prevents all downstream cost (worktree setup, spec, exec, qa) for already-completed issues. Zero API cost — pure local file read.
Edge cases to handle:
- Issue was
ready_for_mergebut PR was rejected and issue reopened → user should use--forceorsequant state reset <issue>to clear the state state.jsondoesn't exist or is corrupted → skip the guard gracefully, proceed with execution- Issue not in
state.jsonat all → proceed normally (new issue) --forcewith multiple issues where some are completed → only re-run the force-specified ones, still skip others? No —--forceshould override for ALL specified issues
Layer 2: Worktree freshness on reuse
Where: In ensureWorktree(), existing-worktree branch (~line 284).
What: When reusing a worktree, check commits behind origin/main. If behind, remove and recreate fresh. This applies regardless of state (covers --force re-runs).
Why this layer: Even if state is cleared with --force, running on a worktree that's 39 commits behind main produces code against an outdated codebase. The AI will make changes that conflict with recent work.
Edge cases to handle:
- Worktree has uncommitted changes → warn, don't destroy (might be manual WIP)
- Worktree has unpushed commits (work in progress from a failed run) → warn, offer to continue or recreate
git fetchneeded to know remote state → do a fetch first (already happens inrebaseBeforePR)- Worktree is ahead of main but has diverged → this is normal for feature branches with new work; only flag as stale if the merge-base is significantly behind
- Chain mode: recreating a worktree mid-chain breaks the chain dependency → in chain mode, rebase onto the chain base after recreation (combine with Chain mode silently fails when worktrees pre-exist from earlier runs #289 fix)
Layer 3: Lifecycle completion (close the loop)
Where: Multiple integration points.
What:
- Auto-cleanup at run start: Before execution, do a lightweight check — for any issue in
ready_for_mergestate, query GitHub for merged PRs viagh pr list --state merged --head feature/<N>-. If found, update state tomerged. This is whatcleanupStaleEntriesdoes but should run automatically. - Merger skill updates state: Add
npx tsx scripts/state/update.ts merged <N>to merger SKILL.md after each successful merge. The skill already has a state tracking section (lines 283-308) with exactly this pattern but implementations may skip it. - Worktree removal after merge: After
/mergercompletes, remove the worktree. Branch stays in git history but the directory is cleaned up.
Edge cases to handle:
- Direct merge without PR (tonight's scenario) → auto-cleanup won't find a merged PR. Supplement with git check:
git branch --merged main | grep feature/<N>-to detect branches already in main regardless of PR status. - Squash merge changes commit SHAs →
git branch --mergedhandles this correctly for squash merges onto main ghCLI not authenticated → skip GitHub checks gracefully, fall through to git-based detection- Rate limiting on
ghAPI calls → batch the checks, cache results during the run
Acceptance Criteria
- AC-1: Pre-flight skip — Issues with
ready_for_mergeormergedstatus instate.jsonare excluded from execution with a clear warning:⚠️ #N: already ready_for_merge — skipping (use --force to re-run) - AC-2: --force override —
--forceflag bypasses the pre-flight state guard for all specified issues - AC-3: Stale worktree recreation — When an existing worktree's merge-base with
origin/mainis behind HEAD, the worktree is removed and recreated from current main (with warning). Worktrees with uncommitted changes are preserved with a warning instead. - AC-4: Chain mode compatibility — Stale worktree recreation in chain mode rebases the fresh worktree onto the chain base branch after creation
- AC-5: Auto-cleanup at run start —
sequant runperforms a lightweight state reconciliation at startup: checksready_for_mergeissues against GitHub (merged PRs) and git (git branch --merged main) to advance state tomerged - AC-6: Merger state update — Merger skill documentation includes explicit state update step (
update.ts merged <N>) after each successful merge - AC-7: Worktree cleanup after merge — Merger skill removes worktrees for successfully merged issues
- AC-8: Graceful degradation — All guards degrade gracefully: missing
state.json→ skip guard;ghauth failure → skip GitHub check; corrupted state → proceed with execution - AC-9: Tests — Unit tests cover: pre-flight skip, --force override, stale worktree detection, chain mode recreation, auto-cleanup state transitions, graceful degradation on missing state
Files to Modify
| File | Changes |
|---|---|
src/commands/run.ts |
Pre-flight state guard, worktree freshness check, auto-cleanup call, --force flag |
src/lib/workflow/state-utils.ts |
Lightweight startup reconciliation (git branch --merged + gh pr check) |
.claude/skills/merger/SKILL.md |
Add explicit state update and worktree removal steps |
src/commands/run.test.ts |
Tests for pre-flight, --force, stale worktree, chain mode |
src/lib/workflow/state-utils.test.ts |
Tests for auto-cleanup reconciliation |
Related
- Chain mode silently fails when worktrees pre-exist from earlier runs #289 — Chain mode worktree pre-existence (rebase fix — necessary but not sufficient)
- fix: Rebase worktrees onto main before PR to prevent lockfile drift #295 — Pre-PR rebase onto origin/main (lockfile drift prevention)
state.jsonalready tracksready_for_merge— this issue makes it a gate, not just a record
Activity
fix(#305): add pre-flight state guard and worktree lifecycle management
admarble commentedon Feb 20, 2026
Implementation Progress Update
Status: ✅ Complete - PR created
AC Coverage Summary
Files Changed
src/commands/run.tssrc/lib/workflow/state-utils.tsreconcileStateAtStartup(),isBranchMergedIntoMain(),isIssueMergedIntoMain()src/lib/workflow/state-utils.test.ts.claude/skills/merger/SKILL.mdTest Results
Test Coverage Analysis
src/commands/run.tssrc/lib/workflow/state-utils.ts.claude/skills/merger/SKILL.mdCoverage: 2/2 changed source files have corresponding tests
PR
PR #306: #306
Self-Evaluation
admarble commentedon Feb 20, 2026
QA Review for Issue #305
AC Coverage
run.ts:2446-2489- checks state.json and skips with warningrun.ts:1439, 2447- bypasses pre-flight guard for all specified issuescheckWorktreeFreshness()andremoveStaleWorktree()inrun.ts:143-276- handles uncommitted/unpushed changesrun.ts:625-635reconcileStateAtStartup()instate-utils.ts:859-939called atrun.ts:2422-2443SKILL.md:154and320-327include explicit state update commandsSKILL.md:143-155and201-217document worktree removal requirementrun.ts:2423-2443and2465-2470handle failures gracefullystate-utils.test.ts:598-986covers reconciliation, branch merge detection, graceful degradationCoverage: 9/9 AC items fully met
CI Status
build (18.x)build (20.x)build (22.x)validate-skillstypecheckvalidate-pluginCI Summary: 6 passed, 0 pending, 0 failed
Quality Metrics
any)Test Coverage Analysis
src/commands/run.tsrun.test.ts(existing)src/lib/workflow/state-utils.tsstate-utils.test.ts(extended)src/lib/workflow/state-utils.test.ts.claude/skills/merger/SKILL.mdCoverage: 2/2 changed source files have corresponding tests
Critical paths without tests: None
Code Review
Strengths:
Issues:
Suggestions:
run.ts:225- could be made configurable via settings.json in a future enhancementAnti-Pattern Detection
Code Patterns
No anti-patterns detected in changed files.
Critical Issues: 0
Warnings: 0
Self-Evaluation
Verdict: READY_FOR_MERGE
All 9 acceptance criteria are met. The implementation provides three robust defense layers:
The code handles edge cases gracefully (uncommitted changes, network failures, missing state files) and includes comprehensive unit tests.
Documentation
Next Steps
--forceflag additionadmarble commentedon Feb 20, 2026
QA Review for Issue #305
AC Coverage
run.ts:2446-2489- checks state.json and skips with clear warningforcefield added toRunOptionsinterface and logic works internally, but--forceis NOT registered as a CLI option inbin/cli.ts(lines 150-202). Users see "use --force to re-run" but cannot actually pass the flag.checkWorktreeFreshness()andremoveStaleWorktree()inrun.ts:163-294handle all edge casesrun.ts:624-635reconcileStateAtStartup()instate-utils.ts:859-939called atrun.ts:2422-2443SKILL.mdupdated with explicitnpx tsx scripts/state/update.ts merged $ISSUEstepSKILL.md:143-155documents worktree removal requirementrun.ts:2423-2443and2465-2470handle failures gracefullystate-utils.test.ts:590-986covers reconciliation, branch merge detection, graceful degradationCoverage: 8/9 AC items met
CI Status
build (18.x)build (20.x)build (22.x)validate-skillstypecheckvalidate-pluginCI Summary: 6 passed, 0 pending, 0 failed
Quality Metrics
any)Test Coverage Analysis
src/commands/run.tsrun.test.ts(existing)src/lib/workflow/state-utils.tsstate-utils.test.ts(extended)src/lib/workflow/state-utils.test.ts.claude/skills/merger/SKILL.mdCoverage: 2/2 changed source files have corresponding tests
Critical paths without tests: None
Code Review
Strengths:
WorktreeFreshnessResult,ReconcileOptions,ReconcileResult)isIssueMergedIntoMain: checks both git branch state AND merge commit messages (handles direct merges without PRs)spawnSynccalls use safe array syntax (no command injection risk)Issues:
--forceflag not registered in CLI (bin/cli.tsline 150-202). Theforceproperty exists inRunOptionsinterface and the runtime logic correctly checksmergedOptions.force, but there is no.option("-f, --force", ...)registered on theruncommand inbin/cli.ts. This means users will see "use --force to re-run" in output but cannot actually pass the flag. Commander.js will error on unrecognized options.Suggestions:
.option("-f, --force", "Force re-execution of completed issues")to the run command inbin/cli.ts(between--no-rebaseand.action(runCommand))run.ts:224) is hardcoded - could be configurable viasettings.jsonin a future enhancementAnti-Pattern Detection
Code Patterns
Critical Issues: 0
Warnings: 0
Security Scan
spawnSynccalls use array arguments (safe from command injection)Skill Command Verification
Skill files changed: 1 (
.claude/skills/merger/SKILL.md)Commands verified:
npx tsx scripts/state/update.ts merged $ISSUE- uses placeholder, syntax verifiedgit worktree remove "$worktree_path" --force- valid git commandgit worktree list | grep "feature/$ISSUE"- valid pipelineVerification Status: Passed (commands with placeholders, syntax valid)
Self-Evaluation
--forceflag silently not working because it's not registered in the CLI. Users would see the "use --force" message but be unable to actually use it.Verdict: AC_NOT_MET
8/9 ACs are MET, but AC-2 is NOT_MET. The
--forceflag is referenced throughout the codebase and works correctly at the TypeScript level, but it is not registered as a CLI option forsequant runinbin/cli.ts. This means the feature is unreachable from the command line.Fix required: Add
.option("-f, --force", "Force re-execution of completed issues")to the run command inbin/cli.ts.Next Steps
--forceCLI option registration inbin/cli.tsfor theruncommandsequant run --forceis recognizedQA performed with agent teams: type-checker, scope-checker, security-scanner, test-runner, ci-checker
fix(#305): register --force flag in CLI for run command
admarble commentedon Feb 20, 2026
QA Re-Review for Issue #305 (Post-Fix)
Fix Applied
Added
.option("-f, --force", "Force re-execution of completed issues (bypass pre-flight state guard)")to theruncommand inbin/cli.ts.Verified:
sequant run --helpnow shows the--forceflagUpdated AC Coverage
--forcenow registered in CLICoverage: 9/9 AC items met
Verdict: READY_FOR_MERGE
All 9 ACs are now met. CI is green. Tests pass. The
--forceflag is properly wired end-to-end.Next Steps
docs: update what-weve-built and changelog for #305
fix(#305): fill QA gaps — export + test worktree functions, fix merge…
docs: update what-weve-built and changelog for #305 gap fixes
test(#592): cover git-fallback escalation + cross-ref in what-weve-built
fix(#592): reconcile in_progress state when PR is merged on GitHub (#602
fix(#616): isBranchMergedIntoMain returns false for empty orphan bran…
chore(#606): tighten reconcile JSDoc, test names, and add waiting_for…
fix(#606): escalate waiting_for_qa_gate to merged when PR merged exte…
feat(#762): lightweight content pre-flight for --chain (#764)
feat(#804): --auto-wait — continue a rate-limited run when the window…
fix(#833): reject malformed numeric CLI flags instead of coercing the…
fix(#834): §7 gates must be reachable — lint /qa's own enforcement ch…
chore(#606): tighten reconcile JSDoc, test names, and add waiting_for…
feat(#762): lightweight content pre-flight for --chain