bundled-plugins-resilience.test.ts 29 KB

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