You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
cleanup-worktree: unanchored substring matcher can delete the wrong branch (838 matched feature/1838-other-work) #844
So 838 matches feature/1838-other-work, and whichever worktree git worktree list --porcelain emits first wins. Reproduced: invoking with 838 resolved to and deleted feature/1838-other-work.
This shape is pre-existing, but #838 changed its consequence in two ways:
Arbitrary globs are also accepted, not just the documented feature/<issue>-* shape: 'feature/*' now resolves to an arbitrary feature branch and tears it down (pre-#838 it errored out).
Acceptance Criteria
AC-1: A bare issue number anchors to the issue-number position in the branch name, so 838 does not match feature/1838-other-work.
AC-2: When the argument matches more than one worktree branch, the script exits non-zero listing every candidate instead of silently picking the first.
AC-3: An over-broad glob that matches multiple branches (e.g. 'feature/*') is rejected by the same ambiguity check rather than tearing down an arbitrary branch.
AC-4: A regression test covers a multi-match fixture for each documented input form; no such fixture exists today.
Chosen design: tiered resolution, multi-match fatal at every tier. Each tier either resolves uniquely, falls through on zero matches, or exits non-zero listing every candidate (branch + path) on 2+:
Candidates — porcelain entries with a branch refs/heads/ line, minus the main worktree (first entry) and minus exec-agent-* branches.
Exact — branch equals the argument. Unique by construction; resolve immediately.
Anchored — branch's last path segment equals the argument, plus, when the argument is all digits, the parseIssueNumberFromBranch inverse: feature/<N>-*, feature/<N>, issue-<N>, <N>-*.
Glob — only when the argument contains *, ?, or [: plain case glob match.
Why this shape
The mis-resolution is deterministic, not a race: porcelain sorts linked worktrees lexicographically by directory basename, and 1838-… < 838-…, so 838 reliably picks feature/1838-other-work when both exist.
The anchored tier is a literal transcription of existing TS behavior — parseIssueNumberFromBranch (src/lib/workflow/worktree-discovery.ts:75-95) and src/lib/merge-check/index.ts:140 are both ^-anchored. The shell script is currently the codebase's only unanchored matcher.
"Keep substring, just add an ambiguity check" is not viable: 838 would still match feature/1838-other-work (fails AC-1, now as an error instead of a wrong delete), and bare issue numbers become permanently ambiguous against exec-agent-<N>-<i> sub-worktree branches — which are real porcelain candidates (this script's own exec-agent reaping at lines 219-235 proves orphans occur). Anchoring first is what makes the ambiguity check fire only on genuine ambiguity.
Globs are kept (with the multi-match-fatal rule) rather than dropped: the 'feature/<issue>-*' form is prescribed in six mirrored locations (fullsolve/SKILL.md:678 ×3 dirs, docs/troubleshooting.md:46, and this script's own --help), and AC-3's wording presumes globs survive behind the ambiguity check.
AC mapping
AC-1: tier 3 anchoring — 838 cannot match feature/1838-other-work.
AC-2: 2+ matches in any tier → exit 1 listing all candidates.
AC-3: 'feature/*' matching 2+ branches hits the same check; a glob matching exactly one branch still resolves (the AC's literal ask).
AC-4: multi-match fixture per documented form (bare number, glob, full name) via the existing harness in __tests__/cleanup-worktree-branch-resolution.integration.test.ts.
Implementation constraints (verified)
Main-worktree exclusion is load-bearing: today '*' resolves to main and reaches git worktree remove "$MAIN_WORKTREE" — but only after the exec-agent-* branch-delete sweep has already run.
The existing test at __tests__/cleanup-worktree-branch-resolution.integration.test.ts:230 passes the non-numeric partial 838-spaced; it survives only via tier 3's last-segment-equals rule. Do not regress it.
Exact tier must win outright: feature/838-fix and feature/838-fix-more can coexist (title truncation at new-feature.sh:88-90), and typing the full name must not trip the ambiguity check.
bash 3.2 floor (macOS): all-digits test is case "$ARG" in ''|*[!0-9]*), glob-detection is case "$ARG" in *[*?[]*); no arrays/mapfile. Process substitution keeps loop variables in the current shell.
The help text (lines 39-46) and header comment (lines 5-11) document "any substring of the branch" — rewrite both, plus the six doc/skill call sites above (three mirrored skill dirs must stay in sync).
Behavior narrowing to state explicitly: bugfix/838-x is no longer reachable by bare 838 (not a sequant branch shape); full name and glob forms still reach it.
A detailed design already lives in the "Decision: ambiguity semantics" comment above, and it holds up against the code. This plan confirms that design and adds two scope corrections verified against the tree.
AC Quality Check
All four ACs are measurable and independently testable. No vague/unmeasurable/open-ended language. AC-2 explicitly pins the failure mode (non-zero exit, list all candidates); AC-4 names the missing artifact (multi-match fixture per input form). ✅ No lint concerns.
Scope Assessment
Non-Goals:⚠️ No Non-Goals section in the issue. Implicit boundary from the design comment (adopt): keep the glob form, keep exact-name resolution, do not re-architect resolution beyond anchoring + ambiguity — bugfix/838-x intentionally becomes unreachable by bare 838 (not a sequant branch shape).
Metric
Value
Status
Feature count
1 (branch resolver)
✅
AC items
4
✅
Directory spread
2 (templates/scripts/, __tests__/)
✅
Verdict: ✅ SCOPE_OK
🔧 Scope corrections (verified against the tree)
1. The script is ONE real file — the other two are symlinks.
Edit onlytemplates/scripts/cleanup-worktree.sh; the symlinks propagate. Do not create/edit the other two (scripts/dev/ is gitignored anyway).
2. The external doc/skill "call sites" need no invocation change — the prose scope is narrower than the design comment implies.
All six prescribed call sites use the glob form'feature/<issue-number>-*' (fullsolve/SKILL.md:678 ×3 identical mirrors, docs/troubleshooting.md:46, plus the script's own --help). A feature/<N>-* glob resolves to exactly one branch in practice, so it stays valid behind the ambiguity check — no change required, and therefore no 3-dir SKILL.md sync required.
The only prose asserting the now-false semantics is inside the script: header comment (line 5, "any substring") and help text (line 40, 838 an issue number, or any substring of the branch). Rewrite those two in-file. (Optional: add a one-line "bare numbers now anchor to the issue-number position" note — but that's the only thing that would pull in the 3 mirrored SKILL.md files, so skip unless desired.)
Acceptance Criteria
AC-1: Bare issue number anchors to the issue-number position (838 ≠ feature/1838-other-work)
Verification: Integration Test Scenario: Given worktrees feature/838-fix and feature/1838-other → When invoked with 838 → Then resolves feature/838-fix only; feature/1838-other is never a candidate. Assumptions: Anchoring mirrors parseIssueNumberFromBranch (worktree-discovery.ts:75–95, ^-anchored) — verified: feature/<N>-*, feature/<N>, issue-<N>, <N>-*.
AC-2: Multi-match → exit non-zero, list every candidate (no first-wins)
Verification: Integration Test Scenario: Given two branches an argument matches → When invoked → Then exit ≠ 0 and stdout/stderr lists each candidate branch + path; no worktree/branch is deleted. Assumptions: The mis-match is deterministic (porcelain sorts linked worktrees lexicographically by basename; 1838- < 838-), not a race — so a fixture reliably reproduces first-wins today.
AC-3: Over-broad glob ('feature/*') hits the same ambiguity check
Verification: Integration Test Scenario: Given ≥2 feature branches → When invoked with 'feature/*' → Then rejected via the AC-2 path (exit non-zero, candidates listed), nothing torn down. A glob matching exactly one branch still resolves normally. Assumptions: Glob detection is bash-3.2-safe (case "$ARG" in *[*?[]*)); glob tier only fires when the arg contains */?/[.
AC-4: Regression fixture — a multi-match case per documented input form
Verification: Integration Test Scenario: Extend __tests__/cleanup-worktree-branch-resolution.integration.test.ts with a multi-branch sandbox; parametrize a multi-match assertion over {bare number, glob, full name}. Assumptions: Existing harness (real throwaway repo + stubbed gh) is reused. Note: full-literal-name is unambiguous by construction, so its "multi-match" case is the exact-tier-wins guard (feature/838-fix + feature/838-fix-more coexisting must NOT trip the check).
Replace the single unanchored case "$_wt_branch" in *"$BRANCH_NAME"* | $BRANCH_NAME) arm (line 160) with candidate collection + tiered resolution:
Collect candidates into a newline-delimited list (bash 3.2: no arrays; keep the while IFS= read -r loop). Exclude the main worktree (first porcelain entry — load-bearing: today '*' reaches git worktree remove "$MAIN_WORKTREE") and exec-agent-* branches.
Anchored tier — last path segment == arg; when arg is all-digits (case "$ARG" in ''|*[!0-9]*)), also accept feature/<N>-*, feature/<N>, issue-<N>, <N>-*. Must still pass the existing 838-spaced last-segment case (test:230).
Glob tier — only when arg contains *?[ — plain case glob.
Ambiguity check — any tier yielding 2+ candidates → print all (branch + path), exit 1. Zero → fall through to the next tier; all tiers empty → existing "Worktree not found".
Phase 2 — In-file docs
Rewrite header line 5 and help line 40 to drop "any substring"; describe anchored bare-number + quoted-glob + full-name forms.
Phase 3 — Regression tests (AC-4)
Add multi-match fixtures to the existing integration test; parametrize over the three input forms. Include an exact-tier-wins negative case.
Design Review
Where does this logic belong? In the shell resolver block of cleanup-worktree.sh — it's the codebase's only unanchored matcher; the TS side (parseIssueNumberFromBranch, merge-check/index.ts:140) is already ^-anchored and is the pattern to mirror.
Simplest correct approach? Tiered exact → anchored → glob, multi-match-fatal at every tier. Rejected: "keep substring + add ambiguity check" — 838 would still collide with 1838 (fails AC-1) and bare numbers stay permanently ambiguous vs real exec-agent-<N>-<i> candidates. Anchoring first is what makes the ambiguity check fire only on genuine ambiguity.
Existing pattern? The ^feature/(\d+)(?:-|$) family from parseIssueNumberFromBranch — transcribed into bash 3.2 case globs.
What would a reviewer challenge? "Why not drop globs?" → six prescribed call sites + AC-3 presume they survive. "Why exclude the main worktree?" → without it 'feature/*'/'*' can resolve to main and remove it. "bash 3.2?" → macOS floor: no arrays/mapfile, process-substitution to keep loop vars in the current shell.
Feature Quality Planning
Standard checks pass. Notable items:
Gate-test discipline (CLAUDE.md): AC-4 fixtures gate the anchoring + ambiguity claims → mutation-verify: revert the anchoring arm, confirm exactly the new multi-match test fails (not a broad file-match), restore, and record the result in the PR body. The tautology detector won't catch a fixture that never exercises the multi-match path (cf. feat(#819): shared trust-model block — issue/PR text is data, not agent instructions #830).
set -e interaction: the ambiguity exit 1 is intended; ensure candidate-collection subshells don't trip set -e prematurely on zero matches.
Open Questions
Message channel for the ambiguity error — stderr + exit 1 (recommended, matches the existing ❌ Error + exit 1 convention at line 171). Impact if wrong: automation can't distinguish "ambiguous" from "not found."
Optional bare-number-anchoring note in the 3 SKILL.md mirrors — Recommendation: skip (keeps scope to 2 dirs). Impact if added: pulls in the 3-dir sync + a lint:skill-calls/doc-consistency pass.
Recommended Workflow
Phases: spec → exec → qa Quality Loop: enabled (matches the /assess recommendation above; destructive-op fix warrants the second pass) Reasoning: Bug fix with an existing integration harness — no separate testgen phase (AC-4 is the test work and stubs add little over the live harness). No ui/browser phase (shell script). security-review not warranted: no new external input surface; the change narrows a destructive matcher.
Label Review
Current:(none) Recommended:bug Reason: Reproduced destructive mis-resolution; not an enhancement. No complex/refactor (localized single-file fix + tests). Quality Loop: Already flagged on via the /assess comment (quality-loop=true); bug label alone won't auto-enable it, so keep the -Q flag when running.
Tiered, anchored branch resolver landed in templates/scripts/cleanup-worktree.sh (the two scripts/* copies are symlinks). Unanchored substring + first-match-wins is gone; bare numbers anchor to the issue-number position and any 2+-way match is fatal.
AC coverage
AC
Description
Status
AC-1
Bare number anchors (838 ≠ feature/1838-other-work)
✅ Implemented
AC-2
Multi-match → exit non-zero, lists every candidate
Tiered, anchored branch resolver in templates/scripts/cleanup-worktree.sh closes the destructive mis-resolution. All 4 ACs met with A+ quality; reviewed inline (301-line diff, single script + its integration test).
AC Coverage
AC
Description
Status
Evidence
AC-1
Bare number anchors (838 ≠ feature/1838-other-work)
✅ MET
anchored tier feature/<N>-* etc.; test AC-1 (900→900-fix, never 1900)
AC-2
Multi-match → exit non-zero, lists every candidate
The integration test executes the real script end-to-end against a throwaway git repo with real worktrees, across all three documented input forms plus the ambiguity paths. Mutation-verified (from exec, re-confirmed): reverting the anchoring → only AC-1 fails; first-match-wins instead of the gate → exactly AC-2/AC-3 multi-match tests fail while the single-match glob test stays green.
Code Review
Strengths:
Tiered exact→anchored→glob is the minimal correct shape; anchoring mirrors the already-^-anchored parseIssueNumberFromBranch. First-match-wins is fully eliminated (2+ in any tier is fatal).
bash 3.2-safe throughout: no arrays/mapfile; _branch_matches used only as an if condition so non-zero returns don't trip set -e; 1 never evaluates to 0; process substitution keeps match counters in the current shell.
Main-worktree + exec-agent-* exclusion is load-bearing and correctly placed (prevents 'feature/*'/'*' from resolving to and removing main).
#575 (spaces in path) and #750 (unmerged-PR gate) regressions preserved — both green.
Issues: none.
Adversarial edge-case trace
feature/838 + feature/838-fix under arg 838 → both anchored-match → ambiguous exit, not a wrong-delete (safe).
_branch_matches returns on first sub-rule, so a branch matching both last-segment and a numeric shape is counted once (no double-count).
Glob arg (feature/*) can't false-match in exact/anchored (string-equality / segment-equality both fail) → falls cleanly to glob tier.
Git refs can't contain *?[, so a full branch name never spuriously trips _is_glob.
Risk Assessment
Likely failure mode: none identified for the safety property — every single-resolution path is anchored or exact; ambiguity is always fatal. Worst realistic case is a refusal (exit 1 asking for the full name), which is the intended safer behavior.
Not tested: paths containing a literal tab or $ (out of scope; same assumption class as the pre-existing code).
Sibling sites considered (cross-file, §5):new-feature.sh (creates, only prints a git branch -D suggestion — no substring-driven deletion) and list-worktrees.sh (read-only) checked — no other unanchored destructive branch matcher exists; the TS side was already ^-anchored. The lone *"\$BRANCH_NAME"* hit is the old code quoted inside a comment, not active.
Sibling-line audit (intra-file, §4 Q5): the only argument-vs-branch matcher in the file is this resolver; downstream consumers use the exact $RESOLVED_BRANCH; the exec-agent-* reaping uses a fixed glob, not the user argument.
Trust-Boundary Check
Finding: Clean — the diff implements only the product requirement (anchored resolver + ambiguity gate + docs + tests). No agent-directed instruction in the issue body was acted on. Status: Clean
Behavior-Rule Survival Check
Old unanchored-substring matcher fully removed from active code (survives only as before/after documentation inside a comment). Status: Clean
Status: Complete. The committed integration suite runs the actual script across every documented form and the destructive ambiguity paths, green in CI — the integration coverage §11's /verify gate exists to guarantee. The /spec plan deliberately designated this harness as the verification vehicle (phases spec→exec→qa, no separate /verify). A separate /verify is therefore redundant here; a maintainer wanting a live manual capture can still run /verify 844 --command "bash scripts/cleanup-worktree.sh --help" (richer live repro is blocked in this environment by the commit-guard hook, not by the change).
CHANGELOG Verification
Check
Status
CHANGELOG.md exists
✅
User-facing change
✅ (fix(#844); documented command)
[Unreleased] entry
✅ Added during QA (### Fixed, includes (#844))
Adversarial Re-Read
Findings: No gaps found — traced all three tiers against the AC text; ran every documented-form fixture via the committed suite (all pass); confirmed the "evidence" is post-fix validation (real script executes the anchored resolver), not a pre-fix repro; inspected process state (clean tree, 0 behind main, CI green); cited cross-file and intra-file sibling sites explicitly; the sole Non-Goal (bugfix/838-x unreachable by bare 838) is intended and documented, not silent scope creep. Status: Clean
Activity
admarble commentedon Jul 29, 2026
#844 — cleanup-worktree: unanchored substring matcher can delete the wrong branch (838 matched feature/1838-other-work)
Open
────────────────────────────────────────────────────────────────
→ PROCEED — Reproduced destructive mis-match; anchor issue-number matching + ambiguity check with regression fixtures
Commands:
sequant run 844 -Q
spec → exec → qa · 4 ACs
────────────────────────────────────────────────────────────────
⚠ Mis-resolution deletes local AND remote branch since #838 — reproduced, not theoretical
────────────────────────────────────────────────────────────────
admarble commentedon Jul 29, 2026
Decision: ambiguity semantics (research summary)
Chosen design: tiered resolution, multi-match fatal at every tier. Each tier either resolves uniquely, falls through on zero matches, or exits non-zero listing every candidate (branch + path) on 2+:
branch refs/heads/line, minus the main worktree (first entry) and minusexec-agent-*branches.parseIssueNumberFromBranchinverse:feature/<N>-*,feature/<N>,issue-<N>,<N>-*.*,?, or[: plaincaseglob match.Why this shape
1838-… < 838-…, so838reliably picksfeature/1838-other-workwhen both exist.parseIssueNumberFromBranch(src/lib/workflow/worktree-discovery.ts:75-95) andsrc/lib/merge-check/index.ts:140are both^-anchored. The shell script is currently the codebase's only unanchored matcher.838would still matchfeature/1838-other-work(fails AC-1, now as an error instead of a wrong delete), and bare issue numbers become permanently ambiguous againstexec-agent-<N>-<i>sub-worktree branches — which are real porcelain candidates (this script's own exec-agent reaping at lines 219-235 proves orphans occur). Anchoring first is what makes the ambiguity check fire only on genuine ambiguity.'feature/<issue>-*'form is prescribed in six mirrored locations (fullsolve/SKILL.md:678 ×3 dirs, docs/troubleshooting.md:46, and this script's own--help), and AC-3's wording presumes globs survive behind the ambiguity check.AC mapping
838cannot matchfeature/1838-other-work.'feature/*'matching 2+ branches hits the same check; a glob matching exactly one branch still resolves (the AC's literal ask).__tests__/cleanup-worktree-branch-resolution.integration.test.ts.Implementation constraints (verified)
'*'resolves tomainand reachesgit worktree remove "$MAIN_WORKTREE"— but only after theexec-agent-*branch-delete sweep has already run.__tests__/cleanup-worktree-branch-resolution.integration.test.ts:230passes the non-numeric partial838-spaced; it survives only via tier 3's last-segment-equals rule. Do not regress it.feature/838-fixandfeature/838-fix-morecan coexist (title truncation at new-feature.sh:88-90), and typing the full name must not trip the ambiguity check.case "$ARG" in ''|*[!0-9]*), glob-detection iscase "$ARG" in *[*?[]*); no arrays/mapfile. Process substitution keeps loop variables in the current shell.bugfix/838-xis no longer reachable by bare838(not a sequant branch shape); full name and glob forms still reach it.admarble commentedon Jul 29, 2026
📋 Plan (spec)
Complexity: Standard (4 ACs, ~2 directories)
A detailed design already lives in the "Decision: ambiguity semantics" comment above, and it holds up against the code. This plan confirms that design and adds two scope corrections verified against the tree.
AC Quality Check
All four ACs are measurable and independently testable. No vague/unmeasurable/open-ended language. AC-2 explicitly pins the failure mode (non-zero exit, list all candidates); AC-4 names the missing artifact (multi-match fixture per input form). ✅ No lint concerns.
Scope Assessment
Non-Goals:⚠️ No Non-Goals section in the issue. Implicit boundary from the design comment (adopt): keep the glob form, keep exact-name resolution, do not re-architect resolution beyond anchoring + ambiguity —
bugfix/838-xintentionally becomes unreachable by bare838(not a sequant branch shape).templates/scripts/,__tests__/)Verdict: ✅ SCOPE_OK
🔧 Scope corrections (verified against the tree)
1. The script is ONE real file — the other two are symlinks.
Edit only
templates/scripts/cleanup-worktree.sh; the symlinks propagate. Do not create/edit the other two (scripts/dev/is gitignored anyway).2. The external doc/skill "call sites" need no invocation change — the prose scope is narrower than the design comment implies.
All six prescribed call sites use the glob form
'feature/<issue-number>-*'(fullsolve/SKILL.md:678 ×3 identical mirrors, docs/troubleshooting.md:46, plus the script's own--help). Afeature/<N>-*glob resolves to exactly one branch in practice, so it stays valid behind the ambiguity check — no change required, and therefore no 3-dir SKILL.md sync required.The only prose asserting the now-false semantics is inside the script: header comment (line 5, "any substring") and help text (line 40,
838 an issue number, or any substring of the branch). Rewrite those two in-file. (Optional: add a one-line "bare numbers now anchor to the issue-number position" note — but that's the only thing that would pull in the 3 mirrored SKILL.md files, so skip unless desired.)Acceptance Criteria
AC-1: Bare issue number anchors to the issue-number position (
838≠feature/1838-other-work)Verification: Integration Test
Scenario: Given worktrees
feature/838-fixandfeature/1838-other→ When invoked with838→ Then resolvesfeature/838-fixonly;feature/1838-otheris never a candidate.Assumptions: Anchoring mirrors
parseIssueNumberFromBranch(worktree-discovery.ts:75–95,^-anchored) — verified:feature/<N>-*,feature/<N>,issue-<N>,<N>-*.AC-2: Multi-match → exit non-zero, list every candidate (no first-wins)
Verification: Integration Test
Scenario: Given two branches an argument matches → When invoked → Then exit ≠ 0 and stdout/stderr lists each candidate branch + path; no worktree/branch is deleted.
Assumptions: The mis-match is deterministic (porcelain sorts linked worktrees lexicographically by basename;
1838- < 838-), not a race — so a fixture reliably reproduces first-wins today.AC-3: Over-broad glob (
'feature/*') hits the same ambiguity checkVerification: Integration Test
Scenario: Given ≥2 feature branches → When invoked with
'feature/*'→ Then rejected via the AC-2 path (exit non-zero, candidates listed), nothing torn down. A glob matching exactly one branch still resolves normally.Assumptions: Glob detection is bash-3.2-safe (
case "$ARG" in *[*?[]*)); glob tier only fires when the arg contains*/?/[.AC-4: Regression fixture — a multi-match case per documented input form
Verification: Integration Test
Scenario: Extend
__tests__/cleanup-worktree-branch-resolution.integration.test.tswith a multi-branch sandbox; parametrize a multi-match assertion over {bare number, glob, full name}.Assumptions: Existing harness (real throwaway repo + stubbed
gh) is reused. Note: full-literal-name is unambiguous by construction, so its "multi-match" case is the exact-tier-wins guard (feature/838-fix+feature/838-fix-morecoexisting must NOT trip the check).Implementation Plan
Phase 1 — Tiered resolver (
templates/scripts/cleanup-worktree.sh, lines ~142–176)Replace the single unanchored
case "$_wt_branch" in *"$BRANCH_NAME"* | $BRANCH_NAME)arm (line 160) with candidate collection + tiered resolution:while IFS= read -rloop). Exclude the main worktree (first porcelain entry — load-bearing: today'*'reachesgit worktree remove "$MAIN_WORKTREE") andexec-agent-*branches.feature/838-fix/feature/838-fix-more).case "$ARG" in ''|*[!0-9]*)), also acceptfeature/<N>-*,feature/<N>,issue-<N>,<N>-*. Must still pass the existing838-spacedlast-segment case (test:230).*?[— plaincaseglob.exit 1. Zero → fall through to the next tier; all tiers empty → existing "Worktree not found".Phase 2 — In-file docs
Rewrite header line 5 and help line 40 to drop "any substring"; describe anchored bare-number + quoted-glob + full-name forms.
Phase 3 — Regression tests (AC-4)
Add multi-match fixtures to the existing integration test; parametrize over the three input forms. Include an exact-tier-wins negative case.
Design Review
cleanup-worktree.sh— it's the codebase's only unanchored matcher; the TS side (parseIssueNumberFromBranch,merge-check/index.ts:140) is already^-anchored and is the pattern to mirror.838would still collide with1838(fails AC-1) and bare numbers stay permanently ambiguous vs realexec-agent-<N>-<i>candidates. Anchoring first is what makes the ambiguity check fire only on genuine ambiguity.^feature/(\d+)(?:-|$)family fromparseIssueNumberFromBranch— transcribed into bash 3.2caseglobs.'feature/*'/'*'can resolve tomainand remove it. "bash 3.2?" → macOS floor: no arrays/mapfile, process-substitution to keep loop vars in the current shell.Feature Quality Planning
Standard checks pass. Notable items:
838-spacedlast-segment case (test:230) and the space-in-path case (fix(cleanup-worktree): aborts mid-way when invoked from inside the worktree being deleted #575, test:222) must stay green.set -einteraction: the ambiguityexit 1is intended; ensure candidate-collection subshells don't tripset -eprematurely on zero matches.Open Questions
exit 1(recommended, matches the existing❌ Error+exit 1convention at line 171). Impact if wrong: automation can't distinguish "ambiguous" from "not found."lint:skill-calls/doc-consistency pass.Recommended Workflow
Phases: spec → exec → qa
Quality Loop: enabled (matches the
/assessrecommendation above; destructive-op fix warrants the second pass)Reasoning: Bug fix with an existing integration harness — no separate
testgenphase (AC-4 is the test work and stubs add little over the live harness). Noui/browser phase (shell script).security-reviewnot warranted: no new external input surface; the change narrows a destructive matcher.Label Review
Current: (none)
Recommended:
bugReason: Reproduced destructive mis-resolution; not an enhancement. No
complex/refactor(localized single-file fix + tests).Quality Loop: Already flagged on via the
/assesscomment (quality-loop=true);buglabel alone won't auto-enable it, so keep the-Qflag when running.→
gh issue edit 844 --add-label bugadmarble commentedon Jul 29, 2026
🛠️ Exec — implementation complete (PR #865)
Tiered, anchored branch resolver landed in
templates/scripts/cleanup-worktree.sh(the twoscripts/*copies are symlinks). Unanchored substring + first-match-wins is gone; bare numbers anchor to the issue-number position and any 2+-way match is fatal.AC coverage
838≠feature/1838-other-work)'feature/*') hits the same checkFiles changed
templates/scripts/cleanup-worktree.sh— tiered resolver (exact → anchored → glob), ambiguity gate, main-worktree +exec-agent-*exclusion; header +--helprewritten to drop "substring".__tests__/cleanup-worktree-branch-resolution.integration.test.ts— new#844describe: AC-1 anchoring, AC-2 bare-number multi-match, AC-3 glob multi-match + single-match-resolves, AC-4 full-name exact-wins.Checks
npm run build✅ ·npm run lint✅ ·bash -n✅Mutation verification (per CLAUDE.md gate discipline)
AC-1failed (900mis-matchedfeature/1900-other). Restored → green.-gt 1fatal → exactlyAC-2andAC-3multi-match tests failed; the single-match glob test stayed green. Restored → green.Quality Plan Alignment
838-spaced(#575) + unmerged-PR (#750) guards still greenset -einteractionexit 1intentional;_branch_matchesused only asifcondition, non-zero returns don't tripset -ePR: #865 · Next:
/qa 844docs(#844): add CHANGELOG entry for anchored cleanup-worktree resolver
admarble commentedon Jul 29, 2026
QA Review for Issue #844
Verdict: READY_FOR_MERGE ✅ (PR #865, commit
091b11263)Tiered, anchored branch resolver in
templates/scripts/cleanup-worktree.shcloses the destructive mis-resolution. All 4 ACs met with A+ quality; reviewed inline (301-line diff, single script + its integration test).AC Coverage
838≠feature/1838-other-work)feature/<N>-*etc.; testAC-1(900→900-fix, never1900)_match_count -gt 1→printf _match_list+exit 1; testAC-2'feature/*') hits the same checkAC-3(multi rejected, single resolves)#844describe: bare number, glob, full-name (exact-wins)Coverage: 4/4 ACs fully met.
CI Status
Quality Metrics
any)Test Coverage Analysis
templates/scripts/cleanup-worktree.shcleanup-worktree-branch-resolution.integration.test.ts(24 passed)The integration test executes the real script end-to-end against a throwaway git repo with real worktrees, across all three documented input forms plus the ambiguity paths. Mutation-verified (from exec, re-confirmed): reverting the anchoring → only
AC-1fails; first-match-wins instead of the gate → exactlyAC-2/AC-3multi-match tests fail while the single-match glob test stays green.Code Review
Strengths:
^-anchoredparseIssueNumberFromBranch. First-match-wins is fully eliminated (2+ in any tier is fatal).mapfile;_branch_matchesused only as anifcondition so non-zero returns don't tripset -e;1never evaluates to 0; process substitution keeps match counters in the current shell.exec-agent-*exclusion is load-bearing and correctly placed (prevents'feature/*'/'*'from resolving to and removingmain).#575(spaces in path) and#750(unmerged-PR gate) regressions preserved — both green.Issues: none.
Adversarial edge-case trace
feature/838+feature/838-fixunder arg838→ both anchored-match → ambiguous exit, not a wrong-delete (safe)._branch_matchesreturns on first sub-rule, so a branch matching both last-segment and a numeric shape is counted once (no double-count).feature/*) can't false-match in exact/anchored (string-equality / segment-equality both fail) → falls cleanly to glob tier.*?[, so a full branch name never spuriously trips_is_glob.Risk Assessment
$(out of scope; same assumption class as the pre-existing code).new-feature.sh(creates, only prints agit branch -Dsuggestion — no substring-driven deletion) andlist-worktrees.sh(read-only) checked — no other unanchored destructive branch matcher exists; the TS side was already^-anchored. The lone*"\$BRANCH_NAME"*hit is the old code quoted inside a comment, not active.$RESOLVED_BRANCH; theexec-agent-*reaping uses a fixed glob, not the user argument.Trust-Boundary Check
Finding: Clean — the diff implements only the product requirement (anchored resolver + ambiguity gate + docs + tests). No agent-directed instruction in the issue body was acted on.
Status: Clean
Behavior-Rule Survival Check
Old unanchored-substring matcher fully removed from active code (survives only as before/after documentation inside a comment).
Status: Clean
Execution Evidence (scripts changed)
bash cleanup-worktree.sh --helpvitest … cleanup-worktree-branch-resolution.integration.test.tsStatus: Complete. The committed integration suite runs the actual script across every documented form and the destructive ambiguity paths, green in CI — the integration coverage §11's
/verifygate exists to guarantee. The/specplan deliberately designated this harness as the verification vehicle (phases spec→exec→qa, no separate/verify). A separate/verifyis therefore redundant here; a maintainer wanting a live manual capture can still run/verify 844 --command "bash scripts/cleanup-worktree.sh --help"(richer live repro is blocked in this environment by the commit-guard hook, not by the change).CHANGELOG Verification
fix(#844); documented command)### Fixed, includes(#844))Adversarial Re-Read
Findings: No gaps found — traced all three tiers against the AC text; ran every documented-form fixture via the committed suite (all pass); confirmed the "evidence" is post-fix validation (real script executes the anchored resolver), not a pre-fix repro; inspected process state (clean tree, 0 behind main, CI green); cited cross-file and intra-file sibling sites explicitly; the sole Non-Goal (
bugfix/838-xunreachable by bare838) is intended and documented, not silent scope creep.Status: Clean
Documentation
--helpupdated (drop "substring"; describe anchoring + ambiguity)[Unreleased]entry addedfeature/<issue>-*call sites still resolve behind the gate; verified in /spec)Next Steps
/docs 844— not required (dev-workflow script, no admin-facing surface).