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,152 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { runAffectedCheck, runFullCheck } from "./check.mjs";
8
+
9
+ function fixture(overrides = {}) {
10
+ const records = [], calls = [];
11
+ const options = {
12
+ platform: 'win32', git: (...args) => args[0] === 'status' ? '' : 'head',
13
+ gates: async () => ({ problems: [], lines: [] }), commands: async () => 0,
14
+ suite: async () => 0, record: (_root, value) => records.push(value),
15
+ spawn: (cmd, args) => { calls.push([cmd, args]); return { status: 0 }; },
16
+ nodeMajor: () => '22', write: () => {}, ...overrides,
17
+ };
18
+ return { options, records, calls };
19
+ }
20
+ const config = { root: 'C:\\repo with space', check: {} };
21
+ test('full check runs gates, commands, and suite, then records the clean host head', async () => {
22
+ const order = [];
23
+ const { options, records } = fixture({
24
+ gates: async () => { order.push('gates'); return { problems: [], lines: [] }; },
25
+ commands: async () => { order.push('commands'); return 0; },
26
+ suite: async () => { order.push('suite'); return 0; },
27
+ });
28
+ assert.equal(await runFullCheck(config, [], options), 0);
29
+ assert.deepEqual(order, ['gates', 'commands', 'suite']);
30
+ assert.deepEqual(records, [{ type: 'leg', os: 'windows', head: 'head', source: 'local' }]);
31
+ });
32
+ for (const stage of ['gates', 'commands', 'suite', 'dirty', 'head changed']) {
33
+ test(`records no evidence for ${stage}`, async () => {
34
+ let heads = 0;
35
+ const { options, records } = fixture({
36
+ ...(stage === 'gates' ? { gates: async () => ({ problems: [{ path: 'a', rule: 'bad', detail: 'bad' }], lines: [] }) } : {}),
37
+ ...(stage === 'commands' ? { commands: async () => 1 } : {}),
38
+ ...(stage === 'suite' ? { suite: async () => 1 } : {}),
39
+ ...(stage === 'dirty' ? { git: (...args) => args[0] === 'status' ? ' M a' : 'head' } : {}),
40
+ ...(stage === 'head changed' ? { git: (...args) => args[0] === 'status' ? '' : String(heads++) } : {}),
41
+ });
42
+ await runFullCheck(config, [], options);
43
+ assert.deepEqual(records, []);
44
+ });
45
+ }
46
+ test('Windows uses Docker and engines Node major for a Linux leg', async () => {
47
+ const { options, calls, records } = fixture();
48
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 0);
49
+ assert.equal(calls[0][0], 'docker');
50
+ assert.ok(calls[1][1].includes('node:22'));
51
+ assert.ok(calls[1][1].includes('type=bind,source=C:\\repo with space,target=/workspace'));
52
+ assert.ok(calls[1][1].some((arg) => arg.startsWith('QC_PLATFORM_GIT_DIR=/qc-git')));
53
+ assert.ok(calls[1][1].every((arg) => !arg.startsWith('GIT_DIR=') && !arg.startsWith('GIT_WORK_TREE=')));
54
+ assert.match(calls[1][1].at(-1), /mktemp -d.*git -c core.autocrlf=false -c core.eol=lf --git-dir="\$QC_PLATFORM_GIT_DIR" archive --format=tar --output="\$qc_tree\/source.tar" 'head'/);
55
+ assert.doesNotMatch(calls[1][1].at(-1), /tar --exclude/);
56
+ assert.equal(records[0].os, 'linux');
57
+ });
58
+ test('Windows falls back to WSL when Docker is absent', async () => {
59
+ const { options, records, calls } = fixture();
60
+ options.spawn = (cmd, args) => { calls.push([cmd, args]); return cmd === 'docker' ? { error: new Error('absent') } : { status: 0, stdout: '/mnt/c/repo\n' }; };
61
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 0);
62
+ assert.equal(calls.at(-1)[0], 'wsl');
63
+ assert.ok(calls.at(-1)[1].includes('/mnt/c/repo'));
64
+ assert.ok(calls.at(-1)[1].every((arg) => !arg.startsWith('GIT_DIR=') && !arg.startsWith('GIT_WORK_TREE=')));
65
+ assert.doesNotMatch(calls.at(-1)[1].at(-1), /corepack enable/);
66
+ assert.match(calls.at(-1)[1].at(-1), /git -c core.autocrlf=false -c core.eol=lf --git-dir="\$QC_PLATFORM_GIT_DIR" archive --format=tar --output="\$qc_tree\/source.tar" 'head'/);
67
+ assert.equal(records[0].os, 'linux');
68
+ });
69
+
70
+ test('the Linux view uses the pinned head bytes despite a CRLF checkout and later edits', async (t) => {
71
+ const root = mkdtempSync(path.join(os.tmpdir(), 'qc-linux-bytes-'));
72
+ t.after(() => rmSync(root, { recursive: true, force: true }));
73
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
74
+ git('init');
75
+ git('config', 'user.name', 'Fixture');
76
+ git('config', 'user.email', 'fixture@example.test');
77
+ git('config', 'core.autocrlf', 'true');
78
+ writeFileSync(path.join(root, 'source.sh'), 'echo stored\n');
79
+ git('add', 'source.sh');
80
+ git('commit', '-m', 'fixture');
81
+ rmSync(path.join(root, 'source.sh'));
82
+ git('checkout', '--', 'source.sh');
83
+ assert.equal(readFileSync(path.join(root, 'source.sh'), 'utf8'), 'echo stored\r\n');
84
+ const head = git('rev-parse', 'HEAD');
85
+ const { options, calls } = fixture({ git });
86
+ assert.equal(await runFullCheck({ root, check: {} }, ['--os', 'linux'], options), 0);
87
+ writeFileSync(path.join(root, 'source.sh'), 'echo edited\r\n');
88
+ writeFileSync(path.join(root, 'untracked.sh'), 'echo untracked\r\n');
89
+ git('add', 'source.sh');
90
+ git('commit', '-m', 'later fixture');
91
+ assert.notEqual(git('rev-parse', 'HEAD'), head);
92
+ const script = calls[1][1].at(-1).split('corepack enable && ')[0];
93
+ const bash = process.platform === 'win32' ? path.join(process.env.ProgramFiles, 'Git', 'bin', 'bash.exe') : 'sh';
94
+ assert.ok(process.platform !== 'win32' || existsSync(bash), 'Git Bash is required on Windows');
95
+ const result = spawnSync(bash, ['-xc', `${script}test "$(cat source.sh)" = 'echo stored' && test "$(wc -c < source.sh)" -eq 12 && test ! -e untracked.sh`], {
96
+ cwd: root, encoding: 'utf8', env: { ...process.env, QC_PLATFORM_GIT_DIR: git('rev-parse', '--absolute-git-dir') },
97
+ });
98
+ assert.equal(result.status, 0, result.stdout + result.stderr);
99
+ });
100
+ test('failed Docker run produces no leg and does not retry in WSL', async () => {
101
+ const { options, records, calls } = fixture();
102
+ options.spawn = (cmd, args) => { calls.push([cmd, args]); return { status: args[0] === 'info' ? 0 : 1 }; };
103
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 1);
104
+ assert.equal(calls.length, 2);
105
+ assert.deepEqual(records, []);
106
+ });
107
+ test('rejects unknown arguments and unsupported target hosts', async () => {
108
+ const { options, records } = fixture({ platform: 'linux' });
109
+ assert.equal(await runFullCheck(config, ['--os', 'windows'], options), 1);
110
+ assert.equal(await runFullCheck(config, ['a.mjs'], options), 1);
111
+ assert.deepEqual(records, []);
112
+ });
113
+
114
+ test('unavailable WSL records no Linux evidence', async () => {
115
+ const { options, records } = fixture({ spawn: () => ({ status: 1 }) });
116
+ assert.equal(await runFullCheck(config, ['--os', 'linux'], options), 1);
117
+ assert.deepEqual(records, []);
118
+ });
119
+
120
+ test('the parent records its temporary view without suppressing evidence in nested fixtures', async (t) => {
121
+ const previous = process.env.QC_PLATFORM_LEG_PARENT;
122
+ process.env.QC_PLATFORM_LEG_PARENT = config.root;
123
+ t.after(() => {
124
+ if (previous === undefined) delete process.env.QC_PLATFORM_LEG_PARENT;
125
+ else process.env.QC_PLATFORM_LEG_PARENT = previous;
126
+ });
127
+ const { options, records } = fixture();
128
+ assert.equal(await runFullCheck(config, [], options), 0);
129
+ assert.deepEqual(records, []);
130
+ assert.equal(await runFullCheck({ ...config, root: 'another-fixture' }, [], options), 0);
131
+ assert.equal(records.length, 1);
132
+ });
133
+
134
+
135
+ test('affected checks preserve gate and command failures and record only a clean unchanged supported head', async () => {
136
+ for (const stage of ['pass', 'gates', 'commands', 'gate error', 'command error', 'dirty', 'checkout dirtied', 'head changed', 'unsupported']) {
137
+ let heads = 0, statuses = 0;
138
+ const { options, records } = fixture({
139
+ ...(stage === 'gates' ? { gates: async () => ({ problems: [{ path: 'a', rule: 'bad', detail: 'bad' }], lines: [] }) } : {}),
140
+ ...(stage === 'commands' ? { commands: async () => 7 } : {}),
141
+ ...(stage === 'gate error' ? { gates: async () => { throw new Error('gate error'); } } : {}),
142
+ ...(stage === 'command error' ? { commands: async () => { throw new Error('command error'); } } : {}),
143
+ ...(stage === 'dirty' ? { git: (...args) => args[0] === 'status' ? ' M a' : 'head' } : {}),
144
+ ...(stage === 'checkout dirtied' ? { git: (...args) => args[0] === 'status' ? (statuses++ ? ' M a' : '') : 'head' } : {}),
145
+ ...(stage === 'head changed' ? { git: (...args) => args[0] === 'status' ? '' : String(heads++) } : {}),
146
+ ...(stage === 'unsupported' ? { platform: 'darwin' } : {}),
147
+ });
148
+ const code = await runAffectedCheck(config, { base: 'main' }, options);
149
+ assert.equal(code, ['gates', 'gate error', 'command error', 'unsupported'].includes(stage) ? 1 : stage === 'commands' ? 7 : 0);
150
+ assert.deepEqual(records, stage === 'pass' ? [{ type: 'leg', os: 'windows', head: 'head', source: 'local' }] : []);
151
+ }
152
+ });
@@ -0,0 +1,46 @@
1
+ // A branch that judges the newest check for each workflow and name.
2
+
3
+ const GREEN = new Set(["success", "neutral", "skipped"]);
4
+
5
+ export function checkVerdict(entry) {
6
+ if (entry.__typename === "StatusContext" || entry.context !== undefined) {
7
+ const state = entry.state?.toLowerCase();
8
+ if (state === "pending" || state === "expected") return "pending";
9
+ return GREEN.has(state) ? "passed" : "failed";
10
+ }
11
+ const status = entry.status?.toLowerCase();
12
+ if (status !== "completed") return status === "queued" ? "queued" : "pending";
13
+ return GREEN.has(entry.conclusion?.toLowerCase()) ? "passed" : "failed";
14
+ }
15
+
16
+ export function pendingCiReason(names, workflowRuns = [], requiredChecks = []) {
17
+ const open = workflowRuns.find((run) => run.status !== "completed");
18
+ if (open) return `${open.name ?? "workflow"} is ${open.status}`;
19
+ const present = new Set(names);
20
+ const missing = requiredChecks.find((name) => !present.has(name));
21
+ return missing === undefined ? null : `${missing} is missing`;
22
+ }
23
+
24
+ export function checkRunsState(runs, { workflowRuns = [], requiredChecks = [] } = {}) {
25
+ const workflowBySuite = new Map(workflowRuns.filter((run) => run.path && run.check_suite_id != null)
26
+ .map((run) => [run.check_suite_id, run.path]));
27
+ const newestByCheck = new Map();
28
+ for (const entry of runs) {
29
+ const suite = entry.check_suite?.id;
30
+ const workflow = workflowBySuite.get(suite);
31
+ const key = JSON.stringify([workflow === undefined ? ["suite", suite] : ["workflow", workflow], entry.name]);
32
+ const current = newestByCheck.get(key);
33
+ const newer = current && entry.started_at && current.started_at && entry.started_at !== current.started_at
34
+ ? entry.started_at > current.started_at
35
+ : entry.id > (current?.id ?? -1);
36
+ if (!current || newer) {
37
+ newestByCheck.set(key, entry);
38
+ }
39
+ }
40
+ const newest = [...newestByCheck.values()];
41
+ const failed = newest.find((entry) => checkVerdict(entry) === "failed");
42
+ if (failed) return { reason: `${failed.name} ended ${failed.conclusion}`, pending: false };
43
+ const open = newest.find((entry) => ["pending", "queued"].includes(checkVerdict(entry)));
44
+ const reason = open ? `${open.name} is ${open.status}` : pendingCiReason(newest.map((entry) => entry.name), workflowRuns, requiredChecks);
45
+ return { reason, pending: reason !== null };
46
+ }
@@ -0,0 +1,32 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkVerdict, checkRunsState } from "./check-verdict.mjs";
4
+
5
+ test("workflow and name identify checks across suites without merging different workflows", () => {
6
+ const older = { name: "build", status: "completed", conclusion: "cancelled", check_suite: { id: 1 }, id: 1 };
7
+ const newer = { ...older, conclusion: "success", check_suite: { id: 2 }, id: 2 };
8
+ for (const runs of [[older, newer], [newer, older]]) {
9
+ const workflowRuns = [{ check_suite_id: 1, path: "ci.yml", status: "completed" }, { check_suite_id: 2, path: "ci.yml", status: "completed" }];
10
+ assert.deepEqual(checkRunsState(runs, { workflowRuns }), { reason: null, pending: false });
11
+ assert.equal(checkRunsState(runs, { workflowRuns: [workflowRuns[0], { ...workflowRuns[1], path: "other.yml" }] }).reason, "build ended cancelled");
12
+ assert.equal(checkRunsState(runs, { workflowRuns: [workflowRuns[1]] }).reason, "build ended cancelled");
13
+ }
14
+ });
15
+
16
+ test("only success, neutral, and skipped pass a completed check", () => {
17
+ for (const conclusion of ["success", "neutral", "skipped", "failure", "cancelled", "timed_out", "action_required", "stale", "startup_failure", "future", "", null, undefined]) {
18
+ const expected = ["success", "neutral", "skipped"].includes(conclusion) ? "passed" : "failed";
19
+ assert.equal(checkVerdict({ status: "completed", conclusion }), expected);
20
+ assert.equal(checkVerdict({ status: "COMPLETED", conclusion: conclusion?.toUpperCase() }), expected);
21
+ }
22
+ });
23
+
24
+ test("unfinished checks and status contexts remain pending", () => {
25
+ for (const status of ["in_progress", "waiting", "pending", "requested", "future"]) {
26
+ assert.equal(checkVerdict({ status, conclusion: "success" }), "pending");
27
+ }
28
+ assert.equal(checkVerdict({ status: "QUEUED" }), "queued");
29
+ for (const state of ["PENDING", "EXPECTED"]) {
30
+ assert.equal(checkVerdict({ __typename: "StatusContext", state }), "pending");
31
+ }
32
+ });
package/src/cli/check.mjs CHANGED
@@ -3,6 +3,11 @@
3
3
 
