bundled-plugins-resilience.test.ts 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. import { existsSync } from "node:fs";
  2. import { createHash } from "node:crypto";
  3. import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { basename, dirname, join, sep } from "node:path";
  6. import type { Logger } from "@zcode/contracts";
  7. import { afterEach, describe, expect, it, vi } from "vitest";
  8. const faults = vi.hoisted(() => ({
  9. afterWriteFile: undefined as ((path: string) => void) | undefined,
  10. failTemporaryRemoveOnce: undefined as string | undefined,
  11. watchedSourceRoot: undefined as string | undefined,
  12. sourcePayloadReads: [] as string[],
  13. sourceDirectoryReads: [] as string[],
  14. omitSeedManifest: false,
  15. fileFactsReads: 0,
  16. afterFileFacts: undefined as (() => Promise<void>) | undefined,
  17. afterBackupRename: undefined as (() => Promise<void>) | undefined,
  18. seedLockTargets: [] as string[],
  19. afterSeedLock: undefined as (() => void) | undefined,
  20. crossDeviceBackupTargetSuffix: undefined as string | undefined,
  21. crossDevicePromoteTargetSuffix: undefined as string | undefined,
  22. moveTargetSuffix: undefined as string | undefined,
  23. promoteCurrentTargetSuffix: undefined as string | undefined,
  24. promoteTargetSuffix: undefined as string | undefined,
  25. recoverBackupTargetSuffix: undefined as string | undefined,
  26. removeTargetSuffix: undefined as string | undefined,
  27. runtimeManifestNotFoundTargetSuffix: undefined as string | undefined,
  28. runtimeManifestTargetSuffix: undefined as string | undefined,
  29. seedLockHeldTargetSuffixes: [] as string[],
  30. seedLockObservedTimeoutsMs: [] as number[],
  31. }));
  32. vi.mock("node:fs/promises", async (importOriginal) => {
  33. const actual = await importOriginal<typeof import("node:fs/promises")>();
  34. return {
  35. ...actual,
  36. async writeFile(...args: Parameters<typeof actual.writeFile>) {
  37. await actual.writeFile(...args);
  38. faults.afterWriteFile?.(String(args[0]));
  39. },
  40. async rm(...args: Parameters<typeof actual.rm>) {
  41. if (String(args[0]) === faults.failTemporaryRemoveOnce) {
  42. faults.failTemporaryRemoveOnce = undefined;
  43. throw Object.assign(new Error("temporary directory is busy"), { code: "EPERM" });
  44. }
  45. return actual.rm(...args);
  46. },
  47. async readFile(...args: Parameters<typeof actual.readFile>) {
  48. const path = String(args[0]);
  49. if (
  50. faults.watchedSourceRoot &&
  51. path.startsWith(faults.watchedSourceRoot + sep) &&
  52. !path.endsWith(join(".zcode-plugin", "plugin.json"))
  53. )
  54. faults.sourcePayloadReads.push(path);
  55. return actual.readFile(...args);
  56. },
  57. async readdir(...args: Parameters<typeof actual.readdir>) {
  58. const path = String(args[0]);
  59. if (
  60. faults.watchedSourceRoot &&
  61. (path === faults.watchedSourceRoot || path.startsWith(faults.watchedSourceRoot + sep))
  62. )
  63. faults.sourceDirectoryReads.push(path);
  64. return actual.readdir(...args);
  65. },
  66. };
  67. });
  68. vi.mock("../src/app/official-plugin-cache-fs.js", async (importOriginal) => {
  69. const actual = await importOriginal<typeof import("../src/app/official-plugin-cache-fs.js")>();
  70. return {
  71. ...actual,
  72. async collectOfficialPluginSourceFiles(
  73. ...args: Parameters<typeof actual.collectOfficialPluginSourceFiles>
  74. ) {
  75. const files = await actual.collectOfficialPluginSourceFiles(...args);
  76. // 模拟入口检查通过后,目录枚举前 manifest 消失;不能提交残缺版本 marker。
  77. return faults.omitSeedManifest && args[0] === faults.watchedSourceRoot
  78. ? files.filter((file) => file.path !== ".zcode-plugin/plugin.json")
  79. : files;
  80. },
  81. async readOfficialPluginFileFacts(paths: readonly string[]) {
  82. const facts = await actual.readOfficialPluginFileFacts(paths);
  83. faults.fileFactsReads += 1;
  84. await faults.afterFileFacts?.();
  85. return facts;
  86. },
  87. async removeOfficialPluginCacheDirectory(
  88. path: string,
  89. budget: Parameters<typeof actual.removeOfficialPluginCacheDirectory>[1],
  90. ): Promise<void> {
  91. if (faults.removeTargetSuffix && path.endsWith(faults.removeTargetSuffix)) {
  92. throw exhaustedErrno("EPERM");
  93. }
  94. await actual.removeOfficialPluginCacheDirectory(path, budget);
  95. },
  96. async renameOfficialPluginCachePath(
  97. fromPath: string,
  98. toPath: string,
  99. budget: ReturnType<typeof actual.createOfficialPluginCacheRetryBudget>,
  100. ): Promise<void> {
  101. if (
  102. faults.recoverBackupTargetSuffix &&
  103. fromPath === `${toPath}.backup` &&
  104. toPath.endsWith(faults.recoverBackupTargetSuffix)
  105. ) {
  106. throw errno("EOWNER");
  107. }
  108. // overlayfs(未启用 redirect_dir)拒绝 rename 位于镜像下层的目录,同一父目录内也返回 EXDEV;
  109. // 该错误不会因重试消失,与容器内复现到的内核行为一致。
  110. if (
  111. faults.crossDeviceBackupTargetSuffix &&
  112. fromPath.endsWith(faults.crossDeviceBackupTargetSuffix) &&
  113. toPath.startsWith(`${fromPath}.backup-`)
  114. ) {
  115. throw errno("EXDEV");
  116. }
  117. if (
  118. faults.crossDevicePromoteTargetSuffix &&
  119. fromPath.includes(".tmp-") &&
  120. toPath.endsWith(faults.crossDevicePromoteTargetSuffix)
  121. ) {
  122. throw errno("EXDEV");
  123. }
  124. if (
  125. faults.moveTargetSuffix &&
  126. fromPath.endsWith(faults.moveTargetSuffix) &&
  127. toPath.startsWith(`${fromPath}.backup-`)
  128. ) {
  129. await actual.removeOfficialPluginCacheDirectory(fromPath, budget);
  130. throw errno("ENOENT");
  131. }
  132. if (
  133. faults.promoteCurrentTargetSuffix &&
  134. fromPath.includes(".tmp-") &&
  135. toPath.endsWith(faults.promoteCurrentTargetSuffix)
  136. ) {
  137. await actual.renameOfficialPluginCachePath(fromPath, toPath, budget);
  138. throw errno("EEXIST");
  139. }
  140. if (
  141. faults.promoteTargetSuffix &&
  142. fromPath.includes(".tmp-") &&
  143. toPath.endsWith(faults.promoteTargetSuffix)
  144. ) {
  145. throw exhaustedErrno("EPERM");
  146. }
  147. await actual.renameOfficialPluginCachePath(fromPath, toPath, budget);
  148. if (toPath.startsWith(`${fromPath}.backup-`)) await faults.afterBackupRename?.();
  149. },
  150. async writeTextFileAtomicallyWithRetry(
  151. path: string,
  152. contents: string,
  153. budget: ReturnType<typeof actual.createOfficialPluginCacheRetryBudget>,
  154. ): Promise<void> {
  155. if (
  156. faults.runtimeManifestNotFoundTargetSuffix &&
  157. path.endsWith(faults.runtimeManifestNotFoundTargetSuffix)
  158. ) {
  159. throw errno("ENOENT");
  160. }
  161. if (faults.runtimeManifestTargetSuffix && path.endsWith(faults.runtimeManifestTargetSuffix)) {
  162. throw exhaustedErrno("EPERM");
  163. }
  164. await actual.writeTextFileAtomicallyWithRetry(path, contents, budget);
  165. },
  166. };
  167. });
  168. vi.mock("../src/app/official-plugin-seed-lock.js", async (importOriginal) => {
  169. const actual = await importOriginal<typeof import("../src/app/official-plugin-seed-lock.js")>();
  170. return {
  171. ...actual,
  172. async withOfficialPluginSeedLock<T>(
  173. targetRoot: string,
  174. action: () => T,
  175. options?: Parameters<typeof actual.withOfficialPluginSeedLock>[2],
  176. ): Promise<T> {
  177. faults.seedLockTargets.push(targetRoot);
  178. if (!faults.seedLockHeldTargetSuffixes.some((suffix) => targetRoot.endsWith(suffix))) {
  179. const result = await actual.withOfficialPluginSeedLock(targetRoot, action, options);
  180. faults.afterSeedLock?.();
  181. return result;
  182. }
  183. faults.seedLockObservedTimeoutsMs.push(options?.timeoutMs ?? -1);
  184. // 只压缩等待参数并保留调用方预算上限(默认 15s 会拖垮测试),
  185. // 仍走真实锁竞争与真实超时错误。
  186. return await actual.withOfficialPluginSeedLock(targetRoot, action, {
  187. ...options,
  188. retryDelayMs: 1,
  189. timeoutMs: Math.min(10, options?.timeoutMs ?? 10),
  190. });
  191. },
  192. };
  193. });
  194. import {
  195. createOfficialPluginPreparation,
  196. resolveOfficialPluginRoots,
  197. } from "../src/app/bundled-plugins.js";
  198. import { OFFICIAL_PLUGIN_DEFINITIONS } from "../src/app/official-plugin-definitions.js";
  199. import { resolveZCodePlugins } from "../src/plugins.js";
  200. const OFFICIAL_CACHE_ROOT = join("cache", "zcode-plugins-official");
  201. const BROWSER_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, "browser-use", "0.5.1");
  202. const ANDROID_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, "android-emulator", "0.1.1");
  203. const SKILL_CREATOR_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, "skill-creator", "0.1.0");
  204. const ANDROID_MANIFEST_SUFFIX = join(ANDROID_CACHE_SUFFIX, ".zcode-plugin", "plugin.json");
  205. const CUA_DEFINITION = OFFICIAL_PLUGIN_DEFINITIONS.find(({ name }) => name === "computer-use");
  206. if (!CUA_DEFINITION) throw new Error("computer-use official plugin definition is missing");
  207. const CUA_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, CUA_DEFINITION.name, CUA_DEFINITION.version);
  208. describe("bundled official plugin cache resilience", () => {
  209. const cleanups: string[] = [];
  210. const originalEntrypoint = process.argv[1];
  211. afterEach(async () => {
  212. vi.useRealTimers();
  213. faults.afterWriteFile = undefined;
  214. faults.failTemporaryRemoveOnce = undefined;
  215. faults.watchedSourceRoot = undefined;
  216. faults.sourcePayloadReads = [];
  217. faults.sourceDirectoryReads = [];
  218. faults.omitSeedManifest = false;
  219. faults.fileFactsReads = 0;
  220. faults.afterFileFacts = undefined;
  221. faults.afterBackupRename = undefined;
  222. faults.seedLockTargets = [];
  223. faults.afterSeedLock = undefined;
  224. process.argv[1] = originalEntrypoint;
  225. faults.crossDeviceBackupTargetSuffix = undefined;
  226. faults.crossDevicePromoteTargetSuffix = undefined;
  227. faults.moveTargetSuffix = undefined;
  228. faults.promoteCurrentTargetSuffix = undefined;
  229. faults.promoteTargetSuffix = undefined;
  230. faults.recoverBackupTargetSuffix = undefined;
  231. faults.removeTargetSuffix = undefined;
  232. faults.runtimeManifestNotFoundTargetSuffix = undefined;
  233. faults.runtimeManifestTargetSuffix = undefined;
  234. faults.seedLockHeldTargetSuffixes = [];
  235. faults.seedLockObservedTimeoutsMs = [];
  236. await Promise.all(cleanups.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  237. });
  238. it.each([false, true])("keeps SEA payload hash validation (corrupt: %s)", async (corrupt) => {
  239. const storageRoot = await createStorageRoot(cleanups);
  240. const payloads: Record<string, string> = {
  241. ".zcode-plugin/plugin.json": JSON.stringify({ name: "skill-creator", version: "0.1.0" }),
  242. "skills/demo/SKILL.md": "# original SEA skill",
  243. };
  244. const files = Object.entries(payloads).map(([path, text]) => ({
  245. path,
  246. sha256: createHash("sha256").update(text).digest("hex"),
  247. }));
  248. const prefix = "zcode-official-plugins/zcode-plugins-official/skill-creator/0.1.0/";
  249. const getBuiltinModule = process.getBuiltinModule.bind(process);
  250. const builtin = vi.spyOn(process, "getBuiltinModule").mockImplementation((id) => {
  251. if (id !== "node:sea") return getBuiltinModule(id);
  252. return {
  253. isSea: () => true,
  254. getAsset: () =>
  255. JSON.stringify({
  256. version: 1,
  257. plugins: [
  258. {
  259. marketplace: "zcode-plugins-official",
  260. name: "skill-creator",
  261. version: "0.1.0",
  262. files,
  263. },
  264. ],
  265. }),
  266. getRawAsset: (key: string) => {
  267. const path = key.slice(prefix.length);
  268. const text = corrupt && path === "skills/demo/SKILL.md" ? "# corrupted" : payloads[path];
  269. return new Uint8Array(Buffer.from(text)).buffer;
  270. },
  271. };
  272. });
  273. try {
  274. const prepared = resolveOfficialPluginRoots({ storageRoot, logger: createLogger() });
  275. if (corrupt)
  276. await expect(prepared).rejects.toMatchObject({ code: "ZCODE_PLUGIN_SOURCES_CHANGED" });
  277. else await prepared;
  278. const marker = join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX, ".zcode-plugin-seed.json");
  279. expect(existsSync(marker)).toBe(!corrupt);
  280. if (!corrupt)
  281. expect(JSON.parse(await readFile(marker, "utf8")).hash).toMatch(/^[a-f0-9]{64}$/);
  282. } finally {
  283. builtin.mockRestore();
  284. }
  285. });
  286. it("shares a startup deadline and keeps timeout degradation until a new owner", async () => {
  287. vi.useFakeTimers();
  288. const preparation = createOfficialPluginPreparation({ startupTimeoutMs: 3_000 });
  289. const late = Promise.withResolvers<Awaited<ReturnType<typeof resolveZCodePlugins>>>();
  290. const success = {
  291. commandRoots: [],
  292. diagnostics: [],
  293. hooks: {},
  294. mcpServers: {},
  295. plugins: [],
  296. skillRoots: [],
  297. };
  298. const first = preparation.resolvePlugins(() => late.promise);
  299. await vi.advanceTimersByTimeAsync(2_900);
  300. const second = preparation.resolvePlugins(() => late.promise);
  301. await vi.advanceTimersByTimeAsync(100);
  302. for (const outcome of await Promise.all([first, second])) {
  303. expect(outcome).toMatchObject({
  304. ...success,
  305. diagnostics: [{ code: "plugin_startup_timeout", severity: "warning" }],
  306. });
  307. }
  308. expect(preparation.startupDegraded).toBe(true);
  309. expect(preparation.signal.aborted).toBe(true);
  310. late.resolve(success);
  311. preparation.invalidate();
  312. const unexpected = vi.fn(async () => success);
  313. await preparation.resolvePlugins(unexpected);
  314. expect(unexpected).not.toHaveBeenCalled();
  315. await preparation.dispose();
  316. const next = createOfficialPluginPreparation({ startupTimeoutMs: 3_000 });
  317. await expect(next.resolvePlugins(unexpected)).resolves.toEqual(success);
  318. expect(unexpected).toHaveBeenCalledOnce();
  319. expect(next.startupDegraded).toBe(false);
  320. const pending = next.resolvePlugins(() => new Promise(() => {}));
  321. const closed = expect(pending).rejects.toMatchObject({ name: "AbortError" });
  322. await next.dispose();
  323. await closed;
  324. expect(vi.getTimerCount()).toBe(0);
  325. });
  326. it("skips discovery and fallback scans after seed exceeds the startup budget", async () => {
  327. const storageRoot = await createStorageRoot(cleanups);
  328. vi.useFakeTimers();
  329. const preparation = createOfficialPluginPreparation({ startupTimeoutMs: 3_000 });
  330. const seed = Promise.withResolvers<[]>();
  331. const prepare = vi.spyOn(preparation, "prepare").mockImplementation(() => seed.promise);
  332. const discoverPlugins = vi.fn();
  333. const options = {
  334. pluginStorageRoot: storageRoot,
  335. workingDirectory: dirname(storageRoot),
  336. skipUserConfig: true,
  337. pluginPreparation: preparation,
  338. pluginDiscovery: { discoverPlugins },
  339. };
  340. const first = resolveZCodePlugins(options);
  341. await vi.advanceTimersByTimeAsync(3_000);
  342. expect((await first).diagnostics).toEqual([
  343. expect.objectContaining({ code: "plugin_startup_timeout" }),
  344. ]);
  345. seed.reject(new Error("late seed failure"));
  346. await resolveZCodePlugins(options);
  347. expect(prepare).toHaveBeenCalledOnce();
  348. expect(discoverPlugins).not.toHaveBeenCalled();
  349. await preparation.dispose();
  350. });
  351. it("lets directory publication finish safely after the startup caller times out", async () => {
  352. const storageRoot = await createStorageRoot(cleanups);
  353. await resolveOfficialPluginRoots({ storageRoot });
  354. const targetRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  355. await writeFile(join(targetRoot, ".zcode-plugin-seed.json"), "{}");
  356. vi.useFakeTimers();
  357. const moved = Promise.withResolvers<void>();
  358. const release = Promise.withResolvers<void>();
  359. faults.afterBackupRename = async () => {
  360. faults.afterBackupRename = undefined;
  361. moved.resolve();
  362. await release.promise;
  363. };
  364. const preparation = createOfficialPluginPreparation({ startupTimeoutMs: 3_000 });
  365. const work = preparation.resolvePlugins(async () => {
  366. await resolveOfficialPluginRoots({ storageRoot, preparation });
  367. return {
  368. commandRoots: [],
  369. diagnostics: [],
  370. hooks: {},
  371. mcpServers: {},
  372. plugins: [],
  373. skillRoots: [],
  374. };
  375. });
  376. try {
  377. await moved.promise;
  378. await vi.advanceTimersByTimeAsync(3_000);
  379. expect((await work).diagnostics[0]?.code).toBe("plugin_startup_timeout");
  380. expect(existsSync(`${targetRoot}.seed-lock`)).toBe(true);
  381. } finally {
  382. release.resolve();
  383. await preparation.dispose();
  384. }
  385. expect(existsSync(join(targetRoot, ".zcode-plugin", "plugin.json"))).toBe(true);
  386. expect(existsSync(`${targetRoot}.seed-lock`)).toBe(false);
  387. await expectNoSeedBackups(targetRoot);
  388. }, 15_000);
  389. it("reuses filesystem versions across fresh owners without scanning or hashing source payload", async () => {
  390. const storageRoot = await createStorageRoot(cleanups);
  391. const fixture = await createVersionedSource(storageRoot);
  392. await resolveOfficialPluginRoots({ storageRoot });
  393. const targetRoot = join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX);
  394. const markerPath = join(targetRoot, ".zcode-plugin-seed.json");
  395. const marker = JSON.parse(await readFile(markerPath, "utf8"));
  396. await writeFile(markerPath, JSON.stringify({ ...marker, hash: "legacy-content-hash" }));
  397. await writeFile(fixture.payload, "same version, changed source");
  398. faults.sourcePayloadReads = [];
  399. faults.sourceDirectoryReads = [];
  400. await resolveOfficialPluginRoots({ storageRoot });
  401. expect(faults.sourcePayloadReads).toEqual([]);
  402. expect(faults.sourceDirectoryReads).toEqual([]);
  403. expect(await readFile(join(targetRoot, "skills", "demo", "SKILL.md"), "utf8")).toBe(
  404. "original source",
  405. );
  406. expect(JSON.parse(await readFile(markerPath, "utf8")).hash).toBe("legacy-content-hash");
  407. });
  408. it("reseeds the same filesystem version when its declared build identity changes", async () => {
  409. const storageRoot = await createStorageRoot(cleanups);
  410. const fixture = await createVersionedSource(storageRoot);
  411. const definition = OFFICIAL_PLUGIN_DEFINITIONS.find((item) => item.name === "skill-creator")!;
  412. const mutable = definition as { buildIdentityPath?: string };
  413. const identityPath = join(fixture.root, "dist", "build-identity.json");
  414. const targetRoot = join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX);
  415. const markerPath = join(targetRoot, ".zcode-plugin-seed.json");
  416. const cachedPayload = () => readFile(join(targetRoot, "skills", "demo", "SKILL.md"), "utf8");
  417. mutable.buildIdentityPath = "dist/build-identity.json";
  418. try {
  419. await mkdir(dirname(identityPath), { recursive: true });
  420. await writeFile(identityPath, '{"cuaHelperBuildId":"pipeline-1"}\n');
  421. await resolveOfficialPluginRoots({ storageRoot });
  422. expect(JSON.parse(await readFile(markerPath, "utf8")).buildIdentity).toBe(
  423. '{"cuaHelperBuildId":"pipeline-1"}\n',
  424. );
  425. // 同一构建身份仍按版本规则复用:只读身份小文件,不读取源正文。
  426. await writeFile(fixture.payload, "same build, edited source");
  427. faults.sourcePayloadReads = [];
  428. await resolveOfficialPluginRoots({ storageRoot });
  429. expect(faults.sourcePayloadReads.length).toBeGreaterThan(0);
  430. expect(faults.sourcePayloadReads.every((path) => path === identityPath)).toBe(true);
  431. expect(await cachedPayload()).toBe("original source");
  432. // 桌面升级换了 Helper build id,版本号不变也必须重建。
  433. await writeFile(identityPath, '{"cuaHelperBuildId":"pipeline-2"}\n');
  434. await writeFile(fixture.payload, "pipeline 2 build");
  435. await resolveOfficialPluginRoots({ storageRoot });
  436. expect(await cachedPayload()).toBe("pipeline 2 build");
  437. expect(JSON.parse(await readFile(markerPath, "utf8")).buildIdentity).toBe(
  438. '{"cuaHelperBuildId":"pipeline-2"}\n',
  439. );
  440. // 旧客户端写入的 marker 没有构建身份,同样视为过期。
  441. const marker = JSON.parse(await readFile(markerPath, "utf8"));
  442. delete marker.buildIdentity;
  443. await writeFile(markerPath, JSON.stringify(marker));
  444. await writeFile(fixture.payload, "after legacy marker");
  445. await resolveOfficialPluginRoots({ storageRoot });
  446. expect(await cachedPayload()).toBe("after legacy marker");
  447. } finally {
  448. delete mutable.buildIdentityPath;
  449. }
  450. });
  451. it.each([false, true])(
  452. "cleans a cancelled seed without changing the old target (busy=%s)",
  453. async (busy) => {
  454. const storageRoot = await createStorageRoot(cleanups);
  455. await createVersionedSource(storageRoot);
  456. await resolveOfficialPluginRoots({ storageRoot });
  457. const targetRoot = join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX);
  458. const markerPath = join(targetRoot, ".zcode-plugin-seed.json");
  459. const marker = JSON.parse(await readFile(markerPath, "utf8"));
  460. const staleMarker = JSON.stringify({ ...marker, pluginVersion: "0.0.0" });
  461. await writeFile(markerPath, staleMarker);
  462. const preparation = createOfficialPluginPreparation();
  463. let disposal: Promise<void> | undefined;
  464. faults.afterWriteFile = (path) => {
  465. if (disposal || !path.startsWith(`${targetRoot}.tmp-`)) return;
  466. // 写入第一份候选文件后中止,确保真实临时目录存在;取消与预算到期共用此 signal。
  467. if (busy)
  468. faults.failTemporaryRemoveOnce = path.slice(0, path.indexOf(sep, targetRoot.length));
  469. disposal = preparation.dispose();
  470. };
  471. try {
  472. await expect(
  473. resolveOfficialPluginRoots({ storageRoot, preparation }),
  474. ).rejects.toBeInstanceOf(Error);
  475. expect(preparation.signal.aborted).toBe(true);
  476. await disposal;
  477. expect(await readdir(dirname(targetRoot))).not.toEqual(
  478. expect.arrayContaining([expect.stringContaining(".tmp-")]),
  479. );
  480. expect(await readFile(markerPath, "utf8")).toBe(staleMarker);
  481. expect(await readFile(join(targetRoot, "skills", "demo", "SKILL.md"), "utf8")).toBe(
  482. "original source",
  483. );
  484. } finally {
  485. await preparation.dispose();
  486. }
  487. },
  488. );
  489. it("copies filesystem payload once when a version marker differs or is missing", async () => {
  490. const storageRoot = await createStorageRoot(cleanups);
  491. const fixture = await createVersionedSource(storageRoot);
  492. await resolveOfficialPluginRoots({ storageRoot });
  493. const targetRoot = join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX);
  494. const markerPath = join(targetRoot, ".zcode-plugin-seed.json");
  495. const marker = JSON.parse(await readFile(markerPath, "utf8"));
  496. await writeFile(markerPath, JSON.stringify({ ...marker, pluginVersion: "0.0.0" }));
  497. for (const removeMarker of [false, true]) {
  498. if (removeMarker) await rm(markerPath);
  499. await writeFile(fixture.payload, `replacement ${removeMarker}`);
  500. faults.sourcePayloadReads = [];
  501. faults.sourceDirectoryReads = [];
  502. await resolveOfficialPluginRoots({ storageRoot });
  503. expect(faults.sourcePayloadReads).toEqual([fixture.payload]);
  504. expect(faults.sourceDirectoryReads.length).toBeGreaterThan(0);
  505. expect(await readFile(join(targetRoot, "skills", "demo", "SKILL.md"), "utf8")).toBe(
  506. `replacement ${removeMarker}`,
  507. );
  508. expect(JSON.parse(await readFile(markerPath, "utf8"))).toMatchObject({
  509. pluginVersion: "0.1.0",
  510. });
  511. expect(JSON.parse(await readFile(markerPath, "utf8"))).not.toHaveProperty("hash");
  512. }
  513. });
  514. it("seeds a bumped filesystem version while preserving the previous version", async () => {
  515. const storageRoot = await createStorageRoot(cleanups);
  516. const fixture = await createVersionedSource(storageRoot);
  517. await resolveOfficialPluginRoots({ storageRoot });
  518. const definition = OFFICIAL_PLUGIN_DEFINITIONS.find((item) => item.name === "skill-creator")!;
  519. const previousVersion = definition.version;
  520. try {
  521. definition.version = "0.1.1";
  522. await writeFile(
  523. join(fixture.root, ".zcode-plugin", "plugin.json"),
  524. JSON.stringify({ name: definition.name, version: definition.version }),
  525. );
  526. await writeFile(fixture.payload, "new version");
  527. faults.sourcePayloadReads = [];
  528. await resolveOfficialPluginRoots({ storageRoot });
  529. expect(faults.sourcePayloadReads).toEqual([fixture.payload]);
  530. expect(
  531. await readFile(
  532. join(
  533. storageRoot,
  534. OFFICIAL_CACHE_ROOT,
  535. "skill-creator",
  536. "0.1.1",
  537. "skills",
  538. "demo",
  539. "SKILL.md",
  540. ),
  541. "utf8",
  542. ),
  543. ).toBe("new version");
  544. expect(
  545. await readFile(
  546. join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX, "skills", "demo", "SKILL.md"),
  547. "utf8",
  548. ),
  549. ).toBe("original source");
  550. } finally {
  551. definition.version = previousVersion;
  552. }
  553. });
  554. it("does not publish a version marker for an incomplete staged filesystem source", async () => {
  555. const storageRoot = await createStorageRoot(cleanups);
  556. await createVersionedSource(storageRoot);
  557. faults.omitSeedManifest = true;
  558. await expect(resolveOfficialPluginRoots({ storageRoot })).rejects.toMatchObject({
  559. code: "ZCODE_PLUGIN_SOURCES_CHANGED",
  560. });
  561. expect(
  562. existsSync(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX, ".zcode-plugin-seed.json")),
  563. ).toBe(false);
  564. });
  565. it("reuses only validated successful preparation and invalidates on cache loss or explicit refresh", async () => {
  566. const storageRoot = await createStorageRoot(cleanups);
  567. const preparation = createOfficialPluginPreparation();
  568. try {
  569. await resolveOfficialPluginRoots({ storageRoot, preparation });
  570. expect(faults.seedLockTargets.length).toBeGreaterThan(0);
  571. faults.seedLockTargets = [];
  572. faults.fileFactsReads = 0;
  573. await resolveOfficialPluginRoots({ storageRoot, preparation });
  574. expect(faults.seedLockTargets).toEqual([]);
  575. expect(faults.fileFactsReads).toBe(2);
  576. process.argv[1] = join(storageRoot, "changed-cli-entry.cjs");
  577. await resolveOfficialPluginRoots({ storageRoot, preparation });
  578. expect(faults.seedLockTargets.length).toBeGreaterThan(0);
  579. faults.seedLockTargets = [];
  580. await rm(join(storageRoot, BROWSER_CACHE_SUFFIX, ".zcode-plugin-seed.json"));
  581. await resolveOfficialPluginRoots({ storageRoot, preparation });
  582. expect(faults.seedLockTargets.length).toBeGreaterThan(0);
  583. faults.seedLockTargets = [];
  584. preparation.invalidate();
  585. await resolveOfficialPluginRoots({ storageRoot, preparation });
  586. expect(faults.seedLockTargets.length).toBeGreaterThan(0);
  587. } finally {
  588. await preparation.dispose();
  589. }
  590. await expect(resolveOfficialPluginRoots({ storageRoot, preparation })).rejects.toMatchObject({
  591. name: "AbortError",
  592. });
  593. }, 15_000);
  594. it.each(["marker deletion", "manifest replacement"] as const)(
  595. "revalidates a cache hit against its original facts after %s",
  596. async (mutation) => {
  597. const storageRoot = await createStorageRoot(cleanups);
  598. const preparation = createOfficialPluginPreparation();
  599. const targetRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  600. const markerPath = join(targetRoot, ".zcode-plugin-seed.json");
  601. const manifestPath = join(targetRoot, ".zcode-plugin", "plugin.json");
  602. try {
  603. await resolveOfficialPluginRoots({ storageRoot, preparation });
  604. const originalManifest = await readFile(manifestPath, "utf8");
  605. faults.seedLockTargets = [];
  606. faults.afterFileFacts = async () => {
  607. faults.afterFileFacts = undefined;
  608. // 首次检查已读到旧状态后再改盘,覆盖可复用判定与最终校验之间的窗口。
  609. if (mutation === "marker deletion") await rm(markerPath);
  610. else await writeFile(manifestPath, JSON.stringify({ name: "external-replacement" }));
  611. };
  612. await expect(resolveOfficialPluginRoots({ storageRoot, preparation })).resolves.toEqual([]);
  613. expect(faults.seedLockTargets).toContain(targetRoot);
  614. expect(existsSync(markerPath)).toBe(true);
  615. expect(await readFile(manifestPath, "utf8")).toBe(originalManifest);
  616. } finally {
  617. await preparation.dispose();
  618. }
  619. },
  620. 15_000,
  621. );
  622. it("does not remember partial seed failure as successful preparation", async () => {
  623. const storageRoot = await createStorageRoot(cleanups);
  624. const preparation = createOfficialPluginPreparation();
  625. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  626. try {
  627. await resolveOfficialPluginRoots({ storageRoot, preparation });
  628. faults.seedLockTargets = [];
  629. await resolveOfficialPluginRoots({ storageRoot, preparation });
  630. expect(faults.seedLockTargets.some((path) => path.endsWith(BROWSER_CACHE_SUFFIX))).toBe(true);
  631. faults.promoteTargetSuffix = undefined;
  632. await resolveOfficialPluginRoots({ storageRoot, preparation });
  633. expect(existsSync(join(storageRoot, BROWSER_CACHE_SUFFIX))).toBe(true);
  634. } finally {
  635. await preparation.dispose();
  636. }
  637. }, 15_000);
  638. it("discards in-flight preparation when its process owner closes", async () => {
  639. const storageRoot = await createStorageRoot(cleanups);
  640. const preparation = createOfficialPluginPreparation();
  641. let disposed: Promise<void> | undefined;
  642. faults.afterSeedLock = () => {
  643. disposed = preparation.dispose();
  644. faults.afterSeedLock = undefined;
  645. };
  646. await expect(resolveOfficialPluginRoots({ storageRoot, preparation })).rejects.toMatchObject({
  647. name: "AbortError",
  648. });
  649. await disposed;
  650. expect(faults.seedLockTargets).toHaveLength(1);
  651. });
  652. it("bounds invalidation during preparation and allows a later retry", async () => {
  653. const storageRoot = await createStorageRoot(cleanups);
  654. const preparation = createOfficialPluginPreparation();
  655. faults.afterSeedLock = () => preparation.invalidate();
  656. try {
  657. await expect(resolveOfficialPluginRoots({ storageRoot, preparation })).rejects.toMatchObject({
  658. code: "ZCODE_PLUGIN_SOURCES_CHANGED",
  659. });
  660. faults.afterSeedLock = undefined;
  661. await expect(resolveOfficialPluginRoots({ storageRoot, preparation })).resolves.toEqual([]);
  662. } finally {
  663. await preparation.dispose();
  664. }
  665. }, 15_000);
  666. it("degrades a persistent transient seed failure when the target is absent", async () => {
  667. const storageRoot = await createStorageRoot(cleanups);
  668. const logger = createLogger();
  669. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  670. await expect(
  671. (async () => await resolveOfficialPluginRoots({ logger, storageRoot }))(),
  672. ).resolves.not.toBeInstanceOf(Error);
  673. expect(existsSync(join(storageRoot, BROWSER_CACHE_SUFFIX))).toBe(false);
  674. expect(existsSync(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX))).toBe(true);
  675. expect(logger.warn).toHaveBeenCalledWith(
  676. "Official plugin cache operation degraded",
  677. expect.objectContaining({
  678. attempts: 4,
  679. degraded: true,
  680. errorCode: "EPERM",
  681. operation: "seed_plugin",
  682. pluginId: "browser-use@zcode-plugins-official",
  683. }),
  684. );
  685. });
  686. it("keeps degraded cache diagnostics through the ordinary plugin resolver", async () => {
  687. const storageRoot = await createStorageRoot(cleanups);
  688. const logger = createLogger();
  689. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  690. await expect(
  691. (async () =>
  692. await resolveZCodePlugins({
  693. logger,
  694. pluginStorageRoot: storageRoot,
  695. skipUserConfig: true,
  696. workingDirectory: dirname(storageRoot),
  697. }))(),
  698. ).resolves.not.toBeInstanceOf(Error);
  699. expect(logger.warn).toHaveBeenCalledWith(
  700. "Official plugin cache operation degraded",
  701. expect.objectContaining({
  702. degraded: true,
  703. errorCode: "EPERM",
  704. pluginId: "browser-use@zcode-plugins-official",
  705. }),
  706. );
  707. });
  708. it("keeps a stale but usable target when promotion fails", async () => {
  709. const storageRoot = await createStorageRoot(cleanups);
  710. await resolveOfficialPluginRoots({ storageRoot });
  711. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  712. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  713. const staleMarker = `${await readFile(markerPath, "utf8")}\n`;
  714. await writeFile(
  715. markerPath,
  716. staleMarker.replace('"pluginVersion": "', '"pluginVersion": "stale-'),
  717. );
  718. const logger = createLogger();
  719. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  720. await expect(
  721. (async () => await resolveOfficialPluginRoots({ logger, storageRoot }))(),
  722. ).resolves.not.toBeInstanceOf(Error);
  723. expect(existsSync(browserRoot)).toBe(true);
  724. expect(await readFile(markerPath, "utf8")).toContain('"pluginVersion": "stale-');
  725. expect(logger.warn).toHaveBeenCalledWith(
  726. "Official plugin cache operation degraded",
  727. expect.objectContaining({
  728. errorCode: "EPERM",
  729. operation: "seed_plugin",
  730. pluginId: "browser-use@zcode-plugins-official",
  731. }),
  732. );
  733. });
  734. it("falls back to a previous usable version when the new target cannot be promoted", async () => {
  735. const storageRoot = await createStorageRoot(cleanups);
  736. expect(await resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  737. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  738. const staleRoot = join(dirname(currentRoot), "0.2.1");
  739. await rename(currentRoot, staleRoot);
  740. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  741. const roots = await resolveOfficialPluginRoots({ storageRoot });
  742. expect(roots).toContain(staleRoot);
  743. });
  744. it("does not reactivate older Android code after a failed security update", async () => {
  745. const definition = OFFICIAL_PLUGIN_DEFINITIONS.find(({ name }) => name === "android-emulator");
  746. if (!definition) throw new Error("Android definition is missing");
  747. const storageRoot = await createStorageRoot(cleanups);
  748. await resolveOfficialPluginRoots({ storageRoot });
  749. const previousVersion = definition.version;
  750. const oldRoot = join(storageRoot, OFFICIAL_CACHE_ROOT, definition.name, previousVersion);
  751. try {
  752. definition.version = "0.1.2";
  753. faults.promoteTargetSuffix = join(OFFICIAL_CACHE_ROOT, definition.name, definition.version);
  754. const roots = await resolveOfficialPluginRoots({ storageRoot });
  755. expect(existsSync(oldRoot)).toBe(true);
  756. expect(roots).not.toContain(oldRoot);
  757. } finally {
  758. definition.version = previousVersion;
  759. }
  760. });
  761. it("degrades an incomplete seed source to a usable previous version instead of failing startup", async () => {
  762. const storageRoot = await createStorageRoot(cleanups);
  763. expect(await resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  764. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  765. const staleRoot = join(dirname(currentRoot), "0.2.1");
  766. await rename(currentRoot, staleRoot);
  767. await rm(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX), { force: true, recursive: true });
  768. // 入口目录旁只有一份缺 dist/docs/skills 的 browser-use 拷贝(升级中的桌面包、
  769. // 未构建 dist 的旧 checkout);其余插件继续从真实 monorepo 源解析。
  770. const entrypointRoot = join(storageRoot, "stale-entrypoint");
  771. const incompletePluginRoot = join(entrypointRoot, "packages", "browser-use-plugin");
  772. await mkdir(join(incompletePluginRoot, ".zcode-plugin"), { recursive: true });
  773. await writeFile(
  774. join(incompletePluginRoot, ".zcode-plugin", "plugin.json"),
  775. JSON.stringify({ name: "browser-use", version: "0.5.1" }),
  776. );
  777. process.argv[1] = join(entrypointRoot, "zcode.cjs");
  778. const logger = createLogger();
  779. let roots: string[] = [];
  780. await expect(
  781. (async () => {
  782. roots = await resolveOfficialPluginRoots({ logger, storageRoot });
  783. })(),
  784. ).resolves.not.toBeInstanceOf(Error);
  785. expect(roots).toContain(staleRoot);
  786. // 残缺源绝不能落成当前版本缓存(会永久命中版本),也不能拖垮其他插件的 seeding。
  787. expect(existsSync(currentRoot)).toBe(false);
  788. expect(existsSync(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX))).toBe(true);
  789. const marketplace = JSON.parse(
  790. await readFile(
  791. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  792. "utf8",
  793. ),
  794. ) as { plugins: Array<{ name: string }> };
  795. expect(marketplace.plugins.some((plugin) => plugin.name === "browser-use")).toBe(true);
  796. expect(logger.warn).toHaveBeenCalledWith(
  797. "Official plugin cache operation degraded",
  798. expect.objectContaining({
  799. degraded: true,
  800. errorCode: "ZCODE_PLUGIN_SEED_INCOMPLETE",
  801. // browser-use 不再携带 node_repl 宿主产物(那是 node-repl-host 的),
  802. // 它自己必需的运行时资产是 browser-client。
  803. missingSeedPaths: expect.arrayContaining(["scripts/browser-client.mjs"]),
  804. operation: "seed_plugin",
  805. pluginId: "browser-use@zcode-plugins-official",
  806. }),
  807. );
  808. });
  809. it("keeps session bootstrap alive when an incomplete seed source has no usable fallback cache", async () => {
  810. const storageRoot = await createStorageRoot(cleanups);
  811. // 全新安装:storageRoot 从未 seed 过,也没有任何旧版本缓存可回退。
  812. const entrypointRoot = join(storageRoot, "fresh-install-entrypoint");
  813. const incompletePluginRoot = join(entrypointRoot, "packages", "browser-use-plugin");
  814. await mkdir(join(incompletePluginRoot, ".zcode-plugin"), { recursive: true });
  815. await writeFile(
  816. join(incompletePluginRoot, ".zcode-plugin", "plugin.json"),
  817. JSON.stringify({ name: "browser-use", version: "0.5.1" }),
  818. );
  819. process.argv[1] = join(entrypointRoot, "zcode.cjs");
  820. const logger = createLogger();
  821. let outcome!: ReturnType<typeof resolveZCodePlugins>;
  822. await expect(
  823. (async () => {
  824. outcome = await resolveZCodePlugins({
  825. logger,
  826. pluginStorageRoot: storageRoot,
  827. skipUserConfig: true,
  828. workingDirectory: dirname(storageRoot),
  829. });
  830. })(),
  831. ).resolves.not.toBeInstanceOf(Error);
  832. // 降级终态之二:无可用旧缓存时该插件本次缺席(不写残缺缓存),只留 warning 级诊断,
  833. // 其余 defaultEnabled 插件与会话引导不受影响。
  834. expect(existsSync(join(storageRoot, BROWSER_CACHE_SUFFIX))).toBe(false);
  835. expect(
  836. outcome.plugins.find((plugin) => plugin.id === "browser-use@zcode-plugins-official"),
  837. ).toBeUndefined();
  838. const rootNotFound = outcome.diagnostics.filter(
  839. (diagnostic) => diagnostic.code === "plugin_root_not_found",
  840. );
  841. expect(rootNotFound).toEqual([
  842. expect.objectContaining({
  843. path: join(storageRoot, BROWSER_CACHE_SUFFIX),
  844. severity: "warning",
  845. }),
  846. ]);
  847. const documentSkills = outcome.plugins.find(
  848. (plugin) => plugin.id === "documents@zcode-plugins-official",
  849. );
  850. expect(documentSkills?.enabled).toBe(true);
  851. expect(logger.warn).toHaveBeenCalledWith(
  852. "Official plugin cache operation degraded",
  853. expect.objectContaining({
  854. errorCode: "ZCODE_PLUGIN_SEED_INCOMPLETE",
  855. operation: "seed_plugin",
  856. pluginId: "browser-use@zcode-plugins-official",
  857. }),
  858. );
  859. });
  860. it("degrades a held seed lock to a usable previous version instead of failing startup", async () => {
  861. const storageRoot = await createStorageRoot(cleanups);
  862. expect(await resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  863. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  864. const staleRoot = join(dirname(currentRoot), "0.2.1");
  865. await rename(currentRoot, staleRoot);
  866. const lockRoot = `${currentRoot}.seed-lock`;
  867. await mkdir(lockRoot, { recursive: true });
  868. await writeFile(
  869. join(lockRoot, "owner.json"),
  870. JSON.stringify({ createdAt: new Date().toISOString(), pid: process.pid }),
  871. );
  872. const logger = createLogger();
  873. faults.seedLockHeldTargetSuffixes = [BROWSER_CACHE_SUFFIX];
  874. let roots: string[] = [];
  875. await expect(
  876. (async () => {
  877. roots = await resolveOfficialPluginRoots({ logger, storageRoot });
  878. })(),
  879. ).resolves.not.toBeInstanceOf(Error);
  880. expect(roots).toContain(staleRoot);
  881. // 锁属于「另一个进程」(owner 存活),降级方绝不能顺手删掉它。
  882. expect(existsSync(lockRoot)).toBe(true);
  883. expect(logger.warn).toHaveBeenCalledWith(
  884. "Official plugin cache operation degraded",
  885. expect.objectContaining({
  886. degraded: true,
  887. errorCode: "ZCODE_PLUGIN_SEED_LOCK_TIMEOUT",
  888. operation: "seed_plugin",
  889. pluginId: "browser-use@zcode-plugins-official",
  890. }),
  891. );
  892. });
  893. it("shares one seed lock wait budget across all plugins", async () => {
  894. const storageRoot = await createStorageRoot(cleanups);
  895. expect(await resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  896. for (const cacheSuffix of [BROWSER_CACHE_SUFFIX, SKILL_CREATOR_CACHE_SUFFIX]) {
  897. const lockRoot = `${join(storageRoot, cacheSuffix)}.seed-lock`;
  898. await mkdir(lockRoot, { recursive: true });
  899. await writeFile(
  900. join(lockRoot, "owner.json"),
  901. JSON.stringify({ createdAt: new Date().toISOString(), pid: process.pid }),
  902. );
  903. }
  904. faults.seedLockHeldTargetSuffixes = [BROWSER_CACHE_SUFFIX, SKILL_CREATOR_CACHE_SUFFIX];
  905. await expect(
  906. (async () => await resolveOfficialPluginRoots({ storageRoot }))(),
  907. ).resolves.not.toBeInstanceOf(Error);
  908. // 两把被持有的锁必须共享同一截止时间:后一次调用拿到的剩余预算严格更小,
  909. // 而不是每个插件都重置成完整的 15s(否则成组遗留锁会让启动冻结 N×15s)。
  910. expect(faults.seedLockObservedTimeoutsMs).toHaveLength(2);
  911. const [firstBudgetMs, secondBudgetMs] = faults.seedLockObservedTimeoutsMs;
  912. expect(firstBudgetMs).toBeGreaterThan(0);
  913. expect(firstBudgetMs).toBeLessThanOrEqual(15_000);
  914. expect(secondBudgetMs).toBeLessThan(firstBudgetMs as number);
  915. });
  916. it("keeps an intact current cache discoverable when the seed lock times out", async () => {
  917. const storageRoot = await createStorageRoot(cleanups);
  918. expect(await resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  919. // 当前版本目录保持完整(不 rename 成旧版本),只把锁交给「另一个存活进程」。
  920. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  921. const lockRoot = `${currentRoot}.seed-lock`;
  922. await mkdir(lockRoot, { recursive: true });
  923. await writeFile(
  924. join(lockRoot, "owner.json"),
  925. JSON.stringify({ createdAt: new Date().toISOString(), pid: process.pid }),
  926. );
  927. const logger = createLogger();
  928. faults.seedLockHeldTargetSuffixes = [BROWSER_CACHE_SUFFIX];
  929. const outcome = await resolveZCodePlugins({
  930. logger,
  931. pluginStorageRoot: storageRoot,
  932. skipUserConfig: true,
  933. workingDirectory: dirname(storageRoot),
  934. });
  935. expect(logger.warn).toHaveBeenCalledWith(
  936. "Official plugin cache operation degraded",
  937. expect.objectContaining({
  938. errorCode: "ZCODE_PLUGIN_SEED_LOCK_TIMEOUT",
  939. operation: "seed_plugin",
  940. pluginId: "browser-use@zcode-plugins-official",
  941. }),
  942. );
  943. // 锁只保护 seed 写入,不保护读取:等锁超时不能让一份完整的当前缓存从 discovery 消失。
  944. // 该不变量依赖 bundled marketplace 分片在 seeding 循环之前写入且不按 seed 成败过滤;
  945. // 若未来把分片写入挪到循环之后,这条断言会失败。
  946. const browserPlugin = outcome.plugins.find(
  947. (plugin) => plugin.id === "browser-use@zcode-plugins-official",
  948. );
  949. expect(browserPlugin?.rootPath).toBe(currentRoot);
  950. expect(browserPlugin?.enabled).toBe(true);
  951. expect(
  952. outcome.diagnostics.filter((diagnostic) => diagnostic.code === "plugin_root_not_found"),
  953. ).toEqual([]);
  954. });
  955. it("does not mix an old zcode-cua cache with the current consumer contract", async () => {
  956. const storageRoot = await createStorageRoot(cleanups);
  957. await resolveOfficialPluginRoots({ storageRoot });
  958. const currentRoot = join(storageRoot, CUA_CACHE_SUFFIX);
  959. const staleRoot = join(dirname(currentRoot), "0.5.9");
  960. await rename(currentRoot, staleRoot);
  961. faults.promoteTargetSuffix = CUA_CACHE_SUFFIX;
  962. const roots = await resolveOfficialPluginRoots({ storageRoot });
  963. expect(roots).not.toContain(staleRoot);
  964. });
  965. it("continues when another process moves the target after the existence check", async () => {
  966. const storageRoot = await createStorageRoot(cleanups);
  967. await resolveOfficialPluginRoots({ storageRoot });
  968. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  969. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  970. const staleMarker = `${await readFile(markerPath, "utf8")}\n`;
  971. await writeFile(
  972. markerPath,
  973. staleMarker.replace('"pluginVersion": "', '"pluginVersion": "stale-'),
  974. );
  975. faults.moveTargetSuffix = BROWSER_CACHE_SUFFIX;
  976. await expect(
  977. (async () => await resolveOfficialPluginRoots({ storageRoot }))(),
  978. ).resolves.not.toBeInstanceOf(Error);
  979. expect(await readFile(markerPath, "utf8")).not.toContain('"pluginVersion": "stale-');
  980. faults.moveTargetSuffix = undefined;
  981. await expect(
  982. (async () => await resolveOfficialPluginRoots({ storageRoot }))(),
  983. ).resolves.not.toBeInstanceOf(Error);
  984. await expectNoSeedBackups(browserRoot);
  985. });
  986. it("replaces an overlay lower-layer target when moving it to backup returns EXDEV", async () => {
  987. const storageRoot = await createStorageRoot(cleanups);
  988. await resolveOfficialPluginRoots({ storageRoot });
  989. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  990. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  991. const staleMarker = `${await readFile(markerPath, "utf8")}\n`;
  992. await writeFile(
  993. markerPath,
  994. staleMarker.replace('"pluginVersion": "', '"pluginVersion": "stale-'),
  995. );
  996. const logger = createLogger();
  997. faults.crossDeviceBackupTargetSuffix = BROWSER_CACHE_SUFFIX;
  998. await expect(
  999. (async () =>
  1000. await resolveZCodePlugins({
  1001. logger,
  1002. pluginStorageRoot: storageRoot,
  1003. skipUserConfig: true,
  1004. workingDirectory: dirname(storageRoot),
  1005. }))(),
  1006. ).resolves.not.toBeInstanceOf(Error);
  1007. // 镜像下层的旧缓存无法 rename 成 backup,但仍须被替换成当前内容,而不是每次启动都失败。
  1008. expect(await readFile(markerPath, "utf8")).not.toContain('"pluginVersion": "stale-');
  1009. expect(existsSync(join(browserRoot, ".zcode-plugin", "plugin.json"))).toBe(true);
  1010. await expectNoSeedBackups(browserRoot);
  1011. const siblings = await readdir(dirname(browserRoot));
  1012. expect(siblings.filter((entry) => entry.includes(".tmp-"))).toEqual([]);
  1013. expect(logger.warn).not.toHaveBeenCalledWith(
  1014. "Official plugin cache operation degraded",
  1015. expect.objectContaining({ pluginId: "browser-use@zcode-plugins-official" }),
  1016. );
  1017. });
  1018. it("degrades a persistent EXDEV promotion to a usable previous version", async () => {
  1019. const storageRoot = await createStorageRoot(cleanups);
  1020. expect(await resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  1021. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  1022. const staleRoot = join(dirname(currentRoot), "0.2.1");
  1023. await rename(currentRoot, staleRoot);
  1024. const logger = createLogger();
  1025. faults.crossDevicePromoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  1026. let roots: string[] = [];
  1027. await expect(
  1028. (async () => {
  1029. roots = await resolveOfficialPluginRoots({ logger, storageRoot });
  1030. })(),
  1031. ).resolves.not.toBeInstanceOf(Error);
  1032. expect(roots).toContain(staleRoot);
  1033. expect(logger.warn).toHaveBeenCalledWith(
  1034. "Official plugin cache operation degraded",
  1035. expect.objectContaining({
  1036. degraded: true,
  1037. errorCode: "EXDEV",
  1038. operation: "seed_plugin",
  1039. pluginId: "browser-use@zcode-plugins-official",
  1040. }),
  1041. );
  1042. });
  1043. it("drops the seed marker before deleting an EXDEV target so an interrupted delete reseeds", async () => {
  1044. const storageRoot = await createStorageRoot(cleanups);
  1045. await resolveOfficialPluginRoots({ storageRoot });
  1046. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  1047. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  1048. const manifestPath = join(browserRoot, ".zcode-plugin", "plugin.json");
  1049. // marker 仍是当前版本,但 manifest 已丢失:走「当前缓存不可用 → 重新 seed」分支。
  1050. await rm(manifestPath, { force: true });
  1051. faults.crossDeviceBackupTargetSuffix = BROWSER_CACHE_SUFFIX;
  1052. // 删除旧 target 中途失败,模拟进程在删除窗口内退出。
  1053. faults.removeTargetSuffix = BROWSER_CACHE_SUFFIX;
  1054. await expect(
  1055. (async () => await resolveOfficialPluginRoots({ logger: createLogger(), storageRoot }))(),
  1056. ).resolves.not.toBeInstanceOf(Error);
  1057. // marker 必须先于目录内容删除;否则残缺目录会带着当前版本被下次启动直接复用。
  1058. expect(existsSync(markerPath)).toBe(false);
  1059. faults.removeTargetSuffix = undefined;
  1060. await expect(
  1061. (async () => await resolveOfficialPluginRoots({ storageRoot }))(),
  1062. ).resolves.not.toBeInstanceOf(Error);
  1063. expect(existsSync(manifestPath)).toBe(true);
  1064. expect(existsSync(markerPath)).toBe(true);
  1065. await expectNoSeedBackups(browserRoot);
  1066. });
  1067. it("converges when another process completes the current seed during promotion", async () => {
  1068. const storageRoot = await createStorageRoot(cleanups);
  1069. await resolveOfficialPluginRoots({ storageRoot });
  1070. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  1071. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  1072. const staleMarker = `${await readFile(markerPath, "utf8")}\n`;
  1073. await writeFile(
  1074. markerPath,
  1075. staleMarker.replace('"pluginVersion": "', '"pluginVersion": "stale-'),
  1076. );
  1077. faults.promoteCurrentTargetSuffix = BROWSER_CACHE_SUFFIX;
  1078. await expect(
  1079. (async () => await resolveOfficialPluginRoots({ storageRoot }))(),
  1080. ).resolves.not.toBeInstanceOf(Error);
  1081. expect(await readFile(markerPath, "utf8")).not.toContain('"pluginVersion": "stale-');
  1082. await expectNoSeedBackups(browserRoot);
  1083. });
  1084. it("does not restore a fixed backup that may belong to an active replacement", async () => {
  1085. const storageRoot = await createStorageRoot(cleanups);
  1086. await resolveOfficialPluginRoots({ storageRoot });
  1087. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  1088. const backupRoot = `${browserRoot}.backup`;
  1089. await rename(browserRoot, backupRoot);
  1090. faults.recoverBackupTargetSuffix = BROWSER_CACHE_SUFFIX;
  1091. await expect(
  1092. (async () => await resolveOfficialPluginRoots({ storageRoot }))(),
  1093. ).resolves.not.toBeInstanceOf(Error);
  1094. expect(existsSync(browserRoot)).toBe(true);
  1095. await expectNoSeedBackups(browserRoot);
  1096. });
  1097. it("keeps a current target usable when only runtime manifest refresh is locked", async () => {
  1098. const storageRoot = await createStorageRoot(cleanups);
  1099. await resolveOfficialPluginRoots({ storageRoot });
  1100. const logger = createLogger();
  1101. process.argv[1] = join(storageRoot, "different-zcode.cjs");
  1102. faults.runtimeManifestTargetSuffix = ANDROID_MANIFEST_SUFFIX;
  1103. await expect(
  1104. (async () => await resolveOfficialPluginRoots({ logger, storageRoot }))(),
  1105. ).resolves.not.toBeInstanceOf(Error);
  1106. expect(existsSync(join(storageRoot, ANDROID_CACHE_SUFFIX))).toBe(true);
  1107. expect(logger.warn).toHaveBeenCalledWith(
  1108. "Official plugin cache operation degraded",
  1109. expect.objectContaining({
  1110. degraded: true,
  1111. operation: "seed_plugin",
  1112. pluginId: "android-emulator@zcode-plugins-official",
  1113. }),
  1114. );
  1115. });
  1116. it("keeps a concurrent winner when runtime manifest temporary file disappears", async () => {
  1117. const storageRoot = await createStorageRoot(cleanups);
  1118. await resolveOfficialPluginRoots({ storageRoot });
  1119. const logger = createLogger();
  1120. process.argv[1] = join(storageRoot, "different-zcode.cjs");
  1121. faults.runtimeManifestNotFoundTargetSuffix = ANDROID_MANIFEST_SUFFIX;
  1122. await expect(
  1123. (async () => await resolveOfficialPluginRoots({ logger, storageRoot }))(),
  1124. ).resolves.not.toBeInstanceOf(Error);
  1125. expect(existsSync(join(storageRoot, ANDROID_CACHE_SUFFIX))).toBe(true);
  1126. expect(logger.warn).toHaveBeenCalledWith(
  1127. "Official plugin cache operation degraded",
  1128. expect.objectContaining({
  1129. degraded: true,
  1130. errorCode: "ENOENT",
  1131. operation: "seed_plugin",
  1132. pluginId: "android-emulator@zcode-plugins-official",
  1133. }),
  1134. );
  1135. });
  1136. it("preserves suppressed plugin catalog/cache without attempting a Windows-locked deletion", async () => {
  1137. const storageRoot = await createStorageRoot(cleanups);
  1138. await resolveOfficialPluginRoots({ storageRoot });
  1139. const logger = createLogger();
  1140. faults.removeTargetSuffix = SKILL_CREATOR_CACHE_SUFFIX;
  1141. await expect(
  1142. (async () =>
  1143. await resolveOfficialPluginRoots({
  1144. logger,
  1145. storageRoot,
  1146. suppressedBuiltins: new Set(["skill-creator@zcode-plugins-official"]),
  1147. }))(),
  1148. ).resolves.not.toBeInstanceOf(Error);
  1149. expect(existsSync(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX))).toBe(true);
  1150. const marketplace = JSON.parse(
  1151. await readFile(
  1152. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  1153. "utf8",
  1154. ),
  1155. ) as { plugins: Array<{ name: string }> };
  1156. // 现行契约:suppressedBuiltins 只控制 runtime discovery。catalog/cache 是恢复入口
  1157. // 的不可变资产,不应触发删除;注入的 EPERM 因而不会被命中,也不产生降级告警。
  1158. expect(marketplace.plugins.some((plugin) => plugin.name === "skill-creator")).toBe(true);
  1159. expect(logger.warn).not.toHaveBeenCalledWith(
  1160. "Official plugin cache operation degraded",
  1161. expect.objectContaining({ operation: "remove_suppressed_plugin" }),
  1162. );
  1163. });
  1164. });
  1165. async function createStorageRoot(cleanups: string[]): Promise<string> {
  1166. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-cache-resilience-"));
  1167. cleanups.push(root);
  1168. return join(root, "plugins");
  1169. }
  1170. async function createVersionedSource(storageRoot: string) {
  1171. const entrypointRoot = join(storageRoot, "versioned-source");
  1172. const root = join(entrypointRoot, "packages", "skill-creator-plugin");
  1173. await mkdir(join(root, ".zcode-plugin"), { recursive: true });
  1174. await mkdir(join(root, "skills", "demo"), { recursive: true });
  1175. await writeFile(
  1176. join(root, ".zcode-plugin", "plugin.json"),
  1177. JSON.stringify({ name: "skill-creator", version: "0.1.0" }),
  1178. );
  1179. const payload = join(root, "skills", "demo", "SKILL.md");
  1180. await writeFile(payload, "original source");
  1181. process.argv[1] = join(entrypointRoot, "zcode.cjs");
  1182. faults.watchedSourceRoot = root;
  1183. return { root, payload };
  1184. }
  1185. async function expectNoSeedBackups(targetRoot: string): Promise<void> {
  1186. const targetName = basename(targetRoot);
  1187. const siblings = await readdir(dirname(targetRoot));
  1188. expect(siblings.filter((entry) => entry.startsWith(`${targetName}.backup`))).toEqual([]);
  1189. }
  1190. function createLogger(): Logger & { warn: ReturnType<typeof vi.fn> } {
  1191. const logger = {
  1192. child: () => logger,
  1193. debug: vi.fn(),
  1194. error: vi.fn(),
  1195. info: vi.fn(),
  1196. warn: vi.fn(),
  1197. };
  1198. return logger;
  1199. }
  1200. function exhaustedErrno(code: string): NodeJS.ErrnoException {
  1201. return Object.assign(new Error(code), {
  1202. code,
  1203. zcodeOfficialPluginCacheAttempts: 4,
  1204. });
  1205. }
  1206. function errno(code: string): NodeJS.ErrnoException {
  1207. return Object.assign(new Error(code), { code });
  1208. }