architecture-harness 0.29.1 → 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.
@@ -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
  });
@@ -4,7 +4,7 @@ import { ownerOf } from "./fleet.mjs";
4
4
  export function overloaded(load) {
5
5
  const reasons = [];
6
6
  if (load?.cpu != null && load.cpu >= 0.9) reasons.push(`cpu ${Math.round(load.cpu * 100)}%`);
7
- if (load?.mem != null && load.mem >= 0.9) reasons.push(`mem ${Math.round(load.mem * 100)}%`);
7
+ if (load?.platform !== "darwin" && load?.mem != null && load.mem >= 0.9) reasons.push(`mem ${Math.round(load.mem * 100)}%`);
8
8
  if (load?.rtt != null && load.rtt >= 2000) reasons.push(`rtt ${load.rtt}ms`);
9
9
  return reasons;
10
10
  }
@@ -135,3 +135,12 @@ test("overloaded peers and Leader get no new work or takeover and keep held work
135
135
  assert.deepEqual(assignTick({ ...input, assignments: dead }).assignments, dead);
136
136
  }
137
137
  });
138
+
139
+
140
+ test("darwin ignores memory overload while CPU and rtt still apply", () => {
141
+ assert.deepEqual(overloaded({ platform: "darwin", mem: 0.95 }), []);
142
+ assert.deepEqual(overloaded({ platform: "linux", mem: 0.95 }), ["mem 95%"]);
143
+ assert.deepEqual(overloaded({ mem: 0.95 }), ["mem 95%"]);
144
+ assert.deepEqual(overloaded({ platform: "darwin", mem: 0.95, cpu: 0.95 }), ["cpu 95%"]);
145
+ assert.deepEqual(overloaded({ platform: "darwin", mem: 0.95, rtt: 6000 }), ["rtt 6000ms"]);
146
+ });
@@ -11,7 +11,8 @@ export const validWork = row => assignmentRef(row) && [null, "plan", "code", "re
11
11
  const validLoad = load => load !== null && typeof load === "object" && !Array.isArray(load) &&
12
12
  Object.entries({ cpu: 1, mem: 1, rtt: 600_000 }).every(([key, limit]) =>
13
13
  load[key] === null || (Number.isFinite(load[key]) && load[key] >= 0 && load[key] <= limit)) &&
14
- Object.keys(load).every(key => ["cpu", "mem", "rtt"].includes(key));
14
+ (load.platform === undefined || (typeof load.platform === "string" && load.platform.length > 0)) &&
15
+ Object.keys(load).every(key => ["platform", "cpu", "mem", "rtt"].includes(key));
15
16
  const validHeartbeat = body => validTerm(body.term) && typeof body.leader === "boolean" && (body.kit === null || typeof body.kit === "string") &&
16
17
  (body.load === undefined || validLoad(body.load)) &&
17
18
  (body.work === undefined || (Array.isArray(body.work) && body.work.every(validWork))) &&
@@ -14,5 +14,5 @@ export function sampleLoad({ os: host = os, previous } = {}) {
14
14
  cpu = round(1 - idle / total);
15
15
  }
16
16
  }
17
- return { cpu, mem: round(1 - host.freemem() / host.totalmem()), sample };
17
+ return { platform: host.platform?.() ?? os.platform(), cpu, mem: round(1 - host.freemem() / host.totalmem()), sample };
18
18
  }
@@ -1,5 +1,11 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { test } from "node:test";
3
+ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { heartbeat, receiveMessage } from "./fleet-node.mjs";
7
+ import { overloaded } from "./fleet-assign.mjs";
8
+ import { readState, writeState } from "./fleet-state.mjs";
3
9
  import { sampleLoad } from "./fleet-load.mjs";
4
10
 
5
11
  const fakeOS = times => ({ cpus: () => times.map(times => ({ times })), freemem: () => 247, totalmem: () => 1000 });
