Skip to content

Guard pr merge --delete-branch against worktree conflicts - #14007

Merged
babakks merged 12 commits into
trunkfrom
tidy-dev-merge-worktree-guards
Aug 21, 2026
Merged

babakks merged 12 commits into
trunkfrom
tidy-dev-merge-worktree-guards

Conversation

@tidy-dev

@tidy-dev tidy-dev commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes https://github.com/github/gh-cli-and-desktop/issues/271
Closes #3442

Makes gh pr merge --delete-branch worktree-aware:

  • Delete the local ref directly when the PR head is checked out nowhere.
  • Switch to the base branch only when the head is current in the main worktree.
  • Remove another linked worktree before deleting its branch.
  • Warn and skip local cleanup when the current/main worktree cannot be removed, the base is busy elsewhere, the worktree is dirty, or inspection fails.

Remote branch deletion still proceeds after safe local skips, and dirty worktrees are never force-removed.

Demo

Before and after demo of gh pr merge --delete-branch worktree cleanup

Tests

The PR build passed all 18 end-to-end scenarios; all 8 legacy behavior-preservation cases also passed on clean gh 2.97.0.

Rework the local-cleanup half of --delete-branch to handle git worktrees:

Scenario 1 - cwd is the PR head worktree: skip local cleanup entirely
and print a warning with manual cleanup instructions, since we cannot
safely check out another branch or remove the worktree we are standing
inside.

Scenario 2 - cwd is not the PR head worktree but a sibling worktree has
the branch: remove that worktree via git worktree remove, then delete
the branch ref. If removal fails (e.g. dirty worktree), warn and skip
rather than exiting non-zero after a successful merge.

The conventional single-working-directory path (no worktrees) is
unchanged. Remote branch deletion proceeds normally in all cases.

Also adds git.Client.WorktreeRemove() helper.

Co-authored-by: Copilot App <[email protected]>
@tidy-dev
tidy-dev marked this pull request as ready for review July 29, 2026 15:20
@tidy-dev
tidy-dev requested a review from a team as a code owner July 29, 2026 15:20
@tidy-dev
tidy-dev requested a review from babakks July 29, 2026 15:23

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Not ready to approve

There is a confirmed unhandled worktree conflict case that can still cause gh pr merge --delete-branch to exit non-zero due to local cleanup (head branch checked out in the main worktree while running from another linked worktree), and the new worktree parsing logic lacks direct unit tests.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

This review doesn't count toward merge requirements. Sign up for the private preview to control whether Copilot approvals count.

Pull request overview

This PR makes gh pr merge --delete-branch safe to run in repositories using git worktree, avoiding failures or confusing partial cleanup states by detecting when the PR head branch is checked out in a linked worktree and adjusting local cleanup behavior accordingly.

Changes:

  • Add git worktree discovery/removal support (git worktree list --porcelain, git worktree remove) to enable worktree-aware cleanup decisions.
  • Update pr merge local branch deletion logic to (a) warn+skip when run inside the head branch’s linked worktree, (b) remove a sibling linked worktree before deleting the local branch, while preserving existing behavior for normal repos.
  • Expand and adjust pr merge tests to cover new worktree scenarios and stub new git calls.
File summaries
File Description
pkg/cmd/pr/merge/merge.go Implements worktree-aware branching of local cleanup and adds helper to locate linked worktrees for a branch.
pkg/cmd/pr/merge/merge_test.go Updates existing delete-branch tests for new git calls and adds new worktree-focused scenarios.
git/objects.go Introduces a git.Worktree struct used to represent parsed worktree entries.
git/client.go Adds Worktrees / WorktreeRemove APIs and parsing logic for git worktree list --porcelain.
Review details
  • Files reviewed: 4/4 changed files
  • Comments generated: 3
  • Review effort level: Low

We're testing this review assessment. Please use 👍 or 👎 to tell us if it's correct.

Comment thread pkg/cmd/pr/merge/merge.go Resolved
Comment thread pkg/cmd/pr/merge/merge_test.go Resolved
Comment thread git/client.go Resolved
@tidy-dev
tidy-dev marked this pull request as draft July 30, 2026 13:00
Comment thread git/client.go Resolved
tidy-dev and others added 5 commits August 4, 2026 12:04
Guard against git branch -D failing when the PR head branch is checked
out in the main worktree while running from a different worktree. Warn
and skip local delete instead of exiting non-zero on local cleanup.

Also add unit tests for parseWorktrees and simplify its record parsing.

Co-authored-by: Copilot App <[email protected]>
When deleting the PR head branch requires checking out the base branch,
git fails if the base branch is checked out in another worktree. Detect
that case and warn+skip local delete instead of exiting non-zero, and
fix an unrealistic worktree fixture in the no-conflict test.

