verify.mjs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { spawnSync } from "node:child_process";
  2. import {
  3. appendFileSync,
  4. mkdirSync,
  5. mkdtempSync,
  6. renameSync,
  7. rmSync,
  8. writeFileSync,
  9. } from "node:fs";
  10. import { tmpdir } from "node:os";
  11. import path from "node:path";
  12. import { fileURLToPath } from "node:url";
  13. import { parseArgs } from "node:util";
  14. // Single definition of the full verification pipeline. GitHub CI runs `pnpm verify`
  15. // so a local run executes the same gates in the same order; previously the order
  16. // only existed inside the workflow file and could not be reproduced locally.
  17. // Platform-conditional gates declare the platforms they support instead of being
  18. // filtered by workflow `if:` expressions.
  19. const root = fileURLToPath(new URL("../", import.meta.url));
  20. const { values } = parseArgs({
  21. options: {
  22. profile: { type: "string", default: "full" },
  23. list: { type: "boolean", default: false },
  24. },
  25. });
  26. const profile = values.profile;
  27. if (!["full", "platform", "docs", "archive", "package"].includes(profile))
  28. throw new Error(`Unknown verification profile: ${profile}`);
  29. if (profile === 'package' && !['darwin', 'linux'].includes(process.platform))
  30. throw new Error('Package verification currently supports Linux and macOS only.');
  31. // Listing must not leave a temporary export directory behind.
  32. const temporary = values.list
  33. ? undefined
  34. : mkdtempSync(path.join(tmpdir(), "mcode-verify-"));
  35. const preview = path.join(temporary ?? tmpdir(), "minimax-code-source.tar.gz");
  36. const steps = [
  37. { name: "check:source", script: "check:source", docs: true },
  38. { name: "check:tsconfig", script: "check:tsconfig", docs: true },
  39. {
  40. name: "export source preview",
  41. docs: true,
  42. requiresGit: true,
  43. command: ["scripts/export-source-preview.mjs", "--out", preview],
  44. },
  45. { name: "test:release-tools", script: "test:release-tools", docs: true },
  46. // Compiler inputs are identical across the matrix. One Linux job runs this;
  47. // all platforms still build and validate native artifacts on their own platform.
  48. { name: "typecheck", script: "typecheck", fullOnly: true },
  49. { name: "build", script: "build" },
  50. { name: "check:standalone", script: "check:standalone" },
  51. { name: "test:artifact", script: "test:artifact" },
  52. { name: "test:capabilities", script: "test:capabilities" },
  53. { name: "test:status-contract", script: "test:status-contract" },
  54. { name: "test:smoke", script: "test:smoke" },
  55. { name: "test:byok", script: "test:byok" },
  56. // The permission facade uses POSIX process and filesystem semantics.
  57. {
  58. name: "test:policy",
  59. script: "test:policy",
  60. platforms: ["darwin", "linux"],
  61. },
  62. // Seatbelt sandbox backend; only macOS provides the native helper.
  63. { name: "test:sandbox", script: "test:sandbox", platforms: ["darwin"] },
  64. {
  65. name: "test:release-package",
  66. command: ['scripts/verify-cli-release.mjs'],
  67. packageOnly: true,
  68. platforms: ['darwin', 'linux'],
  69. },
  70. ];
  71. function skipReason(step) {
  72. if (profile === 'package' && !step.packageOnly) return 'validating an npm release archive';
  73. if (profile !== 'package' && step.packageOnly) return 'requires an npm release archive';
  74. if (profile === "docs" && !step.docs) return "documentation-only change";
  75. if (profile === "archive" && step.requiresGit)
  76. return "validating an already exported archive";
  77. if (step.platforms && !step.platforms.includes(process.platform))
  78. return "not applicable on this platform";
  79. if (step.fullOnly && profile === "platform")
  80. return "covered by the full profile";
  81. return null;
  82. }
  83. const planned = steps.filter((step) => !skipReason(step));
  84. if (values.list) {
  85. for (const step of planned) console.log(step.name);
  86. process.exit(0);
  87. }
  88. // `npm_execpath` may be a JavaScript entry point or a native package-manager
  89. // binary depending on how pnpm was installed, so dispatch on what it actually is
  90. // instead of assuming it can be passed to node.
  91. function runScript(name) {
  92. const execPath = process.env.npm_execpath;
  93. if (execPath && /\.[cm]?js$/u.test(execPath))
  94. return spawnSync(process.execPath, [execPath, "run", name], {
  95. stdio: "inherit",
  96. cwd: root,
  97. });
  98. const command = execPath ?? "pnpm";
  99. const shell = process.platform === "win32";
  100. return spawnSync(shell ? `"${command}"` : command, ["run", name], {
  101. stdio: "inherit",
  102. cwd: root,
  103. shell,
  104. });
  105. }
  106. function run(step) {
  107. const group = Boolean(process.env.GITHUB_ACTIONS);
  108. if (group) console.log(`::group::${step.name}`);
  109. else console.log(`\n=== ${step.name} ===`);
  110. try {
  111. return step.script
  112. ? runScript(step.script)
  113. : spawnSync(process.execPath, step.command, {
  114. stdio: "inherit",
  115. cwd: root,
  116. });
  117. } finally {
  118. if (group) console.log("::endgroup::");
  119. }
  120. }
  121. const started = performance.now();
  122. const revision = spawnSync("git", ["rev-parse", "HEAD"], {
  123. cwd: root,
  124. encoding: "utf8",
  125. });
  126. const report = {
  127. schemaVersion: 1,
  128. // The candidate workflow authenticates its receipt before running this
  129. // profile in a source-only directory that deliberately contains no .git.
  130. revision:
  131. revision.status === 0
  132. ? revision.stdout.trim()
  133. : profile === "archive" &&
  134. /^[a-f0-9]{40}$/u.test(process.env.MCODE_VERIFY_REVISION ?? "")
  135. ? process.env.MCODE_VERIFY_REVISION
  136. : null,
  137. platform: process.platform,
  138. arch: process.arch,
  139. node: process.version,
  140. profile,
  141. startedAt: new Date().toISOString(),
  142. durationMs: 0,
  143. status: "RUNNING",
  144. gates: steps.map((step) => ({
  145. name: step.name,
  146. status: skipReason(step) ? "SKIP" : "NOT_RUN",
  147. reason: skipReason(step),
  148. durationMs: null,
  149. })),
  150. };
  151. const reportDir = process.env.MCODE_VERIFY_REPORT_DIR;
  152. function saveReport() {
  153. report.durationMs = Math.round(performance.now() - started);
  154. if (!reportDir) return;
  155. mkdirSync(reportDir, { recursive: true });
  156. const target = path.join(reportDir, "verification.json");
  157. // Keep the last complete JSON readable even if the runner is interrupted.
  158. writeFileSync(`${target}.tmp`, `${JSON.stringify(report, null, 2)}\n`);
  159. renameSync(`${target}.tmp`, target);
  160. }
  161. function summary() {
  162. return [
  163. `## Verification: ${report.status}`,
  164. "",
  165. `${report.platform}/${report.arch}, Node ${report.node}, profile ${profile}`,
  166. `Revision: ${report.revision ?? "unavailable"}`,
  167. `Elapsed: ${(report.durationMs / 1000).toFixed(1)}s`,
  168. "",
  169. "| Gate | Result | Seconds | Detail |",
  170. "| --- | --- | ---: | --- |",
  171. ...report.gates.map((gate) => {
  172. const detail =
  173. gate.reason ??
  174. (gate.errorCode
  175. ? `spawn error ${gate.errorCode}`
  176. : gate.signal
  177. ? `signal ${gate.signal}`
  178. : gate.exitCode != null
  179. ? `exit ${gate.exitCode}`
  180. : "");
  181. return `| ${gate.name} | ${gate.status} | ${gate.durationMs == null ? "—" : (gate.durationMs / 1000).toFixed(1)} | ${detail} |`;
  182. }),
  183. "",
  184. "Reports contain gate metadata only. Failure output remains in the corresponding job log.",
  185. "",
  186. ].join("\n");
  187. }
  188. let failed;
  189. try {
  190. saveReport();
  191. for (const step of planned) {
  192. const gate = report.gates.find((entry) => entry.name === step.name);
  193. gate.status = "RUNNING";
  194. saveReport();
  195. const gateStarted = performance.now();
  196. let result;
  197. try {
  198. result = run(step);
  199. } catch (error) {
  200. result = { error, status: null, signal: null };
  201. }
  202. gate.durationMs = Math.round(performance.now() - gateStarted);
  203. gate.exitCode = result.status;
  204. gate.signal = result.signal;
  205. gate.errorCode = result.error ? (result.error.code ?? "SPAWN_ERROR") : null;
  206. gate.status = result.status === 0 && !result.error ? "PASS" : "FAIL";
  207. console.log(
  208. `${step.name}: ${gate.status} (${(gate.durationMs / 1000).toFixed(1)}s)`,
  209. );
  210. saveReport();
  211. if (gate.status === "FAIL") {
  212. failed = step.name;
  213. break;
  214. }
  215. }
  216. report.status = failed ? "FAIL" : "PASS";
  217. } finally {
  218. rmSync(temporary, { recursive: true, force: true });
  219. for (const gate of report.gates)
  220. if (gate.status === "NOT_RUN")
  221. gate.reason = "verification stopped before this gate";
  222. saveReport();
  223. const markdown = summary();
  224. if (reportDir)
  225. writeFileSync(path.join(reportDir, "verification.md"), markdown);
  226. if (process.env.GITHUB_STEP_SUMMARY)
  227. appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown);
  228. }
  229. if (failed) {
  230. console.error(`\nVerification failed at: ${failed}`);
  231. process.exitCode = 1;
  232. } else {
  233. const skipped = steps
  234. .filter((step) => !planned.includes(step))
  235. .map((step) => `${step.name} (${skipReason(step)})`);
  236. console.log(
  237. `\nVerification passed: ${planned.length} gates on ${process.platform}.` +
  238. (skipped.length ? ` Skipped: ${skipped.join(", ")}.` : ""),
  239. );
  240. }