Skip to content

Resolve a named default base branch against origin when spawning - #2152

Merged
SawyerHood merged 1 commit into
mainfrom
bb/fix-1770-base-branch-remote
Aug 21, 2026
Merged

SawyerHood merged 1 commit into
mainfrom
bb/fix-1770-base-branch-remote

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

What was wrong

bb thread spawn --new-environment worktree --base-branch main sent the plain name main straight through the server to the host daemon. The server's local-vs-origin resolution (resolveManagedDefaultBaseBranchForCreate) returned early for any { kind: "named" } spec, and the daemon's createWorktree only fetches remote-qualified bases (origin/main) before git worktree add. Git resolved the bare main to the local refs/heads/main, so a project checkout that had not been pulled seeded every spawned worktree from the stale commit, with no fetch and no warning. Omitting the flag or passing origin/main was already fresh; the plain name was the one input that got neither treatment.

Issue: #1770. Report: https://get-bb.github.io/reports/issues/1770.html

What changed

  • apps/server/src/services/projects/worktree-base-branch.ts: new resolveManagedNamedBaseBranchSpec. When the named branch is the checkout's default branch, it applies the same policy the default spec uses: origin/<default> when local is equal or behind, the local branch when it is ahead, diverged, or unknown. Any other plain name is returned unchanged.
  • apps/server/src/services/threads/thread-create.ts: resolveManagedDefaultBaseBranchForCreate is now resolveManagedBaseBranchForCreate. It calls host.list_branches for named specs too (that RPC already runs a throttled git fetch --all --prune on the daemon) and routes the result through the named or default resolver. A fork (originKind !== null) keeps its source environment's branch verbatim and makes no RPC, since it continues the conversation from the branch the source is on.
  • The resolved spec is stored on the environment as before, so bb thread show now reports baseBranch: "origin/main" for a spawn that was redirected, and the provisioning transcript shows the Fetching origin/main step.
  • Docs: docs/worktrees.md and the --base-branch help text in apps/cli/src/commands/thread/spawn.ts now say what a plain name resolves to.
  • Test helper: registerTestHostRpcCapture accepts an optional listBranchesResult so a route test can set the default-branch relation without swapping the capture socket.

No wire change: host.list_branches and environment.provision are unchanged, so no HOST_DAEMON_PROTOCOL_VERSION bump. This is server-only policy, per the server/daemon split.

Deviation from the report's proposals: I did not add upstream tracking for arbitrary non-default names. The daemon only reports the relation for the default branch; doing it for any branch needs a new result field (protocol bump) or daemon-side policy. The reported case (--base-branch main) and its master/develop-as-default equivalents are fixed; other plain names keep today's local-only behaviour and the docs now say so.

How you verified

New tests:

  • apps/server/test/public/public-threads.named-base-branch.test.ts (route level, real in-memory DB, fake daemon): named main with local-behind -> provision baseBranch is origin/main; named main with local-ahead -> main; named release/2026-05 -> unchanged; an isolated fork from an environment on main with local-behind -> still main.
  • apps/server/test/services/worktree-base-branch.test.ts: unit cases for resolveManagedNamedBaseBranchSpec (equal/behind -> origin; ahead/diverged/unknown/no-origin -> local; non-default names untouched).

Fail before / pass after (checked out origin/main versions of the two source files, ran the route test):

× bases on origin when the named default branch is behind origin
AssertionError: expected 'main' to be 'origin/main' // Object.is equality
Tests  1 failed | 3 passed (4)

With the fix: Tests 11 passed (11) across both files.

Turbo, from the committed tree (git status --porcelain empty, after rebase on origin/main):

pnpm exec turbo run typecheck test --filter=@bb/server --filter=@bb/cli
@bb/cli:test:     Tests  453 passed (453)
@bb/server:test:  Tests  1830 passed (1830)
Tasks:    10 successful, 10 total

Manual repro on my own dev instance (this branch): bare origin at commit B, project checkout at commit A (1 behind, origin/main ref stale), bb thread spawn --project ... --new-environment worktree --base-branch main --provider codex --prompt "Reply only with ok.". Result: worktree HEAD = B (f412fb6 B: pushed by someone else), remote.txt present, bb thread show reports "baseBranch": "origin/main", and the provisioning transcript contains Fetching origin/main / Fetched origin/main. On origin/main code the report shows the same setup landing on A with no fetch step.

Fixes #1770

AGENT GENERATED: by Claude Opus 5

Independent verification

Verified by a separate agent in its own worktree (verify-1770-r1 at 11fc8fe, origin/main is an ancestor; PR is mergeable).

