architecture-harness 0.25.0 → 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 (244) hide show
  1. package/package.json +3 -22
  2. package/src/cli/ask.mjs +42 -0
  3. package/src/cli/ask.test.mjs +40 -0
  4. package/src/cli/branch-sync.mjs +126 -0
  5. package/src/cli/branch-sync.test.mjs +428 -0
  6. package/src/cli/budget-guard.mjs +74 -5
  7. package/src/cli/budget-guard.test.mjs +185 -2
  8. package/src/cli/budget-report.mjs +85 -0
  9. package/src/cli/budget-report.test.mjs +173 -0
  10. package/src/cli/budget.mjs +8 -5
  11. package/src/cli/check-commands.mjs +123 -11
  12. package/src/cli/check-commands.test.mjs +360 -6
  13. package/src/cli/check-feature-switches.test.mjs +110 -0
  14. package/src/cli/check-full.test.mjs +152 -0
  15. package/src/cli/check-verdict.mjs +46 -0
  16. package/src/cli/check-verdict.test.mjs +32 -0
  17. package/src/cli/check.mjs +137 -4
  18. package/src/cli/check.test.mjs +45 -0
  19. package/src/cli/checkpoint.mjs +143 -0
  20. package/src/cli/checkpoint.test.mjs +146 -0
  21. package/src/cli/child-run.mjs +7 -2
  22. package/src/cli/child-run.test.mjs +17 -2
  23. package/src/cli/ci-failures.mjs +304 -0
  24. package/src/cli/ci-failures.test.mjs +615 -0
  25. package/src/cli/ci-preview.mjs +62 -0
  26. package/src/cli/ci-preview.test.mjs +85 -0
  27. package/src/cli/ci-state.mjs +25 -29
  28. package/src/cli/ci-state.test.mjs +174 -2
  29. package/src/cli/ci-template.test.mjs +86 -0
  30. package/src/cli/claude-core.test.mjs +37 -0
  31. package/src/cli/codex-implement.mjs +580 -47
  32. package/src/cli/codex-implement.test.mjs +1946 -29
  33. package/src/cli/codex-limit.mjs +85 -0
  34. package/src/cli/codex-limit.test.mjs +179 -0
  35. package/src/cli/codex-reset.mjs +78 -0
  36. package/src/cli/codex-reset.test.mjs +192 -0
  37. package/src/cli/codex-verify.mjs +230 -0
  38. package/src/cli/codex-verify.test.mjs +402 -0
  39. package/src/cli/comment-watch.mjs +391 -0
  40. package/src/cli/comment-watch.test.mjs +392 -0
  41. package/src/cli/commit-guard.mjs +219 -0
  42. package/src/cli/commit-guard.test.mjs +809 -0
  43. package/src/cli/context-budgets.mjs +47 -0
  44. package/src/cli/context-budgets.test.mjs +96 -0
  45. package/src/cli/context-watch.mjs +116 -0
  46. package/src/cli/context-watch.test.mjs +395 -0
  47. package/src/cli/contract-history.mjs +1 -1
  48. package/src/cli/controller-guard.mjs +38 -0
  49. package/src/cli/controller-guard.test.mjs +66 -2
  50. package/src/cli/cost-stop.mjs +5 -1
  51. package/src/cli/cost-stop.test.mjs +26 -0
  52. package/src/cli/diff-shape.mjs +162 -0
  53. package/src/cli/diff-shape.test.mjs +200 -0
  54. package/src/cli/direct-lane.mjs +32 -19
  55. package/src/cli/direct-lane.test.mjs +21 -3
  56. package/src/cli/dispatch-guard.mjs +11 -0
  57. package/src/cli/dispatch-guard.test.mjs +145 -10
  58. package/src/cli/dispatch-reminder.mjs +23 -10
  59. package/src/cli/dispatch-reminder.test.mjs +63 -11
  60. package/src/cli/dispatch-route.mjs +54 -0
  61. package/src/cli/dispatch-route.test.mjs +101 -0
  62. package/src/cli/dispatch-slot.mjs +2 -2
  63. package/src/cli/dispatch-slot.test.mjs +18 -19
  64. package/src/cli/dispatch.test.mjs +3 -3
  65. package/src/cli/e2e-affected.mjs +15 -0
  66. package/src/cli/e2e-affected.test.mjs +73 -0
  67. package/src/cli/fleet.mjs +180 -0
  68. package/src/cli/fleet.test.mjs +213 -0
  69. package/src/cli/gate-slot.mjs +2 -1
  70. package/src/cli/gh-merge-command.mjs +96 -31
  71. package/src/cli/gh-merge-command.test.mjs +74 -0
  72. package/src/cli/gh-run.mjs +64 -3
  73. package/src/cli/gh-run.test.mjs +66 -1
  74. package/src/cli/git-hooks.test.mjs +25 -3
  75. package/src/cli/git-read.mjs +2 -1
  76. package/src/cli/integrate-tree.mjs +47 -0
  77. package/src/cli/integrate.mjs +143 -40
  78. package/src/cli/integrate.test.mjs +347 -1
  79. package/src/cli/integration-lane.mjs +62 -0
  80. package/src/cli/integration-lane.test.mjs +213 -0
  81. package/src/cli/ledger.mjs +4 -2
  82. package/src/cli/ledger.test.mjs +12 -3
  83. package/src/cli/legs.mjs +53 -0
  84. package/src/cli/legs.test.mjs +70 -0
  85. package/src/cli/lint-changed.mjs +59 -10
  86. package/src/cli/lint-changed.test.mjs +112 -1
  87. package/src/cli/locked-tests.mjs +134 -0
  88. package/src/cli/locked-tests.test.mjs +188 -0
  89. package/src/cli/merge-guard.mjs +234 -62
  90. package/src/cli/merge-guard.test.mjs +768 -39
  91. package/src/cli/metrics.mjs +53 -0
  92. package/src/cli/metrics.test.mjs +73 -0
  93. package/src/cli/milestone.mjs +297 -0
  94. package/src/cli/milestone.test.mjs +294 -0
  95. package/src/cli/mutate.mjs +203 -0
  96. package/src/cli/mutate.test.mjs +134 -0
  97. package/src/cli/output-redaction.mjs +26 -0
  98. package/src/cli/output-redaction.test.mjs +117 -0
  99. package/src/cli/overview.mjs +131 -0
  100. package/src/cli/overview.test.mjs +137 -0
  101. package/src/cli/pause.mjs +93 -0
  102. package/src/cli/pause.test.mjs +109 -0
  103. package/src/cli/plan-check.mjs +84 -12
  104. package/src/cli/plan-check.test.mjs +152 -2
  105. package/src/cli/plan-stop.mjs +7 -4
  106. package/src/cli/plan-stop.test.mjs +87 -0
  107. package/src/cli/platform-risk.mjs +46 -0
  108. package/src/cli/platform-risk.test.mjs +38 -0
  109. package/src/cli/plugin-skills.test.mjs +25 -0
  110. package/src/cli/pr-guard.mjs +128 -0
  111. package/src/cli/pr-guard.test.mjs +154 -0
  112. package/src/cli/promotion-branch.mjs +2 -0
  113. package/src/cli/qc.mjs +160 -27
  114. package/src/cli/qc.test.mjs +93 -0
  115. package/src/cli/report-stop.mjs +5 -0
  116. package/src/cli/report-stop.test.mjs +23 -1
  117. package/src/cli/retry-failed.mjs +3 -1
  118. package/src/cli/review-gate.mjs +24 -6
  119. package/src/cli/review-gate.test.mjs +116 -0
  120. package/src/cli/review-promotion.mjs +107 -0
  121. package/src/cli/review-promotion.test.mjs +251 -0
  122. package/src/cli/role-budget.mjs +50 -0
  123. package/src/cli/role-budget.test.mjs +91 -0
  124. package/src/cli/run-log.mjs +73 -0
  125. package/src/cli/run-log.test.mjs +121 -0
  126. package/src/cli/secret-patterns.mjs +16 -0
  127. package/src/cli/secret-patterns.test.mjs +73 -0
  128. package/src/cli/setup-block.mjs +24 -0
  129. package/src/cli/setup-block.test.mjs +96 -0
  130. package/src/cli/setup-checks.mjs +65 -0
  131. package/src/cli/setup-checks.test.mjs +158 -0
  132. package/src/cli/setup-compaction.mjs +55 -0
  133. package/src/cli/setup-compaction.test.mjs +115 -0
  134. package/src/cli/setup-skills.mjs +65 -0
  135. package/src/cli/setup-skills.test.mjs +171 -0
  136. package/src/cli/setup.mjs +107 -0
  137. package/src/cli/setup.test.mjs +275 -0
  138. package/src/cli/skill-length.test.mjs +8 -0
  139. package/src/cli/spawn-command.mjs +47 -0
  140. package/src/cli/spawn-command.test.mjs +64 -0
  141. package/src/cli/task-gate-review.test.mjs +21 -2
  142. package/src/cli/task-gate.mjs +25 -12
  143. package/src/cli/task-gate.test.mjs +43 -5
  144. package/src/cli/tokens.mjs +46 -3
  145. package/src/cli/tokens.test.mjs +103 -3
  146. package/src/cli/tools.mjs +49 -0
  147. package/src/cli/tools.test.mjs +89 -0
  148. package/src/cli/transcript-usage.mjs +27 -0
  149. package/src/cli/transcript-usage.test.mjs +34 -0
  150. package/src/cli/user-config-package.mjs +1 -1
  151. package/src/cli/user-config-toml.mjs +63 -7
  152. package/src/cli/user-config.mjs +39 -7
  153. package/src/cli/user-config.test.mjs +238 -5
  154. package/src/cli/watch-arm.mjs +39 -0
  155. package/src/cli/watch-arm.test.mjs +87 -0
  156. package/src/cli/watch.mjs +80 -35
  157. package/src/cli/watch.test.mjs +233 -27
  158. package/src/cli/work-order-guard.mjs +2 -1
  159. package/src/cli/workflow-hooks.test.mjs +18 -4
  160. package/src/cli/workflow-settings.mjs +44 -8
  161. package/src/cli/workflow-settings.test.mjs +124 -1
  162. package/src/cli/worktree.mjs +14 -1
  163. package/src/cli/worktree.test.mjs +20 -1
  164. package/src/config.mjs +174 -7
  165. package/src/config.test.mjs +327 -5
  166. package/src/consumer-package.mjs +31 -0
  167. package/src/consumer-package.test.mjs +54 -0
  168. package/src/descriptions.mjs +2 -0
  169. package/src/eslint/index.mjs +12 -0
  170. package/src/eslint/jsx.mjs +20 -0
  171. package/src/eslint/preset.mjs +26 -2
  172. package/src/eslint/preset.test.mjs +104 -2
  173. package/src/eslint/rules/no-arbitrary-class-value.mjs +32 -0
  174. package/src/eslint/rules/no-literal-color.mjs +94 -0
  175. package/src/eslint/rules/no-static-inline-style.mjs +41 -0
  176. package/src/eslint/rules/one-component-per-file.mjs +70 -0
  177. package/src/eslint/rules/raw-element-in-primitive.mjs +31 -0
  178. package/src/eslint/rules/timeless-comment.mjs +92 -0
  179. package/src/eslint/rules.test.mjs +189 -0
  180. package/src/eslint/ui-regressions.test.mjs +39 -0
  181. package/src/gates/contract-operations.mjs +3 -3
  182. package/src/gates/contract-operations.test.mjs +28 -0
  183. package/src/gates/feature-switches.mjs +19 -0
  184. package/src/gates/feature-switches.test.mjs +55 -0
  185. package/src/gates/plain-language.mjs +396 -0
  186. package/src/gates/plain-language.test.mjs +210 -0
  187. package/src/gates/runtime-imports.test.mjs +114 -0
  188. package/src/gates/saga-key.test.mjs +1 -1
  189. package/src/global-skills.mjs +9 -0
  190. package/src/global-skills.test.mjs +53 -0
  191. package/src/plugin.test.mjs +3 -2
  192. package/src/ui/class-sites.mjs +38 -6
  193. package/src/ui/codemod.mjs +4 -1
  194. package/src/ui/codemod.test.mjs +52 -0
  195. package/src/ui/components.mjs +5 -3
  196. package/src/ui/components.test.mjs +8 -0
  197. package/src/ui/dupes.test.mjs +18 -0
  198. package/templates/docs/enforcement.md +12 -2
  199. package/templates/docs/ui.md +33 -0
  200. package/templates/githooks/pre-commit +1 -0
  201. package/templates/githooks/pre-push +11 -2
  202. package/templates/github/workflows/ci.yml +57 -3
  203. package/user-config/claude/CLAUDE.core.md +28 -0
  204. package/user-config/claude/settings.shared.json +41 -1
  205. package/src/cli/screens-discovery.mjs +0 -60
  206. package/src/cli/screens.mjs +0 -84
  207. package/src/cli/stack.mjs +0 -14
  208. package/src/cli/throwaway-db.mjs +0 -127
  209. package/src/cli/throwaway-db.test.mjs +0 -83
  210. package/src/screens/auth-context.test.mjs +0 -41
  211. package/src/screens/auth-run.test.mjs +0 -147
  212. package/src/screens/auth.mjs +0 -223
  213. package/src/screens/auth.test.mjs +0 -76
  214. package/src/screens/capture-idle.test.mjs +0 -27
  215. package/src/screens/capture.browser-test.mjs +0 -73
  216. package/src/screens/capture.mjs +0 -175
  217. package/src/screens/capture.test.mjs +0 -28
  218. package/src/screens/catalog.browser-test.mjs +0 -32
  219. package/src/screens/catalog.mjs +0 -72
  220. package/src/screens/catalog.test.mjs +0 -36
  221. package/src/screens/chrome.mjs +0 -21
  222. package/src/screens/compare.mjs +0 -40
  223. package/src/screens/compare.test.mjs +0 -30
  224. package/src/screens/discovery.browser-test.mjs +0 -29
  225. package/src/screens/discovery.mjs +0 -158
  226. package/src/screens/discovery.test.mjs +0 -27
  227. package/src/screens/inventory.mjs +0 -69
  228. package/src/screens/inventory.test.mjs +0 -10
  229. package/src/screens/map.mjs +0 -63
  230. package/src/screens/map.test.mjs +0 -35
  231. package/src/screens/open.browser-test.mjs +0 -50
  232. package/src/screens/regions.mjs +0 -137
  233. package/src/screens/regions.test.mjs +0 -38
  234. package/src/screens/session-files.mjs +0 -39
  235. package/src/screens/session-files.test.mjs +0 -39
  236. package/src/screens/setup.browser-test.mjs +0 -49
  237. package/src/screens/setup.mjs +0 -78
  238. package/src/screens/stack-auth.browser-test.mjs +0 -30
  239. package/src/screens/stack-auth.mjs +0 -106
  240. package/src/screens/stack-auth.test.mjs +0 -65
  241. package/src/screens/write-guard.mjs +0 -26
  242. package/src/stack/stack.mjs +0 -131
  243. package/src/stack/stack.test.mjs +0 -40
  244. package/src/stack/supervisor.mjs +0 -30
