architecture-harness 0.29.2 → 0.29.3

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.3",
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,7 +11,7 @@ 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");
@@ -81,7 +82,12 @@ export function watchedItems(call, origin, parse = PARSERS[call.tool_name]) {
81
82
  };
82
83
  const command = call.tool_input?.command ?? "";
83
84
  for (const { words, env } of ghCalls(command, parse)) {
84
- const { group, verb, args, repo } = ghCommand(words);
85
+ const parsed = { ...ghCommand(words), env };
86
+ const { group, verb, args, repo } = parsed;
87
+ if (group === "api") {
88
+ const match = /^repos\/([^/]+\/[^/]+)\/(issues|pulls)\/(\d+)(?:\/|$)/.exec(apiRequest(parsed)?.endpoint ?? "");
89
+ if (match) add(match[1], Number(match[3]), match[2] === "pulls" ? "pr" : "issue");
90
+ }
85
91
  if (!["issue", "pr"].includes(group)) continue;
86
92
  const found = fields(args, call.cwd ?? process.cwd(), group === "pr" && verb === "review");
87
93
  const repository = found.repo ?? repo ?? env.GH_REPO ?? origin;
@@ -102,6 +108,11 @@ export function watchedItems(call, origin, parse = PARSERS[call.tool_name]) {
102
108
  return [...items.values()];
103
109
  }
104
110
 
111
+ // Ledger: a named command reactivates a retired item without invalidating active watches.
112
+ function watch(state, item) {
113
+ state.append({ ...item, retired: false, ...(state.items.get(itemKey(item))?.retired ? { updatedAt: null } : {}) });
114
+ }
115
+
105
116
  // Resource: append records so simultaneous hooks preserve each other's watches and acknowledgments.
106
117
  function ledger(root, session) {
107
118
  if (!session) return null;
@@ -122,12 +133,16 @@ function ledger(root, session) {
122
133
  if (record.reviewDone) { reviews.delete(record.reviewDone); continue; }
123
134
  if (record.own) { for (const url of record.own) own.add(url); continue; }
124
135
  if (record.next) { next = record.next; continue; }
136
+ if (typeof record.retired === "string") { const item = items.get(record.retired); if (item) item.retired = true; continue; }
125
137
  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() };
138
+ const item = items.get(key) ?? { repo: record.repo, number: record.number, seen: new Set(), shown: new Set(), pending: new Map(), prs: new Set() };
127
139
  if (record.kind) item.kind = record.kind;
140
+ if (record.retired === false) item.retired = false;
141
+ if (record.updatedAt !== undefined) item.updatedAt = record.updatedAt;
128
142
  for (const pr of record.prs ?? []) item.prs.add(pr);
129
143
  for (const pending of record.pending ?? []) item.pending.set(pending.stamp, pending);
130
144
  for (const stamp of record.seen ?? []) item.seen.add(stamp);
145
+ for (const stamp of record.shown ?? []) item.shown.add(stamp);
131
146
  items.set(key, item);
132
147
  } catch { /* A torn record leaves earlier acknowledgments intact. */ }
133
148
  }
@@ -138,6 +153,20 @@ function ledger(root, session) {
138
153
  } };
139
154
  }
140
155
 
156
+ const rateLimited = (error) => /rate.?limit|RATE_LIMITED/i.test(String(error));
157
+ const failureReason = (error) => rateLimited(error) ? "rate limit" : ["deadline", "pages", "response"].includes(error.message) ? error.message : "gh";
158
+
159
+ // Resource: retain only a safe failure category from gh stderr.
160
+ function runCommentGh(args, { cwd, env, timeoutMs }) {
161
+ return new Promise((resolve, reject) => {
162
+ execFile("gh", args, { cwd, env: { ...process.env, ...env }, encoding: "utf8", windowsHide: true,
163
+ timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
164
+ if (error) reject(new Error(rateLimited(stderr) ? "rate limit" : error.killed ? "deadline" : "gh"));
165
+ else resolve(stdout);
166
+ });
167
+ });
168
+ }
169
+
141
170
  // Resource: bound all gh processes in one invocation to a shared deadline.
