Skip to content

Resolve named worktree bases against origin and reuse non-git parent folders - #6336

Merged
ymichael merged 1 commit into
mainfrom
bb/named-base-branch-and-folder-reuse-thr_aix5mkmch4
Oct 26, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/named-base-branch-and-folder-reuse-thr_aix5mkmch4

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

bb thread spawn --base-branch main passed main to git worktree add unchanged. When the local main was behind origin/main, the new worktree started from the stale local commit. Only names that already began with origin/ were fetched first. The default base (no --base-branch) already compared local with origin; named branches skipped that comparison.

Separately, a child of a live thread in a project whose folder is not a Git repository always asked the git-worktree provider for a fresh worktree on the parent's machine. That fails, because there is no repository to make a worktree of.

This is the part of #6193 that still applies after #6165. #6165 rebuilt git reads and the shared git runner on main, which replaced the rest of #6193.

What changed

  • Named bases use the default-branch rule (plugins/environment-git-worktree/host/base-branch.ts):

    • a bare branch name uses origin/<name> when local is equal or behind;
    • it keeps local when local is ahead, diverged or unknown;
    • it uses the remote when only the remote branch exists.

    Explicit remote names such as origin/main and refs/... paths are used exactly. The selected remote base is fetched before creation, as before.

  • The default base is always returned and stored. Before, the resolver returned null when the result equaled the local default, and createWorktree re-read the repository default. defaultBaseBranch and create now share one resolver.

  • readBranchRelation (previously the private readDefaultBranchRelation in bb-environment-provider-host/workspace-git) is exported, so the plugin can compare any local/remote branch pair.

  • Non-git parent reuse (apps/server/src/services/threads/thread-default-policy.ts): a child of a live thread in the same project reuses its parent's environment instead of requesting a worktree. This applies only when:

    • the child asked for the project default, or the implicit host default on the parent's machine;
    • the parent's environment is ready;
    • the environment is not a Git repository and its path is not owned by a provider.
  • Docs: the --base-branch help in bb thread spawn and bb thread fork, the threads guide and the worktree plugin README describe both rules.

No wire changes and no SDK changes.

How you verified

  • pnpm exec turbo run typecheck lint --filter='...[origin/main]': 123/123 pass.
  • pnpm exec turbo run test for the git-worktree, project-checkout and Git plugins, bb-environment-provider-host, @bb/cli and @bb/templates: all pass. The server's thread-default-policy and worktree-base-branch tests pass.
  • Tests added. Against main's code, the stale-base and reuse tests fail and the rest pass:
    • host.test.ts: a stale local main or release now starts from the remote commit. origin/main is used as the remote. refs/heads/main keeps the local commit. These fail on main for main and release.
    • host.test.ts: local commits are kept when local is ahead or diverged, for main, release, refs/heads/main and the default base. These guard against the new rule dropping local work.
    • thread-default-policy.test.ts: implicit project-default and host children of a non-git parent reuse its environment. Both fail on main.

Fixes #1917

AGENT GENERATED

🤖 Generated with Claude Code

…folders

A named --base-branch used the local ref as-is, so a stale local branch
became the base and only origin/-prefixed names were fetched. Named
branches now use the same rule as the default branch: origin/<name> when
local is equal or behind, local when it is ahead, diverged or unknown,
and the remote when only the remote exists. Explicit remote names and
refs/ paths stay exact. The default base is now always returned, so the
resolved branch is stored with the environment.

A child of a live thread in an unmanaged non-Git folder now reuses its
parent's ready environment instead of failing to create a worktree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 8cdbc46 into main Oct 26, 2026
51 checks passed
@ymichael
ymichael deleted the bb/named-base-branch-and-folder-reuse-thr_aix5mkmch4 branch October 26, 2026 21:44
ymichael added a commit that referenced this pull request Oct 27, 2026
## Human comments

## What was wrong

#6336 (8cdbc46) resolves a bare `--base-branch <name>` to
`origin/<name>` when the local branch is equal to or behind the remote.
`createWorktree` then fetches every `<remote>/<branch>` base with
`GIT_TERMINAL_PROMPT=0` and rethrows any fetch error other than
concurrent ref-update races. Before #6336, `--base-branch main` went
straight to `git worktree add` with no network access. Now, if the
machine is offline, the remote is unreachable, or credentials can't
prompt, creating a thread or worktree with a named base fails. The
default base (no `--base-branch`) already failed this way when local
matched origin.

## What changed