4
4
  import { readFile, stat } from "node:fs/promises";
5
5
  import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { appendLeg, gitText, hostOS } from "./legs.mjs";
10
+ import { runCheckCommands, runCommand } from "./check-commands.mjs";
6
11
  import { checkFeatureAnatomy, checkNoEmptyBlock } from "../gates/eight-blocks.mjs";
7
12
  import { checkCitations, checkDocPaths, checkSelfContained, definedIds } from "../gates/citations.mjs";
8
13
  import { checkAgreement, declaredValues } from "../gates/registry-agreement.mjs";
@@ -38,6 +43,7 @@ import { checkFrontendBoundaries } from "../gates/frontend-boundaries.mjs";
38
43
  import { checkTestMirror, mirrorFolders } from "../gates/test-mirror.mjs";
39
44
  import { checkCommentStyle } from "../gates/comment-style.mjs";
40
45
  import { checkEnglishFiles, checkEnglishSource, checkTranslationPairs } from "../gates/english-source.mjs";
46
+ import { checkPlainLanguage } from "../gates/plain-language.mjs";
41
47
  import { checkAdrFormat } from "../gates/adr-format.mjs";
42
48
  import { checkConfigFloor } from "../gates/config-floor.mjs";
43
49
  import { defaults } from "../config.mjs";
