architecture-harness 0.25.1 → 0.26.0

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 (133) hide show
  1. package/package.json +2 -18
  2. package/src/cli/ask.mjs +42 -0
  3. package/src/cli/ask.test.mjs +40 -0
  4. package/src/cli/check-commands.mjs +104 -7
  5. package/src/cli/check-commands.test.mjs +281 -7
  6. package/src/cli/check-full.test.mjs +152 -0
  7. package/src/cli/check.mjs +113 -0
  8. package/src/cli/check.test.mjs +45 -0
  9. package/src/cli/child-run.mjs +7 -2
  10. package/src/cli/child-run.test.mjs +17 -2
  11. package/src/cli/ci-failures.mjs +47 -9
  12. package/src/cli/ci-failures.test.mjs +116 -10
  13. package/src/cli/ci-preview.mjs +62 -0
  14. package/src/cli/ci-preview.test.mjs +85 -0
  15. package/src/cli/ci-state.mjs +2 -2
  16. package/src/cli/ci-state.test.mjs +8 -8
  17. package/src/cli/ci-template.test.mjs +79 -1
  18. package/src/cli/codex-implement.mjs +373 -44
  19. package/src/cli/codex-implement.test.mjs +775 -14
  20. package/src/cli/codex-limit.test.mjs +1 -1
  21. package/src/cli/codex-verify.mjs +230 -0
  22. package/src/cli/codex-verify.test.mjs +402 -0
  23. package/src/cli/comment-watch.mjs +391 -0
  24. package/src/cli/comment-watch.test.mjs +392 -0
  25. package/src/cli/commit-guard.mjs +3 -3
  26. package/src/cli/commit-guard.test.mjs +9 -3
  27. package/src/cli/diff-shape.mjs +162 -0
  28. package/src/cli/diff-shape.test.mjs +200 -0
  29. package/src/cli/dispatch-guard.test.mjs +7 -7
  30. package/src/cli/dispatch-reminder.mjs +18 -8
  31. package/src/cli/dispatch-reminder.test.mjs +46 -10
  32. package/src/cli/dispatch-slot.mjs +2 -2
  33. package/src/cli/dispatch-slot.test.mjs +18 -19
  34. package/src/cli/dispatch.test.mjs +3 -3
  35. package/src/cli/fleet.mjs +180 -0
  36. package/src/cli/fleet.test.mjs +213 -0
  37. package/src/cli/gate-slot.mjs +2 -1
  38. package/src/cli/gh-merge-command.mjs +5 -3
  39. package/src/cli/gh-merge-command.test.mjs +4 -0
  40. package/src/cli/gh-run.mjs +50 -7
  41. package/src/cli/gh-run.test.mjs +35 -5
  42. package/src/cli/git-read.mjs +2 -1
  43. package/src/cli/integrate-tree.mjs +47 -0
  44. package/src/cli/integrate.mjs +35 -26
  45. package/src/cli/integration-lane.mjs +3 -5
  46. package/src/cli/integration-lane.test.mjs +2 -2
  47. package/src/cli/ledger.test.mjs +12 -3
  48. package/src/cli/legs.mjs +53 -0
  49. package/src/cli/legs.test.mjs +70 -0
  50. package/src/cli/locked-tests.mjs +134 -0
  51. package/src/cli/locked-tests.test.mjs +188 -0
  52. package/src/cli/merge-guard.mjs +96 -43
  53. package/src/cli/merge-guard.test.mjs +272 -111
  54. package/src/cli/metrics.mjs +53 -0
  55. package/src/cli/metrics.test.mjs +73 -0
  56. package/src/cli/milestone.mjs +297 -0
  57. package/src/cli/milestone.test.mjs +294 -0
  58. package/src/cli/mutate.mjs +203 -0
  59. package/src/cli/mutate.test.mjs +134 -0
  60. package/src/cli/overview.mjs +131 -0
  61. package/src/cli/overview.test.mjs +137 -0
  62. package/src/cli/platform-risk.mjs +46 -0
  63. package/src/cli/platform-risk.test.mjs +38 -0
  64. package/src/cli/pr-guard.mjs +128 -0
  65. package/src/cli/pr-guard.test.mjs +154 -0
  66. package/src/cli/qc.mjs +76 -20
  67. package/src/cli/qc.test.mjs +35 -1
  68. package/src/cli/retry-failed.mjs +3 -1
  69. package/src/cli/run-log.mjs +73 -0
  70. package/src/cli/run-log.test.mjs +121 -0
  71. package/src/cli/skill-length.test.mjs +8 -0
  72. package/src/cli/tools.mjs +49 -0
  73. package/src/cli/tools.test.mjs +89 -0
  74. package/src/cli/watch.mjs +21 -8
  75. package/src/cli/watch.test.mjs +45 -21
  76. package/src/cli/work-order-guard.mjs +2 -1
  77. package/src/cli/workflow-hooks.test.mjs +1 -1
  78. package/src/cli/workflow-settings.mjs +3 -2
  79. package/src/cli/workflow-settings.test.mjs +11 -1
  80. package/src/config.mjs +64 -2
  81. package/src/config.test.mjs +93 -20
  82. package/src/consumer-package.test.mjs +3 -18
  83. package/src/descriptions.mjs +1 -0
  84. package/src/eslint/index.mjs +2 -0
  85. package/src/eslint/preset.mjs +12 -1
  86. package/src/eslint/preset.test.mjs +1 -1
  87. package/src/eslint/rules/timeless-comment.mjs +92 -0
  88. package/src/eslint/rules.test.mjs +34 -0
  89. package/src/gates/plain-language.mjs +396 -0
  90. package/src/gates/plain-language.test.mjs +210 -0
  91. package/src/global-skills.test.mjs +0 -1
  92. package/templates/docs/enforcement.md +12 -2
  93. package/templates/github/workflows/ci.yml +51 -4
  94. package/src/cli/screens-discovery.mjs +0 -60
  95. package/src/cli/screens.mjs +0 -85
  96. package/src/cli/stack.mjs +0 -14
  97. package/src/cli/throwaway-db.mjs +0 -133
  98. package/src/cli/throwaway-db.test.mjs +0 -137
  99. package/src/screens/auth-context.test.mjs +0 -41
  100. package/src/screens/auth-run.test.mjs +0 -147
  101. package/src/screens/auth.mjs +0 -223
  102. package/src/screens/auth.test.mjs +0 -76
  103. package/src/screens/capture-idle.test.mjs +0 -27
  104. package/src/screens/capture.browser-test.mjs +0 -73
  105. package/src/screens/capture.mjs +0 -176
  106. package/src/screens/capture.test.mjs +0 -28
  107. package/src/screens/catalog.browser-test.mjs +0 -32
  108. package/src/screens/catalog.mjs +0 -72
  109. package/src/screens/catalog.test.mjs +0 -36
  110. package/src/screens/chrome.mjs +0 -21
  111. package/src/screens/compare.mjs +0 -41
  112. package/src/screens/compare.test.mjs +0 -30
  113. package/src/screens/discovery.browser-test.mjs +0 -29
  114. package/src/screens/discovery.mjs +0 -158
  115. package/src/screens/discovery.test.mjs +0 -27
  116. package/src/screens/inventory.mjs +0 -69
  117. package/src/screens/inventory.test.mjs +0 -10
  118. package/src/screens/map.mjs +0 -63
  119. package/src/screens/map.test.mjs +0 -35
  120. package/src/screens/open.browser-test.mjs +0 -50
  121. package/src/screens/regions.mjs +0 -138
  122. package/src/screens/regions.test.mjs +0 -38
  123. package/src/screens/session-files.mjs +0 -39
  124. package/src/screens/session-files.test.mjs +0 -39
  125. package/src/screens/setup.browser-test.mjs +0 -49
  126. package/src/screens/setup.mjs +0 -79
  127. package/src/screens/stack-auth.browser-test.mjs +0 -30
  128. package/src/screens/stack-auth.mjs +0 -107
  129. package/src/screens/stack-auth.test.mjs +0 -65
  130. package/src/screens/write-guard.mjs +0 -26
  131. package/src/stack/stack.mjs +0 -131
  132. package/src/stack/stack.test.mjs +0 -60
  133. package/src/stack/supervisor.mjs +0 -30
@@ -0,0 +1,152 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { runAffectedCheck, runFullCheck } from "./check.mjs";
8
+
9
+ function fixture(overrides = {}) {
10
+ const records = [], calls = [];
11
+ const options = {
12
+ platform: 'win32', git: (...args) => args[0] === 'status' ? '' : 'head',
13
+ gates: async () => ({ problems: [], lines: [] }), commands: async () => 0,
14
+ suite: async () => 0, record: (_root, value) => records.push(value),
15
+ spawn: (cmd, args) => { calls.push([cmd, args]); return { status: 0 }; },
16
+ nodeMajor: () => '22', write: () => {}, ...overrides,
17
+ };
18
+ return { options, records, calls };
19
+ }
20
+ const config = { root: 'C:\\repo with space', check: {} };
21
+ test('full check runs gates, commands, and suite, then records the clean host head', async () => {
22
+ const order = [];
23
+ const { options, records } = fixture({
24
+ gates: async () => { order.push('gates'); return { problems: [], lines: [] }; },
25
+ commands: async () => { order.push('commands'); return 0; },
26
+ suite: async () => { order.push('suite'); return 0; },
27
+ });
28
+ assert.equal(await runFullCheck(config, [], options), 0);
29
+ assert.deepEqual(order, ['gates', 'commands', 'suite']);
30
+ assert.deepEqual(records, [{ type: 'leg', os: 'windows', head: 'head', source: 'local' }]);
31
+ });
32
+ for (const stage of ['gates', 'commands', 'suite', 'dirty', 'head changed']) {
33
+ test(`records no evidence for ${stage}`, async () => {
34
+ let heads = 0;
35
+ const { options, records } = fixture({
36
+ ...(stage === 'gates' ? { gates: async () => ({ problems: [{ path: 'a', rule: 'bad', detail: 'bad' }], lines: [] }) } : {}),
37
+ ...(stage === 'commands' ? { commands: async () => 1 } : {}),
38
+ ...(stage === 'suite' ? { suite: async () => 1 } : {}),
39
+ ...(stage === 'dirty' ? { git: (...args) => args[0] === 'status' ? ' M a' : 'head' } : {}),
40
+ ...(stage === 'head changed' ? { git: (...args) => args[0] === 'status' ? '' : String(heads++) } : {}),
41
+ });
42
+ await runFullCheck(config, [], options);
43
+ assert.deepEqual(records, []);
44
+ });
45
+ }
46
+ test('Windows uses Docker and engines Node major for a Linux leg', async () => {
47
+ const { options, calls, records } = fixture();
48
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 0);
49
+ assert.equal(calls[0][0], 'docker');
50
+ assert.ok(calls[1][1].includes('node:22'));
51
+ assert.ok(calls[1][1].includes('type=bind,source=C:\\repo with space,target=/workspace'));
52
+ assert.ok(calls[1][1].some((arg) => arg.startsWith('QC_PLATFORM_GIT_DIR=/qc-git')));
53
+ assert.ok(calls[1][1].every((arg) => !arg.startsWith('GIT_DIR=') && !arg.startsWith('GIT_WORK_TREE=')));
54
+ assert.match(calls[1][1].at(-1), /mktemp -d.*git -c core.autocrlf=false -c core.eol=lf --git-dir="\$QC_PLATFORM_GIT_DIR" archive --format=tar --output="\$qc_tree\/source.tar" 'head'/);
55
+ assert.doesNotMatch(calls[1][1].at(-1), /tar --exclude/);
56
+ assert.equal(records[0].os, 'linux');
57
+ });
58
+ test('Windows falls back to WSL when Docker is absent', async () => {
59
+ const { options, records, calls } = fixture();
60
+ options.spawn = (cmd, args) => { calls.push([cmd, args]); return cmd === 'docker' ? { error: new Error('absent') } : { status: 0, stdout: '/mnt/c/repo\n' }; };
61
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 0);
62
+ assert.equal(calls.at(-1)[0], 'wsl');
63
+ assert.ok(calls.at(-1)[1].includes('/mnt/c/repo'));
64
+ assert.ok(calls.at(-1)[1].every((arg) => !arg.startsWith('GIT_DIR=') && !arg.startsWith('GIT_WORK_TREE=')));
65
+ assert.doesNotMatch(calls.at(-1)[1].at(-1), /corepack enable/);
66
+ assert.match(calls.at(-1)[1].at(-1), /git -c core.autocrlf=false -c core.eol=lf --git-dir="\$QC_PLATFORM_GIT_DIR" archive --format=tar --output="\$qc_tree\/source.tar" 'head'/);
67
+ assert.equal(records[0].os, 'linux');
68
+ });
69
+
70
+ test('the Linux view uses the pinned head bytes despite a CRLF checkout and later edits', async (t) => {
71
+ const root = mkdtempSync(path.join(os.tmpdir(), 'qc-linux-bytes-'));
72
+ t.after(() => rmSync(root, { recursive: true, force: true }));
73
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
74
+ git('init');
75
+ git('config', 'user.name', 'Fixture');
76
+ git('config', 'user.email', 'fixture@example.test');
77
+ git('config', 'core.autocrlf', 'true');
78
+ writeFileSync(path.join(root, 'source.sh'), 'echo stored\n');
79
+ git('add', 'source.sh');
80
+ git('commit', '-m', 'fixture');
81
+ rmSync(path.join(root, 'source.sh'));
82
+ git('checkout', '--', 'source.sh');
83
+ assert.equal(readFileSync(path.join(root, 'source.sh'), 'utf8'), 'echo stored\r\n');
84
+ const head = git('rev-parse', 'HEAD');
85
+ const { options, calls } = fixture({ git });
86
+ assert.equal(await runFullCheck({ root, check: {} }, ['--os', 'linux'], options), 0);
87
+ writeFileSync(path.join(root, 'source.sh'), 'echo edited\r\n');
88
+ writeFileSync(path.join(root, 'untracked.sh'), 'echo untracked\r\n');
89
+ git('add', 'source.sh');
90
+ git('commit', '-m', 'later fixture');
91
+ assert.notEqual(git('rev-parse', 'HEAD'), head);
92
+ const script = calls[1][1].at(-1).split('corepack enable && ')[0];
93
+ const bash = process.platform === 'win32' ? path.join(process.env.ProgramFiles, 'Git', 'bin', 'bash.exe') : 'sh';
94
+ assert.ok(process.platform !== 'win32' || existsSync(bash), 'Git Bash is required on Windows');
95
+ const result = spawnSync(bash, ['-xc', `${script}test "$(cat source.sh)" = 'echo stored' && test "$(wc -c < source.sh)" -eq 12 && test ! -e untracked.sh`], {
96
+ cwd: root, encoding: 'utf8', env: { ...process.env, QC_PLATFORM_GIT_DIR: git('rev-parse', '--absolute-git-dir') },
97
+ });
98
+ assert.equal(result.status, 0, result.stdout + result.stderr);
99
+ });
100
+ test('failed Docker run produces no leg and does not retry in WSL', async () => {
101
+ const { options, records, calls } = fixture();
102
+ options.spawn = (cmd, args) => { calls.push([cmd, args]); return { status: args[0] === 'info' ? 0 : 1 }; };
103
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 1);
104
+ assert.equal(calls.length, 2);
105
+ assert.deepEqual(records, []);
106
+ });
107
+ test('rejects unknown arguments and unsupported target hosts', async () => {
108
+ const { options, records } = fixture({ platform: 'linux' });
109
+ assert.equal(await runFullCheck(config, ['--os', 'windows'], options), 1);
110
+ assert.equal(await runFullCheck(config, ['a.mjs'], options), 1);
111
+ assert.deepEqual(records, []);
112
+ });
113
+
114
+ test('unavailable WSL records no Linux evidence', async () => {
115
+ const { options, records } = fixture({ spawn: () => ({ status: 1 }) });
116
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 1);
117
+ assert.deepEqual(records, []);
118
+ });
119
+
120
+ test('the parent records its temporary view without suppressing evidence in nested fixtures', async (t) => {
121
+ const previous = process.env.QC_PLATFORM_LEG_PARENT;
122
+ process.env.QC_PLATFORM_LEG_PARENT = config.root;
123
+ t.after(() => {
124
+ if (previous === undefined) delete process.env.QC_PLATFORM_LEG_PARENT;
125
+ else process.env.QC_PLATFORM_LEG_PARENT = previous;
126
+ });
127
+ const { options, records } = fixture();
128
+ assert.equal(await runFullCheck(config, [], options), 0);
129
+ assert.deepEqual(records, []);
130
+ assert.equal(await runFullCheck({ ...config, root: 'another-fixture' }, [], options), 0);
131
+ assert.equal(records.length, 1);
132
+ });
133
+
134
+
135
+ test('affected checks preserve gate and command failures and record only a clean unchanged supported head', async () => {
136
+ for (const stage of ['pass', 'gates', 'commands', 'gate error', 'command error', 'dirty', 'checkout dirtied', 'head changed', 'unsupported']) {
137
+ let heads = 0, statuses = 0;
138
+ const { options, records } = fixture({
139
+ ...(stage === 'gates' ? { gates: async () => ({ problems: [{ path: 'a', rule: 'bad', detail: 'bad' }], lines: [] }) } : {}),
140
+ ...(stage === 'commands' ? { commands: async () => 7 } : {}),
141
+ ...(stage === 'gate error' ? { gates: async () => { throw new Error('gate error'); } } : {}),
142
+ ...(stage === 'command error' ? { commands: async () => { throw new Error('command error'); } } : {}),
143
+ ...(stage === 'dirty' ? { git: (...args) => args[0] === 'status' ? ' M a' : 'head' } : {}),
144
+ ...(stage === 'checkout dirtied' ? { git: (...args) => args[0] === 'status' ? (statuses++ ? ' M a' : '') : 'head' } : {}),
145
+ ...(stage === 'head changed' ? { git: (...args) => args[0] === 'status' ? '' : String(heads++) } : {}),
146
+ ...(stage === 'unsupported' ? { platform: 'darwin' } : {}),
147
+ });
148
+ const code = await runAffectedCheck(config, { base: 'main' }, options);
149
+ assert.equal(code, ['gates', 'gate error', 'command error', 'unsupported'].includes(stage) ? 1 : stage === 'commands' ? 7 : 0);
150
+ assert.deepEqual(records, stage === 'pass' ? [{ type: 'leg', os: 'windows', head: 'head', source: 'local' }] : []);
151
+ }
152
+ });
package/src/cli/check.mjs CHANGED
@@ -3,6 +3,11 @@
3
3
 
4
4
  import { readFile, stat } from "node:fs/promises";
5
5
  import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { appendLeg, gitText, hostOS } from "./legs.mjs";
10
+ import { runCheckCommands, runCommand } from "./check-commands.mjs";
6
11
  import { checkFeatureAnatomy, checkNoEmptyBlock } from "../gates/eight-blocks.mjs";
7
12
  import { checkCitations, checkDocPaths, checkSelfContained, definedIds } from "../gates/citations.mjs";
8
13
  import { checkAgreement, declaredValues } from "../gates/registry-agreement.mjs";
@@ -38,6 +43,7 @@ import { checkFrontendBoundaries } from "../gates/frontend-boundaries.mjs";
38
43
  import { checkTestMirror, mirrorFolders } from "../gates/test-mirror.mjs";
39
44
  import { checkCommentStyle } from "../gates/comment-style.mjs";
40
45
  import { checkEnglishFiles, checkEnglishSource, checkTranslationPairs } from "../gates/english-source.mjs";
46
+ import { checkPlainLanguage } from "../gates/plain-language.mjs";
41
47
  import { checkAdrFormat } from "../gates/adr-format.mjs";
42
48
  import { checkConfigFloor } from "../gates/config-floor.mjs";
43
49
  import { defaults } from "../config.mjs";