@@ -0,0 +1,87 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { ARM_NOTE, decide } from "./watch-arm.mjs";
9
+
10
+ const NOTE = fileURLToPath(new URL("./watch-arm.mjs", import.meta.url));
11
+ const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
12
+
13
+ function checkouts(t, configs) {
14
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-note-")));
15
+ t.after(() => rmSync(base, { recursive: true, force: true }));
16
+ return configs.map((config, index) => {
17
+ const dir = path.join(base, String(index));
18
+ mkdirSync(dir);
19
+ execFileSync("git", ["init", "-q"], { cwd: dir, stdio: "pipe" });
20
+ if (config !== null) writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify(config));
21
+ return dir;
22
+ });
23
+ }
24
+
25
+ const start = (cwd, source) => ({ session_id: "s", cwd, hook_event_name: "SessionStart", source });
26
+
27
+ test("a checkout without dispatch gets no watch note", (t) => {
28
+ const [plain, off] = checkouts(t, [null, { swarm: { toolCallBudget: 50 } }]);
29
+ assert.equal(decide(start(plain, "startup"), {}), null);
30
+ assert.equal(decide(start(off, "startup"), {}), null);
31
+ });
32
+
33
+ test("dispatch adds the watch note on every session start source", (t) => {
34
+ const [on] = checkouts(t, [{ swarm: { dispatch: {} } }]);
35
+ for (const source of ["startup", "resume", "clear", "compact"]) {
36
+ assert.deepEqual(decide(start(on, source), {}), {
37
+ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: ARM_NOTE },
38
+ }, source);
39
+ }
40
+ });
41
+
42
+ test("an implementer gets no watch note", (t) => {
43
+ const [on] = checkouts(t, [{ swarm: { dispatch: {} } }]);
44
+ assert.equal(decide(start(on, "startup"), { QC_ROLE: "implementer" }), null);
45
+ });
46
+
47
+ test("a dispatch config error leaves the note silent", (t) => {
48
+ const [bad] = checkouts(t, [{ swarm: { dispatch: { maxPromptChars: "long" } } }]);
49
+ assert.equal(decide(start(bad, "startup"), {}), null);
50
+ });
51
+
52
+ test("the short note names each watch and the hourly check", () => {
53
+ for (const phrase of ["qc watch --pr <n>", "--codex <wrapper.log>", "--run <workflow>@<branch>", "hourly"]) {
54
+ assert.ok(ARM_NOTE.includes(phrase), phrase);
55
+ }
56
+ assert.ok(ARM_NOTE.length < 700, `${ARM_NOTE.length} characters`);
57
+ });
58
+
59
+ test("the hook prints JSON for an orchestrator and stays silent elsewhere", (t) => {
60
+ const [on, plain] = checkouts(t, [{ swarm: { dispatch: {} } }, null]);
61
+ const run = (cwd, role) => spawnSync(process.execPath, [NOTE], {
62
+ input: JSON.stringify(start(cwd, "startup")),
63
+ encoding: "utf8",
64
+ env: { ...process.env, QC_ROLE: role },
65
+ });
66
+ const noted = run(on, "");
67
+ assert.equal(noted.status, 0, noted.stderr);
68
+ assert.deepEqual(JSON.parse(noted.stdout), {
69
+ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: ARM_NOTE },
70
+ });
71
+ for (const silent of [run(plain, ""), run(on, "implementer")]) {
72
+ assert.equal(silent.status, 0, silent.stderr);
73
+ assert.equal(silent.stdout, "");
74
+ }
75
+ });
76
+
77
+ test("hooks.json arms the watch on SessionStart without a matcher", () => {
78
+ const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
79
+ const entries = (hooks.SessionStart ?? []).filter((entry) =>
80
+ entry.hooks.some((hook) => hook.command.includes("watch-arm.mjs")),
81
+ );
82
+ assert.deepEqual(entries.map((entry) => entry.matcher), [undefined]);
83
+ const hook = entries[0].hooks.find((item) => item.command.includes("watch-arm.mjs"));
84
+ assert.equal(hook.type, "command");
85
+ assert.equal(hook.command, 'node "${CLAUDE_PLUGIN_ROOT}/packages/qc-harness/src/cli/watch-arm.mjs"');
86
+ assert.equal(hook.timeout, 10);
87
+ });
package/src/cli/watch.mjs CHANGED
@@ -1,18 +1,22 @@
1
1
  // `qc watch`: block until the first event among the pull requests, Codex jobs and workflow runs it watches.
