packaging.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { promisify } from "node:util";
  8. import { gunzipSync } from "node:zlib";
  9. import { afterEach, describe, expect, it } from "vitest";
  10. import {
  11. collectBareModuleSpecifiers,
  12. isNodePtyRuntimePath,
  13. resolveProductionPackageClosure,
  14. stageRelease,
  15. } from "../src/packaging/stage.js";
  16. import { resolveHostTarCommand } from "../src/packaging/tarCommand.js";
  17. const execFileAsync = promisify(execFile);
  18. async function runTar(args: string[]): Promise<void> {
  19. await execFileAsync(resolveHostTarCommand(), args);
  20. }
  21. const temporaryDirs: string[] = [];
  22. const macIt = process.platform === "darwin" ? it : it.skip;
  23. async function makeTempDir(): Promise<string> {
  24. const dir = await mkdtemp(join(tmpdir(), "zcode-server-stage-test-"));
  25. temporaryDirs.push(dir);
  26. return dir;
  27. }
  28. afterEach(async () => {
  29. await Promise.all(
  30. temporaryDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })),
  31. );
  32. });
  33. interface FakePackageSpec {
  34. dependencies?: Record<string, string>;
  35. optionalDependencies?: Record<string, string>;
  36. devDependencies?: Record<string, string>;
  37. files?: Record<string, string>;
  38. }
  39. async function writeFakePackage(
  40. nodeModulesDir: string,
  41. name: string,
  42. spec: FakePackageSpec = {},
  43. ): Promise<string> {
  44. const packageDir = join(nodeModulesDir, ...name.split("/"));
  45. await mkdir(packageDir, { recursive: true });
  46. await writeFile(
  47. join(packageDir, "package.json"),
  48. JSON.stringify({
  49. name,
  50. version: "0.0.1",
  51. main: "./index.js",
  52. dependencies: spec.dependencies,
  53. optionalDependencies: spec.optionalDependencies,
  54. devDependencies: spec.devDependencies,
  55. }),
  56. "utf8",
  57. );
  58. await writeFile(join(packageDir, "index.js"), "module.exports = {};\n", "utf8");
  59. for (const [relativePath, contents] of Object.entries(spec.files ?? {})) {
  60. const filePath = join(packageDir, ...relativePath.split("/"));
  61. await mkdir(join(filePath, ".."), { recursive: true });
  62. await writeFile(filePath, contents, "utf8");
  63. }
  64. return packageDir;
  65. }
  66. describe("collectBareModuleSpecifiers", () => {
  67. it("extracts bare imports, dynamic imports and requires as package names", () => {
  68. const source = [
  69. 'import { Hono } from "hono";',
  70. 'import { serve } from "@hono/node-server";',
  71. 'const pty = await import("node-pty");',
  72. 'const utils = require("node-pty/lib/utils");',
  73. ].join("\n");
  74. const names = collectBareModuleSpecifiers(source);
  75. expect(names).toContain("hono");
  76. expect(names).toContain("@hono/node-server");
  77. expect(names).toContain("node-pty");
  78. });
  79. it("ignores node builtins and relative specifiers", () => {
  80. const source = [
  81. 'import { readFile } from "node:fs/promises";',
  82. 'import local from "./local.js";',
  83. 'import parent from "../parent.js";',
  84. ].join("\n");
  85. expect(collectBareModuleSpecifiers(source).size).toBe(0);
  86. });
  87. });
  88. describe("resolveProductionPackageClosure", () => {
  89. it("collects transitive production dependencies but not dev dependencies", async () => {
  90. const root = await makeTempDir();
  91. const nodeModulesDir = join(root, "node_modules");
  92. await writeFakePackage(nodeModulesDir, "pkg-a", {
  93. dependencies: { "pkg-b": "*" },
  94. devDependencies: { "pkg-dev": "*" },
  95. });
  96. await writeFakePackage(nodeModulesDir, "pkg-b", {
  97. dependencies: { "@scope/pkg-c": "*" },
  98. });
  99. await writeFakePackage(nodeModulesDir, "@scope/pkg-c");
  100. await writeFakePackage(nodeModulesDir, "pkg-dev");
  101. const closure = await resolveProductionPackageClosure(["pkg-a"], nodeModulesDir);
  102. expect([...closure.keys()].sort()).toEqual(["@scope/pkg-c", "pkg-a", "pkg-b"]);
  103. });
  104. it("skips missing optional dependencies and unknown entry packages", async () => {
  105. const root = await makeTempDir();
  106. const nodeModulesDir = join(root, "node_modules");
  107. await writeFakePackage(nodeModulesDir, "pkg-a", {
  108. optionalDependencies: { "pkg-missing-optional": "*" },
  109. });
  110. const closure = await resolveProductionPackageClosure(
  111. ["pkg-a", "pkg-not-installed"],
  112. nodeModulesDir,
  113. );
  114. expect([...closure.keys()]).toEqual(["pkg-a"]);
  115. });
  116. });
  117. describe("isNodePtyRuntimePath", () => {
  118. it("keeps runtime files and the target platform prebuild only", () => {
  119. expect(isNodePtyRuntimePath("package.json", "linux-x64")).toBe(true);
  120. expect(isNodePtyRuntimePath("lib/index.js", "linux-x64")).toBe(true);
  121. expect(isNodePtyRuntimePath("typings/node-pty.d.ts", "linux-x64")).toBe(true);
  122. expect(isNodePtyRuntimePath("prebuilds/linux-x64/pty.node", "linux-x64")).toBe(true);
  123. expect(isNodePtyRuntimePath("LICENSE", "linux-x64")).toBe(true);
  124. });
  125. it("drops host build outputs, sources and other platform prebuilds", () => {
  126. expect(isNodePtyRuntimePath("build/Release/pty.node", "linux-x64")).toBe(false);
  127. expect(isNodePtyRuntimePath("build/Debug/pty.node", "linux-x64")).toBe(false);
  128. expect(isNodePtyRuntimePath("prebuilds/darwin-arm64/pty.node", "linux-x64")).toBe(false);
  129. expect(isNodePtyRuntimePath("src/unix/pty.cc", "linux-x64")).toBe(false);
  130. expect(isNodePtyRuntimePath("deps/winpty/x.h", "linux-x64")).toBe(false);
  131. expect(isNodePtyRuntimePath("scripts/post-install.js", "linux-x64")).toBe(false);
  132. });
  133. });
  134. describe("stageRelease", () => {
  135. async function makeStageFixture(): Promise<{
  136. distDir: string;
  137. workspaceNodeModulesDir: string;
  138. agentBundlePath: string;
  139. bundledSkillsDir: string;
  140. nodeBinaryPath: string;
  141. outputDir: string;
  142. notices: { thirdParty: string; node: string; nodeSource: string };
  143. }> {
  144. const root = await makeTempDir();
  145. const distDir = join(root, "dist");
  146. await mkdir(distDir, { recursive: true });
  147. await writeFile(
  148. join(distDir, "server-cli.js"),
  149. 'import "fake-dep";\nimport "node-pty";\n',
  150. "utf8",
  151. );
  152. await writeFile(join(distDir, "server-core.js"), 'import "node:fs";\n', "utf8");
  153. const workspaceNodeModulesDir = join(root, "node_modules");
  154. await writeFakePackage(workspaceNodeModulesDir, "fake-dep", {
  155. dependencies: { "fake-transitive": "*" },
  156. });
  157. await writeFakePackage(workspaceNodeModulesDir, "fake-transitive");
  158. await writeFakePackage(workspaceNodeModulesDir, "node-pty", {
  159. files: {
  160. LICENSE: "node-pty license\n",
  161. "lib/index.js": "module.exports = {};\n",
  162. "typings/node-pty.d.ts": "export {};\n",
  163. "build/Release/pty.node": "host-binary",
  164. "prebuilds/darwin-arm64/pty.node": "darwin-binary",
  165. "prebuilds/darwin-arm64/spawn-helper": "darwin-helper",
  166. "prebuilds/win32-x64/pty.node": "windows-binary",
  167. },
  168. });
  169. await writeFakePackage(workspaceNodeModulesDir, "@lydell/node-pty-linux-x64", {
  170. files: { "prebuilds/linux-x64/pty.node": "linux-binary" },
  171. });
  172. const bundledSkillsDir = join(root, "bundled-skills");
  173. await mkdir(join(bundledSkillsDir, "skills/dynamic-workflows"), { recursive: true });
  174. await writeFile(join(bundledSkillsDir, "README.md"), "bundled skills");
  175. await writeFile(join(bundledSkillsDir, "scratch.txt"), "local only");
  176. for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
  177. await writeFile(join(bundledSkillsDir, "skills/dynamic-workflows", name), `fixture ${name}`);
  178. }
  179. const agentBundlePath = join(root, "zcode.cjs");
  180. await writeFile(agentBundlePath, "// fake agent bundle\n", "utf8");
  181. const nodeBinaryPath = join(root, "node-binary");
  182. await writeFile(nodeBinaryPath, "#!/bin/sh\nexit 0\n", "utf8");
  183. const outputDir = join(root, "out");
  184. const notices = {
  185. thirdParty: "Copyright npm\nComplete terms\n",
  186. node: "Copyright Node\nComplete runtime terms\n",
  187. nodeSource: '{"version":"22.16.0"}\n',
  188. };
  189. return {
  190. distDir,
  191. workspaceNodeModulesDir,
  192. agentBundlePath,
  193. bundledSkillsDir,
  194. nodeBinaryPath,
  195. outputDir,
  196. notices,
  197. };
  198. }
  199. async function writeFakeNativeTools(
  200. toolsDir: string,
  201. tools: Record<string, string>,
  202. ): Promise<void> {
  203. for (const [tool, binaryName] of Object.entries(tools)) {
  204. await mkdir(join(toolsDir, tool), { recursive: true });
  205. await writeFile(join(toolsDir, tool, binaryName), tool, "utf8");
  206. await writeFile(
  207. join(toolsDir, tool, "THIRD-PARTY-NOTICES.txt"),
  208. `Copyright ${tool}\nFull terms\n`,
  209. "utf8",
  210. );
  211. await writeFile(join(toolsDir, tool, "SOURCES.json"), JSON.stringify({ tool }), "utf8");
  212. }
  213. }
  214. it("assembles the release layout for a linux target", async () => {
  215. const fixture = await makeStageFixture();
  216. const staged = await stageRelease({
  217. target: "linux-x64",
  218. appVersion: "9.9.9-test",
  219. archive: false,
  220. ...fixture,
  221. });
  222. const releaseDir = staged.releaseDir;
  223. expect(releaseDir.endsWith("zcode-server-linux-x64")).toBe(true);
  224. const launcher = await readFile(join(releaseDir, "bin", "zcode"), "utf8");
  225. expect(launcher).toContain('"$DIR/runtime/node"');
  226. expect(launcher).toContain('"$DIR/runtime/server-cli.js"');
  227. const launcherStat = await stat(join(releaseDir, "bin", "zcode"));
  228. // Bugfix: NTFS 不保留 POSIX exec 位(Windows 上 stat.mode 恒无 0o111 位),
  229. // 可执行性断言只在 POSIX 宿主上生效;Windows 宿主仍验证文件存在与内容。
  230. if (process.platform !== "win32") expect(launcherStat.mode & 0o111).not.toBe(0);
  231. const runtimePackageJson = JSON.parse(
  232. await readFile(join(releaseDir, "runtime", "package.json"), "utf8"),
  233. ) as { type?: string };
  234. expect(runtimePackageJson.type).toBe("module");
  235. for (const relativePath of [
  236. "runtime/server-cli.js",
  237. "runtime/server-core.js",
  238. "runtime/zcode.cjs",
  239. "runtime/node",
  240. "runtime/node_modules/fake-dep/package.json",
  241. "runtime/node_modules/fake-transitive/package.json",
  242. "runtime/node_modules/node-pty/lib/index.js",
  243. "runtime/node_modules/node-pty/LICENSE",
  244. "runtime/THIRD-PARTY-NOTICES.md",
  245. "runtime/LICENSE.node.txt",
  246. "runtime/NODE-SOURCES.json",
  247. "runtime/licenses/agent/THIRD-PARTY-NOTICES.md",
  248. "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node",
  249. ]) {
  250. await expect(stat(join(releaseDir, ...relativePath.split("/")))).resolves.toBeTruthy();
  251. }
  252. const nodeStat = await stat(join(releaseDir, "runtime", "node"));
  253. // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
  254. if (process.platform !== "win32") expect(nodeStat.mode & 0o111).not.toBe(0);
  255. // 交叉打包安全性:宿主编译产物与非目标平台 prebuilds 不进入发行包。
  256. await expect(stat(join(releaseDir, "runtime/node_modules/node-pty/build"))).rejects.toThrow();
  257. await expect(
  258. stat(join(releaseDir, "runtime/node_modules/node-pty/prebuilds/darwin-arm64")),
  259. ).rejects.toThrow();
  260. // linux 平台 pty.node 由 @lydell 平台包补齐。
  261. const linuxPty = await readFile(
  262. join(releaseDir, "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node"),
  263. "utf8",
  264. );
  265. expect(linuxPty).toBe("linux-binary");
  266. const manifest = JSON.parse(await readFile(join(releaseDir, "manifest.json"), "utf8")) as {
  267. product: string;
  268. target: string;
  269. appVersion: string;
  270. nodeVersion: string;
  271. entrypoints: { cli: string; core: string; agent: string };
  272. };
  273. expect(manifest.product).toBe("zcode-server");
  274. expect(manifest.target).toBe("linux-x64");
  275. expect(manifest.appVersion).toBe("9.9.9-test");
  276. expect(manifest.nodeVersion).toBe("22.16.0");
  277. expect(manifest.entrypoints).toEqual({
  278. cli: "runtime/server-cli.js",
  279. core: "runtime/server-core.js",
  280. agent: "runtime/zcode.cjs",
  281. });
  282. expect(staged.packagedDependencies).toEqual(["fake-dep", "fake-transitive", "node-pty"]);
  283. expect(staged.archivePath).toBeNull();
  284. });
  285. it("keeps official darwin prebuilds including spawn-helper for darwin targets", async () => {
  286. const fixture = await makeStageFixture();
  287. const staged = await stageRelease({
  288. target: "darwin-arm64",
  289. appVersion: "9.9.9-test",
  290. archive: false,
  291. ...fixture,
  292. });
  293. const prebuildDir = join(
  294. staged.releaseDir,
  295. "runtime/node_modules/node-pty/prebuilds/darwin-arm64",
  296. );
  297. await expect(stat(join(prebuildDir, "pty.node"))).resolves.toBeTruthy();
  298. const helperStat = await stat(join(prebuildDir, "spawn-helper"));
  299. // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
  300. if (process.platform !== "win32") expect(helperStat.mode & 0o111).not.toBe(0);
  301. });
  302. it("stages a Windows target with a cmd launcher and zip archive", async () => {
  303. const fixture = await makeStageFixture();
  304. const toolsDir = join(await makeTempDir(), "tools");
  305. await writeFakeNativeTools(toolsDir, { ripgrep: "rg.exe", ugrep: "ugrep.exe" });
  306. const staged = await stageRelease({
  307. target: "win32-x64",
  308. appVersion: "9.9.9-test",
  309. nativeToolsDir: toolsDir,
  310. ...fixture,
  311. });
  312. expect(staged.archivePath).toMatch(/\.zip$/u);
  313. expect(await readFile(join(staged.releaseDir, "bin", "zcode.cmd"), "utf8")).toContain(
  314. "node.exe",
  315. );
  316. await expect(stat(join(staged.releaseDir, "runtime", "node.exe"))).resolves.toBeTruthy();
  317. await expect(
  318. stat(join(staged.releaseDir, "runtime", "tools", "ripgrep", "rg.exe")),
  319. ).resolves.toBeTruthy();
  320. await expect(
  321. stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "ugrep.exe")),
  322. ).resolves.toBeTruthy();
  323. await expect(
  324. stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "THIRD-PARTY-NOTICES.txt")),
  325. ).resolves.toBeTruthy();
  326. await expect(stat(join(staged.releaseDir, "runtime", "tools", "bfs"))).rejects.toThrow();
  327. });
  328. it("每个可独立下载的组件归档都携带适用的第三方声明", async () => {
  329. const fixture = await makeStageFixture();
  330. const toolsDir = join(await makeTempDir(), "tools");
  331. await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
  332. const staged = await stageRelease({
  333. target: "linux-x64",
  334. appVersion: "9.9.9-test",
  335. nativeToolsDir: toolsDir,
  336. ...fixture,
  337. });
  338. const manifest = JSON.parse(
  339. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  340. ) as {
  341. components: Array<{ id: string; archivePath: string }>;
  342. };
  343. const expected: Record<string, string[]> = {
  344. "node-runtime": ["runtime/LICENSE.node.txt", "runtime/NODE-SOURCES.json"],
  345. "server-runtime": ["runtime/THIRD-PARTY-NOTICES.md", "runtime/node_modules/node-pty/LICENSE"],
  346. "agent-runtime": ["runtime/licenses/agent/THIRD-PARTY-NOTICES.md"],
  347. "native-search-tools": [
  348. "runtime/tools/ripgrep/THIRD-PARTY-NOTICES.txt",
  349. "runtime/tools/ugrep/SOURCES.json",
  350. ],
  351. };
  352. expect(manifest.components.map((component) => component.id).sort()).toEqual(
  353. Object.keys(expected).sort(),
  354. );
  355. const extractRoot = await makeTempDir();
  356. for (const component of manifest.components) {
  357. const extractDir = join(extractRoot, component.id);
  358. await mkdir(extractDir, { recursive: true });
  359. await runTar(["-xf", join(fixture.outputDir, component.archivePath), "-C", extractDir]);
  360. for (const member of expected[component.id] ?? []) {
  361. expect(await readFile(join(extractDir, member))).toEqual(
  362. await readFile(join(staged.releaseDir, member)),
  363. );
  364. }
  365. }
  366. });
  367. it.each([true, false])(
  368. "工具目录缺少声明或声明参数为空时拒绝组装发行包(componentArchives=%s)",
  369. async (componentArchives) => {
  370. const fixture = await makeStageFixture();
  371. const toolsDir = join(await makeTempDir(), "tools");
  372. await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
  373. await rm(join(toolsDir, "ripgrep", "THIRD-PARTY-NOTICES.txt"));
  374. await expect(
  375. stageRelease({
  376. target: "linux-x64",
  377. appVersion: "9.9.9-test",
  378. archive: false,
  379. nativeToolsDir: toolsDir,
  380. componentArchives,
  381. ...fixture,
  382. }),
  383. ).rejects.toThrow(/ENOENT/u);
  384. await expect(
  385. stageRelease({
  386. target: "linux-x64",
  387. appVersion: "9.9.9-test",
  388. archive: false,
  389. ...fixture,
  390. notices: { ...fixture.notices, node: " " },
  391. componentArchives,
  392. }),
  393. ).rejects.toThrow(/Missing distribution notice: node/u);
  394. },
  395. );
  396. macIt("omits macOS extended attributes from POSIX release archives", async () => {
  397. const fixture = await makeStageFixture();
  398. await execFileAsync("xattr", ["-w", "com.example.zcode", "value", fixture.nodeBinaryPath]);
  399. const staged = await stageRelease({
  400. target: "linux-x64",
  401. appVersion: "9.9.9-test",
  402. ...fixture,
  403. });
  404. const archive = gunzipSync(await readFile(staged.archivePath ?? ""));
  405. const tarText = archive.toString("latin1");
  406. expect(tarText).not.toContain("LIBARCHIVE.xattr");
  407. expect(tarText).not.toContain("SCHILY.xattr");
  408. });
  409. it("bundled workflow skills ship in the agent component and affect its hash", async () => {
  410. const fixture = await makeStageFixture();
  411. const officialPluginsDir = join(await makeTempDir(), "packages");
  412. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  413. const options = {
  414. ...fixture,
  415. officialPluginsDir,
  416. target: "linux-x64" as const,
  417. appVersion: "test",
  418. archive: false,
  419. };
  420. const staged = await stageRelease(options);
  421. const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
  422. const component = manifest.components.find(
  423. (entry: { id: string }) => entry.id === "agent-runtime",
  424. );
  425. expect(component.paths).toContain("runtime/packages/bundled-skills");
  426. expect(manifest.plugins).not.toContain("bundled-skills");
  427. const archive = gunzipSync(
  428. await readFile(join(fixture.outputDir, component.archivePath)),
  429. ).toString("utf8");
  430. for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
  431. expect(
  432. await readFile(
  433. join(staged.releaseDir, "runtime/packages/bundled-skills/skills/dynamic-workflows", name),
  434. "utf8",
  435. ),
  436. ).toBe(`fixture ${name}`);
  437. expect(archive).toContain(`fixture ${name}`);
  438. }
  439. await writeFile(
  440. join(fixture.bundledSkillsDir, "skills/dynamic-workflows/examples.md"),
  441. "updated example",
  442. );
  443. const updated = await stageRelease(options);
  444. const next = JSON.parse(await readFile(join(updated.releaseDir, "manifest.json"), "utf8"));
  445. expect(
  446. next.components.find((entry: { id: string }) => entry.id === "agent-runtime").sha256,
  447. ).not.toBe(component.sha256);
  448. expect(
  449. next.components.find((entry: { id: string }) => entry.id === "official-plugins").sha256,
  450. ).toBe(
  451. manifest.components.find((entry: { id: string }) => entry.id === "official-plugins").sha256,
  452. );
  453. });
  454. it.each(["SKILL.md", "patterns.md", "examples.md", "entire-pack"])(
  455. "rejects missing bundled skill asset %s",
  456. async (missing) => {
  457. const fixture = await makeStageFixture();
  458. await rm(
  459. missing === "entire-pack"
  460. ? fixture.bundledSkillsDir
  461. : join(fixture.bundledSkillsDir, "skills/dynamic-workflows", missing),
  462. { recursive: true },
  463. );
  464. await expect(
  465. stageRelease({ ...fixture, target: "linux-x64", appVersion: "test", archive: false }),
  466. ).rejects.toThrow(/bundled skill/i);
  467. },
  468. );
  469. async function writeOfficialPluginFixture(
  470. officialPluginsDir: string,
  471. name: string,
  472. options: { mcpEntry?: string; withMcpEntryFile?: boolean; withManifest?: boolean } = {},
  473. ): Promise<void> {
  474. const pluginDir = join(officialPluginsDir, name);
  475. await mkdir(join(pluginDir, ".zcode-plugin"), { recursive: true });
  476. await writeFile(join(pluginDir, "README.md"), name, "utf8");
  477. // 真实官方插件的 package.json 都是 tracked 文件,是"该目录属于当前 checkout"的判据。
  478. await writeFile(
  479. join(pluginDir, "package.json"),
  480. JSON.stringify({ name: `@zcode/${name}`, private: true }),
  481. "utf8",
  482. );
  483. const manifest: Record<string, unknown> = {
  484. name: name.replace(/-plugin$/u, ""),
  485. version: "0.1.0",
  486. };
  487. if (options.mcpEntry) {
  488. manifest.mcpServers = {
  489. [name]: { command: "node", args: [`\${ZCODE_PLUGIN_ROOT}/${options.mcpEntry}`] },
  490. };
  491. if (options.withMcpEntryFile !== false) {
  492. const entryPath = join(pluginDir, ...options.mcpEntry.split("/"));
  493. await mkdir(join(entryPath, ".."), { recursive: true });
  494. await writeFile(entryPath, "// mcp server\n", "utf8");
  495. }
  496. }
  497. if (options.withManifest !== false) {
  498. await writeFile(
  499. join(pluginDir, ".zcode-plugin", "plugin.json"),
  500. JSON.stringify(manifest),
  501. "utf8",
  502. );
  503. }
  504. }
  505. it.each(["absent", "incomplete", "stale"])(
  506. "stages bundled skills from the agent source when the plugin cache is %s",
  507. async (cacheState) => {
  508. const fixture = await makeStageFixture();
  509. const officialPluginsDir = join(await makeTempDir(), "packages");
  510. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  511. if (cacheState !== "absent") {
  512. const cachedPackDir = join(officialPluginsDir, "bundled-skills");
  513. await mkdir(join(cachedPackDir, "skills/dynamic-workflows"), { recursive: true });
  514. await writeFile(join(cachedPackDir, "README.md"), "old cached pack");
  515. const files =
  516. cacheState === "stale" ? ["SKILL.md", "patterns.md", "examples.md"] : ["SKILL.md"];
  517. for (const name of files) {
  518. await writeFile(
  519. join(cachedPackDir, "skills/dynamic-workflows", name),
  520. "old cached skill",
  521. );
  522. }
  523. }
  524. // 冲突整合时两条复制路径曾并存:插件缓存缺文件会拒绝有效技能包,旧缓存会覆盖 Agent 源。
  525. // 技能包只从 bundledSkillsDir 读取,并只由 agent-runtime 交付。
  526. const staged = await stageRelease({
  527. ...fixture,
  528. target: "linux-x64",
  529. appVersion: "test",
  530. archive: false,
  531. officialPluginsDir,
  532. });
  533. const stagedPackDir = join(staged.releaseDir, "runtime/packages/bundled-skills");
  534. expect(await readFile(join(stagedPackDir, "README.md"), "utf8")).toBe("bundled skills");
  535. for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
  536. expect(await readFile(join(stagedPackDir, "skills/dynamic-workflows", name), "utf8")).toBe(
  537. `fixture ${name}`,
  538. );
  539. }
  540. // 保留发布白名单:本地临时文件不能进入发行包或组件归档。
  541. await expect(stat(join(stagedPackDir, "scratch.txt"))).rejects.toThrow();
  542. const manifest = JSON.parse(
  543. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  544. ) as {
  545. plugins: string[];
  546. components: Array<{ id: string; paths: string[]; archivePath: string }>;
  547. };
  548. expect(manifest.plugins).toEqual(["zcode-guide"]);
  549. const agentComponent = manifest.components.find((entry) => entry.id === "agent-runtime")!;
  550. expect(agentComponent.paths).toContain("runtime/packages/bundled-skills");
  551. const agentExtractDir = await makeTempDir();
  552. await runTar([
  553. "-xf",
  554. join(fixture.outputDir, agentComponent.archivePath),
  555. "-C",
  556. agentExtractDir,
  557. ]);
  558. expect(
  559. await readFile(
  560. join(
  561. agentExtractDir,
  562. "runtime/packages/bundled-skills/skills/dynamic-workflows/SKILL.md",
  563. ),
  564. "utf8",
  565. ),
  566. ).toBe("fixture SKILL.md");
  567. await expect(
  568. stat(join(agentExtractDir, "runtime/packages/bundled-skills/scratch.txt")),
  569. ).rejects.toThrow();
  570. const pluginComponent = manifest.components.find((entry) => entry.id === "official-plugins")!;
  571. const pluginExtractDir = await makeTempDir();
  572. await runTar([
  573. "-xf",
  574. join(fixture.outputDir, pluginComponent.archivePath),
  575. "-C",
  576. pluginExtractDir,
  577. ]);
  578. await expect(
  579. stat(join(pluginExtractDir, "runtime/packages/zcode-guide-plugin")),
  580. ).resolves.toBeTruthy();
  581. await expect(
  582. stat(join(pluginExtractDir, "runtime/packages/bundled-skills")),
  583. ).rejects.toThrow();
  584. },
  585. );
  586. it("stages the official plugin set and excludes the on-demand superpowers package", async () => {
  587. const fixture = await makeStageFixture();
  588. const officialPluginsDir = join(await makeTempDir(), "packages");
  589. const pluginNames = [
  590. "android-emulator-plugin",
  591. "browser-use-plugin",
  592. "document-skills-plugin",
  593. "ios-simulator-plugin",
  594. "restore-legacy-sessions-plugin",
  595. "skill-creator-plugin",
  596. "zcode-guide-plugin",
  597. "superpowers-plugin",
  598. ];
  599. const mcpRuntimePlugins = new Set([
  600. "android-emulator-plugin",
  601. "browser-use-plugin",
  602. "ios-simulator-plugin",
  603. ]);
  604. for (const name of pluginNames) {
  605. await writeOfficialPluginFixture(
  606. officialPluginsDir,
  607. name,
  608. mcpRuntimePlugins.has(name) ? { mcpEntry: "dist/mcp/server.js" } : {},
  609. );
  610. }
  611. const staged = await stageRelease({
  612. target: "linux-x64",
  613. appVersion: "9.9.9-test",
  614. archive: false,
  615. officialPluginsDir,
  616. ...fixture,
  617. });
  618. for (const name of pluginNames.filter((name) => name !== "superpowers-plugin")) {
  619. await expect(
  620. stat(join(staged.releaseDir, "runtime/packages", name, "README.md")),
  621. ).resolves.toBeTruthy();
  622. }
  623. for (const name of mcpRuntimePlugins) {
  624. await expect(
  625. stat(join(staged.releaseDir, "runtime/packages", name, "dist/mcp/server.js")),
  626. ).resolves.toBeTruthy();
  627. }
  628. await expect(
  629. stat(join(staged.releaseDir, "runtime/packages/superpowers-plugin")),
  630. ).rejects.toThrow();
  631. const manifest = JSON.parse(
  632. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  633. ) as {
  634. plugins?: string[];
  635. components?: Array<{ id: string }>;
  636. };
  637. expect(manifest.plugins).toEqual([
  638. "android-emulator",
  639. "browser-use",
  640. "document-skills",
  641. "ios-simulator",
  642. "restore-legacy-sessions",
  643. "skill-creator",
  644. "zcode-guide",
  645. ]);
  646. expect(manifest.components?.some((component) => component.id === "official-plugins")).toBe(
  647. true,
  648. );
  649. });
  650. it.each([true, false])(
  651. "fails closed on a missing MCP entry with componentArchives=%s",
  652. async (componentArchives) => {
  653. // Bug 原因:插件 dist 被 gitignore,干净 CI 工作区里 android-emulator / ios-simulator 没有
  654. // dist/mcp/server.js;legacy prepare-prebuilds.mjs 曾构建并断言该文件,切到 stageRelease 后只剩
  655. // 整目录复制,archive 会静默带上只有 plugin.json 与 skills、缺 MCP 入口的插件。staging 必须以
  656. // plugin.json 的 mcpServers 声明为事实源 fail-closed。
  657. const fixture = await makeStageFixture();
  658. const officialPluginsDir = join(await makeTempDir(), "packages");
  659. await writeOfficialPluginFixture(officialPluginsDir, "android-emulator-plugin", {
  660. mcpEntry: "dist/mcp/server.js",
  661. withMcpEntryFile: false,
  662. });
  663. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  664. await expect(
  665. stageRelease({
  666. target: "linux-x64",
  667. appVersion: "9.9.9-test",
  668. archive: false,
  669. officialPluginsDir,
  670. componentArchives,
  671. ...fixture,
  672. }),
  673. ).rejects.toThrow(/android-emulator-plugin[\s\S]*dist\/mcp\/server\.js/u);
  674. },
  675. );
  676. it("fails closed when a staged official plugin has no plugin manifest", async () => {
  677. const fixture = await makeStageFixture();
  678. const officialPluginsDir = join(await makeTempDir(), "packages");
  679. await writeOfficialPluginFixture(officialPluginsDir, "ios-simulator-plugin", {
  680. withManifest: false,
  681. });
  682. await expect(
  683. stageRelease({
  684. target: "linux-x64",
  685. appVersion: "9.9.9-test",
  686. archive: false,
  687. officialPluginsDir,
  688. ...fixture,
  689. }),
  690. ).rejects.toThrow(/ios-simulator-plugin[\s\S]*plugin\.json/u);
  691. });
  692. it("ignores orphaned *-plugin directories left behind by a previous checkout", async () => {
  693. // Bug 原因:CI 用 GIT_CLEAN_FLAGS "-e node_modules/" 跨 job 保留 node_modules,其它分支
  694. // (例如曾把 zcode-cua-plugin 改名为 computer-use-plugin 的分支)install 过的插件目录切回本
  695. // 分支后只剩 node_modules,tracked 文件全被 checkout 删掉。旧规则仅按 "-plugin" 后缀识别官方
  696. // 插件,会把这种僵尸目录当插件 stage,随后 fail-closed 校验读不到 plugin.json 而整段失败。
  697. const fixture = await makeStageFixture();
  698. const officialPluginsDir = join(await makeTempDir(), "packages");
  699. await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
  700. const orphanDir = join(officialPluginsDir, "computer-use-plugin");
  701. await mkdir(join(orphanDir, "node_modules", "@zcode", "computer-use"), { recursive: true });
  702. await writeFile(
  703. join(orphanDir, "node_modules", "@zcode", "computer-use", "package.json"),
  704. "{}",
  705. "utf8",
  706. );
  707. const staged = await stageRelease({
  708. target: "linux-x64",
  709. appVersion: "9.9.9-test",
  710. archive: false,
  711. officialPluginsDir,
  712. ...fixture,
  713. });
  714. await expect(
  715. stat(join(staged.releaseDir, "runtime/packages/computer-use-plugin")),
  716. ).rejects.toThrow();
  717. const manifest = JSON.parse(
  718. await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
  719. ) as { plugins?: string[] };
  720. expect(manifest.plugins).toEqual(["zcode-guide"]);
  721. });
  722. it("removes stale component archives before restaging a target", async () => {
  723. const fixture = await makeStageFixture();
  724. const staleDir = join(fixture.outputDir, "components", "linux-x64");
  725. await mkdir(staleDir, { recursive: true });
  726. await writeFile(join(staleDir, "stale-component.tar.gz"), "stale", "utf8");
  727. await stageRelease({
  728. target: "linux-x64",
  729. appVersion: "9.9.9-test",
  730. archive: false,
  731. ...fixture,
  732. });
  733. await expect(stat(join(staleDir, "stale-component.tar.gz"))).rejects.toThrow();
  734. });
  735. it.each(["linux-x64", "linux-arm64"] as const)(
  736. "stages an installable full %s archive without standalone components",
  737. async (target) => {
  738. const fixture = await makeStageFixture();
  739. await writeFakePackage(fixture.workspaceNodeModulesDir, "@lydell/node-pty-linux-arm64", {
  740. files: { "prebuilds/linux-arm64/pty.node": "linux-arm64-binary" },
  741. });
  742. const options = { ...fixture, target, appVersion: "9.9.9-test" };
  743. const original = await stageRelease(options);
  744. expect(original.componentArchivePaths.length).toBeGreaterThan(0);
  745. const expected = JSON.parse(
  746. await readFile(join(original.releaseDir, "manifest.json"), "utf8"),
  747. );
  748. for (const component of expected.components) {
  749. expect(component.archivePath).toBeTruthy();
  750. delete component.archivePath;
  751. }
  752. const staged = await stageRelease({ ...options, componentArchives: false });
  753. expect(staged.componentArchivePaths).toEqual([]);
  754. await expect(stat(join(fixture.outputDir, "components", target))).rejects.toMatchObject({
  755. code: "ENOENT",
  756. });
  757. await expect(stat(join(fixture.outputDir, ".components"))).rejects.toMatchObject({
  758. code: "ENOENT",
  759. });
  760. const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
  761. expect(manifest).toEqual(expected);
  762. // 用真实整包 installer 验证没有组件 archivePath 仍可安装,且整包摘要校验仍会拒绝错误身份。
  763. const { ReleaseInstaller } = await import(
  764. fileURLToPath(new URL("../src/runtime/releaseInstaller.ts", import.meta.url))
  765. );
  766. const { resolveServerLayout } = await import(
  767. fileURLToPath(new URL("../src/runtime/paths.ts", import.meta.url))
  768. );
  769. const installer = new ReleaseInstaller(
  770. resolveServerLayout(join(await makeTempDir(), "server")),
  771. );
  772. const archivePath = staged.archivePath!;
  773. const archiveSha256 = createHash("sha256")
  774. .update(await readFile(archivePath))
  775. .digest("hex");
  776. await expect(
  777. installer.installArchive({ archivePath, target, archiveSha256: "0".repeat(64) }),
  778. ).rejects.toThrow(/checksum mismatch/);
  779. const installed = await installer.installArchive({ archivePath, target, archiveSha256 });
  780. expect(
  781. JSON.parse(await readFile(join(installed.releaseDir, "manifest.json"), "utf8")),
  782. ).toEqual(expected);
  783. expect(await readFile(join(installed.releaseDir, "runtime", "zcode.cjs"))).toEqual(
  784. await readFile(fixture.agentBundlePath),
  785. );
  786. },
  787. );
  788. });