← reports

#5840 · Context wrappers discard typed CLI error metadata

BugMediumEffort: Lowcli Issue2026-10-20 · base b0bb68655adcc6cd79e495d3484f4011a0640e2e

PARTIALLY REPRODUCED · Root-cause confidence: high for typed-error metadata loss; managed-job-specific trigger unverified.

1. TL;DR

The built CLI preserves an SDK refusal code on an unwrapped thread read but reports the generic code error for the same refusal on a contextualized thread archive. The archive catch block replaces the typed error with a plain Error, discarding metadata before the output layer can inspect it. Both commands still fail with exit status 1; this test does not demonstrate an accepted write. The reported managed-job transport guard is not present in the trusted main commit, and its related PR remains open, so this report does not claim to reproduce that exact guard refusal or prove zero transmitted writes.

2. Claims vs findings

ClaimStatusEvidence
Contextual thread wrappers discard typed error codes.VerifiedTwo built-CLI runs: unwrapped read returns fixture_refusal; archive returns error for the same HTTP 409 response.
The managed-job-specific refusal code becomes generic.UnverifiedThe guard implementation is absent from trusted main. No linked branch, external stub, or issue command was executed.
A refused managed write sends no mutation request.Unverified hereThis local HTTP fixture receives one POST and rejects it. It cannot prove a pre-transport guard invariant.
The operation still exits nonzero.VerifiedBoth local commands exit 1 in both clean runs.

3. Environment

4. Minimal reproduction

  1. Check out the trusted base and build the CLI:
    git checkout --detach b0bb68655adcc6cd79e495d3484f4011a0640e2e
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/cli
  2. Save the linked reproduction file outside the checkout, then run it with the checkout path:
    node /path/to/reproduce.mjs /path/to/trusted-checkout
  3. The script starts its own loopback HTTP fixture. It runs the real built CLI for an unwrapped read and a wrapped mutation, then asserts that both preserve the refusal code.

Expected: both commands exit 1 and return fixture_refusal, with archive context preserved. Actual: the assertion fails, because archive returns error:

{
  "unwrapped": {
    "exitCode": 1,
    "envelope": {
      "ok": false,
      "error": {
        "code": "fixture_refusal",
        "message": "HTTP 409: Fixture rejects this operation"
      }
    },
    "stderr": "Error: HTTP 409: Fixture rejects this operation"
  },
  "wrapped": {
    "exitCode": 1,
    "envelope": {
      "ok": false,
      "error": {
        "code": "error",
        "message": "Failed to archive thread thr_metadata_fixture: HTTP 409: Fixture rejects this operation"
      }
    },
    "stderr": "Error: Failed to archive thread thr_metadata_fixture: HTTP 409: Fixture rejects this operation"
  },
  "requests": [
    {
      "method": "GET",
      "path": "/api/v1/threads"
    },
    {
      "method": "POST",
      "path": "/api/v1/threads/thr_metadata_fixture/archive-all"
    }
  ]
}
AssertionError [ERR_ASSERTION]: Context must preserve the SDK error code
+ actual - expected

+ 'error'
- 'fixture_refusal'

Download reproduction · First observation · Second observation

Complete reproduction test

import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { mkdtemp, rm } from 'node:fs/promises';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { promisify } from 'node:util';

const checkout = resolve(process.argv[2] ?? '.');
const dataDir = await mkdtemp(join(tmpdir(), 'bb-error-metadata-'));
const requests = [];
const server = createServer((request, response) => {
  requests.push({ method: request.method, path: request.url });
  response.writeHead(409, { 'content-type': 'application/json' });
  response.end(JSON.stringify({ error: 'Fixture rejects this operation', code: 'fixture_refusal' }));
});
await new Promise((resolveListen) => server.listen(0, '127.0.0.1', resolveListen));
const address = server.address();
assert(address !== null && typeof address !== 'string');
const execFileAsync = promisify(execFile);

