architecture-harness 0.26.0 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/package.json +3 -2
  2. package/src/cli/ask.mjs +3 -1
  3. package/src/cli/ask.test.mjs +17 -1
  4. package/src/cli/bash-command-guard.mjs +37 -5
  5. package/src/cli/bash-command-guard.test.mjs +18 -0
  6. package/src/cli/check-full.test.mjs +4 -3
  7. package/src/cli/check.mjs +1 -1
  8. package/src/cli/ci-template.test.mjs +37 -2
  9. package/src/cli/cli.test.mjs +8 -0
  10. package/src/cli/codex-implement.mjs +5 -4
  11. package/src/cli/codex-implement.test.mjs +93 -0
  12. package/src/cli/commit-msg.mjs +4 -0
  13. package/src/cli/commit-msg.test.mjs +10 -0
  14. package/src/cli/fleet-assign.mjs +46 -0
  15. package/src/cli/fleet-assign.test.mjs +114 -0
  16. package/src/cli/fleet-github.mjs +124 -0
  17. package/src/cli/fleet-github.test.mjs +243 -0
  18. package/src/cli/fleet-message.mjs +50 -0
  19. package/src/cli/fleet-message.test.mjs +72 -0
  20. package/src/cli/fleet-node.mjs +555 -0
  21. package/src/cli/fleet-node.test.mjs +1284 -0
  22. package/src/cli/fleet-platform.mjs +200 -0
  23. package/src/cli/fleet-platform.test.mjs +316 -0
  24. package/src/cli/fleet-state.mjs +75 -0
  25. package/src/cli/fleet-state.test.mjs +114 -0
  26. package/src/cli/fleet-talk.mjs +143 -0
  27. package/src/cli/fleet-talk.test.mjs +178 -0
  28. package/src/cli/fleet.mjs +142 -13
  29. package/src/cli/fleet.test.mjs +314 -11
  30. package/src/cli/legs.mjs +3 -3
  31. package/src/cli/legs.test.mjs +24 -1
  32. package/src/cli/merge-guard.mjs +8 -6
  33. package/src/cli/merge-guard.test.mjs +38 -0
  34. package/src/cli/platform-risk.mjs +95 -1
  35. package/src/cli/platform-risk.test.mjs +185 -0
  36. package/src/cli/qc.mjs +6 -0
  37. package/src/cli/repl-commands.mjs +168 -0
  38. package/src/cli/repl-commands.test.mjs +133 -0
  39. package/src/cli/role-line.mjs +49 -0
  40. package/src/cli/role-line.test.mjs +55 -0
  41. package/src/cli/watch.mjs +35 -2
  42. package/src/cli/watch.test.mjs +106 -0
  43. package/src/cli/workflow-hooks.test.mjs +13 -4
  44. package/src/config.mjs +2 -2
