architecture-harness 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/package.json +2 -18
  2. package/src/cli/ask.mjs +42 -0
  3. package/src/cli/ask.test.mjs +40 -0
  4. package/src/cli/check-commands.mjs +104 -7
  5. package/src/cli/check-commands.test.mjs +281 -7
  6. package/src/cli/check-full.test.mjs +152 -0
  7. package/src/cli/check.mjs +113 -0
  8. package/src/cli/check.test.mjs +45 -0
  9. package/src/cli/child-run.mjs +7 -2
  10. package/src/cli/child-run.test.mjs +17 -2
  11. package/src/cli/ci-failures.mjs +47 -9
  12. package/src/cli/ci-failures.test.mjs +116 -10
  13. package/src/cli/ci-preview.mjs +62 -0
  14. package/src/cli/ci-preview.test.mjs +85 -0
  15. package/src/cli/ci-state.mjs +2 -2
  16. package/src/cli/ci-state.test.mjs +8 -8
  17. package/src/cli/ci-template.test.mjs +79 -1
  18. package/src/cli/codex-implement.mjs +373 -44
  19. package/src/cli/codex-implement.test.mjs +775 -14
  20. package/src/cli/codex-limit.test.mjs +1 -1
  21. package/src/cli/codex-verify.mjs +230 -0
  22. package/src/cli/codex-verify.test.mjs +402 -0
  23. package/src/cli/comment-watch.mjs +391 -0
  24. package/src/cli/comment-watch.test.mjs +392 -0
  25. package/src/cli/commit-guard.mjs +3 -3
  26. package/src/cli/commit-guard.test.mjs +9 -3
  27. package/src/cli/diff-shape.mjs +162 -0
  28. package/src/cli/diff-shape.test.mjs +200 -0
  29. package/src/cli/dispatch-guard.test.mjs +7 -7
  30. package/src/cli/dispatch-reminder.mjs +18 -8
  31. package/src/cli/dispatch-reminder.test.mjs +46 -10
  32. package/src/cli/dispatch-slot.mjs +2 -2
  33. package/src/cli/dispatch-slot.test.mjs +18 -19
  34. package/src/cli/dispatch.test.mjs +3 -3
  35. package/src/cli/fleet.mjs +180 -0
  36. package/src/cli/fleet.test.mjs +213 -0
  37. package/src/cli/gate-slot.mjs +2 -1
  38. package/src/cli/gh-merge-command.mjs +5 -3
  39. package/src/cli/gh-merge-command.test.mjs +4 -0
  40. package/src/cli/gh-run.mjs +50 -7
  41. package/src/cli/gh-run.test.mjs +35 -5
  42. package/src/cli/git-read.mjs +2 -1
  43. package/src/cli/integrate-tree.mjs +47 -0
  44. package/src/cli/integrate.mjs +35 -26
  45. package/src/cli/integration-lane.mjs +3 -5
  46. package/src/cli/integration-lane.test.mjs +2 -2
  47. package/src/cli/ledger.test.mjs +12 -3
  48. package/src/cli/legs.mjs +53 -0
  49. package/src/cli/legs.test.mjs +70 -0
  50. package/src/cli/locked-tests.mjs +134 -0
  51. package/src/cli/locked-tests.test.mjs +188 -0
  52. package/src/cli/merge-guard.mjs +96 -43
  53. package/src/cli/merge-guard.test.mjs +272 -111
  54. package/src/cli/metrics.mjs +53 -0
  55. package/src/cli/metrics.test.mjs +73 -0
  56. package/src/cli/milestone.mjs +297 -0
  57. package/src/cli/milestone.test.mjs +294 -0
  58. package/src/cli/mutate.mjs +203 -0
  59. package/src/cli/mutate.test.mjs +134 -0
  60. package/src/cli/overview.mjs +131 -0
  61. package/src/cli/overview.test.mjs +137 -0
  62. package/src/cli/platform-risk.mjs +46 -0
  63. package/src/cli/platform-risk.test.mjs +38 -0
  64. package/src/cli/pr-guard.mjs +128 -0
  65. package/src/cli/pr-guard.test.mjs +154 -0
  66. package/src/cli/qc.mjs +76 -20
  67. package/src/cli/qc.test.mjs +35 -1
  68. package/src/cli/retry-failed.mjs +3 -1
  69. package/src/cli/run-log.mjs +73 -0
  70. package/src/cli/run-log.test.mjs +121 -0
  71. package/src/cli/skill-length.test.mjs +8 -0
  72. package/src/cli/tools.mjs +49 -0
  73. package/src/cli/tools.test.mjs +89 -0
  74. package/src/cli/watch.mjs +21 -8
  75. package/src/cli/watch.test.mjs +45 -21
  76. package/src/cli/work-order-guard.mjs +2 -1
  77. package/src/cli/workflow-hooks.test.mjs +1 -1
  78. package/src/cli/workflow-settings.mjs +3 -2
  79. package/src/cli/workflow-settings.test.mjs +11 -1
  80. package/src/config.mjs +64 -2
  81. package/src/config.test.mjs +93 -20
  82. package/src/consumer-package.test.mjs +3 -18
  83. package/src/descriptions.mjs +1 -0
  84. package/src/eslint/index.mjs +2 -0
  85. package/src/eslint/preset.mjs +12 -1
  86. package/src/eslint/preset.test.mjs +1 -1
  87. package/src/eslint/rules/timeless-comment.mjs +92 -0
  88. package/src/eslint/rules.test.mjs +34 -0
  89. package/src/gates/plain-language.mjs +396 -0
  90. package/src/gates/plain-language.test.mjs +210 -0
  91. package/src/global-skills.test.mjs +0 -1
  92. package/templates/docs/enforcement.md +12 -2
  93. package/templates/github/workflows/ci.yml +51 -4
  94. package/src/cli/screens-discovery.mjs +0 -60
  95. package/src/cli/screens.mjs +0 -85
  96. package/src/cli/stack.mjs +0 -14
  97. package/src/cli/throwaway-db.mjs +0 -133
  98. package/src/cli/throwaway-db.test.mjs +0 -137
  99. package/src/screens/auth-context.test.mjs +0 -41
  100. package/src/screens/auth-run.test.mjs +0 -147
  101. package/src/screens/auth.mjs +0 -223
  102. package/src/screens/auth.test.mjs +0 -76
  103. package/src/screens/capture-idle.test.mjs +0 -27
  104. package/src/screens/capture.browser-test.mjs +0 -73
  105. package/src/screens/capture.mjs +0 -176
  106. package/src/screens/capture.test.mjs +0 -28
  107. package/src/screens/catalog.browser-test.mjs +0 -32
  108. package/src/screens/catalog.mjs +0 -72
  109. package/src/screens/catalog.test.mjs +0 -36
  110. package/src/screens/chrome.mjs +0 -21
  111. package/src/screens/compare.mjs +0 -41
  112. package/src/screens/compare.test.mjs +0 -30
  113. package/src/screens/discovery.browser-test.mjs +0 -29
  114. package/src/screens/discovery.mjs +0 -158
  115. package/src/screens/discovery.test.mjs +0 -27
  116. package/src/screens/inventory.mjs +0 -69
  117. package/src/screens/inventory.test.mjs +0 -10
  118. package/src/screens/map.mjs +0 -63
  119. package/src/screens/map.test.mjs +0 -35
  120. package/src/screens/open.browser-test.mjs +0 -50
  121. package/src/screens/regions.mjs +0 -138
  122. package/src/screens/regions.test.mjs +0 -38
  123. package/src/screens/session-files.mjs +0 -39
  124. package/src/screens/session-files.test.mjs +0 -39
  125. package/src/screens/setup.browser-test.mjs +0 -49
  126. package/src/screens/setup.mjs +0 -79
  127. package/src/screens/stack-auth.browser-test.mjs +0 -30
  128. package/src/screens/stack-auth.mjs +0 -107
  129. package/src/screens/stack-auth.test.mjs +0 -65
  130. package/src/screens/write-guard.mjs +0 -26
  131. package/src/stack/stack.mjs +0 -131
  132. package/src/stack/stack.test.mjs +0 -60
  133. package/src/stack/supervisor.mjs +0 -30
@@ -0,0 +1,391 @@
1
+ #!/usr/bin/env node
2
+ // Trigger: surface GitHub comments and keep their acknowledgments in a session ledger.
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { load } from "../config.mjs";
8
+ import { PARSERS, programName } from "./bash-command-guard.mjs";
9
+ import { checkoutRootOf } from "./checkout-root.mjs";
10
+ import { commonDirOf } from "./ledger.mjs";
11
+ import { originOf } from "./git-read.mjs";
12
+ import { ghCalls, ghCommand, ghMerges } from "./gh-merge-command.mjs";
13
+ import { expandHome, parsePages, runGhAsync } from "./gh-run.mjs";
14
+ import { commandWords } from "./shell-command.mjs";
15
+
16
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
17
+ const itemKey = ({ repo, number }) => `${repo.toLowerCase()}#${number}`;
18
+ const itemUrl = /https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/(issues|pull)\/(\d+)/g;
19
+
20
+ // GitHub links no reference inside code, so a hex colour such as `#128282` names no issue.
21
+ const withoutCode = (body) => body.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, "").replace(/(`+)[^`]*?\1/g, "");
22
+
23
+ // Fragment: extract issue references from a body or a commit message.
24
+ function references(body, repo, add, linked = false) {
25
+ body = withoutCode(body);
26
+ for (const match of body.matchAll(itemUrl)) add(match[1], Number(match[3]));
27
+ if (linked) for (const match of body.matchAll(/\b([\w.-]+\/[\w.-]+)#(\d+)\b/g)) add(match[1], Number(match[2]));
28
+ if (linked) {
29
+ for (const match of body.matchAll(/(?<![\w/])#(\d+)\b/g)) add(repo, Number(match[1]));
30
+ } else {
31
+ for (const match of body.matchAll(/\b(?:fixes|refs)\s+([^\r\n]*)/gi)) references(match[1], repo, add, true);
32
+ }
33
+ }
34
+
35
+ // Fragment: read a command's body flags without running the shell.
36
+ function fields(args, cwd, review = false) {
37
+ const result = { selector: null, repo: null, body: "", state: "COMMENTED" };
38
+ args = [...args];
39
+ const values = new Set(["-R", "--repo", "-b", "--body", "-F", "--body-file", "-m", "--message", "--title", "-t", "--base", "-B", "--head", "-H", "--json", "--jq", "--template"]);
40
+ for (let i = 0; i < args.length; i++) {
41
+ if (/^-[a-zA-Z]/.test(args[i])) {
42
+ const token = args[i];
43
+ const flags = [];
44
+ for (let j = 1; j < token.length; j++) {
45
+ const flag = `-${token[j]}`;
46
+ if (values.has(flag)) {
47
+ flags.push(`-${token.slice(j)}`);
48
+ break;
49
+ }
50
+ flags.push(flag);
51
+ }
52
+ args.splice(i, 1, ...flags);
53
+ }
54
+ const attached = /^-([bmF])(.+)$/s.exec(args[i]);
55
+ const [flag, ...tail] = attached ? [`-${attached[1]}`, attached[2].replace(/^=/, "")] : args[i].split("=");
56
+ if (review) {
57
+ if (["-a", "--approve"].includes(flag)) result.state = "APPROVED";
58
+ if (["-r", "--request-changes"].includes(flag)) result.state = "CHANGES_REQUESTED";
59
+ if (["-c", "--comment"].includes(flag)) result.state = "COMMENTED";
60
+ }
61
+ if (values.has(flag)) {
62
+ const value = tail.length ? tail.join("=") : args[++i];
63
+ if (flag === "-R" || flag === "--repo") result.repo = value;
64
+ if (["-b", "--body", "-m", "--message"].includes(flag)) result.body += `\n${value ?? ""}`;
65
+ if (["-F", "--body-file"].includes(flag) && value && value !== "-") {
66
+ result.body += `\n${readFileSync(path.resolve(cwd, value), "utf8")}`;
67
+ }
68
+ } else if (/^-R.+/.test(flag)) result.repo = flag.slice(2).replace(/^=/, "");
69
+ else if (!flag.startsWith("-") && result.selector === null) result.selector = args[i];
70
+ }
71
+ return result;
72
+ }
73
+
74
+ export function watchedItems(call, origin, parse = PARSERS[call.tool_name]) {
75
+ const items = new Map();
76
+ const add = (repo, number, kind = "issue") => {
77
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo ?? "") || !Number.isSafeInteger(number) || number < 1) return;
78
+ const item = { repo: repo.toLowerCase(), number, kind };
79
+ if (items.get(itemKey(item))?.kind === "pr") item.kind = "pr";
80
+ items.set(itemKey(item), item);
81
+ };
82
+ const command = call.tool_input?.command ?? "";
83
+ for (const { words, env } of ghCalls(command, parse)) {
84
+ const { group, verb, args, repo } = ghCommand(words);
85
+ if (!["issue", "pr"].includes(group)) continue;
86
+ const found = fields(args, call.cwd ?? process.cwd(), group === "pr" && verb === "review");
87
+ const repository = found.repo ?? repo ?? env.GH_REPO ?? origin;
88
+ if (/^\d+$/.test(found.selector ?? "")) add(repository, Number(found.selector), group);
89
+ for (const match of (found.selector ?? "").matchAll(itemUrl)) add(match[1], Number(match[3]), match[2] === "pull" ? "pr" : "issue");
90
+ references(found.body, repository, add);
91
+ }
92
+ for (const segment of parse(command)) {
93
+ const [program, verb, ...args] = commandWords(segment);
94
+ if (programName(program) === "git") {
95
+ const words = [verb, ...args];
96
+ const commit = words.indexOf("commit");
97
+ if (commit !== -1) references(fields(words.slice(commit + 1), call.cwd ?? process.cwd()).body, origin, add);
98
+ }
99
+ }
100
+ const output = typeof call.tool_response === "string" ? call.tool_response : JSON.stringify(call.tool_response ?? "");
101
+ if (ghCalls(command, parse).length) for (const match of output.matchAll(itemUrl)) add(match[1], Number(match[3]), match[2] === "pull" ? "pr" : "issue");
102
+ return [...items.values()];
103
+ }
104
+
105
+ // Resource: append records so simultaneous hooks preserve each other's watches and acknowledgments.
106
+ function ledger(root, session) {
107
+ if (!session) return null;
108
+ const common = commonDirOf(root);
109
+ if (!common) return null;
110
+ const file = path.join(common, "qc", `comment-watch-${hash(session)}.jsonl`);
111
+ const items = new Map();
112
+ const own = new Set();
113
+ const reviews = new Map();
114
+ const starts = new Map();
115
+ let next = null;
116
+ try {
117
+ for (const line of readFileSync(file, "utf8").split("\n")) {
118
+ try {
119
+ const record = JSON.parse(line);
120
+ if (record.reviewStart) { starts.set(record.reviewStart, record.start); continue; }
121
+ if (record.review) { reviews.set(record.review.key, record.review); continue; }
122
+ if (record.reviewDone) { reviews.delete(record.reviewDone); continue; }
123
+ if (record.own) { for (const url of record.own) own.add(url); continue; }
124
+ if (record.next) { next = record.next; continue; }
125
+ const key = itemKey(record);
126
+ const item = items.get(key) ?? { repo: record.repo, number: record.number, seen: new Set(), pending: new Map(), prs: new Set() };
127
+ if (record.kind) item.kind = record.kind;
128
+ for (const pr of record.prs ?? []) item.prs.add(pr);
129
+ for (const pending of record.pending ?? []) item.pending.set(pending.stamp, pending);
130
+ for (const stamp of record.seen ?? []) item.seen.add(stamp);
131
+ items.set(key, item);
132
+ } catch { /* A torn record leaves earlier acknowledgments intact. */ }
133
+ }
134
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
135
+ return { items, own, reviews, starts, next, append(record) {
136
+ mkdirSync(path.dirname(file), { recursive: true });
137
+ appendFileSync(file, `\n${JSON.stringify(record)}\n`);
138
+ } };
139
+ }
140
+
141
+ // Resource: bound all gh processes in one invocation to a shared deadline.
142
+ function github(root, config, deadline, run) {
143
+ return async (repo, args) => {
144
+ const dir = Object.entries(config.github?.configDirs ?? {}).find(([owner]) => owner.toLowerCase() === repo.split("/")[0].toLowerCase())?.[1];
145
+ const env = expandHome({ GH_PROMPT_DISABLED: "1", ...(dir ? { GH_CONFIG_DIR: dir } : {}) });
146
+ if (env.GH_CONFIG_DIR && !existsSync(path.resolve(root, env.GH_CONFIG_DIR))) delete env.GH_CONFIG_DIR;
147
+ const timeoutMs = deadline - Date.now();
148
+ if (timeoutMs <= 0) throw new Error("deadline");
149
+ const text = await run(args, { cwd: root, env, timeoutMs });
150
+ if (text === null) throw new Error("gh");
151
+ const result = args.includes("--paginate") ? parsePages(text) : JSON.parse(text);
152
+ if (result === null) throw new Error("pages");
153
+ return result;
154
+ };
155
+ }
156
+
157
+ async function comments(item, gh) {
158
+ const prefix = `repos/${item.repo}`;
159
+ const list = async (endpoint) => {
160
+ const pages = await gh(item.repo, ["api", "--paginate", `${prefix}/${endpoint}?per_page=100`]);
161
+ if (!Array.isArray(pages) || !pages.every(Array.isArray)) throw new Error("pages");
162
+ return pages.flat().map(row => ({ ...row, endpoint: `${prefix}/${endpoint}` }));
163
+ };
164
+ const endpoints = [`issues/${item.number}/comments`];
165
+ if (item.kind === "pr") endpoints.push(`pulls/${item.number}/reviews`, `pulls/${item.number}/comments`);
166
+ return (await Promise.all(endpoints.map(list))).flat();
167
+ }
168
+
169
+ async function unseen(item, gh, state) {
170
+ const rows = await comments(item, gh);
171
+ for (const marker of state.reviews.values()) {
172
+ if (itemKey(marker) !== itemKey(item)) continue;
173
+ const row = rows.filter(row => row.endpoint.endsWith("/reviews") &&
174
+ !state.own.has(`${row.endpoint}:${row.id}`) && Date.parse(row.submitted_at) >= Date.parse(marker.start) &&
175
+ (marker.empty ? row.state === marker.state : hash(row.body ?? "") === marker.bodyHash))
176
+ .sort((a, b) => Date.parse(a.submitted_at) - Date.parse(b.submitted_at) || a.id - b.id)[0];
177
+ if (!row) continue;
178
+ const key = `${row.endpoint}:${row.id}`;
179
+ state.append({ own: [key] });
180
+ state.own.add(key);
181
+ state.append({ reviewDone: marker.key });
182
+ state.reviews.delete(marker.key);
183
+ }
184
+ return rows.filter((row) => !state.own.has(row.html_url) && !state.own.has(row.url) && !state.own.has(`${row.endpoint}:${row.id}`) && (row.body?.trim() || row.state))
185
+ .map((row) => ({ row, stamp: hash(JSON.stringify([row.html_url, row.id, row.updated_at ?? row.submitted_at ?? row.created_at, row.body, row.state])) }))
186
+ .filter(({ stamp }) => !item.seen?.has(stamp));
187
+ }
188
+
189
+ const bodyOf = (row) => [row.state, row.body].filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
190
+ const truncated = (row) => bodyOf(row).length > 700;
191
+ const describe = (item, row) => `@${row.user?.login ?? "unknown"} on ${itemKey(item)} ${row.html_url}: ${bodyOf(row).slice(0, 700)}${truncated(row) ? ` [truncated; read in full: gh api ${row.endpoint} --paginate]` : ""}`;
192
+ const context = (event, text) => ({ hookSpecificOutput: { hookEventName: event, additionalContext: text } });
193
+
194
+ // Ledger: retain truncated previews so a full read can acknowledge them from any hook.
195
+ function recordPreview(state, item, fresh, acknowledge = false) {
196
+ const seen = acknowledge ? fresh.filter(({ row }) => !truncated(row)).map(({ stamp }) => stamp) : [];
197
+ const pending = fresh.filter(({ row }) => truncated(row)).map(({ row, stamp }) => ({ stamp, id: row.id, endpoint: row.endpoint, url: row.url }));
198
+ if (seen.length || pending.length) state.append({ repo: item.repo, number: item.number, seen, pending });
199
+ }
200
+
201
+ // Ledger: acknowledge only pending comments covered by a successful full read.
202
+ function acknowledge(state, command, repo, number) {
203
+ const args = command.args;
204
+ const view = ["pr", "issue"].includes(command.group) && command.verb === "view" && args.includes("--comments");
205
+ const request = apiRequest(command);
206
+ const endpoint = request?.method === "GET" ? request.endpoint : null;
207
+ for (const item of state.items.values()) {
208
+ const seen = [...item.pending.values()].filter(pending => !item.seen.has(pending.stamp) && (
209
+ (view && item.repo.toLowerCase() === repo?.toLowerCase() && item.number === number &&
210
+ (pending.endpoint.includes("/issues/") || (command.group === "pr" && pending.endpoint.endsWith("/reviews")))) ||
211
+ (endpoint && (endpoint === pending.endpoint ||
212
+ (pending.endpoint.endsWith("/comments") && endpoint === pending.endpoint.replace(/\/\d+\/comments$/, `/comments/${pending.id}`))))
213
+ )).map(pending => pending.stamp);
214
+ if (seen.length) state.append({ repo: item.repo, number: item.number, seen });
215
+ }
216
+ }
217
+
218
+ // Fragment: identify a REST request and distinguish full reads from session writes.
219
+ function apiRequest(command) {
220
+ if (command.group !== "api") return null;
221
+ // API flags may precede the endpoint; keep their names with their values.
222
+ const apiWords = command.rest;
223
+ let method;
224
+ let write = false;
225
+ let endpoint;
226
+ const values = new Set(["--method", "--field", "--raw-field", "--input", "--header", "--hostname", "--jq", "--template", "--cache", "--preview"]);
227
+ for (let i = 0; i < apiWords.length; i++) {
228
+ const word = apiWords[i];
229
+ const long = /^(--[^=]+)(?:=(.*))?$/.exec(word);
230
+ if (long && values.has(long[1])) {
231
+ const value = long[2] ?? apiWords[++i];
232
+ if (long[1] === "--method") method = value;
233
+ if (["--field", "--raw-field", "--input"].includes(long[1])) write = true;
234
+ continue;
235
+ }
236
+ if (/^-[^-]/.test(word)) {
237
+ const valueFlag = /[FfHXqtp]/.exec(word.slice(1));
238
+ if (valueFlag) {
239
+ const value = word.slice(valueFlag.index + 2).replace(/^=/, "") || apiWords[++i];
240
+ if (valueFlag[0] === "X") method = value;
241
+ if (/[fF]/.test(valueFlag[0])) write = true;
242
+ }
243
+ continue;
244
+ }
245
+ if (/^(?:https:\/\/api.github.com\/)?\/?repos\//.test(word)) endpoint ??= word.replace(/^https:\/\/api.github.com\//, "").replace(/^\//, "").split("?")[0].replace(/^repos\/([^/]+\/[^/]+)/, match => match.toLowerCase());
246
+ }
247
+ return { endpoint, method: method ?? (write ? "POST" : "GET") };
248
+ }
249
+
250
+ // Fragment: keep the URLs returned by session writes, without using the account login.
251
+ function createdKeys(response, endpoint) {
252
+ if (typeof response === "string") {
253
+ try { return createdKeys(JSON.parse(response), endpoint); } catch { /* gh also prints plain URLs. */ }
254
+ return [...response.matchAll(/https:\/\/[^\s"'<>\\]+/g)].map(match => match[0]);
255
+ }
256
+ if (Array.isArray(response)) return response.flatMap(row => createdKeys(row, endpoint));
257
+ if (!response || typeof response !== "object") return [];
258
+ return [response.html_url, response.url, endpoint && response.id ? `${endpoint}:${response.id}` : null,
259
+ ...createdKeys(response.stdout ?? response.output ?? response.content ?? response.text, endpoint)].filter(Boolean);
260
+ }
261
+
262
+ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTargets } = {}) {
263
+ const root = checkoutRootOf(call.cwd ?? process.cwd());
264
+ if (!root || !call.session_id) return null;
265
+ const event = call.hook_event_name;
266
+ try {
267
+ const config = load(root);
268
+ if (config.commentWatch === false) return null;
269
+ const state = ledger(root, call.session_id);
270
+ if (!state) return null;
271
+ const deadline = Date.now() + 3500;
272
+ const gh = github(root, config, deadline, run);
273
+ if (event === "PostToolUse") {
274
+ const parse = PARSERS[call.tool_name];
275
+ if (!parse) return null;
276
+ const origin = originOf(root, 1000);
277
+ if (call.tool_response?.is_error || call.tool_response?.exit_code > 0) return null;
278
+ const watched = watchedItems(call, origin, parse);
279
+ const prs = [...state.items.values(), ...watched].filter(item => item.kind === "pr");
280
+ for (const item of watched) state.append({ ...item, prs: prs.filter(pr => pr.repo === item.repo).map(itemKey) });
281
+ for (const { words, env } of ghCalls(call.tool_input?.command ?? "", parse)) {
282
+ const command = ghCommand(words);
283
+ const request = apiRequest(command);
284
+ if (request?.method === "POST" && /^repos\/[^/]+\/[^/]+\/(?:issues(?:\/\d+\/comments)?|pulls(?:\/\d+\/(?:comments|reviews))?)$/.test(request.endpoint ?? "")) {
285
+ state.append({ own: createdKeys(call.tool_response, request.endpoint) });
286
+ }
287
+ const found = fields(command.args, root, command.group === "pr" && command.verb === "review");
288
+ const created = command.verb === "create" ? [...JSON.stringify(call.tool_response ?? "").matchAll(itemUrl)].find(match => match[2] === "pull") : null;
289
+ let repo = created?.[1] ?? [...(found.selector ?? "").matchAll(itemUrl)][0]?.[1] ?? found.repo ?? command.repo ?? env.GH_REPO ?? origin;
290
+ if (["pr", "issue"].includes(command.group) && ["create", "comment", "review"].includes(command.verb)) {
291
+ state.append({ own: createdKeys(call.tool_response) });
292
+ }
293
+ if (!repo) continue;
294
+ const selector = created?.[3] ?? found.selector;
295
+ let number = /^\d+$/.test(selector ?? "") ? Number(selector) : Number([...(selector ?? "").matchAll(itemUrl)][0]?.[3]);
296
+ if (command.group === "pr" && !["list", "status"].includes(command.verb) && (command.verb !== "create" || created)) {
297
+ const pr = await gh(repo, ["pr", "view", ...(selector ? [selector] : []), "-R", repo, "--json", "number,body"]);
298
+ number = pr.number;
299
+ const key = itemKey({ repo, number });
300
+ state.append({ repo, number, kind: "pr" });
301
+ references(pr.body ?? "", repo, (repo, number) => state.append({ repo, number, kind: "issue", prs: [key] }), true);
302
+ }
303
+ if (Number.isSafeInteger(number) && ["create", "comment", "review"].includes(command.verb)) {
304
+ const resource = command.verb === "review" ? `pulls/${number}/reviews` : `issues/${number}/comments`;
305
+ const endpoint = `repos/${repo.toLowerCase()}/${resource}`;
306
+ const keys = createdKeys(call.tool_response, endpoint);
307
+ state.append({ own: keys });
308
+ if (command.group === "pr" && command.verb === "review" && !keys.some(key => key.startsWith(`${endpoint}:`) || /(?:#pullrequestreview-\d+|\/pulls\/\d+\/reviews\/\d+)$/.test(key))) {
309
+ const body = found.body.replace(/^\n/, "");
310
+ const start = state.starts.get(hash(call.tool_input.command)) ?? new Date(Math.floor(Date.now() / 1000) * 1000).toISOString();
311
+ const review = { repo: repo.toLowerCase(), number, start, bodyHash: hash(body), empty: body.length === 0,
312
+ state: found.state };
313
+ state.append({ review: { ...review, key: randomUUID() } });
314
+ }
315
+ if (command.group === "pr" && command.verb === "review") state.append({ reviewStart: hash(call.tool_input.command), start: null });
316
+ }
317
+ acknowledge(state, command, repo, number);
318
+ }
319
+ return null;
320
+ }
321
+ if (event === "UserPromptSubmit" || event === "Stop") {
322
+ const lines = [];
323
+ const items = [...state.items.values()];
324
+ const start = Math.max(0, items.findIndex(item => itemKey(item) === state.next));
325
+ await Promise.all(items.map(async (_, i) => {
326
+ const item = items[(start + i) % items.length];
327
+ try {
328
+ const fresh = await unseen(item, gh, state);
329
+ lines.push(...fresh.map(({ row }) => describe(item, row)));
330
+ recordPreview(state, item, fresh, event === "UserPromptSubmit");
331
+ } catch { lines.push(`Comment watch: GitHub comments for ${itemKey(item)} could not be checked; retry on the next prompt.`); }
332
+ }));
333
+ return lines.length ? (event === "Stop" ? { systemMessage: lines.join("\n") } : context(event, lines.join("\n"))) : null;
334
+ }
335
+ if (event === "PreToolUse") {
336
+ const parse = PARSERS[call.tool_name];
337
+ if (!parse) return null;
338
+ if (ghCalls(call.tool_input?.command ?? "", parse).some(({ words }) => {
339
+ const command = ghCommand(words);
340
+ return command.group === "pr" && command.verb === "review";
341
+ })) state.append({ reviewStart: hash(call.tool_input.command), start: new Date(Math.floor(Date.now() / 1000) * 1000).toISOString() });
342
+ const merges = mergeTargets ?? ghMerges(call.tool_input?.command ?? "", parse);
343
+ if (!merges.length) return null;
344
+ const origin = originOf(root, 1000);
345
+ const lines = [];
346
+ let failed = false;
347
+ for (const merge of merges) {
348
+ let repo = merge.repo ?? origin;
349
+ let selector = merge.selector;
350
+ if (merge.nodeId) {
351
+ const result = await gh(repo ?? "", ["api", "graphql", "-f", `query=query { node(id: ${JSON.stringify(merge.nodeId)}) { ... on PullRequest { number repository { nameWithOwner } } } }`]);
352
+ repo = result.data?.node?.repository?.nameWithOwner;
353
+ selector = String(result.data?.node?.number ?? "");
354
+ }
355
+ if (!repo) throw new Error("repository");
356
+ const pr = await gh(repo, ["pr", "view", ...(selector ? [selector] : []), "-R", repo, "--json", "number,body,commits"]);
357
+ const targets = new Map();
358
+ const key = itemKey({ repo, number: pr.number });
359
+ const add = (repo, number, kind = "issue") => targets.set(itemKey({ repo, number }), { repo: repo.toLowerCase(), number, kind, prs: [key] });
360
+ references(pr.body ?? "", repo, add, true);
361
+ for (const commit of pr.commits ?? []) references(`${commit.messageHeadline ?? ""}\n${commit.messageBody ?? ""}`, repo, add);
362
+ for (const item of state.items.values()) {
363
+ if (item.prs.has(key) || (item.kind !== "pr" && !item.prs.size && item.repo === repo.toLowerCase())) add(item.repo, item.number, item.kind);
364
+ }
365
+ add(repo, pr.number, "pr");
366
+ await Promise.all([...targets.values()].map(async target => {
367
+ state.append(target);
368
+ const item = { ...state.items.get(itemKey(target)), ...target };
369
+ try {
370
+ const fresh = await unseen(item, gh, state);
371
+ recordPreview(state, item, fresh);
372
+ lines.push(...fresh.map(({ row }) => describe(item, row)));
373
+ }
374
+ catch { failed = true; lines.push(`GitHub comments for ${itemKey(target)} could not be checked.`); }
375
+ }));
376
+ }
377
+ if (lines.length || failed) return { hookSpecificOutput: { hookEventName: event, permissionDecision: "deny", permissionDecisionReason: `Merge guard: read these unseen GitHub comments on the next prompt before merging. Retry any failed checks.\n${lines.join("\n")}` } };
378
+ }
379
+ return null;
380
+ } catch {
381
+ const note = "Comment watch: GitHub comments could not be checked; retry on the next prompt.";
382
+ if (event === "PreToolUse") return { hookSpecificOutput: { hookEventName: event, permissionDecision: "deny", permissionDecisionReason: "Merge guard: GitHub comments could not be checked. Retry before merging." } };
383
+ return ["UserPromptSubmit", "PreToolUse"].includes(event) ? context(event, note) : { systemMessage: note };
384
+ }
385
+ }
386
+
387
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
388
+ let input = "";
389
+ for await (const chunk of process.stdin) input += chunk;
390
+ try { const result = await commentWatch(JSON.parse(input)); if (result) process.stdout.write(`${JSON.stringify(result)}\n`); } catch { /* Ignore non-hook input. */ }
391
+ }