@@ -11,3 +17,34 @@ test("first CPU sample is unknown; memory and CPU deltas round to two decimals",
11
17
  assert.equal(second.cpu, 0.25);
12
18
  assert.equal(sampleLoad({ os: fakeOS([{ user: 20, nice: 0, sys: 10, idle: 70, irq: 0 }, { user: 10, idle: 90 }]), previous: first.sample }).cpu, null);
13
19
  });
20
+
21
+
22
+ test("load samples report the host platform", () => {
23
+ for (const platform of ["darwin", "linux", "win32"]) {
24
+ const load = sampleLoad({ os: { ...fakeOS([{ user: 10, idle: 90 }]), platform: () => platform } });
25
+ assert.equal(load.platform, platform);
26
+ }
27
+ });
28
+
29
+
30
+ test("darwin platform reaches local and remote heartbeat loads", async t => {
31
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-load-"));
32
+ mkdirSync(path.join(root, ".git"));
33
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
34
+ const fleet = { self: "a", secret: "ab".repeat(32), nodes: [
35
+ { id: "a", address: "localhost" }, { id: "b", address: "localhost" },
36
+ ] };
37
+ writeState(root, "node", { leader: true, term: 1 });
38
+ const sent = [];
39
+ await heartbeat({ root, fleet, repo: "o/r", leader: true,
40
+ os: { ...fakeOS([{ user: 10, idle: 90 }]), freemem: () => 50, platform: () => "darwin" },
41
+ fetch: async (_url, options) => { sent.push(JSON.parse(options.body)); return { status: 202 }; },
42
+ });
43
+ const load = readState(root, "peers").a.load;
44
+ assert.equal(load.platform, "darwin");
45
+ assert.equal(load.mem, 0.95);
46
+ assert.deepEqual(overloaded(load), []);
47
+ assert.equal(sent[0].body.load.platform, "darwin");
48
+ assert.deepEqual(receiveMessage({ root, fleet, message: sent[0] }), { ok: true });
49
+ assert.equal(readState(root, "peers").a.load.platform, "darwin");
50
+ });
@@ -1,6 +1,6 @@
1
1
  import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
2
2
 
3
- export const KINDS = Object.freeze(["assign", "plan", "approve", "question", "answer", "pushed", "verdict", "platform-check", "platform-result", "heartbeat", "propose-leader", "leader"]);
3
+ export const KINDS = Object.freeze(["assign", "plan", "approve", "question", "answer", "say", "pushed", "verdict", "platform-check", "platform-result", "heartbeat", "propose-leader", "leader"]);
4
4
  const plain = value => value !== null && typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value));
5
5
  const validSecret = secret => typeof secret === "string" && secret.length >= 64 && !/[^0-9a-f]/i.test(secret);
6
6
 
@@ -21,7 +21,7 @@ test("canonical JSON sorts recursively and signatures cover all unsigned fields"
21
21
  });
22
22
 
