Skip to content

Remove dead code and simplify module surfaces - #2140

Merged
SawyerHood merged 5 commits into
mainfrom
bb/remove-unnecessary-code-thr_wunnzz5n7i
Aug 21, 2026
Merged

SawyerHood merged 5 commits into
mainfrom
bb/remove-unnecessary-code-thr_wunnzz5n7i

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

What was wrong

The codebase carried a lot of code that nothing reached: symbols and files with no consumer, options that no caller passes, branches the types make impossible, feature flags that graduated but kept their if guards, pass-through wrappers that only forward arguments, barrel files that re-export hundreds of names nobody imports through them, and the same small helper copied into many files. This code has no effect on behavior, but every reader must still parse it.

What changed

Net −16k lines across 1,732 files. No behavior change. Four commits, two per pass:

  1. Remove dead code, pass-through wrappers, and stale barrels — unused symbols and files, dead branches, unused params/options, single-use wrappers inlined, dead barrel lines, tests and stories that existed only for deleted code. Drops the unused cronstrue dependency from apps/app.
  2. Drop export from module-private symbols — ~900 declarations that were exported but only used inside their own file.
  3. Remove more dead code, duplicate helpers, and unused options — second pass over the same ground plus repo-wide sweeps for duplicate helpers and legacy/compat paths. Folds byte-identical helper copies into one shared module where the consumer already depends on it (e.g. describeError ×11, createDeferred ×15 → @bb/test-helpers, DelayedLoading ×4 → @bb/shared-ui). Removes unused ws/@types/ws/tsx devDependencies from apps/connect and an unused @radix-ui/react-slot from apps/web.
  4. Drop export from more module-private symbols — ~700 more.

Out of scope on purpose: @get-bb/plugin-sdk and @bb/sdk exports (public API), CLI commands and flags, server routes, DB schema and migrations, generated code, wire payload shapes between the server and host daemon (HOST_DAEMON_PROTOCOL_VERSION is unchanged), and parsers for persisted or legacy data.

Every removal was found by one agent, adversarially verified by a second agent that searched the whole repo (including strings, configs, docs, .ladle, and stories) for any remaining reference, and then applied by a third. 41 proposals were rejected at verification or apply time, and I reverted 2 more by hand.

How you verified

Fixes #

AGENT GENERATED: by Claude Opus 5

@SawyerHood
SawyerHood force-pushed the bb/remove-unnecessary-code-thr_wunnzz5n7i branch from fad59a9 to 1540bc2 Compare August 21, 2026 04:26
SawyerHood and others added 5 commits August 21, 2026 04:36
Delete code that nothing reaches: unused symbols and files, dead
branches, options no caller passes, single-use wrappers that only
forward arguments, duplicate helpers, and barrel re-exports with no
consumer. Tests and stories that existed only for deleted code go with
it. Behavior is unchanged; every removal was checked against all
references (including strings, configs, and docs) before it was applied.

Co-Authored-By: Claude <[email protected]>
These declarations were exported but only ever used inside their own
file. Removing the keyword makes each module's real surface visible at a
glance. No runtime change.

Co-Authored-By: Claude <[email protected]>
Second pass over the codebase. Delete code that nothing reaches: options
no caller passes, branches the types make impossible, leftover feature
flags that are always on, pass-through wrappers, barrel re-exports with
no consumer, and test helpers whose only subjects were removed. Fold
byte-identical helper copies into one shared module where the consumer
already depends on it. Behavior is unchanged; every removal was checked
against all references (including strings, configs, and docs) before it
was applied.

Co-Authored-By: Claude <[email protected]>
These declarations were exported but only ever used inside their own
file. Removing the keyword makes each module's real surface visible at a
glance. No runtime change.

