packaging.test.ts 37 KB

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