Skip to content

Delete the branch a removed worktree created when nothing would be lost - #7242

Merged
ymichael merged 5 commits into
mainfrom
bb/server-o3-worktree-removal-leaves-its-branch-beh-thr_rfnkcrag5v
Nov 9, 2026
Merged

ymichael merged 5 commits into
mainfrom
bb/server-o3-worktree-removal-leaves-its-branch-beh-thr_rfnkcrag5v

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Removing a managed worktree ran git worktree remove --force and deleted the directory, but never deleted the branch bb had created with git worktree add -B. Every thread left a bb/* branch behind. ~/Projects/bb now has 3,953 orphaned bb/* branches as loose refs, plus their stale [branch] config sections. Git reads all of them in every process, and in full every time a ref is listed. That cost reaches every hot git path: bb--git status, github-pr-status refresh, and the shared-refs snapshot the ref watcher reads once per repo.

What changed

  • The worktree plugin records the branch it owns. create returns ownsBranch. It is true in reset mode, in a restore that had to recreate the branch, and in a restore onto a branch an earlier removal kept: kept branches are marked branch.<name>.bbOwned=true in git config, and the marker goes away with the branch's config section. The server stores { ownedBranch: { name, repositoryPath, baseBranch } } as the environment resource. Adopted worktrees, environments created before this change (resource null), and restores onto any other existing branch, such as the user's own, get no ownedBranch, so bb never deletes those branches.
  • remove deletes the owned branch after the worktree is gone, only when nothing would be lost (deleteOwnedBranch in host/worktree.ts):
    • It is kept if any worktree has it checked out. This check runs under the worktree metadata lock that creation also takes.
    • It is deleted if every commit on it is on a remote, a tag, or its recorded base (rev-list <tip> --not --tags --remotes <base>). Commits that survive only on another local branch keep the branch, because a restore could not bring them back to the thread.
    • Otherwise it is deleted only if it was squash-merged into its recorded base. The check compares patch IDs: the branch's net diff against base commits that touch the same paths. It is skipped, and the branch kept, when the base is more than 2,000 commits past the merge base or the branch touches more than 200 paths.
    • Deletion is a compare-and-delete (update-ref -d <ref> <oid>) followed by removal of its branch.<name> config section.
    • A branch with unpushed, unmerged commits is kept, marked as bb's, and reported. A cleanup error never fails the removal.
  • A failed create cleans up its branch too. When git worktree add makes the branch but the create still fails (for example a failing post-checkout hook), the create removes the worktree and deletes the branch it owns under the same rules. A cancelled create still leaves both for the later removal, as before.
  • Restore recreates a deleted branch from its remote. If the local branch is missing and exactly one refs/remotes/<remote>/<name> exists, restore runs git worktree add --track -b <name> <path> <remote>/<name> instead of starting fresh from the base. Pushed-but-unmerged work therefore comes back after an archive and unarchive.
  • Core: environment removal now writes provider progress to the server log ("Environment removal", info level) instead of discarding it, so kept branches are visible. packages/environment-provider-host RunGitOptions now exposes the existing input option for git patch-id.
  • Docs: docs/worktrees.md, the bb guide environments template, the remote-dev-servers guide page, and the plugin README no longer say the branch is always kept.
  • Wire changes: none on the server/daemon protocol. The plugin's private host contract gains remove.ownedBranch and create output ownsBranch. Its server and host halves ship together in the bundled plugin.
  • Ref-scaling hot paths: Watch only each worktree's own refs, report branch-name changes separately, and read shared refs once per repo #7082 already reads the shared-refs snapshot once per repo instead of once per environment. On ~/Projects/bb, that for-each-ref costs about 230 ms whatever the format: dropping %(upstream)%(push) saves only about 10%. The cost is the number of refs, which this change stops growing. No further code change was clearly worth it.

How you verified

Real repo (~/Projects/bb, read-only classification of the 3,953 orphaned bb/* branches; nothing was deleted):

Class Branches This change
Tip already in origin/main 1,598 deleted
Commits all on a remote, tag, or other branch 299 deleted, except those held only by another local branch (now kept)
Squash-merged into origin/main (patch-id match) 1,393 deleted (if within the 2,000-commit window at removal time)
Unpushed or unmerged commits 663 (+1 with no merge base) kept and reported

So 3,290 of 3,953 (83%) would not have accumulated. The squash count used patch IDs of all origin/main commits since May, without the 2,000-commit window. Normally bb removes a worktree minutes after the thread is archived, when the window is small.

Ref cost (temp repo, 40 runs each, load about 10–20):

1 branch 4,001 loose branches + 3,400 config sections
git rev-parse HEAD 12.3 ms 16.1 ms
git status --porcelain=v2 --branch 14.7 ms 19.6 ms
for-each-ref refs/heads refs/remotes 12.8 ms 117 ms

Churn repro: 100 simulated threads in a temp clone with a bare origin. Each was created and then removed through the real host entry (harness). The mix matches the real repo: 40 with no commits, 8 pushed, 33 squash-merged on the "server" with the remote branch deleted and the source fetched with --prune, and 19 unpushed. origin/main's host code and this branch ran on the same script, in alternating runs:

origin/main (2 runs) this branch (2 runs)
bb/* branches left 100, 100 19, 19 (exactly the unpushed ones)
loose refs/heads files 101 20
worktrees left 0 0
remove latency median / p90 195/231, 173/190 ms 330/406, 307/521 ms

Removal runs in the background after retirement. The extra 130–150 ms is 6–13 more git processes on a machine at load 14–21.

End to end: pnpm start:worktree from this branch on an empty dev data dir (not signed in to Connect). The project is a temp repo cloned from a temp bare remote, with a second clone acting as "GitHub" for the squash merge. Everything was driven through the source CLI (pnpm bb:dev, with the inherited BB_* variables unset). Each thread was created with thread spawn --new-environment worktree; its agent turn failed with "Not logged in", which doesn't affect provisioning. Each was archived with thread archive, and teardown ran after the five-minute grace. Git state was read from the source repo afterwards. The log lines are the new "Environment removal" server log.

Case Setup before archive After teardown Server log
a) pushed 1 commit, pushed to origin/bb/o3-pushed-… local branch gone, remote-tracking ref kept Deleted branch bb/o3-pushed-thr_3bvrthbnjv
b) unpushed 1 local commit branch kept at 568cef8, branch.….bbowned=true Kept branch bb/o3-unpushed-thr_c2shbc5u2e because it has commits that are on no remote, tag, or other branch and were not squash-merged into its base
c) squash-merged 2 commits, pushed, squash-merged on the remote, remote branch deleted, fetch --prune branch gone Deleted branch bb/o3-squash-thr_xycyurrf6h
d) restore after delete thread unarchive + thread restore-environment on (a) branch recreated at the pushed f25eb7b, upstream origin/bb/o3-pushed-…; environment resource has ownedBranch branch 'bb/o3-pushed-…' set up to track 'origin/bb/o3-pushed-…' (provisioning log)
e) restore onto kept branch restore (b); its resource has ownedBranch again; then pushed and archived branch, its upstream config and its bbowned marker gone Deleted branch bb/o3-unpushed-thr_c2shbc5u2e
d) second archive archive the restored (a) branch and its branch.…remote/merge config section gone Deleted branch bb/o3-pushed-thr_3bvrthbnjv

Final repo state: only main, no stale [branch] sections, and no worktrees besides the main checkout.

Tests

  • host.test.ts adds real-git cases for each rule:
    • deletes the branch and its config section when nothing else would be lost
    • deletes when the commits are on a remote
    • keeps unpushed commits and reports why
    • keeps a branch whose commits survive only on another local branch
    • deletes the branch when a post-checkout hook fails the create
    • deletes when squash-merged; keeps when squash-merged then extended; keeps when only partly squash-merged
    • keeps a branch checked out elsewhere, and leaves the user's own branch alone
    • leaves legacy ownedBranch: null removals alone
    • still reports removal when the repository is gone
    • restores a deleted pushed branch from its remote with tracking
    • owns a kept branch again on restore
    • does not claim a user branch a restore reuses
  • server.test.ts: create records ownedBranch; restore onto an existing branch records none; remove forwards only a parsed ownedBranch.
  • provider-orchestration.test.ts: removal progress reaches the server log.
  • Against origin/main's plugin source, the new host and server tests fail: 21 failures. Most fail because main's strict contract rejects the new fields, which is why the churn repro is the behavioural before/after.
  • pnpm exec turbo run test typecheck --filter=bb-plugin-environment-git-worktree --filter=bb-environment-provider-host --filter=@bb/templates --filter=@bb/web
  • pnpm exec turbo run typecheck --filter=@bb/server
  • pnpm exec turbo run test --filter=@bb/server -- test/services/environments
  • oxfmt --check on the changed files

Not verified: a remote (non-local) host machine; the e2e ran with the local daemon only. Existing bb/* branches on this machine were deliberately left alone.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 3 commits November 9, 2026 13:58
…ailed creates

Only remotes, tags, and the recorded base now make a branch's commits safe
to delete: a restore can bring those back, but not commits that live only on
another local branch. A create that fails after git made the branch, such as
a failing post-checkout hook, now deletes the branch it owns along with the
worktree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-removal-leaves-its-branch-beh-thr_rfnkcrag5v
@ymichael
ymichael merged commit dcd4062 into main Nov 9, 2026
51 checks passed
@ymichael
ymichael deleted the bb/server-o3-worktree-removal-leaves-its-branch-beh-thr_rfnkcrag5v branch November 9, 2026 22:19
ymichael added a commit that referenced this pull request Nov 16, 2026
…und (#7553)

## Human comments

## What was wrong

Past environment bugs (#3650, #4325, #6828, #6892, #7194, #7242, #7311
and others) were each caught after release, one ordering at a time. No
test drove the real environment engine, the real Worktree and Project
checkout plugins, and real git together through orderings of user and
machine events. The ordering test added here found two bugs on main, and
this PR fixes both.

1. **A deleted environment stuck after an unarchive, then removed with
no grace.** `DELETE /environments/:id` only sets `teardownStatus:
"running"`; the removal happens on the next sweep. If a thread was
unarchived before that sweep, `sweepProviderEnvironmentInSlot` returned
early for an environment with live threads and never cleared the
request. The environment stayed in `teardown` indefinitely: restore
refused it ("not destroyed") and cleanup refused it ("still has live
threads"). The next archive skipped both the 30 s archive undo grace and
the 5-minute retire grace, and removed the worktree, uncommitted files
included, within a second.
2. **A thread failed when the same daemon reconnected during worktree
setup.** #5961 records a setup marker before sending
`environment.attach`. When the daemon reconnected as the same instance
(#3650's case), the server re-sent the attach, but
`runEnvironmentProvisionCommand` refused because the marker was
unfinished. The thread failed with "An earlier setup has an unknown
outcome…", even though the setup was still running and finished seconds
later. The #3650 test seeds a path the provider doesn't own, so it never
writes the marker. Proof runs show the failure starts at #5961.

## What changed

- `apps/server/src/services/environments/environment-engine.ts`
- **Bug 1:** when the sweep finds live threads on an environment whose
removal was requested but has not started (`teardownStatus: "running"`
while still `ready`; starting a removal sets `error`), it withdraws the
request (`teardownStatus` and `retireAt` back to null), and normal
retirement applies. The withdrawal is silent: nothing is added to the
thread's timeline. A removal that has already started is untouched
(#6892's path).
- **Bug 2:** a new `resumeEnvironmentProvisioningForReconnectedDaemon`,
called only from the daemon socket-open path, may re-send an attach
whose setup marker is unfinished. This is safe because the session-open
route, which is awaited before the daemon opens its socket, already
interrupts every provisioning environment when a *different* daemon
instance replaces the session. An environment still provisioning at
socket open therefore had its setup sent to this same daemon, and
`RuntimeManager.ensureEnvironment` joins the in-flight setup (or returns
the finished entry). `resumeEnvironmentProvisioningForHost` keeps main's
signature and behaviour. Every other path keeps #5961's refusal: the
periodic sweep, retries, and the server-move release.
- `apps/server/src/ws/daemon-protocol.ts`: socket open calls the new
resume.
- `packages/templates/src/templates/bb-guide-environments.md`: `bb
environment delete` notes that unarchiving a thread before removal
starts cancels the request.
- New tests:
-
`apps/server/test/services/environments/provider-orchestration.test.ts`:
archive, `DELETE /environments/:id`, unarchive; then the sweep keeps the
environment ready, and never calls `remove`.
-
`apps/server/test/environments/environment-lifecycle-orderings.test.ts`:
the ordering suite.
- **Real code, real data.** A migrated SQLite database
(`createMigratedConnection`), the real server environment engine and
routes, and the real Worktree and Project checkout plugins. Their host
halves run in host-entry harnesses against real git repositories (with a
bare `origin`) in a fresh `mkdtemp` directory, reached through
`plugin.host.call` on a fake daemon.
- **Fake daemon.** It runs turns, answers `environment.attach` by
inspecting the real workspace, can hold or fail any host operation, and
can disconnect, reconnect, or restart as a new instance.
- **Ten orderings** built from create, attach a second thread, archive,
unarchive, remove or retire, restore, failed setup, and daemon
disconnect, reconnect and restart, on one or two machines.
- **Rules checked after every ordering**, compared by rule and subject
only, never messages, counts or timings:
      - `removed-in-use`
      - `work-lost`
      - `orphaned-worktree` / `-branch` / `-claim` / `-row`
- `unsettled-environment` / `unsettled-thread` / `thread-failed` /
`create-raced`
- `setup-rerun`: a restarted daemon is never asked to re-run a setup
whose outcome is unknown. This guards #5961, and it fails if the restart
interrupt at session open is removed.

      There are no known failures.

No protocol, wire, schema, CLI, SDK or plugin API changes. No new
`@bb/db` query functions. No existing test is changed: the server-move
code and its tests, `internal-events-tool-calls.test.ts`, and #5961's
tests are identical to main.

**What a user would see differently, beyond the bugs going away
(decisions for Michael):**
- Deleting an environment and then unarchiving one of its threads before
the removal starts (up to one 10 s sweep) keeps the workspace. Within
one sweep, `bb environment show` returns to `Lifecycle: active`. Before,
the environment was stuck in `teardown` and the next archive removed it
within a second, skipping both graces.
- If the server restarts during worktree setup and the same daemon
process reconnects, setup now resumes instead of failing with "An
earlier setup has an unknown outcome". A restarted daemon still fails
the thread as before.

**Run time:** about 25 s of test time for the ordering file (10
orderings), in its own isolated worker.

## How you verified

**Live, before and after**, using `pnpm start:worktree` from this
checkout on fresh dev data dirs (never a copy of `~/.bb`), the real host
daemon, real Claude Code turns, and temp git repos with an `origin`:
- **Bug 1.** Spawn a worktree thread, `bb thread archive`, `bb
environment delete`, `bb thread unarchive`.
- *Before:* the environment stayed `teardown / running`.
`restore-environment` → 409 "Thread must be settled…"; `environment
cleanup` → 409 "still has live threads". When the thread was archived
again, the worktree and an uncommitted `notes.txt` were gone within 1 s.
- *After:* within one sweep the environment was back to `Lifecycle:
active`. The thread's timeline gets no new entry. On the next archive
the worktree and `notes.txt` survived 60 s, with `retireAt` 5 minutes
out.
- **Bug 2, daemon reconnect.** A 60 s `.bb-env-setup.sh`; the server was
paused with SIGSTOP for 40 s so the daemon's lease expired.
`host_daemon_sessions` shows the same `instance_id` reconnecting.
- *Before:* "Workspace setup interrupted" → "An earlier setup has an
unknown outcome…", while the setup then finished.
- *After:* the setup completed, the marker finished, the thread went
idle and Claude replied "ok". `.bb-env-setup.sh` ran once.
- **Bug 2, server restart.** The server process was killed with SIGKILL
during the same 60 s setup, and the launcher restarted it (new PID
within 3 s). The daemon kept its PID and `instance_id`, so its session
was replaced by the same instance. The thread went idle with Claude's
"ok", the setup marker finished, and the script's own run log has
exactly one line.
- **#5961's protection, live on the fixed build.** The daemon was killed
with SIGKILL during setup and respawned as a new instance. The thread
failed with "Host daemon restarted while preparing the workspace", and
setup was not re-run.
- **Server-move release path, shown by existing tests.** This PR doesn't
change `apps/server/src/services/server-move/environment.ts` (zero diff
against main). Its call, `resumeEnvironmentProvisioningForHost`, keeps
main's signature and behaviour (`setupRunsOnConnectedDaemon: false`).
The existing, unmodified `test/server-move/freeze-work.test.ts` asserts
that a move release calls it with `{ hostId }`. The existing, unmodified
#5961 test in `test/environments/environment-provisioning.test.ts`
("does not replace an unresolved RuntimeManager setup with a new
successful attempt") asserts that this path still refuses an unfinished
setup. Both pass.

**Proof runs of the test** (kept out of this PR). The test was run on
each listed fix's merge commit and its parent, and the violations were
diffed:

| Fix | Caught? | Ordering → violation on the parent |
|---|---|---|
| #3650 | yes | reconnect during setup → `thread-failed: A` |
| #4325 | yes | second thread's setup fails on a shared checkout →
`orphaned-claim: env(B)` |
| #6828 | yes | retire with a `refs/worktree/*` ref → `work-lost:
worktree-ref in A` |
| #6892 | yes | unarchive while removal runs → `orphaned-row: env(A)` |
| #7194 | yes | slow removal on machine a while b's grace passes →
`unsettled-environment: env(B)` |
| #7242 | yes | archive and retire → `orphaned-branch: env(B)` |
| #7311 | yes | three creates on one checkout path → `create-raced:
create C`, `thread-failed: A` |
| #3756 (extra) | yes | archive during setup → `unsettled-thread: A` |
| #4187 | no | The cancel only fired on a second placement pass while
the new thread still owned the merged checkout row. Public actions join
in one pass. |
| #5961 | no | Before #5961, attach-based setup wrote no persisted hook
record, so the retry loop it fixed never arises here. |
| #6016 | no | Directory moves are not among the orderings. |
| #6889 | no | Only an error message changed, and the test asserts
rules, not messages. |

The restart ordering and the `setup-rerun` rule were added after the
proof runs. They guard the reconnect fix and were checked by the
mutation above rather than against history.

**Local:** targeted suites pass: `test/environments`,
`test/services/environments`, thread provisioning recovery, internal
events tool calls, periodic sweeps, public environment routes,
environment providers, live commands and `test/server-move` (375 tests),
plus `@bb/thread-view` and `@bb/templates` tests. `turbo run typecheck
lint:type-aware` for `@bb/server` and `@bb/thread-view` pass, and `oxfmt
--check` is clean. CI runs the full suites.

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

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 24, 2026
… them up and keep them warm (#8065)

## Human comments

## What was wrong

#8007 added `additionalPaths` so an environment provider can give a
thread extra folders, but no provider returned any, and nothing let an
environment take a project folder out of the thread's workspace. A
worktree thread in a multi-folder project could only branch the main
repository: every other repository in `bb project folder` stayed a
shared checkout that all threads wrote to. Setup scripts also ran only
in the main workspace, and warm worktrees could not carry extra
repositories.

## What changed

**Core contract (experimental, documented in `docs/api_to_audit.md`).**
- `additionalPaths` becomes a list of `{ path, replaces? }` entries
(domain: `replaces: string | null`, filled once when the create result
is parsed). `replaces` names the project folder an entry stands in for.
`mergeWorkspaceFolderPaths` (`workspace-folder-paths.ts`) is the one
place that builds the session's folders: project folders minus the
replaced ones, plus each entry's `path`. A replaced folder stays out
even when its replacement is missing, so a thread never falls back to
writing the shared checkout. Migration 0171 converts recorded
`additional_paths` strings into entries that replace nothing. `bb
environment show` prints `Folder: <path> (replaces project folder
<folder>)`.
- `setup(path, { folders })`: a create can name the extra folders it
made. Core stores them (`environments.setup_folder_paths`, migration
0170), runs each folder's `.bb-env-setup.sh` once, in order, before the
main one (each as its own hook operation, `…:setup:folder:<i>`), and
runs teardown in the main workspace first, then the folders in reverse.
A create fails if it set up a folder it did not return in
`additionalPaths`. After `adopt`, `folders` may name only folders the
adopted environment recorded: core forgets their finished setup records
(`forgetFinishedEnvironmentHookOperations`) and runs them again, then
the main one. Recovery inspects and acknowledges each folder's hooks.
- Plugin SDK 0.6.197. No daemon wire change: hooks already run per path,
and the daemon still receives the merged folder list.

**Worktree provider (`plugins/environment-git-worktree`).**
- Inputs gain `folders: string[]` (default `[]`). `validate`/`create`
refuse a folder that is not one of the project's folders on that
machine.
- New host RPC `createFolders` (`host/folders.ts`): each folder must be
the top folder of a repository with a commit, and no two (including the
main checkout) may share a git common dir. It makes a worktree of each
folder next to the main one, detached at that repository's default base.
If one fails, everything made is removed.
- Create and restore pass the new folder worktrees to `setup`, so their
setup scripts run before the main worktree's.
- Removal removes every worktree in the environment's directory and
deletes each repository's bb-owned branch under the #7242 rules.
- Picker: "Also branch:" lists the machine's project folders that are
git repositories (`listBranchableFolders`).
- Warm pools: folders are set per machine (each checkout has its own
folder paths), on the settings page under each machine or with `bb
worktree pool folders <project-id> <folder>... [--host <host-id>]`, and
stored next to #8112's per-machine counts. Members are created with
those folders and handed only to a create that branches exactly that
set. On handoff the provider checks each folder worktree like the main
one, fast-forwards any that is behind its remote, renames the
placeholder in every worktree, and calls `setup(main, { folders: moved
})`, so only moved folders (and then the main worktree) are set up
again. Reconcile replaces members whose folder set differs or whose
folder worktree left the placeholder or its base.
- Settings: each machine's folder checkboxes sit under it and are shown
only while it keeps warm worktrees; a chosen folder that is no longer a
git project folder there is flagged. Ladle stories cover every state.

**Storage retention.** An environment's `additionalPaths` count as
bb-owned (never offered as external worktrees), their uncommitted
changes block automatic recovery of an interrupted cleanup, and their
size is added to the leftover worktree's.

**Docs.** README, the worktree skill, the bb guide's environments and
projects chapters, and the plugin-authoring references.

## How you verified

- New and updated tests: `environment-holds.test.ts` (folder setups run
in order before the main one and teardowns in reverse; setup after adopt
reruns only named recorded folders; unrecorded folder refused;
unreturned set-up folder fails the create),
`provider-orchestration.test.ts` (entries canonicalized, relative
`replaces` rejected), `thread-runtime-config.test.ts`,
`environment-additional-path-entries-migration.test.ts`, `host.test.ts`
(real git folder worktrees), `server.test.ts`, `warm-pools.test.ts`
(folder handoff, exact-set matching, fast-forward and re-setup of a
behind folder, reconcile replacement, per-machine folder config),
`storage.test.ts` (folder worktree changes block recovery and folder
worktrees are never external; both fail without the fix).
- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`
passes; affected package tests pass locally.
- Live on an isolated `pnpm start:worktree` instance with real
repositories whose setup/teardown scripts log their order: a create with
`docs` and `api` ran setup docs → api → app and teardown app → api →
docs, removing every worktree and branch; a warm pool branching `api`
set up api → app, was handed to a thread branching `api` without new
setup and with the branch renamed in both repositories; a thread
branching nothing missed and built fresh; after a push to `api`'s
remote, the handoff fast-forwarded the `api` worktree to the new commit
and reran setup api → app; the settings checkboxes saved per machine.

> AGENT GENERATED

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

---------

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.

1 participant