bundled-plugins-resilience.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. import { existsSync } from "node:fs";
  2. import { mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { basename, dirname, join } from "node:path";
  5. import type { Logger } from "@zcode/contracts";
  6. import { afterEach, describe, expect, it, vi } from "vitest";
  7. const faults = vi.hoisted(() => ({
  8. moveTargetSuffix: undefined as string | undefined,
  9. promoteCurrentTargetSuffix: undefined as string | undefined,
  10. promoteTargetSuffix: undefined as string | undefined,
  11. recoverBackupTargetSuffix: undefined as string | undefined,
  12. removeTargetSuffix: undefined as string | undefined,
  13. runtimeManifestNotFoundTargetSuffix: undefined as string | undefined,
  14. runtimeManifestTargetSuffix: undefined as string | undefined,
  15. seedLockHeldTargetSuffixes: [] as string[],
  16. seedLockObservedTimeoutsMs: [] as number[],
  17. }));
  18. vi.mock("../src/app/official-plugin-cache-fs.js", async (importOriginal) => {
  19. const actual = await importOriginal<typeof import("../src/app/official-plugin-cache-fs.js")>();
  20. return {
  21. ...actual,
  22. removeOfficialPluginCacheDirectory(path: string): void {
  23. if (faults.removeTargetSuffix && path.endsWith(faults.removeTargetSuffix)) {
  24. throw exhaustedErrno("EPERM");
  25. }
  26. actual.removeOfficialPluginCacheDirectory(path);
  27. },
  28. renameOfficialPluginCachePath(
  29. fromPath: string,
  30. toPath: string,
  31. budget: ReturnType<typeof actual.createOfficialPluginCacheRetryBudget>,
  32. ): void {
  33. if (
  34. faults.recoverBackupTargetSuffix &&
  35. fromPath === `${toPath}.backup` &&
  36. toPath.endsWith(faults.recoverBackupTargetSuffix)
  37. ) {
  38. throw errno("EOWNER");
  39. }
  40. if (
  41. faults.moveTargetSuffix &&
  42. fromPath.endsWith(faults.moveTargetSuffix) &&
  43. toPath.startsWith(`${fromPath}.backup-`)
  44. ) {
  45. actual.removeOfficialPluginCacheDirectory(fromPath, budget);
  46. throw errno("ENOENT");
  47. }
  48. if (
  49. faults.promoteCurrentTargetSuffix &&
  50. fromPath.includes(".tmp-") &&
  51. toPath.endsWith(faults.promoteCurrentTargetSuffix)
  52. ) {
  53. actual.renameOfficialPluginCachePath(fromPath, toPath, budget);
  54. throw errno("EEXIST");
  55. }
  56. if (
  57. faults.promoteTargetSuffix &&
  58. fromPath.includes(".tmp-") &&
  59. toPath.endsWith(faults.promoteTargetSuffix)
  60. ) {
  61. throw exhaustedErrno("EPERM");
  62. }
  63. actual.renameOfficialPluginCachePath(fromPath, toPath, budget);
  64. },
  65. writeTextFileAtomicallyWithRetry(
  66. path: string,
  67. contents: string,
  68. budget: ReturnType<typeof actual.createOfficialPluginCacheRetryBudget>,
  69. ): void {
  70. if (
  71. faults.runtimeManifestNotFoundTargetSuffix &&
  72. path.endsWith(faults.runtimeManifestNotFoundTargetSuffix)
  73. ) {
  74. throw errno("ENOENT");
  75. }
  76. if (faults.runtimeManifestTargetSuffix && path.endsWith(faults.runtimeManifestTargetSuffix)) {
  77. throw exhaustedErrno("EPERM");
  78. }
  79. actual.writeTextFileAtomicallyWithRetry(path, contents, budget);
  80. },
  81. };
  82. });
  83. vi.mock("../src/app/official-plugin-seed-lock.js", async (importOriginal) => {
  84. const actual = await importOriginal<typeof import("../src/app/official-plugin-seed-lock.js")>();
  85. return {
  86. ...actual,
  87. withOfficialPluginSeedLock<T>(
  88. targetRoot: string,
  89. action: () => T,
  90. options?: Parameters<typeof actual.withOfficialPluginSeedLock>[2],
  91. ): T {
  92. if (!faults.seedLockHeldTargetSuffixes.some((suffix) => targetRoot.endsWith(suffix))) {
  93. return actual.withOfficialPluginSeedLock(targetRoot, action, options);
  94. }
  95. faults.seedLockObservedTimeoutsMs.push(options?.timeoutMs ?? -1);
  96. // 只压缩等待参数并保留调用方预算上限(默认 15s 会拖垮测试),
  97. // 仍走真实锁竞争与真实超时错误。
  98. return actual.withOfficialPluginSeedLock(targetRoot, action, {
  99. ...options,
  100. retryDelayMs: 1,
  101. timeoutMs: Math.min(10, options?.timeoutMs ?? 10),
  102. });
  103. },
  104. };
  105. });
  106. import { resolveOfficialPluginRoots } from "../src/app/bundled-plugins.js";
  107. import { OFFICIAL_PLUGIN_DEFINITIONS } from "../src/app/official-plugin-definitions.js";
  108. import { resolveZCodePlugins } from "../src/plugins.js";
  109. const OFFICIAL_CACHE_ROOT = join("cache", "zcode-plugins-official");
  110. const BROWSER_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, "browser-use", "0.5.1");
  111. const ANDROID_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, "android-emulator", "0.1.0");
  112. const SKILL_CREATOR_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, "skill-creator", "0.1.0");
  113. const ANDROID_MANIFEST_SUFFIX = join(ANDROID_CACHE_SUFFIX, ".zcode-plugin", "plugin.json");
  114. const CUA_DEFINITION = OFFICIAL_PLUGIN_DEFINITIONS.find(({ name }) => name === "computer-use");
  115. if (!CUA_DEFINITION) throw new Error("computer-use official plugin definition is missing");
  116. const CUA_CACHE_SUFFIX = join(OFFICIAL_CACHE_ROOT, CUA_DEFINITION.name, CUA_DEFINITION.version);
  117. describe("bundled official plugin cache resilience", () => {
  118. const cleanups: string[] = [];
  119. const originalEntrypoint = process.argv[1];
  120. afterEach(async () => {
  121. process.argv[1] = originalEntrypoint;
  122. faults.moveTargetSuffix = undefined;
  123. faults.promoteCurrentTargetSuffix = undefined;
  124. faults.promoteTargetSuffix = undefined;
  125. faults.recoverBackupTargetSuffix = undefined;
  126. faults.removeTargetSuffix = undefined;
  127. faults.runtimeManifestNotFoundTargetSuffix = undefined;
  128. faults.runtimeManifestTargetSuffix = undefined;
  129. faults.seedLockHeldTargetSuffixes = [];
  130. faults.seedLockObservedTimeoutsMs = [];
  131. await Promise.all(cleanups.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  132. });
  133. it("degrades a persistent transient seed failure when the target is absent", async () => {
  134. const storageRoot = await createStorageRoot(cleanups);
  135. const logger = createLogger();
  136. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  137. expect(() => resolveOfficialPluginRoots({ logger, storageRoot })).not.toThrow();
  138. expect(existsSync(join(storageRoot, BROWSER_CACHE_SUFFIX))).toBe(false);
  139. expect(existsSync(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX))).toBe(true);
  140. expect(logger.warn).toHaveBeenCalledWith(
  141. "Official plugin cache operation degraded",
  142. expect.objectContaining({
  143. attempts: 4,
  144. degraded: true,
  145. errorCode: "EPERM",
  146. operation: "seed_plugin",
  147. pluginId: "browser-use@zcode-plugins-official",
  148. }),
  149. );
  150. });
  151. it("keeps degraded cache diagnostics through the ordinary plugin resolver", async () => {
  152. const storageRoot = await createStorageRoot(cleanups);
  153. const logger = createLogger();
  154. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  155. expect(() =>
  156. resolveZCodePlugins({
  157. logger,
  158. pluginStorageRoot: storageRoot,
  159. skipUserConfig: true,
  160. workingDirectory: dirname(storageRoot),
  161. }),
  162. ).not.toThrow();
  163. expect(logger.warn).toHaveBeenCalledWith(
  164. "Official plugin cache operation degraded",
  165. expect.objectContaining({
  166. degraded: true,
  167. errorCode: "EPERM",
  168. pluginId: "browser-use@zcode-plugins-official",
  169. }),
  170. );
  171. });
  172. it("keeps a stale but usable target when promotion fails", async () => {
  173. const storageRoot = await createStorageRoot(cleanups);
  174. resolveOfficialPluginRoots({ storageRoot });
  175. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  176. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  177. const staleMarker = `${await readFile(markerPath, "utf8")}\n`;
  178. await writeFile(markerPath, staleMarker.replace('"hash": "', '"hash": "stale-'));
  179. const logger = createLogger();
  180. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  181. expect(() => resolveOfficialPluginRoots({ logger, storageRoot })).not.toThrow();
  182. expect(existsSync(browserRoot)).toBe(true);
  183. expect(await readFile(markerPath, "utf8")).toContain('"hash": "stale-');
  184. expect(logger.warn).toHaveBeenCalledWith(
  185. "Official plugin cache operation degraded",
  186. expect.objectContaining({
  187. errorCode: "EPERM",
  188. operation: "seed_plugin",
  189. pluginId: "browser-use@zcode-plugins-official",
  190. }),
  191. );
  192. });
  193. it("falls back to a previous usable version when the new target cannot be promoted", async () => {
  194. const storageRoot = await createStorageRoot(cleanups);
  195. expect(resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  196. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  197. const staleRoot = join(dirname(currentRoot), "0.2.1");
  198. await rename(currentRoot, staleRoot);
  199. faults.promoteTargetSuffix = BROWSER_CACHE_SUFFIX;
  200. const roots = resolveOfficialPluginRoots({ storageRoot });
  201. expect(roots).toContain(staleRoot);
  202. });
  203. it("degrades an incomplete seed source to a usable previous version instead of failing startup", async () => {
  204. const storageRoot = await createStorageRoot(cleanups);
  205. expect(resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  206. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  207. const staleRoot = join(dirname(currentRoot), "0.2.1");
  208. await rename(currentRoot, staleRoot);
  209. await rm(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX), { force: true, recursive: true });
  210. // 入口目录旁只有一份缺 dist/docs/skills 的 browser-use 拷贝(升级中的桌面包、
  211. // 未构建 dist 的旧 checkout);其余插件继续从真实 monorepo 源解析。
  212. const entrypointRoot = join(storageRoot, "stale-entrypoint");
  213. const incompletePluginRoot = join(entrypointRoot, "packages", "browser-use-plugin");
  214. await mkdir(join(incompletePluginRoot, ".zcode-plugin"), { recursive: true });
  215. await writeFile(
  216. join(incompletePluginRoot, ".zcode-plugin", "plugin.json"),
  217. JSON.stringify({ name: "browser-use", version: "0.5.1" }),
  218. );
  219. process.argv[1] = join(entrypointRoot, "zcode.cjs");
  220. const logger = createLogger();
  221. let roots: string[] = [];
  222. expect(() => {
  223. roots = resolveOfficialPluginRoots({ logger, storageRoot });
  224. }).not.toThrow();
  225. expect(roots).toContain(staleRoot);
  226. // 残缺源绝不能落成当前版本缓存(会永久命中 hash),也不能拖垮其他插件的 seeding。
  227. expect(existsSync(currentRoot)).toBe(false);
  228. expect(existsSync(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX))).toBe(true);
  229. const marketplace = JSON.parse(
  230. await readFile(
  231. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  232. "utf8",
  233. ),
  234. ) as { plugins: Array<{ name: string }> };
  235. expect(marketplace.plugins.some((plugin) => plugin.name === "browser-use")).toBe(true);
  236. expect(logger.warn).toHaveBeenCalledWith(
  237. "Official plugin cache operation degraded",
  238. expect.objectContaining({
  239. degraded: true,
  240. errorCode: "ZCODE_PLUGIN_SEED_INCOMPLETE",
  241. // browser-use 不再携带 node_repl 宿主产物(那是 node-repl-host 的),
  242. // 它自己必需的运行时资产是 browser-client。
  243. missingSeedPaths: expect.arrayContaining(["scripts/browser-client.mjs"]),
  244. operation: "seed_plugin",
  245. pluginId: "browser-use@zcode-plugins-official",
  246. }),
  247. );
  248. });
  249. it("keeps session bootstrap alive when an incomplete seed source has no usable fallback cache", async () => {
  250. const storageRoot = await createStorageRoot(cleanups);
  251. // 全新安装:storageRoot 从未 seed 过,也没有任何旧版本缓存可回退。
  252. const entrypointRoot = join(storageRoot, "fresh-install-entrypoint");
  253. const incompletePluginRoot = join(entrypointRoot, "packages", "browser-use-plugin");
  254. await mkdir(join(incompletePluginRoot, ".zcode-plugin"), { recursive: true });
  255. await writeFile(
  256. join(incompletePluginRoot, ".zcode-plugin", "plugin.json"),
  257. JSON.stringify({ name: "browser-use", version: "0.5.1" }),
  258. );
  259. process.argv[1] = join(entrypointRoot, "zcode.cjs");
  260. const logger = createLogger();
  261. let outcome!: ReturnType<typeof resolveZCodePlugins>;
  262. expect(() => {
  263. outcome = resolveZCodePlugins({
  264. logger,
  265. pluginStorageRoot: storageRoot,
  266. skipUserConfig: true,
  267. workingDirectory: dirname(storageRoot),
  268. });
  269. }).not.toThrow();
  270. // 降级终态之二:无可用旧缓存时该插件本次缺席(不写残缺缓存),只留 warning 级诊断,
  271. // 其余 defaultEnabled 插件与会话引导不受影响。
  272. expect(existsSync(join(storageRoot, BROWSER_CACHE_SUFFIX))).toBe(false);
  273. expect(
  274. outcome.plugins.find((plugin) => plugin.id === "browser-use@zcode-plugins-official"),
  275. ).toBeUndefined();
  276. const rootNotFound = outcome.diagnostics.filter(
  277. (diagnostic) => diagnostic.code === "plugin_root_not_found",
  278. );
  279. expect(rootNotFound).toEqual([
  280. expect.objectContaining({
  281. path: join(storageRoot, BROWSER_CACHE_SUFFIX),
  282. severity: "warning",
  283. }),
  284. ]);
  285. const documentSkills = outcome.plugins.find(
  286. (plugin) => plugin.id === "documents@zcode-plugins-official",
  287. );
  288. expect(documentSkills?.enabled).toBe(true);
  289. expect(logger.warn).toHaveBeenCalledWith(
  290. "Official plugin cache operation degraded",
  291. expect.objectContaining({
  292. errorCode: "ZCODE_PLUGIN_SEED_INCOMPLETE",
  293. operation: "seed_plugin",
  294. pluginId: "browser-use@zcode-plugins-official",
  295. }),
  296. );
  297. });
  298. it("degrades a held seed lock to a usable previous version instead of failing startup", async () => {
  299. const storageRoot = await createStorageRoot(cleanups);
  300. expect(resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  301. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  302. const staleRoot = join(dirname(currentRoot), "0.2.1");
  303. await rename(currentRoot, staleRoot);
  304. const lockRoot = `${currentRoot}.seed-lock`;
  305. await mkdir(lockRoot, { recursive: true });
  306. await writeFile(
  307. join(lockRoot, "owner.json"),
  308. JSON.stringify({ createdAt: new Date().toISOString(), pid: process.pid }),
  309. );
  310. const logger = createLogger();
  311. faults.seedLockHeldTargetSuffixes = [BROWSER_CACHE_SUFFIX];
  312. let roots: string[] = [];
  313. expect(() => {
  314. roots = resolveOfficialPluginRoots({ logger, storageRoot });
  315. }).not.toThrow();
  316. expect(roots).toContain(staleRoot);
  317. // 锁属于「另一个进程」(owner 存活),降级方绝不能顺手删掉它。
  318. expect(existsSync(lockRoot)).toBe(true);
  319. expect(logger.warn).toHaveBeenCalledWith(
  320. "Official plugin cache operation degraded",
  321. expect.objectContaining({
  322. degraded: true,
  323. errorCode: "ZCODE_PLUGIN_SEED_LOCK_TIMEOUT",
  324. operation: "seed_plugin",
  325. pluginId: "browser-use@zcode-plugins-official",
  326. }),
  327. );
  328. });
  329. it("shares one seed lock wait budget across all plugins", async () => {
  330. const storageRoot = await createStorageRoot(cleanups);
  331. expect(resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  332. for (const cacheSuffix of [BROWSER_CACHE_SUFFIX, SKILL_CREATOR_CACHE_SUFFIX]) {
  333. const lockRoot = `${join(storageRoot, cacheSuffix)}.seed-lock`;
  334. await mkdir(lockRoot, { recursive: true });
  335. await writeFile(
  336. join(lockRoot, "owner.json"),
  337. JSON.stringify({ createdAt: new Date().toISOString(), pid: process.pid }),
  338. );
  339. }
  340. faults.seedLockHeldTargetSuffixes = [BROWSER_CACHE_SUFFIX, SKILL_CREATOR_CACHE_SUFFIX];
  341. expect(() => resolveOfficialPluginRoots({ storageRoot })).not.toThrow();
  342. // 两把被持有的锁必须共享同一截止时间:后一次调用拿到的剩余预算严格更小,
  343. // 而不是每个插件都重置成完整的 15s(否则成组遗留锁会让启动冻结 N×15s)。
  344. expect(faults.seedLockObservedTimeoutsMs).toHaveLength(2);
  345. const [firstBudgetMs, secondBudgetMs] = faults.seedLockObservedTimeoutsMs;
  346. expect(firstBudgetMs).toBeGreaterThan(0);
  347. expect(firstBudgetMs).toBeLessThanOrEqual(15_000);
  348. expect(secondBudgetMs).toBeLessThan(firstBudgetMs as number);
  349. });
  350. it("keeps an intact current cache discoverable when the seed lock times out", async () => {
  351. const storageRoot = await createStorageRoot(cleanups);
  352. expect(resolveOfficialPluginRoots({ storageRoot })).toEqual([]);
  353. // 当前版本目录保持完整(不 rename 成旧版本),只把锁交给「另一个存活进程」。
  354. const currentRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  355. const lockRoot = `${currentRoot}.seed-lock`;
  356. await mkdir(lockRoot, { recursive: true });
  357. await writeFile(
  358. join(lockRoot, "owner.json"),
  359. JSON.stringify({ createdAt: new Date().toISOString(), pid: process.pid }),
  360. );
  361. const logger = createLogger();
  362. faults.seedLockHeldTargetSuffixes = [BROWSER_CACHE_SUFFIX];
  363. const outcome = resolveZCodePlugins({
  364. logger,
  365. pluginStorageRoot: storageRoot,
  366. skipUserConfig: true,
  367. workingDirectory: dirname(storageRoot),
  368. });
  369. expect(logger.warn).toHaveBeenCalledWith(
  370. "Official plugin cache operation degraded",
  371. expect.objectContaining({
  372. errorCode: "ZCODE_PLUGIN_SEED_LOCK_TIMEOUT",
  373. operation: "seed_plugin",
  374. pluginId: "browser-use@zcode-plugins-official",
  375. }),
  376. );
  377. // 锁只保护 seed 写入,不保护读取:等锁超时不能让一份完整的当前缓存从 discovery 消失。
  378. // 该不变量依赖 bundled marketplace 分片在 seeding 循环之前写入且不按 seed 成败过滤;
  379. // 若未来把分片写入挪到循环之后,这条断言会失败。
  380. const browserPlugin = outcome.plugins.find(
  381. (plugin) => plugin.id === "browser-use@zcode-plugins-official",
  382. );
  383. expect(browserPlugin?.rootPath).toBe(currentRoot);
  384. expect(browserPlugin?.enabled).toBe(true);
  385. expect(
  386. outcome.diagnostics.filter((diagnostic) => diagnostic.code === "plugin_root_not_found"),
  387. ).toEqual([]);
  388. });
  389. it("does not mix an old zcode-cua cache with the current consumer contract", async () => {
  390. const storageRoot = await createStorageRoot(cleanups);
  391. resolveOfficialPluginRoots({ storageRoot });
  392. const currentRoot = join(storageRoot, CUA_CACHE_SUFFIX);
  393. const staleRoot = join(dirname(currentRoot), "0.5.9");
  394. await rename(currentRoot, staleRoot);
  395. faults.promoteTargetSuffix = CUA_CACHE_SUFFIX;
  396. const roots = resolveOfficialPluginRoots({ storageRoot });
  397. expect(roots).not.toContain(staleRoot);
  398. });
  399. it("continues when another process moves the target after the existence check", async () => {
  400. const storageRoot = await createStorageRoot(cleanups);
  401. resolveOfficialPluginRoots({ storageRoot });
  402. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  403. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  404. const staleMarker = `${await readFile(markerPath, "utf8")}\n`;
  405. await writeFile(markerPath, staleMarker.replace('"hash": "', '"hash": "stale-'));
  406. faults.moveTargetSuffix = BROWSER_CACHE_SUFFIX;
  407. expect(() => resolveOfficialPluginRoots({ storageRoot })).not.toThrow();
  408. expect(await readFile(markerPath, "utf8")).not.toContain('"hash": "stale-');
  409. faults.moveTargetSuffix = undefined;
  410. expect(() => resolveOfficialPluginRoots({ storageRoot })).not.toThrow();
  411. await expectNoSeedBackups(browserRoot);
  412. });
  413. it("converges when another process completes the current seed during promotion", async () => {
  414. const storageRoot = await createStorageRoot(cleanups);
  415. resolveOfficialPluginRoots({ storageRoot });
  416. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  417. const markerPath = join(browserRoot, ".zcode-plugin-seed.json");
  418. const staleMarker = `${await readFile(markerPath, "utf8")}\n`;
  419. await writeFile(markerPath, staleMarker.replace('"hash": "', '"hash": "stale-'));
  420. faults.promoteCurrentTargetSuffix = BROWSER_CACHE_SUFFIX;
  421. expect(() => resolveOfficialPluginRoots({ storageRoot })).not.toThrow();
  422. expect(await readFile(markerPath, "utf8")).not.toContain('"hash": "stale-');
  423. await expectNoSeedBackups(browserRoot);
  424. });
  425. it("does not restore a fixed backup that may belong to an active replacement", async () => {
  426. const storageRoot = await createStorageRoot(cleanups);
  427. resolveOfficialPluginRoots({ storageRoot });
  428. const browserRoot = join(storageRoot, BROWSER_CACHE_SUFFIX);
  429. const backupRoot = `${browserRoot}.backup`;
  430. await rename(browserRoot, backupRoot);
  431. faults.recoverBackupTargetSuffix = BROWSER_CACHE_SUFFIX;
  432. expect(() => resolveOfficialPluginRoots({ storageRoot })).not.toThrow();
  433. expect(existsSync(browserRoot)).toBe(true);
  434. await expectNoSeedBackups(browserRoot);
  435. });
  436. it("keeps a current target usable when only runtime manifest refresh is locked", async () => {
  437. const storageRoot = await createStorageRoot(cleanups);
  438. resolveOfficialPluginRoots({ storageRoot });
  439. const logger = createLogger();
  440. process.argv[1] = join(storageRoot, "different-zcode.cjs");
  441. faults.runtimeManifestTargetSuffix = ANDROID_MANIFEST_SUFFIX;
  442. expect(() => resolveOfficialPluginRoots({ logger, storageRoot })).not.toThrow();
  443. expect(existsSync(join(storageRoot, ANDROID_CACHE_SUFFIX))).toBe(true);
  444. expect(logger.warn).toHaveBeenCalledWith(
  445. "Official plugin cache operation degraded",
  446. expect.objectContaining({
  447. degraded: true,
  448. operation: "seed_plugin",
  449. pluginId: "android-emulator@zcode-plugins-official",
  450. }),
  451. );
  452. });
  453. it("keeps a concurrent winner when runtime manifest temporary file disappears", async () => {
  454. const storageRoot = await createStorageRoot(cleanups);
  455. resolveOfficialPluginRoots({ storageRoot });
  456. const logger = createLogger();
  457. process.argv[1] = join(storageRoot, "different-zcode.cjs");
  458. faults.runtimeManifestNotFoundTargetSuffix = ANDROID_MANIFEST_SUFFIX;
  459. expect(() => resolveOfficialPluginRoots({ logger, storageRoot })).not.toThrow();
  460. expect(existsSync(join(storageRoot, ANDROID_CACHE_SUFFIX))).toBe(true);
  461. expect(logger.warn).toHaveBeenCalledWith(
  462. "Official plugin cache operation degraded",
  463. expect.objectContaining({
  464. degraded: true,
  465. errorCode: "ENOENT",
  466. operation: "seed_plugin",
  467. pluginId: "android-emulator@zcode-plugins-official",
  468. }),
  469. );
  470. });
  471. it("preserves suppressed plugin catalog/cache without attempting a Windows-locked deletion", async () => {
  472. const storageRoot = await createStorageRoot(cleanups);
  473. resolveOfficialPluginRoots({ storageRoot });
  474. const logger = createLogger();
  475. faults.removeTargetSuffix = SKILL_CREATOR_CACHE_SUFFIX;
  476. expect(() =>
  477. resolveOfficialPluginRoots({
  478. logger,
  479. storageRoot,
  480. suppressedBuiltins: new Set(["skill-creator@zcode-plugins-official"]),
  481. }),
  482. ).not.toThrow();
  483. expect(existsSync(join(storageRoot, SKILL_CREATOR_CACHE_SUFFIX))).toBe(true);
  484. const marketplace = JSON.parse(
  485. await readFile(
  486. join(storageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  487. "utf8",
  488. ),
  489. ) as { plugins: Array<{ name: string }> };
  490. // 现行契约:suppressedBuiltins 只控制 runtime discovery。catalog/cache 是恢复入口
  491. // 的不可变资产,不应触发删除;注入的 EPERM 因而不会被命中,也不产生降级告警。
  492. expect(marketplace.plugins.some((plugin) => plugin.name === "skill-creator")).toBe(true);
  493. expect(logger.warn).not.toHaveBeenCalledWith(
  494. "Official plugin cache operation degraded",
  495. expect.objectContaining({ operation: "remove_suppressed_plugin" }),
  496. );
  497. });
  498. });
  499. async function createStorageRoot(cleanups: string[]): Promise<string> {
  500. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-cache-resilience-"));
  501. cleanups.push(root);
  502. return join(root, "plugins");
  503. }
  504. async function expectNoSeedBackups(targetRoot: string): Promise<void> {
  505. const targetName = basename(targetRoot);
  506. const siblings = await readdir(dirname(targetRoot));
  507. expect(siblings.filter((entry) => entry.startsWith(`${targetName}.backup`))).toEqual([]);
  508. }
  509. function createLogger(): Logger & { warn: ReturnType<typeof vi.fn> } {
  510. const logger = {
  511. child: () => logger,
  512. debug: vi.fn(),
  513. error: vi.fn(),
  514. info: vi.fn(),
  515. warn: vi.fn(),
  516. };
  517. return logger;
  518. }
  519. function exhaustedErrno(code: string): NodeJS.ErrnoException {
  520. return Object.assign(new Error(code), {
  521. code,
  522. zcodeOfficialPluginCacheAttempts: 4,
  523. });
  524. }
  525. function errno(code: string): NodeJS.ErrnoException {
  526. return Object.assign(new Error(code), { code });
  527. }