Skip to content

Commit 4d036f5

Browse files
Techno911claude
andcommitted
feat(provider-claude-code): не дублировать скиллы, которые Claude Code видит сам
Claude Code сканирует <home>/.claude/skills и <cwd>/.claude/skills сам, а bb дополнительно отдаёт ему свой резолвнутый каталог плагином bb-global-skills. Скиллы, лежащие в обоих местах, приходили в каталог сессии дважды — голым именем и с префиксом bb-global-skills:. На проекте пользователя это около 45 дублей и порядка 13 500 токенов на старт треда, из-за чего каталог упирался в skillListingBudgetFraction и Claude Code сам вырезал описания у части скиллов. Перед сборкой плагина для сессии каталог фильтруется по именам, которые Claude Code уже видит нативно в этой сессии (сравнение по имени папки и по полю name во front-matter). Отфильтрованный набор стейджится симлинками в каталог с именем-хешем и переиспользуется всеми сессиями с тем же набором. Если пересечений нет, каталог отдаётся как прежде, без стейджинга. Провайдеры без собственного файлового сканера (Codex и прочие ACP) получают полный каталог: их путь не тронут. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 8b34393 commit 4d036f5

3 files changed

Lines changed: 324 additions & 11 deletions

File tree

‎plugins/provider-claude-code/src/bridge/__tests__/skill-plugins.test.ts‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
mkdirSync,
44
mkdtempSync,
55
readFileSync,
6+
readdirSync,
67
readlinkSync,
78
rmSync,
89
writeFileSync,
@@ -12,8 +13,10 @@ import { join } from "node:path";
1213
import { afterEach, beforeEach, describe, expect, it } from "vitest";
1314
import {
1415
CLAUDE_SKILL_PLUGIN_NAME,
16+
collectNativeClaudeSkillNames,
1517
createClaudeSkillPluginsRoot,
1618
ensureClaudeSkillPlugin,
19+
resolveDedupedSkillRootPath,
1720
} from "../skill-plugins.js";
1821

