bundled-skills.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { createHash } from "node:crypto";
  2. import { existsSync } from "node:fs";
  3. import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import type { Logger } from "@zcode/contracts";
  7. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  8. // 候选目录可控:默认指向真实 monorepo(复现开发态 / 桌面态),用例按需换成临时目录。
  9. const fakeBaseDirs = vi.hoisted(() => ({ dirs: undefined as string[] | undefined }));
  10. vi.mock("../src/app/bundled-plugins.js", async (importOriginal) => {
  11. const actual = await importOriginal<typeof import("../src/app/bundled-plugins.js")>();
  12. return {
  13. ...actual,
  14. candidateBaseDirs: () => fakeBaseDirs.dirs ?? actual.candidateBaseDirs(),
  15. };
  16. });
  17. const {
  18. BUNDLED_SKILL_PACK_REQUIRED_PATHS,
  19. DYNAMIC_WORKFLOW_SKILL_NAME,
  20. SEA_BUNDLED_SKILL_ASSET_PREFIX,
  21. resolveBundledSkillRoots,
  22. } = await import("../src/app/bundled-skills.js");
  23. type SeaModuleLike = { getAsset: unknown; getRawAsset: unknown; isSea(): boolean };
  24. const originalGetBuiltinModule = process.getBuiltinModule;
  25. function installSea(module: SeaModuleLike | undefined): void {
  26. Object.defineProperty(process, "getBuiltinModule", {
  27. configurable: true,
  28. value: module
  29. ? (id: string) => {
  30. if (id === "node:sea") return module;
  31. return originalGetBuiltinModule(id as never);
  32. }
  33. : originalGetBuiltinModule,
  34. writable: true,
  35. });
  36. }
  37. function createLogger(): Logger & { warnings: Array<{ context: unknown; message: string }> } {
  38. const warnings: Array<{ context: unknown; message: string }> = [];
  39. return {
  40. debug() {},
  41. error() {},
  42. info() {},
  43. warn(message: string, context?: unknown) {
  44. warnings.push({ context, message });
  45. },
  46. warnings,
  47. } as unknown as Logger & { warnings: Array<{ context: unknown; message: string }> };
  48. }
  49. interface FakeSeaPack {
  50. files: Map<string, Buffer>;
  51. manifest: { files: Array<{ path: string; sha256: string }>; hash: string; version: 1 };
  52. }
  53. function createFakeSeaPack(
  54. contents: Record<string, string>,
  55. options: { corruptFirst?: boolean } = {},
  56. ): FakeSeaPack {
  57. const files = new Map<string, Buffer>();
  58. const manifestFiles = Object.entries(contents)
  59. .map(([path, text]) => {
  60. const bytes = Buffer.from(text);
  61. files.set(path, bytes);
  62. return { path, sha256: createHash("sha256").update(bytes).digest("hex") };
  63. })
  64. .sort((left, right) => left.path.localeCompare(right.path));
  65. if (options.corruptFirst && manifestFiles[0]) {
  66. // 清单声称的 hash 与资产字节不一致:解压必须拒绝,而不是落盘一个改过的技能。
  67. manifestFiles[0].sha256 = "0".repeat(64);
  68. }
  69. const hash = createHash("sha256")
  70. .update(JSON.stringify(manifestFiles.map((file) => [file.path, file.sha256])))
  71. .digest("hex");
  72. return { files, manifest: { files: manifestFiles, hash, version: 1 } };
  73. }
  74. function seaModuleFor(pack: FakeSeaPack): SeaModuleLike {
  75. return {
  76. getAsset: (key: string) => {
  77. if (key === `${SEA_BUNDLED_SKILL_ASSET_PREFIX}manifest.json`) {
  78. return JSON.stringify(pack.manifest);
  79. }
  80. throw new Error(`unknown asset ${key}`);
  81. },
  82. getRawAsset: (key: string) => {
  83. const bytes = pack.files.get(key.slice(SEA_BUNDLED_SKILL_ASSET_PREFIX.length));
  84. if (!bytes) throw new Error(`unknown raw asset ${key}`);
  85. // node:sea 的 getRawAsset 返回独占的 ArrayBuffer;Buffer 可能来自共享池,必须拷贝成精确尺寸。
  86. return Uint8Array.from(bytes).buffer;
  87. },
  88. isSea: () => true,
  89. };
  90. }
  91. const COMPLETE_PACK = Object.fromEntries(
  92. BUNDLED_SKILL_PACK_REQUIRED_PATHS.map((path) => [path, `# ${path}\n`]),
  93. );
  94. describe("resolveBundledSkillRoots", () => {
  95. let tempRoot: string;
  96. beforeEach(async () => {
  97. tempRoot = await mkdtemp(join(tmpdir(), "zcode-bundled-skills-"));
  98. fakeBaseDirs.dirs = undefined;
  99. });
  100. afterEach(async () => {
  101. installSea(undefined);
  102. fakeBaseDirs.dirs = undefined;
  103. await rm(tempRoot, { force: true, recursive: true });
  104. });
  105. it("finds the real pack next to the CLI sources and reads it in place", () => {
  106. const roots = resolveBundledSkillRoots({ cliStorageRoot: join(tempRoot, "cli") });
  107. expect(roots).toHaveLength(1);
  108. const [root] = roots;
  109. expect(root).toMatchObject({ scope: "system", source: "bundled" });
  110. expect(root?.path.endsWith(join("bundled-skills", "skills"))).toBe(true);
  111. expect(existsSync(join(root!.path, DYNAMIC_WORKFLOW_SKILL_NAME, "SKILL.md"))).toBe(true);
  112. // 非 SEA 形态不落盘:storage 里不应出现任何解压产物。
  113. expect(existsSync(join(tempRoot, "cli", "bundled-skills"))).toBe(false);
  114. });
  115. it("refuses a staged pack that lost a required file, and warns", async () => {
  116. const stagedRoot = join(tempRoot, "entry");
  117. await mkdir(
  118. join(stagedRoot, "packages", "bundled-skills", "skills", DYNAMIC_WORKFLOW_SKILL_NAME),
  119. {
  120. recursive: true,
  121. },
  122. );
  123. await writeFile(
  124. join(
  125. stagedRoot,
  126. "packages",
  127. "bundled-skills",
  128. "skills",
  129. DYNAMIC_WORKFLOW_SKILL_NAME,
  130. "SKILL.md",
  131. ),
  132. "# partial",
  133. );
  134. fakeBaseDirs.dirs = [stagedRoot];
  135. const logger = createLogger();
  136. expect(resolveBundledSkillRoots({ cliStorageRoot: join(tempRoot, "cli"), logger })).toEqual([]);
  137. expect(logger.warnings.map((entry) => entry.message)).toEqual([
  138. "Bundled skill pack unavailable",
  139. ]);
  140. });
  141. it("finds a complete staged pack through any candidate base directory", async () => {
  142. const stagedRoot = join(tempRoot, "entry");
  143. for (const [path, text] of Object.entries(COMPLETE_PACK)) {
  144. const filePath = join(stagedRoot, "packages", "bundled-skills", ...path.split("/"));
  145. await mkdir(join(filePath, ".."), { recursive: true });
  146. await writeFile(filePath, text);
  147. }
  148. fakeBaseDirs.dirs = [join(tempRoot, "nowhere"), stagedRoot];
  149. expect(resolveBundledSkillRoots({ cliStorageRoot: join(tempRoot, "cli") })).toEqual([
  150. {
  151. path: join(stagedRoot, "packages", "bundled-skills", "skills"),
  152. priority: expect.any(Number),
  153. scope: "system",
  154. source: "bundled",
  155. },
  156. ]);
  157. });
  158. describe("SEA", () => {
  159. it("extracts the embedded pack once into a content-hashed directory and reuses it", async () => {
  160. const pack = createFakeSeaPack(COMPLETE_PACK);
  161. installSea(seaModuleFor(pack));
  162. fakeBaseDirs.dirs = [join(tempRoot, "nowhere")];
  163. const cliStorageRoot = join(tempRoot, "cli");
  164. const expectedPackRoot = join(cliStorageRoot, "bundled-skills", pack.manifest.hash);
  165. const first = resolveBundledSkillRoots({ cliStorageRoot });
  166. expect(first).toEqual([
  167. {
  168. path: join(expectedPackRoot, "skills"),
  169. priority: expect.any(Number),
  170. scope: "system",
  171. source: "bundled",
  172. },
  173. ]);
  174. for (const [path, text] of Object.entries(COMPLETE_PACK)) {
  175. await expect(readFile(join(expectedPackRoot, ...path.split("/")), "utf8")).resolves.toBe(
  176. text,
  177. );
  178. }
  179. // 第二次启动:目录已完整,不重新解压,也不留下临时目录。
  180. const second = resolveBundledSkillRoots({ cliStorageRoot });
  181. expect(second).toEqual(first);
  182. const siblings = await readdir(join(cliStorageRoot, "bundled-skills"));
  183. expect(siblings).toEqual([pack.manifest.hash]);
  184. });
  185. it("rejects an asset whose bytes do not match the manifest and falls back to a complete older pack", async () => {
  186. const cliStorageRoot = join(tempRoot, "cli");
  187. fakeBaseDirs.dirs = [join(tempRoot, "nowhere")];
  188. const good = createFakeSeaPack(COMPLETE_PACK);
  189. installSea(seaModuleFor(good));
  190. const goodRoots = resolveBundledSkillRoots({ cliStorageRoot });
  191. const corrupt = createFakeSeaPack(
  192. { ...COMPLETE_PACK, [BUNDLED_SKILL_PACK_REQUIRED_PATHS[0]]: "changed" },
  193. {
  194. corruptFirst: true,
  195. },
  196. );
  197. installSea(seaModuleFor(corrupt));
  198. const logger = createLogger();
  199. expect(resolveBundledSkillRoots({ cliStorageRoot, logger })).toEqual(goodRoots);
  200. expect(logger.warnings.map((entry) => entry.message)).toEqual([
  201. "Bundled skill pack seed degraded",
  202. ]);
  203. expect(existsSync(join(cliStorageRoot, "bundled-skills", corrupt.manifest.hash))).toBe(false);
  204. const siblings = await readdir(join(cliStorageRoot, "bundled-skills"));
  205. expect(siblings.some((name) => name.includes(".tmp-"))).toBe(false);
  206. });
  207. it("falls through to the filesystem pack when the binary carries no bundled skill manifest", () => {
  208. installSea({
  209. getAsset: () => {
  210. throw new Error("no such asset");
  211. },
  212. getRawAsset: () => {
  213. throw new Error("no such asset");
  214. },
  215. isSea: () => true,
  216. });
  217. const roots = resolveBundledSkillRoots({ cliStorageRoot: join(tempRoot, "cli") });
  218. expect(roots).toHaveLength(1);
  219. expect(roots[0]?.path.endsWith(join("bundled-skills", "skills"))).toBe(true);
  220. });
  221. });
  222. });