Skip to content

Let environment providers call core's steps, and create environments before threads - #7863

Merged
ymichael merged 6 commits into
mainfrom
bb/environment-provider-api-v2
Nov 20, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/environment-provider-api-v2

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Core drove an environment provider at fixed points (create → core runs setup → first turn) and inferred what happened instead of being told. Two problems came out of that. First, core handed providers values that didn't exist yet: suggestedBranchName comes from the thread title, so core waited for the title before create (#7807 needed a rename hook to avoid it). Second, core decided adoption after the fact: when create returned a path that another environment already had, bindEnvironmentPath silently folded the new reservation into it. Environments also could not exist before a thread.

What changed

Provider contract v2 (packages/plugin-sdk/src/environment-provider.ts, apiVersion: 2). Contexts carry the environment instead of a thread, plus core's steps as calls, in the order the provider needs:

  • branchName() replaces suggestedBranchName. Core starts title generation for every new thread and never waits for it before create; branchName() resolves once the title settles, and at once for an environment without a thread.
  • setup(path) is a durable request. Core claims and binds the path, records it as provider-owned, and applies provision.requested (creating → provisioning). The thread attaches, and the existing attach operation runs setup through runEnvironmentHook (reconnect, cancel and recovery are unchanged). A new column, environments.create_pending, records that create hasn't returned. The attach operation waits for create before inspecting the workspace, so the environment is ready, and the thread starts, only after create returns created with the same path. After a restart with setup finished and create pending, core re-runs create without re-running setup. If create never calls setup, setup runs after create, as before.
  • locate({ host, projectCheckout, inputs }) → { path, reuse } | null replaces experimental_existingPath and post-create path adoption. Core checks path admission and claims the path on the reservation.
    • With reuse: true, the thread joins the environment at that path as it is.
    • Otherwise create runs on a fresh reservation. Core refuses it while another live thread uses that environment, and folds the result into the environment only when create returns the located path.
    • A create that returns another environment's path it did not locate fails with "Workspace … already belongs to environment …".
  • v1 adapter. Version-1 providers keep main's runtime behaviour. The adapter adds thread, sets suggestedBranchName = await branchName() (so v1 still waits for the title), keeps main's experimental_claimPath(path) and projectCheckout.experimental_ownsPath, and reads experimental_existingPath(inputs) as { path, reuse: true }. It also still folds a v1 create into the environment that already has the returned path, with main's refusal of another provider's row. Version 2 stays strict.

Decisions on the experimental members:

  • experimental_claimPath is removed from version 2. With locate(), core knows the path before create and claims it on the reservation. It also runs the "another thread is using this workspace" check whenever create will fold into an existing environment. That was the only reason Project checkout called claimPath, and the post-create bind already claims any produced path. Version 1 keeps it through the adapter.
  • projectCheckout.experimental_ownsPath becomes projectCheckout.ownsPath in version 2. A provider decides ownsPath in its result from whether bb cloned the checkout, and only core knows that. Project checkout is the caller. These are members of contexts that bb.experimental_environments providers receive, so they carry no nested experimental_ prefix.
  • owns { path, branch } from the plan is dropped. Core has no reader once core stops renaming branches, remove() already receives the provider's resource, and a field core ignores would be an accepted-but-ignored field. ownsPath is unchanged. If the pool's handoff later needs core to know the owned branch, that PR adds the field with the handoff as its caller.

