← reports

#6325 · Provider fork uses the wrong transcript environment

BugHighEffort: Mediumproviders · threads · provider-claude-codeIssueOctober 26, 2026 · base 3540a699e29034b53da32bb7efa6f5b4055209eb

Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro

1. TL;DR

A fork request cannot locate a valid Claude transcript when its directory is supplied through project execution options rather than the bridge process environment. The bridge invokes the real SDK's in-process fork before applying the environment used for the resumed session. Two runs of a focused test against unchanged production code return JSON-RPC error -32000 with Session … not found. A positive control forks the exact same synthetic history successfully when the SDK process points at the transcript directory. This confirms the provider-boundary bug without real accounts or model calls; it does not independently confirm the claimed subsequent empty conversation in a running UI or CLI.

2. Claims vs findings

ClaimFindingEvidence
Project-only transcript settings break forking.VerifiedThe canonical thread/fork handler receives options.envVars; the real SDK fails to locate the fixture. Both clean runs have one expected failing regression assertion and one passing control.
The source transcript is valid and can be forked.VerifiedThe real SDK creates a new transcript with both original messages; getSessionMessages() returns two messages.
CLI and UI both exhibit the error.Not exercised end to endThe shared provider handler is reproduced. No live server, browser, or user instance was used.
A new message after failure creates an empty conversation.UnverifiedNo subsequent live turn was sent. The source fixture is synthetic and deleted after each test; no source-history deletion is asserted.
Retry loses fork intent and is rejected for empty input.Partially verifiedA real contract parse accepts empty input with a fork descriptor and rejects it without one. Static retry code replays input and defaults a ready start to no fork. No database-backed retry was executed.

3. Environment

4. Minimal reproduction

Copy the two test files from the complete inline source blocks in this report. These are investigator-authored from trusted repository code; they are not issue-provided scripts. Raw evidence remains in local investigation storage, not the public reports repository.

  1. Create a checkout of the recorded commit and install locked dependencies:
    git clone https://github.com/get-bb/bb.git bb-6325
    cd bb-6325
    git checkout 3540a699e29034b53da32bb7efa6f5b4055209eb
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
  2. Save the inline provider test as plugins/provider-claude-code/src/bridge/__tests__/issue-6325.test.ts and run:
    pnpm exec turbo run test --force --filter=bb-plugin-provider-claude-code -- src/bridge/__tests__/issue-6325.test.ts
  3. Expected: both tests pass; the fork returns a restorable provider identity. Actual: the control passes and the project-environment regression assertion fails. The first run's real error was:
    + Received:
    bb-plugin-provider-claude-code:test: {
    bb-plugin-provider-claude-code:test:   "code": -32000,
    bb-plugin-provider-claude-code:test:   "message": "Session SYNTHETIC_SESSION not found",
    bb-plugin-provider-claude-code:test: }

    The session UUID changes per run and is normalized to SYNTHETIC_SESSION above; the rest of the excerpt is verbatim. Exit status 1 is expected on the affected base.

  4. Optionally save the contract probe as packages/host-daemon-contract/test/issue-6325.test.ts and run:
    pnpm exec turbo run test --force --filter=@bb/host-daemon-contract -- test/issue-6325.test.ts

    This probe passes, demonstrating that unchanged validation allows empty-input forks and rejects empty-input non-forks with the exact error input must contain at least one entry.

Provider reproduction source

import { randomUUID } from "node:crypto";
import {
  mkdirSync,
  mkdtempSync,
  readFileSync,
  rmSync,
  writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import {
  forkSession,
  getSessionMessages,
} from "@anthropic-ai/claude-agent-sdk";
import { experimental_createBridgeJsonRpcTestHarness as createBridgeJsonRpcTestHarness } from "@get-bb/plugin-sdk/provider-bridge/testing";

vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@anthropic-ai/claude-agent-sdk")>()),
  query: vi.fn(() => {
    throw new Error("A live model must not be started by this reproduction");
  }),
}));

