Repository navigation
Conversation
|
🚨 SLOP COP 🚨 · I am the Slop Cop. I am reviewing this pull request for security, code quality, performance, architecture, duplication, and end-to-end behavior. |
SawyerHood
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5: This PR makes provider exits and workspace recovery safer. It also preserves Codex command output when events arrive out of order.
I found three issues:
- High — old provider pipes remain active. The one-second deadline finalizes the exit but leaves the old streams and handlers open. A descendant can send stale JSON-RPC after a replacement starts.
- High — the stale-event guard ignores the attempt ID. Old progress can enter a newer attempt on the same provisioning environment.
- Medium — the Docs watcher test remains unreliable. A longer timeout does not fix a filesystem event that occurs before watcher readiness.
I found no additional security, performance, architecture, duplication, or refactor issue that needs a comment.
I checked the exact requested SHA. The PR head later merged main, but that merge did not change these lines.
Seven Turbo test tasks passed. Six Turbo typechecks passed. The current GitHub CI passed. A real Codex thread reached idle and returned ok in the browser.
The Docs test passed once in my isolated run. Another worker saw it fail in both a broad run and an isolated run.
I submitted this as a comment-only review. I did not approve the pull request or request changes through GitHub.
|
Closing this oversized validation branch in favor of focused replacement PRs.
The provisioning restart-survival/schema work is intentionally abandoned. The corrected runbook will validate only completed provisioning failure followed by a fresh retry on the next message. |
## What this fixes Test-determinism and QA/runbook maintenance only, extracted from #1385. | Issue | Simple explanation | Fix | |---|---|---| | Docs watcher test was timing-dependent | The test wrote a real file and then raced native FSEvents plus a 250ms debounce, so it failed whenever the `watch-vaults` service had not attached yet or the host was busy. | Give the Docs plugin a watcher injection seam that defaults to native `fs.watch`, and have the test drive a fake watcher directly. It now asserts the watched root, the published `vault-changed` signal, and watcher cleanup on abort — with no filesystem-event timing. | | Database-maintenance test depended on file order | The `@bb/server` vitest project runs with `isolate: false`, so files share the module-level `lastDatabaseMaintenanceCheckAt`. `periodic-sweeps.test.ts` parks it at wall time, while this file swept from a hardcoded `1_000_000_000_000` (2001) — every sweep then looked "too soon". | Start the synthetic clock a day ahead of wall time so it always leads any real timestamp another file records. | | Daemon restart helper only worked once | `buildDaemonRestartCommand` baked in the PID captured at build time, so a second run left the first replacement daemon alive and raced a second one onto the same port and data dir. | Resolve the PID from the daemon PID file at run time (build-time PID as first-run fallback), and refuse to run when the resolved value is not a positive integer so a corrupt PID file cannot become a stray `kill`. | | Archive runbook expected immediate destruction | A last-live archived managed worktree stays revivable for the five-minute undo grace period (`MANAGED_ENVIRONMENT_RETIRE_GRACE_MS`), so the old expectation was wrong. | Assert `retiring` plus a preserved worktree first, then permanently delete the archived thread and wait for destruction. | | Runbook tracked the wrong restarted daemon | `DAEMON_PID=$!` after `eval "$RESTART_DAEMON_COMMAND"` captures the shell's job, not the detached daemon. | Read the authoritative PID file (`.paths.daemonRestartPidPath`) exported by the standalone harness after each restart. | | Permission QA used non-public modes and unreliable probes | `readonly` and `workspace-write` are not accepted by the CLI (public modes are `accept-edits`, `auto`, `full`), and Codex sandboxes commonly permit the OS temp dir, so `/tmp` probes were not reliably outside the workspace. | Cover only the public modes and place the approval/denial probes under `$HOME`. A new contract test rejects stale mode names and pins the probe targets. | | Provisioning runbook promised restart recovery | The old "Server restart during environment provisioning" scenario killed the server mid-RPC and implied lost-result recovery and persisted attempt identity. | Removed entirely. Replaced with the supported contract: a `.bb-env-setup.sh` hook fails exactly once, the thread and environment settle in `error` with `thread_provisioning_failed`, and one explicit `bb thread tell ... --mode auto` starts a fresh provisioning attempt that reaches `ready` before the turn runs. A contract test keeps the restart scenario from returning. | ## Scope No product behavior, database schema, migration, Drizzle snapshot, provisioning implementation, host-daemon wire contract, or protocol-version change. The full diff is 8 files. Only two are non-test sources: - `plugins/docs/server.ts` — adds the watcher injection seam; the default parameter is the existing native `fs.watch` implementation, so production behavior is unchanged. - `tests/qa/src/shared.ts` — QA-harness helper in the `tests/qa` package. **Deliberately omitted:** the provider-interaction integration commit from #1385 (`0fc13d45e`). It deletes roughly 750 lines of live-provider scenarios covering `auto` permission mode plus the `auto-ask`/`auto-deny` harness presets. Its premise does hold on current main — `auto` pairs with `approvalReviewer: "automatic"`, which the Codex adapter maps to `auto_review` rather than routing to `onInteractiveRequest` — so it is not strictly coupled to the excluded Codex runtime commits. It is omitted because it is a coverage deletion rather than a flaky-test or QA fix, and it cannot be validated here: `src/integration*.test.ts` is excluded from the default `test` task and only runs via `test:integration` against real providers. Removing unverifiable integration coverage does not belong in a no-product-change PR; it is left as a follow-up. ## Validation Run on this branch rebased onto current `main`: - `turbo run typecheck test --filter=bb-plugin-simple-notes --filter=@bb/qa --force` — 5/5 tasks; Docs 59 tests, QA 25 tests. - `turbo run typecheck test --filter=@bb/server --force` — 161 files, 1450 tests passed. - Database-maintenance flake reproduced before the fix with `--no-file-parallelism --sequence.shuffle.files --sequence.seed=3` (4 failures), and passing on that same ordering after. - The standalone-restart regression assertions were confirmed to fail against the previous `buildDaemonRestartCommand`. - `turbo run lint` on the touched packages — no lint tasks are defined for them. - Prettier clean; final diff audited for schema/migration/contract/provisioning paths (none). Runbook claims were checked against `main` rather than assumed: `thread_provisioning_failed`, `error` in `threadStatusValues`, `bb thread wait --status`, `bb thread delete --yes`, `bb thread tell --mode auto`, `PROJECT_ROOT` exported by the QA harness, and `MANAGED_ENVIRONMENT_RETIRE_GRACE_MS = 5 * 60_000`. ### Pre-existing macOS-only failure, not from this PR `packages/agent-runtime/src/runtime.process-lifecycle.test.ts > bounds provider stderr while data arrives without a newline` fails on clean `origin/main` on macOS. Its fake child writes 100KB to stderr and immediately calls `process.exit(42)`. Pipe writes are asynchronous on macOS, so the child exits without flushing bytes that never reach the parent; this is distinct from the real parent-side `exit`-before-`close` drain bug. CI's `Tests (packages)` shard runs on Ubuntu, where the fixture passes. #1402 fixes both issues separately: the fixture uses `process.exitCode = 42` so Node flushes naturally, while the runtime waits for stream close before finalizing provider exit. Those provider-runtime changes are explicitly out of scope here, and this branch touches no `agent-runtime` files. > AGENT GENERATED: by Claude Opus 5 (1M context) --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Extracted from #1385 as a focused split: only the provider process shutdown/replacement race fixes, plus their regression tests. No Codex adapter, provisioning, schema, or docs changes ride along. ## The races An exited provider process could corrupt the state of the session that replaced it. Three distinct races made that possible. **1. Exit vs. close drain.** The manager finalized a provider on the child `exit` event. Node can emit `exit` before the final stdout/stderr bytes have been read from the pipes, so pending requests were rejected and exit diagnostics reported *without* the provider's last output — losing exactly the error text that explains why it died. Finalization now waits for `close` (stdio fully drained), bounded by a one-second grace deadline so a descendant that inherited a pipe cannot block finalization forever. **2. Replacement synchronization.** A caller could observe an exited provider and start a replacement while the old process was still draining, briefly yielding two "current" providers for one process key. Provider entries now carry an explicit `exitFinalized` promise. The replacement, shutdown, and concurrent-start paths await it and then **re-check** whether another caller already created the replacement, so only one current provider exists. **3. Stale stream output.** A descendant holding an inherited pipe could emit protocol messages after the replacement became current, injecting stale output into a fresh session. When the grace deadline expires the old readline interface is closed and both provider pipes destroyed; the stdout/stderr callbacks additionally verify their process is still current before forwarding anything. ## Two distinct issues behind the stderr test These were initially conflated and are worth separating: - **Fixture bug (test-only).** `bounds provider stderr while data arrives without a newline` fails deterministically on current `main`. The fake provider did `process.stderr.write(100KB)` then `process.exit(42)`. `process.exit()` discards Node's async-buffered pipe output, so the child attempted ~100,011 bytes but the parent only ever saw 65,536 — at *both* `exit` and `close`. No parent-side drain can recover bytes the child never wrote. Fixed by setting `process.exitCode = 42` and letting the process exit naturally. - **Production bug (issue 1 above).** Genuinely separate. Verified by experiment: clean-`main` runtime + fixed fixture passes 3/3, so that test does *not* exercise the drain race. The production race is covered instead by `drains provider stderr before reporting process exit`, where a descendant writes to the inherited pipe 50 ms *after* the provider exits — an ordering that guarantees `exit` precedes the final data and that only the close/grace fix handles. ## Tests Six regression tests in `runtime.process-lifecycle.test.ts`: final output after exit, concurrent replacement/start synchronization, descendant-held pipes, stale descendant output after replacement, stream destruction, and bounded cleanup. Each was mutation-verified — every fix was individually reverted to confirm the corresponding test actually fails, rather than passing incidentally: | Reverted fix | Failing test(s) | | --- | --- | | stream destruction | `cuts off inherited provider output…` | | close/grace drain | `drains provider stderr…`, `cuts off inherited…` | | `ensureProvider` synchronization | `waits for an exited provider…`, `starts a single replacement…`, `cuts off inherited…` | | shutdown skip for exited process | `does not wait for an already-exited provider…` | This caught two initially-weak assertions, which were then strengthened: the stream-destruction check passed incidentally because the descendant had already exited and let the pipes EOF naturally, and the shutdown test had no assertion at all and relied on vitest's ambient timeout. ## Scope Product reliability change. **No database schema, migration, or Drizzle snapshot change. No host-daemon contract or protocol-version change** — verified by inspection: `RuntimeProviderProcess` never leaves `@bb/agent-runtime`, the new `exitFinalized` field is a `Promise` (inherently non-serializable), and the only production consumers of the adjusted `listRunningProviders()` are two host-local `length === 0` bookkeeping checks in `runtime-manager.ts` that are never serialized. `HOST_DAEMON_PROTOCOL_VERSION` is therefore deliberately unchanged. ## Validation - `turbo run typecheck lint test --filter=@bb/agent-runtime --filter=@bb/host-daemon` — green (916 + 543 tests) - `turbo run build` for both packages — green - `runtime.process-lifecycle.test.ts` run 20× consecutively — 20/20, no flake - Rebased onto latest `main` (`c288a199a`) and re-validated > AGENT GENERATED: by Claude Opus 5 Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Two Codex runtime reliability fixes, split out of #1385 so they can be reviewed on their own. ## Bug 1: command output lost when Codex reorders events Codex app-server normally reports a shell command as `function_call` → `function_call_output` (the full stdout) → `item/completed`. Sometimes the `item/completed` event arrives **before** the raw record carrying the output. The adapter only repaired a completed item using output it had already captured. In the reordered case there was nothing captured yet, so it published the provider's truncated `aggregatedOutput` and the real output — which arrived a moment later — was dropped. Users saw a finished command with missing or partial output. **Fix:** when a completed command item arrives while its shell call is still awaiting raw output, hold it instead of publishing it. Repair and emit it as soon as the raw record lands. If the raw record never arrives, flush the held item at turn completion, so output is at worst delayed rather than lost. Unparseable raw output clears the pending shell call so the completed item is released unchanged. ## Bug 2: generated-title rename fails on a brand-new session A new Codex rollout file can exist briefly before its first record is written. A generated-title rename landing in that window fails with `rollout at <path> is empty`, and the thread keeps its placeholder title even though the same call would succeed moments later. **Fix:** retry only that exact transient error, and only for Codex, backing off 50 ms then 200 ms before a final attempt. Every other rename failure, and every other provider, still fails immediately. The backoff is only ever paid when the rename has *already* failed — the happy path returns on the first attempt — and the full 250 ms only when it fails for good, where the alternative was failing instantly and leaving the thread on a placeholder title. ## Protocol version Bug 1 changes what the host daemon sends the server, so `HOST_DAEMON_PROTOCOL_VERSION` goes 109 → **110** with its contract test and comment updated. Older daemons can publish a truncated completed item, so enrolled machines must update. Note for reviewers: #1408 bumped the constant to 109 and updated the assertion, but left the test name and comment describing 108. Rebasing onto it meant rewriting those exact lines, so this PR lands a correct 110 lineage and clears that stale wording as a side effect. These are product reliability changes only — **no database schema, migration, or Drizzle snapshot changes**, and no other behavior from #1385. ## Validation - `turbo run typecheck --filter=@bb/agent-runtime --filter=@bb/host-daemon-contract` — pass - `turbo run typecheck --filter=@bb/host-daemon --filter=@bb/server` (downstream protocol consumers) — pass - `turbo run test --filter=@bb/host-daemon-contract` — 49/49 pass - Rebased onto `3bd8e79a0` and fully re-validated - `turbo run test --filter=@bb/agent-runtime` — **921 pass, 0 failures** - Prettier clean on all changed files Three regression tests were each verified to **fail against current `main` and pass with the fix**: - adapter: repairs a completed item when the raw output arrives late - adapter: flushes the held item at turn end when raw output never arrives - runtime: retries the rename through one empty-rollout error and applies the title A fourth test pins the exhaustion path: a rollout that stays empty makes exactly 3 attempts and then propagates the error, so the retry can neither loop nor swallow a genuine failure. ## Previously-noted test failure is resolved upstream Earlier revisions of this description flagged `runtime.process-lifecycle.test.ts > bounds provider stderr while data arrives without a newline` as failing locally on macOS. #1402 landed that fix on `main` (the fixture used `process.exit()`, which discards Node's async-buffered pipe output on macOS). After rebasing onto it, **the full suite is green: 921/921 with zero failures.** > AGENT GENERATED: by Claude Opus 5 --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
Review follow-ups
Validation
pnpm exec turbo run lint --force— passed with 0 errors (148 pre-existing warnings)pnpm exec turbo run typecheck --force— 58/58 tasks passedpnpm exec turbo run build --force— 14/14 tasks passedpnpm exec turbo run test --force— 55/55 tasks passedenv -u OPENAI_API_KEY pnpm exec turbo run test:integration --force— 57 runtime tests and 11 real-provider tests passedqa/manual-runbook.mdwith Codex, Claude Code, and Pi, including provisioning, server/daemon recovery, and pending-interaction scenariosProtocol
HOST_DAEMON_PROTOCOL_VERSIONfrom 105 to 108 for daemon/server event contract changes and to resolve an independent version collision with the latestmain