142
171
  function github(root, config, deadline, run) {
143
172
  return async (repo, args) => {
@@ -166,6 +195,17 @@ async function comments(item, gh) {
166
195
  return (await Promise.all(endpoints.map(list))).flat();
167
196
  }
168
197
 
198
+ // Fragment: ask for every watched item's metadata in one request per repository.
199
+ async function itemMetadata(repo, items, gh) {
200
+ const [owner, name] = repo.split("/");
201
+ const fields = items.map(item => `item_${item.number}: issueOrPullRequest(number: ${item.number}) { __typename ... on Issue { state updatedAt } ... on PullRequest { state updatedAt } }`).join(" ");
202
+ const result = await gh(repo, ["api", "graphql", "-f", `owner=${owner}`, "-f", `name=${name}`,
203
+ "-f", `query=query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`]);
204
+ if (result.errors?.length) throw new Error(result.errors.some(error => rateLimited(`${error.type} ${error.message}`)) ? "rate limit" : "response");
205
+ if (!result.data?.repository) throw new Error("response");
206
+ return result.data.repository;
207
+ }
208
+
169
209
  async function unseen(item, gh, state) {
170
210
  const rows = await comments(item, gh);
171
211
  for (const marker of state.reviews.values()) {
@@ -194,8 +234,10 @@ const context = (event, text) => ({ hookSpecificOutput: { hookEventName: event,
194
234
  // Ledger: retain truncated previews so a full read can acknowledge them from any hook.
195
235
  function recordPreview(state, item, fresh, acknowledge = false) {
196
236
  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 });
237
+ const shown = fresh.filter(({ row }) => truncated(row)).map(({ stamp }) => stamp);
238
+ const pending = fresh.filter(({ row }) => truncated(row) || !acknowledge)
239
+ .map(({ row, stamp }) => ({ stamp, id: row.id, endpoint: row.endpoint, url: row.url, ...(!truncated(row) ? { row } : {}) }));
240
+ if (seen.length || pending.length) state.append({ repo: item.repo, number: item.number, seen, shown, pending });
199
241
  }
200
242
 
201
243
  // Ledger: acknowledge only pending comments covered by a successful full read.
@@ -221,8 +263,10 @@ function apiRequest(command) {
221
263
  // API flags may precede the endpoint; keep their names with their values.
222
264
  const apiWords = command.rest;
223
265
  let method;
266
+ let hostname = command.env?.GH_HOST ?? "github.com";
224
267
  let write = false;
225
268
  let endpoint;
269
+ let endpointHost;
226
270
  const values = new Set(["--method", "--field", "--raw-field", "--input", "--header", "--hostname", "--jq", "--template", "--cache", "--preview"]);
227
271
  for (let i = 0; i < apiWords.length; i++) {
228
272
  const word = apiWords[i];
@@ -230,6 +274,7 @@ function apiRequest(command) {
230
274
  if (long && values.has(long[1])) {
231
275
  const value = long[2] ?? apiWords[++i];
232
276
  if (long[1] === "--method") method = value;
277
+ if (long[1] === "--hostname") hostname = value;
233
278
  if (["--field", "--raw-field", "--input"].includes(long[1])) write = true;
234
279
  continue;
235
280
  }
@@ -242,8 +287,13 @@ function apiRequest(command) {
242
287
  }
243
288
  continue;
244
289
  }
245
- if (/^(?:https:\/\/api.github.com\/)?\/?repos\//.test(word)) endpoint ??= word.replace(/^https:\/\/api.github.com\//, "").replace(/^\//, "").split("?")[0].replace(/^repos\/([^/]+\/[^/]+)/, match => match.toLowerCase());
290
+ if (!endpoint && /^(?:https:\/\/api.github.com\/)?\/?repos\//.test(word)) {
291
+ endpointHost = word.startsWith("https://api.github.com/") ? "github.com" : undefined;
292
+ endpoint = word.replace(/^https:\/\/api.github.com\//, "").replace(/^\//, "").split("?")[0].replace(/^repos\/([^/]+\/[^/]+)/, match => match.toLowerCase());
293
+ }
246
294
  }
295
+ // Watch identities and comment requests currently cover GitHub.com only.
296
+ if ((endpointHost ?? hostname)?.toLowerCase() !== "github.com") return null;
247
297
  return { endpoint, method: method ?? (write ? "POST" : "GET") };
248
298
  }
249
299
 
@@ -259,7 +309,7 @@ function createdKeys(response, endpoint) {
259
309
  ...createdKeys(response.stdout ?? response.output ?? response.content ?? response.text, endpoint)].filter(Boolean);
260
310
  }
261
311
 
262
- export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTargets } = {}) {
312
+ export async function commentWatch(call, { gh: run = runCommentGh, merges: mergeTargets } = {}) {
263
313
  const root = checkoutRootOf(call.cwd ?? process.cwd());
264
314
  if (!root || !call.session_id) return null;
265
315
  const event = call.hook_event_name;
@@ -277,9 +327,9 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
277
327
  if (call.tool_response?.is_error || call.tool_response?.exit_code > 0) return null;
278
328
  const watched = watchedItems(call, origin, parse);
279
329
  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) });
330
+ for (const item of watched) watch(state, { ...item, prs: prs.filter(pr => pr.repo === item.repo).map(itemKey) });
281
331
  for (const { words, env } of ghCalls(call.tool_input?.command ?? "", parse)) {
282
- const command = ghCommand(words);
332
+ const command = { ...ghCommand(words), env };
283
333
  const request = apiRequest(command);
284
334
  if (request?.method === "POST" && /^repos\/[^/]+\/[^/]+\/(?:issues(?:\/\d+\/comments)?|pulls(?:\/\d+\/(?:comments|reviews))?)$/.test(request.endpoint ?? "")) {
285
335
  state.append({ own: createdKeys(call.tool_response, request.endpoint) });
@@ -297,8 +347,8 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
297
347
  const pr = await gh(repo, ["pr", "view", ...(selector ? [selector] : []), "-R", repo, "--json", "number,body"]);
298
348
  number = pr.number;
299
349
  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);
350
+ watch(state, { repo, number, kind: "pr" });
351
+ references(pr.body ?? "", repo, (repo, number) => watch(state, { repo, number, kind: "issue", prs: [key] }), true);
302
352
  }
303
353
  if (Number.isSafeInteger(number) && ["create", "comment", "review"].includes(command.verb)) {
304
354
  const resource = command.verb === "review" ? `pulls/${number}/reviews` : `issues/${number}/comments`;
@@ -320,16 +370,61 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
320
370
  }
321
371
  if (event === "UserPromptSubmit" || event === "Stop") {
322
372
  const lines = [];
323
- const items = [...state.items.values()];
373
+ if (event === "UserPromptSubmit") for (const item of state.items.values()) {
374
+ if (!item.retired) continue;
375
+ const pending = [...item.pending.values()].filter(pending => pending.row && !item.seen.has(pending.stamp)).map(({ row, stamp }) => ({ row, stamp }));
376
+ lines.push(...pending.map(({ row }) => describe(item, row)));
377
+ recordPreview(state, item, pending, true);
378
+ }
379
+ const items = [...state.items.values()].filter(item => !item.retired);
324
380
  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];
381
+ const ordered = [...items.slice(start), ...items.slice(0, start)];
382
+ const repos = new Map();
383
+ for (const item of ordered) {
384
+ const repo = item.repo.toLowerCase();
385
+ if (!repos.has(repo)) repos.set(repo, []);
386
+ repos.get(repo).push(item);
387
+ }
388
+ let failed = 0;
389
+ let checked = 0;
390
+ const reasons = new Set();
391
+ let stopped = false;
392
+ const metadataByRepo = new Map();
393
+ const stopAfter = (item) => {
394
+ stopped = true;
395
+ state.append({ next: itemKey(ordered[(ordered.indexOf(item) + 1) % ordered.length]) });
396
+ };
397
+ for (const item of ordered) {
398
+ const repo = item.repo.toLowerCase();
399
+ if (!metadataByRepo.has(repo)) {
400
+ try {
401
+ metadataByRepo.set(repo, { data: await itemMetadata(item.repo, repos.get(repo), gh) });
402
+ } catch (error) {
403
+ metadataByRepo.set(repo, { error });
404
+ }
405
+ }
327
406
  try {
328
- const fresh = await unseen(item, gh, state);
329
- lines.push(...fresh.map(({ row }) => describe(item, row)));
407
+ const { data: metadata, error } = metadataByRepo.get(repo);
408
+ if (error) throw error;
409
+ const info = metadata[`item_${item.number}`];
410
+ if (!info || !["OPEN", "CLOSED", "MERGED"].includes(info.state) || typeof info.updatedAt !== "string" || !info.updatedAt) throw new Error("response");
411
+ if (info.__typename === "PullRequest") item.kind = "pr";
412
+ const changed = info.updatedAt !== item.updatedAt;
413
+ const fresh = changed ? await unseen(item, gh, state)
414
+ : [...item.pending.values()].filter(pending => pending.row && !item.seen.has(pending.stamp)).map(({ row, stamp }) => ({ row, stamp }));
415
+ lines.push(...fresh.filter(({ stamp }) => !item.shown.has(stamp)).map(({ row }) => describe(item, row)));
330
416
  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
- }));
417
+ if (changed) state.append({ repo: item.repo, number: item.number, kind: item.kind, updatedAt: info.updatedAt });
418
+ if (["CLOSED", "MERGED"].includes(info.state)) state.append({ retired: itemKey(item) });
419
+ } catch (error) {
420
+ reasons.add(failureReason(error));
421
+ if (rateLimited(error) || error.message === "deadline") { stopAfter(item); break; }
422
+ failed++;
423
+ }
424
+ checked++;
425
+ }
426
+ if (stopped) failed += items.length - checked;
427
+ if (failed) lines.push(`Comment watch: ${failed} items could not be checked (${[...reasons].join(", ")}); retry on the next prompt.`);
333
428
  return lines.length ? (event === "Stop" ? { systemMessage: lines.join("\n") } : context(event, lines.join("\n"))) : null;
334
429
  }
335
430
  if (event === "PreToolUse") {
@@ -364,7 +459,7 @@ export async function commentWatch(call, { gh: run = runGhAsync, merges: mergeTa
364
459
  }
365
460
  add(repo, pr.number, "pr");
366
461
  await Promise.all([...targets.values()].map(async target => {
367
- state.append(target);
462
+ watch(state, target);
368
463
  const item = { ...state.items.get(itemKey(target)), ...target };
369
464
  try {
370
465
  const fresh = await unseen(item, gh, state);
@@ -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,18 +135,27 @@ 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
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 ?? [] };
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: {} };
@@ -200,6 +296,23 @@ test("only session-created URLs are skipped, including reviews and PRs", (t) =>
200
296
  assert.match(output, /Comment 4/);
201
297
  });
202
298
 
299
+ test("truncated comments print once across prompts and Stop but still block merging", (t) => {
300
+ const f = fixture(t);
301
+ f.rows[0].body = "x".repeat(850);
302
+ f.update();
303
+ f.run("PostToolUse", "gh issue view 4");
304
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
305
+ assert.equal(f.run("UserPromptSubmit"), null);
306
+ assert.equal(f.run("Stop"), null);
307
+ for (let attempt = 0; attempt < 2; attempt++) {
308
+ const guard = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
309
+ assert.equal(guard?.hookSpecificOutput?.permissionDecision, "deny");
310
+ assert.match(JSON.stringify(guard), /truncated/);
311
+ }
312
+ f.run("PostToolUse", "gh issue view 4 --comments");
313
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
314
+ });
315
+
203
316
  test("full reads acknowledge only the comment kinds their output contains", (t) => {
204
317
  for (const [command, seen] of [
205
318
  ["gh issue view 4 --comments", [1]],
@@ -222,12 +335,14 @@ test("full reads acknowledge only the comment kinds their output contains", (t)
222
335
  assert.match(output, /truncated/i, command);
223
336
  assert.match(output, /gh api repos\/shawrylk\/example\/pulls\/7\/comments --paginate/, command);
224
337
  assert.doesNotMatch(output, /hidden request/, command);
225
- assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/i, command);
338
+ assert.equal(f.run("UserPromptSubmit"), null, command);
339
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/i, command);
226
340
  assert.equal(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput?.permissionDecision, "deny", command);
227
341
  f.run("PostToolUse", command, "comment-watch.mjs", "session-a", { exit_code: 1 });
228
- assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/i, command);
342
+ assert.equal(f.run("UserPromptSubmit"), null, command);
343
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/i, command);
229
344
  f.run("PostToolUse", command);
230
- const remaining = JSON.stringify(f.run("UserPromptSubmit"));
345
+ const remaining = JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs"));
231
346
  for (const row of f.rows) assert.equal(remaining.includes(`Comment ${row.id} `), !seen.includes(row.id), command);
232
347
  }
233
348
  });
@@ -373,20 +488,242 @@ test("API merges check comments with dispatch on and off in both shells", (t) =>
373
488
  }
374
489
  });
375
490
 
376
- test("polls use one issue request and three PR requests in parallel", (t) => {
491
+ test("polls batch metadata per repository and fetch comments only when updatedAt changes", (t) => {
377
492
  const f = fixture(t);
378
493
  f.run("PostToolUse", "gh pr view 7");
379
494
  writeFileSync(f.calls, "");
380
- f.update({ delay: 250 });
381
495
  f.run("UserPromptSubmit");
382
496
  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")));
497
+ const metadata = calls.filter(call => call.args[1] === "graphql");
498
+ assert.equal(metadata.length, 2);
499
+ const query = metadata.find(call => call.args.includes("owner=shawrylk")).args.join(" ");
500
+ for (const number of [4, 7]) assert.match(query, new RegExp(`item_${number}:.*issueOrPullRequest\\(number: ${number}\\)`));
501
+ assert.match(query, /state updatedAt/);
502
+ const commentCalls = calls.filter(call => call.args[1] !== "graphql");
503
+ assert.equal(commentCalls.length, 5);
504
+ assert.ok(commentCalls.every(call => call.args.includes("--paginate")));
386
505
  assert.ok(calls.every(call => !call.args.includes("--slurp")));
506
+ writeFileSync(f.calls, "");
507
+ assert.equal(f.run("UserPromptSubmit"), null);
508
+ const unchanged = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
509
+ assert.equal(unchanged.length, 2);
510
+ assert.ok(unchanged.every(call => call.args[1] === "graphql"));
511
+ f.run("PostToolUse", "gh issue view 4");
512
+ writeFileSync(f.calls, "");
513
+ assert.equal(f.run("UserPromptSubmit"), null);
514
+ const named = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse);
515
+ assert.ok(named.every(call => call.args[1] === "graphql"));
387
516
  f.rows[0].body = "Retry this item";
388
517
  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/);
518
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment watch: 1 items could not be checked \(gh\); retry on the next prompt\./);
390
519
  f.update();
520
+ writeFileSync(f.calls, "");
391
521
  assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Retry this item/);
