Skip to content

fix(state): reconcile false-positive — empty orphan branches mistakenly flagged as merged #616

Closed

Description

@admarble

Bug

npx sequant run <issues> falsely reports open issues as "already merged" after a previous run on those issues was interrupted (SIGINT) before any commits were made.

Reproduction

  1. Run npx sequant run 608 604 -q — sequant creates worktrees + branches feature/608-... and feature/604-... from main, starts the spec phase.
  2. Press ^C before any commit lands.
  3. SIGINT cleanup runs git worktree remove --force on each worktree. The underlying branches are not deleted — their tips equal the main commit they were forked from.
  4. Re-run npx sequant run 608 604 -q — both issues are skipped:
    !  #608: already merged — skipping (use --force to re-run)
    !  #604: already merged — skipping (use --force to re-run)
    
    Both issues are still OPEN on GitHub. State has been corrupted to status: "merged".

Root cause

isBranchMergedIntoMain in src/lib/workflow/pr-status.ts uses git branch --merged main, which lists any branch whose tip is reachable from main — including empty branches whose tip equals an old main ancestor with zero commits added. For the orphaned branches above, git branch --merged main returns them as "merged", isIssueMergedIntoMain returns true, and reconcileStateAtStartup advances the issue from in_progress to merged.

Confirmed locally: git rev-list --count main..feature/608-investigate-metrics-... is 0, and git branch --merged main lists both branches. No real merge ever occurred — git log main --grep "(#608)" and --grep "(#604)" return empty.

This is the inverse of #592 / #606 (which fix "state thinks open but GitHub says merged"). Here state thinks merged but GitHub says open.