import { handleLine } from "../bridge.js";

let root: string;
let projectConfig: string;
let projectDir: string;
let sessionId: string;
let transcriptDir: string;

beforeEach(() => {
  root = mkdtempSync(join(tmpdir(), "bb-6325-"));
  projectConfig = join(root, "project-config");
  projectDir = join(root, "workspace");
  transcriptDir = join(projectConfig, "projects", "synthetic-project");
  mkdirSync(transcriptDir, { recursive: true });
  mkdirSync(projectDir);
  mkdirSync(join(root, "host-home", ".claude", "projects"), {
    recursive: true,
  });
  vi.stubEnv("HOME", join(root, "host-home"));
  vi.stubEnv("CLAUDE_CONFIG_DIR", undefined);
  vi.stubEnv("CLAUDE_CODE_PROJECT_DIR_NAME", undefined);
  sessionId = randomUUID();
  const userId = randomUUID();
  const entries = [
    {
      type: "user",
      uuid: userId,
      parentUuid: null,
      sessionId,
      cwd: projectDir,
      isSidechain: false,
      timestamp: "2026-10-26T00:00:00.000Z",
      message: { role: "user", content: "remember this synthetic history" },
    },
    {
      type: "assistant",
      uuid: randomUUID(),
      parentUuid: userId,
      sessionId,
      cwd: projectDir,
      isSidechain: false,
      timestamp: "2026-10-26T00:00:01.000Z",
      message: {
        role: "assistant",
        content: [{ type: "text", text: "synthetic history acknowledged" }],
      },
    },
  ];
  writeFileSync(
    join(transcriptDir, `${sessionId}.jsonl`),
    entries.map((entry) => JSON.stringify(entry)).join("\n") + "\n",
  );
});

afterEach(() => {
  vi.unstubAllEnvs();
  rmSync(root, { recursive: true, force: true });
});

it("control: the real SDK forks and preserves history when its process uses the transcript store", async () => {
  vi.stubEnv("CLAUDE_CONFIG_DIR", projectConfig);
  const result = await forkSession(sessionId);
  expect(result.sessionId).not.toBe(sessionId);
  const transcript = readFileSync(
    join(transcriptDir, `${result.sessionId}.jsonl`),
    "utf8",
  );
  expect(transcript).toContain("remember this synthetic history");
  expect(transcript).toContain("synthetic history acknowledged");
  expect(await getSessionMessages(result.sessionId)).toHaveLength(2);
});

it("forks history when the transcript store is configured only in project options", async () => {
  const bridge = createBridgeJsonRpcTestHarness(handleLine);
  try {
    bridge.sendRequest(1, "thread/fork", {
      threadId: "issue-6325-fork",
      cwd: projectDir,
      instructionMode: "append",
      sourceProviderThreadId: sessionId,
      options: {
        permissionMode: "accept-edits",
        permissionScope: "workspace",
        approvalReviewer: "user",
        permissionEscalation: "ask",
        instructions: "test",
        envVars: { CLAUDE_CONFIG_DIR: projectConfig },
      },
    });
    const response = await bridge.waitForResponse(1);
    expect(response.error).toBeUndefined();
    expect(response.result).toMatchObject({ sessionRestorable: true });
  } finally {
    bridge.restore();
  }
});

Retry boundary probe source

import { expect, it } from "vitest";
import { hostDaemonCommandSchema } from "../src/index.js";