2
2
  // The wait is a shell command, so it costs no model tokens, and its exit is the event.
3
3
 
4
- import { spawnSync } from "node:child_process";
5
4
  import { closeSync, fstatSync, openSync, readSync } from "node:fs";
6
5
  import path from "node:path";
6
+ import { parseApiList, runGhResult } from "./gh-run.mjs";
7
+ import { checkVerdict, pendingCiReason } from "./check-verdict.mjs";
8
+ import { load } from "../config.mjs";
9
+ import { checkoutRootOf } from "./checkout-root.mjs";
10
+ import { recordRun, resolveFailures } from "./ci-failures.mjs";
11
+ import { originOf, repoOfSpelling } from "./git-read.mjs";
12
+ import { holdRefusal } from "./pause.mjs";
13
+ import { appendRun, runLogFileOf } from "./run-log.mjs";
7
14
 
8
15
  const DEFAULT_MAX_MINUTES = 55;
9
16
  const DEFAULT_INTERVAL_SECONDS = 60;
10
17
  const QUEUED_LIMIT_MS = 15 * 60_000;
11
18
  const CODEX_TAIL_BYTES = 2048;
12
- const GH_TIMEOUT_MS = 20_000;
13
19
  const SHA_SUFFIX = /^(.+)@([0-9a-f]{7,40})$/i;
14
- const FAILED_CONCLUSIONS = new Set(["FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"]);
15
- const FAILED_STATES = new Set(["FAILURE", "ERROR"]);
16
20
 
17
21
  export const EXIT = { PASSED: 0, BAD_INPUT: 1, TIMEOUT: 4, FAILED: 5, QUEUED: 6 };
18
22
 
@@ -90,22 +94,11 @@ const parseJson = (text) => {
90
94
  }
91
95
  };
92
96
 
93
- /** @returns "failed", "queued", "pending", or "passed" for one rollup entry, a check run or a status context. */
94
- function entryState(entry) {
95
- if (entry.__typename === "StatusContext" || entry.context !== undefined) {
96
- if (FAILED_STATES.has(entry.state)) return "failed";
97
- return entry.state === "SUCCESS" ? "passed" : "pending";
98
- }
99
- if (entry.status !== "COMPLETED") return entry.status === "QUEUED" ? "queued" : "pending";
100
- if (FAILED_CONCLUSIONS.has(entry.conclusion)) return "failed";
101
- return "passed";
102
- }
103
-
104
97
  /**
105
98
  * Watches one pull request. The queued timers belong to a head, so a new head starts them over.
106
99
  * @returns a function that polls once and answers `{ state, detail, code }` for an event, or null.
107
100
  */
108
- function pullRequestWatcher(number, { repo, gh, now }) {
101
+ function pullRequestWatcher(number, { repo, gh, now, requiredChecks }) {
109
102
  let head = null;
110
103
  let queuedSince = new Map();
111
104
  const args = ["pr", "view", String(number), "--json", "headRefOid,statusCheckRollup", ...(repo ? ["-R", repo] : [])];
@@ -117,12 +110,17 @@ function pullRequestWatcher(number, { repo, gh, now }) {
117
110
  queuedSince = new Map();
118
111
  }
119
112
  const at = now();
120
- const states = view.statusCheckRollup.map((entry) => [entry.name ?? entry.context, entryState(entry)]);
121
- if (states.some(([, state]) => state === "failed")) return { state: "failed", detail: head, code: EXIT.FAILED };
113
+ const states = view.statusCheckRollup.map((entry) => [entry.name ?? entry.context, checkVerdict(entry)]);
114
+ if (states.some(([, state]) => state === "failed")) return { state: "failed", detail: head, code: EXIT.FAILED, prHead: head };
122
115
  for (const [name] of [...queuedSince]) if (!states.some(([other, state]) => other === name && state === "queued")) queuedSince.delete(name);
123
116
  for (const [name, state] of states) if (state === "queued" && !queuedSince.has(name)) queuedSince.set(name, at);
124
117
  if ([...queuedSince.values()].some((since) => at - since > QUEUED_LIMIT_MS)) return { state: "queued", detail: head, code: EXIT.QUEUED };
125
- if (states.length > 0 && states.every(([, state]) => state === "passed")) return { state: "passed", detail: head, code: EXIT.PASSED };
118
+ if (states.length > 0 && states.every(([, state]) => state === "passed")) {
119
+ const workflows = parseApiList(gh(["api", `repos/${repo ?? "{owner}/{repo}"}/actions/runs?head_sha=${encodeURIComponent(head)}&per_page=100`, "--paginate"]), "workflow_runs");
120
+ const checkNames = view.statusCheckRollup.filter((entry) => entry.__typename !== "StatusContext" && entry.context === undefined).map((entry) => entry.name);
121
+ if (workflows === null || pendingCiReason(checkNames, workflows.filter((run) => run.head_sha === head), requiredChecks)) return null;
122
+ return { state: "passed", detail: head, code: EXIT.PASSED, runs: workflows.filter((run) => run.head_sha === head) };
123
+ }
126
124
  return null;
127
125
  };
128
126
  }
@@ -131,7 +129,9 @@ function codexWatcher(file) {
131
129
  return () => {
132
130
  const tail = readTail(file);
133
131
  const line = tail?.split(/\r?\n/).reverse().find((text) => text.startsWith("exit "));
134
- return line === undefined ? null : { state: "exit", detail: line.slice("exit ".length).trim(), code: EXIT.PASSED };
132
+ if (line === undefined) return null;
133
+ const detail = line.slice("exit ".length).trim();
134
+ return { state: "exit", detail, code: detail === "0" ? EXIT.PASSED : EXIT.FAILED };
135
135
  };
136
136
  }
137
137
 
@@ -140,22 +140,24 @@ function codexWatcher(file) {
140
140
  * or the one that `@<sha>` pins. A run of an earlier head never fires.
141
141
  */
142
142
  function runWatcher({ workflow, branch, sha }, { repo, gh }) {
143
- const headArgs = ["api", `repos/${repo ?? "{owner}/{repo}"}/commits/${branch}`, "--jq", ".sha"];
144
- const listArgs = ["run", "list", "--workflow", workflow, "--branch", branch, "--limit", "20", "--json", "status,conclusion,headSha", ...(repo ? ["-R", repo] : [])];
143
+ const headArgs = ["api", `repos/${repo ?? "{owner}/{repo}"}/commits/${encodeURIComponent(sha ?? branch)}`, "--jq", ".sha"];
144
+ let pinnedHead = sha?.length === 40 ? sha : null;
145
145
  return () => {
146
- const head = sha ?? gh(headArgs)?.trim();
146
+ const head = sha ? (pinnedHead ??= gh(headArgs)?.trim()) : gh(headArgs)?.trim();
147
147
  if (!head) return null;
148
- const latest = parseJson(gh(listArgs))?.find((run) => typeof run.headSha === "string" && run.headSha.startsWith(head.toLowerCase()) || run.headSha === head);
149
- if (!latest || latest.status !== "completed") return null;
150
- return latest.conclusion === "success"
151
- ? { state: "passed", detail: latest.headSha, code: EXIT.PASSED }
152
- : { state: "failed", detail: latest.headSha, code: EXIT.FAILED };
148
+ const listArgs = ["api", `repos/${repo ?? "{owner}/{repo}"}/actions/workflows/${encodeURIComponent(workflow)}/runs?branch=${encodeURIComponent(branch)}&head_sha=${encodeURIComponent(head)}&per_page=100`, "--paginate"];
149
+ const runs = parseApiList(gh(listArgs), "workflow_runs")?.filter((run) => typeof run.head_sha === "string" && run.head_sha.toLowerCase() === head.toLowerCase());
150
+ if (!runs?.length || pendingCiReason([], runs)) return null;
151
+ const latest = runs[0];
152
+ return checkVerdict(latest) === "passed"
153
+ ? { state: "passed", detail: latest.head_sha, code: EXIT.PASSED, runs: [{ ...latest, head_branch: branch }] }
154
+ : { state: "failed", detail: latest.head_sha, code: EXIT.FAILED, runs: runs.filter((run) => checkVerdict(run) === "failed").map((run) => ({ ...run, head_branch: branch })) };
153
155
  };
154
156
  }
155
157
 
156
158
  /** @returns gh's stdout on exit 0; throws an Error with gh's message when gh fails, times out, or is missing. */
157
159
  function readGh(args) {
158
- const result = spawnSync("gh", args, { encoding: "utf8", windowsHide: true, timeout: GH_TIMEOUT_MS });
160
+ const result = runGhResult(args);
159
161
  if (result.status === 0) return result.stdout ?? "";
160
162
  const reason = (result.stderr ?? "").split(/\r?\n/).find((line) => line.trim()) ?? result.error?.message ?? `gh exited ${result.status}`;
161
163
  throw new Error(reason.trim());
@@ -168,7 +170,8 @@ const realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
168
170
  * @param deps `gh` returns stdout, null, or throws; `say`, `warn`, `now` and `sleep` replace the output and the clock, for a test.
169
171
  * @returns the exit code: 0 an item finished well, 4 the bound passed, 5 a check or run failed, 6 a job stayed queued.
170
172
  */
171
- export async function runWatch(argv, { gh = readGh, say = console.log, warn = console.error, now = Date.now, sleep = realSleep } = {}) {
173
+ export async function runWatch(argv, { gh = readGh, say = console.log, warn = console.error, now = Date.now, sleep = realSleep, requiredChecks, cwd = process.cwd() } = {}) {
174
+ const started = now();
172
175
  let parsed;
173
176
  try {
174
177
  parsed = parseWatchArgs(argv);
@@ -176,6 +179,16 @@ export async function runWatch(argv, { gh = readGh, say = console.log, warn = co
176
179
  console.error(`${error.message}\n${USAGE}`);
177
180
  return EXIT.BAD_INPUT;
178
181
  }
182
+ if (parsed.repo) requiredChecks = [];
183
+ if (requiredChecks === undefined) {
184
+ requiredChecks = [];
185
+ try {
186
+ const root = checkoutRootOf(cwd);
187
+ if (root) requiredChecks = load(root).ci.requiredChecks;
188
+ } catch (error) {
189
+ warn(`watch: cannot read qc.config.json: ${String(error?.message ?? error).split(/\r?\n/)[0]}`);
190
+ }
191
+ }
179
192
  const read = (args) => {
180
193
  try {
181
194
  const out = gh(args);
@@ -186,17 +199,49 @@ export async function runWatch(argv, { gh = readGh, say = console.log, warn = co
186
199
  return null;
187
200
  }
188
201
  };
189
- const context = { repo: parsed.repo, gh: read, now };
202
+ const context = { repo: parsed.repo, gh: read, now, requiredChecks };
203
+ const root = checkoutRootOf(cwd);
204
+ const origin = root && originOf(root);
205
+ for (const { branch } of parsed.runs) {
206
+ const refusal = root && (!parsed.repo || !origin || repoOfSpelling(parsed.repo) === origin) && holdRefusal(root, branch);
207
+ if (refusal) {
208
+ say(refusal);
209
+ return EXIT.FAILED;
210
+ }
211
+ }
190
212
  const watchers = [
191
- ...parsed.prs.map((number) => ({ item: `pr:${number}`, poll: pullRequestWatcher(number, context) })),
213
+ ...parsed.prs.map((number) => ({ target: { pr: number }, item: `pr:${number}`, poll: pullRequestWatcher(number, context) })),
192
214
  ...parsed.codex.map((file) => ({ item: `codex:${file}`, poll: codexWatcher(file) })),
193
- ...parsed.runs.map((entry) => ({ item: `run:${entry.workflow}@${entry.branch}${entry.sha ? `@${entry.sha}` : ""}`, poll: runWatcher(entry, context) })),
215
+ ...parsed.runs.map((entry) => ({ target: { run: `${entry.workflow}@${entry.branch}${entry.sha ? `@${entry.sha}` : ""}` }, item: `run:${entry.workflow}@${entry.branch}${entry.sha ? `@${entry.sha}` : ""}`, poll: runWatcher(entry, context) })),
194
216
  ];
195
- const deadline = now() + parsed.maxMinutes * 60_000;
217
+ const deadline = started + parsed.maxMinutes * 60_000;
196
218
  for (;;) {
197
- for (const { item, poll } of watchers) {
219
+ for (const { item, poll, target } of watchers) {
198
220
  const event = poll();
199
221
  if (event) {
222
+ if (target && ["passed", "failed"].includes(event.state)) {
223
+ try {
224
+ appendRun(runLogFileOf(cwd), {
225
+ kind: "ci", time: new Date(now()).toISOString(), ...target, head: event.detail,
226
+ result: event.state === "passed" ? "pass" : "fail",
227
+ minutes: Math.round(Math.max(0, now() - started) / 6000) / 10,
228
+ });
229
+ } catch { warn("watch: cannot write run log"); }
230
+ }
231
+ try {
232
+ const root = checkoutRootOf(cwd);
233
+ if (root) {
234
+ const runs = event.runs ?? (event.prHead ? parseApiList(read(["api", `repos/${parsed.repo ?? "{owner}/{repo}"}/actions/runs?head_sha=${encodeURIComponent(event.prHead)}&per_page=100`, "--paginate"]), "workflow_runs") : []) ?? [];
235
+ for (const run of runs) {
236
+ if (!run.head_branch || !run.head_sha || run.head_sha !== event.detail) continue;
237
+ const repository = repoOfSpelling(run.head_repository?.full_name ?? run.repository?.full_name ?? parsed.repo ?? originOf(root) ?? "");
238
+ if (event.code === EXIT.PASSED) resolveFailures(root, run.head_branch, run.head_sha, run.id, repository);
239
+ else if (checkVerdict(run) === "failed" && run.id) recordRun(root, { id: run.id, branch: run.head_branch, head: run.head_sha, repository }, { gh, warn, repo: parsed.repo });
240
+ }
241
+ }
242
+ } catch (error) {
243
+ warn(`watch: cannot update CI records: ${String(error.message).split(/\r?\n/)[0]}`);
244
+ }
200
245
  say(`EVENT ${item} ${event.state} ${event.detail}`);
201
246
  return event.code;
202
247
  }
@@ -1,11 +1,46 @@
1
1
  import { strict as assert } from "node:assert";
2
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
5
6
  import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
6
8
  import { parseWatchArgs, runWatch } from "./watch.mjs";
7
9
 
8
10
  const MIN = 60_000;
11
+ const pages = (values) => values.map(page => JSON.stringify(page)).join("\n");
12
+ const RUN_HEAD = "abc1234" + "a".repeat(33);
13
+
14
+ test("the watch and CI reference sections describe pending workflows and required checks", () => {
15
+ const reference = readFileSync(new URL("../../../../docs/reference.md", import.meta.url), "utf8");
16
+ const watchSection = reference.slice(reference.indexOf("#### Wait on CI with bounds"), reference.indexOf("### 10."));
17
+ assert.match(watchSection, /ci\.requiredChecks/);
18
+ assert.match(watchSection, /--paginate/);
19
+ assert.match(watchSection, /`success`, `neutral`, and `skipped`/);
20
+ assert.match(watchSection, /head_sha/);
21
+ assert.match(watchSection, /git top level/);
22
+ assert.match(watchSection, /one warning to stderr/);
23
+ assert.match(watchSection, /commit status never counts as a required check/);
24
+ assert.match(watchSection, /`--run` ignores `ci\.requiredChecks`/);
25
+ const ciSection = reference.slice(reference.indexOf('With `requireGreen: "not-red"`'), reference.indexOf("The hooks read these markers:"));
26
+ assert.match(ciSection, /workflow and name/);
27
+ assert.match(ciSection, /ci\.requiredChecks/);
28
+ assert.match(ciSection, /`stale` and `startup_failure`/);
29
+ assert.match(ciSection, /suite id/);
30
+ assert.match(ciSection, /repository decides, never the checkout/);
31
+ assert.match(ciSection, /commit status never counts as a required check/);
32
+ assert.match(ciSection, /failed workflow read preserves pending or red checks/);
33
+ const greenRow = reference.split("\n").find((line) => line.startsWith("| Green head |"));
34
+ assert.match(greenRow, /unfinished workflows and missing required checks/);
35
+ assert.doesNotMatch(greenRow, /A head with no check runs passes/);
36
+ });
37
+
38
+ test("qc help describes the watch SHA suffix and bad-input exit code", () => {
39
+ const result = spawnSync(process.execPath, [fileURLToPath(new URL("./qc.mjs", import.meta.url))], { encoding: "utf8" });
40
+ assert.equal(result.status, 0, result.stderr);
41
+ assert.match(result.stdout, /qc watch .*--run <workflow>@<branch>\[@<sha>\]/);
42
+ assert.match(result.stdout, /exit 0 done, 1 bad input, 4 bound/);
43
+ });
9
44
 
10
45
  /** A clock that the sleep advances, so a bound of 55 minutes costs no time. */
11
46
  function fakeClock() {
@@ -16,9 +51,11 @@ function fakeClock() {
16
51
  /** `answers` is a list of stdout values, one per gh call; the last one repeats. A function answer gets the arguments. `null` is a failing gh. */
17
52
  function stubGh(answers) {
18
53
  const calls = [];
54
+ let answerIndex = 0;
19
55
  const gh = (args) => {
20
56
  calls.push(args);
21
- const answer = answers[Math.min(calls.length - 1, answers.length - 1)];
57
+ if (args[0] === "api" && args[1].includes("/actions/runs?")) return pages([{ workflow_runs: [] }]);
58
+ const answer = answers[Math.min(answerIndex++, answers.length - 1)];
22
59
  return typeof answer === "function" ? answer(args) : answer;
23
60
  };
24
61
  return { gh, calls };
@@ -27,11 +64,20 @@ function stubGh(answers) {
27
64
  const rollup = (head, ...checks) => JSON.stringify({ headRefOid: head, statusCheckRollup: checks });
28
65
  const check = (name, status, conclusion = "") => ({ __typename: "CheckRun", name, status, conclusion });
29
66
 
30
- async function watch(argv, { gh, time = fakeClock() } = {}) {
67
+ async function watch(argv, { gh, time = fakeClock(), cwd, requiredChecks = cwd === undefined ? [] : undefined, run = runWatch } = {}) {
31
68
  const lines = [];
32
69
  const warnings = [];
33
- const code = await runWatch(argv, { gh, say: (line) => lines.push(line), warn: (line) => warnings.push(line), now: time.now, sleep: time.sleep });
34
- return { code, lines, warnings, time };
70
+ const temporary = cwd === undefined ? mkdtempSync(path.join(os.tmpdir(), "qc-watch-checkout-")) : null;
71
+ try {
72
+ if (temporary) {
73
+ const initialized = spawnSync("git", ["init", "-q", temporary], { encoding: "utf8" });
74
+ assert.equal(initialized.status, 0, initialized.stderr);
75
+ }
76
+ const code = await run(argv, { gh, requiredChecks, cwd: cwd ?? temporary, say: (line) => lines.push(line), warn: (line) => warnings.push(line), now: time.now, sleep: time.sleep });
77
+ return { code, lines, warnings, time };
78
+ } finally {
79
+ if (temporary) rmSync(temporary, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
80
+ }
35
81
  }
36
82
 
37
83
  test("parseWatchArgs reads repeated flags and the defaults", () => {
@@ -76,6 +122,114 @@ test("--pr counts a failed status context", async () => {
76
122
  assert.equal((await watch(["--pr", "7"], { gh })).code, 5);
77
123
  });
78
124
 
125
+ test("--pr rejects every completed conclusion outside the green allowlist", async () => {
126
+ for (const conclusion of ["STALE", "STARTUP_FAILURE", "FUTURE_CONCLUSION", "", null, undefined]) {
127
+ const { gh } = stubGh([rollup("h", check("build", "COMPLETED", conclusion))]);
128
+ assert.equal((await watch(["--pr", "7"], { gh })).code, 5, String(conclusion));
129
+ }
130
+ });
131
+
132
+ test("--pr waits for head workflows even when every visible check passes", async () => {
133
+ const calls = [];
134
+ const gh = (args) => {
135
+ calls.push(args);
136
+ if (args[0] === "pr") return rollup("abc1234", check("lint", "COMPLETED", "SUCCESS"));
137
+ return pages([{ workflow_runs: [] }, { workflow_runs: [{ name: "CI", head_sha: "abc1234", status: "queued" }] }]);
138
+ };
139
+ assert.equal((await watch(["--pr", "7", "--repo", "o/r", "--max", "1"], { gh })).code, 4);
140
+ assert.equal(calls[1][1], "repos/o/r/actions/runs?head_sha=abc1234&per_page=100");
141
+ assert.ok(calls[1].includes("--paginate"));
142
+ assert.ok(!calls[1].includes("--slurp"));
143
+ });
144
+
145
+ test("--pr waits for missing required checks and passes when they appear", async () => {
146
+ const { gh } = stubGh([rollup("h", check("lint", "COMPLETED", "SUCCESS"))]);
147
+ assert.equal((await watch(["--pr", "7", "--max", "1"], { gh, requiredChecks: ["build"] })).code, 4);
148
+ const ready = stubGh([rollup("h", check("build", "COMPLETED", "SUCCESS"))]);
149
+ assert.equal((await watch(["--pr", "7"], { gh: ready.gh, requiredChecks: ["build"] })).code, 0);
150
+ });
151
+
152
+ test("a commit status cannot satisfy a required check-run name", async () => {
153
+ const { gh } = stubGh([rollup("h", check("lint", "COMPLETED", "SUCCESS"), { __typename: "StatusContext", context: "build", state: "SUCCESS" })]);
154
+ assert.equal((await watch(["--pr", "7", "--max", "1"], { gh, requiredChecks: ["build"] })).code, 4);
155
+ });
156
+
157
+ test("watch reads required checks at the git top level only for the local repository", async (t) => {
158
+ const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-watch-config-"));
159
+ t.after(() => rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
160
+ mkdirSync(path.join(cwd, ".git"));
161
+ const nested = path.join(cwd, "nested");
162
+ mkdirSync(nested);
163
+ writeFileSync(path.join(cwd, "qc.config.json"), JSON.stringify({ ci: { requiredChecks: ["build"] } }));
164
+ writeFileSync(path.join(nested, "qc.config.json"), JSON.stringify({ ci: null }));
165
+ const { gh } = stubGh([rollup("h", check("lint", "COMPLETED", "SUCCESS"))]);
166
+ const local = await watch(["--pr", "7", "--max", "1"], { cwd: nested, gh });
167
+ assert.equal(local.code, 4);
168
+ assert.deepEqual(local.warnings, []);
169
+ const remote = await watch(["--pr", "7", "--repo", "other/repo"], { cwd: nested, gh });
170
+ assert.equal(remote.code, 0);
171
+ assert.deepEqual(remote.warnings, []);
172
+ });
173
+
174
+ test("an unreadable watch config warns once and continues with no required checks", async (t) => {
175
+ const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-watch-bad-config-"));
176
+ t.after(() => rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
177
+ mkdirSync(path.join(cwd, ".git"));
178
+ writeFileSync(path.join(cwd, "qc.config.json"), JSON.stringify({ ci: null }));
179
+ const { gh } = stubGh([rollup("h", check("lint", "IN_PROGRESS")), rollup("h", check("lint", "COMPLETED", "SUCCESS"))]);
180
+ const result = await watch(["--pr", "7"], { cwd, gh });
181
+ assert.equal(result.code, 0);
182
+ assert.equal(result.warnings.length, 1);
183
+ assert.match(result.warnings[0], /^watch:.*config.*ci must be an object/);
184
+ const file = path.join(cwd, "wrapper.log");
185
+ writeFileSync(file, "exit 0\n");
186
+ const codex = await watch(["--codex", file], { cwd, gh });
187
+ assert.equal(codex.code, 0);
188
+ assert.equal(codex.warnings.length, 1);
189
+ const remote = await watch(["--pr", "7", "--repo", "other/repo"], { cwd, gh });
190
+ assert.equal(remote.code, 0);
191
+ assert.deepEqual(remote.warnings, []);
192
+ });
193
+
194
+ test("--run resolves a short pinned sha and bounds every list by the full head", async () => {
195
+ const head = "abc1234" + "a".repeat(33);
196
+ const calls = [];
197
+ let polls = 0;
198
+ const gh = (args) => {
199
+ calls.push(args);
200
+ if (args[1].includes("/commits/")) return head;
201
+ return JSON.stringify({ workflow_runs: [{ head_sha: head, status: ++polls === 1 ? "in_progress" : "completed", conclusion: "success" }] });
202
+ };
203
+ const result = await watch(["--run", "ci.yml@main@abc1234", "--repo", "o/r"], { gh });
204
+ assert.equal(result.code, 0);
205
+ assert.deepEqual(calls[0], ["api", "repos/o/r/commits/abc1234", "--jq", ".sha"]);
206
+ assert.equal(calls.filter((args) => args[1].includes("/commits/")).length, 1);
207
+ for (const args of calls.slice(1)) assert.match(args[1], new RegExp(`[?&]head_sha=${head}(?:&|$)`));
208
+ assert.ok(calls.every((args) => !args[1].includes("commits/main")));
209
+ });
210
+
211
+ test("--pr uses the green allowlist for terminal status-context states", async () => {
212
+ for (const state of ["SUCCESS", "NEUTRAL", "SKIPPED", "ERROR", "FUTURE_STATE"]) {
213
+ const { gh } = stubGh([rollup("h", { __typename: "StatusContext", context: "ci", state })]);
214
+ assert.equal((await watch(["--pr", "7"], { gh })).code, ["SUCCESS", "NEUTRAL", "SKIPPED"].includes(state) ? 0 : 5, state);
215
+ }
216
+ });
217
+
218
+ test("--run accepts neutral and skipped workflow conclusions", async () => {
219
+ for (const conclusion of ["neutral", "skipped"]) {
220
+ const { gh } = stubGh([pages([{ workflow_runs: [{ head_sha: RUN_HEAD, status: "completed", conclusion }] }])]);
221
+ assert.equal((await watch(["--run", `ci.yml@main@${RUN_HEAD}`], { gh })).code, 0);
222
+ }
223
+ });
224
+
225
+ test("--run waits for an unfinished head workflow on a later page", async () => {
226
+ const { gh } = stubGh([pages([
227
+ { workflow_runs: [{ head_sha: RUN_HEAD, status: "completed", conclusion: "success" }] },
228
+ { workflow_runs: [{ head_sha: RUN_HEAD, status: "queued", conclusion: null }] },
229
+ ])]);
230
+ assert.equal((await watch(["--run", `ci.yml@main@${RUN_HEAD}`, "--max", "1"], { gh })).code, 4);
231
+ });
232
+
79
233
  test("--pr exits 6 when a job stays QUEUED past 15 minutes", async () => {
80
234
  const { gh } = stubGh([rollup("abc123", check("a", "QUEUED"))]);
81
235
  const { code, lines, time } = await watch(["--pr", "7"], { gh });
@@ -116,17 +270,19 @@ test("the default bound is 55 minutes", async () => {
116
270
 
117
271
  function wrapper(t, text) {
118
272
  const dir = mkdtempSync(path.join(os.tmpdir(), "qc-watch-"));
119
- t.after(() => rmSync(dir, { recursive: true, force: true }));
273
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
120
274
  const file = path.join(dir, "wrapper.log");
121
275
  if (text !== undefined) writeFileSync(file, text);
122
276
  return file;
123
277
  }
124
278
 
125
- test("--codex exits 0 on a line that starts with `exit `", async (t) => {
126
- const file = wrapper(t, "working\nmore output\nexit 2\n");
127
- const { code, lines } = await watch(["--codex", file], { gh: () => null });
128
- assert.equal(code, 0);
129
- assert.deepEqual(lines, [`EVENT codex:${file} exit 2`]);
279
+ test("--codex returns 0 for success and 5 for every nonzero runner exit", async (t) => {
280
+ for (const status of [0, 1, 2, 3, 4, 5, 6, 7, 9]) {
281
+ const file = wrapper(t, `working\nmore output\nexit ${status}\n`);
282
+ const { code, lines } = await watch(["--codex", file], { gh: () => null });
283
+ assert.equal(code, status === 0 ? 0 : 5);
284
+ assert.deepEqual(lines, [`EVENT codex:${file} exit ${status}`]);
285
+ }
130
286
  });
131
287
 
132
288
  test("--codex ignores `exit` inside a line and a missing file, then times out", async (t) => {
@@ -142,13 +298,13 @@ test("--codex reads only the last 2 KB", async (t) => {
142
298
  });
143
299
 
144
300
  test("--run exits 0 on a success and 5 on a failure", async () => {
145
- const run = (status, conclusion) => (args) => (args[0] === "api" ? "deadbeef\n" : JSON.stringify([{ status, conclusion, headSha: "deadbeef" }]));
301
+ const run = (status, conclusion) => (args) => (args[1].includes("/commits/") ? "deadbeef\n" : pages([{ workflow_runs: [{ status, conclusion, head_sha: "deadbeef" }] }]));
146
302
  const pass = stubGh([run("in_progress", ""), run("in_progress", ""), run("completed", "success")]);
147
303
  const first = await watch(["--run", "ci.yml@feat/x", "--repo", "o/r"], { gh: pass.gh });
148
304
  assert.equal(first.code, 0);
149
305
  assert.deepEqual(first.lines, ["EVENT run:ci.yml@feat/x passed deadbeef"]);
150
- assert.deepEqual(pass.calls[0], ["api", "repos/o/r/commits/feat/x", "--jq", ".sha"]);
151
- assert.deepEqual(pass.calls[1], ["run", "list", "--workflow", "ci.yml", "--branch", "feat/x", "--limit", "20", "--json", "status,conclusion,headSha", "-R", "o/r"]);
306
+ assert.deepEqual(pass.calls[0], ["api", "repos/o/r/commits/feat%2Fx", "--jq", ".sha"]);
307
+ assert.deepEqual(pass.calls[1], ["api", "repos/o/r/actions/workflows/ci.yml/runs?branch=feat%2Fx&head_sha=deadbeef&per_page=100", "--paginate"]);
152
308
  const fail = await watch(["--run", "ci.yml@feat/x"], { gh: stubGh([run("completed", "failure")]).gh });
153
309
  assert.equal(fail.code, 5);
154
310
  assert.deepEqual(fail.lines, ["EVENT run:ci.yml@feat/x failed deadbeef"]);
@@ -194,13 +350,28 @@ test("--codex keeps a whole first line when the 2 KB cut lands on a line start",
194
350
  assert.deepEqual(lines, [`EVENT codex:${file} exit 4`]);
195
351
  });
196
352
 
353
+ test("--run reads every workflow-run page and encodes the workflow and branch", async () => {
354
+ const calls = [];
355
+ const gh = (args) => {
356
+ calls.push(args);
357
+ return pages([
358
+ { workflow_runs: [{ status: "completed", conclusion: "success", head_sha: "other99" }] },
359
+ { workflow_runs: [{ status: "completed", conclusion: "success", head_sha: RUN_HEAD }] },
360
+ ]);
361
+ };
362
+ assert.equal((await watch(["--run", `ci test.yml@feat/x@${RUN_HEAD}`, "--repo", "o/r"], { gh })).code, 0);
363
+ assert.ok(calls[0].includes("--paginate"));
364
+ assert.ok(!calls[0].includes("--slurp"));
365
+ assert.equal(calls[0][1], `repos/o/r/actions/workflows/ci%20test.yml/runs?branch=feat%2Fx&head_sha=${RUN_HEAD}&per_page=100`);
366
+ });
367
+
197
368
  test("--run ignores a completed run on the previous head, and fires on the run of the current head", async () => {
198
369
  const time = fakeClock();
199
- const stale = { status: "completed", conclusion: "success", headSha: "oldhead" };
200
- const fresh = { status: "completed", conclusion: "failure", headSha: "newhead" };
370
+ const stale = { status: "completed", conclusion: "success", head_sha: "oldhead" };
371
+ const fresh = { status: "completed", conclusion: "failure", head_sha: "newhead" };
201
372
  const answer = (args) => {
202
- if (args[0] === "api") return "newhead\n";
203
- return JSON.stringify(time.clock.now < 2 * MIN ? [stale] : [fresh, stale]);
373
+ if (args[1].includes("/commits/")) return "newhead\n";
374
+ return pages([{ workflow_runs: time.clock.now < 2 * MIN ? [stale] : [fresh, stale] }]);
204
375
  };
205
376
  const { code, lines } = await watch(["--run", "ci.yml@feat/x"], { gh: stubGh([answer]).gh, time });
206
377
  assert.equal(code, 5);
@@ -208,27 +379,28 @@ test("--run ignores a completed run on the previous head, and fires on the run o
208
379
  });
209
380
 
210
381
  test("--run <wf>@<branch> never fires on a run of another head, so it times out", async () => {
211
- const answer = (args) => (args[0] === "api" ? "newhead\n" : JSON.stringify([{ status: "completed", conclusion: "success", headSha: "oldhead" }]));
382
+ const answer = (args) => (args[1].includes("/commits/") ? "newhead\n" : pages([{ workflow_runs: [{ status: "completed", conclusion: "success", head_sha: "oldhead" }] }]));
212
383
  const { code, lines } = await watch(["--run", "ci.yml@feat/x", "--max", "5"], { gh: stubGh([answer]).gh });
213
384
  assert.equal(code, 4);
214
385
  assert.deepEqual(lines, ["EVENT timeout"]);
215
386
  });
216
387
 
217
388
  test("--run <wf>@<branch>@<sha> pins the head and reads no branch head", async () => {
218
- const runs = JSON.stringify([
219
- { status: "completed", conclusion: "failure", headSha: "other99" },
220
- { status: "completed", conclusion: "success", headSha: "abc1234" },
221
- ]);
389
+ const runs = pages([{ workflow_runs: [
390
+ { status: "completed", conclusion: "failure", head_sha: "other99" },
391
+ { status: "completed", conclusion: "success", head_sha: RUN_HEAD },
392
+ ] }]);
222
393
  const { gh, calls } = stubGh([runs]);
223
- const { code, lines } = await watch(["--run", "ci.yml@feat/x@abc1234"], { gh });
394
+ const { code, lines } = await watch(["--run", `ci.yml@feat/x@${RUN_HEAD}`], { gh });
224
395
  assert.equal(code, 0);
225
- assert.deepEqual(lines, ["EVENT run:ci.yml@feat/x@abc1234 passed abc1234"]);
226
- assert.ok(calls.every((args) => args[0] === "run"), "no api call");
396
+ assert.deepEqual(lines, [`EVENT run:ci.yml@feat/x@${RUN_HEAD} passed ${RUN_HEAD}`]);
397
+ assert.ok(calls.every((args) => args[0] === "api" && args[1].includes("/actions/workflows/")), "no branch-head read");
227
398
  });
228
399
 
229
400
  test("a gh error writes one stderr line with the first line of the error, and the wait goes on", async () => {
230
401
  let calls = 0;
231
- const gh = () => {
402
+ const gh = (args) => {
403
+ if (args[0] === "api") return pages([{ workflow_runs: [] }]);
232
404
  calls += 1;
233
405
  if (calls === 1) throw new Error("HTTP 502 bad gateway\nmore detail");
234
406
  return rollup("h", check("a", "COMPLETED", "SUCCESS"));
@@ -244,3 +416,37 @@ test("a gh that answers null writes a stderr line and is not an event", async ()
244
416
  assert.equal(code, 4);
245
417
  assert.ok(warnings.length >= 1 && warnings.every((line) => line.startsWith("watch: gh failed: ")));
246
418
  });
419
+
420
+
421
+ test("the watch helper isolates its ledger and holds in a temporary checkout", async () => {
422
+ let calls = 0;
423
+ await watch(["--run", `ci.yml@main@${RUN_HEAD}`], { gh: () => JSON.stringify({ workflow_runs: [{ status: "completed", conclusion: "success", head_sha: RUN_HEAD }] }), run: async (argv, options) => {
424
+ calls += 1;
425
+ assert.ok(options.cwd);
426
+ assert.notEqual(options.cwd, process.cwd());
427
+ assert.match(readFileSync(path.join(options.cwd, ".git/HEAD"), "utf8"), /^ref:/);
428
+ return runWatch(argv, { ...options, gh: () => JSON.stringify({ workflow_runs: [{ status: "completed", conclusion: "success", head_sha: RUN_HEAD }] }) });
429
+ } });
430
+ assert.equal(calls, 1, "the helper must call the supplied run function");
431
+ });
432
+
433
+ test("watch logs only final CI events with head, target, result and elapsed minutes", async (t) => {
434
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-watch-metrics-"));
435
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
436
+ assert.equal(spawnSync("git", ["init", "-q", dir]).status, 0);
437
+ const file = path.join(dir, ".git", "qc", "runs.jsonl");
438
+ const done = rollup(RUN_HEAD, check("build", "COMPLETED", "SUCCESS"));
439
+ const { gh } = stubGh([rollup(RUN_HEAD, check("build", "IN_PROGRESS")), done]);
440
+ assert.equal((await watch(["--pr", "249"], { cwd: dir, gh, time: fakeClock() })).code, 0);
441
+ let rows = readFileSync(file, "utf8").trim().split("\n").map(JSON.parse);
442
+ assert.deepEqual({ ...rows[0], time: null }, { kind: "ci", time: null, pr: 249, head: RUN_HEAD, result: "pass", minutes: 1 });
443
+ const failed = pages([{ workflow_runs: [{ head_sha: RUN_HEAD, status: "completed", conclusion: "failure" }] }]);
444
+ assert.equal((await watch(["--run", `ci.yml@topic@${RUN_HEAD}`], { cwd: dir, gh: stubGh([failed]).gh })).code, 5);
445
+ rows = readFileSync(file, "utf8").trim().split("\n").map(JSON.parse);
446
+ assert.deepEqual({ ...rows[1], time: null }, { kind: "ci", time: null, run: `ci.yml@topic@${RUN_HEAD}`, head: RUN_HEAD, result: "fail", minutes: 0 });
447
+ assert.equal((await watch(["--pr", "1", "--max", "1"], { cwd: dir, gh: stubGh([null]).gh })).code, 4);
448
+ const wrapper = path.join(dir, "wrapper.log");
449
+ writeFileSync(wrapper, "exit 0\n");
450
+ assert.equal((await watch(["--codex", wrapper], { cwd: dir })).code, 0);
451
+ assert.equal(readFileSync(file, "utf8").trim().split("\n").length, 2);
452
+ });