Skip to content

Commit e475093

Browse files
author
Techno911
committed
fix(skills): dedup skill listing by SKILL.md content, not just filePath
The same skill often gets registered under several roots at once (a shared-user copy in .bb/shared-provider-skills mirrored into a provider's own native root such as .claude/skills, or into .agents/skills for another provider). listProjectSkills concatenated four independent scan groups (provider-native, shared, bb-owned, plugin) with no dedup across them, so the identical skill showed up once per registration. Dedup by content digest (SKILL.md sha256), not by name: two unrelated skills can legitimately share a name and must not be merged. The digest for provider/shared scans is free - command-discovery.ts already reads the full SKILL.md to parse frontmatter, so it now hashes that same read once and carries it on DiscoveredSkill.contentSha256 (optional/nullable, so older builds and hand-built test fixtures keep validating). bb-owned and plugin skills are hashed locally since they already live on the server's own disk. Resolution by opaque skillId (read/write/delete a skill file) still searches the full undeduped registration list, so no previously issued id stops resolving - only the display list collapses duplicates, never the disk or the addressable set of ids. Nothing on disk changes; .claude/skills and .agents/skills stay as they are.
1 parent 2679385 commit e475093

6 files changed

Lines changed: 259 additions & 14 deletions

File tree

‎apps/host-daemon/src/command-discovery.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ interface ParsedFrontmatter {
8181
name: string | null;
8282
description: string | null;
8383
argumentHint: string | null;
84+
contentSha256: string | null;
8485
}
8586

8687
interface SkillFileMatch {
@@ -141,24 +142,29 @@ async function parseFrontmatter(filePath: string): Promise<ParsedFrontmatter> {
141142
try {
142143
content = await fs.readFile(filePath, "utf8");
143144
} catch {
144-
return { name: null, description: null, argumentHint: null };
145+
return { name: null, description: null, argumentHint: null, contentSha256: null };
145146
}
147+
// Computed once here, from the same read used for frontmatter, so a
148+
// content-based dedup upstream (bb-server's skill listing) never needs a
149+
// second round-trip just to hash a SKILL.md it already scanned.
150+
const contentSha256 = createHash("sha256").update(content, "utf8").digest("hex");
146151

147152
if (!hasSupportedFrontmatterDelimiter(content)) {
148-
return { name: null, description: null, argumentHint: null };
153+
return { name: null, description: null, argumentHint: null, contentSha256 };
149154
}
150155

151156
let data: Record<string, unknown>;
152157
try {
153158
data = matter(content).data;
154159
} catch {
155-
return { name: null, description: null, argumentHint: null };
160+
return { name: null, description: null, argumentHint: null, contentSha256 };
156161
}
157162

158163
return {
159164
name: readFrontmatterString(data, "name"),
160165
description: readFrontmatterString(data, "description"),
161166
argumentHint: readFrontmatterString(data, "argument-hint"),
167+
contentSha256,
162168
};
163169
}
164170

@@ -517,6 +523,7 @@ function buildSkillRecord(
517523
filePath: match.filePath,
518524
rootKind: root.rootKind,
519525
linked: match.linked,
526+
contentSha256: match.frontmatter.contentSha256,
520527
};
521528
}
522529

‎apps/host-daemon/src/command-handlers/list-skills.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ describe("resolveSkillScanRoots + discoverSkills", () => {
146146
filePath: files["proj-bb"],
147147
rootKind: "bb-project",
148148
linked: false,
149+
contentSha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
149150
});
150151
expect(byName(skills, "data-bb")).toBeUndefined();
151152
expect(byName(skills, "proj-agent")?.rootKind).toBe("provider-project");

‎apps/server/src/services/skills/shared-skills.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type { SharedInjectedSkillSource } from "./injected-skills.js";
1414
interface ResolvedSharedSkills {
1515
runtimeSources: SharedInjectedSkillSource[];
1616
summaries: SkillSummary[];
17+
digestByFilePath: ReadonlyMap<string, string>;
1718
}
1819

1920
export function hostPathDirname(filePath: string): string {
@@ -25,7 +26,11 @@ export function hostPathDirname(filePath: string): string {
2526
function toSharedSkill(
2627
deps: Pick<LoggedWorkSessionDeps, "logger">,
2728
skill: DiscoveredSkill,
28-
): { runtimeSource: SharedInjectedSkillSource; summary: SkillSummary } | null {
29+
): {
30+
runtimeSource: SharedInjectedSkillSource;
31+
summary: SkillSummary;
32+
contentSha256: string | null;
33+
} | null {
2934
if (
3035
(skill.rootKind !== "shared-user" && skill.rootKind !== "shared-project") ||
3136
skill.description === null
@@ -64,6 +69,7 @@ function toSharedSkill(
6469
manageable: false,
6570
registrySkillId: null,
6671
},
72+
contentSha256: skill.contentSha256 ?? null,
6773
};
6874
}
6975

@@ -73,7 +79,7 @@ export async function resolveSharedSkills(
7379
): Promise<ResolvedSharedSkills> {
7480
const roots = deps.config.sharedSkillRoots;
7581
if (roots.user.length === 0 && roots.project.length === 0) {
76-
return { runtimeSources: [], summaries: [] };
82+
return { runtimeSources: [], summaries: [], digestByFilePath: new Map() };
7783
}
7884
const result = await callHostRetryableOnlineRpc(deps, {
7985
hostId: args.hostId,
@@ -107,8 +113,15 @@ export async function resolveSharedSkills(
107113
names.add(entry.runtimeSource.name);
108114
resolved.push(entry);
109115
}
116+
const digestByFilePath = new Map<string, string>();
117+
for (const entry of resolved) {
118+
if (entry.contentSha256 !== null) {
119+
digestByFilePath.set(entry.summary.filePath, entry.contentSha256);
120+
}
121+
}
110122
return {
111123
runtimeSources: resolved.map((entry) => entry.runtimeSource),
112124
summaries: resolved.map((entry) => entry.summary),
125+
digestByFilePath,
113126
};
114127
}

‎apps/server/src/services/skills/skill-listing.ts‎

Lines changed: 135 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -209,10 +209,107 @@ function listBbPluginSkills(deps: AppDeps): SkillSummary[] {
209209
.sort(compareSkillSummaries);
210210
}
211211

212-
export async function listProjectSkills(
212+
/**
213+
* The same physical skill is often registered under more than one root: a
214+
* shared-user copy in `.bb/shared-provider-skills` is frequently mirrored
215+
* into a provider's own native root (e.g. `~/.claude/skills`) so the
216+
* provider's own tooling can see it outside bb. Each registration produces
217+
* its own SkillSummary with a distinct filePath, so a plain filePath dedup
218+
* (as done inside assembleSkillList for a single provider scan) does not
219+
* catch it. Dedup here by the SKILL.md content digest instead of by name:
220+
* two unrelated skills can legitimately share a name, and merging those
221+
* would silently hide one of them.
222+
*/
223+
export function dedupSkillSummariesByDigest(
224+
skills: readonly SkillSummary[],
225+
digestByFilePath: ReadonlyMap<string, string>,
226+
): SkillSummary[] {
227+
const bestByDigest = new Map<string, SkillSummary>();
228+
const passthrough: SkillSummary[] = [];
229+
for (const skill of skills) {
230+
const digest = digestByFilePath.get(skill.filePath);
231+
if (digest === undefined) {
232+
passthrough.push(skill);
233+
continue;
234+
}
235+
const existing = bestByDigest.get(digest);
236+
if (
237+
existing === undefined ||
238+
SKILL_SCOPE_ORDER.indexOf(skill.scope) <
239+
SKILL_SCOPE_ORDER.indexOf(existing.scope)
240+
) {
241+
bestByDigest.set(digest, skill);
242+
}
243+
}
244+
return [...bestByDigest.values(), ...passthrough];
245+
}
246+
247+
/**
248+
* bb-owned and plugin skills live on the bb server's own local disk (their
249+
* filePath is resolvable with plain fs), so their digest is computed
250+
* directly instead of round-tripping through a host RPC.
251+
*/
252+
async function computeLocalSkillContentDigest(
253+
filePath: string,
254+
): Promise<string | null> {
255+
try {
256+
const contents = await fs.readFile(filePath);
257+
return createHash("sha256").update(contents).digest("hex");
258+
} catch {
259+
// A skill we can't read the content of is left un-deduped: showing an
260+
// extra row is safer than silently merging on a guess.
261+
return null;
262+
}
263+
}
264+
265+
async function buildLocalSkillContentDigestIndex(
266+
skills: readonly SkillSummary[],
267+
): Promise<Map<string, string>> {
268+
const uniqueFilePaths = [...new Set(skills.map((skill) => skill.filePath))];
269+
const entries = await Promise.all(
270+
uniqueFilePaths.map(async (filePath) => {
271+
const digest = await computeLocalSkillContentDigest(filePath);
272+
return digest === null ? null : ([filePath, digest] as const);
273+
}),
274+
);
275+
return new Map(
276+
entries.filter((entry): entry is readonly [string, string] => entry !== null),
277+
);
278+
}
279+
280+
/**
281+
* Provider-native scans already read every SKILL.md once (to parse its
282+
* frontmatter) and carry the resulting digest on the DiscoveredSkill, so the
283+
* digest for those scopes is free — no second read over RPC.
284+
*/
285+
function collectProviderSkillDigests(
286+
perProvider: readonly ProviderSkillDiscovery[],
287+
): Map<string, string> {
288+
const digestByFilePath = new Map<string, string>();
289+
for (const { skills } of perProvider) {
290+
for (const skill of skills) {
291+
if (skill.contentSha256 !== null && skill.contentSha256 !== undefined) {
292+
digestByFilePath.set(skill.filePath, skill.contentSha256);
293+
}
294+
}
295+
}
296+
return digestByFilePath;
297+
}
298+
299+
interface ProjectSkillRegistrations {
300+
/** Every registration a skill has, one row per (scope, root) pair — not
301+
* deduped by content. Reads/writes/deletes resolve a skill by its opaque
302+
* id, including ids for registrations that the deduped display list in
303+
* listProjectSkills later collapses away, so this raw list is what
304+
* resolveProjectSkill searches. */
305+
skills: SkillSummary[];
306+
digestByFilePath: Map<string, string>;
307+
}
308+
309+
async function listAllProjectSkillRegistrations(
213310
deps: AppDeps,
214311
args: { workspace: CommandWorkspace },
215-
): Promise<SkillSummary[]> {
312+
): Promise<ProjectSkillRegistrations> {
216313
const skillProviders = deps.providerRegistry
217314
.list()
218315
.filter(providerHasNativeRootSurface);
@@ -235,12 +332,39 @@ export async function listProjectSkills(
235332
cwd: args.workspace.cwd,
236333
}),
237334
]);
238-
return [
239-
...assembleSkillList(perProvider),
240-
...sharedSkills.summaries,
241-
...listServerOwnedSkills(deps),
242-
...listBbPluginSkills(deps),
243-
].sort(compareSkillSummaries);
335+
const serverOwned = listServerOwnedSkills(deps);
336+
const plugin = listBbPluginSkills(deps);
337+
const localDigestByFilePath = await buildLocalSkillContentDigestIndex([
338+
...serverOwned,
339+
...plugin,
340+
]);
341+
const digestByFilePath = new Map([
342+
...collectProviderSkillDigests(perProvider),
343+
...sharedSkills.digestByFilePath,
344+
...localDigestByFilePath,
345+
]);
346+
return {
347+
skills: [
348+
...assembleSkillList(perProvider),
349+
...sharedSkills.summaries,
350+
...serverOwned,
351+
...plugin,
352+
],
353+
digestByFilePath,
354+
};
355+
}
356+
357+
export async function listProjectSkills(
358+
deps: AppDeps,
359+
args: { workspace: CommandWorkspace },
360+
): Promise<SkillSummary[]> {
361+
const { skills, digestByFilePath } = await listAllProjectSkillRegistrations(
362+
deps,
363+
args,
364+
);
365+
return dedupSkillSummariesByDigest(skills, digestByFilePath).sort(
366+
compareSkillSummaries,
367+
);
244368
}
245369

246370
function isServerOwnedSkill(deps: AppDeps, skill: SkillSummary): boolean {
@@ -365,7 +489,9 @@ async function resolveProjectSkill(
365489
workspace: CommandWorkspace;
366490
},
367491
): Promise<SkillSummary> {
368-
const skills = await listProjectSkills(deps, { workspace: args.workspace });
492+
const { skills } = await listAllProjectSkillRegistrations(deps, {
493+
workspace: args.workspace,
494+
});
369495
const match = skills.find((skill) => skill.id === args.skillId);
370496
if (!match) {
371497
throw new ApiError(404, "not_found", "Skill not found");

‎apps/server/test/skills/skill-listing.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import type { DiscoveredSkill, SkillRootKind } from "@bb/host-daemon-contract";
22
import { createHash } from "node:crypto";
33
import type { SkillProvider } from "@bb/server-contract";
44
import { describe, expect, it } from "vitest";
5+
import type { SkillSummary } from "@bb/server-contract";
56
import {
67
assembleSkillList,
8+
dedupSkillSummariesByDigest,
79
mapSkillScope,
810
} from "../../src/services/skills/skill-listing.js";
911

@@ -235,3 +237,94 @@ describe("assembleSkillList", () => {
235237
});
236238
});
237239
});
240+
241+
describe("dedupSkillSummariesByDigest", () => {
242+
function summary(
243+
name: string,
244+
scope: SkillSummary["scope"],
245+
filePath: string,
246+
): SkillSummary {
247+
return {
248+
id: `skill_${createHash("sha256").update(filePath).digest("hex")}`,
249+
name,
250+
description: null,
251+
provider: null,
252+
scope,
253+
pluginId: null,
254+
filePath,
255+
manageable: false,
256+
registrySkillId: null,
257+
};
258+
}
259+
260+
it("collapses the same SKILL.md content registered under two scopes, keeping the wider one", () => {
261+
const bbShared = summary(
262+
"chip-client-fixture",
263+
"shared-user",
264+
"/Users/techno/.bb/shared-provider-skills/chip-client-fixture/SKILL.md",
265+
);
266+
const providerCopy = summary(
267+
"chip-client-fixture",
268+
"provider-user",
269+
"/Users/techno/.claude/skills/chip-client-fixture/SKILL.md",
270+
);
271+
const digest = "same-content-digest";
272+
const result = dedupSkillSummariesByDigest(
273+
[providerCopy, bbShared],
274+
new Map([
275+
[bbShared.filePath, digest],
276+
[providerCopy.filePath, digest],
277+
]),
278+
);
279+
expect(result).toHaveLength(1);
280+
expect(result[0]).toMatchObject({
281+
name: "chip-client-fixture",
282+
scope: "shared-user",
283+
filePath: bbShared.filePath,
284+
});
285+
});
286+
287+
it("does not merge two different skills that only happen to share a name", () => {
288+
const first = summary(
289+
"editorial-composition",
290+
"shared-user",
291+
"/a/editorial-composition/SKILL.md",
292+
);
293+
const second = summary(
294+
"editorial-composition",
295+
"provider-user",
296+
"/b/editorial-composition/SKILL.md",
297+
);
298+
const result = dedupSkillSummariesByDigest(
299+
[first, second],
300+
new Map([
301+
[first.filePath, "digest-a"],
302+
[second.filePath, "digest-b"],
303+
]),
304+
);
305+
expect(result).toHaveLength(2);
306+
});
307+
308+
it("passes through skills whose digest could not be computed", () => {
309+
const skill = summary("undigested", "provider-user", "/x/SKILL.md");
310+
expect(dedupSkillSummariesByDigest([skill], new Map())).toEqual([skill]);
311+
});
312+
313+
it("lock: no two entries in the result ever share a content digest", () => {
314+
const skills = [
315+
summary("x", "shared-project", "/p/SKILL.md"),
316+
summary("x", "provider-project", "/q/SKILL.md"),
317+
summary("x", "provider-user", "/r/SKILL.md"),
318+
];
319+
const digestByFilePath = new Map([
320+
["/p/SKILL.md", "dup"],
321+
["/q/SKILL.md", "dup"],
322+
["/r/SKILL.md", "dup"],
323+
]);
324+
const result = dedupSkillSummariesByDigest(skills, digestByFilePath);
325+
const digests = result.map((skill) => digestByFilePath.get(skill.filePath));
326+
expect(new Set(digests).size).toBe(digests.length);
327+
expect(result).toHaveLength(1);
328+
expect(result[0]).toMatchObject({ scope: "shared-project" });
329+
});
330+
});

‎packages/host-daemon-contract/src/commands.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,11 @@ const discoveredSkillSchema = z.object({
706706
filePath: z.string(),
707707
rootKind: skillRootKindSchema,
708708
linked: z.boolean(),
709+
// sha256 of the raw SKILL.md bytes, computed once while reading the file
710+
// for frontmatter. Optional/nullable so older host-daemon builds and
711+
// hand-built test fixtures that predate this field keep validating; a
712+
// missing digest just means the caller can't dedup that entry by content.
713+
contentSha256: z.string().nullable().optional(),
709714
});
710715
export type DiscoveredSkill = z.infer<typeof discoveredSkillSchema>;
711716

0 commit comments

Comments
 (0)