architecture-harness 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/package.json +1 -1
  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/codex-implement.mjs +5 -4
  10. package/src/cli/codex-implement.test.mjs +93 -0
  11. package/src/cli/commit-msg.mjs +4 -0
  12. package/src/cli/commit-msg.test.mjs +10 -0
  13. package/src/cli/fleet-assign.mjs +46 -0
  14. package/src/cli/fleet-assign.test.mjs +114 -0
  15. package/src/cli/fleet-github.mjs +124 -0
  16. package/src/cli/fleet-github.test.mjs +243 -0
  17. package/src/cli/fleet-message.mjs +50 -0
  18. package/src/cli/fleet-message.test.mjs +72 -0
  19. package/src/cli/fleet-node.mjs +555 -0
  20. package/src/cli/fleet-node.test.mjs +1282 -0
  21. package/src/cli/fleet-platform.mjs +200 -0
  22. package/src/cli/fleet-platform.test.mjs +316 -0
  23. package/src/cli/fleet-state.mjs +75 -0
  24. package/src/cli/fleet-state.test.mjs +114 -0
  25. package/src/cli/fleet-talk.mjs +143 -0
  26. package/src/cli/fleet-talk.test.mjs +178 -0
  27. package/src/cli/fleet.mjs +142 -13
  28. package/src/cli/fleet.test.mjs +314 -11
  29. package/src/cli/legs.mjs +3 -3
  30. package/src/cli/legs.test.mjs +24 -1
  31. package/src/cli/merge-guard.mjs +8 -6
  32. package/src/cli/merge-guard.test.mjs +38 -0
  33. package/src/cli/platform-risk.mjs +95 -1
  34. package/src/cli/platform-risk.test.mjs +185 -0
  35. package/src/cli/qc.mjs +6 -0
  36. package/src/cli/repl-commands.mjs +168 -0
  37. package/src/cli/repl-commands.test.mjs +133 -0
  38. package/src/cli/role-line.mjs +49 -0
  39. package/src/cli/role-line.test.mjs +55 -0
  40. package/src/cli/watch.mjs +35 -2
  41. package/src/cli/watch.test.mjs +106 -0
  42. package/src/cli/workflow-hooks.test.mjs +13 -4
  43. package/src/config.mjs +2 -2
