Skip to content

Stop CLI commands from reporting success for failed operations - #7748

Merged
ymichael merged 6 commits into
mainfrom
bb/class-fix-cli-commands-reporting-false-success-thr_2ptrjaw73f
Nov 18, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/class-fix-cli-commands-reporting-false-success-thr_2ptrjaw73f

Conversation

@ymichael

@ymichael ymichael commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Two halves of one bug let a command report success for work that failed or never finished.

  1. Server: mutating routes answered a bare {ok: true} whatever happened. Examples:

    • DELETE /hosts/:id, ?force=true and POST /hosts/:id/retry-cleanup returned 200 after provider teardown failed (host left removing, teardownStatus: "failed").
    • POST /environments/:id/cleanup?recover=true awaited a sweep that recorded the failure, then returned {ok: true}.
    • POST /threads/:id/stop returned {ok: true} after swallowing a failed interrupt.
    • Many other routes returned {ok: true} for work that was only queued.

    The SDK then fabricated {ok: true} itself (readVoid followed by return { ok: true }), so callers could not tell even when the body had more to say.

  2. CLI: commands printed results before deciding whether they failed. if (outputJson(opts, result)) return; came before the failure check, so --json exited 0. Other commands never checked failure fields. status.get's fetchSilent and thread show's pending-todos lookup swallowed every error. Each command used its own exit mechanism.

Reproduced live on origin/main (3678415), pnpm start:worktree plus a local machine-provider plugin whose removal always fails:

$ bb machine remove host_iwp7qnqsfu --yes        -> "Machine host_iwp7qnqsfu removed", exit=0
$ bb machine remove host_iwp7qnqsfu --yes --json -> {"ok": true}, exit=0
$ bb machine show host_iwp7qnqsfu --json         -> lifecycle.phase "removing", teardown {status: "failed"}
$ bb machine retry-cleanup host_iwp7qnqsfu       -> "Machine host_iwp7qnqsfu cleanup retried", exit=0
$ BB_SERVER_URL=http://127.0.0.1:<closed> bb status -> exit=0 (#2382)

What changed

Server: one outcome shape, one owner, one guard

  • Shape: OperationResponse = { ok: true, progress: "complete" | "in-progress" } (packages/server-contract/src/api/operation.ts).
    • The server owner is apps/server/src/services/lib/operation-response.ts (operationComplete() / operationInProgress()).
    • All 25 routes that returned a bare {ok: true} now return it.
    • Each one's progress follows what the handler actually did:
      • in-progress: compact, environment delete/cleanup, project delete, retry-update;
      • complete: files, desktop-browser tab actions, queue deletes, unarchive, plan/goal/context clear, telemetry, config reload, attachments copy, thread delete.
  • Failures are errors:
    • machine remove / force / retry-cleanup → 502 machine_teardown_failed (readMachineRemovalOutcome);
    • cleanup --recover → 502 environment_teardown_failed (readEnvironmentRecoveryOutcome);
    • thread stop leaving the thread starting/active → 409 thread_stop_unfinished.
  • Guard: packages/server-contract/test/operation-responses.test.ts. A type-level contract test over publicApiRoutes:
    • Every mutating route's 2xx JSON body must not be a bare {ok: true}.
    • It must also not be failure-shaped, unless allowlisted with a reason. Failure-shaped means ok/success can be false, outcome/state/result can be a failure value, an error field is present, or a results batch contains any of these.
    • Allowlisted (5): import-cookies (typed per-reason outcome the desktop dialog renders), server/move and server/move/cancel (state-machine snapshots), ai-services/test (diagnostic probe), cli-skills/install (batch).
    • A stale allowlist entry also fails.
    • Proof: with origin/main's public-api.ts, api/hosts.ts and api/system.ts, it fails and names all 25 routes, including delete /hosts/:id, post /hosts/:id/retry-cleanup, post /environments/:id/cleanup and post /threads/:id/stop.
  • Limit: the raw app.post plugin routes (apps/server/src/routes/plugins.ts, plugin-catalog.ts) are not in publicApiRoutes, so the type guard can't see them. They already answer failures with non-2xx, except outcomes the CLI checks (plugin enable/install load errors, marketplace refresh batches). The every-command CLI guard below covers those.

SDK

  • Every method that used readVoid now returns the route's typed body. readVoid is deleted from the transport, so a discarded body can no longer be fabricated into {ok: true}.
  • status.get maps only a 404 to null (a missing thread or project); any other failure propagates.