Acceptance criteria

  • isBranchMergedIntoMain returns false for an empty branch whose tip is an ancestor of main with zero commits added.
  • isBranchMergedIntoMain continues to return true for an actually-merged branch (tip recorded as a non-first parent of a merge commit on the base branch).
  • isIssueMergedIntoMain continues to detect squash-merged issues via the existing (#N) / Merge #N commit-message grep (Method 2).
  • After SIGINT-then-rerun on an issue list, npx sequant run <issue> does not skip those issues as "already merged" when the branches are empty orphans with no commits.
  • Test: empty-branch fixture passed to isBranchMergedIntoMain returns false.
  • Test: empty-branch fixture passed to isIssueMergedIntoMain (via the branch-discovery Method 1 path) returns false when no (#N) commit exists.
  • Existing #305 tests for isBranchMergedIntoMain and isIssueMergedIntoMain updated to mock the new merge-evidence check (git rev-parse + git rev-list --merges --parents) instead of git branch --merged.
  • CHANGELOG entry under [Unreleased] / Fixed.

Out of scope (follow-up candidates)

  • Branch-deletion hygiene in SIGINT cleanup (deleting empty orphan branches alongside git worktree remove). The bug is fixed by the detection change alone; orphan-branch cleanup is a separate hygiene concern.

Activity

  1. added
    bug
    state
    cli
    on May 9, 2026
  2. admarble commented on May 9, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #616

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original isBranchMergedIntoMain returns false for empty orphan whose tip is an ancestor of main MET New impl resolves tip via git rev-parse and only returns true when tip appears as a non-first parent of a merge commit. Smoke-tested on a real ad-hoc test-orphan-616 branch off main: returns false (old code's git branch --merged main listed it as merged — confirmed).
    AC-2 Original Continues to return true for actually-merged branches MET Unit test L907-926 covers the merge-parent case. End-to-end check on real repo: isIssueMergedIntoMain(607) returns true (merged via squash, picked up by Method 2).
    AC-3 Original isIssueMergedIntoMain Method 2 (#N)/Merge #N grep unchanged MET pr-status.ts:140-168 is byte-identical to main; squash-merge detection path is unchanged.
    AC-4 Original After SIGINT-then-rerun, run does not skip empty-orphan issues MET Fix is at the detection layer; reconcileStateAtStartup no longer advances in_progress → merged for empty branches. Verified end-to-end with the smoke test above.
    AC-5 Original Test: empty-branch fixture → isBranchMergedIntoMain returns false MET state-utils.test.ts:928-948.
    AC-6 Original Test: empty-branch fixture → isIssueMergedIntoMain Method 1 returns false when no (#N) exists MET state-utils.test.ts:1034-1098 ("regression: empty feature branch from interrupted run is NOT detected as merged"), uses production issue numbers 608 in fixture.
    AC-7 Original Existing #305 tests updated to mock new merge-evidence check MET All four isBranchMergedIntoMain (#305) tests and the reconcileStateAtStartup test L790-869 now mock git rev-parse + git rev-list --merges --parents. git branch --merged mocking removed.
    AC-8 Original CHANGELOG entry under [Unreleased] / Fixed MET CHANGELOG.md line 19 — comprehensive entry naming the function, root cause, and prior #592/#606 cross-reference, with issue tag (#616).

    Coverage: 8/8 AC items met
    Original ACs: 8/8 met
    Derived ACs: N/A — no /spec quality plan in issue comments

    Quality Plan Verification

    N/A — no Feature Quality Planning section found in issue #616 comments.

    Incremental QA Summary

    N/A — first QA run.

    CI Status

    Check State Bucket Impact
    build (20.x) SUCCESS pass ✅ MET
    build (22.x) SUCCESS pass ✅ MET
    typecheck SUCCESS pass ✅ MET
    validate-plugin SUCCESS pass ✅ MET
    validate-skills SUCCESS pass ✅ MET

    CI Summary: 5 passed, 0 pending, 0 failed. PR #617 mergeable=MERGEABLE, mergeStateStatus=CLEAN.

    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 3 OK
    Lines added +232 -
    Lines deleted -63 -

    Cache Status

    N/A — caching not configured for this run.

    Build Verification

    N/A — npm run build passed on the feature branch.

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/workflow/pr-status.ts Standard (state/CLI flow) ✅ Yes src/lib/workflow/state-utils.test.ts (re-exports + tests pr-status exports; 33/33 passed)
    src/lib/workflow/state-utils.test.ts — (test file) — —
    CHANGELOG.md Optional (docs) — —

    Coverage: 1/1 changed source files have corresponding tests
    Critical paths without tests: None

    Code Review

    Strengths:

    • New doc-block on isBranchMergedIntoMain is excellent — defines "merged" precisely (non-first parent of a merge commit), names the squash-merge caveat, and points callers at isIssueMergedIntoMain's grep path for squash detection.
    • Implementation is small, surgical, and contained to one function. Defensive: returns false on unresolved branch, malformed merge lines (parts.length > 2), and any thrown error.
    • Regression test mirrors the production reproduction from the issue body verbatim (issue numbers 608/604), satisfying the verbatim-fixture preference.
    • Existing fix: pre-flight state guard and worktree lifecycle management #305 tests cleanly migrated rather than duplicated; mock surface (rev-parse + rev-list --merges --parents) matches the new implementation.
    • Verified end-to-end on this repo: created an empty test-orphan-616 branch off main — old logic (git branch --merged main) lists it as merged; new logic returns false.

    Issues:

    • pr-status.ts:106 doc-comment for isIssueMergedIntoMain still says: "1. Check if branch exists and is merged via git branch --merged <baseBranch>". Method 1 no longer uses git branch --merged — it now delegates to the rewritten isBranchMergedIntoMain. Stale and misleading after this PR; should read something like "1. Check via isBranchMergedIntoMain (branch tip recorded as a non-first parent of a merge commit on the base branch)". Non-blocking but worth fixing in this PR or as a follow-up.

    Suggestions:

    • The new check uses -200 as the merge lookback. Sequant's main has ~29 merge commits today, so this is comfortably sufficient. If the project ever grows past ~200 merge commits and an issue's merge sits older than that window, the check could miss it — but Method 2's commit-message grep ((#N) / Merge #N) covers that case in isIssueMergedIntoMain, so this is a graceful degradation, not a hazard. Worth a one-line code comment on -200 if it's revisited.
    • Fast-forward merges (no merge commit produced) will now return false from isBranchMergedIntoMain where the old code would return true. This is by design per the AC-2 wording ("non-first parent of a merge commit"), and isIssueMergedIntoMain Method 2 still picks up FF merges via the conventional-commit (#N) suffix in sequant's workflow. No action needed; flagging for future readers of the diff.

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Tests assert on returned booleans, not on internals.
    Coverage Depth ✅ OK Empty-orphan, non-existent branch, no-merges-on-base, real-merge, and Method 2 (Merge #N) all covered.
    Mock Hygiene ✅ OK Only child_process.spawnSync is mocked — the external boundary. No internal modules mocked.
    Test Reliability ✅ OK No timing/network/IO; mockSpawnSync.mockReset() in each beforeEach.

    Issues Found: None.

    Anti-Pattern Detection

    Dependency Audit

    N/A — package.json not modified.

    Code Patterns

    File:Line Category Pattern Suggestion
    — — None detected —

    Critical Issues: 0
    Warnings: 0

    Call-Site Review

    N/A — no new exported functions; isBranchMergedIntoMain was modified in place. Existing call sites in isIssueMergedIntoMain (pr-status.ts:133) and reconcileStateAtStartup (via state-utils re-export) remain unchanged and pass through correctly under the new behavior (verified by the smoke test and existing test L790-869).

    Execution Evidence

    Test Type Command Exit Code Result
    Unit tests npx vitest run src/lib/workflow/state-utils.test.ts 0 33/33 passed
    Build npm run build 0 clean
    Smoke (empty orphan) npx tsx -e calling isBranchMergedIntoMain("test-orphan-616") 0 false (matches AC-1 expectation; old code would return true)
    Smoke (real merge) isIssueMergedIntoMain(607) 0 true (squash-merged via Method 2; AC-3 preserved)
    Smoke (open issue) isIssueMergedIntoMain(616) 0 false

    Evidence status: Complete

    Skill Command Verification

    N/A — no .claude/skills/**/*.md files modified.

    CLI Registration Verification

    N/A — RunOptions and bin/cli.ts not modified.

    Smoke Test

    Test Command Result Notes
    Happy path (real merge) isIssueMergedIntoMain(607) ✅ true Squash-merge correctly detected by Method 2.
    Bug-repro path Created empty test-orphan-616 branch off main; called isBranchMergedIntoMain ✅ false Old code returns true here (git branch --merged main lists the branch); new code returns false.
    Negative path isBranchMergedIntoMain("does/not/exist") ✅ false git rev-parse non-zero status → early return.

    Smoke Test Status: Complete

    Self-Evaluation

    • Verified working: Yes — created an actual empty orphan branch off main in this repo and confirmed isBranchMergedIntoMain now returns false where the old git branch --merged main path returned the branch as merged. Cross-checked against a real squash-merged issue (feat(#552): detect behavior-rule implementations across skill+runtime touchpoints #607) to confirm Method 2 still flips true.
    • Test efficacy: High — the regression test mirrors the production scenario (issue numbers 608/604, branch name feature/608-investigate-metrics-gap) and asserts on the post-fix outcome (false). It would catch a regression to git branch --merged-style logic immediately.
    • Likely failure mode in production: A merged feature whose merge commit sits past the -200 lookback in git rev-list. In sequant's repo (~29 merges) this is far off, and isIssueMergedIntoMain Method 2 ((#N) grep) catches squash-merges regardless. Acceptable.
    • Verdict confidence: High — ACs literally verified, end-to-end behavior reproduced on the real bug scenario, CI all green, no anti-patterns.

    Verdict: AC_MET_BUT_NOT_A_PLUS

    All 8 acceptance criteria are literally met, tests pass (33/33), build is clean, CI is green, and the fix has been end-to-end-verified against the actual bug repro on this repo. The single non-A+ blocker is a stale doc-comment at pr-status.ts:106 describing Method 1 as using git branch --merged <baseBranch> — that's no longer true after this change. Tiny, non-blocking, but should be tightened either in this PR or as a follow-up so future readers don't trust a stale description.

    Documentation

    • CHANGELOG entry added ([Unreleased] / Fixed, with issue tag (#616))
    • N/A — no README/docs changes needed (internal lib behavior fix)
    • Polish: pr-status.ts:106 doc-comment for isIssueMergedIntoMain Method 1 still references git branch --merged; recommend updating to reflect the new merge-evidence check.

    Next Steps

    1. (Optional, polish) Update the stale doc-comment at src/lib/workflow/pr-status.ts:106 so Method 1 no longer references git branch --merged. One-line edit; can be appended to this PR or filed as a follow-up.
    2. Run /docs 616 if any user-facing surface is being touched (none in this PR — fix is internal logic; CHANGELOG already covers the user-visible behavior change).
    3. Merge PR fix(#616): isBranchMergedIntoMain returns false for empty orphan branches #617 (mergeable=MERGEABLE, mergeStateStatus=CLEAN, all 5 CI checks green).
  3. added
    needs-improvement
    on May 9, 2026
  4. added a commit that references this issue on May 9, 2026
  5. admarble commented on May 10, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #616 (re-run on 263369c)

    Incremental re-run after the doc-comment gap from the prior AC_MET_BUT_NOT_A_PLUS verdict was closed by 263369c docs(#616): correct stale Method 1 description on isIssueMergedIntoMain.

    Incremental QA Summary

    Last QA: prior run on ac2be37 (verdict: AC_MET_BUT_NOT_A_PLUS — sole blocker: stale doc-comment at pr-status.ts:106)
    Changes since last QA: 1 file (src/lib/workflow/pr-status.ts, +1/-1 in the isIssueMergedIntoMain JSDoc)

    Check / AC Status Re-run? Reason
    AC-1 … AC-8 MET Cached Source code for isBranchMergedIntoMain and tests unchanged since ac2be37; verified verbatim
    Type safety PASS Re-evaluated Confirmed clean on the new commit
    Tests 33/33 PASS Re-evaluated npx vitest run src/lib/workflow/state-utils.test.ts
    Build PASS Always fresh npm run build clean — JSDoc {@link} parses fine
    CI status PASS Always fresh All 5 checks now SUCCESS on 263369c (were pending at last QA)
    Doc-comment gap RESOLVED Re-evaluated New Method 1 line: 1. Find \feature/-*` branches with `git branch -a` and check via {@link isBranchMergedIntoMain}`

    Summary: 8 ACs cached as MET, 4 always-fresh (build + CI + tests + the gap), 0 regressions.

    CI Status

    Check State Bucket Impact
    build (20.x) SUCCESS pass ✅ MET
    build (22.x) SUCCESS pass ✅ MET
    typecheck SUCCESS pass ✅ MET
    validate-plugin SUCCESS pass ✅ MET
    validate-skills SUCCESS pass ✅ MET

    CI Summary: 5 passed, 0 pending, 0 failed. PR #617 mergeable=MERGEABLE, mergeStateStatus=CLEAN.

    Stale Branch Check

    Check Value
    Commits behind main 1
    Threshold 5
    Status ✅ OK (within threshold)

    The branch is one commit behind main — 60778b6 fix(#614): resolve npm audit cluster 1 landed on main during this session. Unrelated to this PR's surface area; no rebase required.

    Quality Metrics (cumulative diff vs main)

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 3 OK
    Lines added +233 -
    Lines deleted -64 -

    Code Review (delta from prior QA)

    Strengths:

    • The gap-fix commit is surgical: one JSDoc line, no runtime change. {@link isBranchMergedIntoMain} keeps the precise definition of "merged" in one place (the docblock on isBranchMergedIntoMain, which already covers "non-first parent of a merge commit" and the squash-merge caveat) — eliminates the drift surface that produced the original gap.
    • Per feedback_gap_fix_review.md (gap-fix commits need their own adversarial pass): re-grep'd git branch --merged across src/ — only the remaining hit is at pr-status.ts:46, inside the rewritten function's own docblock, intentionally referencing "the older `git branch --merged` check" as historical context. Keep.
    • Per feedback_gap_fixing_diminishing_returns.md: the two prior "Suggestions" (-200 lookback rationale comment, FF-merge note) were correctly left out of scope — they were forward-looking polish, not unmet ACs.

    Issues: None.

    Suggestions: None.

    Adversarial Pass on the Gap-Fix Commit (per feedback_gap_fix_review.md)

    Question Answer
    Did the fix introduce new gaps? No — single-line JSDoc edit; no runtime, types, or test surface affected.
    Does {@link isBranchMergedIntoMain} resolve correctly? Yes — tsc passed; same-file reference; no hyperlink rendering needed.
    Does the new prose match the actual code? Yes — pr-status.ts:119 does git branch -a; :127-128 filters with feature/<N>-... regex; :133 calls isBranchMergedIntoMain.
    Anywhere else still saying "git branch --merged" in a misleading way? No — only :46 (intentional historical context) and the two test-file comments at state-utils.test.ts:931, :1038 (intentional contrast with old behavior).
    Stale branch (1 commit behind main) introduce conflict risk? No — #614 touched package.json/package-lock.json/audit deps; this PR touches src/lib/workflow/pr-status.ts, state-utils.test.ts, CHANGELOG.md. No path overlap. gh pr view reports MERGEABLE / CLEAN.

    Self-Evaluation

    • Verified working: Yes — re-confirmed isBranchMergedIntoMain smoke (empty orphan → false; merged #607 → true) on ac2be37 in the prior QA. 263369c is JSDoc-only; nothing to re-execute.
    • Test efficacy: High — 33/33 pass; regression test for the empty-orphan scenario remains.
    • Likely failure mode: Same as prior QA — none affecting this PR's contract; -200 lookback caveat is graceful degradation covered by Method 2's commit-message grep.
    • Verdict confidence: High.

    Verdict: READY_FOR_MERGE

    All 8 ACs MET (unchanged from prior QA), CI is fully green on the head SHA, the sole AC_MET_BUT_NOT_A_PLUS blocker (stale Method 1 doc-comment) is resolved by 263369c, no new gaps introduced, branch is mergeable and clean.

    Documentation

    • CHANGELOG entry present under [Unreleased] / Fixed with issue tag (#616).
    • Internal JSDoc now accurate.
    • N/A — no README/docs changes needed (internal lib behavior fix).

    Next Steps

    1. Merge PR fix(#616): isBranchMergedIntoMain returns false for empty orphan branches #617. Recommended squash to keep the 2-commit fix as a single fix(#616) entry on main.
    2. After merge, sequant's reconcileStateAtStartup will no longer falsely advance empty-orphan SIGINT-aborted issues from in_progress to merged — the original repro condition will be resolved on the next release.
    3. Optional follow-up (out of scope): if -200 lookback ever becomes a concern as the repo grows, file an issue to revisit; not actionable today (sequant has ~29 merge commits on main).
  6. added
    ready-for-review
    and removed
    needs-improvement
    on May 10, 2026
  7. added a commit that references this issue on May 10, 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

    bugcliready-for-reviewstate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions