architecture-harness 0.29.2 → 0.29.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.29.2",
3
+ "version": "0.29.4",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -2,6 +2,7 @@
2
2
  // Trigger: surface GitHub comments and keep their acknowledgments in a session ledger.
3
3
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
+ import { execFile } from "node:child_process";
5
6
  import path from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
8
  import { load } from "../config.mjs";
@@ -10,11 +11,23 @@ import { checkoutRootOf } from "./checkout-root.mjs";
10
11
  import { commonDirOf } from "./ledger.mjs";
11
12
  import { originOf } from "./git-read.mjs";
12
13
  import { ghCalls, ghCommand, ghMerges } from "./gh-merge-command.mjs";
13
- import { expandHome, parsePages, runGhAsync } from "./gh-run.mjs";
14
+ import { expandHome, parsePages } from "./gh-run.mjs";
14
15
  import { commandWords } from "./shell-command.mjs";
15
16
 
16
17
  const hash = (value) => createHash("sha256").update(value).digest("hex");
17
18
  const itemKey = ({ repo, number }) => `${repo.toLowerCase()}#${number}`;
19
+ // Prompt and Stop hooks have 5 seconds. The merge guard hook has 25 seconds and also spends up to 6 seconds on its lane.
20
+ const POLL_DEADLINE_MS = 3500;
21
+ const MERGE_DEADLINE_MS = 10_000;
22
+ const PAGE_SIZE = 100;
23
+ // A later `since` read starts this far before the last check, so local clock skew cannot hide a comment.
24
+ const SINCE_MARGIN_MS = 10 * 60_000;
25
+ // A /dev/null comment matches only the viewer's comment created in this window around the post-tool hook.
26
+ const POSTED_BEFORE_MS = 2 * 60_000;
27
+ const POSTED_AFTER_MS = 60_000;
28
+ const MARKER_TTL_MS = 10 * 60_000;
29
+ const iso = (ms) => new Date(Math.floor(ms / 1000) * 1000).toISOString();
30
+ const bodyText = (body) => (body ?? "").split("\r").join("").trim();
18
31
  const itemUrl = /https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/(issues|pull)\/(\d+)/g;
19
32
 
20
33
  // GitHub links no reference inside code, so a hex colour such as `#128282` names no issue.
@@ -28,7 +41,7 @@ function references(body, repo, add, linked = false) {
28
41
  if (linked) {
29
42
  for (const match of body.matchAll(/(?<![\w/])#(\d+)\b/g)) add(repo, Number(match[1]));
30
43
  } else {
31
- for (const match of body.matchAll(/\b(?:fixes|refs)\s+([^\r\n]*)/gi)) references(match[1], repo, add, true);
44
+ for (const match of body.matchAll(/\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|refs)\s+([^\n\r]*)/gi)) references(match[1], repo, add, true);
32
45
  }
33
46
  }
34
47
 
@@ -81,7 +94,12 @@ export function watchedItems(call, origin, parse = PARSERS[call.tool_name]) {
81
94
  };
82
95
  const command = call.tool_input?.command ?? "";
83
96
  for (const { words, env } of ghCalls(command, parse)) {
84
- const { group, verb, args, repo } = ghCommand(words);
97
+ const parsed = { ...ghCommand(words), env };
98
+ const { group, verb, args, repo } = parsed;
99
+ if (group === "api") {
100
+ const match = /^repos\/([^/]+\/[^/]+)\/(issues|pulls)\/(\d+)(?:\/|$)/.exec(apiRequest(parsed)?.endpoint ?? "");
101
+ if (match) add(match[1], Number(match[3]), match[2] === "pulls" ? "pr" : "issue");
102
+ }
85
103
  if (!["issue", "pr"].includes(group)) continue;
86
104
  const found = fields(args, call.cwd ?? process.cwd(), group === "pr" && verb === "review");
87
105
  const repository = found.repo ?? repo ?? env.GH_REPO ?? origin;
@@ -102,6 +120,11 @@ export function watchedItems(call, origin, parse = PARSERS[call.tool_name]) {
102
120
  return [...items.values()];
103
121
  }
104
122
 
123
+ // Ledger: a named command reactivates a retired item without invalidating active watches.
124
+ function watch(state, item) {
125
+ state.append({ ...item, retired: false, ...(state.items.get(itemKey(item))?.retired ? { updatedAt: null } : {}) });
126
+ }
127
+
105
128
  // Resource: append records so simultaneous hooks preserve each other's watches and acknowledgments.
106
129
  function ledger(root, session) {
107
130
  if (!session) return null;
@@ -112,32 +135,53 @@ function ledger(root, session) {
112
135
  const own = new Set();
113
136
  const reviews = new Map();
114
137
  const starts = new Map();
138
+ const viewers = new Map();
115
139
  let next = null;
116
140
  try {
117
141
  for (const line of readFileSync(file, "utf8").split("\n")) {
118
142
  try {
119
143
  const record = JSON.parse(line);
144
+ if (record.viewer?.owner && record.viewer.login) { viewers.set(record.viewer.owner, record.viewer.login); continue; }
120
145
  if (record.reviewStart) { starts.set(record.reviewStart, record.start); continue; }
121
146
  if (record.review) { reviews.set(record.review.key, record.review); continue; }
122
147
  if (record.reviewDone) { reviews.delete(record.reviewDone); continue; }
123
148
  if (record.own) { for (const url of record.own) own.add(url); continue; }
124
149
  if (record.next) { next = record.next; continue; }
150
+ if (typeof record.retired === "string") { const item = items.get(record.retired); if (item) item.retired = true; continue; }
125
151
  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() };
152
+ const item = items.get(key) ?? { repo: record.repo, number: record.number, seen: new Set(), shown: new Set(), pending: new Map(), prs: new Set(), cursors: new Map() };
127
153
  if (record.kind) item.kind = record.kind;
154
+ if (record.cursor?.endpoint) item.cursors.set(record.cursor.endpoint, record.cursor);
155
+ if (record.retired === false) item.retired = false;
156
+ if (record.updatedAt !== undefined) item.updatedAt = record.updatedAt;
128
157
  for (const pr of record.prs ?? []) item.prs.add(pr);
129
158
  for (const pending of record.pending ?? []) item.pending.set(pending.stamp, pending);
130
159
  for (const stamp of record.seen ?? []) item.seen.add(stamp);
160
+ for (const stamp of record.shown ?? []) item.shown.add(stamp);
131
161
  items.set(key, item);
132
162
  } catch { /* A torn record leaves earlier acknowledgments intact. */ }
133
163
  }
134
164
  } catch (error) { if (error.code !== "ENOENT") throw error; }
135
- return { items, own, reviews, starts, next, append(record) {
165
+ return { items, own, reviews, starts, viewers, next, append(record) {
136
166
  mkdirSync(path.dirname(file), { recursive: true });
137
167
  appendFileSync(file, `\n${JSON.stringify(record)}\n`);
138
168
  } };
139
169
  }
140
170
 
171
+ const rateLimited = (error) => /rate.?limit|RATE_LIMITED/i.test(String(error));
172
+ const failureReason = (error) => rateLimited(error) ? "rate limit" : ["deadline", "pages", "response"].includes(error.message) ? error.message : "gh";
173
+
174
+ // Resource: retain only a safe failure category from gh stderr.
175
+ function runCommentGh(args, { cwd, env, timeoutMs }) {
176
+ return new Promise((resolve, reject) => {
177
+ execFile("gh", args, { cwd, env: { ...process.env, ...env }, encoding: "utf8", windowsHide: true,
178
+ timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
179
+ if (error) reject(new Error(rateLimited(stderr) ? "rate limit" : error.killed ? "deadline" : "gh"));
180
+ else resolve(stdout);
181
+ });
182
+ });
183
+ }
184
+
141
185
  // Resource: bound all gh processes in one invocation to a shared deadline.
142
186
  function github(root, config, deadline, run) {
143
187
  return async (repo, args) => {
@@ -154,26 +198,107 @@ function github(root, config, deadline, run) {
154
198
  };
155
199
  }
156
200
 
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
- };
201
+ // Fragment: read one endpoint page by page from the item's cursor, and keep the progress of each full page.
202
+ // Comment endpoints accept `since`; the reviews endpoint does not, so its cursor keeps the last page instead.
203
+ async function readEndpoint(item, endpoint, gh, rows, progress, fromStart) {
204
+ const full = `repos/${item.repo}/${endpoint}`;
205
+ const since = !endpoint.endsWith("/reviews");
206
+ const cursor = item.cursors?.get(endpoint) ?? {};
207
+ const started = cursor.started ?? iso(Date.now());
208
+ // A merge reads from page 1: an edit moves a comment to an earlier `since` page, and reviews have no `since`.
209
+ let page = !fromStart && Number.isSafeInteger(cursor.page) && cursor.page > 0 ? cursor.page : 1;
210
+ for (;;) {
211
+ const query = [`per_page=${PAGE_SIZE}`, ...(since && cursor.since ? [`since=${cursor.since}`] : []), `page=${page}`].join("&");
212
+ const result = await gh(item.repo, ["api", `${full}?${query}`]);
213
+ if (!Array.isArray(result)) throw new Error("pages");
214
+ rows.push(...result.map(row => ({ ...row, endpoint: full })));
215
+ if (result.length < PAGE_SIZE) break;
216
+ // A resumed scan reads this full page again, so a deleted comment that shifts the pages hides no row.
217
+ progress.set(endpoint, { endpoint, since: cursor.since ?? null, page, started });
218
+ page++;
219
+ }
220
+ progress.set(endpoint, since ? { endpoint, since: iso(Date.parse(started) - SINCE_MARGIN_MS), page: 1 } : { endpoint, page });
221
+ }
222
+
223
+ async function comments(item, gh, progress, fromStart) {
164
224
  const endpoints = [`issues/${item.number}/comments`];
165
225
  if (item.kind === "pr") endpoints.push(`pulls/${item.number}/reviews`, `pulls/${item.number}/comments`);
166
- return (await Promise.all(endpoints.map(list))).flat();
226
+ const rows = [];
227
+ const results = await Promise.allSettled(endpoints.map(endpoint => readEndpoint(item, endpoint, gh, rows, progress, fromStart)));
228
+ return { rows, error: results.find(result => result.status === "rejected")?.reason };
229
+ }
230
+
231
+ function saveCursors(state, item, progress) {
232
+ for (const cursor of progress.values()) state.append({ repo: item.repo, number: item.number, cursor });
233
+ }
234
+
235
+ const ownRow = (state, row) => state.own.has(row.html_url) || state.own.has(row.url) || state.own.has(`${row.endpoint}:${row.id}`);
236
+ const previewOf = (row) => ({ id: row.id, url: row.url, html_url: row.html_url, endpoint: row.endpoint, user: { login: row.user?.login },
237
+ state: row.state, body: (row.body ?? "").slice(0, 700), truncated: true });
238
+
239
+ // Fragment: pending rows the session has not acknowledged; a legacy record without a preview still names its comment.
240
+ function pendingRows(item, all) {
241
+ return [...(item.pending?.values() ?? [])].filter(pending => !item.seen?.has(pending.stamp) && (all || pending.row))
242
+ .map(pending => ({ stamp: pending.stamp, row: pending.row ?? pending.preview ??
243
+ { id: pending.id, url: pending.url, html_url: pending.url, endpoint: pending.endpoint, body: "", truncated: true } }));
244
+ }
245
+
246
+ // Fragment: ask for every watched item's metadata in one request per repository.
247
+ async function itemMetadata(repo, items, gh) {
248
+ const [owner, name] = repo.split("/");
249
+ const fields = items.map(item => `item_${item.number}: issueOrPullRequest(number: ${item.number}) { __typename ... on Issue { state updatedAt } ... on PullRequest { state updatedAt } }`).join(" ");
250
+ const result = await gh(repo, ["api", "graphql", "-f", `owner=${owner}`, "-f", `name=${name}`,
251
+ "-f", `query=query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`]);
252
+ if (result.errors?.length) throw new Error(result.errors.some(error => rateLimited(`${error.type} ${error.message}`)) ? "rate limit" : "response");
253
+ if (!result.data?.repository) throw new Error("response");
254
+ return result.data.repository;
255
+ }
256
+
257
+ // Fragment: new rows since the item's cursor plus the pending rows not yet acknowledged.
258
+ // A failed read keeps the rows it got as pending, saves its page progress, and throws.
259
+ // Resource: the gh account login for a repository owner, cached in the ledger.
260
+ async function viewerLogin(state, repo, gh) {
261
+ const owner = repo.split("/")[0].toLowerCase();
262
+ if (state.viewers.has(owner)) return state.viewers.get(owner);
263
+ try {
264
+ const login = (await gh(repo, ["api", "user"]))?.login;
265
+ if (typeof login !== "string" || !login) return null;
266
+ state.append({ viewer: { owner, login } });
267
+ state.viewers.set(owner, login);
268
+ return login;
269
+ } catch {
270
+ // Without the login no comment can match the marker, so the comment stays unseen; that is the safe side.
271
+ return null;
272
+ }
273
+ }
274
+
275
+ // Fragment: claim the session's /dev/null comment by viewer login, body, and the time nearest the post.
276
+ async function claimComment(marker, item, rows, gh, state) {
277
+ const posted = Date.parse(marker.posted);
278
+ const candidates = Number.isNaN(posted) ? [] : rows.filter(row => row.endpoint.endsWith(`/issues/${item.number}/comments`) &&
279
+ !state.own.has(`${row.endpoint}:${row.id}`) && hash(bodyText(row.body)) === marker.bodyHash &&
280
+ Date.parse(row.created_at) >= posted - POSTED_BEFORE_MS && Date.parse(row.created_at) <= posted + POSTED_AFTER_MS);
281
+ const login = candidates.length ? await viewerLogin(state, item.repo, gh) : null;
282
+ const row = candidates.filter(row => login && row.user?.login?.toLowerCase() === login.toLowerCase())
283
+ .sort((a, b) => Math.abs(Date.parse(a.created_at) - posted) - Math.abs(Date.parse(b.created_at) - posted) || a.id - b.id)[0];
284
+ if (row) return row;
285
+ if (Number.isNaN(posted) || Date.now() > posted + MARKER_TTL_MS) {
286
+ state.append({ reviewDone: marker.key });
287
+ state.reviews.delete(marker.key);
288
+ }
289
+ return null;
167
290
  }
168
291
 
169
- async function unseen(item, gh, state) {
170
- const rows = await comments(item, gh);
171
- for (const marker of state.reviews.values()) {
292
+ async function unseen(item, gh, state, fromStart = false) {
293
+ const progress = new Map();
294
+ const { rows, error } = await comments(item, gh, progress, fromStart);
295
+ for (const marker of [...state.reviews.values()]) {
172
296
  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];
297
+ const row = marker.kind === "comment" ? await claimComment(marker, item, rows, gh, state)
298
+ : rows.filter(row => row.endpoint.endsWith("/reviews") &&
299
+ !state.own.has(`${row.endpoint}:${row.id}`) && Date.parse(row.submitted_at) >= Date.parse(marker.start) &&
300
+ (marker.empty ? row.state === marker.state : hash(row.body ?? "") === marker.bodyHash))
301
+ .sort((a, b) => Date.parse(a.submitted_at) - Date.parse(b.submitted_at) || a.id - b.id)[0];
177
302
  if (!row) continue;
178
303
  const key = `${row.endpoint}:${row.id}`;
179
304
  state.append({ own: [key] });
@@ -181,21 +306,33 @@ async function unseen(item, gh, state) {
181
306
  state.append({ reviewDone: marker.key });
182
307
  state.reviews.delete(marker.key);
183
308
  }
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))
309
+ const fresh = new Map(rows.filter((row) => !ownRow(state, row) && (row.body?.trim() || row.state))
185
310
  .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));
311
+ .filter(({ stamp }) => !item.seen?.has(stamp)).map(entry => [entry.stamp, entry]));
312
+ const read = [...fresh.values()];
313
+ for (const entry of pendingRows(item, true)) if (!fresh.has(entry.stamp) && !ownRow(state, entry.row)) fresh.set(entry.stamp, entry);
314
+ if (error) {
315
+ const kept = read.filter(({ stamp }) => !item.pending?.has(stamp))
316
+ .map(({ row, stamp }) => ({ stamp, id: row.id, endpoint: row.endpoint, url: row.url, ...(truncated(row) ? { preview: previewOf(row) } : { row }) }));
317
+ if (kept.length) state.append({ repo: item.repo, number: item.number, pending: kept });
318
+ saveCursors(state, item, progress);
319
+ throw error;
320
+ }
321
+ return { fresh: [...fresh.values()], progress };
187
322
  }
188
323
 
189
324
  const bodyOf = (row) => [row.state, row.body].filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
190
- const truncated = (row) => bodyOf(row).length > 700;
325
+ const truncated = (row) => row.truncated === true || bodyOf(row).length > 700;
191
326
  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
327
  const context = (event, text) => ({ hookSpecificOutput: { hookEventName: event, additionalContext: text } });
193
328
 
194
329
  // Ledger: retain truncated previews so a full read can acknowledge them from any hook.
195
330
  function recordPreview(state, item, fresh, acknowledge = false) {
196
331
  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 });
332
+ const shown = fresh.filter(({ row }) => truncated(row)).map(({ stamp }) => stamp);
333
+ const pending = fresh.filter(({ row }) => truncated(row) || !acknowledge)
334
+ .map(({ row, stamp }) => ({ stamp, id: row.id, endpoint: row.endpoint, url: row.url, ...(!truncated(row) ? { row } : { preview: previewOf(row) }) }));
335
+ if (seen.length || pending.length) state.append({ repo: item.repo, number: item.number, seen, shown, pending });
199
336
  }
200
337
 
201
338
  // Ledger: acknowledge only pending comments covered by a successful full read.
@@ -221,8 +358,10 @@ function apiRequest(command) {
221
358
  // API flags may precede the endpoint; keep their names with their values.
222
359
  const apiWords = command.rest;
223
360
  let method;
361
+ let hostname = command.env?.GH_HOST ?? "github.com";
224
362
  let write = false;
225
363
  let endpoint;
364
+ let endpointHost;
226
365
  const values = new Set(["--method", "--field", "--raw-field", "--input", "--header", "--hostname", "--jq", "--template", "--cache", "--preview"]);
227
366
  for (let i = 0; i < apiWords.length; i++) {
228
367
  const word = apiWords[i];
@@ -230,6 +369,7 @@ function apiRequest(command) {
230
369
  if (long && values.has(long[1])) {
231
370
  const value = long[2] ?? apiWords[++i];
232
371
  if (long[1] === "--method") method = value;
372
+ if (long[1] === "--hostname") hostname = value;
233
373
  if (["--field", "--raw-field", "--input"].includes(long[1])) write = true;
234
374
  continue;
235
375
  }
@@ -242,8 +382,13 @@ function apiRequest(command) {
242
382
  }
243
383
  continue;
244
384
  }
245
- if (/^(?:https:\/\/api.github.com\/)?\/?repos\//.test(word)) endpoint ??= word.replace(/^https:\/\/api.github.com\//, "").replace(/^\//, "").split("?")[0].replace(/^repos\/([^/]+\/[^/]+)/, match => match.toLowerCase());
385
+ if (!endpoint && /^(?:https:\/\/api.github.com\/)?\/?repos\//.test(word)) {
386
+ endpointHost = word.startsWith("https://api.github.com/") ? "github.com" : undefined;
387
+ endpoint = word.replace(/^https:\/\/api.github.com\//, "").replace(/^\//, "").split("?")[0].replace(/^repos\/([^/]+\/[^/]+)/, match => match.toLowerCase());
388
+ }
246
389
  }
390
+ // Watch identities and comment requests currently cover GitHub.com only.
391
+ if ((endpointHost ?? hostname)?.toLowerCase() !== "github.com") return null;
247
392
  return { endpoint, method: method ?? (write ? "POST" : "GET") };
248
393
  }
249
394
 
@@ -259,7 +404,7 @@ function createdKeys(response, endpoint) {
259
404
  ...createdKeys(response.stdout ?? response.output ?? response.content ?? response.text, endpoint)].filter(Boolean);
260
405
  }
261
406
 
262
- export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTargets } = {}) {
407
+ export async function commentWatch(call, { gh: run = runCommentGh, merges: mergeTargets } = {}) {
263
408
  const root = checkoutRootOf(call.cwd ?? process.cwd());
264
409
  if (!root || !call.session_id) return null;
265
410
  const event = call.hook_event_name;
@@ -268,7 +413,7 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
268
413
  if (config.commentWatch === false) return null;
269
414
  const state = ledger(root, call.session_id);
270
415
  if (!state) return null;
271
- const deadline = Date.now() + 3500;
416
+ const deadline = Date.now() + (event === "PreToolUse" ? MERGE_DEADLINE_MS : POLL_DEADLINE_MS);
272
417
  const gh = github(root, config, deadline, run);
273
418
  if (event === "PostToolUse") {
274
419
  const parse = PARSERS[call.tool_name];
@@ -276,10 +421,11 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
276
421
  const origin = originOf(root, 1000);
277
422
  if (call.tool_response?.is_error || call.tool_response?.exit_code > 0) return null;
278
423
  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) });
424
+ // Only a PR named in the same command links an item; a later merge reads the PR body and commits for the rest.
425
+ const prs = watched.filter(item => item.kind === "pr");
426
+ for (const item of watched) watch(state, { ...item, prs: prs.filter(pr => pr.repo === item.repo).map(itemKey) });
281
427
  for (const { words, env } of ghCalls(call.tool_input?.command ?? "", parse)) {
282
- const command = ghCommand(words);
428
+ const command = { ...ghCommand(words), env };
283
429
  const request = apiRequest(command);
284
430
  if (request?.method === "POST" && /^repos\/[^/]+\/[^/]+\/(?:issues(?:\/\d+\/comments)?|pulls(?:\/\d+\/(?:comments|reviews))?)$/.test(request.endpoint ?? "")) {
285
431
  state.append({ own: createdKeys(call.tool_response, request.endpoint) });
@@ -297,14 +443,20 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
297
443
  const pr = await gh(repo, ["pr", "view", ...(selector ? [selector] : []), "-R", repo, "--json", "number,body"]);
298
444
  number = pr.number;
299
445
  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);
446
+ watch(state, { repo, number, kind: "pr" });
447
+ references(pr.body ?? "", repo, (repo, number) => watch(state, { repo, number, kind: "issue", prs: [key] }), true);
302
448
  }
303
449
  if (Number.isSafeInteger(number) && ["create", "comment", "review"].includes(command.verb)) {
304
450
  const resource = command.verb === "review" ? `pulls/${number}/reviews` : `issues/${number}/comments`;
305
451
  const endpoint = `repos/${repo.toLowerCase()}/${resource}`;
306
452
  const keys = createdKeys(call.tool_response, endpoint);
307
453
  state.append({ own: keys });
454
+ // Output sent to /dev/null carries no URL, so the next read matches the session's comment by author, body, and time.
455
+ const comment = bodyText(found.body);
456
+ if (command.verb === "comment" && comment && !keys.some(key => key.startsWith(`${endpoint}:`) || /#issuecomment-\d+$/.test(key))) {
457
+ state.append({ review: { kind: "comment", repo: repo.toLowerCase(), number, posted: new Date().toISOString(),
458
+ bodyHash: hash(comment), key: randomUUID() } });
459
+ }
308
460
  if (command.group === "pr" && command.verb === "review" && !keys.some(key => key.startsWith(`${endpoint}:`) || /(?:#pullrequestreview-\d+|\/pulls\/\d+\/reviews\/\d+)$/.test(key))) {
309
461
  const body = found.body.replace(/^\n/, "");
310
462
  const start = state.starts.get(hash(call.tool_input.command)) ?? new Date(Math.floor(Date.now() / 1000) * 1000).toISOString();
@@ -320,16 +472,61 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
320
472
  }
321
473
  if (event === "UserPromptSubmit" || event === "Stop") {
322
474
  const lines = [];
323
- const items = [...state.items.values()];
475
+ if (event === "UserPromptSubmit") for (const item of state.items.values()) {
476
+ if (!item.retired) continue;
477
+ const pending = [...item.pending.values()].filter(pending => pending.row && !item.seen.has(pending.stamp)).map(({ row, stamp }) => ({ row, stamp }));
478
+ lines.push(...pending.map(({ row }) => describe(item, row)));
479
+ recordPreview(state, item, pending, true);
480
+ }
481
+ const items = [...state.items.values()].filter(item => !item.retired);
324
482
  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];
483
+ const ordered = [...items.slice(start), ...items.slice(0, start)];
484
+ const repos = new Map();
485
+ for (const item of ordered) {
486
+ const repo = item.repo.toLowerCase();
487
+ if (!repos.has(repo)) repos.set(repo, []);
488
+ repos.get(repo).push(item);
489
+ }
490
+ let failed = 0;
491
+ let checked = 0;
492
+ const reasons = new Set();
493
+ let stopped = false;
494
+ const metadataByRepo = new Map();
495
+ const stopAfter = (item) => {
496
+ stopped = true;
497
+ state.append({ next: itemKey(ordered[(ordered.indexOf(item) + 1) % ordered.length]) });
498
+ };
499
+ for (const item of ordered) {
500
+ const repo = item.repo.toLowerCase();
501
+ if (!metadataByRepo.has(repo)) {
502
+ try {
503
+ metadataByRepo.set(repo, { data: await itemMetadata(item.repo, repos.get(repo), gh) });
504
+ } catch (error) {
505
+ metadataByRepo.set(repo, { error });
506
+ }
507
+ }
327
508
  try {
328
- const fresh = await unseen(item, gh, state);
329
- lines.push(...fresh.map(({ row }) => describe(item, row)));
509
+ const { data: metadata, error } = metadataByRepo.get(repo);
510
+ if (error) throw error;
511
+ const info = metadata[`item_${item.number}`];
512
+ if (!info || !["OPEN", "CLOSED", "MERGED"].includes(info.state) || typeof info.updatedAt !== "string" || !info.updatedAt) throw new Error("response");
513
+ if (info.__typename === "PullRequest") item.kind = "pr";
514
+ const changed = info.updatedAt !== item.updatedAt;
515
+ const { fresh, progress } = changed ? await unseen(item, gh, state) : { fresh: pendingRows(item, false), progress: new Map() };
516
+ lines.push(...fresh.filter(({ stamp }) => !item.shown.has(stamp)).map(({ row }) => describe(item, row)));
330
517
  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
- }));
518
+ saveCursors(state, item, progress);
519
+ if (changed) state.append({ repo: item.repo, number: item.number, kind: item.kind, updatedAt: info.updatedAt });
520
+ if (["CLOSED", "MERGED"].includes(info.state)) state.append({ retired: itemKey(item) });
521
+ } catch (error) {
522
+ reasons.add(failureReason(error));
523
+ if (rateLimited(error) || error.message === "deadline") { stopAfter(item); break; }
524
+ failed++;
525
+ }
526
+ checked++;
527
+ }
528
+ if (stopped) failed += items.length - checked;
529
+ if (failed) lines.push(`Comment watch: ${failed} items could not be checked (${[...reasons].join(", ")}); retry on the next prompt.`);
333
530
  return lines.length ? (event === "Stop" ? { systemMessage: lines.join("\n") } : context(event, lines.join("\n"))) : null;
334
531
  }
335
532
  if (event === "PreToolUse") {
@@ -353,22 +550,28 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
353
550
  selector = String(result.data?.node?.number ?? "");
354
551
  }
355
552
  if (!repo) throw new Error("repository");
356
- const pr = await gh(repo, ["pr", "view", ...(selector ? [selector] : []), "-R", repo, "--json", "number,body,commits"]);
553
+ const pr = await gh(repo, ["pr", "view", ...(selector ? [selector] : []), "-R", repo, "--json", "number,body,commits,closingIssuesReferences"]);
357
554
  const targets = new Map();
358
555
  const key = itemKey({ repo, number: pr.number });
359
556
  const add = (repo, number, kind = "issue") => targets.set(itemKey({ repo, number }), { repo: repo.toLowerCase(), number, kind, prs: [key] });
360
557
  references(pr.body ?? "", repo, add, true);
361
558
  for (const commit of pr.commits ?? []) references(`${commit.messageHeadline ?? ""}\n${commit.messageBody ?? ""}`, repo, add);
559
+ for (const ref of pr.closingIssuesReferences ?? []) {
560
+ const owner = ref.repository?.owner?.login;
561
+ const name = ref.repository?.name;
562
+ add(owner && name ? `${owner}/${name}` : repo, ref.number);
563
+ }
362
564
  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);
565
+ if (item.prs.has(key)) add(item.repo, item.number, item.kind);
364
566
  }
365
567
  add(repo, pr.number, "pr");
366
568
  await Promise.all([...targets.values()].map(async target => {
367
- state.append(target);
569
+ watch(state, target);
368
570
  const item = { ...state.items.get(itemKey(target)), ...target };
369
571
  try {
370
- const fresh = await unseen(item, gh, state);
572
+ const { fresh, progress } = await unseen(item, gh, state, true);
371
573
  recordPreview(state, item, fresh);
574
+ saveCursors(state, item, progress);
372
575
  lines.push(...fresh.map(({ row }) => describe(item, row)));
373
576
  }
374
577
  catch { failed = true; lines.push(`GitHub comments for ${itemKey(target)} could not be checked.`); }
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
  import { createHash } from "node:crypto";
4
- import { watchedItems } from "./comment-watch.mjs";
4
+ import { commentWatch, watchedItems } from "./comment-watch.mjs";
5
5
  import { PARSERS } from "./bash-command-guard.mjs";
6
6
  import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
7
  import { spawnSync } from "node:child_process";
@@ -19,6 +19,93 @@ test("watch detection keeps closed issues, PR output, and body references", () =
19
19
  ["owner/repo#4", "owner/repo#5", "owner/repo#6", "owner/repo#7"]);
20
20
  });
21
21
 
22
+ test("API hostname flags cannot alias an enterprise item to a GitHub.com watch", () => {
23
+ for (const tool_name of ["Bash", "PowerShell"]) {
24
+ for (const flags of ["--hostname ghe.example.com", "--hostname=ghe.example.com"]) {
25
+ for (const command of [`gh api ${flags} repos/owner/repo/issues/4`, `gh api repos/owner/repo/issues/4 ${flags}`]) {
26
+ assert.deepEqual(watchedItems({ tool_name, tool_input: { command } }, "owner/repo"), []);
27
+ }
28
+ }
29
+ const items = watchedItems({ tool_name, tool_input: { command: "gh api --hostname github.com repos/owner/repo/issues/4" } }, "owner/repo");
30
+ assert.deepEqual(items, [{ repo: "owner/repo", number: 4, kind: "issue" }]);
31
+ }
32
+ });
33
+
34
+ test("an enterprise API read cannot acknowledge pending GitHub.com feedback", (t) => {
35
+ const f = fixture(t);
36
+ f.rows[0].body = "Pending feedback ".repeat(100);
37
+ f.update();
38
+ f.run("PostToolUse", "gh issue view 4");
39
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
40
+ f.run("PostToolUse", "gh api --hostname ghe.example.com repos/shawrylk/example/issues/4/comments");
41
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
42
+ f.run("PostToolUse", "gh api --hostname github.com repos/shawrylk/example/issues/4/comments");
43
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
44
+ });
45
+
46
+ for (const [tool_name, prefix] of [
47
+ ["Bash", "GH_HOST=ghe.example.com "],
48
+ ["Bash", "export GH_HOST=ghe.example.com; "],
49
+ ["PowerShell", '$env:GH_HOST = "ghe.example.com"; '],
50
+ ]) test(`${tool_name} API detection honors the command host (${prefix.trim()})`, () => {
51
+ const endpoint = "repos/owner/repo/issues/4";
52
+ const detect = (args) => watchedItems({ tool_name, tool_input: { command: `${prefix}gh api ${args}` } }, "owner/repo");
53
+ assert.deepEqual(detect(endpoint), []);
54
+ for (const flags of ["--hostname github.com", "--hostname=github.com"]) {
55
+ assert.deepEqual(detect(`${flags} ${endpoint}`), [{ repo: "owner/repo", number: 4, kind: "issue" }]);
56
+ assert.deepEqual(detect(`${endpoint} ${flags}`), [{ repo: "owner/repo", number: 4, kind: "issue" }]);
57
+ }
58
+ });
59
+
60
+ for (const [tool_name, prefix] of [
61
+ ["Bash", "GH_HOST=ghe.example.com "],
62
+ ["PowerShell", '$env:GH_HOST = "ghe.example.com"; '],
63
+ ]) test(`${tool_name} enterprise API reads neither reactivate nor acknowledge a GitHub.com watch`, (t) => {
64
+ const f = fixture(t);
65
+ f.rows[0].body = "Pending feedback ".repeat(100);
66
+ f.update({ metadata: { 4: { state: "CLOSED" } }, body: "Fixes #4" });
67
+ f.run("PostToolUse", "gh issue view 4");
68
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
69
+ f.run("PostToolUse", `${prefix}gh api repos/shawrylk/example/issues/4/comments`, "comment-watch.mjs", "session-a", "", tool_name);
70
+ writeFileSync(f.calls, "");
71
+ assert.equal(f.run("UserPromptSubmit"), null);
72
+ assert.equal(readFileSync(f.calls, "utf8"), "");
73
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
74
+ f.run("PostToolUse", `${prefix}gh api --hostname github.com repos/shawrylk/example/issues/4/comments`, "comment-watch.mjs", "session-a", "", tool_name);
75
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
76
+ });
77
+
78
+ for (const [tool_name, prefix] of [
79
+ ["Bash", "GH_HOST=ghe.example.com "],
80
+ ["Bash", "export GH_HOST=ghe.example.com; "],
81
+ ["PowerShell", '$env:GH_HOST = "ghe.example.com"; '],
82
+ ]) test(`${tool_name} absolute API detection uses the URL host (${prefix.trim()})`, () => {
83
+ const endpoint = "https://api.github.com/repos/owner/repo/issues/4/comments";
84
+ const detect = (args) => watchedItems({ tool_name, tool_input: { command: `${prefix}gh api ${args}` } }, "owner/repo");
85
+ for (const args of [endpoint, `--hostname ghe.example.com ${endpoint}`, `${endpoint} --hostname ghe.example.com`]) {
86
+ assert.deepEqual(detect(args), [{ repo: "owner/repo", number: 4, kind: "issue" }]);
87
+ }
88
+ assert.deepEqual(detect("--hostname github.com https://ghe.example.com/api/v3/repos/owner/repo/issues/4/comments"), []);
89
+ });
90
+
91
+ for (const [tool_name, prefix] of [
92
+ ["Bash", "GH_HOST=ghe.example.com "],
93
+ ["PowerShell", '$env:GH_HOST = "ghe.example.com"; '],
94
+ ]) test(`${tool_name} absolute GitHub.com reads reactivate and acknowledge a watch under GH_HOST`, (t) => {
95
+ const f = fixture(t);
96
+ f.rows[0].body = "Pending feedback ".repeat(100);
97
+ f.update({ metadata: { 4: { state: "CLOSED" } }, body: "Fixes #4" });
98
+ f.run("PostToolUse", "gh issue view 4");
99
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
100
+ writeFileSync(f.calls, "");
101
+ assert.equal(f.run("UserPromptSubmit"), null);
102
+ assert.equal(readFileSync(f.calls, "utf8"), "");
103
+ f.run("PostToolUse", `${prefix}gh api https://api.github.com/repos/shawrylk/example/issues/4/comments --paginate`, "comment-watch.mjs", "session-a", "", tool_name);
104
+ assert.equal(f.run("UserPromptSubmit"), null);
105
+ assert.match(readFileSync(f.calls, "utf8"), /item_4:/);
106
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
107
+ });
108
+
22
109
  test("PowerShell detects explicit repositories, body files, and commit references", (t) => {
23
110
  const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-comment-detection-"));
24
111
  t.after(() => rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
@@ -48,31 +135,55 @@ function fixture(t) {
48
135
  import cp from 'node:child_process';
49
136
  import { syncBuiltinESMExports } from 'node:module';
50
137
  import { appendFileSync, readFileSync } from 'node:fs';
138
+ import { createHash } from 'node:crypto';
51
139
  const original = cp.spawnSync;
52
140
  cp.spawnSync = (program, args, options) => {
53
141
  if (program === 'git' && args.join(' ') === 'remote get-url origin') return { status: 0, stdout: 'https://github.com/shawrylk/example.git' };
54
142
  if (program !== 'gh') return original(program, args, options);
55
143
  appendFileSync(process.env.CALLS, JSON.stringify({args, config: options.env.GH_CONFIG_DIR}) + '\\n');
56
144
  const data = JSON.parse(readFileSync(process.env.DATA, 'utf8'));
57
- if (data.fail || args.some(arg => arg.includes(data.failEndpoint ?? 'NEVER_MATCH'))) return { status: 1, stderr: 'TOKEN_MUST_STAY_SECRET' };
145
+ if (data.fail || args.some(arg => arg.includes(data.failEndpoint ?? 'NEVER_MATCH'))) return { status: 1, stderr: data.failure ?? 'TOKEN_MUST_STAY_SECRET' };
58
146
  if (args[0] === 'api' && args[1].includes('/git/ref/heads/') && args.at(-2) === '--jq' && args.at(-1) === '.object.sha') return { status: 0, stdout: data.baseOid };
59
147
  let result;
60
- if (args[0] === 'pr') result = { baseRefName: 'main', baseRefOid: data.baseOid, labels: [], number: 7, body: data.body ?? 'Fixes #4; https://github.com/ArentInc/other/issues/8', commits: data.commits ?? [] };
148
+ if (args[0] === 'pr') result = { baseRefName: 'main', baseRefOid: data.baseOid, labels: [], number: 7, body: data.body ?? 'Fixes #4; https://github.com/ArentInc/other/issues/8', commits: data.commits ?? [], closingIssuesReferences: data.closing ?? [] };
61
149
  else if (args[1] === 'user') result = { login: 'self' };
62
- else if (args[1] === 'graphql') result = { data: { node: { number: 7, repository: { nameWithOwner: 'shawrylk/example' } } } };
150
+ else if (args[1] === 'graphql') {
151
+ const query = args.find(arg => arg.startsWith('query=')) ?? '';
152
+ const repository = Object.fromEntries([...query.matchAll(/item_(\\d+):/g)].map(([, number]) => {
153
+ const rows = data.rows.filter(row => row.endpoint.startsWith('issues/' + number + '/') || row.endpoint.startsWith('pulls/' + number + '/'));
154
+ const updatedAt = new Date(parseInt(createHash('sha256').update(JSON.stringify(rows)).digest('hex').slice(0, 8), 16) * 1000).toISOString();
155
+ return ['item_' + number, { __typename: number === '7' ? 'PullRequest' : 'Issue', state: 'OPEN', updatedAt, ...data.metadata?.[number] }];
156
+ }));
157
+ result = data.graphqlReply ?? { data: { repository, node: { number: 7, repository: { nameWithOwner: 'shawrylk/example' } } } };
158
+ }
63
159
  else {
64
160
  const endpoint = args.at(-1);
65
161
  if (/issues\\/7$/.test(endpoint)) result = { pull_request: {} };
66
162
  else if (/issues\\/\\d+$/.test(endpoint)) result = {};
67
- else result = [[], data.rows.filter(row => endpoint.includes(row.endpoint)).map(({endpoint, ...row}) => row)];
163
+ else if (args.includes('--paginate')) result = [[], data.rows.filter(row => endpoint.includes(row.endpoint)).map(({endpoint, ...row}) => row)];
164
+ else {
165
+ const [route, query = ''] = endpoint.split('?');
166
+ const params = new URLSearchParams(query);
167
+ const since = params.get('since');
168
+ const size = Number(params.get('per_page') ?? 30);
169
+ const page = Number(params.get('page') ?? 1);
170
+ result = data.rows.filter(row => route.endsWith('/' + row.endpoint) && (!since || !row.updated_at || row.updated_at >= since))
171
+ .map(({endpoint, ...row}) => row).slice((page - 1) * size, page * size);
172
+ }
68
173
  }
69
- return {status: 0, stdout: args.includes('--paginate') ? result.map(page => JSON.stringify(page)).join('\\n') : JSON.stringify(result)};
174
+ const rows = Array.isArray(result) ? result.flat().length : 0;
175
+ return {status: 0, rows, stdout: args.includes('--paginate') ? result.map(page => JSON.stringify(page)).join('\\n') : JSON.stringify(result)};
70
176
  };
71
177
  cp.execFile = (program, args, options, callback) => {
72
178
  const data = JSON.parse(readFileSync(process.env.DATA, 'utf8'));
73
179
  appendFileSync(process.env.CALLS, JSON.stringify({ start: Date.now(), args, config: options.env.GH_CONFIG_DIR }) + '\\n');
74
180
  const result = cp.spawnSync(program, args, options);
75
- setTimeout(() => callback(result.status ? new Error('gh failed') : null, result.stdout, result.stderr), data.delay ?? 0);
181
+ const delay = (data.delay ?? 0) + (data.rowDelay ?? 0) * (result.rows ?? 0);
182
+ if (options.timeout && delay > options.timeout) {
183
+ setTimeout(() => callback(Object.assign(new Error('killed'), { killed: true }), '', ''), options.timeout);
184
+ return;
185
+ }
186
+ setTimeout(() => callback(result.status ? new Error('gh failed') : null, result.stdout, result.stderr), delay);
76
187
  };
77
188
  syncBuiltinESMExports();
78
189
  `);
@@ -142,7 +253,7 @@ test("prompts show shared-login feedback once, retain failures, and isolate sess
142
253
  const output = f.run("UserPromptSubmit").hookSpecificOutput.additionalContext;
143
254
  for (const id of [1, 2, 3, 4, 5]) assert.match(output, new RegExp(`Comment ${id}`));
144
255
  assert.equal(f.run("UserPromptSubmit"), null);
145
- f.rows.push({ ...f.rows[0], body: "Edited comment" });
256
+ f.rows.push({ ...f.rows[0], body: "Edited comment", updated_at: new Date().toISOString() });
146
257
  f.update();
147
258
  assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Edited comment/);
148
259
  assert.equal(f.run("UserPromptSubmit", "", "comment-watch.mjs", "other-session"), null);
@@ -200,6 +311,23 @@ test("only session-created URLs are skipped, including reviews and PRs", (t) =>
200
311
  assert.match(output, /Comment 4/);
201
312
  });
202
313
 
314
+ test("truncated comments print once across prompts and Stop but still block merging", (t) => {
315
+ const f = fixture(t);
316
+ f.rows[0].body = "x".repeat(850);
317
+ f.update();
318
+ f.run("PostToolUse", "gh issue view 4");
319
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
320
+ assert.equal(f.run("UserPromptSubmit"), null);
321
+ assert.equal(f.run("Stop"), null);
322
+ for (let attempt = 0; attempt < 2; attempt++) {
323
+ const guard = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
324
+ assert.equal(guard?.hookSpecificOutput?.permissionDecision, "deny");
325
+ assert.match(JSON.stringify(guard), /truncated/);
326
+ }
327
+ f.run("PostToolUse", "gh issue view 4 --comments");
328
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
329
+ });
330
+
203
331
  test("full reads acknowledge only the comment kinds their output contains", (t) => {
204
332
  for (const [command, seen] of [
205
333
  ["gh issue view 4 --comments", [1]],
@@ -222,12 +350,14 @@ test("full reads acknowledge only the comment kinds their output contains", (t)
222
350
  assert.match(output, /truncated/i, command);
223
351
  assert.match(output, /gh api repos\/shawrylk\/example\/pulls\/7\/comments --paginate/, command);
224
352
  assert.doesNotMatch(output, /hidden request/, command);
225
- assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/i, command);
353
+ assert.equal(f.run("UserPromptSubmit"), null, command);
354
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/i, command);
226
355
  assert.equal(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput?.permissionDecision, "deny", command);
227
356
  f.run("PostToolUse", command, "comment-watch.mjs", "session-a", { exit_code: 1 });
228
- assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/i, command);
357
+ assert.equal(f.run("UserPromptSubmit"), null, command);
358
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/i, command);
229
359
  f.run("PostToolUse", command);
230
- const remaining = JSON.stringify(f.run("UserPromptSubmit"));
360
+ const remaining = JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs"));
231
361
  for (const row of f.rows) assert.equal(remaining.includes(`Comment ${row.id} `), !seen.includes(row.id), command);
232
362
  }
233
363
  });
@@ -335,13 +465,13 @@ test("a PR body read at merge skips hex colours in code spans", (t) => {
335
465
  assert.doesNotMatch(readFileSync(f.calls, "utf8"), /issues\/128282/);
336
466
  });
337
467
 
338
- test("merge targets include commit-only references and previously watched issues", (t) => {
468
+ test("merge targets include commit-only references and issues an earlier command linked to the PR", (t) => {
339
469
  const f = fixture(t);
340
470
  f.rows.length = 0;
341
471
  f.rows.push(...[9, 10].map(id => ({ id, endpoint: `issues/${id}/comments`, body: `Comment ${id}`, html_url: `https://github.com/comments/${id}` })));
342
472
  f.update({ commits: [{ messageHeadline: "Fixes #9", messageBody: "Refs #11" }] });
343
473
  f.run("PostToolUse", "gh pr view 7");
344
- f.run("PostToolUse", 'git commit -m "Refs #10"');
474
+ f.run("PostToolUse", 'gh pr comment 7 --body "Refs #10"');
345
475
  const output = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
346
476
  assert.match(JSON.stringify(output), /Comment 9/);
347
477
  assert.match(JSON.stringify(output), /Comment 10/);
@@ -373,20 +503,406 @@ test("API merges check comments with dispatch on and off in both shells", (t) =>
373
503
  }
374
504
  });
375
505
 
376
- test("polls use one issue request and three PR requests in parallel", (t) => {
506
+ test("polls batch metadata per repository and fetch comments only when updatedAt changes", (t) => {
377
507
  const f = fixture(t);
378
508
  f.run("PostToolUse", "gh pr view 7");
379
509
  writeFileSync(f.calls, "");
380
- f.update({ delay: 250 });
381
510
  f.run("UserPromptSubmit");
382
511
  const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
383
- assert.equal(calls.length, 5);
384
- assert.ok(Math.max(...calls.map(call => call.start)) - Math.min(...calls.map(call => call.start)) < 200);
385
- assert.ok(calls.every(call => call.args.includes("--paginate")));
512
+ const metadata = calls.filter(call => call.args[1] === "graphql");
513
+ assert.equal(metadata.length, 2);
514
+ const query = metadata.find(call => call.args.includes("owner=shawrylk")).args.join(" ");
515
+ for (const number of [4, 7]) assert.match(query, new RegExp(`item_${number}:.*issueOrPullRequest\\(number: ${number}\\)`));
516
+ assert.match(query, /state updatedAt/);
517
+ const commentCalls = calls.filter(call => call.args[1] !== "graphql");
518
+ assert.equal(commentCalls.length, 5);
519
+ assert.ok(commentCalls.every(call => call.args.at(-1).includes("per_page=100")));
386
520
  assert.ok(calls.every(call => !call.args.includes("--slurp")));
387
- f.rows[0].body = "Retry this item";
521
+ writeFileSync(f.calls, "");
522
+ assert.equal(f.run("UserPromptSubmit"), null);
523
+ const unchanged = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
524
+ assert.equal(unchanged.length, 2);
525
+ assert.ok(unchanged.every(call => call.args[1] === "graphql"));
526
+ f.run("PostToolUse", "gh issue view 4");
527
+ writeFileSync(f.calls, "");
528
+ assert.equal(f.run("UserPromptSubmit"), null);
529
+ const named = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse);
530
+ assert.ok(named.every(call => call.args[1] === "graphql"));
531
+ Object.assign(f.rows[0], { body: "Retry this item", updated_at: new Date().toISOString() });
388
532
  f.update({ failEndpoint: "issues/4/comments" });
389
- assert.match(JSON.stringify(f.run("UserPromptSubmit")), /shawrylk\/example#4 could not be checked; retry on the next prompt/);
533
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment watch: 1 items could not be checked \(gh\); retry on the next prompt\./);
390
534
  f.update();
535
+ writeFileSync(f.calls, "");
391
536
  assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Retry this item/);
537
+ const retry = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start && call.args[1] !== "graphql");
538
+ assert.equal(retry.length, 1);
539
+ assert.match(retry[0].args.at(-1), /issues\/4\/comments/);
540
+ });
541
+
542
+ test("a Stop preview is acknowledged on the next prompt even when updatedAt is unchanged", (t) => {
543
+ const f = fixture(t);
544
+ f.run("PostToolUse", "gh issue view 4");
545
+ assert.match(JSON.stringify(f.run("Stop")), /Comment 1/);
546
+ writeFileSync(f.calls, "");
547
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
548
+ const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse);
549
+ assert.ok(calls.every(call => call.args[1] === "graphql"));
550
+ const guard = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
551
+ assert.doesNotMatch(JSON.stringify(guard), /Comment 1/);
552
+ });
553
+
554
+ for (const state of ["CLOSED", "MERGED"]) test(`${state} items retire after one successful check and a named command watches them again`, (t) => {
555
+ const f = fixture(t);
556
+ const number = state === "MERGED" ? 7 : 4;
557
+ const command = state === "MERGED" ? "gh pr view 7" : "gh issue view 4";
558
+ f.update({ body: "", metadata: { [number]: { state } }, failEndpoint: `issues/${number}/comments` });
559
+ f.run("PostToolUse", command);
560
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /could not be checked/);
561
+ f.update({ body: "", metadata: { [number]: { state } } });
562
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), new RegExp(`Comment ${number === 4 ? 1 : 4}`));
563
+ writeFileSync(f.calls, "");
564
+ assert.equal(f.run("UserPromptSubmit"), null);
565
+ assert.equal(f.run("Stop"), null);
566
+ assert.equal(readFileSync(f.calls, "utf8"), "");
567
+ const ledgerPath = path.join(f.cwd, ".git", "qc", `comment-watch-${createHash("sha256").update("session-a").digest("hex")}.jsonl`);
568
+ const records = readFileSync(ledgerPath, "utf8").split("\n").filter(Boolean).map(JSON.parse);
569
+ assert.ok(records.some(record => record.retired === `shawrylk/example#${number}`));
570
+ f.run("PostToolUse", command);
571
+ writeFileSync(f.calls, "");
572
+ f.run("UserPromptSubmit");
573
+ const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
574
+ assert.equal(calls.filter(call => call.args[1] === "graphql").length, 1);
575
+ assert.equal(calls.filter(call => call.args.at(-1).includes("per_page=100")).length, number === 7 ? 3 : 1);
576
+ });
577
+
578
+ test("a merge checks a retired issue named in the PR body again", (t) => {
579
+ const f = fixture(t);
580
+ f.update({ metadata: { 4: { state: "CLOSED" } } });
581
+ f.run("PostToolUse", "gh issue close 4");
582
+ f.run("UserPromptSubmit");
583
+ Object.assign(f.rows[0], { body: "Feedback after retirement", updated_at: new Date().toISOString() });
584
+ f.update();
585
+ assert.equal(f.run("UserPromptSubmit"), null);
586
+ writeFileSync(f.calls, "");
587
+ const guard = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
588
+ assert.equal(guard?.hookSpecificOutput?.permissionDecision, "deny");
589
+ assert.match(JSON.stringify(guard), /Feedback after retirement/);
590
+ assert.match(readFileSync(f.calls, "utf8"), /issues\/4\/comments/);
591
+ });
592
+
593
+ for (const failure of ["metadata", "comments", "partial GraphQL"]) test(`five ${failure} failures print one summary and retry`, (t) => {
594
+ const f = fixture(t);
595
+ f.run("PostToolUse", [1, 2, 3, 4, 5].map(number => `gh issue view ${number}`).join("; "));
596
+ f.update(failure === "partial GraphQL" ? { graphqlReply: { data: { repository: {} }, errors: [{ message: "TOKEN_MUST_STAY_SECRET" }] } }
597
+ : { failEndpoint: failure === "metadata" ? "graphql" : "/comments" });
598
+ const output = f.run("UserPromptSubmit").hookSpecificOutput.additionalContext;
599
+ assert.equal(output, `Comment watch: 5 items could not be checked (${failure === "partial GraphQL" ? "response" : "gh"}); retry on the next prompt.`);
600
+ f.update();
601
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
602
+ });
603
+
604
+ for (const endpoint of ["graphql", "issues/1/comments"]) test(`rate limits on ${endpoint} end polling before further calls`, (t) => {
605
+ const f = fixture(t);
606
+ f.run("PostToolUse", "gh issue view 1; gh issue view 4; gh issue view 8 -R ArentInc/other");
607
+ f.update({ failEndpoint: endpoint, failure: "API rate limit exceeded TOKEN_MUST_STAY_SECRET" });
608
+ writeFileSync(f.calls, "");
609
+ assert.equal(f.run("UserPromptSubmit").hookSpecificOutput.additionalContext,
610
+ "Comment watch: 3 items could not be checked (rate limit); retry on the next prompt.");
611
+ const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
612
+ assert.equal(calls.length, endpoint === "graphql" ? 1 : 2);
613
+ f.update();
614
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
615
+ });
616
+
617
+ test("consecutive polls continue past an item whose comments exhaust the deadline", async (t) => {
618
+ const f = fixture(t);
619
+ f.run("PostToolUse", "gh issue view 4; gh issue view 5");
620
+ let now = Date.now();
621
+ t.mock.method(Date, "now", () => now);
622
+ const requests = [];
623
+ const poll = () => commentWatch({ cwd: f.cwd, session_id: "session-a", hook_event_name: "UserPromptSubmit" }, {
624
+ gh: async (args, options) => {
625
+ requests.push(args);
626
+ if (args[1] === "graphql") return JSON.stringify({ data: { repository: {
627
+ item_4: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
628
+ item_5: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
629
+ } } });
630
+ if (args.at(-1).includes("issues/4/comments")) {
631
+ now += options.timeoutMs;
632
+ throw new Error("deadline");
633
+ }
634
+ return JSON.stringify([{ id: 5, body: "Later feedback", updated_at: "2026-01-01T00:00:00Z" }]);
635
+ },
636
+ });
637
+ assert.match(JSON.stringify(await poll()), /2 items could not be checked \(deadline\)/);
638
+ requests.length = 0;
639
+ const second = JSON.stringify(await poll());
640
+ assert.match(second, /Later feedback/);
641
+ assert.match(second, /1 items could not be checked \(deadline\)/);
642
+ assert.match(requests[1].at(-1), /issues\/5\/comments/);
643
+ assert.match(requests[2].at(-1), /issues\/4\/comments/);
644
+ });
645
+
646
+ test("poll rotation reaches another repository after two items exhaust the deadline", async (t) => {
647
+ const f = fixture(t);
648
+ f.run("PostToolUse", "gh issue view 4; gh issue view 5; gh issue view 8 -R owner/other");
649
+ let now = Date.now();
650
+ t.mock.method(Date, "now", () => now);
651
+ const requests = [];
652
+ const poll = () => commentWatch({ cwd: f.cwd, session_id: "session-a", hook_event_name: "UserPromptSubmit" }, {
653
+ gh: async (args, options) => {
654
+ requests.push(args);
655
+ if (args[1] === "graphql") return JSON.stringify({ data: { repository: Object.fromEntries(
656
+ [...args.at(-1).matchAll(/item_(\d+):/g)].map(([, number]) => [
657
+ `item_${number}`, { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
658
+ ]),
659
+ ) } });
660
+ if (/issues\/[45]\/comments/.test(args.at(-1))) {
661
+ now += options.timeoutMs;
662
+ throw new Error("deadline");
663
+ }
664
+ return JSON.stringify([{ id: 8, body: "Other repository feedback", updated_at: "2026-01-01T00:00:00Z" }]);
665
+ },
666
+ });
667
+ for (let i = 0; i < 2; i++) {
668
+ assert.match(JSON.stringify(await poll()), /3 items could not be checked \(deadline\)/);
669
+ }
670
+ requests.length = 0;
671
+ const third = JSON.stringify(await poll());
672
+ assert.match(third, /Other repository feedback/);
673
+ assert.match(third, /2 items could not be checked \(deadline\)/);
674
+ assert.match(requests[1].at(-1), /repos\/owner\/other\/issues\/8\/comments/);
675
+ const metadata = requests.filter(args => args[1] === "graphql");
676
+ assert.equal(metadata.length, 2);
677
+ assert.equal(metadata.filter(args => args.includes("name=example")).length, 1);
678
+ assert.match(metadata.find(args => args.includes("name=example")).at(-1), /item_4:.*item_5:/);
679
+ });
680
+
681
+ test("all poll requests share the 3.5 second deadline", async (t) => {
682
+ const f = fixture(t);
683
+ f.run("PostToolUse", "gh issue view 4; gh issue view 5");
684
+ let now = Date.now();
685
+ t.mock.method(Date, "now", () => now);
686
+ const requests = [];
687
+ const output = await commentWatch({ cwd: f.cwd, session_id: "session-a", hook_event_name: "UserPromptSubmit" }, {
688
+ gh: async (args, options) => {
689
+ requests.push(args);
690
+ assert.equal(options.timeoutMs, 3500);
691
+ now += 3501;
692
+ return JSON.stringify({ data: { repository: {
693
+ item_4: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
694
+ item_5: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
695
+ } } });
696
+ },
697
+ });
698
+ assert.equal(requests.length, 1);
699
+ assert.equal(output.hookSpecificOutput.additionalContext,
700
+ "Comment watch: 2 items could not be checked (deadline); retry on the next prompt.");
701
+ });
702
+
703
+ test("old ledger records stay readable and previews append without replacing them", (t) => {
704
+ const f = fixture(t);
705
+ f.rows[0].body = "x".repeat(850);
706
+ f.update();
707
+ const row = f.rows[0];
708
+ const stamp = createHash("sha256").update(JSON.stringify([row.html_url, row.id, row.updated_at, row.body, row.state])).digest("hex");
709
+ const dir = path.join(f.cwd, ".git", "qc");
710
+ mkdirSync(dir, { recursive: true });
711
+ const file = path.join(dir, `comment-watch-${createHash("sha256").update("session-a").digest("hex")}.jsonl`);
712
+ const old = JSON.stringify({ repo: "shawrylk/example", number: 4, kind: "issue", pending: [
713
+ { stamp, id: row.id, endpoint: "repos/shawrylk/example/issues/4/comments" },
714
+ ] }) + "\n";
715
+ writeFileSync(file, old);
716
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
717
+ assert.equal(f.run("UserPromptSubmit"), null);
718
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
719
+ f.run("PostToolUse", "gh issue view 4 --comments");
720
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
721
+ assert.ok(readFileSync(file, "utf8").startsWith(old));
722
+ });
723
+
724
+ test("a closed item's short Stop preview is acknowledged on the next prompt without polling", (t) => {
725
+ const f = fixture(t);
726
+ f.update({ metadata: { 4: { state: "CLOSED" } } });
727
+ f.run("PostToolUse", "gh issue view 4");
728
+ assert.match(JSON.stringify(f.run("Stop")), /Comment 1/);
729
+ writeFileSync(f.calls, "");
730
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
731
+ assert.equal(readFileSync(f.calls, "utf8"), "");
732
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /Comment 1/);
733
+ });
734
+
735
+ test("a gh API command naming a retired item watches it again", (t) => {
736
+ const f = fixture(t);
737
+ f.update({ metadata: { 4: { state: "CLOSED" } } });
738
+ f.run("PostToolUse", "gh issue view 4");
739
+ f.run("UserPromptSubmit");
740
+ Object.assign(f.rows[0], { body: "New feedback on the retired issue", updated_at: new Date().toISOString() });
741
+ f.update();
742
+ f.run("PostToolUse", "gh api repos/shawrylk/example/issues/4");
743
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /New feedback on the retired issue/);
744
+ });
745
+
746
+ test("a 500-comment issue no longer exceeds the deadline after its first check", (t) => {
747
+ const f = fixture(t);
748
+ f.rows.length = 0;
749
+ for (let id = 1; id <= 500; id++) f.rows.push({ id, endpoint: "issues/4/comments", user: { login: "other" }, body: `Old note ${id}`,
750
+ html_url: `https://github.com/shawrylk/example/issues/4#issuecomment-${id}`, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" });
751
+ // 8 ms a row: one page of 100 takes 0.8 s, and the full history takes 4 s against the 3.5 s prompt deadline.
752
+ f.update({ rowDelay: 8 });
753
+ f.run("PostToolUse", "gh issue view 4");
754
+ const first = JSON.stringify(f.run("UserPromptSubmit"));
755
+ assert.match(first, /1 items could not be checked \(deadline\)/);
756
+ const output = JSON.stringify(f.run("UserPromptSubmit"));
757
+ assert.doesNotMatch(output, /could not be checked/);
758
+ assert.match(output, /Old note 1\b/);
759
+ assert.match(output, /Old note 500\b/);
760
+ const now = new Date().toISOString();
761
+ f.rows.push({ id: 501, endpoint: "issues/4/comments", user: { login: "other" }, body: "Fresh foreign note",
762
+ html_url: "https://github.com/shawrylk/example/issues/4#issuecomment-501", created_at: now, updated_at: now });
763
+ f.update({ rowDelay: 8 });
764
+ writeFileSync(f.calls, "");
765
+ const next = JSON.stringify(f.run("UserPromptSubmit"));
766
+ assert.match(next, /Fresh foreign note/);
767
+ assert.doesNotMatch(next, /could not be checked/);
768
+ assert.doesNotMatch(next, /Old note/);
769
+ const reads = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start && call.args[1] !== "graphql");
770
+ assert.ok(reads.length > 0 && reads.every(call => /[?&]since=/.test(call.args.at(-1))), JSON.stringify(reads));
771
+ });
772
+
773
+ for (const redirected of [false, true]) test(`comments the session posts with gh issue comment and gh pr comment are own (${redirected ? "output to /dev/null" : "URL output"})`, (t) => {
774
+ const f = fixture(t);
775
+ const now = new Date().toISOString();
776
+ const note = (id, number, body) => ({ id, endpoint: `issues/${number}/comments`, user: { login: "self" }, body,
777
+ html_url: `https://github.com/shawrylk/example/issues/${number}#issuecomment-${id}`, created_at: now, updated_at: now });
778
+ f.rows.length = 0;
779
+ f.rows.push(note(40, 4, "Triage: load timeout, joins #2925."), note(41, 7, "Ready to merge."));
780
+ f.update({ body: "Fixes #4" });
781
+ const tail = redirected ? " >/dev/null" : "";
782
+ f.run("PostToolUse", `gh issue comment 4 --body "Triage: load timeout, joins #2925."${tail}`, "comment-watch.mjs", "session-a",
783
+ { stdout: redirected ? "" : f.rows[0].html_url, stderr: "" }, "Bash");
784
+ f.run("PostToolUse", `gh pr comment 7 --body "Ready to merge."${tail}`, "comment-watch.mjs", "session-a",
785
+ { stdout: redirected ? "" : f.rows[1].html_url, stderr: "" }, "Bash");
786
+ const merge = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
787
+ assert.notEqual(merge?.hookSpecificOutput?.permissionDecision, "deny", JSON.stringify(merge));
788
+ assert.equal(f.run("UserPromptSubmit"), null);
789
+ });
790
+
791
+ test("a merge names one new foreign comment and ignores watched issues the PR does not link", (t) => {
792
+ const f = fixture(t);
793
+ const now = new Date().toISOString();
794
+ const note = (id, number, body, login) => ({ id, endpoint: `issues/${number}/comments`, user: { login }, body,
795
+ html_url: `https://github.com/shawrylk/example/issues/${number}#issuecomment-${id}`, created_at: now, updated_at: now });
796
+ f.rows.length = 0;
797
+ f.rows.push(note(50, 4, "Session triage note", "self"), note(51, 12, "Dashboard chatter", "other"));
798
+ f.update({ body: "Fixes #4" });
799
+ f.run("PostToolUse", 'gh issue comment 4 --body "Session triage note" >/dev/null', "comment-watch.mjs", "session-a", { stdout: "", stderr: "" }, "Bash");
800
+ f.run("PostToolUse", "gh issue view 12", "comment-watch.mjs", "session-a", { stdout: "", stderr: "" }, "Bash");
801
+ const passed = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
802
+ assert.notEqual(passed?.hookSpecificOutput?.permissionDecision, "deny", JSON.stringify(passed));
803
+ f.rows.push(note(52, 4, "Please keep the permission assertions", "reviewer"));
804
+ f.update({ body: "Fixes #4" });
805
+ const denied = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput;
806
+ assert.equal(denied?.permissionDecision, "deny");
807
+ assert.match(denied.permissionDecisionReason, /@reviewer on shawrylk\/example#4 .*Please keep the permission assertions/);
808
+ assert.doesNotMatch(denied.permissionDecisionReason, /Session triage note|Dashboard chatter/);
809
+ });
810
+
811
+ const issueNote = (id, number, body, login, at) => ({ id, endpoint: `issues/${number}/comments`, user: { login }, body,
812
+ html_url: `https://github.com/shawrylk/example/issues/${number}#issuecomment-${id}`, created_at: at, updated_at: at });
813
+
814
+ test("a foreign comment with the same body as an own /dev/null comment still denies the merge", (t) => {
815
+ const f = fixture(t);
816
+ const earlier = new Date(Date.now() - 120_000).toISOString();
817
+ const now = new Date().toISOString();
818
+ f.rows.length = 0;
819
+ f.rows.push(issueNote(60, 4, "LGTM", "reviewer", earlier), issueNote(61, 4, "LGTM", "self", now));
820
+ f.update({ body: "Fixes #4" });
821
+ f.run("PostToolUse", 'gh issue comment 4 --body "LGTM" >/dev/null', "comment-watch.mjs", "session-a", { stdout: "", stderr: "" }, "Bash");
822
+ const denied = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput;
823
+ assert.equal(denied?.permissionDecision, "deny");
824
+ assert.match(denied.permissionDecisionReason, /@reviewer on shawrylk\/example#4/);
825
+ assert.doesNotMatch(denied.permissionDecisionReason, /@self/);
826
+ });
827
+
828
+ test("an own comment marker from a failed post never claims a later foreign comment", (t) => {
829
+ const f = fixture(t);
830
+ f.rows.length = 0;
831
+ f.update({ body: "Fixes #4" });
832
+ f.run("PostToolUse", 'gh issue comment 4 --body "Done." >/dev/null 2>&1 || true', "comment-watch.mjs", "session-a", { stdout: "", stderr: "" }, "Bash");
833
+ f.rows.push(issueNote(70, 4, "Done.", "reviewer", new Date().toISOString()));
834
+ f.update({ body: "Fixes #4" });
835
+ const denied = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput;
836
+ assert.equal(denied?.permissionDecision, "deny");
837
+ assert.match(denied.permissionDecisionReason, /@reviewer on shawrylk\/example#4 .*Done\./);
838
+ });
839
+
840
+ test("an own /dev/null comment stays unseen when the viewer login cannot be read", (t) => {
841
+ const f = fixture(t);
842
+ f.rows.length = 0;
843
+ f.rows.push(issueNote(75, 4, "Session note", "self", new Date().toISOString()));
844
+ f.update({ body: "Fixes #4", failEndpoint: "user" });
845
+ f.run("PostToolUse", 'gh issue comment 4 --body "Session note" >/dev/null', "comment-watch.mjs", "session-a", { stdout: "", stderr: "" }, "Bash");
846
+ const denied = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput;
847
+ assert.equal(denied?.permissionDecision, "deny");
848
+ assert.match(denied.permissionDecisionReason, /Session note/);
849
+ });
850
+
851
+ for (const [link, extra] of [
852
+ ["a commit that says Closes #4", { commits: [{ messageHeadline: "fix: x", messageBody: "Closes #4" }] }],
853
+ ["a commit that says Resolved #4", { commits: [{ messageHeadline: "Resolved #4", messageBody: "" }] }],
854
+ ["the Development sidebar", { closing: [{ number: 4, repository: { name: "example", owner: { login: "shawrylk" } } }] }],
855
+ ]) test(`an issue linked by ${link} gates the merge`, (t) => {
856
+ const f = fixture(t);
857
+ f.rows.length = 0;
858
+ f.update({ body: "Summary only", ...extra });
859
+ f.run("PostToolUse", "gh issue view 4", "comment-watch.mjs", "session-a", { stdout: "", stderr: "" }, "Bash");
860
+ f.rows.push(issueNote(80, 4, "Requirement changed, do not merge", "reviewer", new Date().toISOString()));
861
+ f.update({ body: "Summary only", ...extra });
862
+ const denied = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput;
863
+ assert.equal(denied?.permissionDecision, "deny");
864
+ assert.match(denied.permissionDecisionReason, /Requirement changed, do not merge/);
865
+ });
866
+
867
+ test("a merge reads every review page, so an edited review on page 1 still denies", (t) => {
868
+ const f = fixture(t);
869
+ f.rows.length = 0;
870
+ for (let id = 1; id <= 150; id++) f.rows.push({ id, endpoint: "pulls/7/reviews", user: { login: "reviewer" }, state: "COMMENTED",
871
+ body: `Review ${id}`, html_url: `https://github.com/shawrylk/example/pull/7#pullrequestreview-${id}`, submitted_at: "2026-01-01T00:00:00Z" });
872
+ f.update({ body: "Summary only" });
873
+ f.run("PostToolUse", "gh pr view 7");
874
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Review 150\b/);
875
+ assert.equal(f.run("UserPromptSubmit"), null);
876
+ assert.notEqual(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput?.permissionDecision, "deny");
877
+ f.rows[0].body = "Edited: this breaks the import path";
878
+ f.update({ body: "Summary only" });
879
+ writeFileSync(f.calls, "");
880
+ const denied = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput;
881
+ assert.equal(denied?.permissionDecision, "deny");
882
+ assert.match(denied.permissionDecisionReason, /Edited: this breaks the import path/);
883
+ const reviewReads = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start && /pulls\/7\/reviews/.test(call.args.at(-1)));
884
+ assert.match(reviewReads[0].args.at(-1), /page=1$/);
885
+ });
886
+
887
+ test("a merge rereads a partial comment scan from page 1, so an edit on an early page still denies", (t) => {
888
+ const f = fixture(t);
889
+ f.rows.length = 0;
890
+ for (let id = 1; id <= 300; id++) f.rows.push(issueNote(id, 4, id === 1 ? "LGTM" : `Note ${id}`, "reviewer", "2026-01-01T00:00:00Z"));
891
+ f.update({ body: "Fixes #4" });
892
+ // The ledger of a first scan that stopped at page 3, after a prompt acknowledged every row it had shown.
893
+ const stamp = (row) => createHash("sha256").update(JSON.stringify([row.html_url, row.id, row.updated_at, row.body, row.state])).digest("hex");
894
+ const dir = path.join(f.cwd, ".git", "qc");
895
+ mkdirSync(dir, { recursive: true });
896
+ writeFileSync(path.join(dir, `comment-watch-${createHash("sha256").update("session-a").digest("hex")}.jsonl`), [
897
+ { repo: "shawrylk/example", number: 4, kind: "issue", prs: ["shawrylk/example#7"], seen: f.rows.map(stamp) },
898
+ { repo: "shawrylk/example", number: 4, cursor: { endpoint: "issues/4/comments", since: null, page: 3, started: new Date(Date.now() - 60_000).toISOString() } },
899
+ ].map(record => JSON.stringify(record)).join("\n") + "\n");
900
+ Object.assign(f.rows[0], { body: "blocker, do not merge", updated_at: new Date().toISOString() });
901
+ f.update({ body: "Fixes #4" });
902
+ writeFileSync(f.calls, "");
903
+ const denied = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput;
904
+ assert.equal(denied?.permissionDecision, "deny");
905
+ assert.match(denied.permissionDecisionReason, /@reviewer on shawrylk\/example#4 .*blocker, do not merge/);
906
+ const reads = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start && /issues\/4\/comments/.test(call.args.at(-1)));
907
+ assert.match(reads[0].args.at(-1), /page=1$/);
392
908
  });
@@ -10,6 +10,15 @@ import { pathToFileURL } from "node:url";
10
10
  import { gitOut, gitStatusWithin } from "./git-read.mjs";
11
11
 
12
12
  const LINTABLE = /\.(?:[cm]?[jt]sx?)$/;
13
+ const CONFIG_NAMES = ["eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", "eslint.config.ts", "eslint.config.mts", "eslint.config.cts"];
14
+
15
+ /** True when a flat config sits in the folder of `file` or in any folder above it. */
16
+ function configAbove(file) {
17
+ for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
18
+ if (CONFIG_NAMES.some((name) => existsSync(path.join(dir, name)))) return true;
19
+ if (path.dirname(dir) === dir) return false;
20
+ }
21
+ }
13
22
  const DIFF_TIMEOUT_MS = 30_000;
14
23
 
15
24
  /**
@@ -174,13 +183,21 @@ export async function runLintChanged(config, args) {
174
183
  const eslint = new ESLint({ cwd: root });
175
184
  const files = [];
176
185
  const applicableBaseline = new Map();
186
+ let unconfigured = 0;
177
187
  for (const file of new Set([...changed.keys(), ...Object.keys(baseline)])) {
178
188
  if (!LINTABLE.test(file) || (wanted.size > 0 && !wanted.has(file))) continue;
189
+ // ESLint can arrive as a dependency of another package, so an install does not mean the repository uses it.
190
+ // ESLint 9 looks up the config from cwd only, so a config in a subfolder keeps the file and its old error.
191
+ if (typeof eslint.findConfigFile === "function" && !(await eslint.findConfigFile(path.join(root, file))) && !configAbove(path.join(root, file))) {
192
+ unconfigured++;
193
+ continue;
194
+ }
179
195
  if (await eslint.isPathIgnored(path.join(root, file))) continue;
180
196
  if (Object.hasOwn(baseline, file)) applicableBaseline.set(file, baseline[file]);
181
197
  if (!options.staged && !existsSync(path.join(root, file))) continue;
182
198
  files.push(file);
183
199
  }
200
+ if (unconfigured > 0) console.log(`lint skipped ${unconfigured} file(s) with no ESLint config`);
184
201
  const results = [];
185
202
  for (const file of files) {
186
203
  const filePath = path.join(root, file);
@@ -101,6 +101,21 @@ test("a repository without ESLint skips the lint", (t) => {
101
101
  assert.match(result.stdout, /lint skipped/);
102
102
  });
103
103
 
104
+ test("a file with no ESLint config is skipped, and the lint passes", (t) => {
105
+ const { root, qc } = repo(t);
106
+ rmSync(path.join(root, "eslint.config.mjs"));
107
+ writeFileSync(path.join(root, "src", "new.mjs"), "var fresh = 1;\nexport { fresh };\n");
108
+ const result = qc();
109
+ assert.equal(result.status, 0, result.stderr);
110
+ assert.match(result.stdout, /lint skipped 1 file\(s\) with no ESLint config/);
111
+ mkdirSync(path.join(root, "nested"));
112
+ writeFileSync(path.join(root, "nested", "eslint.config.mjs"), 'export default [{ rules: { "no-var": "error" } }];\n');
113
+ writeFileSync(path.join(root, "nested", "file.mjs"), "var nested = 1;\nexport { nested };\n");
114
+ const nested = qc("nested/file.mjs");
115
+ assert.notEqual(nested.status, 0, "a config in a subfolder keeps its file linted");
116
+ assert.doesNotMatch(nested.stdout, /lint skipped/);
117
+ });
118
+
104
119
  test("qc lint applies the baseline per file and rule up to the recorded count", (t) => {
105
120
  const { root, qc } = repo(t);
106
121
  writeFileSync(path.join(root, "eslint-suppressions.json"), JSON.stringify({ "src/old.mjs": { "no-var": { count: 1 } } }));