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
@@ -5,6 +5,8 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { test } from "node:test";
7
7
  import { decide } from "./dispatch-guard.mjs";
8
+ import { checkpointPathOf } from "./checkpoint.mjs";
9
+ import { runtimeTagOf } from "./dispatch-route.mjs";
8
10
  import { appendRecord, readLedger } from "./ledger.mjs";
9
11
  import { judgeTask, recordDispatch } from "./task-gate.mjs";
10
12
 
@@ -39,6 +41,9 @@ function workspace(t, config = { swarm: { dispatch: {} } }) {
39
41
  git(main, "worktree", "add", "-q", "-b", "feat/1-x", linked);
40
42
  const tmp = path.join(base, "tmp");
41
43
  mkdirSync(tmp);
44
+ const checkpoint = checkpointPathOf(main, "s");
45
+ mkdirSync(path.dirname(checkpoint), { recursive: true });
46
+ writeFileSync(checkpoint, "## Goal\nTest the review gate.\n## Rules\nKeep the gate checks on.\n## Tasks\nDispatch the review.\n## Next\nCheck the result.\n");
42
47
  return { base, main, origin, linked, tmp, ledger: path.join(main, ".git", "qc", "ledger.jsonl") };
43
48
  }
44
49
 
@@ -56,12 +61,26 @@ const call = (ws, type, prompt) => ({
56
61
  hook_event_name: "PreToolUse",
57
62
  tool_name: "Agent",
58
63
  tool_use_id: "toolu_1",
59
- tool_input: { subagent_type: type, description: "Review", prompt },
64
+ tool_input: { subagent_type: type, description: runtimeTagOf({ subagent_type: type }, { codexModel: null }) + "Review", prompt },
60
65
  });
61
66
  const reviewPrompt = (ws, more = "") => `Review the branch.\nWorktree: ${ws.linked}\n${more}`;
62
67
  const judge = (ws, type, prompt, deps = { ciState: green }) => judgeTask(call(ws, type, prompt), ws.tmp, deps);
63
68
  const branchVerdict = (ws, sha) => appendRecord(ws.ledger, { type: "verdict", kind: "branch", verdict: "APPROVED", sha, branch: "feat/1-x" });
64
69
 
70
+ test("the task gate passes required checks from the repository despite an invalid worktree config", (t) => {
71
+ const ws = workspace(t, { swarm: { dispatch: {} }, ci: { requiredChecks: ["build"] } });
72
+ writeFileSync(path.join(ws.linked, "qc.config.json"), JSON.stringify({ ci: null }));
73
+ const seen = [];
74
+ const task = judge(ws, BRANCH_REVIEWER, reviewPrompt(ws), {
75
+ ciState: (sha, cwd, options) => {
76
+ seen.push({ sha, cwd, options });
77
+ return { reason: "CI on head: build is missing", unknown: null, pending: true };
78
+ },
79
+ });
80
+ assert.match(task.refusal ?? "", /build is missing/);
81
+ assert.deepEqual(seen, [{ sha: git(ws.linked, "rev-parse", "HEAD"), cwd: ws.linked, options: { requiredChecks: ["build"] } }]);
82
+ });
83
+
65
84
  test("a reviewer whose head holds the tip of the base, with green CI, passes with no note", (t) => {
66
85
  const ws = workspace(t);
67
86
  const task = judge(ws, BRANCH_REVIEWER, reviewPrompt(ws));
@@ -176,7 +195,7 @@ test("a long brief file warns and still passes, and the warning reaches the sess
176
195
  const task = implement(ws, "Read it.", brief);
177
196
  assert.equal(task.refusal, null);
178
197
  assert.match(task.note ?? "", /9 numbered findings/);
179
- const output = decide(call(ws, IMPLEMENTER, `Read it.\nBrief: ${brief}\nWorktree: ${ws.linked}`), ws.tmp, Date.now(), { ciState: green });
198
+ const output = decide(call(ws, IMPLEMENTER, `Read it.\nBrief: ${brief}\nWorktree: ${ws.linked}\nRuntime: claude test`), ws.tmp, Date.now(), { ciState: green });
180
199
  assert.match(output.hookSpecificOutput.additionalContext, /disjoint paths/);
181
200
  assert.equal(output.hookSpecificOutput.permissionDecision, undefined);
182
201
  });
@@ -3,6 +3,7 @@
3
3
 
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
+ import { load } from "../config.mjs";
6
7
  import { checkoutRootOf } from "./checkout-root.mjs";
7
8
  import { ciNotGreen, ciState as readCiState } from "./ci-state.mjs";
8
9
  import { typeOf } from "./dispatch.mjs";
@@ -34,7 +35,8 @@ const fixRoundRefusal = (branch, sha, type) =>
34
35
  const unreviewedRefusal = (branch, stopHead, head) =>
35
36
  `Task gate: an implementer stopped on ${branch} at ${short(stopHead)}, and no review in the ledger names ${short(stopHead)} or a later commit. ` +
36
37
  `Dispatch the task reviewer on ${short(head)} first; its first line \`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>\` records the review. ` +
37
- `The review runs once CI on the head is green: when CI on ${short(stopHead)} has failed or still runs, the next implementer continues the task and this gate passes it. ` +
38
+ `The review runs once CI on the head is green. ` +
39
+ `A prompt with no \`Fix:\` line passes when CI on ${short(head)} has failed or still runs. ` +
38
40
  `If that stop handed off, its report named \`HANDOFF: <note path>\`; the same line in the next implementer prompt continues the task. ` +
39
41
  `\`qc ledger ${branch}\` lists what is recorded. A CI fix adds a line \`Fix: ci\`, and a review fix adds \`Fix: review\`.`;
40
42
 
@@ -81,8 +83,8 @@ export function continuedStop(records, branch, handoff) {
81
83
  return reviewed ? null : stop;
82
84
  }
83
85
 
84
- /** A CI fix or a review fix may start on a red or unreviewed head; a CI fix on a head whose CI is green is refused. */
85
- function fixVerdict({ records, branch, head, fix, ciStatus }) {
86
+ /** A CI fix needs known-red CI; a review fix needs CHANGES_REQUIRED and reviews of stops, except the newest continued HANDOFF. */
87
+ function fixVerdict({ records, branch, head, fix, ciStatus, cwd, git, handoff }) {
86
88
  if (fix === "ci") {
87
89
  const state = ciStatus(head);
88
90
  if (state.reason === null) {
@@ -95,17 +97,21 @@ function fixVerdict({ records, branch, head, fix, ciStatus }) {
95
97
  if (last?.verdict !== "CHANGES_REQUIRED") {
96
98
  return { refusal: `Task gate: \`Fix: review\` on ${branch}, where no review in the ledger asks for changes. Drop the line, or dispatch the reviewer first.` };
97
99
  }
100
+ const unreviewed = unreviewedImplementerStop({ records, branch, head, cwd, git });
101
+ if (unreviewed && unreviewed !== continuedStop(records, branch, handoff)) {
102
+ return { refusal: unreviewedRefusal(branch, unreviewed.head, head) };
103
+ }
98
104
  return { refusal: null, fix };
99
105
  }
100
106
 
101
107
  /**
102
108
  * The task gate's answer for an implementer on `branch`: `refusal` is the reason it may not start now, or null.
103
- * `ciPass` is `{ sha, reason }` when an unreviewed stop head passes because CI on it is not green, else absent.
109
+ * `ciPass` is `{ sha, reason }` when an unreviewed stop passes because CI on the branch head is not green, else absent.
104
110
  * Only implementer commits need a review, so a controller commit after a reviewed head passes. `cwd` is any
105
111
  * checkout; `git` reads it, and `ci` answers why CI on a sha is not green, or null.
106
112
  */
107
- export function gateVerdict({ records, branch, head, reason, type, cwd, git = gitRead, handoff = null, ci = (sha) => ciNotGreen(sha, cwd), fix = null, ciStatus = (sha) => readCiState(sha, cwd) }) {
108
- if (fix !== null) return fixVerdict({ records, branch, head, fix, ciStatus });
113
+ export function gateVerdict({ records, branch, head, reason, type, cwd, git = gitRead, handoff = null, requiredChecks = [], ci = (sha) => ciNotGreen(sha, cwd, { requiredChecks }), fix = null, ciStatus = (sha) => readCiState(sha, cwd, { requiredChecks }) }) {
114
+ if (fix !== null) return fixVerdict({ records, branch, head, fix, ciStatus, cwd, git, handoff });
109
115
  // A continuation of the newest stop's hand-off is the same task, so it is neither a fix round nor a new task.
110
116
  const continued = continuedStop(records, branch, handoff);
111
117
  const why = reason ?? (continued ? `continues the hand-off ${continued.handoff}` : null);
@@ -114,9 +120,9 @@ export function gateVerdict({ records, branch, head, reason, type, cwd, git = gi
114
120
  const unreviewed = unreviewedImplementerStop({ records, branch, head, cwd, git });
115
121
  if (unreviewed && unreviewed !== continued) {
116
122
  // A head that CI failed changes before a review, so a review now would be spent on a commit that is replaced.
117
- const notGreen = ci(unreviewed.head);
123
+ const notGreen = ci(head);
118
124
  if (notGreen === null) return { refusal: unreviewedRefusal(branch, unreviewed.head, head) };
119
- return { refusal: null, ciPass: { sha: unreviewed.head, reason: notGreen } };
125
+ return { refusal: null, ciPass: { sha: head, reason: notGreen } };
120
126
  }
121
127
  const current = latestVerdictFor(records, head, ["task", "branch"]);
122
128
  if (current?.verdict === "CHANGES_REQUIRED" && why === null) return { refusal: fixRoundRefusal(branch, current.sha, type) };
@@ -186,6 +192,14 @@ export function judgeTask(call, tmp = os.tmpdir(), { ci, ciState, reads = defaul
186
192
  briefNote = brief.note;
187
193
  }
188
194
  if (!taskTypeIn(type, workflow.review)) return pass(workflow, base, briefNote);
195
+ const state = (sha, checkout) => {
196
+ if (ci && !ciState) return { reason: ci(sha), unknown: null };
197
+ try {
198
+ return (ciState ?? readCiState)(sha, checkout, { requiredChecks: load(workflow.root).ci.requiredChecks });
199
+ } catch (error) {
200
+ return { reason: null, unknown: `cannot read repository CI configuration: ${error.message}` };
201
+ }
202
+ };
189
203
  if (!workflow.review.implementerTypes.includes(type)) {
190
204
  // A reviewer waits for its checks. Its worktree tells the stop which branch the verdict belongs to,
191
205
  // and a checkout the gate cannot read would skip every check, so that refuses.
@@ -193,7 +207,6 @@ export function judgeTask(call, tmp = os.tmpdir(), { ci, ciState, reads = defaul
193
207
  if (!root) return refuse(unreadableRefusal(type, `no git checkout exists at "${named}"`));
194
208
  const branch = branchOfCheckout(root);
195
209
  const head = headOf(root);
196
- const state = ciState ?? (ci ? (sha) => ({ reason: ci(sha), unknown: null }) : (sha) => readCiState(sha, root));
197
210
  let records = [];
198
211
  let ledgerNote = null;
199
212
  try {
@@ -201,7 +214,7 @@ export function judgeTask(call, tmp = os.tmpdir(), { ci, ciState, reads = defaul
201
214
  } catch (error) {
202
215
  ledgerNote = `Task gate could not read the ledger (${error.message}), so the one-review check did not run.`;
203
216
  }
204
- const checked = reviewerCheck({ type, prompt, review: workflow.review, base: workflow.base, records, root, branch, head, ciState: state, reads });
217
+ const checked = reviewerCheck({ type, prompt, review: workflow.review, base: workflow.base, records, root, branch, head, ciState: (sha) => state(sha, root), reads });
205
218
  if (checked.refusal) return refuse(checked.refusal);
206
219
  const scope = scopeOf(prompt);
207
220
  const scoped = scope && workflow.review.reviewerTypes.branch.includes(type) ? { scope } : {};
@@ -226,8 +239,8 @@ export function judgeTask(call, tmp = os.tmpdir(), { ci, ciState, reads = defaul
226
239
  const fix = fixOf(prompt);
227
240
  const { refusal, ciPass, note: fixNote } = gateVerdict({
228
241
  records, branch: worktree.branch, head: worktree.head, reason, type, cwd: workflow.root, handoff, fix,
229
- ...(ci ? { ci } : {}),
230
- ...(ciState ? { ciStatus: ciState } : {}),
242
+ ci: ci ?? ((sha) => state(sha, workflow.root).reason),
243
+ ciStatus: (sha) => state(sha, workflow.root),
231
244
  });
232
245
  if (refusal) return refuse(refusal);
233
246
  const continues = handoff ? { handoff } : {};
@@ -5,6 +5,8 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { test } from "node:test";
7
7
  import { decide as dispatchDecide } from "./dispatch-guard.mjs";
8
+ import { checkpointPathOf } from "./checkpoint.mjs";
9
+ import { runtimeTagOf } from "./dispatch-route.mjs";
8
10
  import { appendRecord, readLedger } from "./ledger.mjs";
9
11
  import { gitOut } from "./git-read.mjs";
10
12
  import { BRIEF } from "./test-brief.mjs";
@@ -36,6 +38,9 @@ function workspace(t) {
36
38
  git(main, "worktree", "add", "-q", "-b", "feat/1-x", linked);
37
39
  const tmp = path.join(base, "tmp");
38
40
  mkdirSync(tmp);
41
+ const checkpoint = checkpointPathOf(main, "s");
42
+ mkdirSync(path.dirname(checkpoint), { recursive: true });
43
+ writeFileSync(checkpoint, "## Goal\nTest the task gate.\n## Rules\nKeep the gate checks on.\n## Tasks\nDispatch the task.\n## Next\nCheck the result.\n");
39
44
  return { main, off, linked, tmp, ledger: path.join(main, ".git", "qc", "ledger.jsonl") };
40
45
  }
41
46
 
@@ -52,7 +57,7 @@ const dispatch = (cwd, prompt, subagent_type = "architecture:sdd-implementer", e
52
57
  hook_event_name: "PreToolUse",
53
58
  tool_name: "Agent",
54
59
  tool_use_id: "toolu_1",
55
- tool_input: { subagent_type, description: "Task", prompt },
60
+ tool_input: { subagent_type, description: runtimeTagOf({ subagent_type }, { codexModel: null }) + "Task", prompt },
56
61
  ...extra,
57
62
  });
58
63
  const taskPrompt = (worktree, more = "") => `Read the brief.\nBrief: ${BRIEF}\nWorktree: ${worktree}\n${more}`;
@@ -71,6 +76,22 @@ const verdict = (ws, sha, value = "APPROVED", kind = "task") =>
71
76
  appendRecord(ws.ledger, { type: "verdict", kind, verdict: value, sha, branch: "feat/1-x" });
72
77
  const refusalOf = (ws, more = "") => judgeTask(dispatch(ws.main, taskPrompt(ws.linked, more)), ws.tmp).refusal;
73
78
 
79
+ test("CI on the branch head lets an implementer continue after a controller commit", (t) => {
80
+ const ws = workspace(t);
81
+ const stopped = commitIn(ws.linked, "implementer.txt");
82
+ implementerStop(ws, stopped);
83
+ const head = commitIn(ws.linked, "controller.txt");
84
+ for (const state of ["build ended failure", "build is in_progress"]) {
85
+ const ci = (sha) => sha === head ? `CI on ${sha.slice(0, 7)}: ${state}` : null;
86
+ const task = judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp, { ci });
87
+ assert.equal(task.refusal, null);
88
+ assert.deepEqual(task.record.ciPass, { sha: head, reason: ci(head) });
89
+ const refusal = judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp, { ci: () => null }).refusal;
90
+ assert.ok(refusal.includes(`when CI on ${head.slice(0, 7)}`));
91
+ assert.match(refusal, /A prompt with no `Fix:` line passes when/);
92
+ }
93
+ });
94
+
74
95
  test("the prompt lines are read exactly", () => {
75
96
  assert.equal(worktreeNamed("x\n Worktree: C:/a b/wt \ny"), "C:/a b/wt");
76
97
  assert.equal(worktreeNamed("worktree: /tmp/wt"), "/tmp/wt");
@@ -272,7 +293,7 @@ test("an implementer the task gate refuses holds no implementer slot", (t) => {
272
293
  const ws = workspace(t);
273
294
  recordDispatch(judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp));
274
295
  implementerStop(ws, commitIn(ws.linked, "b.txt"));
275
- const output = dispatchDecide(dispatch(ws.main, taskPrompt(ws.linked), "architecture:sdd-implementer", { tool_use_id: "toolu_2" }), ws.tmp);
296
+ const output = dispatchDecide(dispatch(ws.main, taskPrompt(ws.linked, "Runtime: claude test"), "architecture:sdd-implementer", { tool_use_id: "toolu_2" }), ws.tmp);
276
297
  assert.match(output?.hookSpecificOutput?.permissionDecisionReason ?? "", /^Task gate:/);
277
298
  const slots = path.join(ws.tmp, "architecture-kit", "dispatch");
278
299
  const claims = existsSync(slots) ? readdirSync(slots, { recursive: true }).filter((name) => String(name).endsWith(".claim")) : [];
@@ -281,7 +302,7 @@ test("an implementer the task gate refuses holds no implementer slot", (t) => {
281
302
 
282
303
  test("the guard records an accepted task dispatch", (t) => {
283
304
  const ws = workspace(t);
284
- assert.equal(dispatchDecide(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp), null);
305
+ assert.equal(dispatchDecide(dispatch(ws.main, taskPrompt(ws.linked, "Runtime: claude test")), ws.tmp), null);
285
306
  assert.deepEqual(readLedger(ws.ledger).map((record) => [record.type, record.task, record.branch]), [["dispatch", true, "feat/1-x"]]);
286
307
  });
287
308
 
@@ -479,6 +500,18 @@ test("after CHANGES_REQUIRED, a continuation of the fix round's hand-off needs n
479
500
  assert.equal(refusalOf(ws, `HANDOFF: ${note}`), null);
480
501
  });
481
502
 
503
+ test("Fix: review continues only the matching hand-off of the newest stop", (t) => {
504
+ const ws = workspace(t);
505
+ const reviewed = commitIn(ws.linked, "reviewed.txt");
506
+ implementerStop(ws, reviewed);
507
+ verdict(ws, reviewed, "CHANGES_REQUIRED");
508
+ const note = path.join(ws.tmp, "handoffs", "fix-review.md");
509
+ implementerStop(ws, commitIn(ws.linked, "partial.txt"), "feat/1-x", note);
510
+ assert.match(refusalOf(ws, "Fix: review") ?? "", /no review/);
511
+ assert.match(refusalOf(ws, `Fix: review\nHANDOFF: ${note}.other`) ?? "", /no review/);
512
+ assert.equal(refusalOf(ws, `Fix: review\nHANDOFF: ${note}`), null);
513
+ });
514
+
482
515
  test("a stop that a later CHANGES_REQUIRED reviewed is no longer continued by its HANDOFF line", (t) => {
483
516
  const ws = workspace(t);
484
517
  const note = path.join(ws.tmp, "handoffs", "t1-1.md");
@@ -582,13 +615,18 @@ test("a Fix: ci line passes an unreviewed implementer commit while CI on the hea
582
615
  assert.match(refusalOf(ws) ?? "", /Fix: ci/);
583
616
  });
584
617
 
585
- test("a Fix: review line passes a fresh implementer after CHANGES_REQUIRED and over an unreviewed fix commit", (t) => {
618
+ test("a Fix: review line needs CHANGES_REQUIRED and refuses an unreviewed fix stop", (t) => {
586
619
  const ws = workspace(t);
587
620
  const moved = commitIn(ws.linked, "b.txt");
588
621
  implementerStop(ws, moved);
589
622
  verdict(ws, moved, "CHANGES_REQUIRED", "branch");
590
- implementerStop(ws, commitIn(ws.linked, "c.txt"));
623
+ assert.equal(refusalOf(ws, "Fix: review"), null);
624
+ const fixed = commitIn(ws.linked, "c.txt");
625
+ implementerStop(ws, fixed);
591
626
  assert.notEqual(refusalOf(ws), null);
627
+ assert.match(refusalOf(ws, "Fix: review") ?? "", /no review in the ledger/);
628
+ assert.match(judgeTask(dispatch(ws.main, taskPrompt(ws.linked, "Fix: review")), ws.tmp, { ci: () => "red" }).refusal ?? "", /no review in the ledger/);
629
+ verdict(ws, fixed, "CHANGES_REQUIRED");
592
630
  assert.equal(refusalOf(ws, "Fix: review"), null);
593
631
  });
594
632
 
@@ -4,7 +4,7 @@
4
4
  import { readdirSync, realpathSync, statSync } from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
- import { agentTypeOf, contextOf, readRequests } from "./transcript-usage.mjs";
7
+ import { agentTypeOf, contextOf, readHookTimings, readRequests } from "./transcript-usage.mjs";
8
8
 
9
9
  export const RATES = { read: 0.1, write5m: 1.25, write1h: 2 };
10
10
  const FIVE_MINUTES = 5 * 60_000;
@@ -16,6 +16,31 @@ const writeOf = (usage) => usage.cache_creation_input_tokens ?? 0;
16
16
  const write1hOf = (usage) => usage.cache_creation?.ephemeral_1h_input_tokens ?? 0;
17
17
  const inputOf = (usage) => usage.input_tokens ?? 0;
18
18
 
19
+ /** Branch: the first cache collapse after three consecutive warm requests of one agent. */
20
+ export function firstCollapseOf(requests) {
21
+ let warm = 0;
22
+ let ttl = FIVE_MINUTES;
23
+ for (const [index, request] of requests.entries()) {
24
+ const prompt = contextOf(request.usage);
25
+ if (prompt === 0) continue;
26
+ if (readOf(request.usage) / prompt >= 0.2) {
27
+ if (writeOf(request.usage) > 0) ttl = write1hOf(request.usage) > 0 ? ONE_HOUR : FIVE_MINUTES;
28
+ warm += 1;
29
+ continue;
30
+ }
31
+ if (warm >= 3) {
32
+ const previous = requests[index - 1];
33
+ const causes = [];
34
+ if (previous.model && request.model && previous.model !== request.model) causes.push("model change");
35
+ if (Number.isFinite(previous.at) && Number.isFinite(request.at) && request.at - previous.at > ttl) causes.push("cache expiry");
36
+ return { request: request.id ?? `#${index + 1}`, call: index + 1, cause: causes.join(" and ") || "unknown" };
37
+ }
38
+ warm = 0;
39
+ if (writeOf(request.usage) > 0) ttl = write1hOf(request.usage) > 0 ? ONE_HOUR : FIVE_MINUTES;
40
+ }
41
+ return null;
42
+ }
43
+
19
44
  function median(values) {
20
45
  if (values.length === 0) return 0;
21
46
  const sorted = [...values].sort((a, b) => a - b);
@@ -119,6 +144,10 @@ const SUMMED = ["agents", "calls", "read", "write5m", "write1h", "input", "outpu
119
144
 
120
145
  /** Per-type statistics of one session, `main` first and then by tokens read, and their total. */
121
146
  export function summarizeSession({ main = [], agents = [] }, rates = RATES) {
147
+ const collapses = [{ type: MAIN, id: MAIN, requests: main }, ...agents].flatMap((agent, index) => {
148
+ const collapse = firstCollapseOf(agent.requests);
149
+ return collapse ? [{ agent: agent.id ?? `agent-${index}`, type: agent.type, ...collapse }] : [];
150
+ });
122
151
  const byType = new Map();
123
152
  const statsOf = (type) => byType.get(type) ?? byType.set(type, emptyStats(type)).get(type);
124
153
  if (main.length > 0) addAgent(statsOf(MAIN), main, rates);
@@ -134,7 +163,7 @@ export function summarizeSession({ main = [], agents = [] }, rates = RATES) {
134
163
  sum.maxContext = Math.max(sum.maxContext, stats.maxContext);
135
164
  }
136
165
  // The types' own credits are already in their cost1h, so the total takes none of its own.
137
- return { types, total: finish(sum, rates, 0) };
166
+ return { types, total: finish(sum, rates, 0), ...(collapses.length ? { collapses } : {}) };
138
167
  }
139
168
 
140
169
  const UNKNOWN = "unknown";
@@ -244,8 +273,20 @@ export function runTokens(config, args = [], out = console.log, err = console.er
244
273
  }
245
274
  const report = summarizeSession({
246
275
  main: files.main ? readRequests(files.main) : [],
247
- agents: files.agents.map((file) => ({ type: agentTypeOf(file) ?? UNKNOWN, requests: readRequests(file) })),
276
+ agents: files.agents.map((file) => ({ id: path.basename(file, ".jsonl"), type: agentTypeOf(file) ?? UNKNOWN, requests: readRequests(file) })),
248
277
  });
278
+ const hooks = new Map();
279
+ for (const file of [files.main, ...files.agents].filter(Boolean)) {
280
+ for (const { hook, event, durationMs } of readHookTimings(file)) {
281
+ const key = JSON.stringify([hook, event]);
282
+ const stats = hooks.get(key) ?? { hook, event, calls: 0, totalMs: 0, maxMs: 0 };
283
+ stats.calls += 1;
284
+ stats.totalMs += durationMs;
285
+ stats.maxMs = Math.max(stats.maxMs, durationMs);
286
+ hooks.set(key, stats);
287
+ }
288
+ }
289
+ if (hooks.size > 0) report.hooks = [...hooks.values()];
249
290
  if (options.json) {
250
291
  out(JSON.stringify({ session: files.id, ...report }, null, 2));
251
292
  return 0;
@@ -254,5 +295,7 @@ export function runTokens(config, args = [], out = console.log, err = console.er
254
295
  out(row(COLUMNS.map(([name]) => name)));
255
296
  for (const stats of [...report.types, report.total]) out(row(COLUMNS.map(([, , cell]) => cell(stats))));
256
297
  for (const text of FOOTER) out(text);
298
+ if (report.collapses) out(`collapse: ${report.collapses.map((collapse) => `${collapse.agent} (${collapse.type}) request=${collapse.request} call=${collapse.call} likely=${collapse.cause}`).join("; ")}`);
299
+ if (hooks.size) out(`hook: ${[...hooks.values()].map((hook) => `${hook.hook} event=${hook.event} calls=${hook.calls} total=${hook.totalMs}ms avg=${Math.round(hook.totalMs / hook.calls)}ms max=${hook.maxMs}ms`).join("; ")}`);
257
300
  return 0;
258
301
  }
@@ -3,10 +3,11 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, utimesSync,
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { test } from "node:test";
6
- import { RATES, claudeDirOf, costsOf, projectKeyOf, runTokens, sessionFiles, summarizeSession } from "./tokens.mjs";
6
+ import { RATES, claudeDirOf, costsOf, firstCollapseOf, projectKeyOf, runTokens, sessionFiles, summarizeSession } from "./tokens.mjs";
7
7
  import { readRequests } from "./transcript-usage.mjs";
8
8
 
9
9
  const MINUTE = 60_000;
10
+
10
11
  const req = (id, minute, read, write, { input = 2, model = "m", w1h = 0 } = {}) => ({
11
12
  id,
12
13
  model,
@@ -20,6 +21,40 @@ const req = (id, minute, read, write, { input = 2, model = "m", w1h = 0 } = {})
20
21
  },
21
22
  });
22
23
 
24
+ test("collapse names the first request below 20 percent after three warm requests", () => {
25
+ const warm = [1, 2, 3].map((n) => req(`w${n}`, n, 800, 198));
26
+ assert.equal(firstCollapseOf(warm), null);
27
+ assert.equal(firstCollapseOf([...warm.slice(0, 2), req("early", 3, 0, 998)]), null);
28
+ assert.equal(firstCollapseOf([...warm, req("edge", 4, 200, 798)]), null);
29
+ assert.deepEqual(firstCollapseOf([...warm, req("drop", 4, 199, 799), req("later", 5, 0, 998)]),
30
+ { request: "drop", call: 4, cause: "unknown" });
31
+ assert.deepEqual(firstCollapseOf([...warm, req("changed", 4, 0, 998, { model: "other" })]),
32
+ { request: "changed", call: 4, cause: "model change" });
33
+ assert.equal(firstCollapseOf([...warm, req("empty", 4, 0, 0, { input: 0 })]), null);
34
+ });
35
+
36
+ test("collapse ignores tool lists", () => {
37
+ const warm = [1, 2, 3].map((n) => ({ ...req(`w${n}`, n, 800, 198), tools: ["Read"] }));
38
+ assert.deepEqual(firstCollapseOf([...warm, { ...req("tools", 4, 0, 998), tools: ["Read", "Skill"] }]),
39
+ { request: "tools", call: 4, cause: "unknown" });
40
+ });
41
+
42
+ test("collapse names cache expiry only after the observed cache lifetime", () => {
43
+ const warm = [1, 2, 3].map((n) => req(`w${n}`, n, 800, 198));
44
+ assert.equal(firstCollapseOf([...warm, req("expired", 9, 0, 998)]).cause, "cache expiry");
45
+ assert.equal(firstCollapseOf([...warm, req("edge", 8, 0, 998)]).cause, "unknown");
46
+ const hourly = warm.map((r) => ({ ...r, usage: { ...r.usage, cache_creation: { ephemeral_1h_input_tokens: 198 } } }));
47
+ assert.equal(firstCollapseOf([...hourly, req("warm1h", 9, 0, 998)]).cause, "unknown");
48
+ assert.equal(firstCollapseOf([...hourly, req("expired1h", 64, 0, 998)]).cause, "cache expiry");
49
+ assert.equal(firstCollapseOf([...warm, req("both", 9, 0, 998, { model: "other" })]).cause, "model change and cache expiry");
50
+ });
51
+
52
+ test("read-only warm requests preserve the last observed cache lifetime", () => {
53
+ const warm = [req("write", 1, 800, 198, { w1h: 198 }), req("read1", 2, 1000, 0), req("read2", 3, 1000, 0)];
54
+ assert.equal(firstCollapseOf([...warm, req("valid", 9, 0, 998)]).cause, "unknown");
55
+ assert.equal(firstCollapseOf([...warm, req("expired", 64, 0, 998)]).cause, "cache expiry");
56
+ });
57
+
23
58
  test("with no gap past five minutes, the one-hour lifetime only raises the write price", () => {
24
59
  const { cost, cost1h, gapMisses } = costsOf([req("a", 0, 0, 1000), req("b", 1, 1000, 100)]);
25
60
  assert.equal(cost, 1000 * 1.25 + 2 + 1000 * 0.1 + 100 * 1.25 + 2);
@@ -196,8 +231,8 @@ function fakeSession(t) {
196
231
  }
197
232
 
198
233
  test("the project key replaces each character outside letters and digits with a dash", () => {
199
- if (process.platform === "win32") assert.equal(projectKeyOf("C:\\Users\\x\\qc-mono"), "C--Users-x-qc-mono");
200
- else assert.equal(projectKeyOf("/home/u/qc-mono"), "-home-u-qc-mono");
234
+ if (process.platform === "win32") assert.equal(projectKeyOf("C:\\Users\\x\\example-app"), "C--Users-x-example-app");
235
+ else assert.equal(projectKeyOf("/home/u/example-app"), "-home-u-example-app");
201
236
  });
202
237
 
203
238
  test("the project key keeps a digit", () => {
@@ -312,6 +347,21 @@ test("qc tokens prints a table with a footer that names the rates", (t) => {
312
347
  assert.match(text, /total/);
313
348
  assert.match(text, /API list prices/);
314
349
  assert.match(text, /subagentPromptCacheTtl/);
350
+ assert.equal(lines.filter((line) => line.startsWith("collapse:")).length, 0);
351
+ });
352
+
353
+ test("qc tokens prints one collapse summary line only when it has data", (t) => {
354
+ const { dir, project } = fakeSession(t);
355
+ const files = sessionFiles({ claudeDir: dir, project, session: "s1" });
356
+ const requests = [req("cold", 0, 0, 998), ...[1, 2, 3].map((n) => req(`warm${n}`, n, 800, 198)),
357
+ req("rebuild", 4, 0, 998, { model: "other" }), req("later", 5, 0, 998)];
358
+ writeFileSync(files.main, requests.map(({ id, model, usage }) => JSON.stringify({ type: "assistant", message: { id, model, usage } })).join("\n"));
359
+ const lines = [];
360
+ runTokens({ root: project }, ["--claude-dir", dir, "--session", "s1"], (line) => lines.push(line));
361
+ assert.deepEqual(lines.filter((line) => line.startsWith("collapse:")),
362
+ ["collapse: main (main) request=rebuild call=5 likely=model change"]);
363
+ const separated = summarizeSession({ agents: requests.map((request) => ({ type: "same", requests: [request] })) });
364
+ assert.equal(Object.hasOwn(separated, "collapses"), false);
315
365
  });
316
366
 
317
367
  test("qc tokens with no session to read says so and exits 1", (t) => {
@@ -320,3 +370,53 @@ test("qc tokens with no session to read says so and exits 1", (t) => {
320
370
  assert.equal(runTokens({ root: path.join(dir, "none") }, ["--claude-dir", dir], () => {}, (text) => errors.push(text)), 1);
321
371
  assert.match(errors.join("\n"), /no session/);
322
372
  });
373
+
374
+ test("qc tokens prints one hook latency summary line, and omits absent data", (t) => {
375
+ const { dir, project } = fakeSession(t);
376
+ const files = sessionFiles({ claudeDir: dir, project, session: "s1" });
377
+ const lines = [];
378
+ const args = ["--claude-dir", dir, "--session", "s1"];
379
+ runTokens({ root: project }, args, (line) => lines.push(line));
380
+ assert.equal(lines.filter((line) => line.startsWith("hook:")).length, 0);
381
+ for (const [file, durationMs] of [[files.main, 12], [files.agents[0], 20]]) {
382
+ writeFileSync(file, JSON.stringify({ type: "attachment", attachment: {
383
+ type: "hook_cancelled", hookName: "SessionStart:startup", hookEvent: "SessionStart", durationMs,
384
+ } }));
385
+ }
386
+ lines.length = 0;
387
+ runTokens({ root: project }, args, (line) => lines.push(line));
388
+ assert.deepEqual(lines.filter((line) => line.startsWith("hook:")),
389
+ ["hook: SessionStart:startup event=SessionStart calls=2 total=32ms avg=16ms max=20ms"]);
390
+ lines.length = 0;
391
+ runTokens({ root: project }, [...args, "--json"], (line) => lines.push(line));
392
+ assert.deepEqual(JSON.parse(lines.join("\n")).hooks,
393
+ [{ hook: "SessionStart:startup", event: "SessionStart", calls: 2, totalMs: 32, maxMs: 20 }]);
394
+ });
395
+
396
+
397
+ test("qc tokens caps summaries across agents and hooks and omits empty JSON diagnostics", (t) => {
398
+ const { dir, project } = fakeSession(t);
399
+ const files = sessionFiles({ claudeDir: dir, project, session: "s1" });
400
+ const args = ["--claude-dir", dir, "--session", "s1"];
401
+ const lines = [];
402
+ runTokens({ root: project }, [...args, "--json"], (line) => lines.push(line));
403
+ const empty = JSON.parse(lines.join("\n"));
404
+
405
+ for (const [i, file] of [files.main, ...files.agents].entries()) {
406
+ const requests = [...[1, 2, 3].map((n) => req(`warm${n}`, n, 800, 198)), req("drop", 4, 0, 998)];
407
+ writeFileSync(file, [...requests.map(({ id, model, usage }) => ({ type: "assistant", message: { id, model, usage } })),
408
+ { type: "attachment", attachment: { type: "hook_success", hookName: `hook-${i}`, hookEvent: "Start", durationMs: i + 1 } },
409
+ ].map((record) => JSON.stringify(record)).join("\n"));
410
+ }
411
+ lines.length = 0;
412
+ runTokens({ root: project }, args, (line) => lines.push(line));
413
+ assert.equal(lines.filter((line) => line.startsWith("collapse:")).length, 1);
414
+ assert.equal(lines.filter((line) => line.startsWith("hook:")).length, 1);
415
+ lines.length = 0;
416
+ runTokens({ root: project }, [...args, "--json"], (line) => lines.push(line));
417
+ const report = JSON.parse(lines.join("\n"));
418
+ assert.equal(report.collapses.length, 1 + files.agents.length);
419
+ assert.equal(report.hooks.length, 1 + files.agents.length);
420
+ assert.equal(Object.hasOwn(empty, "collapses"), false);
421
+ assert.equal(Object.hasOwn(empty, "hooks"), false);
422
+ });
@@ -0,0 +1,49 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ // The tool pins live together so upgrades change one table.
6
+ const TOOLS = {
7
+ stack: { repo: "shawrylk/qc-stack", sha: "e34c270d92e3995b2e512f6eb690ea3cb0bc4699", bin: "qc-stack" },
8
+ screens: { repo: "shawrylk/qc-screens", sha: "886c303508f4406f397b2221b470115c3cb89589", bin: "qc-screens" },
9
+ "throwaway-db": { repo: "shawrylk/qc-throwaway-db", sha: "042fb52425d92ad5f656aa2c18884350ebe4dc08", bin: "qc-throwaway-db" },
10
+ };
11
+
12
+ /** Runs a pinned tool without passing its arguments through a shell. */
13
+ export async function runTool(command, argv, {
14
+ spawn: spawnChild = spawn,
15
+ fileExists = existsSync,
16
+ execPath = process.execPath,
17
+ platform = process.platform,
18
+ env = process.env,
19
+ stderr = console.error,
20
+ } = {}) {
21
+ const tool = TOOLS[command];
22
+ const paths = platform === "win32" ? path.win32 : path.posix;
23
+ const nodeDir = paths.dirname(execPath);
24
+ const npmCli = [
25
+ paths.join(nodeDir, "node_modules/npm/bin/npx-cli.js"),
26
+ paths.join(nodeDir, "../lib/node_modules/npm/bin/npx-cli.js"),
27
+ ].find(fileExists);
28
+ if (!npmCli && platform === "win32") {
29
+ stderr("qc: cannot find npx-cli.js next to node");
30
+ return 1;
31
+ }
32
+ const args = ["--yes"];
33
+ for (const pkg of command === "stack" ? [tool, TOOLS.screens] : [tool]) {
34
+ args.push("-p", `github:${pkg.repo}#${pkg.sha}`);
35
+ }
36
+ args.push(tool.bin, ...argv);
37
+ const childEnv = { ...env };
38
+ if (childEnv.npm_config_allow_git === undefined) childEnv.npm_config_allow_git = "all";
39
+ return new Promise((resolve) => {
40
+ const child = spawnChild(npmCli ? execPath : "npx", npmCli ? [npmCli, ...args] : args, {
41
+ stdio: "inherit", env: childEnv,
42
+ });
43
+ child.on("error", (error) => {
44
+ stderr(`qc: ${error.message}`);
45
+ resolve(1);
46
+ });
47
+ child.on("exit", (code) => resolve(code ?? 1));
48
+ });
49
+ }
@@ -0,0 +1,89 @@
1
+ import assert from "node:assert/strict";
2
+ import { EventEmitter } from "node:events";
3
+ import test from "node:test";
4
+ import { runTool } from "./tools.mjs";
5
+
6
+ function capture(overrides = {}) {
7
+ const calls = [];
8
+ return {
9
+ calls,
10
+ options: {
11
+ execPath: "/opt/node/bin/node",
12
+ platform: "linux",
13
+ env: { PATH: "/bin", CUSTOM: "kept" },
14
+ fileExists: (file) => file === "/opt/node/lib/node_modules/npm/bin/npx-cli.js",
15
+ spawn: (...args) => {
16
+ calls.push(args);
17
+ const child = new EventEmitter();
18
+ queueMicrotask(() => child.emit("exit", 0));
19
+ return child;
20
+ },
21
+ ...overrides,
22
+ },
23
+ };
24
+ }
25
+
26
+ test("screens uses the POSIX npm launcher and preserves argv and the caller's env", async () => {
27
+ const { calls, options } = capture();
28
+ const argv = ["--map", "path with 'quotes'.json", "--targets", "left,right", "--help"];
29
+ assert.equal(await runTool("screens", argv, options), 0);
30
+ assert.deepEqual(calls, [["/opt/node/bin/node", [
31
+ "/opt/node/lib/node_modules/npm/bin/npx-cli.js", "--yes", "-p",
32
+ "github:shawrylk/qc-screens#886c303508f4406f397b2221b470115c3cb89589", "qc-screens", ...argv,
33
+ ], { stdio: "inherit", env: { PATH: "/bin", CUSTOM: "kept", npm_config_allow_git: "all" } }]]);
34
+ assert.deepEqual(options.env, { PATH: "/bin", CUSTOM: "kept" });
35
+ });
36
+
37
+ test("stack installs both pinned packages with the Windows npm launcher and keeps an explicit git policy", async () => {
38
+ const { calls, options } = capture({
39
+ execPath: "C:\\Program Files\\nodejs\\node.exe",
40
+ platform: "win32",
41
+ env: { npm_config_allow_git: "none" },
42
+ fileExists: (file) => file === "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npx-cli.js",
43
+ });
44
+ assert.equal(await runTool("stack", ["status", "app", "--timeout", "1500"], options), 0);
45
+ assert.deepEqual(calls, [[options.execPath, [
46
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npx-cli.js", "--yes", "-p",
47
+ "github:shawrylk/qc-stack#e34c270d92e3995b2e512f6eb690ea3cb0bc4699", "-p",
48
+ "github:shawrylk/qc-screens#886c303508f4406f397b2221b470115c3cb89589", "qc-stack",
49
+ "status", "app", "--timeout", "1500",
50
+ ], { stdio: "inherit", env: { npm_config_allow_git: "none" } }]]);
51
+ const emptyPolicy = capture({ env: { npm_config_allow_git: "" } });
52
+ await runTool("stack", [], emptyPolicy.options);
53
+ assert.equal(emptyPolicy.calls[0][2].env.npm_config_allow_git, "");
54
+ });
55
+
56
+ test("throwaway-db falls back to shell-free npx on POSIX and keeps the command separator", async () => {
57
+ const { calls, options } = capture({ fileExists: () => false });
58
+ const argv = ["--port", "auto", "--", "node", "script with spaces.mjs", "a&b"];
59
+ await runTool("throwaway-db", argv, options);
60
+ assert.deepEqual(calls, [["npx", ["--yes", "-p",
61
+ "github:shawrylk/qc-throwaway-db#042fb52425d92ad5f656aa2c18884350ebe4dc08", "qc-throwaway-db", ...argv,
62
+ ], { stdio: "inherit", env: { PATH: "/bin", CUSTOM: "kept", npm_config_allow_git: "all" } }]]);
63
+ });
64
+
65
+ test("the runner passes exit codes, maps signals and spawn errors to 1, and refuses a Windows shell fallback", async () => {
66
+ for (const code of [0, 17, null]) {
67
+ const { options } = capture({ spawn: () => {
68
+ const child = new EventEmitter();
69
+ queueMicrotask(() => child.emit("exit", code, code === null ? "SIGTERM" : null));
70
+ return child;
71
+ } });
72
+ assert.equal(await runTool("screens", [], options), code ?? 1);
73
+ }
74
+ const errors = [];
75
+ const failed = capture({
76
+ stderr: (message) => errors.push(message),
77
+ spawn: () => {
78
+ const child = new EventEmitter();
79
+ queueMicrotask(() => child.emit("error", new Error("spawn failed")));
80
+ return child;
81
+ },
82
+ });
83
+ assert.equal(await runTool("screens", [], failed.options), 1);
84
+ assert.match(errors.pop(), /spawn failed/);
85
+ const missing = capture({ platform: "win32", fileExists: () => false, stderr: (message) => errors.push(message) });
86
+ assert.equal(await runTool("screens", [], missing.options), 1);
87
+ assert.equal(errors.pop(), "qc: cannot find npx-cli.js next to node");
88
+ assert.equal(missing.calls.length, 0);
89
+ });