Environments before threads and user holds (from #7808, without plugin holds and the pool):

  • New surfaces: bb.sdk.environments.experimental_create({ hold: "user" }), bb environment create, bb environment list --held-by user, and Environment.heldBy / statusMessage.
  • The creation intent lives on the row (environments.held_by plus the existing provider columns). A user-held environment is never retired for having no threads.
  • Version-1 providers, composed providers, and a located path that already has an environment are refused.

Providers.

  • Worktree (v2). Cold create is fetch, worktree add --detach, setup(path), then git switch -C <await branchName()> through a new nameBranch host call. locate answers adopting an existing worktree with reuse: true.
  • Project checkout (v2). locate returns the checkout path with reuse unless a branch is requested. Its in-plugin claim loop and experimental_claimPath calls are gone; it awaits branchName() only for a new branch.
  • Personal workspace is unchanged on v2.

Wire. HOST_DAEMON_PROTOCOL_VERSION stays: no server/daemon command, payload or WebSocket field changes. The Worktree plugin's own host contract gains nameBranch, and create.branchName becomes nullable; that contract ships with the plugin. The plugin SDK goes to 0.6.166.

Migration. 0161_environment_holds_and_create_pending (rebased onto main's 0160_plugin_marketplace_enabled) adds environments.held_by and environments.create_pending.

Docs.

  • docs/api_to_audit.md: the v1 adapter, the steps, locate, these decisions, and user holds.
  • The backend-events.md / backend-machines.md plugin-authoring references.
  • The bb-guide-environments chapter, the CLI command index, and docs/worktrees.md (setup now starts on a detached HEAD).
  • The Plugin Guide surface (plugins/plugin-api-docs/src/surfaces.ts).

Behaviour changes versus main:

  • Title. Core no longer waits for the title before create. Title generation starts for every new thread. The "Generating title" and "Generated title" steps no longer appear in the setup transcript. A title that lands after the turn has started reaches the agent session through the existing rename path.
  • Worktree setup starts while the title is being generated, on a detached HEAD at the base. The branch is created alongside setup and is final before the agent starts.
  • Concurrent Local threads on one checkout no longer each run the provider's create and fold together. The later ones wait, bounded by path-claim settle, on the first reservation's claim, then join its environment. The "Workspace is being prepared by another thread" failure is gone; the bound ends in the usual busy error.
  • Branch switches while another live thread uses the checkout are refused at reservation, with the same message as before.
  • Stopping a starting thread whose environment's create has not returned (after setup()) aborts the create (branchName() rejects on abort), removes the environment, and puts the thread back on its provider request. Before, stopping during setup left the environment ready.
  • Undeclared paths. A version-2 create that returns a path another environment already has fails with "Workspace … already belongs to environment …" unless it located that path, instead of adopting it. The old "owned by the X environment provider" message for a foreign provider's row is replaced by this one.
  • Setup re-runs are unchanged (fresh on every provisioning command), except while create is pending: setup that already finished for the path is not run again.
  • New capability: environments can be created and held before any thread.

How you verified

  • Turbo: pnpm exec turbo run typecheck lint test over every changed package; all pass, including @bb/server (4363 passed, 3 skipped, on main 3a81951). The other packages: @bb/db, @bb/cli, @bb/sdk, @bb/domain, @bb/server-contract, @bb/templates, @bb/test-helpers, @bb/core-ui, @get-bb/plugin-sdk, and the Worktree, Project checkout, Personal workspace, git, github-pr-status, storage-retention, bb-guide and plugin-api-docs plugins.
  • apps/server/test/environments/create-steps.test.ts (new):
    • setup runs once, on the attach operation, while the title is pending;
    • setup reported before create returns leaves the environment provisioning with no thread start;
    • the thread starts only after create returns, on the final branch;
    • a setup failure fails the thread with the script's message;
    • a held environment that requests setup drops its claim (this test fails without the fix);
    • a restart with setup finished re-runs create but not setup, and an unfinished setup is an unknown outcome.
  • apps/server/test/environments/locate.test.ts (new):
    • two Local threads share one row with one create;
    • a branch switch folds into the shared row, which a 5 ms sampler saw stay ready throughout;
    • a failed switch fails only the new thread;
    • an undeclared path errors;
    • a branch switch while another thread works there is refused;
    • a second switch waits behind the first one's claim, then is refused.
  • Review fixes, each with a test that fails on the previous head:
    • a resume whose context can't be built fails the environment instead of looping (the previous head hangs);
    • a throwing locate fails the create;
    • a thread can join a held environment whose setup is running;
    • a failed held create releases its claim;
    • stopping after setup() cancels the create;
    • a v1 provider's concurrent creates on one path fold together;
    • setup() on a located path is refused before binding;
    • the held branchName() waits for the title and keeps its name;
    • a failed Worktree nameBranch removes the worktree and its branch.
  • Lifecycle orderings: all 10 pass with environment-lifecycle-orderings.test.ts's orderings unchanged, except the checkout race. Under locate the 2nd and 3rd threads wait on the first claim instead of running their own create, so that ordering's steps changed and its invariant checks did not.
  • Fixture tests that relied on silent adoption were migrated to declare the path with locate.
  • Tests deleted because they tested a removed mechanism, each with a replacement:
    • Project checkout "ends a blocked path claim", Worktree "refuses a path another environment already claimed", and orchestration "serializes concurrent branchless checkout attaches" / "reserves a checkout before concurrent branch mutations": the plugin-side claim → locate.test.ts's claim and exclusivity tests.
    • path-claim-release "a thread finishing setup waits for another create still preparing its path": the second create no longer exists → "makes threads that locate a path another create still prepares wait, then join its environment".
    • Holds "refuses an exclusive claim while another live thread works in the path" → locate.test.ts.
  • Live (pnpm start:worktree, Codex titles; times in ms from thread creation):
    • Cold untitled worktree on a tiny repo: setup starts at 242, title 1422, branch by 1502, setup ends 3265, ready 3375, turn/started 3946.
    • Project checkout new-branch thread: title 1047, checkout -b by 1131, folded into the existing checkout row (which stayed ready) at 1188, turn/started 1545.
    • v1 fixture built against the published SDK 0.6.157: create receives suggestedBranchName = bb/describe-the-empty-workspace-briefly-<thread> and the generated thread.title.
    • No rename in server or daemon logs.

AGENT GENERATED

ymichael and others added 6 commits November 20, 2026 12:01
…before threads

Core drove a provider at fixed points and inferred what happened: it waited
for the thread title before create because suggestedBranchName needed it,
and adopted any environment whose path create happened to return.

Environment providers gain apiVersion 2. Contexts carry the environment
instead of a thread, and core's steps as calls: branchName() resolves once
the title settles (core starts title generation for every thread and never
waits for it), and setup(path) is a durable request that moves the
environment to provisioning so the existing attach operation runs setup
while create continues. environments.create_pending keeps the environment
from becoming ready, and the thread from starting, until create returns.
locate() answers where an environment lives before create: core claims the
path, reuses the environment there or folds create's result into it, and a
create that returns another environment's undeclared path fails instead of
adopting it. Version 2 drops experimental_claimPath (core claims the located
path) and reads projectCheckout.ownsPath; a version-1 adapter keeps
published providers working, including their experimental_claimPath(path)
and folding a create into the environment that already has its path.
Stopping the only thread of an environment whose create has not returned
aborts the create, removes the environment and puts the thread back on its
provider request.

Environments can be created before threads and held by the user
(bb environment create, sdk.environments.experimental_create, list --held-by).
Worktree names its branch after setup has started on a detached worktree;
Project checkout locates its checkout. Plugin SDK 0.6.166.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A thread whose earlier attempt left a removed reservation skipped locate(),
the path claim and the live-thread check, and reserving again cleared any
claim. A retried branch switch then ran checkout -b under another thread
working in the checkout and folded into its environment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A held environment has no thread, so bb environment show is its only status
surface. statusMessage only kept the provider's last progress step: a failed
setup still said "Using workspace: …", and ready or deleted environments kept
"Created branch …". Record the failure reason on provision.failed, and return
null for ready and destroyed environments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bindEnvironmentPath took the provider's resource, merge base and plugin id
but read only the declared target; the engine writes the other fields from
the create result after binding. Pass the target id alone, and drop a
requestSetup check that the declared-path refusal above it already covers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Plugin authors now type-check only against apiVersion: 2. Version-1
providers built against earlier SDKs still run: their contexts move to
internal PluginEnvironmentProviderV1* types for core's adapter and the tests
that cover it, and registering one reports a plugin problem asking the
author to migrate. Registration problems now accumulate instead of the last
one replacing the others.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/environment-provider-api-v2 branch from ef9bb4d to 1332c5b Compare November 20, 2026 20:01
@ymichael
ymichael merged commit 94678a0 into main Nov 20, 2026
98 of 99 checks passed
@ymichael
ymichael deleted the bb/environment-provider-api-v2 branch November 20, 2026 20:32
ymichael added a commit that referenced this pull request Nov 20, 2026
ymichael added a commit that referenced this pull request Nov 20, 2026
ymichael added a commit that referenced this pull request Nov 21, 2026
ymichael added a commit that referenced this pull request Nov 21, 2026
ymichael added a commit that referenced this pull request Nov 21, 2026
ymichael added a commit that referenced this pull request Nov 23, 2026
ymichael added a commit that referenced this pull request Nov 23, 2026
## 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`, `.worktreeinclude` and
`.bb-env-setup.sh` (mostly `pnpm 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.adopt`**
- `hold: "plugin"` on `bb.sdk.environments.experimental_create`. Inside
a plugin it always means the calling plugin; the plugin-facing type has
no `pluginId`.
- Threads cannot join a plugin-held environment: thread placement and
directory changes refuse with `409 environment_held`.
- Disabling or uninstalling a plugin releases its holds on environments
no thread owns (on the same unregister signal that clears its queue
waits), so they retire like any unused environment once their provider
is available.
- `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.
- The plugin's hold stays until create returns. Then core clears it and
records the resource create returns (for Worktree, the thread's named
branch). While the hold is on, no other thread can join the environment,
and core can tell after a restart that a handover was unfinished.
- A provider may call `ctx.setup(path)` after `adopt`; setup runs again
on the adopted environment before the thread starts. Without that call,
setup does not run again.
- A create that fails after `adopt` (wrong path returned, abort, bad
result) fails the thread without starting it: the adopted environment
goes to `error`, the hold and `create_pending` are cleared, and normal
retirement removes it.
- A restart between `adopt` and 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 what `adopt` had recorded, which could start a
thread before its fast-forward or setup had run.
- Steps the provider reports after `adopt` land on the adopted
environment and the thread's provisioning log. `adopt` drops the held
environment's unflushed log from before the thread existed.

**Worktree plugin: the warm pool**
- Setting: per-project size 0–4, off by default. `bb worktree pool
status|set`, a settings section and the `worktree` skill. 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.
- Refill: `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.
- Handoff, only for a default-base create. It follows a cold create's
order: worktree first, setup next, branch name last, so the title wait
overlaps the rest.
1. Reserve the oldest ready member under a lock scoped to the project
and machine.
2. Read the remote's default base with `git ls-remote`, and fetch that
commit if it is not local yet.
3. Under the git ref lock, check that the member is still on its
placeholder branch and at that commit or behind it. A member that is not
(the base was rewritten, or the checkout was used) is deleted and the
next one is tried.
  4. `ctx.adopt(member)`, recording the placeholder as the owned branch.
5. If the member is behind: `git merge --ff-only` to the remote commit,
then `ctx.setup(path)` again. Both run while the title is still being
generated.
6. Await `branchName()`. Under the git ref lock, write the name to the
worktree's completion file, then rename the placeholder to it.
  7. Return the named branch as the resource.
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.
- Settings and `bb worktree pool status` show, 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.
- Removal deletes the recorded branch and the branch named in the
completion file, so a worktree renamed just before a restart does not
leak its branch.
- Freshness: while a pool exists, each reconcile fetches the default
base and deletes members that are no longer on it (base rewritten),
failed, older than 8 h, or over the size. Members that are only behind
are kept and moved forward at handoff. Turning a pool off deletes its
members.
- `bb.sdk.environments.list` now takes a page size (#7932); the pool
pages through its members 500 at a time.
- `scripts/check-branch-ref-owner.mjs` allowlists `host/handoff.ts`: its
`merge-base --is-ancestor` compares 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_by` and `create_pending` columns from
#7863's 0161. `HOST_DAEMON_PROTOCOL_VERSION` is 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 SDK `adopt`
comment, the Plugin Guide surface, the plugin README and the `worktree`
skill.

### What a warm hit waits for

T is the title, F is fetching and creating the worktree, S is setup.

| Path | Wait before the agent starts |
|---|---|
| Cold (unchanged from #7863) | max(T, F + S) |
| Warm hit, member current | max(T, ~0.3 s) |
| Warm hit, member behind | max(T, S), plus a fast-forward; setup is
usually quick when its inputs did not change |

The first version of this PR replaced members whenever the default base
moved. On this repo `main` moves 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:worktree` server with a tiny local repo, a bare remote,
a pushing clone, pool size 1, and an idempotent `.bb-env-setup.sh` that
takes 15 s when `deps.txt` changes and returns at once otherwise. Times
are from thread creation.

| Run | Result |
|---|---|
| Warm hit, member current | provisioning completed +416 ms |
| Warm hit, member behind by a commit that leaves `deps.txt` alone |
fast-forwarded to the new commit; setup ran again and returned at once;
provisioning completed +1.18 s |
| Warm hit, member behind by a commit that changes `deps.txt` |
fast-forward, then setup started 1 s later, while the title was still
pending; the branch was renamed when the title arrived 1 s after that
(reflog); `turn/started` +16.5 s for a 15 s setup |
| `kill -9` of the server 0.6 s after spawn (adopted, setup running,
branch still the placeholder) | after the automatic restart the member
was destroyed (hold released, directory and placeholder branch deleted);
the thread got a fresh worktree on the current commit, `turn/started`
+27.6 s including ~12 s of restart; no leftover branches |
| `kill -9` after the rename, before create returned (`thr_2skjwjn82w`;
a temporary, uncommitted 20 s pause after the rename held the window
open) | at the kill, the worktree was on
`bb/rename-crash-test-thr_2skjwjn82w` with 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 s |
| Two creates at once with one member | one takes the member, the other
builds a cold worktree |
| Pool of 1 grown to 3 | second member created 20:42:49 and ready
20:43:04; third created 20:43:05 (it used to wait for the next 2-minute
tick) |
| Project whose folder was deleted | settings and `bb worktree pool
status` show "The project folder … is missing or is not a git
repository." (clearing after a later successful check is covered by
`warm-pools.test.ts`) |
| `bb worktree pool set` with 4 projects keeping pools, one fetching
from GitHub | 0.66–0.88 s, the same as a read-only `pool 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
background |
| Settings open on a phone-width page while a pool grows from 1 to 2 |
"1 preparing" after 3.3 s and "2 ready" after 14.7 s, without a reload;
long status lines wrap |

**Tests**
- `apps/server/test/environments/environment-holds.test.ts`:
- threads joining a plugin-held environment are refused, including
during a handover, until create returns;
- a provider's `adopt` hands its plugin's held environment to the
thread, and another plugin's hold is kept;
- setup runs again, before the thread starts, when the provider calls
setup after adopt;
- a restart before create returned discards the adopted environment and
gives the thread a new one;
- stopping the thread before create returned discards the adopted
environment;
- create returning a different path than it adopted fails the thread
without starting it;
  - steps reported after adopt show on the thread and the environment;
  - disabling a plugin releases its holds.
- `plugins/environment-git-worktree/host.test.ts` (real git):
- a member is checked, then its placeholder renamed in place without
moving the checkout;
- a remote commit that has not been fetched is fetched, and a member
behind it is fast-forwarded;
- a member is refused after the base was rewritten, or when it is on
another branch;
- removal deletes the renamed branch when the record still names the
placeholder;
- a used checkout gets its placeholder back, and a held ref lock answers
busy quickly;
  - an unreachable remote falls back to the last fetched base.
- `plugins/environment-git-worktree/warm-pools.test.ts`:
- adopt happens on the placeholder, then the branch is renamed once the
title arrives;
  - fast-forward and setup run before the title settles;
- a refused, busy or timed-out member falls back, and a refused adopt
leaves the branch alone;
- another create can take the next member while one waits for its title;
  - one member goes to only one of two simultaneous creates;
- reconcile keeps members that are behind and deletes those no longer on
the base, failed, too old or over the size; turning a pool off deletes
its members;
- a size change replies while a pool's remote check is still running (it
hangs on the previous code).
- turbo typecheck and lint over `...[origin/main]` (167/167 tasks).
turbo test plus `check:query-costs` over the 12 changed packages (23/23
tasks): `@bb/server` 4438 passed, 3 skipped; Worktree 191; `@bb/db` 756;
`@bb/cli` 1412 passed, 1 skipped; `@get-bb/plugin-sdk` 445. Plugin SDK
version guard passes.

> AGENT GENERATED

---------

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