Skip to content

Give plugins their own files directory with bb.storage.experimental_directory() - #7957

Merged
ymichael merged 3 commits into
mainfrom
bb/implement-plugin-storage-api-gap-5-thr_qicma3guqw
Nov 21, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/implement-plugin-storage-api-gap-5-thr_qicma3guqw

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

bb already gives every plugin <dataDir>/plugins/<id>/, but a plugin had no way to get a path inside it for its own files. So plugins built the path themselves from bb.server.experimental_dataDir, even though that member's JSDoc said it was not a place to write. Account Pool wrote its account credentials and machine tokens into core's secrets/ folder (secrets/accounts), next to core's secret-setting files. In a 503-repo community corpus, 32 repos use experimental_dataDir and about 22 of them write their own files under plugins/<id>/, two of them into secrets/ as well. Core built the same folder by hand in three more places (data.db in bb.storage.database(), logs/, secrets/), plus the update-snapshot code.

What changed

  • New SDK member: bb.storage.experimental_directory(): string (packages/plugin-sdk/src/backend-contract.ts). It returns <dataDir>/plugins/<id>/files and creates it with mode 0700 when it is missing. It is a method, not a field, because it creates the folder, the same way database() does.
  • One resolver: pluginDirectory(dataDir, id, part) (apps/server/src/services/plugins/plugin-directory.ts, part = data.db | logs | secrets | files). It replaces the hand-written joins in plugin-api.ts (database()), plugin-log.ts, plugin-settings.ts, plugin-service.ts (uninstall, HTTP token) and plugin-state-snapshot.ts, and the new method uses it too. Plugin ids that would collide with core's folders are already refused by derivePluginId (Refuse plugin ids that name core's folders under plugins/ #7887).
  • Lifetime: uninstall deletes files/ along with secrets/, as Michael decided. data.db and logs/ keep their current lifetime and survive uninstall. Update snapshots now copy files/, and rollback restores it, the same as data.db and secrets/. Without that, Account Pool's credentials would go from rolled-back to not rolled-back just by moving folders. A snapshot taken before this change has no files/ copy, so restoring it removes the folder: the plugin goes back to the state it had then. No schema change; the snapshot's copy sits at <snapshotPath>/files.
  • Snapshot copies are clones. files/ and secrets/ are cloned into the snapshot and back on rollback (cloneTree in plugin-state-snapshot.ts). On macOS this runs /bin/cp -cRp, which uses clonefile(2) and falls back to a plain copy on other filesystems. Elsewhere it uses fs.cp(..., { recursive: true, mode: COPYFILE_FICLONE }), which reflinks on btrfs/XFS and otherwise copies. fs.cp with COPYFILE_FICLONE can't clone on macOS: Node 22.23 / libuv 1.51 clones only through Linux's FICLONE ioctl, so on APFS it quietly copies every byte (measured below), and COPYFILE_FICLONE_FORCE fails with ENOSYS.
  • experimental_dataDir JSDoc now says read-only: use it to migrate off files bb used to manage or to compare paths, and never write under it.
  • Account Pool keeps credentials and machine tokens in files/accounts. On load it moves secrets/accounts there once (moveAccountSecretFiles in store.ts). Each file is moved with rename, so modes and contents don't change. Files with the same name are replaced by the copy from secrets/ (only an older Account Pool writes there). Then the empty folder is removed. A second run finds nothing to move. Its bbPluginSdk range is now >=0.6.177.
  • Fake plugin host (@get-bb/plugin-sdk/testing) implements the method as a files folder in its temp storage root.
  • Uninstall wording now says "settings, secrets, stored files, and schedules" in the CLI plugin remove help and pinned-update hint, the app's remove/uninstall confirmation, the server's removal log lines and bb-guide-plugins.md.
  • Docs: docs/api_to_audit.md has a new bb.storage.experimental_directory() entry and a rewritten experimental_dataDir entry (callers, corpus count). The Plugin Guide storage card gets a bullet (the member is on PluginStorage, which is already in its apiSymbols). The bb-plugin-authoring skill covers it in backend-foundation.md (bb.storage, bb.server) and quickstart.md (on-disk state). docs/configuration.md gives Account Pool's new path.
  • Plugin SDK 0.6.176 → 0.6.177. No wire change, no DB migration.