@@ -81,6 +87,99 @@ const PATHSPEC_BUDGET = 8_000;
81
87
 
82
88
  const read = (file) => readFile(file, "utf8").catch(() => null);
83
89
 
90
+ function nodeMajor(root) {
91
+ const engines = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).engines?.node;
92
+ const major = /\d+/.exec(engines ?? "")?.[0];
93
+ if (!major) throw new Error("package.json engines.node must name a Node major");
94
+ return major;
95
+ }
96
+
97
+ function testSuite(root) {
98
+ const manager = existsSync(path.join(root, "pnpm-lock.yaml")) ? "pnpm" : existsSync(path.join(root, "yarn.lock")) ? "yarn" : "npm";
99
+ return runCommand(root, `${manager} test`);
100
+ }
101
+
102
+ const cleanHead = (git) => git("status", "--porcelain", "--untracked-files=all") === "";
103
+
104
+ async function checkGates(config, options, write) {
105
+ const { problems, lines } = await (options.gates ?? runCheck)(config);
106
+ for (const line of lines) write(line);
107
+ for (const problem of problems) write(`FAIL ${problem.feature ?? problem.path} ${problem.rule}: ${problem.detail}`);
108
+ return problems.length === 0;
109
+ }
110
+
111
+ function recordCleanLeg(config, git, head, clean, os, record = appendLeg) {
112
+ if (process.env.QC_PLATFORM_LEG_PARENT !== config.root && clean && git("rev-parse", "HEAD") === head && cleanHead(git)) {
113
+ record(config.root, { type: "leg", os, head, source: "local" });
114
+ }
115
+ }
116
+
117
+ export async function runFullCheck(config, args = [], options = {}) {
118
+ const write = options.write ?? console.log;
119
+ const git = options.git ?? ((...words) => gitText(config.root, ...words));
120
+ const spawn = options.spawn ?? spawnSync;
121
+ const record = options.record ?? appendLeg;
122
+ const host = hostOS(options.platform);
123
+ const target = args.length === 0 ? host : args.length === 2 && args[0] === "--os" ? args[1] : null;
124
+ if (!["linux", "windows"].includes(target) || (target !== host && !(host === "windows" && target === "linux"))) {
125
+ write("check --full accepts --os linux or --os windows; cross-platform runs need Windows and target Linux");
126
+ return 1;
127
+ }
128
+ try {
129
+ const head = git("rev-parse", "HEAD");
130
+ const clean = cleanHead(git);
131
+ let code;
132
+ if (target !== host) {
133
+ const major = (options.nodeMajor ?? nodeMajor)(config.root);
134
+ const opts = { cwd: config.root, stdio: "inherit", windowsHide: true };
135
+ const docker = spawn("docker", ["info"], { ...opts, stdio: "ignore" });
136
+ const cli = path.relative(config.root, fileURLToPath(new URL("./qc.mjs", import.meta.url))).split(path.sep).join("/");
137
+ const quotedCli = `'${cli.replace(/'/g, "'\\''")}'`;
138
+ const command = `if [ -f pnpm-lock.yaml ]; then pnpm install --frozen-lockfile; else npm ci; fi && node ${quotedCli} check --full`;
139
+ // A temporary view gives Linux its own dependencies without exporting Git variables into test fixtures.
140
+ const linuxView = `qc_tree=$(mktemp -d /tmp/qc-platform.XXXXXX) && trap 'rm -rf "$qc_tree"' EXIT && git -c core.autocrlf=false -c core.eol=lf --git-dir="$QC_PLATFORM_GIT_DIR" archive --format=tar --output="$qc_tree/source.tar" '${head.replace(/'/g, "'\\''")}' && tar -xf "$qc_tree/source.tar" -C "$qc_tree" && rm "$qc_tree/source.tar" && printf 'gitdir: %s\\n' "$QC_PLATFORM_GIT_DIR" > "$qc_tree/.git" && cd "$qc_tree" && export QC_PLATFORM_LEG_PARENT="$qc_tree" && `;
141
+ const common = path.resolve(config.root, git("rev-parse", "--git-common-dir"));
142
+ const gitDir = path.resolve(config.root, git("rev-parse", "--absolute-git-dir"));
143
+ if (docker.status === 0) {
144
+ const containerGitDir = path.posix.join("/qc-git", path.relative(common, gitDir).split(path.sep).join("/"));
145
+ code = spawn("docker", ["run", "--rm", "--mount", `type=bind,source=${config.root},target=/workspace`, "--mount", `type=bind,source=${common},target=/qc-git`, "-e", `QC_PLATFORM_GIT_DIR=${containerGitDir}`, "-w", "/workspace", `node:${major}`, "sh", "-lc", `${linuxView}corepack enable && ${command}`], opts).status ?? 1;
146
+ } else {
147
+ const convert = (value) => {
148
+ const converted = spawn("wsl", ["--exec", "wslpath", "-u", value], { ...opts, stdio: "pipe", encoding: "utf8" });
149
+ if (converted.status !== 0 || !converted.stdout?.trim()) throw new Error("Linux check needs Docker or WSL");
150
+ return converted.stdout.trim();
151
+ };
152
+ const wslRoot = convert(config.root);
153
+ const wslGit = convert(gitDir);
154
+ const wslCommand = `test "$(node -p 'process.versions.node.split(String.fromCharCode(46))[0]')" = ${major} && ${command}`;
155
+ code = spawn("wsl", ["--cd", wslRoot, "--exec", "env", `QC_PLATFORM_GIT_DIR=${wslGit}`, "sh", "-lc", `${linuxView}${wslCommand}`], opts).status ?? 1;
156
+ }
157
+ } else {
158
+ if (!await checkGates(config, options, write)) return 1;
159
+ code = await (options.commands ?? runCheckCommands)(config);
160
+ if (code === 0) code = await (options.suite ?? testSuite)(config.root);
161
+ }
162
+ if (code !== 0) return code;
163
+ recordCleanLeg(config, git, head, clean, target, record);
164
+ return 0;
165
+ } catch (error) { write(`check --full: ${error.message}`); return 1; }
166
+ }
167
+
168
+ export async function runAffectedCheck(config, selection = {}, options = {}) {
169
+ const write = options.write ?? console.log;
170
+ const git = options.git ?? ((...words) => gitText(config.root, ...words));
171
+ const os = hostOS(options.platform);
172
+ try {
173
+ if (!["linux", "windows"].includes(os)) throw new Error("unsupported platform");
174
+ const head = git("rev-parse", "HEAD"), clean = cleanHead(git);
175
+ if (!await checkGates(config, options, write)) return 1;
176
+ const code = await (options.commands ?? runCheckCommands)(config, { ...selection, affected: true });
177
+ if (code !== 0) return code;
178
+ recordCleanLeg(config, git, head, clean, os, options.record);
179
+ return 0;
180
+ } catch (error) { write(`qc check: ${error.message}`); return 1; }
181
+ }
182
+
84
183
  /** A problem names a path a reader can open — forward slashes always, since every gate splits on "/". */
