| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844 |
- import { execFile } from "node:child_process";
- import { createHash } from "node:crypto";
- import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { fileURLToPath } from "node:url";
- import { promisify } from "node:util";
- import { gunzipSync } from "node:zlib";
- import { afterEach, describe, expect, it } from "vitest";
- import {
- collectBareModuleSpecifiers,
- isNodePtyRuntimePath,
- resolveProductionPackageClosure,
- stageRelease,
- } from "../src/packaging/stage.js";
- import { resolveHostTarCommand } from "../src/packaging/tarCommand.js";
- const execFileAsync = promisify(execFile);
- async function runTar(args: string[]): Promise<void> {
- await execFileAsync(resolveHostTarCommand(), args);
- }
- const temporaryDirs: string[] = [];
- const macIt = process.platform === "darwin" ? it : it.skip;
- async function makeTempDir(): Promise<string> {
- const dir = await mkdtemp(join(tmpdir(), "zcode-server-stage-test-"));
- temporaryDirs.push(dir);
- return dir;
- }
- afterEach(async () => {
- await Promise.all(
- temporaryDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })),
- );
- });
- interface FakePackageSpec {
- dependencies?: Record<string, string>;
- optionalDependencies?: Record<string, string>;
- devDependencies?: Record<string, string>;
- files?: Record<string, string>;
- }
- async function writeFakePackage(
- nodeModulesDir: string,
- name: string,
- spec: FakePackageSpec = {},
- ): Promise<string> {
- const packageDir = join(nodeModulesDir, ...name.split("/"));
- await mkdir(packageDir, { recursive: true });
- await writeFile(
- join(packageDir, "package.json"),
- JSON.stringify({
- name,
- version: "0.0.1",
- main: "./index.js",
- dependencies: spec.dependencies,
- optionalDependencies: spec.optionalDependencies,
- devDependencies: spec.devDependencies,
- }),
- "utf8",
- );
- await writeFile(join(packageDir, "index.js"), "module.exports = {};\n", "utf8");
- for (const [relativePath, contents] of Object.entries(spec.files ?? {})) {
- const filePath = join(packageDir, ...relativePath.split("/"));
- await mkdir(join(filePath, ".."), { recursive: true });
- await writeFile(filePath, contents, "utf8");
- }
- return packageDir;
- }
- describe("collectBareModuleSpecifiers", () => {
- it("extracts bare imports, dynamic imports and requires as package names", () => {
- const source = [
- 'import { Hono } from "hono";',
- 'import { serve } from "@hono/node-server";',
- 'const pty = await import("node-pty");',
- 'const utils = require("node-pty/lib/utils");',
- ].join("\n");
- const names = collectBareModuleSpecifiers(source);
- expect(names).toContain("hono");
- expect(names).toContain("@hono/node-server");
- expect(names).toContain("node-pty");
- });
- it("ignores node builtins and relative specifiers", () => {
- const source = [
- 'import { readFile } from "node:fs/promises";',
- 'import local from "./local.js";',
- 'import parent from "../parent.js";',
- ].join("\n");
- expect(collectBareModuleSpecifiers(source).size).toBe(0);
- });
- });
- describe("resolveProductionPackageClosure", () => {
- it("collects transitive production dependencies but not dev dependencies", async () => {
- const root = await makeTempDir();
- const nodeModulesDir = join(root, "node_modules");
- await writeFakePackage(nodeModulesDir, "pkg-a", {
- dependencies: { "pkg-b": "*" },
- devDependencies: { "pkg-dev": "*" },
- });
- await writeFakePackage(nodeModulesDir, "pkg-b", {
- dependencies: { "@scope/pkg-c": "*" },
- });
- await writeFakePackage(nodeModulesDir, "@scope/pkg-c");
- await writeFakePackage(nodeModulesDir, "pkg-dev");
- const closure = await resolveProductionPackageClosure(["pkg-a"], nodeModulesDir);
- expect([...closure.keys()].sort()).toEqual(["@scope/pkg-c", "pkg-a", "pkg-b"]);
- });
- it("skips missing optional dependencies and unknown entry packages", async () => {
- const root = await makeTempDir();
- const nodeModulesDir = join(root, "node_modules");
- await writeFakePackage(nodeModulesDir, "pkg-a", {
- optionalDependencies: { "pkg-missing-optional": "*" },
- });
- const closure = await resolveProductionPackageClosure(
- ["pkg-a", "pkg-not-installed"],
- nodeModulesDir,
- );
- expect([...closure.keys()]).toEqual(["pkg-a"]);
- });
- });
- describe("isNodePtyRuntimePath", () => {
- it("keeps runtime files and the target platform prebuild only", () => {
- expect(isNodePtyRuntimePath("package.json", "linux-x64")).toBe(true);
- expect(isNodePtyRuntimePath("lib/index.js", "linux-x64")).toBe(true);
- expect(isNodePtyRuntimePath("typings/node-pty.d.ts", "linux-x64")).toBe(true);
- expect(isNodePtyRuntimePath("prebuilds/linux-x64/pty.node", "linux-x64")).toBe(true);
- expect(isNodePtyRuntimePath("LICENSE", "linux-x64")).toBe(true);
- });
- it("drops host build outputs, sources and other platform prebuilds", () => {
- expect(isNodePtyRuntimePath("build/Release/pty.node", "linux-x64")).toBe(false);
- expect(isNodePtyRuntimePath("build/Debug/pty.node", "linux-x64")).toBe(false);
- expect(isNodePtyRuntimePath("prebuilds/darwin-arm64/pty.node", "linux-x64")).toBe(false);
- expect(isNodePtyRuntimePath("src/unix/pty.cc", "linux-x64")).toBe(false);
- expect(isNodePtyRuntimePath("deps/winpty/x.h", "linux-x64")).toBe(false);
- expect(isNodePtyRuntimePath("scripts/post-install.js", "linux-x64")).toBe(false);
- });
- });
- describe("stageRelease", () => {
- async function makeStageFixture(): Promise<{
- distDir: string;
- workspaceNodeModulesDir: string;
- agentBundlePath: string;
- bundledSkillsDir: string;
- nodeBinaryPath: string;
- outputDir: string;
- notices: { thirdParty: string; node: string; nodeSource: string };
- }> {
- const root = await makeTempDir();
- const distDir = join(root, "dist");
- await mkdir(distDir, { recursive: true });
- await writeFile(
- join(distDir, "server-cli.js"),
- 'import "fake-dep";\nimport "node-pty";\n',
- "utf8",
- );
- await writeFile(join(distDir, "server-core.js"), 'import "node:fs";\n', "utf8");
- const workspaceNodeModulesDir = join(root, "node_modules");
- await writeFakePackage(workspaceNodeModulesDir, "fake-dep", {
- dependencies: { "fake-transitive": "*" },
- });
- await writeFakePackage(workspaceNodeModulesDir, "fake-transitive");
- await writeFakePackage(workspaceNodeModulesDir, "node-pty", {
- files: {
- LICENSE: "node-pty license\n",
- "lib/index.js": "module.exports = {};\n",
- "typings/node-pty.d.ts": "export {};\n",
- "build/Release/pty.node": "host-binary",
- "prebuilds/darwin-arm64/pty.node": "darwin-binary",
- "prebuilds/darwin-arm64/spawn-helper": "darwin-helper",
- "prebuilds/win32-x64/pty.node": "windows-binary",
- },
- });
- await writeFakePackage(workspaceNodeModulesDir, "@lydell/node-pty-linux-x64", {
- files: { "prebuilds/linux-x64/pty.node": "linux-binary" },
- });
- const bundledSkillsDir = join(root, "bundled-skills");
- await mkdir(join(bundledSkillsDir, "skills/dynamic-workflows"), { recursive: true });
- await writeFile(join(bundledSkillsDir, "README.md"), "bundled skills");
- await writeFile(join(bundledSkillsDir, "scratch.txt"), "local only");
- for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
- await writeFile(join(bundledSkillsDir, "skills/dynamic-workflows", name), `fixture ${name}`);
- }
- const agentBundlePath = join(root, "zcode.cjs");
- await writeFile(agentBundlePath, "// fake agent bundle\n", "utf8");
- const nodeBinaryPath = join(root, "node-binary");
- await writeFile(nodeBinaryPath, "#!/bin/sh\nexit 0\n", "utf8");
- const outputDir = join(root, "out");
- const notices = {
- thirdParty: "Copyright npm\nComplete terms\n",
- node: "Copyright Node\nComplete runtime terms\n",
- nodeSource: '{"version":"22.16.0"}\n',
- };
- return {
- distDir,
- workspaceNodeModulesDir,
- agentBundlePath,
- bundledSkillsDir,
- nodeBinaryPath,
- outputDir,
- notices,
- };
- }
- async function writeFakeNativeTools(
- toolsDir: string,
- tools: Record<string, string>,
- ): Promise<void> {
- for (const [tool, binaryName] of Object.entries(tools)) {
- await mkdir(join(toolsDir, tool), { recursive: true });
- await writeFile(join(toolsDir, tool, binaryName), tool, "utf8");
- await writeFile(
- join(toolsDir, tool, "THIRD-PARTY-NOTICES.txt"),
- `Copyright ${tool}\nFull terms\n`,
- "utf8",
- );
- await writeFile(join(toolsDir, tool, "SOURCES.json"), JSON.stringify({ tool }), "utf8");
- }
- }
- it("assembles the release layout for a linux target", async () => {
- const fixture = await makeStageFixture();
- const staged = await stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- ...fixture,
- });
- const releaseDir = staged.releaseDir;
- expect(releaseDir.endsWith("zcode-server-linux-x64")).toBe(true);
- const launcher = await readFile(join(releaseDir, "bin", "zcode"), "utf8");
- expect(launcher).toContain('"$DIR/runtime/node"');
- expect(launcher).toContain('"$DIR/runtime/server-cli.js"');
- const launcherStat = await stat(join(releaseDir, "bin", "zcode"));
- // Bugfix: NTFS 不保留 POSIX exec 位(Windows 上 stat.mode 恒无 0o111 位),
- // 可执行性断言只在 POSIX 宿主上生效;Windows 宿主仍验证文件存在与内容。
- if (process.platform !== "win32") expect(launcherStat.mode & 0o111).not.toBe(0);
- const runtimePackageJson = JSON.parse(
- await readFile(join(releaseDir, "runtime", "package.json"), "utf8"),
- ) as { type?: string };
- expect(runtimePackageJson.type).toBe("module");
- for (const relativePath of [
- "runtime/server-cli.js",
- "runtime/server-core.js",
- "runtime/zcode.cjs",
- "runtime/node",
- "runtime/node_modules/fake-dep/package.json",
- "runtime/node_modules/fake-transitive/package.json",
- "runtime/node_modules/node-pty/lib/index.js",
- "runtime/node_modules/node-pty/LICENSE",
- "runtime/THIRD-PARTY-NOTICES.md",
- "runtime/LICENSE.node.txt",
- "runtime/NODE-SOURCES.json",
- "runtime/licenses/agent/THIRD-PARTY-NOTICES.md",
- "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node",
- ]) {
- await expect(stat(join(releaseDir, ...relativePath.split("/")))).resolves.toBeTruthy();
- }
- const nodeStat = await stat(join(releaseDir, "runtime", "node"));
- // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
- if (process.platform !== "win32") expect(nodeStat.mode & 0o111).not.toBe(0);
- // 交叉打包安全性:宿主编译产物与非目标平台 prebuilds 不进入发行包。
- await expect(stat(join(releaseDir, "runtime/node_modules/node-pty/build"))).rejects.toThrow();
- await expect(
- stat(join(releaseDir, "runtime/node_modules/node-pty/prebuilds/darwin-arm64")),
- ).rejects.toThrow();
- // linux 平台 pty.node 由 @lydell 平台包补齐。
- const linuxPty = await readFile(
- join(releaseDir, "runtime/node_modules/node-pty/prebuilds/linux-x64/pty.node"),
- "utf8",
- );
- expect(linuxPty).toBe("linux-binary");
- const manifest = JSON.parse(await readFile(join(releaseDir, "manifest.json"), "utf8")) as {
- product: string;
- target: string;
- appVersion: string;
- nodeVersion: string;
- entrypoints: { cli: string; core: string; agent: string };
- };
- expect(manifest.product).toBe("zcode-server");
- expect(manifest.target).toBe("linux-x64");
- expect(manifest.appVersion).toBe("9.9.9-test");
- expect(manifest.nodeVersion).toBe("22.16.0");
- expect(manifest.entrypoints).toEqual({
- cli: "runtime/server-cli.js",
- core: "runtime/server-core.js",
- agent: "runtime/zcode.cjs",
- });
- expect(staged.packagedDependencies).toEqual(["fake-dep", "fake-transitive", "node-pty"]);
- expect(staged.archivePath).toBeNull();
- });
- it("keeps official darwin prebuilds including spawn-helper for darwin targets", async () => {
- const fixture = await makeStageFixture();
- const staged = await stageRelease({
- target: "darwin-arm64",
- appVersion: "9.9.9-test",
- archive: false,
- ...fixture,
- });
- const prebuildDir = join(
- staged.releaseDir,
- "runtime/node_modules/node-pty/prebuilds/darwin-arm64",
- );
- await expect(stat(join(prebuildDir, "pty.node"))).resolves.toBeTruthy();
- const helperStat = await stat(join(prebuildDir, "spawn-helper"));
- // Bugfix: 同上,NTFS 无 POSIX exec 位,可执行性断言只在 POSIX 宿主生效。
- if (process.platform !== "win32") expect(helperStat.mode & 0o111).not.toBe(0);
- });
- it("stages a Windows target with a cmd launcher and zip archive", async () => {
- const fixture = await makeStageFixture();
- const toolsDir = join(await makeTempDir(), "tools");
- await writeFakeNativeTools(toolsDir, { ripgrep: "rg.exe", ugrep: "ugrep.exe" });
- const staged = await stageRelease({
- target: "win32-x64",
- appVersion: "9.9.9-test",
- nativeToolsDir: toolsDir,
- ...fixture,
- });
- expect(staged.archivePath).toMatch(/\.zip$/u);
- expect(await readFile(join(staged.releaseDir, "bin", "zcode.cmd"), "utf8")).toContain(
- "node.exe",
- );
- await expect(stat(join(staged.releaseDir, "runtime", "node.exe"))).resolves.toBeTruthy();
- await expect(
- stat(join(staged.releaseDir, "runtime", "tools", "ripgrep", "rg.exe")),
- ).resolves.toBeTruthy();
- await expect(
- stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "ugrep.exe")),
- ).resolves.toBeTruthy();
- await expect(
- stat(join(staged.releaseDir, "runtime", "tools", "ugrep", "THIRD-PARTY-NOTICES.txt")),
- ).resolves.toBeTruthy();
- await expect(stat(join(staged.releaseDir, "runtime", "tools", "bfs"))).rejects.toThrow();
- });
- it("每个可独立下载的组件归档都携带适用的第三方声明", async () => {
- const fixture = await makeStageFixture();
- const toolsDir = join(await makeTempDir(), "tools");
- await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
- const staged = await stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- nativeToolsDir: toolsDir,
- ...fixture,
- });
- const manifest = JSON.parse(
- await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
- ) as {
- components: Array<{ id: string; archivePath: string }>;
- };
- const expected: Record<string, string[]> = {
- "node-runtime": ["runtime/LICENSE.node.txt", "runtime/NODE-SOURCES.json"],
- "server-runtime": ["runtime/THIRD-PARTY-NOTICES.md", "runtime/node_modules/node-pty/LICENSE"],
- "agent-runtime": ["runtime/licenses/agent/THIRD-PARTY-NOTICES.md"],
- "native-search-tools": [
- "runtime/tools/ripgrep/THIRD-PARTY-NOTICES.txt",
- "runtime/tools/ugrep/SOURCES.json",
- ],
- };
- expect(manifest.components.map((component) => component.id).sort()).toEqual(
- Object.keys(expected).sort(),
- );
- const extractRoot = await makeTempDir();
- for (const component of manifest.components) {
- const extractDir = join(extractRoot, component.id);
- await mkdir(extractDir, { recursive: true });
- await runTar(["-xf", join(fixture.outputDir, component.archivePath), "-C", extractDir]);
- for (const member of expected[component.id] ?? []) {
- expect(await readFile(join(extractDir, member))).toEqual(
- await readFile(join(staged.releaseDir, member)),
- );
- }
- }
- });
- it.each([true, false])(
- "工具目录缺少声明或声明参数为空时拒绝组装发行包(componentArchives=%s)",
- async (componentArchives) => {
- const fixture = await makeStageFixture();
- const toolsDir = join(await makeTempDir(), "tools");
- await writeFakeNativeTools(toolsDir, { bfs: "bfs", ripgrep: "rg", ugrep: "ugrep" });
- await rm(join(toolsDir, "ripgrep", "THIRD-PARTY-NOTICES.txt"));
- await expect(
- stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- nativeToolsDir: toolsDir,
- componentArchives,
- ...fixture,
- }),
- ).rejects.toThrow(/ENOENT/u);
- await expect(
- stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- ...fixture,
- notices: { ...fixture.notices, node: " " },
- componentArchives,
- }),
- ).rejects.toThrow(/Missing distribution notice: node/u);
- },
- );
- macIt("omits macOS extended attributes from POSIX release archives", async () => {
- const fixture = await makeStageFixture();
- await execFileAsync("xattr", ["-w", "com.example.zcode", "value", fixture.nodeBinaryPath]);
- const staged = await stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- ...fixture,
- });
- const archive = gunzipSync(await readFile(staged.archivePath ?? ""));
- const tarText = archive.toString("latin1");
- expect(tarText).not.toContain("LIBARCHIVE.xattr");
- expect(tarText).not.toContain("SCHILY.xattr");
- });
- it("bundled workflow skills ship in the agent component and affect its hash", async () => {
- const fixture = await makeStageFixture();
- const officialPluginsDir = join(await makeTempDir(), "packages");
- await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
- const options = {
- ...fixture,
- officialPluginsDir,
- target: "linux-x64" as const,
- appVersion: "test",
- archive: false,
- };
- const staged = await stageRelease(options);
- const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
- const component = manifest.components.find(
- (entry: { id: string }) => entry.id === "agent-runtime",
- );
- expect(component.paths).toContain("runtime/packages/bundled-skills");
- expect(manifest.plugins).not.toContain("bundled-skills");
- const archive = gunzipSync(
- await readFile(join(fixture.outputDir, component.archivePath)),
- ).toString("utf8");
- for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
- expect(
- await readFile(
- join(staged.releaseDir, "runtime/packages/bundled-skills/skills/dynamic-workflows", name),
- "utf8",
- ),
- ).toBe(`fixture ${name}`);
- expect(archive).toContain(`fixture ${name}`);
- }
- await writeFile(
- join(fixture.bundledSkillsDir, "skills/dynamic-workflows/examples.md"),
- "updated example",
- );
- const updated = await stageRelease(options);
- const next = JSON.parse(await readFile(join(updated.releaseDir, "manifest.json"), "utf8"));
- expect(
- next.components.find((entry: { id: string }) => entry.id === "agent-runtime").sha256,
- ).not.toBe(component.sha256);
- expect(
- next.components.find((entry: { id: string }) => entry.id === "official-plugins").sha256,
- ).toBe(
- manifest.components.find((entry: { id: string }) => entry.id === "official-plugins").sha256,
- );
- });
- it.each(["SKILL.md", "patterns.md", "examples.md", "entire-pack"])(
- "rejects missing bundled skill asset %s",
- async (missing) => {
- const fixture = await makeStageFixture();
- await rm(
- missing === "entire-pack"
- ? fixture.bundledSkillsDir
- : join(fixture.bundledSkillsDir, "skills/dynamic-workflows", missing),
- { recursive: true },
- );
- await expect(
- stageRelease({ ...fixture, target: "linux-x64", appVersion: "test", archive: false }),
- ).rejects.toThrow(/bundled skill/i);
- },
- );
- async function writeOfficialPluginFixture(
- officialPluginsDir: string,
- name: string,
- options: { mcpEntry?: string; withMcpEntryFile?: boolean; withManifest?: boolean } = {},
- ): Promise<void> {
- const pluginDir = join(officialPluginsDir, name);
- await mkdir(join(pluginDir, ".zcode-plugin"), { recursive: true });
- await writeFile(join(pluginDir, "README.md"), name, "utf8");
- // 真实官方插件的 package.json 都是 tracked 文件,是"该目录属于当前 checkout"的判据。
- await writeFile(
- join(pluginDir, "package.json"),
- JSON.stringify({ name: `@zcode/${name}`, private: true }),
- "utf8",
- );
- const manifest: Record<string, unknown> = {
- name: name.replace(/-plugin$/u, ""),
- version: "0.1.0",
- };
- if (options.mcpEntry) {
- manifest.mcpServers = {
- [name]: { command: "node", args: [`\${ZCODE_PLUGIN_ROOT}/${options.mcpEntry}`] },
- };
- if (options.withMcpEntryFile !== false) {
- const entryPath = join(pluginDir, ...options.mcpEntry.split("/"));
- await mkdir(join(entryPath, ".."), { recursive: true });
- await writeFile(entryPath, "// mcp server\n", "utf8");
- }
- }
- if (options.withManifest !== false) {
- await writeFile(
- join(pluginDir, ".zcode-plugin", "plugin.json"),
- JSON.stringify(manifest),
- "utf8",
- );
- }
- }
- it.each(["absent", "incomplete", "stale"])(
- "stages bundled skills from the agent source when the plugin cache is %s",
- async (cacheState) => {
- const fixture = await makeStageFixture();
- const officialPluginsDir = join(await makeTempDir(), "packages");
- await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
- if (cacheState !== "absent") {
- const cachedPackDir = join(officialPluginsDir, "bundled-skills");
- await mkdir(join(cachedPackDir, "skills/dynamic-workflows"), { recursive: true });
- await writeFile(join(cachedPackDir, "README.md"), "old cached pack");
- const files =
- cacheState === "stale" ? ["SKILL.md", "patterns.md", "examples.md"] : ["SKILL.md"];
- for (const name of files) {
- await writeFile(
- join(cachedPackDir, "skills/dynamic-workflows", name),
- "old cached skill",
- );
- }
- }
- // 冲突整合时两条复制路径曾并存:插件缓存缺文件会拒绝有效技能包,旧缓存会覆盖 Agent 源。
- // 技能包只从 bundledSkillsDir 读取,并只由 agent-runtime 交付。
- const staged = await stageRelease({
- ...fixture,
- target: "linux-x64",
- appVersion: "test",
- archive: false,
- officialPluginsDir,
- });
- const stagedPackDir = join(staged.releaseDir, "runtime/packages/bundled-skills");
- expect(await readFile(join(stagedPackDir, "README.md"), "utf8")).toBe("bundled skills");
- for (const name of ["SKILL.md", "patterns.md", "examples.md"]) {
- expect(await readFile(join(stagedPackDir, "skills/dynamic-workflows", name), "utf8")).toBe(
- `fixture ${name}`,
- );
- }
- // 保留发布白名单:本地临时文件不能进入发行包或组件归档。
- await expect(stat(join(stagedPackDir, "scratch.txt"))).rejects.toThrow();
- const manifest = JSON.parse(
- await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
- ) as {
- plugins: string[];
- components: Array<{ id: string; paths: string[]; archivePath: string }>;
- };
- expect(manifest.plugins).toEqual(["zcode-guide"]);
- const agentComponent = manifest.components.find((entry) => entry.id === "agent-runtime")!;
- expect(agentComponent.paths).toContain("runtime/packages/bundled-skills");
- const agentExtractDir = await makeTempDir();
- await runTar([
- "-xf",
- join(fixture.outputDir, agentComponent.archivePath),
- "-C",
- agentExtractDir,
- ]);
- expect(
- await readFile(
- join(
- agentExtractDir,
- "runtime/packages/bundled-skills/skills/dynamic-workflows/SKILL.md",
- ),
- "utf8",
- ),
- ).toBe("fixture SKILL.md");
- await expect(
- stat(join(agentExtractDir, "runtime/packages/bundled-skills/scratch.txt")),
- ).rejects.toThrow();
- const pluginComponent = manifest.components.find((entry) => entry.id === "official-plugins")!;
- const pluginExtractDir = await makeTempDir();
- await runTar([
- "-xf",
- join(fixture.outputDir, pluginComponent.archivePath),
- "-C",
- pluginExtractDir,
- ]);
- await expect(
- stat(join(pluginExtractDir, "runtime/packages/zcode-guide-plugin")),
- ).resolves.toBeTruthy();
- await expect(
- stat(join(pluginExtractDir, "runtime/packages/bundled-skills")),
- ).rejects.toThrow();
- },
- );
- it("stages the official plugin set and excludes the on-demand superpowers package", async () => {
- const fixture = await makeStageFixture();
- const officialPluginsDir = join(await makeTempDir(), "packages");
- const pluginNames = [
- "android-emulator-plugin",
- "browser-use-plugin",
- "document-skills-plugin",
- "ios-simulator-plugin",
- "restore-legacy-sessions-plugin",
- "skill-creator-plugin",
- "zcode-guide-plugin",
- "superpowers-plugin",
- ];
- const mcpRuntimePlugins = new Set([
- "android-emulator-plugin",
- "browser-use-plugin",
- "ios-simulator-plugin",
- ]);
- for (const name of pluginNames) {
- await writeOfficialPluginFixture(
- officialPluginsDir,
- name,
- mcpRuntimePlugins.has(name) ? { mcpEntry: "dist/mcp/server.js" } : {},
- );
- }
- const staged = await stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- officialPluginsDir,
- ...fixture,
- });
- for (const name of pluginNames.filter((name) => name !== "superpowers-plugin")) {
- await expect(
- stat(join(staged.releaseDir, "runtime/packages", name, "README.md")),
- ).resolves.toBeTruthy();
- }
- for (const name of mcpRuntimePlugins) {
- await expect(
- stat(join(staged.releaseDir, "runtime/packages", name, "dist/mcp/server.js")),
- ).resolves.toBeTruthy();
- }
- await expect(
- stat(join(staged.releaseDir, "runtime/packages/superpowers-plugin")),
- ).rejects.toThrow();
- const manifest = JSON.parse(
- await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
- ) as {
- plugins?: string[];
- components?: Array<{ id: string }>;
- };
- expect(manifest.plugins).toEqual([
- "android-emulator",
- "browser-use",
- "document-skills",
- "ios-simulator",
- "restore-legacy-sessions",
- "skill-creator",
- "zcode-guide",
- ]);
- expect(manifest.components?.some((component) => component.id === "official-plugins")).toBe(
- true,
- );
- });
- it.each([true, false])(
- "fails closed on a missing MCP entry with componentArchives=%s",
- async (componentArchives) => {
- // Bug 原因:插件 dist 被 gitignore,干净 CI 工作区里 android-emulator / ios-simulator 没有
- // dist/mcp/server.js;legacy prepare-prebuilds.mjs 曾构建并断言该文件,切到 stageRelease 后只剩
- // 整目录复制,archive 会静默带上只有 plugin.json 与 skills、缺 MCP 入口的插件。staging 必须以
- // plugin.json 的 mcpServers 声明为事实源 fail-closed。
- const fixture = await makeStageFixture();
- const officialPluginsDir = join(await makeTempDir(), "packages");
- await writeOfficialPluginFixture(officialPluginsDir, "android-emulator-plugin", {
- mcpEntry: "dist/mcp/server.js",
- withMcpEntryFile: false,
- });
- await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
- await expect(
- stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- officialPluginsDir,
- componentArchives,
- ...fixture,
- }),
- ).rejects.toThrow(/android-emulator-plugin[\s\S]*dist\/mcp\/server\.js/u);
- },
- );
- it("fails closed when a staged official plugin has no plugin manifest", async () => {
- const fixture = await makeStageFixture();
- const officialPluginsDir = join(await makeTempDir(), "packages");
- await writeOfficialPluginFixture(officialPluginsDir, "ios-simulator-plugin", {
- withManifest: false,
- });
- await expect(
- stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- officialPluginsDir,
- ...fixture,
- }),
- ).rejects.toThrow(/ios-simulator-plugin[\s\S]*plugin\.json/u);
- });
- it("ignores orphaned *-plugin directories left behind by a previous checkout", async () => {
- // Bug 原因:CI 用 GIT_CLEAN_FLAGS "-e node_modules/" 跨 job 保留 node_modules,其它分支
- // (例如曾把 zcode-cua-plugin 改名为 computer-use-plugin 的分支)install 过的插件目录切回本
- // 分支后只剩 node_modules,tracked 文件全被 checkout 删掉。旧规则仅按 "-plugin" 后缀识别官方
- // 插件,会把这种僵尸目录当插件 stage,随后 fail-closed 校验读不到 plugin.json 而整段失败。
- const fixture = await makeStageFixture();
- const officialPluginsDir = join(await makeTempDir(), "packages");
- await writeOfficialPluginFixture(officialPluginsDir, "zcode-guide-plugin");
- const orphanDir = join(officialPluginsDir, "computer-use-plugin");
- await mkdir(join(orphanDir, "node_modules", "@zcode", "computer-use"), { recursive: true });
- await writeFile(
- join(orphanDir, "node_modules", "@zcode", "computer-use", "package.json"),
- "{}",
- "utf8",
- );
- const staged = await stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- officialPluginsDir,
- ...fixture,
- });
- await expect(
- stat(join(staged.releaseDir, "runtime/packages/computer-use-plugin")),
- ).rejects.toThrow();
- const manifest = JSON.parse(
- await readFile(join(staged.releaseDir, "manifest.json"), "utf8"),
- ) as { plugins?: string[] };
- expect(manifest.plugins).toEqual(["zcode-guide"]);
- });
- it("removes stale component archives before restaging a target", async () => {
- const fixture = await makeStageFixture();
- const staleDir = join(fixture.outputDir, "components", "linux-x64");
- await mkdir(staleDir, { recursive: true });
- await writeFile(join(staleDir, "stale-component.tar.gz"), "stale", "utf8");
- await stageRelease({
- target: "linux-x64",
- appVersion: "9.9.9-test",
- archive: false,
- ...fixture,
- });
- await expect(stat(join(staleDir, "stale-component.tar.gz"))).rejects.toThrow();
- });
- it.each(["linux-x64", "linux-arm64"] as const)(
- "stages an installable full %s archive without standalone components",
- async (target) => {
- const fixture = await makeStageFixture();
- await writeFakePackage(fixture.workspaceNodeModulesDir, "@lydell/node-pty-linux-arm64", {
- files: { "prebuilds/linux-arm64/pty.node": "linux-arm64-binary" },
- });
- const options = { ...fixture, target, appVersion: "9.9.9-test" };
- const original = await stageRelease(options);
- expect(original.componentArchivePaths.length).toBeGreaterThan(0);
- const expected = JSON.parse(
- await readFile(join(original.releaseDir, "manifest.json"), "utf8"),
- );
- for (const component of expected.components) {
- expect(component.archivePath).toBeTruthy();
- delete component.archivePath;
- }
- const staged = await stageRelease({ ...options, componentArchives: false });
- expect(staged.componentArchivePaths).toEqual([]);
- await expect(stat(join(fixture.outputDir, "components", target))).rejects.toMatchObject({
- code: "ENOENT",
- });
- await expect(stat(join(fixture.outputDir, ".components"))).rejects.toMatchObject({
- code: "ENOENT",
- });
- const manifest = JSON.parse(await readFile(join(staged.releaseDir, "manifest.json"), "utf8"));
- expect(manifest).toEqual(expected);
- // 用真实整包 installer 验证没有组件 archivePath 仍可安装,且整包摘要校验仍会拒绝错误身份。
- const { ReleaseInstaller } = await import(
- fileURLToPath(new URL("../src/runtime/releaseInstaller.ts", import.meta.url))
- );
- const { resolveServerLayout } = await import(
- fileURLToPath(new URL("../src/runtime/paths.ts", import.meta.url))
- );
- const installer = new ReleaseInstaller(
- resolveServerLayout(join(await makeTempDir(), "server")),
- );
- const archivePath = staged.archivePath!;
- const archiveSha256 = createHash("sha256")
- .update(await readFile(archivePath))
- .digest("hex");
- await expect(
- installer.installArchive({ archivePath, target, archiveSha256: "0".repeat(64) }),
- ).rejects.toThrow(/checksum mismatch/);
- const installed = await installer.installArchive({ archivePath, target, archiveSha256 });
- expect(
- JSON.parse(await readFile(join(installed.releaseDir, "manifest.json"), "utf8")),
- ).toEqual(expected);
- expect(await readFile(join(installed.releaseDir, "runtime", "zcode.cjs"))).toEqual(
- await readFile(fixture.agentBundlePath),
- );
- },
- );
- });
|