Skip to content

Add the provider-literal ratchet guardrail (G1) - #2120

Merged
SawyerHood merged 6 commits into
mainfrom
bb/provider-literal-ratchet
Aug 21, 2026
Merged

SawyerHood merged 6 commits into
mainfrom
bb/provider-literal-ratchet

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

What was wrong

The provider-plugin migration deletes core's per-provider carve-outs (the census found 198 provider-id literals across 58 core files). Nothing stops a future change from re-adding a providerId === "codex" branch while the migration is in flight, or after it finishes. Progress toward a provider-agnostic core needs to be one-directional and enforced.

What changed

Adds guardrail G1, a CI ratchet:

  • scripts/check-provider-literal-ratchet.mjs scans core (everything outside plugins/provider-* and examples/, excluding tests, fixtures, stories, generated, and dist) for provider-id literals — "codex", "claude-code", "pi", "acp-…", "cursor", providerId === "…", isAcpProviderId, RESERVED_PROVIDER_ID_OWNERS, and the like. Pure Node, no ripgrep dependency on the runner.
  • scripts/provider-literal-baseline.json holds a per-file count. The check fails if any file's count rises or a new core file appears; a reduction requires --write to regenerate the baseline, so every removal is a committed, visible diff. When the baseline hits zero, the file and the guard are deleted.
  • Wired into the ci.yml checks job beside the existing repo guards (bundle budget, npm version).
  • Self-test in @bb/scripts covering: passes against the committed baseline, fails on a planted providerId === "codex" file, and the live count agrees with the baseline.
  • Documented in docs/debugging-and-qa.md.