@@ -0,0 +1,124 @@
1
+ import { createMessage, verifyMessage } from "./fleet-message.mjs";
2
+ import { parseMarker, roleComment } from "./role-line.mjs";
3
+ import { parsePages, runGh } from "./gh-run.mjs";
4
+ import { highestTerm, validTerm, pruneSeen, readState, writeState } from "./fleet-state.mjs";
5
+
6
+ const assignmentRef = row => row && typeof row.repo === "string" && /^[a-z0-9][a-z0-9-]*\/[a-z0-9_.-]+$/i.test(row.repo) &&
7
+ Number.isSafeInteger(row.issue) && row.issue > 0 && Number.isSafeInteger(row.epoch) && row.epoch > 0;
8
+ export const validBranch = value => value === undefined || value === null || (typeof value === "string" && value.length > 0 && !/[\s\x00-\x1f\x7f]/.test(value));
9
+ export const validHead = value => value === undefined || value === null || (typeof value === "string" && /^[0-9a-f]{40}$/i.test(value));
10
+ export const validWork = row => assignmentRef(row) && [null, "plan", "code", "review", "merge"].includes(row.step) && validBranch(row.branch) && validHead(row.head);
11
+ const validHeartbeat = body => validTerm(body.term) && typeof body.leader === "boolean" && (body.kit === null || typeof body.kit === "string") &&
12
+ (body.work === undefined || (Array.isArray(body.work) && body.work.every(validWork))) &&
13
+ (body.assigned === undefined || (Array.isArray(body.assigned) && body.assigned.every(assignmentRef)));
14
+
15
+ const WORK_KINDS = new Set(["assign", "plan", "approve", "question", "answer", "pushed", "verdict", "platform-check", "platform-result"]);
16
+ const isWork = message => WORK_KINDS.has(message?.kind) && Number.isSafeInteger(message.body?.issue) && message.body.issue > 0;
17
+
18
+ /** HTTP and GitHub share verification and synchronous replay/queue persistence. */
19
+ export function receiveMessage({ root, fleet, message, clock = Date.now }) {
20
+ const time = clock();
21
+ const seen = pruneSeen(readState(root, "seen"), time);
22
+ const result = verifyMessage(message, { secret: fleet.secret, nodes: fleet.nodes, seen, now: time });
23
+ if (!result.ok) return result;
24
+ if (message.kind === "heartbeat" && !validHeartbeat(message.body)) {
25
+ return { ok: false, reason: "bad-heartbeat" };
26
+ }
27
+ // No await between verification and persistence: requests cannot race the saved IDs.
28
+ if (message.kind !== "heartbeat") writeState(root, "queue", [...readState(root, "queue"), message]);
29
+ writeState(root, "seen", seen);
30
+ if (message.kind === "heartbeat") {
31
+ const election = readState(root, "election"), node = readState(root, "node");
32
+ const highest = Math.max(highestTerm(root), message.body.term);
33
+ const accepted = message.body.leader && message.body.term >= highest;
34
+ election.highest = highest;
35
+ if (message.body.term > (node.term ?? 1)) writeState(root, "node", { ...node, leader: false, term: highest });
36
+ if (accepted) {
37
+ election.lastLeaderAt = time;
38
+ if (readState(root, "proposal").term <= message.body.term) writeState(root, "proposal", {});
39
+ }
40
+ writeState(root, "election", election);
41
+ const peers = readState(root, "peers");
42
+ const previous = peers[message.from];
43
+ if (message.body.term < (previous?.term ?? 1) || (message.body.term === (previous?.term ?? 1) &&
44
+ Date.parse(message.time) <= Date.parse(previous?.messageTime))) {
45
+ peers[message.from].time = time;
46
+ } else Object.defineProperty(peers, message.from, { value: { time, messageTime: message.time, kit: message.body.kit, term: message.body.term, leader: accepted,
47
+ ...(message.body.os === undefined ? {} : { os: message.body.os }),
48
+ ...(message.body.work === undefined ? {} : { work: message.body.work }),
49
+ ...(message.body.assigned === undefined ? {} : { assigned: message.body.assigned }) }, enumerable: true, configurable: true, writable: true });
50
+ for (const peer of Object.values(peers)) if ((peer.term ?? 1) < highest) peer.leader = false;
51
+ writeState(root, "peers", peers);
52
+ }
53
+ return { ok: true };
54
+ }
55
+
56
+ /** Work alone can bypass HTTP backoff when retries or missing heartbeats warrant it. */
57
+ export function githubFallback({ root, entry, now }) {
58
+ if (!isWork(entry.message)) return false;
59
+ const last = readState(root, "peers")[entry.node]?.time;
60
+ return entry.attempts >= 3 || !Number.isFinite(last) || now - last >= 90_000;
61
+ }
62
+
63
+ /** A failed comment leaves the original entry available on the next node tick. */
64
+ export function postGithubMessage({ root, fleet, entry, leader = false, clock = Date.now, gh = runGh, signal }) {
65
+ if (signal?.aborted) return false;
66
+ try {
67
+ const message = createMessage({ ...entry.message, from: fleet.self, time: new Date(clock()).toISOString() }, fleet.secret);
68
+ const issue = message.body.issue;
69
+ const body = roleComment({ role: leader ? "leader" : "coder", node: fleet.self, kind: message.kind, ref: `#${issue}`,
70
+ summary: `${message.kind} for #${issue}`,
71
+ body: `<!-- qc:msg to=${entry.node} ${Buffer.from(JSON.stringify(message)).toString("base64url")} -->` }, { secret: fleet.secret });
72
+ return typeof gh(["issue", "comment", String(issue), "--repo", message.repo, "--body", body], { cwd: root }) === "string";
73
+ } catch { return false; }
74
+ }
75
+
76
+ function commentMessage(comment, { fleet, login, repo }) {
77
+ const source = /^https:\/\/api\.github\.com\/repos\/([^/]+\/[^/]+)\/issues\/([1-9]\d*)$/.exec(comment?.issue_url);
78
+ const issue = Number(source?.[2]);
79
+ if (source?.[1].toLowerCase() !== repo.toLowerCase() || !Number.isSafeInteger(issue)) return null;
80
+ const marker = parseMarker(comment?.body, { secret: fleet.secret, nodes: fleet.nodes.map(node => node.id), ownAuthor: comment?.user?.login === login });
81
+ if (marker.refused) return null;
82
+ const lines = comment.body.split("\n").filter(line => line.startsWith("<!-- qc:msg"));
83
+ if (lines.length !== 1) return null;
84
+ const match = /^<!-- qc:msg to=([\w-]+) ([\w-]+) -->$/.exec(lines[0]);
85
+ if (!match || match[1] !== fleet.self) return null;
86
+ try {
87
+ const bytes = Buffer.from(match[2], "base64url");
88
+ if (bytes.length > 64 * 1024 || bytes.toString("base64url") !== match[2]) return null;
89
+ const message = JSON.parse(bytes.toString("utf8"));
90
+ if (!isWork(message) || message.from !== marker.node || message.kind !== marker.kind || marker.ref !== `#${issue}`
91
+ || message.repo?.toLowerCase() !== repo.toLowerCase() || message.body.issue !== issue) return null;
92
+ return message;
93
+ } catch { return null; }
94
+ }
95
+
96
+ /** Discover work across repositories using GitHub timestamps and a replay-safe overlap. */
97
+ export function readGithub({ root, fleet, repo, clock = Date.now, gh = runGh }) {
98
+ const repos = new Set([repo, ...Object.values(readState(root, "assignments")).map(row => row.repo)].filter(Boolean).map(repo => repo.toLowerCase()));
99
+ if (!repos.size) return;
100
+ let login;
101
+ try { login = JSON.parse(gh(["api", "user"], { cwd: root }))?.login; }
102
+ catch { return; }
103
+ if (typeof login !== "string" || !login) return;
104
+ const state = readState(root, "github");
105
+ const cursors = { ...state.cursors };
106
+ for (const repo of repos) {
107
+ try {
108
+ const since = cursors[repo] ?? new Date(clock() - 600_000).toISOString();
109
+ const pages = parsePages(gh(["api", "--paginate", `repos/${repo}/issues/comments?per_page=100&since=${since}`], { cwd: root }));
110
+ if (!pages?.length || !pages.every(Array.isArray)) continue;
111
+ let newest = -Infinity;
112
+ for (const comment of pages.flat()) {
113
+ const updated = Date.parse(comment?.updated_at);
114
+ if (Number.isFinite(updated)) newest = Math.max(newest, updated);
115
+ const message = commentMessage(comment, { fleet, login, repo });
116
+ if (message) receiveMessage({ root, fleet, message, clock });
117
+ }
118
+ if (Number.isFinite(newest)) {
119
+ Object.defineProperty(cursors, repo, { value: new Date(newest - 60_000).toISOString(), enumerable: true, configurable: true, writable: true });
120
+ writeState(root, "github", { ...state, cursors });
121
+ }
122
+ } catch { /* A gh/read failure keeps this repository's cursor for the next poll. */ }
123
+ }
124
+ }
@@ -0,0 +1,243 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { createMessage, verifyMessage } from "./fleet-message.mjs";
7
+ import { roleComment, parseMarker } from "./role-line.mjs";
8
+ import { readState, writeState } from "./fleet-state.mjs";
9
+ import { flushOutbox, receiveMessage, createNodeServer } from "./fleet-node.mjs";
10
+ import { readGithub } from "./fleet-github.mjs";
11
+
12
+ const now = Date.parse("2026-11-24T00:00:00Z");
13
+ const secret = "ab".repeat(32);
14
+ const kinds = ["assign", "plan", "approve", "question", "answer", "pushed", "verdict", "platform-check", "platform-result"];
15
+ const fleet = { self: "a", secret, nodes: [{ id: "a", address: "127.0.0.1" }, { id: "b", address: "127.0.0.1" }] };
16
+ function fixture(t) {
17
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-github-"));
18
+ mkdirSync(path.join(root, ".git"));
19
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
20
+ writeState(root, "peers", { b: { time: now } });
21
+ return root;
22
+ }
23
+ const message = (patch = {}) => createMessage({ from: "b", repo: "o/r", kind: "question", body: { issue: 7, text: "private payload" }, time: new Date(now).toISOString(), ...patch }, secret);
24
+ const entry = (patch = {}) => ({ node: "b", message: message({ from: "a", time: new Date(now - 600_000).toISOString() }), attempts: 3, nextAttempt: now + 60_000, ...patch });
25
+ function comment(msg = message(), { to = "a", author = "me", marker = {}, body } = {}) {
26
+ return { user: { login: author }, issue_url: `https://api.github.com/repos/${msg.repo}/issues/${msg.body.issue}`,
27
+ updated_at: new Date(now).toISOString(), body: body ?? roleComment({ role: "coder", node: msg.from, kind: msg.kind, ref: `#${msg.body.issue}`, summary: `${msg.kind} for #${msg.body.issue}`,
28
+ body: `<!-- qc:msg to=${to} ${Buffer.from(JSON.stringify(msg)).toString("base64url")} -->`, ...marker }, { secret }) };
29
+ }
30
+ const fakeReader = (comments, calls = []) => args => {
31
+ calls.push(args);
32
+ if (args[0] === "api" && args[1] === "user") return JSON.stringify({ login: "me" });
33
+ assert.equal(args[0], "api");
34
+ assert.deepEqual(args.slice(0, 2), ["api", "--paginate"]);
35
+ assert.match(args[2], /^repos\/o\/[rst]\/issues\/comments\?per_page=100&since=/);
36
+ assert.ok(Number.isFinite(Date.parse(new URL(`https://api.github.com/${args[2]}`).searchParams.get("since"))));
37
+ return typeof comments === "string" ? comments : JSON.stringify(comments);
38
+ };
39
+
40
+ test("every work kind falls back after three failures, is re-signed, and posts only its hidden payload", async t => {
41
+ for (const leader of [true, false]) {
42
+ const root = fixture(t), calls = [];
43
+ writeState(root, "node", { leader, term: 1 });
44
+ const pending = kinds.map(kind => entry({ message: message({ from: "a", kind, time: new Date(now - 600_000).toISOString() }) }));
45
+ const leaderOnly = new Set(["assign", "approve", "answer"]);
46
+ const posted = pending.filter(row => leader || !leaderOnly.has(row.message.kind));
47
+ const rejected = pending.filter(row => !leader && leaderOnly.has(row.message.kind));
48
+ writeState(root, "outbox", pending);
49
+ await flushOutbox({ root, fleet, leader, clock: () => now, fetch: async () => assert.fail("no HTTP after threshold"),
50
+ gh: args => { calls.push(args); return "posted"; } });
51
+ assert.equal(calls.length, leader ? 9 : 6);
52
+ for (const [index, args] of calls.entries()) {
53
+ assert.deepEqual(args.slice(0, 6), ["issue", "comment", "7", "--repo", "o/r", "--body"]);
54
+ const body = args[6], kind = posted[index].message.kind;
55
+ assert.ok(body.startsWith(`**${leader ? "Leader" : "Coder"}** · ${kind} for #7\n\n`));
56
+ assert.equal(parseMarker(body, { secret, nodes: ["a", "b"], ownAuthor: true }).node, "a");
57
+ const payload = /^<!-- qc:msg to=b ([\w-]+) -->$/m.exec(body);
58
+ assert.ok(payload);
59
+ assert.equal(body.split("\n\n")[1], payload[0]);
60
+ const signed = JSON.parse(Buffer.from(payload[1], "base64url"));
61
+ assert.deepEqual(verifyMessage(signed, { secret, nodes: fleet.nodes, now }), { ok: true });
62
+ assert.equal(signed.id, posted[index].message.id);
63
+ assert.equal(signed.time, new Date(now).toISOString());
64
+ assert.deepEqual(signed.body, posted[index].message.body);
65
+ }
66
+ assert.deepEqual(readState(root, "outbox"), []);
67
+ assert.deepEqual(readState(root, "dead", []), rejected.map(row => ({ ...row, reason: "not leader" })));
68
+ }
69
+ });
70
+
71
+ test("third failed HTTP send falls back in that tick; first two with a live peer stay on HTTP", async t => {
72
+ const root = fixture(t), calls = [];
73
+ let time = now;
74
+ writeState(root, "outbox", [entry({ attempts: 1, nextAttempt: now })]);
75
+ const opts = { root, fleet, clock: () => time, fetch: async () => { calls.push("http"); throw new Error("offline"); }, gh: () => { calls.push("github"); return "posted"; } };
76
+ await flushOutbox(opts);
77
+ assert.deepEqual(calls, ["http"]);
78
+ time = readState(root, "outbox")[0].nextAttempt;
79
+ await flushOutbox(opts);
80
+ assert.deepEqual(calls, ["http", "http", "github"]);
81
+ assert.deepEqual(readState(root, "outbox"), []);
82
+ });
83
+
84
+ test("heartbeat age at 90 seconds and missing heartbeat bypass retry delay; younger heartbeat does not", async t => {
85
+ for (const age of [89_999, 90_000, 90_001, null]) {
86
+ const root = fixture(t), calls = [];
87
+ writeState(root, "peers", age === null ? {} : { b: { time: now - age } });
88
+ writeState(root, "outbox", [entry({ attempts: 0 })]);
89
+ await flushOutbox({ root, fleet, clock: () => now, gh: () => { calls.push("github"); return "posted"; }, fetch: async () => assert.fail("retry not due") });
90
+ assert.equal(calls.length, age === 89_999 ? 0 : 1);
91
+ }
92
+ });
93
+
94
+ test("heartbeats, election messages, and work without a positive issue never use GitHub", async t => {
95
+ const root = fixture(t);
96
+ const messages = ["heartbeat", "leader", "propose-leader"].map(kind => message({ kind }));
97
+ messages.push(...[undefined, 0, -1, "7"].map(issue => message({ body: issue === undefined ? {} : { issue } })));
98
+ writeState(root, "outbox", messages.map(message => entry({ message })));
99
+ await flushOutbox({ root, fleet, clock: () => now, gh: () => assert.fail("not eligible"), fetch: async () => assert.fail("retry not due") });
100
+ assert.equal(readState(root, "outbox").length, messages.length);
101
+ });
102
+
103
+ test("failed posts remain for the next tick and do not block another eligible entry or lose concurrent sends", async t => {
104
+ for (const failure of [null, new Error("offline")]) {
105
+ const root = fixture(t), first = entry(), second = entry(), concurrent = entry({ attempts: 0 });
106
+ writeState(root, "outbox", [first, second]);
107
+ let calls = 0;
108
+ const opts = { root, fleet, clock: () => now, fetch: async () => assert.fail("GitHub owns retry"), gh: () => {
109
+ calls++;
110
+ if (calls === 1) {
111
+ writeState(root, "outbox", [...readState(root, "outbox"), concurrent]);
112
+ if (failure) throw failure;
113
+ return failure;
114
+ }
115
+ return "posted";
116
+ } };
117
+ await flushOutbox(opts);
118
+ assert.deepEqual(readState(root, "outbox").map(row => row.message.id), [first.message.id, concurrent.message.id]);
119
+ await flushOutbox(opts);
120
+ assert.equal(calls, 3);
121
+ assert.deepEqual(readState(root, "outbox").map(row => row.message.id), [concurrent.message.id]);
122
+ }
123
+ });
124
+
125
+ test("a receiver clock 60 seconds ahead cannot skip a comment after an empty poll", t => {
126
+ const root = fixture(t), calls = [];
127
+ let serverTime = now;
128
+ const good = message({ time: new Date(now + 1000).toISOString() });
129
+ const posted = { ...comment(good), issue_url: "https://api.github.com/repos/o/r/issues/7",
130
+ updated_at: new Date(now + 1000).toISOString() };
131
+ const unrelated = { user: { login: "someone-else" }, body: "ordinary comment",
132
+ issue_url: "https://api.github.com/repos/o/r/issues/99", updated_at: new Date(now + 3000).toISOString() };
133
+ writeState(root, "assignments", { "o/r#7": { repo: "o/r", issue: 7, node: "a" } });
134
+ const opts = { root, fleet, repo: "o/r", clock: () => serverTime + 60_000, gh: args => {
135
+ calls.push(args);
136
+ if (args[1] === "user") return JSON.stringify({ login: "me" });
137
+ const endpoint = args.find(arg => arg.startsWith("repos/"));
138
+ const since = new URL(`https://api.github.com/${endpoint}`).searchParams.get("since")
139
+ ?? args.find(arg => arg.startsWith("since="))?.slice(6);
140
+ return JSON.stringify([posted, unrelated].filter(row => Date.parse(row.updated_at) <= serverTime && Date.parse(row.updated_at) >= Date.parse(since)));
141
+ } };
142
+ readGithub(opts);
143
+ serverTime += 1000;
144
+ readGithub(opts);
145
+ assert.deepEqual(readState(root, "queue"), [good], "the empty poll must not advance past the next GitHub comment");
146
+ assert.equal(readState(root, "github").cursors["o/r"], new Date(now - 59_000).toISOString());
147
+ assert.deepEqual(calls.filter(args => args[1] !== "user").map(args => args.find(arg => arg.startsWith("repos/"))), [
148
+ `repos/o/r/issues/comments?per_page=100&since=${new Date(now - 540_000).toISOString()}`,
149
+ `repos/o/r/issues/comments?per_page=100&since=${new Date(now - 539_000).toISOString()}`,
150
+ ]);
151
+ serverTime += 2000;
152
+ readGithub(opts);
153
+ assert.equal(readState(root, "github").cursors["o/r"], new Date(now - 57_000).toISOString());
154
+ assert.deepEqual(readState(root, "queue"), [good], "overlapping reads silently discard seen IDs");
155
+ const saved = readState(root, "github");
156
+ readGithub({ ...opts, gh: fakeReader([]) });
157
+ assert.deepEqual(readState(root, "github"), saved, "an empty read preserves the cursor");
158
+ readGithub({ ...opts, gh: args => { if (args[1] === "user") return JSON.stringify({ login: "me" }); throw new Error("offline"); } });
159
+ assert.deepEqual(readState(root, "github"), saved, "a gh error preserves the cursor");
160
+ });
161
+
162
+ test("GitHub reads the serve repository and every assigned repository once with durable repository cursors", t => {
163
+ const root = fixture(t), calls = [];
164
+ writeState(root, "assignments", {
165
+ "o/r#7": { repo: "o/r", issue: 7, node: "a" }, "o/r#8": { repo: "o/r", issue: 8, node: "b" },
166
+ "o/s#9": { repo: "o/s", issue: 9, node: "a" },
167
+ "o/t#10": { repo: "o/t", issue: 10, node: "b" },
168
+ });
169
+ const opts = { root, fleet, repo: "o/r", clock: () => now, gh: fakeReader([comment()], calls) };
170
+ readGithub(opts);
171
+ const reads = calls.filter(args => args[1] !== "user");
172
+ assert.deepEqual(reads.map(args => args[2].split("?")[0]), ["repos/o/r/issues/comments", "repos/o/s/issues/comments", "repos/o/t/issues/comments"]);
173
+ assert.deepEqual(readState(root, "queue").map(msg => msg.id).length, 1, "comments must match their repository");
174
+ assert.deepEqual(readState(root, "github").cursors, Object.fromEntries(["o/r", "o/s", "o/t"].map(repo => [repo, new Date(now - 60_000).toISOString()])));
175
+ calls.length = 0;
176
+ readGithub({ ...opts, clock: () => now + 120_000 });
177
+ assert.ok(calls.filter(args => args[1] !== "user").every(args => args[2].endsWith(`since=${new Date(now - 60_000).toISOString()}`)));
178
+ });
179
+
180
+ test("GitHub compares repository names without case", t => {
181
+ for (const repo of ["acme/repo", "Acme/Repo"]) {
182
+ const root = fixture(t), calls = [];
183
+ const good = message({ repo });
184
+ const posted = { ...comment(good), issue_url: "https://api.github.com/repos/Acme/Repo/issues/7" };
185
+ writeState(root, "assignments", { "Acme/Repo#7": { repo: "Acme/Repo", issue: 7, node: "a" } });
186
+ readGithub({ root, fleet, repo: "acme/repo", clock: () => now, gh: args => {
187
+ calls.push(args);
188
+ if (args[1] === "user") return JSON.stringify({ login: "me" });
189
+ return JSON.stringify([posted]);
190
+ } });
191
+ assert.deepEqual(readState(root, "queue"), [good], "the repository casing must not drop authenticated work");
192
+ assert.equal(calls.filter(args => args[1] !== "user").length, 1, "repository casing must not cause duplicate reads");
193
+ }
194
+ });
195
+
196
+ test("GitHub accepts only own authenticated addressed work, and shares HTTP signature, sender, time and replay checks", async t => {
197
+ const root = fixture(t);
198
+ writeState(root, "assignments", { "o/r#7": { repo: "o/r", issue: 7, node: "a" } });
199
+ const good = message(), httpFirst = message();
200
+ assert.deepEqual(receiveMessage({ root, fleet, message: httpFirst, clock: () => now }), { ok: true });
201
+ const badSignature = message(); badSignature.sig = "00".repeat(32);
202
+ const invalid = [
203
+ comment(message(), { author: "someone-else" }), comment(message(), { to: "b" }),
204
+ comment(message(), { body: "<!-- qc:msg to=a garbage -->" }),
205
+ comment(message(), { marker: { node: "a" } }),
206
+ comment(badSignature), comment(message({ from: "unknown" }), { marker: { node: "b" } }),
207
+ comment(message({ time: new Date(now - 300_001).toISOString() })), comment(httpFirst),
208
+ comment(message({ kind: "leader" })), comment(message({ kind: "heartbeat" })),
209
+ comment(message(), { marker: { ref: "#8" } }),
210
+ { ...comment(message({ repo: "o/s" })), issue_url: "https://api.github.com/repos/o/r/issues/7" },
211
+ { ...comment(message()), issue_url: "https://api.github.com/repos/o/r/issues/8" },
212
+ { ...comment(message()), issue_url: "invalid" },
213
+ { ...comment(message()), issue_url: "https://api.github.com/repos/o/s/issues/7" },
214
+ comment(message(), { body: comment().body.replace(/sig=./, "sig=z") }),
215
+ ];
216
+ const malformed = roleComment({ role: "coder", node: "b", kind: "question", ref: "#7", summary: "question for #7", body: "<!-- qc:msg to=a eA -->" }, { secret });
217
+ readGithub({ root, fleet, clock: () => now, gh: fakeReader([...invalid, comment(message(), { body: malformed }), comment(good), comment(good)]) });
218
+ assert.deepEqual(readState(root, "queue"), [httpFirst, good]);
219
+ const server = await createNodeServer({ root, fleet, clock: () => now, listen: { port: 0 } });
220
+ t.after(() => new Promise(resolve => server.close(resolve)));
221
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/message`, { method: "POST", body: JSON.stringify(good) });
222
+ assert.equal((await response.json()).reason, "seen-id");
223
+ });
224
+
225
+ test("paginated comments are read and gh errors or invalid responses preserve each read cursor", t => {
226
+ const root = fixture(t), cursor = new Date(now - 120_000).toISOString();
227
+ writeState(root, "assignments", { "o/r#7": { repo: "o/r", issue: 7, node: "a" } });
228
+ for (const result of [null, "bad-json", "{}", new Error("offline")]) {
229
+ writeState(root, "github", { cursors: { "o/r": cursor } });
230
+ readGithub({ root, fleet, clock: () => now, gh: args => {
231
+ if (args[1] === "user") return JSON.stringify({ login: "me" });
232
+ if (result instanceof Error) throw result;
233
+ return result;
234
+ } });
235
+ assert.equal(readState(root, "github").cursors["o/r"], cursor);
236
+ }
237
+ const good = message();
238
+ readGithub({ root, fleet, clock: () => now, gh: fakeReader(`[]\n${JSON.stringify([comment(good)])}`) });
239
+ assert.deepEqual(readState(root, "queue"), [good]);
240
+ const saved = readState(root, "github");
241
+ readGithub({ root, fleet, clock: () => now + 120_000, gh: () => { throw new Error("user read failed"); } });
242
+ assert.deepEqual(readState(root, "github"), saved);
243
+ });
@@ -0,0 +1,50 @@
1
+ import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
2
+
3
+ export const KINDS = Object.freeze(["assign", "plan", "approve", "question", "answer", "pushed", "verdict", "platform-check", "platform-result", "heartbeat", "propose-leader", "leader"]);
4
+ const plain = value => value !== null && typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value));
5
+ const validSecret = secret => typeof secret === "string" && secret.length >= 64 && !/[^0-9a-f]/i.test(secret);
6
+
7
+ /** Canonical JSON for wire data: sort object keys recursively, preserving array order. */
8
+ export function canonical(value) {
9
+ if (value === null || typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) return JSON.stringify(value);
10
+ if (Array.isArray(value)) return `[${Array.from(value, item => canonical(item)).join(",")}]`;
11
+ if (plain(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
12
+ throw new TypeError("message must contain only JSON data");
13
+ }
14
+
15
+ function signature(unsigned, secret) {
16
+ if (!validSecret(secret)) throw new TypeError("secret must be hex with at least 64 characters");
17
+ // Use the complete shared hex text as the key, including odd-length secrets.
18
+ return createHmac("sha256", secret).update(canonical(unsigned)).digest("hex");
19
+ }
20
+
21
+ /** Create a signed data envelope; no body fields are interpreted as instructions. */
22
+ export function createMessage(fields, secret) {
23
+ const { sig: _sig, ...unsigned } = { v: 1, id: randomUUID(), time: new Date().toISOString(), ...fields };
24
+ return { ...unsigned, sig: signature(unsigned, secret) };
25
+ }
26
+
27
+ /** Return a named refusal, or accept and remember the ID in the caller's seen state. */
28
+ export function verifyMessage(message, { secret, nodes = [], seen = {}, now = Date.now() } = {}) {
29
+ const refuse = reason => ({ ok: false, reason });
30
+ try {
31
+ if (!plain(message)) return refuse("bad-message");
32
+ const { sig, ...unsigned } = message;
33
+ if (typeof sig !== "string" || sig.length !== 64 || /[^0-9a-f]/i.test(sig) || !validSecret(secret)) return refuse("bad-signature");
34
+ if (!plain(message.body)) return refuse("bad-body");
35
+ const expected = signature(unsigned, secret);
36
+ if (!timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(expected, "hex"))) return refuse("bad-signature");
37
+ if (message.v !== 1) return refuse("bad-version");
38
+ if (typeof message.id !== "string" || !message.id) return refuse("bad-id");
39
+ if (!nodes.some(node => node.id === message.from)) return refuse("unknown-sender");
40
+ if (!KINDS.includes(message.kind)) return refuse("unknown-kind");
41
+ if (typeof message.repo !== "string" || !/^[a-z0-9][a-z0-9-]*\/[a-z0-9_.-]+$/i.test(message.repo) || message.repo.trim() !== message.repo) return refuse("bad-repo");
42
+ const time = typeof message.time === "string" ? Date.parse(message.time) : NaN;
43
+ if (!Number.isFinite(time) || !Number.isFinite(now) || Math.abs(now - time) > 300_000) return refuse("bad-time");
44
+ if (Object.hasOwn(seen, message.id)) return refuse("seen-id");
45
+ Object.defineProperty(seen, message.id, { value: now, enumerable: true, writable: true, configurable: true });
46
+ return { ok: true };
47
+ } catch {
48
+ return refuse("bad-message");
49
+ }
50
+ }
@@ -0,0 +1,72 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { createHmac } from "node:crypto";
3
+ import { test } from "node:test";
4
+ import { KINDS, canonical, createMessage, verifyMessage } from "./fleet-message.mjs";
5
+
6
+ const secret = "ab".repeat(32);
7
+ const now = Date.parse("2026-11-24T12:00:00Z");
8
+ const fields = { id: "message-1", kind: "assign", repo: "owner/name", from: "a1", time: new Date(now).toISOString(), body: { number: 238 } };
9
+ const options = () => ({ secret, nodes: [{ id: "a1" }], seen: {}, now });
10
+ const signed = changes => createMessage({ ...fields, ...changes }, secret);
11
+
12
+ test("canonical JSON sorts recursively and signatures cover all unsigned fields", () => {
13
+ assert.equal(canonical({ z: [{ b: 2, a: 1 }], a: { z: null, a: true } }), '{"a":{"a":true,"z":null},"z":[{"a":1,"b":2}]}');
14
+ assert.equal(canonical(JSON.parse('{"__proto__":{"z":1},"b":2}')), '{"__proto__":{"z":1},"b":2}');
15
+ const message = signed({ body: { z: 1, a: { d: 2, c: 3 } }, extra: "covered" });
16
+ const { sig, ...unsigned } = message;
17
+ assert.equal(sig, createHmac("sha256", secret).update(canonical(unsigned)).digest("hex"));
18
+ for (const key of Object.keys(unsigned)) {
19
+ assert.deepEqual(verifyMessage({ ...message, [key]: "tampered" }, options()), { ok: false, reason: key === "body" ? "bad-body" : "bad-signature" });
20
+ }
21
+ });
22
+
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"]);
25
+ for (const kind of KINDS) assert.deepEqual(verifyMessage(signed({ kind, body: { command: "do not execute" } }), options()), { ok: true });
26
+ const context = options();
27
+ const message = signed();
28
+ assert.deepEqual(verifyMessage(message, context), { ok: true });
29
+ assert.equal(context.seen[message.id], now);
30
+ assert.deepEqual(verifyMessage(message, context), { ok: false, reason: "seen-id" });
31
+ const generated = createMessage({ kind: "heartbeat", repo: "owner/name", from: "a1", body: {} }, secret);
32
+ assert.equal(generated.v, 1);
33
+ assert.ok(generated.id);
34
+ assert.ok(Number.isFinite(Date.parse(generated.time)));
35
+ for (const key of ["a".repeat(65), "AB".repeat(40)]) {
36
+ const message = createMessage(fields, key);
37
+ assert.deepEqual(verifyMessage(message, { ...options(), secret: key }), { ok: true });
38
+ }
39
+ });
40
+
41
+ test("each refusal has a named reason and does not throw", () => {
42
+ const message = signed();
43
+ const { sig: _sig, ...missing } = message;
44
+ for (const bad of [missing, { ...message, sig: "00".repeat(32) }, { ...message, sig: "a" }, { ...message, sig: "g".repeat(64) }, { ...message, sig: 1 }, { ...message, sig: `${message.sig}\n` }]) {
45
+ assert.deepEqual(verifyMessage(bad, options()), { ok: false, reason: "bad-signature" });
46
+ }
47
+ for (const [changes, reason] of [
48
+ [{ from: "unknown" }, "unknown-sender"], [{ kind: "exec" }, "unknown-kind"],
49
+ ...["owner", "a/b/c", "/name", "owner/", "owner/name\n", "owner/name\r"].map(repo => [{ repo }, "bad-repo"]),
50
+ ...[null, [], "text", 1].map(body => [{ body }, "bad-body"]),
51
+ [{ time: "invalid" }, "bad-time"], [{ v: 2 }, "bad-version"], [{ id: "" }, "bad-id"],
52
+ ]) {
53
+ const context = options();
54
+ assert.deepEqual(verifyMessage(signed(changes), context), { ok: false, reason });
55
+ assert.deepEqual(context.seen, {});
56
+ }
57
+ for (const value of [null, [], 1, "message"]) assert.deepEqual(verifyMessage(value, options()), { ok: false, reason: "bad-message" });
58
+ assert.deepEqual(verifyMessage(message, { ...options(), secret: "cd".repeat(32) }), { ok: false, reason: "bad-signature" });
59
+ for (const badSecret of [undefined, null, "ab", `${secret}\n`]) assert.deepEqual(verifyMessage(message, { ...options(), secret: badSecret }), { ok: false, reason: "bad-signature" });
60
+ const unusualBody = signed({ body: {} });
61
+ Object.setPrototypeOf(unusualBody.body, { inherited: true });
62
+ assert.deepEqual(verifyMessage(unusualBody, options()), { ok: false, reason: "bad-body" });
63
+ const cyclic = signed({ body: {} });
64
+ cyclic.body.self = cyclic.body;
65
+ assert.deepEqual(verifyMessage(cyclic, options()), { ok: false, reason: "bad-message" });
66
+ assert.deepEqual(verifyMessage(signed({ id: "__proto__" }), options()), { ok: true });
67
+ });
68
+
69
+ test("five minute clock skew is inclusive in both directions", () => {
70
+ for (const offset of [-300_000, 300_000]) assert.deepEqual(verifyMessage(signed({ time: new Date(now + offset).toISOString() }), options()), { ok: true });
71
+ for (const offset of [-300_001, 300_001]) assert.deepEqual(verifyMessage(signed({ time: new Date(now + offset).toISOString() }), options()), { ok: false, reason: "bad-time" });
72
+ });