architecture-harness 0.26.0 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/package.json +3 -2
  2. package/src/cli/ask.mjs +3 -1
  3. package/src/cli/ask.test.mjs +17 -1
  4. package/src/cli/bash-command-guard.mjs +37 -5
  5. package/src/cli/bash-command-guard.test.mjs +18 -0
  6. package/src/cli/check-full.test.mjs +4 -3
  7. package/src/cli/check.mjs +1 -1
  8. package/src/cli/ci-template.test.mjs +37 -2
  9. package/src/cli/cli.test.mjs +8 -0
  10. package/src/cli/codex-implement.mjs +5 -4
  11. package/src/cli/codex-implement.test.mjs +93 -0
  12. package/src/cli/commit-msg.mjs +4 -0
  13. package/src/cli/commit-msg.test.mjs +10 -0
  14. package/src/cli/fleet-assign.mjs +46 -0
  15. package/src/cli/fleet-assign.test.mjs +114 -0
  16. package/src/cli/fleet-github.mjs +124 -0
  17. package/src/cli/fleet-github.test.mjs +243 -0
  18. package/src/cli/fleet-message.mjs +50 -0
  19. package/src/cli/fleet-message.test.mjs +72 -0
  20. package/src/cli/fleet-node.mjs +555 -0
  21. package/src/cli/fleet-node.test.mjs +1284 -0
  22. package/src/cli/fleet-platform.mjs +200 -0
  23. package/src/cli/fleet-platform.test.mjs +316 -0
  24. package/src/cli/fleet-state.mjs +75 -0
  25. package/src/cli/fleet-state.test.mjs +114 -0
  26. package/src/cli/fleet-talk.mjs +143 -0
  27. package/src/cli/fleet-talk.test.mjs +178 -0
  28. package/src/cli/fleet.mjs +142 -13
  29. package/src/cli/fleet.test.mjs +314 -11
  30. package/src/cli/legs.mjs +3 -3
  31. package/src/cli/legs.test.mjs +24 -1
  32. package/src/cli/merge-guard.mjs +8 -6
  33. package/src/cli/merge-guard.test.mjs +38 -0
  34. package/src/cli/platform-risk.mjs +95 -1
  35. package/src/cli/platform-risk.test.mjs +185 -0
  36. package/src/cli/qc.mjs +6 -0
  37. package/src/cli/repl-commands.mjs +168 -0
  38. package/src/cli/repl-commands.test.mjs +133 -0
  39. package/src/cli/role-line.mjs +49 -0
  40. package/src/cli/role-line.test.mjs +55 -0
  41. package/src/cli/watch.mjs +35 -2
  42. package/src/cli/watch.test.mjs +106 -0
  43. package/src/cli/workflow-hooks.test.mjs +13 -4
  44. package/src/config.mjs +2 -2