Scope is provider-id literals only. Tool-name keying (thread-view's Read/Task/TodoWrite tables) is retired by its own workstream and collides with unrelated identifiers, so it is tracked separately, not in this ratchet.

Baseline at introduction: 198 literals across 58 core files. The top concentrations are exactly what the migration dismantles — the provider registry (23), the daemon skill-discovery tables (20), the app icon map (14), the runtime codex-recovery block (11).

How you verified

  • pnpm exec turbo run test --filter=@bb/scripts green, including the three ratchet self-tests (pass / planted-literal fail / baseline agreement).
  • node scripts/check-provider-literal-ratchet.mjs prints ratchet OK: 198 literals across 58 core files.
  • --write and --list exercised manually.
  • No production code touched; guard + baseline + CI wiring + docs only.

Part of the provider-plugin migration (see docs/provider-plugin-api.md and https://get-bb.github.io/reports/design/provider-plugin-api.html).

Fixes #

AGENT GENERATED: by Claude Opus 4.8

@bb-slop-cop

bb-slop-cop Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

🚨 slopcop/review — I am the Slop Cop. I am reviewing this pull request for security, code quality, performance, architecture, and test behavior.

I will post one final review after the parallel checks finish.

} catch {
continue;
}
if (!text.includes("codex") && !text.includes("claude") &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — This fast reject can discard names that the later pattern list intends to count. A file that only uses PRODUCT_DEFAULT_PROVIDER_ID or another uppercase constant contains none of these lowercase hints. Please derive the reject from the patterns or remove it; the full scan takes about 0.22 seconds.


it("fails when a core file gains a new provider-id branch", () => {
const planted = join(ROOT, "packages", "domain", "src", "__ratchet_probe__.ts");
writeFileSync(planted, 'export const x = providerId === "codex" ? 1 : 2;\n');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — This test overwrites a fixed source path and always deletes it. An existing local file or link at this path loses data. Please use a unique temporary directory, or create the probe exclusively and fail if the target exists.

join("examples", ""),
];
const EXCLUDED_FILE_RE = /\.(test|spec|stories)\.[cm]?tsx?$|\.snap$|\.d\.ts$/;
const INCLUDED_FILE_RE = /\.[cm]?tsx?$/;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — This filter excludes JavaScript, MJS, and CJS from the stated core scope. The existing Pi-specific path in apps/host-daemon/scripts/bundle-manifest.mjs proves that relevant core code exists there. Please include supported source types and regenerate the baseline.

const list = run(["--list"]);
expect(list.code).toBe(0);
const m = list.out.match(/(\d+) provider-id literals across (\d+) core files/);
expect(m).toBeTruthy();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The test name says that the live total matches the baseline, but this assertion only checks the output shape. It never reads the JSON or compares either captured number. Please assert both values and cover baseline growth plus the same-line bypass.

let count = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (PATTERNS.some((re) => re.test(line))) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — This counts matched lines, not provider literals. For example, provider-model-catalog.ts:18 already has two literals on one line but adds only one count. Another branch on that line passes without changing the baseline. Please count stable occurrences or parsed syntax nodes, and add a same-line regression test.


let baseline;
try {
baseline = JSON.parse(readFileSync(BASELINE_PATH, "utf8"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The check trusts the baseline from the same pull request. A change can add a provider branch, run --write, and pass because CI never compares the new baseline with the trusted base branch. Please fetch the base commit and reject new or increased baseline entries.

@bb-slop-cop bb-slop-cop Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

Plain English summary: This pull request adds a CI alarm for provider-specific code. It records current references and should reject new references.

I found four material gaps in that alarm:

  • The check trusts the baseline from the pull request. An author can add a branch, run --write, and pass CI.
  • The scanner counts lines instead of literals. A new branch on an existing matched line does not change the count.
  • The scanner excludes JavaScript files. It also skips some uppercase provider constants before the pattern check.
  • The probe test can overwrite and delete an existing local source file.

The tests also need stronger inputs and assertions. Turbo does not include the root scanner, baseline, or scan roots in the package test hash. The baseline agreement test checks only the output format.

Two references point to the missing docs/provider-plugin-api.md file. Prettier also reports format errors in three changed files.

I found no separate external security issue. I found no shared ratchet utility that this code duplicates. A pure scanner with small fixtures would improve this design.

Performance looks good. One full scan took about 0.22 seconds. The @bb/scripts suite passed all 100 tests.

A browser test does not apply because this change has no browser route. I tested the real command and the package suite instead.

I would fix the guard bypasses before merge. I left exact line comments with concrete fixes.

SawyerHood added a commit that referenced this pull request Aug 21, 2026
Six material fixes from the SlopCop review of #2120:

- Count occurrences, not matched lines. A second provider id on a line
  that already matched now moves the number (the provider-model-catalog
  two-ids-on-one-line case). One combined non-overlapping regex, so
  'providerId === "codex"' counts once, not twice.
- Include .js/.mjs/.cjs/.jsx, not only .ts/.tsx — core has provider
  references in .mjs (e.g. the host-daemon bundle manifest).
- Remove the lowercase fast-reject that skipped files whose only match was
  an uppercase constant (PRODUCT_DEFAULT_PROVIDER_ID). The full scan is
  ~0.2s; no pre-filter needed.
- Add a base-branch guard (--base <ref>, wired to origin/<base> in CI):
  reject any per-file increase versus the base branch's committed
  baseline, so an author cannot add a branch, run --write, and pass on the
  raised baseline. Degrades to the exact committed check when the base has
  no baseline yet (bootstrap).
- --write refuses to raise the total unless BB_RATCHET_ALLOW_INCREASE=1.
- Refactor the scanner into a pure exported scanTree(root) and rewrite the
  self-test against a tmpdir fixture tree: real counting assertions
  (multi-id line, named constants, .mjs/.js, uppercase-only, exclusions,
  no double count) instead of scanning the live repo. Removes the
  overwrite-a-real-file probe and the Turbo-hash staleness.

Baseline is now an occurrence count: 214 references across 57 core files
(was 198 line-matches; the same code, counted correctly). Prettier clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@SawyerHood

Copy link
Copy Markdown
Collaborator Author

Thanks — all six review points were on the money and are fixed in the pushed commit:

  1. Occurrence count, not lines. One combined non-overlapping regex; a second id on an already-matching line now counts. providerId === "codex" counts once (the RHS-literal alternatives cover the comparison form, so no double count). Fixture test asserts the two-ids-on-one-line case.
  2. .js/.mjs/.cjs/.jsx included. Fixture test covers .mjs and .js.
  3. Fast-reject removed. The lowercase pre-filter that skipped uppercase-only files (PRODUCT_DEFAULT_PROVIDER_ID) is gone; the full scan is ~0.2s. Fixture test covers an uppercase-only constant.
  4. Base-branch guard. New --base <ref>, wired in CI to origin/<base_ref> after a shallow fetch: any per-file increase versus the base branch's committed baseline fails, so add-a-branch-then---write can't pass. Degrades to the exact committed check when the base has no baseline yet (bootstrap — which is this PR).
  5. --write won't raise the total without BB_RATCHET_ALLOW_INCREASE=1.
  6. Pure scanTree(root) + fixture tests. The self-test builds a tmpdir tree with known literals and asserts real counts; it no longer writes/deletes a real source path, and no longer depends on live-repo state (which also addresses the Turbo-hash staleness — the primary guard is the uncached CI step regardless).

Baseline is now an occurrence count: 214 across 57 files (was 198 line-matches; same code, counted correctly). The two dangling docs/provider-plugin-api.md references now also point at the live design report. Prettier clean; @bb/scripts 105 tests green.

AGENT GENERATED: by Claude Opus 4.8

SawyerHood added a commit that referenced this pull request Aug 21, 2026
Six material fixes from the SlopCop review of #2120:

- Count occurrences, not matched lines. A second provider id on a line
  that already matched now moves the number (the provider-model-catalog
  two-ids-on-one-line case). One combined non-overlapping regex, so
  'providerId === "codex"' counts once, not twice.
- Include .js/.mjs/.cjs/.jsx, not only .ts/.tsx — core has provider
  references in .mjs (e.g. the host-daemon bundle manifest).
- Remove the lowercase fast-reject that skipped files whose only match was
  an uppercase constant (PRODUCT_DEFAULT_PROVIDER_ID). The full scan is
  ~0.2s; no pre-filter needed.
- Add a base-branch guard (--base <ref>, wired to origin/<base> in CI):
  reject any per-file increase versus the base branch's committed
  baseline, so an author cannot add a branch, run --write, and pass on the
  raised baseline. Degrades to the exact committed check when the base has
  no baseline yet (bootstrap).
- --write refuses to raise the total unless BB_RATCHET_ALLOW_INCREASE=1.
- Refactor the scanner into a pure exported scanTree(root) and rewrite the
  self-test against a tmpdir fixture tree: real counting assertions
  (multi-id line, named constants, .mjs/.js, uppercase-only, exclusions,
  no double count) instead of scanning the live repo. Removes the
  overwrite-a-real-file probe and the Turbo-hash staleness.

Baseline is now an occurrence count: 214 references across 57 core files
(was 198 line-matches; the same code, counted correctly). Prettier clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/provider-literal-ratchet branch from f5deeee to 2e5fdd7 Compare August 21, 2026 07:16
SawyerHood added a commit that referenced this pull request Aug 21, 2026
…2136)

Stacked on #2124 (`bb/provider-contract`). WS1a of the provider-plugin
migration: the generic assembler, one streaming + one usage dialect,
extension ingest validation, the published testing kit, the scripted
echo bridge as the harness default, and — last commit — the deletion of
the legacy `ProviderAdapter` path and the v2 delta dialects.

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

## What was wrong

The contract PR landed the grammar v3 vocabulary but left the assembler
stubbed (`UnsupportedDeltaShapeError` in every v3 shape and in
`extension.state`), kept two streaming and two usage dialects, validated
no extension payload, published no testing kit, and the runtime still
carried a legacy `ProviderAdapter` interface whose only non-bridge
implementation was a 674-line fake adapter driven by a legacy-dialect
script (the integration harness's default provider).

## What changed (one commit per layer; the last deletes)

1. **Assembler builds the v3 core kinds** (`92ae9cd`) — `fileRead`,
`search`, `planSteps` open pending and settle from the terminal shape
like `command`; a foreground `delegation` settles through
`item/completed`, a `background: true` delegation is thread-attached
like a background task (`item/delegation/progress|completed`, no turn
needed, survives turn settlement and `session.ended`).
`ASSEMBLER_GRAMMAR_VERSIONS` → `[2, 3]`.
2. Presentation persistence shipped upstream in #2124 (`fc88906`);
nothing to do here.
3. **Extension kinds + ingest validation** (`f174c5d`) — `extension`
items and the new `thread/extensionState/updated` event assemble. The
server validates every extension payload against the owning plugin's
declared Standard Schema at ingest
(`apps/server/src/internal/extension-payloads.ts`; registrations carry
the validators, the registry resolves `"<pluginId>/<name>"` through the
plugin-id prefix; 64 KiB cap). An undeclared kind, a schema miss, a
validator error, or an oversized payload is persisted as
`provider/unhandled` in the same batch slot — G11-visible, never
dropped, never stored unvalidated. `extensionKindSchema` parses to the
`ExtensionKind` type.
4. **One streaming dialect, one usage dialect** (`cce9415`) — every text
stream is an item keyed like any other:
`item.textDelta`/`item.textClose`, anonymous streams keyed by
`key.channel` (+ `parentRef`). `usage { total, last, modelContextWindow
}` is forwarded verbatim; bridges that report per turn (claude, pi)
accumulate with the bridge kit's `addTokenUsage` and reset at
`session.reset`; codex sends `contextWindow` (now with `providerTurnId`)
beside it. All four bridges + the echo example migrated. **Calibration
goldens unchanged** for codex, claude, acp, pi.
5. **`provider/recovery`** (`e5f5a3b`) — decoded by the adapter,
forwarded to the runtime's new `onProviderRecovery` hook (the daemon
logs it; WS4 acts per kind). Grammar negotiation shipped upstream
(`0816b4c`).
6. **Published testing kit** (`03815e3`) —
`@get-bb/plugin-sdk/provider-bridge/testing`: conformance kit, the real
assembler, delta→event collector, JSON-RPC harness, calibration
normalizer. Framework-agnostic (`captureBridgeJsonRpcOutput` patches
`process.stdout.write`, no `vi`). `experimental_` value names +
`docs/api_to_audit.md` entry; G10 doc-sync test asserts the entry. The
assembler moved into `@bb/provider-bridge-protocol` (`assembler`
subpath) — the SDK cannot depend on the runtime (cycle). The echo
example and every first-party bridge suite import only
`@get-bb/plugin-sdk/provider-bridge` + the testing entry; the echo
example's `@bb/*` devDependencies are gone.
**Scripted echo bridge as the harness default** (`3d3cb9e`) —
`tests/scripted-echo-provider` (the echo bridge + scripted directives:
`delay:`, `approve:`, `ask_user`, `call_tool:`, `hold_turn`,
`fail_turn:`, …; session/process behaviour via
`providerOptions.scripted` / `SCRIPTED_ECHO_OPTIONS`;
`SCRIPTED_ECHO_RECORD_PATH` records every request,
`SCRIPTED_ECHO_PROCESS_LOG_PATH` every process step). Passes the
conformance suite. The integration harness has no `adapterFactory` seam:
the fake providers are declarations backed by the built scripted
artifact, run by the daemon through the real adapter.
7. **Deletion** (`a9a3950`) — `ProviderAdapter` → concrete
`BridgeProtocolAdapter`; `adapterFactory` /
`createAgentRuntimeWithAdapters`; the fake adapter + script;
`message.delta/close`, `usage.turn/exact` from schema + assembler;
assembler `[3, 3]` and every bridge reports it (a bridge that predates
`grammarVersions` reads as v2 and is refused at the handshake; the
conformance handshake scenario checks the same). Runtime unit suites +
the daemon's thread.stop race suite run the scripted echo bridge through
the real bootstrap + adapter + assembler; the process manager gains a
`createAdapter` seam for raw-script spawn/stderr/exit tests.
`HOST_DAEMON_PROTOCOL_VERSION` → 148.

### Tests deleted (subject no longer exists)
- command-contract: "rejects required adapter commands that return no-op
plans", "rejects no-op steer commands", the noop half of "rejects no-op
stop commands" (only the fake adapter's `buildCommandPlan` seam could
plan a noop; handshake gating is pinned in
`bridge-protocol-adapter.test.ts`).
- lifecycle: "passes Codex-shaped thread/start ids to accepted command
translation" (`translateAcceptedCommand` is a no-op for bridges),
"preserves merged shell env when reconfiguring a thread" (the
session-rebuild path is unreachable: bridges classify every settings
change as `live`; env is covered by the start/resume tests), "drops a
delta into an item nothing opened, with a visible warning" (the only
seam that could feed a malformed event was the `translateEvent`
override; the grammar gate is exercised by the new replayed-turn bridge
test).
- input-accepted: "suppresses provider-emitted user message echoes"
(bridges never emit `userMessage`).
- multi-thread: "maps thread/started before identity", "drops unscoped
provider events" (legacy `thread/event` dialect routing; every
`thread/delta` names its bb thread id).
- process-lifecycle: "continues startup when an optional post-initialize
read is unsupported" (the only post-initialize request is the handshake
itself).
Everything else is ported faithfully; literal-id assertions became
assertions on the assembler-minted ids (#1224), `AdapterCommand`
recordings became request-record assertions on the same wire facts.

## Regression oracle status

- **Parity replay (A2)**: `bb/provider-recordings` does not exist on
origin; not in the base. Coordinator requires it before merge.
- **Corpus row snapshots (A4, #2121)**: not in the base.
- **G1 ratchet (#2120)**: not in the base. This PR adds no provider-id
literal to core (the scripted bridge's codex-shaped archived error is
test-only).
- **Conformance kit**: green for echo, scripted echo, codex,
claude-code, acp, pi.
- **Calibration goldens**: byte-identical for codex, claude, acp, pi
through the dialect migration.

### Intended byte-level difference (allowlist)
- **WS1a #2136, layer 4**: a provider-named text item that streamed
before `session.ended` now settles with its accumulated text instead of
its opened (empty) shape. Reason: one streaming dialect means the
assembler owns the stream text for named items too; losing streamed text
on interrupt was the v2 behaviour, not a feature.

### Wire discipline
`HOST_DAEMON_PROTOCOL_VERSION` 147 → 148: the daemon emits a new event
type (`thread/extensionState/updated`) and its bridges speak grammar v3
only, which a 147 daemon would refuse at the handshake.
`PROVIDER_BRIDGE_PROTOCOL_VERSION` stays 2 (envelope and methods
unchanged; the grammar range gates).

## Gates (all `--concurrency 4`)

Typecheck — green, 27 tasks: `@bb/domain @bb/provider-bridge-protocol
@bb/agent-runtime @bb/server @bb/host-daemon @bb/host-daemon-contract
@get-bb/plugin-sdk @bb/thread-view @bb/db` and `provider-codex
provider-claude-code provider-acp provider-pi echo-provider
scripted-echo-provider @bb/integration-tests @bb/app @bb/mobile
@bb/cli`.

Tests:
| package | result |
|---|---|
| @bb/domain | 148/148 |
| @bb/provider-bridge-protocol (incl. the assembler suite) | 213/213 |
| @bb/host-daemon-contract | 52/52 |
| @get-bb/plugin-sdk | 127/127 |
| @bb/thread-view | 379/379 |
| @bb/db | 406/406 |
| @bb/agent-runtime (incl. pi conformance) | 336/336 |
| bb-plugin-provider-codex | 172/172 |
| bb-plugin-provider-claude-code | 263/263 |
| bb-plugin-provider-acp | 181/181 |
| bb-plugin-echo-provider / scripted-echo-provider | 2/2, 1/1 |
| @bb/host-daemon | 556/556 |
| @bb/integration-tests (fake stack on the scripted bridge) | 55/55 |
| @bb/server | 1821/1823 — two pre-existing, environmental locals:
`internal-skill-trees` (umask 0664 vs 0644, passes in CI) and
`plugin-update` "waits one full interval" (5 s timeout under load; test
and subject untouched by this PR) |

Perf (assembler micro-benchmark, 20 000 mixed turns = 1 340 000 deltas →
1 380 000 events, 3 runs each, same workload): contract head (v2
dialect) min 457 ms / 2.93 M deltas/s; this branch (v3 dialect) min 436
ms / 3.07 M deltas/s — ~4 % faster, heap delta no worse. Within the +10
% gate.

> AGENT GENERATED: by Claude Opus 5

---------

Co-authored-by: Claude <[email protected]>
SawyerHood added a commit that referenced this pull request Aug 21, 2026
…le ProviderInfo (#2148)

> **Stacked on #2153 (recordings + parity harness) ← #2136 (WS1a) ←
#2124 (contract)** — re-stacked linearly at the coordinator's request so
the full stack merges conflict-free. Base: `bb/provider-recordings`. DO
NOT MERGE — coordinator review.

## What was wrong

Provider facts lived in core tables keyed by provider id, and the shared
server↔daemon execution contract carried Claude/Codex-named knobs:

- `PRODUCT_PROVIDER_ORDER`, `RESERVED_PROVIDER_ID_OWNERS`,
`PRODUCT_DEFAULT_PROVIDER_ID` in the server registry.
- Five `codex*`/`claudeCode*` keys on the shared `AppSettings`, resolved
in `thread-commands.ts` by `providerId === …`.
- `claudeCodePermissionMode`, `workflowsEnabled`, `memoryEnabled`,
`providerSubagentsEnabled` on `RuntimeThreadExecutionOptions` (the G2
allowlist entry), plus a `providerId !== "claude-code"` guard in the
runtime.
- Three copies of the Claude model catalog (plugin, server, app) and a
vendored `PLACEHOLDER_PROVIDER_INFOS` roster in the app; sign-in hints,
install URLs, brand prefixes and plan-mode copy in per-provider tables
on web and mobile.
- The contract PR added the additive declaration / `ProviderInfo`
fields; nothing populated or consumed them (G10 gaps: `family`,
`models`, `env`, `deriveProviderOptions`, `promptMode`).

## What changed

Spec: `WS2a-registry.md` layers 1–7 (docs/provider-plugin-api.md §1,
§6).

**L1 — `bb.providers.register` + single `ProviderInfo`.** New
`bb.providers` namespace on `BbPluginApi`;
`bb.agents.experimental_registerProvider` stays as an alias sharing the
same registration table (additive-then-delete: both work; the four
first-party `server.ts` files moved to the new call).
`buildPluginProviderRegistration` now projects `strings`,
`reasoningLevels` (declared options, or the coarse ladder labelled),
`serviceTiers` (declared, or `default`/`fast` when
`supportsServiceTier`), `extensionKinds` namespaced by the **owning
plugin id**, and `family`. New declaration fields, validated in the
shared host policy: `experimental_family`,
`experimental_models.fallback`, `experimental_env.passthrough`,
`experimental_deriveProviderOptions`.

**L2 — options hook + `promptMode`.** The server runs the owning
plugin's `experimental_deriveProviderOptions(ctx)` on every session/turn
command (`ctx = { threadId, projectId, model, permissionMode,
promptMode?, settings }`, `settings` = the plugin's own non-secret
`bb.settings` values, read synchronously) and sends the bounded-JSON
result as a REQUIRED `options.providerOptions`. `promptMode: "plan"` is
set only when the prompt carries the provider's *declared* `plan`
composer command (Pi never sees it). `claudeCodePermissionMode` + the
three booleans are deleted from `runtimeThreadExecutionOptionsSchema`,
`ProviderExecutionContext`, and the runtime's literal-id guard; the
bridge adapter merges the bag over the static bridge options instead of
rest-sweeping "provider-flavored" fields. `bridgeExecutionOptionsSchema`
gains `promptMode`. The Claude plugin maps `promptMode` to its native
plan flag inside its own bag; the Claude/Codex bridges already read
their knobs from the bag, so no bridge code changed.

**L3 — provider-scoped settings.** The five keys are gone from
`appSettingsSchema`; `provider-codex` defines
`memoryEnabled`/`subagentsDisabled`, `provider-claude-code` adds
`workflowsDisabled`, both derived into `providerOptions` by their hooks.
Drizzle data migration `0105_provider_settings_to_plugins` copies stored
values into `plugin_settings` (existing plugin rows win) and retires the
shared rows. `supportsWorkflows` is deleted from the declaration and
`ProviderServerCapabilities` (it only ever fed `workflowsEnabled`). Web:
the hardcoded Codex/Claude settings pages, `SETTINGS_PROVIDER_ENTRIES`,
`/settings/providers/:providerId` are gone; a generic **Settings →
Providers** bucket lists every registered provider with order + default
controls, and per-provider knobs live on the plugin's settings page.
Mobile: `ProviderSettingsScreen` and its route are gone (plugin detail
already renders `bb.settings` forms).

**L4 — flat ids + user order.** `RESERVED_PROVIDER_ID_OWNERS`,
`reservedProviderIdProblem`, `PRODUCT_PROVIDER_ORDER`,
`PRODUCT_DEFAULT_PROVIDER_ID` deleted. Collision = first live
registration wins (`assertProviderRegistrable` keeps only the "has a
bridge" check). `registry.list()` orders by an install rank the plugin
runtime supplies (bundled plugins by their `BUNDLED_PLUGINS` index —
reordered to codex, claude-code, pi, acp so today's picker order is
preserved — then others by `installedAt`, then registration sequence),
under two new app settings `providerOrder: string[]` and
`defaultProviderId: string | null` (`bb settings general …` works
unchanged, docs/configuration.md updated). `thread-default-policy`
resolves the default as the user's choice when registered+available,
else the first available listed provider.

**L5 — duplicate catalogs.** Server `claude-code-fallback-models.ts`
deleted; the model-list route serves `registration.fallbackModels` (from
the declaration) on a transient probe failure. App
`PLACEHOLDER_PROVIDER_INFOS` and `CLAUDE_CODE_PLACEHOLDER_MODELS`
deleted (a cold cache waits for the first probe; a remembered
per-routing roster still replays). The Claude catalog data moved to an
import-free `src/model-catalog-data.ts` (the server loads `server.ts`
with only the SDK root specifier resolvable, so it must not pull in
`@get-bb/plugin-sdk/provider-bridge`). Web + mobile usage banners, the
picker's brand strip, the missing-CLI install link, and the plan-mode
permission display now read `ProviderInfo.strings` — the mobile usage
table's keys (`claudeCode`, `cursor`) never matched the server's
provider-id keys, which this fixes as a side effect.
`effective-prompt-mode` keys on the presence of `strings.planModeCopy`,
not `providerId === "claude-code"`.

**L6 — directory.** `bb.sdk.providers.list()` already existed
(verified). New `app.experimental_useProviders()` (`{ status, providers:
ProviderInfo[] }`) in the SDK, app implementation, and test harness
(`providers` option); `provider-retry` and `automations` read provider
names from it instead of local tables. Icons remain vendored — see the
api_to_audit entry for why.

**`env.passthrough`** replaces the daemon's hardcoded
`BB_CLAUDE_CODE_EXECUTABLE` forwarding: `bridgeLaunch.envPassthrough`
(REQUIRED on the wire) names the variables; the runtime picks exactly
those from the daemon env into the bridge process env. #2153's
record-mode forward (`BB_PROVIDER_BRIDGE_RECORD_DIR`, read from the
daemon's own env) stays beside it in `providerProcessEnvFromShellEnv` —
it is a daemon concern, not a provider declaration.

**Wire:** `HOST_DAEMON_PROTOCOL_VERSION` 148 (WS1a) → **149**;
protocol.ts keeps all three log entries (147 contract, 148 WS1a, 149
this PR). Changes: `options` shape (fields removed, `providerOptions`
required, `promptMode` optional) and `bridgeLaunch.envPassthrough`
required.

**Docs / surfaces:** docs/api_to_audit.md (registration entry rewritten
for flat ids + install order; target-state-fields entry expanded with
the hook/models/env/family and migration; new
`experimental_useProviders` entry), bb-plugin-authoring SKILL.md
(`bb.providers.register` with every new field), docs/configuration.md
(Providers bucket, `providerOrder`/`defaultProviderId`, plugin-scoped
knobs), docs/provider-bridge-protocol.md alias rename, echo-provider
example.

### G10 doc-sync gaps (`provider-plugin-doc.test.ts`)

`family`, `models`, `env`, `deriveProviderOptions`, `promptMode` →
mapped to real fields. `maintenance` stays a gap, retargeted to the
stabilization audit: it is a pure fold of the three
`experimental_provider{Health,Usage,Installation}` booleans, and
declaring the same three facts twice during the transition would break
one-fact-one-place.

### Deliberately NOT done here (noted for WS4)

- `AgentRuntimeSkillRoot` is still a closed union keyed by first-party
id (WS1a's flag). Dissolving it needs the `skills/configure` root to
carry both the skills dir and the plugin root (Claude consumes the
latter), i.e. a bridge-protocol + Claude bridge change — WS4's lane.
- `provider-registry.ts` keeps 9 `isAcpProviderId` hits for the dynamic
ACP tier (custom agents resolved from config) — WS2b deletes the tier.

### Relation to WS1a

Now stacked on top of WS1a (#2136), so there is no sibling overlap to
reconcile: the restack commit ports the scripted-echo launch helper and
WS1a's new dispatch / extension-payload tests to this PR's shapes
(`envPassthrough`, `readSettings`, no `supportsWorkflows`) and keeps
`HOST_DAEMON_PROTOCOL_VERSION = 149` with all three log entries.

## Guardrails

**G1 (provider-literal ratchet,
`scripts/check-provider-literal-ratchet.mjs` from #2120 — not in this
base, so no baseline file is committed here; measured with the script
checked out from that branch):**

`214 → 149` references, `57 → 41` core files.

| file | before | after |
|---|---|---|
| `apps/app/src/components/pickers/model-brand-prefix.ts` | 2 | 0 |
| `apps/app/src/components/pickers/model-load-error-message.tsx` | 1 | 0
|
| `apps/app/src/components/settings/UsageLimitsSettingsSection.tsx` | 2
| 0 |
| `apps/app/src/components/settings/settings-nav.tsx` | 2 | 0 |
| `apps/app/src/hooks/queries/system-queries.ts` | 7 | 0 |
| `apps/app/src/views/SettingsView.tsx` | 4 | 0 |
| `apps/mobile/src/data/settings/usage-limits-model.ts` | 8 | 0 |
| `apps/mobile/src/screens/settings/ProviderSettingsScreen.tsx` | 4 | 0
(deleted) |
| `apps/mobile/src/screens/settings/SettingsScreen.tsx` | 2 | 0 |
| `apps/mobile/src/screens/shell/hrefs.ts` | 2 | 0 |
| `apps/server/src/services/providers/provider-registry.ts` | 24 | 9 |
| `apps/server/src/services/system/execution-options.ts` | 1 | 0 |
| `apps/server/src/services/threads/thread-commands.ts` | 6 | 0 |
| `apps/server/src/services/threads/thread-default-policy.ts` | 4 | 0 |
| `packages/agent-runtime/src/execution-options.ts` | 1 | 0 |
| `packages/client-core/src/prompt/effective-prompt-mode.ts` | 2 | 0 |
| `packages/plugin-sdk/src/app-contract.ts` | 2 | 0 |

**G2 (`provider-contract-purity`):** allowlist now **empty** —
`claudeCodePermissionMode` removed with the field.

**Registry equality:** `first-party-provider-plugins.test.ts` pins the
client-read `ProviderInfo` fields (id, displayName, logoUrl, available,
the three maintenance booleans, capabilities, composerActions) for codex
/ claude-code / pi / acp-cursor to their pre-PR values, plus the picker
order, and asserts the new projections are filled.

## How I verified

All with `--concurrency 4`:

- `turbo run typecheck` — **74/74 tasks green** (whole repo).
- `turbo run build` — 18/18 green. `turbo run lint` — green
(pre-existing app warnings only).
- `turbo run test` for `@bb/server` (193 files / 1817 tests; the only
failure is the known local-umask `internal-skill-trees` case, passes in
CI), `@bb/app` (414 files), `@bb/mobile` (124), `@bb/agent-runtime`
(31), `@bb/host-daemon` (47), `@bb/domain`, `@get-bb/plugin-sdk`,
`@bb/provider-bridge-protocol`, `@bb/host-daemon-contract`, `@bb/db`,
`@bb/client-core`, `@bb/cli`, `@bb/server-contract`, `@bb/thread-view`,
`@bb/scripts`, `@bb/plugin-build`, `@bb/demo-server`, and the plugins
`provider-claude-code`, `provider-codex`, `provider-acp`,
`provider-retry`, `automations`, `tasks` — all green.
- Tests that fail before / pass after:
`plugin-provider-registration.test.ts` (projection of
strings/tiers/levels/kinds/family/models/env + the hook bound to
settings + non-JSON rejection), `provider-registry.test.ts`
(install-rank order, user order overlay, unknown default → null, freed
ids), `thread-default-policy.test.ts` (user default + order),
`thread-runtime-config.test.ts` (providerOptions per provider, hook
context, promptMode only for plan-declaring providers),
`first-party-provider-plugins.test.ts` (client-field pin),
`migrate.test.ts` (0105 carries values, plugin rows win, shared rows
retired), `ProvidersSettingsSection.test.tsx`,
`execution-options.test.ts` (structural bag equality), mobile
`settings-models.test.ts` (usage rows keyed by provider id).

Not run: the live-CLI integration suite
(`agent-runtime#test:integration`) and the corpus gate (not in this
base).

> AGENT GENERATED: by Claude Opus 5

---------

Co-authored-by: Claude <[email protected]>
SawyerHood and others added 5 commits August 21, 2026 14:21
The provider-plugin migration removes core's per-provider carve-outs. To
keep that irreversible, this adds a CI guard that counts provider-id
literals in core (everything outside plugins/provider-* and examples) and
holds a per-file baseline that may only shrink. Adding a providerId ===
"codex" branch, or a new core file that names a provider id, fails the
build; removing literals requires regenerating the baseline so each
reduction is a committed, visible diff. When the baseline reaches zero the
file and the guard are deleted.

Scope is provider-*id* literals only. Tool-name keying (thread-view's
Read/Task/TodoWrite tables) is retired by its own workstream and would add
false positives here, so it is tracked separately.

Baseline at introduction: 198 literals across 58 core files. Top
concentrations are the ones the migration dismantles: the provider
registry (23), the daemon skill-discovery tables (20), the app icon map
(14), and the runtime's codex recovery block (11).

- scripts/check-provider-literal-ratchet.mjs (check / --write / --list),
  pure Node, no ripgrep dependency on the runner
- scripts/provider-literal-baseline.json
- wired into the ci.yml checks job beside the other repo guards
- self-test in @bb/scripts covering pass, planted-literal failure, and
  baseline-total agreement
- documented in docs/debugging-and-qa.md

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Six material fixes from the SlopCop review of #2120:

- Count occurrences, not matched lines. A second provider id on a line
  that already matched now moves the number (the provider-model-catalog
  two-ids-on-one-line case). One combined non-overlapping regex, so
  'providerId === "codex"' counts once, not twice.
- Include .js/.mjs/.cjs/.jsx, not only .ts/.tsx — core has provider
  references in .mjs (e.g. the host-daemon bundle manifest).
- Remove the lowercase fast-reject that skipped files whose only match was
  an uppercase constant (PRODUCT_DEFAULT_PROVIDER_ID). The full scan is
  ~0.2s; no pre-filter needed.
- Add a base-branch guard (--base <ref>, wired to origin/<base> in CI):
  reject any per-file increase versus the base branch's committed
  baseline, so an author cannot add a branch, run --write, and pass on the
  raised baseline. Degrades to the exact committed check when the base has
  no baseline yet (bootstrap).
- --write refuses to raise the total unless BB_RATCHET_ALLOW_INCREASE=1.
- Refactor the scanner into a pure exported scanTree(root) and rewrite the
  self-test against a tmpdir fixture tree: real counting assertions
  (multi-id line, named constants, .mjs/.js, uppercase-only, exclusions,
  no double count) instead of scanning the live repo. Removes the
  overwrite-a-real-file probe and the Turbo-hash staleness.

Baseline is now an occurrence count: 214 references across 57 core files
(was 198 line-matches; the same code, counted correctly). Prettier clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… ratchet

A full-stack dry run surfaced a scope gap: the ratchet's test exclusions
covered test/, tests/, and __tests__/ but not this repo's src/testing/
convention, so the parity and conformance harnesses landing in #2153
(which must name providers to map each recording to its bridge module and
fake child) registered as 10 new core carve-outs. That is test tooling,
the same category as __tests__, not a provider branch in core.

Add "testing" to the excluded path segments, document why in the header,
and add a fixture test proving a provider id under src/testing/ does not
count. Regenerated baseline: 213 references across 56 files (one existing
src/testing hit was already being miscounted as core).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…e onto current main

The full-stack dry run flagged apps/mobile/src/screens/dev/prompt-chip-fixtures.ts,
a dev-only fixture screen that #2138 added to main after the baseline was
taken. It is fixture data, the same category as .ladle and stories, not a
provider branch in core. Exclude the dev/ segment and regenerate the
baseline against current main: 209 references across 55 files.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The provider-plugin v3 stack (#2124 … #2179) landed on main and deleted 61
provider-id references from core: the reserved-id tables, the three Claude
model tables, the placeholder provider infos, the claude/codex settings
knobs on the shared contract, and the per-provider runtime branches the
registry and bridges now own. Regenerated baseline: 148 references across
40 core files (from 209 / 55). The ratchet holds it there.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/provider-literal-ratchet branch from 2e5fdd7 to aa40030 Compare August 21, 2026 14:21
The two tests that scan the real repo tree took 6.4s and 5.7s on the CI
runner and tripped vitest's 5s default (they take ~0.3s locally). The
fixture-based tests, which carry the real coverage, were unaffected. Same
class of slow-runner flake the agent-runtime bridge tests hit; same fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@SawyerHood
SawyerHood merged commit fcada5a into main Aug 21, 2026
13 checks passed
@SawyerHood
SawyerHood deleted the bb/provider-literal-ratchet branch August 21, 2026 14:42
SawyerHood added a commit that referenced this pull request Aug 21, 2026
## What was wrong

`plugins/provider-acp/server.ts` declared `fork: "tip"` for every
built-in ACP agent through `ACP_BASE_CAPABILITIES`. The server projects
that to `supportsFork: true` (the `POST /api/v1/threads/fork` gate and
the app's "Fork into new thread" action). But neither `cursor-agent acp`
(2026.08.11) nor `grok agent stdio` advertises
`sessionCapabilities.fork` in its ACP `initialize` reply, so the
bridge's per-session guard (`bridge.ts`: "does not advertise
session/fork support") rejected the fork only after the server had
already created and started the fork thread. The thread landed in
`status: error` with `system/error { code: thread_command_failed }`.
Issue: #1833. Report: https://get-bb.github.io/reports/issues/1833.html

The issue suggested deriving fork per agent at initialize time. That is
not a drop-in: the agent's `initialize` happens per session inside the
bridge after the server has created the thread, and there is no
daemon-to-server capability channel. The declaration is the server-side
source of truth (same as `supportsManualCompaction`), so it has to match
the agent.

## What changed

- `plugins/provider-acp/server.ts`: `acp-cursor` and `acp-grok` now
declare `fork: "none"`. The base stays `"tip"`; opencode, omp
(oh-my-pi), and hermes-agent all advertise `sessionCapabilities.fork` in
their ACP adapters (checked upstream sources:
`packages/opencode/src/acp/service.ts`,
`packages/coding-agent/src/modes/acp/acp-agent.ts`,
`acp_adapter/server.py`). Added a comment on the base capability
explaining why the declaration must match the agent.
-
`apps/server/test/services/plugins/first-party-provider-plugins.test.ts`:
the golden pin now records the fork ladder per first-party provider and
asserts `registration.serverCapabilities.fork`,
`registry.supportsFork()`, and the composed
`ProviderInfo.capabilities.supportsFork` against it.

Effects: `POST /threads/fork` on a Cursor or Grok thread returns HTTP
400 `Provider acp-cursor does not support thread forks` without creating
a thread; the app hides the fork action for those providers; the
declared ceiling that rides `bridgeLaunch.capabilities.fork` to the
daemon also becomes `"none"`, so the runtime rejects `thread/fork`
before spawning the agent.

No wire shape changes (the existing `fork` field just carries a
different value), so no `HOST_DAEMON_PROTOCOL_VERSION` bump. No CLI or
config surface changes. Custom `acp-*` agents still fall back to the
tier-wide `"tip"`; giving them a per-agent `fork` config field is a
separate change.

## How you verified

Probed the agents directly (same `initialize` request the bridge sends):

```
$ node probe.mjs cursor-agent acp     -> sessionCapabilities: { list: {} }                 fork advertised: false
$ node probe.mjs grok agent stdio     -> sessionCapabilities: { list, resume, close }      fork advertised: false
```

New test fails on origin/main with the test file applied and the plugin
unchanged:

```
FAIL test/services/plugins/first-party-provider-plugins.test.ts > first-party provider plugins > are the sole source of the built-in providers
AssertionError: acp-cursor: expected 'tip' to be 'none' // Object.is equality
```

Passes on this branch (`Tests 2 passed (2)`).

From the committed tree (`git status --porcelain` empty):

```
pnpm exec turbo run typecheck --filter=@bb/server --filter=bb-plugin-provider-acp
 Tasks:    6 successful, 6 total
pnpm exec turbo run test --filter=@bb/server --filter=bb-plugin-provider-acp
 bb-plugin-provider-acp: Tests 181 passed (181)
 @bb/server: Test Files 1 failed | 194 passed (195); Tests 1 failed | 1822 passed (1823)
```

The one server failure is `test/internal/internal-skill-trees.test.ts`
(`mode: 420` vs `436`), the known local umask 0002 failure unrelated to
this change; it passes here under `umask 022` and in CI.

Manual repro on this branch against a dev instance of this worktree:

```
$ curl -s $BB_SERVER_URL/api/v1/system/providers | ... supportsFork
codex True / claude-code True / pi True / acp-cursor False / acp-grok False
$ pnpm bb:dev thread spawn --provider acp-cursor ... --prompt "Reply only with ok."   -> thr_7u6gb8ppn2, reached idle
$ pnpm bb:dev thread fork thr_7u6gb8ppn2 --workspace reuse --prompt "Reply only with ok." --json
Error: Failed to fork thread thr_7u6gb8ppn2: HTTP 400: Provider acp-cursor does not support thread forks
$ GET /threads?projectId=...   -> only thr_7u6gb8ppn2 (idle); no fork thread created
```

Fixes #1833

> AGENT GENERATED: by Claude Opus 5


## Rebase

Rebased onto `origin/main` (`cf00cfe06`) after the grammar-v3 bridge
stack (#2148 `bb.providers.register` + single `ProviderInfo`, #2179
WS1b-acp) rewrote both touched files. The fix maps 1:1 onto the new
code:

- `plugins/provider-acp/server.ts`: the declarations now carry
`experimental_strings` / `experimental_serviceTiers` and register
through `bb.providers.register`, but `ACP_BASE_CAPABILITIES.fork: "tip"`
and the per-agent `capabilities` spreads are unchanged, so the `fork:
"none"` overrides for `acp-cursor` and `acp-grok` and the base comment
apply as before. Still no wire-shape change, so no
`HOST_DAEMON_PROTOCOL_VERSION` bump.
-
`apps/server/test/services/plugins/first-party-provider-plugins.test.ts`:
main dropped `supportsWorkflows` from the golden pin (conflict resolved
by adding only the `fork` ladder), and #2148 added a new test, "pins the
client-read ProviderInfo fields of the four core providers", that pinned
`acp-cursor` at `supportsFork: true`. That pin now reads `supportsFork:
false` with a `#1833` comment; `supportsSessionRewind: false` is
unchanged. The fork-ladder assertions in the first test
(`registration.serverCapabilities.fork`, `registry.supportsFork()`,
composed `ProviderInfo.capabilities.supportsFork`) carried over
verbatim; `serverCapabilities.fork` still exists on main
(`plugin-provider-registration.ts` projects `supportsFork:
capabilities.fork !== "none"`).

Re-verified on the new base. With `plugins/provider-acp/server.ts`
reverted to `origin/main` and the test file in place, the tests fail (so
main does not already cover the bug):

```
FAIL ... > are the sole source of the built-in providers
AssertionError: acp-cursor: expected 'tip' to be 'none' // Object.is equality
FAIL ... > pins the client-read ProviderInfo fields of the four core providers
AssertionError: expected { id: 'acp-cursor', …(8) } to strictly equal { id: 'acp-cursor', …(8) }
Tests 2 failed | 1 passed (3)
```

With the fix restored: `Tests 3 passed (3)`. From the committed tree
(`git status --porcelain` empty):

```
pnpm exec turbo run typecheck --filter=@bb/server --filter=bb-plugin-provider-acp
 Tasks:    6 successful, 6 total
pnpm exec turbo run test --filter=@bb/server --filter=bb-plugin-provider-acp
 bb-plugin-provider-acp: Test Files 15 passed (15); Tests 196 passed (196)
 @bb/server: Test Files 1 failed | 197 passed | 1 skipped (199); Tests 1 failed | 1896 passed (1897)
```

The one server failure is again
`test/internal/internal-skill-trees.test.ts` (`mode: 420` vs `436`), the
known local umask 0002 failure; it passes in CI.

## Independent verification

Verified by a second agent on a separate worktree (branch
`verify-1833-r1` = `ece689920`, `origin/main` is an ancestor,
`mergeable: MERGEABLE`).

Commands run:

```
git fetch origin main && git fetch origin bb/fix-1833-acp-cursor-fork && git checkout -b verify-1833-r1 FETCH_HEAD
pnpm install --frozen-lockfile --prefer-offline && pnpm exec turbo run build
node probe.mjs cursor-agent acp   -> cursor-agent sessionCapabilities: {"list":{}} fork advertised: false
node probe.mjs grok agent stdio   -> grok sessionCapabilities: {"list":{},"resume":{},"close":{}} fork advertised: false
git checkout origin/main -- plugins/provider-acp/server.ts
cd apps/server && pnpm exec vitest run test/services/plugins/first-party-provider-plugins.test.ts
git checkout HEAD -- plugins/provider-acp/server.ts
cd apps/server && pnpm exec vitest run test/services/plugins/first-party-provider-plugins.test.ts
pnpm exec turbo run typecheck --filter=@bb/server --filter=bb-plugin-provider-acp
pnpm exec turbo run test --filter=@bb/server --filter=bb-plugin-provider-acp --force
```

Fail-before / pass-after:

- With `plugins/provider-acp/server.ts` reverted to `origin/main` and
the PR's test file in place: `Tests 1 failed | 1 passed (2)` with
`AssertionError: acp-cursor: expected 'tip' to be 'none' // Object.is
equality`.
- With the PR's source restored: `Tests 2 passed (2)`.

Typecheck and tests:

- `turbo typecheck` for `@bb/server` and `bb-plugin-provider-acp`:
`Tasks: 6 successful, 6 total`.
- `turbo test`: `bb-plugin-provider-acp` 14 files passed; `@bb/server`
1822 passed, 1 failed. The single failure is
`test/internal/internal-skill-trees.test.ts` (`mode: 420` vs `436`), the
known umask-0002 environment failure on this workstation; it also fails
on clean `main` here and passes in CI.

Repro on the fixed branch (own dev instance, server :20051, data dir
under `~/.bb-dev`, deleted afterwards):

- `GET /api/v1/system/providers` -> `acp-cursor False`, `acp-grok False`
(codex/claude-code/pi still `True`).
- Spawned an `acp-cursor` thread (`thr_4gh8bikbv6`), waited to `idle`,
then `pnpm bb:dev thread fork thr_4gh8bikbv6 --workspace reuse --prompt
"Reply only with ok." --json` -> `HTTP 400: Provider acp-cursor does not
support thread forks`. Thread list for the project still holds only the
source thread (`idle`); no errored fork thread was created. The original
symptom no longer reproduces.

CI: 11 checks pass, 2 skipped (Node Compatibility Smoke, iOS simulator
flows), none failing.

Review notes:

- Root-cause fix at the right layer: the server-side declaration is the
fork gate and the app affordance, and its value also rides
`bridgeLaunch.capabilities.fork` to the runtime adapter's
`effectiveFork()` ceiling, so `thread/fork` is refused before the agent
is spawned. No wire shape change, so no protocol bump is needed.
- Residual risk: custom `acp-*` agents configured through
`customAcpAgents` still inherit the tier-wide
`ACP_TIER_CAPABILITIES.supportsFork: true`
(`apps/server/src/services/providers/acp-provider-tier.ts`), so a custom
agent without `session/fork` still hits the errored-thread path. A
per-agent `fork` field on that config is a sensible follow-up, not a
blocker for this PR. opencode/omp/hermes fork support was checked from
upstream sources only (not installed here).

> AGENT GENERATED: by Claude Opus 5



## Independent verification (post-rebase)

Re-verified by a second agent after the rebase onto the grammar-v3
bridge rewrite (branch `verify-2150-rb` = `2d84751d9`, one commit on
`cf00cfe06`). `origin/main` had moved one more commit (`fcada5a3b`,
#2120 provider-literal ratchet) by the time of this check; a local `git
merge --no-commit origin/main` was clean (the ratchet scans core only
and excludes `plugins/provider-*`), and GitHub reports `mergeable:
MERGEABLE`.

Does the fix still target the right code path after the v3 rewrite? Yes:

- `apps/server/src/services/threads/thread-fork.ts:39`
(`requireForkCapableProvider`) still gates `POST /threads/fork` on
`providerRegistry.supportsFork()`, which for a registered plugin
provider reads `registration.info.capabilities.supportsFork` = `fork !==
"none"` (`plugin-provider-registration.ts:211`).
- The app still reads `ProviderInfo.capabilities.supportsFork`
(`useForkThreadFromMessage.ts:54`, `ThreadDetailView.tsx:977`,
`RootComposeView.tsx:538`).
- `provider-bridge-launch.ts:48-50` still forwards
`registration.serverCapabilities.fork` to the daemon, and
`packages/agent-runtime/src/bridge-protocol-adapter.ts`
`effectiveFork()` still takes the declaration as a ceiling over the
handshake, so `thread/fork` is refused before cursor-agent is spawned.
- The v3 bridge (`plugins/provider-acp/src/bridge/bridge.ts`) still
advertises `fork: "tip"` unconditionally in its handshake (line ~2372)
and only checks `agentCapabilities.sessionCapabilities.fork` per session
at agent initialize (lines 1718-1721, "does not advertise session/fork
support"). Nothing in the rewrite made the static declaration redundant;
it is still the only up-front gate.

Commands run:

```
git fetch origin main && git fetch origin bb/fix-1833-acp-cursor-fork && git checkout -b verify-2150-rb FETCH_HEAD
pnpm install --frozen-lockfile --prefer-offline && pnpm exec turbo run build
git checkout origin/main -- plugins/provider-acp/server.ts
cd apps/server && pnpm exec vitest run test/services/plugins/first-party-provider-plugins.test.ts
git checkout HEAD -- plugins/provider-acp/server.ts
cd apps/server && pnpm exec vitest run test/services/plugins/first-party-provider-plugins.test.ts
pnpm exec turbo run typecheck --filter=@bb/server --filter=bb-plugin-provider-acp
pnpm exec turbo run test --filter=@bb/server --filter=bb-plugin-provider-acp --force
```

Fail-before / pass-after (only non-test source file is
`plugins/provider-acp/server.ts`):

- With `server.ts` from `origin/main` and the PR's test file: `Tests 2
failed | 1 passed (3)`. Failing assertions: `AssertionError: acp-cursor:
expected 'tip' to be 'none' // Object.is equality` and, in the #2148 pin
test, `AssertionError: expected { id: 'acp-cursor', …(8) } to strictly
equal { id: 'acp-cursor', …(8) }` (supportsFork true vs false).
- With the PR's source restored: `Tests 3 passed (3)`.

Typecheck and tests (from the committed tree, `git status --porcelain`
empty):

- `turbo typecheck`: `Tasks: 6 successful, 6 total`.
- `turbo test`: `bb-plugin-provider-acp` Test Files 15 passed (15);
`@bb/server` Tests 1 failed | 1896 passed (1897). The single failure is
`test/internal/internal-skill-trees.test.ts` (`mode: 420` vs `436`), the
known umask-0002 local failure; it passes in CI.

Repro on the fixed branch (own dev instance, server :26547, data dir
under `~/.bb-dev`, deleted afterwards):

- `GET /api/v1/system/providers` -> `codex True`, `claude-code True`,
`pi True`, `acp-cursor False`, `acp-grok False`.
- Spawned an `acp-cursor` thread (`thr_2c8kkaj7rz`) with cursor-agent
2026.08.11, waited to `idle`, then `pnpm bb:dev thread fork
thr_2c8kkaj7rz --workspace reuse --prompt "Reply only with ok." --json`
-> `HTTP 400: Provider acp-cursor does not support thread forks`. A
direct `POST /api/v1/threads/fork` also returned 400. The project's
thread list still holds only the source thread (`idle`); no errored fork
thread was created. The original symptom no longer reproduces.

CI on `2d84751d9`: all checks pass (server, packages, integration,
app-1/2/3, both Package Smoke runners, Checks, version check); iOS
simulator flows and Node Compatibility Smoke skipped; none pending or
failing.

Residual risks (unchanged from the pre-rebase review): custom `acp-*`
agents configured through `customAcpAgents` still fall back to
`ACP_TIER_CAPABILITIES.supportsFork: true`
(`apps/server/src/services/providers/acp-provider-tier.ts:43`) and can
still hit the errored-thread path; a per-agent `fork` field on that
config is a follow-up. No wire shape change (the `fork` field already
rides `bridgeLaunch.capabilities`; only its value for two providers
changes), so no `HOST_DAEMON_PROTOCOL_VERSION` bump is needed.

> 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

Codex labels each reconnect attempt with a structured `codexErrorInfo`
(for example `{ responseStreamDisconnected: { httpStatusCode } }`,
`willRetry: true`, failure text in `additionalDetails`), then reports
the terminal failure for the same stream error with `codexErrorInfo:
"other"` and the failure text moved to `message`. That downgrade is
upstream: codex-rs `notify_stream_error` always labels retries
`ResponseStreamDisconnected`, while `CodexErr::to_codex_protocol_error`
maps `CodexErrorDetails::Stream` to `CodexErrorInfo::Other`. The bridge
trusted the terminal value, so the final timeline row lost the
`stream-disconnected` category and rendered as a generic **Provider
error** (the detail text is longer than the 80-char title budget, so the
disconnect cause was only visible after expanding the row).

Issue: #1840. The independent report URL
(https://get-bb.github.io/reports/issues/1840.html) returns 404; the
issue body and #1563 carry the repro.

## What changed

- `plugins/provider-codex/src/delta-translation.ts`: the translation
state remembers the retry-time `codexErrorInfo` and failure text per
codex `threadId\0turnId`. A terminal (`willRetry: false`) error whose
`codexErrorInfo` is `other` and whose failure text equals the remembered
retry text reuses the retry classification. The context is consumed by
the terminal error, dropped on `turn/completed`, and never crosses
turns. Unrelated terminal errors and every non-`other` terminal value
keep the provider-reported classification. No provider prose is parsed.
- `plugins/provider-codex/src/translator.ts`: `thread/closed` also
clears the retry context for that codex thread (exported
`clearCodexEventTranslationThreadState`).
- No wire change between server and host daemon: the `provider/error`
event shape is unchanged, only the value of `errorInfo` on this one
path. No CLI or doc surface changes.

Relation to #1563: that PR (same design, by @ymichael and @brsbl)
targets `plugins/provider-codex/src/event-translation.ts`, which #1834
deleted when it moved Codex onto the narrow-grammar delta translator. It
no longer merges (`git merge-tree` reports a content conflict in
`delta-translation.ts`). This PR ports that design onto
`delta-translation.ts`, with a flat `Map` keyed by thread+turn instead
of nested maps.

## How you verified

Tests added in `plugins/provider-codex/src/translator.test.ts` (`codex
terminal retry-error classification`):

- carries the retry classification into the degraded terminal error (and
the context is consumed, so a repeat stays `other`)
- does not relabel an unrelated terminal error after a reconnect
- scopes the retry context to the turn and drops it on `turn/completed`
- drops the retry context when the codex thread closes

Fail-before: with `delta-translation.ts` and `translator.ts` restored
from `origin/main`, `pnpm exec turbo run test
--filter=bb-plugin-provider-codex --force -- --run
src/translator.test.ts` fails the first test:

```
× carries the retry classification into the degraded terminal error
AssertionError: expected [ { type: 'provider/error', …(7) } ] to deep equally contain ObjectContaining{…}
  expected "category": "stream-disconnected", "providerCode": "responseStreamDisconnected"
  received "category": "unknown", "providerCode": "other"
```

The three negative tests pass on `origin/main` as expected (they pin
that the guard does not over-apply).

Pass-after, from the committed tree (`git status --porcelain` empty):

- `pnpm exec turbo run typecheck test --filter=bb-plugin-provider-codex`
→ `Tasks: 7 successful, 7 total` (16 test files, 176 tests passed)
- `pnpm exec turbo run build` → `Tasks: 18 successful, 18 total`

Manual replay of the incident's two events (reconnect with
`responseStreamDisconnected`, then terminal `other` with the same
`stream disconnected before completion: ...` text) through
`createCodexEventTranslator` via `node --conditions=source --import
tsx`: the terminal delta now carries `errorInfo: { category:
"stream-disconnected", providerCode: "responseStreamDisconnected",
httpStatusCode: null }`.


## Rebase

Rebased onto `origin/main` after the grammar-v3 bridge stack landed
(#2124, #2136, #2153, #2148, #2164). That stack rewrote
`delta-translation.ts` (presentation on every item,
`injectedToolsByName` on the translation state, delegation items) and
`translator.ts` (`clearClosedThreadState` now returns the closes for
open delegations), but it did not touch the `error` case,
`toProviderErrorInfo`, or `turn/completed`, so the fix maps onto the new
code unchanged:

- The only textual conflict was in `CodexEventTranslationState` /
`createCodexEventTranslationState`, where main added
`injectedToolsByName` next to where this PR adds `retryErrorsByTurnKey`.
Resolved by keeping both fields.
- `clearCodexEventTranslationThreadState` is still called from
`clearClosedThreadState` in `translator.ts`, before it returns the
delegation closes that main added.
- The tests merged cleanly into `translator.test.ts`; they run through
the grammar-v3 `createDeltaAssembler` harness on main, and the
`provider/error` event shape they assert is unchanged.

Re-verified on the new base (`798b720ef`, one commit on top of
`origin/main`):

- Fail-before: with `delta-translation.ts` and `translator.ts` restored
from `origin/main`, `pnpm exec turbo run test
--filter=bb-plugin-provider-codex --force -- --run
src/translator.test.ts -t "codex terminal retry-error classification"` →
`1 failed | 3 passed`; `carries the retry classification into the
degraded terminal error` fails with expected `"category":
"stream-disconnected", "providerCode": "responseStreamDisconnected"`,
received `"category": "unknown", "providerCode": "other"`. The bug is
still present on current main.
- Pass-after, from the committed tree (`git status --porcelain` empty):
`pnpm exec turbo run typecheck test --filter=bb-plugin-provider-codex
--force` → `Tasks: 7 successful, 7 total`, `Test Files 18 passed (18)`,
`Tests 197 passed (197)`. `pnpm exec turbo run build` → `Tasks: 18
successful, 18 total`.

Fixes #1840

> AGENT GENERATED: by Claude Opus 5


## Independent verification

Verified on a fresh checkout of `bb/fix-1840-codex-stream-disconnect`
(282f32e, one commit on top of `origin/main`; `git merge-base
--is-ancestor origin/main HEAD` true, GitHub reports MERGEABLE).

Root cause checked against current upstream sources (not from the PR
description): `codex-rs/core/src/session/mod.rs` `notify_stream_error`
hard-codes `CodexErrorInfo::ResponseStreamDisconnected` for every retry
notification, `codex-rs/core/src/responses_retry.rs` returns the raw
`CodexErr` once retries are exhausted, and
`codex-rs/protocol/src/error.rs` `to_codex_protocol_error` has no arm
for `CodexErrorDetails::Stream` so it hits `_ => CodexErrorInfo::Other`.
The app-server maps `EventMsg::StreamError` to `error` with `willRetry:
true` plus `additionalDetails`, and `EventMsg::Error` to `willRetry:
false` with `additional_details: None`. The PR's correlation (retry
`additionalDetails` vs terminal `message`, same thread+turn, `other`
only) matches that wire shape exactly.

Commands:

- `pnpm install --frozen-lockfile --prefer-offline` and `pnpm exec turbo
run build` (18/18).
- Fail-before: `git checkout origin/main --
plugins/provider-codex/src/delta-translation.ts
plugins/provider-codex/src/translator.ts`, then `pnpm exec turbo run
test --filter=bb-plugin-provider-codex --force -- --run
src/translator.test.ts -t "codex terminal retry-error classification"`:
1 failed, 3 passed. Failing assertion: `carries the retry classification
into the degraded terminal error` -> `AssertionError: expected [ { type:
'provider/error', ...(7) } ] to deep equally contain
ObjectContaining{...}`, expected `"category": "stream-disconnected",
"providerCode": "responseStreamDisconnected", "httpStatusCode": 502`,
received `"category": "unknown", "providerCode": "other",
"httpStatusCode": null`.
- Pass-after: restored the PR sources (`git status --porcelain` empty),
`pnpm exec turbo run typecheck test --filter=bb-plugin-provider-codex
--force` -> `Tasks: 7 successful, 7 total`, `Test Files 16 passed (16)`,
`Tests 176 passed (176)`.
- Only `packages/thread-view/src/error-display.ts` consumes the
`stream-disconnected` category (title text); no runtime recovery keys on
it, so the blast radius is the timeline row title.

Repro on the fixed branch: a real Codex stream outage cannot be
triggered deterministically here, so I replayed upstream-shaped events
through `createCodexEventTranslator` directly (`node --conditions=source
--import tsx`): four `Reconnecting... n/5` retries labelled
`responseStreamDisconnected` with the failure text in
`additionalDetails`, then a terminal `other` with that text as `message`
and `additionalDetails: null`. Fixed branch:
`{"category":"stream-disconnected","providerCode":"responseStreamDisconnected","httpStatusCode":null}`.
Same script with `origin/main` sources:
`{"category":"unknown","providerCode":"other"}`. Extra negative replays
on the fixed branch all stayed correct: unrelated terminal text after a
retry stays `unknown`; a structured terminal value
(`responseTooManyFailedAttempts`, 503) is never overridden by the
remembered retry; a thread-scoped retry (no `turnId`) does not relabel a
turn-scoped terminal; a retry on a different codex thread does not leak
across threads.

CI: all checks pass (Checks, Package Smoke ubuntu+macos, Tests
app-1/2/3, integration, server, packages, version check).

Residual risks (minor, not blocking): the correlation needs the terminal
`message` to equal the last notified retry's `additionalDetails`; the
terminal `CodexErr` is the attempt after the last notified retry, so if
the inner reqwest text differs between attempts the row falls back to
today's generic label (never to a wrong one). Retry context for a turn
whose child dies without `thread/closed` or `turn/completed` lives in
the per-session translator until the session is released (a few bytes).
The upstream mapping gap in codex-rs remains.

> AGENT GENERATED: by Claude Opus 5




## Independent verification (post-rebase)

Re-verified after the rebase onto the grammar-v3 bridge. Checked out
`798b720ef` (one commit on top of `cf00cfe06`); `origin/main` had since
gained #2120 (provider-literal ratchet), which merges cleanly and
excludes `plugins/provider-*`, so it cannot affect this PR (`node
scripts/check-provider-literal-ratchet.mjs --base origin/main` ->
`ratchet OK: 148 references across 40 core files`).

Fix still targets the right code path in the rewritten translator: the
v3 stack left the `error` case, `toProviderErrorInfo`, and
`turn/completed` unchanged; `clearCodexEventTranslationThreadState` runs
inside `clearClosedThreadState` before the delegation closes it now
returns; `translateEvent` still routes `error` events through
`translateCodexEventToDeltas(event, eventTranslationState)` with the
single per-session state. Nothing downstream reclassifies:
`@bb/agent-runtime` `shouldRestartCodexThreadAfterEvent` keys only on
`rate-limit`/`unauthorized` categories (a retry-time label is always
`stream-disconnected`, so restart policy is unchanged) and
`packages/thread-view/src/error-display.ts` is the only consumer of the
category.

Commands (all from the committed tree):

- Fail-before on current main source: `git checkout origin/main --
plugins/provider-codex/src/delta-translation.ts
plugins/provider-codex/src/translator.ts`, then `pnpm exec vitest run
src/translator.test.ts -t "codex terminal retry-error classification"`
in `plugins/provider-codex` -> `1 failed | 3 passed`; `carries the retry
classification into the degraded terminal error` fails with expected
`"category": "stream-disconnected", "providerCode":
"responseStreamDisconnected", "httpStatusCode": 502`, received
`"category": "unknown", "providerCode": "other", "httpStatusCode": null`
(`src/translator.test.ts:1272`).
- Pass-after (sources restored, `git status --porcelain` empty): same
vitest command -> `4 passed`. `pnpm exec turbo run typecheck test
--filter=bb-plugin-provider-codex --force` -> `Tasks: 7 successful, 7
total`, `Test Files 18 passed (18)`, `Tests 197 passed (197)`.
- Dependents: `pnpm exec turbo run typecheck test
--filter=@bb/provider-parity --filter=@bb/agent-runtime
--filter=@bb/provider-bridge-protocol --force` -> `Tasks: 10 successful,
10 total` (parity 43 passed, agent-runtime 439 passed, bridge-protocol
217 passed). The parity suite replays every committed recording,
including `recordings/codex/auth-failure`, through the current bridge
with zero diffs.
- `pnpm exec prettier --check` and `pnpm exec eslint` on the three
touched files: clean.

Repro on the fixed branch: replayed the issue's event sequence (four
`Reconnecting... n/5` retries labelled `responseStreamDisconnected` with
the failure text in `additionalDetails`, then terminal `other` with that
text as `message`) through `createCodexEventTranslator` via `node
--conditions=source --import tsx`: terminal delta is
`{"category":"stream-disconnected","providerCode":"responseStreamDisconnected","httpStatusCode":null}`.
A terminal-only event with no preceding retry stays `unknown`/`other`
(by design). Cross-checked against upstream
`codex-rs/protocol/src/error.rs` (`Stream(..)` still falls to `_ =>
CodexErrorInfo::Other`; terminal `message` is `self.to_string()`, the
same text `notify_stream_error` puts in `additional_details`).

CI: all 11 check-runs on `798b720ef` succeed (Checks, Package Smoke
ubuntu+macos, Tests app-1/2/3, integration, server, packages, version
check x2); 2 skipped (node-compat smoke, iOS flows).

Residual risk (minor, not blocking): the real recorded `auth-failure`
cell shows Codex's failure text can carry per-request `cf-ray`/`request
id` values that differ between the last retry and the terminal attempt;
there the exact-text guard does not fire and the terminal row stays the
generic label exactly as on main (for that 401 case a
`stream-disconnected` label would arguably be wrong anyway, and the
runtime's 401 restart text pattern still matches). Retry context for
errors without a `turnId` is only dropped on `thread/closed`.

> 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

Issue #1529 (report: https://get-bb.github.io/reports/issues/1529.html).
The wedge itself lives in Cursor's CLI: its Shell tool re-spawns every
command with the cwd persisted from the last run, Node's `spawn` fails
with ENOENT once that directory is deleted (`git worktree remove`), and
Cursor's ACP adapter reports the call as `status: "completed"` with no
`content` and no `rawOutput`. bb cannot fix that, but bb made it
invisible. `plugins/provider-acp/src/delta-translation.ts` derived the
exit code from the ACP status alone (`completed` -> 0, `failed` -> 1).
ACP has no exit-code field, and Cursor also reports a command that
really exited non-zero as `status: "completed"` with the real code in
`rawOutput.exitCode`. So the bb timeline and `bb thread log` showed
"exit code 0" both for commands that never ran and for commands that
exited 1.

## What changed

- `plugins/provider-acp/src/wire.ts`:
`acpToolCallRawOutputExitCodeSchema` parses `{ exitCode: integer }` out
of the agent-defined `rawOutput` payload at the boundary.
-
`packages/provider-bridge-protocol/recordings/acp-cursor/*/bridge→runtime.current.ndjson`:
re-recorded acp-cursor lanes (six cells); only `exitCode` on item closes
changed. Details under Rebase below.
- `plugins/provider-acp/src/delta-translation.ts`: `toolCallClose` now
gets its exit code from `extractAcpExitCode`. A reported integer
`rawOutput.exitCode` wins. Without one, a `failed` call still maps to 1
(non-zero is all we know) and a `completed` call carries no `exitCode`
instead of a fabricated 0. `exitCode` is already optional on the
`commandExecution` item, the delta close, the thread-view exec
lifecycle, the CLI formatter, and the app's `TerminalOutputBlock`, so
consumers render "unknown" by omitting the exit-code line.

Behavior change for every ACP provider: a completed command without a
reported exit code no longer shows `exit code 0`; a completed command
with `rawOutput.exitCode: 1` now renders as an error with `exit 1`.
Translation only, nothing crosses the server/daemon wire, so no
`HOST_DAEMON_PROTOCOL_VERSION` bump. I did not take the report's
optional step of mapping a result-less completed call to `failed`: that
guesses, and omitting the exit code is the honest signal.

The wedge remains upstream (Cursor CLI, `cursor-agent` 2026.08.11). With
this change the agent's own "returned no exit status" text is no longer
contradicted by a bb row claiming success.

## How you verified

New tests in `plugins/provider-acp/src/delta-translation.test.ts`
(`command exit codes`), using the exact `tool_call`/`tool_call_update`
shapes recorded from `cursor-agent acp`. Against the origin/main sources
they fail:

```
× uses rawOutput.exitCode when the agent reports a non-zero exit as completed
  AssertionError: expected +0 to be 1
× omits the exit code when a completed call carries no result at all
  AssertionError: expected +0 to be undefined
× prefers a reported exit code over the failed-status fallback
  AssertionError: expected 1 to be 127
× ignores non-integer exit codes in rawOutput
  AssertionError: expected +0 to be undefined
```

With the fix: `pnpm exec turbo run typecheck test
--filter=bb-plugin-provider-acp` passes (14 files, 186 tests). The
existing `translates execute tool calls into command executions`
expectation dropped its `exitCode: 0` (no exit code was reported in that
fixture).

Manual check on my dev instance with a real `acp-cursor` thread and the
report's prompt (scratch repo + worktree, `git worktree remove --force`,
then `echo hi; git status`, then `pwd` with a working-directory
override, then `false`). `bb thread log --format verbose` after the fix:

```
── Ran echo hi; git status
  $ echo hi; git status
                                   <- no fabricated "exit code 0"
── Ran pwd
  {"exitCode":0,"stdout":".../repo/base\n","stderr":""}
── Ran false (error)
  {"exitCode":1,"stdout":"","stderr":""}
  exit 1                           <- was "exit code 0" before
```

The persisted items: the two wedged `echo hi; git status` calls are
`status: "completed"` with no `exitCode`; `false` is `exitCode: 1`.

## Rebase

Rebased onto current main (`cf00cfe06`) after #2136 (WS1a generic
assembler) and #2179 (WS1b-acp: ACP bridge to grammar v3 with
presentation) rewrote `plugins/provider-acp/src/delta-translation.ts`.
What moved:

- `extractAcpToolCallOutputText`, `buildAcpFileChanges`, and
`classifyAcpToolCall` now live in
`plugins/provider-acp/src/tool-classification.ts` and return `{ item,
presentation }`; the PR's conflict hunks that carried copies of those
helpers were dropped, not re-added.
- `toolCallClose` still derived the exit code from the ACP status on
main (`terminal ? { exitCode: status === "failed" ? 1 : 0 } : {}`), so
the bug was still present. The fix maps one-to-one:
`extractAcpExitCode(args.event, args.status)` replaces the `terminal`
flag, and the close spreads `exitCode` only when one is known. The new
`classified.item` / `classified.presentation` fields and the
injected-tool binding cleanup from #2179 are kept as-is.
- `wire.ts` (`acpToolCallRawOutputExitCodeSchema`) applied without
conflict.
- Test fixture `translates execute tool calls into command executions`
keeps main's new `presentation` block and drops `exitCode: 0`, as
before.

Re-verified on the new base. With `git checkout origin/main --
delta-translation.ts wire.ts`, `vitest run
src/delta-translation.test.ts`: 5 failed / 32 passed (`expected +0 to be
1`, `expected +0 to be undefined`, `expected 1 to be 127`, `expected +0
to be undefined`, plus the fixture diff). With the fix restored, from
the committed tree: `pnpm exec turbo run typecheck test
--filter=bb-plugin-provider-acp --force` → `Tasks: 7 successful, 7
total`; `Test Files 15 passed (15)`, `Tests 201 passed (201)` (includes
the recorded ACP conformance cells).

Fixes #1529

> AGENT GENERATED: by Claude Opus 5


### Rebase onto `75d6fc4d4` and acp-cursor re-record

Rebased onto current main (`75d6fc4d4`, five commits ahead of the
previous base `cf00cfe06`: #2202, #2201, #2147, #2150, #2120). None
touch `plugins/provider-acp/src/{delta-translation,wire}.ts`; the rebase
applied clean and the fix is unchanged.

The verifier found that the fix changes what the ACP bridge emits for
committed acp-cursor recordings, so `pnpm exec turbo run test
--filter=@bb/provider-parity --force` failed on
`acp-cursor/{approval-deny,steer,web-search}` (3 failed / 40 passed on
the rebased tree before this change; CI had only been green through a
turbo cache hit). Ran `pnpm --filter @bb/provider-parity rerecord
--provider acp-cursor` (planning with this checkout's assembler; no
`--plan-with` needed) and committed the resulting
`bridge→runtime.current.ndjson` lanes. Checked every changed line at the
delta level (parsed old vs new, removed `exitCode`, deep-equal): the
ONLY change is `exitCode` on `item.close` deltas. Line counts are
unchanged, row-count pins are unchanged, `parity-allowlist.json` is
untouched.

- `approval-deny`: `touch ~/bb-recording-outside.txt` close, `exitCode:
0` -> absent (Cursor reported no `rawOutput`).
- `steer`: the fourth `sleep 2` close, `exitCode: 0` -> absent (the
steer interrupted it before a `completed` update; the other four keep
their reported `0`).
- `web-search`: the `node -e ...` close, `exitCode: 0` -> `1` (Cursor
reported `rawOutput.exitCode: 1` under `status: "completed"`; this is
the #1529 shape).
- `subagent`, `turn-tools`, `user-question`, `web-search`:
`tool`/`fileChange` closes drop the `exitCode: 0` the old code attached
to every terminal close. The assembler only reads `exitCode` on
commands, which is why those cells passed before; the re-recorded lanes
now match the wire.
- `fork` re-recorded identically except for the recording machine's
checkout path inside the "does not advertise session/fork support" error
string; left as committed.

Re-verified from the committed tree (`git status --porcelain` empty).
Fail-before: with `git checkout origin/main -- delta-translation.ts
wire.ts`, `vitest run src/delta-translation.test.ts` -> 5 failed / 32
passed (`expected +0 to be 1`, `expected +0 to be undefined`, `expected
1 to be 127`, `expected +0 to be undefined`, plus the fixture diff).
Pass-after: 37 passed. `pnpm exec turbo run typecheck test
--filter=bb-plugin-provider-acp --filter=@bb/provider-bridge-protocol
--filter=@bb/provider-parity --force` -> `Tasks: 11 successful, 11
total` (`Cached: 0 cached`); `bb-plugin-provider-acp` 15 files / 201
tests, `@bb/provider-bridge-protocol` 15 files / 217 tests,
`@bb/provider-parity` 1 file / 43 tests (all 43 cells reproduce their
recordings).

## Independent verification

Checked out `bb/fix-1529-shell-session-deleted-cwd` (e042d5a, one
commit on top of 2ff8598) in a separate worktree; `git merge-tree
--write-tree origin/main HEAD` merges clean against current main
(703213a). PR diff is limited to
`plugins/provider-acp/src/{delta-translation.ts,wire.ts,delta-translation.test.ts}`;
no wire change between server and daemon, so no
`HOST_DAEMON_PROTOCOL_VERSION` bump needed. Consumers of `exitCode`
(`delta-assembler` close fields, `thread-view/exec-lifecycle.ts`,
`format-timeline-text.ts`, `TerminalOutputBlock`) all treat it as
optional/nullable; a missing code falls back to the item status, a
non-zero code maps to `error`.

Fail-before / pass-after (`pnpm exec vitest run
src/delta-translation.test.ts` in `plugins/provider-acp`):

- With `git checkout origin/main -- delta-translation.ts wire.ts`: 5
failed / 20 passed. `expected +0 to be 1`, `expected +0 to be
undefined`, `expected 1 to be 127`, `expected +0 to be undefined`, plus
`translates execute tool calls into command executions` (fixture no
longer expects the fabricated `exitCode: 0`).
- With the PR sources restored: 25 passed.

`pnpm exec turbo run typecheck test --filter=bb-plugin-provider-acp
--force`: 7 tasks successful, 14 test files / 186 tests passed. `gh pr
checks 2131`: all checks pass (Checks, Package Smoke x2, Tests
app-1/2/3, integration, packages, server, version check).

Repro on the fixed branch (own dev instance, scratch repo + worktree,
real `acp-cursor` thread thr_eenfcb5cv5 with the report's prompt plus a
final `false`): `bb thread log --format verbose` shows `Ran echo hi; git
status` with no output and no exit-code line, and `Ran false (error) ...
exit 1`. Persisted items: seq 42 `{"command":"echo hi; git
status","status":"completed"}` (no `exitCode`), seq 54
`{"command":"false","status":"completed","exitCode":1}`. On main the
same log printed `exit code 0` for both. The upstream wedge itself still
reproduces (Cursor returns "The shell command returned no exit status"
for step 3 and heals after the working-directory override), which is
outside bb's control.

Residual risks: completed ACP commands from agents that do not report
`rawOutput.exitCode` (or use a different key) no longer show `exit code
0`; a Cursor call that never ran is still rendered as a completed row
with no output rather than as failed. Merging closes #1529 although the
wedge needs an upstream Cursor CLI fix; the body above says so.

> AGENT GENERATED: by Claude Opus 5




## Independent verification (post-rebase)

Checked out `bb/fix-1529-shell-session-deleted-cwd` at 06c27aa (one
commit on top of 75d6fc4) in a fresh worktree. Since the rebase main
gained only 85eec4d (#2210, iOS TestFlight CI; no overlap) and GitHub
reports the PR `MERGEABLE`. The fix still targets the live path after
today's grammar-v3 bridge stack: `createAcpDeltaTranslator` is wired
once in `plugins/provider-acp/src/bridge/bridge.ts`, and `toolCallClose`
is the only place the ACP bridge emits a command `exitCode`; no legacy
`event-translation.ts` remains. The delta/assembler contract is
unchanged (`exitCode` already optional in `thread-delta.ts` and applied
only to `commandExecution` in `delta-assembler.ts`), so no
`HOST_DAEMON_PROTOCOL_VERSION` bump is needed. `thread-view` projects a
missing code to `null` (no exit line) and a non-zero one to an `error`
row.

Recordings: parsed every changed line of the six re-recorded
`acp-cursor/*/bridge→runtime.current.ndjson` lanes against 75d6fc4
with `exitCode` stripped; all 9 changed deltas are deep-equal otherwise,
line counts unchanged, other acp-cursor cells byte-identical. The
`web-search` `node -e` close moves 0 -> 1 because Cursor reported
`rawOutput.exitCode: 1` under `status: "completed"` (the #1529 shape in
a real recording).

Fail-before / pass-after (`pnpm exec vitest run
src/delta-translation.test.ts` in `plugins/provider-acp`): with `git
checkout origin/main -- plugins/provider-acp/src/delta-translation.ts
plugins/provider-acp/src/wire.ts` -> 5 failed / 32 passed: `expected +0
to be 1`, `expected +0 to be undefined`, `expected 1 to be 127`,
`expected +0 to be undefined`, plus the `translates execute tool calls
into command executions` fixture. Sources restored -> 37 passed (37).

From the committed tree (`git status --porcelain` empty), after `pnpm
install --frozen-lockfile --prefer-offline` and `pnpm exec turbo run
build` (18/18): `pnpm exec turbo run typecheck test
--filter=bb-plugin-provider-acp --filter=@bb/provider-bridge-protocol
--filter=@bb/provider-parity --force` -> `Tasks: 11 successful, 11
total`, `Cached: 0 cached`; bb-plugin-provider-acp 15 files / 201 tests,
@bb/provider-bridge-protocol 15 files / 217 tests, @bb/provider-parity 1
file / 43 tests. `gh pr checks 2131`: all required checks pass on
06c27aa.

Repro on the fixed branch (own dev instance, scratch repo + `git
worktree add`, real `acp-cursor` thread thr_5mn7xbb4j2 with the report's
verbatim prompt): the upstream wedge still reproduces (Cursor returns
"The shell command returned no exit status" for steps 3 and 4 and heals
after the working-directory override), and bb now persists those two
items as `{"command":"echo hi; git status","status":"completed"}` /
`{"command":"echo alive","status":"completed"}` with no `exitCode` and
no output, where main wrote `exitCode: 0`. A second thread
(thr_sxg224nzrj) in which Cursor reported `rawOutput.exitCode: 127` and
`126` under `status: "completed"` rendered as `exit 127` / `exit 126`
`(error)` rows in `bb thread log`.

Residual risks: unchanged from the previous section. The wedge itself is
a Cursor CLI bug; merging closes #1529 on the bb side only (misreported
exit codes), which the body states.

> AGENT GENERATED: by Claude Opus 5

Co-authored-by: Claude <[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