skill-catalog.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import fs from "node:fs";
  2. import { mkdir, mkdtemp, rename, rm, symlink, writeFile } from "node:fs/promises";
  3. import { syncBuiltinESMExports } from "node:module";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join } from "node:path";
  6. import { afterEach, beforeEach, expect, it, vi } from "vitest";
  7. import { SkillNotFoundError, type SkillLoadOutcome, type SkillRoot } from "@zcode/contracts";
  8. import {
  9. createCatalogSkillPort,
  10. createSkillCatalogLoader,
  11. createSkillCatalogSource,
  12. createSkillCatalogSourceRegistry,
  13. type SkillCatalogSourceOptions,
  14. } from "../src/skills/catalog.js";
  15. interface Fixture {
  16. root: string;
  17. home: string;
  18. workspace: string;
  19. userConfig: string;
  20. projectConfig: string;
  21. plugins: string;
  22. options: SkillCatalogSourceOptions & { homeDirectory: string };
  23. }
  24. let fixture: Fixture;
  25. beforeEach(async () => {
  26. const root = await mkdtemp(join(tmpdir(), "skill-catalog-"));
  27. const home = join(root, "home");
  28. const workspace = join(root, "workspace");
  29. const userConfig = join(home, ".zcode", "cli", "config.json");
  30. const plugins = join(home, ".zcode", "cli", "plugins");
  31. await mkdir(plugins, { recursive: true });
  32. await mkdir(join(home, ".zcode", "skills"), { recursive: true });
  33. await mkdir(join(workspace, ".git"), { recursive: true });
  34. const projectConfig = join(workspace, ".zcode", "config.json");
  35. fixture = {
  36. root,
  37. home,
  38. workspace,
  39. userConfig,
  40. projectConfig,
  41. plugins,
  42. options: {
  43. homeDirectory: home,
  44. workingDirectory: workspace,
  45. configPaths: [projectConfig, userConfig],
  46. userConfigPath: userConfig,
  47. pluginStorageRoot: plugins,
  48. pluginRoots: [],
  49. bundledRoots: [],
  50. },
  51. };
  52. });
  53. afterEach(() => rm(fixture.root, { recursive: true, force: true }));
  54. async function writeSkill(directory: string, name: string, description = `${name} skill`) {
  55. await mkdir(directory, { recursive: true });
  56. await writeFile(
  57. join(directory, "SKILL.md"),
  58. `---\nname: ${name}\ndescription: ${description}\n---\nbody of ${name}\n`,
  59. );
  60. }
  61. async function writeJson(path: string, value: unknown) {
  62. await mkdir(dirname(path), { recursive: true });
  63. await writeFile(path, JSON.stringify(value));
  64. }
  65. function names(outcome: SkillLoadOutcome): string[] {
  66. return outcome.skills.map((skill) => skill.qualifiedName ?? skill.name).toSorted();
  67. }
  68. async function load(options: SkillCatalogSourceOptions & { homeDirectory: string }) {
  69. const loaded = await createSkillCatalogLoader(options).load();
  70. loaded.commit();
  71. return loaded;
  72. }
  73. async function installPlugin(name: string) {
  74. const plugin = join(fixture.root, "installed", name);
  75. await writeJson(join(plugin, ".zcode-plugin", "plugin.json"), { name });
  76. await writeSkill(join(plugin, "skills", "demo"), "demo");
  77. await writeJson(join(fixture.plugins, "installed_plugins.json"), {
  78. version: 1,
  79. plugins: [
  80. {
  81. id: `${name}@test`,
  82. name,
  83. marketplace: "test",
  84. version: "1.0.0",
  85. installPath: plugin,
  86. installedAt: "2026-01-01T00:00:00Z",
  87. updatedAt: "2026-01-01T00:00:00Z",
  88. scope: "user",
  89. },
  90. ],
  91. });
  92. return plugin;
  93. }
  94. it("follows plugin enablement from the configuration and installation commit points", async () => {
  95. const plugin = await installPlugin("example");
  96. await writeJson(fixture.userConfig, { plugins: { enabledPlugins: { "example@test": true } } });
  97. const enabled = await load(fixture.options);
  98. expect(names(enabled.outcome)).toEqual(["example:demo"]);
  99. // 插件目录只由安装流程写入:只监听提交点,不监听插件 manifest 与 skill 目录。
  100. expect(enabled.files).toContain(join(fixture.plugins, "installed_plugins.json"));
  101. expect(enabled.files).toContain(fixture.userConfig);
  102. expect([...enabled.files].some((file) => file.startsWith(plugin))).toBe(false);
  103. expect([...enabled.directories!].some((directory) => directory.startsWith(plugin))).toBe(false);
  104. // 工作区配置优先于用户配置。
  105. await writeJson(fixture.projectConfig, {
  106. plugins: { enabledPlugins: { "example@test": false } },
  107. });
  108. expect(names((await load(fixture.options)).outcome)).toEqual([]);
  109. expect(
  110. names((await load({ ...fixture.options, excludedPluginIds: ["example@test"] })).outcome),
  111. ).toEqual([]);
  112. });
  113. it("reuses plugin names across reloads but follows a plugin renamed in place", async () => {
  114. const plugin = await installPlugin("example");
  115. await writeJson(fixture.userConfig, {
  116. plugins: { enabledPlugins: { "example@test": true, "renamed@test": true } },
  117. });
  118. const loader = createSkillCatalogLoader(fixture.options);
  119. const first = (await loader.load()).outcome;
  120. expect(names(first)).toEqual(["example:demo"]);
  121. // 名字查找从 skill 根向上走,根目录下的 manifest 先命中。缓存复用时不再查找,所以看不到它。
  122. const decoy = join(first.skills[0]!.rootPath, ".cursor-plugin", "plugin.json");
  123. await writeJson(decoy, { name: "decoy" });
  124. expect(names((await loader.load()).outcome)).toEqual(["example:demo"]);
  125. await rm(dirname(decoy), { recursive: true });
  126. // 同一路径改名:插件名缓存跨重读共用,键里的 pluginId 变化后必须重新读取。
  127. await writeJson(join(plugin, ".zcode-plugin", "plugin.json"), { name: "renamed" });
  128. expect(names((await loader.load()).outcome)).toEqual(["renamed:demo"]);
  129. });
  130. it("finds an installed plugin without installPath in its cache directory, like startup", async () => {
  131. const cached = join(fixture.plugins, "cache", "test", "example", "1.0.0");
  132. await writeJson(join(cached, ".zcode-plugin", "plugin.json"), { name: "example" });
  133. await writeSkill(join(cached, "skills", "demo"), "demo");
  134. await writeJson(join(fixture.plugins, "installed_plugins.json"), {
  135. version: 1,
  136. plugins: [
  137. {
  138. id: "example@test",
  139. name: "example",
  140. marketplace: "test",
  141. version: "1.0.0",
  142. installPath: "",
  143. installedAt: "2026-01-01T00:00:00Z",
  144. scope: "user",
  145. },
  146. ],
  147. });
  148. await writeJson(fixture.userConfig, { plugins: { enabledPlugins: { "example@test": true } } });
  149. // 修复前空路径被解析成进程 cwd,实时目录读不到这个插件,或读到 cwd 下的同名目录。
  150. const loaded = await load(fixture.options);
  151. expect(loaded.outcome.skills.map((skill) => [skill.qualifiedName, skill.path])).toEqual([
  152. ["example:demo", join(cached, "skills", "demo", "SKILL.md")],
  153. ]);
  154. });
  155. it("applies skill toggles from both configuration files and keeps project roots out", async () => {
  156. const user = join(fixture.home, ".zcode", "skills", "user-skill");
  157. const project = join(fixture.workspace, ".agents", "skills", "project-skill");
  158. const extra = join(fixture.root, "extra");
  159. await writeSkill(user, "user-skill");
  160. await writeSkill(project, "project-skill");
  161. await writeSkill(join(extra, "extra-skill"), "extra-skill");
  162. await writeJson(fixture.userConfig, { skills: { roots: [extra] } });
  163. // 项目配置只能写绝对路径的开关,不能加 skills.roots(与启动配置同一 scope)。
  164. await writeJson(fixture.projectConfig, { skills: { roots: [extra] } });
  165. expect(names((await load(fixture.options)).outcome)).toEqual([
  166. "extra-skill",
  167. "project-skill",
  168. "user-skill",
  169. ]);
  170. // 设置页写用户配置;工作区配置写绝对路径开关。两个来源分别生效。
  171. await writeJson(fixture.projectConfig, {});
  172. await writeJson(fixture.userConfig, {
  173. skills: { [join(user, "SKILL.md")]: { enable: false } },
  174. });
  175. expect(names((await load(fixture.options)).outcome)).toEqual(["project-skill"]);
  176. await writeJson(fixture.userConfig, {});
  177. await writeJson(fixture.projectConfig, {
  178. skills: { [join(project, "SKILL.md")]: { enable: false } },
  179. });
  180. expect(names((await load(fixture.options)).outcome)).toEqual(["user-skill"]);
  181. // 两个来源同时有开关时都生效:修复前项目层的开关整体替换了用户层的开关。
  182. await writeJson(fixture.userConfig, {
  183. skills: { [join(user, "SKILL.md")]: { enable: false } },
  184. });
  185. expect(names((await load(fixture.options)).outcome)).toEqual([]);
  186. });
  187. it("watches skill roots but not existing skills, plain subdirectories or bundled roots", async () => {
  188. const userRoot = join(fixture.home, ".agents", "skills");
  189. await writeSkill(join(userRoot, "alpha"), "alpha");
  190. await mkdir(join(userRoot, "pending"), { recursive: true });
  191. await mkdir(join(userRoot, ".hidden"), { recursive: true });
  192. const bundled = join(fixture.root, "bundled");
  193. await writeSkill(join(bundled, "builtin"), "builtin");
  194. await writeSkill(join(bundled, "workflow"), "workflow");
  195. const bundledRoot: SkillRoot = {
  196. path: bundled,
  197. priority: 1_000_000,
  198. scope: "system",
  199. source: "bundled",
  200. };
  201. const loaded = await load({
  202. ...fixture.options,
  203. bundledRoots: [bundledRoot],
  204. fixedDisabledPaths: [join(bundled, "workflow", "SKILL.md")],
  205. });
  206. expect(names(loaded.outcome)).toEqual(["alpha", "builtin"]);
  207. expect([...loaded.directories!].toSorted()).toEqual(
  208. [
  209. join(fixture.home, ".zcode", "skills"),
  210. userRoot,
  211. join(fixture.workspace, ".zcode", "skills"),
  212. join(fixture.workspace, ".agents", "skills"),
  213. ].toSorted(),
  214. );
  215. expect(loaded.files).toContain(join(userRoot, "SKILL.md"));
  216. // 已有 skill 的 SKILL.md 不监听:原地修改描述等下一次全量重读,数量与 skill 数无关。
  217. expect(loaded.files).not.toContain(join(userRoot, "alpha", "SKILL.md"));
  218. // 没有 SKILL.md 的子目录(例如分类目录)也不监听,否则监听数随目录数增长且永不撤销。
  219. expect(loaded.files).not.toContain(join(userRoot, "pending", "SKILL.md"));
  220. expect(loaded.files).not.toContain(join(userRoot, ".hidden", "SKILL.md"));
  221. expect([...loaded.files].some((file) => file.startsWith(bundled))).toBe(false);
  222. });
  223. it("publishes new and removed skill directories in an open source", async () => {
  224. const source = await createSkillCatalogSource(fixture.options);
  225. try {
  226. expect(names(source.getSnapshot())).toEqual([]);
  227. // 工作区还没有 .agents:锚点在工作区根,创建整条路径后被发现。
  228. await writeSkill(join(fixture.workspace, ".agents", "skills", "fresh"), "fresh");
  229. await vi.waitFor(() => expect(names(source.getSnapshot())).toEqual(["fresh"]), {
  230. timeout: 5_000,
  231. });
  232. await writeSkill(join(fixture.home, ".zcode", "skills", "second"), "second");
  233. await vi.waitFor(() => expect(names(source.getSnapshot())).toEqual(["fresh", "second"]), {
  234. timeout: 5_000,
  235. });
  236. await rm(join(fixture.workspace, ".agents", "skills", "fresh"), { recursive: true });
  237. await vi.waitFor(() => expect(names(source.getSnapshot())).toEqual(["second"]), {
  238. timeout: 5_000,
  239. });
  240. } finally {
  241. source.close();
  242. }
  243. });
  244. it("shares one entry for sessions with the same inputs", async () => {
  245. const registry = createSkillCatalogSourceRegistry();
  246. try {
  247. const first = await registry.acquire(fixture.options);
  248. const second = await registry.acquire({ ...fixture.options });
  249. expect(second.getSnapshot()).toBe(first.getSnapshot());
  250. first.close();
  251. first.close();
  252. second.close();
  253. } finally {
  254. registry.close();
  255. }
  256. });
  257. it("loads a skill written inside the debounce window by flushing once on a miss", async () => {
  258. const source = await createSkillCatalogSource(fixture.options);
  259. const port = createCatalogSkillPort(source);
  260. try {
  261. expect(await port.discoverSkills({ workingDirectory: fixture.workspace })).toBe(
  262. port.currentCatalog(),
  263. );
  264. await writeSkill(join(fixture.home, ".zcode", "skills", "just-written"), "just-written");
  265. const content = await port.loadSkill({
  266. name: "just-written",
  267. workingDirectory: fixture.workspace,
  268. });
  269. expect(content.content).toBe("body of just-written");
  270. expect(names(port.currentCatalog())).toEqual(["just-written"]);
  271. const missing = port.loadSkill({ name: "missing", workingDirectory: fixture.workspace });
  272. await expect(missing).rejects.toThrow("Skill not found: missing");
  273. // Skill tool 按错误类型转成模型文字,不解析 message。
  274. await expect(missing).rejects.toBeInstanceOf(SkillNotFoundError);
  275. } finally {
  276. port.close();
  277. }
  278. });
  279. it("reloads once when a listed skill file is gone and reports it as not found", async () => {
  280. const gone = join(fixture.home, ".zcode", "skills", "gone");
  281. await writeSkill(gone, "gone");
  282. const source = await createSkillCatalogSource(fixture.options);
  283. const port = createCatalogSkillPort(source);
  284. try {
  285. expect(names(port.currentCatalog())).toEqual(["gone"]);
  286. // 去抖窗口内快照仍列出它;修复前直接返回原始的 ENOENT 文件错误。
  287. await rm(gone, { recursive: true });
  288. await expect(
  289. port.loadSkill({ name: "gone", workingDirectory: fixture.workspace }),
  290. ).rejects.toThrow("Skill not found: gone");
  291. expect(names(port.currentCatalog())).toEqual([]);
  292. } finally {
  293. port.close();
  294. }
  295. });
  296. // 信任边界回归:插件目录不在监听范围,快照建立后插件文件被换成链接时没有重读。
  297. // 修复前端口按快照路径直接读取,插件外文件的内容作为 skill 正文交给模型。
  298. it.for(["file", "skill directory", "skills root"] as const)(
  299. "refuses a plugin skill whose %s became a link after the snapshot",
  300. async (form, ctx) => {
  301. const plugin = await installPlugin("example");
  302. await writeJson(fixture.userConfig, { plugins: { enabledPlugins: { "example@test": true } } });
  303. const outside = join(fixture.root, "outside");
  304. await writeSkill(join(outside, "demo"), "demo", "outside skill");
  305. const source = await createSkillCatalogSource(fixture.options);
  306. const port = createCatalogSkillPort(source);
  307. const request = { name: "example:demo", workingDirectory: fixture.workspace };
  308. // Windows 普通权限下创建目录 junction 不需要特权,文件链接会 EPERM。
  309. const directoryLink = process.platform === "win32" ? "junction" : "dir";
  310. try {
  311. expect((await port.loadSkill(request)).content).toBe("body of demo");
  312. const skills = join(plugin, "skills");
  313. if (form === "file") {
  314. await rm(join(skills, "demo", "SKILL.md"));
  315. try {
  316. await symlink(join(outside, "demo", "SKILL.md"), join(skills, "demo", "SKILL.md"));
  317. } catch (error) {
  318. if ((error as NodeJS.ErrnoException).code !== "EPERM") throw error;
  319. ctx.skip();
  320. }
  321. } else if (form === "skill directory") {
  322. await rename(join(skills, "demo"), join(fixture.root, "moved-demo"));
  323. await symlink(join(outside, "demo"), join(skills, "demo"), directoryLink);
  324. } else {
  325. await rename(skills, join(fixture.root, "moved-skills"));
  326. await symlink(outside, skills, directoryLink);
  327. }
  328. await expect(port.loadSkill(request)).rejects.toThrow("Skill not found: example:demo");
  329. expect(names(port.currentCatalog())).toEqual([]);
  330. } finally {
  331. port.close();
  332. }
  333. },
  334. );
  335. it("keeps loading a user skill that is a link", async () => {
  336. const target = join(fixture.root, "shared", "linked");
  337. await writeSkill(target, "linked");
  338. await symlink(
  339. target,
  340. join(fixture.home, ".zcode", "skills", "linked"),
  341. process.platform === "win32" ? "junction" : "dir",
  342. );
  343. const source = await createSkillCatalogSource(fixture.options);
  344. const port = createCatalogSkillPort(source);
  345. try {
  346. // 用户级 skill 支持用链接导入,不做插件的链接检查。
  347. const content = await port.loadSkill({ name: "linked", workingDirectory: fixture.workspace });
  348. expect(content.content).toBe("body of linked");
  349. } finally {
  350. port.close();
  351. }
  352. });
  353. it("stops a cancelled load before reloading the catalog", async () => {
  354. const flush = vi.fn(async () => {});
  355. const port = createCatalogSkillPort({
  356. getSnapshot: () => ({ skills: [], diagnostics: [], totalDiscovered: 0 }),
  357. flush,
  358. close: () => {},
  359. });
  360. const controller = new AbortController();
  361. controller.abort();
  362. // 未命中会触发全量重读;用户停止后不能再等重读结束。
  363. await expect(
  364. port.loadSkill(
  365. { name: "missing", workingDirectory: fixture.workspace },
  366. { signal: controller.signal },
  367. ),
  368. ).rejects.toThrow("Skill operation cancelled");
  369. expect(flush).not.toHaveBeenCalled();
  370. });
  371. it("keeps the system watch handle count independent of the number of skills", async () => {
  372. // chokidar 的 ESM 入口按名字导入 fs.watch;改写 CJS 导出后同步到 ESM 绑定,统计真实句柄。
  373. const original = fs.watch;
  374. let handles = 0;
  375. fs.watch = ((...args: Parameters<typeof fs.watch>) => {
  376. handles += 1;
  377. return original.apply(fs, args);
  378. }) as typeof fs.watch;
  379. syncBuiltinESMExports();
  380. const count = async (skills: number) => {
  381. const userRoot = join(fixture.home, ".agents", "skills");
  382. await rm(userRoot, { recursive: true, force: true });
  383. for (let index = 0; index < skills; index += 1)
  384. await writeSkill(join(userRoot, `skill-${index}`), `skill-${index}`);
  385. // 根目录里的普通文件不占句柄:只登记过的文件才通过过滤。
  386. await writeFile(join(userRoot, "README.md"), "notes");
  387. handles = 0;
  388. const source = await createSkillCatalogSource(fixture.options);
  389. const opened = handles;
  390. expect(source.getSnapshot().skills).toHaveLength(skills);
  391. source.close();
  392. return opened;
  393. };
  394. try {
  395. const few = await count(2);
  396. const many = await count(40);
  397. // 按 skill 监听(depth 1)时句柄随数量增长,实测 49 个 skill 约 100 个;这里每个根目录一个。
  398. expect(many).toBe(few);
  399. expect(few).toBeGreaterThan(0);
  400. } finally {
  401. fs.watch = original;
  402. syncBuiltinESMExports();
  403. }
  404. });