522
+ const retry = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start && call.args[1] !== "graphql");
523
+ assert.equal(retry.length, 1);
524
+ assert.match(retry[0].args.at(-1), /issues\/4\/comments/);
525
+ });
526
+
527
+ test("a Stop preview is acknowledged on the next prompt even when updatedAt is unchanged", (t) => {
528
+ const f = fixture(t);
529
+ f.run("PostToolUse", "gh issue view 4");
530
+ assert.match(JSON.stringify(f.run("Stop")), /Comment 1/);
531
+ writeFileSync(f.calls, "");
532
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
533
+ const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse);
534
+ assert.ok(calls.every(call => call.args[1] === "graphql"));
535
+ const guard = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
536
+ assert.doesNotMatch(JSON.stringify(guard), /Comment 1/);
537
+ });
538
+
539
+ for (const state of ["CLOSED", "MERGED"]) test(`${state} items retire after one successful check and a named command watches them again`, (t) => {
540
+ const f = fixture(t);
541
+ const number = state === "MERGED" ? 7 : 4;
542
+ const command = state === "MERGED" ? "gh pr view 7" : "gh issue view 4";
543
+ f.update({ body: "", metadata: { [number]: { state } }, failEndpoint: `issues/${number}/comments` });
544
+ f.run("PostToolUse", command);
545
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /could not be checked/);
546
+ f.update({ body: "", metadata: { [number]: { state } } });
547
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), new RegExp(`Comment ${number === 4 ? 1 : 4}`));
548
+ writeFileSync(f.calls, "");
549
+ assert.equal(f.run("UserPromptSubmit"), null);
550
+ assert.equal(f.run("Stop"), null);
551
+ assert.equal(readFileSync(f.calls, "utf8"), "");
552
+ const ledgerPath = path.join(f.cwd, ".git", "qc", `comment-watch-${createHash("sha256").update("session-a").digest("hex")}.jsonl`);
553
+ const records = readFileSync(ledgerPath, "utf8").split("\n").filter(Boolean).map(JSON.parse);
554
+ assert.ok(records.some(record => record.retired === `shawrylk/example#${number}`));
555
+ f.run("PostToolUse", command);
556
+ writeFileSync(f.calls, "");
557
+ f.run("UserPromptSubmit");
558
+ const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
559
+ assert.equal(calls.filter(call => call.args[1] === "graphql").length, 1);
560
+ assert.equal(calls.filter(call => call.args.includes("--paginate")).length, number === 7 ? 3 : 1);
561
+ });
562
+
563
+ test("a merge checks a retired issue named in the PR body again", (t) => {
564
+ const f = fixture(t);
565
+ f.update({ metadata: { 4: { state: "CLOSED" } } });
566
+ f.run("PostToolUse", "gh issue close 4");
567
+ f.run("UserPromptSubmit");
568
+ f.rows[0].body = "Feedback after retirement";
569
+ f.update();
570
+ assert.equal(f.run("UserPromptSubmit"), null);
571
+ writeFileSync(f.calls, "");
572
+ const guard = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
573
+ assert.equal(guard?.hookSpecificOutput?.permissionDecision, "deny");
574
+ assert.match(JSON.stringify(guard), /Feedback after retirement/);
575
+ assert.match(readFileSync(f.calls, "utf8"), /issues\/4\/comments/);
576
+ });
577
+
578
+ for (const failure of ["metadata", "comments", "partial GraphQL"]) test(`five ${failure} failures print one summary and retry`, (t) => {
579
+ const f = fixture(t);
580
+ f.run("PostToolUse", [1, 2, 3, 4, 5].map(number => `gh issue view ${number}`).join("; "));
581
+ f.update(failure === "partial GraphQL" ? { graphqlReply: { data: { repository: {} }, errors: [{ message: "TOKEN_MUST_STAY_SECRET" }] } }
582
+ : { failEndpoint: failure === "metadata" ? "graphql" : "/comments" });
583
+ const output = f.run("UserPromptSubmit").hookSpecificOutput.additionalContext;
584
+ assert.equal(output, `Comment watch: 5 items could not be checked (${failure === "partial GraphQL" ? "response" : "gh"}); retry on the next prompt.`);
585
+ f.update();
586
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
587
+ });
588
+
589
+ for (const endpoint of ["graphql", "issues/1/comments"]) test(`rate limits on ${endpoint} end polling before further calls`, (t) => {
590
+ const f = fixture(t);
591
+ f.run("PostToolUse", "gh issue view 1; gh issue view 4; gh issue view 8 -R ArentInc/other");
592
+ f.update({ failEndpoint: endpoint, failure: "API rate limit exceeded TOKEN_MUST_STAY_SECRET" });
593
+ writeFileSync(f.calls, "");
594
+ assert.equal(f.run("UserPromptSubmit").hookSpecificOutput.additionalContext,
595
+ "Comment watch: 3 items could not be checked (rate limit); retry on the next prompt.");
596
+ const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
597
+ assert.equal(calls.length, endpoint === "graphql" ? 1 : 2);
598
+ f.update();
599
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
600
+ });
601
+
602
+ test("consecutive polls continue past an item whose comments exhaust the deadline", async (t) => {
603
+ const f = fixture(t);
604
+ f.run("PostToolUse", "gh issue view 4; gh issue view 5");
605
+ let now = Date.now();
606
+ t.mock.method(Date, "now", () => now);
607
+ const requests = [];
608
+ const poll = () => commentWatch({ cwd: f.cwd, session_id: "session-a", hook_event_name: "UserPromptSubmit" }, {
609
+ gh: async (args, options) => {
610
+ requests.push(args);
611
+ if (args[1] === "graphql") return JSON.stringify({ data: { repository: {
612
+ item_4: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
613
+ item_5: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
614
+ } } });
615
+ if (args.at(-1).includes("issues/4/comments")) {
616
+ now += options.timeoutMs;
617
+ throw new Error("deadline");
618
+ }
619
+ return JSON.stringify([{ id: 5, body: "Later feedback", updated_at: "2026-01-01T00:00:00Z" }]);
620
+ },
621
+ });
622
+ assert.match(JSON.stringify(await poll()), /2 items could not be checked \(deadline\)/);
623
+ requests.length = 0;
624
+ const second = JSON.stringify(await poll());
625
+ assert.match(second, /Later feedback/);
626
+ assert.match(second, /1 items could not be checked \(deadline\)/);
627
+ assert.match(requests[1].at(-1), /issues\/5\/comments/);
628
+ assert.match(requests[2].at(-1), /issues\/4\/comments/);
629
+ });
630
+
631
+ test("poll rotation reaches another repository after two items exhaust the deadline", async (t) => {
632
+ const f = fixture(t);
633
+ f.run("PostToolUse", "gh issue view 4; gh issue view 5; gh issue view 8 -R owner/other");
634
+ let now = Date.now();
635
+ t.mock.method(Date, "now", () => now);
636
+ const requests = [];
637
+ const poll = () => commentWatch({ cwd: f.cwd, session_id: "session-a", hook_event_name: "UserPromptSubmit" }, {
638
+ gh: async (args, options) => {
639
+ requests.push(args);
640
+ if (args[1] === "graphql") return JSON.stringify({ data: { repository: Object.fromEntries(
641
+ [...args.at(-1).matchAll(/item_(\d+):/g)].map(([, number]) => [
642
+ `item_${number}`, { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
643
+ ]),
644
+ ) } });
645
+ if (/issues\/[45]\/comments/.test(args.at(-1))) {
646
+ now += options.timeoutMs;
647
+ throw new Error("deadline");
648
+ }
649
+ return JSON.stringify([{ id: 8, body: "Other repository feedback", updated_at: "2026-01-01T00:00:00Z" }]);
650
+ },
651
+ });
652
+ for (let i = 0; i < 2; i++) {
653
+ assert.match(JSON.stringify(await poll()), /3 items could not be checked \(deadline\)/);
654
+ }
655
+ requests.length = 0;
656
+ const third = JSON.stringify(await poll());
657
+ assert.match(third, /Other repository feedback/);
658
+ assert.match(third, /2 items could not be checked \(deadline\)/);
659
+ assert.match(requests[1].at(-1), /repos\/owner\/other\/issues\/8\/comments/);
660
+ const metadata = requests.filter(args => args[1] === "graphql");
661
+ assert.equal(metadata.length, 2);
662
+ assert.equal(metadata.filter(args => args.includes("name=example")).length, 1);
663
+ assert.match(metadata.find(args => args.includes("name=example")).at(-1), /item_4:.*item_5:/);
664
+ });
665
+
666
+ test("all poll requests share the 3.5 second deadline", async (t) => {
667
+ const f = fixture(t);
668
+ f.run("PostToolUse", "gh issue view 4; gh issue view 5");
669
+ let now = Date.now();
670
+ t.mock.method(Date, "now", () => now);
671
+ const requests = [];
672
+ const output = await commentWatch({ cwd: f.cwd, session_id: "session-a", hook_event_name: "UserPromptSubmit" }, {
673
+ gh: async (args, options) => {
674
+ requests.push(args);
675
+ assert.equal(options.timeoutMs, 3500);
676
+ now += 3501;
677
+ return JSON.stringify({ data: { repository: {
678
+ item_4: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
679
+ item_5: { state: "OPEN", updatedAt: "2026-01-01T00:00:00Z" },
680
+ } } });
681
+ },
682
+ });
683
+ assert.equal(requests.length, 1);
684
+ assert.equal(output.hookSpecificOutput.additionalContext,
685
+ "Comment watch: 2 items could not be checked (deadline); retry on the next prompt.");
686
+ });
687
+
688
+ test("old ledger records stay readable and previews append without replacing them", (t) => {
689
+ const f = fixture(t);
690
+ f.rows[0].body = "x".repeat(850);
691
+ f.update();
692
+ const row = f.rows[0];
693
+ const stamp = createHash("sha256").update(JSON.stringify([row.html_url, row.id, row.updated_at, row.body, row.state])).digest("hex");
694
+ const dir = path.join(f.cwd, ".git", "qc");
695
+ mkdirSync(dir, { recursive: true });
696
+ const file = path.join(dir, `comment-watch-${createHash("sha256").update("session-a").digest("hex")}.jsonl`);
697
+ const old = JSON.stringify({ repo: "shawrylk/example", number: 4, kind: "issue", pending: [
698
+ { stamp, id: row.id, endpoint: "repos/shawrylk/example/issues/4/comments" },
699
+ ] }) + "\n";
700
+ writeFileSync(file, old);
701
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
702
+ assert.equal(f.run("UserPromptSubmit"), null);
703
+ assert.match(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
704
+ f.run("PostToolUse", "gh issue view 4 --comments");
705
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /truncated/);
706
+ assert.ok(readFileSync(file, "utf8").startsWith(old));
707
+ });
708
+
709
+ test("a closed item's short Stop preview is acknowledged on the next prompt without polling", (t) => {
710
+ const f = fixture(t);
711
+ f.update({ metadata: { 4: { state: "CLOSED" } } });
712
+ f.run("PostToolUse", "gh issue view 4");
713
+ assert.match(JSON.stringify(f.run("Stop")), /Comment 1/);
714
+ writeFileSync(f.calls, "");
715
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Comment 1/);
716
+ assert.equal(readFileSync(f.calls, "utf8"), "");
717
+ assert.doesNotMatch(JSON.stringify(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")), /Comment 1/);
718
+ });
719
+
720
+ test("a gh API command naming a retired item watches it again", (t) => {
721
+ const f = fixture(t);
722
+ f.update({ metadata: { 4: { state: "CLOSED" } } });
723
+ f.run("PostToolUse", "gh issue view 4");
724
+ f.run("UserPromptSubmit");
725
+ f.rows[0].body = "New feedback on the retired issue";
726
+ f.update();
727
+ f.run("PostToolUse", "gh api repos/shawrylk/example/issues/4");
728
+ assert.match(JSON.stringify(f.run("UserPromptSubmit")), /New feedback on the retired issue/);
392
729
  });