Repository navigation
Conversation
… the branch once Providers that declare experimental_renameBranch no longer wait for title generation: create runs with <prefix><threadId>, and core renames the branch once to the titled name, before setup when the title lands first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…adopted rows Co-Authored-By: Claude Opus 5.5 <[email protected]>
…from git Members of objects passed to bb.experimental_* APIs carry no nested prefix, so the provider hook is renameBranch. The owed rename now stores only its thread: core reads the checkout's current branch just before calling the hook and passes it as from. When bindEnvironmentPath adopts an existing environment and carries the owed rename over, from was the reserved row's bb/<threadId> while the adopted worktree sat on another branch, so the provider kept it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/start-worktree-creation-before-thread-titles-exi-thr_4jrkyryhrb
branch
from
November 19, 2026 05:12
c1c40db to
1c42487
Compare
Since from is the checked-out branch, core no longer guards against a checkout that switched to a branch the user or agent made; only the provider's own ownership record does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Collaborator
Author
|
Closing: the rename hook is superseded by a version-2 environment provider contract, where create awaits ctx.branchName() instead of renaming afterwards. That work replaces this PR.
|
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]>
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 thread that gets a new environment waited for title generation before the environment provider's
createran (about 1.1–1.4s on a dev server, about 1.3s p50 in production). The worktree branch name (<prefix><title-slug>-<threadId>) was built from the generated title, andensureThreadProvisionEnvironmentReadyawaitedinferThreadMetadatabeforeresolveEnvironmentProvider. So every new worktree thread paid for the title before any git work started.What changed since review
experimental_renameBranchis nowrenameBranch. Members of objects passed tobb.experimental_*APIs carry no nestedexperimental_prefix. Renamed in the SDK declaration,host-policynormalization, the core callers, the Worktree plugin, the server tests,docs/api_to_audit.mdand the plugin-authoring reference. The Plugin Guide surface lists only the context and result type names, which did not change. A repo-widegit grep experimental_renameBranchfinds nothing.fromis the checkout's real branch:host.inspect_git_checkoutjust before calling the hook and passes that asfrom. The owed rename on the row stores only{ threadId }.fromwas the reserved row'ssuggestedBranchName(bb/<threadId>). WhenbindEnvironmentPathadopted an existing environment and carried the owed rename over, the adopted checkout was on a different branch, so the provider answeredkept.fromand the audit entry now say that a provider renames only a branch it created for this environment and answerskeptotherwise. Worktree does this by checking thatownedBranch.name === from.inspectEnvironmentBranchis split out ofrefreshAttachedEnvironmentBranch, which still records the branch after a rename.fromis the adopted checkout's branch. The old adoption test, which assertedfrom: bb/<threadId>, is replaced. The new test fails on the reviewed head.df9619d8e8a, which had no conflicts. Plugin SDK version is 0.6.165.What changed
Plugin SDK: new optional
renameBranch(context)on environment providers.{ environment, resource, from, to, report, signal }.fromis the branch the checkout is on, read from git just before the call.renamed(optionally with a replacement resource),keptwith a reason, orfailed.PluginEnvironmentProviderRenameBranchContext/Resultare listed in the Plugin Guide surface, with an entry indocs/api_to_audit.md. SDK bumped to 0.6.165.Core (
services/environments/environment-branch-rename.ts):suggestedBranchNameis<prefix><threadId>. Core persists the owed rename (environments.pending_branch_rename,{ threadId }, migration 0160) before callingcreate.createreturns, core renames inside the create operation, before the environment reachesprovisioning. Setup and "Using branch" then see the final name.branch_renamesystem/operationentry.keptandfailedclear the owed rename. A throw (including an unreachable host during the branch read) or an unregistered provider leaves it for the newenvironment-branch-renameperiodic sweep. The sweep also finishes renames that a restart interrupted.Worktree plugin: declares the hook. A new
renameBranchhost RPC (host/branch-rename.ts) renames only when all of these hold:refs/heads/<from>;<from>has no upstream and no remote-tracking ref of that name;<to>does not exist.If HEAD is already on
<to>, it reportsrenamed. The server side also checks that the resource'sownedBranch.nameisfrom, and keeps adopted (user-supplied) worktrees.git branch -mcarriesbranch.<from>.*config, includingbbOwned. The resource'sownedBranch.nameis updated, so removal deletes the renamed branch.Project checkout is unchanged and keeps waiting for the title. Its new branches live in a shared checkout whose environment row outlives any one thread.
Adopted rows:
bindEnvironmentPathmoves an owed rename onto the existing row it binds to and clears it on the reserved row it destroys. It never overwrites a rename that row already owes.Docs:
docs/worktrees.md, the Worktree README, the plugin-authoring reference anddocs/api_to_audit.md.Wire: no daemon protocol change. The rename goes through the generic plugin host RPC, and the branch read uses the existing
host.inspect_git_checkout, soHOST_DAEMON_PROTOCOL_VERSIONstays 271.Changes from the agreed design:
createwould have received, not only "the first generated title". When generation fails or is skipped (prompts under 5 words skip it), the branch is renamed to the fallback-title slug.-u).How you verified
apps/server/test/threads/environment-branch-rename.test.ts(real migrated DB, 8 cases):kept: rename is cleared, resource keptcreatelanding on an existing environment row whose checkout is onbb/earlier-task-thr_earlier: the hook runs on that row withfrom: bb/earlier-task-thr_earlierWith the reviewed head's rename code restored, the adoption, detached-HEAD and owed-shape cases fail (3 of 8).
Worktree host tests against real repos:
bbOwnedconfig carried overturbo run typecheckon@bb/server,@bb/db,@get-bb/plugin-sdk, the worktree plugin and plugin-api-docs.turbo run teston the worktree, project-checkout and plugin-api-docs plugins and the SDK (734 tests). Server provisioning, title, environment-provider, restore and orchestration suites (269 tests).turbo run linton server, db, SDK and worktree.Live, on a
pnpm start:worktreedev server at this head (Codex writing titles,.bb-env-setup.shwritinggit branch --show-currentand a timestamp). Times are ms from thread creation.git worktree addran. git createdbb/thr_g7mjeqs5hm(Preparing worktree (new branch 'bb/thr_g7mjeqs5hm')), and setup at 1,515–1,616 ms sawbb/confirm-login-redirect-fix-plan-…-thr_…. "Using branch" showed the titled name, and there was no timeline entry, as expected.--title(no rename) it took 88–540 ms, so the rename shows no measurable cost.bb/thr_…, and the rename landed afterwards: at 1,497 and 3,757 ms on the big repo, and at 1,486 ms on the tiny repo, where the turn started at 2,504 ms. Each wrote thebranch_renameentry, e.g.Renamed branch bb/thr_2732nfuni6 to bb/confirm-login-redirect-fix-plan-3-thr_2732nfuni6. The environment'sbranch_namematches git HEAD.createalways returns one fixed worktree path, with a HEAD-guardedrenameBranchlike Worktree's. Thread 1 created the rowenv_gwmvj9pcs4and was renamed tobb/confirm-checkout-timeout-fix-thr_fn74ubqrj2. Thread 1 was then archived, which left the row ready with no owner.createreturned the same path, andbindEnvironmentPathbound thread 2 toenv_gwmvj9pcs4. Its reserved rowenv_4vqvw9e4dybecamedestroyed/removed.from: bb/confirm-checkout-timeout-fix-thr_fn74ubqrj2and renamed it. The timeline showsRenamed branch bb/confirm-checkout-timeout-fix-thr_fn74ubqrj2 to bb/confirm-payment-webhook-retry-fix-thr_43fxa6ys6m, and git HEAD andbranch_nameagree. On the reviewed headfromwould have beenbb/thr_43fxa6ys6m, and the provider would have kept the branch.branch_renameentries. Every environment'sbranch_nameequalsgit branch --show-current.🤖 Generated with Claude Code