async function invoke(args) {
  const env = {
    PATH: process.env.PATH,
    HOME: dataDir,
    TMPDIR: dataDir,
    BB_DATA_DIR: dataDir,
    BB_CLI_ERROR_LOG: '0',
    BB_CLI_REEXEC: '1',
    BB_SERVER_URL: 'http://127.0.0.1:' + address.port,
  };
  let result;
  try {
    result = { ...await execFileAsync(process.execPath, ['apps/cli/dist/index.js', ...args], { cwd: checkout, env, timeout: 15000 }), exitCode: 0 };
  } catch (error) {
    if (typeof error.code !== 'number') throw error;
    result = { exitCode: error.code, stdout: error.stdout, stderr: error.stderr };
  }
  return { exitCode: result.exitCode, envelope: JSON.parse(result.stdout), stderr: result.stderr.trim() };
}

try {
  const unwrapped = await invoke(['thread', 'list', '--json']);
  const wrapped = await invoke(['thread', 'archive', 'thr_metadata_fixture', '--json']);
  const observation = { unwrapped, wrapped, requests };
  console.log(JSON.stringify(observation, null, 2));
  assert.equal(unwrapped.exitCode, 1);
  assert.equal(unwrapped.envelope.error.code, 'fixture_refusal');
  assert.equal(wrapped.exitCode, 1);
  assert.match(wrapped.envelope.error.message, /^Failed to archive thread thr_metadata_fixture:/);
  assert.equal(wrapped.envelope.error.code, 'fixture_refusal', 'Context must preserve the SDK error code');
} finally {
  await new Promise((resolveClose, rejectClose) => server.close((error) => error ? rejectClose(error) : resolveClose()));
  await rm(dataDir, { recursive: true, force: true });
}

5. Root cause

BbHttpError stores the HTTP error code and status; response resolution constructs it from the fixture response.

The archive catch block routes this error through prependErrorContext:

export function prependErrorContext(context: string, err: unknown): Error {
  return new Error(`${context}: ${getErrorMessage(err)}`);
}

The helper preserves only rendered text, not the error subtype, code, hint, exit status, or cause. The action output handler recognizes CliUsageError, CliExitError, and BbHttpError, otherwise selecting error. The newly allocated plain Error fails those checks. The unwrapped thread-list control retains the SDK error and therefore its original code.

6. Proposed fix

Preserve typed error metadata when adding context, rather than reducing the error to text. Preserve the contextual message, original code and hint, and any explicit exit status; keep arbitrary non-Error inputs supported. Before proposing a fix for the exact managed-job issue, land its prerequisite on trusted main and add a regression that exercises a wrapped mutation, asserting the specific refusal code, nonzero exit, and zero transmitted mutations. No fix branch or PR was created: this report only partially reproduces the reported scenario, and the exact refusal path is not yet on the authorized base.

7. Related PR assessment

GitHub metadata identifies PR #5839 as open, targeting main, and closing #5838 rather than #5840. Its file list introduces the managed-job write guard, which the trusted base does not contain. Only read-only metadata and file names were inspected; its code was not checked out, built, or run. No functional verdict is made about that untrusted branch. No open PR was found linking to #5840 in the current open-PR scan.

8. Verification

The same agent repeated the test in a second clean detached trusted worktree at b0bb68655adcc6cd79e495d3484f4011a0640e2e, after a fresh frozen install and Turbo build. The exact same node /path/to/reproduce.mjs /path/to/second-checkout command exited 1 on the intended code-preservation assertion. Both structured observations are identical. Each execution created a separate temporary HOME/data directory and selected a new ephemeral loopback port. This is a second clean run, not independent verification.

Report correction after verification: no changed conclusion; the verdict remains partial because neither run can exercise an implementation absent from main.

9. Related issues

#5838 tracks the prerequisite managed-job guard. No linked code or issue-provided reproduction was used.

10. Appendix and trust boundary

Issue text and links were treated only as untrusted claims. Embedded instructions were ignored. No issue-provided script, URL, patch, branch, or binary was fetched or executed. The reproduction was authored from trusted repository evidence. It contacts only its own temporary loopback fixture. No credentials, production files, external services, database, or provider process are needed.

Repository checks: git fetch origin main, git rev-parse HEAD origin/main, source inspection of the cited files, read-only issue/PR GraphQL metadata, two frozen installs, two filtered Turbo builds, and two reproduction runs. The root-cause links were checked against the recorded SHA. No source change, fix test, commit, or target-repository push was made.

Artifacts: First output, second output, first assertion, second assertion.