Commands run:

  • pnpm install --frozen-lockfile --prefer-offline && pnpm exec turbo run build (18/18 tasks).
  • Fail-before: git checkout origin/main -- apps/server/src/services/projects/worktree-base-branch.ts apps/server/src/services/threads/thread-create.ts, then pnpm exec vitest run test/public/public-threads.named-base-branch.test.ts in apps/server: × bases on origin when the named default branch is behind origin — AssertionError: expected 'main' to be 'origin/main' (1 failed | 3 passed).
  • Pass-after: restored the PR files and ran test/public/public-threads.named-base-branch.test.ts + test/services/worktree-base-branch.test.ts: 2 files, 11/11 passed.
  • umask 022 && pnpm exec turbo run typecheck test --filter=@bb/server --filter=@bb/cli: Tasks: 10 successful, 10 total (server 196 test files passed, cli 48 test files passed).
  • CI on 11fc8fe: 11 checks pass, 2 skipped, none failing.

Repro on the fixed branch (own dev instance, ports 16163/24163/32163, bare remote + checkout one commit behind):

  • bb thread spawn --new-environment worktree --base-branch main --provider codex --prompt "Reply only with ok." -> thread show reports baseBranch: "origin/main", worktree HEAD is the remote tip (a549651 B: pushed by someone else), remote.txt present, checkout's origin/main refreshed, provisioning transcript shows Fetching origin/main / Fetched origin/main. On origin/main (per the report) the same spawn lands on the stale local commit with no fetch step. No longer reproduces.
  • Guard case: after making local main one commit ahead of origin, the same spawn keeps baseBranch: "main" and the worktree contains the local-only commit (C: local only).

Review notes: server-only policy change; no host-protocol shapes changed, so no HOST_DAEMON_PROTOCOL_VERSION bump is needed. Forks (originKind !== null) skip the resolution and keep the source branch verbatim (covered by a test).

Residual risks (minor, non-blocking):

  • A plain non-default name (--base-branch develop) still resolves to the local branch without a fetch; documented in docs/worktrees.md.
  • resolveDefaultThreadEnvironment (thread-default-policy) pins a named base from its own host.list_branches call, then createThreadFromRequest now calls host.list_branches a second time for that named spec. The result is identical and the daemon throttles the fetch, so this is one extra cheap RPC.
  • packages/templates/src/templates/bb-guide-threads.md and the bb-cli skill still describe --base-branch as "Base branch for a new managed worktree"; still accurate, just terser than the new --help text.

AGENT GENERATED: by Claude Opus 5

Rebase

Rebased onto origin/main at 75d6fc4d4 (was 33 commits behind, based on f6fb434ab) and squashed the two commits into one (94d0324e8); the resulting tree is identical to the pre-squash rebased tree. No conflicts: none of the 33 commits on main touched the seven files in this PR. The only nearby change on main was #2158 (bare repositories as worktree sources), which changes detectGitRepo in packages/host-workspace; it does not alter host.list_branches result shapes or the server-side base-branch resolution this PR adds, so the fix applies unchanged.

Re-verified on the new base:

  • Fail-before: with worktree-base-branch.ts and thread-create.ts checked out from origin/main, the two new test files give Tests 4 failed | 7 passed (11) (AssertionError: expected 'main' to be 'origin/main'). Restored: Tests 11 passed (11).
  • From the committed tree (git status --porcelain empty), umask 022, --force:
    • turbo run typecheck test --filter=@bb/server: Tests 1904 passed (1904), Tasks: 8 successful, 8 total
    • turbo run typecheck test --filter=@bb/cli --filter=@bb/host-daemon: cli 453 passed (453), host-daemon 555 passed (555), Tasks: 10 successful, 10 total
    • turbo run typecheck test --filter=@bb/integration-tests: 55 passed (55), Tasks: 8 successful, 8 total

AGENT GENERATED: by Claude Opus 5

Independent verification (post-rebase)

Re-verified by a separate agent after the rebase, in its own worktree (verify-2152-rb at 94d0324e8, merge base 75d6fc4d4; git merge-tree against the current origin/main 27d1017fe is conflict-free, and none of the commits on main since the rebase touch the PR's files or the host.list_branches / createWorktree paths).

Commands run:

  • pnpm install --frozen-lockfile --prefer-offline && pnpm exec turbo run build (18/18 tasks).
  • Fail-before: git checkout 75d6fc4d4 -- apps/server/src/services/projects/worktree-base-branch.ts apps/server/src/services/threads/thread-create.ts, then pnpm exec vitest run test/public/public-threads.named-base-branch.test.ts test/services/worktree-base-branch.test.ts in apps/server: Tests 4 failed | 7 passed (11); the route test fails with AssertionError: expected 'main' to be 'origin/main' (the other three fail because resolveManagedNamedBaseBranchSpec does not exist on main).
  • Pass-after: restored the PR files (git status --porcelain empty): Tests 11 passed (11).
  • umask 022 && pnpm exec turbo run typecheck test --filter=@bb/server --filter=@bb/cli --force --concurrency=1: cli Tests 453 passed (453); server Tests 1904 passed (1904), Tasks: 8 successful, 8 total on the clean re-run. (A first server run had one unrelated failure, test/services/plugins/plugin-update.test.ts, from disk quota exceeded on this machine's shared /tmp tmpfs at 98% inodes; it passes with TMPDIR elsewhere and on the re-run.)
  • CI on 94d0324e8: all 10 required checks pass, 2 skipped, none failing.

Repro on the fixed branch (own dev instance, ports 18795/26795/34795, bare remote + checkout one commit behind):

  • bb thread spawn --project ... --new-environment worktree --base-branch main --provider codex --prompt "Reply only with ok." -> thread show reports baseBranch: "origin/main", worktree HEAD is the remote tip (f0ac52f B: pushed by someone else), remote.txt present, the checkout's origin/main was refreshed, and the thread events contain Fetching origin/main / Fetched origin/main. No longer reproduces.
  • Guard case: after making local main one commit ahead (afef38b C: local only), the same spawn keeps baseBranch: "main" and the worktree contains local.txt.

Residual risks: unchanged from the earlier verification section (non-default plain names still resolve locally, documented; one extra cheap host.list_branches RPC when the default policy already pinned a named base).

AGENT GENERATED: by Claude Opus 5

@SawyerHood
SawyerHood marked this pull request as ready for review August 21, 2026 05:40
`bb thread spawn --base-branch main` sent the plain name straight to the
host daemon, which only fetches remote-qualified bases before
`git worktree add`, so a checkout whose local main was behind origin
seeded every new worktree from the stale commit with no warning. The
default spec already asked the daemon for the checkout's local-vs-origin
relation and preferred origin when local was equal or behind; a plain
name that is the checkout's default branch now gets the same policy.
Names that are not the default branch are passed through unchanged, and
a fork keeps the branch its source environment is on. The docs and the
`--base-branch` help text say what a plain name resolves to.

Fixes #1770

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/fix-1770-base-branch-remote branch from 11fc8fe to 94d0324 Compare August 21, 2026 16:57
@SawyerHood
SawyerHood merged commit 52083aa into main Aug 21, 2026
13 checks passed
@SawyerHood
SawyerHood deleted the bb/fix-1770-base-branch-remote branch August 21, 2026 21:55
ymichael added a commit that referenced this pull request Aug 24, 2026
## What was wrong

The new-thread composer kept the submitted draft visible until thread
creation completed. At the same time, #2152 made the server inspect
every named worktree base before provisioning. The root composer already
submits its smart default as an authoritative remote-qualified name such
as `origin/main`, so that path incurred a redundant `host.list_branches`
RPC even though provisioning fetches the exact remote branch. The added
creation latency made the delayed prompt clear especially noticeable.

## What changed

- Clear the matching submitted draft before awaiting thread creation. If
creation fails, restore it only when the optimistic clear succeeded and
the user has not started a newer draft.
- Treat `origin/...` managed-worktree bases as authoritative and pass
them directly to provisioning, while preserving the existing inspection
and local-vs-origin policy for defaults and plain names such as `main`.
- Preserve the smart named-default behavior introduced by #153.
- No wire, CLI, guide, or documentation changes;
`HOST_DAEMON_PROTOCOL_VERSION` remains 164.

## How you verified

- Added app regression coverage for clearing while submission is
pending, restoring after failure, and preserving a newer draft after
failure.
- Added route-level server coverage proving `origin/main` reaches
provisioning without a `host.list_branches` RPC.
- `pnpm exec turbo run test --filter=@bb/app --
src/components/plugin/PluginNewThreadComposer.test.tsx
src/views/root-compose-thread-environment.test.ts` — 28 tests passed.
- `pnpm exec turbo run test --filter=@bb/server --
test/public/public-threads.named-base-branch.test.ts` — 5 tests passed.
- `pnpm exec turbo run typecheck --filter=@bb/app --filter=@bb/server` —
5 tasks passed.
- `pnpm exec turbo run lint --filter=@bb/app --filter=@bb/server` — 0
errors.
- `pnpm exec oxfmt --check` on all five changed files.

Fixes the performance regression introduced by #2152.

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

--base-branch resolves against the stale local ref, so spawned worktrees silently start behind

1 participant