CLI: one owner for result output and exit codes (apps/cli/src/command-result.ts)

  • outputJson, printJsonResult, printJsonLine, reportCommandResult, reportOperation and passThroughExitCode all live there.
  • outputJson's parameter rejects, at compile time, untyped payloads (unknown, any, and index signatures of unknown) and failure-shaped payloads (same rule as the server guard). Those must go through reportCommandResult, which requires an explicit failure decision.
  • Source guard: apps/cli/src/__tests__/command-result-owner.test.ts. An AST scan of commands/ that fails on any direct JSON.stringify written to stdout (including through a conditional, like the old browser.ts print), any process.exit, and any process.exitCode. The only allowlisted exceptions are the two passthroughs of a plugin command's exit code (plugin run, retired environment git aliases).
  • Migrated onto the owner:
    • every direct JSON print (machine, plugin, project, settings, terminal, thread organization/show, browser);
    • the 17 console.error + process.exit(1) pairs in plugin.ts;
    • browser import-cookies, plugin safe-mode off, server move (recovery keeps its own exit code), server move cancel;
    • terminal run/wait (via passThroughExitCode, output unchanged);
    • the rolled-back plugin update.

One rule for in-progress results

progress: "in-progress" means the server accepted the work and is still carrying it out. It exits 0, and the text says it is still in progress. A failed operation exits non-zero. reportOperation applies the rule everywhere:

  • machine remove/retry-cleanup ("is still being removed");
  • thread stop ("is still stopping; check it with bb thread show"; a thread still active fails server-side);
  • environment cleanup/delete;
  • project delete;
  • compact;
  • retry-update.

The first version of this PR exited 1 for a stopping thread; it now follows this rule.

Class members