Co-Authored-By: Claude <[email protected]>
The public SDK .d.ts bundle that the bb-app build emits names these
types in the inferred type of publicApiRoutes, so they must stay
exported even though nothing in the repo imports them directly. The
repo typecheck runs with declaration: false and did not catch this; the
bb-app build and the tarball smoke did.

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/remove-unnecessary-code-thr_wunnzz5n7i branch from 1540bc2 to 484dc93 Compare August 21, 2026 04:38
@SawyerHood
SawyerHood merged commit 9dff424 into main Aug 21, 2026
13 checks passed
@SawyerHood
SawyerHood deleted the bb/remove-unnecessary-code-thr_wunnzz5n7i branch August 21, 2026 04:43
SawyerHood added a commit that referenced this pull request Aug 21, 2026
Pi's threshold compaction runs after agent_end and attaches its
contextCompaction item to the turn that just closed, with no second
turn/completed (#1542). isRootTurnWorkItem counted it as root work, so
every compacted pi thread flipped active and stayed there until a stop.
Compaction is provider maintenance, not agent work; exclude it at the
one shared rule so the server status, the daemon grammar, and the
runtime active-turn state all agree.

The server reopen check memoizes thread rows per event batch and evicts
a row whenever the loop applies a lifecycle change, so root items on an
active thread cost one lookup per thread rather than one per item. The
root turn/started lookup is inlined because main removed the unused
@bb/db helper in #2140.

Co-Authored-By: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 21, 2026
…, interaction split (#2124)

## What was wrong

The provider-plugin migration
([docs/provider-plugin-api.md](#2119),
design thread `thr_qs25ef3tq2`) has no shared vocabulary yet. Every
later workstream — the generic assembler (WS1a), the per-bridge
migrations (WS1b), the registry and strings (WS2a/2b), projection and
renderers (WS3), runtime recovery (WS4), the interaction split (WS5) —
needs the same types: the v3 delta grammar, `presentation`, extension
kinds, the new core item kinds, the handshake range, typed recovery, and
the approval/request split. Without one contract PR they each invent
their own and the stacks conflict.

## What changed

Types and schemas, plus the two narrow runtime pieces review asked for
(presentation carry-through, grammar-range gate). Everything is ADDITIVE
and lives beside what exists (A1 additive-then-delete: v3 is accepted
next to v2). No v3 shape is assembled yet; no existing path is deleted.

**Delta grammar v3** —
`packages/provider-bridge-protocol/src/thread-delta.ts`
- New item shapes on `deltaItemShapeSchema`: `fileRead { path, cmd? }`,
`search { mode: content|path|list, query, path?, cmd? }`, `delegation {
childRef, label, background, summary? }`, `planSteps { steps,
explanation? }`, and `extension { kind: "<pluginId>/<name>", payload }`
(its lifecycle delta must carry `presentation`). Each is documented with
the corpus motivation (Claude `Read` 7,568 calls → `fileRead`; codex
`spawnAgent`/`wait` + Claude `Agent` + `local_agent` background tasks →
`delegation`; codex `update_plan` in 295 threads + Claude
`TaskCreate`/`TaskUpdate` → `planSteps`).
- Optional `presentation` on `item.open` and `item.close`
(`deltaPresentationSchema` = the domain's
`threadEventItemPresentationSchema`: `label {pending, completed}`, `icon
{glyph}` (host glyphs only — a plugin-relative asset path cannot outlive
the plugin; a durable content-addressed form is WS3's, recorded as a G10
gap), `title?`, `detail? (≤280)`, `suppress?`, `tint? {light, dark}`).
Presentation lives in ONE place — the lifecycle delta — and is REQUIRED
there when the shape is `extension`. The `tool` shape's doc names it as
the escape hatch for generic tools. The assembler persists it: the
open's value on `item/started`; on settlement the close's value wins and
the open's survives when the close carries none (close-echo). Items that
never carried one gain no key, so v2 streams are byte-identical.
- `item.progress.snapshot` widened to `backgroundTask | delegation`.
- New thread-scoped `extension.state { extensionKind, payload }` delta
kind. Only the namespace shape is validated; the payload is opaque with
a `TODO(WS1a)` pointing at server ingest validation.
- `provider/recovery` is a bridge **notification** (`notifications.ts`),
not a delta: it is a runtime signal the way `session/replaced` and
`provider/raw` are, never persisted. `{ threadId?, kind:
sessionArchived|authRequired|restartRecommended|staleTurn|rateLimited,
message, retryable }`. No consumer yet (WS4).

**Handshake** — `handshake.ts`: `grammarVersions: [min, max]` in BOTH
directions — the runtime states the range its assembler speaks in the
`initialize` params (`ASSEMBLER_GRAMMAR_VERSIONS`, `[2, 2]` until WS1a
implements the v3 shapes), the bridge states its own in the result
(default `[2, 2]`: a silent side speaks exactly the version it
negotiated), `negotiateGrammarVersion` picks the highest common version,
and a disjoint range fails startup with the same legible error a wrong
`protocolVersion` does. `steerMode: "inject" | "queue"` (default
`"queue"`: the conservative reading, consistent with this handshake's
"absence is a definite no"; nothing branches on it yet, and every
first-party bridge now declares its real mode — `inject` for
pi/claude/codex, `queue` for ACP v1's cancel-then-prompt). Nothing
removed.

**Domain** — `packages/domain/src/provider-event.ts`,
`item-presentation.ts` (new), `provider-extension-kind.ts` (new)
- Canonical items `fileRead`, `search`, `delegation`, `planSteps`,
`extension`; optional `presentation` on every existing provider-produced
variant (`userMessage` excluded: bb authors it).
- `item/delegation/progress` and `item/delegation/completed` events,
thread-scoped exactly as `item/backgroundTask/*` (rationale recorded in
`thread-event-scope.ts`). Wired through the exhaustive switches:
`thread-event-scope.ts`, `packages/db/src/stored-event-item-fields.ts`,
`apps/server/src/internal/events.ts`, plus
`packages/thread-view/src/event-decode.ts` and the grammar checker,
which were also exhaustive.
- `CORE_ITEM_KINDS` + `CoreItemKind` with a type-level exhaustiveness
check against `threadEventItemSchema` (G4).
- `provider-types.ts`: optional `strings`,
`serviceTiers`/`reasoningLevels` (`{id,label,description?}[]`),
`extensionKinds` on `providerInfoSchema`; `ProviderRecoveryKind`.
`ProviderInfo` construction is unchanged.
- `pending-interactions.ts`: `tool_use { itemId, tool, presentation }`
approval subject added to `pendingInteractionApprovalSubjectSchema`; new
`interactionRequestPayloadSchema = user_question | plan_review |
"<pluginId>/<name>"` beside the untouched
`pendingInteractionPayloadSchema`. No producers rewired.

**Plugin SDK** — `PluginProviderDeclaration` gains
`experimental_strings`, `experimental_serviceTiers`,
`experimental_reasoningLevels`, `experimental_extensionKinds`;
`validatePluginProviderDeclaration` validates, freezes and carries them
(not silently dropped; not projected — WS2a). Audit entry in
`docs/api_to_audit.md`. `@get-bb/plugin-sdk/provider-bridge` exports the
v3 shapes/types, presentation, handshake and recovery schemas.
`docs/provider-plugin-api.md` lands here byte-identical to #2119 so the
G10 test has its subject; if #2119 merges first the rebase is a no-op.

**Mobile** — `apps/mobile/src/screens/thread/timeline/item-kind-map.ts`:
`MOBILE_ITEM_KIND_MAP satisfies Record<CoreItemKind | "extension", …>`,
so a new domain kind without a mobile decision fails to typecheck. New
kinds fall through to the existing registry fallback until WS3.

**Guardrail seeds**
- G2 `provider-contract-purity.test.ts` + committed
`provider-contract-purity.allowlist.json`: no key on the
provider-agnostic contract names a provider (segment match, so `pi` does
not trip on `capabilities`). The only allowlisted offender is
`runtimeThreadExecutionOptionsSchema.claudeCodePermissionMode` (WS2b). A
new matching key or an unused entry fails.
- G3 `grammar-version.test.ts` +
`provider-bridge-grammar.v2.snapshot.json`: a structural snapshot (every
delta kind/field, item shape/field, presentation, capabilities, method
tables) paired with `PROVIDER_BRIDGE_PROTOCOL_VERSION`, which stays at
**2** — every v3 addition is a new union member or an optional field,
which `version.ts` defines as non-bumping; the v2-deletion workstream
bumps.
- G4 type-level `CORE_ITEM_KINDS` exhaustiveness + the mobile kind map.
- G10 `packages/plugin-sdk/src/__tests__/provider-plugin-doc.test.ts`:
extracts every ```ts block from the doc and maps each field onto the
real contract (zod keys at runtime, interface keys via `satisfies`) or
an explicit `{ gap: "WS…" }`; a gap that lands fails, and a doc edit
fails until the map is updated. Full compilation of the blocks is left
as a TODO for stabilization because the doc's blocks are target-state
pseudo-code (`bb.providers.register`, `app.slots.timelineRenderer`,
`TimelineRow { kind, payload, presentation }` do not exist yet). No new
dependency was added.

**"Unsupported until WS<n>" stubs** (for the coordinator to track; every
one is an explicit case, never a silent default):
- WS1a — `packages/agent-runtime/src/delta-assembler.ts`:
`UnsupportedDeltaShapeError` thrown for every v3 shape in
`shapeMatchesItem` (L717), `buildOpenedItem` (L874),
`buildClosedItemFromShape` (L1053), the delegation `item.progress`
snapshot (L1406), and the `extension.state` delta (L2028).
- WS5 — throws:
`apps/server/src/services/interactions/pending-interaction-timeline.ts`
L447 and L507; `plugins/provider-codex/src/interactive-requests.ts`
L266; `plugins/provider-claude-code/src/interactions.ts` L300;
`packages/agent-runtime/src/test/runtime-integration-harness.ts` L740.
- WS5 — declarative-base rendering of `tool_use` from its `presentation`
(explicit `case "tool_use"`, marked "Declarative base only"):
`packages/core-ui/src/pending-interaction-formatting.ts` L190,
`packages/core-ui/src/pending-interaction-presentation.ts` L54,
`apps/app/.../ThreadPendingInteractionBanner.tsx` L400,
`apps/server/src/internal/interactive-requests.ts` L45,
`apps/mobile/src/data/interactions/approval-presentation.ts` L81,
`apps/cli/src/commands/thread/interactions.ts` L137 and L258.
- WS3 — `apps/mobile/src/screens/thread/timeline/item-kind-map.ts`:
`fileRead`, `search`, `planSteps`, `delegation`, `extension` are `{
fallback: "WS3 …" }`.

**`HOST_DAEMON_PROTOCOL_VERSION` is bumped to 147.** The daemon wire
carries `threadEventSchema` and `pendingInteractionCreateSchema`, and
this PR widens both: new union members (item kinds, `item/delegation/*`
event types, the `tool_use` subject) and an optional field
(`presentation`). An older daemon never emits any of them and nothing in
this version produces them, so compatibility is believed preserved in
both directions — but the repository rule is to bump rather than ship a
widened wire on an untested assumption, and the mismatch moves enrolled
machines onto a daemon whose runtime also negotiates the delta grammar
range. `PROVIDER_BRIDGE_PROTOCOL_VERSION` stays at 2 per `version.ts`
("Additive changes … do NOT bump the version"); the grammar itself is
negotiated through `grammarVersions`. The daemon contract's
optional-field allowlist
(`packages/host-daemon-contract/test/contract.test.ts`) gained the four
`tool_use` presentation fields with their omission semantics.

Not done here, by design: no assembly of the v3 shapes, no projection,
no `ProviderInfo` projection from the new declaration fields, no
producer of `tool_use`/`plan_review`/extension requests, no
event-pruning trigger for `item/delegation/progress` (WS1a adds it with
the producer). The only runtime behavior added is the narrow
presentation carry-through and the grammar-range gate above, both raised
by review.

## How you verified

- `pnpm exec turbo run typecheck` — **74/74 packages green** (covers
provider-bridge-protocol, domain, server-contract, plugin-sdk,
agent-runtime, server, app, mobile, host-daemon-contract, cli, core-ui,
thread-view, db, and the three provider plugins).
- `pnpm exec turbo run test --force` piped to a file for every package
with new or affected tests, all green:
`@bb/domain` 148 · `@bb/provider-bridge-protocol` 114 ·
`@get-bb/plugin-sdk` 126 · `@bb/agent-runtime` 427 ·
`@bb/host-daemon-contract` 52 · `@bb/server-contract` 58 · `@bb/core-ui`
17 · `@bb/thread-view` 379 · `@bb/db` 406 · `@bb/mobile` 833 · `@bb/cli`
453 · `bb-plugin-provider-codex` 172 · `bb-plugin-provider-claude-code`
263 · `bb-plugin-provider-acp` 181. CI runs the server and app suites.
- New tests (fail before, pass after):
`packages/domain/test/provider-event-v3-items.test.ts`,
`packages/domain/test/interaction-split.test.ts`,
`packages/provider-bridge-protocol/src/thread-delta-v3.test.ts`,
`packages/provider-bridge-protocol/src/contract-tests/{provider-contract-purity,grammar-version}.test.ts`,
`packages/plugin-sdk/src/__tests__/{provider-plugin-doc,provider-declaration-v3}.test.ts`,
`apps/mobile/src/screens/thread/timeline/item-kind-map.test.ts`.
- Existing suites are untouched-green: the assembler's exhaustive
switches gained throwing v3 cases, and presentation is attached only
when a delta carries one, so every existing v2 stream assembles
byte-for-byte as before (new assembler tests cover open, close-echo,
close-wins, dual-settle, and the no-key v2 path; new adapter tests cover
the grammar-range gate).

**Review round (SlopCop, 5 findings, all addressed in commits
`acd4225`…`6ed9bf1`):** presentation persisted by the assembler; two-way
grammar negotiation with a startup gate; `HOST_DAEMON_PROTOCOL_VERSION`
→ 147; one presentation location (required on the delta for `extension`
shapes); persisted icons glyph-only with the asset form recorded as a
WS3 gap.

Rebased over #2140 (`9dff42407`, "Remove dead code and simplify module
surfaces"). Conflicts in `provider-event.ts`, `pending-interactions.ts`,
`notifications.ts` resolved by the rule "restore `export` only on
symbols another package imports; otherwise accept the de-export; keep
every v3 member". Restored export on **0** symbols: everything the v3
grammar, bridge kit and SDK surface import cross-package
(`threadEventPlanStepSchema`, `providerRateLimitStateSchema`,
`threadEventItemStatusSchema`, …) was still exported on `main`; the only
breakage was this PR's own same-package test importing two now-private
approval schemas, rewritten to parse through the public
`pendingInteractionPayloadSchema`. The new `itemPresentationField`, the
`tool_use` subject and the request family sit beside #2140's private
`threadEventWebSearchItemSchema`,
`pendingInteractionApprovalSubjectSchema` and
`AnyPendingInteractionPayload`; #2140's removal of the unused
`ProviderRawNotification` type is kept. Verified after the rebase:
typecheck green for domain, provider-bridge-protocol, plugin-sdk,
agent-runtime, server, thread-view, core-ui, mobile, app, cli,
host-daemon-contract and the three provider plugins; tests green for
domain 146, provider-bridge-protocol 114, plugin-sdk 126, agent-runtime
423, host-daemon-contract 52, core-ui 17.

`@get-bb/plugin-sdk` is bumped 0.4.10 → 0.4.11 (top commit, via
`scripts/bump-plugin-sdk.mjs --patch`, both version files together):
0.4.10 is published, and this PR widens the SDK's public surface
(`provider-bridge.ts` v3 exports, `backend-contract.ts` declaration
fields), so the npm version guard requires a new version.
`check-npm-version-guard.mjs` passes locally.

Part of the provider-plugin migration; no single issue. Target doc:
#2119.

> AGENT GENERATED: by Claude Opus 5

---------

Co-authored-by: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 21, 2026
…rdings, and the parity harness (#2153)

Stacked on #2136 (WS1a,
`bb/ws1a-assembler-testing-kit-stack-on-2124-thr_jkbj56vr97`), itself
stacked on the contract #2124. Landing order: contract → WS1a → this →
WS2a → #2121 → codex → claude.

**Why stacked, not independent.** `@bb/provider-parity` and the three
`bridge.recorded-conformance.test.ts` files import
`createBridgeDeltaEventCollector`, which lives at
`@bb/agent-runtime/test/bridge-delta-assembly` on `main` and at
`@bb/provider-bridge-protocol/testing` on WS1a. No ordering of two
independent PRs yields a buildable `main`, so this PR follows the move
(and drops `provider-parity`'s `@bb/agent-runtime` dependency). The
recorded `bridge→runtime` lanes are grammar v2, which WS1a's v3-only
assembler refuses, so every replayable cell now also carries a
`bridge→runtime.current.ndjson` written by `pnpm --filter
@bb/provider-parity rerecord --plan-with <main checkout>` through this
branch's bridges; they assemble to the **unchanged** pins in
`row-counts.json`. The 10 pi cells (in-process SDK, not replayable) keep
their pins and are reported, not failed.

**Do not merge.** Coordinator reviews, Sawyer merges the stack.

## What was wrong

The provider-plugin migration will break byte-equivalence with today's
translators on purpose, which removes the regression oracle the goldens
provide. Calibration sessions are scripted fakes and the integration
suite runs a fake adapter, so nothing checks a bridge against what the
provider CLIs really emit across the behavior matrix. Design:
"Regression confidence" (A2, A3) and "Corpus" in the ideal-state
provider API spec. No bridge may migrate before this lands.

## What changed

**Bridge record mode** (`BB_PROVIDER_BRIDGE_RECORD_DIR`, off by default,
additive)
- `bridge-worker-entry.ts` tees both sides of the runtime wire for every
bridge, first- or third-party, before the bridge module loads.
- Bridges tee their provider child with
`experimental_recordProviderChildIo(child, { threadId })` (codex
`app-server-connection.ts`, acp `agent-connection.ts`). Claude's pipe
belongs to the Agent SDK, so `sdk-session.ts` takes the SDK's
`spawnClaudeCodeProcess` seam over when
`experimental_isProviderBridgeRecording()`. Pi runs in-process and
records its SDK event boundary (`AgentSessionEvent` in,
prompt/abort/compact out).
- Layout `<dir>/<providerId>/<threadId>/<direction>.ndjson` (`_process`
for lines that belong to no thread); one `{ts, run, seq, dir, line}` per
line, appended per line, never buffered. Responses land in the scope of
the request they answer. `run` identifies the bridge process so a thread
served by several processes merges back in order.
- The daemon forwards the variable from its own env (not the shell env,
which doubles as the agent's shell environment); the runtime appends the
provider id. `withoutBridgeRuntimeEnv` and the existing `BB_*` allowlist
both strip it from provider children.
- Docs: `docs/provider-bridge-protocol.md` ("Record mode"),
`docs/debugging-and-qa.md`, `docs/configuration.md`,
`docs/api_to_audit.md` (both new `experimental_` SDK members).

**Recordings** — 52 redacted cells under
`packages/provider-bridge-protocol/recordings/<provider>/<cell>/` with a
`manifest.json` each (provider, cell, CLI version, date, description,
lane line counts). `scripts/provider-recordings/redact.mjs` rewrites
paths under `$HOME`, emails, `ls -l` owner columns, token shapes
(`bbde_`, `ghp_`, `github_pat_`, `sk-`, `sk-ant-`, `xox?-`, `bbcm_`,
JWTs, bearer values, `Authorization` headers), secret-shaped env keys,
collapses Claude's `system/init` and `control_response` catalogs to
names, and trims strings over 2,000 chars to head/tail with a marker. It
is idempotent and exits 3 if any pattern survives. `package-cells.mjs`
cuts the raw per-thread recordings into cells. Raw recordings stay in
`~/.bb/provider-recordings/raw` (gitignored).

**Parity harness (A2)**
- `@bb/provider-bridge-protocol/testing/parity`: `replayRecording`
drives the recorded `runtime→bridge` lane into a bridge process and
`replay-provider-child.mjs` plays the provider lanes back as the
bridge's child — the recording *is* the script. The child gates each
recorded provider line on the live bridge's own writes (method/subtype
for requests, id for responses), maps bridge-minted ids to recorded
ones, cuts the lanes into one segment per spawned child, paces
spontaneous lines behind the harness's cursor so steers and interrupts
land between the same two provider lines they did live, and never hangs
a divergent bridge (stall → generic answer, logged). Serves JSON-RPC
(codex, ACP) and the Claude CLI control protocol. Each replay runs in
its own temp workspace and (for Claude) its own `CLAUDE_CONFIG_DIR`,
with a seeded source transcript per recorded `thread/fork`, so
recordings replay on any machine.
- `compareParity(old, new, allowlist)` diffs normalized events (the
resurrected `diffCalibrationStreams`, `#2140` had removed it),
normalized rows, and grammar drops. Allowlist entries are
`{provider|"*", cell|"*", layer, path (JSON pointer with `*`/`**`), pr,
reason}`; an entry that masks nothing is reported stale and fails.
- `@bb/provider-parity` wires the real delta assembler and
`@bb/thread-view` projection (mirroring `timeline.ts`), owns `pnpm
parity --old <checkout> --new . [--provider] [--cell] [--dump-dir]`, and
loads each leg's assembler and projector from that leg's own checkout
(its `@bb/provider-parity`, else the collector at its pre/post-WS1a
home), so a `main` `--old` leg assembles with `main`'s assembler.
- `parity.self.test.ts` (CI): every cell assembles to the counts pinned
in `recordings/row-counts.json` (events, rows; `provider/unhandled` and
grammar drops may only go down — G11), every allowlist entry names a PR,
reason, and pointer (staleness is judged by `pnpm parity --old <main>`,
which an old==new replay cannot), and every replayable cell replays
through the current bridge with zero event/row/grammar diffs and zero
stalls. `UPDATE_PARITY_ROW_COUNTS=1` rewrites the pins deliberately.

**Current bridge lanes (merged from #2177, reviewed as harness owner)**
— a recording is never rewritten. When a bridge change alters what the
bridge emits, `pnpm --filter @bb/provider-parity rerecord [--plan-with
<recording-time checkout>]` writes `bridge→runtime.current.ndjson`
beside the recorded lane; the self-suite and recorded conformance
pin/compare against it when present, and `pnpm parity` paces the old leg
from the recorded lane and the new leg from the current one. Also from
#2177: `pnpm parity --dump-dir`, a 300 ms drain before each replayed
runtime request and a 50 ms gap after a replayed response (the steer-ack
position race seen twice in CI). Two follow-ups on top: the harness's
own `initialize` response is kept out of re-recorded lanes, and
re-recorded lanes pass through `redact.mjs` before they are written (a
bridge error can quote the replay child's command line). 39 current
lanes are committed (every replayable cell) — see "Why stacked" above.

**Conformance** — `checkRecordedCellReplay` + `replayRecordedCells` add
the recorded-traffic scenario set (`recorded/<cell>/{replays,
events-schema-valid, grammar, turn-lifecycle, not-empty}`); each
first-party bridge gets `bridge.recorded-conformance.test.ts` over turn,
steer, stop, approval allow/deny, question, resume, fork.

No translation behavior change. No wire change;
`HOST_DAEMON_PROTOCOL_VERSION` is untouched.

## How you verified

On the stacked head `39066e19b` (WS1a base), one Turbo invocation at a
time at `--concurrency 4`: typecheck 12/12 tasks (protocol, parity,
agent-runtime, host-daemon, plugin-sdk, codex, claude-code, acp); tests
— protocol 218, codex 173, claude-code 262, acp 182 (each
`bridge.recorded-conformance.test.ts` green), parity self-suite 43/43
with `row-counts.json` untouched; `pnpm parity --old . --new .` 39
passed / 0 failed / 13 skipped; `pnpm rerecord --plan-with
/home/sawyer/projects/bb` 39 OK / 0 STALL; redaction sweep over
recordings + current lanes `0 survivors`, idempotent.

Earlier, on the `main`-based head `0923c1c59` (after merging #2177): CI
green (Checks, Package Smoke ×2, Tests app-1/2/3, integration, packages,
server); 21/21 Turbo tasks, 1,848 tests (protocol 101, parity 43,
agent-runtime 418, host-daemon 552, plugin-sdk 117, codex 173,
claude-code 262, acp 182); the steer/stop-interrupt cells stable across
3 repeated runs. New tests in this PR: recorder routing/tee/oversize,
worker-entry record tee, `withoutBridgeRuntimeEnv` strips the knob,
daemon forwards it to bridge processes but not the shell env, the
43-test parity self-suite, three recorded-conformance suites.

An earlier CI run on `main` failed in `packages` because ACP and Claude
replays depended on the recording machine (`cwd`, `~/.claude`
transcripts for `forkSession`, `PATH`); reproduced locally with the
directory moved away and a bare `HOME`, fixed as described above.

**Matrix** (`codex-cli 0.149.0`, `Claude Code 2.1.238` / Agent SDK
0.3.197, `cursor-agent 2026.08.11`, pi `@earendil-works/pi-coding-agent
0.84.0`, recorded 2026-08-21 through `scripts/bb-dev-app` + the `bb`
CLI):

| cell | codex | claude-code | acp-cursor | pi |
| --- | --- | --- | --- | --- |
| 1 turn (shell + edit + read) | ✅ | ✅ | ✅ | ✅ |
| 2 steer mid-turn | ✅ | ✅ | ✅ | ✅ |
| 3 stop mid-turn, new turn | ✅ | ✅ | ✅ | ✅ |
| 4 approval allow | ✅ | ✅ | ✅ | ⛔ pi has only `full` mode; nothing asks
|
| 4 approval deny | ✅ | ✅ | ✅ | ⛔ same |
| 5 user question | ✅ (bb tool) | ✅ (`AskUserQuestion`) | ✅ (bb tool) |
✅ (bb tool) |
| 6 subagent / delegation | ✅ (native `subAgentActivity`) | ✅ (`Agent`)
| ✅ (bb delegation) | ✅ (bb delegation) |
| 7 resume after `thread stop` | ✅ | ✅ | ✅ | ✅ |
| 8 fork | ✅ | ✅ | ✅ recorded as the agent's refusal: `cursor-agent`
advertises no `session/fork` (0 events, pinned) | ✅ |
| 9 plan mode | ✅ (`/plan` command mention) | ✅
(`claudeCodePermissionMode: plan`, plan approval interaction) | ⛔ no
plan command | ⛔ no plan command |
| 10 model list | ✅ (`_process` scope) | ✅ | ✅ | ✅ |
| 11 web search / fetch | ✅ (`webSearch` item) | ✅ (`WebSearch` +
`WebFetch`) | ✅ (Web Fetch tool) | ✅ (curl fallback; pi has no web tool)
|
| 12 compaction | ✅ | ✅ | ⛔ server 409: provider does not support manual
compaction | ✅ |
| 13 archived session resume | ✅ (archived natively via app-server
`thread/archive`; bridge unarchives and retries) | n/a | n/a | n/a |
| 13 empty rollout | ✅ (0-byte rollout → `failed to read session
metadata`) + bonus `missing-rollout` | n/a | n/a | n/a |
| 13 auth failure | ✅ real 401 ×11 via empty `CODEX_HOME` | ✅ "Not
logged in" via empty `CLAUDE_CONFIG_DIR` | ⛔ not attempted: no
config-dir knob to point at an empty store without touching the real
login | ⛔ not attempted: pi's keys live in its own config; no safe
override |
| 13 429 | none occurred naturally (not forced) | — | — | — |

**Redaction sweep** (`node scripts/provider-recordings/redact.mjs
packages/provider-bridge-protocol/recordings /tmp/redact-stack`):
```
redacted 241 recording files into /tmp/redact-stack (home=/home/sawyer → /home/user); 0 survivors
```
`diff -rq` between the committed fixtures (recordings + current lanes)
and that output is empty (idempotent). The only remaining occurrence of
the username is the public skill name `bb-global-skills:sawyer-voice` in
Claude's advertised skill catalog.

**Parity self-run** (`pnpm parity --old . --new .`): `39 passed, 0
failed, 13 skipped (52 cells)` — the 13 skips are the 3 process-scoped
`model-list` cells (no thread events) and the 10 pi cells (in-process
SDK, no child to replay; still pinned and assembled by the self-suite).
Every PASS line reports identical old/new counts, e.g. `codex/steer: old
87 events/3 rows, new 87 events/3 rows, unhandled 0→0, grammar drops
0→0`. The cross-checkout path was exercised too: `--old
/home/sawyer/projects/bb` (on `main`, no `provider-parity` package)
loaded that checkout's `@bb/agent-runtime` collector and bridge and
matched on all 16 codex thread cells.

**Sizes**: recordings 6.9 MB total including the 39 current lanes (6.2
MB without) — codex 1.6 MB, claude-code 1.2 MB, acp-cursor 932 KB, pi
2.5 MB recorded; largest cell `pi/turn-tools` 828 KB.

Fixes none (step-0 PR of the provider-plugin migration).

> AGENT GENERATED: by Claude Opus 5

---------

Co-authored-by: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 21, 2026
## What was wrong

`InlineVisDirective` in `plugins/inline-vis/app.tsx` starts in `loading`
and stays there until the `prepareHtmlPreview` RPC resolves. The loading
branch rendered a bare one-line "Loading visualization…" box with no
height (37px in the app). The ready branch renders a header plus an
iframe whose inline height comes from the directive's `height` attribute
(default 224px, min 120px). The card therefore grew by hundreds of
pixels in one React commit (measured 37px -> 515px for `height="480"`).
The thread timeline is bottom-anchored, so that growth scrolled every
earlier message upward on every mount of the directive, not only on cold
loads. The preview height is known synchronously from the attributes, so
the final geometry was knowable in the loading state; it just was not
used.

Issue: #1837. Report: https://get-bb.github.io/reports/issues/1837.html

## What changed

- `plugins/inline-vis/app.tsx`: extracted the card chrome (outer card +
header row) into a small `PreviewCard` so the loading and ready states
cannot drift. The loading branch now renders that card with a `size-5`
spacer where the open-in-sidebar button goes, and a `role="status"` /
`aria-busy` / `aria-label="Loading visualization <file>"` container with
`style.height = previewHeight` holding a plain `<Skeleton
className="size-full" />` from `@bb/shared-ui/skeleton`. The ready
branch is unchanged except for using `PreviewCard`.
- `plugins/inline-vis/app.test.tsx`: new test pins the behaviour (loader
height equals the iframe height, same card/header classes, status role
and label); the existing sandbox test now finds the loader by role
instead of the removed text.
- Error, missing-file, and invalid-height branches still render compact
alerts; loading -> error shrinks the card, which is acceptable for an
error path and out of scope here.
- No server, wire, CLI, or doc changes. App-side plugin UI only.

Relation to #1555: that PR also reserves the height, but it duplicates
the header markup, uses `.animate-shine-icon` inside an `aria-hidden`
grid, which `theme.css` pauses since #1880 (so its advertised shimmer is
frozen in the app), and its ~100-line test pins data attributes and
class names rather than behaviour. It also predates #2140, which removed
the `PrepareHtmlPreviewRpcResult` type it touches. This PR is the
~20-line version the report recommends: shared header, fixed-height
`Skeleton` with its built-in pulse (verified running in the app), and a
behaviour-only test.

## How you verified

- New test fails on `origin/main` `app.tsx` (`git checkout origin/main
-- plugins/inline-vis/app.tsx`, then `pnpm exec vitest run app.test.tsx`
in `plugins/inline-vis`):
  ```
× reserves the preview height while loading so the timeline does not
jump
  AssertionError: expected '' to be '480px' // Object.is equality
  ```
- On this branch, from the committed tree (`git status --porcelain`
empty): `pnpm exec turbo run typecheck test
--filter=bb-plugin-inline-vis --force` -> `Tasks: 6 successful, 6
total`, `Tests 17 passed (17)`.
- Manual repro in a dev instance (`scripts/bb-dev-app current`,
claude-code turn that replied with `::inline-vis{file="demo.html"
height="480"}`), holding the `prepareHtmlPreview` request in headless
Chrome and measuring the card before and after release:
- main `app.tsx`: loading `boxHeight: 37` -> ready `boxHeight: 515`,
`deltaHeight: 478`; the user message above moved from `top: 75` to `top:
17`.
- this branch: loading `boxHeight: 515` -> ready `boxHeight: 515`,
`deltaHeight: 0`; user message stays at `top: 17`; skeleton
`animationName: pulse`, `playState: running`.

Fixes #1837

> AGENT GENERATED: by Claude Opus 5


## Independent verification

Checked out `140e23e7f` (`git fetch origin
bb/fix-1837-inline-vis-layout-jump && git checkout -b verify-1837-r1
FETCH_HEAD`); `origin/main` is an ancestor, GitHub reports `MERGEABLE`.
Diff: `plugins/inline-vis/app.tsx` + `plugins/inline-vis/app.test.tsx`
only, +117/-17.

Fail-before: `git checkout origin/main -- plugins/inline-vis/app.tsx`,
then `pnpm exec vitest run app.test.tsx` in `plugins/inline-vis`:

```
FAIL app.test.tsx > InlineVisDirective > reserves the preview height while loading so the timeline does not jump
AssertionError: expected '' to be '480px' // Object.is equality
Tests  2 failed | 5 passed (7)
```

(The second failure is the existing sandbox test, which now looks the
loader up by `role="status"` name.)

Pass-after: restored `app.tsx` from the PR head (`git status
--porcelain` empty), `pnpm exec vitest run app.test.tsx` -> `Tests 7
passed (7)`. `pnpm exec turbo run typecheck test
--filter=bb-plugin-inline-vis --force` -> `Tasks: 6 successful, 6
total`, `Tests 17 passed (17)`.

Repro on the fixed branch: own dev instance (`scripts/bb-dev-app
current`, app :13647 / server :21647), scratch project with `demo.html`,
real claude-code turn replying `::inline-vis{file="demo.html"
height="480"}`. Headless Chrome via doobie held the `prepareHtmlPreview`
RPC, measured the card, released it, measured again:

```
before: state=loading cardHeight=515 innerHeight=480 userMsgTop=17 role=status label="Loading visualization demo.html" skeleton animation=pulse playState=running
after:  state=ready   cardHeight=515 innerHeight=480 userMsgTop=17
deltaHeight: 0, userMsgShift: 0
```

The report measured 37px -> 515px (delta 478) for the same scenario on
main. The issue no longer reproduces.

CI: all required checks green on `140e23e7f` (Checks, Tests app-1/2/3,
integration, server, packages, Package Smoke ubuntu/macos, version
check).

Residual risks: error / missing-file / invalid-height branches still
render compact alerts, so loading -> error shrinks the card (error path,
out of scope). The loader no longer shows visible "Loading
visualization" text; it is conveyed through `role="status"` +
`aria-label`. No wire, CLI, or plugin-API surface changed, so no
protocol bump or doc update is required.

> AGENT GENERATED: by Claude Opus 5

Co-authored-by: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 21, 2026
## What was wrong

A forked thread came up with an empty timeline (#1500, report:
https://get-bb.github.io/reports/issues/1500.html). The provider cloned
the source session, so the model held the whole conversation, but
nothing in the fork path (`thread-fork.ts` -> `thread-create.ts`
`resolveForkDescriptor` -> `thread.start{fork}`) ever wrote that
conversation into the fork's events, and the timeline is a projection of
a thread's own events. The same path also ignored `sourceSeqEnd` for the
model: it only looked up which provider session was current at that
sequence (`getProviderThreadIdAtOrBeforeSequence`) and never mapped it
to the `providerCheckpointId` recorded on that turn's `turn/completed`.
`thread.start.fork` had no checkpoint field, so pi, claude-code, and
codex always cloned the session tip regardless of the requested anchor,
and the app's per-message Fork button and `bb thread fork
--source-seq-end` promised a branch point they did not deliver.

## What changed

- `apps/server/src/services/threads/thread-fork-history.ts` (new):
resolves a fork point. With `sourceSeqEnd` the anchor is the completed
root turn that contains the sequence (or the last one before it, so a
user-message row anchors before its own turn, like editing it). The
point carries the session to clone, that turn's checkpoint
(`resolveTurnProviderCheckpointId`, shared with edit-message including
the legacy codex turn-id fallback), and the sequence of its
`turn/completed`. It rejects with 400 `fork_source_session_unavailable`
when the anchor is before the first turn, inside a turn that has not
completed, has no checkpoint, or is earlier than the latest turn on a
provider without `supportsSessionRewind` (tip-only, e.g. ACP) instead of
silently forking the tip.
- Tip forks (no `sourceSeqEnd`) inherit every completed root turn. When
the source is idle the fork clones the session tip. When the source is
mid-turn, its session tip already holds the running turn's prompt and
partial output while the inherited timeline stops at the last completed
turn, so a checkpoint-capable provider now clones through that last
completed turn's checkpoint instead; tip-only providers keep the tip
clone. This addresses the reviewer's point that model context and
timeline diverged in that window.
- `thread-create.ts`: a visible fork copies the source's conversation
rows (`client/turn/requested` with its acceptance, `turn/started`,
`turn/input/accepted`, `item/completed`,
`item/backgroundTask/completed`, `turn/completed`, `thread/compacted`,
`system/manager/user_message`) through that sequence into the fork
before its own thread-start rows, so inherited history takes the lowest
sequences. Only turns that completed inside the window come along.
Copied rows keep their payload and `created_at`, take fresh ids and
sequences, index search segments, and carry a null `provider_thread_id`
column so the fork's live session stays the one its own
`thread/identity` names. Hidden forks (side chats, plugin workers
rendered by their owner next to the source) still clone the session but
keep their own timeline empty; this also keeps the side-chat plugin's
empty-fork sweep from seeing inherited user messages as user work.
- Side-chat behavior change (plugin code untouched): the plugin passes
the anchored message's `sourceSeqEnd` to `threads.fork`. On main that
anchor only chose a provider session id, so pi/claude-code/codex side
chats always cloned the tip. Now a side chat anchored on an earlier
completed turn gets a checkpoint fork whose model context ends at that
turn, which is what the plugin's own comments describe. An anchor inside
a running turn, or an earlier turn on a tip-only (ACP) provider, returns
`fork_source_session_unavailable`, which the plugin already handles by
falling back to a tip fork (`plugins/side-chat/server.ts`, covered by
its existing tests).
- `packages/db/src/data/events.ts`:
`copyStoredThreadEventsInTransaction`, `findLastRootStoredTurnStarted`,
`findLastCompletedRootStoredTurn`; removes the now-unused
`getStoredProviderThreadIdAtOrBeforeSequence`. The row copy reads the
selected source rows into memory once (one bounded typed query per
inherited type) because each copy is re-parsed to index search segments;
the in-memory filter only drops the few rows of turns or queued requests
still open at the window's end. Large source threads pay that memory and
duplicate storage per fork.
- Wire: `thread.start.fork.sourceProviderCheckpointId?: string` in
`@bb/host-daemon-contract` (absent = tip, matching the bridge protocol's
`thread/fork`), forwarded by `packages/agent-runtime/src/runtime.ts` to
the adapter's `thread/fork`. **`HOST_DAEMON_PROTOCOL_VERSION` 152 ->
153** (146 -> 147, then 151 -> 152, before two rebases onto a moving
main). An older daemon would strip the field and clone the tip.
- `thread-edit-message.ts`: uses the shared
`resolveTurnProviderCheckpointId` instead of its inline codex fallback
(no behavior change).
- CI guard (provider-literal ratchet): `resolveTurnProviderCheckpointId`
stays in `thread-edit-message.ts` as an export and
`thread-fork-history.ts` imports it from there, instead of moving it
into `thread-events.ts`, which would have given that file a new
`"codex"` literal; `scripts/provider-literal-baseline.json` is
regenerated for the resulting decrease (`thread-edit-message.ts` 2 -> 1,
total 148 -> 147).
- Docs/CLI: `--source-seq-end` help text in `bb thread fork` / `bb
thread spawn`, `bb-guide-threads.md`, the bb-cli SKILL,
`docs/provider-bridge-protocol.md`, and the
`forkThreadRequestSchema.sourceSeqEnd` doc now describe the
turn-anchored semantics.

Deviation from the issue: the issue also floats an `events.append` /
"adopt session" SDK API (#1028). Not done here; copying at fork time
covers the fork case with no new plugin surface. The choice to skip
history for hidden forks is a server policy decision; an explicit
request knob can be added later if a hidden fork ever needs inherited
history.

Revision after review: `copyForkSourceHistory` was declared `: number`
with a bare `return;`, which failed `@bb/server` typecheck and the CI
Checks job; it returns `void` now (its caller never read the count). The
mid-turn tip fork behavior above is new in this revision. Rebased onto
current main (resolved against #2140's dead-code removal in `@bb/db` and
`thread-create.ts`).

## How you verified

New tests in `apps/server/test/public/public-thread-fork.test.ts` ("fork
branch point and inherited history": checkpoint + inherited conversation
for an anchor on an assistant message, a user-message anchor branching
before its turn, idle tip fork inheriting every completed turn, mid-turn
tip fork branching at the last completed turn's checkpoint with nothing
of the running turn, a mid-turn tip fork on a tip-only provider cloning
the tip, hidden fork inheriting nothing, rejections for
running-turn/pre-first-turn anchors, tip-only provider accepting only
its latest turn) plus checkpoint assertions in
`thread-create-seed-without-run.test.ts` and
`public-thread-fork.test.ts`'s existing fork-point test.

Fail before (the 14 non-test source files checked out from
`origin/main`, new module removed, tests from this branch): 10 failed,
e.g.

```
AssertionError: expected { Object (sourceProviderThreadId) } to deeply equal { …(2) }
AssertionError: expected [] to deeply equal [ 'Reply only with ok.', 'ok', …(2) ]
AssertionError: expected 201 to be 400 // Object.is equality
```

Pass after, on the rebased head: `pnpm exec turbo run typecheck` for
server, agent-runtime, host-daemon-contract, db, host-daemon, sdk, cli,
server-contract, templates green (12/12 tasks). `pnpm exec turbo run
lint` green. `pnpm exec turbo run test --filter=@bb/server`: 1829
passed, 2 failed, both unrelated (the known local umask-only
`internal-skill-trees` 0644-vs-0664 assertion, and a 5s timeout in
`plugin-update.test.ts` under parallel load that passes alone, 27/27).
`@bb/host-daemon` 551, `@bb/agent-runtime` 418, `@bb/cli` 453,
`@bb/host-daemon-contract` 52, `@bb/server-contract` 58, `@bb/db` 405,
`@bb/templates` 41, `bb-plugin-side-chat` 29, all passed.

Manual repro on an own dev instance with the pi provider on the rebased
head (two cheap turns "ok" / "second"; `turn/completed` at seq 15
recorded checkpoint `32261d5c`):

- `bb thread fork <src> --workspace reuse` -> `bb thread log` shows all
four inherited messages.
- `bb thread fork <src> --workspace reuse --source-seq-end 13` (turn 1's
assistant message) -> log shows "Reply only with ok." / "ok" only; the
fork's pi session file has `parentSession=<src>` and only turn 1's user
and assistant entries (checkpoint inclusive).
- `--source-seq-end 3` -> `HTTP 400: Cannot fork at sequence 3: no turn
has started at or before it`.
- Mid-turn: started a third turn that runs `sleep 40`, forked at the tip
while `turn/started`=3 and `turn/completed`=2. The fork's log shows the
four completed messages; its pi session file has `parentSession=<src>`
and only turns 1-2, while the source's session already held turn 3's
prompt and its bash tool call.

Fixes #1500

> AGENT GENERATED: by Claude Opus 5



## Independent verification

Verified round 2 at head `96289f260` (origin/main `f6fb434ab` is an
ancestor; no rebase needed) in a separate worktree with its own dev
instance (ports 13662/21662/29662).

Commands:

- `git checkout origin/main -- <11 non-test source files>` + remove
`thread-fork-history.ts`, then `pnpm exec vitest run
test/public/public-thread-fork.test.ts
test/threads/thread-create-seed-without-run.test.ts` from `apps/server`:
**10 failed / 30 passed**. Failing assertions: `expected { Object
(sourceProviderThreadId) } to deeply equal { …(2) }`, `expected [] to
deeply equal [ 'Reply only with ok.', 'ok', …(2) ]`, `expected 201 to be
400`, `expected undefined to be 'checkpoint-after-turn-1'`.
- `git checkout HEAD -- <same files>`, same command: **40 passed**.
- `pnpm exec turbo run typecheck` for `@bb/server`, `agent-runtime`,
`host-daemon-contract`, `db`, `host-daemon`, `sdk`, `cli`,
`server-contract`, `templates`, `app`: `Tasks: 13 successful, 13 total`.
- `pnpm exec turbo run test --force` for `@bb/server`, `db`,
`host-daemon-contract`, `agent-runtime`, `server-contract`, `cli`,
`templates`, `host-daemon`, `bb-plugin-side-chat`: 14/15 tasks green;
`@bb/server` 1830 passed / 1 failed, the failure being the known local
umask-only `internal-skill-trees` mode 0644-vs-0664 assertion
(unrelated, passes in CI).
- CI (`gh pr checks 2142`): all jobs pass (Checks, Package Smoke x2,
Tests app-1/2/3, integration, packages, server).

Live repro on the fixed branch (pi provider, source thread with two
turns "ok"/"second", turn 1 `turn/completed` at seq 15 with checkpoint
`9f0ee844`):

- `bb thread fork <src> --workspace reuse`: timeline has all four
conversation rows; fork events are the 10 inherited rows (null
`provider_thread_id` column, payload keeps the source session id)
followed by the fork's own `client/turn/requested`,
`client/thread/start`, `thread/identity`, provisioning.
- `--source-seq-end 13` (turn 1's assistant message): timeline shows
"Reply only with ok." / "ok" only; the fork's pi session file has
`parentSession=<src>` and only turn 1's two entries.
- `--source-seq-end 3`: `HTTP 400: Cannot fork at sequence 3: no turn
has started at or before it`.
- Mid-turn (turn 3 running `sleep 45`): tip fork inherits turns 1-2 only
and its pi session holds turns 1-2 while the source's already holds turn
3's prompt; `sourceSeqEnd: 28` (inside the running turn) returns 400
`fork_source_session_unavailable`.
- After turn 3 (with a `commandExecution` tool call) completed, a tip
fork renders the inherited tool-call turn as a completed "Worked for"
group in both `/timeline` and `bb thread log`; no crash on
`item/completed` rows without `item/started`.
- Browser (headless Chrome): the seq-13 fork page renders the inherited
user/assistant rows plus the "Forked from" chip.

Residual risks: wire change needs enrolled daemons on protocol 147
(older daemons would strip the checkpoint and clone the tip); checkpoint
forks on claude-code/codex reuse the rewind path's checkpoint ids but
were not live-tested here (pi was); side chats anchored on an earlier
completed turn now get a checkpoint fork rather than a tip clone;
`findLastCompletedRootStoredTurn` accepts an `atOrBeforeSequence` bound
no caller passes (minor dead parameter). Hidden forks inherit no history
by server policy.

> AGENT GENERATED: by Claude Opus 5

## Stack

Layer 2/2 of GitHub stack #2217 (`gh stack`), depends on #2154 (layer
1/2, protocol 151). Base is `bb/fix-1681-pi-notification-wake`;
`HOST_DAEMON_PROTOCOL_VERSION` 152. After #2154 merges, GitHub retargets
this PR to `main`. Rebased onto #2154's head (itself on main at
`75d6fc4d4`): conflicts were `protocol.ts`, `contract.test.ts`, and
`docs/provider-bridge-protocol.md` (kept main's rewritten open-work note
and this PR's fork note side by side); the two review-round commits are
squashed into one. Re-verified on the new base: the fork tests fail with
the 14 non-test source files checked out from the base (`9 failed`, e.g.
`expected { Object (sourceProviderThreadId) } to deeply equal { …(2) }`,
`expected [] to deeply equal [ 'Reply only with ok.', 'ok', …(2) ]`,
`expected 201 to be 400`) and pass on this head; `turbo run typecheck
test` for host-daemon-contract, host-daemon, agent-runtime, server, db,
server-contract, cli and templates is green except the known local-only
umask `internal-skill-trees` assertion.

> AGENT GENERATED: by Claude Opus 5



## Independent verification (guards)

Re-verified head `d811c206c` (protocol 152, base
`bb/fix-1681-pi-notification-wake` at `bdf47388f`, itself on
`origin/main` `27d1017fe`) after the CI-guard amendments, in a separate
worktree.

- Guard fix is mechanical: `git range-diff e522476~1..e522476
origin/bb/fix-1681-pi-notification-wake..HEAD` shows only (a)
`resolveTurnProviderCheckpointId` + `CODEX_NATIVE_TURN_ID_PATTERN` moved
verbatim from `thread-events.ts` to an export in
`thread-edit-message.ts`, (b) `thread-fork-history.ts` importing it from
`./thread-edit-message.js`, and (c)
`scripts/provider-literal-baseline.json` `thread-edit-message.ts` 2 ->
1, total 148 -> 147. The bottom layer's range-diff shows only the
`@get-bb/plugin-sdk` 0.4.11 -> 0.4.12 bump
(`packages/plugin-sdk/package.json`,
`packages/domain/src/plugin-sdk-version.ts`). Everything else in `git
diff e522476 HEAD --stat` is the four unrelated main commits picked up
by the rebase.
- No import cycle from the move: `thread-create.ts ->
thread-fork-history.ts -> thread-edit-message.ts`, and none of
`thread-edit-message.ts`'s local imports (`thread-send`,
`thread-turn-dispatch`, `thread-lifecycle`, `thread-commands`,
`thread-runtime-config`, `thread-data`, `thread-events`) import
`thread-create` or `thread-fork*`.
- `node scripts/check-provider-literal-ratchet.mjs`: `Provider-literal
ratchet OK: 147 references across 40 core files.`
- Fail-before: `git checkout origin/bb/fix-1681-pi-notification-wake --
<17 non-test source files>` + `thread-fork-history.ts` removed, then
`vitest run test/public/public-thread-fork.test.ts
test/threads/thread-create-seed-without-run.test.ts` in `@bb/server`:
**10 failed / 30 passed** (`expected [] to deeply equal [ 'Reply only
with ok.', 'ok', …(2) ]`, `expected { Object (sourceProviderThreadId) }
to deeply equal { …(2) }`, `expected 201 to be 400`, `expected undefined
to be 'checkpoint-after-turn-1'`).
- Pass-after: `git checkout HEAD -- .`, same command: **40 passed**.
- `pnpm exec turbo run typecheck --filter=@bb/server
--filter=@bb/host-daemon-contract`: `Tasks: 5 successful, 5 total`;
`@bb/host-daemon-contract` `contract.test.ts`: 38 passed.
- CI: `gh pr checks 2142` all pass on run `32508211062` (head_sha
`d811c206c`): Checks, Package Smoke x2, Tests app-1/2/3, integration,
packages, server. `mergeable: MERGEABLE`, `mergeStateStatus: CLEAN`.
#2154 (bottom layer) is also fully green and CLEAN on `main`.
- Live repro was not re-run for this guard-only pass; the earlier
round's pi-provider repro on the same logic stands (the moved helper's
body is byte-identical).


## Rebase (2026-08-21, second)

Rebased onto #2154's new head `9e632c399`. `main` took protocol **151**
(#2242), which pushed #2154 to **152**, so this layer is renumbered
**152 -> 153**: its comment block sits above #2154's 152 block and the
lockstep assertion in `contract.test.ts` moves to `toBe(153)`.
`protocol.ts` was the only conflict; the SDK version files no longer
appear in the stack's diff, because both layers now adopt main's
unpublished `0.4.13`.

Re-verified on the new base: `node
scripts/check-provider-literal-ratchet.mjs --base <#2154 head>` -> `OK:
147 references across 40 core files` (the helper stays in
`thread-edit-message.ts`). `turbo run typecheck` for cli, server,
agent-runtime, db, host-daemon-contract, server-contract, templates:
`Tasks: 10 successful, 10 total`. `turbo run test` for the same set:
server-contract 7/7 files, host-daemon-contract 3/3, db 28/28,
agent-runtime 31/31, cli 48/48, templates 6/6, server 200 passed / 1
skipped with only the known local-only umask failure
`internal-skill-trees` (0644 vs 0664 under umask 0002), which passes in
CI.

Stack #2217 is unchanged: base is still
`bb/fix-1681-pi-notification-wake`, and GitHub retargets this PR to
`main` when #2154 merges.

> AGENT GENERATED: by Claude Opus 5

Co-authored-by: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 25, 2026
## Human comments

## What was wrong

Many server, db, domain and contract tests duplicated a stronger test at
the owning boundary. Examples:
- three "Unsupported tool" variants that hit the same fallback branch;
- twin public-thread and thread-parent tests;
- ten "ships X enabled/disabled" builtin tests.

Others pinned incidental literals, such as exact gzip byte counts in
`payload-size.test.ts` and copied icon and logo lists. Some couldn't
fail at all: a check for a connect route that doesn't exist, and a
"migrates without throwing" test that every db test already repeats.

A few kept dead production code alive:
- `hasCompletedEventLoopWorkForTests` (no callers since #4259)
- `pruneThreadEventsBeforeSequence` (no callers since #3766)
- `claimQueuedThreadMessage`
- `createHostDaemonClient` in the host-daemon-contract source

## What changed

Found by a read-only test audit using the repo `test-audit` skill
(#4361).

- **Dead production code removed, with its tests:**
  - `hasCompletedEventLoopWorkForTests`
- `pruneThreadEventsBeforeSequence` and its transaction variant. The
other prune wrappers are unchanged.
- `claimQueuedThreadMessage`. Test call sites use
`claimQueuedThreadMessageGroup` with `{ kind: "explicit-send" }`.
  - `isAgentDelegatedChildThread`, inlined.
- **Tests rewritten or moved:**
- The randomized `timeline-context-order-cache` test now prunes through
the live `advanceThreadPruning` path, and asserts that rows are actually
pruned.
- `createHostDaemonClient` moves into its only user,
`internal-session-protocol-version.test.ts`. The wire schema is
unchanged, so no `HOST_DAEMON_PROTOCOL_VERSION` bump.
- **Duplicates folded into their keepers or tables:** the builtin plugin
defaults, `requestMatchesEntityTag` cases and pending-interaction
`reason`.
- **Not in this PR:** the `thread_dynamic_context_file_states` table (no
writer since #2140) and its schema test. Dropping it needs a migration
decision.

Production +1/−117, tests +137/−1555.

## How you verified

- `pnpm exec turbo run test lint typecheck` passes for `@bb/server`,
`@bb/db`, `@bb/domain`, `@bb/server-contract` and
`@bb/host-daemon-contract`.
- The only failures were `@bb/server` timeouts at load average 40. The
base commit shows them too, and they pass when rerun alone.
  - oxlint's `no-comments` errors match base.
- An independent verifier used before and after worktrees on 175d5ac.
For each removed test it wrote the bug that test catches as a production
change, then checked that the old test fails and a remaining test also
fails.
  - Result: 44 OK, 5 with no unique failure mode, 0 lost.
- Builtin plugin icon names stay covered by `PluginIcon.test.tsx`
("resolves every named branding.icon the shipped plugins declare").
  - Both `isParentNotifiableChildThread` clauses stay caught.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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