- **Fallback rule**
(`plugins/environment-git-worktree/host/worktree.ts`,
`host/base-branch.ts`): `resolveWorktreeBaseBranch` now returns `{ ref,
fetchFailureFallback }`. `fetchFailureFallback` is true only when the
resolver picked `origin/<name>` itself, for a bare named branch or for
the project default. When the fetch of such a base fails with
`git_command_failed` or `git_command_timeout`, the worktree is created
from the existing `refs/remotes/origin/<name>` instead of failing. A
queued ref-lock timeout also surfaces as `git_command_timeout`, so it
falls back too.
- **Why the last fetched remote-tracking ref, not the local branch:**
the resolver picks `origin/<name>` only when local is `equal` or
`local-behind`, or when no local branch exists. A failed fetch leaves
the ref unchanged, so the fallback commit is always the local branch or
a descendant of it. When local is ahead, diverged or unknown, the
resolver keeps the local branch and never fetches, so local work is
never replaced by an older commit. Keeping the same ref also keeps the
returned and stored base (`mergeBaseBranch`) accurate (`origin/<name>`),
and that ref updates on the next successful fetch.
- **Why any git failure, not only network or auth:** git reports DNS,
TLS, proxy, auth, missing-repository and timeout failures with
transport- and version-specific stderr. Matching on that text would be
fragile. All of these leave the same safe choice, and the warning shows
the user which one happened.
- **Explicit remote names still fail hard.** Before #6336,
`--base-branch origin/main` always fetched and failed hard, so this is
not a regression. Someone who types a remote ref is asking for the
remote's current state. The default branch and bare names fall back the
same way, since in both cases bb chose the remote.
`refs/remotes/origin/<name>` is already used exactly without a fetch,
which gives an explicit offline option.
- **Cancellation:** the fallback is skipped when the signal is aborted
or the error is `provision_cancelled`.
- **Progress:** the existing `Failed to fetch origin/<name>` step
(status `failed`) is followed by an output line with git's error and a
completed `git-fetch-fallback` step: `Using the last fetched
origin/<name> (<short sha>); it may be out of date`. If the
remote-tracking ref has disappeared, the original error is rethrown.
- **Docs:** the threads guide
(`packages/templates/src/templates/bb-guide-threads.md`) and the plugin
README describe the fallback and how explicit refs behave. The
`--base-branch` help in `bb thread spawn` and `bb thread fork` doesn't
mention fetching and is unchanged.
- No wire, contract, or `HOST_DAEMON_PROTOCOL_VERSION` changes: the
`create` and `defaultBaseBranch` outputs keep their shapes, and the new
field stays inside the plugin host.

## How you verified

