← reports

#6562 · Selected Claude skill expansion depends on prompt position

Bug Priority: Medium Effort: Medium providers provider-claude-code

Issue #6562 · October 29, 2026 · trusted base 3bacfac9ed69d42392076e5b3da2815bec822cd8

REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro

1. TL;DR

BB can send an explicitly selected skill to Claude as ordinary text instead of invoking it. The reproduced case is a skill mention embedded after other text, including a skill in a later input fragment. BB replaces the dollar trigger with a slash but leaves the command in that position; the installed Claude SDK expands the command only when it leads the prompt in the tested cases. A fixture with disable-model-invocation: true therefore contributes no skill instructions to the outgoing model request when its command is embedded. A leading command is a successful control and a workaround: the flag alone does not make every direct invocation fail.

2. Claims vs findings

Reported behaviorFindingEvidence
An explicit selection can fail to load a user-only skill.Verified for an embedded mention.The real SDK's first outgoing messages contain the fixture body for the leading command, but not for the embedded command. BB's bridge retains the embedded position.
The frontmatter flag makes the skill impossible to invoke.Not true as a blanket statement.The same skill and flag expand successfully with the command at the start.
The desktop behavior occurs on macOS in release 0.48.0.Unverified platform/version detail.These checks exercise current trusted main on Linux, not the reporter's desktop or screenshots.
The issue overlaps with earlier skill-chip behavior.Likely overlap.Existing issue #2318 describes an embedded skill command and the same frontmatter setting. This investigation verifies command position, not its separate trailing-space allegation.

3. Environment

4. Minimal reproduction

A. Observe BB's outgoing provider input

  1. Start from the trusted commit, install the locked dependencies, and build the SDK with Turbo.
  2. In plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts, extend the existing selected-dollar-skill test as shown below. This preserves its real JSON-RPC bridge harness and replaces only the SDK transport, allowing observation of the exact prompt sent to the SDK.
  3. Run the focused test. Expected behavior is a selected skill at the beginning of the SDK prompt, with the remaining prose retained.
git clone https://github.com/get-bb/bb.git bb-6562
cd bb-6562
git checkout --detach 3bacfac9ed69d42392076e5b3da2815bec822cd8
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk
git apply /path/to/regression.patch
pnpm exec turbo run test --filter=bb-plugin-provider-claude-code -- src/bridge/__tests__/bridge.test.ts -t 'invokes a selected'

Apply this test-only patch to the unchanged trusted production code before running the focused test:

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 8baf166c0d..4249fed343 100644
--- a/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts
+++ b/plugins/provider-claude-code/src/bridge/__tests__/bridge.test.ts
@@ -2956,7 +2956,32 @@ describe("bridge", () => {
     },
   );
 
