Skip to content

Create new-environment worktrees before their titles exist and rename the branch once - #7807

Closed
ymichael wants to merge 5 commits into
mainfrom
bb/start-worktree-creation-before-thread-titles-exi-thr_4jrkyryhrb
Closed

ymichael wants to merge 5 commits into
mainfrom
bb/start-worktree-creation-before-thread-titles-exi-thr_4jrkyryhrb

Conversation

@ymichael

@ymichael ymichael commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A thread that gets a new environment waited for title generation before the environment provider's create ran (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, and ensureThreadProvisionEnvironmentReady awaited inferThreadMetadata before resolveEnvironmentProvider. So every new worktree thread paid for the title before any git work started.

What changed since review

  • Hook renamed: experimental_renameBranch is now renameBranch. Members of objects passed to bb.experimental_* APIs carry no nested experimental_ prefix. Renamed in the SDK declaration, host-policy normalization, the core callers, the Worktree plugin, the server tests, docs/api_to_audit.md and the plugin-authoring reference. The Plugin Guide surface lists only the context and result type names, which did not change. A repo-wide git grep experimental_renameBranch finds nothing.
  • from is the checkout's real branch:
    • Core now reads the branch with host.inspect_git_checkout just before calling the hook and passes that as from. The owed rename on the row stores only { threadId }.
    • Before this change, from was the reserved row's suggestedBranchName (bb/<threadId>). When bindEnvironmentPath adopted an existing environment and carried the owed rename over, the adopted checkout was on a different branch, so the provider answered kept.
    • When the checkout is on no branch (detached), the rename is dropped.
    • Core therefore no longer guards against a checkout that switched to a branch the user or agent made. The SDK declaration on from and the audit entry now say that a provider renames only a branch it created for this environment and answers kept otherwise. Worktree does this by checking that ownedBranch.name === from.
    • inspectEnvironmentBranch is split out of refreshAttachedEnvironmentBranch, which still records the branch after a rename.
  • New server tests (real migrated DB):
    • adoption: from is the adopted checkout's branch. The old adoption test, which asserted from: bb/<threadId>, is replaced. The new test fails on the reviewed head.
    • detached HEAD: the rename is dropped.
  • Rebased onto main df9619d8e8a, which had no conflicts. Plugin SDK version is 0.6.165.
  • Unchanged from review: Project checkout still has no hook and still waits for the title.

What changed

  • Plugin SDK: new optional renameBranch(context) on environment providers.

    • Context: { environment, resource, from, to, report, signal }. from is the branch the checkout is on, read from git just before the call.
    • Result: renamed (optionally with a replacement resource), kept with a reason, or failed.
    • New types PluginEnvironmentProviderRenameBranchContext/Result are listed in the Plugin Guide surface, with an entry in docs/api_to_audit.md. SDK bumped to 0.6.165.
  • Core (services/environments/environment-branch-rename.ts):

    • Providers that declare the hook no longer wait for the title. Inference runs in the background.
    • If the title is still pending when the create context is built, suggestedBranchName is <prefix><threadId>. Core persists the owed rename (environments.pending_branch_rename, { threadId }, migration 0160) before calling create.
    • If the title settled before create returns, core renames inside the create operation, before the environment reaches provisioning. Setup and "Using branch" then see the final name.
    • If the title settles after create, core renames when it lands, re-reads the branch from git (and again after a running setup finishes), and appends a thread-scoped branch_rename system/operation entry.
    • Turn start and removal both wait for an in-flight rename. Neither ever waits for a pending title. A retiring, failed or destroyed environment drops the rename.
    • kept and failed clear the owed rename. A throw (including an unreachable host during the branch read) or an unregistered provider leaves it for the new environment-branch-rename periodic sweep. The sweep also finishes renames that a restart interrupted.
    • Providers without the hook behave as before: they await the title, and the transcript still shows "Generating title".
  • Worktree plugin: declares the hook. A new renameBranch host RPC (host/branch-rename.ts) renames only when all of these hold:

    • HEAD is 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 reports renamed. The server side also checks that the resource's ownedBranch.name is from, and keeps adopted (user-supplied) worktrees. git branch -m carries branch.<from>.* config, including bbOwned. The resource's ownedBranch.name is 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: bindEnvironmentPath moves 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 and docs/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, so HOST_DAEMON_PROTOCOL_VERSION stays 271.

