Skip to content

Create environments before threads, and keep warm worktrees ready as plugin policy - #7808

Closed
ymichael wants to merge 1 commit into
mainfrom
bb/warm-worktree-pool-with-core-setup-runner-thr_zv2frvrfum
Closed

ymichael wants to merge 1 commit into
mainfrom
bb/warm-worktree-pool-with-core-setup-runner-thr_zv2frvrfum

Conversation

@ymichael

@ymichael ymichael commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A new worktree thread on this repo waits ~24–33 s before its first turn starts: git fetch, git worktree add, .worktreeinclude, then .bb-env-setup.sh (mostly pnpm install). Nothing could do that work ahead of time, because core could only create an environment for a thread: the provider contexts carried thread, the setup recovery path needed a starting thread, and an environment with no live threads was retired after the grace period.

The earlier version of this PR worked around that from the plugin side. It is gone:

  • bb.experimental_environments.runSetupScript let the plugin run setup outside core's create path. That was a second setup path, and the claimed worktree ran setup again at handoff. Now core runs setup for every environment, thread or not, on the one durable environment:<id>:<key>:setup row, and never re-runs it at handoff.
  • experimental_projectSource.removed existed so the plugin could clean up its pool when a source went away. Pool members are now core environments, so project deletion and machine removal remove them with no plugin code.
  • The plugin's own pool state (host/pool.ts and its JSON state machine, the poolPrepare/poolReady/poolReconcile/poolDiscard RPCs, the worktrees/pool/ directory) is replaced by ordinary environments that the plugin holds. The setup/teardown unification (runEnvironmentHook, protocol 271) is not in this PR either. It is being reworked separately (PR A).

What changed

Design: environments before threads, with pooling as a plugin (approved 2026-11-18). Core owns the lifecycle, and the plugin owns the policy.