1922
describe("claude skill plugins", () => {
@@ -125,3 +128,142 @@ describe("claude skill plugins", () => {
125128
expect(nameOf(b)).toMatch(/^bb-global-skills-[0-9a-f]{8}$/u);
126129
});
127130
});
131+
132+
describe("claude skill catalog deduplication", () => {
133+
let baseDir: string;
134+
135+
beforeEach(() => {
136+
baseDir = mkdtempSync(join(tmpdir(), "bb-claude-skill-dedup-test-"));
137+
});
138+
139+
afterEach(() => {
140+
rmSync(baseDir, { recursive: true, force: true });
141+
});
142+
143+
function writeSkill(root: string, directory: string, name = directory): void {
144+
mkdirSync(join(root, directory), { recursive: true });
145+
writeFileSync(
146+
join(root, directory, "SKILL.md"),
147+
`---\nname: ${name}\ndescription: ${name}\n---\n`,
148+
);
149+
}
150+
151+
function stageRootDir(): string {
152+
const stageRoot = join(baseDir, "deduped");
153+
mkdirSync(stageRoot, { recursive: true });
154+
return stageRoot;
155+
}
156+
157+
it("drops catalog skills Claude Code already sees in the home and project directories", () => {
158+
const catalog = join(baseDir, "catalog");
159+
writeSkill(catalog, "chip-rag");
160+
writeSkill(catalog, "chip-brand");
161+
writeSkill(catalog, "chip-ui-law");
162+
163+
const homeDir = join(baseDir, "home");
164+
writeSkill(join(homeDir, ".claude", "skills"), "chip-rag");
165+
const cwd = join(baseDir, "project");
166+
writeSkill(join(cwd, ".claude", "skills"), "chip-brand");
167+
168+
const nativeSkillNames = collectNativeClaudeSkillNames({ homeDir, cwd });
169+
const resolved = resolveDedupedSkillRootPath({
170+
stageRoot: stageRootDir(),
171+
rootPath: catalog,
172+
nativeSkillNames,
173+
});
174+
175+
expect(resolved).not.toBe(catalog);
176+
expect(readdirSync(resolved).sort()).toEqual(["chip-ui-law"]);
177+
expect(
178+
readFileSync(join(resolved, "chip-ui-law", "SKILL.md"), "utf8"),
179+
).toContain("name: chip-ui-law");
180+
});
181+
182+
it("matches a native skill by its front-matter name when the directory differs", () => {
183+
const catalog = join(baseDir, "catalog");
184+
writeSkill(catalog, "chip-rag");
185+
writeSkill(catalog, "chip-ui-law");
186+
187+
const homeDir = join(baseDir, "home");
188+
writeSkill(
189+
join(homeDir, ".claude", "skills"),
190+
"renamed-folder",
191+
"chip-rag",
192+
);
193+
const cwd = join(baseDir, "project");
194+
195+
const resolved = resolveDedupedSkillRootPath({
196+
stageRoot: stageRootDir(),
197+
rootPath: catalog,
198+
nativeSkillNames: collectNativeClaudeSkillNames({ homeDir, cwd }),
199+
});
200+
201+
expect(readdirSync(resolved).sort()).toEqual(["chip-ui-law"]);
202+
});
203+
204+
it("keeps the whole catalog for a session with no natively visible skills, as providers without a file scanner get it", () => {
205+
const catalog = join(baseDir, "catalog");
206+
writeSkill(catalog, "chip-ui-law");
207+
const homeDir = join(baseDir, "home");
208+
const cwd = join(baseDir, "project");
209+
const stageRoot = stageRootDir();
210+
211+
const resolved = resolveDedupedSkillRootPath({
212+
stageRoot,
213+
rootPath: catalog,
214+
nativeSkillNames: collectNativeClaudeSkillNames({ homeDir, cwd }),
215+
});
216+
217+
expect(resolved).toBe(catalog);
218+
expect(readdirSync(stageRoot)).toEqual([]);
219+
});
220+
221+
it("reuses one staging directory for the same filtered set", () => {
222+
const catalog = join(baseDir, "catalog");
223+
writeSkill(catalog, "chip-rag");
224+
writeSkill(catalog, "chip-ui-law");
225+
const homeDir = join(baseDir, "home");
226+
writeSkill(join(homeDir, ".claude", "skills"), "chip-rag");
227+
const cwd = join(baseDir, "project");
228+
const stageRoot = stageRootDir();
229+
const nativeSkillNames = collectNativeClaudeSkillNames({ homeDir, cwd });
230+
231+
const first = resolveDedupedSkillRootPath({
232+
stageRoot,
233+
rootPath: catalog,
234+
nativeSkillNames,
235+
});
236+
const second = resolveDedupedSkillRootPath({
237+
stageRoot,
238+
rootPath: catalog,
239+
nativeSkillNames,
240+
});
241+
242+
expect(second).toBe(first);
243+
expect(readdirSync(stageRoot)).toHaveLength(1);
244+
});
245+
246+
it("ignores directories without SKILL.md on both sides", () => {
247+
const catalog = join(baseDir, "catalog");
248+
writeSkill(catalog, "chip-ui-law");
249+
mkdirSync(join(catalog, "not-a-skill"), { recursive: true });
250+
const homeDir = join(baseDir, "home");
251+
mkdirSync(join(homeDir, ".claude", "skills", "chip-ui-law"), {
252+
recursive: true,
253+
});
254+
255+
const nativeSkillNames = collectNativeClaudeSkillNames({
256+
homeDir,
257+
cwd: join(baseDir, "project"),
258+
});
259+
260+
expect(nativeSkillNames.size).toBe(0);
261+
expect(
262+
resolveDedupedSkillRootPath({
263+
stageRoot: stageRootDir(),
264+
rootPath: catalog,
265+
nativeSkillNames,
266+
}),
267+
).toBe(catalog);
268+
});
269+
});

‎plugins/provider-claude-code/src/bridge/bridge.ts‎

