source-sync.test.mjs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { copyFileSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, existsSync, rmSync, realpathSync, symlinkSync } from 'node:fs';
  4. import path from 'node:path';
  5. import { tmpdir } from 'node:os';
  6. import { execFileSync, spawnSync } from 'node:child_process';
  7. import { prepareSourceSync } from '../scripts/prepare-source-sync.mjs';
  8. import { extractionPath, inventoryPath } from '../scripts/lib/release-metadata.mjs';
  9. import { extractSourceArchive } from '../scripts/lib/source-archive.mjs';
  10. import { classifyChanges } from '../scripts/ci-changes.mjs';
  11. import { suiteInventoryViolations } from '../scripts/lib/vitest-suites.mjs';
  12. import { Header } from 'tar';
  13. import { gzipSync } from 'node:zlib';
  14. import { createHash } from 'node:crypto';
  15. import { fileURLToPath } from 'node:url';
  16. import { parse as parseYaml } from 'yaml';
  17. function fixture(t) {
  18. const home = mkdtempSync(path.join(tmpdir(), 'source-sync-'));
  19. t.after(() => rmSync(home, { recursive: true, force: true }));
  20. const source = path.join(home, 'source'), root = path.join(home, 'public');
  21. mkdirSync(path.join(source, 'packages/example'), { recursive: true });
  22. mkdirSync(path.join(root, path.dirname(extractionPath)), { recursive: true });
  23. mkdirSync(path.join(root, 'packages/example'), { recursive: true });
  24. const git = (...args) => execFileSync('git', ['-C', source, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
  25. git('init'); git('config', 'user.name', 'Fixture'); git('config', 'user.email', 'fixture@example.invalid');
  26. const write = (base, name, text) => writeFileSync(path.join(base, 'packages/example', name), text);
  27. write(source, 'a.txt', 'first\nsecond\nthird\nfourth\nfifth\n');
  28. write(source, 'delete.txt', 'old\n');
  29. git('add', 'packages/example/a.txt', 'packages/example/delete.txt'); git('-c', 'core.hooksPath=', 'commit', '-m', 'Fixture baseline');
  30. const baseline = git('rev-parse', 'HEAD');
  31. for (const name of ['a.txt', 'delete.txt']) write(root, name, readFileSync(path.join(source, 'packages/example', name)));
  32. writeFileSync(path.join(root, extractionPath), JSON.stringify({ sourceRevision: baseline, packageRoots: ['packages/example'] }));
  33. writeFileSync(path.join(root, inventoryPath), JSON.stringify({ files: ['packages/example/a.txt', 'packages/example/delete.txt'] }));
  34. return { source, root, out: path.join(home, 'review'), ref: 'HEAD', git, write };
  35. }
  36. test('sync proposes updates/deletions, reports unlisted files and does not mutate public source', t => {
  37. const f = fixture(t);
  38. f.write(f.source, 'a.txt', 'new\n'); f.write(f.source, 'new.txt', 'unreviewed\n');
  39. f.git('rm', 'packages/example/delete.txt');
  40. f.git('add', 'packages/example/a.txt', 'packages/example/new.txt'); f.git('-c', 'core.hooksPath=', 'commit', '-m', 'Fixture change');
  41. const before = readFileSync(path.join(f.root, 'packages/example/a.txt'));
  42. const result = prepareSourceSync(f);
  43. assert.deepEqual(result.entries.map(e => e.status), ['update-candidate', 'delete-candidate', 'unlisted-source-review']);
  44. assert.deepEqual(readFileSync(path.join(f.root, 'packages/example/a.txt')), before);
  45. assert.equal(existsSync(path.join(f.out, 'candidates/packages/example/new.txt')), false);
  46. assert.equal(readFileSync(path.join(f.out, 'candidates/packages/example/a.txt'), 'utf8'), 'new\n');
  47. });
  48. test('three-way merge preserves public adaptations and exposes overlapping conflicts', t => {
  49. const f = fixture(t);
  50. f.write(f.root, 'a.txt', 'public\nsecond\nthird\nfourth\nfifth\n');
  51. f.write(f.source, 'a.txt', 'first\nsecond\nthird\nfourth\nupstream\n');
  52. f.git('add', 'packages/example/a.txt'); f.git('-c', 'core.hooksPath=', 'commit', '-m', 'Fixture change');
  53. assert.equal(prepareSourceSync(f).entries[0].status, 'merged-candidate');
  54. assert.equal(readFileSync(path.join(f.out, 'candidates/packages/example/a.txt'), 'utf8'), 'public\nsecond\nthird\nfourth\nupstream\n');
  55. f.write(f.root, 'a.txt', 'first\nsecond\nthird\nfourth\nconflicting\n');
  56. f.out += '-conflict';
  57. assert.equal(prepareSourceSync(f).entries[0].status, 'merge-conflict');
  58. assert.match(readFileSync(path.join(f.out, 'candidates/packages/example/a.txt'), 'utf8'), /<<<<<<< public/);
  59. });
  60. test('rejects existing output, output in repositories and unsafe inventory', t => {
  61. const f = fixture(t);
  62. assert.throws(() => prepareSourceSync({ ...f, out: f.root }), /Output/);
  63. assert.throws(() => prepareSourceSync({ ...f, out: path.join(f.source, 'review') }), /Output/);
  64. mkdirSync(f.out);
  65. assert.throws(() => prepareSourceSync(f), /Output/);
  66. writeFileSync(path.join(f.root, inventoryPath), JSON.stringify({ files: ['../outside'] }));
  67. assert.throws(() => prepareSourceSync({ ...f, out: `${f.out}-new` }), /Unsafe inventory/);
  68. });
  69. // Exercise the real verification dispatcher in an isolated repository. These
  70. // commands stand in for gates, so a failure test cannot accidentally run builds
  71. // or the release-tools suite recursively.
  72. function verificationFixture(t) {
  73. const directory = mkdtempSync(path.join(tmpdir(), 'verify-fixture-'));
  74. t.after(() => rmSync(directory, { recursive: true, force: true }));
  75. const root = path.join(directory, 'source');
  76. mkdirSync(path.join(root, 'scripts'), { recursive: true });
  77. const verifier = path.join(root, 'scripts/verify.mjs');
  78. copyFileSync(new URL('../scripts/verify.mjs', import.meta.url), verifier);
  79. const manager = path.join(directory, 'manager.cjs');
  80. writeFileSync(manager, `
  81. const fs = require('node:fs');
  82. const path = require('node:path');
  83. const gate = process.argv[3];
  84. const report = JSON.parse(fs.readFileSync(path.join(process.env.MCODE_VERIFY_REPORT_DIR, 'verification.json')));
  85. if (report.status !== 'RUNNING' || report.gates.find(g => g.name === gate)?.status !== 'RUNNING') process.exit(99);
  86. console.log('FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED');
  87. if (gate === process.env.VERIFY_FIXTURE_FAIL) process.exit(17);
  88. `);
  89. const exportRecord = path.join(directory, 'export-path.txt');
  90. writeFileSync(path.join(root, 'scripts/export-source-preview.mjs'), `
  91. import { writeFileSync } from 'node:fs';
  92. writeFileSync(process.argv[3], 'synthetic export');
  93. writeFileSync(process.env.VERIFY_FIXTURE_EXPORT, process.argv[3]);
  94. `);
  95. const reportDir = path.join(directory, 'reports');
  96. const summaryPath = path.join(directory, 'summary.md');
  97. function run(args = [], env = {}) {
  98. return spawnSync(process.execPath, [verifier, ...args], {
  99. cwd: root,
  100. encoding: 'utf8',
  101. timeout: 20000,
  102. env: {
  103. ...process.env,
  104. npm_execpath: manager,
  105. MCODE_VERIFY_REPORT_DIR: reportDir,
  106. GITHUB_STEP_SUMMARY: summaryPath,
  107. VERIFY_FIXTURE_EXPORT: exportRecord,
  108. VERIFY_FIXTURE_FAIL: '',
  109. ...env,
  110. },
  111. });
  112. }
  113. return {
  114. run, exportRecord, reportDir, summaryPath,
  115. report: () => JSON.parse(readFileSync(path.join(reportDir, 'verification.json'), 'utf8')),
  116. };
  117. }
  118. test('platform verification omits only the compiler gate and invalid profiles fail closed', t => {
  119. const f = verificationFixture(t);
  120. const full = f.run(['--list']);
  121. const platform = f.run(['--profile', 'platform', '--list']);
  122. assert.equal(full.status, 0, full.stderr);
  123. assert.equal(platform.status, 0, platform.stderr);
  124. const gates = full.stdout.trim().split('\n');
  125. assert.ok(gates.includes('typecheck'));
  126. assert.deepEqual(platform.stdout.trim().split('\n'), gates.filter(g => g !== 'typecheck'));
  127. assert.notEqual(f.run(['--profile', 'platfrom', '--list']).status, 0);
  128. assert.notEqual(f.run(['--unknown']).status, 0);
  129. assert.equal(existsSync(f.reportDir), false);
  130. assert.equal(existsSync(f.exportRecord), false);
  131. });
  132. test('verification reports successes and intentional skips without collecting gate output', t => {
  133. const f = verificationFixture(t);
  134. const result = f.run(['--profile', 'platform']);
  135. assert.equal(result.status, 0, result.stderr);
  136. const report = f.report();
  137. assert.equal(report.status, 'PASS');
  138. assert.equal(report.platform, process.platform);
  139. assert.equal(report.node, process.version);
  140. assert.equal(report.profile, 'platform');
  141. assert.equal(report.gates.find(g => g.name === 'typecheck').status, 'SKIP');
  142. assert.match(report.gates.find(g => g.name === 'typecheck').reason, /full profile/);
  143. assert.equal(report.gates.find(g => g.name === 'build').status, 'PASS');
  144. assert.equal(report.gates.find(g => g.name === 'test:byok').status, 'PASS');
  145. assert.ok(report.gates.every(g => ['PASS', 'SKIP'].includes(g.status)));
  146. assert.ok(report.gates.filter(g => g.status === 'PASS').every(g => g.durationMs >= 0 && g.exitCode === 0));
  147. assert.equal(existsSync(path.dirname(readFileSync(f.exportRecord, 'utf8'))), false);
  148. assert.doesNotMatch(JSON.stringify(report), /FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED/);
  149. assert.doesNotMatch(readFileSync(f.summaryPath, 'utf8'), /FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED/);
  150. assert.equal(readFileSync(f.summaryPath, 'utf8'), readFileSync(path.join(f.reportDir, 'verification.md'), 'utf8'));
  151. });
  152. test('compiler failure fails full verification, preserves evidence, and stops dependent gates', t => {
  153. const f = verificationFixture(t);
  154. const result = f.run([], { VERIFY_FIXTURE_FAIL: 'typecheck' });
  155. assert.equal(result.status, 1, result.stderr);
  156. const report = f.report();
  157. assert.equal(report.status, 'FAIL');
  158. assert.equal(report.gates.find(g => g.name === 'typecheck').status, 'FAIL');
  159. assert.equal(report.gates.find(g => g.name === 'typecheck').exitCode, 17);
  160. assert.equal(report.gates.find(g => g.name === 'check:source').status, 'PASS');
  161. assert.equal(report.gates.find(g => g.name === 'build').status, 'NOT_RUN');
  162. assert.match(report.gates.find(g => g.name === 'build').reason, /stopped/);
  163. assert.equal(existsSync(path.dirname(readFileSync(f.exportRecord, 'utf8'))), false);
  164. assert.match(readFileSync(f.summaryPath, 'utf8'), /Verification: FAIL/);
  165. assert.doesNotMatch(JSON.stringify(report), /FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED/);
  166. });
  167. test('missing package manager produces failure metadata instead of a passing verification', t => {
  168. const f = verificationFixture(t);
  169. const result = f.run([], { npm_execpath: path.join(f.reportDir, 'missing-executable') });
  170. assert.equal(result.status, 1, result.stderr);
  171. const report = f.report();
  172. assert.equal(report.status, 'FAIL');
  173. assert.equal(report.gates[0].status, 'FAIL');
  174. assert.ok(report.gates[0].errorCode || report.gates[0].exitCode !== 0);
  175. assert.equal(report.gates.find(g => g.name === 'build').status, 'NOT_RUN');
  176. });
  177. test('documentation and archive profiles preserve their required validation gates', t => {
  178. const f = verificationFixture(t);
  179. const full = f.run(['--list']).stdout.trim().split('\n');
  180. const docs = f.run(['--profile', 'docs', '--list']);
  181. assert.equal(docs.status, 0, docs.stderr);
  182. assert.deepEqual(docs.stdout.trim().split('\n'), ['check:source', 'check:tsconfig', 'export source preview', 'test:release-tools']);
  183. const archive = f.run(['--profile', 'archive', '--list']);
  184. assert.equal(archive.status, 0, archive.stderr);
  185. assert.deepEqual(archive.stdout.trim().split('\n'), full.filter(g => g !== 'export source preview'));
  186. const failure = f.run(['--profile', 'docs'], { VERIFY_FIXTURE_FAIL: 'check:source' });
  187. assert.equal(failure.status, 1);
  188. assert.equal(f.report().status, 'FAIL');
  189. });
  190. test('change classification is conservative for mixed changes, metadata and missing diffs', () => {
  191. assert.deepEqual(classifyChanges(['README.md', 'docs/installation.md']), { docsOnly: true });
  192. for (const files of [[], ['README.md', 'packages/tui/src/main.ts'], ['docs/run.mjs'], ['release/public-source.json'], ['.github/workflows/ci.yml'], ['scripts/export-source-preview.mjs']])
  193. assert.equal(classifyChanges(files).docsOnly, false);
  194. assert.deepEqual(classifyChanges(['.github/PULL_REQUEST_TEMPLATE.md', 'docs/source-sync.md']), { docsOnly: true });
  195. for (const file of ['.github/actions/setup-gitleaks/action.yml', '.github/ISSUE_TEMPLATE/config.yml', '.github/unknown.md', '.github/PULL_REQUEST_TEMPLATE.md/run.js'])
  196. assert.equal(classifyChanges([file]).docsOnly, false, file);
  197. });
  198. test('CI aggregate rejects failed, cancelled, missing and unexpectedly skipped checks', { skip: process.platform === 'win32' }, () => {
  199. // This shell step only runs on the aggregate job's Ubuntu runner.
  200. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8'));
  201. const script = workflow.jobs.verification.steps[0].run;
  202. const full = { CLASSIFICATION: 'success', DOCS_ONLY: 'false', DOCS_RESULT: 'skipped', MATRIX_RESULT: 'success' };
  203. const docs = { CLASSIFICATION: 'success', DOCS_ONLY: 'true', DOCS_RESULT: 'success', MATRIX_RESULT: 'skipped' };
  204. const run = env => spawnSync('bash', ['-e', '-c', script], { env: { ...process.env, ...env }, encoding: 'utf8' }).status;
  205. assert.equal(run(full), 0);
  206. assert.equal(run(docs), 0);
  207. for (const result of ['failure', 'cancelled', 'skipped', '']) {
  208. assert.notEqual(run({ ...full, MATRIX_RESULT: result }), 0);
  209. assert.notEqual(run({ ...docs, DOCS_RESULT: result }), 0);
  210. assert.notEqual(run({ ...full, CLASSIFICATION: result }), 0);
  211. }
  212. assert.notEqual(run({ ...full, DOCS_ONLY: '' }), 0);
  213. for (const result of ['success', 'failure', 'cancelled', ''])
  214. assert.notEqual(run({ ...docs, MATRIX_RESULT: result }), 0);
  215. for (const result of ['success', 'failure', 'cancelled', ''])
  216. assert.notEqual(run({ ...full, DOCS_RESULT: result }), 0);
  217. for (const scope of ['', 'unknown', 'True'])
  218. assert.notEqual(run({ ...full, DOCS_ONLY: scope }), 0);
  219. });
  220. test('ordinary CI preserves three platforms without invoking release-only matrices', () => {
  221. const readWorkflow = name => parseYaml(readFileSync(new URL(`../.github/workflows/${name}.yml`, import.meta.url), 'utf8'));
  222. const ci = readWorkflow('ci');
  223. assert.ok(Object.hasOwn(ci.on, 'pull_request'));
  224. assert.deepEqual(ci.on.push.branches, ['main']);
  225. assert.deepEqual(Object.keys(ci.jobs).sort(), ['changes', 'docs', 'verification', 'verify']);
  226. assert.deepEqual(ci.jobs.verify.strategy.matrix.os, ['ubuntu-latest', 'macos-latest', 'windows-latest']);
  227. assert.deepEqual(ci.jobs.verify.strategy.matrix.node, ['24']);
  228. assert.deepEqual(ci.jobs.verify.strategy.matrix.include, [{ os: 'ubuntu-latest', node: '24', profile: 'full' }]);
  229. assert.equal(ci.jobs.verify.needs, 'changes');
  230. assert.equal(ci.jobs.verify.if, "needs.changes.outputs.docs_only == 'false'");
  231. assert.equal(ci.jobs.docs.if, "needs.changes.outputs.docs_only == 'true'");
  232. assert.equal(ci.jobs.verification.if, '${{ always() }}');
  233. assert.deepEqual(ci.jobs.verification.needs, ['changes', 'docs', 'verify']);
  234. assert.ok(ci.jobs.verify.steps.some(step => step.run === "pnpm verify --profile ${{ matrix.profile || 'platform' }}"));
  235. const compatibility = readWorkflow('compatibility');
  236. assert.deepEqual(Object.keys(compatibility.on).sort(), ['schedule', 'workflow_dispatch']);
  237. assert.deepEqual(compatibility.jobs.compatibility.strategy.matrix.node, ['22.19.0', '24.2.0', '25', '26']);
  238. assert.deepEqual(compatibility.jobs.compatibility.strategy.matrix.os, ci.jobs.verify.strategy.matrix.os);
  239. const audit = readWorkflow('security');
  240. assert.ok(Object.hasOwn(audit.on, 'pull_request'));
  241. assert.ok(audit.jobs['source-history-artifact'].steps.some(step => step.run?.includes('gitleaks dir dist')));
  242. });
  243. test('manual source candidates pin every checkout and receipt to the selected revision', () => {
  244. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/source-candidate.yml', import.meta.url), 'utf8'));
  245. assert.deepEqual(Object.keys(workflow.on).sort(), ['workflow_call', 'workflow_dispatch']);
  246. assert.equal(workflow.on.workflow_call.inputs.revision.required, true);
  247. assert.equal(workflow.env.MCODE_CANDIDATE_REVISION, '${{ inputs.revision || github.sha }}');
  248. assert.equal(workflow.concurrency['cancel-in-progress'], false);
  249. assert.match(workflow.concurrency.group, /inputs\.revision \|\| github\.sha/);
  250. const revision = '${{ env.MCODE_CANDIDATE_REVISION }}';
  251. for (const job of Object.values(workflow.jobs)) {
  252. const checkout = job.steps.find(step => step.uses?.startsWith('actions/checkout@'));
  253. assert.equal(checkout.with.ref, revision);
  254. for (const step of job.steps.filter(step => step.run?.includes('scripts/source-candidate.mjs')))
  255. assert.equal(step.env.REVISION, revision);
  256. }
  257. const validate = workflow.jobs.validate;
  258. assert.deepEqual(validate.strategy.matrix.os, ['ubuntu-latest', 'macos-latest', 'windows-latest']);
  259. assert.ok(validate.steps.some(step => step.run?.includes('--store-dir "$RUNNER_TEMP/candidate-store" --registry https://registry.npmjs.org/')));
  260. const verify = validate.steps.find(step => step.run === 'pnpm verify --profile archive');
  261. assert.equal(verify.env.MCODE_VERIFY_REVISION, revision);
  262. assert.deepEqual(workflow.jobs.publish.needs, ['export', 'validate']);
  263. assert.ok(workflow.jobs.publish.steps.some(step => step.run?.includes('scripts/source-candidate.mjs finalize')));
  264. assert.equal(workflow.permissions.contents, 'read');
  265. });
  266. function archiveFixture(t, entries) {
  267. const directory = mkdtempSync(path.join(tmpdir(), 'archive-fixture-'));
  268. t.after(() => rmSync(directory, { recursive: true, force: true }));
  269. const blocks = [];
  270. for (const entry of entries) {
  271. const content = Buffer.from(entry.content ?? '');
  272. const header = new Header({ path: entry.path, type: entry.type ?? 'File', linkpath: entry.linkpath, size: content.length, mode: 0o644, uid: 0, gid: 0, mtime: new Date(0) });
  273. header.encode();
  274. blocks.push(header.block, content, Buffer.alloc((512 - content.length % 512) % 512));
  275. }
  276. const archive = path.join(directory, 'source.tar.gz');
  277. writeFileSync(archive, gzipSync(Buffer.concat([...blocks, Buffer.alloc(1024)])));
  278. return { directory, archive };
  279. }
  280. test('native and Node source extractors produce identical file content', async t => {
  281. const f = archiveFixture(t, [
  282. { path: 'minimax-code/README.md', content: 'Source preview\n' },
  283. { path: 'minimax-code/nested/file.txt', content: 'portable contents\n' },
  284. ]);
  285. for (const extractor of ['native', 'node']) {
  286. const output = path.join(f.directory, extractor);
  287. mkdirSync(output);
  288. assert.equal(await extractSourceArchive(f.archive, output, extractor), extractor);
  289. assert.equal(readFileSync(path.join(output, 'minimax-code/nested/file.txt'), 'utf8'), 'portable contents\n');
  290. }
  291. });
  292. test('Windows extraction ignores a shadow tar executable on PATH', { skip: process.platform !== 'win32' }, t => {
  293. const f = archiveFixture(t, [{ path: 'minimax-code/README.md', content: 'Windows archive\n' }]);
  294. const shadow = path.join(f.directory, 'shadow');
  295. const output = path.join(f.directory, 'output');
  296. mkdirSync(shadow);
  297. mkdirSync(output);
  298. // Node rejects tar flags. If extraction accidentally uses PATH, this fake
  299. // tar.exe makes the regression fail without needing Git Bash installed.
  300. copyFileSync(process.execPath, path.join(shadow, 'tar.exe'));
  301. const script = `import { extractSourceArchive } from ${JSON.stringify(new URL('../scripts/lib/source-archive.mjs', import.meta.url).href)};
  302. const result = await extractSourceArchive(${JSON.stringify(f.archive)}, ${JSON.stringify(output)}, 'native');
  303. if (result !== 'native') process.exit(1);`;
  304. const result = spawnSync(process.execPath, ['--input-type=module', '--eval', script], {
  305. encoding: 'utf8', env: { ...process.env, PATH: `${shadow}${path.delimiter}${process.env.PATH ?? ''}` },
  306. });
  307. assert.equal(result.status, 0, result.stderr);
  308. assert.equal(readFileSync(path.join(output, 'minimax-code/README.md'), 'utf8'), 'Windows archive\n');
  309. });
  310. test('source archive rejects traversal, links, Git history and duplicate entries before writing files', async t => {
  311. const good = { path: 'minimax-code/good.txt', content: 'safe' };
  312. for (const bad of [
  313. { path: 'minimax-code/../../outside.txt', content: 'unsafe' },
  314. { path: 'minimax-code/link', type: 'SymbolicLink', linkpath: '../../outside' },
  315. { path: 'minimax-code/link', type: 'Link', linkpath: '../../outside' },
  316. { path: 'minimax-code/.git/config', content: 'history' },
  317. { path: 'minimax-code/file:stream', content: 'stream' },
  318. good,
  319. ]) {
  320. const f = archiveFixture(t, [good, bad]);
  321. for (const extractor of ['native', 'node']) {
  322. const output = path.join(f.directory, extractor);
  323. mkdirSync(output);
  324. await assert.rejects(extractSourceArchive(f.archive, output, extractor), /unreviewed/);
  325. assert.deepEqual(readdirSync(output), []);
  326. }
  327. }
  328. });
  329. test('candidate rejects mismatched receipts and requires three successful same-revision reports', t => {
  330. const f = archiveFixture(t, [{ path: 'minimax-code/README.md', content: 'source' }]);
  331. const revision = 'a'.repeat(40);
  332. const receipt = { schemaVersion: 1, revision, sha256: createHash('sha256').update(readFileSync(f.archive)).digest('hex'), format: 'source-only-no-git-history', publicationPerformed: false };
  333. writeFileSync(`${f.archive}.json`, JSON.stringify(receipt));
  334. const script = fileURLToPath(new URL('../scripts/source-candidate.mjs', import.meta.url));
  335. const run = (...args) => spawnSync(process.execPath, [script, ...args, '--archive', f.archive, '--revision', revision], { encoding: 'utf8', timeout: 15000 });
  336. const destination = path.join(f.directory, 'unpacked');
  337. assert.equal(run('unpack', '--destination', destination).status, 0);
  338. assert.notEqual(run('unpack', '--destination', destination).status, 0);
  339. writeFileSync(`${f.archive}.json`, JSON.stringify({ ...receipt, sha256: '0'.repeat(64) }));
  340. assert.notEqual(run('unpack', '--destination', `${destination}-bad`).status, 0);
  341. assert.equal(existsSync(`${destination}-bad`), false);
  342. writeFileSync(`${f.archive}.json`, JSON.stringify(receipt));
  343. const reports = path.join(f.directory, 'reports');
  344. mkdirSync(reports);
  345. for (const platform of ['linux', 'darwin', 'win32']) {
  346. const folder = path.join(reports, platform);
  347. mkdirSync(folder);
  348. writeFileSync(path.join(folder, 'verification.json'), JSON.stringify({ revision, platform, arch: 'fixture', node: 'v24', profile: 'archive', status: 'PASS', gates: [{ name: 'build', status: 'PASS' }] }));
  349. }
  350. assert.equal(run('finalize', '--reports', reports).status, 0);
  351. assert.equal(JSON.parse(readFileSync(path.join(f.directory, 'candidate.json'))).sha256, receipt.sha256);
  352. const windows = path.join(reports, 'win32/verification.json');
  353. const report = JSON.parse(readFileSync(windows));
  354. for (const change of [{ status: 'FAIL' }, { revision: 'b'.repeat(40) }, { gates: [{ name: 'build', status: 'NOT_RUN' }] }]) {
  355. writeFileSync(windows, JSON.stringify({ ...report, ...change }));
  356. assert.notEqual(run('finalize', '--reports', reports).status, 0);
  357. }
  358. rmSync(path.dirname(windows), { recursive: true });
  359. assert.notEqual(run('finalize', '--reports', reports).status, 0);
  360. });
  361. test('source inventory rejects unregistered, missing and duplicate first-party test gates', () => {
  362. const existing = 'packages/example/src/existing.test.ts';
  363. const omitted = 'packages/example/test/omitted.spec.tsx';
  364. const missing = 'packages/example/test/missing.test.ts';
  365. const files = [existing, omitted, 'third_party/vendor/vendor.test.ts', 'test/release.test.mjs'];
  366. assert.deepEqual(suiteInventoryViolations(files, { capability: [existing, existing, missing] }), [
  367. `${existing}: duplicate Vitest registration`,
  368. `${missing}: registered Vitest file is missing`,
  369. `${omitted}: first-party test is absent from test/vitest-suites.json`,
  370. ]);
  371. assert.deepEqual(suiteInventoryViolations(files, { capability: [existing, omitted] }), []);
  372. });
  373. test('suite runner preserves gate arguments and canonicalizes Windows temporary paths', t => {
  374. const root = mkdtempSync(path.join(tmpdir(), 'suite-runner-'));
  375. t.after(() => rmSync(root, { recursive: true, force: true }));
  376. for (const directory of ['scripts/lib', 'test', 'node_modules/vitest', 'temporary'])
  377. mkdirSync(path.join(root, directory), { recursive: true });
  378. for (const file of ['scripts/run-vitest-suite.mjs', 'scripts/lib/vitest-suites.mjs'])
  379. copyFileSync(new URL(`../${file}`, import.meta.url), path.join(root, file));
  380. writeFileSync(path.join(root, 'test/vitest-suites.json'), JSON.stringify({ suites: { fixture: ['test/example.test.ts'] } }));
  381. writeFileSync(path.join(root, 'node_modules/vitest/package.json'), JSON.stringify({ bin: { vitest: 'cli.cjs' } }));
  382. writeFileSync(path.join(root, 'node_modules/vitest/cli.cjs'), 'console.log(JSON.stringify({args:process.argv.slice(2),temp:process.env.TEMP,tmp:process.env.TMP,cwd:process.cwd()})); process.exit(17);');
  383. const alias = path.join(root, 'temporary-alias');
  384. symlinkSync(path.join(root, 'temporary'), alias, process.platform === 'win32' ? 'junction' : 'dir');
  385. for (const platform of ['linux', 'darwin', 'win32']) {
  386. const preload = path.join(root, 'platform.cjs');
  387. writeFileSync(preload, `Object.defineProperty(process, 'platform', { value: ${JSON.stringify(platform)} });`);
  388. const result = spawnSync(process.execPath, ['--require', preload, path.join(root, 'scripts/run-vitest-suite.mjs'), 'fixture'], {
  389. encoding: 'utf8', env: { ...process.env, TEMP: alias, TMP: alias, TMPDIR: alias },
  390. });
  391. assert.equal(result.status, 17, result.stderr);
  392. const child = JSON.parse(result.stdout);
  393. assert.deepEqual(child.args, ['run', '--config', 'vitest.oss.config.mjs',
  394. ...(platform === 'win32' ? ['--maxWorkers', '1'] : []), 'test/example.test.ts']);
  395. assert.equal(realpathSync(child.cwd), realpathSync(root));
  396. const expected = platform === 'win32' ? realpathSync.native(alias) : alias;
  397. assert.equal(child.temp, expected);
  398. assert.equal(child.tmp, expected);
  399. }
  400. });
  401. test('public support forms preserve destination URLs and separate Desktop from CLI reports', () => {
  402. const forms = ['01-bug-report.yml', '02-feature-request.yml', '03-question.yml'];
  403. for (const name of forms) {
  404. const form = parseYaml(readFileSync(new URL(`../.github/ISSUE_TEMPLATE/${name}`, import.meta.url), 'utf8'));
  405. const product = form.body.find(field => field.id === 'product');
  406. assert.equal(product.validations.required, true);
  407. assert.ok(product.attributes.options.includes('Desktop app'));
  408. assert.ok(product.attributes.options.includes('CLI - ACP'));
  409. assert.ok(product.attributes.options.includes('CLI - headless'));
  410. const ids = form.body.filter(field => field.id).map(field => field.id);
  411. assert.equal(new Set(ids).size, ids.length);
  412. }
  413. const bug = parseYaml(readFileSync(new URL('../.github/ISSUE_TEMPLATE/01-bug-report.yml', import.meta.url), 'utf8'));
  414. assert.notEqual(bug.body.find(field => field.id === 'upload-id').validations?.required, true);
  415. for (const retired of ['bug.yml', 'feature.yml'])
  416. assert.equal(existsSync(new URL(`../.github/ISSUE_TEMPLATE/${retired}`, import.meta.url)), false);
  417. assert.equal(classifyChanges(['README_ZH.md', 'README.md']).docsOnly, true);
  418. });
  419. test('issue notification is restricted to public destination events and builds payloads offline', t => {
  420. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/sync-issue-to-feishu.yml', import.meta.url), 'utf8'));
  421. assert.deepEqual(workflow.on, { issues: { types: ['opened'] } });
  422. assert.deepEqual(workflow.permissions, { contents: 'read', issues: 'read' });
  423. const job = workflow.jobs['notify-feishu'];
  424. assert.equal(job.if, "${{ github.repository == 'MiniMax-AI/minimax-code' && github.event.repository.private == false && !github.event.issue.pull_request }}");
  425. const generate = job.steps.find(step => step.name === 'Build Feishu payload').run;
  426. // Execute only the payload builder, never the delivery step or its secrets.
  427. assert.doesNotMatch(generate, /\$\{\{\s*github\.event/);
  428. const script = generate.match(/^node <<'EOF'\r?\n([\s\S]*?)\r?\nEOF\s*$/)?.[1];
  429. assert.ok(script);
  430. const directory = mkdtempSync(path.join(tmpdir(), 'support-payload-'));
  431. t.after(() => rmSync(directory, { recursive: true, force: true }));
  432. const marker = path.join(directory, 'must-not-execute');
  433. const event = {
  434. repository: { full_name: 'MiniMax-AI/minimax-code', html_url: 'https://github.com/MiniMax-AI/minimax-code' },
  435. issue: { number: 7, title: 'Synthetic issue', body: `$(touch ${marker}) <at id=all>test</at>`, labels: [{ name: 'bug' }], created_at: '2026-09-18T00:00:00Z', html_url: 'https://github.com/MiniMax-AI/minimax-code/issues/7', user: { login: 'fixture' } },
  436. };
  437. const eventPath = path.join(directory, 'event.json');
  438. writeFileSync(eventPath, JSON.stringify(event));
  439. const result = spawnSync(process.execPath, ['--input-type=commonjs'], {
  440. input: script, cwd: directory, encoding: 'utf8', timeout: 10000,
  441. env: { ...process.env, GITHUB_EVENT_PATH: eventPath, FEISHU_BOT_SECRET: '', FEISHU_BOT_WEBHOOK: '' },
  442. });
  443. assert.equal(result.status, 0, result.stderr);
  444. assert.equal(existsSync(marker), false);
  445. const payload = JSON.parse(readFileSync(path.join(directory, 'feishu-payload.json'), 'utf8'));
  446. assert.equal(payload.card.header.template, 'red');
  447. assert.equal(payload.card.card_link.url, event.issue.html_url);
  448. assert.equal(payload.card.header.title.content, 'GitHub Issue #7: Synthetic issue');
  449. assert.doesNotMatch(JSON.stringify(payload), /<at /);
  450. assert.match(JSON.stringify(payload), /‹at id=all›/);
  451. assert.equal(payload.sign, undefined);
  452. });
  453. test('source imports preserve vendored Office schema bytes through Git staging', t => {
  454. const directory = mkdtempSync(path.join(tmpdir(), 'source-import-bytes-'));
  455. t.after(() => rmSync(directory, { recursive: true, force: true }));
  456. const git = (...args) => execFileSync('git', ['-C', directory, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
  457. git('init');
  458. copyFileSync(new URL('../.gitattributes', import.meta.url), path.join(directory, '.gitattributes'));
  459. const schema = 'packages/local-runtime/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd';
  460. mkdirSync(path.dirname(path.join(directory, schema)), { recursive: true });
  461. const bytes = Buffer.from('<schema>\r\n <element name="fixture"/>\r\n</schema>\r\n');
  462. writeFileSync(path.join(directory, schema), bytes);
  463. for (const autocrlf of ['true', 'false']) {
  464. git('-c', `core.autocrlf=${autocrlf}`, 'add', '--', '.gitattributes', schema);
  465. assert.deepEqual(git('show', `:${schema}`), bytes);
  466. }
  467. });