# Member (origin/main) Fix
1 bb machine remove (machine.ts:486; routes/hosts.ts:319-323; SDK hosts.ts:301) 502 on failed teardown; in-progress while removing
2 bb machine remove --force same
3 bb machine retry-cleanup same
4 bb machine remove of a bb connect machine (routes/hosts.ts:110-139) warnings in the success body; CLI prints it to stderr, exit 0 (the host is removed)
5 bb environment cleanup --recover (routes/environments.ts:99; environment.ts:185) 502 environment_teardown_failed
6 bb thread stop (routes/threads/actions.ts:443; SDK threads.ts:1609) in-progress while stopping; 409 if still active
7 bb status against a dead server (status.ts:71-81, #2382) server_unreachable, exit 1
8 bb status with a context thread/project the server lacks (SDK status.ts:48 fetchSilent) 404 → null → context_not_found, exit 1; other errors propagate
9 bb thread show swallowing head-state failures (thread/pending-todos.ts) only 404 is "no todos"; other errors fail
10 bb terminal close --if-clean fails unless the session is exited
11 bb machine provider-cli install providerCliInstallFailure, shared with updates apply
12 bb updates apply --json, and "Everything is up to date" when a status check failed reporter; unchecked machines fail
13 bb skill install-cli-skills --json reporter
14 bb settings ai-services test --json reporter
15 bb marketplace refresh --json reporter
16 bb plugin update (rolled-back) reporter
17 bb plugin install (plugin loads in error) reporter (matches plugin enable)
— 25 bare-ack routes and 10 SDK {ok: true} fabrications OperationResponse and readJson

Left out, with reasons: bb thread open/pane print Delivered: false truthfully. tell --compact-first, updates app cancel and server move cancel don't report success for a failure. plugin new's npm warning and machine enroll's launcher symlink are side effects. #2382's stalled-daemon hang (no timeouts) is a different failure mode. #6912 happens below the server, in the ACP bridge.

The every-command guard, v2 (apps/cli/src/__tests__/failing-server-guard.test.ts)

  • Coverage: every leaf command in CORE_COMMAND_GROUPS, text and --json, 452 invocations, about 2 s.
    • Valid placeholder ids are chosen by command group, with per-command arguments where a command validates input.
    • A route-keyed responder answers lookups with real fixtures (hosts, threads, environments, plugins, update checks, install jobs).
  • How it fails each request:
    1. It records every request the command makes.
    2. It re-runs the command once per recorded request, failing that request: with HTTP 500, or with a route-keyed failure body inside a 2xx where the failure is in-band (marketplace refresh, cli-skills install, ai-services test, import-cookies, provider-cli install job, plugin update rolled-back, plugin install error, terminal close left running).
    3. It asserts a non-zero exit, no hang, and no stdout after the failed response other than the error envelope. A command whose output after a failure is legitimate is allowlisted with a reason: updates apply (partial batch), status (local context).
  • Zero-request runs fail unless the command is allowlisted with a reason (14 local commands, e.g. guide, plugin build, server unlock).
  • Proof: run against origin/main's apps/cli/src/commands, it fails 16 invocations across every CLI-side member: provider-cli install, marketplace refresh, plugin install, plugin update, ai-services test, install-cli-skills, status, terminal close, thread show, updates apply. Members 1–6 are server-side; the contract guard and route tests catch those.

Decisions for review

  • 502 machine_teardown_failed (machine remove/retry-cleanup) and 502 environment_teardown_failed (cleanup --recover) replace 200 for failed teardown. The app's remove dialog now stays open with the error instead of closing, and plugins calling hosts.delete get a rejection.
  • A failed bb connect credential revoke is now a success with a warning, not a 502. The host is already removed, so a retry would only get 404. The app dialog closes as on main; the CLI prints Warning: ….
  • In-progress results exit 0 with explicit text (the rule above). thread stop → 409 only when the thread is still active or starting.
  • bb status exits non-zero when the server is unreachable or its context is unknown. bb thread show fails when head-state fails for any reason other than 404.
  • Failure messages now go to stderr as Error: …, including plugin.ts usage errors (previously unprefixed). --json failures include the payload or the envelope.
  • The SDK types are additive: { ok: true } → { ok: true; progress; ... }, HostActionResult kept, SDK 0.6.159 as assigned. A plugin built against 0.6.156 still compiles. A plugin test double typed as one of these methods must add progress; the one bundled case, provider-codex/goal-card.test.tsx, is updated.

Docs: guide chapters json, machines, environments, thread-lifecycle, terminals and overview, plus the plugin-authoring backend-machines reference.

How you verified

  • Live (rebuilt pnpm start:worktree, real CLI):
    • machine remove → Error: HTTP 502: QA: provider removal failed, exit 1. --json → machine_teardown_failed envelope, exit 1.
    • With the provider's removal now succeeding: retry-cleanup --json → {"ok": true, "progress": "complete", "warnings": []}, exit 0.
    • thread stop on a pending thread → progress: "complete", exit 0.
    • BB_THREAD_ID=thr_doesnotexist bb status → context, then Error: The context thread thr_doesnotexist was not found on the server, exit 1.
    • bb status on a closed port → exit 1.
    • terminal close --if-clean after input → exit 1.
  • Guards: the contract guard fails on main (25 routes). The CLI owner guard fails on main (41 sites). Every-command guard v2 fails on main's CLI (16 invocations).
  • Tests that fail on main:
    • server: failed-teardown removal 502, connect-revoke warning, cleanup --recover 502, stop in-progress body;
    • CLI: per-member JSON and text failure cases, in-progress text.
  • turbo run typecheck lint for cli, server, sdk, app, server-contract, plugin-sdk, templates and all plugins: pass.
  • turbo run test for cli (1401), sdk, server-contract, templates, scripts, provider-codex, workflows, side-chat and storage-retention: pass. Full apps/server vitest: 4244 passed. App machine/project/thread suites: 124 passed.

Part of #2382: fixes the unreachable-server case only; the stalled-daemon hang is not addressed.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/class-fix-cli-commands-reporting-false-success-thr_2ptrjaw73f branch 2 times, most recently from ab9e8cc to 4e69d45 Compare November 18, 2026 05:38
ymichael and others added 6 commits November 18, 2026 13:49
The server answered machine removal, cleanup retry, and thread stop with a
plain {ok: true} even when the provider teardown failed or the thread was
still running, and several CLI commands printed --json results before their
failure check, so they exited 0. Failed operations now surface as errors or
as an explicit status, and the CLI reports results through one
reportCommandResult owner that exits non-zero on a reported failure.

Guards: outputJson rejects payloads that carry an ok/success failure flag at
compile time, and every registered command is run against a failing server
and must exit non-zero without success output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…no server

bb status now exits non-zero when the server does not answer, so the wrapper
test runs bb guide --json instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Mutating routes now answer a shared { ok, progress } outcome instead of a
bare { ok: true }, and fail with an error status when the work failed. A
type-level contract test over publicApiRoutes forbids bare acknowledgements
and unlisted failure-shaped 2xx bodies. The SDK reads every body instead of
fabricating { ok: true }, and readVoid is gone.

On the CLI, command-result.ts owns all JSON output and exit codes: a source
guard forbids direct JSON writes and process.exit elsewhere, outputJson
rejects untyped and failure-shaped results, and the every-command guard now
fails each recorded request in turn with route-keyed failure bodies and
rejects commands that never reach the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/class-fix-cli-commands-reporting-false-success-thr_2ptrjaw73f branch from 4e69d45 to f174e23 Compare November 18, 2026 21:50
@ymichael
ymichael merged commit 3a34f5c into main Nov 18, 2026
52 checks passed
@ymichael
ymichael deleted the bb/class-fix-cli-commands-reporting-false-success-thr_2ptrjaw73f branch November 18, 2026 21:58
ymichael added a commit that referenced this pull request Nov 18, 2026
…eeds-recovery state

Rebased onto origin/main as one commit. The drop of hosts.suspend_retry_at
is regenerated as migration 0159, the plugin SDK moves to 0.6.162, and the
retry-cleanup guard test expects the 502 machine_teardown_failed answer that
#7748 added. The bb-app launcher restart budget (#3340) is left out of this
PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant