Skip to content

Let worktree threads branch the project's other git repositories, set them up and keep them warm - #8065

Merged
ymichael merged 19 commits into
mainfrom
bb/worktree-provider-branch-extra-project-repos-via-thr_st62g7p24h
Nov 24, 2026
Merged

ymichael merged 19 commits into
mainfrom
bb/worktree-provider-branch-extra-project-repos-via-thr_st62g7p24h

Conversation

@ymichael

@ymichael ymichael commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

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 Delete the branch a removed worktree created when nothing would be lost #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 Per-machine warm worktree counts, on a shared settings list #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

@ymichael
ymichael force-pushed the bb/worktree-provider-branch-extra-project-repos-via-thr_st62g7p24h branch from ab4263d to 23905ad Compare November 24, 2026 05:58
ymichael added a commit that referenced this pull request Nov 24, 2026
…er (#8094)

## Human comments

## What was wrong

#7869 lets a plugin hold environments (`hold: "plugin"`) and hand one to
a new thread with `ctx.adopt`. Nothing showed that the folders a
provider records with an environment (`additionalPaths`) survive that
hand-off, or a later restore. The Plugin Guide did not explain how a
custom provider keeps its own prebuilt environments.

## What changed

No core change: the engine already handles these cases. This PR adds the
tests that prove it, and the docs.

**Tests** (`apps/server/test/environments/environment-holds.test.ts`).
The test provider now has a `restore` and can return `additionalPaths`.
New cases:
- A held environment keeps the folders it was created with when a
thread's create adopts it and omits `additionalPaths`. The environment
response shows them.
- A create that returns `additionalPaths` after `adopt` replaces them.
- A restore of an adopted environment receives its folders in
`previous.environment.additionalPaths`, and the rebuilt environment
records the folders restore returns.
- A restore that adopts another held environment keeps that
environment's folders.

**Docs.**
- `bb-plugin-authoring/references/backend-machines.md`: a new section,
"Keeping prebuilt environments for your provider". It shows a complete
provider whose environments are an app checkout plus sibling `api` and
`docs` checkouts. It covers building held environments with
`experimental_create({ hold: "plugin" })`, telling them apart in
`create` by `heldBy`, adopting a ready one, refilling, returning the
resource after `adopt` (or `remove()` gets null), and what `restore`
must return.
- Plugin Guide (`plugin-api-docs/src/surfaces.ts`): a reference
paragraph on the Environment providers surface with the same rules.

`replacedProjectFolders` is left to #8065, which has not landed.

## How you verified

**Live.** I ran the docs example as a real plugin (`bb plugin install`
of a local "stack" provider) on a `pnpm start:worktree` server.
- `bb stack warm <project> <host>` built a held environment with `app`,
plus `api` and `docs` as `additionalPaths`.
- A Claude Code thread on the Stack provider adopted it. The hold
cleared, the refill built a new held one, and the agent listed the warm
environment's `api` and `docs` folders as writable.
- Archiving the thread and deleting its environment removed the adopted
stack's directory, so `remove()` received the resource.
- `bb thread restore-environment` rebuilt it with new `api` and `docs`
folders, and the agent listed those after the restore.
- The first run caught two mistakes in my draft example, now fixed:
- With no resource returned after `adopt`, the stack's directory was
never removed.
- Returning `previous.environment.additionalPaths` as-is from `restore`
pointed at the destroyed folders.

**Checks:**
- `environment-holds.test.ts`: 21 passed.
- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`.
- The `bb-plugin-plugin-api-docs`, `bb-plugin-bb-guide` and
`@bb/templates` tests.
- The docs example typechecks against the plugin SDK.

> AGENT GENERATED

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael and others added 12 commits November 24, 2026 12:27
The Worktree environment provider takes a `folders` input: project folders
(bb project folder) that are git repositories get their own worktree next
to the main one, on the thread's branch, returned as additionalPaths. The
create result's new replacedProjectFolders tells the server to drop those
shared folders from the thread's writable folders and instructions;
mergeWorkspaceFolderPaths is the one place that applies it. Removal sweeps
every worktree in the environment's directory and deletes each repository's
bb-owned branch. Plugin SDK 0.6.188.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Restore skips folders that left the project, reports each skip, and
always returns the folder lists so a restore without folder worktrees
clears the recorded ones. Folder worktrees report "Worktree at <path>"
instead of "Using workspace". The picker, validate and create share one
project folder lookup (a project has one checkout per machine). The
picker says extra repositories start from their default branch. Restore
the indent of an unrelated api_to_audit entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
additionalPaths becomes a list of { path, replaces } entries instead of two
parallel lists, so a folder worktree names the shared folder it stands in
for. Migration 0169 turns recorded paths into entries that replace nothing.

Storage retention now treats an environment's folders as part of it: they
count as bb-owned (never offered as external worktrees), their uncommitted
changes keep an interrupted cleanup from being recovered, and their size is
added to the leftover worktree's size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
setup(path, { folders }) records the folders on the environment
(environments.setup_folder_paths). Core runs each folder's setup script once,
in order, before the main one, each as its own hook operation, and runs their
teardown scripts after the main one in reverse. A setup after adopt runs only
in the adopted path. A create fails when it set up a folder it did not
return in additionalPaths. Recovery inspects and acknowledges every folder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tree

A warm pool can also branch some project folders (bb worktree pool folders,
or the settings page). Members are created with those folders and go only to
a thread that branches exactly that set; reconcile replaces members whose
folders differ or whose folder worktree left the placeholder branch or its
default base. Handoff renames the placeholder in every folder worktree.

Cold create and restore pass their new folder worktrees to setup, so each
runs its .bb-env-setup.sh before the main worktree's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A folder's setup runs only once, so a warm member is never fast-forwarded in
a folder: on handoff the host reads each folder's remote default base and a
member whose folder worktree is behind it is deleted and the next member, or
a fresh worktree, is used. Reconcile also replaces members whose folder
worktree is not at its fetched base.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A warm member whose folder worktree is behind its repository's default
branch is no longer discarded. The handoff fast-forwards that folder
worktree and calls setup(path, { folders }) with the moved folders. After
adopt, core accepts folders the adopted environment recorded, forgets their
finished setup records, and runs them again in recorded order before the main
worktree; untouched folders are not set up again. Reconcile replaces only
members whose folder history was rewritten or that left the placeholder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…per-machine pools

Main added 0169 and per-machine warm pool counts (#8112). The branch's
migrations become 0170 (setup_folder_paths) and 0171 (additional path
entries). Pool folders are stored next to the project's and machines'
counts, and the settings list shows the folder choices as nested rows under
a project that keeps warm worktrees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each machine's checkout has its own project folder paths, so a pool's folders
are now stored and set per machine (folders: { hostId: [...] } in the
warm-pools KV entry). setWarmPoolFolders and bb worktree pool folders take the
machine (--host, optional when the project has one checkout) and only accept
that machine's project folders. Status reports each checkout's folders, and
the settings list shows each machine's own folder checkboxes under it,
flagging a chosen folder that is no longer a git project folder there. The
Ladle stories cover every state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/worktree-provider-branch-extra-project-repos-via-thr_st62g7p24h branch from 23905ad to 292e133 Compare November 24, 2026 20:28
@ymichael ymichael changed the title Let worktree threads branch the project's other git repositories Let worktree threads branch the project's other git repositories, set them up and keep them warm Nov 24, 2026
ymichael and others added 7 commits November 24, 2026 12:40
…id the folder lookup promise

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The picker section reads "Folder worktrees:" and the trigger "+N folder(s)".
Settings shows a Folder worktrees sub-header under each machine with one
checkbox row per folder name, and bb worktree pool status prints
"Folder worktrees:".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
BranchPickerRow takes align="first-line" for two-line rows: the leading
icon and the check sit in a box one line tall, so they line up with the
title instead of centring across both lines. Folder paths use TruncateStart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The worktree picker saves the folders a user ticks in localStorage, per
project and machine, and starts the next worktree thread with them when the
composer has no inputs yet. Once the machine's branchable folders load, a
remembered folder that is no longer offered is dropped from the selection
and from storage. The base branch is not remembered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 8ddf983 into main Nov 24, 2026
98 of 99 checks passed
@ymichael
ymichael deleted the bb/worktree-provider-branch-extra-project-repos-via-thr_st62g7p24h branch November 24, 2026 21:58
ymichael added a commit that referenced this pull request Nov 24, 2026
Main (#8065) gave warm worktrees folder worktrees, each read, checked and
fast-forwarded with separate readRemoteBase, checkPoolMember and
fastForward calls. Those calls no longer exist on this branch, so each
folder worktree is now claimed with claimPoolMember too, all at once
once the main worktree's claim succeeds, reusing each folder's remote
base for the next member.

Because a claim can move a checkout, a member whose folder claim is
busy, timed out, or has no readable base is kept only when none of its
worktrees moved; otherwise it is deleted. A folder claim that throws
deletes the member, and so does a refused adopt after any worktree moved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 24, 2026
…der each result is from

Squashed rebase of #8076 onto main after #8065. Extra folders now come
from main's mergeWorkspaceFolderPaths, so a project folder replaced by an
environment folder is searched through its replacement only. Plugin SDK
0.6.199 and host daemon protocol 284 for the host.list_paths rootPaths
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 24, 2026
…de them replaceable

#8065 turned an environment's additionalPaths into { path, replaces } entries that can replace a project folder with the thread's worktree. Repo discovery now passes those entries to mergeWorkspaceFolderPaths, so it lists the same folders as the thread's instructions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 24, 2026
…de them replaceable

#8065 turned an environment's additionalPaths into { path, replaces } entries that can replace a project folder with the thread's worktree. Repo discovery now passes those entries to mergeWorkspaceFolderPaths, so it lists the same folders as the thread's instructions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 24, 2026
…n one host call (#8121)

## Human comments

## What was wrong

Finding #8 of the server→daemon RPC audit. Two separate problems made
creating a project-default worktree thread slow on a remote machine.

First, the create request inspected the project checkout twice, one
after the other. `resolveProjectDefaultThreadEnvironment` called
`host.inspect_git_checkout` to choose the worktree provider. Provider
placement then called `resolveGitCheckoutAvailability`, which sent the
same RPC for the same path again. Its dedupe only covers calls that are
in flight at the same moment, and these two run in sequence.

Second, the worktree plugin's warm-pool handoff made separate plugin
host calls in a row: `readRemoteBase`, then `checkPoolMember`, then
`fastForward` when the member was behind the remote base, then
`nameHandedOffBranch`.

## What changed

- **Server: one checkout inspection per create request.**
`createGitCheckoutInspector(deps)`
(`services/environments/provider-availability.ts`) memoizes
`host.inspect_git_checkout` per (host, path) for one request.
- `thread-create.ts` creates one and passes it to both
`resolveCreateThreadEnvironment` and
`resolveThreadEnvironmentPlacement`. Placement's
`validateProviderSelection` reuses the result through
`gitCheckoutAvailability()`.
- Every other `completeProviderSelection` caller gets a fresh inspector,
so its behavior is unchanged.
  - The TTL-cached machine-availability path keeps its in-flight dedupe.
- **Worktree plugin: one `claimPoolMember` host call** replaces
`readRemoteBase`, `checkPoolMember` and `fastForward`
(`host/handoff.ts`, `contract.ts`, `warm-pools.ts`, `server.ts`).
- The claim reads the remote base. When the server passes the base from
an earlier claim, the claim of the next candidate reuses it instead.
- It then runs the same check under the ref lock, and fast-forwards the
member when it is behind the base.
- The server still owns reservation, discard and adopt policy. It still
reserves one member at a time, so two creates running at once still get
different members.
  - Failure handling, because the claim can now move the checkout:
- A member whose fast-forward fails is refused and discarded. Before,
the create failed after adopt.
- If adopt fails after the claim moved the member, the member is
discarded. Its setup ran against the old commit, so it must not go back
into the pool.
- A claim call that throws (disconnect, abort, or still running after 15
minutes) discards the member, because it may have moved.
- Folder worktrees (from #8065, merged in): once the main worktree's
claim succeeds, each folder worktree is claimed with `claimPoolMember`
too, all at once, reusing each folder's remote base for the next member.
This replaces the separate `readRemoteBase`, `checkPoolMember` and
`fastForward` calls per folder. A member whose folder claim is busy,
timed out or has no readable base is kept only when none of its
worktrees moved; otherwise it is deleted.
- Time limits: reading the base and checking the member get 15 s
together, as before. The server passes that budget as `checkTimeoutMs`
and the host applies it to those steps only. When it runs out the claim
returns `timed-out`, the member is kept and a fresh worktree is built.
The fast-forward is not under that budget: the call gets the create's
15-minute timeout, the limit the fast-forward had before.
- A remote base that can't be read returns `base-unavailable`. The
member is kept and a fresh worktree is built, as before.
- `nameHandedOffBranch` stays a separate call. It needs `branchName()`,
which waits for the thread title to settle.
- **Docs:** `plugins/environment-git-worktree/README.md`,
`docs/worktrees.md`, and the `experimental_` adopt entry in
`docs/api_to_audit.md` now describe the new order.
- **No daemon wire change.** `claimPoolMember` is a plugin host method,
and its code ships to the daemon in the plugin artifact. Core protocol
commands are untouched, so `HOST_DAEMON_PROTOCOL_VERSION` is not bumped.

## How you verified

**Real servers, main vs this branch, same input.**
- Setup: `pnpm start` for main (`40b8939`) and for this branch, each on
its own `/tmp` data dir. Each server had a second enrolled daemon behind
a TCP proxy that adds 100 ms each way (200 ms RTT). The proxy decodes
the daemon WebSocket frames and logs each `host-rpc.request`/`response`.
- The project's only checkout was on that remote machine, with a warm
pool of size 1.
- Each round waited for a ready member, then `POST /api/v1/threads` with
`environment: {type: "project-default"}`, and polled until the
environment was `ready`.
- 8 rounds per case, with main and branch interleaved.
- "Behind base" means a new commit was pushed to the remote just before
the create, so the member had to fast-forward and run setup again.

| 200 ms RTT remote machine | main | branch |
|---|---|---|
| `POST /threads` response, median (min–max) | 470 ms (458–477) | **240
ms** (236–252) |
| host RPCs awaited in the create request | 2 (`inspect_git_checkout`
×2) | **1** |
| environment ready, member at base | 1458 ms (1425–1585) | **1056 ms**
(1018–1170) |
| environment ready, member behind base | 2044 ms (2002–2225) | **1396
ms** (1378–1653) |
| warm-claim host calls before adopt (at base / behind) | 2 / 3 | **1 /
1** |
| all host RPCs from create to ready (at base / behind) | 8 / 9 | **6 /
6** |

Sequences seen in the proxy log. A background `provider.list_models`
refresh is left out because the request doesn't await it.
- main, at base: `inspect_git_checkout > inspect_git_checkout >
readRemoteBase > checkPoolMember > nameHandedOffBranch > …`
- branch, at base: `inspect_git_checkout > claimPoolMember >
nameHandedOffBranch > …`
- main, behind: `… readRemoteBase > checkPoolMember > fastForward >
nameHandedOffBranch > environment.hook.run …`
- branch, behind: `… claimPoolMember > nameHandedOffBranch >
environment.hook.run …`

On the local primary daemon (no proxy, 6 interleaved rounds), the create
response went from a 56 ms to a 38 ms median. Time to ready was
unchanged within noise: 206 vs 206 ms at base, 386 vs 374 ms behind
base.

**Tests**
- `public-threads.project-default.test.ts` now asserts that a branch
checkout is inspected exactly once. It fails on main, which inspects
twice, and passes here.
- `warm-pools.test.ts`:
  - covers the new call order;
- checks that a refused member's claim passes its base on to the next
candidate, so the remote is read once;
- checks that a member the claim moved is discarded when adopt is
refused, and that a member whose claim timed out is discarded.
- `host.test.ts` runs `claimPoolMember` against real git repos: usable,
fetch then fast-forward, refused after a rewritten base, offline
fallback, used placeholder, and busy lock.
- It also checks that a check that runs out of time returns `timed-out`
and leaves the member alone, and that a fast-forward slower than the
check's budget still finishes. That second test fails when the
fast-forward is put back under the check's budget.
- **Folder worktree, real server.** A project with one extra repository
and a warm pool that branches it. After a new commit landed only in that
repository, the thread got the warm worktree, the folder claim moved the
folder from 1b44b75 to 0d4e22c, setup ran again, and both worktrees were
renamed to the thread's branch. The steps shown match main's wording.
- **Slow fast-forward, real server.** A `post-merge` hook that sleeps 20
s stands in for a slow fast-forward in a large repository. Before the
timeout fix, the create waited 15 s, the claim hit its deadline, the
member was discarded and a fresh worktree was built. With it, the thread
got the warm worktree after the 20 s fast-forward ("Moved the warm
worktree from 3eb71f2 to 22a1ba1; setup runs again"), and no member was
discarded.
- Commands:
- `pnpm exec turbo run typecheck lint lint:type-aware
--filter=@bb/server --filter=bb-plugin-environment-git-worktree`
  - `vitest run` for the 5 affected server test files (204 tests)
  - the full worktree plugin suite (222 tests)

> 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 25, 2026
…der each result is from

Squashed rebase of #8076 onto main after #8065. Extra folders now come
from main's mergeWorkspaceFolderPaths, so a project folder replaced by an
environment folder is searched through its replacement only. Plugin SDK
0.6.202 and host daemon protocol 284 for the host.list_paths rootPaths
change.

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