Skip to content
307 linesCodeBlameRaw
1import assert from "node:assert/strict";
2import { readFileSync, readdirSync } from "node:fs";
3import { DatabaseSync } from "node:sqlite";
4import { test } from "node:test";
5
6import { parseMarketplaceManifest } from "../../../packages/contracts/src/claude-plugin.ts";
7import { type Fetch, fetchMarketplace, fetchPlugin } from "./customize-fetch.ts";
8import * as marketplaces from "./marketplaces.ts";
9import * as plugins from "./plugins.ts";
10import { skillByName } from "./skill-library.ts";
11import { attachedRows, shelfFrom } from "./skills.ts";
12
13/** D1, as far as Customize uses it, over node's SQLite with the service's migrations. */
14function fakeD1(): D1Database {
15 const db = new DatabaseSync(":memory:");
16 const dir = new URL("../migrations/", import.meta.url);
17 for (const file of readdirSync(dir).sort()) db.exec(readFileSync(new URL(file, dir), "utf8"));
18 const statement = (sql: string, params: unknown[] = []) => ({
19 bind: (...values: unknown[]) => statement(sql, values),
20 first: async () => (db.prepare(sql).get(...(params as never[])) as unknown) ?? null,
21 run: async () => {
22 const r = db.prepare(sql).run(...(params as never[]));
23 return { meta: { changes: Number(r.changes) } };
24 },
25 all: async () => ({ results: db.prepare(sql).all(...(params as never[])) }),
26 });
27 const batch = async (statements: { run: () => Promise<unknown> }[]) => Promise.all(statements.map((s) => s.run()));
28 return { prepare: (sql: string) => statement(sql), batch } as unknown as D1Database;
29}
30
31const SHA = "0123456789abcdef0123456789abcdef01234567";
32
33/** GitHub, in miniature: a marketplace repository with two plugins, and raw files. */
34const REPO: Record<string, string> = {
35 ".claude-plugin/marketplace.json": JSON.stringify({
36 name: "acme-tools",
37 owner: { name: "Acme" },
38 metadata: { description: "Acme's tools" },
39 plugins: [
40 { name: "release", source: "./plugins/release", description: "Cut releases", category: "development", version: "1.2.0" },
41 { name: "docs-skills", source: "./", description: "Writing skills", strict: false, skills: ["./skills/brief"] },
42 { name: "from-npm", source: { source: "npm", package: "@acme/x" }, description: "Not here" },
43 ],
44 }),
45 "plugins/release/.claude-plugin/plugin.json": JSON.stringify({ name: "release", version: "1.2.0", description: "Cuts releases", author: { name: "Acme" } }),
46 "plugins/release/README.md": "# Release\n\nCuts releases.",
47 "plugins/release/skills/release-notes/SKILL.md": "---\nname: release-notes\ndescription: Use when asked for release notes.\nallowed-tools: Read, Bash\n---\n\nRead the merged pull requests, group them, write the notes.\n",
48 "plugins/release/skills/release-notes/references/template.md": "# Notes\n",
49 "plugins/release/skills/code/SKILL.md": "---\nname: code\ndescription: A plugin skill with a foundational name.\n---\n\nIt is called release:code here.\n",
50 "plugins/release/commands/cut.md": "---\ndescription: Cut a release now.\n---\n\nRun the release script.\n",
51 "plugins/release/agents/releaser.md": "---\nname: releaser\ndescription: Cuts a release end to end.\ntools: Read, Bash\nmodel: sonnet\n---\n\nYou cut releases carefully.\n",
52 "plugins/release/.mcp.json": JSON.stringify({ mcpServers: { tracker: { type: "http", url: "https://mcp.example.com/mcp" }, local: { command: "npx", args: ["server"] }, keyed: { type: "http", url: "https://keyed.example.com/mcp", headers: { "X-Key": "${ACME_KEY}" } } } }),
53 "plugins/release/hooks/hooks.json": JSON.stringify({ hooks: {} }),
54 "skills/brief/SKILL.md": "---\nname: brief\ndescription: Use when asked for a brief.\n---\n\nWrite a one-page brief.\n",
55};
56
57function githubFetch(repo = "acme/tools", files = REPO): Fetch {
58 return async (url) => {
59 const u = new URL(url);
60 if (u.hostname === "raw.githubusercontent.com") {
61 const [, owner, name, ref, ...rest] = u.pathname.split("/");
62 const path = rest.map(decodeURIComponent).join("/");
63 if (`${owner}/${name}` !== repo || (ref !== SHA && ref !== "HEAD" && ref !== "main")) return new Response("no", { status: 404 });
64 const file = files[path];
65 return file === undefined ? new Response("no", { status: 404 }) : new Response(file, { status: 200 });
66 }
67 if (u.hostname === "api.github.com") {
68 if (u.pathname === `/repos/${repo}/commits/HEAD` || u.pathname === `/repos/${repo}/commits/main`) return Response.json({ sha: SHA });
69 if (u.pathname === `/repos/${repo}/git/trees/${SHA}`) return Response.json({ tree: Object.entries(files).map(([path, content]) => ({ path, type: "blob", size: content.length })), truncated: false });
70 return new Response("no", { status: 404 });
71 }
72 return new Response("no", { status: 404 });
73 };
74}
75
76const ws = "wsp_acme";
77const at = new Date("2026-10-11T12:00:00.000Z");
78const deps = { fetchFn: githubFetch() };
79
80test("a marketplace is read from GitHub by its address, its plugins listed with where each would be fetched from", async () => {
81 const read = await fetchMarketplace({ source: "github", repo: "acme/tools" }, deps);
82 assert.ok(read.ok);
83 assert.equal(read.sha, SHA);
84 const manifest = parseMarketplaceManifest(read.json);
85 assert.ok(manifest.ok);
86 const db = fakeD1();
87 const added = await marketplaces.addMarketplace(db, ws, null, { source: "github", repo: "acme/tools" }, "chase", deps, "g1t.sh", at);
88 assert.ok(added.ok);
89 assert.deepEqual({ name: added.value.name, owner: added.value.owner, plugins: added.value.plugins, builtin: added.value.builtin, can_remove: added.value.can_remove }, { name: "acme-tools", owner: "Acme", plugins: 3, builtin: false, can_remove: true });
90 const again = await marketplaces.addMarketplace(db, ws, null, { source: "github", repo: "acme/tools" }, "chase", deps, "g1t.sh", at);
91 assert.equal(!again.ok && again.error.code, "conflict");
92 const reserved = await marketplaces.addMarketplace(db, ws, "claude-plugins-official", { source: "github", repo: "acme/tools" }, "chase", deps, "g1t.sh", at);
93 assert.equal(!reserved.ok && reserved.error.code, "invalid");
94 // The built-ins can't be read in this test (no GitHub), so they are listed with a problem and no plugins; the workspace's own lists three.
95 const all = await marketplaces.loadAll(db, ws, deps, "g1t.sh", at);
96 const listings = marketplaces.discoverPlugins(all, new Map(), "g1t.sh");
97 // The workspace's own marketplace first; g1t's announced plugins after it.
98 assert.deepEqual(
99 listings.filter((l) => l.marketplace === "acme-tools").map((l) => [l.ref, l.availability.kind, l.fetch.kind]),
100 [
101 ["release@acme-tools", "available", "github"],
102 ["docs-skills@acme-tools", "available", "github"],
103 ["from-npm@acme-tools", "unavailable", "unsupported"],
104 ],
105 );
106 assert.ok(listings.some((l) => l.ref === "mail@g1t" && l.availability.kind === "soon"));
107 assert.deepEqual(listings[0]!.fetch, { kind: "github", repo: "acme/tools", ref: null, sha: null, path: "plugins/release" });
108 const skills = marketplaces.discoverSkills(listings, new Set());
109 assert.deepEqual(
110 skills.map((s) => [s.ref, s.plugin, s.added]),
111 [["docs-skills:brief", "docs-skills", false]],
112 );
113 const out = marketplaces.marketplacesOut(all, true);
114 assert.deepEqual(
115 out.map((m) => [m.name, m.builtin, m.can_remove]),
116 [
117 ["claude-plugins-official", true, false],
118 ["anthropic-agent-skills", true, false],
119 ["acme-tools", false, true],
120 ["g1t", true, false],
121 ],
122 );
123 const removed = await marketplaces.removeMarketplace(db, ws, "acme-tools");
124 assert.ok(removed.ok);
125 assert.equal(!(await marketplaces.removeMarketplace(db, ws, "claude-plugins-official")).ok, true);
126});
127
128test("a plugin is fetched from GitHub at a commit, read, and installed: skills into the library under its name, agents kept, servers found", async () => {
129 const plan = { kind: "github" as const, repo: "acme/tools", ref: null, sha: null, path: "plugins/release" };
130 const fetched = await fetchPlugin(plan, deps);
131 assert.ok(fetched.ok);
132 assert.equal(fetched.sha, SHA);
133 assert.deepEqual(fetched.files.map((f) => f.path).sort(), [".claude-plugin/plugin.json", ".mcp.json", "README.md", "agents/releaser.md", "commands/cut.md", "hooks/hooks.json", "skills/code/SKILL.md", "skills/release-notes/SKILL.md", "skills/release-notes/references/template.md"]);
134 const read = plugins.readPlugin(fetched.files, fetched.sha, null);
135 assert.equal(read.manifest?.version, "1.2.0");
136 assert.deepEqual(
137 read.components.skills.map((s) => [s.name, s.description]),
138 [
139 ["code", "A plugin skill with a foundational name."],
140 ["release-notes", "Use when asked for release notes."],
141 ],
142 );
143 assert.deepEqual(read.components.commands.map((c) => c.name), ["cut"]);
144 assert.deepEqual(read.agents.map((a) => [a.name, a.model, a.tools]), [["releaser", "sonnet", ["Read", "Bash"]]]);
145 assert.deepEqual(
146 read.components.mcp_servers.map((s) => [s.name, s.type, s.remote]),
147 [
148 ["tracker", "http", true],
149 ["local", "stdio", false],
150 ["keyed", "http", true],
151 ],
152 );
153 assert.equal(read.components.hooks, true);
154 assert.equal(read.readme, "# Release\n\nCuts releases.");
155
156 const db = fakeD1();
157 await marketplaces.addMarketplace(db, ws, null, { source: "github", repo: "acme/tools" }, "chase", deps, "g1t.sh", at);
158 const all = await marketplaces.loadAll(db, ws, deps, "g1t.sh", at);
159 const listings = marketplaces.discoverPlugins(all, new Map(), "g1t.sh");
160 const listing = marketplaces.findListing(listings, "release@acme-tools")!;
161 const entry = marketplaces.entryOf(all, { name: "release", marketplace: "acme-tools" })!;
162 const done = await plugins.install(db, { workspaceId: ws, listing, entry: entry.entry, marketplace: { name: "acme-tools", source: entry.source, pluginRoot: entry.pluginRoot }, host: "g1t.sh", by: "chase", deps, now: at });
163 assert.ok(done.ok);
164 assert.deepEqual(done.value.skills.map((s) => [s.name, s.problem]), [
165 ["code", null],
166 ["release-notes", null],
167 ["cut", null],
168 ]);
169 assert.equal(done.value.install.sha, SHA);
170 assert.deepEqual(done.value.install.fetch, { ...plan, sha: SHA });
171 // The library has them, named by the plugin, read-only, with Claude Code's tools kept aside.
172 const notes = await skillByName(db, ws, "release-notes", "release@acme-tools");
173 assert.ok(notes);
174 assert.equal(notes.plugin, "release@acme-tools");
175 assert.equal(await skillByName(db, ws, "release-notes"), null);
176 const code = await skillByName(db, ws, "code", "release@acme-tools");
177 assert.ok(code, "a plugin skill may carry a foundational name");
178 const version = await db.prepare("SELECT skill_md FROM skill_versions WHERE skill_id = ? AND version = 1").bind(notes.id).first<{ skill_md: string }>();
179 assert.match(version!.skill_md, /allowed-tools: Read, Bash/);
180 // Attached to every agent, it reaches an agent as `release:release-notes`.
181 await db.prepare("INSERT INTO skill_attachments (id, workspace_id, skill_id, scope, target, version, attached_by, attached_at) VALUES ('ska_1', ?, ?, 'workspace', '', 1, 'chase', ?)").bind(ws, notes.id, at.toISOString()).run();
182 const rows = await attachedRows(db, ws, "agt_1", []);
183 const shelf = shelfFrom([], rows).skills.filter((s) => s.kind === "library");
184 assert.deepEqual(shelf.map((s) => s.name), ["release:release-notes"]);
185 // Installed twice is a conflict; its agents are templates; Discover marks it installed.
186 const twice = await plugins.install(db, { workspaceId: ws, listing: { ...listing, availability: { kind: "installed", enabled: true } }, entry: entry.entry, marketplace: { name: "acme-tools", source: entry.source, pluginRoot: entry.pluginRoot }, host: "g1t.sh", by: "chase", deps, now: at });
187 assert.equal(!twice.ok && twice.error.code, "conflict");
188 assert.deepEqual((await plugins.pluginAgents(db, ws)).map((a) => [a.ref, a.model]), [["release:releaser", "sonnet"]]);
189 const marked = marketplaces.discoverPlugins(all, new Map([["release@acme-tools", { enabled: true }]]), "g1t.sh");
190 assert.deepEqual(marked[0]!.availability, { kind: "installed", enabled: true });
191 // Switched off, its skills leave prompts; uninstalled, they are archived and detached.
192 const off = await plugins.setEnabled(db, ws, "release@acme-tools", false, at);
193 assert.ok(off.ok && !off.value.enabled);
194 assert.deepEqual(await attachedRows(db, ws, "agt_1", []), []);
195 assert.deepEqual((await plugins.pluginAgents(db, ws)).length, 0);
196 await plugins.setEnabled(db, ws, "release@acme-tools", true, at);
197 assert.equal((await attachedRows(db, ws, "agt_1", [])).length, 1);
198 const gone = await plugins.uninstall(db, ws, "release@acme-tools", "chase", at);
199 assert.ok(gone.ok);
200 assert.deepEqual(gone.value.skills.sort(), ["code", "cut", "release-notes"]);
201 assert.equal(await skillByName(db, ws, "release-notes", "release@acme-tools"), null);
202 assert.deepEqual(await attachedRows(db, ws, "agt_1", []), []);
203 assert.deepEqual(await plugins.listInstalls(db, ws), []);
204});
205
206test("a skills-only plugin at a marketplace's root installs the skills its entry names", async () => {
207 const db = fakeD1();
208 await marketplaces.addMarketplace(db, ws, null, { source: "github", repo: "acme/tools" }, "chase", deps, "g1t.sh", at);
209 const all = await marketplaces.loadAll(db, ws, deps, "g1t.sh", at);
210 const listings = marketplaces.discoverPlugins(all, new Map(), "g1t.sh");
211 const listing = marketplaces.findListing(listings, "docs-skills@acme-tools")!;
212 const entry = marketplaces.entryOf(all, { name: "docs-skills", marketplace: "acme-tools" })!;
213 const done = await plugins.install(db, { workspaceId: ws, listing, entry: entry.entry, marketplace: { name: "acme-tools", source: entry.source, pluginRoot: entry.pluginRoot }, host: "g1t.sh", by: "chase", deps, now: at });
214 assert.ok(done.ok);
215 assert.deepEqual(done.value.skills.map((s) => s.name), ["brief"]);
216 // Not the marketplace's other plugins' skills, though they are in the same repository.
217 assert.equal(await skillByName(db, ws, "release-notes", "docs-skills@acme-tools"), null);
218 const skills = marketplaces.discoverSkills(listings, new Set(["docs-skills@acme-tools/brief"]));
219 assert.equal(skills[0]!.added, true);
220});
221
222test("what can't be fetched says why, and a marketplace that moved on shows an update", async () => {
223 const npm = await fetchPlugin({ kind: "unsupported", why: "It is published on npm." }, deps);
224 assert.equal(!npm.ok && npm.message, "It is published on npm.");
225 const missing = await fetchPlugin({ kind: "github", repo: "acme/tools", ref: null, sha: null, path: "plugins/nothing" }, deps);
226 assert.equal(!missing.ok && missing.message, "There are no files in plugins/nothing of acme/tools.");
227 const gone = await fetchMarketplace({ source: "github", repo: "acme/gone" }, deps);
228 assert.match(!gone.ok ? gone.message : "", /no \.claude-plugin\/marketplace\.json/);
229 const row: plugins.PluginRow = { id: "plg_1", workspace_id: ws, ref: "release@acme-tools", name: "release", marketplace: "acme-tools", display_name: null, description: "", version: "1.0.0", sha: "a".repeat(40), fetch: JSON.stringify({ kind: "github", repo: "acme/tools", ref: null, sha: "a".repeat(40), path: "plugins/release" }), components: "{}", agents: "[]", problems: "[]", enabled: 1, installed_by: "chase", installed_at: at.toISOString(), updated_at: at.toISOString(), uninstalled_by: null, uninstalled_at: null };
230 const listing = { ref: "release@acme-tools", name: "release", marketplace: "acme-tools", display_name: null, description: "", version: "1.2.0", author: null, homepage: null, category: null, tags: [], keywords: [], fetch: { kind: "github" as const, repo: "acme/tools", ref: null, sha: null, path: "plugins/release" }, availability: { kind: "available" as const }, skills: [] };
231 assert.deepEqual(plugins.installsOut([row], [listing])[0]!.update, { version: "1.2.0", sha: null });
232 assert.equal(plugins.installsOut([row], [{ ...listing, version: "1.0.0" }])[0]!.update, null);
233});
234
235test("a plugin skill larger than a version holds keeps its text and leaves its biggest binaries out", () => {
236 const big = "A".repeat(1_200_000);
237 const files = [
238 { path: "SKILL.md", content: "---\nname: canvas\ndescription: Use when drawing.\n---\n\nDraw.\n", encoding: "utf8" as const },
239 { path: "reference.md", content: "# Reference\n", encoding: "utf8" as const },
240 { path: "fonts/a.ttf", content: big, encoding: "base64" as const },
241 { path: "fonts/b.ttf", content: big, encoding: "base64" as const },
242 { path: "scripts/draw.py", content: "print(1)\n", encoding: "utf8" as const },
243 ];
244 const fitted = plugins.fitSkillFolder(files);
245 assert.deepEqual(fitted.omitted, ["fonts/a.ttf"], "one font out brings it under the limit; text stays");
246 assert.deepEqual(fitted.files.map((f) => f.path).sort(), ["SKILL.md", "fonts/b.ttf", "reference.md", "scripts/draw.py"]);
247 assert.deepEqual(plugins.fitSkillFolder(files.slice(0, 2)).omitted, []);
248});
249
250test("an installed plugin updates in place at its marketplace's newer commit: skill versions move with their attachments, gone skills are archived; unchanged when at the same commit", async () => {
251 const db = fakeD1();
252 await marketplaces.addMarketplace(db, ws, null, { source: "github", repo: "acme/tools" }, "chase", deps, "g1t.sh", at);
253 const all = await marketplaces.loadAll(db, ws, deps, "g1t.sh", at);
254 const listings = marketplaces.discoverPlugins(all, new Map(), "g1t.sh");
255 const listing = marketplaces.findListing(listings, "release@acme-tools")!;
256 const entry = marketplaces.entryOf(all, { name: "release", marketplace: "acme-tools" })!;
257 const input = { workspaceId: ws, listing, entry: entry.entry, marketplace: { name: "acme-tools", source: entry.source, pluginRoot: entry.pluginRoot }, host: "g1t.sh", by: "chase", deps, now: at };
258 const installed = await plugins.install(db, input);
259 assert.ok(installed.ok);
260 const notes = (await skillByName(db, ws, "release-notes", "release@acme-tools"))!;
261 await db.prepare("INSERT INTO skill_attachments (id, workspace_id, skill_id, scope, target, version, attached_by, attached_at) VALUES ('ska_1', ?, ?, 'workspace', '', 1, 'chase', ?)").bind(ws, notes.id, at.toISOString()).run();
262 // Same commit: nothing moves.
263 const same = await plugins.update(db, input);
264 assert.ok(same.ok && same.value.unchanged);
265 // The repository moves on: a new version, a changed skill, the "code" skill gone.
266 const NEXT = "fedcba9876543210fedcba9876543210fedcba98";
267 const files = { ...REPO };
268 delete files["plugins/release/skills/code/SKILL.md"];
269 files["plugins/release/.claude-plugin/plugin.json"] = JSON.stringify({ name: "release", version: "1.3.0", description: "Cuts releases, now with notes" });
270 files["plugins/release/skills/release-notes/SKILL.md"] = "---\nname: release-notes\ndescription: Use when asked for release notes or a changelog.\n---\n\nRead the merged pull requests, group them, write the notes, link each.\n";
271 const moved: Fetch = async (url, init) => {
272 const u = new URL(url);
273 if (u.hostname === "api.github.com" && (u.pathname.endsWith("/commits/HEAD") || u.pathname.endsWith("/commits/main"))) return Response.json({ sha: NEXT });
274 if (u.hostname === "api.github.com" && u.pathname === `/repos/acme/tools/git/trees/${NEXT}`) return Response.json({ tree: Object.entries(files).map(([path, content]) => ({ path, type: "blob", size: content.length })), truncated: false });
275 if (u.hostname === "raw.githubusercontent.com") {
276 const [, , , ref, ...rest] = u.pathname.split("/");
277 const file = files[rest.map(decodeURIComponent).join("/")];
278 return ref === NEXT && file !== undefined ? new Response(file) : new Response("no", { status: 404 });
279 }
280 return githubFetch()(url, init);
281 };
282 const updated = await plugins.update(db, { ...input, deps: { fetchFn: moved }, now: new Date(at.getTime() + 60_000) });
283 assert.ok(updated.ok, !updated.ok ? updated.error.message : "");
284 assert.equal(updated.value.unchanged, false);
285 assert.equal(updated.value.install.version, "1.3.0");
286 assert.equal(updated.value.install.sha, NEXT);
287 assert.equal(updated.value.install.description, "Cuts releases, now with notes");
288 const after = (await skillByName(db, ws, "release-notes", "release@acme-tools"))!;
289 assert.equal(after.version, 2);
290 assert.equal((await db.prepare("SELECT version FROM skill_attachments WHERE id = 'ska_1'").first<{ version: number }>())!.version, 2, "the attachment followed");
291 assert.equal(await skillByName(db, ws, "code", "release@acme-tools"), null, "a skill the plugin no longer has is archived");
292 assert.deepEqual(plugins.installsOut([(await plugins.installByRef(db, ws, "release@acme-tools"))!], [listing])[0]!.update, { version: "1.2.0", sha: null }, "the marketplace's cached listing still says 1.2.0 until it is read again");
293});
294
295test("g1t's own announced plugins are listed, as Soon, and can't be installed yet", async () => {
296 const db = fakeD1();
297 const all = await marketplaces.loadAll(db, ws, deps, "g1t.sh", at);
298 const listings = marketplaces.discoverPlugins(all, new Map(), "g1t.sh");
299 const own = listings.filter((l) => l.marketplace === "g1t");
300 assert.ok(own.length >= 5);
301 assert.ok(own.every((l) => l.availability.kind === "soon"));
302 const mail = marketplaces.findListing(listings, "mail@g1t")!;
303 assert.equal(mail.display_name, "Mail");
304 const entry = marketplaces.entryOf(all, { name: "mail", marketplace: "g1t" })!;
305 const refused = await plugins.install(db, { workspaceId: ws, listing: mail, entry: entry.entry, marketplace: { name: "g1t", source: entry.source, pluginRoot: null }, host: "g1t.sh", by: "chase", deps, now: at });
306 assert.equal(!refused.ok && refused.error.code, "invalid");
307});