-  it("translates tagged dollar skill mentions without changing plain dollar text", async () => {
+  it.each([
+    {
+      prefix: "Use ",
+      trigger: "$",
+      precedingText: [],
+      expected: "/review Use  but keep $PATH and $review",
+    },
+    {
+      prefix: "Use ",
+      trigger: "/",
+      precedingText: [],
+      expected: "/review Use  but keep $PATH and $review",
+    },
+    {
+      prefix: "",
+      trigger: "/",
+      precedingText: [],
+      expected: "/review but keep $PATH and $review",
+    },
+    {
+      prefix: "",
+      trigger: "$",
+      precedingText: [{ type: "text", text: "Inspect this fixture." }],
+      expected: "/review Inspect this fixture.\n but keep $PATH and $review",
+    },
+  ])("invokes a selected $trigger skill ahead of surrounding prose: $prefix", async ({ prefix, trigger, precedingText, expected }) => {
     const bridge = createBridgeJsonRpcTestHarness(handleLine);
     const queries: ControlledClaudeQuery[] = [];
     queryMock.mockImplementation(() => {
@@ -2975,16 +3000,17 @@ describe("bridge", () => {
         canonicalTurnParams({
           threadId,
           input: [
+            ...precedingText,
             {
               type: "text",
-              text: "Use $review but keep $PATH and $review",
+              text: `${prefix}${trigger}review but keep $PATH and $review`,
               mentions: [
                 {
-                  start: 4,
-                  end: 11,
+                  start: prefix.length,
+                  end: prefix.length + "/review".length,
                   resource: {
                     kind: "command",
-                    trigger: "$",
+                    trigger,
                     name: "review",
                     source: "skill",
                     origin: "user",
@@ -2998,9 +3024,7 @@ describe("bridge", () => {
         }),
       );
 
-      expect(await readNextPromptText(call)).toBe(
-        "Use /review but keep $PATH and $review",
-      );
+      expect(await readNextPromptText(call)).toBe(expected);
       await bridge.waitForResponse(2);
       await stopBridgeThread({ bridge, queries, threadId });
     } finally {

Observed baseline assertions (three failures; the already-leading control passes):

Expected: "/review Use  but keep $PATH and $review"
Received: "Use /review but keep $PATH and $review"

Expected: "/review Inspect this fixture.\n but keep $PATH and $review"
Received: "Inspect this fixture.\n/review but keep $PATH and $review"

Tests  3 failed | 1 passed | 101 skipped (105)

B. Prove the missing skill context using the real SDK

Save the following as sdk-context.mjs outside the checkout, then run it from the checkout root. The local endpoint captures the first outgoing model request; it does not emulate skill loading. The actual Claude executable loads and expands the fixture. The script compares otherwise identical prompts with the command leading or embedded, and asserts both results. It deliberately supplies only a loopback endpoint and a non-credential test value.

env -i PATH=/usr/local/bin:/usr/bin:/bin HOME=/tmp node /path/to/sdk-context.mjs

Actual output, in both checkouts:
{"leadingSkillContentLoaded":true,"embeddedSkillContentLoaded":false}
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";

const { query } = await import(pathToFileURL(resolve(
  "plugins/provider-claude-code/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs",
)).href);
const root = await mkdtemp(join(tmpdir(), "skill-context-6562-"));
const marker = "MANUAL_SKILL_CONTEXT_6562";
const skillDirectory = join(root, ".claude", "skills", "manual-probe");
await mkdir(skillDirectory, { recursive: true });
await mkdir(join(root, "home"));
await writeFile(join(skillDirectory, "SKILL.md"), [
  "---",
  "name: manual-probe",
  "description: Manual context probe",
  "disable-model-invocation: true",
  "---",
  `Return ${marker}.`,
].join("\n"));

async function capture(prompt) {
  let captured;
  let finishCapture;
  const ready = new Promise((resolveCapture) => { finishCapture = resolveCapture; });
  const server = createServer(async (request, response) => {
    const chunks = [];
    for await (const chunk of request) chunks.push(chunk);
    if (request.url?.startsWith("/v1/messages")) {
      captured = JSON.parse(Buffer.concat(chunks).toString());
      finishCapture();
    }
    response.writeHead(200, { "content-type": "application/json" });
    response.end(JSON.stringify({
      id: "msg_probe", type: "message", role: "assistant",
      model: "claude-sonnet-4-6", content: [{ type: "text", text: "ok" }],
      stop_reason: "end_turn", stop_sequence: null,
      usage: { input_tokens: 1, output_tokens: 1 },
    }));
  });
  await new Promise((resolveListen) => server.listen(0, "127.0.0.1", resolveListen));
  const port = server.address().port;
  const controller = new AbortController();
  async function* input() {
    yield { type: "user", message: { role: "user", content: prompt }, parent_tool_use_id: null, session_id: "" };
  }
  const session = query({
    prompt: input(),
    options: {
      cwd: root,
      abortController: controller,
      settingSources: ["project"],
      tools: [],
      maxTurns: 1,
      model: "claude-sonnet-4-6",
      persistSession: false,
      env: {
        PATH: "/usr/local/bin:/usr/bin:/bin",
        HOME: join(root, "home"),
        CLAUDE_CONFIG_DIR: join(root, "home"),
        ANTHROPIC_API_KEY: "local-probe-not-a-credential",
        ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`,
        CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
      },
    },
  });
  const consume = (async () => {
    try { for await (const message of session) void message; }
    catch (error) { if (!controller.signal.aborted) throw error; }
  })();
  const timeout = setTimeout(() => controller.abort(), 30000);
  try {
    await Promise.race([ready, consume]);
    assert.ok(captured, "The isolated SDK must reach the local capture endpoint");
    return JSON.stringify(captured.messages).includes(marker);
  } finally {
    clearTimeout(timeout);
    controller.abort();
    session.close();
    await consume;
    server.closeAllConnections();
    await new Promise((resolveClose) => server.close(resolveClose));
  }
}

try {
  const leading = await capture("/manual-probe inspect the fixture");
  const embedded = await capture("Please use /manual-probe to inspect the fixture");
  console.log(JSON.stringify({ leadingSkillContentLoaded: leading, embeddedSkillContentLoaded: embedded }));
  assert.equal(leading, true, "The control must expand the user-only skill at the start");
  assert.equal(embedded, false, "The embedded slash token does not expand the user-only skill");
} finally {
  await rm(root, { recursive: true, force: true });
}

This is a nonvisual context-delivery defect. No screenshot is used as evidence, and no actual model response is claimed.

5. Root cause

The shared selector validates the resource as an explicitly selected skill and checks that its offsets match the visible token: selectedSkillMentions. Selection is therefore available to the provider; it is not necessary to guess from arbitrary slash text.

Claude's normalizer changes only the trigger character and keeps its original offset:

for (const mention of selectedSkillMentions(entry)) {
  if (mention.resource.trigger === "$") replacements.add(mention.start);
}
for (const start of replacements) {
  normalized = `${normalized.slice(0, start)}/${normalized.slice(start + 1)}`;
}

The prompt builder then joins text and attachment markers with newlines. Finally, runTurnInput obtains this string and pushes it to the SDK. Thus explicit selection is reduced to a token that the tested native parser does not expand when embedded.

The real-SDK control makes the causal distinction: identical file, frontmatter, model name, and input transport; only command position changes. The skill body appears in the outgoing request only in the leading case. No body injection occurs in BB's input builder to compensate for the embedded position. This explains the missing context without needing to speculate about model compliance.

6. Proposed fix and safety gate

For exactly one validated selected skill, remove that token from its input fragment and put /skill-name before the combined remaining text and attachment markers. Preserve ordinary dollar/slash text and retain existing behavior for multiple selections. This follows the already-existing single-selection handling in the Pi provider; it requires no new wire field or API.

A local candidate in the Claude bridge passes all four focused cases after those same cases produced three failures on unchanged production code. Provider lint and typecheck pass; git diff --check passes. The candidate changes two files, 105 additions plus 50 deletions = 155 changed text lines, with no binary or dependency changes.

No pull request is published. The mandatory green-existing-suite condition is not met: the full provider suite has six additional failures in this environment both before and after the candidate. On unchanged production code plus the new tests it reports 404 passed / 9 failed; after the candidate it reports 407 passed / 6 failed. The remaining failures involve executable discovery and root-dependent permission expectations, not the selected-skill regression. The stopped candidate remains local and is not pushed. No linked open pull request for #6562 was found during the investigation.

Scope limits: multiple simultaneous skill selections, malformed/missing mention metadata, skill argument substitutions, and other provider versions are not verified by the real-SDK probe. A leading slash command is the verified workaround. A follow-up should rerun the existing suite in its supported environment before publishing a fix.

7. Related issues

#2318 is open and describes the same embedded-command loading mechanism alongside a separate spacing concern. Treat these reports as potentially overlapping; this investigation neither closes an issue as duplicate nor claims to reproduce that separate spacing defect.

8. Verification

The same agent repeated both experiments in a second clean detached checkout at 3bacfac9ed69d42392076e5b3da2815bec822cd8, created with git worktree add --detach CLEAN_DIR <base>. It received a fresh frozen install and only the test-only regression patch; production code remained unchanged. This is a repeat check, not an independent review.

9. Appendix

The exact repeatable evidence is embedded above. Repro scripts and the test-only patch remain local; repository publication policy permits self-contained HTML, not separate executable artifacts or raw logs.

Focused baseline, checkout 1:  3 failed | 1 passed | 101 skipped
Focused baseline, checkout 2:  3 failed | 1 passed | 101 skipped
Focused local candidate:      4 passed | 101 skipped
Full baseline with new tests: 9 failed | 404 passed, 28 files
Full local candidate:         6 failed | 407 passed, 28 files
Provider lint:                0 warnings, 0 errors
Provider typecheck:           passed
git diff --check:             passed
Candidate diff --numstat:     test 75 additions / 48 deletions
                             production 30 additions / 2 deletions

Additional baseline suite failures, also present after the candidate:
- native installation discovery outside PATH
- fallback executable selection outside PATH
- full sandbox preparation for a Plan preset, two parameter cases
- permission refresh before turn/start
- permission refresh before turn/steer

Build preparation: pnpm install --frozen-lockfile --prefer-offline passed in both checkouts. An initial repository-wide pnpm exec turbo run build stopped in the GitHub plugin because SDK distribution files had not yet been built. pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk then passed, and the provider's Turbo tests ran successfully through dependency preparation. No unrelated build or test code was changed.

Other verification commands: pnpm exec oxfmt on the two candidate files; pnpm exec turbo run lint typecheck --filter=bb-plugin-provider-claude-code; git diff --check; git diff --numstat origin/main. Root-cause permalinks were checked against the recorded trusted base. No live app, browser, or paid model session was needed.