Reports

#5843 · Resident turns discard updated dynamic-tool definitions

BugPriority: MediumEffort: Mediumproviders · host · provider-claude-code

GitHub issue · October 20, 2026 · trusted base e0f6fda5a02332bd4eb44183542a57f34f3263d7

PARTIALLY REPRODUCED · root-cause confidence: high for the verified resident-update defect

1. TL;DR

When an already-attached thread receives a later turn with new tool definitions, the daemon drops those definitions before calling the agent runtime. The same turn succeeds, but the runtime can only retain its initial tool snapshot. A focused test reproduces both an initially empty snapshot and a stale tool definition; releasing the session first makes both controls pass. The Claude bridge already detects changed construction settings, including tools, when explicitly resumed, and a second probe verifies that this rebuild restores its bridge configuration without changing the provider conversation identity. The exact macOS plugin-reload timing and real Claude CLI tool-search behavior were not reproduced; the verdict is therefore partial rather than a claim of full end-to-end reproduction.

2. Claims vs findings

ClaimStatusEvidence
An initially empty tool snapshot stays empty on resident turns.Verified at daemon/runtime and SDK-configuration boundariesTwo successive submissions never deliver new tools to the runtime; the provider probe keeps one query with no bridge until resume.
A changed tool snapshot is not refreshed on later turns.Verified at those boundariesThe stale-description daemon case fails identically; the provider probe keeps the old allowed tool name until explicit resume.
Releasing and resuming restores tools.Verified at those boundariesBoth release controls pass; explicit Claude resume creates a second query with the current bridge tool and the same provider conversation ID.
The provider has no comparison for changed dynamic tools.Too broadOrdinary turn input has none, but handleThreadResume compares the full construction configuration, which includes dynamicTools.
A scheduled wake-up concurrent with plugin relocation supplies an empty tool set.UnverifiedNo real plugin reload, scheduling race, or reporter runtime data was used.
The actual Claude CLI loses deferred bridge tools in that race.UnverifiedThe SDK query is mocked; no actual Claude process or ToolSearch execution.

3. Environment

4. Minimal reproduction

  1. Use a clean checkout at the recorded commit and run the frozen install and Turbo build.
  2. Save the complete inline daemon test below at apps/host-daemon/test/command/issue-5843.test.ts.
  3. Save and apply the complete inline provider patch below, which only extends the existing provider test fixture and local query-options test type.
  4. Run the commands below. Neither artifact changes production code or adds a dependency.
git clone https://github.com/get-bb/bb.git bb-5843
cd bb-5843
git checkout --detach e0f6fda5a02332bd4eb44183542a57f34f3263d7
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build

# Copy the inline daemon test below to:
# apps/host-daemon/test/command/issue-5843.test.ts
# Save the inline provider patch below as provider-repro.patch, then apply it.
git apply provider-repro.patch

pnpm exec turbo run test --force --filter=@bb/host-daemon -- --run test/command/issue-5843.test.ts
# Expected exit 1 on affected main: two resident cases fail, two release controls pass.
pnpm exec turbo run test --force --filter=bb-plugin-provider-claude-code -- --run src/bridge/__tests__/bridge.test.ts -t 'issue 5843 tool snapshot lifecycle'
# Expected exit 0: two provider lifecycle probes pass.
pnpm exec turbo run test --filter=@bb/host-daemon -- --run test/command/thread-dispatch.test.ts
# Existing daemon dispatch suite: 34 tests pass.

Expected contract: an updated tool set supplied with a later turn reaches some runtime entry point, whether by safe resume/rebuild or a supported turn update. All four daemon cases would pass.

Actual, both clean runs: resident empty/stale cases fail; both release controls pass. The actual emitted runtime-delivery traces are:

{"initial":"empty","release":false,"starts":1,"resumes":0,"turns":2,"toolDeliveries":[[]]}
{"initial":"stale","release":false,"starts":1,"resumes":0,"turns":2,"toolDeliveries":[[{"name":"fixture_echo","description":"Old fixture tool","inputSchema":{"type":"object","properties":{},"additionalProperties":false}}]]}
Tests  2 failed | 2 passed (4)

The provider probe passes both cases: ordinary turns reuse the original SDK query and bridge configuration; explicit resume with the current tool list closes that query and creates a resumed one with mcp__bb-bridge__fixture_echo.

