source-sync.test.mjs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  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. import { cliBuildVersion, cliExternalModules, cliReleaseTargets, versionFromTag } from '../scripts/lib/cli-release.mjs';
  18. import { releaseManifest } from '../scripts/package-cli-release.mjs';
  19. import { validateReleaseReports } from '../scripts/publish-cli-release.mjs';
  20. import { compareVersions, releaseCli } from '../scripts/release-cli.mjs';
  21. import { compareRuns, validateRun, validateRequest, validateToolOutput, median, selectScenarios } from '../scripts/perf/report.mjs';
  22. test('performance defaults to the 100-round suite; long history requires explicit selection', () => {
  23. const config = JSON.parse(readFileSync(new URL('../scripts/perf/config.json', import.meta.url), 'utf8'));
  24. assert.deepEqual(selectScenarios(config).map(s => s.id), ['upstream-100']);
  25. assert.deepEqual(selectScenarios(config, { suite: 'full' }).map(s => s.id), ['startup', 'upstream-100', 'history-300']);
  26. assert.deepEqual(selectScenarios(config, { scenario: 'startup' }).map(s => s.id), ['startup']);
  27. assert.throws(() => selectScenarios(config, { suite: 'typo' }));
  28. assert.throws(() => selectScenarios(config, { scenario: 'typo' }));
  29. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/performance.yml', import.meta.url), 'utf8'));
  30. assert.equal(workflow.on.workflow_dispatch.inputs.suite.default, 'full');
  31. assert.deepEqual(workflow.on.workflow_dispatch.inputs.suite.options, ['full', 'basic']);
  32. const compare = workflow.jobs.performance.steps.find(s => s.name === 'Compare on this runner');
  33. assert.equal(compare.env.PERF_SUITE, "${{ inputs.suite || 'basic' }}");
  34. assert.match(compare.run, /--suite "\$PERF_SUITE"/);
  35. });
  36. test('performance request audit rejects truncated wire history and empty tool results', () => {
  37. const responses = [
  38. { message: { content: 'full history', tool_calls: [{ id: 'call_long_run_1', function: { name: 'bash', arguments: { command: 'ls' } } }] } },
  39. { message: { content: 'done' } }, { message: { content: ' ' } },
  40. ];
  41. const messages = [{ role: 'user', content: 'task' },
  42. { role: 'assistant', content: 'full history', tool_calls: [{ id: 'call_long_run_1', function: { name: 'bash', arguments: '{"command":"ls"}' } }] },
  43. { role: 'tool', tool_call_id: 'call_long_run_1', content: 'README.txt\n' }];
  44. assert.doesNotThrow(() => validateRequest({ messages }, responses, 2, process.cwd(), 'task'));
  45. assert.throws(() => validateRequest({ messages: messages.slice(0, 1) }, responses, 2, process.cwd(), 'task'), /conversation length/);
  46. assert.throws(() => validateRequest({ messages: [] }, responses, 1, process.cwd(), 'task'), /conversation length/);
  47. assert.throws(() => validateRequest({ messages: [messages[0], messages[2], messages[1]] }, responses, 2, process.cwd(), 'task'), /order changed/);
  48. assert.throws(() => validateRequest({ messages: [{ role: 'user', content: 'wrong' }] }, responses, 1, process.cwd(), 'task'), /task changed/);
  49. assert.doesNotThrow(() => validateRequest({ messages: [messages[0]] }, responses, 1, process.cwd(), 'task'));
  50. const changed = structuredClone(messages);
  51. changed[1].content = 'shortened';
  52. assert.throws(() => validateRequest({ messages: changed }, responses, 2, process.cwd(), 'task'), /body changed/);
  53. changed[1].content = 'full history'; changed[2].content = '';
  54. assert.throws(() => validateRequest({ messages: changed }, responses, 2, process.cwd(), 'task'), /lost fixture/);
  55. assert.throws(() => validateToolOutput([], 'ls', process.cwd()), /lost fixture/);
  56. assert.throws(() => validateToolOutput('wrong', 'echo expected', process.cwd()), /Echo/);
  57. assert.throws(() => validateToolOutput('/wrong', 'pwd', process.cwd()), /directory/);
  58. assert.doesNotThrow(() => validateToolOutput(realpathSync(process.cwd()) + '\n', 'pwd', process.cwd()));
  59. });
  60. test('performance comparison rejects incomplete, invalid and unstable samples', () => {
  61. const config = { repetitions: 3, maxSpread: 0.3, thresholds: { cpuSeconds: { relative: 0.2, absolute: 0.5 } } };
  62. const runs = values => values.map(cpuSeconds => ({ cpuSeconds }));
  63. assert.equal(median([3, 1, 2]), 2);
  64. assert.equal(compareRuns(runs([10, 10, 10]), runs([10, 10, 10]), config)[0].status, 'PASS');
  65. assert.equal(compareRuns(runs([10, 10, 10]), runs([13, 13, 13]), config)[0].status, 'REGRESSION');
  66. assert.equal(compareRuns(runs([1, 1, 1]), runs([1.4, 1.4, 1.4]), config)[0].status, 'PASS');
  67. assert.equal(compareRuns(runs([10, 10, 10]), runs([10, 10, 20]), config)[0].status, 'INCONCLUSIVE');
  68. assert.throws(() => compareRuns(runs([10, 10]), runs([10, 10, 10]), config));
  69. assert.throws(() => compareRuns(runs([10, NaN, 10]), runs([10, 10, 10]), config));
  70. assert.throws(() => compareRuns(runs([0, 0, 0]), runs([10, 10, 10]), config));
  71. });
  72. test('performance measurements require complete successful tool execution', () => {
  73. const meta = { schemaVersion: 1, status: 'ok', exit: { code: 0 }, mock: { requests: 2 },
  74. sampling: { backend: 'rusage', withTree: true }, summary: { count: 10 },
  75. duration: { endToEndMs: 1000 }, cost: { cpuSeconds: 0.5 }, peaks: { treeRssBytes: 1024 } };
  76. const messages = [
  77. { role: 'assistant', content: [{ type: 'toolCall', id: 'call_long_run_1', name: 'bash' }] },
  78. { role: 'toolResult', toolCallId: 'call_long_run_1', isError: false },
  79. { role: 'assistant', content: [{ type: 'text', text: 'done' }] },
  80. ];
  81. assert.equal(validateRun(meta, messages, { turns: 1 }, 'done').rssBytes, 1024);
  82. const expected = [{ message: { content: '', tool_calls: [{ function: { arguments: { command: 'pwd' } } }] } }];
  83. const withArguments = structuredClone(messages);
  84. withArguments[0].content[0].arguments = { command: 'pwd' };
  85. assert.doesNotThrow(() => validateRun(meta, withArguments, { turns: 1 }, 'done', expected));
  86. withArguments[0].content[0].arguments.command = 'true';
  87. assert.throws(() => validateRun(meta, withArguments, { turns: 1 }, 'done', expected), /command changed/);
  88. withArguments[0].content[0].arguments.command = 'pwd';
  89. expected[0].message.content = 'body that must be retained';
  90. assert.throws(() => validateRun(meta, withArguments, { turns: 1 }, 'done', expected), /body changed/);
  91. for (const mutate of [
  92. (m, _) => { m.status = 'timeout'; }, (m, _) => { m.mock.requests = 1; },
  93. (m, _) => { m.sampling.backend = 'ps'; }, (m, _) => { m.summary.count = 0; },
  94. (m, _) => { m.cost.cpuSeconds = null; }, (_, rows) => { rows[1].isError = true; },
  95. (_, rows) => { rows[1].toolCallId = 'wrong'; }, (_, rows) => { rows.pop(); },
  96. (_, rows) => { rows.push(rows[1]); },
  97. ]) {
  98. const copiedMeta = structuredClone(meta), copiedMessages = structuredClone(messages);
  99. mutate(copiedMeta, copiedMessages);
  100. assert.throws(() => validateRun(copiedMeta, copiedMessages, { turns: 1 }, 'done'));
  101. }
  102. });
  103. test('performance workflow uses pinned mock input and an unprivileged PR job', () => {
  104. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/performance.yml', import.meta.url), 'utf8'));
  105. const config = JSON.parse(readFileSync(new URL('../scripts/perf/config.json', import.meta.url), 'utf8'));
  106. assert.ok(Object.hasOwn(workflow.on, 'pull_request'));
  107. assert.ok(!Object.hasOwn(workflow.on, 'pull_request_target'));
  108. assert.deepEqual(workflow.permissions, { contents: 'read' });
  109. const steps = workflow.jobs.performance.steps;
  110. const benchmark = steps.find(s => s.with?.repository === 'KonghaYao/harness-perf-benchmark');
  111. assert.equal(benchmark.with.ref, config.benchmarkRevision);
  112. assert.match(config.benchmarkRevision, /^[a-f0-9]{40}$/);
  113. for (const step of steps.filter(s => s.uses)) assert.match(step.uses, /@[a-f0-9]{40}$/);
  114. const standard = config.scenarios.find(s => s.id === 'upstream-100');
  115. assert.deepEqual([standard.turns, standard.bodyKb, standard.chunkSize], [100, 4, 64]);
  116. assert.ok(config.scenarios.some(s => s.minimumTextUnits > 1048576));
  117. });
  118. test('release tags are canonical and must match both source versions without overriding them', t => {
  119. for (const tag of ['v0.4.13', 'v1.0.0-rc.1', 'v0.0.0', 'v2.3.4-beta-test.0'])
  120. assert.equal(versionFromTag(tag), tag.slice(1));
  121. for (const tag of [undefined, '', '0.4.13', 'v01.2.3', 'v1.02.3', 'v1.2.03', 'v1.2.3-01', 'v1.2.3+build', 'v1.2.3\n', 'v1.2.3;echo bad', 'v1.2.3/../bad'])
  122. assert.throws(() => versionFromTag(tag), /Release tag/);
  123. const f = fixture(t);
  124. mkdirSync(path.join(f.root, 'packages/tui'), { recursive: true });
  125. const manifest = path.join(f.root, 'packages/tui/package.json');
  126. writeFileSync(manifest, JSON.stringify({ version: '0.4.12', private: true }));
  127. writeFileSync(path.join(f.root, 'package.json'), JSON.stringify({ version: '0.4.12', private: true }));
  128. const before = readFileSync(manifest);
  129. assert.equal(cliBuildVersion(f.root, 'v0.4.12'), '0.4.12');
  130. assert.throws(() => cliBuildVersion(f.root, 'v0.4.13-rc.1'), /Release tag must match/);
  131. assert.deepEqual(readFileSync(manifest), before);
  132. writeFileSync(manifest, JSON.stringify({ version: '0.4.13' }));
  133. assert.throws(() => cliBuildVersion(f.root, null), /Root and TUI/);
  134. });
  135. function cliReleaseFixture(t) {
  136. const home = mkdtempSync(path.join(tmpdir(), 'cli-release-'));
  137. t.after(() => rmSync(home, { recursive: true, force: true }));
  138. const root = path.join(home, 'checkout'), remote = path.join(home, 'remote.git');
  139. execFileSync('git', ['init', '--bare', remote], { stdio: 'ignore' });
  140. execFileSync('git', ['init', '--initial-branch=main', root], { stdio: 'ignore' });
  141. const git = (...args) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
  142. git('config', 'user.name', 'Release Fixture'); git('config', 'user.email', 'release@example.invalid');
  143. git('config', 'core.hooksPath', path.join(home, 'no-hooks'));
  144. mkdirSync(path.join(root, 'packages/tui'), { recursive: true });
  145. for (const name of ['package.json', 'packages/tui/package.json']) writeFileSync(path.join(root, name), JSON.stringify({ name: 'fixture', version: '1.2.3', private: true }, null, 2) + '\n');
  146. git('add', '.'); git('commit', '-m', 'Fixture baseline'); git('remote', 'add', 'origin', remote); git('push', '-u', 'origin', 'main');
  147. return { root, remote, git, base: git('rev-parse', 'HEAD') };
  148. }
  149. test('release command bumps source before tagging, pushes a release branch and opens its version PR', t => {
  150. const f = cliReleaseFixture(t);
  151. const prs = [];
  152. const plan = releaseCli({ root: f.root, version: '1.2.4', dryRun: true });
  153. assert.equal(plan.tag, 'v1.2.4');
  154. assert.equal(f.git('status', '--porcelain'), '');
  155. assert.equal(f.git('rev-parse', 'HEAD'), f.base);
  156. const result = releaseCli({ root: f.root, version: '1.2.4', openPullRequest: request => prs.push(request) });
  157. assert.equal(f.git('branch', '--show-current'), 'release/v1.2.4');
  158. assert.equal(f.git('cat-file', '-t', 'v1.2.4'), 'tag');
  159. assert.equal(f.git('rev-parse', 'v1.2.4^{commit}'), result.revision);
  160. assert.equal(f.git('rev-parse', 'origin/main'), f.base);
  161. assert.equal(f.git('rev-parse', 'origin/release/v1.2.4'), result.revision);
  162. for (const name of ['package.json', 'packages/tui/package.json'])
  163. assert.equal(JSON.parse(f.git('show', `v1.2.4:${name}`)).version, '1.2.4');
  164. assert.equal(prs.length, 1);
  165. assert.equal(prs[0].branch, 'release/v1.2.4');
  166. assert.equal(f.git('ls-remote', 'origin', 'refs/heads/main').split('\t')[0], f.base);
  167. assert.ok(f.git('ls-remote', 'origin', 'refs/tags/v1.2.4'));
  168. });
  169. test('release command rejects dirty trees, version regressions, stale bases and existing remote tags', t => {
  170. const f = cliReleaseFixture(t);
  171. const release = version => releaseCli({ root: f.root, version, dryRun: true });
  172. for (const version of ['1.2.3', '1.2.2', '1.2.3-rc.1']) assert.throws(() => release(version), /must be newer/);
  173. writeFileSync(path.join(f.root, 'untracked'), 'unfinished');
  174. assert.throws(() => release('1.2.4'), /clean working tree/);
  175. f.git('add', 'untracked'); f.git('commit', '-m', 'Unreviewed change');
  176. assert.throws(() => release('1.2.4'), /latest origin\/main/);
  177. f.git('switch', '--detach', f.base);
  178. f.git('tag', 'v1.2.4'); f.git('push', 'origin', 'refs/tags/v1.2.4'); f.git('tag', '-d', 'v1.2.4');
  179. assert.throws(() => release('1.2.4'), /already exists on origin/);
  180. assert.equal(f.git('rev-parse', 'HEAD'), f.base);
  181. assert.equal(f.git('status', '--porcelain'), '');
  182. for (const [a, b] of [['1.2.4', '1.2.3'], ['1.2.4', '1.2.4-rc.1'], ['1.2.4-rc.10', '1.2.4-rc.2'], ['1.2.4-beta', '1.2.4-1']]) {
  183. assert.equal(compareVersions(a, b), 1); assert.equal(compareVersions(b, a), -1);
  184. }
  185. });
  186. test('rejected tag pushes cannot leave a partial remote release branch or open a version PR', { skip: process.platform === 'win32' }, t => {
  187. const f = cliReleaseFixture(t);
  188. execFileSync('git', ['--git-dir', f.remote, 'config', 'core.hooksPath', path.join(f.remote, 'hooks')]);
  189. writeFileSync(path.join(f.remote, 'hooks/update'), '#!/bin/sh\ncase "$1" in refs/tags/*) exit 1 ;; esac\nexit 0\n', { mode: 0o755 });
  190. let opened = false;
  191. assert.throws(() => releaseCli({ root: f.root, version: '1.2.4', openPullRequest: () => { opened = true; } }));
  192. assert.equal(opened, false);
  193. assert.equal(f.git('ls-remote', 'origin', 'refs/tags/v1.2.4', 'refs/heads/release/v1.2.4'), '');
  194. assert.equal(f.git('rev-parse', 'origin/main'), f.base);
  195. assert.equal(f.git('rev-parse', 'v1.2.4^{commit}'), f.git('rev-parse', 'HEAD'));
  196. });
  197. test('npm release manifests require native SQLite and pin installed external dependencies', t => {
  198. const f = fixture(t);
  199. for (const name of cliExternalModules) {
  200. const directory = path.join(f.root, 'node_modules', name);
  201. mkdirSync(directory, { recursive: true });
  202. writeFileSync(path.join(directory, 'package.json'), JSON.stringify({ name, version: '1.2.3' }));
  203. }
  204. const manifest = releaseManifest([f.root], '0.4.13');
  205. assert.equal(manifest.version, '0.4.13');
  206. assert.equal(manifest.private, true);
  207. assert.equal(manifest.bin.mcode, 'cli.js');
  208. assert.equal(manifest.dependencies['better-sqlite3'], '1.2.3');
  209. assert.equal(manifest.dependencies['@vscode/ripgrep'], '1.2.3');
  210. assert.equal(manifest.optionalDependencies['@mariozechner/clipboard'], '1.2.3');
  211. assert.equal(manifest.scripts, undefined);
  212. const conflicting = path.join(f.source, 'node_modules/better-sqlite3');
  213. mkdirSync(conflicting, { recursive: true });
  214. writeFileSync(path.join(conflicting, 'package.json'), JSON.stringify({ name: 'better-sqlite3', version: '9.9.9' }));
  215. assert.throws(() => releaseManifest([f.root, f.source], '0.4.13'), /Expected one installed version/);
  216. });
  217. test('CLI publication requires every supported installation receipt for the exact archive and revision', t => {
  218. const f = fixture(t);
  219. const archive = path.join(f.root, 'minimax-code-0.4.13.tar.gz');
  220. writeFileSync(archive, 'synthetic archive');
  221. const sha256 = createHash('sha256').update(readFileSync(archive)).digest('hex');
  222. writeFileSync(`${archive}.sha256`, `${sha256} ${path.basename(archive)}\n`);
  223. const revision = 'a'.repeat(40);
  224. const reports = path.join(f.root, 'reports');
  225. for (const target of cliReleaseTargets) {
  226. const directory = path.join(reports, `cli-install-${target.os}-${target.node}`);
  227. mkdirSync(directory, { recursive: true });
  228. writeFileSync(path.join(directory, 'package-install.json'), JSON.stringify({
  229. status: 'PASS', version: '0.4.13', revision, sha256,
  230. platform: target.os.startsWith('ubuntu') ? 'linux' : 'darwin', node: `v${target.node}`,
  231. }));
  232. writeFileSync(path.join(directory, 'verification.json'), JSON.stringify({
  233. status: 'PASS', profile: 'package', revision, gates: [{ name: 'test:release-package', status: 'PASS' }],
  234. }));
  235. }
  236. const options = { archive, reports, version: '0.4.13', revision };
  237. assert.equal(validateReleaseReports(options), sha256);
  238. assert.throws(() => validateReleaseReports({ ...options, version: '0.4.14' }));
  239. assert.throws(() => validateReleaseReports({ ...options, revision: 'b'.repeat(40) }));
  240. const target = cliReleaseTargets.at(-1);
  241. const receipt = path.join(reports, `cli-install-${target.os}-${target.node}`, 'package-install.json');
  242. const original = readFileSync(receipt, 'utf8');
  243. for (const override of [{ sha256: '0'.repeat(64) }, { status: 'FAIL' }, { node: 'v20.0.0' }]) {
  244. writeFileSync(receipt, JSON.stringify({ ...JSON.parse(original), ...override }));
  245. assert.throws(() => validateReleaseReports(options));
  246. }
  247. rmSync(receipt);
  248. assert.throws(() => validateReleaseReports(options));
  249. writeFileSync(receipt, original);
  250. writeFileSync(archive, 'changed archive');
  251. assert.throws(() => validateReleaseReports(options));
  252. });
  253. test('CLI release publishes only tag pushes after full verification and archive installation', () => {
  254. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/cli-release.yml', import.meta.url), 'utf8'));
  255. assert.deepEqual(workflow.on.push, { tags: ['v*'] });
  256. assert.equal(workflow.on.workflow_dispatch.inputs.tag.required, false);
  257. assert.equal(workflow.permissions.contents, 'read');
  258. assert.equal(workflow.concurrency['cancel-in-progress'], false);
  259. assert.ok(workflow.jobs.build.steps.some(step => step.run === 'pnpm verify'));
  260. assert.ok(workflow.jobs.build.steps.some(step => step.run?.includes('cliBuildVersion(process.cwd(), tag)')));
  261. assert.deepEqual(workflow.jobs.publish.needs, ['build', 'install']);
  262. assert.equal(workflow.jobs.publish.if, "github.event_name == 'push'");
  263. assert.equal(workflow.jobs.publish.permissions.contents, 'write');
  264. assert.equal(workflow.jobs.install.strategy.matrix, '${{ fromJSON(needs.build.outputs.matrix) }}');
  265. const install = workflow.jobs.install.steps.find(step => step.run === 'pnpm verify --profile package');
  266. assert.ok(install.env.MCODE_RELEASE_ARCHIVE.endsWith('.tar.gz'));
  267. for (const job of Object.values(workflow.jobs)) {
  268. for (const step of job.steps) {
  269. if (step.uses && !step.uses.startsWith('./')) assert.match(step.uses, /@[a-f0-9]{40}$/);
  270. if (step.uses?.startsWith('actions/checkout@')) assert.equal(step.with['persist-credentials'], false);
  271. if (step.run) assert.doesNotMatch(step.run, /\$\{\{.*(?:inputs|github\.(?:ref|event))/);
  272. }
  273. }
  274. });
  275. import { runInNewContext } from 'node:vm';
  276. function fixture(t) {
  277. const home = mkdtempSync(path.join(tmpdir(), 'source-sync-'));
  278. t.after(() => rmSync(home, { recursive: true, force: true }));
  279. const source = path.join(home, 'source'), root = path.join(home, 'public');
  280. mkdirSync(path.join(source, 'packages/example'), { recursive: true });
  281. mkdirSync(path.join(root, path.dirname(extractionPath)), { recursive: true });
  282. mkdirSync(path.join(root, 'packages/example'), { recursive: true });
  283. const git = (...args) => execFileSync('git', ['-C', source, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
  284. git('init'); git('config', 'user.name', 'Fixture'); git('config', 'user.email', 'fixture@example.invalid');
  285. const write = (base, name, text) => writeFileSync(path.join(base, 'packages/example', name), text);
  286. write(source, 'a.txt', 'first\nsecond\nthird\nfourth\nfifth\n');
  287. write(source, 'delete.txt', 'old\n');
  288. git('add', 'packages/example/a.txt', 'packages/example/delete.txt'); git('-c', 'core.hooksPath=', 'commit', '-m', 'Fixture baseline');
  289. const baseline = git('rev-parse', 'HEAD');
  290. for (const name of ['a.txt', 'delete.txt']) write(root, name, readFileSync(path.join(source, 'packages/example', name)));
  291. writeFileSync(path.join(root, extractionPath), JSON.stringify({ sourceRevision: baseline, packageRoots: ['packages/example'] }));
  292. writeFileSync(path.join(root, inventoryPath), JSON.stringify({ files: ['packages/example/a.txt', 'packages/example/delete.txt'] }));
  293. return { source, root, out: path.join(home, 'review'), ref: 'HEAD', git, write };
  294. }
  295. test('sync proposes updates/deletions, reports unlisted files and does not mutate public source', t => {
  296. const f = fixture(t);
  297. f.write(f.source, 'a.txt', 'new\n'); f.write(f.source, 'new.txt', 'unreviewed\n');
  298. f.git('rm', 'packages/example/delete.txt');
  299. f.git('add', 'packages/example/a.txt', 'packages/example/new.txt'); f.git('-c', 'core.hooksPath=', 'commit', '-m', 'Fixture change');
  300. const before = readFileSync(path.join(f.root, 'packages/example/a.txt'));
  301. const result = prepareSourceSync(f);
  302. assert.deepEqual(result.entries.map(e => e.status), ['update-candidate', 'delete-candidate', 'unlisted-source-review']);
  303. assert.deepEqual(readFileSync(path.join(f.root, 'packages/example/a.txt')), before);
  304. assert.equal(existsSync(path.join(f.out, 'candidates/packages/example/new.txt')), false);
  305. assert.equal(readFileSync(path.join(f.out, 'candidates/packages/example/a.txt'), 'utf8'), 'new\n');
  306. });
  307. test('three-way merge preserves public adaptations and exposes overlapping conflicts', t => {
  308. const f = fixture(t);
  309. f.write(f.root, 'a.txt', 'public\nsecond\nthird\nfourth\nfifth\n');
  310. f.write(f.source, 'a.txt', 'first\nsecond\nthird\nfourth\nupstream\n');
  311. f.git('add', 'packages/example/a.txt'); f.git('-c', 'core.hooksPath=', 'commit', '-m', 'Fixture change');
  312. assert.equal(prepareSourceSync(f).entries[0].status, 'merged-candidate');
  313. assert.equal(readFileSync(path.join(f.out, 'candidates/packages/example/a.txt'), 'utf8'), 'public\nsecond\nthird\nfourth\nupstream\n');
  314. f.write(f.root, 'a.txt', 'first\nsecond\nthird\nfourth\nconflicting\n');
  315. f.out += '-conflict';
  316. assert.equal(prepareSourceSync(f).entries[0].status, 'merge-conflict');
  317. assert.match(readFileSync(path.join(f.out, 'candidates/packages/example/a.txt'), 'utf8'), /<<<<<<< public/);
  318. });
  319. test('rejects existing output, output in repositories and unsafe inventory', t => {
  320. const f = fixture(t);
  321. assert.throws(() => prepareSourceSync({ ...f, out: f.root }), /Output/);
  322. assert.throws(() => prepareSourceSync({ ...f, out: path.join(f.source, 'review') }), /Output/);
  323. mkdirSync(f.out);
  324. assert.throws(() => prepareSourceSync(f), /Output/);
  325. writeFileSync(path.join(f.root, inventoryPath), JSON.stringify({ files: ['../outside'] }));
  326. assert.throws(() => prepareSourceSync({ ...f, out: `${f.out}-new` }), /Unsafe inventory/);
  327. });
  328. // Exercise the real verification dispatcher in an isolated repository. These
  329. // commands stand in for gates, so a failure test cannot accidentally run builds
  330. // or the release-tools suite recursively.
  331. function verificationFixture(t) {
  332. const directory = mkdtempSync(path.join(tmpdir(), 'verify-fixture-'));
  333. t.after(() => rmSync(directory, { recursive: true, force: true }));
  334. const root = path.join(directory, 'source');
  335. mkdirSync(path.join(root, 'scripts'), { recursive: true });
  336. const verifier = path.join(root, 'scripts/verify.mjs');
  337. copyFileSync(new URL('../scripts/verify.mjs', import.meta.url), verifier);
  338. const manager = path.join(directory, 'manager.cjs');
  339. writeFileSync(manager, `
  340. const fs = require('node:fs');
  341. const path = require('node:path');
  342. const gate = process.argv[3];
  343. const report = JSON.parse(fs.readFileSync(path.join(process.env.MCODE_VERIFY_REPORT_DIR, 'verification.json')));
  344. if (report.status !== 'RUNNING' || report.gates.find(g => g.name === gate)?.status !== 'RUNNING') process.exit(99);
  345. console.log('FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED');
  346. if (gate === process.env.VERIFY_FIXTURE_FAIL) process.exit(17);
  347. `);
  348. const exportRecord = path.join(directory, 'export-path.txt');
  349. writeFileSync(path.join(root, 'scripts/export-source-preview.mjs'), `
  350. import { writeFileSync } from 'node:fs';
  351. writeFileSync(process.argv[3], 'synthetic export');
  352. writeFileSync(process.env.VERIFY_FIXTURE_EXPORT, process.argv[3]);
  353. `);
  354. const reportDir = path.join(directory, 'reports');
  355. const summaryPath = path.join(directory, 'summary.md');
  356. function run(args = [], env = {}) {
  357. return spawnSync(process.execPath, [verifier, ...args], {
  358. cwd: root,
  359. encoding: 'utf8',
  360. timeout: 20000,
  361. env: {
  362. ...process.env,
  363. npm_execpath: manager,
  364. MCODE_VERIFY_REPORT_DIR: reportDir,
  365. GITHUB_STEP_SUMMARY: summaryPath,
  366. VERIFY_FIXTURE_EXPORT: exportRecord,
  367. VERIFY_FIXTURE_FAIL: '',
  368. ...env,
  369. },
  370. });
  371. }
  372. return {
  373. run, exportRecord, reportDir, summaryPath,
  374. report: () => JSON.parse(readFileSync(path.join(reportDir, 'verification.json'), 'utf8')),
  375. };
  376. }
  377. test('platform verification omits only the compiler gate and invalid profiles fail closed', t => {
  378. const f = verificationFixture(t);
  379. const full = f.run(['--list']);
  380. const platform = f.run(['--profile', 'platform', '--list']);
  381. assert.equal(full.status, 0, full.stderr);
  382. assert.equal(platform.status, 0, platform.stderr);
  383. const gates = full.stdout.trim().split('\n');
  384. assert.ok(gates.includes('typecheck'));
  385. assert.deepEqual(platform.stdout.trim().split('\n'), gates.filter(g => g !== 'typecheck'));
  386. assert.notEqual(f.run(['--profile', 'platfrom', '--list']).status, 0);
  387. assert.notEqual(f.run(['--unknown']).status, 0);
  388. assert.equal(existsSync(f.reportDir), false);
  389. assert.equal(existsSync(f.exportRecord), false);
  390. });
  391. test('verification reports successes and intentional skips without collecting gate output', t => {
  392. const f = verificationFixture(t);
  393. const result = f.run(['--profile', 'platform']);
  394. assert.equal(result.status, 0, result.stderr);
  395. const report = f.report();
  396. assert.equal(report.status, 'PASS');
  397. assert.equal(report.platform, process.platform);
  398. assert.equal(report.node, process.version);
  399. assert.equal(report.profile, 'platform');
  400. assert.equal(report.gates.find(g => g.name === 'typecheck').status, 'SKIP');
  401. assert.match(report.gates.find(g => g.name === 'typecheck').reason, /full profile/);
  402. assert.equal(report.gates.find(g => g.name === 'build').status, 'PASS');
  403. assert.equal(report.gates.find(g => g.name === 'test:byok').status, 'PASS');
  404. assert.ok(report.gates.every(g => ['PASS', 'SKIP'].includes(g.status)));
  405. assert.ok(report.gates.filter(g => g.status === 'PASS').every(g => g.durationMs >= 0 && g.exitCode === 0));
  406. assert.equal(existsSync(path.dirname(readFileSync(f.exportRecord, 'utf8'))), false);
  407. assert.doesNotMatch(JSON.stringify(report), /FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED/);
  408. assert.doesNotMatch(readFileSync(f.summaryPath, 'utf8'), /FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED/);
  409. assert.equal(readFileSync(f.summaryPath, 'utf8'), readFileSync(path.join(f.reportDir, 'verification.md'), 'utf8'));
  410. });
  411. test('compiler failure fails full verification, preserves evidence, and stops dependent gates', t => {
  412. const f = verificationFixture(t);
  413. const result = f.run([], { VERIFY_FIXTURE_FAIL: 'typecheck' });
  414. assert.equal(result.status, 1, result.stderr);
  415. const report = f.report();
  416. assert.equal(report.status, 'FAIL');
  417. assert.equal(report.gates.find(g => g.name === 'typecheck').status, 'FAIL');
  418. assert.equal(report.gates.find(g => g.name === 'typecheck').exitCode, 17);
  419. assert.equal(report.gates.find(g => g.name === 'check:source').status, 'PASS');
  420. assert.equal(report.gates.find(g => g.name === 'build').status, 'NOT_RUN');
  421. assert.match(report.gates.find(g => g.name === 'build').reason, /stopped/);
  422. assert.equal(existsSync(path.dirname(readFileSync(f.exportRecord, 'utf8'))), false);
  423. assert.match(readFileSync(f.summaryPath, 'utf8'), /Verification: FAIL/);
  424. assert.doesNotMatch(JSON.stringify(report), /FIXTURE_OUTPUT_MUST_NOT_BE_UPLOADED/);
  425. });
  426. test('missing package manager produces failure metadata instead of a passing verification', t => {
  427. const f = verificationFixture(t);
  428. const result = f.run([], { npm_execpath: path.join(f.reportDir, 'missing-executable') });
  429. assert.equal(result.status, 1, result.stderr);
  430. const report = f.report();
  431. assert.equal(report.status, 'FAIL');
  432. assert.equal(report.gates[0].status, 'FAIL');
  433. assert.ok(report.gates[0].errorCode || report.gates[0].exitCode !== 0);
  434. assert.equal(report.gates.find(g => g.name === 'build').status, 'NOT_RUN');
  435. });
  436. test('documentation and archive profiles preserve their required validation gates', t => {
  437. const f = verificationFixture(t);
  438. const full = f.run(['--list']).stdout.trim().split('\n');
  439. const docs = f.run(['--profile', 'docs', '--list']);
  440. assert.equal(docs.status, 0, docs.stderr);
  441. assert.deepEqual(docs.stdout.trim().split('\n'), ['check:source', 'check:tsconfig', 'export source preview', 'test:release-tools']);
  442. const archive = f.run(['--profile', 'archive', '--list']);
  443. assert.equal(archive.status, 0, archive.stderr);
  444. assert.deepEqual(archive.stdout.trim().split('\n'), full.filter(g => g !== 'export source preview'));
  445. const packageProfile = f.run(['--profile', 'package', '--list']);
  446. if (['linux', 'darwin'].includes(process.platform)) {
  447. assert.equal(packageProfile.status, 0, packageProfile.stderr);
  448. assert.equal(packageProfile.stdout.trim(), 'test:release-package');
  449. } else assert.notEqual(packageProfile.status, 0);
  450. const failure = f.run(['--profile', 'docs'], { VERIFY_FIXTURE_FAIL: 'check:source' });
  451. assert.equal(failure.status, 1);
  452. assert.equal(f.report().status, 'FAIL');
  453. });
  454. test('change classification is conservative for mixed changes, metadata and missing diffs', () => {
  455. assert.deepEqual(classifyChanges(['README.md', 'docs/installation.md']), { docsOnly: true });
  456. 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']])
  457. assert.equal(classifyChanges(files).docsOnly, false);
  458. assert.deepEqual(classifyChanges(['.github/PULL_REQUEST_TEMPLATE.md', 'docs/source-sync.md']), { docsOnly: true });
  459. 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'])
  460. assert.equal(classifyChanges([file]).docsOnly, false, file);
  461. });
  462. test('CI aggregate rejects failed, cancelled, missing and unexpectedly skipped checks', { skip: process.platform === 'win32' }, () => {
  463. // This shell step only runs on the aggregate job's Ubuntu runner.
  464. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/ci.yml', import.meta.url), 'utf8'));
  465. const script = workflow.jobs.verification.steps[0].run;
  466. const full = { CLASSIFICATION: 'success', DOCS_ONLY: 'false', DOCS_RESULT: 'skipped', MATRIX_RESULT: 'success' };
  467. const docs = { CLASSIFICATION: 'success', DOCS_ONLY: 'true', DOCS_RESULT: 'success', MATRIX_RESULT: 'skipped' };
  468. const run = env => spawnSync('bash', ['-e', '-c', script], { env: { ...process.env, ...env }, encoding: 'utf8' }).status;
  469. assert.equal(run(full), 0);
  470. assert.equal(run(docs), 0);
  471. for (const result of ['failure', 'cancelled', 'skipped', '']) {
  472. assert.notEqual(run({ ...full, MATRIX_RESULT: result }), 0);
  473. assert.notEqual(run({ ...docs, DOCS_RESULT: result }), 0);
  474. assert.notEqual(run({ ...full, CLASSIFICATION: result }), 0);
  475. }
  476. assert.notEqual(run({ ...full, DOCS_ONLY: '' }), 0);
  477. for (const result of ['success', 'failure', 'cancelled', ''])
  478. assert.notEqual(run({ ...docs, MATRIX_RESULT: result }), 0);
  479. for (const result of ['success', 'failure', 'cancelled', ''])
  480. assert.notEqual(run({ ...full, DOCS_RESULT: result }), 0);
  481. for (const scope of ['', 'unknown', 'True'])
  482. assert.notEqual(run({ ...full, DOCS_ONLY: scope }), 0);
  483. });
  484. test('ordinary CI pauses Windows without invoking release-only matrices', () => {
  485. const readWorkflow = name => parseYaml(readFileSync(new URL(`../.github/workflows/${name}.yml`, import.meta.url), 'utf8'));
  486. const ci = readWorkflow('ci');
  487. assert.ok(Object.hasOwn(ci.on, 'pull_request'));
  488. assert.deepEqual(ci.on.push.branches, ['main']);
  489. assert.deepEqual(Object.keys(ci.jobs).sort(), ['changes', 'docs', 'verification', 'verify']);
  490. assert.deepEqual(ci.jobs.verify.strategy.matrix.os, ['ubuntu-latest', 'macos-latest']);
  491. assert.deepEqual(ci.jobs.verify.strategy.matrix.node, ['24']);
  492. assert.deepEqual(ci.jobs.verify.strategy.matrix.include, [{ os: 'ubuntu-latest', node: '24', profile: 'full' }]);
  493. assert.equal(ci.jobs.verify.needs, 'changes');
  494. assert.equal(ci.jobs.verify.if, "needs.changes.outputs.docs_only == 'false'");
  495. assert.equal(ci.jobs.docs.if, "needs.changes.outputs.docs_only == 'true'");
  496. assert.equal(ci.jobs.verification.if, '${{ always() }}');
  497. assert.deepEqual(ci.jobs.verification.needs, ['changes', 'docs', 'verify']);
  498. assert.ok(ci.jobs.verify.steps.some(step => step.run === "pnpm verify --profile ${{ matrix.profile || 'platform' }}"));
  499. const compatibility = readWorkflow('compatibility');
  500. assert.deepEqual(Object.keys(compatibility.on).sort(), ['schedule', 'workflow_dispatch']);
  501. assert.deepEqual(compatibility.jobs.compatibility.strategy.matrix.node, ['22.19.0', '24.2.0', '25', '26']);
  502. assert.deepEqual(compatibility.jobs.compatibility.strategy.matrix.os, ci.jobs.verify.strategy.matrix.os);
  503. const audit = readWorkflow('security');
  504. assert.ok(Object.hasOwn(audit.on, 'pull_request'));
  505. assert.ok(audit.jobs['source-history-artifact'].steps.some(step => step.run?.includes('gitleaks dir dist')));
  506. });
  507. test('manual source candidates pin every checkout and receipt to the selected revision', () => {
  508. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/source-candidate.yml', import.meta.url), 'utf8'));
  509. assert.deepEqual(Object.keys(workflow.on).sort(), ['workflow_call', 'workflow_dispatch']);
  510. assert.equal(workflow.on.workflow_call.inputs.revision.required, true);
  511. assert.equal(workflow.env.MCODE_CANDIDATE_REVISION, '${{ inputs.revision || github.sha }}');
  512. assert.equal(workflow.concurrency['cancel-in-progress'], false);
  513. assert.match(workflow.concurrency.group, /inputs\.revision \|\| github\.sha/);
  514. const revision = '${{ env.MCODE_CANDIDATE_REVISION }}';
  515. for (const job of Object.values(workflow.jobs)) {
  516. const checkout = job.steps.find(step => step.uses?.startsWith('actions/checkout@'));
  517. assert.equal(checkout.with.ref, revision);
  518. for (const step of job.steps.filter(step => step.run?.includes('scripts/source-candidate.mjs')))
  519. assert.equal(step.env.REVISION, revision);
  520. }
  521. const validate = workflow.jobs.validate;
  522. assert.deepEqual(validate.strategy.matrix.os, ['ubuntu-latest', 'macos-latest']);
  523. assert.ok(validate.steps.some(step => step.run?.includes('--store-dir "$RUNNER_TEMP/candidate-store" --registry https://registry.npmjs.org/')));
  524. const verify = validate.steps.find(step => step.run === 'pnpm verify --profile archive');
  525. assert.equal(verify.env.MCODE_VERIFY_REVISION, revision);
  526. assert.deepEqual(workflow.jobs.publish.needs, ['export', 'validate']);
  527. assert.ok(workflow.jobs.publish.steps.some(step => step.run?.includes('scripts/source-candidate.mjs finalize')));
  528. assert.equal(workflow.permissions.contents, 'read');
  529. });
  530. function archiveFixture(t, entries) {
  531. const directory = mkdtempSync(path.join(tmpdir(), 'archive-fixture-'));
  532. t.after(() => rmSync(directory, { recursive: true, force: true }));
  533. const blocks = [];
  534. for (const entry of entries) {
  535. const content = Buffer.from(entry.content ?? '');
  536. 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) });
  537. header.encode();
  538. blocks.push(header.block, content, Buffer.alloc((512 - content.length % 512) % 512));
  539. }
  540. const archive = path.join(directory, 'source.tar.gz');
  541. writeFileSync(archive, gzipSync(Buffer.concat([...blocks, Buffer.alloc(1024)])));
  542. return { directory, archive };
  543. }
  544. test('native and Node source extractors produce identical file content', async t => {
  545. const f = archiveFixture(t, [
  546. { path: 'minimax-code/README.md', content: 'Source preview\n' },
  547. { path: 'minimax-code/nested/file.txt', content: 'portable contents\n' },
  548. ]);
  549. for (const extractor of ['native', 'node']) {
  550. const output = path.join(f.directory, extractor);
  551. mkdirSync(output);
  552. assert.equal(await extractSourceArchive(f.archive, output, extractor), extractor);
  553. assert.equal(readFileSync(path.join(output, 'minimax-code/nested/file.txt'), 'utf8'), 'portable contents\n');
  554. }
  555. });
  556. test('Windows extraction ignores a shadow tar executable on PATH', { skip: process.platform !== 'win32' }, t => {
  557. const f = archiveFixture(t, [{ path: 'minimax-code/README.md', content: 'Windows archive\n' }]);
  558. const shadow = path.join(f.directory, 'shadow');
  559. const output = path.join(f.directory, 'output');
  560. mkdirSync(shadow);
  561. mkdirSync(output);
  562. // Node rejects tar flags. If extraction accidentally uses PATH, this fake
  563. // tar.exe makes the regression fail without needing Git Bash installed.
  564. copyFileSync(process.execPath, path.join(shadow, 'tar.exe'));
  565. const script = `import { extractSourceArchive } from ${JSON.stringify(new URL('../scripts/lib/source-archive.mjs', import.meta.url).href)};
  566. const result = await extractSourceArchive(${JSON.stringify(f.archive)}, ${JSON.stringify(output)}, 'native');
  567. if (result !== 'native') process.exit(1);`;
  568. const result = spawnSync(process.execPath, ['--input-type=module', '--eval', script], {
  569. encoding: 'utf8', env: { ...process.env, PATH: `${shadow}${path.delimiter}${process.env.PATH ?? ''}` },
  570. });
  571. assert.equal(result.status, 0, result.stderr);
  572. assert.equal(readFileSync(path.join(output, 'minimax-code/README.md'), 'utf8'), 'Windows archive\n');
  573. });
  574. test('source archive rejects traversal, links, Git history and duplicate entries before writing files', async t => {
  575. const good = { path: 'minimax-code/good.txt', content: 'safe' };
  576. for (const bad of [
  577. { path: 'minimax-code/../../outside.txt', content: 'unsafe' },
  578. { path: 'minimax-code/link', type: 'SymbolicLink', linkpath: '../../outside' },
  579. { path: 'minimax-code/link', type: 'Link', linkpath: '../../outside' },
  580. { path: 'minimax-code/.git/config', content: 'history' },
  581. { path: 'minimax-code/file:stream', content: 'stream' },
  582. good,
  583. ]) {
  584. const f = archiveFixture(t, [good, bad]);
  585. for (const extractor of ['native', 'node']) {
  586. const output = path.join(f.directory, extractor);
  587. mkdirSync(output);
  588. await assert.rejects(extractSourceArchive(f.archive, output, extractor), /unreviewed/);
  589. assert.deepEqual(readdirSync(output), []);
  590. }
  591. }
  592. });
  593. test('candidate rejects mismatched receipts and requires successful same-revision Linux and macOS reports', t => {
  594. const f = archiveFixture(t, [{ path: 'minimax-code/README.md', content: 'source' }]);
  595. const revision = 'a'.repeat(40);
  596. const receipt = { schemaVersion: 1, revision, sha256: createHash('sha256').update(readFileSync(f.archive)).digest('hex'), format: 'source-only-no-git-history', publicationPerformed: false };
  597. writeFileSync(`${f.archive}.json`, JSON.stringify(receipt));
  598. const script = fileURLToPath(new URL('../scripts/source-candidate.mjs', import.meta.url));
  599. const run = (...args) => spawnSync(process.execPath, [script, ...args, '--archive', f.archive, '--revision', revision], { encoding: 'utf8', timeout: 15000 });
  600. const destination = path.join(f.directory, 'unpacked');
  601. assert.equal(run('unpack', '--destination', destination).status, 0);
  602. assert.notEqual(run('unpack', '--destination', destination).status, 0);
  603. writeFileSync(`${f.archive}.json`, JSON.stringify({ ...receipt, sha256: '0'.repeat(64) }));
  604. assert.notEqual(run('unpack', '--destination', `${destination}-bad`).status, 0);
  605. assert.equal(existsSync(`${destination}-bad`), false);
  606. writeFileSync(`${f.archive}.json`, JSON.stringify(receipt));
  607. const reports = path.join(f.directory, 'reports');
  608. mkdirSync(reports);
  609. for (const platform of ['linux', 'darwin']) {
  610. const folder = path.join(reports, platform);
  611. mkdirSync(folder);
  612. writeFileSync(path.join(folder, 'verification.json'), JSON.stringify({ revision, platform, arch: 'fixture', node: 'v24', profile: 'archive', status: 'PASS', gates: [{ name: 'build', status: 'PASS' }] }));
  613. }
  614. assert.equal(run('finalize', '--reports', reports).status, 0);
  615. const manifest = JSON.parse(readFileSync(path.join(f.directory, 'candidate.json')));
  616. assert.equal(manifest.sha256, receipt.sha256);
  617. assert.deepEqual(manifest.validation.map(report => report.platform).sort(), ['darwin', 'linux']);
  618. const macos = path.join(reports, 'darwin/verification.json');
  619. const report = JSON.parse(readFileSync(macos));
  620. for (const change of [{ status: 'FAIL' }, { revision: 'b'.repeat(40) }, { gates: [{ name: 'build', status: 'NOT_RUN' }] }, { platform: 'linux' }, { platform: 'win32' }]) {
  621. writeFileSync(macos, JSON.stringify({ ...report, ...change }));
  622. assert.notEqual(run('finalize', '--reports', reports).status, 0);
  623. }
  624. rmSync(path.dirname(macos), { recursive: true });
  625. assert.notEqual(run('finalize', '--reports', reports).status, 0);
  626. });
  627. test('source inventory rejects unregistered, missing and duplicate first-party test gates', () => {
  628. const existing = 'packages/example/src/existing.test.ts';
  629. const omitted = 'packages/example/test/omitted.spec.tsx';
  630. const missing = 'packages/example/test/missing.test.ts';
  631. const files = [existing, omitted, 'third_party/vendor/vendor.test.ts', 'test/release.test.mjs'];
  632. assert.deepEqual(suiteInventoryViolations(files, { capability: [existing, existing, missing] }), [
  633. `${existing}: duplicate Vitest registration`,
  634. `${missing}: registered Vitest file is missing`,
  635. `${omitted}: first-party test is absent from test/vitest-suites.json`,
  636. ]);
  637. assert.deepEqual(suiteInventoryViolations(files, { capability: [existing, omitted] }), []);
  638. });
  639. test('suite runner preserves gate arguments and canonicalizes Windows temporary paths', t => {
  640. const root = mkdtempSync(path.join(tmpdir(), 'suite-runner-'));
  641. t.after(() => rmSync(root, { recursive: true, force: true }));
  642. for (const directory of ['scripts/lib', 'test', 'node_modules/vitest', 'temporary'])
  643. mkdirSync(path.join(root, directory), { recursive: true });
  644. for (const file of ['scripts/run-vitest-suite.mjs', 'scripts/lib/vitest-suites.mjs'])
  645. copyFileSync(new URL(`../${file}`, import.meta.url), path.join(root, file));
  646. writeFileSync(path.join(root, 'test/vitest-suites.json'), JSON.stringify({ suites: { fixture: ['test/example.test.ts'] } }));
  647. writeFileSync(path.join(root, 'node_modules/vitest/package.json'), JSON.stringify({ bin: { vitest: 'cli.cjs' } }));
  648. 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);');
  649. const alias = path.join(root, 'temporary-alias');
  650. symlinkSync(path.join(root, 'temporary'), alias, process.platform === 'win32' ? 'junction' : 'dir');
  651. for (const platform of ['linux', 'darwin', 'win32']) {
  652. const preload = path.join(root, 'platform.cjs');
  653. writeFileSync(preload, `Object.defineProperty(process, 'platform', { value: ${JSON.stringify(platform)} });`);
  654. const result = spawnSync(process.execPath, ['--require', preload, path.join(root, 'scripts/run-vitest-suite.mjs'), 'fixture'], {
  655. encoding: 'utf8', env: { ...process.env, TEMP: alias, TMP: alias, TMPDIR: alias },
  656. });
  657. assert.equal(result.status, 17, result.stderr);
  658. const child = JSON.parse(result.stdout);
  659. assert.deepEqual(child.args, ['run', '--config', 'vitest.oss.config.mjs',
  660. ...(platform === 'win32' ? ['--maxWorkers', '1'] : []), 'test/example.test.ts']);
  661. assert.equal(realpathSync(child.cwd), realpathSync(root));
  662. const expected = platform === 'win32' ? realpathSync.native(alias) : alias;
  663. assert.equal(child.temp, expected);
  664. assert.equal(child.tmp, expected);
  665. }
  666. });
  667. test('public support forms preserve destination URLs and separate Desktop from CLI reports', () => {
  668. const forms = ['01-bug-report.yml', '02-feature-request.yml', '03-question.yml', 'docs.yml'];
  669. for (const name of forms) {
  670. const form = parseYaml(readFileSync(new URL(`../.github/ISSUE_TEMPLATE/${name}`, import.meta.url), 'utf8'));
  671. const product = form.body.find(field => field.id === 'product');
  672. assert.equal(product.validations.required, name !== '03-question.yml');
  673. assert.equal(product.attributes.label, 'Product or interface');
  674. assert.ok(product.attributes.options.includes('CLI - interactive TUI'));
  675. assert.ok(product.attributes.options.includes('Desktop app'));
  676. assert.ok(product.attributes.options.includes('CLI - ACP'));
  677. assert.ok(product.attributes.options.includes('CLI - headless'));
  678. const ids = form.body.filter(field => field.id).map(field => field.id);
  679. assert.equal(new Set(ids).size, ids.length);
  680. }
  681. const bug = parseYaml(readFileSync(new URL('../.github/ISSUE_TEMPLATE/01-bug-report.yml', import.meta.url), 'utf8'));
  682. assert.notEqual(bug.body.find(field => field.id === 'upload-id').validations?.required, true);
  683. for (const retired of ['bug.yml', 'feature.yml'])
  684. assert.equal(existsSync(new URL(`../.github/ISSUE_TEMPLATE/${retired}`, import.meta.url)), false);
  685. assert.equal(classifyChanges(['README_ZH.md', 'README.md']).docsOnly, true);
  686. });
  687. test('issue product labels follow current form answers without replacing unrelated labels', async () => {
  688. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/label-issue-product.yml', import.meta.url), 'utf8'));
  689. assert.deepEqual(workflow.on, { issues: { types: ['opened', 'edited'] } });
  690. assert.deepEqual(workflow.permissions, { issues: 'write' });
  691. assert.equal(workflow.concurrency['cancel-in-progress'], false);
  692. const job = workflow.jobs['label-product'];
  693. assert.equal(job.if, "${{ github.repository == 'MiniMax-AI/minimax-code' && github.event.repository.private == false && !github.event.issue.pull_request }}");
  694. assert.equal(job.steps.length, 1); // No checkout or execution of issue-supplied code.
  695. const run = job.steps[0].run;
  696. assert.doesNotMatch(run, /\$\{\{/);
  697. const script = run.match(/^node <<'EOF'\r?\n([\s\S]*?)\r?\nEOF\s*$/)?.[1];
  698. assert.ok(script);
  699. async function replay(body, labels, failureStatus) {
  700. const writes = [];
  701. const issuePath = '/repos/MiniMax-AI/minimax-code/issues/7';
  702. await runInNewContext(script, {
  703. require: name => {
  704. assert.equal(name, 'node:fs');
  705. return { readFileSync: () => JSON.stringify({ issue: { number: 7, body: '### Product or interface\n\nDesktop app', labels: [] } }) };
  706. },
  707. process: { env: { GITHUB_EVENT_PATH: 'fixture.json', GITHUB_REPOSITORY: 'MiniMax-AI/minimax-code', GITHUB_API_URL: 'https://api.github.invalid', GH_TOKEN: 'synthetic' } },
  708. fetch: async (url, options) => {
  709. assert.equal(options.headers.Authorization, 'Bearer synthetic');
  710. if (options.method === 'GET') {
  711. assert.equal(url, `https://api.github.invalid${issuePath}`);
  712. return { ok: !failureStatus, status: failureStatus || 200, json: async () => ({ body, labels: labels.map(name => ({ name })) }) };
  713. }
  714. writes.push({ method: options.method, path: url.replace(`https://api.github.invalid${issuePath}`, ''), body: options.body && JSON.parse(options.body) });
  715. return { ok: true, status: 204 };
  716. },
  717. });
  718. return writes;
  719. }
  720. const answer = product => `### Product or interface\n\n${product}\n\n### Question\n\nSynthetic question`;
  721. const add = name => ({ method: 'POST', path: '/labels', body: { labels: [name] } });
  722. const remove = name => ({ method: 'DELETE', path: `/labels/${name}`, body: undefined });
  723. assert.deepEqual(await replay(answer('CLI - interactive TUI'), ['bug', 'desktop']), [add('tui'), remove('desktop')]);
  724. assert.deepEqual(await replay(answer('Desktop app').replace(/\n/g, '\r\n'), ['question']), [add('desktop')]);
  725. assert.deepEqual(await replay(answer('Desktop app'), ['desktop', 'bug']), []);
  726. for (const product of ['CLI - headless', 'CLI - ACP', 'Source build or repository tooling']) {
  727. assert.deepEqual(await replay(answer(product), ['tui', 'bug']), [remove('tui')]);
  728. }
  729. for (const body of [null, 'Desktop app', answer('_No response_'), answer('$(touch must-not-execute)')]) {
  730. assert.deepEqual(await replay(body, ['desktop', 'bug']), []);
  731. }
  732. await assert.rejects(replay(answer('Desktop app'), [], 403), /GitHub GET failed: 403/);
  733. });
  734. test('issue forms label incoming reports for triage and retain collaborator-only PR guidance', () => {
  735. for (const [name, type] of [
  736. ['01-bug-report.yml', 'bug'], ['02-feature-request.yml', 'enhancement'],
  737. ['03-question.yml', 'question'], ['docs.yml', 'documentation'],
  738. ]) {
  739. const form = parseYaml(readFileSync(new URL(`../.github/ISSUE_TEMPLATE/${name}`, import.meta.url), 'utf8'));
  740. assert.deepEqual(form.labels, [type, 'needs-triage']);
  741. }
  742. const config = parseYaml(readFileSync(new URL('../.github/ISSUE_TEMPLATE/config.yml', import.meta.url), 'utf8'));
  743. assert.equal(config.blank_issues_enabled, false);
  744. const policy = config.contact_links.find(link => link.url.endsWith('/CONTRIBUTING.md'));
  745. assert.match(policy.about, /only from repository collaborators/);
  746. assert.match(policy.about, /external PRs are not accepted/);
  747. const question = parseYaml(readFileSync(new URL('../.github/ISSUE_TEMPLATE/03-question.yml', import.meta.url), 'utf8'));
  748. assert.equal(question.body.find(field => field.id === 'platform').validations.required, false);
  749. assert.equal(question.body.find(field => field.id === 'question').validations.required, true);
  750. });
  751. test('issue notification is restricted to public destination events and builds payloads offline', t => {
  752. const workflow = parseYaml(readFileSync(new URL('../.github/workflows/sync-issue-to-feishu.yml', import.meta.url), 'utf8'));
  753. assert.deepEqual(workflow.on, { issues: { types: ['opened'] } });
  754. assert.deepEqual(workflow.permissions, { contents: 'read', issues: 'read' });
  755. const job = workflow.jobs['notify-feishu'];
  756. assert.equal(job.if, "${{ github.repository == 'MiniMax-AI/minimax-code' && github.event.repository.private == false && !github.event.issue.pull_request }}");
  757. const generate = job.steps.find(step => step.name === 'Build Feishu payload').run;
  758. // Execute only the payload builder, never the delivery step or its secrets.
  759. assert.doesNotMatch(generate, /\$\{\{\s*github\.event/);
  760. const script = generate.match(/^node <<'EOF'\r?\n([\s\S]*?)\r?\nEOF\s*$/)?.[1];
  761. assert.ok(script);
  762. const directory = mkdtempSync(path.join(tmpdir(), 'support-payload-'));
  763. t.after(() => rmSync(directory, { recursive: true, force: true }));
  764. const marker = path.join(directory, 'must-not-execute');
  765. const event = {
  766. repository: { full_name: 'MiniMax-AI/minimax-code', html_url: 'https://github.com/MiniMax-AI/minimax-code' },
  767. 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' } },
  768. };
  769. const eventPath = path.join(directory, 'event.json');
  770. writeFileSync(eventPath, JSON.stringify(event));
  771. const result = spawnSync(process.execPath, ['--input-type=commonjs'], {
  772. input: script, cwd: directory, encoding: 'utf8', timeout: 10000,
  773. env: { ...process.env, GITHUB_EVENT_PATH: eventPath, FEISHU_BOT_SECRET: '', FEISHU_BOT_WEBHOOK: '' },
  774. });
  775. assert.equal(result.status, 0, result.stderr);
  776. assert.equal(existsSync(marker), false);
  777. const payload = JSON.parse(readFileSync(path.join(directory, 'feishu-payload.json'), 'utf8'));
  778. assert.equal(payload.card.header.template, 'red');
  779. assert.equal(payload.card.card_link.url, event.issue.html_url);
  780. assert.equal(payload.card.header.title.content, 'GitHub Issue #7: Synthetic issue');
  781. assert.doesNotMatch(JSON.stringify(payload), /<at /);
  782. assert.match(JSON.stringify(payload), /‹at id=all›/);
  783. assert.equal(payload.sign, undefined);
  784. });
  785. test('source imports preserve vendored Office schema bytes through Git staging', t => {
  786. const directory = mkdtempSync(path.join(tmpdir(), 'source-import-bytes-'));
  787. t.after(() => rmSync(directory, { recursive: true, force: true }));
  788. const git = (...args) => execFileSync('git', ['-C', directory, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
  789. git('init');
  790. copyFileSync(new URL('../.gitattributes', import.meta.url), path.join(directory, '.gitattributes'));
  791. const schema = 'packages/local-runtime/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd';
  792. mkdirSync(path.dirname(path.join(directory, schema)), { recursive: true });
  793. const bytes = Buffer.from('<schema>\r\n <element name="fixture"/>\r\n</schema>\r\n');
  794. writeFileSync(path.join(directory, schema), bytes);
  795. for (const autocrlf of ['true', 'false']) {
  796. git('-c', `core.autocrlf=${autocrlf}`, 'add', '--', '.gitattributes', schema);
  797. assert.deepEqual(git('show', `:${schema}`), bytes);
  798. }
  799. });