@@ -50,6 +56,7 @@ import { literalRegistries } from "../registries.mjs";
50
56
  import { checkThresholdRatchet } from "../gates/threshold-ratchet.mjs";
51
57
  import { checkParity, placeholderSlices } from "../gates/parity.mjs";
52
58
  import { checkIntegrationImports } from "../gates/integration-imports.mjs";
59
+ import { checkFeatureSwitches } from "../gates/feature-switches.mjs";
53
60
  import { checkClosedSetWriters, matchedKeys } from "../gates/closed-set-writers.mjs";
54
61
  import { checkDocClaims, parseDocClaims } from "../gates/doc-claims.mjs";
55
62
  import { checkContractIdempotency, checkLedgerGrowth } from "../gates/contract-idempotency.mjs";
@@ -80,6 +87,99 @@ const PATHSPEC_BUDGET = 8_000;
80
87
 
81
88
  const read = (file) => readFile(file, "utf8").catch(() => null);
82
89
 
90
+ function nodeMajor(root) {
91
+ const engines = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).engines?.node;
92
+ const major = /\d+/.exec(engines ?? "")?.[0];
93
+ if (!major) throw new Error("package.json engines.node must name a Node major");
94
+ return major;
95
+ }
96
+
97
+ function testSuite(root) {
98
+ const manager = existsSync(path.join(root, "pnpm-lock.yaml")) ? "pnpm" : existsSync(path.join(root, "yarn.lock")) ? "yarn" : "npm";
99
+ return runCommand(root, `${manager} test`);
100
+ }
101
+
102
+ const cleanHead = (git) => git("status", "--porcelain", "--untracked-files=all") === "";
103
+
104
+ async function checkGates(config, options, write) {
105
+ const { problems, lines } = await (options.gates ?? runCheck)(config);
106
+ for (const line of lines) write(line);
107
+ for (const problem of problems) write(`FAIL ${problem.feature ?? problem.path} ${problem.rule}: ${problem.detail}`);
108
+ return problems.length === 0;
109
+ }
110
+
111
+ function recordCleanLeg(config, git, head, clean, os, record = appendLeg) {
112
+ if (process.env.QC_PLATFORM_LEG_PARENT !== config.root && clean && git("rev-parse", "HEAD") === head && cleanHead(git)) {
113
+ record(config.root, { type: "leg", os, head, source: "local" });
114
+ }
115
+ }
116
+
117
+ export async function runFullCheck(config, args = [], options = {}) {
118
+ const write = options.write ?? console.log;
119
+ const git = options.git ?? ((...words) => gitText(config.root, ...words));
120
+ const spawn = options.spawn ?? spawnSync;
121
+ const record = options.record ?? appendLeg;
122
+ const host = hostOS(options.platform);
123
+ const target = args.length === 0 ? host : args.length === 2 && args[0] === "--os" ? args[1] : null;
124
+ if (!["linux", "windows"].includes(target) || (target !== host && !(host === "windows" && target === "linux"))) {
125
+ write("check --full accepts --os linux or --os windows; cross-platform runs need Windows and target Linux");
126
+ return 1;
127
+ }
128
+ try {
129
+ const head = git("rev-parse", "HEAD");
130
+ const clean = cleanHead(git);
131
+ let code;
132
+ if (target !== host) {
133
+ const major = (options.nodeMajor ?? nodeMajor)(config.root);
134
+ const opts = { cwd: config.root, stdio: "inherit", windowsHide: true };
135
+ const docker = spawn("docker", ["info"], { ...opts, stdio: "ignore" });
136
+ const cli = path.relative(config.root, fileURLToPath(new URL("./qc.mjs", import.meta.url))).split(path.sep).join("/");
137
+ const quotedCli = `'${cli.replace(/'/g, "'\\''")}'`;
138
+ const command = `if [ -f pnpm-lock.yaml ]; then pnpm install --frozen-lockfile; else npm ci; fi && node ${quotedCli} check --full`;
139
+ // A temporary view gives Linux its own dependencies without exporting Git variables into test fixtures.
140
+ const linuxView = `qc_tree=$(mktemp -d /tmp/qc-platform.XXXXXX) && trap 'rm -rf "$qc_tree"' EXIT && git -c core.autocrlf=false -c core.eol=lf --git-dir="$QC_PLATFORM_GIT_DIR" archive --format=tar --output="$qc_tree/source.tar" '${head.replace(/'/g, "'\\''")}' && tar -xf "$qc_tree/source.tar" -C "$qc_tree" && rm "$qc_tree/source.tar" && printf 'gitdir: %s\\n' "$QC_PLATFORM_GIT_DIR" > "$qc_tree/.git" && cd "$qc_tree" && export QC_PLATFORM_LEG_PARENT="$qc_tree" && `;
141
+ const common = path.resolve(config.root, git("rev-parse", "--git-common-dir"));
142
+ const gitDir = path.resolve(config.root, git("rev-parse", "--absolute-git-dir"));
143
+ if (docker.status === 0) {
144
+ const containerGitDir = path.posix.join("/qc-git", path.relative(common, gitDir).split(path.sep).join("/"));
145
+ code = spawn("docker", ["run", "--rm", "--mount", `type=bind,source=${config.root},target=/workspace`, "--mount", `type=bind,source=${common},target=/qc-git`, "-e", `QC_PLATFORM_GIT_DIR=${containerGitDir}`, "-w", "/workspace", `node:${major}`, "sh", "-lc", `${linuxView}corepack enable && ${command}`], opts).status ?? 1;
146
+ } else {
147
+ const convert = (value) => {
148
+ const converted = spawn("wsl", ["--exec", "wslpath", "-u", value], { ...opts, stdio: "pipe", encoding: "utf8" });
149
+ if (converted.status !== 0 || !converted.stdout?.trim()) throw new Error("Linux check needs Docker or WSL");
150
+ return converted.stdout.trim();
151
+ };
152
+ const wslRoot = convert(config.root);
153
+ const wslGit = convert(gitDir);
154
+ const wslCommand = `test "$(node -p 'process.versions.node.split(String.fromCharCode(46))[0]')" = ${major} && ${command}`;
155
+ code = spawn("wsl", ["--cd", wslRoot, "--exec", "env", `QC_PLATFORM_GIT_DIR=${wslGit}`, "sh", "-lc", `${linuxView}${wslCommand}`], opts).status ?? 1;
156
+ }
157
+ } else {
158
+ if (!await checkGates(config, options, write)) return 1;
159
+ code = await (options.commands ?? runCheckCommands)(config);
160
+ if (code === 0) code = await (options.suite ?? testSuite)(config.root);
161
+ }
162
+ if (code !== 0) return code;
163
+ recordCleanLeg(config, git, head, clean, target, record);
164
+ return 0;
165
+ } catch (error) { write(`check --full: ${error.message}`); return 1; }
166
+ }
167
+
168
+ export async function runAffectedCheck(config, selection = {}, options = {}) {
169
+ const write = options.write ?? console.log;
170
+ const git = options.git ?? ((...words) => gitText(config.root, ...words));
171
+ const os = hostOS(options.platform);
172
+ try {
173
+ if (!["linux", "windows"].includes(os)) throw new Error("unsupported platform");
174
+ const head = git("rev-parse", "HEAD"), clean = cleanHead(git);
175
+ if (!await checkGates(config, options, write)) return 1;
176
+ const code = await (options.commands ?? runCheckCommands)(config, { ...selection, affected: true });
177
+ if (code !== 0) return code;
178
+ recordCleanLeg(config, git, head, clean, os, options.record);
179
+ return 0;
180
+ } catch (error) { write(`qc check: ${error.message}`); return 1; }
181
+ }
182
+
83
183
  /** A problem names a path a reader can open — forward slashes always, since every gate splits on "/". */