package/src/cli/legs.mjs CHANGED
@@ -23,8 +23,8 @@ export function legRecords(root) {
23
23
 
24
24
  export function appendLeg(root, record) {
25
25
  if (record.type !== undefined && !["leg", "leg-preview"].includes(record.type)) throw new Error("invalid platform leg type");
26
- if (!["linux", "windows"].includes(record.os)) throw new Error("unknown platform for leg");
27
- if (!record.head || !["local", "preview"].includes(record.source)) throw new Error("invalid platform leg");
26
+ if (!["linux", "windows", "darwin"].includes(record.os)) throw new Error("unknown platform for leg");
27
+ if (!record.head || !["local", "preview", "fleet"].includes(record.source)) throw new Error("invalid platform leg");
28
28
  const file = ledgerFileOf(root);
29
29
  if (!file) throw new Error("platform legs need a git worktree");
30
30
  mkdirSync(path.dirname(file), { recursive: true });
@@ -35,7 +35,7 @@ export function appendLeg(root, record) {
35
35
  export function readyProblems(root, head) {
36
36
  const config = load(root);
37
37
  const hits = platformRisk(root, config.check.base, head);
38
- const passed = new Set(legRecords(root).filter((record) => record.type === "leg" && record.head === head && ["linux", "windows"].includes(record.os) && ["local", "preview"].includes(record.source)).map((record) => record.os));
38
+ const passed = new Set(legRecords(root).filter((record) => record.type === "leg" && record.head === head && ["linux", "windows", "darwin"].includes(record.os) && ["local", "preview", "fleet"].includes(record.source)).map((record) => record.os));
39
39
  const missing = hits.length > 0 || passed.size === 0 ? config.ready.platforms.filter((os) => !passed.has(os)) : [];
40
40
  return { missing, hits };
41
41
  }
@@ -66,5 +66,28 @@ test('leg records share the common ledger and tolerate torn lines', (t) => {
66
66
  assert.equal(legRecords(root).length, 1);
67
67
  assert.throws(() => appendLeg(root, { os: 'linux', head: 'x', source: 'affected' }), /invalid platform leg/);
68
68
  assert.throws(() => appendLeg(root, { os: 'linux', head: 'x', source: 'local', type: 'affected' }), /invalid platform leg type/);
69
- assert.throws(() => appendLeg(root, { os: 'darwin', head: 'x', source: 'local' }), /platform/);
69
+ assert.throws(() => appendLeg(root, { os: 'freebsd', head: 'x', source: 'local' }), /platform/);
70
+ });
71
+
72
+
73
+ test('fleet Windows and macOS legs satisfy configured risky-head readiness', t => {
74
+ const { root, git } = legFixture(t);
75
+ writeFileSync(path.join(root, 'qc.config.json'), JSON.stringify({ check: { base: 'base' }, ready: { platforms: ['windows', 'darwin'] } }));
76
+ writeFileSync(path.join(root, 'a.mjs'), 'process.platform;\n');
77
+ git('add', '.'); git('commit', '-qm', 'risk');
78
+ const head = git('rev-parse', 'HEAD');
79
+ appendLeg(root, { os: 'windows', head, source: 'fleet' });
80
+ assert.deepEqual(readyProblems(root, head).missing, ['darwin']);
81
+ appendLeg(root, { os: 'darwin', head, source: 'fleet' });
82
+ assert.deepEqual(readyProblems(root, head).missing, []);
83
+ });
84
+
85
+ test('affected checks on macOS record the native passing leg', async t => {
86
+ const { root, git } = legFixture(t);
87
+ git('add', '.'); git('commit', '-qm', 'config');
88
+ const output = [];
89
+ const code = await runAffectedCheck({ root }, {}, { platform: 'darwin', gates: async () => ({ problems: [], lines: [] }),
90
+ commands: async () => 0, write: line => output.push(line) });
91
+ assert.equal(code, 0, output.join('\n'));
92
+ assert.equal(legRecords(root).at(-1).os, 'darwin');
70
93
  });
@@ -11,7 +11,7 @@
11
11
  import { commentWatch } from "./comment-watch.mjs";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { defaults, PROMOTION_SCOPE } from "../config.mjs";
14
- import { PARSERS } from "./bash-command-guard.mjs";
14
+ import { guardCommands } from "./bash-command-guard.mjs";
15
15
  import { checkoutRootOf } from "./checkout-root.mjs";
16
16
  import { configAtBase, gitBy, LANE_BUDGET_MS, mergeLane, sizeLine } from "./direct-lane.mjs";
17
17
  import { ghApiMerges, ghMerges } from "./gh-merge-command.mjs";
@@ -302,14 +302,16 @@ function recordMerge(merge, call, workflow, gh, deadline) {
302
302
  return null;
303
303
  }
304
304
 
305
- /** The verdict on one Bash or PowerShell event. @returns the hook output, or null to let it pass with no message. */
305
+ /** The verdict on one Bash, PowerShell or REPL event. @returns the hook output, or null to let it pass with no message. */
306
306
  export function decide(call, { gh = runGh, commentCheck = commentWatch } = {}) {
307
+ return guardCommands(call, (command, parse) => decideCommand(call, command, parse, { gh, commentCheck }));
308
+ }
309
+
310
+ function decideCommand(call, command, parse, { gh, commentCheck }) {
307
311
  const deadline = Date.now() + LANE_BUDGET_MS;
308
312
  const event = call.hook_event_name;
309
313
  if (event !== "PreToolUse" && !POST_EVENTS.has(event)) return null;
310
- const parse = PARSERS[call.tool_name];
311
- const command = call.tool_input?.command;
312
- if (!parse || typeof command !== "string" || !MAYBE_GH.test(command)) return null;
314
+ if (!MAYBE_GH.test(command)) return null;
313
315
  const cwd = call.cwd ?? process.cwd();
314
316
  const root = checkoutRootOf(cwd);
315
317
  if (!root) return null;
@@ -317,7 +319,7 @@ export function decide(call, { gh = runGh, commentCheck = commentWatch } = {}) {
317
319
  const apiMerges = event === "PreToolUse" ? ghApiMerges(command, parse, { cwd }) : [];
318
320
  const targets = [...merges, ...apiMerges.map(apiPrOf).filter(Boolean)];
319
321
  const checked = event === "PreToolUse" && targets.length ? commentCheck(call, { gh: gh === runGh ? runGhAsync : gh, merges: targets }) : null;
320
- if (checked instanceof Promise) return checked.then(result => decide(call, { gh, commentCheck: () => result }));
322
+ if (checked instanceof Promise) return checked.then(result => decideCommand(call, command, parse, { gh, commentCheck: () => result }));
321
323
  const commentResult = checked;
322
324
  if (commentResult?.hookSpecificOutput?.permissionDecision === "deny") return commentResult;
323
325
  if (event === "PreToolUse" && (merges.length > 0 || apiMerges.length > 0)) {
@@ -1243,3 +1243,41 @@ test("a milestone validates approved member trees, migrations and aggregate poli
1243
1243
  }
1244
1244
  assert.deepEqual(failures, []);
1245
1245
  });
1246
+
1247
+ test("REPL literal commands require the same merge approval and identify the first denial", (t) => {
1248
+ const ws = workspace(t);
1249
+ const cwd = ws.on;
1250
+ const repl = (code) => ({ ...shell(cwd, ""), tool_name: "REPL", tool_input: { code } });
1251
+ const command = `gh pr merge 60 --match-head-commit ${SHA}`;
1252
+ for (const code of [`$\`${command}\``, `$("${command}")`, `tools.Bash({ command: "${command}" })`]) {
1253
+ const reason = denied(decide(repl(code)));
1254
+ assert.match(reason ?? "", /no APPROVED branch review/, code);
1255
+ assert.ok(reason.includes(command), reason);
1256
+ }
1257
+ const reason = denied(decide(repl('$`git status`; $`gh pr merge 60`; $`gh pr merge 61`')));
1258
+ assert.match(reason ?? "", /gh pr merge 60/);
1259
+ assert.doesNotMatch(reason, /gh pr merge 61/);
1260
+ assert.match(denied(decide(repl('$`gh pr merge 60`; $`broken'))) ?? "", /gh pr merge 60/);
1261
+ for (const code of ['const answer = 42;', '$`git status`; $("gh pr view 60")']) {
1262
+ assert.equal(decide(repl(code)), null, code);
1263
+ }
1264
+ assert.equal(decide({ ...repl(''), tool_input: { command: "gh pr merge 60" } }), null);
1265
+ appendRecord(ws.ledgerOf(cwd), verdict("branch", "APPROVED"));
1266
+ assert.equal(decide(repl(`$\`${command}\``)), null);
1267
+ });
1268
+
1269
+ test("REPL merge checks await comments in command order and keep the first denial", async (t) => {
1270
+ const ws = workspace(t);
1271
+ const cwd = ws.on;
1272
+ const seen = [];
1273
+ appendRecord(ws.ledgerOf(cwd), verdict("branch", "APPROVED"));
1274
+ const call = { ...shell(cwd, ""), tool_name: "REPL", tool_input: {
1275
+ code: `$\`gh pr merge 60 --match-head-commit ${SHA}\`; $\`gh pr merge 61\`; $\`gh pr merge 62\``,
1276
+ } };
1277
+ const output = await decide(call, { commentCheck: async (_call, { merges }) => {
1278
+ seen.push(merges[0].selector);
1279
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: "comments checked" } };
1280
+ } });
1281
+ assert.deepEqual(seen, ["60", "61"]);
1282
+ assert.match(denied(output) ?? "", /gh pr merge 61/);
1283
+ });
@@ -1,5 +1,6 @@
1
1
  // A branch scans added lines and file metadata for platform risks.
2
2
  import { execFileSync } from "node:child_process";
3
+ import { appendFileSync } from "node:fs";
3
4
 
4
5
  const CODE_FILE = /\.(?:[cm]?[jt]sx?|sh|bash|zsh|ps1|psm1|bat|cmd|py|go|rs|java|cs|[ch]|[ch]pp|rb|php|swift|kt|kts|scala|sql|tf|hcl|lua|ex|exs|vue|svelte|css|scss)$|(?:^|\/)(?:Dockerfile|Makefile)$/i;
5
6
 
@@ -11,6 +12,75 @@ const patterns = [
11
12
  ["process.platform", /\bprocess\s*\.\s*platform\b/],
12
13
  ];
13
14
 
15
+ // Keep literal offsets stable while masking exemptions and walking template expressions.
16
+ function scanLine(source) {
17
+ const paths = source.split("");
18
+ let optedOut = false;
19
+ let expressionSlashes = 0;
20
+ const mask = (start, end) => { paths.fill(" ", start, end); };
21
+ const exempt = (start, end) => {
22
+ const before = source.slice(0, start);
23
+ const after = source.slice(end);
24
+ const url = /^(?:https?:\/\/|node:)/.test(source.slice(start + 1));
25
+ const withoutComments = before.replace(/\/\*.*?\*\/|\/\/.*$/g, " ");
26
+ const requireCall = /\brequire\s*\(\s*$/.exec(withoutComments);
27
+ const bareRequire = requireCall && !/[\w$.?]\s*$/.test(withoutComments.slice(0, requireCall.index));
28
+ const specifier = /\b(?:import|export)\s+[^;"'`]*\bfrom\s*$|\bimport\s*$|\bimport\s*\(\s*$/.test(before) || bareRequire;
29
+ const relativeUrl = /\bnew\s+URL\s*\(\s*$/.test(before) && /^\s*,\s*import\s*\.\s*meta\s*\.\s*url\s*\)/.test(after);
30
+ return url || specifier || relativeUrl;
31
+ };
32
+ const walk = (start, inTemplate = false) => {
33
+ let braces = 0;
34
+ let i = start;
35
+ while (i < source.length) {
36
+ const char = source[i];
37
+ // A slash can start a regex with braces; do not guess its expression boundary.
38
+ if (inTemplate && char === "/") expressionSlashes += 1;
39
+ if (source.startsWith("//", i)) {
40
+ if (!inTemplate && !/`|\$\{|\}/.test(source.slice(0, i)) && /^\/\/ qc-platform-ok\s*$/.test(source.slice(i))) optedOut = true;
41
+ return source.length;
42
+ }
43
+ if (source.startsWith("/*", i)) {
44
+ const end = source.indexOf("*/", i + 2);
45
+ i = end < 0 ? source.length : end + 2;
46
+ } else if (char === '"' || char === "'") {
47
+ const begin = i++;
48
+ while (i < source.length && source[i] !== char) i += source[i] === "\\" ? 2 : 1;
49
+ if (i < source.length) {
50
+ i += 1;
51
+ if (exempt(begin, i)) mask(begin, i);
52
+ }
53
+ } else if (char === "`") {
54
+ const begin = i++;
55
+ const slashesBefore = expressionSlashes;
56
+ const raw = [];
57
+ let segment = begin;
58
+ while (i < source.length) {
59
+ if (source[i] === "\\") i += 2;
60
+ else if (source.startsWith("${", i)) {
61
+ raw.push([segment, i + 2]);
62
+ i = walk(i + 2, true);
63
+ segment = i;
64
+ if (source[i] === "}") i += 1;
65
+ } else if (source[i] === "`") {
66
+ raw.push([segment, ++i]);
67
+ if (expressionSlashes === slashesBefore && exempt(begin, i)) for (const [from, to] of raw) mask(from, to);
68
+ break;
69
+ } else i += 1;
70
+ }
71
+ } else if (char === "}" && inTemplate && braces === 0) return i;
72
+ else {
73
+ if (char === "{") braces += 1;
74
+ if (char === "}") braces -= 1;
75
+ i += 1;
76
+ }
77
+ }
78
+ return i;
79
+ };
80
+ walk(0);
81
+ return { paths: paths.join(""), optedOut };
82
+ }
83
+
14
84
  export function riskHits(diff) {
15
85
  const hits = [];
16
86
  let file = "";
@@ -31,7 +101,13 @@ export function riskHits(diff) {
31
101
  } else if (/^(?:new file mode|old mode|new mode) 120000$/.test(text)) add("symlink");
32
102
  else if (text.startsWith("@@")) line = Number(/\+(\d+)/.exec(text)?.[1] ?? 1);
33
103
  else if (text.startsWith("+") && !text.startsWith("+++")) {
34
- if (CODE_FILE.test(file)) for (const [reason, pattern] of patterns) if (pattern.test(text.slice(1))) add(reason);
104
+ const source = text.slice(1);
105
+ if (CODE_FILE.test(file)) {
106
+ const { paths, optedOut } = scanLine(source);
107
+ if (!optedOut) for (const [reason, pattern] of patterns) {
108
+ if (pattern.test(reason === "hard-coded path separator" ? paths : source)) add(reason);
109
+ }
110
+ }
35
111
  line += 1;
36
112
  } else if (text.startsWith(" ")) line += 1;
37
113
  }
@@ -44,3 +120,21 @@ export function platformRisk(root, base = "origin/main", head = "HEAD") {
44
120
  });
45
121
  return riskHits(diff);
46
122
  }
123
+
124
+ export function runPlatformRisk(root, args = []) {
125
+ if (!(args.length === 0 || (args.length === 2 && args[0] === "--base" && args[1] && !args[1].startsWith("-")))) {
126
+ console.error("usage: qc platform-risk [--base <ref>]");
127
+ return 1;
128
+ }
129
+ try {
130
+ const hits = platformRisk(root, args[1]);
131
+ const result = `risky=${hits.length > 0}\n`;
132
+ if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, result);
133
+ for (const { file, line, reason } of hits.slice(0, 10)) console.log(`${file}:${line} ${reason}`);
134
+ process.stdout.write(result);
135
+ return 0;
136
+ } catch (error) {
137
+ console.error(`qc platform-risk: ${String(error.message).replace(/\s+/g, " ")}`);
138
+ return 1;
139
+ }
140
+ }
@@ -1,7 +1,109 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
3
8
  import { riskHits } from "./platform-risk.mjs";
4
9
 
10
+ const cli = fileURLToPath(new URL("./qc.mjs", import.meta.url));
11
+
12
+ test('comments before require members keep path risk', () => {
13
+ for (const source of ['x./* member */require("C:/deps.txt");', 'x?. /* member */ require("C:/deps.txt");']) {
14
+ assert.deepEqual(riskHits(`+++ b/a.js\n+${source}\n`), [
15
+ { file: 'a.js', line: 1, reason: 'hard-coded path separator' },
16
+ ], source);
17
+ }
18
+ });
19
+
20
+ test('template specifiers with a slash in an expression keep path risk', () => {
21
+ const source = 'import(`./${/}/.test(name) ? readFileSync("C:/deps.txt") : "dep"}`);';
22
+ assert.deepEqual(riskHits(`+++ b/a.js\n+${source}\n`), [
23
+ { file: 'a.js', line: 1, reason: 'hard-coded path separator' },
24
+ ]);
25
+ });
26
+
27
+ test('opt-out on a multiline template expression keeps path risk', () => {
28
+ assert.deepEqual(riskHits('+++ b/a.js\n+const value = `\n+${readFileSync("C:/deps.txt")} // qc-platform-ok\n+`;\n'), [
29
+ { file: 'a.js', line: 2, reason: 'hard-coded path separator' },
30
+ ]);
31
+ });
32
+
33
+ test('opt-out text inside strings and templates keeps platform risk', () => {
34
+ for (const source of [
35
+ 'const value = "EPERM // qc-platform-ok',
36
+ "const value = 'EPERM // qc-platform-ok",
37
+ 'const value = `EPERM // qc-platform-ok',
38
+ 'const value = `EPERM ${value // qc-platform-ok',
39
+ ]) {
40
+ assert.ok(riskHits(`+++ b/a.js\n+${source}\n`).length > 0, source);
41
+ }
42
+ });
43
+
44
+ test('exempt template specifiers preserve paths in expressions', () => {
45
+ const source = 'import(`./${readFileSync("C:/deps.txt")}`);';
46
+ assert.deepEqual(riskHits(`+++ b/a.js\n+${source}\n`), [
47
+ { file: 'a.js', line: 1, reason: 'hard-coded path separator' },
48
+ ]);
49
+ });
50
+
51
+ test('require property calls keep path risk', () => {
52
+ for (const source of ['x.require("a/b");', 'x?.require("a/b");']) {
53
+ assert.deepEqual(riskHits(`+++ b/a.js\n+${source}\n`), [
54
+ { file: 'a.js', line: 1, reason: 'hard-coded path separator' },
55
+ ], source);
56
+ }
57
+ });
58
+
59
+ for (const source of [
60
+ 'import value from "pkg/value";',
61
+ 'export { value } from "./value.js";',
62
+ 'import "./setup.js";',
63
+ 'import("./lazy.js");',
64
+ 'require("pkg/value");',
65
+ 'new URL("./asset.svg", import.meta.url);',
66
+ 'const url = "http://example.com/file";',
67
+ 'const url = "https://example.com/file";',
68
+ 'const builtin = "node:fs/promises";',
69
+ ]) {
70
+ test(`ignores specifier or URL: ${source}`, () => {
71
+ assert.deepEqual(riskHits(`+++ b/a.js\n@@ -0,0 +1 @@\n+${source}\n`), []);
72
+ });
73
+ }
74
+
75
+ for (const source of ['"a/b"', String.raw`'C:\\x'`, 'listen(3000)', String.raw`"\r\n"`, 'EPERM', 'process.platform']) {
76
+ test(`trailing opt-out suppresses every reason: ${source}`, () => {
77
+ assert.deepEqual(riskHits(`+++ b/a.js\n@@ -0,0 +1 @@\n+${source}; // qc-platform-ok\n`), []);
78
+ });
79
+ }
80
+
81
+ for (const source of ['"a/b"', String.raw`'C:\\x'`]) {
82
+ test(`still flags a plain path: ${source}`, () => {
83
+ assert.deepEqual(riskHits(`+++ b/a.js\n@@ -0,0 +1 @@\n+${source}\n`), [
84
+ { file: 'a.js', line: 1, reason: 'hard-coded path separator' },
85
+ ]);
86
+ });
87
+ }
88
+
89
+ test('specifier exemptions preserve other strings and risk reasons', () => {
90
+ for (const source of [
91
+ 'import value from "pkg/value"; const fixture = "a/b";',
92
+ 'require("pkg/value"); const fixture = "a/b";',
93
+ 'new URL("./asset.svg", otherBase);',
94
+ 'const fixture = "a/b"; // qc-platform-ok followed by more text',
95
+ ]) {
96
+ assert.deepEqual(riskHits(`+++ b/a.js\n+${source}\n`).map(({ reason }) => reason), ['hard-coded path separator']);
97
+ }
98
+ assert.deepEqual(riskHits('+++ b/a.js\n+const url = "http://localhost:3000/file";\n').map(({ reason }) => reason), ['fixed port']);
99
+ });
100
+
101
+ test('opt-out preserves line numbers and accepts trailing whitespace and CRLF', () => {
102
+ assert.deepEqual(riskHits('+++ b/a.js\n@@ -0,0 +7 @@\n+"a/b"; // qc-platform-ok \r\n+EPERM\n'), [
103
+ { file: 'a.js', line: 8, reason: 'EPERM' },
104
+ ]);
105
+ });
106
+
5
107
  for (const source of ['listen(3000)', 'listen(7)', 'const port = 8080', '"foo/bar"', '"foo\\\\bar"', '"/tmp"', 'split("/")', '"\\r\\n"', 'EPERM', 'process.platform']) {
6
108
  test(`flags added platform risk: ${source}`, () => {
7
109
  assert.equal(riskHits(`diff --git a/a.js b/a.js\n+++ b/a.js\n@@ -1 +7 @@\n+${source}\n`)[0].file, 'a.js');
@@ -36,3 +138,86 @@ test('scans code files after a prose file', () => {
36
138
  assert.deepEqual(hits, [{ file: `code.${extension}`, line: 3, reason: 'EPERM' }]);
37
139
  }
38
140
  });
141
+
142
+
143
+ function commandRepo(t, source = 'const value = 1;\n') {
144
+ const root = mkdtempSync(path.join(tmpdir(), 'qc-platform-risk-'));
145
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
146
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
147
+ git('init', '-q');
148
+ git('config', 'user.name', 'Test');
149
+ git('config', 'user.email', process.env.GIT_AUTHOR_EMAIL || 'test@example.com');
150
+ git('commit', '--allow-empty', '-qm', 'base');
151
+ git('update-ref', 'refs/remotes/origin/main', 'HEAD');
152
+ writeFileSync(path.join(root, 'code.mjs'), source);
153
+ git('add', '.');
154
+ git('commit', '-qm', 'change');
155
+ const run = (args = [], env = {}) => spawnSync(process.execPath, [cli, 'platform-risk', ...args], {
156
+ cwd: root, encoding: 'utf8', env: { ...process.env, GITHUB_OUTPUT: '', ...env },
157
+ });
158
+ return { root, run };
159
+ }
160
+
161
+ test('platform-risk command reports no hits using origin/main by default', (t) => {
162
+ const { run } = commandRepo(t);
163
+ const result = run();
164
+ assert.equal(result.status, 0, result.stderr);
165
+ assert.equal(result.stdout, 'risky=false\n');
166
+ });
167
+
168
+ test('platform-risk command reports changed line hits with an explicit base', (t) => {
169
+ const { run } = commandRepo(t, 'const value = 1;\nprocess.platform;\n');
170
+ const result = run(['--base', 'HEAD^']);
171
+ assert.equal(result.status, 0, result.stderr);
172
+ assert.equal(result.stdout, 'code.mjs:2 process.platform\nrisky=true\n');
173
+ });
174
+
175
+ test('platform-risk command prints at most ten hits', (t) => {
176
+ const { run } = commandRepo(t, 'process.platform;\n'.repeat(12));
177
+ const result = run();
178
+ assert.equal(result.status, 0, result.stderr);
179
+ assert.deepEqual(result.stdout.trim().split('\n'), [
180
+ ...Array.from({ length: 10 }, (_, i) => `code.mjs:${i + 1} process.platform`), 'risky=true',
181
+ ]);
182
+ });
183
+
184
+ test('platform-risk command appends its boolean to GITHUB_OUTPUT', (t) => {
185
+ for (const risky of [false, true]) {
186
+ const { root, run } = commandRepo(t, risky ? 'process.platform;\n' : 'const value = 1;\n');
187
+ const output = path.join(root, 'output');
188
+ writeFileSync(output, 'existing=value\n');
189
+ const result = run([], { GITHUB_OUTPUT: output });
190
+ assert.equal(result.status, 0, result.stderr);
191
+ assert.equal(readFileSync(output, 'utf8'), `existing=value\nrisky=${risky}\n`);
192
+ }
193
+ });
194
+
195
+ test('platform-risk command fails on a bad base without publishing a safe result', (t) => {
196
+ const { root, run } = commandRepo(t);
197
+ const output = path.join(root, 'output');
198
+ writeFileSync(output, 'existing=value\n');
199
+ const result = run(['--base', 'missing-base'], { GITHUB_OUTPUT: output });
200
+ assert.equal(result.status, 1);
201
+ assert.match(result.stderr, /missing-base/);
202
+ assert.doesNotMatch(result.stdout, /risky=/);
203
+ assert.equal(readFileSync(output, 'utf8'), 'existing=value\n');
204
+ });
205
+
206
+
207
+ test('platform-risk command rejects malformed arguments', (t) => {
208
+ const { run } = commandRepo(t);
209
+ for (const args of [['--base'], ['--base', '--unknown'], ['--unknown'], ['extra'], ['--base', 'HEAD', 'extra']]) {
210
+ const result = run(args);
211
+ assert.equal(result.status, 1);
212
+ assert.match(result.stderr, /usage:/);
213
+ assert.doesNotMatch(result.stdout, /risky=/);
214
+ }
215
+ });
216
+
217
+ test('platform-risk command fails when GITHUB_OUTPUT cannot be written', (t) => {
218
+ const { root, run } = commandRepo(t);
219
+ const result = run([], { GITHUB_OUTPUT: root });
220
+ assert.equal(result.status, 1);
221
+ assert.match(result.stderr, /EISDIR|EPERM|EACCES/);
222
+ assert.doesNotMatch(result.stdout, /risky=/);
223
+ });
package/src/cli/qc.mjs CHANGED
@@ -18,6 +18,7 @@ const USAGE = `qc — architecture gates
18
18
  qc ci-preview [--os <linux|windows|both>]
19
19
  dispatch CI for this head and record passing platform legs
20
20
  qc ready-check print missing platform legs and up to three risk hits; silent on a pass
21
+ qc platform-risk [--base <ref>] print up to ten changed-line platform risks and risky=true|false
21
22
  qc e2e the repository's e2e command with the changed files
22
23
  qc lint [--staged] [--base <ref>] [file...]
23
24
  ESLint on the changed lines only: a problem on an untouched line never fails
@@ -100,6 +101,11 @@ Every gate reads qc.config.json. A key it does not set keeps the reference defau
100
101
 
101
102
  async function main() {
102
103
  const [command, ...rest] = process.argv.slice(2);
104
+ if (command === "platform-risk") {
105
+ const { runPlatformRisk } = await import("./platform-risk.mjs");
106
+ process.exitCode = runPlatformRisk(process.cwd(), rest);
107
+ return;
108
+ }
103
109
  if (command === "overview" || command === "debt") {
104
110
  const valid = command === "overview" ? rest.length === 0 :
105
111
  (rest[0] === "file" && rest.length === 2) || (rest[0] === "due" && rest.length === 1);
@@ -0,0 +1,168 @@
1
+ // Read only the literal shell forms used by REPL. This scans text, including comments and strings;
2
+ // it never evaluates JavaScript. A malformed recognized form discards only that form.
3
+ const FORMS = /(?<![\w$.])\$\s*(?=`|\()|(?<![\w$.])tools\s*\.\s*Bash\s*\(\s*(?=\{)/g;
4
+ const SPACE = /\s/;
5
+ const LINE_END = /[\r\n\u2028\u2029]/;
6
+ const EXPRESSION_KEYWORD = /^(?:return|throw|case|delete|void|typeof|new|in|instanceof|yield|await|else|do)$/;
7
+ const ESCAPES = { n: "\n", r: "\r", t: "\t", b: "\b", f: "\f", v: "\v", "0": "\0" };
8
+ const invalid = () => { throw new SyntaxError("Incomplete REPL command literal"); };
9
+ const whitespace = (code, at) => { while (SPACE.test(code[at] ?? "") && at < code.length) at++; return at; };
10
+
11
+ function trivia(code, at) {
12
+ for (;;) {
13
+ at = whitespace(code, at);
14
+ if (code.startsWith("/*", at)) {
15
+ const end = code.indexOf("*/", at + 2);
16
+ if (end < 0) return invalid();
17
+ at = end + 2;
18
+ } else if (code.startsWith("//", at)) {
19
+ at += 2;
20
+ while (at < code.length && !LINE_END.test(code[at])) at++;
21
+ } else return at;
22
+ }
23
+ }
24
+
25
+ function escapeAt(code, at) {
26
+ const char = code[at + 1];
27
+ if (char === undefined) return invalid();
28
+ if (char === "\n") return ["", at + 2];
29
+ if (char === "\r") return ["", at + (code[at + 2] === "\n" ? 3 : 2)];
30
+ if (char === "x" || char === "u") {
31
+ const braced = char === "u" && code[at + 2] === "{";
32
+ const start = at + (braced ? 3 : 2);
33
+ const end = braced ? code.indexOf("}", start) : start + (char === "x" ? 2 : 4);
34
+ const digits = code.slice(start, end);
35
+ if (end < start || !/^[\da-f]+$/i.test(digits) || (!braced && digits.length !== end - start)) return invalid();
36
+ const value = Number.parseInt(digits, 16);
37
+ if (value > 0x10ffff) return invalid();
38
+ return [String.fromCodePoint(value), end + (braced ? 1 : 0)];
39
+ }
40
+ return [ESCAPES[char] ?? char, at + 2];
41
+ }
42
+
43
+ function literalAt(code, at) {
44
+ const quote = code[at++];
45
+ let value = "";
46
+ while (at < code.length) {
47
+ const char = code[at];
48
+ if (char === quote) return [value, at + 1];
49
+ if (char === "\\") {
50
+ const escaped = escapeAt(code, at);
51
+ value += escaped[0];
52
+ at = escaped[1];
53
+ } else if (quote === "`" && code.startsWith("${", at)) {
54
+ at = groupEnd(code, at + 1);
55
+ value += "QC_VALUE";
56
+ } else {
57
+ if (quote !== "`" && /[\r\n]/.test(char)) return invalid();
58
+ value += char;
59
+ at++;
60
+ }
61
+ }
62
+ return invalid();
63
+ }
64
+
65
+ function regexEnd(code, at) {
66
+ at++;
67
+ let inClass = false;
68
+ while (at < code.length) {
69
+ const char = code[at];
70
+ if (LINE_END.test(char)) return invalid();
71
+ if (char === "\\") {
72
+ if (at + 1 >= code.length || LINE_END.test(code[at + 1])) return invalid();
73
+ at += 2;
74
+ continue;
75
+ }
76
+ if (char === "/" && !inClass) {
77
+ at++;
78
+ while (/[a-z]/i.test(code[at] ?? "")) at++;
79
+ return at;
80
+ }
81
+ if (char === "[") inClass = true;
82
+ else if (char === "]") inClass = false;
83
+ at++;
84
+ }
85
+ return invalid();
86
+ }
87
+
88
+ // Track expression starts just far enough to distinguish regex literals from division.
89
+ function expressionToken(code, at, regexAllowed) {
90
+ const next = trivia(code, at);
91
+ // Division can continue across a line end, so trivia keeps the state it found.
92
+ if (next !== at) return [next, regexAllowed];
93
+ const char = code[at];
94
+ if ('\'"`'.includes(char)) return [literalAt(code, at)[1], false];
95
+ if ("{([".includes(char)) return [groupEnd(code, at), char === "{"];
96
+ if (char === "/" && regexAllowed) return [regexEnd(code, at), false];
97
+ const word = /^[\w$]+/.exec(code.slice(at))?.[0];
98
+ if (word) return [at + word.length, EXPRESSION_KEYWORD.test(word)];
99
+ return [at + 1, ",=:!&|?};~+-*%<>^/".includes(char)];
100
+ }
101
+
102
+ // Balance expression delimiters without interpreting the expression's value.
103
+ function groupEnd(code, at) {
104
+ const close = { "{": "}", "(": ")", "[": "]" }[code[at++]];
105
+ let regexAllowed = true;
106
+ while (at < code.length) {
107
+ if (code[at] === close) return at + 1;
108
+ [at, regexAllowed] = expressionToken(code, at, regexAllowed);
109
+ }
110
+ return invalid();
111
+ }
112
+
113
+ function bashLiterals(code, at) {
114
+ const end = groupEnd(code, at);
115
+ const commands = [];
116
+ at++;
117
+ while (at < end - 1) {
118
+ at = trivia(code, at);
119
+ let key;
120
+ if (code[at] === '"' || code[at] === "'") [key, at] = literalAt(code, at);
121
+ else {
122
+ key = /^[\w$]+/.exec(code.slice(at))?.[0];
123
+ if (key) at += key.length;
124
+ }
125
+ if (key === "command") {
126
+ let start = trivia(code, at);
127
+ if (code[start] === ":") {
128
+ start = trivia(code, start + 1);
129
+ if (code[start] === '"' || code[start] === "'") {
130
+ const [value, next] = literalAt(code, start);
131
+ if ([",", "}"].includes(code[trivia(code, next)])) commands.push(value);
132
+ }
133
+ }
134
+ }
135
+ // Skip a property value, so a nested object's command key is never mistaken for this one.
136
+ let regexAllowed = false;
137
+ while (at < end - 1 && code[at] !== ",") {
138
+ [at, regexAllowed] = expressionToken(code, at, regexAllowed);
139
+ }
140
+ at++;
141
+ }
142
+ return commands;
143
+ }
144
+
145
+ /** Shell commands in source order. Malformed forms are skipped independently. */
146
+ export function replCommands(code) {
147
+ if (typeof code !== "string") return [];
148
+ const commands = [];
149
+ for (const match of code.matchAll(FORMS)) {
150
+ try {
151
+ let at = match.index + match[0].length;
152
+ let command = null;
153
+ if (match[0].startsWith("tools")) commands.push(...bashLiterals(code, at));
154
+ else if (code[at] === "`") command = literalAt(code, at)[0];
155
+ else {
156
+ at = trivia(code, at + 1);
157
+ if (code[at] === '"' || code[at] === "'") {
158
+ const [value, end] = literalAt(code, at);
159
+ if (code[trivia(code, end)] === ")") command = value;
160
+ }
161
+ }
162
+ if (command !== null) commands.push(command);
163
+ } catch {
164
+ continue;
165
+ }
166
+ }
167
+ return commands;
168
+ }