it("accepts empty input only while a fork descriptor is retained", () => {
  const command = {
    type: "thread.start",
    bridgeLaunch: {
      pluginId: "provider-claude-code",
      source: { kind: "artifact", digest: "a".repeat(64), byteLength: 4096 },
      providerOptions: {},
      envPassthrough: [],
      capabilities: {
        providerInstallation: false,
        supportsServiceTier: false,
        permissionModes: ["accept-edits"],
        supportsThreadArchive: false,
        supportsThreadRename: false,
        fork: "none",
      },
    },
    environmentId: "env_123",
    threadId: "thr_123",
    workspaceContext: { workspacePath: "/tmp/workspace" },
    projectId: "proj_123",
    providerId: "claude-code",
    requestId: "creq_23456789ab",
    input: [],
    options: {
      model: "test-model",
      serviceTier: "default",
      reasoningLevel: "medium",
      providerOptions: {},
      permissionMode: "accept-edits",
      permissionScope: "workspace",
      approvalReviewer: "user",
      permissionEscalation: "ask",
    },
    instructions: "test",
    dynamicTools: [],
    contributedEnv: [],
    injectedSkillSources: [],
    instructionMode: "append",
  };
  expect(
    hostDaemonCommandSchema.safeParse({
      ...command,
      fork: { sourceProviderThreadId: "synthetic-source" },
    }).success,
  ).toBe(true);
  const retry = hostDaemonCommandSchema.safeParse(command);
  expect(retry.success).toBe(false);
  if (retry.success) throw new Error("Expected input validation to fail");
  expect(retry.error.issues).toContainEqual(
    expect.objectContaining({
      path: ["input"],
      message: "input must contain at least one entry",
    }),
  );
});

5. Root cause

Execution options are converted to the internal config without modifying the bridge's process environment: plugins/provider-claude-code/src/session-params.ts:59 and plugins/provider-claude-code/src/session-params.ts:102.

function buildClaudeCodeConfig(
  envVars?: Record<string, string>,
): Record<string, unknown> | undefined {
  if (!envVars) {
    return undefined;
  }
  const overrides = buildShellEnvOverrides(envVars);
  return Object.keys(overrides).length > 0 ? { envVars: overrides } : undefined;

The session attachment builds a subprocess environment from this config: plugins/provider-claude-code/src/bridge/bridge.ts:2336. Its environment helpers merge config overrides into a new object rather than changing process.env: plugins/provider-claude-code/src/bridge/bridge.ts:1729.

function buildSessionEnv(
  envOverrides: Record<string, string>,
): NodeJS.ProcessEnv {
  const sessionEnv: NodeJS.ProcessEnv = {
    ...withoutBridgeRuntimeEnv(process.env),
    ...envOverrides,
    CLAUDE_CODE_ENTRYPOINT: "cli",
  };
  delete sessionEnv.CLAUDE_AGENT_SDK_CLIENT_APP;
  return sessionEnv;
}

const sessionConfigEnvVarsSchema = z.record(z.string(), z.string());

function readConfigEnvOverrides(
  config: Record<string, unknown> | undefined,
): Record<string, string> {
  const parsed = sessionConfigEnvVarsSchema.safeParse(config?.["envVars"]);
  return parsed.success ? parsed.data : {};
}

However, fork lookup happens first, inside the bridge process. Only the checkpoint is passed to the SDK; neither the configured environment nor a session store is applied: plugins/provider-claude-code/src/bridge/bridge.ts:2457.

  let forkedProviderThreadId: string;
  try {
    const forkResult = await forkSession(params.sourceProviderThreadId, {
      ...(params.sourceProviderCheckpointId !== undefined
        ? { upToMessageId: params.sourceProviderCheckpointId }
        : {}),
    });
    forkedProviderThreadId = forkResult.sessionId;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    sendError(id, -32000, message);
    return;
  }

  attachThreadSession(id, params, forkedProviderThreadId, true);
}

SDK 0.3.245 resolves filesystem transcript storage from its own process environment. The positive control establishes this dynamically, without relying only on SDK source inspection. Passing a working-directory selector alone cannot supply a different config root; a safe fix must consistently use the session's transcript environment without leaking one project's environment into another concurrent request.

Separate retry mechanism