84
184
  const relativeTo = (root) => (file) => (path.relative(root, file) || file).split(path.sep).join("/");
85
185
 
@@ -517,10 +617,11 @@ async function contractKeys(config, lines) {
517
617
  if (text === null) return [];
518
618
  let document;
519
619
  try {
520
- const { parse } = await import("yaml");
620
+ const { importConsumerPackage } = await import("../consumer-package.mjs");
621
+ const { parse } = await importConsumerPackage("yaml", config.root);
521
622
  document = parse(text);
522
623
  } catch (error) {
523
- const rule = error?.code === "ERR_MODULE_NOT_FOUND" ? "contract-reader-unavailable" : "unreadable-contract";
624
+ const rule = ["ERR_MODULE_NOT_FOUND", "MODULE_NOT_FOUND"].includes(error?.code) ? "contract-reader-unavailable" : "unreadable-contract";
524
625
  return [{ path: contract, rule, detail: error.message }];
525
626
  }
526
627
  const problems = checkContractKeys(document, contract);
@@ -536,7 +637,7 @@ async function contractIdempotency(config, lines) {
536
637
  if (text === null) return [];
537
638
  let operations;
538
639
  try {
539
- operations = await contractOperations(text);
640
+ operations = await contractOperations(text, { root: config.root });
540
641
  } catch (error) {
541
642
  const rule = error.code === "CONTRACT_PEER_MISSING" ? "contract-reader-unavailable" : "unreadable-contract";
542
643
  return [{ path: contract, rule, detail: error.message }];
@@ -567,7 +668,7 @@ async function contractRouteAgreement(config, routes, lines) {
567
668
  if (text === null) return [];
568
669
  let operations;
569
670
  try {
570
- operations = await contractOperations(text);
671
+ operations = await contractOperations(text, { root: config.root });
571
672
  } catch (error) {
572
673
  const rule = error.code === "CONTRACT_PEER_MISSING" ? "contract-reader-unavailable" : "unreadable-contract";
573
674
  return [{ path: contract, rule, detail: error.message }];
@@ -916,6 +1017,20 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
916
1017
  }
917
1018
  }
918
1019
 
1020
+ if (enabled(config.gates, "plain-language")) {
1021
+ // Its own roots and its own extensions: a language rule asks which language, this one asks how
1022
+ // plainly, and a repository answers the two questions over different parts of its tree.
1023
+ const { roots, extensions, exclude } = config.plainLanguage;
1024
+ const extension = new RegExp(`\\.(${extensions.join("|")})$`);
1025
+ const excluded = exclude.map((pattern) => new RegExp(pattern));
1026
+ const files = roots
1027
+ .flatMap((root) => tree.under(root))
1028
+ .filter((file) => extension.test(file) && !excluded.some((pattern) => pattern.test(file)));
1029
+ const prose = await readEach(config.root, files);
1030
+ problems.push(...checkPlainLanguage(prose, config.plainLanguage));
1031
+ lines.push(`OK prose ${prose.length} file(s) in short sentences, the active voice and the approved words`);
1032
+ }
1033
+
919
1034
  if (enabled(config.gates, "adr-format")) {
920
1035
  const records = await citableFiles(config, tree, [config.adr.root]);
921
1036
  const docs = records.filter((file) => file.path.endsWith(".md"));
@@ -935,6 +1050,24 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
935
1050
  lines.push(`OK integration ${subjects.length} integration test(s), each importing the product it integrates with`);
936
1051
  }
937
1052
 
1053
+ if (enabled(config.gates, "feature-switches")) {
1054
+ let fileCount = 0;
1055
+ const switchProblems = [];
1056
+ for (const root of config.featureRoots.map(posix)) {
1057
+ for (const folder of tree.foldersIn(root)) {
1058
+ const featureRoot = join(root, folder);
1059
+ const rels = tree.under(featureRoot).filter((file) => SOURCE_EXTENSION.test(file) && !SKIP.test(`/${file}`) && !/\.spec\.[cm]?[jt]sx?$/.test(file));
1060
+ const files = await readEach(config.root, rels);
1061
+ fileCount += files.length;
1062
+ switchProblems.push(...checkFeatureSwitches(files, config.featureSwitches, featureRoot));
1063
+ }
1064
+ }
1065
+ problems.push(...switchProblems);
1066
+ lines.push(switchProblems.length === 0
1067
+ ? `OK switches ${fileCount} file(s) hold no unwire constant outside ${config.featureSwitches.file}`
1068
+ : `FAIL switches ${fileCount} file(s), ${switchProblems.length} unwire constant(s) outside ${config.featureSwitches.file}`);
1069
+ }
1070
+
938
1071
  if (enabled(config.gates, "closed-set-writers")) {
939
1072
  problems.push(...(await closedSets(config, tree, lines)));
940
1073
  }
@@ -0,0 +1,45 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import test from "node:test";
7
+ import { defaults, merge } from "../config.mjs";
8
+ import { runCheck } from "./check.mjs";
9
+
10
+ function proseFixture(t, file) {
11
+ const root = mkdtempSync(path.join(tmpdir(), "qc-prose-selection-"));
12
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
13
+ execFileSync("git", ["init", "-q"], { cwd: root });
14
+ mkdirSync(path.join(root, "docs"));
15
+ writeFileSync(path.join(root, "docs", file), "// Utilize helpers.\n");
16
+ return (plainLanguage = {}) => ({
17
+ ...merge(defaults, {
18
+ featureRoots: [],
19
+ gates: {
20
+ ...Object.fromEntries(Object.keys(defaults.gates).map((name) => [name, false])),
21
+ "plain-language": true,
22
+ },
23
+ plainLanguage: { roots: ["docs"], ...plainLanguage },
24
+ }),
25
+ root,
26
+ });
27
+ }
28
+
29
+ test("runCheck reads JavaScript comments with the default prose extensions", async (t) => {
30
+ const config = proseFixture(t, "note.js");
31
+ const { problems } = await runCheck(config());
32
+ assert.deepEqual(problems.map(({ path, rule }) => ({ path, rule })), [
33
+ { path: "docs/note.js", rule: "unapproved-word" },
34
+ ]);
35
+ });
36
+
37
+ test("runCheck honors the prose extensions and excludes", async (t) => {
38
+ const config = proseFixture(t, "note.mjs");
39
+ const extensions = await runCheck(config({ extensions: ["js"] }));
40
+ const exclude = await runCheck(config({ exclude: ["note\\.mjs$"] }));
41
+ assert.deepEqual({ extensions: extensions.problems, exclude: exclude.problems }, {
42
+ extensions: [],
43
+ exclude: [],
44
+ });
45
+ });
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, statSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { CONFIG_FILE, load } from "../config.mjs";
6
+ import { checkoutRootOf } from "./checkout-root.mjs";
7
+ import { readState, writeState } from "./budget-counter.mjs";
8
+
9
+ export const HEADINGS = ["## Goal", "## Rules", "## Tasks", "## Next"];
10
+
11
+ export function checkpointPathOf(cwd, sessionId) {
12
+ const root = checkoutRootOf(cwd);
13
+ if (!root) return null;
14
+ let git = path.join(root, ".git");
15
+ if (statSync(git).isFile()) {
16
+ const pointer = readFileSync(git, "utf8").trim();
17
+ if (!pointer.startsWith("gitdir: ")) throw new Error("Invalid Git directory pointer");
18
+ git = path.resolve(root, pointer.slice(8));
19
+ }
20
+ const common = path.join(git, "commondir");
21
+ if (existsSync(common)) git = path.resolve(git, readFileSync(common, "utf8").trim());
22
+ const session = String(sessionId ?? "session").replace(/[^A-Za-z0-9_-]/g, "_") || "session";
23
+ return path.join(git, "qc", "checkpoints", `${session}.md`);
24
+ }
25
+
26
+ /** The fragment that names a checkpoint even when its Git path cannot resolve. */
27
+ export function checkpointNameOf(cwd, sessionId) {
28
+ try {
29
+ return checkpointPathOf(cwd, sessionId) ?? "the session checkpoint";
30
+ } catch {
31
+ return "the session checkpoint";
32
+ }
33
+ }
34
+
35
+ export function checkpointProblem(text) {
36
+ const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
37
+ const missing = HEADINGS.filter((heading) => !lines.includes(heading));
38
+ if (missing.length) return `missing heading: ${missing.join(", ")}`;
39
+ return lines.length > 60 ? "exceeds 60 non-blank lines" : null;
40
+ }
41
+
42
+ export function readCheckpoint(file, { maxAgeMinutes = 30, now = Date.now() } = {}) {
43
+ try {
44
+ const text = readFileSync(file, "utf8");
45
+ const problem = checkpointProblem(text);
46
+ if (problem) return { text, problem };
47
+ const stale = maxAgeMinutes > 0 && now - statSync(file).mtimeMs > maxAgeMinutes * 60_000;
48
+ return { text, problem: stale ? `older than ${maxAgeMinutes} minutes` : null };
49
+ } catch (error) {
50
+ return { text: null, problem: error.code === "ENOENT" ? "missing file" : `cannot read file (${error.code ?? "error"})` };
51
+ }
52
+ }
53
+
54
+ export function checkpointSettingsAt(cwd) {
55
+ const root = checkoutRootOf(cwd);
56
+ return root && existsSync(path.join(root, CONFIG_FILE)) ? load(root).checkpoint : null;
57
+ }
58
+
59
+ // This reader limits each dispatch to the transcript's last 256 KiB.
60
+ function dispatchMessageOf(call) {
61
+ if (!call.transcript_path || !call.tool_use_id) return null;
62
+ let fd;
63
+ try {
64
+ fd = openSync(call.transcript_path, "r");
65
+ const size = fstatSync(fd).size;
66
+ const start = Math.max(0, size - 256 * 1024);
67
+ const buffer = Buffer.alloc(size - start);
68
+ const length = readSync(fd, buffer, 0, buffer.length, start);
69
+ const lines = buffer.subarray(0, length).toString("utf8").split(/\r?\n/);
70
+ if (start) lines.shift();
71
+ for (let i = lines.length - 1; i >= 0; i--) {
72
+ let record;
73
+ try { record = JSON.parse(lines[i]); } catch { continue; }
74
+ if (record.type !== "assistant") continue;
75
+ if (record.message?.content?.some((block) => block.type === "tool_use" && block.id === call.tool_use_id)) {
76
+ return typeof record.message.id === "string" ? record.message.id : null;
77
+ }
78
+ }
79
+ } catch {
80
+ return null;
81
+ } finally {
82
+ if (fd !== undefined) closeSync(fd);
83
+ }
84
+ return null;
85
+ }
86
+
87
+ export function checkpointRefusal(call, now = Date.now()) {
88
+ const cwd = call.cwd ?? process.cwd();
89
+ const settings = checkpointSettingsAt(cwd);
90
+ if (!settings) return null;
91
+ const file = checkpointNameOf(cwd, call.session_id);
92
+ if (file === "the session checkpoint") {
93
+ return `Checkpoint: ${file}\ncannot resolve its path. Restore the Git pointer before dispatch.\nRequired headings: ${HEADINGS.join(", ")}.`;
94
+ }
95
+ const message = dispatchMessageOf(call);
96
+ const stateFile = `${file}.dispatch.json`;
97
+ const state = message ? readState(stateFile) : {};
98
+ const at = message && state.message === message && Number.isFinite(state.at) ? Math.min(now, state.at) : now;
99
+ const checkpoint = readCheckpoint(file, { ...settings, now: at });
100
+ if (checkpoint.problem) return `Checkpoint: ${file}\n${checkpoint.problem}. Update the file before dispatch.\nRequired headings: ${HEADINGS.join(", ")}.`;
101
+ if (message && state.message !== message) {
102
+ try { writeState(stateFile, { message, at: now }); } catch { /* A lost batch record keeps the age check strict. */ }
103
+ }
104
+ return null;
105
+ }
106
+
107
+ export function checkpointNote(file) {
108
+ return `Checkpoint: ${file}\nWrite and update this file before dispatch and compaction. Use ${HEADINGS.join(", ")}; keep at most 60 non-blank lines.`;
109
+ }
110
+
111
+ export function decide(call) {
112
+ if (call.hook_event_name !== "SessionStart" || call.agent_id) return null;
113
+ const context = (additionalContext) => ({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext } });
114
+ let file;
115
+ try {
116
+ const cwd = call.cwd ?? process.cwd();
117
+ if (!checkpointSettingsAt(cwd)) return null;
118
+ file = checkpointPathOf(cwd, call.session_id);
119
+ const note = checkpointNote(file);
120
+ if (call.source !== "compact" && call.source !== "resume") return context(note);
121
+ const checkpoint = readCheckpoint(file, { maxAgeMinutes: 0 });
122
+ if (checkpoint.text === null) return context(`${note}\nCheckpoint: ${checkpoint.problem}.`);
123
+ const lines = checkpoint.text.split(/\r?\n/).filter((line) => line.trim());
124
+ const header = `Checkpoint ${file} is the source of truth for open work.\n`;
125
+ const cap = "\nCheckpoint print capped at 60 lines and 4,000 characters. Read the file for the rest.";
126
+ const preview = lines.slice(0, 60).join("\n");
127
+ const truncated = lines.length > 60 || header.length + preview.length > 4000;
128
+ return context(header + (truncated ? lines.slice(0, 58).join("\n").slice(0, Math.max(0, 4000 - header.length - cap.length)) + cap : preview));
129
+ } catch (error) {
130
+ return context(`Checkpoint${file ? ` ${file}` : ""}: cannot read (${String(error.message).replace(/[\r\n]+/g, " ")}).`);
131
+ }
132
+ }
133
+
134
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
135
+ try {
136
+ let input = "";
137
+ for await (const chunk of process.stdin) input += chunk;
138
+ const result = decide(JSON.parse(input));
139
+ if (result) process.stdout.write(JSON.stringify(result));
140
+ } catch {
141
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: "Checkpoint: cannot read hook input." } }));
142
+ }
143
+ }