Co-authored-by: Copilot App <[email protected]>
Collapse the five per-scenario worktree deleteBranch tests into a single
table-driven test with named subtests, matching the AGENTS.md testing
guidance and removing repeated setup boilerplate.

Co-authored-by: Copilot App <[email protected]>
Trunk migrated BranchDeleteRemote to safeurl.JoinPath, which escapes the
branch ref's slash (heads%2Ffeature). Update the new worktree test stubs
to match the encoded path so httpmock.REST matches after merging trunk.

Co-authored-by: Copilot App <[email protected]>

@babakks babakks left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR, @tidy-dev! 🍻 I think my main comment is this one for now (skip the child ones).

I haven't fully reviewed the PR yet (i.e. tests), but wanted to share thoughts with you. Sorry if :copilot: is being so verbose.

Just acknowledging the scenarios laid out below are already covered by the current PR. So, this is just about making it easier to follow. This is also why I'm happy to keep it as is if you don't see value in the refactor, or you'd rather see it as a follow-up.


I'm having a hard time following the flow here, and I think I've worked out why and how to improve it. Obviously, the original cleanup logic was written under an assumption that no longer holds: it only ever asked "is cwd currently on the PR head branch?", because in a single working directory a branch can only ever be checked out in that one place. So "I'm on the head branch" and "the head branch is checked out somewhere" were the same statement, and the code could safely do checkout-base then delete.