@@ -0,0 +1,133 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { replCommands } from "./repl-commands.mjs";
4
+
5
+ test("reads tagged templates, string calls, and tools.Bash command literals in source order", () => {
6
+ assert.deepEqual(replCommands('await $`git status`; $("git log"); tools.Bash({ command: \'git diff\' });'),
7
+ ["git status", "git log", "git diff"]);
8
+ assert.deepEqual(replCommands("$( 'git status' ); tools.Bash({ timeout: 1000, command: \"git log\", cwd: dir });"),
9
+ ["git status", "git log"]);
10
+ });
11
+
12
+ test("replaces interpolation values with a shell word", () => {
13
+ assert.deepEqual(replCommands('await $`git commit -m ${message} ${options.flag}`'),
14
+ ["git commit -m QC_VALUE QC_VALUE"]);
15
+ assert.deepEqual(replCommands('$`echo ${ { a: { b: "}" } } } done`'), ["echo QC_VALUE done"]);
16
+ });
17
+
18
+ test("decodes escaped delimiters and string literal escapes", () => {
19
+ assert.deepEqual(replCommands('$`echo \\`hello\\` \\${value}`'), ['echo `hello` ${value}']);
20
+ assert.deepEqual(replCommands('$("git\\x20commit\\u0020--no-verify\\n"); $(\'echo \\\'hello\\\'\');'),
21
+ ["git commit --no-verify\n", "echo 'hello'"]);
22
+ });
23
+
24
+ test("balances nested templates, braces, comments, and quotes inside values", () => {
25
+ assert.deepEqual(replCommands('$`echo ${`nested ${ {value: "}"} }`} tail`'), ["echo QC_VALUE tail"]);
26
+ assert.deepEqual(replCommands('$`echo ${fn(/* } */ "}", \'{\', {value: `x${1}`})} tail`'), ["echo QC_VALUE tail"]);
27
+ assert.deepEqual(replCommands('$`echo ${await $`git status`} tail`'), ["echo QC_VALUE tail", "git status"]);
28
+ });
29
+
30
+ test("regex literals in interpolations preserve the remaining shell command", () => {
31
+ assert.deepEqual(replCommands("$`echo ${/'/.test(\"\")}; git commit --no-verify`"),
32
+ ["echo QC_VALUE; git commit --no-verify"]);
33
+ });
34
+
35
+ test("tools.Bash skips regex literals in property values", () => {
36
+ assert.deepEqual(replCommands('tools.Bash({ description: /}/.source, command: "git commit --no-verify" })'),
37
+ ["git commit --no-verify"]);
38
+ assert.deepEqual(replCommands(String.raw`tools.Bash({ description: /[},'\/]*/gi.source, command: "git commit --no-verify" })`),
39
+ ["git commit --no-verify"]);
40
+ });
41
+
42
+ test("division across a line end keeps the Bash command", () => {
43
+ assert.deepEqual(replCommands('const timeoutMs = 120000; tools.Bash({ command: "git commit --no-verify", timeout: timeoutMs\n / 2 });'),
44
+ ["git commit --no-verify"]);
45
+ });
46
+
47
+ test("regex scanning follows expression starts and preserves division", () => {
48
+ const expressions = [
49
+ "(/'/)", "(0, /'/)", "value = /'/", "({ pattern: /'/ })", "[/'/]", "!/'/", "value && /'/",
50
+ "value || /'/", "value ? /'/ : /}/", "(() => { /'/; })()", "(() => { {} /'/; })()",
51
+ "(() => { value; /'/; })()", "(() => { return /'/; })()", "value\n/ 2",
52
+ "(() => { return /* note */ /'/; })()", String.raw`/\/'[}]/gi`,
53
+ "12 / 3", "(12) / 3", "values[0] / 3", "value / /* note */ 3", "value / /}/.source.length",
54
+ ];
55
+ for (const expression of expressions) {
56
+ assert.deepEqual(replCommands('$`echo ${' + expression + '}; git commit --no-verify`'),
57
+ ["echo QC_VALUE; git commit --no-verify"], expression);
58
+ assert.deepEqual(replCommands(`tools.Bash({ description: ${expression}, command: "git commit --no-verify" })`),
59
+ ["git commit --no-verify"], expression);
60
+ }
61
+ });
62
+
63
+ test("line comments end at every JavaScript line terminator", () => {
64
+ for (const lineEnd of ["\r", "\n", "\u2028", "\u2029"]) {
65
+ assert.deepEqual(replCommands(`tools.Bash({ // note${lineEnd}command: "git commit --no-verify" })`),
66
+ ["git commit --no-verify"], JSON.stringify(lineEnd));
67
+ assert.deepEqual(replCommands('$`echo ${value // note' + lineEnd + '}; git commit --no-verify`'),
68
+ ["echo QC_VALUE; git commit --no-verify"], JSON.stringify(lineEnd));
69
+ }
70
+ });
71
+
72
+ test("string calls skip comments and whitespace around the argument", () => {
73
+ assert.deepEqual(replCommands('$("git commit --no-verify" /* note */)'),
74
+ ["git commit --no-verify"]);
75
+ assert.deepEqual(replCommands('$( /* before */ // note\r "git commit --no-verify" // after\u2028 /* end */ )'),
76
+ ["git commit --no-verify"]);
77
+ });
78
+
79
+ test("reads two commands and retains templates inside comments and strings", () => {
80
+ assert.deepEqual(replCommands('await $`git status`; await $`git commit --no-verify`;'),
81
+ ["git status", "git commit --no-verify"]);
82
+ assert.deepEqual(replCommands('// $`git commit --no-verify`\nconst text = "$`gh pr merge 1`";'),
83
+ ["git commit --no-verify", "gh pr merge 1"]);
84
+ });
85
+
86
+ test("reads only the three literal forms", () => {
87
+ for (const code of ['', 'const value = 1;', '$(command)', 'tools.Bash({ command })',
88
+ 'tools.Bash({ command: getCommand() })', 'other.Bash({ command: "git status" })',
89
+ 'shell`git status`', 'shell$("git status")', 'tools.Bash({ other: "git status" })']) {
90
+ assert.deepEqual(replCommands(code), [], code);
91
+ }
92
+ });
93
+
94
+ test("a malformed form preserves commands before and after it", () => {
95
+ assert.deepEqual(replCommands('$`git commit --no-verify`; // $("unterminated'),
96
+ ["git commit --no-verify"]);
97
+ assert.deepEqual(replCommands('$("bad\\xZZ"); $`git commit --no-verify`'),
98
+ ["git commit --no-verify"]);
99
+ assert.deepEqual(replCommands('tools.Bash({ command: "unterminated }); $`git commit --no-verify`'),
100
+ ["git commit --no-verify"]);
101
+ });
102
+
103
+ test("tools.Bash skips comments while scanning properties", () => {
104
+ assert.deepEqual(replCommands('tools.Bash({ /* ignored, command: "fake" */ command: "git commit --no-verify" })'),
105
+ ["git commit --no-verify"]);
106
+ assert.deepEqual(replCommands('tools.Bash({ timeout: 1000, // ignored, command: "fake"\n command /* key */ : /* value */ "git commit --no-verify" /* end */ })'),
107
+ ["git commit --no-verify"]);
108
+ assert.deepEqual(replCommands('tools.Bash({ timeout: 1000 /* comma, command: "fake" */, command: "git status" })'),
109
+ ["git status"]);
110
+ });
111
+
112
+ test("tools.Bash reads single- and double-quoted command keys", () => {
113
+ for (const key of ['"command"', "'command'"]) {
114
+ assert.deepEqual(replCommands(`tools.Bash({ ${key}: "git commit --no-verify" })`),
115
+ ["git commit --no-verify"]);
116
+ }
117
+ });
118
+
119
+ test("tools.Bash returns every literal value of duplicate command keys", () => {
120
+ assert.deepEqual(replCommands('tools.Bash({ command: "git status", command: "git commit --no-verify" })'),
121
+ ["git status", "git commit --no-verify"]);
122
+ assert.deepEqual(replCommands('tools.Bash({ command: getCommand(), "command": "git status", nested: { command: "fake" }, \'command\': "git commit --no-verify" })'),
123
+ ["git status", "git commit --no-verify"]);
124
+ });
125
+
126
+ test("an incomplete form contributes no command", () => {
127
+ for (const code of ['$`unterminated', '$`echo ${value`', '$("unterminated)',
128
+ 'tools.Bash({ command: "unterminated })', '$("bad\\xZZ")']) {
129
+ assert.deepEqual(replCommands(code), [], code);
130
+ }
131
+ assert.deepEqual(replCommands('$`git status`; $`unterminated'), ["git status"]);
132
+ assert.deepEqual(replCommands(null), []);
133
+ });
@@ -0,0 +1,49 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ export const ROLES = Object.freeze(["Leader", "Coder", "Reviewer"]);
4
+ const roles = ROLES.map((role) => role.toLowerCase());
5
+ const token = /^[a-zA-Z0-9_-]+$/;
6
+ const reference = /^#[1-9]\d*$/;
7
+ const signature = (secret, { role, node, kind, ref }, body) => createHmac("sha256", secret)
8
+ .update(`qc:v1|${role}|${node}|${kind}|${ref}|${body}`).digest("hex");
9
+
10
+ /** Format a public role heading and a private, optionally authenticated marker. */
11
+ export function roleComment({ role, node, kind, ref, summary, body }, { secret } = {}) {
12
+ if (!roles.includes(role) || !token.test(kind ?? "") || !reference.test(ref ?? "")
13
+ || typeof summary !== "string" || /[\r\n]|-->/.test(summary)
14
+ || typeof body !== "string" || /^<!-- qc:v1\b/m.test(body)
15
+ || (secret && !token.test(node ?? ""))) throw new Error("Invalid role comment");
16
+ const fields = { role, node, kind, ref };
17
+ const auth = secret ? ` n=${node}` : "";
18
+ const sig = secret ? ` sig=${signature(secret, fields, body)}` : "";
19
+ return `**${ROLES[roles.indexOf(role)]}** · ${summary}\n\n${body}\n\n<!-- qc:v1 role=${role}${auth} kind=${kind} ref=${ref}${sig} -->`;
20
+ }
21
+
22
+ /** Read only a final marker from our own author; authenticate fleet comments. */
23
+ export function parseMarker(text, { secret, nodes = [], ownAuthor } = {}) {
24
+ const refuse = (reason) => ({ refused: reason });
25
+ if (ownAuthor !== true) return refuse("not-own-author");
26
+ const trimmed = typeof text === "string" ? text.trimEnd() : "";
27
+ const marker = trimmed.slice(trimmed.lastIndexOf("\n") + 1);
28
+ if (!marker.startsWith("<!-- qc:v1")) return refuse("missing-marker");
29
+ const match = /^<!-- qc:v1 role=(leader|coder|reviewer)(?: n=([\w-]+))? kind=([\w-]+) ref=(#[1-9]\d*)(?: sig=([a-fA-F0-9]*))? -->$/.exec(marker);
30
+ if (!match) return refuse("invalid-marker");
31
+ const [, role, node, kind, ref, sig] = match;
32
+ if (!node && sig === undefined) {
33
+ return secret ? refuse("signature-required") : { role, kind, ref };
34
+ }
35
+ if (!node || sig === undefined) return refuse("invalid-marker");
36
+ if (!secret) return refuse("secret-required");
37
+ if (!nodes.includes(node)) return refuse("unknown-node");
38
+ const prefix = trimmed.slice(0, -marker.length);
39
+ const heading = `**${ROLES[roles.indexOf(role)]}** · `;
40
+ const split = prefix.indexOf("\n\n");
41
+ if (!prefix.startsWith(heading) || split < 0 || !prefix.endsWith("\n\n")
42
+ || /[\r\n]|-->/.test(prefix.slice(heading.length, split))) return refuse("invalid-marker");
43
+ const body = prefix.slice(split + 2, -2);
44
+ if (/^<!-- qc:v1\b/m.test(body)) return refuse("invalid-marker");
45
+ const expected = Buffer.from(signature(secret, { role, node, kind, ref }, body), "hex");
46
+ const actual = Buffer.from(sig, "hex");
47
+ if (sig.length !== 64 || actual.length !== expected.length || !timingSafeEqual(actual, expected)) return refuse("invalid-signature");
48
+ return { role, node, kind, ref, sig };
49
+ }
@@ -0,0 +1,55 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createHmac } from "node:crypto";
4
+ import { ROLES, roleComment, parseMarker } from "./role-line.mjs";
5
+
6
+ const fields = { role: "coder", node: "desk-1", kind: "question", ref: "#239", summary: "Question", body: "Which option?\nKeep the data?" };
7
+ const secret = "shared secret";
8
+ const options = { secret, nodes: ["desk-1"], ownAuthor: true };
9
+ const signed = () => roleComment(fields, { secret });
10
+
11
+ test("signed comments show a role and authenticate the exact body", () => {
12
+ assert.deepEqual(ROLES, ["Leader", "Coder", "Reviewer"]);
13
+ const sig = createHmac("sha256", secret).update(`qc:v1|coder|desk-1|question|#239|${fields.body}`).digest("hex");
14
+ assert.equal(signed(), `**Coder** · Question\n\n${fields.body}\n\n<!-- qc:v1 role=coder n=desk-1 kind=question ref=#239 sig=${sig} -->`);
15
+ assert.deepEqual(parseMarker(signed(), options), { role: "coder", node: "desk-1", kind: "question", ref: "#239", sig });
16
+ });
17
+
18
+ test("one PC writes a role and unsigned marker without the node", () => {
19
+ const comment = roleComment(fields);
20
+ assert.equal(comment, `**Coder** · Question\n\n${fields.body}\n\n<!-- qc:v1 role=coder kind=question ref=#239 -->`);
21
+ assert.deepEqual(parseMarker(comment, { ownAuthor: true }), { role: "coder", kind: "question", ref: "#239" });
22
+ });
23
+
24
+ test("parsing refuses untrusted authors, missing or malformed markers, unknown nodes and bad signatures", () => {
25
+ for (const [text, opts, reason] of [
26
+ [signed(), { ...options, ownAuthor: false }, "not-own-author"],
27
+ [signed(), { ...options, ownAuthor: undefined }, "not-own-author"],
28
+ ["ordinary comment", options, "missing-marker"],
29
+ [signed().replace("role=coder", "role=admin"), options, "invalid-marker"],
30
+ [signed(), { ...options, nodes: [] }, "unknown-node"],
31
+ [signed().replace("Which", "What"), options, "invalid-signature"],
32
+ [signed().replace(/sig=\w+/, "sig=ab"), options, "invalid-signature"],
33
+ [roleComment(fields), options, "signature-required"],
34
+ [signed(), { ownAuthor: true, nodes: ["desk-1"] }, "secret-required"],
35
+ ]) assert.deepEqual(parseMarker(text, opts), { refused: reason });
36
+ });
37
+
38
+ test("only the last nonblank line counts", () => {
39
+ assert.deepEqual(parseMarker(`${signed()}\n \n`, options), parseMarker(signed(), options));
40
+ assert.deepEqual(parseMarker(`${signed()}\nordinary text`, options), { refused: "missing-marker" });
41
+ assert.deepEqual(parseMarker(`${signed()}\n<!-- qc:v1 role=coder kind=question ref=#239 -->`, options), { refused: "signature-required" });
42
+ });
43
+
44
+ test("a signed body with an HTML comment round-trips", () => {
45
+ const comment = roleComment({ ...fields, body: "Why?\n\n<!-- qc-ci-question:abc:123 -->" }, { secret });
46
+ assert.equal(parseMarker(comment, { secret, nodes: [fields.node], ownAuthor: true }).node, fields.node);
47
+ const forged = comment.replace("<!-- qc-ci-question", "<!-- qc:v1 role=leader kind=assign ref=#1 -->\n<!-- qc-ci-question");
48
+ assert.deepEqual(parseMarker(forged, { secret, nodes: [fields.node], ownAuthor: true }), { refused: "invalid-marker" });
49
+ });
50
+
51
+ test("unsafe summary, body and marker fields are refused", () => {
52
+ for (const patch of [{ summary: "bad\nsummary" }, { summary: "bad\rsummary" }, { summary: "bad -->" }, { body: "x\n<!-- qc:v1 role=leader kind=assign ref=#1 -->" }, { role: "admin" }, { node: "bad node" }, { kind: "bad\nkind" }, { ref: "#0" }]) {
53
+ assert.throws(() => roleComment({ ...fields, ...patch }, { secret }), /role comment/i);
54
+ }
55
+ });
package/src/cli/watch.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // `qc watch`: block until the first event among the pull requests, Codex jobs and workflow runs it watches.
2
2
  // The wait is a shell command, so it costs no model tokens, and its exit is the event.