23
23
  test("good messages accept every fixed kind, keep command text inert, and reject replays", () => {
24
- assert.deepEqual(KINDS, ["assign", "plan", "approve", "question", "answer", "pushed", "verdict", "platform-check", "platform-result", "heartbeat", "propose-leader", "leader"]);
24
+ assert.deepEqual(KINDS, ["assign", "plan", "approve", "question", "answer", "say", "pushed", "verdict", "platform-check", "platform-result", "heartbeat", "propose-leader", "leader"]);
25
25
  for (const kind of KINDS) assert.deepEqual(verifyMessage(signed({ kind, body: { command: "do not execute" } }), options()), { ok: true });
26
26
  const context = options();
27
27
  const message = signed();
@@ -196,8 +196,8 @@ const loadRounds = new Map();
196
196
 
197
197
  export async function heartbeat({ root = process.cwd(), fleet, repo, kit = null, leader = false, os: host = os, clock = Date.now, fetch = nodeFetch, signal }) {
198
198
  const previous = loadRounds.get(root);
199
- const { cpu, mem, sample } = sampleLoad({ os: host, previous: previous?.sample });
200
- const load = { cpu, mem, rtt: previous?.rtt ?? null };
199
+ const { platform, cpu, mem, sample } = sampleLoad({ os: host, previous: previous?.sample });
200
+ const load = { platform, cpu, mem, rtt: previous?.rtt ?? null };
201
201
  const durations = [];
202
202
  // No snapshot survives a network await: confirmation may rebuild assignments during a send.
203
203
  const bodyFor = id => {
@@ -234,7 +234,7 @@ export async function heartbeat({ root = process.cwd(), fleet, repo, kit = null,
234
234
  const latest = bodyFor(fleet.self);
235
235
  if (latest.leader) {
236
236
  const peers = readState(root, "peers");
237
- peers[fleet.self] = { time: clock(), ...latest, load: { cpu, mem, rtt } };
237
+ peers[fleet.self] = { time: clock(), ...latest, load: { platform, cpu, mem, rtt } };
238
238
  writeState(root, "peers", peers);
239
239
  }
240
240
  }
@@ -267,8 +267,11 @@ export async function startNode({ root = process.cwd(), fleet, leader = false, s
267
267
  const self = localNode(fleet);
268
268
  const record = readState(root, "node");
269
269
  if (Number.isSafeInteger(record.pid) && record.pid > 0) {
270
- if (!await healthy(self, record.instance, fetch, 1000)) throw new Error("fleet node is stale: instance health does not match");
271
- if (isLive(record.pid, kill)) return { running: true, already: true };
270
+ if (isLive(record.pid, kill)) {
271
+ if (!await healthy(self, record.instance, fetch, 1000)) throw new Error("fleet node is stale: instance health does not match");
272
+ return { running: true, already: true };
273
+ }
274
+ removeNode(root);
272
275
  }
273
276
  const instance = randomUUID();
274
277
  mkdirSync(stateDir(root), { recursive: true, mode: 0o700 });
@@ -304,8 +307,8 @@ export async function stopNode({ root = process.cwd(), fleet, fetch = nodeFetch,
304
307
  const deadline = clock() + 5000;
305
308
  const record = readState(root, "node");
306
309
  if (!Number.isSafeInteger(record.pid) || record.pid <= 0) { removeNode(root); return { stopped: true, already: true }; }
307
- if (!await healthy(localNode(fleet), record.instance, fetch, 1000)) throw new Error("fleet node is stale: instance health does not match");
308
310
  if (!isLive(record.pid, kill)) { removeNode(root); return { stopped: true, already: true }; }
311
+ if (!await healthy(localNode(fleet), record.instance, fetch, 1000)) throw new Error("fleet node is stale: instance health does not match");
309
312
  try { kill(record.pid, "SIGTERM"); }
310
313
  catch (error) { if (error.code !== "ESRCH") throw error; }
311
314
  while (isLive(record.pid, kill)) {
@@ -454,11 +457,15 @@ async function electionTick({ root, fleet, repo, clock, fetch, signal }) {
454
457
  }
455
458
  }
456
459
  writeState(root, "queue", kept);
457
- if (dead && candidate === fleet.self && live.length && (!election.candidateTerm || election.candidateTerm < election.highest)) {
460
+ const proposal = readState(root, "proposal");
461
+ const retry = (proposal.id !== fleet.self || proposal.term !== election.candidateTerm) &&
462
+ (election.candidateAt === undefined || now - election.candidateAt >= 30_000);
463
+ if (dead && candidate === fleet.self && live.length && (!election.candidateTerm || election.candidateTerm < election.highest || retry)) {
458
464
  const term = election.highest + 1;
459
465
  if (!validTerm(term)) throw new Error("fleet term exhausted");
460
466
  election.highest = term;
461
467
  election.candidateTerm = term;
468
+ election.candidateAt = now;
462
469
  election.votedTerm = term;
463
470
  writeState(root, "election", election);
464
471
  for (const node of live) replies.push([node, "propose-leader", term]);