Repository navigation
perf: load bb command groups on demand and split the CLI bundle (C1) - #2349
Merged
Merged
Conversation
Every bb invocation evaluated the whole 3.3 MB single-file bundle: index.ts statically imported all 17 command groups (zod, @bb/domain, server-contract, the SDK, templates, plugin-build, mime-db), so bb --version took ~200 ms against a ~20 ms node floor. Each group is now import()-ed from a static table (command-groups.ts) only when its name is the first argument, context-env and the plugin proxy load lazily, version.ts reads package.json without zod, and mime-types loads only for attachment upload. A single-file bundle alone regressed bb status/thread by ~45 ms (esbuild lazy wrappers are pre-parsed and then parsed again on first call), so the dev and packaged CLI builds are now code-split along the import() boundaries (dist/index-chunks, dist/bb-chunks; bb-app ships the chunk dir). Measured on the turbo-built artifacts: --version 197 -> 27 ms, thread --help 200 -> ~178 ms, status 268 -> ~204 ms, --help unchanged and byte-identical. Verified with new command-groups and startup-graph tests, the full @bb/cli and @bb/scripts suites, bb-app metadata test, and npm pack --dry-run listing the chunks. Co-Authored-By: Claude <[email protected]>
Review of the code-split CLI found four gaps: nothing asserted the built CLI is actually split (dropping --split kept every test green while reinstating the single-file cost on every command), the launcher's artifact check did not cover host-daemon/dist/bb-chunks (a chunkless install failed every bb call with a raw ERR_MODULE_NOT_FOUND stack instead of 'Missing bundled bb CLI chunks'), a turbo cache-hit restore can overlay a previous build's hashed chunks into the directory bb-app packs wholesale, and the only test that ran a built bundle built it single-file. A comment in index.ts also described context-env while sitting on the command-groups type import. requiredArtifactPaths now lists the bb-chunks directory; pruneUnreferencedChunks in scripts/build-utils.mjs walks the entry's chunk imports and packages/bb-app/scripts/build.mjs prunes the copied bb-chunks to what dist/bb reaches; startup-graph.test.ts also runs the turbo-built dist/index.js under the resolve hook (--version touches only shared chunk-*.js files, thread --help loads only the thread chunk) with @bb/cli#test now depending on @bb/cli#build; packaged-plugin-build.test.ts builds with --split and checks --version from the chunk dir; the CommandGroupDeps type import folds into the command-groups value import. Verified: the launcher test fails without the new artifact entry; the dist-graph cases fail against a single-file dist/index.js and pass after a --split rebuild; the --version assertion fails with PARENT_LOOKUP_MAX_DEPTH=4 and passes at 8; the prune test covers minified import shapes, a chunk cycle, sourcemaps, and a stale chunk that still imports live ones, and the helper removes nothing from the real packaged bb-chunks. turbo typecheck for @bb/cli and bb-app passes. Co-Authored-By: Claude <[email protected]>
…ndle in place Round-2 review of the code-split CLI found four gaps. The stale-chunk prune lived inside the cached bb-app#build task body, so a turbo cache-hit restore of bb-app's own host-daemon/** (which writes over the directory without clearing it) re-created the A-union-B chunk overlay that npm pack then shipped. pruneUnreferencedChunks had no floor: an entry whose chunk references the specifier regex did not recognise (a .mjs chunk extension, say) reached nothing, and every chunk was deleted with exit code 0. The new dist-graph cases in startup-graph.test.ts ran node against the shared apps/cli/dist, which @bb/scripts#test's nested turbo build rewrites in place (O_TRUNC per file) with no ordering between the two tasks, a reproducible low-frequency SyntaxError flake. And the launcher's artifact check accepted an empty bb-chunks directory, which fails the entry's static import exactly like a missing one. The prune now lives in packages/bb-app/scripts/prune-bb-chunks.mjs, run as the package's prepack hook (npm runs it for npm pack and npm publish whether or not the task body ran; it logs to stderr so npm pack --json stays parseable for smoke-tarball) and still from build.mjs after the host-daemon copy. pruneUnreferencedChunks throws when the entry reaches no chunk in the directory. startup-graph.test.ts builds its own --split bundle under apps/cli/.tmp (gitignored at every level; inside the workspace so version.ts's parent walk still resolves) with the same build-node-entry.mjs invocation as the package build, and pins the shipped build's --split flag from apps/cli/package.json; the @bb/cli#test -> @bb/cli#build turbo edge that existed only for this suite is dropped, since no @bb/cli test reads apps/cli/dist any more. ArtifactPath is a discriminated file | chunk-dir union and a chunk-dir counts as present only when it holds a .js file. The publish workflow comment that said bb-app has no prepack hook is updated. Verified: each proving test fails against the HEAD version of its source and passes after (prune floor test resolves instead of rejecting; empty bb-chunks dir did not throw; prepack metadata and npm pack --dry-run --json fixture fail without the hook; the --split guard fails with the flag removed from apps/cli/package.json). The startup-graph suite passes with apps/cli/dist moved aside. scripts/build.mjs runs end to end, and a real npm pack --dry-run --json in packages/bb-app prunes a planted stale chunk while its stdout stays pure JSON. turbo typecheck for bb-app and @bb/cli, and turbo test for @bb/cli, bb-app, and @bb/scripts (71 files) pass. Co-Authored-By: Claude <[email protected]>
The guard loads all 17 command-group modules in one test; `plugin` alone pulls the plugin build toolchain and the scaffold templates. Under vitest's 5s default that timed out on a contended CI runner (#2349). Match the 30s the sibling build/spawn tests in this directory already use. Co-Authored-By: Claude <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Aug 24, 2026
## What was wrong The parity self-test `pi/compaction reproduces its recording` fails on `main` (CI for #2346 and #2349, job `Tests (packages, ubuntu-latest, Node 22.x)`). The recording contains a steer. After the steer, pi writes the `prompt` response and then the `tool_execution_end` for `sleep 2`. One pipe read can carry both lines. The pi bridge handled a chunk in one synchronous loop: the event's delivery (`deliverInOrder`) runs one microtask hop after its line, but the steer's `input.accepted` runs several `await` hops after the response. So `item.close` went out before `input.accepted`, and the bridge's output order depended on pipe chunking. The parity replay child keeps a 50 ms gap after a response, but a starved CI runner can stall the bridge past that gap. The diff in CI shows this exactly: `turn/input/accepted` moved, and the `sleep 2` row spans seq 9–11 instead of 9–12. The other red test on `main` (`bridge.lifecycle.test.ts > a failed construction leaves no child`, #2346 only) is the pi lifecycle budget flake that #2353 addresses. ## What changed - `plugins/provider-pi/src/bridge/rpc-child.ts`: `PiRpcChild` queues stdout lines and handles one line per event-loop turn (`setImmediate`). A request's continuation finishes before the next line, which is the order a line-at-a-time read gives. - `plugins/provider-pi/src/bridge/fake-pi-rpc.mjs`: new knob `FAKE_PI_BATCH_STEER_REPLY=1` writes a steer's `prompt` response and the resumed run's first event in one stdout write. - `plugins/provider-pi/src/bridge/bridge.round2.test.ts`: regression test that pins the ack before the same-chunk event. No wire change. `HOST_DAEMON_PROTOCOL_VERSION` stays the same: only the bridge's ordering became deterministic. ## How you verified - The new round2 test fails before the change (ack at index 5, event at index 4) and passes after it. - Deterministic repro of the parity failure: a replay child patched to write the post-response line in the same write failed the `pi/compaction` cell 3/3 before the change and passed 3/3 after it. The patch was a local experiment and is not part of this PR. - `pnpm exec turbo run test typecheck --filter=./plugins/provider-pi --filter=@bb/provider-parity --force`: pi plugin 105/105, parity 56/56, typecheck clean. - Off-pipeline: real `pi` (0.84.3) slice of `@bb/agent-runtime#test:integration` (`integration.provider-basic.test.ts -t "pi provider"`): 8/8, including "steers an active turn". Fixes the `pi/compaction` parity failure on `main` (no issue filed). > AGENT GENERATED Co-authored-by: Claude <[email protected]>
ymichael
added a commit
that referenced
this pull request
Aug 24, 2026
## What was wrong The Pi lifecycle test coupled two separate contracts. To prove that a failed construction leaves no child, it requested a permanently mismatched model. Production correctly treats an initial mismatch as a transient auth race and retries eight times, so this single lifecycle assertion launched nine real Node children in series and imported the real Pi extension nine times. The test asserted only that more than one child spawned and that all children exited; it did not need nine real processes to prove cleanup. Under packages-shard contention, those avoidable serial launches crossed the harness's unchanged 60-second response deadline and produced `no response to thread/start` in the [failed packages job on PR #2349](https://github.com/get-bb/bb/actions/runs/32773414046/job/97578813957). ## What changed The retry policy and real-process lifecycle coverage are now separate: - `runPiTransientAuthConstruction` contains the unchanged production policy and accepts injected construction, discard, closed-state, and wait operations. A zero-process test deterministically proves one initial attempt plus eight retries, eight failed-attempt discards, and propagation of the ninth error. - The existing real-process transient-mismatch test still proves that a mismatched child is killed, a replacement child succeeds, and no construction-time session error leaks. - The failed-construction lifecycle test now uses a fake-Pi fault that exits before its first response. It launches one real child and still verifies the bridge error, exact spawn count, observed process exit, and no child left behind. - The scratch-file lifecycle case uses the same one-process construction failure and verifies its tool/prompt files disappear after the child exits. The earlier timeout-only changes were reverted: the shared request deadline remains 60 seconds, and the existing lifecycle wrappers remain 90 and 60 seconds. Production retry count, delay, child detachment, and error behavior are unchanged. This does not alter the host-daemon wire protocol, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged. ## How you verified Before edits, the parent and worker independently confirmed that `HEAD`, `origin/main`, and `git merge-base HEAD origin/main` all equaled `21cb6b68b8fdffe2cd576f11c8af500f98d22c11`, with a clean worktree. Exact GitHub issue/PR and bb thread searches found no overlapping lifecycle fix; PRs #2337 and #2342 cover different provider-pi signatures. The original coupled test reproduced the exact CI error under 256 CPU competitors at 61.288 seconds: `Error: no response to thread/start`. With the structural split and the original clocks restored, the identical stress command passed with 150 milliseconds of lifecycle test time (7.73 seconds total including imports). The deterministic nine-attempt policy test completes in 1–2 milliseconds. - Focused retry-policy and failed-construction coverage — 3 passed, 6 skipped - `pnpm exec turbo run test --filter=bb-plugin-provider-pi --force` — 18 files, 105 tests passed - `pnpm exec turbo run typecheck --filter=bb-plugin-provider-pi --force` — 4 Turbo tasks passed - `pnpm exec turbo run build --filter=@bb/server --force` — 4 Turbo tasks passed - `pnpm exec oxfmt plugins/provider-pi/src/bridge/rpc-session.retry.test.ts --check` — passed - `git diff origin/main --check` — passed > AGENT GENERATED: by GPT-5.6-Sol
ymichael
added a commit
that referenced
this pull request
Aug 25, 2026
## What was wrong Published `bb-app` packages retained `prepack: node scripts/prune-bb-chunks.mjs`, but the npm `files` allowlist omitted that script. The server deliberately runs `npm pack` from the installed package root to serve `/install/bb-app.tgz`, so installed servers returned HTTP 500 instead of an artifact. Shipping the script alone would still leave its workspace-relative helper import outside the package. ## What changed Removed the source-only prepack hook from the published manifest and kept stale-chunk cleanup in the existing release build, immediately after build output is copied. Extended the real tarball smoke to source-pack and install `bb-app`, repack that installed layout with npm, and verify that every live CLI chunk survives. The focused cleanup unit now invokes the build cleanup directly instead of starting another npm process, avoiding the existing timing-sensitive Vitest signature without increasing its timeout. No server/daemon wire contract, CLI surface, documentation, lockfile, or protocol version changed. ## How you verified - Red: at the introducing commit, `pnpm start:worktree` produced the source tarball; a server launched from that installed tarball returned HTTP 500 from `/install/bb-app.tgz`. Its artifact-service `npm pack` failed with `MODULE_NOT_FOUND` for the omitted prune script. - Green: `BB_PI_BRIDGE_COMMAND=/tmp/bb-pr-deliberately-missing-pi BB_PI_BRIDGE_ARGS=[] pnpm exec turbo run smoke:tarball --filter=bb-app --force --env-mode=loose` — 12/12 tasks passed, including real installed-layout repacking. - `pnpm exec turbo run test typecheck build --filter=bb-app --filter=@bb/scripts --force` — 17/17 tasks passed; bb-app 72/72 tests and scripts 120/120 tests. - `pnpm exec turbo run test --filter=@bb/server --force -- test/app/bb-app-artifact.test.ts` — 12/12 artifact-service tests passed. - Prettier and `git diff --check` passed. Fixes the packaging regression introduced by #2349. > AGENT GENERATED
ymichael
added a commit
that referenced
this pull request
Aug 25, 2026
## What was wrong The code-split CLI dynamically imported the CommonJS `undici` package and requested its named `Agent` export, but esbuild emitted that split chunk with only a default export. Every plugin-contributed command therefore failed while constructing its dispatcher, before the server-side handler ran; ordinary core commands were unaffected. ## What changed The plugin proxy now statically imports `Agent` inside its already lazy-loaded module and caches the dispatcher synchronously, preserving bundler interop without adding undici to core-command startup. The startup-graph suite now executes both a direct plugin command and `bb plugin run` from a real split artifact against a small HTTP fixture. No CLI contract, documentation, server/daemon wire behavior, or `HOST_DAEMON_PROTOCOL_VERSION` change is required. ## How you verified The new split-artifact regression test failed before the production change with `Agent is not a constructor` and passes after it. - `pnpm exec turbo run test --filter=@bb/cli --force` — 50 files, 476 tests passed - `pnpm exec turbo run typecheck --filter=@bb/cli --force` — 4 tasks passed - `pnpm exec turbo run build --filter=bb-app --force` — 11 tasks passed - Dev and packaged split artifacts both ran direct `automation --help`, explicit `plugin run automations --help`, and core `status --json` successfully Fixes #2349 > AGENT GENERATED
This was referenced Nov 25, 2026
ymichael
pushed a commit
that referenced
this pull request
Nov 25, 2026
## Human comments ## What was wrong `main()` in `apps/cli/src/index.ts` loaded, evaluated and registered all 20 core command groups and ran `addJsonShapeHelp()` before it called `tryPluginCommandProxy`. For a plugin command (`bb git`, `bb workflows`, `bb browser-automation`), `selectCommandGroups` returns every group because the first argument is not a core name, and the proxy then runs the command and exits. So every plugin command paid for code it never used: about 120 ms of CPU and 40 to 60 ms of wall time on this machine. The order is left from before #2349: at that time the proxy read the known command names from `program.commands`, so it had to run after registration. #2349 moved the names to the static `CORE_COMMAND_GROUPS` table but kept the order. I confirmed the cost with a resolve-hook trace of the built CLI (all 20 group chunks and `json-shapes` load for `bb fixture inspect x`) and with timings before I changed anything. ## What changed - `apps/cli/src/index.ts`: `main()` loads `context-env` and runs the plugin proxy first, then loads and registers the selected command groups. The proxy block moved; no code was added. When no plugin owns the name, the proxy returns and the CLI continues on the same path as before with the same groups, so the new order can cost nothing extra and cannot change the output of a core command, an unknown command or a soft alias. The proxy reads only `process.argv`, the server URL and the server response, and registration reads nothing the proxy writes (the group list is chosen from the first argument before the soft alias rewrites `process.argv[2]`). - Tests: `startup-graph.test.ts` asserts that a plugin command from the split bundle loads no core group chunk and no `json-shapes` chunk. `cli-entry-errors.e2e.test.ts` pins the error and suggestion for an unknown top-level name that no plugin owns (`bb thraed list` gives `Did you mean: bb thread?`). The existing soft alias tests (`bb host list --json`, `bb hosts --help` with the server down) and plugin help tests did not change and still pass. No wire, CLI or protocol changes. Not done: the soft alias path still loads all groups, as before. Loading only the alias target would be a separate change in behavior with a small gain, because soft aliases are rare compared to plugin commands. ## How you verified - New assertion in `startup-graph.test.ts` ("uses registered plugin help from the split artifact") against the unfixed `index.ts`: fails, 20 core group chunks loaded (`browser-*.js` through `voice-*.js`). With the fix: passes. - New e2e test for the unknown command passes before and after the change (it guards the fallback path). - Timings of the built CLI against a local fixture server, 30 runs per case, two rounds each (median): | Command | Measure | Before | After | | --- | --- | --- | --- | | `bb fixture inspect x` (plugin) | wall time | 206.5 / 228.3 ms | 165.2 / 169.9 ms | | `bb fixture inspect x` (plugin) | CPU user+sys | 321 / 304 ms | 193 / 185 ms | | `bb thread --help` (core) | wall time | 127.5 / 135.7 ms | 133.9 / 123.6 ms | | `bb --version` | wall time | 32.5 / 32.9 ms | 32.3 / 58.9 ms (noise) | The core command and `--version` rows show no change outside the noise of a shared machine. - `pnpm exec turbo run typecheck test lint lint:type-aware --continue --filter=@bb/cli`: all tasks pass (81 test files, 1438 tests). `@bb/cli` has no `lint` task. `oxfmt --check` on the changed files passes. Fixes #8174 > AGENT GENERATED
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.
What was wrong
Every
bbinvocation evaluated a single 3.3 MB bundle (an internal performance sweep, finding C1): all 17 command groups, the plugin CLI proxy,@bb/sdk,@bb/server-contract,@bb/domain(zod + ~670z.objects), templates and mime-db were imported eagerly, andversion.tsbuilt a zod schema just to readpackage.json.bb --versiontook 195 ms here (500–560 ms on the sweep's hardware) against a ~20 ms Node floor; agents drive bb in tight loops, so this compounds.What changed
apps/cli/src/command-groups.tsregisters command groups through lazyimport()loaders in the existing help order;index.tskeeps onlycommander, the re-exec shim,version.tsand the group table as static imports and loadscontext-env/ the plugin proxy on demand.version.tsnarrowspackage.jsonwith a type guard instead of zod.pluginProxyCandidatemoved next to the group table.import()boundaries: devapps/cli/dist/index.js+index-chunks/, packagedapps/host-daemon/dist/bb+bb-chunks/(scripts/build-utils.mjssplitting,build-node-entry.mjs --split,apps/host-daemon/scripts/bundle-manifest.mjs). Single-file lazy loading alone measured slower for hot commands (bb thread --help+45 ms) because esbuild's lazy wrappers are parsed twice, so splitting is required for the win. No--externalflags were added:bb-appdoes not declare undici/ws/mime-db.packages/bb-appshipshost-daemon/dist/bb-chunks;requiredArtifactPathsrequires a non-empty chunk dir (friendly error instead of a rawERR_MODULE_NOT_FOUND); unreferenced hashed chunks are pruned after the host-daemon copy and in aprepackhook, so a turbo cache-hit restore cannot ship stale chunks.Measured (Node 24, same machine, 5 runs each; baseline is HEAD's sources built with the same script):
bb --version195 → 27 ms;bb thread --help197 → 177 ms;bb status(no server, load + failed connect) 265 → 203 ms;bb --helpunchanged;bb --help,bb thread --help,bb,bb bogus,bb --versionoutputs byte-identical. Entry 3.3 MB → 43 KB minified + 34 chunks.How you verified
New tests:
apps/cli/src/__tests__/command-groups.test.ts(group selection; drift guard that every loader registers exactly the named commands in help order),startup-graph.test.ts(resolve-hook graph:--versionloads no zod/domain/sdk/server-contract/templates/context-env;thread --helploads only the thread group; a split bundle built into a temp dir uses one chunk forthreadand none for other groups),packaged-plugin-build.test.tsnow builds with--splitand asserts--versionfrom the real chunk layout,packages/bb-app/test/index.test.ts(files list, prepack prune, missing/empty chunk dir error),packages/scripts/test/build-utils.test.mjs(pruneUnreferencedChunks, refuses to prune when the entry reaches no chunk).npm pack --dry-run --jsonlistsbb+ all chunks and no stale files.On this branch:
pnpm exec turbo run typecheck(76/76),pnpm exec turbo run lint,pnpm exec turbo run test(all packages green). Not run locally:packages/bb-appsmoke:tarball(CI runs it on PRs) — please watch that job, and ideally install the packed tarball once and runbb --version,bb status,bb plugin build.Fixes: no issue — source is an internal performance sweep (finding C1).