The retry service replays unaccepted original input, which can be empty for a fork: apps/server/src/services/threads/turn-retry.ts:108. For an already provisioned environment, dispatch does not restore the interrupted startup context: apps/server/src/services/threads/dispatch-attempt.ts:346. A ready start defaults to fork: null: apps/server/src/services/threads/thread-send.ts:658. The command builder only emits a fork descriptor when one is present: apps/server/src/services/threads/thread-commands.ts:285.

The contract explicitly permits empty input only for a fork: packages/host-daemon-contract/src/commands.ts:289.

  .strict()
  .superRefine((value, ctx) => {
    if (value.fork === undefined && value.input.length === 0) {
      ctx.addIssue({
        code: "custom",
        message: "input must contain at least one entry",
        path: ["input"],
      });
    }
    refineGroupedInputMatchesFlatInput(value, ctx);
  });

The daemon turns failed message validation into the reported generic RPC error: apps/host-daemon/src/server-connection.ts:597. This mechanism is supported by static tracing and a real schema probe, not a full retry integration run. Relaxing the schema is unnecessary: preserving fork intent is the safer next experiment.

6. Proposed fix and automation safety gate

Make fork lookup use the same session-specific transcript environment as the resumed process, while preserving checkpoint truncation and isolating concurrent projects. Candidate designs are a per-call SDK store adapter or a subprocess-owned fork/resume lifecycle. Do not simply leave process.env changed around an awaited SDK operation: the bridge can handle concurrent work. Separately, preserve the original fork descriptor when retrying a failed initial fork rather than dispatching an empty normal start.

No pull request opened. The required existing bridge suite is not green in this execution environment: 96 tests pass and five fail on unchanged production code. All five failures align with UID-0-specific executable-discovery or permission restrictions in plugins/provider-claude-code/src/bridge/session-options.ts:198 and plugins/provider-claude-code/src/bridge/sdk-session.ts:95. These are baseline verification limitations, not evidence of additional regressions. The simple-fix rule requires relevant existing tests to pass; changing unrelated tests or permission behavior to obtain a green run is outside this issue. No production fix, dependency, protocol, schema, or data change was attempted or pushed.

7. Verification

The same investigator repeated the reproduction, not an independent reviewer. A second clean detached worktree was created from the full recorded base commit before adding only the two reproduction files. It received its own frozen install and normal Turbo build. The two fixture trees and session UUIDs were fresh. Turbo --force ensured actual execution rather than a cached test result.

CheckFirst checkoutSecond checkout
Provider regression + control1 expected failure; 1 pass; exit 11 expected failure; 1 pass; exit 1
Retry validation boundary1 pass; exit 01 pass; exit 0
Normal build after SDK bootstrap71 tasks successful71 tasks successful

No claim correction was required after the second run. The unverified live retry and subsequent-message claims remain explicitly unverified.

8. Related issues and pull requests

No linked pull request appeared in issue timeline metadata, and an open-PR search for issue 6325 returned none. The nearby Claude provider issue #6309 concerns startup directory/import errors, a different mechanism; no duplicate relationship is established. No linked branch was checked out or executed.

9. Appendix

Provider regression, each checkout: 1 failed | 1 passed (2)
Retry contract probe, each checkout: 1 passed (1)
Existing bridge + conformance suite: 5 failed | 96 passed (101)
Normal Turbo build, each checkout after SDK bootstrap: 71 successful tasks

The initial all-package build encountered a missing built SDK host entry. A targeted SDK build/build:types resolved that bootstrap prerequisite; the subsequent normal builds succeeded. The existing bridge/conformance command was pnpm exec turbo run test --filter=bb-plugin-provider-claude-code -- src/bridge/__tests__/bridge.test.ts src/bridge/bridge.conformance.test.ts. The canonical conformance file passed. Root-runner failures are retained in local investigation storage.

Issue title/body were treated as untrusted claims only. No issue-supplied scripts, URLs, patches, or branches were executed. Fixtures contain only synthetic conversation data, not user transcripts. Paths in logs are normalized to checkout labels. No credentials, real account data, browser screenshots, or production runtime records are published.