Repository navigation
Add manual context compaction across providers - #1152
Conversation
|
🚨 SLOP COP 🚨 · I am SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, and end-to-end behavior. I will post one final review after the parallel checks finish. |
9a63de9 to
041b652
Compare
SawyerHood
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5: This change adds a context clean-up command for several providers. Some providers finish incorrectly, block other work, or expose the command too early.
I reviewed the requested SHA 9a63de9699e8a5beea001a336df9fb6fedcb87eb. The pull request later moved to 041b652e, but these code paths remain unchanged.
I found these defects:
- [P1] Non-Codex compaction takes a shared provider write lane. A stalled request can block unrelated sessions for 20 minutes.
- [P1] ACP prompt compaction hides tool activity but still permits file reads and writes.
- [P2] The daemon does not retain the runtime during compaction.
- [P2] Claude returns success when the SDK consumes
/compact, before compaction completes. - [P2] Pi emits
thread/compactedfor aborted and failed compactions. - [P2] New-thread composers offer
/compactbefore a thread exists. - [P2] Invalid mention ranges can replace a normal prompt with compaction.
- [P3] Failed UI compactions refresh broad, unrelated query groups.
The implementation also repeats compact detection and draft recovery in four UI paths. One shared action can reduce this duplication.
The provider adapters use different completion rules. A shared terminal contract and the existing compaction lifecycle can prevent these differences.
I ran the branch dev app and used the browser command surface. Codex returned 200, showed compaction, and reduced context use from 7% to 2%.
The source CLI also compacted the same thread. Ten changed packages passed type checks, and 129 focused tests passed.
The full local run passed nine package tasks. One unrelated machine-install test failed, while GitHub checks passed.
dc6f9f8 to
203228a
Compare
|
Review triage complete at 78396d4.
For the two general observations: compact detection is now centralized in isStandaloneBuiltinCompactCommand and shared by both submission controllers. Draft ownership remains controller-specific because the full thread composer and plugin/embedded composer have different persistence and callback lifecycles; combining those controllers is outside this feature. Provider-specific signals are already normalized into the shared compaction lifecycle, while command settlement consistently means accepted rather than terminally completed. Verification on the new tip: all affected typechecks pass; full suites pass for domain (129), agent-runtime (840), host-daemon (493), and app (2,419). |
12eff85 to
777f4e7
Compare
81ded63 to
7d3a323
Compare
## Motivation The four provider adapters (claude-code, codex, pi, acp) and three bridges carry near-verbatim copies of the same machinery: stdio harness, session registry, adapter identity/command/translation boilerplate, turn lifecycle, item-id scoping, and tool item translation. That duplication has a measurable history of making cross-provider work slow and lossy: - **Manual compaction (#1152)** landed through 19 commits, more than 11 of them iterating the same feature provider-by-provider ("Make OpenCode ACP compaction reliable", "Avoid false Pi compaction success", "Show ACP compaction lifecycle", "Fix compaction lifecycle races", ...). One feature, re-fought per adapter. - **Rate-limit normalization (#1027)** only ever shipped to 2 of 4 providers. On main today, `ProviderRateLimitState` is referenced by claude-code and codex translation only — Pi and ACP have zero references. Duplication didn't just slow the change down; it silently dropped half the matrix. - **`classifyExecutionSettingsChange` (#1236)** had to touch all four adapters to change one provider's behavior, because the member wiring is copied everywhere. After this PR, the shared machinery lives in `packages/agent-runtime/src/shared/` and a cross-provider change of this kind is a one-place change. ## Honest accounting Repo-wide this is roughly **−300 lines net** (2,204 insertions, 2,512 deletions, all inside `packages/agent-runtime`). The ~1,640-line figure from the de-slop audit counts *duplicated* lines, not deletable ones — extracting a shared implementation still costs its one copy plus parameterization. The value of this PR is **one-place-change for cross-provider behavior**, not raw deletion. ## Commit-by-commit review guide The 8 commits are logically staged; each is independently revertable and behavior-preserving: 1. **`fff1c494c` share bridge stdio harness** — the three bridges' identical stdin/stdout JSON-RPC loop (readline wiring, dispatch, error replies) moves to `shared/bridge-harness.ts`. 2. **`e1e7615ba` share bridge session registry** — the per-bridge `Map`-of-sessions bookkeeping (create/get/stop/dispose) moves to `shared/bridge-session-registry.ts`. 3. **`66fee1a30` share bridge environment helpers** — env-override construction/parsing dedup in `shared/adapter-utils.ts` (round-trip covered by a new test), plus `shared/mime-types.ts`. 4. **`6e6e9fbc1` share standard adapter members** — the biggest one. Each adapter's copied identity/launch members, `initialize` plan, unsupported-command fallbacks, accepted-command translation, model-list parsing, and tool-call decoding collapse into `createStandardAdapterMembers()` (`shared/standard-adapter-members.ts`); adapters keep only their provider-specific `buildProviderCommandPlan`. Review focus: confirm each adapter's per-command plans are unchanged (they are moved, not edited). 5. **`4c6a3c65b` centralize provider turn hooks** — per-adapter `ensureXTurnStarted` wrappers and the copied error-envelope-to-events helper become `onTurnStart`/`onTurnFinish` hooks and `buildErrorEvents` on the shared turn-state registry; `shared/provider-error-events.ts` is deleted. 6. **`276516e32` share scoped item id factories** — the copied open/completed scoped-item-id resolution moves to `shared/scoped-item-ids.ts`. 7. **`fbd671c2a` share tool item translation** — the copied toolUse/toolResult item builders move to `shared/tool-item-translation.ts`. 8. **`86a313d7b` remove dead exports and helpers** — deletes exports and helpers made unreferenced by the extractions (verified by repo-wide typecheck). ## Wire compatibility (server ↔ host daemon) **No `HOST_DAEMON_PROTOCOL_VERSION` bump needed, and none is included.** The diff is confined to `packages/agent-runtime`; `packages/host-daemon-contract` (session payloads, WS messages, host RPC commands/results) is untouched and the protocol version stays at 106 on both sides. The refactor changes where adapter/bridge code lives, not what crosses the wire: the 900+ adapter tests that assert exact translated `ThreadEvent` output (ids, scopes, payloads) pass without any expectation changes, so the event stream the daemon posts to the server is byte-identical. ## Rebase provenance This branch originated in archived thread `thr_jyia7bkdqn` and was rebased onto current main (original authorship preserved in the commits). The rebase crossed #1280 (sent-message editing) and #1321 (provider-unhandled-event fix), both of which touched the same adapters; conflicts were resolved by preserving main's shipped behavior and re-grafting it into the extracted structure: - `thread/discard` command plans re-added per provider (acp: noop, claude-code: `thread/stop`, pi: `thread/discard`) inside each `buildProviderCommandPlan`. - Claude Code's `latestProviderCheckpointId` reset moved into the shared `onTurnStart` hook (fires only for newly opened turns, same guard as the removed wrapper). - `sourceProviderCheckpointId` forwarding re-added to the claude-code and pi `thread/fork` plans. The rebase delta vs the original branch inside `packages/agent-runtime` is exactly the sum of #1280 + #1321 (+1,124/−36), i.e. nothing from main was lost and nothing beyond the refactor was introduced. ## Verification - `pnpm exec turbo run typecheck` — whole repo, 58/58 tasks pass. - `pnpm exec turbo run test --filter=@bb/agent-runtime` — 907 passed, 1 failed: `runtime.process-lifecycle.test.ts > bounds provider stderr while data arrives without a newline`, which fails identically on unmodified origin/main (reproduced during this work; also documented as pre-existing in #1321). The lifecycle suites (`runtime.lifecycle.test.ts` 28/28, `runtime.process-lifecycle.test.ts` 21/21 excluding the pre-existing failure) covering the Codex recovery paths pass. - `pnpm exec turbo run test --filter=@bb/host-daemon` (the only dependent of `@bb/agent-runtime`) — 541/541 pass. > AGENT GENERATED: by Claude Fable 5 🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary - reuse the existing structured `/compact` turn path instead of adding a second host-daemon compaction command - preserve the existing Codex and Claude Code behavior; add native Pi compaction and OpenCode ACP `/compact` handling at the provider adapter boundary - add provider-aware typeahead plus `POST /threads/:id/compact`, `sdk.threads.compact()`, and `bb thread compact` - leave Cursor ACP and arbitrary custom ACP agents unsupported because ACP does not expose a standard compaction method and Cursor does not interpret its interactive `/compress` command over ACP - report Pi and OpenCode completion, failure, and interruption through normal visible timeline events ## Provider behavior | Provider | Behavior | | --- | --- | | Codex | Existing native `thread/compact/start` mapping | | Claude Code | Existing selected `/compact` turn behavior | | Pi | Selected `/compact` maps to the Pi SDK `compact()` operation | | OpenCode ACP | Selected `/compact` maps to an ACP `session/prompt` containing the exact provider control | | Cursor ACP | Unsupported; Cursor does not expose compatible compaction through ACP | | Other ACP agents | Unsupported unless a concrete provider integration is added | ## Simplified request path The composer submits `/compact` exactly like any other selected built-in command. The SDK/CLI endpoint synthesizes that same structured input and delegates to the existing `sendThreadMessage` path. This means request persistence, composer clearing, lifecycle settlement, and failure display all use the ordinary turn machinery. Only the Pi and OpenCode adapters need new dispatch behavior. They recognize the exact selected built-in command, start provider-local compaction, acknowledge the turn promptly, and translate the provider outcome back into the existing `contextCompaction`, `thread/compacted`, and `turn/completed` events. This branch does not add a host-daemon RPC, change the daemon protocol, configure generic ACP prompt compaction, intercept composer submission, or summarize/reseed sessions. ## Validation - relevant package typechecks passed - relevant package lint passed - focused provider/runtime tests: 339 passed - focused server compaction/typeahead tests: 6 passed - app command-suggestion tests: 5 passed - CLI suite: 383 passed - the full agent-runtime suite passed 859 tests but still has one unrelated existing failure in `runtime.process-lifecycle.test.ts` (`bounds provider stderr while data arrives without a newline`), reproduced on retry; all changed provider tests pass ## Diff shape after cleanup The branch is now 1,022 additions / 126 deletions across 39 files. It removes the branch-only daemon command, runtime API, protocol bump, generic ACP configuration, Claude/Codex duplicate plumbing, composer interception, and unrelated `dev:stop` work. Fixes get-bb#1103
## Human comments ## What was wrong Every send into an active thread checks whether the active turn is a provider-started compaction. That check, `isStoredTurnProviderCompactionRunning`, came in with #6420 and first shipped in desktop v0.48.0. In long threads it blocks the server for seconds (#6786). Its first query looks for the turn's latest root `contextCompaction` lifecycle event. It filters by thread, turn, type, item kind and parent, ordered by `sequence DESC LIMIT 1`. bb never runs `ANALYZE`, so there is no `sqlite_stat1`. Without statistics, SQLite picks the unique `events_thread_sequence_idx (thread_id=?)` because it already returns rows in `ORDER BY` order. It then reads the table row of every event in the thread, newest first, until one matches. Most turns contain no compaction, so the usual send reads the thread's whole history. On a 348k-event thread that took 9 to 18 s of wall time (1.4 to 3.2 s CPU). The event loop stalled with the send in flight, before the message was stored. ## What changed - **The query:** in `packages/db/src/data/events.ts`, the compaction query in `isStoredTurnProviderCompactionRunning` reads from `events INDEXED BY events_thread_turn_type_item_sequence_idx`. That index seeks `(thread_id, turn_id, type)`, so the query reads only the active turn's `item/started` and `item/completed` rows, then sorts them in a temporary B-tree. On the thread above that is at most 505 rows in any turn, 20 on average. - **The selected column:** it becomes `sql<ThreadEventType>`, because drizzle will not resolve `events.type` against a raw-SQL `from()`. The other pinned queries in this file do the same. - **The rows returned are the same.** `INDEXED BY` changes only the access path, and the `WHERE` clause is unchanged. `(thread_id, sequence)` is unique, so `ORDER BY sequence DESC LIMIT 1` has no ties and returns the same row. The repro script checks this on every turn it times. #6420's predicate, and which sends it queues, are unchanged for every provider and turn shape. - **Why this index:** I pinned the turn index rather than `events_thread_type_item_kind_sequence_idx`. That one would read every compaction event in the thread's history (1,876 on the thread above), and that count only grows. The turn index's cost is bounded by the turn. - **Order of the two checks:** I kept the order #6420 wrote. Checking `turn/input/accepted` first returns the same answer and would skip the lookup in user turns. On its own, though, it leaves the history walk in every turn that accepted no input, and those are common: 152 of the 5,798 turns on that claude-code thread. With the index pinned, the lookup is bounded either way. - No schema, migration, wire or protocol change, and no `HOST_DAEMON_PROTOCOL_VERSION` bump. Costs and failure mode: - **A large current turn costs more than it did.** The old plan could stop early when the current turn's compaction was near the tip, which is the Pi extension case. The pinned plan always reads and sorts the turn's lifecycle rows. Synthetic, warm cache, with a running compaction at the end of the turn: main 0.01 ms, pinned 0.28 ms at 1,010 lifecycle rows (about twice the largest turn on the thread above), and 5.3 ms at 10,000 rows. In the larger Linux run below, a 60,000-event current turn with its compaction at the tip took 0.010 ms on main and 19 ms pinned warm, and 15 ms and 115 ms cold. The cost is linear in the turn's size and no longer depends on how long the thread is. - **If the index is ever renamed or dropped,** the statement fails at prepare with `no such index`, and every send that reaches this lookup (a send into a thread with an active turn) fails loudly. It does not fall back to a scan. The new query-plan test calls the function and asserts the index name in its plan, and the existing "drops redundant events indexes after creating their consolidated replacement" test asserts the index exists. Both would fail first. ## How you verified - **New test:** `packages/db/test/query-plans.test.ts`, "finds a turn's running provider compaction through the turn index". - It seeds a running compaction, a completed one, a nested one, and one in a turn that accepted input. It checks the function returns `true` only for the first, and `false` for those and for a turn with no compaction. - It asserts that the compaction query's plan seeks `events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?)`, and that neither statement seeks by thread only. - With the `events.ts` change reverted, the return-value assertions pass and the plan assertion fails with `Received: "SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)"`. With the change, it passes. - **`packages/db`:** - `pnpm exec vitest run test/query-plans.test.ts`: 50 tests passed. - `pnpm exec vitest run test/data/events.test.ts test/data/event-rewrite-generation.test.ts`: 103 passed. - `pnpm exec turbo run lint test --filter=@bb/db` (the CI job's form): 54 files, 635 tests passed. `@bb/db` has no lint task. - `pnpm run typecheck` passes. - **`apps/server`:** `pnpm run typecheck` passes. `pnpm exec vitest run` on `public-thread-compaction`, `thread-events`, `thread-send-dispatch`, `requested-queue-drain`, `queue-drain-failure`, `parent-system-message-dispatch`, `thread-send-error-recovery` and `public-thread-offline-followup` passed 105 tests in 8 files. These include #6420's queued-during-compaction case and its three steering controls. - **Full suites on Linux** (Node 22.21.1, pnpm 9.15.0, better-sqlite3 12.10.0 with SQLite 3.53.1, one Vitest worker): - `@bb/db`: 635 tests passed in 54 files. - `@bb/server`: 3,786 passed, 3 failed, 1 skipped. The 3 failures also fail with both changed files restored to `916d684ac2`: two cases of "resolves an unset HOME and preserves explicit HOME" in `install-machine-script.test.ts`, and "uses the first and last committer dates from plugin history" in `bb-official-generator.test.ts` (a `+00:00` date suffix where the test expects `Z`). - Both packages typecheck. `turbo run build --filter=@bb/db --filter=@bb/server` passes, which builds the server and its dependencies; `@bb/db` itself has no build script. `oxlint` aborted inside its allocator there, on this head and on `main` alike, so that run gives no lint result. The Mac lint run above is the lint evidence. - **Same rows as before:** a differential harness ran the production function and both raw statements on real migrated SQLite over 2,013 cases, 2,000 of them randomized event sequences. Every case returned the same selected row (`type`, or no row) from both statements, and the function returned the expected boolean against an independent oracle. The cases cover empty turns, several compactions where the latest wins, nested compactions, older turns, other threads, accepted input and a 60,000-event turn. The pinned plan was also checked on a schema upgraded from desktop v0.47.1 with that release's own migration runner, and after `ANALYZE`, where both statements pick the turn index. - **Lint and format:** - `oxlint -c .oxlintrc.json` on both files reports only two `bb(no-comments)` errors, on lines 477–478 of `query-plans.test.ts`. They are already on `main` and outside this change. - `oxfmt --check` on the test file, `git diff --check` and `scripts/check-source-nul.mjs` pass. - `packages/db/src/data/` is excluded from oxfmt, and running oxfmt on the changed function leaves it unchanged. - **Plan on a real database:** read-only `EXPLAIN QUERY PLAN` on a 33 GB, 33M-row bb database (no `sqlite_stat1`): - before: `SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)` - after: `SEARCH events USING INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?)`, `USE TEMP B-TREE FOR ORDER BY` - **Synthetic timing**, with the script from the issue: - Setup: one 350,000-event thread among 1.4M rows, warm page cache, medians of 5 runs. - The machine was loaded (one-minute load average about 20 on 18 CPUs), and main's figure moved by up to about 20% between runs. | Rows | Current turn | main | pinned | | --- | --- | --- | --- | | 220 B | user turn, accepted input | 52.1 ms | 0.03 ms | | 220 B | provider-started, no compaction | 51.4 ms | 0.03 ms | | 1 KB | user turn, accepted input | 180 ms | 0.03 ms | | 1 KB | provider-started, no compaction | 210 ms | 0.07 ms | | 1 KB | 10,000 lifecycle rows, no compaction | 171 ms | 5.0 ms | | 1 KB | 10,000 lifecycle rows, running compaction at the end | 0.01 ms | 5.3 ms | - **A database larger than memory:** the numbers above are a warm-cache CPU floor. The logged production walks took about 6 times their CPU time, which I take to be disk reads and waiting on a loaded machine; I did not measure the Mac's page cache or I/O, so that is an inference. To measure the cold case directly, the comparison was repeated on a Linux VM with 4 CPUs and 4 GiB of RAM: - The database was 8 GB, with 4.8M events of about 1 KB in 13 interleaved threads of 350,000 events each. It was built by the real migrations, with no `ANALYZE`, and used the production connection's cache and mmap settings. - Each scenario ran on its own thread. Warm cells are 20 samples after one prewarm. Cold cells are 8 samples, each after closing the connection and running `sync` and `echo 3 > /proc/sys/vm/drop_caches`. The variant order alternated every iteration, and every result was checked against the expected answer. - Medians of the statement alone, milliseconds: | Current turn | main warm | pinned warm | main cold | pinned cold | | --- | --- | --- | --- | --- | | user turn, accepted input | 405 | 0.007 | 35,738 | 21 | | provider-started, no compaction | 445 | 0.004 | 34,839 | 21 | | 60,000 lifecycle rows, no compaction | 466 | 20 | 35,710 | 146 | | 60,000 lifecycle rows, running compaction at the end | 0.010 | 19 | 15 | 115 | - With four CPU-burner processes running, the medians were similar: 573 ms on main and 0.004 ms pinned warm in the provider-started turn, and 36.7 s and 19 ms cold. - **Real send route:** `POST /api/v1/threads/:id/send` into the active provider-started turn of a 350,001-event thread, 12 alternating pairs with a warm cache. The median was 503 ms on main and 22 ms pinned, and the slowest was 27.9 s on main and 33 ms pinned. All requests returned `delivery: "sent"`. - I did not time the pinned query on the production database, because that would mean running queries against its data rather than only explaining them. - **Send-path sweep:** I captured every `SELECT` on `events` during a test-harness steer, into an active turn with and without accepted input, and explained each plan. With the change, no statement walks the whole thread. Two seeks by thread prefix remain, and both are bounded: - `getLastStoredTurnRequestEvent` stops at the newest turn request. - The thread-state lookup uses the partial `events_thread_state_thread_sequence_idx`, which holds only goal and extension-state events. - **Not changed here:** `getStoredTurnRequestEventForTurn`, which `isManualCompactionActive` has called since #1152, seeks `events_thread_type_sequence_idx (thread_id=? AND type=?)` for the turn's accepted input. In a provider-started turn, which has none, it reads every accepted-input row in the thread. In the large run that was about 5,800 rows, and the lookup took 8 ms warm and 0.9 s cold in a profiled send (profiler overhead included). It predates #6420, and the issue describes it. Fixes #6786 > AGENT GENERATED Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
/compactturn path instead of adding a second host-daemon compaction command/compacthandling at the provider adapter boundaryPOST /threads/:id/compact,sdk.threads.compact(), andbb thread compact/compresscommand over ACPProvider behavior
thread/compact/startmapping/compactturn behavior/compactmaps to the Pi SDKcompact()operation/compactmaps to an ACPsession/promptcontaining the exact provider controlSimplified request path
The composer submits
/compactexactly like any other selected built-in command. The SDK/CLI endpoint synthesizes that same structured input and delegates to the existingsendThreadMessagepath. This means request persistence, composer clearing, lifecycle settlement, and failure display all use the ordinary turn machinery.Only the Pi and OpenCode adapters need new dispatch behavior. They recognize the exact selected built-in command, start provider-local compaction, acknowledge the turn promptly, and translate the provider outcome back into the existing
contextCompaction,thread/compacted, andturn/completedevents.This branch does not add a host-daemon RPC, change the daemon protocol, configure generic ACP prompt compaction, intercept composer submission, or summarize/reseed sessions.
Validation
runtime.process-lifecycle.test.ts(bounds provider stderr while data arrives without a newline), reproduced on retry; all changed provider tests passDiff shape after cleanup
The branch is now 1,022 additions / 126 deletions across 39 files. It removes the branch-only daemon command, runtime API, protocol bump, generic ACP configuration, Claude/Codex duplicate plumbing, composer interception, and unrelated
dev:stopwork.Fixes #1103