The worktree scenarios have been layered on top of that same structure, reusing the old checkout-base-then-delete path and bolting guard branches around it. That reuse is what makes this hard to read: the legacy path and the new worktree guards are interleaved, several of the if arms are implicitly coupled (one only runs because an earlier one didn't), and the base branch handling is tangled up with cases that never actually touch the base branch.

Suggestion

I think it's worth stepping back and reassessing the scenarios from scratch. The key realization is that currentBranch == head is just one special case of a single broader question: "where is the PR head branch checked out, relative to cwd?" Keying off that one dimension gives a flat, mutually exclusive set of cases:

Head branch is checked out... git constraint in play Action
nowhere (ref only) branch not checked out anywhere, -D succeeds delete the ref directly
in the current worktree, which is the main worktree cannot delete the branch we are on, must move off it first switch to base, pull, delete (the only row that touches base)
in the current worktree, which is a linked worktree cannot repurpose the worktree we are standing in warn and skip
in another linked worktree must un-check-out before -D, and a linked worktree is removable remove that worktree, then delete the ref
in the main worktree (we are elsewhere) cannot remove the main worktree, cannot -D a branch checked out there warn and skip

Every row reduces to the same precondition: make sure no worktree has the head branch checked out, then delete the ref. The base branch logic is only needed in a single row, which is what decouples everything else.

Here is a sketch of how the body could read (not real code):

// ---- Locate the head branch: the single master dimension ----
headWt = worktreeForBranch(worktrees, pr.HeadRefName)   // nil if not checked out anywhere
mainWt = worktrees[0]                                   // git always lists main first

// Row 1: head not checked out anywhere -> just delete the ref.
if headWt == nil:
    return deleteRefAndReport(switchedTo = "")

// Row 2 & 3: head is checked out in THIS worktree.
if headWt.Path == currentWorkdir:
    isMain = (currentWorkdir == mainWt.Path)

    // Row 3: linked worktree we are standing in -> cannot clean up safely.
    if not isMain:
        warnSkip_currentLinked(currentWorkdir)
        return nil

    // Row 2: main worktree, sitting on head -> legacy "switch off head" path.
    // This is the ONLY leaf that touches the base branch.
    baseWt = worktreeForBranch(worktrees, pr.BaseRefName)
    if baseWt != nil and baseWt.Path != currentWorkdir:
        // base busy in another worktree -> checkout would fatal.
        warnSkip_baseBusy(baseWt.Path)
        return nil

    if not switchToBase():           // CheckoutBranch or CheckoutNewBranch + Pull
        return nil                   // warn inside; do not fail the merge
    return deleteRefAndReport(switchedTo = pr.BaseRefName)

// Row 4 & 5: head is checked out in ANOTHER worktree.
if headWt.Path == mainWt.Path:
    // Row 5: main worktree elsewhere -> cannot remove it, cannot -D.
    warnSkip_headInMain(mainWt.Path)
    return nil

// Row 4: another linked worktree -> remove it, then delete the ref.
if err = GitClient.WorktreeRemove(headWt.Path); err != nil:
    warn("could not remove worktree %s; skipping local delete: %s", headWt.Path, err)
    return nil
info("Removed worktree %s", headWt.Path)
return deleteRefAndReport(switchedTo = "")

A nice side effect is that currentBranch disappears entirely (locating the head via the worktree list subsumes it and naturally handles detached HEAD), and worktreeForBranch replaces both current helpers. Happy to talk it through if you want to pair on it.

Comment thread git/objects.go Resolved
Comment thread pkg/cmd/pr/merge/merge.go Resolved
Comment thread pkg/cmd/pr/merge/merge.go Resolved
Comment thread pkg/cmd/pr/merge/merge.go Resolved
Comment thread pkg/cmd/pr/merge/merge.go Resolved
The len(worktrees) > 0 guard was always true since Worktrees() always
lists at least the main worktree. Reuse the existing isInLinkedWorktree
predicate instead, which already implies len > 1 (keeping worktrees[0]
access safe) and folds in the path comparison. Behavior is unchanged.

Co-authored-by: Copilot App <[email protected]>
ieuanign added a commit to ieuanign/skills that referenced this pull request Aug 9, 2026
…esolved comments

`skills/dev-loop-pr-comments/read-comments.mjs` returns a pull request's unresolved comments as
one list: thread-anchored review comments, review bodies and issue comments, in a single entry
shape a consumer switches on by `origin`.

Exclusions are signals, never inferences. A resolved thread goes on GraphQL's own `isResolved`,
because REST cannot express it and a guess returns every comment the pull request ever carried; a
minimised comment goes because hiding one is a human saying it is dealt with; a PENDING review is
unsubmitted and a bodyless review is the envelope around inline comments already collected.

Absence is carried, not filled in. An outdated comment keeps `line: null` while its stale
`originalLine` travels separately, so *no line* and *line moved* stay distinguishable.

Bodies never reach a shell: `gh` is spawned with an argument array, `shell: false`, and its stdout
is parsed. All four connections paginate, the nested one by count because `gh --paginate` follows
only the first pageInfo in a response, and any failure exits non-zero with no JSON so that an empty
list can only mean no unresolved comments.

The folder holds the module alone — no SKILL.md, no manifest entry — so nothing installs or invokes
it yet. The normaliser is exported and importing it runs no fetch.

Verified live, read-only, no mutation issued: cli/cli#14007 → 5 review-thread + 2 review-body
entries against an independent query's 9 threads / 4 resolved / 5 unresolved comments / 3 reviews
of which 2 carry a body; bodies byte-identical for all 5; two entries with line=null,
originalLine=431, outdated=true. cli/cli#14027 → 3 threads all resolved, 2 review bodies, 1 issue
comment. cli/cli#14099 with the page size forced to 1 reproduces its full-page output byte for
byte, exercising every cursor including the per-thread comment refetch. Missing gh, an unknown pull
request, an unresolvable repository and a bad argument each exit non-zero with empty stdout.

Deviation: the changeset is hand-written as .changeset/140-read-unresolved-pr-comments.md rather
than generated by `npm run changeset`, which names files after human-id words; every tracked
changeset here is named <issue>-<slug>.md.
ieuanign added a commit to ieuanign/skills that referenced this pull request Aug 9, 2026
…checked, not just parsed

The check suite proved read-comments.mjs PARSED. Everything that makes it safe to point at a
pull request — which comments it drops, which fields it refuses to invent, and whether a body
survives — was unobserved. `scripts/pr-comment-read.mjs` observes it, at the same seam the
state-machine harness uses: the exported pure function, driven over fixtures, spawning nothing
and reaching no network.

Seven scenarios over the normaliser's public interface, none touching an internal. A resolved
thread is excluded whole while an unresolved one is kept whole; a minimised comment goes at all
three origins; a bodyless, whitespace-only or PENDING review is not a comment while a review that
said something is. An outdated comment keeps `line: null` with `originalLine` beside it, so the
scenario fails the moment anything substitutes the stale anchor. A body carrying backticks,
`$(...)`, quotes, a backslash, a pipe and a newline comes back byte for byte, through the JSON
round trip the reader actually prints. Every entry carries the same eleven keys whatever its
origin, and an empty pull request is an empty list.

Each scenario was confirmed to FAIL against a deliberately broken normaliser before being kept:
dropping the `isResolved` guard admits the resolved thread's two comments, and substituting
`originalLine` into `line` turns null into 431.

check.sh gains one stage after the bundled-module syntax stage, streaming its own ok/FAIL line per
scenario with only its exit code read — the state-machine stage's shape.

Verified live, read-only, no mutation issued (the module sends query documents only):
cli/cli#14027 → 3 entries (2 review-body, 1 issue-comment) against an independent query's 3
threads all resolved, 5 reviews of which 2 carry a body and 3 are bodyless, 1 issue comment.
cli/cli#14007 → 7 entries (5 review-thread, 2 review-body) against 9 threads / 4 resolved /
5 unresolved carrying 5 comments none minimised, 3 reviews of which 2 carry a body, 0 issue
comments; both null-line entries report originalLine=431, outdated=true, matching the independent
query exactly. Both runs exited 0 with empty stderr and one parseable JSON document on stdout.

`npm run check` green, including `claude plugin validate . --strict` with the manifest-unlisted
skills/dev-loop-pr-comments/ folder in place.
ieuanign added a commit to ieuanign/skills that referenced this pull request Aug 9, 2026
…te their intent

Step 3's table gains a `#` key and a Reason column, and stays one line per
comment: what runs past a clause goes to a keyed expansion beneath it. A
`disagreed with` row is marked `(!)` — plain ASCII, so it reads the same in a
terminal as in GitHub's renderer — and its expansion is mandatory. A fix row's
one-clause statement of intent is written once and is the string Step 5 hands
the writer. Steps 4, 5 and 10 now render that one definition rather than
restating it, and the ledger comment carries it as the copy that outlives the
run.

AC 8 — live, read-only verification of the classification as written
====================================================================
Comments read through skills/dev-loop-pr-comments/read-comments.mjs. No `gh`
write of any kind, no worktree provisioned, no gate answered: this exercised
Step 3 only.

cli/cli#14007 — "Guard `pr merge --delete-branch` against worktree conflicts",
7 unresolved comments, all 7 classified. Supplied three of the four reasons:

- out of scope for this branch — babakks, pkg/cmd/pr/merge/merge.go:410,
  discussion_r3719732624 ("In a follow-up we can extract git commands used in
  `pr checkout --worktree`"). Evidence: the separate work is a follow-up
  extracting the git commands `pr checkout --worktree` runs so they can reuse
  this branch's `ToplevelDir` — the commenter names it a follow-up himself.

- already addressed — babakks, merge.go stale anchor 431 (outdated),
  discussion_r3719948135 ("**nitpick:** `len(worktrees)` is always `> 0`").
  Evidence: ea3d3191f "Simplify main-worktree head check, drop misleading len
  guard" drops the `len(worktrees) > 0 &&` conjunct the comment calls
  misleading; merge.go is its only file.
  Two more rows took the same reason: discussion_r3720203296 (same commit — its
  new `if` is that comment's suggestion block character for character) and
  copilot-pull-request-reviewer's review body pullrequestreview-4810038780,
  whose two stated grounds are both met by d7fe64365 "Handle head branch checked
  out in main worktree during pr merge cleanup" — it handles that case in
  `deleteLocalBranch` and adds `TestParseWorktrees` to git/client_test.go, the
  direct unit tests the review says are missing.

- disagreed with (!) — babakks, review body pullrequestreview-4863309209, the
  proposal to restructure `deleteLocalBranch` around "where is the head branch
  checked out". Evidence, in full, is the expansion; in short: the reviewer
  states in the same comment that the scenarios are already covered, so the
  restructure changes no behaviour, and rewriting the whole cleanup flow inside
  a pull request that exists to guard one command widens the blast radius of a
  bug fix. Declined outright rather than deferred, which is what separates it
  from the `out of scope` row above.

Two rows classified fix: discussion_r3719711480 (rename `Worktree.Branch` to
`Ref` at git/objects.go:82) and discussion_r3720001340 (return the errors from
`Worktrees` and `ToplevelDir` instead of discarding them — still `worktrees, _
:=` at head). More than one fix row, so a real run would stop at Step 4.

No comment on 14007 classified `question`: the one opening "**question:** why
can't we simplify this `if`-statement" carries a ```suggestion``` block, so it
asks for a change, and ea3d3191f made it — `already addressed`, above.

cli/cli#13948 — "Add issue field support to gh CLI" — supplied the fourth:

- question — zwick, pkg/cmd/issue/create/create.go:102,
  discussion_r3639448805. Evidence, verbatim: "Can I create an issue with
  multiple Issue Field Values?"

No comment across either pull request came back `unclassified`: every one fit an
intent, and every skip's evidence was produced.

Deviation: the changeset was hand-written at .changeset/142-skip-reasons.md
rather than generated with `npm run changeset`, which names files with a random
human-id. Every existing changeset here is named `<issue>-<slug>.md`.
ieuanign added a commit to ieuanign/skills that referenced this pull request Aug 9, 2026
…n resolves to its default

A leading `auto` puts the harness in unattended mode, read off the arguments once
and carried as one value: no later step re-derives it, and no other argument and
no profile key overrides it.

Suppression removes Step 4's question and nothing else. Every comment is still
classified, the table is still rendered and still written to Step 5's file, and
each of the gate's questions resolves to a stated default — every fix row
proceeds, a skip stays skipped with its reason and evidence, an unclassified row
is reported and acted on by nothing, and a table with no fix row stops the run
having provisioned nothing. Step 1's five refusals and Step 6's three profile
reads are preconditions rather than gates and fire under both modes, so no
unattended default is invented for a profile key.

Where the gate asked, an unattended run posts the table on the pull request
instead — one rendering of Step 3's table, quoted heredoc, body on stdin. Step 7
now passes the run's real mode; `skillDir` stays absent under both modes, which
is the execute phase's documented no-notifier configuration.

Verified: npm run check (exit 0); the table rendered from cli/cli#14007's seven
unresolved comments through read-comments.mjs, read-only, seven columns on every
row; a quoted heredoc carried a body holding backticks, $(...), quotes and $HOME
byte for byte with nothing executed.
ieuanign added a commit to ieuanign/skills that referenced this pull request Aug 9, 2026
…on the pull request

Step 10 becomes the run's conclusion rather than only its ledger, and under
`unattended` it posts on every path past Step 4's table — the ones that ended
before the phase was ever dispatched included. That table told the pull request a
worktree, these commits and a push were coming, and the run that promised them is
the only thing that can say they never came. It is a second comment beside it and
never an edit to it, which keeps the two-comment count and the append-only rule
one fact rather than two.

A run that ended fills what sections it has, leaves out the ones it cannot, adds
Step 9's account — label, stage, reason verbatim, diagnosis, attempts — and
closes on what nothing else records once this session goes: the kept worktree by
path, the kept table file by path, and the run handle. That handle is a derived
fact, `$CLAUDE_CODE_SESSION_ID` read once, written in exactly one place and never
in a message; unset or empty is a missing line and nothing else about the run
changes.

The table file's lifetime follows the work rather than the comment alone: deleted
on the pushed path once the conclusion carrying its content has posted and never
before it, kept beside every worktree that is kept, and named in the comment
there — a worktree without the plan its commits were made against is one nobody
can pick up.

Deviation: the plan's assumption that everything after `start` gets an
explanation comment is narrowed to the paths past Step 4's table. A run that ends
at Step 2 — a failed read, or no unresolved comments — promised the pull request
nothing and posted no table, so its account is its closing message and it writes
nothing on somebody else's artifact.

Verified: npm run check (exit 0); a conclusion comment for an ended run rendered
from cli/cli#14007's seven real unresolved comments through read-comments.mjs,
read-only with no gh write and no worktree, then fed through a quoted heredoc
byte for byte — backticks, $(id), ${HOME}, quotes and apostrophes intact, nothing
executed and nothing expanded; the handle line present with
$CLAUDE_CODE_SESSION_ID set and absent rather than empty with it unset; an
unconfigured channel silent and exit 0.

Not verified here, and reported rather than claimed: acceptance criterion 8's
unattended end-to-end run. The harness dispatches the Workflow tool and a
dispatched subagent has none, so this lane cannot drive the execute phase.
tidy-dev and others added 3 commits August 19, 2026 07:37
Classify local branch cleanup by where the PR head is checked out, and skip cleanup safely when worktree discovery fails.

Co-authored-by: Copilot App <[email protected]>
Match the Worktree model to Git's fully qualified ref terminology.

Co-authored-by: Copilot App <[email protected]>
@tidy-dev
tidy-dev marked this pull request as ready for review August 19, 2026 13:56
@tidy-dev
tidy-dev requested a review from babakks August 19, 2026 13:57

@babakks babakks left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update, @tidy-dev! 🎉 The reshaped flow in deleteLocalBranch addresses my earlier concern really well. Organising it around where the head branch is checked out makes it far easier to follow, and the coupling between branches that I was worried about is gone. Much nicer to reason about now.

I also did a thorough pass and, with a big assist from :copilot:, walked through every scenario I could come up with against real PRs, both the new worktree flows and the classic non-worktree flows. Everything held up solid. 🚀

Just a couple of minor inline notes left, nothing blocking. Really appreciate you taking the time to restructure this, it turned out great! 🍻

Comment thread git/client.go Resolved
Comment thread pkg/cmd/pr/merge/merge.go Resolved
Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 19c04729-87af-4473-88bb-a263d66b20f1
@babakks
babakks enabled auto-merge August 21, 2026 13:49
@babakks
babakks merged commit d9cba2a into trunk Aug 21, 2026
11 checks passed
@babakks
babakks deleted the tidy-dev-merge-worktree-guards branch August 21, 2026 13:52
tianjianjiang added a commit to tianjianjiang/smith that referenced this pull request Sep 7, 2026
… post-merge sync (#252)

* docs(worktree): document built-in isolation guard, rtk collision, and post-merge sync

Claude Code's worktree isolation guard refuses any command whose text cannot
prove its git stays inside the worktree. The rtk PreToolUse hook rewrites
git into rtk git, which is exactly that shape, so every git command in a
worktree session was refused (rtk-ai/rtk#3864). Record the fix
(exclude_commands = ["git"] in rtk's config) in smith-worktree.

The post-merge reminder hook and smith-gh-pr's cleanup block told the agent
to run git -C into the primary checkout or git checkout the default branch
from inside a worktree; both are blocked there. Point them at ExitWorktree
first, and note that gh 2.99.0+ handles --delete-branch with linked
worktrees (cli/cli#14007).

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(worktree): correct worktree-dirty-guard hook path

The hook lives in smith-git/scripts/hooks/, as README.md and
smith-git/references/HOOKS.md already state; smith-worktree/SKILL.md was the
only reference still pointing at smith-ctx-claude/scripts/.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
restarter added a commit to restarter/lets-workflow that referenced this pull request Sep 22, 2026
#186)

## Summary

A worker session could finish or vanish leaving no record, and nothing
noticed: lets-g5wuz and lets-cbmg7 shipped (#184, #185) and their
sessions left no snapshot, no `released-` marker, nothing that surfaced
them. The same session model (stable session id, changing pid and
terminal) also broke on resume: `lets peers tell` to an orchestrator
resumed with `claude -r` failed `peer_unreachable` while `lets peers
orchestrator` reported it alive.

### Why the archive hook never fired

Orca never archived those two worktrees. gh 2.101.0 (installed
2026-09-15) includes cli/cli#14007 (gh >= 2.99): `gh pr merge
--delete-branch`, run from another checkout, removes the head branch's
linked worktree itself. Orca's trace (`~/Library/Application
Support/orca/logs/main.trace.ndjson.1`) has no `worktree.remove` /
`archive_hook` span for either; each worktree vanished one second after
its merge (#185 10:19:39Z -> cbmg7 PTYs killed 10:19:40Z; #184 10:33:15Z
-> g5wuz 10:33:16Z), while every Orca "Delete" in this repo ran the
hook, second-exact with its marker. Their task-state files are still in
`.lets/sessions/` - `release` never ran. `/lets:done`'s own merge is not
this path: gh never removes the current or main worktree.

### What changes

- **Session record.** A snapshot records the full HEAD it covers (`-
head: <sha>`, 40 or 64 hex); `/lets:done` writes one before its final
gate, whatever is picked.
- **`lets worktree record --task <id>... [--ref]`.** Per task: `present`
/ `stale` / `missing` by git ancestry (never by time; legacy
`-snapshot-precompact` files still read), the local traces (task-state
files, `refs/heads/` branches), live worktrees, the marker, and
`orphan`. An incomplete inventory fails instead of answering
`orphan=false`.
- **`/lets:start --main`** offers orphans (in progress, a local trace,
no worktree, no marker) in Reopen next to archived claims.
- **`release`** writes its marker (now with `snapshot=`) first, then
compare-and-deletes the task-state file under its lock
(`taskstate.RemoveIfTask`) - a file that changed meanwhile, an
unreadable one or an invalid id is kept, with the reason in
`released.task_state_kept`. A missing record, a failed marker or a kept
file prints a `lets:` line on stderr (even with `--quiet`) and fires
`lets notify`.
- **taskstate** temps moved to `.tasktmp-*`: `.task-<slug>.<digits>.tmp`
is also the state file of a legal branch (`feature.12345.tmp`), which
`Remove` used to delete as a stranded temp.
- **Rule** (lets-rules `## Worktrees`): a worker's PR merged from
another checkout goes without `--delete-branch`, only after `record`
shows `present`; archive in Orca afterwards.
- **Resumed sessions** (peerscmd): one peer per session id - two live
pids, counted machine-wide, are `session_duplicated`; a binding resolves
to the live holder of the name, else the one role file registered under
it (`bound_ambiguous` on a tie); `tell` reports why it cannot reach
(`state`); `lets peers tail <name>`.

### Review

The plan went through three Codex review rounds and the branch through
two; every finding was checked against the code, the confirmed ones are
folded in, and the two answered differently are argued in the plan's Key
Decisions. `TestResume_NewPidNewName` is intentionally RED at eaf120f
(it reproduces the renamed-resume mismatch) and green from 942d519.

## Test plan

- [x] `make test` (race) - green
- [x] `make lint` - 0 issues
- [x] `cd cli && GOOS=windows go vet ./internal/cli/` - clean
- [x] `./cli/lets worktree record --task lets-cbmg7 --task lets-g5wuz
--json` - both show their surviving task-state trace, no worktree, no
marker, `record=missing`, `orphan=true` (the vanished state, now
visible)
- [ ] Owner smoke, resume: bind a worker to a throwaway orchestrator
(`claude --model opus`, `/rename SMOKE-ORC`, `/lets:start --main`),
`/lets:orc ping hi` from the worker; close the orchestrator tab, `claude
-r <sid>` in a new Orca pane, ping again - expect delivery via the
claude route, or a named refusal at resolution (`session_duplicated`
when the old process still runs, `target_in_other_repo` when resumed
from another directory), never `alive` then `peer_unreachable`
- [ ] Owner smoke, archive: in a throwaway Orca worktree with a claimed
task and no snapshot, press Delete - expect the stderr/notify alarm and
a marker ending `|snapshot=missing`

## Task

lets-11zwo: A worker session can vanish leaving no record, and nothing
notices

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
DominicBoettger added a commit to andashi/home that referenced this pull request Sep 27, 2026
The paragraph claimed it of gh in general. Upstream fixed it in v2.99.0, in
cli/cli#14007, "safely handle --delete-branch with linked worktrees"; this clone
runs 2.98.0, which is why it fired on #207. Verified against the release data
rather than taken from the review: v2.99.0 was published 2026-09-01 and its
notes carry that line.

So the first remedy is upgrading gh, with the merge-confirm-delete sequence as
the version-independent fallback. A tool bug written down without its version
outlives the bug and sends the next reader to work around something already
fixed. The lesson under it - a correct action reporting failure is as bad as a
broken check answering permissively - is not version-scoped and stays.
DominicBoettger added a commit to andashi/home that referenced this pull request Sep 27, 2026
The paragraph claimed it of gh in general. Upstream fixed it in v2.99.0, in
cli/cli#14007, "safely handle --delete-branch with linked worktrees"; this clone
runs 2.98.0, which is why it fired on #207. Verified against the release data
rather than taken from the review: v2.99.0 was published 2026-09-01 and its
notes carry that line.

So the first remedy is upgrading gh, with the merge-confirm-delete sequence as
the version-independent fallback. A tool bug written down without its version
outlives the bug and sends the next reader to work around something already
fixed. The lesson under it - a correct action reporting failure is as bad as a
broken check answering permissively - is not version-scoped and stays.
DominicBoettger added a commit to andashi/home that referenced this pull request Sep 27, 2026
The paragraph claimed it of gh in general. Upstream fixed it in v2.99.0, in
cli/cli#14007, "safely handle --delete-branch with linked worktrees"; this clone
runs 2.98.0, which is why it fired on #207. Verified against the release data
rather than taken from the review: v2.99.0 was published 2026-09-01 and its
notes carry that line.

So the first remedy is upgrading gh, with the merge-confirm-delete sequence as
the version-independent fallback. A tool bug written down without its version
outlives the bug and sends the next reader to work around something already
fixed. The lesson under it - a correct action reporting failure is as bad as a
broken check answering permissively - is not version-scoped and stays.
DominicBoettger added a commit to andashi/home that referenced this pull request Sep 27, 2026
…ps (#212)

* docs: the eighth way a test runs and tests nothing, and two merge traps

A fake that can only return a right-shaped answer proves nothing about the
rejection it is supposed to exercise, and it is always the convenient one to
write. Three instances turned up in a single day, each found by somebody other
than the author of the fake: one closed a tapped dialog faster than a device
does, one printed a single line where the real tool prints more than a pipe
buffer holds, and one always returned a value that differed from the previous
value, so an implementation regressing to the weaker comparison passed the new
test. The dimension differs - speed, size, ordering - and the shape does not.

Two merge traps from the same day. gh pr merge --delete-branch checks out main
locally afterwards, which fails inside a worktree, so the command exits non-zero
for a merge that has already succeeded and leaves the branch in place; every
other failure collected here answers too permissively, and this one is a correct
action reporting failure, which is no better. And the merge gate read only the
pull request, never what the pull request merges into, although the CI section
has said since #132 that red on main is fixed before the next merge.

Both counts in the affected sections are removed rather than corrected. The
merge section said "three conditions" while the script enforced seven and
announced four, and the list of mechanisms counted itself in two places. A
number restated in prose goes stale with nothing going red, which is the same
failure the sections are about.

* docs: scope the --delete-branch worktree trap to gh before v2.99.0

The paragraph claimed it of gh in general. Upstream fixed it in v2.99.0, in
cli/cli#14007, "safely handle --delete-branch with linked worktrees"; this clone
runs 2.98.0, which is why it fired on #207. Verified against the release data
rather than taken from the review: v2.99.0 was published 2026-09-01 and its
notes carry that line.

So the first remedy is upgrading gh, with the merge-confirm-delete sequence as
the version-independent fallback. A tool bug written down without its version
outlives the bug and sends the next reader to work around something already
fixed. The lesson under it - a correct action reporting failure is as bad as a
broken check answering permissively - is not version-scoped and stays.

* docs: the review bot has two names in one API response

resolvedBy.login is coderabbitai[bot]; the same actor is coderabbitai in
comments.nodes[].author.login. A check comparing the resolver to the unsuffixed
name matches nothing and counts zero, which is indistinguishable from "no
bot-resolved threads" and reads as a pass.

The merge gate's condition for this was dead from the day it was written. It was
added because the bot resolves its own threads on a rebase, including ones whose
fixes the rebase does not contain, and it never once fired. What exposed it was
this pull request: the bot resolved its own thread here with no reply, the gate
waved it through, and the condition existed precisely to stop that.

Break-checked in both directions after the fix - with the suffix stripped the
gate refuses and names the thread, with the old comparison restored it goes
silent and falls through to a later condition.

* docs: a red test whose fixture is a state the system cannot be in

The fixture-side of the preceding entry. Chasing the apps write-back defect, a
reproduction set the applied baseline to an entry carrying an explicit activity,
which the store never emits there - the applied state is its read-back. The case
went red and was targeted, 28 others passed, and it demonstrated a silent loss of
the activity. With a reachable baseline the same code produces a duplicate entry
carrying a stale label, which is what the review had said and what that
reproduction was taken as disproving.

Both faults are real and only one occurs. Derive the baseline from what the
producing code emits, not from what makes the case read well.

* docs: a third shape, the answer computed and then thrown away

A shell for loop exits with its last iteration's status, so a loop that validates
every file reports only the last one. An invalid config or a syntax error
anywhere but at the end passes green. Found in the provisioning repository's only
workflow and demonstrated with three files whose middle member was broken: exit 0
before the fix, exit 1 after. Its make check had it right locally, so the gate
that ran automatically was the weaker of the two.

It shares two properties with the bot-suffix defect recorded above. Both produce
a quiet success - one counted zero and called it clean, the other computed every
answer and kept the last - and both sat in a checker nobody had watched fail.
That workflow was also unparseable YAML for a period and did not run at all, so
it was silently useless twice in two different ways.

A scan of this repository's loops found four candidates and no defects: the
hygiene workflow and the helper tests accumulate and exit after the loop, and
delete_snapshots ignores its deletes deliberately because the list afterwards is
the check. The negative result is recorded so nobody re-runs the scan hopefully.

* docs: the break check does not catch an unreachable fixture

The list closed by claiming one check catches every mechanism on it, and the
mechanism added last describes that check's own passing result: a case that goes
red, targeted, with the others green, while proving the wrong thing. So the claim
was false about the entry directly above it.

The check now states both halves: break what the test guards and watch that test
go red, and separately ask whether the fixture is a state the system can be in,
answered from what the producing code emits. Found by review on the draft that
introduced the contradiction.

* docs: break the test in the input its guard is about

Second correction to the same closing sentence, in a second direction. It claimed
one break catches mechanisms 1 to 8. It does not catch 1: a break in the code is
a break in a declared input, so the task re-runs and says nothing about whether a
change to the undeclared external document would have run it. ConfigParserTest
was verified by breaking ADR 0002's example and passed because it had not run;
breaking the parser would have gone red and proved the wrong thing.

The check now reads as three questions rather than one claim: break what the test
guards and watch that test go red; break it in the input the guard is about; and
confirm the fixture is a state the system can be in.

A sentence claiming to cover a list makes a claim about every item on it, and
this one was wrong about two.
Mereithhh added a commit to Mereithhh/very-happy that referenced this pull request Oct 21, 2026
…#645)

gh >= 2.99.0 (cli/cli#14007) makes 'pr merge --delete-branch' run 'git worktree remove' on
another linked worktree that has the head branch checked out. All team workers' worktrees
share this repository, so landing a worker's PR removed the worker's active worktree.
Merge with --squash only, then delete just the remote head branch via the API (same-repo
PRs). Fake-gh/git test wired into quality.yml.
samthorold added a commit to samthorold/commons that referenced this pull request Oct 23, 2026
Its remove-when is met: gh 2.99.0 makes `gh pr merge --delete-branch`
worktree-aware (cli/cli#14007, closing cli/cli#3442), and this machine
now runs gh 2.103.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

Support gh pr merge -d with git worktrees

4 participants