Complete daemon reproduction test

import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { HostDaemonCommand } from "@bb/host-daemon-contract";
import { encodeClientTurnRequestIdNumber, type DynamicTool } from "@bb/domain";
import { expect, it, vi } from "vitest";
import { dispatchCommand } from "../../src/command-dispatch.js";
import {
  createHarness,
  DISPATCH_TEST_BRIDGE_LAUNCH,
} from "./dispatch-helpers.js";

const currentTools: DynamicTool[] = [
  {
    name: "fixture_echo",
    description: "Current fixture tool",
    inputSchema: { type: "object", properties: {}, additionalProperties: false },
  },
];

it.each([
  { initial: "empty", release: false },
  { initial: "stale", release: false },
  { initial: "empty", release: true },
  { initial: "stale", release: true },
])(
  "delivers current tools from $initial attachment with release=$release",
  async ({ initial, release }) => {
    const scratch = mkdtempSync(join(tmpdir(), "bb-5843-repro-"));
    const workspacePath = join(scratch, "workspace");
    const harness = createHarness({ workspacePath });
    const start = vi.spyOn(harness.runtime, "startThread");
    const resume = vi.spyOn(harness.runtime, "resumeThread");
    const run = vi.spyOn(harness.runtime, "runTurn");
    const options = {
      model: "fixture-model",
      serviceTier: "default" as const,
      reasoningLevel: "medium" as const,
      providerOptions: {},
      permissionMode: "full" as const,
      permissionScope: "full" as const,
      approvalReviewer: null,
      permissionEscalation: null,
    };
    const dispatchOptions = harness.dispatchOptions({
      dataDir: join(scratch, "data"),
      threadStorageRootPath: join(scratch, "storage"),
    });
    const initialTools = initial === "empty"
      ? []
      : currentTools.map((tool) => ({ ...tool, description: "Old fixture tool" }));
    try {
      await dispatchCommand(
        {
          type: "thread.start",
          bridgeLaunch: DISPATCH_TEST_BRIDGE_LAUNCH,
          environmentId: "env-5843",
          threadId: "thread-5843",
          workspaceContext: { workspacePath },
          projectId: "project-5843",
          providerId: "fake",
          requestId: encodeClientTurnRequestIdNumber({ value: 1 }),
          input: [],
          options,
          instructions: "Fixture instructions",
          dynamicTools: initialTools,
          contributedEnv: [],
          injectedSkillSources: [],
          instructionMode: "append",
        },
        dispatchOptions,
      );
      const submit: Extract<HostDaemonCommand, { type: "turn.submit" }> = {
        type: "turn.submit",
        bridgeLaunch: DISPATCH_TEST_BRIDGE_LAUNCH,
        environmentId: "env-5843",
        threadId: "thread-5843",
        requestId: encodeClientTurnRequestIdNumber({ value: 2 }),
        input: [{ type: "text", text: "Fixture input", mentions: [] }],
        options,
        target: { mode: "start" },
        resumeContext: {
          bridgeLaunch: DISPATCH_TEST_BRIDGE_LAUNCH,
          workspaceContext: { workspacePath },
          projectId: "project-5843",
          providerId: "fake",
          providerThreadId: "provider-thread-5843",
          instructions: "Fixture instructions",
          dynamicTools: currentTools,
          contributedEnv: [],
          injectedSkillSources: [],
          instructionMode: "append",
        },
      };
      if (release) {
        await harness.runtime.stopThread({ threadId: "thread-5843" });
      }
      for (const value of [2, 3]) {
        await dispatchCommand(
          { ...submit, requestId: encodeClientTurnRequestIdNumber({ value }) },
          dispatchOptions,
        );
        harness.threadControls.endActiveTurn("thread-5843");
      }
      const deliveries = [
        ...start.mock.calls.map(([args]) => args),
        ...resume.mock.calls.map(([args]) => args),
        ...run.mock.calls.map(([args]) => args),
      ];
      console.log(JSON.stringify({
        initial,
        release,
        starts: start.mock.calls.length,
        resumes: resume.mock.calls.length,
        turns: run.mock.calls.length,
        toolDeliveries: deliveries.flatMap((args) =>
          "dynamicTools" in args ? [args.dynamicTools] : [],
        ),
      }));
      expect(deliveries).toContainEqual(expect.objectContaining({
        dynamicTools: currentTools,
      }));
    } finally {
      await harness.manager.shutdownAll();
      start.mockRestore();
      resume.mockRestore();
      run.mockRestore();
      rmSync(scratch, { recursive: true, force: true });
    }
  },
);