Core: creation intent on the environment, one create path

  • An environment's creation intent is its row: project, host, provider id/plugin/selection (machine + inputs), name, and the new held_by. For thread-less environments the engine rebuilds the create context from the row (resolveHeldEnvironmentOperationContext). Threads still build it from their provisioning context. Both go through the same runCreate, bind and setup (environment.attach) path. recoverEnvironmentProvisionRequest issues setup with initiator: null for a held environment with no starting thread, so the periodic sweep and the daemon-reconnect resume work without a thread. Settling a setup that had no initiator now advances threads that joined mid-setup, and fails them on failure (previously only possible for directory-change attaches, which have no bound threads, so that path behaves as before).
  • suggestedBranchName: <prefix><slug(title)>-<threadId> for threads (unchanged), <prefix><slug(name)>-<envId> or <prefix><envId> without a thread.
  • Holds (environments.held_by, migration 0160_environment_holds): null | "user" | "plugin:<id>". Existing rows are null and behave as before.
    • Both retirement places (refreshProviderRetirement, the lifecycle sweep/query) skip held environments unless the machine is being removed.
    • Joining a plugin-held environment (--environment, threads.create reuse, a provider's experimental_existingPath, directory changes) is refused with 409 environment_held "Environment env_x is held by ". User-held environments accept joins.
    • Handoff: bindEnvironmentPath(db, row, path, produced) adopts an existing environment held by the producing provider's plugin and, in the same immediate transaction, clears held_by and takes the produced resource and mergeBaseBranch. An environment held by another plugin is refused. Setup does not re-run (status stays ready, setup row count unchanged).
  • Surfaces
    • POST /api/v1/environments → bb.sdk.environments.experimental_create({ projectId, hostId?, provider?: { id, inputs? }, name?, hold: "user" | "plugin" }). Inside a plugin, hold: "plugin" holds for the calling plugin. Omitted host → the project's default checkout machine. Omitted provider → worktree (personal workspace for the personal project). Omitted inputs → {}, so schema defaults apply. Composed providers (new machine per thread) and version-1 providers are refused.
    • list({ heldBy }) filter; Environment.heldBy and Environment.statusMessage (progress / failure reason for thread-less creates).
    • CLI: bb environment create --project <id> [--machine] [--provider <id> --inputs <json>] [--name] (always holds for the user), bb environment list --held-by <holder>, and show/list print the holder.
  • Provider contract apiVersion. register is overloaded on apiVersion: omitted or 1 gets today's contexts with thread, and old source still type-checks (verified against the published SDK 0.6.157, below). Version 2 contexts carry environment: { id, name, projectId } and pathKeys: "per-environment" | "per-attempt". Core keeps one implementation: invokeCreate/providerRestoreCall add thread for version 1, and refuse it with " can't create an environment before a thread exists" when there is none. Additive fields don't bump the version. The adapter is listed in docs/api_to_audit.md for deletion at stabilization.
  • First-party providers on version 2: worktree, project checkout and personal workspace. Modal registers only a composition (machine provider + project checkout), so it has no create/restore contexts to move. Project checkout's live-thread check (context.thread.id) moved into core path admission as experimental_claimPath(path, { exclusive: true }), which rejects with the same "Cannot checkout branch while another thread is using this workspace" while a live thread other than the driving one works at the path (assertNoOtherLiveThreadUsesPath).

The pool (plugins/environment-git-worktree), kept from the earlier version: the scheduler and settings (warm-pools.ts, rebuilt on the SDK), the settings section, bb worktree pool status|set, and the worktree skill (now declared in the manifest).

  • Setting: per-project size 0–4, off by default.
  • Refill: experimental_create({ provider: worktree default base, hold: "plugin" }), unnamed, so its placeholder branch is <prefix><envId>. One at a time per machine, debounced (5 s at start, 10 s after a handoff, every 2 min), with a 10-minute backoff after a failure. Core runs creation and setup durably.
  • Handoff happens in create, only for a default-base create whose environment has no holder. The plugin reads that with bb.sdk.environments.get, so user-held creates and pool refills always build cold. It lists its ready members for the project and machine and picks the oldest under a lock scoped to that project and machine. The host then waits at most 2 s for the git ref lock and, inside it, repairs the placeholder branch, checks HEAD against the last fetched default base and runs git branch -m <placeholder> <suggestedBranchName>; if writing the .completed marker fails it renames the branch back. The create returns the path plus an ownedBranch resource naming the new branch. A member that is behind or was used is deleted and the next one is tried. A busy lock, an RPC error or a timeout builds a fresh worktree at once, without trying more members.
  • Self-repair: core never tells a provider that a path it returned was refused, for example when the bind fails, the create is aborted or an RPC response is lost. So before every handoff and on every reconcile, a member whose checkout is not on its recorded placeholder (Environment.branchName from setup; core only rewrites it when a thread attaches) is renamed back to the placeholder. It is kept if it has no commits beyond the base and a clean tree. Otherwise it is deleted, and because it carries the placeholder name again, core's removal handles that branch with its usual safety rules.
  • Freshness: while a pool exists, every reconcile fetches the default base (refreshPoolBase) and deletes members that are behind it, failed, older than 8 h, or over the size. Turning a pool off deletes its members. A project whose lookup fails with anything but a 404 keeps its members untouched. Every discard re-checks the handoff reservation inside the per-project-and-machine queue, so a queued handoff and a discard never act on the same member. The checkout is never moved at handoff.

Versions: plugin SDK 0.6.164 → 0.6.165. HOST_DAEMON_PROTOCOL_VERSION stays 271: no daemon wire field changed (the new RPCs belong to the worktree plugin's own host contract, which ships with the plugin).

Docs: Plugin Guide surface + backend-events.md / backend-machines.md (backend-events.md stays at its 500-line cap), docs/api_to_audit.md (context versions + adapter deletion, exclusive claims, holds / experimental_create), bb-guide-environments + bb-cli command index, docs/worktrees.md#warm-worktrees, docs/configuration.md, the plugin README and the worktree skill.

Hit-rate tradeoff (freshness is pool policy)

A member is handed out only while it equals the last fetched default base, and members behind it are replaced. On this repo main moved 22.5 times a day over the last 14 days (median gap 5.6 min, p25 1.4 min). Replaying the 517 real thread starts in this project over the same 14 days (2-min fetches, ~30 s setup, one refill at a time) against that commit history gives a pool hit rate of 41% at size 1, 54% at size 2, 63% at size 4 (37% / 44% / 51% with 60 s setup). Two things cost the misses: bursts of child threads drain the pool faster than one-at-a-time refills, and every base move invalidates all members. A miss falls back to today's cold path, so it is never slower than main. The cost is one setup run per member per upstream change while a pool is on. A handed-out member can be up to one fetch interval (2 min) behind the remote, while a cold create fetches first.

Review fixes (after fd55a59)

  1. A thread-less create took a pooled member and failed. The handoff now runs only when the environment being created has no holder (environments.get). That replaces the own-member check and covers pool refills. Tested in the plugin, and on the real dev server: with a pool of 1, bb environment create produced its own env_j4n4kh9xy4 on bb/fix1-check-env_j4n4kh9xy4, and member env_2s6xahhatt stayed held on bb/env_2s6xahhatt.
  2. A transient projects.get error discarded the pool. Non-404 lookup failures now leave that project's members alone. Discards re-check the reservation inside the serialized queue.
  3. A failure after the rename orphaned the renamed branch. Fixed by the placeholder repair above, plus a rename-back when the marker write fails.
  4. A slow fetch could stall every create. Serialization is now per project and machine, the host waits at most 2 s for the ref lock (the fetch can hold it for 60 s) and answers busy, any error or timeout goes cold at once, and the base commit is read inside the lock.

Decisions for review

  1. bb.sdk.environments.experimental_create, not create. The design names it create. AGENTS.md requires an experimental_ prefix on new public plugin API members, and every SDK precedent (experimental_cleanup, experimental_listAncestors) follows it. heldBy, statusMessage and the heldBy list filter are unprefixed fields, like instanceKey.
  2. --inputs <json>, not --input k=v. Provider inputs are nested ({"branch":{"kind":"named","name":"release"}}), and bb thread spawn already takes JSON (--environment-inputs).
  3. Version-2 path keys stay thread-based for thread-driven creates. Core derives pathKey from the driving thread when there is one, and from the environment id only without a thread. Worktree directory names stay thr_x-1, and storage-retention's worktrees/thr_… thread links keep working. Only pooled and thread-less worktrees are named env_x-1.
  4. Thread-less creation needs an existing machine. Compositions (Modal) are refused, because their machine lifetime is tied to a thread.
  5. Environments held by an uninstalled plugin stay until deleted. Nothing releases a hold in v1, per the design. A pluginId passed outside a plugin is not authenticated, the same as plugin metadata.
  6. No UI change. The app's "reuse existing" picker is built from threads, so held environments without threads never appear there. The holder shows in the CLI and the API. "New workspace" stays the design's follow-up.
  7. K3 covers a server restart. A restart of the daemon during setup leaves its outcome unknown and ends in error/needs-recovery, exactly as for thread environments today. I observed this when I first stopped both processes.
  8. The hit-rate tradeoff is your call. As built, a member is handed out only while it matches the last fetched base, which replays to 41/54/63% hits at size 1/2/4 on this repo. The alternative, moving the checkout at handoff and re-running setup, would hit more often but run setup on the thread's critical path. I kept the design's choice.
  9. Pool constants come from the earlier version: max size 4, 2-minute reconcile, 8 h TTL, 10-minute failure backoff.

How you verified

Kill tests on a real dev server (pnpm start:worktree from this branch, project = a fresh clone of this repo with origin on GitHub, agent codex; script kept outside the PR):

  • K1 PASS. Time from the server receiving the spawn to turn/started, titled thread, on this repo:

    run pooled cold
    1 936 ms 33 444 ms
    2 593 ms 24 005 ms
    3 575 ms 23 985 ms
    4 570 ms 23 737 ms

    The workspace is ready at 235 ms (handoff itself ≈ 86 ms). The rest is codex's app-server start. The first codex launch on a fresh server took 2.3 s regardless of the pool (run 0, excluded). Wall time from the CLI invocation adds ~0.75 s of tsx start. In every pooled run the thread got the ready member, the setup row count was unchanged (e.g. 19 → 19), and the branch was bb/pool-hit-timing-<threadId>.
    After the review fixes (head a9f696b, fresh server): K1 passes again. Pooled runs reached turn/started in 577 ms, 1 995 ms, and 2 386 ms on the first codex launch; cold runs took 24.3–27.0 s. The environment was ready at 203–497 ms in every pooled run, and the rest is codex's start, which varied between 0.4 s and 2.2 s. The setup row count stayed the same each time. K2 passes again.

  • K2 PASS. Two simultaneous spawns with one ready member: thr_xpa8fkjat4 got env_h8h2carrms, thr_bfid5ukfbb cold-created env_ngdkzudwgg, and both started.

  • K3 PASS. bb environment create, then killed only the server process (by its listening port; the launcher restarted it and kept the daemon) while setup was running. env_6q5ka48jji ended ready on the same operation row environment:env_6q5ka48jji:env_6q5ka48jji-1:setup, with no error.

  • K4 PASS. A user-held env_rdsxzv7enf with no threads outlived the 300 s grace (retire_at stayed null). Handed-off env_3f5f7aqe6y lost its hold and retired 324 s after its thread was archived.

  • K5 PASS. Pool size 2 on a throwaway project, then bb project delete: both pooled worktrees and their branches are gone, with no plugin code involved.

  • K6 PASS. bb thread spawn --environment <pooled> is refused with "held by environment-git-worktree". A user-held environment was joined by a thread and stays heldBy: user.

  • K7 PASS. A fixture plugin built with bb plugin new against the published @get-bb/[email protected] (no apiVersion, uses context.thread.id) type-checks unchanged. It created /…/v1-workspaces/thr_n3nrtytg84 (thread-keyed, as today), removed it on retire, and bb thread restore-environment restored it as env_hkurhwj54b. bb environment create --provider v1-fixture is refused with "V1 fixture can't create an environment before a thread exists".

Tests added

  • apps/server/test/environments/environment-holds.test.ts (9): thread-less create from the stored intent (context, branch name, path key, initiator: null setup, one setup row); v1 refusal; a held environment survives 24 h of sweeps; join refused for plugin-held and allowed for user-held; handoff clears the hold, takes the resource and doesn't re-run setup; a thread that joins mid-setup starts when setup finishes (fails without the new settlement branch); restart resume for held vs unheld rows on the same operation row; exclusive claim refusal.
  • plugins/environment-git-worktree/host.test.ts (7, real git): rename in place without moving HEAD; refuse when behind the fetched base (after refreshPoolBase reports the new commit); refuse a checkout on another branch while the placeholder still exists; rename succeeds, the handoff is then refused, and after repair and removal no branch is left; a used checkout gets its placeholder back so removal owns that branch; a failed marker write renames the branch back; a held ref lock answers busy in under 10 s (the default lock wait is 5 minutes).
  • plugins/environment-git-worktree/warm-pools.test.ts (14): handoff result and resource; user-held and pool-refill creates get a cold worktree while the pool is on; busy or a timed-out handoff goes cold at once without trying a second member; refusal → delete + cold create; a failing member listing → cold create; one member to only one of two concurrent creates; named bases stay cold, reconcile replaces stale members and refills with hold: "plugin"; a 503 project lookup keeps the members; reconcile restores an unused member to its placeholder, or deletes a used one; failed members are deleted with their error in status; and size 0 deletes everything. With the holder check or the 404-only check removed, the new user-held, refill and 503 tests fail.
  • Provider and plugin tests moved to version-2 contexts; migration tests rewind the new column; query-cost cases for insertHeldEnvironment and findOtherLiveThreadAtEnvironmentPath (check:query-costs passes).

Commands

  • pnpm exec turbo run typecheck --filter='...[origin/main]': 107/107 tasks.
  • pnpm exec turbo run test --filter='...[origin/main]': 107/109 on the first run. The two failures, the Plugin Guide bullet cap and the backend-events.md 500-line cap, are fixed and re-run green (plugin-api-docs 75/75, shipped-skills-quality 37/37).
  • turbo run lint on the touched packages; oxfmt on touched files that were formatted on main.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/warm-worktree-pool-with-core-setup-runner-thr_zv2frvrfum branch from a2070b8 to 16c5222 Compare November 19, 2026 06:05
@ymichael ymichael changed the title Keep warm worktrees ready so new worktree threads start without waiting Create environments before threads, and keep warm worktrees ready as plugin policy Nov 19, 2026
@ymichael
ymichael force-pushed the bb/warm-worktree-pool-with-core-setup-runner-thr_zv2frvrfum branch 2 times, most recently from 95b6761 to fd55a59 Compare November 19, 2026 06:17
Core owns the environment lifecycle; plugins own policy. An environment's
creation intent (project, machine, provider selection, name, holder) now lives
on its row, so core can create one with no thread through the same create and
setup path threads use. A new environments.held_by column keeps held
environments from retiring without threads, refuses joins to plugin-held
ones, and is cleared atomically in bindEnvironmentPath when the holding
plugin's provider hands the environment to a new thread, which also takes the
produced resource and merge base.

Environment providers gain apiVersion 2: create and restore contexts carry
the environment instead of the thread. Core keeps one implementation with a
version-1 adapter at the call boundary, and refuses version-1 providers for
thread-less creation. Worktree, project checkout and personal workspace move
to version 2; project checkout's live-thread check moves into core path
admission as experimental_claimPath(path, { exclusive: true }).

Surfaces: bb.sdk.environments.experimental_create, list({ heldBy }),
Environment.heldBy and statusMessage, bb environment create and
bb environment list --held-by.

The Worktree plugin's warm pool is plugin policy on top: per-project size,
plugin-held members created through experimental_create, handoff inside
create by renaming the unused placeholder branch, freshness by replacing
members behind the fetched default base, and bb worktree pool status|set.

Plugin SDK 0.6.165.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael

Copy link
Copy Markdown
Collaborator Author

Closing: superseded by #7863, which carries environments before threads, user holds and the version-2 environment provider contract. The warm worktree pool (plugin holds, adopt, and the pool policy) follows in its own PR after #7863 merges.

AGENT GENERATED

@ymichael ymichael closed this Nov 19, 2026
ymichael added a commit that referenced this pull request Nov 20, 2026
…before threads (#7863)

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

---------

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