Changes from the agreed design:

  • Target name. The rename target is the name create would 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.
  • Where the rename is persisted. It lives on the environment row, not in the thread's provisioning state. That state ends when the turn starts, and mid-turn renames still need to survive restarts.
  • Hook-provider transcript. For hook providers the "Generating title" provisioning steps are gone, because title generation no longer blocks provisioning.
  • Remote-ref guard. The host guard also keeps a branch that has a remote-tracking ref of the same name (pushed without -u).

How you verified

  • apps/server/test/threads/environment-branch-rename.test.ts (real migrated DB, 8 cases):

    • title before create returns: rename runs before setup is queued
    • title after setup: rename runs mid-turn, writes the timeline entry, and the branch is recorded from git
    • title failure: rename uses the fallback title
    • environment retiring: rename is dropped
    • provider kept: rename is cleared, resource kept
    • create landing on an existing environment row whose checkout is on bb/earlier-task-thr_earlier: the hook runs on that row with from: bb/earlier-task-thr_earlier
    • checkout on no branch: rename is dropped
    • provided title: no rename

    With 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:

    • rename, and an idempotent retry
    • bbOwned config carried over
    • removal deletes the renamed branch
    • kept when the branch has an upstream, was pushed without tracking, HEAD switched, or the target exists
  • turbo run typecheck on @bb/server, @bb/db, @get-bb/plugin-sdk, the worktree plugin and plugin-api-docs. turbo run test on 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 lint on server, db, SDK and worktree.

  • Live, on a pnpm start:worktree dev server at this head (Codex writing titles, .bb-env-setup.sh writing git branch --show-current and a timestamp). Times are ms from thread creation.

    • Cold path, 8,951-file repo, 4 threads without a title.
      • Worktree create started at 4–6 ms in every case.
      • In 2 of 4 runs, the title landed while git worktree add ran. git created bb/thr_g7mjeqs5hm (Preparing worktree (new branch 'bb/thr_g7mjeqs5hm')), and setup at 1,515–1,616 ms saw bb/confirm-login-redirect-fix-plan-…-thr_…. "Using branch" showed the titled name, and there was no timeline entry, as expected.
      • Created worktree → Using workspace took 450–514 ms with the in-create rename. In 3 threads with --title (no rename) it took 88–540 ms, so the rename shows no measurable cost.
    • Slow title, same repo and tiny repo, 3 threads. Setup saw 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 the branch_rename entry, e.g. Renamed branch bb/thr_2732nfuni6 to bb/confirm-login-redirect-fix-plan-3-thr_2732nfuni6. The environment's branch_name matches git HEAD.
    • Adoption.
      • Setup: a throwaway local fixture plugin whose create always returns one fixed worktree path, with a HEAD-guarded renameBranch like Worktree's. Thread 1 created the row env_gwmvj9pcs4 and was renamed to bb/confirm-checkout-timeout-fix-thr_fn74ubqrj2. Thread 1 was then archived, which left the row ready with no owner.
      • Thread 2's create returned the same path, and bindEnvironmentPath bound thread 2 to env_gwmvj9pcs4. Its reserved row env_4vqvw9e4dy became destroyed/removed.
      • The hook got from: bb/confirm-checkout-timeout-fix-thr_fn74ubqrj2 and renamed it. The timeline shows Renamed branch bb/confirm-checkout-timeout-fix-thr_fn74ubqrj2 to bb/confirm-payment-webhook-retry-fix-thr_43fxa6ys6m, and git HEAD and branch_name agree. On the reviewed head from would have been bb/thr_43fxa6ys6m, and the provider would have kept the branch.
    • After all 10 threads: 10 environment rows, 0 with an owed rename, and 5 branch_rename entries. Every environment's branch_name equals git branch --show-current.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 4 commits November 18, 2026 20:57
… 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]>
…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
ymichael force-pushed the bb/start-worktree-creation-before-thread-titles-exi-thr_4jrkyryhrb branch from c1c40db to 1c42487 Compare November 19, 2026 05:12
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]>
@ymichael

Copy link
Copy Markdown
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.

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