- New tests in `plugins/environment-git-worktree/host.test.ts`. Each one
clones a source repo, then points `origin` at a missing path to make it
unreachable:
- `uses the last fetched remote when the fetch fails for {equal, behind}
with base {main, default}` and `remote-only with base release`: the
worktree is created at the clone's last fetched `origin/<name>`, the
result's `baseBranch` is `origin/<name>`, local `main` is untouched, and
progress includes both `Failed to fetch` and `Using the last fetched …
(<sha>)`. **All 5 fail on main** ("git fetch … does not appear to be a
git repository") and pass with this change.
- `keeps a local base that is ahead without fetching for base {main,
default}`: created from the local commit with no fetch step. These guard
the rule above.
- `fails when an explicit remote base cannot be fetched`: `origin/main`
still returns `failed` and leaves no worktree.
- `cancels a create whose base fetch is still running`: a fake
`core.sshCommand` hangs the fetch, the create is aborted, the call
rejects, there is no fallback step, and no worktree is left.
  - The guard tests pass on main as well as with this change.
- `pnpm exec turbo run test --filter=bb-plugin-environment-git-worktree`
on main's source with the new tests: 5 failed, 116 passed. With the fix:
121 passed.
- `pnpm exec turbo run typecheck lint test
--filter=bb-plugin-environment-git-worktree --filter=@bb/templates`:
11/11 tasks successful.

> AGENT GENERATED

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 18, 2026
## Human comments

## What was wrong

Choosing between a local branch and `origin/<name>` had no single owner.
The rule "use `origin/<name>` unless the local branch is ahead or has
diverged" existed three times: `resolveDefaultWorktreeBaseBranch` in the
server (`apps/server/src/services/projects/worktree-base-branch.ts`), an
identical copy in the git-worktree plugin, and a third version written
as `merge-base --is-ancestor` in the Git plugin (#7425). A fourth site,
project-checkout's new-branch base, used a different rule: the local
branch always won. Each fix touched one site, and the others kept the
old behavior. Two bugs are still live on main:

- **Project checkout bases new branches on a stale local branch.**
Reproduced live on a source dev instance at `1fa400dec78`. In a clone
where `main` is 1 behind `origin/main`, `bb thread spawn
--environment-provider project-checkout --environment-inputs
'{"branch":{"kind":"new","baseBranch":"main"}}'` created
`bb/reply-with-ok-thr_…` at `d167c6c` (local `main`). `origin/main` was
at `bd9d253`, and the environment recorded `mergeBaseBranch: main`. This
is the #1770/#1917 bug in a provider those fixes never reached.
- **The diff cache misses moves of `origin/<base>`.** The host watch set
(`packages/host-workspace/src/git.ts` `fingerprintFor`) covered
`refs/heads/<base>` and `refs/remotes/<base>`. Since #7425, though, the
Git plugin resolves a bare `<base>` against
`refs/remotes/origin/<base>`. For a non-default base such as `release`,
a fetch that moves `origin/release` therefore left the refs fingerprint
unchanged, and the merge base stayed cached.

## What changed

- `packages/environment-provider-host/src/workspace-git.ts` now owns the
rule:
- `resolveBranchRef(cwd, name)` → `{ ref, source: "local" | "origin" |
"as-given" }`. It makes one `for-each-ref` read of the candidates, then
compares them only when both local and origin exist.
- `readDefaultBranchRefs(...).baseBranch` applies the same internal
`chooseBranchRef` to the default branch.
  - `branchRefCandidates(name)` lists the refs the resolver reads.
- All three are exported from `bb-environment-provider-host/git` and
`/workspace-git`. The worktree plugin was the only user of
`readBranchRelation`, so it is deleted.
- Callers moved onto it:
- git-worktree `host/base-branch.ts`: named and default bases.
`fetchFailureFallback` is now `source === "origin"`.
- Git plugin `resolveMergeBaseBranch`: resolve the ref, then one
`rev-parse`.
- project-checkout `planSwitch`: new-branch base. Switching to an
*existing* branch keeps local-first lookup, because that is your own
branch.
- host-workspace `fingerprintFor`: watches
`branchRefCandidates(mergeBaseBranch)`, which now includes
`refs/remotes/origin/<base>`.
- **Server/daemon:** `host.inspect_git_source` returns
`defaultWorktreeBaseBranch`, resolved on the host. The server stops
recomputing it: the route passes the field through and
`projectSourceHasWorktreeBase` reads it.
`apps/server/src/services/projects/worktree-base-branch.ts` and its test
are deleted. `projectBranchesResponseSchema` keeps the same public
`defaultWorktreeBaseBranch` field. **Wire change:
`HOST_DAEMON_PROTOCOL_VERSION` 266 → 267.**
- **Guard:** `bb-environment-provider-host/testing/branch-ref-cases`
provides one case table on real Git repos: local only, origin only,
equal, local behind, local ahead, diverged, `origin/<name>`,
`refs/heads/<name>`, missing. It also derives the default-branch subset.
The same table runs against every caller:
- the resolver itself
(`packages/environment-provider-host/test/branch-ref.test.ts`)
- the worktree named and default bases
(`plugins/environment-git-worktree/host/base-branch.test.ts`)
- the Git plugin merge base
(`plugins/git/host/merge-base-branch.test.ts`)
- the project-checkout new branch
(`plugins/environment-project-checkout/host.test.ts`)
- the daemon's `inspect_git_source`
(`apps/host-daemon/test/command/host-branches-dispatch.test.ts`)
- the host-workspace watch set
(`packages/host-workspace/test/shared-refs-branch-ref.test.ts`)
- **Owner guard:** `scripts/check-branch-ref-owner.mjs` runs in the CI
plan job next to the provider-literal ratchet. Source outside
`workspace-git.ts` fails it when it builds `refs/remotes/origin/${…}` or
`` `origin/${…}` `` refs, concatenates `"origin/" +`, or runs
`merge-base --is-ancestor`. Tests and fixtures are exempt. Five files
are allowlisted, each with a reason. The allowlist exempts whole files,
with no per-file counts, so a harmless edit to an allowlisted file never
fails CI:
  - marketplace and plugin-update clones (fresh clones, server-side)
  - bb-app's self-update fast-forward check
  - the branch picker's origin-default pin
- project-checkout's switch to an *existing* branch, which keeps local
first by design

A lint rule would not do this job: CI lints only packages that have a
`lint` script, and `apps/server`, `apps/host-daemon`, `packages/bb-app`
and the two environment plugins have none. Fixture tests are in
`packages/scripts/test/branch-ref-owner.test.mjs`. Against the pre-#6336
worktree copy, the pre-#7425 and #7425 Git plugin copies, and the old
project-checkout code, the check fails on each file.
- **Owned-branch cleanup**
(`plugins/environment-git-worktree/host/worktree.ts`
`hasCommitsOnlyOnBranch`) resolves the stored base through
`resolveBranchRef`. Before, a stored bare base such as `main` was read
as-is. If origin squash-merged the branch and its remote branch was
pruned, cleanup compared against the stale local `main` and kept the
branch. It erred toward keeping, never toward deleting. Origin is only
chosen when it contains the local branch, so a resolved base can only
reveal merges that really happened. A new test, which fails without the
change, is in `host.test.ts`.
- The host watch set's default-branch refs and project-checkout's
`switch --track` now use `branchRefCandidates` and the full origin ref,
instead of building them by hand.
- Docs: `docs/worktrees.md` still said explicit names are used as-is
(out of date since #6336). The project-checkout README described
local-wins for new branches. Both now describe the shared rule.

### Root cause history

| | Issue | Fixed by | Site patched | Prevented by one resolver + table?
|
|---|---|---|---|---|
| closed | #1770 `--base-branch` resolves the stale local ref | #2152 |
server spawn | Yes. The equal and behind rows. |
| closed | #1917 the same, for named bases in the worktree plugin |
#6336 | worktree plugin | Yes. It re-implemented #2152's rule; the table
fails on the pre-#6336 code (below). |
| — | regression from #6336: fetch failure on an auto-chosen origin |
#6393 | worktree plugin | No. Fetch fallback is separate policy; it now
keys off `source === "origin"`. |
| closed | #5851 project checkout on a fresh clone: `invalid reference:
dev` | #5855 | project-checkout | Yes. The origin-only row. |
| — | diffs against remote-only defaults | #6359 | Git plugin | Yes. The
origin-only row. |
| closed | #7114 Diff tab prefers stale local base | #7425 | Git plugin
(third copy) | Yes. The table fails on the pre-#7425 code (below). |
| unfiled | project-checkout new branch from stale local base | this PR
| project-checkout | Fixed here, reproduced live. |
| unfiled | diff cache misses `origin/<base>` moves | this PR |
host-workspace watch set | Fixed here. |
| open | #3955 worktrees provisioned from stale refs | partly
#6336/#6393 | — | Only the provisioning half. The long-lived-turn drift
half is a separate feature, so this PR does not close it. |
| closed | #5373 marketplace add for a non-default branch | #5375 |
marketplace clone | No. That is a server-owned clone with its own
fallback, deliberately left separate. |

Copies deleted:
- the server's `resolveDefaultWorktreeBaseBranch` and its test
- the worktree plugin's `resolveDefaultWorktreeBaseBranch` and its
named-base `hasRef` logic (#6336)
- the Git plugin's `merge-base --is-ancestor` copy (#7425)
- project-checkout's local-wins new-branch base (#5855's fallback)
- `readBranchRelation` and `revParseRef`

## Decisions for review

1. **Project-checkout new branches start from `origin/<base>` when the
local base is equal or behind.** You will see:
- New branches include upstream commits that your local `main` has not
pulled yet.
- In the common equal case, the recorded merge base and Git panel base
now read `origin/main` instead of `main`. The commit is the same.

This is what new worktrees already do. Local commits are still kept when
the local branch is ahead or has diverged. The provider does not fetch
first, so "origin" means the last fetched ref, as before.
2. **Daemon resolves, server passes through.** This needed the protocol
bump instead of keeping a shared pure function on both sides of the
server/daemon line. It means the server's displayed default base is
computed by the same code that creates the worktree.

## How you verified

- **Guard on main before the fix** (the same table, production code
untouched):
- project-checkout: `local equals origin` and `local behind origin`
failed (`mergeBaseBranch: "release"`, HEAD at the stale local commit).
- host-workspace watch set: `origin only`, `local equals origin` and
`local behind origin` failed (the fingerprint did not change when
`origin/release` moved).
- worktree and Git plugin: all passed, since their bugs were already
fixed.
- **Guard against the historical bugs:** I temporarily restored the old
logic.
- Pre-#6336 worktree named base (always as-given): `origin only`, `local
equals origin` and `local behind origin` failed.
  - Pre-#7425 Git plugin (local first): `local behind origin` failed.
- **After the fix:** every table row passes at every caller (resolver
14, worktree 14, Git plugin 9, project-checkout 20, host-workspace 8,
daemon inspect 26 including 5 table rows).
- `node scripts/check-branch-ref-owner.mjs` passes, and the fixture
tests pass with it (5).
- Existing suites pass: `workspace-git.test.ts`, `host.test.ts`
(worktree, 63), `workspace-reads.test.ts`, `git.test.ts`,
`host-workspace.test.ts`, `contract.test.ts`, and the server tests for
workspace routing, named base branch, project default and thread default
policy.
- `pnpm exec turbo run typecheck` passes on the affected packages, and
oxlint passes on the changed files.
- **Live, on a source dev instance with an isolated data dir:** I
spawned the same project-checkout thread on a fresh clone with `main`
behind `origin/main`.
  - Before (main): branch at `d167c6c` (stale), `mergeBaseBranch: main`.
- After: branch at `bd9d253` (`origin/main`), `mergeBaseBranch:
origin/main`, and `GET /projects/:id/branches` returns
`defaultWorktreeBaseBranch: "origin/main"` from the daemon.

> 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.

spawn --base-branch <name> resolves the stale local ref; only remote-prefixed names are fetched

1 participant