85
184
  const relativeTo = (root) => (file) => (path.relative(root, file) || file).split(path.sep).join("/");
86
185
 
@@ -918,6 +1017,20 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
918
1017
  }
919
1018
  }
920
1019
 
1020
+ if (enabled(config.gates, "plain-language")) {
1021
+ // Its own roots and its own extensions: a language rule asks which language, this one asks how
1022
+ // plainly, and a repository answers the two questions over different parts of its tree.
1023
+ const { roots, extensions, exclude } = config.plainLanguage;
1024
+ const extension = new RegExp(`\\.(${extensions.join("|")})$`);
1025
+ const excluded = exclude.map((pattern) => new RegExp(pattern));
1026
+ const files = roots
1027
+ .flatMap((root) => tree.under(root))
1028
+ .filter((file) => extension.test(file) && !excluded.some((pattern) => pattern.test(file)));
1029
+ const prose = await readEach(config.root, files);
1030
+ problems.push(...checkPlainLanguage(prose, config.plainLanguage));
1031
+ lines.push(`OK prose ${prose.length} file(s) in short sentences, the active voice and the approved words`);
1032
+ }
1033
+
921
1034
  if (enabled(config.gates, "adr-format")) {
922
1035
  const records = await citableFiles(config, tree, [config.adr.root]);
923
1036
  const docs = records.filter((file) => file.path.endsWith(".md"));
@@ -0,0 +1,45 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import test from "node:test";
7
+ import { defaults, merge } from "../config.mjs";
8
+ import { runCheck } from "./check.mjs";
9
+
10
+ function proseFixture(t, file) {
11
+ const root = mkdtempSync(path.join(tmpdir(), "qc-prose-selection-"));
12
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
13
+ execFileSync("git", ["init", "-q"], { cwd: root });
14
+ mkdirSync(path.join(root, "docs"));
15
+ writeFileSync(path.join(root, "docs", file), "// Utilize helpers.\n");
16
+ return (plainLanguage = {}) => ({
17
+ ...merge(defaults, {
18
+ featureRoots: [],
19
+ gates: {
20
+ ...Object.fromEntries(Object.keys(defaults.gates).map((name) => [name, false])),
21
+ "plain-language": true,
22
+ },
23
+ plainLanguage: { roots: ["docs"], ...plainLanguage },
24
+ }),
25
+ root,
26
+ });
27
+ }
28
+
29
+ test("runCheck reads JavaScript comments with the default prose extensions", async (t) => {
30
+ const config = proseFixture(t, "note.js");
31
+ const { problems } = await runCheck(config());
32
+ assert.deepEqual(problems.map(({ path, rule }) => ({ path, rule })), [
33
+ { path: "docs/note.js", rule: "unapproved-word" },
34
+ ]);
35
+ });
36
+
37
+ test("runCheck honors the prose extensions and excludes", async (t) => {
38
+ const config = proseFixture(t, "note.mjs");
39
+ const extensions = await runCheck(config({ extensions: ["js"] }));
40
+ const exclude = await runCheck(config({ exclude: ["note\\.mjs$"] }));
41
+ assert.deepEqual({ extensions: extensions.problems, exclude: exclude.problems }, {
42
+ extensions: [],
43
+ exclude: [],
44
+ });
45
+ });
@@ -3,9 +3,14 @@
3
3
 
4
4
  import { spawn } from "node:child_process";
5
5
 
6
- /** One shell command line from argv words; a word with a space or a quote is quoted. */
7
- export function commandLine(words) {
6
+ /**
7
+ * One shell command line from argv words, quoted for the shell that `runInShell` starts on `platform`.
8
+ * @throws on Windows when a word holds a line break, because cmd.exe ends the command there
9
+ */
10
+ export function commandLine(words, platform = process.platform) {
8
11
  const args = words[0] === "--" ? words.slice(1) : words;
12
+ if (platform !== "win32") return args.map((arg) => (/^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`)).join(" ");
13
+ if (args.some((arg) => /[\r\n]/.test(arg))) throw new Error("cmd.exe cannot pass an argument with a line break; put the commands in a script file and run that file");
9
14
  return args.map((arg) => (/^$|[\s"]/.test(arg) ? `"${arg.replaceAll('"', '\\"')}"` : arg)).join(" ");
10
15
  }
11
16
 
@@ -1,9 +1,24 @@
1
1
  import { strict as assert } from "node:assert";
2
+ import { mkdtempSync, readFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
2
5
  import { test } from "node:test";
3
6
  import { commandLine, runInShell, splitAtDashes } from "./child-run.mjs";
4
7
 
5
- test("a word with a space or a quote is quoted, and a leading -- is dropped", () => {
6
- assert.equal(commandLine(["--", "pnpm", "vitest", "run", "a b.test.ts", 'say "hi"']), 'pnpm vitest run "a b.test.ts" "say \\"hi\\""');
8
+ test("each word is quoted for the shell of the platform, and a leading -- is dropped", () => {
9
+ const words = ["--", "pnpm", "vitest", "run", "a b.test.ts", 'say "hi"'];
10
+ assert.equal(commandLine(words, "win32"), 'pnpm vitest run "a b.test.ts" "say \\"hi\\""');
11
+ assert.equal(commandLine(words, "linux"), `pnpm vitest run 'a b.test.ts' 'say "hi"'`);
12
+ assert.equal(commandLine(["bash", "-c", "echo $HOME\necho it's", ""], "linux"), `bash -c 'echo $HOME\necho it'\\''s' ''`);
13
+ assert.throws(() => commandLine(["bash", "-c", "a\nb"], "win32"), /line break/);
14
+ });
15
+
16
+ test("the shell hands each word to the command unchanged", async () => {
17
+ const word = process.platform === "win32" ? `one 'two' $HOME \`x\` "q"` : `line one\nline 'two' $HOME \`x\` "q"`;
18
+ const out = path.join(mkdtempSync(path.join(tmpdir(), "child-run-")), "word.txt");
19
+ const script = `require("node:fs").writeFileSync(process.argv[2], process.argv[1])`;
20
+ assert.equal(await runInShell(commandLine([process.execPath, "-e", script, word, out])), 0);
21
+ assert.equal(readFileSync(out, "utf8"), word);
7
22
  });
8
23
 
9
24
  test("argv splits at its first --", () => {
@@ -4,7 +4,8 @@ import { readFileSync, realpathSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { appendRecord, ledgerFileOf, readLedger, shaMatches } from "./ledger.mjs";
6
6
  import { runGhResult } from "./gh-run.mjs";
7
- import { holdBranch, holdRefusal } from "./pause.mjs";
7
+ import { holdRefusal } from "./pause.mjs";
8
+ import { askIssue } from "./ask.mjs";
8
9
  import { load } from "../config.mjs";
9
10
  import { isAncestor, originOf, repoOfSpelling } from "./git-read.mjs";
10
11
 
@@ -77,6 +78,7 @@ function readGh(args, root) {
77
78
  export function recordRun(root, { id, branch, head, repository }, { gh = (args) => readGh(args, root), warn = console.error, repo } = {}) {
78
79
  const file = ledgerFileOf(root);
79
80
  if (!file) return [];
81
+ repository = repoOfSpelling(repository ?? repo ?? originOf(root) ?? "");
80
82
  let log;
81
83
  try {
82
84
  log = gh(["run", "view", String(id), "--log-failed", ...(repo ? ["-R", repo] : [])]);
@@ -86,7 +88,6 @@ export function recordRun(root, { id, branch, head, repository }, { gh = (args)
86
88
  return null;
87
89
  }
88
90
  const records = recordsOf(root);
89
- repository = repoOfSpelling(repository ?? repo ?? originOf(root) ?? "");
90
91
  const added = [];
91
92
  for (const failure of parseFailedLog(log)) {
92
93
  const key = JSON.stringify([repository, String(id), branch, head, failure.job, failure.file, failure.test]);
@@ -95,25 +96,62 @@ export function recordRun(root, { id, branch, head, repository }, { gh = (args)
95
96
  appendRecord(file, record);
96
97
  added.push(record);
97
98
  }
98
- if (repository && repository === originOf(root) && added.some((failure) => repeatCount(root, branch, failure) >= 3)) holdBranch(root, branch, "the same CI test failed on three heads in a row");
99
+ const failures = openFailures(root, branch, repository);
100
+ const heads = failureHeads(root, branch, { repository }, failures);
101
+ let streakHeads = [];
102
+ const repeated = failures.find((failure) => {
103
+ if (failure.run !== String(id) || !sameHead(failure.head, head)) return false;
104
+ streakHeads = trailingFailureHeads(heads, failure);
105
+ return streakHeads.length >= 3;
106
+ });
107
+ if (repository && repository === originOf(root) && repeated) {
108
+ try {
109
+ const prs = JSON.parse(gh(["api", `repos/${repository}/commits/${head}/pulls`]));
110
+ const reference = /\b(?:refs|close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+(?:([\w.-]+\/[\w.-]+))?#([1-9]\d*)\b/gi;
111
+ const pr = prs.find((pr) => pr.state === "open" && pr.head?.repo?.full_name === repository && pr.head?.ref === branch);
112
+ const issue = [...(pr?.body ?? "").matchAll(reference)]
113
+ .find((match) => !match[1] || match[1].toLowerCase() === repository.toLowerCase())?.[2];
114
+ if (!issue) {
115
+ warn(`ci-failures: no linked issue in the PR for ${branch}; cannot ask about three failing heads`.replace(/[\r\n]+/g, " "));
116
+ } else {
117
+ const marker = `<!-- qc-ci-question:${Buffer.from(branch).toString("base64url")}:${head} -->`;
118
+ const pages = JSON.parse(gh(["api", `repos/${repository}/issues/${issue}/comments`, "--paginate", "--slurp"]));
119
+ if (!Array.isArray(pages) || !pages.every(Array.isArray)) throw new Error("cannot read issue comments");
120
+ const markers = streakHeads.map((sha) => `<!-- qc-ci-question:${Buffer.from(branch).toString("base64url")}:${sha} -->`);
121
+ if (!pages.flat().some((comment) => markers.some((marker) => comment.body?.includes(marker)))) {
122
+ askIssue(issue, `The CI test ${repeated.test} on branch ${branch} has failed on three heads in a row. How should we proceed?\n\n${marker}`, { cwd: root, repo: repository, gh });
123
+ }
124
+ }
125
+ } catch (error) {
126
+ warn(`ci-failures: gh failed: ${String(error.message).split(/\r?\n/)[0]}`);
127
+ }
128
+ }
99
129
  return added;
100
130
  }
101
131
 
102
132
  const identity = (r) => JSON.stringify([r.test, r.file, r.os]);
103
133
 
104
- export function repeatCount(root, branch, failure) {
134
+ function failureHeads(root, branch, failure, failures = openFailures(root, branch, failure.repository ?? originOf(root))) {
105
135
  const heads = new Map();
106
- for (const record of openFailures(root, branch, failure.repository ?? originOf(root))) {
136
+ for (const record of failures) {
107
137
  const head = [...heads.keys()].find((head) => sameHead(head, record.head)) ?? record.head;
108
138
  if (!heads.has(head)) heads.set(head, new Set());
109
139
  heads.get(head).add(identity(record));
110
140
  }
111
- let count = 0;
112
- for (const tests of [...heads.values()].reverse()) {
141
+ return heads;
142
+ }
143
+
144
+ function trailingFailureHeads(heads, failure) {
145
+ const trailing = [];
146
+ for (const [head, tests] of [...heads].reverse()) {
113
147
  if (!tests.has(identity(failure))) break;
114
- count += 1;
148
+ trailing.push(head);
115
149
  }
116
- return count;
150
+ return trailing.reverse();
151
+ }
152
+
153
+ export function repeatCount(root, branch, failure) {
154
+ return trailingFailureHeads(failureHeads(root, branch, failure), failure).length;
117
155
  }
118
156
 
119
157
  function section(text, name) {