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
@@ -6,7 +6,7 @@ import { execFileSync, spawnSync } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import path from "node:path";
8
8
  import { recordRun, openFailures, resolveFailures, ciBriefRefusal, lessonRefusal, lessonRules, rerunFailures, runCiFailures, parseFailedLog } from "./ci-failures.mjs";
9
- import { holdRefusal, runResume } from "./pause.mjs";
9
+ import { holdBranch, holdRefusal, runResume } from "./pause.mjs";
10
10
  import { appendRecord, ledgerFileOf, readLedger } from "./ledger.mjs";
11
11
  import { runWatch } from "./watch.mjs";
12
12
 
@@ -45,18 +45,20 @@ function fixture(t) {
45
45
  return root;
46
46
  }
47
47
 
48
- test("records the repository and holds only failures from the local origin", (t) => {
48
+ test("records the repository and asks only for failures from the local origin", (t) => {
49
49
  const root = fixture(t);
50
50
  for (const [id, head] of [[1, "aaaaaaa"], [2, "bbbbbbb"], [3, "ccccccc"]]) {
51
51
  recordRun(root, { id, branch: "main", head }, { repo: "fork/repo", gh: () => tap });
52
52
  }
53
53
  assert.equal(readLedger(ledgerFileOf(root))[0].repository, "fork/repo");
54
54
  assert.equal(holdRefusal(root, "main"), null);
55
+ const calls = [];
55
56
  for (const [id, head] of [[4, "ddddddd"], [5, "eeeeeee"], [6, "fffffff"]]) {
56
- recordRun(root, { id, branch: "main", head }, { gh: () => tap });
57
+ recordRun(root, { id, branch: "main", head }, { gh: (args) => { calls.push(args); return args[0] === "run" ? tap : args[1]?.endsWith("/pulls") ? JSON.stringify([{ body: "Refs #227", state: "open", head: { ref: "main", repo: { full_name: "local/repo" } } }]) : "[]"; } });
57
58
  }
59
+ assert.ok(calls.some((args) => args[1] === "repos/local/repo/commits/fffffff/pulls"));
58
60
  assert.equal(readLedger(ledgerFileOf(root)).at(-1).repository, "local/repo");
59
- assert.ok(holdRefusal(root, "main"));
61
+ assert.equal(holdRefusal(root, "main"), null);
60
62
  });
61
63
 
62
64
  test("watch isolates fork and explicit repositories when recording and resolving", async (t) => {
@@ -94,7 +96,7 @@ test("watch isolates fork and explicit repositories when recording and resolving
94
96
 
95
97
  test("a local branch hold leaves an explicit foreign repository watch available", async (t) => {
96
98
  const root = fixture(t);
97
- for (const [id, head] of [[1, "aaaaaaa"], [2, "bbbbbbb"], [3, "ccccccc"]]) recordRun(root, { id, branch: "main", head }, { gh: () => tap });
99
+ holdBranch(root, "main", "operator hold");
98
100
  assert.ok(holdRefusal(root, "main"));
99
101
  assert.equal(await runWatch(["--run", "ci.yml@main", "--repo", "other/repo"], { cwd: root, requiredChecks: [], say: () => {},
100
102
  gh: (args) => args.includes(".sha") ? "ddddddd" : JSON.stringify({ workflow_runs: [{ id: 4, head_sha: "ddddddd", status: "completed", conclusion: "success" }] }),
@@ -103,7 +105,7 @@ test("a local branch hold leaves an explicit foreign repository watch available"
103
105
 
104
106
  test("an unreadable origin keeps the hold on an explicit repository watch", async (t) => {
105
107
  const root = fixture(t);
106
- for (const [id, head] of [[1, "aaaaaaa"], [2, "bbbbbbb"], [3, "ccccccc"]]) recordRun(root, { id, branch: "main", head }, { gh: () => tap });
108
+ holdBranch(root, "main", "operator hold");
107
109
  execFileSync("git", ["remote", "remove", "origin"], { cwd: root });
108
110
  assert.ok(holdRefusal(root, "main"));
109
111
  const lines = [];
@@ -219,9 +221,20 @@ test("watch records a failed run, preserves exit 5 on a log error, and resolves
219
221
  assert.equal(openFailures(root, "feat/test").length, 0);
220
222
  });
221
223
 
222
- test("repeat heads require diagnosis, third heads hold only that branch, and resume alone preserves the hold", (t) => {
224
+ test("three red heads → a needs-user question, and no hold record", (t) => {
223
225
  const root = fixture(t);
224
- const record = (id, head, log = tap) => recordRun(root, { id, branch: "feat/test", head }, { gh: () => log });
226
+ const calls = [];
227
+ const comments = [];
228
+ let currentHead;
229
+ const gh = (args) => {
230
+ calls.push(args);
231
+ if (args[0] === "run") return tap;
232
+ if (args[1] === `repos/local/repo/commits/${currentHead}/pulls`) return JSON.stringify([{ body: "Refs #227", state: "open", head: { ref: "feat/test", repo: { full_name: "local/repo" }, sha: currentHead } }]);
233
+ if (args[0] === "api") return JSON.stringify([comments]);
234
+ if (args[1] === "comment") comments.push({ body: args[args.indexOf("--body") + 1] });
235
+ return "[]";
236
+ };
237
+ const record = (id, head) => { currentHead = head; return recordRun(root, { id, branch: "feat/test", head }, { gh }); };
225
238
  record(1, "aaaaaaa");
226
239
  assert.match(ciBriefRefusal(root, "feat/test", ""), /cleanup retries/);
227
240
  assert.equal(ciBriefRefusal(root, "green", ""), null);
@@ -234,8 +247,20 @@ test("repeat heads require diagnosis, third heads hold only that branch, and res
234
247
  assert.match(ciBriefRefusal(root, "feat/test", brief), /## Diagnosis/);
235
248
  assert.match(ciBriefRefusal(root, "feat/test", `${brief}\n## Diagnosis\nRoot cause: open handle\n`), /Evidence:/);
236
249
  assert.equal(ciBriefRefusal(root, "feat/test", `${brief}\n## Diagnosis\nRoot cause: open handle\nEvidence: log shows EBUSY; cleanup code leaves it open.\n`), null);
250
+ assert.equal(calls.filter((args) => args[0] === "issue").length, 0);
251
+ record(4, "ccccccc");
237
252
  record(4, "ccccccc");
238
- assert.match(holdRefusal(root, "feat/test"), /operator.*qc resume --branch feat\/test/i);
253
+ record(5, "ccccccc");
254
+ record(6, "ddddddd");
255
+ const questions = calls.filter((args) => args[0] === "issue" && args[1] === "comment");
256
+ assert.equal(questions.length, 1);
257
+ assert.equal(questions[0][2], "227");
258
+ assert.match(comments[0].body, /cleanup retries/);
259
+ assert.equal(holdRefusal(root, "feat/test"), null);
260
+ assert.ok(readLedger(ledgerFileOf(root)).every((record) => record.type === "ci-failure"));
261
+ holdBranch(root, "feat/test", "existing operator hold");
262
+ record(7, "eeeeeee");
263
+ assert.match(holdRefusal(root, "feat/test"), /qc resume/);
239
264
  assert.equal(holdRefusal(root, "other"), null);
240
265
  assert.equal(runResume(root, [], { say: () => {} }), 0);
241
266
  assert.ok(holdRefusal(root, "feat/test"));
@@ -297,7 +322,7 @@ test("rerun appends unique open test files, honors configuration, and propagates
297
322
 
298
323
  test("a held watched branch exits 5 without fetching and leaves other branches available", async (t) => {
299
324
  const root = fixture(t);
300
- for (const [id, head] of [[1, "aaaaaaa"], [2, "bbbbbbb"], [3, "ccccccc"]]) recordRun(root, { id, branch: "feat/test", head }, { gh: () => tap });
325
+ holdBranch(root, "feat/test", "operator hold");
301
326
  assert.equal(await runWatch(["--run", "ci.yml@feat/test"], { cwd: root, requiredChecks: [], gh: () => assert.fail("held branch"), say: () => {} }), 5);
302
327
  });
303
328
 
@@ -306,6 +331,10 @@ test("the command table exposes ci-failures and reruns a green branch without gh
306
331
  const qc = fileURLToPath(new URL("./qc.mjs", import.meta.url));
307
332
  const help = spawnSync(process.execPath, [qc], { cwd: root, encoding: "utf8" });
308
333
  assert.match(help.stdout, /qc ci-failures --run <id>/);
334
+ assert.match(help.stdout, /qc ask --issue <n>/);
335
+ const ask = spawnSync(process.execPath, [qc, "ask", "--issue", "0", "Why?"], { cwd: root, encoding: "utf8" });
336
+ assert.equal(ask.status, 1);
337
+ assert.match(ask.stderr, /Usage: qc ask/);
309
338
  const result = spawnSync(process.execPath, [qc, "ci-failures", "--rerun", "--branch", "green"], { cwd: root, encoding: "utf8" });
310
339
  assert.equal(result.status, 0, result.stderr);
311
340
  assert.equal(result.stdout, "");
@@ -507,3 +536,80 @@ test("the skip line stays within 200 characters for many long paths", (t) => {
507
536
  assert.ok(warnings[0].length <= 200);
508
537
  assert.match(warnings[0], /skip 10 test files:/);
509
538
  });
539
+
540
+
541
+ test("CI questions use only PR issue references and diagnose missing issues or GitHub failures", (t) => {
542
+ for (const mode of ["advanced PR", "old PR", "retry same run", "retry next head"]) {
543
+ const root = fixture(t);
544
+ const comments = [];
545
+ const warnings = [];
546
+ let failAsk = mode !== "advanced PR";
547
+ let head;
548
+ const gh = (args) => {
549
+ if (args[0] === "run") return tap;
550
+ if (args[1] === `repos/local/repo/commits/${head}/pulls`) return JSON.stringify([
551
+ { body: "Closes #12", state: "closed", head: { ref: "feat/test", repo: { full_name: "local/repo" }, sha: "0000000" } },
552
+ { body: "Refs #13", state: "open", head: { ref: "other", repo: { full_name: "local/repo" }, sha: head } },
553
+ ...(mode === "advanced PR" ? [{ body: "Refs #13", state: "open", head: { ref: "feat/test", repo: { full_name: "fork/repo" }, sha: "ddddddd" } }] : []),
554
+ { body: mode === "old PR" ? "No linked issue" : "Refs #227", state: "open", head: { ref: "feat/test", repo: { full_name: "local/repo" }, sha: mode === "advanced PR" ? "ddddddd" : head } },
555
+ ]);
556
+ if (args[0] === "api") return JSON.stringify([comments]);
557
+ if (args[0] === "issue" && args[1] === "comment") {
558
+ if (failAsk) throw new Error("GitHub unavailable");
559
+ assert.equal(args[2], "227");
560
+ comments.push({ body: args[args.indexOf("--body") + 1] });
561
+ }
562
+ return "[]";
563
+ };
564
+ const record = (id, sha) => {
565
+ head = sha;
566
+ recordRun(root, { id, branch: "feat/test", head }, { gh, warn: (s) => warnings.push(s) });
567
+ };
568
+ record(1, "aaaaaaa"); record(2, "bbbbbbb"); record(3, "ccccccc");
569
+ if (mode === "advanced PR") {
570
+ assert.equal(comments.length, 1, "C asks even after its associated PR advances to D");
571
+ assert.deepEqual(warnings, []);
572
+ }
573
+ failAsk = false;
574
+ record(mode === "retry next head" ? 4 : 3, mode === "retry next head" ? "ddddddd" : "ccccccc");
575
+ if (mode === "old PR") {
576
+ assert.equal(comments.length, 0);
577
+ assert.ok(warnings.every((s) => /no linked issue/.test(s)), warnings.join("\n"));
578
+ } else {
579
+ assert.equal(comments.length, 1, mode);
580
+ record(5, "eeeeeee");
581
+ assert.equal(comments.length, 1, "successful question deduplicates later heads");
582
+ }
583
+ }
584
+ for (const body of ["Fixes #12", "closed #13", "Resolves local/repo#14", "Refs #15", "Mentions #16", "Closes foreign/repo#17"]) {
585
+ const root = fixture(t);
586
+ const calls = [];
587
+ const warnings = [];
588
+ const gh = (args) => {
589
+ calls.push(args);
590
+ if (args[0] === "run") return tap;
591
+ if (args[1] === "repos/local/repo/commits/ccccccc/pulls") return JSON.stringify([{ body, state: "open", head: { ref: "feature-without-number", repo: { full_name: "local/repo" }, sha: "ccccccc" } }]);
592
+ return "[]";
593
+ };
594
+ for (const [id, head] of [[1, "aaaaaaa"], [2, "bbbbbbb"], [3, "ccccccc"]]) recordRun(root, { id, branch: "feature-without-number", head }, { gh, warn: (line) => warnings.push(line) });
595
+ const question = calls.find((args) => args[0] === "issue" && args[1] === "comment");
596
+ if (/Mentions|foreign/.test(body)) {
597
+ assert.equal(question, undefined);
598
+ assert.equal(warnings.length, 1);
599
+ assert.doesNotMatch(warnings[0], /\n/);
600
+ } else {
601
+ assert.equal(question?.[2], /#(\d+)/.exec(body)[1]);
602
+ assert.equal(warnings.length, 0);
603
+ assert.ok(calls.filter((args) => args[0] !== "run").every((args) => args[0] === "api" ? args[1].includes("local/repo") : args[args.indexOf("-R") + 1] === "local/repo"));
604
+ }
605
+ assert.equal(holdRefusal(root, "feature-without-number"), null);
606
+ }
607
+ const root = fixture(t);
608
+ const warnings = [];
609
+ for (const [id, head] of [[1, "aaaaaaa"], [2, "bbbbbbb"], [3, "ccccccc"]]) recordRun(root, { id, branch: "main", head }, {
610
+ gh: (args) => { if (args[0] === "run") return tap; throw new Error("offline\nprivate details"); }, warn: (line) => warnings.push(line),
611
+ });
612
+ assert.deepEqual(warnings, ["ci-failures: gh failed: offline"]);
613
+ assert.equal(openFailures(root, "main").length, 3);
614
+ assert.equal(holdRefusal(root, "main"), null);
615
+ });
@@ -0,0 +1,62 @@
1
+ // A pipeline reserves platform previews, dispatches CI, and records passing legs.
2
+ import { execFileSync } from "node:child_process";
3
+ import { closeSync, mkdirSync, openSync, unlinkSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { appendLeg, gitText, legRecords } from "./legs.mjs";
6
+ import { ledgerFileOf } from "./ledger.mjs";
7
+
8
+ const ghCommand = (root, args) => execFileSync("gh", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 16 * 1024 * 1024 });
9
+ const platforms = (value) => value === "both" ? ["linux", "windows"] : [value];
10
+ const jobOS = (name) => /windows/i.test(name) ? "windows" : /linux|ubuntu/i.test(name) ? "linux" : null;
11
+
12
+ export async function runCiPreview(root, args = [], options = {}) {
13
+ const write = options.write ?? console.error;
14
+ const os = args.length === 0 ? "both" : args.length === 2 && args[0] === "--os" ? args[1] : null;
15
+ if (!["linux", "windows", "both"].includes(os)) { write("ci-preview: use --os linux, windows, or both"); return 1; }
16
+ const git = options.git ?? ((...words) => gitText(root, ...words));
17
+ const gh = options.gh ?? ((words) => ghCommand(root, words));
18
+ const records = options.records ?? (() => legRecords(root));
19
+ const record = options.record ?? appendLeg;
20
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
21
+ let lock;
22
+ let fd;
23
+ try {
24
+ const head = git("rev-parse", "HEAD");
25
+ const branch = git("branch", "--show-current");
26
+ if (!branch) throw new Error("a preview needs a branch");
27
+ const file = ledgerFileOf(root);
28
+ if (!file) throw new Error("a preview needs a git worktree");
29
+ mkdirSync(path.dirname(file), { recursive: true });
30
+ lock = `${file}.preview-lock`;
31
+ fd = openSync(lock, "wx");
32
+ const wanted = platforms(os);
33
+ const previous = records();
34
+ if (wanted.some((leg) => previous.some((r) => r.head === head && r.os === leg && r.source === "preview"))) throw new Error("a preview already exists for this head and platform");
35
+ const listArgs = ["run", "list", "--workflow", "ci.yml", "--event", "workflow_dispatch", "--branch", branch, "--commit", head, "--limit", "100", "--json", "databaseId,headSha"];
36
+ const before = new Set(JSON.parse(gh(listArgs)).map((run) => run.databaseId));
37
+ for (const leg of wanted) record(root, { type: "leg-preview", os: leg, head, source: "preview" });
38
+ gh(["workflow", "run", "ci.yml", "--ref", branch, "-f", `os=${os}`]);
39
+ let run;
40
+ for (let attempt = 0; attempt < (options.attempts ?? 30); attempt += 1) {
41
+ const candidates = JSON.parse(gh(listArgs)).filter((r) => r.headSha === head && !before.has(r.databaseId));
42
+ if (candidates.length > 1) throw new Error("multiple new preview runs match this head");
43
+ if (candidates.length === 1) { run = candidates[0]; break; }
44
+ await sleep(2000);
45
+ }
46
+ if (!run) throw new Error("the dispatched preview run did not appear");
47
+ gh(["run", "watch", String(run.databaseId)]);
48
+ const result = JSON.parse(gh(["run", "view", String(run.databaseId), "--json", "headSha,jobs"]));
49
+ if (result.headSha !== head) throw new Error("preview run head differs from the requested head");
50
+ let passed = 0;
51
+ for (const leg of wanted) {
52
+ const jobs = result.jobs.filter((job) => jobOS(job.name) === leg);
53
+ if (jobs.length > 0 && jobs.every((job) => job.conclusion === "success")) {
54
+ record(root, { type: "leg", os: leg, head, source: "preview" });
55
+ passed += 1;
56
+ }
57
+ }
58
+ if (passed !== wanted.length) { write("ci-preview: one or more requested platform legs failed or are missing"); return 1; }
59
+ return 0;
60
+ } catch (error) { write(`ci-preview: ${error.message.split("\n")[0]}`); return 1; }
61
+ finally { if (fd !== undefined) { closeSync(fd); unlinkSync(lock); } }
62
+ }
@@ -0,0 +1,85 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, mkdirSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { runCiPreview } from "./ci-preview.mjs";
7
+
8
+ function fixture(t, jobs = [{ name: 'test (ubuntu-latest)', conclusion: 'success' }, { name: 'test (windows-latest)', conclusion: 'success' }]) {
9
+ const root = mkdtempSync(path.join(tmpdir(), 'qc-preview-'));
10
+ mkdirSync(path.join(root, '.git'));
11
+ t.after(() => rmSync(root, { recursive: true, force: true }));
12
+ const calls = [], records = [];
13
+ let lists = 0;
14
+ const options = {
15
+ git: (...args) => args[0] === 'branch' ? 'feat/test' : 'abc123',
16
+ gh: (args) => {
17
+ calls.push(args);
18
+ if (args[0] === 'workflow') return '';
19
+ if (args[1] === 'list') return lists++ === 0 ? '[]' : JSON.stringify([{ databaseId: 7, headSha: 'abc123' }]);
20
+ if (args[1] === 'view') return JSON.stringify({ headSha: 'abc123', jobs });
21
+ return '';
22
+ },
23
+ records: () => records,
24
+ record: (_root, record) => records.push(record),
25
+ sleep: async () => {}, attempts: 2, write: () => {},
26
+ };
27
+ return { root, options, calls, records };
28
+ }
29
+ test('dispatches both, waits, and records each passing leg once', async (t) => {
30
+ const { root, options, calls, records } = fixture(t);
31
+ assert.equal(await runCiPreview(root, ['--os', 'both'], options), 0);
32
+ assert.deepEqual(calls[1], ['workflow', 'run', 'ci.yml', '--ref', 'feat/test', '-f', 'os=both']);
33
+ assert.ok(calls.some((args) => args[1] === 'watch' && args.includes('7')));
34
+ assert.deepEqual(records.filter((r) => r.type === 'leg').map((r) => r.os), ['linux', 'windows']);
35
+ assert.equal(await runCiPreview(root, ['--os', 'windows'], options), 1);
36
+ assert.equal(calls.filter((args) => args[0] === 'workflow').length, 1);
37
+ });
38
+ test('records only the successful platform when another fails', async (t) => {
39
+ const { root, options, records } = fixture(t, [{ name: 'linux', conclusion: 'success' }, { name: 'windows', conclusion: 'failure' }]);
40
+ assert.equal(await runCiPreview(root, ['--os', 'both'], options), 1);
41
+ assert.deepEqual(records.filter((r) => r.type === 'leg').map((r) => r.os), ['linux']);
42
+ });
43
+ test('refuses invalid input and detached heads before dispatch', async (t) => {
44
+ const { root, options, calls } = fixture(t);
45
+ assert.equal(await runCiPreview(root, ['--os', 'mac'], options), 1);
46
+ options.git = (...args) => args[0] === 'branch' ? '' : 'head';
47
+ assert.equal(await runCiPreview(root, [], options), 1);
48
+ assert.deepEqual(calls, []);
49
+ });
50
+ test('does not credit a stale run or missing platform jobs', async (t) => {
51
+ const { root, options, records } = fixture(t, []);
52
+ assert.equal(await runCiPreview(root, ['--os', 'linux'], options), 1);
53
+ assert.equal(records.filter((r) => r.type === 'leg').length, 0);
54
+ });
55
+ test('a lookup failure dispatches nothing and reserves nothing', async (t) => {
56
+ const { root, options, records } = fixture(t);
57
+ options.gh = () => { throw new Error('offline'); };
58
+ assert.equal(await runCiPreview(root, [], options), 1);
59
+ assert.deepEqual(records, []);
60
+ });
61
+ test('dispatch failure retains the reservation and prevents a second preview', async (t) => {
62
+ const { root, options, records } = fixture(t);
63
+ const original = options.gh;
64
+ options.gh = (args) => { if (args[0] === 'workflow') throw new Error('offline'); return original(args); };
65
+ assert.equal(await runCiPreview(root, ['--os', 'linux'], options), 1);
66
+ assert.equal(records[0].type, 'leg-preview');
67
+ assert.equal(await runCiPreview(root, ['--os', 'linux'], options), 1);
68
+ assert.equal(records.length, 1);
69
+ });
70
+ test('rejects stale head results and times out when no new run appears', async (t) => {
71
+ const { root, options, records } = fixture(t);
72
+ const original = options.gh;
73
+ options.gh = (args) => args[1] === 'view' ? JSON.stringify({ headSha: 'stale', jobs: [] }) : original(args);
74
+ assert.equal(await runCiPreview(root, ['--os', 'linux'], options), 1);
75
+ assert.equal(records.filter((r) => r.type === 'leg').length, 0);
76
+ options.git = (...args) => args[0] === 'branch' ? 'feat/test' : 'new-head';
77
+ options.gh = () => '[]';
78
+ assert.equal(await runCiPreview(root, ['--os', 'linux'], options), 1);
79
+ assert.equal(records.filter((r) => r.type === 'leg').length, 0);
80
+ });
81
+ test('a failed job prevents credit even when another job for that platform passes', async (t) => {
82
+ const { root, options, records } = fixture(t, [{ name: 'linux unit', conclusion: 'success' }, { name: 'linux integration', conclusion: 'failure' }]);
83
+ assert.equal(await runCiPreview(root, ['--os', 'linux'], options), 1);
84
+ assert.equal(records.filter((r) => r.type === 'leg').length, 0);
85
+ });
@@ -23,12 +23,12 @@ export function ciState(sha, cwd, { gh = runGh, origin = originOf, requiredCheck
23
23
  if (typeof sha !== "string" || sha === "") return unknown("there is no commit to ask about");
24
24
  const repo = origin(cwd, ORIGIN_TIMEOUT_MS);
25
25
  if (repo === null) return unknown("the checkout has no readable origin");
26
- const out = gh(["api", `repos/${repo}/commits/${sha}/check-runs?per_page=100&filter=all`, "--paginate", "--slurp"], { cwd, timeoutMs: GH_TIMEOUT_MS });
26
+ const out = gh(["api", `repos/${repo}/commits/${sha}/check-runs?per_page=100&filter=all`, "--paginate"], { cwd, timeoutMs: GH_TIMEOUT_MS });
27
27
  if (out === null) return unknown("gh failed or timed out");
28
28
  const runs = parseApiList(out, "check_runs");
29
29
  if (runs === null) return unknown("gh answered with no readable check_runs list");
30
30
  let state = checkRunsState(runs, { requiredChecks });
31
- const workflows = gh(["api", `repos/${repo}/actions/runs?head_sha=${encodeURIComponent(sha)}&per_page=100`, "--paginate", "--slurp"], { cwd, timeoutMs: GH_TIMEOUT_MS });
31
+ const workflows = gh(["api", `repos/${repo}/actions/runs?head_sha=${encodeURIComponent(sha)}&per_page=100`, "--paginate"], { cwd, timeoutMs: GH_TIMEOUT_MS });
32
32
  const workflowRuns = parseApiList(workflows, "workflow_runs");
33
33
  if (workflowRuns === null && state.reason === null) return unknown("gh answered with no readable workflow_runs list");
34
34
  if (workflowRuns !== null) state = checkRunsState(runs, {
@@ -9,7 +9,7 @@ const SHA = "a".repeat(40);
9
9
  const run = (name, status, conclusion = null) => ({ name, status, conclusion });
10
10
  const reply = (...runs) => JSON.stringify({ total_count: runs.length, check_runs: runs, workflow_runs: [] });
11
11
 
12
- const ciGh = (checks, workflows) => (args) => args[1].includes("/actions/runs") ? JSON.stringify(workflows) : reply(...checks);
12
+ const ciGh = (checks, workflows) => (args) => args[1].includes("/actions/runs") ? (Array.isArray(workflows) ? workflows : [workflows]).map(page => JSON.stringify(page)).join("\n") : reply(...checks);
13
13
 
14
14
  test("unfinished workflows on the head are pending before checks exist and after checks pass", () => {
15
15
  for (const status of ["queued", "in_progress", "waiting", "pending", "requested"]) {
@@ -22,7 +22,7 @@ test("unfinished workflows on the head are pending before checks exist and after
22
22
  assert.equal(state.unknown, null);
23
23
  assert.equal(state.reason, `CI on aaaaaaa: CI is ${status}`);
24
24
  assert.ok(calls[1].args.includes("--paginate"));
25
- assert.ok(calls[1].args.includes("--slurp"));
25
+ assert.ok(!calls[1].args.includes("--slurp"));
26
26
  assert.equal(calls[1].args[1], `repos/o/r/actions/runs?head_sha=${SHA}&per_page=100`);
27
27
  assert.ok(calls[0].options.timeoutMs + calls[1].options.timeoutMs + 1000 < 10000);
28
28
  }
@@ -45,14 +45,14 @@ test("a failed check wins over queued workflows and missing required checks", ()
45
45
  });
46
46
 
47
47
  test("unreadable workflow lists keep a green-looking head unknown", () => {
48
- for (const answer of [null, "not JSON", "{}", '[{"workflow_runs":[]},{}]']) {
48
+ for (const answer of [null, "not JSON", "{}", '{"workflow_runs":[]}\n{}']) {
49
49
  const gh = (args) => args[1].includes("/actions/runs") ? answer : reply(run("lint", "completed", "success"));
50
50
  assert.match(ciState(SHA, "/c", { gh, origin: () => "o/r" }).unknown ?? "", /gh/);
51
51
  }
52
52
  });
53
53
 
54
54
  test("unreadable workflows preserve pending and failed checks", () => {
55
- for (const answer of [null, "not JSON", "{}", '[{"workflow_runs":[]},{}]']) {
55
+ for (const answer of [null, "not JSON", "{}", '{"workflow_runs":[]}\n{}']) {
56
56
  for (const [status, conclusion] of [["in_progress", null], ["completed", "failure"]]) {
57
57
  const gh = (args) => args[1].includes("/actions/runs") ? answer : reply(run("build", status, conclusion));
58
58
  assert.deepEqual(ciState(SHA, "/c", { gh, origin: () => "o/r" }), {
@@ -75,7 +75,7 @@ test("workflow paths let a newer suite supersede a cancelled suite", () => {
75
75
 
76
76
  test("ciState uses caller-required checks and ignores invalid checkout configuration", (t) => {
77
77
  const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-ci-required-"));
78
- t.after(() => rmSync(cwd, { recursive: true, force: true }));
78
+ t.after(() => rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
79
79
  writeFileSync(path.join(cwd, "qc.config.json"), JSON.stringify({ ci: null }));
80
80
  for (const checks of [[], [run("lint", "completed", "success")]]) {
81
81
  const state = ciState(SHA, cwd, { gh: ciGh(checks, [{ workflow_runs: [] }]), origin: () => "o/r", requiredChecks: ["build"] });
@@ -96,14 +96,14 @@ test("ciState reads every check-run page", () => {
96
96
  const calls = [];
97
97
  const gh = (args) => {
98
98
  calls.push(args);
99
- return JSON.stringify([
99
+ return [
100
100
  { check_runs: [run("lint", "completed", "success")] },
101
101
  { check_runs: [run("build", "completed", "failure")] },
102
- ]);
102
+ ].map(page => JSON.stringify(page)).join("\n");
103
103
  };
104
104
  assert.equal(ciState(SHA, "/c", { gh, origin: () => "o/r" }).reason, "CI on aaaaaaa: build ended failure");
105
105
  assert.ok(calls[0].includes("--paginate"));
106
- assert.ok(calls[0].includes("--slurp"));
106
+ assert.ok(!calls[0].includes("--slurp"));
107
107
  assert.match(calls[0][1], /[?&]filter=all(?:&|$)/);
108
108
  });
109
109
 
@@ -12,9 +12,45 @@ test("the template runs on pull requests and trunk pushes, and cancels stale pul
12
12
  assert.ok(Object.hasOwn(workflow.on, "pull_request"));
13
13
  assert.deepEqual(workflow.on.push.branches, ["main", "master"]);
14
14
  assert.ok(workflow.concurrency.group.includes("github.event.pull_request.number"));
15
- assert.equal(workflow.concurrency["cancel-in-progress"], "${{ github.event_name == 'pull_request' }}");
15
+ assert.equal(workflow.concurrency["cancel-in-progress"], "${{ github.event_name != 'merge_group' }}");
16
16
  });
17
17
 
18
+ const KIT_WORKFLOW = fileURLToPath(new URL("../../../../.github/workflows/ci.yml", import.meta.url));
19
+
20
+ for (const [name, file] of [["template", WORKFLOW], ["kit", KIT_WORKFLOW]]) {
21
+ test(`${name} skips drafts and starts CI when a draft becomes ready`, () => {
22
+ const workflow = parse(readFileSync(file, "utf8"));
23
+ assert.deepEqual(workflow.on.push.branches, name === "template" ? ["main", "master"] : ["main"]);
24
+ assert.deepEqual(workflow.on.pull_request.types, ["opened", "synchronize", "reopened", "ready_for_review"]);
25
+ assert.equal(workflow.jobs.gates.if, "${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }}");
26
+ assert.ok(workflow.concurrency.group.includes("github.event.pull_request.number"));
27
+ assert.ok(workflow.concurrency.group.includes("github.event_name"));
28
+ assert.equal(workflow.concurrency["cancel-in-progress"], "${{ github.event_name != 'merge_group' }}");
29
+ assert.ok(Object.hasOwn(workflow.on, "merge_group"));
30
+ });
31
+
32
+ test(`${name} dispatch chooses Linux, Windows, or both matrix legs`, () => {
33
+ const workflow = parse(readFileSync(file, "utf8"));
34
+ const input = workflow.on.workflow_dispatch.inputs.os;
35
+ assert.equal(input.type, "choice");
36
+ assert.equal(input.required, true);
37
+ assert.equal(input.default, "both");
38
+ assert.deepEqual(input.options, ["linux", "windows", "both"]);
39
+ assert.equal(workflow.jobs.gates["runs-on"], "${{ matrix.os }}");
40
+ assert.equal(workflow.jobs.gates.defaults.run.shell, "bash");
41
+ const matrix = workflow.jobs.gates.strategy.matrix.os;
42
+ const expression = matrix.slice(3, -2).trim().replace(/fromJSON/g, "JSON.parse");
43
+ const evaluate = (event, os) => Function("github", "inputs", `return (${expression})`)({ event_name: event }, { os });
44
+ assert.deepEqual(evaluate("workflow_dispatch", "linux"), ["ubuntu-latest"]);
45
+ assert.deepEqual(evaluate("workflow_dispatch", "windows"), ["windows-latest"]);
46
+ assert.deepEqual(evaluate("workflow_dispatch", "both"), ["ubuntu-latest", "windows-latest"]);
47
+ const normal = ["ubuntu-latest", "windows-latest"];
48
+ assert.deepEqual(evaluate("pull_request", ""), normal);
49
+ assert.deepEqual(evaluate("push", ""), normal);
50
+ assert.deepEqual(evaluate("merge_group", ""), normal);
51
+ });
52
+ }
53
+
18
54
  test("the template installs with the package manager of the lockfile, so no one tool is assumed", () => {
19
55
  const text = runs();
20
56
  assert.match(text, /pnpm-lock\.yaml.*pnpm install --frozen-lockfile/);
@@ -36,3 +72,45 @@ test("the policy checks of a pull request are opt-in, not steps of the template"
36
72
  assert.doesNotMatch(text, /qc pr-check|qc prose/);
37
73
  assert.doesNotMatch(readFileSync(WORKFLOW, "utf8"), /^\s*# - run:/m);
38
74
  });
75
+
76
+
77
+ test("the CI template runs --affected on pull_request and pnpm test on push to main and on schedule", async () => {
78
+ for (const file of [WORKFLOW, KIT_WORKFLOW]) {
79
+ const workflow = parse(readFileSync(file, "utf8"));
80
+ assert.deepEqual(workflow.on.schedule, [{ cron: "0 2 * * *" }]);
81
+ assert.deepEqual(workflow.permissions, { contents: "read" });
82
+ const steps = workflow.jobs.gates.steps;
83
+ if (file === KIT_WORKFLOW) {
84
+ assert.doesNotMatch(readFileSync(file, "utf8"), /\bnpx\s+qc\b/);
85
+ }
86
+ const affected = steps.find((step) => /check --affected --base origin\/main/.test(step.run ?? ""));
87
+ assert.equal(affected.if, "github.event_name == 'pull_request'");
88
+ const full = steps.find((step) => /pnpm test|run test/.test(step.run ?? ""));
89
+ assert.equal(full.if, "github.event_name != 'pull_request'");
90
+ const job = workflow.jobs['report-failure'];
91
+ assert.equal(job.needs, 'gates');
92
+ assert.deepEqual(job.concurrency, { group: 'ci-red-${{ github.sha }}', 'cancel-in-progress': false });
93
+ assert.equal(job.if, "${{ always() && needs.gates.result == 'failure' && ((github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'schedule') }}");
94
+ assert.equal(job.permissions.issues, 'write');
95
+ assert.equal(workflow.jobs.gates.permissions?.issues, undefined);
96
+ const script = job.steps.find((step) => step.uses?.startsWith('actions/github-script@')).with.script;
97
+ const calls = [], issues = [];
98
+ const github = { rest: { issues: {
99
+ async createLabel(args) { calls.push(args); },
100
+ async listForRepo() { return { data: issues }; },
101
+ async create(args) { calls.push(args); issues.push({ title: args.title }); },
102
+ } }, async paginate(fn, args) { return (await fn(args)).data; } };
103
+ const context = { repo: { owner: 'owner', repo: 'repo' }, sha: 'abc123', serverUrl: 'https://github.com', runId: 42 };
104
+ const run = new (Object.getPrototypeOf(async function() {}).constructor)('github', 'context', script);
105
+ await run(github, context); await run(github, context);
106
+ const created = calls.filter((args) => args.body);
107
+ assert.equal(created.length, 1);
108
+ assert.deepEqual(created[0].labels, ['ci-red', 'priority']);
109
+ assert.match(created[0].body, /abc123/);
110
+ assert.match(created[0].body, /https:\/\/github.com\/owner\/repo\/actions\/runs\/42/);
111
+ github.rest.issues.createLabel = async () => { throw Object.assign(Error('exists'), { status: 422 }); };
112
+ await run(github, context); assert.equal(calls.filter((args) => args.body).length, 1);
113
+ github.rest.issues.createLabel = async () => { throw Object.assign(Error('denied'), { status: 403 }); };
114
+ await assert.rejects(run(github, context), /denied/);
115
+ }
116
+ });