Repository navigation
Keep warm worktrees ready and hand them to new threads - #7869
Merged
Merged
Conversation
ymichael
force-pushed
the
bb/environment-provider-api-v2
branch
5 times, most recently
from
November 20, 2026 20:01
ef9bb4d to
1332c5b
Compare
ymichael
force-pushed
the
bb/environment-pool
branch
2 times, most recently
from
November 20, 2026 23:47
30c999a to
2ee5a58
Compare
ymichael
added a commit
that referenced
this pull request
Nov 21, 2026
## Human comments ## What was wrong Two tests added in #7911, "fetches only the resolved commit instead of the whole repository" and "falls back to a full clone when the server refuses to serve the commit directly", sit in the same `describe.concurrent` block of `apps/server/test/services/plugins/plugin-install.test.ts`. Each one configures git by writing `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` into `process.env`, then restores the old values. The plugin service has no other way to receive git config: `runInstallCommand` spawns git with `process.env`. When both tests overlap, the shallow test overwrites `GIT_CONFIG_KEY_0` (`protocol.version` becomes `url.….insteadOf`) or its restore deletes the variables. The fallback test's probe `git fetch --depth 1 <repo> <sha>` then runs over protocol v2, which serves any commit, so it succeeds. That produces the CI failure `AssertionError: promise resolved "{ stdout: '', …(1) }" instead of rejecting` seen on #7893 and #7869. ## What changed - The two tests move into their own non-concurrent `describe.skipIf(!hasGit)("git sources configured through the server process environment")`, placed between the two concurrent suites. Vitest runs a non-concurrent sibling as its own group, after the preceding concurrent group finishes and before the next one starts (`partitionSuiteChildren` in `@vitest/runner`). So nothing else in the file runs while `process.env` holds their git config. Moving them out of "git sources" is required: `describe.concurrent` makes the suite itself concurrent, so "git sources" and "multi-plugin repositories" run in parallel, and `test.sequential` inside "git sources" would still overlap the other suite. - The probe git commands (`git clone` and `git fetch`) get their config through the child `env` option (`gitConfigEnv`) instead of `process.env`. `withProcessGitConfig` now wraps only the `service.install` call, which has no other config channel. - Nothing else in the file mutates `process.env` inside a concurrent block. The npm-config tests sit in sequential describes, and the file already gets an isolated worker because it mutates `process.env`. Test-only change; production code is untouched. ## How you verified - Reproduced on main by running only the two tests, so they always overlap: `vitest run test/services/plugins/plugin-install.test.ts -t "fetches only the resolved commit|falls back to a full clone"` failed **15/15** runs with the exact CI error (the fetch printed `* branch <sha> -> FETCH_HEAD`). - Same command with this change: **20/20** passed. - Full file, 8 consecutive runs: 8/8 passed (64/64 tests each). - `pnpm exec turbo run typecheck --filter=@bb/server` and `pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-install.test.ts` both passed. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/environment-pool
branch
3 times, most recently
from
November 21, 2026 04:52
c5265a8 to
881af45
Compare
This was referenced Nov 21, 2026
Closed
Builds the Worktree plugin's warm pool on environments before threads. Environments can now be held by a plugin (hold: "plugin"): threads cannot join them, and a version-2 provider of that plugin hands one to a new thread with ctx.adopt(environmentId), which in one transaction clears the hold and moves the thread's reservation onto it, so setup does not run again. A refused adopt changes nothing. The pool keeps up to four members per checkout at the default base on an unused placeholder branch. A default-base create reserves the oldest member, waits for the thread's branch name, renames the placeholder under the git ref lock after checking the member is still at the fetched base, then adopts it; when core refuses the adoption the branch is renamed back and the next member or a cold worktree is used. bb worktree pool status|set, settings UI, skill and docs. Plugin SDK 0.6.167. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s to the caller A create that fails after adopt() moves the adopted environment through provisioning to error and fails its thread, instead of starting the thread with create_pending left set. A create still running after adopt keeps the thread from starting. adopt(environmentId, resource) records the resource in the same swap, so a restart before create returns finishes from what adopt recorded (the startup sweep now visits create_pending rows), and removal deletes the renamed branch. Inside a plugin, environments.experimental_create with hold "plugin" always holds for the calling plugin. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lds of disabled plugins A warm worktree was handed out while it matched the last fetched default base, so a thread spawned right after an upstream push started on older code than a fresh worktree would. The handoff now reads the remote's base with git ls-remote while the title is generated and refuses a member that is not at it; when the remote cannot be reached it falls back to the last fetched base, as a fresh worktree's fetch does, and says so. Steps a provider reported after adopt went to the destroyed reservation, so the adopted environment kept "Preparing Worktree…" and the thread's log never said a warm worktree was used. The reporter now follows the adopted row, adopt drops the held environment's unflushed threadless log, and the Worktree plugin reports "Using a warm worktree at <base> (<commit>)". Plugin holds outlived their plugin: disabling or uninstalling it left its environments held forever. Core now releases a plugin's holds on the same unregister signal that clears its queue waits, and they retire normally. Co-Authored-By: Claude Opus 5.5 <[email protected]>
check:query-costs requires a case for every exported query function in packages/db/src/data. adoptHeldEnvironment and releaseEnvironmentHolds had none, which failed the "Query costs on long threads and long turns" job. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ing them A warm worktree was handed out only while it sat at the remote's current default base, so every upstream commit invalidated the whole pool and most thread starts on a busy repo went cold. Now the handoff accepts a member whose HEAD is an ancestor of the remote base, fetching the base first when its commit is missing locally. After adopt, the provider fast-forwards the checkout and calls setup(path); core runs setup again after create returns and before the thread starts. Reconcile only discards members that are no longer on the base (a rewritten default branch). Core: setup(path) after adopt, at the adopted path, runs setup after create returns. A restart between adopt and create returning now also runs setup again, because the provider may have moved the checkout before it could ask. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ndovers A warm handoff waited for the thread's title before adopting the worktree, so a worktree that had to be moved forward ran setup after the title instead of alongside it, as a fresh worktree does. The pool now checks a member, adopts it on its placeholder branch, fast-forwards it and starts setup at once, and renames the branch when the title settles, in the same order as a fresh create. Core keeps the plugin's hold until create returns, so a handover in progress is recognizable: other threads still cannot join it, setup after adopt starts immediately, a stopped thread discards it like any pending create, and a restart before create returns discards it and provisions the thread again instead of finishing from a stale record. A plugin's holds are released on disable only for environments no thread is taking. The Worktree host writes the new branch name to the worktree's completion file before renaming, and removal deletes that branch as well as the recorded one, so a restart after the rename leaves no branch behind. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…guard Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… lines A refill returned as soon as core accepted the create, so the pool only noticed the member was ready at the next 2-minute reconcile: settings kept showing "preparing", and a pool of 2 or more started each further member a tick later. The pool now watches the new member until its setup settles, then reconciles at once, and announces the refill when it starts. Status lines in settings wrap instead of truncating. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A pool's last error stayed until the server restarted, even after later checks succeeded, and showed raw git and filesystem errors. The host now reports a missing project folder as its own result; the pool words each problem as a sentence that says what it will do next, logs the raw error, and clears the problem when a later check succeeds outside a retry backoff. Settings and `bb worktree pool status` show the problem on its own line, say "being set up" instead of "preparing", and name the machine only when a project has checkouts on more than one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changing a pool's size waited for a full reconcile before replying, and a reconcile fetches the default base of every project with a pool, one after another. On a machine whose bb project fetches from GitHub that held the settings dropdown disabled for about 1.5 s (longer when a reconcile was already running, since the change then waited for a second pass). The size is now saved and the reconcile started in the background; settings refresh from the pool's change signal as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/environment-pool
branch
from
November 23, 2026 17:48
ef18b40 to
3c9bf64
Compare
ymichael
added a commit
that referenced
this pull request
Nov 23, 2026
#8049) ## Human comments ## What was wrong Warm worktrees (#7869) are configured on the Worktree plugin's settings page, but nothing in the new-thread flow points there. A user picking a base branch can't tell whether warm worktrees exist for the project, or where to turn them on. ## What changed Only `plugins/environment-git-worktree` changes; no SDK, wire, or core changes. - `app.tsx`: - While the branch picker is open, it calls the existing `warmPoolStatus` RPC and refreshes on `warm-pools-changed`. - The Default branch row shows a pill with the number of ready warm worktrees on the chosen machine, for example "2 warm". The pill is hidden while the project's pool is off, when none are ready, or when the status call fails. - A "Worktree settings" row (settings icon) at the bottom of the picker opens the plugin's settings page through `navigate.experimental_toSettings()`, the path core uses for settings. It is a regular picker row, so arrow keys reach it. - `README.md`: one sentence on the hint. ## How you verified - New tests in `app.test.tsx`: - The count includes only the chosen machine. - The pill is hidden while the pool is off, even with ready members. - The count updates on the realtime signal while the picker is open. - The picker is unchanged when the status call fails. - The settings row calls `experimental_toSettings()` and closes the picker without changing the inputs. - `pnpm exec turbo run typecheck test --filter=bb-plugin-environment-git-worktree`: 196 tests passed. - Manual check on `pnpm start:worktree` with a 2-member pool: - The picker showed "2 warm" on Default branch. - Worktree settings opened `/settings/plugins/environment-git-worktree` with the Warm worktrees section. - A project with the pool off showed no pill. > 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 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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
A new worktree thread on this repo waits ~24–33 s before its first turn, for
git fetch,git worktree add,.worktreeincludeand.bb-env-setup.sh(mostlypnpm install). #7863 lets environments exist before threads and lets a provider call core's steps, but nothing yet prepares a worktree ahead of time and hands it to a thread.Builds on #7863, now merged. Size: 42 files, +3633 / −75.
What changed
Core: plugin holds and
ctx.adopthold: "plugin"onbb.sdk.environments.experimental_create. Inside a plugin it always means the calling plugin; the plugin-facing type has nopluginId.409 environment_held.ctx.adopt(environmentId, resource)on version-2 create contexts. It hands an environment that the calling plugin holds (ready, same project and machine) to the thread being created: in one transaction it moves the thread's reservation onto that environment and records the resource the provider passes. A refused adopt changes nothing.ctx.setup(path)afteradopt; setup runs again on the adopted environment before the thread starts. Without that call, setup does not run again.adopt(wrong path returned, abort, bad result) fails the thread without starting it: the adopted environment goes toerror, the hold andcreate_pendingare cleared, and normal retirement removes it.adoptand create returning, or a stop of the thread in that window, discards the adopted environment and resets the thread's provisioning to ask its provider for a new one. The thread then gets another warm worktree or a cold one. Before, the restart sweep finished the create from whatadopthad recorded, which could start a thread before its fast-forward or setup had run.adoptland on the adopted environment and the thread's provisioning log.adoptdrops the held environment's unflushed log from before the thread existed.Worktree plugin: the warm pool
bb worktree pool status|set, a settings section and theworktreeskill. Changing a size saves it and replies at once; the reconcile it starts runs in the background, and settings refresh from the pool's change signal.experimental_create({ hold: "plugin" })at the default base, unnamed, so the member sits on placeholder branch<prefix><envId>. Core runs creation and setup durably. One refill at a time per machine, debounced (5 s after start, 10 s after a handoff, then every 2 min), with a 10-minute backoff after a failure. After a refill, the pool checks the new member every 2 s until its setup settles, then reconciles at once, so settings show it as ready and the next refill starts without waiting for the 2-minute tick.git ls-remote, and fetch that commit if it is not local yet.ctx.adopt(member), recording the placeholder as the owned branch.git merge --ff-onlyto the remote commit, thenctx.setup(path)again. Both run while the title is still being generated.branchName(). Under the git ref lock, write the name to the worktree's completion file, then rename the placeholder to it.If the remote can't be reached, the check uses the last fetched base, as a cold create's fetch fallback does, and the log says the worktree may be out of date. If the base can't be read at all, the member is kept and the thread gets a cold worktree. A refused adopt tries the next member, or a cold worktree; nothing on disk changed yet.
bb worktree pool statusshow, per checkout, how many warm worktrees are ready or being set up, and any problem as a plain sentence on its own line: a missing project folder (reported by the host as its own result), a failed check for updates, a failed setup, or a failed create, each saying when it retries. The raw error goes to the plugin log. A problem clears once a later check succeeds outside a retry backoff.bb.sdk.environments.listnow takes a page size (Require a page size in the SDK's list calls and page through lists in core #7932); the pool pages through its members 500 at a time.scripts/check-branch-ref-owner.mjsallowlistshost/handoff.ts: itsmerge-base --is-ancestorcompares a member's commit with the remote base commit and chooses no branch.Versions: plugin SDK 0.6.179 (one above main's 0.6.178). No migration: the PR uses the
held_byandcreate_pendingcolumns from #7863's 0161.HOST_DAEMON_PROTOCOL_VERSIONis unchanged: the new host calls (checkPoolMember,fastForward,nameHandedOffBranch,refreshPoolBase) belong to the Worktree plugin's own host contract, which ships with the plugin.Docs:
docs/worktrees.md(warm worktrees),docs/configuration.md,docs/api_to_audit.md(plugin holds,adopt), the bb-guide environments template,backend-machines.md, the Plugin SDKadoptcomment, the Plugin Guide surface, the plugin README and theworktreeskill.What a warm hit waits for
T is the title, F is fetching and creating the worktree, S is setup.
The first version of this PR replaced members whenever the default base moved. On this repo
mainmoves 22.5 times a day (median gap 5.6 min), so a replay of 517 real thread starts gave hit rates of 41–63%. Members that are behind are now moved forward instead, so the remaining misses are an empty pool (bursts of threads faster than one-at-a-time refills), a rewritten base, or a busy git lock. I have not re-run the replay with this rule. A miss falls back to the cold path, so it is never slower than without a pool, and the handoff checks the remote, so a thread never starts on older code than a cold create would.How you verified
Rebased onto main at a71ea2a. The live runs below used this handoff code on an earlier base (before #7932, #7957, #7944, #7960 and #7961), on a
pnpm start:worktreeserver with a tiny local repo, a bare remote, a pushing clone, pool size 1, and an idempotent.bb-env-setup.shthat takes 15 s whendeps.txtchanges and returns at once otherwise. Times are from thread creation.deps.txtalonedeps.txtturn/started+16.5 s for a 15 s setupkill -9of the server 0.6 s after spawn (adopted, setup running, branch still the placeholder)turn/started+27.6 s including ~12 s of restart; no leftover brancheskill -9after the rename, before create returned (thr_2skjwjn82w; a temporary, uncommitted 20 s pause after the rename held the window open)bb/rename-crash-test-thr_2skjwjn82wwith that name in its completion file, while the database still recorded the placeholder; after the restart the member was destroyed and its directory and both branches deleted (the thread's branch reflog starts fresh at the new create); the thread got a cold worktree and finished its turn at +31.1 sbb worktree pool statusshow "The project folder … is missing or is not a git repository." (clearing after a later successful check is covered bywarm-pools.test.ts)bb worktree pool setwith 4 projects keeping pools, one fetching from GitHubpool status(was ~2.1 s while it waited for every pool to fetch its remote); a shrink from 2 to 1 and back still deleted and refilled a member in the backgroundTests
apps/server/test/environments/environment-holds.test.ts:adopthands its plugin's held environment to the thread, and another plugin's hold is kept;plugins/environment-git-worktree/host.test.ts(real git):plugins/environment-git-worktree/warm-pools.test.ts:...[origin/main](167/167 tasks). turbo test pluscheck:query-costsover the 12 changed packages (23/23 tasks):@bb/server4438 passed, 3 skipped; Worktree 191;@bb/db756;@bb/cli1412 passed, 1 skipped;@get-bb/plugin-sdk445. Plugin SDK version guard passes.