Complete provider lifecycle probe patch

diff --git a/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts b/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts
index f0fe2b039..c976fe95f 100644
--- a/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts
+++ b/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts
@@ -100,11 +100,13 @@ interface ControlledClaudeQuery {
 
 interface ClaudeQueryCallOptions {
   allowDangerouslySkipPermissions?: boolean;
+  allowedTools?: BridgeSessionOptions["allowedTools"];
   canUseTool?: CanUseTool;
   env?: Record<string, string | undefined>;
   extraArgs?: Record<string, string | null>;
   hooks?: BridgeSessionHooks;
   model?: string;
+  mcpServers?: BridgeSessionOptions["mcpServers"];
   permissionMode?: ClaudePermissionMode;
   resume?: string;
   sandbox?: BridgeSessionOptions["sandbox"];
@@ -5806,6 +5808,98 @@ describe("canonical skills/configure", () => {
   });
 });
 
+describe("issue 5843 tool snapshot lifecycle", () => {
+  it.each(["empty", "stale"])(
+    "refreshes an %s snapshot on explicit resume, not ordinary turns",
+    async (initial) => {
+      queryMock.mockReset();
+      const bridge = createBridgeJsonRpcTestHarness(handleLine);
+      const queries: ControlledClaudeQuery[] = [];
+      queryMock.mockImplementation(() => {
+        const query = createControlledClaudeQuery();
+        queries.push(query);
+        return query;
+      });
+      const threadId = `thread-5843-${initial}`;
+      const options = {
+        permissionMode: "full",
+        permissionScope: "full",
+        approvalReviewer: null,
+        permissionEscalation: null,
+      };
+      const session = {
+        threadId,
+        cwd: "/tmp/fixture-workspace",
+        instructionMode: "append",
+        options,
+      };
+      const tools = [{
+        name: "fixture_echo",
+        description: "Current fixture tool",
+        inputSchema: { type: "object", properties: {} },
+      }];
+      try {
+        bridge.sendRequest(1, "thread/start", {
+          ...session,
+          dynamicTools: initial === "empty" ? [] : [{
+            ...tools[0],
+            name: "fixture_old",
+          }],
+        });
+        const providerThreadId = getProviderThreadIdFromResult(
+          await bridge.waitForResponse(1),
+        );
+        for (const requestId of [2, 3]) {
+          bridge.sendRequest(requestId, "turn/start", {
+            threadId,
+            providerThreadId,
+            clientRequestId: requestId === 2 ? "creq_23456789ab" : "creq_23456789ac",
+            input: [{ type: "text", text: "Fixture input", mentions: [] }],
+            options,
+          });
+          await readNextPrompt(getLatestQueryCall());
+          await bridge.waitForResponse(requestId);
+          queries[0]?.emit(createSuccessfulResultMessage(providerThreadId));
+          await bridge.flushWork();
+        }
+        expect(queries).toHaveLength(1);
+        expect(getLatestQueryOptions().allowedTools).toEqual(
+          initial === "empty" ? undefined : ["mcp__bb-bridge__fixture_old"],
+        );
+        expect(Object.keys(getLatestQueryOptions().mcpServers ?? {})).toEqual(
+          initial === "empty" ? [] : ["bb-bridge"],
+        );
+        bridge.sendRequest(4, "thread/resume", {
+          ...session,
+          providerThreadId,
+          dynamicTools: tools,
+        });
+        await bridge.waitForResponse(4);
+        expect(queries).toHaveLength(2);
+        expect(queries[0]?.close).toHaveBeenCalledOnce();
+        expect(getLatestQueryOptions().resume).toBe(providerThreadId);
+        expect(getLatestQueryOptions().allowedTools).toEqual([
+          "mcp__bb-bridge__fixture_echo",
+        ]);
+        expect(Object.keys(getLatestQueryOptions().mcpServers ?? {})).toEqual([
+          "bb-bridge",
+        ]);
+      } finally {
+        bridge.sendRequest(99, "thread/stop", {
+          threadId,
+          providerThreadId: threadId,
+          intent: "interrupt",
+          activeTurnId: null,
+        });
+        await bridge.flushWork();
+        queries.forEach((query) => query.finish());
+        await bridge.waitForResponse(99);
+        bridge.restore();
+      }
+    },
+  );
+});
+
 describe("canonical model context-window hint", () => {
   const canonicalOptions = {
     permissionMode: "full",

5. Root cause

The server constructs turn submissions with current tools inside resumeContext (see server payload construction). At the daemon, an already-present thread bypasses the only path which forwards that tool set:

apps/host-daemon/src/command-handlers/thread.ts:186

async function resumeThreadRuntimeIfMissing(
  args: ResumeThreadRuntimeIfMissingArgs,
): Promise<void> {
  const { command, entry, options } = args;
  const { resumeContext } = command;
  if (entry.runtime.hasThread(command.threadId)) {
    return;
  }

apps/host-daemon/src/command-handlers/thread.ts:204

  await entry.runtime.resumeThread({
    bridgeLaunch,
    skillRoots: entry.skillRoots,
    environmentId: command.environmentId,
    threadId: command.threadId,
    projectId: resumeContext.projectId,
    providerThreadId: resumeContext.providerThreadId,
    providerId: resumeContext.providerId,
    contributedEnv: resumeContext.contributedEnv,
    options: command.options,
    instructions: resumeContext.instructions,
    dynamicTools: resumeContext.dynamicTools,
    instructionMode: resumeContext.instructionMode,
  });

The ordinary turn path forwards environment/instruction changes, but not tools:

apps/host-daemon/src/command-handlers/thread.ts:338

async function runSubmittedTurn(
  command: TurnSubmitCommand,
  entry: RuntimeEntry,
): Promise<void> {
  await entry.runtime.runTurn({
    threadId: command.threadId,
    input: command.input,
    clientRequestId: command.requestId,
    options: command.options,
    contributedEnv: command.resumeContext.contributedEnv,
    instructions: command.resumeContext.instructions,
  });
}

This is not merely a missing SDK call in Claude's turn handler: runtime turn/steer arguments and canonical turn fields do not declare a tool-set update. The fresh definitions are never delivered on that path.

Claude snapshots dynamicTools in construction configuration and creates the MCP bridge only for a nonempty initial tool set:

plugins/provider-claude-code/src/bridge/bridge.ts:2306

  }
  sessionOptions.canUseTool = createCanUseTool(threadIdRef);
  if (params.dynamicTools && params.dynamicTools.length > 0) {
    const mcpServer = buildBridgeMcpServer(
      params.dynamicTools,
      createForwardToolCall(() => threadIdRef.current),
    );
    sessionOptions.mcpServers = { [BB_BRIDGE_MCP_SERVER_NAME]: mcpServer };
    sessionOptions.allowedTools = getAllowedToolNames(params.dynamicTools);
  }

Importantly, the existing resume handler compares the construction configuration and reattaches when it differs:

plugins/provider-claude-code/src/bridge/bridge.ts:2365

  const sessionConstructionConfig = toSessionConstructionConfig(params);

  const existing = threadAttachments.get(threadId);
  const existingSession = existing?.residentSession;
  if (
    existing &&
    requestedProviderThreadId &&
    !existing.closing &&
    !existingSession?.streamEnded &&
    existing.providerThreadId === requestedProviderThreadId &&
    isDeepStrictEqual(
      existing.sessionConstructionConfig,
      sessionConstructionConfig,
    )

The changed-config branch closes the old session and calls attachThreadSession with resume=true. That behavior is verified by the provider probe. A provider-only turn-handler change cannot repair definitions which never arrive.

6. Proposed fix and simple-fix decision

Refresh construction-scoped tool definitions at the resident runtime boundary before accepting a new turn. Compare normalized definitions (including name, description, schema and presentation), avoid restarting unchanged sessions, preserve provider conversation identity, and reuse the existing Claude resume/rebuild path when tools change. Keep the runtime's cached configuration synchronized so later process recovery also sees the new definitions. Steering and active-turn behavior need explicit lifecycle coverage across providers.

No production patch or pull request: the verified gap is in daemon-to-runtime resident-configuration delivery, not just the provider subsystem. A safe repair needs coordinated daemon/runtime lifecycle work, outside this rule's one-existing-subsystem simple-fix limit. The exact live plugin-reload trigger is additionally unverified. No fix branch was created or pushed; no public protocol or data was changed.

7. Verification

The same agent repeated the investigation in a second clean trusted checkout at the recorded commit. This is a repeated clean run, not independent verification. Before copying the newly authored test and patch, that checkout had no working-tree changes. It received its own frozen install and full Turbo build. Each test case created new temporary paths; no ports were needed.

CheckFirst checkoutSecond checkout
Daemon regression (unchanged production)2 intended failures, 2 release controls passSame, with Turbo --force; exit 1
Claude lifecycle probe2 pass2 pass, with Turbo --force; exit 0
Existing daemon dispatch suite34 passNot repeated; no production change
Full existing provider bridge fileFive unrelated failures after excluding the initial probe assertion mistakePristine trusted file: same five failures, 89 pass

The first provider probe incorrectly equated absent option properties with present properties containing undefined. Its assertion was corrected to inspect the actual tool list and server keys; both probes then passed in both checkouts. This changed no root-cause conclusion. Existing provider-file failures concern executable discovery and permission/sandbox expectations, reproduced before adding the probe in the second checkout. They were not repaired. No broader passing-suite claim is made.

Exact summaries from the second daemon and provider runs and the pristine-provider baseline are reproduced below. Raw logs and tests remain in the local report backup, not public repository directories, in accordance with the reports repository's publication rules. Failed SDK-option diffs are intentionally not published because they include inherited environment details.

@bb/host-daemon:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
@bb/host-daemon:test:  Test Files  1 failed (1)
@bb/host-daemon:test:       Tests  2 failed | 2 passed (4)
bb-plugin-provider-claude-code:test:  Test Files  1 passed (1)
bb-plugin-provider-claude-code:test:       Tests  2 passed | 94 skipped (96)
@bb/host-daemon:test:  Test Files  1 passed (1)
@bb/host-daemon:test:       Tests  34 passed (34)
bb-plugin-provider-claude-code:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 5 ⎯⎯⎯⎯⎯⎯⎯
bb-plugin-provider-claude-code:test:  FAIL  |bb-plugin-provider-claude-code| src/bridge/__tests__/bridge.test.ts > bridge > falls back to well-known install locations when PATH discovery fails
bb-plugin-provider-claude-code:test:  FAIL  |bb-plugin-provider-claude-code| src/bridge/__tests__/bridge.test.ts > bridge > prepares the 'full' sandbox before approving a Plan preset (undefined, undefined)
bb-plugin-provider-claude-code:test:  FAIL  |bb-plugin-provider-claude-code| src/bridge/__tests__/bridge.test.ts > bridge > prepares the 'full' sandbox before approving a Plan preset (true, undefined)
bb-plugin-provider-claude-code:test:  FAIL  |bb-plugin-provider-claude-code| src/bridge/__tests__/bridge.test.ts > bridge > refreshes permissions before turn/start and preserves the conversation
bb-plugin-provider-claude-code:test:  FAIL  |bb-plugin-provider-claude-code| src/bridge/__tests__/bridge.test.ts > bridge > refreshes permissions before turn/steer and preserves the conversation
bb-plugin-provider-claude-code:test:       Tests  5 failed | 89 passed (94)

8. Related issues and pull requests

#3626 describes a related missing-tool symptom after provider reconnect/compaction. No shared root cause is claimed. The present experiment isolates changed tool definitions on normal resident submissions. GitHub issue timeline metadata and an open-PR search found no linked open pull request for #5843 at investigation time. No pull-request branch or code was checked out.

9. Appendix

The repeatable commands, full daemon test and full provider patch are inline above; no external artifact is required. The daemon reproduction exercises changed descriptions as well as empty-to-present definitions; the Claude probe separately exercises changed names and preserves provider identity. No waiting period is needed because these are synchronous configuration-delivery decisions, not an attempt to recreate the reported timing race.

Issue content was treated only as untrusted hypotheses. No issue-supplied commands, patches, external links, plugins, or runtime data were executed or fetched. All executed repository code came from the recorded trusted main commit, plus these newly authored reproduction tests. There is no visual claim and no screenshot.

> AGENT GENERATED