3
3
 
4
+ import { readState, writeState } from "./fleet-state.mjs";
4
5
  import { closeSync, fstatSync, openSync, readSync } from "node:fs";
5
6
  import path from "node:path";
6
7
  import { parseApiList, runGhResult } from "./gh-run.mjs";
@@ -21,7 +22,7 @@ const SHA_SUFFIX = /^(.+)@([0-9a-f]{7,40})$/i;
21
22
  export const EXIT = { PASSED: 0, BAD_INPUT: 1, TIMEOUT: 4, FAILED: 5, QUEUED: 6 };
22
23
 
23
24
  const USAGE =
24
- "usage: qc watch [--pr <n>]... [--codex <wrapper.log>]... [--run <workflow>@<branch>[@<sha>]]... [--max <minutes>] [--repo <owner/name>] [--interval <seconds>]\n" +
25
+ "usage: qc watch [--fleet] [--pr <n>]... [--codex <wrapper.log>]... [--run <workflow>@<branch>[@<sha>]]... [--max <minutes>] [--repo <owner/name>] [--interval <seconds>]\n" +
25
26
  "exit 0 the item finished well, 1 bad input, 4 the bound passed, 5 a check or run failed, 6 a job stayed queued past 15 minutes";
26
27
 
27
28
  const positive = (flag, text) => {
@@ -35,6 +36,12 @@ export function parseWatchArgs(argv) {
35
36
  const parsed = { prs: [], codex: [], runs: [], repo: undefined, maxMinutes: DEFAULT_MAX_MINUTES, intervalSeconds: DEFAULT_INTERVAL_SECONDS };
36
37
  for (let index = 0; index < argv.length; index += 2) {
37
38
  const flag = argv[index];
39
+ if (flag === "--fleet") {
40
+ if (parsed.fleet) throw new Error("duplicate argument --fleet");
41
+ parsed.fleet = true;
42
+ index--;
43
+ continue;
44
+ }
38
45
  const value = argv[index + 1];
39
46
  if (!["--pr", "--codex", "--run", "--max", "--repo", "--interval"].includes(flag)) throw new Error(`unknown argument ${flag}`);
40
47
  if (value === undefined) throw new Error(`${flag} needs a value`);
@@ -50,7 +57,8 @@ export function parseWatchArgs(argv) {
50
57
  else if (flag === "--interval") parsed.intervalSeconds = positive(flag, value);
51
58
  else parsed.repo = value;
52
59
  }
53
- if (parsed.prs.length + parsed.codex.length + parsed.runs.length === 0) throw new Error("name at least one item: --pr, --codex or --run");
60
+ if (!parsed.fleet && parsed.prs.length + parsed.codex.length + parsed.runs.length === 0) throw new Error("name at least one item: --pr, --codex or --run");
61
+ if (parsed.fleet) parsed.intervalSeconds = 5;
54
62
  return parsed;
55
63
  }
56
64
 
@@ -216,6 +224,31 @@ export async function runWatch(argv, { gh = readGh, say = console.log, warn = co
216
224
  ];
217
225
  const deadline = started + parsed.maxMinutes * 60_000;
218
226
  for (;;) {
227
+ if (parsed.fleet) {
228
+ try {
229
+ const watched = readState(cwd, "watched");
230
+ const messages = readState(cwd, "node").leader === true
231
+ ? readState(cwd, "queue").filter(message => ["plan", "question"].includes(message.kind))
232
+ : readState(cwd, "inbox");
233
+ const proposal = readState(cwd, "proposal");
234
+ if (Number.isSafeInteger(proposal.term) && proposal.term > 0) {
235
+ messages.push({ id: `propose-leader:${proposal.term}`, kind: "propose-leader", term: proposal.term });
236
+ }
237
+ const fresh = messages.filter(message => !Object.hasOwn(watched, message.id));
238
+ if (fresh.length) {
239
+ for (const message of fresh) {
240
+ if (Object.hasOwn(watched, message.id)) continue;
241
+ Object.defineProperty(watched, message.id, { value: true, enumerable: true, configurable: true });
242
+ say(`EVENT fleet:${message.kind} ${message.term ?? message.id}`);
243
+ }
244
+ writeState(cwd, "watched", watched);
245
+ return EXIT.PASSED;
246
+ }
247
+ } catch (error) {
248
+ warn(`watch: ${error.message}`);
249
+ return EXIT.BAD_INPUT;
250
+ }
251
+ }
219
252
  for (const { item, poll, target } of watchers) {
220
253
  const event = poll();
221
254
  if (event) {
@@ -450,3 +450,109 @@ test("watch logs only final CI events with head, target, result and elapsed minu
450
450
  assert.equal((await watch(["--codex", wrapper], { cwd: dir })).code, 0);
451
451
  assert.equal(readFileSync(file, "utf8").trim().split("\n").length, 2);
452
452
  });
453
+
454
+ test("fleet watch polls every five seconds, reports Leader requests once, and persists IDs", async t => {
455
+ const { readState, writeState } = await import("./fleet-state.mjs");
456
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-fleet-"));
457
+ mkdirSync(path.join(root, ".git"));
458
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
459
+ writeState(root, "node", { leader: true });
460
+ writeState(root, "queue", [{ id: "p", kind: "plan" }, { id: "q", kind: "question" }, { id: "x", kind: "pushed" }]);
461
+ const lines = [], sleeps = [];
462
+ const deps = { cwd: root, say: line => lines.push(line), gh: () => { throw new Error("unexpected gh"); },
463
+ sleep: async ms => { sleeps.push(ms); writeState(root, "queue", [{ id: "p", kind: "plan" }, { id: "fresh", kind: "question" }]); } };
464
+ assert.equal(await runWatch(["--fleet"], deps), 0);
465
+ assert.deepEqual(lines, ["EVENT fleet:plan p", "EVENT fleet:question q"]);
466
+ assert.deepEqual(Object.keys(readState(root, "watched")).sort(), ["p", "q"]);
467
+ lines.length = 0;
468
+ assert.equal(await runWatch(["--fleet"], deps), 0);
469
+ assert.deepEqual(sleeps, [5000]);
470
+ assert.deepEqual(lines, ["EVENT fleet:question fresh"]);
471
+ });
472
+
473
+ test("follower fleet watch reports inbox approvals and answers, ignoring the request queue", async t => {
474
+ const { writeState } = await import("./fleet-state.mjs");
475
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-follower-"));
476
+ mkdirSync(path.join(root, ".git"));
477
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
478
+ writeState(root, "queue", [{ id: "ignored", kind: "plan" }]);
479
+ writeState(root, "plans", { "o/r#7": { id: "approval", kind: "approve" } });
480
+ writeState(root, "answers", { q1: { id: "answer", kind: "answer" } });
481
+ writeState(root, "inbox", [{ id: "approval", kind: "approve" }, { id: "answer", kind: "answer" }]);
482
+ const lines = [];
483
+ assert.equal(await runWatch(["--fleet"], { cwd: root, say: line => lines.push(line) }), 0);
484
+ assert.deepEqual(lines, ["EVENT fleet:approve approval", "EVENT fleet:answer answer"]);
485
+ });
486
+
487
+ test("regression: follower watch keeps two approvals and answers accepted between polls", async t => {
488
+ const { readState, writeState } = await import("./fleet-state.mjs");
489
+ const { receiveTalk } = await import("./fleet-talk.mjs");
490
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-inbox-"));
491
+ mkdirSync(path.join(root, ".git"));
492
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
493
+ writeState(root, "peers", { b: { leader: true } });
494
+ writeState(root, "assignments", { "o/r#7": { node: "a", epoch: 3 } });
495
+ const time = new Date().toISOString(), fleet = { self: "a" }, events = [];
496
+ for (const id of ["first", "second"]) {
497
+ const messages = [
498
+ { id: `approve-${id}`, kind: "approve", body: { issue: 7, epoch: 3, plan: "p", approved: id === "second", note: "Review" } },
499
+ { id: `answer-${id}`, kind: "answer", body: { issue: 7, epoch: 3, question: "q", text: id } },
500
+ ].map(message => ({ ...message, repo: "o/r", from: "b", time }));
501
+ writeState(root, "queue", messages);
502
+ receiveTalk(root, fleet, false, Date.parse(time));
503
+ events.push(...messages.map(({ id, kind, repo, body: { issue }, time }) => ({ id, kind, repo, issue, time })));
504
+ }
505
+ const lines = [];
506
+ const deps = { cwd: root, say: line => lines.push(line) };
507
+ assert.equal(await runWatch(["--fleet"], deps), 0);
508
+ assert.deepEqual(lines, events.map(({ id, kind }) => `EVENT fleet:${kind} ${id}`));
509
+ assert.deepEqual(readState(root, "inbox"), events);
510
+ assert.equal(readState(root, "plans")["o/r#7"].id, "approve-second");
511
+ assert.equal(readState(root, "answers").q.id, "answer-second");
512
+ writeState(root, "inbox", [...events, { id: "fresh", kind: "approve", repo: "o/r", issue: 7, time }]);
513
+ lines.length = 0;
514
+ assert.equal(await runWatch(["--fleet"], deps), 0);
515
+ assert.deepEqual(lines, ["EVENT fleet:approve fresh"]);
516
+ writeState(root, "inbox", Array.from({ length: 200 }, (_, i) => ({ ...events[0], id: `old-${i}` })));
517
+ writeState(root, "queue", [{ ...readState(root, "plans")["o/r#7"], id: "newest" }]);
518
+ receiveTalk(root, fleet, false, Date.parse(time));
519
+ const inbox = readState(root, "inbox");
520
+ assert.equal(inbox.length, 201);
521
+ assert.equal(inbox[0].id, "old-0");
522
+ assert.equal(inbox.at(-1).id, "newest");
523
+ lines.length = 0;
524
+ assert.equal(await runWatch(["--fleet"], deps), 0);
525
+ assert.deepEqual(lines, [...Array.from({ length: 200 }, (_, i) => `EVENT fleet:approve old-${i}`), "EVENT fleet:approve newest"]);
526
+ lines.length = 0;
527
+ const clock = fakeClock();
528
+ assert.equal(await runWatch(["--fleet", "--max", "1"], { ...deps, ...clock }), 4);
529
+ assert.deepEqual(lines, ["EVENT timeout"]);
530
+
531
+ // Interleave an unprinted entry with printed entries to verify pruning uses IDs.
532
+ const unprinted = { ...events[0], id: "unprinted" };
533
+ writeState(root, "inbox", [inbox[0], unprinted, ...inbox.slice(1)]);
534
+ writeState(root, "queue", [{ ...readState(root, "plans")["o/r#7"], id: "next" }]);
535
+ receiveTalk(root, fleet, false, Date.parse(time));
536
+ assert.deepEqual(readState(root, "inbox").map(({ id }) => id), ["unprinted", ...inbox.slice(1).map(({ id }) => id), "next"]);
537
+ lines.length = 0;
538
+ assert.equal(await runWatch(["--fleet"], deps), 0);
539
+ assert.deepEqual(lines, ["EVENT fleet:approve unprinted", "EVENT fleet:approve next"]);
540
+
541
+ // A later reply drops the two oldest of the now 202 printed entries.
542
+ writeState(root, "queue", [{ ...readState(root, "plans")["o/r#7"], id: "last" }]);
543
+ receiveTalk(root, fleet, false, Date.parse(time));
544
+ assert.deepEqual(readState(root, "inbox").map(({ id }) => id), [...inbox.slice(2).map(({ id }) => id), "next", "last"]);
545
+ });
546
+
547
+ test("fleet watch announces each proposed Leader term once", async t => {
548
+ const { writeState } = await import("./fleet-state.mjs");
549
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-election-")), lines = [];
550
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
551
+ mkdirSync(path.join(root, ".git"));
552
+ writeState(root, "proposal", { id: "b", term: 2 });
553
+ assert.equal(await runWatch(["--fleet"], { cwd: root, say: text => lines.push(text), sleep: async () => { throw new Error("proposal event missing"); } }), 0);
554
+ assert.deepEqual(lines, ["EVENT fleet:propose-leader 2"]);
555
+ writeState(root, "proposal", { id: "b", term: 3 });
556
+ assert.equal(await runWatch(["--fleet"], { cwd: root, say: text => lines.push(text), sleep: async () => { throw new Error("proposal event missing"); } }), 0);
557
+ assert.deepEqual(lines, ["EVENT fleet:propose-leader 2", "EVENT fleet:propose-leader 3"]);
558
+ });
@@ -17,7 +17,7 @@ const matchersOf = (event, script) =>
17
17
  test("hooks.json runs each workflow check on its events", () => {
18
18
  assert.deepEqual(matchersOf("PreToolUse", "controller-guard.mjs"), ["Write|Edit|MultiEdit|NotebookEdit"]);
19
19
  for (const event of ["PreToolUse", "PostToolUse", "PostToolUseFailure"]) {
20
- assert.deepEqual(matchersOf(event, "merge-guard.mjs"), ["Bash|PowerShell"], event);
20
+ assert.deepEqual(matchersOf(event, "merge-guard.mjs"), [event === "PreToolUse" ? "Bash|PowerShell|REPL" : "Bash|PowerShell"], event);
21
21
  }
22
22
  for (const script of ["report-stop.mjs", "plan-stop.mjs"]) {
23
23
  assert.deepEqual(matchersOf("PreToolUse", script), ["SubagentHandback"], script);
@@ -51,7 +51,7 @@ test("every hook script in src/cli is registered, in hooks.json or in a shell ho
51
51
 
52
52
  test("workflow scripts stay silent without swarm.dispatch, and the merge guard denies an unreadable base", (t) => {
53
53
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-workflow-hooks-")));
54
- t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }));
54
+ t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
55
55
  execFileSync("git", ["init", "-q"], { cwd: base, stdio: "pipe" });
56
56
  writeFileSync(path.join(base, "qc.config.json"), JSON.stringify({ swarm: {}, commentWatch: false }));
57
57
  const events = {
@@ -95,7 +95,7 @@ test("hooks.json runs the skill guard on the Skill tool, and gives the dispatch
95
95
 
96
96
  test("the skill guard is silent without swarm.dispatch, and denies a code-review skill with it", (t) => {
97
97
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-skill-hooks-")));
98
- t.after(() => rmSync(base, { recursive: true, force: true }));
98
+ t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
99
99
  execFileSync("git", ["init", "-q"], { cwd: base, stdio: "pipe" });
100
100
  const run = (config) => {
101
101
  writeFileSync(path.join(base, "qc.config.json"), JSON.stringify(config));
@@ -109,7 +109,7 @@ test("the skill guard is silent without swarm.dispatch, and denies a code-review
109
109
  test("cost-stop.mjs runs on every SubagentStop, and is silent in a checkout without swarm.dispatch", (t) => {
110
110
  assert.deepEqual(matchersOf("SubagentStop", "cost-stop.mjs"), [undefined]);
111
111
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-cost-hooks-")));
112
- t.after(() => rmSync(base, { recursive: true, force: true }));
112
+ t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
113
113
  execFileSync("git", ["init", "-q"], { cwd: base, stdio: "pipe" });
114
114
  writeFileSync(path.join(base, "qc.config.json"), JSON.stringify({ swarm: {} }));
115
115
  const transcript = path.join(base, "agent.jsonl");
@@ -123,3 +123,12 @@ test("cost-stop.mjs runs on every SubagentStop, and is silent in a checkout with
123
123
  assert.equal(result.stdout, "");
124
124
  assert.equal(existsSync(path.join(base, ".git", "qc", "ledger.jsonl")), false);
125
125
  });
126
+
127
+
128
+ test("only the command and merge PreToolUse guards add REPL to their matchers", () => {
129
+ assert.deepEqual(matchersOf("PreToolUse", "bash-command-guard.mjs"), ["Bash|PowerShell|REPL"]);
130
+ const replHooks = Object.entries(hooks).flatMap(([event, entries]) => entries
131
+ .filter((entry) => entry.matcher?.split("|").includes("REPL"))
132
+ .flatMap((entry) => entry.hooks.map((hook) => [event, /src\/cli\/([a-z-]+\.mjs)/.exec(hook.command)?.[1]])));
133
+ assert.deepEqual(replHooks, [["PreToolUse", "bash-command-guard.mjs"], ["PreToolUse", "merge-guard.mjs"]]);
134
+ });
package/src/config.mjs CHANGED
@@ -797,8 +797,8 @@ export function load(root = process.cwd()) {
797
797
  }
798
798
  if (typeof review !== "boolean") throw new TypeError("integrate.review must be a boolean");
799
799
  if (!isPlainObject(config.ready) || !Array.isArray(config.ready.platforms) || config.ready.platforms.length === 0 ||
800
- config.ready.platforms.some((os) => !["linux", "windows"].includes(os)) || new Set(config.ready.platforms).size !== config.ready.platforms.length) {
801
- throw new TypeError("ready.platforms must be a non-empty array of distinct linux and windows platforms");
800
+ config.ready.platforms.some((os) => !["linux", "windows", "darwin"].includes(os)) || new Set(config.ready.platforms).size !== config.ready.platforms.length) {
801
+ throw new TypeError("ready.platforms must be a non-empty array of distinct linux, windows and darwin platforms");
802
802
  }
803
803
  if (!isPlainObject(config.check)) throw new TypeError("check must be an object");
804
804
  const { related, sincePush, e2e, commands, base } = config.check;