Lines changed: 52 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ import {
2828
experimental_defineProviderBridge,
2929
} from "@get-bb/plugin-sdk/provider-bridge";
3030
import { randomUUID } from "node:crypto";
31+
import { mkdirSync } from "node:fs";
32+
import { homedir } from "node:os";
3133
import { join as joinPath, resolve as resolvePath } from "node:path";
3234
import { isDeepStrictEqual } from "node:util";
3335
import {
@@ -87,8 +89,10 @@ import {
8789
type PermissionEscalationWorkContext,
8890
} from "./session-options.js";
8991
import {
92+
collectNativeClaudeSkillNames,
9093
createClaudeSkillPluginsRoot,
9194
ensureClaudeSkillPlugin,
95+
resolveDedupedSkillRootPath,
9296
} from "./skill-plugins.js";
9397
import {
9498
buildBridgeMcpServer,
@@ -352,22 +356,35 @@ function nextInteractiveRequestId(): string {
352356
interactiveRequestIdCounter += 1;
353357
return `interaction-${interactiveRequestIdCounter}`;
354358
}
355-
let configuredSkillRoots: ClaudeCodeSkillRoot[] | null = null;
359+
let configuredSkillRootSources: readonly { id: string; path: string }[] | null =
360+
null;
361+
let skillPluginsBySessionCwd = new Map<string, ClaudeCodeSkillRoot[]>();
356362
let skillPluginsRoot: string | null = null;
363+
let skillDedupStageRoot: string | null = null;
357364
let bridgeTempDir: string | null = null;
358365

359366
function assembleSkillPlugins(
360367
roots: readonly { id: string; path: string }[],
368+
cwd: string,
361369
): ClaudeCodeSkillRoot[] {
362370
const takenNames = new Map<string, string>();
363371
const assembled: ClaudeCodeSkillRoot[] = [];
372+
const nativeSkillNames = collectNativeClaudeSkillNames({
373+
homeDir: homedir(),
374+
cwd,
375+
});
364376
for (const root of roots) {
365377
try {
378+
const path = resolveDedupedSkillRootPath({
379+
stageRoot: requireSkillDedupStageRoot(),
380+
rootPath: root.path,
381+
nativeSkillNames,
382+
});
366383
assembled.push({
367384
id: root.id,
368385
localPluginPath: ensureClaudeSkillPlugin({
369386
pluginsRoot: requireSkillPluginsRoot(),
370-
root: { id: root.id, path: root.path },
387+
root: { id: root.id, path },
371388
takenNames,
372389
}),
373390
});
@@ -380,6 +397,29 @@ function assembleSkillPlugins(
380397
return assembled;
381398
}
382399

400+
function skillPluginsForSession(
401+
cwd: string,
402+
): ClaudeCodeSkillRoot[] | undefined {
403+
if (configuredSkillRootSources === null) {
404+
return undefined;
405+
}
406+
const cached = skillPluginsBySessionCwd.get(cwd);
407+
if (cached !== undefined) {
408+
return cached;
409+
}
410+
const assembled = assembleSkillPlugins(configuredSkillRootSources, cwd);
411+
skillPluginsBySessionCwd.set(cwd, assembled);
412+
return assembled;
413+
}
414+
415+
function requireSkillDedupStageRoot(): string {
416+
if (skillDedupStageRoot === null) {
417+
skillDedupStageRoot = joinPath(requireSkillPluginsRoot(), ".deduped");
418+
mkdirSync(skillDedupStageRoot, { recursive: true });
419+
}
420+
return skillDedupStageRoot;
421+
}
422+
383423
function requireSkillPluginsRoot(): string {
384424
if (skillPluginsRoot === null) {
385425
skillPluginsRoot = createClaudeSkillPluginsRoot(
@@ -1276,13 +1316,13 @@ async function getWritableThreadSession(
12761316
return undefined;
12771317
}
12781318
const replacement: ClaudeSessionRestart | null = threadSession.streamEnded
1279-
? {
1280-
reason: "Thread session replaced after Claude SDK stream ended",
1281-
showRuntimeNote: false,
1282-
}
1283-
: intent === "new-turn"
1284-
? threadSession.restartBeforeNextTurn
1285-
: null;
1319+
? {
1320+
reason: "Thread session replaced after Claude SDK stream ended",
1321+
showRuntimeNote: false,
1322+
}
1323+
: intent === "new-turn"
1324+
? threadSession.restartBeforeNextTurn
1325+
: null;
12861326
if (replacement === null) {
12871327
return threadSession;
12881328
}
@@ -2052,7 +2092,8 @@ async function handleRequest(request: ClaudeCodeJsonRpcRequest): Promise<void> {
20522092
sendResult(request.id, await closeThreadForStop(request.params.threadId));
20532093
break;
20542094
case "skills/configure":
2055-
configuredSkillRoots = assembleSkillPlugins(request.params.roots);
2095+
configuredSkillRootSources = request.params.roots;
2096+
skillPluginsBySessionCwd = new Map<string, ClaudeCodeSkillRoot[]>();
20562097
sendResult(request.id, { ok: true });
20572098
break;
20582099
}
@@ -2221,7 +2262,7 @@ function toClaudeSessionParams(
22212262
instructionMode: params.instructionMode,
22222263
dynamicTools: params.dynamicTools,
22232264
disallowedTools: params.disallowedTools,
2224-
skillRoots: configuredSkillRoots ?? undefined,
2265+
skillRoots: skillPluginsForSession(params.cwd),
22252266
});
22262267
}
22272268

0 commit comments

Comments
 (0)