Community callers that can move to bb.storage.experimental_directory() (not edited here): OXI-717/bb-plugins account-pool-balanced (request journal), nfour/bb-plugins bb-plugin-performance (metrics/), architawr/bb-plugin-diagram-fences (engines/), ComicBit/bb-plugin-nudger (exports/), sajov/bb-plugins bb-plugin-recall (mirror/, hardcoded id), g4f4r0/bb-plugins voice-tools (writes into core's secrets/), smsunarto/bb-plugins agent-instructions (catalog publish), patleeman/bb-plugins bb-plugin-ds4 (guesses homedir()/.bb).

How you verified

Tests (each fails on origin/main):

  • plugins/account-pool/src/server.test.ts, "moves account and machine-token files out of secrets/accounts once and fails over across them". It seeds 3 accounts and a machine token in secrets/accounts, loads the plugin and then reloads it. It checks that the folder moved with contents and modes (0600, dir 0700) unchanged and didn't change on reload, that the old machine token still authenticates, and that a 429 on the first account fails over to the second. With Account Pool's old path code: promise resolved "undefined" instead of rejecting (secrets/accounts still there).
  • apps/server/test/services/plugins/plugin-settings-storage.test.ts, "creates the plugin's files directory, keeps it across reloads, and deletes only it on remove". It uses a real path-installed plugin through createPluginService.
  • apps/server/test/services/plugins/plugin-state-snapshot.test.ts: the restore test now changes and adds files in files/ after the snapshot. Without the snapshot change: expected 'changed-file' to be 'original-file'.
  • Existing Account Pool tests now read secrets from files/accounts.

Live, with pnpm start:worktree (clean env), the source CLI and a fake Anthropic upstream that returns 429 for sk-one:

  1. On origin/main: enabled Account Pool, added API-key accounts sk-one, sk-two, sk-three, and minted a machine token. All 4 files were 0600 in secrets/accounts. A request failed over from sk-one to sk-two (HTTP 200).
  2. Stopped the server, checked out this branch, started it again on the same data dir. secrets/accounts was gone. files/accounts held the same 4 files, mode 0600, in a 0700 folder. The 3 account files were byte-identical. The token file differed only in lastUsedAt (the main server wrote it at shutdown; same value and mintedAt). bb pool status listed 3 accounts and the machine token. The old token authenticated, and the request went to sk-two (sk-one was still remembered as exhausted).
  3. Restarted again: every file byte-identical with the same modes.
  4. Made the upstream also reject sk-two: the request failed over to sk-three (HTTP 200).
  5. Path plugin calling bb.storage.experimental_directory(): plugins/filer/files/note.txt was created. bb plugin remove filer deleted files/ and kept data.db and logs/. bb plugin remove --help shows the new wording.

Snapshot cost (macOS 27.2, APFS, on a dedicated APFS disk image holding only this dev data dir, so df sees nothing else). A git: plugin from a local repo tracking main, with a 498 MB files/: 4 × 100 MB random files plus 5,000 × 20 KB files in 50 folders. Each run is one bb plugin update after a new commit. "Peak extra disk" is the lowest free space sampled every 50 ms during the update, compared with before it.

Copy files/ Update wall time Peak extra disk Extra disk after
this branch, cp -cRp empty 34.6 s — 0 MB
main-style fs.cp 498 MB 35.0 s, 32.8 s 548 MB, 548 MB 0 MB
this branch, cp -cRp 498 MB 35.8 s, 33.7 s 1 MB, 1 MB 0 MB
fs.cp + COPYFILE_FICLONE (first try) 498 MB 45.9 s, 42.1 s 548 MB (sampled on the second run only) 0 MB

The copy step on its own, warm cache, 3 runs: fs.cp 2.14 / 1.96 / 2.06 s and +548 MB each time; cp -cRp 0.91 / 0.68 / 0.64 s and +1 MB. Update wall time hardly moves because the 30 s activation stabilization window dominates it. A rollback restores with the same clone, so it pays the same again. btrfs/XFS reflinks were not measured; CI runs the Linux fs.cp path in the snapshot tests.

Disk use across updates: a successful update deletes its snapshot as soon as the new version passes the stabilization window (plugin-activation.ts), so nothing builds up. That is why "after" is 0 in every row; the cost is the peak during the update. A rolled-back update keeps its snapshot (status restored) until it is 7 days old (retainedUntil) or the server restarts (the boot GC drops snapshots from earlier processes unless a rollback is unfinished). There is no per-plugin count cap. So on a filesystem without clones, every rolled-back update adds one full copy of files/ for up to 7 days. That is an audit question in docs/api_to_audit.md; this PR adds no pruning.

Commands (output in thread storage):

  • pnpm exec turbo run typecheck lint for @bb/server, @get-bb/plugin-sdk, bb-plugin-account-pool, @bb/app, @bb/cli, @bb/templates, @bb/domain, bb-plugin-plugin-api-docs, bb-plugin-bb-guide
  • lint:type-aware for @bb/server, bb-plugin-account-pool, @get-bb/plugin-sdk
  • turbo run test for @get-bb/plugin-sdk, bb-plugin-account-pool (395), @bb/cli, @bb/templates, @bb/domain, bb-plugin-plugin-api-docs, bb-plugin-bb-guide
  • @bb/server test/services/plugins (624), @bb/app ToolsView.plugin-detail.test.tsx
  • Re-ran typecheck/lint and the Account Pool and server plugin suites after rebasing on 4e45c9b.

Not done:

  • Downgrade: if bb is downgraded after this change, Account Pool's credentials stay in files/accounts. The older Account Pool reads secrets/accounts, finds nothing, and the pool has accounts without credentials until they are added again or the folder is moved back by hand.
  • Account Pool is a builtin, and bb plugin remove account-pool is refused (HTTP 409), so the uninstall rule never deletes its credentials. Disabling it keeps them, as before.
  • Automations still builds its folder from the data.db path, and core's legacy-automations export writes plugins/automations/import. Both were left as they are because they aren't in this gap.

🤖 Generated with Claude Code

AGENT GENERATED

ymichael and others added 3 commits November 20, 2026 16:44
…irectory()

Plugins had no supported place for their own files, so Account Pool and about
22 community plugins built <dataDir>/plugins/<id>/... from
bb.server.experimental_dataDir by hand. Account Pool wrote its credentials into
core's secrets/ folder.

- bb.storage.experimental_directory() returns <dataDir>/plugins/<id>/files and
  creates it (0700) when missing. Uninstall deletes it, like secrets/; update
  snapshots copy it and rollback restores it. data.db and logs/ keep their
  current lifetime.
- One server resolver, pluginDirectory(dataDir, id, part), replaces core's
  hand-written joins for data.db, logs/, secrets/ and the snapshot code, and
  backs the new method.
- Account Pool moves secrets/accounts into files/accounts once on load,
  file by file with rename, so modes stay 0600 and a second run does nothing.
- experimental_dataDir's JSDoc is narrowed to read-only migration and path
  comparison.
- Plugin SDK 0.6.177.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fs.cp with COPYFILE_FICLONE does a full copy on macOS (libuv clones only through
Linux's FICLONE ioctl), so on darwin the snapshot uses /bin/cp -cRp, which uses
clonefile(2) and falls back to a copy by itself. Elsewhere fs.cp with
COPYFILE_FICLONE reflinks on btrfs/XFS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 2a46eee into main Nov 21, 2026
54 checks passed
@ymichael
ymichael deleted the bb/implement-plugin-storage-api-gap-5-thr_qicma3guqw branch November 21, 2026 04:05
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