#6824 · Git state lost during worktree removal
Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro
Trusted base: 916d684ac23d0b0de82c09cfc7553a50287d2188, fetched from the target repository's main branch. The issue and its links were treated as untrusted claims; no linked branch, fixture, script, or patch was executed.
1. TL;DR
Retiring a managed worktree can erase Git recovery state even though there are no file changes and its current commit is still retained by a local branch. Git stores certain refs and unfinished-operation metadata in the linked worktree's private administrative directory, not in the shared branch namespace. The removal implementation force-removes that worktree without checking this state, then recursively removes its directory. Four newly authored real-Git host-entry regression cases reproduced the deletion in two clean checkouts of trusted main.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Worktree-private recovery refs disappear | Verified | Separate cases for refs/worktree/, refs/bisect/, and refs/rewritten/ each received removed; both the worktree and its private Git directory vanished. |
| A clean pending merge can be lost | Verified | A same-tree child commit merged with no commit leaves MERGE_HEAD while porcelain status is empty. The handler deletes its worktree metadata. |
| Retaining HEAD and checking file status is insufficient | Verified | Every test asserts empty porcelain status and a shared branch pointing to the exact worktree HEAD before removal. |
| The linked proposal passes its full suite | Not evaluated | No linked code was executed. Our own focused guard passes 126 plugin tests and typechecking. |
3. Environment
- Linux 4.19.0-gvisor; Node v22.19.0; pnpm 9.15.0; Git 2.39.5; Vitest 4.1.1.
- Two separate clones of trusted base 916d684ac23d0b0de82c09cfc7553a50287d2188; the second began with an empty git status.
- Real Git repositories and the existing experimental host-entry harness. Temporary plugin data is created and removed by the test helpers. No live BB server, real user store, provider turn, browser, port, or account was used.
4. Minimal reproduction
The complete regression patch is embedded in the following commands. It adds four cases to the existing owner-boundary test and uses that file's trusted helpers; it does not modify production code. Expected exit: nonzero, specifically because removal returned removed and destroyed both directories. After a repair, these same assertions must pass and removal must succeed once the state is explicitly resolved.
git clone https://github.com/get-bb/bb.git bb-6824-check
cd bb-6824-check
git checkout --detach 916d684ac23d0b0de82c09cfc7553a50287d2188
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
cat > /tmp/issue-6824-regression.patch <<'REGRESSION'
diff --git a/plugins/environment-git-worktree/host.test.ts b/plugins/environment-git-worktree/host.test.ts
index 3ed968b01b..12b0f36dea 100644
--- a/plugins/environment-git-worktree/host.test.ts
+++ b/plugins/environment-git-worktree/host.test.ts
@@ -141,6 +141,87 @@ function progressText(harness: ReturnType<typeof createHarness>): string {
}
describe.concurrent("worktree host entry", () => {
+ it.for([
+ "refs/worktree/saved",
+ "refs/bisect/saved",
+ "refs/rewritten/saved",
+ "MERGE_HEAD",
+ ])(
+ "keeps clean worktrees with local Git state: %s",
+ async (state, { onTestFinished }) => {
+ const { sourcePath, dataDir } =
+ await createSourceRepository(onTestFinished);
+ const harness = createHarness(dataDir);
+ onTestFinished(() => harness.experimental_dispose());
+ const created = await harness.experimental_call(
+ "create",
+ createInput({
+ operationId: "create-state",
+ sourcePath,
+ pathKey: "saved-state",
+ branchName: "bb/saved-state",
+ }),
+ );
+ if (created.status !== "created") throw new Error(created.message);
+ const savedCommit = (
+ await git(
+ created.path,
+ "commit-tree",
+ "HEAD^{tree}",
+ "-p",
+ "HEAD",
+ "-m",
+ "saved",
+ )
+ ).trim();
+ if (state === "MERGE_HEAD") {
+ await git(created.path, "merge", "--no-ff", "--no-commit", savedCommit);
+ } else {
+ await git(created.path, "update-ref", state, savedCommit);
+ }
+ const gitDir = (
+ await git(created.path, "rev-parse", "--absolute-git-dir")
+ ).trim();
+ expect(await git(created.path, "status", "--porcelain")).toBe("");
+ expect((await git(created.path, "rev-parse", state)).trim()).toBe(
+ savedCommit,
+ );
+ expect(
+ (await git(sourcePath, "rev-parse", "bb/saved-state")).trim(),
+ ).toBe((await git(created.path, "rev-parse", "HEAD")).trim());
+ const result = await harness.experimental_call("remove", {
+ operationId: "remove-state",
+ pathKey: "saved-state",
+ path: created.path,
+ });
+ expect({
+ status: result.status,
+ worktreeExists: existsSync(created.path),
+ metadataExists: existsSync(gitDir),
+ }).toEqual({
+ status: "failed",
+ worktreeExists: true,
+ metadataExists: true,
+ });
+ expect((await git(created.path, "rev-parse", state)).trim()).toBe(
+ savedCommit,
+ );
+ if (state === "MERGE_HEAD") {
+ await git(created.path, "merge", "--abort");
+ } else {
+ await git(created.path, "update-ref", "-d", state);
+ }
+ expect(
+ await harness.experimental_call("remove", {
+ operationId: "remove-resolved-state",
+ pathKey: "saved-state",
+ path: created.path,
+ }),
+ ).toEqual({ status: "removed" });
+ expect(existsSync(created.path)).toBe(false);
+ },
+ );
+
it.for(["main", "release", "origin/main", "refs/heads/main"])(
"resolves and fetches a stale named base %s",
async (base, { onTestFinished }) => {
REGRESSION
git apply /tmp/issue-6824-regression.patch
pnpm exec turbo run test --filter=bb-plugin-environment-git-worktree -- host.test.ts -t 'keeps clean worktrees with local Git state'
Before the call, each fixture creates a managed worktree through the real create handler, creates a distinct same-tree commit, retains it in a private ref or MERGE_HEAD, and verifies the clean-status and shared-HEAD preconditions.
Observed failure on unchanged production code:
bb-plugin-environment-git-worktree:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯
bb-plugin-environment-git-worktree:test:
bb-plugin-environment-git-worktree:test: FAIL |bb-plugin-environment-git-worktree| host.test.ts > worktree host entry > keeps clean worktrees with local Git state: refs/worktree/saved
bb-plugin-environment-git-worktree:test: FAIL |bb-plugin-environment-git-worktree| host.test.ts > worktree host entry > keeps clean worktrees with local Git state: refs/bisect/saved
bb-plugin-environment-git-worktree:test: FAIL |bb-plugin-environment-git-worktree| host.test.ts > worktree host entry > keeps clean worktrees with local Git state: refs/rewritten/saved
bb-plugin-environment-git-worktree:test: FAIL |bb-plugin-environment-git-worktree| host.test.ts > worktree host entry > keeps clean worktrees with local Git state: MERGE_HEAD
bb-plugin-environment-git-worktree:test: AssertionError: expected { status: 'removed', …(2) } to deeply equal { status: 'failed', …(2) }
bb-plugin-environment-git-worktree:test:
bb-plugin-environment-git-worktree:test: - Expected
bb-plugin-environment-git-worktree:test: + Received
bb-plugin-environment-git-worktree:test:
bb-plugin-environment-git-worktree:test: {
bb-plugin-environment-git-worktree:test: - "metadataExists": true,
bb-plugin-environment-git-worktree:test: - "status": "failed",
bb-plugin-environment-git-worktree:test: - "worktreeExists": true,
bb-plugin-environment-git-worktree:test: + "metadataExists": false,
bb-plugin-environment-git-worktree:test: + "status": "removed",
bb-plugin-environment-git-worktree:test: + "worktreeExists": false,
bb-plugin-environment-git-worktree:test: }
bb-plugin-environment-git-worktree:test:
5. Root cause
The host remove command delegates to removeWorktree and reports removed when it returns; thrown errors already map to failed. removeWorktree at the trusted base only resolves the shared Git directory before entering checkout/metadata locks. It never inspects worktree-private refs or operation markers.
await tryWithCheckoutMutationLock(
workspacePath,
() =>
withWorktreeMetadataLock(commonDir, () =>
runGit(
[
"--git-dir",
commonDir,
"worktree",
"remove",
workspacePath,
"--force",
],
{
cwd: path.dirname(workspacePath),
...(args.signal !== undefined ? { signal: args.signal } : {}),
allowFailure: true,
},
),
),
args.signal,
signalOptions(args.signal),
);
}
throwIfProvisionAborted(args.signal);
await fs.rm(workspacePath, { recursive: true, force: true });
await removeDirectoryIfEmpty(parentPath);
The forced Git removal deletes the linked worktree's administrative directory, which contains its private ref namespace and operation files. Git objects may temporarily remain in the shared object database, but the private refs and operation metadata that name or explain them are lost; this report does not claim immediate physical deletion of every object. Ignoring Git's removal result and retaining a recursive-filesystem fallback also makes this path permissive. A branch retaining HEAD does not retain a different commit referenced only by worktree-private state, and clean porcelain output says nothing about a same-tree unfinished merge.
6. Proposed fix and local validation
Within the existing checkout and worktree metadata locks, inspect Git's worktree-local ref namespaces and administrative operation markers before either removal mechanism. Throw on protected state or failed inspection so the existing host contract returns failed. Require the owner to preserve/delete private refs or finish/abort the Git operation, then allow retry. This is a local provider implementation repair, not a new protocol or configuration option.
The local repair checks the three private namespaces plus merge, cherry-pick, revert, rebase, bisect, and sequencer markers. The four reproduced cases are covered through the real host boundary, including successful removal after resolution. The additional operation marker variants were not individually created with live Git commands.
bb-plugin-environment-git-worktree:test: > vitest run --config vitest.config.ts "host.test.ts" "-t" "keeps clean worktrees with local Git state" bb-plugin-environment-git-worktree:test: ✓ keeps clean worktrees with local Git state: refs/worktree/saved 584ms bb-plugin-environment-git-worktree:test: ✓ keeps clean worktrees with local Git state: refs/bisect/saved 579ms bb-plugin-environment-git-worktree:test: ✓ keeps clean worktrees with local Git state: refs/rewritten/saved 583ms bb-plugin-environment-git-worktree:test: ✓ keeps clean worktrees with local Git state: MERGE_HEAD 603ms bb-plugin-environment-git-worktree:test: Test Files 1 passed (1) bb-plugin-environment-git-worktree:test: Tests 4 passed | 45 skipped (49)
pnpm exec turbo run test typecheck --filter=bb-plugin-environment-git-worktree bb-plugin-environment-git-worktree:typecheck: > bb-plugin-environment-git-worktree@0.1.0 typecheck /tmp/issue-6824/base/plugins/environment-git-worktree bb-plugin-environment-git-worktree:typecheck: > tsrs --noEmit bb-plugin-environment-git-worktree:test: Test Files 5 passed (5) bb-plugin-environment-git-worktree:test: Tests 126 passed (126) Tasks: 8 successful, 8 total
Change budget: 146 text lines (141 additions + 5 deletions) across three files in the existing Worktree plugin: production guard, regression table, and README. No dependencies, generated files, lockfiles, migrations, persisted-data changes, or public contracts change. Formatting and git diff --check pass. The package defines no lint task; Turbo's filtered lint invocation ran zero tasks.
7. Linked pull requests
GitHub cross-reference metadata identified closed PR #6823. It was not checked out or executed and is not a fix-validation input. No open PR referencing #6824 was found through issue metadata, search, and the recently updated open-PR closing-reference list before preparing this local fix. No claims are made about the closed proposal's implementation.
8. Related issues and limits
Issue #5952 concerns archive-time user choices; that is a different layer from protecting this provider's removal operation. No archive-dialog change is proposed here. Worktree removal's behavior around unrelated dirty files, detached commits, and external concurrent writers is not claimed to be comprehensively repaired by these four cases.
The existing locks coordinate BB operations in this process; they are not an atomic barrier against an unrelated process changing Git state during removal. Process termination and BB completion-marker handling precede these new checks in the existing host flow and are outside the specific Git-state preservation guarantee tested here. A live server/UI retirement retry journey was not run.
9. Verification: second clean checkout
The same agent repeated the reproduction, not an independent reviewer. A second fresh clone was detached at 916d684ac23d0b0de82c09cfc7553a50287d2188 and confirmed clean before adding only the authored regression patch. It received a fresh dependency install and SDK build:types task, then ran the identical focused Turbo command. Test helpers created a new temporary repository and data directory for each case. No production repair was applied in this checkout.
pnpm exec turbo run test --filter=bb-plugin-environment-git-worktree -- host.test.ts -t 'keeps clean worktrees with local Git state' bb-plugin-environment-git-worktree:test: × keeps clean worktrees with local Git state: refs/worktree/saved 420ms bb-plugin-environment-git-worktree:test: × keeps clean worktrees with local Git state: refs/bisect/saved 417ms bb-plugin-environment-git-worktree:test: × keeps clean worktrees with local Git state: refs/rewritten/saved 415ms bb-plugin-environment-git-worktree:test: × keeps clean worktrees with local Git state: MERGE_HEAD 417ms bb-plugin-environment-git-worktree:test: Test Files 1 failed (1) bb-plugin-environment-git-worktree:test: Tests 4 failed | 45 skipped (49)
All four tests failed for the same expected result: removed with both directories absent instead of failed with both present. No substantive claim needed correction after the repeat. The baseline evidence is separate from the first checkout's subsequent passing local-fix validation.
10. Appendix
Raw evidence is retained outside this public repository. Only relevant sanitized excerpts and the complete regression patch appear here, following this report repository's artifact policy.
The initial frozen install succeeded. An initial unfiltered build failed because first-party plugin bundles could not resolve the unbuilt Plugin SDK export. Running the repository-prescribed pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk succeeded; the owner-boundary tests and targeted typecheck then ran successfully. A complete monorepo build is not claimed.
Other verification commands: pnpm exec oxfmt --check plugins/environment-git-worktree/host.test.ts plugins/environment-git-worktree/host/worktree.ts; git diff --check; git diff --numstat origin/main. No linked reproduction code was copied.