probe.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. import assert from "node:assert/strict";
  2. import { access, mkdir, readFile, writeFile, symlink } from "node:fs/promises";
  3. import { delimiter, join, dirname } from "node:path";
  4. import {
  5. agentCommand,
  6. bash,
  7. config,
  8. directory,
  9. docs,
  10. tools,
  11. entries,
  12. entryDefinition,
  13. entryPath,
  14. hash,
  15. isWindows,
  16. record,
  17. put,
  18. get,
  19. execute,
  20. selected,
  21. plugin,
  22. tree,
  23. snapshots,
  24. ancestors,
  25. assertSameAgent,
  26. } from "./runtime.mjs";
  27. // 应用签名只有 macOS 有;其他平台没有对应的系统级校验,不伪造通过。
  28. const verifySignatures = async () => {
  29. if (process.platform !== "darwin") return "not-applicable";
  30. await execute("/usr/bin/codesign", [
  31. "--verify",
  32. "--deep",
  33. "--strict",
  34. join((await record("libreoffice")).installationDir, "LibreOffice.app"),
  35. ]);
  36. await execute("/usr/bin/codesign", ["--verify", "--deep", "--strict", config.systemApplication]);
  37. return "valid-before-and-after";
  38. };
  39. const sameFile = (actual, expected) =>
  40. isWindows ? actual?.toLowerCase() === expected.toLowerCase() : actual === expected;
  41. assert.equal(process.env.ZCODE_PREINSTALLED_TOOLS_AVAILABLE, "1");
  42. assert.ok(sameFile(process.env.PATH.split(delimiter)[0], join(config.root, "bin")));
  43. assert.equal(process.env.PYTHONDONTWRITEBYTECODE, undefined);
  44. assert.equal(process.env.PYTHONPYCACHEPREFIX, undefined);
  45. const phase = process.argv[2];
  46. const documentChecks = join(directory, "document_checks.py");
  47. const workbook = join(docs, "公式 样例.xlsx");
  48. const selection = async () =>
  49. Object.fromEntries(
  50. await Promise.all(tools.map(async (id) => [id, await Promise.all(entries[id].map(selected))])),
  51. );
  52. let result;
  53. if (phase === "before") {
  54. for (const id of tools)
  55. await assert.rejects(access(join(config.root, "tools", id, "installation.json")), {
  56. code: "ENOENT",
  57. });
  58. // macOS 在隔离 HOME 下放系统应用链接;Windows 的系统 LibreOffice 本来就在 Program Files,由插件正常发现。
  59. if (process.platform === "darwin") {
  60. const applications = join(dirname(config.storageRoot), "Applications");
  61. await mkdir(applications, { recursive: true });
  62. await symlink(config.systemApplication, join(applications, "LibreOffice.app"));
  63. }
  64. const systemOnlyPath = isWindows
  65. ? [join(process.env.SystemRoot, "System32"), process.env.SystemRoot].join(delimiter)
  66. : "/usr/bin:/bin";
  67. const documents = await plugin("documents");
  68. const initial = await execute(
  69. config.python,
  70. [join(documents, "scripts/zcode_libreoffice.py"), "check"],
  71. 0,
  72. { env: { ...process.env, PATH: systemOnlyPath } },
  73. );
  74. const systemCheck = JSON.parse(initial.stdout);
  75. assert.equal(systemCheck.source, "system");
  76. await execute(config.python, [documentChecks, "prepare"]);
  77. const inputHashes = Object.fromEntries(
  78. await Promise.all(
  79. [
  80. "中文 字体验收.docx",
  81. "中文 字体验收.pptx",
  82. "legacy/中文 字体验收.doc",
  83. "公式 样例.xlsx",
  84. ].map(async (name) => [name, await hash(join(docs, name))]),
  85. ),
  86. );
  87. const profile = await tree(config.defaultProfile);
  88. await put("default-profile-before", profile);
  89. result = {
  90. inputHashes,
  91. snapshots: await snapshots(),
  92. ancestors: await ancestors(),
  93. systemCheck,
  94. systemNotice: initial.stderr,
  95. selected: await selection(),
  96. defaultProfileFiles: Object.keys(profile).length,
  97. };
  98. } else if (phase === "main") {
  99. const continuity = await assertSameAgent();
  100. const initial = await get("before");
  101. for (const [name, digest] of Object.entries(initial.inputHashes))
  102. assert.equal(await hash(join(docs, name)), digest);
  103. const installed = Object.fromEntries(
  104. await Promise.all(tools.map(async (id) => [id, await record(id)])),
  105. );
  106. const pythonBase = join(installed.python.installationDir, "python");
  107. await put("python-base-before", await tree(pythonBase));
  108. const roots = Object.fromEntries(
  109. await Promise.all(
  110. ["documents", "pdf", "spreadsheets", "presentations"].map(async (name) => [
  111. name,
  112. await plugin(name),
  113. ]),
  114. ),
  115. );
  116. await put(
  117. "plugins",
  118. Object.fromEntries(
  119. await Promise.all(
  120. Object.entries(roots).map(async ([name, path]) => [
  121. name,
  122. {
  123. path,
  124. metadata: JSON.parse(await readFile(join(path, ".zcode-plugin/plugin.json"), "utf8")),
  125. },
  126. ]),
  127. ),
  128. ),
  129. );
  130. for (const id of tools)
  131. for (const name of entries[id])
  132. assert.ok(sameFile(await selected(name), entryPath(name)), `${name} 未解析到预装入口`);
  133. await verifySignatures();
  134. const runPlugin = (label, path, args, expected = 0) =>
  135. execute("zcode-python", [documentChecks, "run", label, path, ...args], expected);
  136. await runPlugin(
  137. "documents",
  138. join(roots.documents, "skills/docx/scripts/add_toc_placeholders.py"),
  139. [join(docs, "目录.docx"), "--auto"],
  140. );
  141. const palette = await runPlugin("pdf", join(roots.pdf, "skills/pdf/scripts/pdf.py"), [
  142. "palette.generate",
  143. "--title",
  144. "预装验收",
  145. "--format",
  146. "json",
  147. "--seed",
  148. "12",
  149. ]);
  150. await writeFile(join(directory, "palette.json"), palette.stdout);
  151. await execute("zcode-python", [documentChecks, "report"]);
  152. for (const name of ["Word PDF", "PPT PDF", "旧文档"])
  153. await mkdir(join(docs, name), { recursive: true });
  154. // 两个独立文档并行转换,复用真实插件的隔离配置;不会共享用户默认 profile。
  155. await Promise.all([
  156. runPlugin("word-conversion", join(roots.documents, "scripts/zcode_libreoffice.py"), [
  157. "run",
  158. "--",
  159. "--convert-to",
  160. "pdf",
  161. "--outdir",
  162. join(docs, "Word PDF"),
  163. join(docs, "中文 字体验收.docx"),
  164. ]),
  165. runPlugin("presentations", join(roots.presentations, "scripts/zcode_libreoffice.py"), [
  166. "run",
  167. "--",
  168. "--convert-to",
  169. "pdf",
  170. "--outdir",
  171. join(docs, "PPT PDF"),
  172. join(docs, "中文 字体验收.pptx"),
  173. ]),
  174. ]);
  175. await runPlugin("legacy-word", join(roots.documents, "scripts/zcode_libreoffice.py"), [
  176. "run",
  177. "--",
  178. "--convert-to",
  179. "docx",
  180. "--outdir",
  181. join(docs, "旧文档"),
  182. join(docs, "legacy/中文 字体验收.doc"),
  183. ]);
  184. await runPlugin("office", join(roots.pdf, "skills/pdf/scripts/pdf.py"), [
  185. "convert.office",
  186. join(docs, "中文 字体验收.docx"),
  187. "--output",
  188. join(docs, "Office PDF.pdf"),
  189. ]);
  190. const recalc = JSON.parse(
  191. (
  192. await runPlugin(
  193. "spreadsheets",
  194. join(roots.spreadsheets, "skills/xlsx/xlsx.py"),
  195. ["recalc", workbook, "120"],
  196. 1,
  197. )
  198. ).stdout,
  199. );
  200. assert.equal(recalc.status, "errors_found");
  201. assert.equal(recalc.total_errors, 1);
  202. assert.equal(recalc.total_formulas, 2);
  203. assert.equal(recalc.libreoffice_source, "managed");
  204. assert.deepEqual(recalc.error_summary["#DIV/0!"].locations, ["Sheet!D1"]);
  205. await put("recalculation", recalc);
  206. await runPlugin("pdf2image", join(roots.pdf, "skills/pdf/scripts/pdf.py"), [
  207. "form.render",
  208. join(docs, "Word PDF/中文 字体验收.pdf"),
  209. join(docs, "Word images"),
  210. ]);
  211. await execute("pdftoppm", [
  212. "-png",
  213. "-r",
  214. "110",
  215. join(docs, "PPT PDF/中文 字体验收.pdf"),
  216. join(docs, "PPT PDF/slide"),
  217. ]);
  218. await execute("zcode-python", [documentChecks, "check"]);
  219. const checks = await get("document-results");
  220. const render = await get("runtime-pdf2image");
  221. // pdf2image 在 Windows 上调用 pdftoppm.exe;两种写法都按 PATH 上实际解析到的程序核对。
  222. const pdftoppm = render.subprocesses.filter((item) =>
  223. /^pdftoppm(?:\.exe)?$/i.test(item.executable),
  224. );
  225. assert.ok(pdftoppm.length > 0);
  226. const binDir = join(config.root, "bin");
  227. assert.ok(
  228. pdftoppm.every(
  229. (item) =>
  230. sameFile(item.resolved, join(binDir, "pdftoppm")) ||
  231. (isWindows &&
  232. item.resolved?.toLowerCase().startsWith(`${binDir.toLowerCase()}\\pdftoppm.`)),
  233. ),
  234. JSON.stringify(pdftoppm),
  235. );
  236. for (const name of ["documents", "pdf", "spreadsheets", "presentations", "pdf2image"]) {
  237. const receipt = await get(`runtime-${name}`);
  238. assert.ok(receipt.executable.startsWith(join(installed.python.installationDir, "overlay")));
  239. // PDF/xlsx已有脚本会自行禁写缓存;入口默认策略在脚本执行前取证,不改插件行为。
  240. assert.equal(receipt.startupPolicy.dontWriteBytecode, false);
  241. assert.equal(receipt.startupPolicy.pycachePrefix, null);
  242. assert.equal(receipt.pycachePrefix, null);
  243. }
  244. const defaultImports = JSON.parse(
  245. (
  246. await execute("zcode-python", [
  247. "-c",
  248. "import sys,json; assert not sys.dont_write_bytecode; assert sys.pycache_prefix is None; import openpyxl,xlsxwriter,defusedxml,docx,lxml,reportlab,pypdf,pikepdf,pdfplumber,pypdfium2,pdf2image,PIL,pptx,matplotlib,pandas,numpy; print(json.dumps({'dontWriteBytecode':sys.dont_write_bytecode,'pycachePrefix':sys.pycache_prefix,'executable':sys.executable}))",
  249. ])
  250. ).stdout,
  251. );
  252. await put("default-cache-imports", defaultImports);
  253. await execute("zcode-python", [
  254. "-m",
  255. "pip",
  256. "install",
  257. "--no-index",
  258. "--no-deps",
  259. join(docs, "zcode_full_chain_probe-1.0-py3-none-any.whl"),
  260. ]);
  261. const addon = JSON.parse(
  262. (
  263. await execute("zcode-python", [
  264. "-c",
  265. "import json,zcode_full_chain_probe as p;print(json.dumps({'value':p.value,'path':p.__file__}))",
  266. ])
  267. ).stdout,
  268. );
  269. assert.equal(addon.value, "overlay-only");
  270. assert.ok(addon.path.startsWith(join(installed.python.installationDir, "overlay")));
  271. await put("addon", addon);
  272. await writeFile(
  273. join(installed.python.installationDir, "overlay", "acceptance-marker.txt"),
  274. "preserve while disabled; remove with resource",
  275. );
  276. result = {
  277. ...continuity,
  278. plugins: Object.keys(roots),
  279. formulas: checks.formulas,
  280. pdf2imageEntry: pdftoppm[0].resolved,
  281. installed,
  282. selections: await selection(),
  283. checks,
  284. };
  285. } else if (phase.endsWith("-off") || phase.endsWith("-on")) {
  286. const continuity = await assertSameAgent();
  287. const disabled = phase.endsWith("-off") ? phase.slice(0, -4) : null;
  288. const selections = await selection();
  289. for (const id of tools)
  290. for (let index = 0; index < entries[id].length; index++) {
  291. // Git Bash 解析 shim 入口得到 <name>.exe;比较无扩展名路径会让“已关闭”断言恒为真。
  292. const managed = entryPath(entries[id][index]);
  293. if (id === disabled) assert.ok(!sameFile(selections[id][index], managed));
  294. else
  295. assert.ok(
  296. sameFile(selections[id][index], managed),
  297. `${entries[id][index]} 未解析到预装入口`,
  298. );
  299. }
  300. let actual;
  301. let pluginSelection;
  302. if (disabled === "python") {
  303. // 插件的原写法;Windows 上 python3 常是应用商店占位程序,失败也如实记录,只断言未用预装版本。
  304. pluginSelection = await execute(
  305. bash,
  306. [
  307. "-c",
  308. '"$(command -v zcode-python || command -v python3)" -c "import sys;print(sys.executable)"',
  309. ],
  310. isWindows ? null : 0,
  311. );
  312. actual = pluginSelection.stdout.trim();
  313. assert.ok(!actual.startsWith((await record("python")).installationDir));
  314. } else {
  315. actual = (
  316. await execute("zcode-python", ["-c", "import sys;print(sys.executable)"])
  317. ).stdout.trim();
  318. assert.ok(actual.startsWith((await record("python")).installationDir));
  319. }
  320. if (phase.startsWith("libreoffice")) {
  321. const check = await execute("zcode-python", [
  322. join(await plugin("documents"), "scripts/zcode_libreoffice.py"),
  323. "check",
  324. ]);
  325. assert.equal(JSON.parse(check.stdout).source, disabled ? "system" : "managed");
  326. if (disabled) assert.ok(check.stderr.includes("未就绪或已关闭"));
  327. }
  328. assert.equal(
  329. await readFile(
  330. join((await record("python")).installationDir, "overlay/acceptance-marker.txt"),
  331. "utf8",
  332. ),
  333. "preserve while disabled; remove with resource",
  334. );
  335. result = {
  336. ...continuity,
  337. disabled,
  338. selections,
  339. pythonExecutable: actual,
  340. ...(pluginSelection
  341. ? {
  342. pluginSelection: {
  343. code: pluginSelection.code,
  344. stdout: pluginSelection.stdout,
  345. stderr: pluginSelection.stderr,
  346. },
  347. }
  348. : {}),
  349. };
  350. } else if (phase === "fallbacks") {
  351. await assertSameAgent();
  352. await execute("zcode-python", [join(directory, "fallback_checks.py")]);
  353. result = await get("fallback-results");
  354. } else if (phase.startsWith("upgrade-")) {
  355. const currentAncestors = await ancestors();
  356. const agent = currentAncestors.find((item) => agentCommand.test(item.command));
  357. assert.ok(agent, JSON.stringify(currentAncestors));
  358. const continuity = {
  359. agentPid: agent.pid,
  360. ancestors: currentAncestors,
  361. snapshots: await snapshots(),
  362. };
  363. if (phase === "upgrade-after") {
  364. const prior = await get("upgrade-before");
  365. assert.equal(continuity.agentPid, prior.agentPid);
  366. assert.deepEqual(continuity.snapshots, prior.snapshots);
  367. }
  368. const installation = await record("qpdf");
  369. // resourceId 由测试从真实 .artifact.json 读出,不按平台写死。
  370. const expected =
  371. phase === "upgrade-before" ? config.qpdfResourceIds.before : config.qpdfResourceIds.after;
  372. assert.equal(installation.resourceId, expected);
  373. const text = await entryDefinition("qpdf");
  374. assert.ok(text.includes(installation.installationDir));
  375. const version = await execute("qpdf", ["--version"]);
  376. await execute("qpdf", ["--check", join(docs, "Office PDF.pdf")]);
  377. result = {
  378. ...continuity,
  379. resourceId: installation.resourceId,
  380. entry: text,
  381. version: version.stdout,
  382. };
  383. } else if (phase === "finish") {
  384. const continuity = await assertSameAgent();
  385. assert.deepEqual(
  386. await tree(join((await record("python")).installationDir, "python")),
  387. await get("python-base-before"),
  388. );
  389. assert.deepEqual(await tree(config.defaultProfile), await get("default-profile-before"));
  390. const signatures = await verifySignatures();
  391. result = {
  392. ...continuity,
  393. pythonBaseUnchanged: true,
  394. defaultProfileUnchanged: true,
  395. signatures,
  396. };
  397. } else throw new Error(`Unknown phase: ${phase}`);
  398. await put(phase, result);
  399. console.log(JSON.stringify({ phase, success: true, ...(phase === "before" ? result : {}) }));