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,200 @@
1
+ import { execFile, spawn as spawnProcess } from "node:child_process";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { promisify } from "node:util";
7
+ import { load } from "../config.mjs";
8
+ import { appendLeg, hostOS } from "./legs.mjs";
9
+ import { platformRisk } from "./platform-risk.mjs";
10
+ import { createMessage } from "./fleet-message.mjs";
11
+ import { sendMessage } from "./fleet-node.mjs";
12
+ import { highestTerm, latestLeader, livePeer, readState, writeState } from "./fleet-state.mjs";
13
+ import { roleComment } from "./role-line.mjs";
14
+ import { runGh } from "./gh-run.mjs";
15
+
16
+ const execute = promisify(execFile);
17
+ const runGit = (root, ...args) => execute("git", args, { cwd: root, timeout: 60_000 });
18
+ const active = new Set();
19
+ const validIssue = value => Number.isSafeInteger(value) && value > 0;
20
+ export const validPlatformBranch = value => typeof value === "string" && /^[A-Za-z0-9._/-]+$/.test(value) && !value.startsWith("-");
21
+ const validHead = value => typeof value === "string" && /^[a-f0-9]{40}$/i.test(value);
22
+ const validPush = body => body && validIssue(body.issue) && validIssue(body.epoch) && validPlatformBranch(body.branch) && validHead(body.head);
23
+ function tailLines(text) {
24
+ let tail = text.trimEnd().split(/\r?\n/).slice(-40).join("\n");
25
+ while (Buffer.byteLength(JSON.stringify(tail)) > 48_000) tail = tail.slice(Math.max(1, Math.ceil(tail.length / 4)));
26
+ return tail;
27
+ }
28
+
29
+ /** Use this installed kit in the detached checkout, keeping only bounded output. */
30
+ export function runPlatformCheck(root, { spawn = spawnProcess, timeout = 30 * 60_000, signal } = {}) {
31
+ return new Promise(resolve => {
32
+ let output = "", expired = false, aborted = false, cleanupFailed = false, leftChild = false, settled = false, timer, drainTimer, child, stopping;
33
+ const append = chunk => { output = (output + chunk.toString()).split(/\r?\n/).slice(-41).join("\n").slice(-48_000); };
34
+ async function stopTree(child) {
35
+ if (!child?.pid) return false;
36
+ if (process.platform === "win32") {
37
+ stopping ??= execute("taskkill", ["/pid", String(child.pid), "/t", "/f"]).catch(error => {
38
+ if (child.exitCode === null && child.signalCode === null) {
39
+ cleanupFailed = true; append(`\nprocess tree cleanup: ${error.message}`);
40
+ }
41
+ });
42
+ await stopping;
43
+ return false;
44
+ }
45
+ try { process.kill(-child.pid, "SIGKILL"); return true; }
46
+ catch (error) {
47
+ if (error.code !== "ESRCH") { cleanupFailed = true; append(`\nprocess tree cleanup: ${error.message}`); }
48
+ return false;
49
+ }
50
+ }
51
+ const onAbort = () => {
52
+ aborted = true; append("\nplatform check aborted");
53
+ void stopTree(child);
54
+ };
55
+ const finish = ok => {
56
+ if (settled) return;
57
+ settled = true; clearTimeout(timer); clearTimeout(drainTimer);
58
+ signal?.removeEventListener("abort", onAbort);
59
+ child?.stdout?.destroy(); child?.stderr?.destroy();
60
+ resolve({ ok: ok && !expired && !aborted && !leftChild && !cleanupFailed, tail: tailLines(output) });
61
+ };
62
+ try {
63
+ if (signal?.aborted) { onAbort(); finish(false); return; }
64
+ child = spawn(process.execPath, [fileURLToPath(new URL("./qc.mjs", import.meta.url)), "check", "--affected", "--base", "origin/main"],
65
+ { cwd: root, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
66
+ child.stdout.on("data", append); child.stderr.on("data", append);
67
+ child.once("error", async error => { append(`\n${error.message}`); await stopTree(child); finish(false); });
68
+ child.once("exit", async code => {
69
+ clearTimeout(timer);
70
+ leftChild = await stopTree(child) && !expired && !aborted;
71
+ if (leftChild) append("\ncheck left a child process");
72
+ const drained = () => {
73
+ if ([child.stdout, child.stderr].every(stream => stream.readableEnded || stream.destroyed)) finish(code === 0);
74
+ };
75
+ drainTimer = setTimeout(() => finish(code === 0), 5000);
76
+ for (const stream of [child.stdout, child.stderr]) {
77
+ stream.once("end", drained); stream.once("close", drained);
78
+ }
79
+ drained();
80
+ });
81
+ timer = setTimeout(() => {
82
+ expired = true; append("\nplatform check timed out");
83
+ void stopTree(child);
84
+ }, timeout);
85
+ signal?.addEventListener("abort", onAbort, { once: true });
86
+ if (signal?.aborted) onAbort();
87
+ } catch (error) { append(error.message); finish(false); }
88
+ });
89
+ }
90
+
91
+ function leaderId(root) {
92
+ const peers = readState(root, "peers"), leader = latestLeader(peers, highestTerm(root));
93
+ return Object.keys(peers).find(id => peers[id] === leader);
94
+ }
95
+
96
+ /** Queue before transport so an interrupted command can be retried by the node. */
97
+ export async function sendPushed({ root, fleet, repo, issue, epoch, branch, head, node = {}, say = console.log }) {
98
+ const id = leaderId(root), recipient = fleet.nodes.find(row => row.id === id && row.active !== false && row.address);
99
+ if (!recipient) throw new Error("no addressed Leader heartbeat");
100
+ const message = createMessage({ from: fleet.self, repo, kind: "pushed", body: { issue, epoch, branch, head } }, fleet.secret);
101
+ const entry = { node: id, message, attempts: 0, nextAttempt: 0 };
102
+ writeState(root, "outbox", [...readState(root, "outbox"), entry]);
103
+ const { flushOutbox } = await import("./fleet-node.mjs");
104
+ await flushOutbox({ ...node, root, fleet });
105
+ say(`pushed ${message.id}`);
106
+ return 0;
107
+ }
108
+
109
+ async function checkHead({ root, body, git, check, signal }) {
110
+ let temporary, checkout, result;
111
+ try {
112
+ await git(root, "fetch", "origin", body.branch);
113
+ temporary = mkdtempSync(path.join(os.tmpdir(), "qc-fleet-platform-"));
114
+ checkout = path.join(temporary, "checkout");
115
+ await git(root, "-c", "core.ignoreStat=false", "worktree", "add", "--detach", checkout, body.head);
116
+ result = await check(checkout, { timeout: 30 * 60_000, signal });
117
+ const actual = await git(checkout, "rev-parse", "HEAD");
118
+ // A dirty index can make refresh exit nonzero; status below determines cleanliness.
119
+ try { await git(checkout, "-c", "core.ignoreStat=false", "update-index", "--really-refresh"); } catch {}
120
+ const status = await git(checkout, "-c", "core.ignoreStat=false", "status", "--porcelain", "--untracked-files=all");
121
+ if (actual.stdout.trim() !== body.head) {
122
+ result = { ok: false, tail: `${result.tail ?? ""}\nplatform check HEAD ${actual.stdout.trim()} does not match requested head ${body.head}` };
123
+ } else if (status.stdout !== "") {
124
+ result = { ok: false, tail: `${result.tail ?? ""}\nplatform check worktree has uncommitted changes` };
125
+ }
126
+ } catch (error) { result = { ok: false, tail: `${result?.tail ?? ""}\n${error.message}` }; }
127
+ finally {
128
+ if (checkout) {
129
+ try { await git(root, "worktree", "remove", "--force", checkout); }
130
+ catch (error) { result = { ok: false, tail: `${result?.tail ?? ""}\nworktree cleanup: ${error.message}` }; }
131
+ }
132
+ if (temporary) rmSync(temporary, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
133
+ }
134
+ return { ok: result.ok === true, tail: tailLines(result.tail ?? "") };
135
+ }
136
+
137
+ /** A separate asynchronous worker leaves the heartbeat tick free during checks. */
138
+ export async function platformTick({ root, fleet, clock = Date.now, config, risk = platformRisk, git = runGit,
139
+ check = runPlatformCheck, os = hostOS(), fetch, gh = runGh, signal, warn = console.error }) {
140
+ if (active.has(root) || signal?.aborted) return;
141
+ active.add(root);
142
+ try {
143
+ const queue = readState(root, "queue");
144
+ const message = queue.find(row => ["pushed", "platform-check", "platform-result"].includes(row.kind));
145
+ if (!message) return;
146
+ const { body, from, repo, kind } = message;
147
+ const peers = readState(root, "peers");
148
+ const leader = () => readState(root, "node").leader === true;
149
+ const send = async (id, kind, body) => {
150
+ const node = fleet.nodes.find(row => row.id === id && row.active !== false && row.address);
151
+ if (!node) return;
152
+ const outgoing = createMessage({ from: fleet.self, repo, kind, body, time: new Date(clock()).toISOString() }, fleet.secret);
153
+ if (id === fleet.self) writeState(root, "queue", [...readState(root, "queue"), outgoing]);
154
+ else await sendMessage({ root, fleet, node, message: outgoing, fetch, clock, signal });
155
+ };
156
+ // Remove only this envelope before any await; concurrent deliveries remain queued.
157
+ writeState(root, "queue", queue.filter(row => row !== message));
158
+ if (kind === "pushed") {
159
+ const holds = () => {
160
+ const row = readState(root, "assignments")[`${repo}#${body.issue}`];
161
+ return leader() && row?.node === from && row.epoch === body.epoch;
162
+ };
163
+ if (!validPush(body) || !holds()) return;
164
+ await git(root, "fetch", "origin", body.branch);
165
+ if (!holds()) return;
166
+ config ??= load(root);
167
+ if (risk(root, config.check.base, body.head).length === 0) return;
168
+ for (const platform of config.ready.platforms.filter(platform => platform !== peers[from]?.os)) {
169
+ if (!holds()) return;
170
+ const current = readState(root, "peers");
171
+ const node = fleet.nodes.filter(node => node.active !== false && node.address && current[node.id]?.os === platform &&
172
+ livePeer(current[node.id], clock())).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)[0];
173
+ if (!node) warn(`no live ${platform} node for #${body.issue}`);
174
+ else await send(node.id, "platform-check", { issue: body.issue, epoch: body.epoch, branch: body.branch, head: body.head, pusher: from });
175
+ }
176
+ } else if (kind === "platform-check") {
177
+ if (!validPush(body) || from !== leaderId(root) || !fleet.nodes.some(node => node.id === body.pusher)) return;
178
+ const result = await checkHead({ root, body, git, check, signal });
179
+ for (const id of new Set([body.pusher, from])) await send(id, "platform-result", { issue: body.issue, head: body.head, os, ...result });
180
+ } else {
181
+ if (!body || !validIssue(body.issue) || !validHead(body.head) || !["linux", "windows", "darwin"].includes(body.os) ||
182
+ peers[from]?.os !== body.os || typeof body.ok !== "boolean" || typeof body.tail !== "string") return;
183
+ const assignment = readState(root, "assignments")[`${repo}#${body.issue}`];
184
+ if (assignment?.node === fleet.self && body.ok) appendLeg(root, { os: body.os, head: body.head, source: "fleet" });
185
+ if (leader()) {
186
+ const tail = tailLines(body.tail).replace(/^<!-- qc:v1/gm, " <!-- qc:v1");
187
+ const fence = "`".repeat(Math.max(3, ...Array.from(tail.matchAll(/`+/g), match => match[0].length + 1)));
188
+ const comment = roleComment({ role: "reviewer", node: fleet.self, kind: "platform-result", ref: `#${body.issue}`,
189
+ summary: `platform check on ${body.os}: ${body.ok ? "pass" : "fail"}`, body: `${fence}\n${tail}\n${fence}` }, { secret: fleet.secret });
190
+ try {
191
+ const posted = gh(["issue", "comment", String(body.issue), "--repo", repo, "--body", comment], { cwd: root });
192
+ if (typeof posted !== "string") throw new Error("platform result comment failed");
193
+ } catch (error) {
194
+ writeState(root, "queue", [...readState(root, "queue"), message]);
195
+ throw error;
196
+ }
197
+ }
198
+ }
199
+ } finally { active.delete(root); }
200
+ }
@@ -0,0 +1,316 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { execFileSync, spawn as spawnProcess } from "node:child_process";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { EventEmitter } from "node:events";
8
+ import { PassThrough } from "node:stream";
9
+ import { platformTick, runPlatformCheck } from "./fleet-platform.mjs";
10
+ import { readState, writeState } from "./fleet-state.mjs";
11
+ import { legRecords } from "./legs.mjs";
12
+
13
+ const head = "a".repeat(40), now = 100_000;
14
+ function fixture(t, self = "leader") {
15
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-platform-"));
16
+ mkdirSync(path.join(root, ".git"));
17
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
18
+ const fleet = { self, secret: "ab".repeat(32), nodes: ["leader", "pusher", "win-z", "win-a", "mac", "dead", "inactive"].map((id, index) =>
19
+ ({ id, address: "localhost", port: 8100 + index, active: id !== "inactive" })) };
20
+ writeState(root, "node", { leader: self === "leader", term: 1 });
21
+ writeState(root, "assignments", { "o/r#244": { repo: "o/r", issue: 244, epoch: 2, node: "pusher" } });
22
+ writeState(root, "peers", {
23
+ leader: { time: now, leader: true, term: 1, os: "linux" }, pusher: { time: now, os: "linux" },
24
+ "win-z": { time: now, os: "windows" }, "win-a": { time: now, os: "windows" }, mac: { time: now, os: "darwin" },
25
+ dead: { time: now - 90_000, os: "darwin" }, inactive: { time: now, os: "darwin" },
26
+ });
27
+ const sent = [], urls = [], calls = [], comments = [], warnings = [];
28
+ const deps = { root, fleet, clock: () => now, config: { check: { base: "base" }, ready: { platforms: ["linux", "windows", "darwin"] } },
29
+ risk: (...args) => { calls.push(["risk", ...args]); return [{ reason: "platform" }]; },
30
+ git: async (...args) => { calls.push(["git", ...args]); return { stdout: args[1] === "rev-parse" ? `${head}\n` : "" }; },
31
+ check: async (...args) => { calls.push(["check", ...args]); return { ok: true, tail: "passed" }; },
32
+ gh: (args, options) => { comments.push({ args, options }); return "comment-url"; },
33
+ fetch: async (url, options) => { urls.push(url); sent.push(JSON.parse(options.body)); return { status: 202 }; },
34
+ warn: text => warnings.push(text) };
35
+ const queue = (kind, body = {}, from = "pusher") => writeState(root, "queue", [...readState(root, "queue"),
36
+ { id: String(readState(root, "queue").length), repo: "o/r", from, kind, body: { issue: 244, epoch: 2, branch: "feat/244", head, ...body } }]);
37
+ return { ...deps, deps, sent, urls, calls, comments, warnings, queue };
38
+ }
39
+
40
+ test("Leader fetches risky pushed heads and chooses the lowest live ID for each other OS", async t => {
41
+ const f = fixture(t);
42
+ f.queue("pushed");
43
+ await platformTick(f.deps);
44
+ assert.deepEqual(f.calls.slice(0, 2), [["git", f.root, "fetch", "origin", "feat/244"], ["risk", f.root, "base", head]]);
45
+ assert.deepEqual(f.sent.map(m => [m.kind, m.body]), ["windows", "darwin"].map(() => ["platform-check", { issue: 244, epoch: 2, branch: "feat/244", head, pusher: "pusher" }]));
46
+ assert.deepEqual(f.urls, ["http://localhost:8103/message", "http://localhost:8104/message"]);
47
+ assert.deepEqual(readState(f.root, "queue"), []);
48
+ });
49
+
50
+ test("pushed rejects wrong owner, epoch, branch and head before git; safe diffs send nothing", async t => {
51
+ const f = fixture(t);
52
+ f.queue("pushed", {}, "mac"); f.queue("pushed", { epoch: 1 });
53
+ f.queue("pushed", { branch: "bad;command" }); f.queue("pushed", { head: "--help" });
54
+ for (let n = 0; n < 4; n++) await platformTick(f.deps);
55
+ assert.deepEqual(f.calls, []);
56
+ f.queue("pushed");
57
+ await platformTick({ ...f.deps, risk: () => [] });
58
+ assert.equal(f.sent.length, 0);
59
+ const peers = readState(f.root, "peers"); delete peers.mac; writeState(f.root, "peers", peers);
60
+ f.queue("pushed"); await platformTick(f.deps);
61
+ assert.deepEqual(f.warnings, ["no live darwin node for #244"]);
62
+ });
63
+
64
+ test("worker accepts only the Leader, checks a detached head serially, and reports to pusher and Leader", async t => {
65
+ const f = fixture(t, "mac");
66
+ f.queue("platform-check", { pusher: "pusher" }, "win-a");
67
+ f.queue("platform-check", { pusher: "pusher", branch: "bad branch" }, "leader");
68
+ await platformTick(f.deps); await platformTick(f.deps);
69
+ assert.deepEqual(f.calls, []);
70
+ let release;
71
+ const waiting = new Promise(resolve => { release = resolve; });
72
+ f.queue("platform-check", { pusher: "pusher" }, "leader");
73
+ f.queue("platform-check", { pusher: "pusher" }, "leader");
74
+ const running = platformTick({ ...f.deps, os: "darwin", check: async (cwd, options) => {
75
+ f.calls.push(["check", cwd, options]); await waiting; return { ok: true, tail: "done" };
76
+ } });
77
+ await new Promise(resolve => setImmediate(resolve));
78
+ await platformTick(f.deps);
79
+ assert.equal(f.calls.filter(row => row[0] === "check").length, 1);
80
+ assert.equal(readState(f.root, "queue").length, 1);
81
+ release(); await running;
82
+ const add = f.calls.find(row => row.includes("add"));
83
+ assert.deepEqual(add.slice(2, 7), ["-c", "core.ignoreStat=false", "worktree", "add", "--detach"]);
84
+ assert.equal(add.at(-1), head);
85
+ const run = f.calls.find(row => row[0] === "check");
86
+ assert.equal(run[1], add[7]);
87
+ assert.equal(run[2].timeout, 30 * 60_000);
88
+ assert.deepEqual(f.calls.at(-1).slice(2), ["worktree", "remove", "--force", add[7]]);
89
+ assert.deepEqual(f.sent.map(m => m.body), [1, 2].map(() => ({ issue: 244, head, os: "darwin", ok: true, tail: "done" })));
90
+ });
91
+
92
+ test("failed setup and runner errors still clean up and send failed results", async t => {
93
+ for (const stage of ["fetch", "add", "check"]) {
94
+ const f = fixture(t, "mac"); f.queue("platform-check", { pusher: "pusher" }, "leader");
95
+ await platformTick({ ...f.deps, os: "darwin", git: async (...args) => {
96
+ f.calls.push(["git", ...args]); if (args.includes(stage)) throw new Error(`${stage} failed`);
97
+ }, check: async () => { throw new Error("check failed"); } });
98
+ assert.equal(f.sent[0].body.ok, false);
99
+ assert.match(f.sent[0].body.tail, new RegExp(`${stage} failed`));
100
+ if (stage !== "fetch") assert.ok(f.calls.some(row => row.includes("remove")));
101
+ }
102
+ });
103
+
104
+ test("only heartbeat-matching passing results add fleet legs; Leader posts Reviewer result comments", async t => {
105
+ const f = fixture(t, "pusher");
106
+ for (const [from, body] of [["mac", { os: "windows", ok: true }], ["mac", { os: "darwin", ok: false }],
107
+ ["mac", { os: "darwin", ok: true }], ["win-a", { os: "windows", ok: true, head: "bad" }]]) {
108
+ f.queue("platform-result", { tail: "output", ...body }, from);
109
+ }
110
+ for (let n = 0; n < 4; n++) await platformTick(f.deps);
111
+ assert.deepEqual(legRecords(f.root).map(({ os, head, source }) => ({ os, head, source })), [{ os: "darwin", head, source: "fleet" }]);
112
+ const leader = fixture(t);
113
+ leader.queue("platform-result", { os: "darwin", ok: false, tail: "error\n```\nend" }, "mac");
114
+ await platformTick(leader.deps);
115
+ assert.equal(leader.comments.length, 1);
116
+ const comment = leader.comments[0].args;
117
+ assert.deepEqual(comment.slice(0, 6), ["issue", "comment", "244", "--repo", "o/r", "--body"]);
118
+ assert.match(comment[6], /Reviewer/);
119
+ assert.match(comment[6], /kind=platform-result/);
120
+ assert.match(comment[6], /platform check on darwin: fail/);
121
+ assert.match(comment[6], /error/);
122
+ });
123
+
124
+ test("checks must leave the requested HEAD and a clean worktree", async t => {
125
+ const f = fixture(t, "mac");
126
+ const git = (cwd, ...args) => ({ stdout: execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) });
127
+ git(f.root, "init");
128
+ writeFileSync(path.join(f.root, "tracked"), "original");
129
+ git(f.root, "add", "tracked");
130
+ git(f.root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "first");
131
+ const other = git(f.root, "rev-parse", "HEAD").stdout.trim();
132
+ git(f.root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-m", "requested");
133
+ const requested = git(f.root, "rev-parse", "HEAD").stdout.trim();
134
+ git(f.root, "remote", "add", "origin", f.root);
135
+ git(f.root, "branch", "feat/244");
136
+ for (const mode of ["moved", "dirty", "hidden-untracked", "ignore-stat", "clean"]) {
137
+ git(f.root, "config", "status.showUntrackedFiles", mode === "hidden-untracked" ? "no" : "all");
138
+ git(f.root, "config", "core.ignoreStat", mode === "ignore-stat" ? "true" : "false");
139
+ let checkout;
140
+ f.queue("platform-check", { pusher: "pusher", head: requested }, "leader");
141
+ await platformTick({ ...f.deps, git, check: async cwd => {
142
+ checkout = cwd;
143
+ if (mode === "moved") git(cwd, "checkout", "--detach", other);
144
+ if (["dirty", "hidden-untracked"].includes(mode)) writeFileSync(path.join(cwd, "untracked"), "changed");
145
+ if (mode === "ignore-stat") execFileSync(process.execPath,
146
+ ["-e", "require('node:fs').writeFileSync('tracked', 'changed')"], { cwd });
147
+ return { ok: true, tail: "command passed\n" };
148
+ } });
149
+ const result = f.sent.at(-1).body;
150
+ assert.equal(existsSync(path.dirname(checkout)), false);
151
+ assert.equal(git(f.root, "worktree", "list", "--porcelain").stdout.includes(checkout), false);
152
+ assert.equal(result.ok, mode === "clean", mode);
153
+ if (mode === "moved") assert.match(result.tail.split("\n").at(-1), /HEAD.*requested/i);
154
+ if (["dirty", "hidden-untracked", "ignore-stat"].includes(mode)) assert.match(result.tail.split("\n").at(-1), /worktree.*(dirty|clean|changes)/i);
155
+ if (mode === "clean") assert.equal(result.tail, "command passed");
156
+ }
157
+ });
158
+
159
+ async function assertProcessGone(pid) {
160
+ for (let attempt = 0; attempt < 100; attempt++) {
161
+ try { process.kill(pid, 0); }
162
+ catch (error) { assert.equal(error.code, "ESRCH"); return; }
163
+ await new Promise(resolve => setTimeout(resolve, 20));
164
+ }
165
+ assert.fail(`grandchild ${pid} is still alive`);
166
+ }
167
+
168
+ for (const ending of ["exit 0", "abort"]) {
169
+ test(`${ending} stops a real long-lived grandchild`, { skip: ending === "exit 0" && process.platform === "win32" }, async t => {
170
+ const f = fixture(t, "mac"), controller = new AbortController();
171
+ const heartbeat = path.join(f.root, "heartbeat");
172
+ const grandchildScript = `const fs = require('node:fs'); fs.writeFileSync(${JSON.stringify(heartbeat)}, 'ready'); process.send(process.pid); setInterval(() => fs.appendFileSync(${JSON.stringify(heartbeat)}, '.'), 25);`;
173
+ const childScript = `const { spawn } = require('node:child_process'); const child = spawn(process.execPath, ['-e', ${JSON.stringify(grandchildScript)}], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }); child.once('message', pid => { console.log(pid); ${ending === "exit 0" ? "process.exit(0);" : ""} }); setInterval(() => {}, 1000);`;
174
+ let child, grandchild, deadline;
175
+ t.after(() => {
176
+ clearTimeout(deadline);
177
+ for (const pid of [grandchild, child?.pid]) {
178
+ if (!pid) continue;
179
+ try { process.kill(pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") throw error; }
180
+ }
181
+ });
182
+ const running = runPlatformCheck(f.root, { signal: controller.signal, timeout: 10_000,
183
+ spawn: (_command, _args, options) => {
184
+ child = spawnProcess(process.execPath, ["-e", childScript], options);
185
+ child.stdout.once("data", data => {
186
+ grandchild = Number(data.toString().trim());
187
+ if (ending === "abort") controller.abort();
188
+ });
189
+ return child;
190
+ } });
191
+ const result = await Promise.race([running, new Promise((_, reject) => {
192
+ deadline = setTimeout(() => reject(new Error(`${ending} did not settle`)), 4000);
193
+ })]);
194
+ clearTimeout(deadline);
195
+ assert.ok(grandchild > 0);
196
+ if (process.platform !== "win32") await assertProcessGone(grandchild);
197
+ const stopped = readFileSync(heartbeat, "utf8");
198
+ await new Promise(resolve => setTimeout(resolve, 150));
199
+ assert.equal(readFileSync(heartbeat, "utf8"), stopped, "grandchild must stop writing");
200
+ assert.equal(result.ok, false);
201
+ assert.match(result.tail, ending === "exit 0" ? /check left a child process/ : /abort/i);
202
+ });
203
+ }
204
+
205
+ test("timeout stops a real child and its long-lived grandchild and removes the worktree", async t => {
206
+ const f = fixture(t, "mac");
207
+ const heartbeat = path.join(f.root, "heartbeat");
208
+ const grandchildScript = `const fs = require('node:fs'); fs.writeFileSync(${JSON.stringify(heartbeat)}, 'ready'); setInterval(() => fs.appendFileSync(${JSON.stringify(heartbeat)}, '.'), 25);`;
209
+ const childScript = `const { spawn } = require('node:child_process'); const child = spawn(process.execPath, ['-e', ${JSON.stringify(grandchildScript)}], { stdio: ['ignore', 'inherit', 'inherit'] }); console.log(child.pid); setInterval(() => {}, 1000);`;
210
+ let child, grandchild, checkout, deadline;
211
+ t.after(() => {
212
+ clearTimeout(deadline);
213
+ for (const pid of [grandchild, child?.pid]) {
214
+ if (!pid) continue;
215
+ try { process.kill(pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") throw error; }
216
+ }
217
+ });
218
+ f.queue("platform-check", { pusher: "pusher" }, "leader");
219
+ const running = platformTick({ ...f.deps, check: async (cwd, options) => {
220
+ checkout = cwd;
221
+ return runPlatformCheck(cwd, { ...options, timeout: 1500, spawn: (_command, _args, spawnOptions) => {
222
+ child = spawnProcess(process.execPath, ["-e", childScript], { ...spawnOptions, cwd: f.root });
223
+ child.stdout.once("data", data => { grandchild = Number(data.toString().trim()); });
224
+ return child;
225
+ } });
226
+ } });
227
+ await Promise.race([running, new Promise((_, reject) => {
228
+ deadline = setTimeout(() => reject(new Error("timeout left descendant output pipes open")), 4000);
229
+ })]);
230
+ clearTimeout(deadline);
231
+ assert.ok(grandchild > 0);
232
+ assert.equal(f.sent.at(-1).body.ok, false);
233
+ assert.match(f.sent.at(-1).body.tail, /timed out/);
234
+ assert.equal(existsSync(path.dirname(checkout)), false);
235
+ assert.ok(f.calls.some(row => row[2] === "worktree" && row[3] === "remove" && row[5] === checkout));
236
+ const stopped = readFileSync(heartbeat, "utf8");
237
+ await new Promise(resolve => setTimeout(resolve, 150));
238
+ assert.equal(readFileSync(heartbeat, "utf8"), stopped, "grandchild must stop writing after timeout");
239
+ });
240
+
241
+ test("check runner uses this kit and bounds output to forty lines", async () => {
242
+ let child, invocation;
243
+ const spawn = (...args) => {
244
+ invocation = args;
245
+ child = new EventEmitter(); child.stdout = new PassThrough(); child.stderr = new PassThrough();
246
+ return child;
247
+ };
248
+ const running = runPlatformCheck("/checkout", { spawn, timeout: 1000 });
249
+ child.stdout.write(Array.from({ length: 60 }, (_, n) => `line ${n}\n`).join(""));
250
+ child.stderr.write("last error\n"); child.stdout.end(); child.stderr.end(); child.emit("exit", 1); child.emit("close", 1);
251
+ const result = await running;
252
+ assert.equal(invocation[0], process.execPath);
253
+ assert.deepEqual(invocation[1].slice(1), ["check", "--affected", "--base", "origin/main"]);
254
+ assert.match(invocation[1][0], /qc\.mjs$/);
255
+ assert.equal(invocation[2].cwd, "/checkout");
256
+ assert.equal(invocation[2].detached, process.platform !== "win32");
257
+ assert.equal(result.ok, false); assert.equal(result.tail.split("\n").length, 40);
258
+ assert.equal(result.tail.split("\n").at(-1), "last error");
259
+ });
260
+
261
+ test("check runner drains late output after exit without needing a child close event", async t => {
262
+ const child = new EventEmitter(); child.stdout = new PassThrough(); child.stderr = new PassThrough();
263
+ const running = runPlatformCheck("/checkout", { spawn: () => child });
264
+ let deadline;
265
+ t.after(() => { clearTimeout(deadline); child.emit("close", 0); });
266
+ child.emit("exit", 0);
267
+ child.stdout.end("late output\n"); child.stderr.end();
268
+ const result = await Promise.race([running, new Promise((_, reject) => {
269
+ deadline = setTimeout(() => reject(new Error("runner waited for child close after pipes drained")), 1000);
270
+ })]);
271
+ assert.deepEqual(result, { ok: true, tail: "late output" });
272
+ });
273
+
274
+ test("check runner destroys pipes still open five seconds after exit", async t => {
275
+ const child = new EventEmitter(); child.stdout = new PassThrough(); child.stderr = new PassThrough();
276
+ const running = runPlatformCheck("/checkout", { spawn: () => child });
277
+ let deadline;
278
+ t.after(() => { clearTimeout(deadline); child.emit("close", 0); });
279
+ child.stdout.write("before exit\n"); child.emit("exit", 0);
280
+ const result = await Promise.race([running, new Promise((_, reject) => {
281
+ deadline = setTimeout(() => reject(new Error("runner did not bound pipe draining after exit")), 6500);
282
+ })]);
283
+ assert.deepEqual(result, { ok: true, tail: "before exit" });
284
+ assert.equal(child.stdout.destroyed, true);
285
+ assert.equal(child.stderr.destroyed, true);
286
+ });
287
+
288
+ test("Leader retries result comments after gh errors without losing newly queued work", async t => {
289
+ const f = fixture(t);
290
+ f.queue("platform-result", { os: "darwin", ok: true, tail: "passed" }, "mac");
291
+ await assert.rejects(platformTick({ ...f.deps, gh: () => { f.queue("question"); throw new Error("gh offline"); } }), /gh offline/);
292
+ assert.deepEqual(readState(f.root, "queue").map(row => row.kind).sort(), ["platform-result", "question"]);
293
+ await platformTick(f.deps);
294
+ assert.equal(f.comments.length, 1);
295
+ assert.deepEqual(readState(f.root, "queue").map(row => row.kind), ["question"]);
296
+ });
297
+
298
+ test("Leader rechecks ownership and role after fetch and between platform sends", async t => {
299
+ for (const phase of ["fetch", "send"]) {
300
+ const f = fixture(t); f.queue("pushed");
301
+ await platformTick({ ...f.deps, git: async () => {
302
+ if (phase === "fetch") writeState(f.root, "assignments", {});
303
+ }, fetch: async (_url, options) => {
304
+ f.sent.push(JSON.parse(options.body)); writeState(f.root, "node", { leader: false, term: 2 });
305
+ return { status: 202 };
306
+ } });
307
+ assert.equal(f.sent.length, phase === "send" ? 1 : 0);
308
+ }
309
+ });
310
+
311
+ test("large escaped output remains deliverable within the fleet message limit", async t => {
312
+ const f = fixture(t, "mac"); f.queue("platform-check", { pusher: "pusher" }, "leader");
313
+ await platformTick({ ...f.deps, os: "darwin", check: async () => ({ ok: true, tail: "\u0000".repeat(80_000) + "\nlast line\n" }) });
314
+ assert.ok(Buffer.byteLength(JSON.stringify(f.sent[0])) <= 64 * 1024);
315
+ assert.ok(f.sent[0].body.tail.endsWith("last line"));
316
+ });
@@ -0,0 +1,75 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { commonDirOf } from "./ledger.mjs";
5
+
6
+ const FILES = ["election", "proposal", "work", "assignments", "questions", "seen", "queue", "outbox", "dead", "peers", "node", "plans", "answers", "inbox", "watched", "github"];
7
+
8
+ /** State is private to git's shared directory, outside every worktree's tracked files. */
9
+ export function stateDir(root = process.cwd()) {
10
+ const common = commonDirOf(root);
11
+ if (!common) throw new Error("fleet state needs a git common dir");
12
+ return path.join(common, "qc", "fleet");
13
+ }
14
+
15
+ function stateFile(root, name) {
16
+ if (!FILES.includes(name)) throw new Error(`unknown fleet state file: ${name}`);
17
+ return path.join(stateDir(root), `${name}.json`);
18
+ }
19
+
20
+ /** Missing state is empty; corrupt or unreadable state is an error. */
21
+ export function readState(root, name) {
22
+ const file = stateFile(root, name);
23
+ try {
24
+ return JSON.parse(readFileSync(file, "utf8"));
25
+ } catch (error) {
26
+ if (error.code === "ENOENT") return ["queue", "outbox", "dead", "inbox"].includes(name) ? [] : {};
27
+ throw error;
28
+ }
29
+ }
30
+
31
+ /** Replace one complete snapshot, using a unique temporary file in the same directory. */
32
+ export function writeState(root, name, value) {
33
+ const file = stateFile(root, name);
34
+ const serialized = JSON.stringify(value, null, 2);
35
+ if (serialized === undefined) throw new TypeError("fleet state value must serialize to JSON");
36
+ const data = `${serialized}\n`;
37
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
38
+ const temporary = `${file}.${randomUUID()}.tmp`;
39
+ try {
40
+ writeFileSync(temporary, data, { flag: "wx", mode: 0o600 });
41
+ renameSync(temporary, file);
42
+ } finally {
43
+ rmSync(temporary, { force: true, maxRetries: 10, retryDelay: 100 });
44
+ }
45
+ }
46
+
47
+ /** Return a fresh ID-to-receipt-time snapshot retaining the inclusive ten-minute edge. */
48
+ export function pruneSeen(seen, now = Date.now()) {
49
+ return Object.fromEntries(Object.entries(seen).filter(([, time]) => Number.isFinite(time) && now - time <= 600_000));
50
+ }
51
+
52
+ /** Prefer the highest observed term, then receipt order within that term. */
53
+ export function latestLeader(peers, minimum = 1) {
54
+ const highest = Math.max(minimum, ...Object.values(peers).map(peer => peer.term ?? 1));
55
+ return Object.values(peers).filter(peer => peer.leader === true && (peer.term ?? 1) >= highest && Number.isFinite(peer.time))
56
+ .sort((a, b) => b.time - a.time)[0];
57
+ }
58
+
59
+ export const validTerm = term => Number.isSafeInteger(term) && term > 0;
60
+ export const livePeer = (peer, now) => Number.isFinite(peer?.time) && now - peer.time >= 0 && now - peer.time < 90_000;
61
+ export function highestTerm(root, node = readState(root, "node")) {
62
+ return Math.max(1, readState(root, "election").highest ?? 1, node.term ?? 1,
63
+ ...Object.values(readState(root, "peers")).map(peer => peer.term ?? 1));
64
+ }
65
+ export function leaderDead(root, now) {
66
+ const election = readState(root, "election");
67
+ const times = Object.values(readState(root, "peers")).filter(peer => peer.leader).map(peer => peer.time).filter(Number.isFinite);
68
+ const last = Math.max(election.lastLeaderAt ?? election.started ?? (times.length ? -Infinity : now), ...times);
69
+ return now - last >= 90_000;
70
+ }
71
+ export function leaderCandidate(root, fleet, now) {
72
+ const peers = readState(root, "peers");
73
+ return (fleet.leaders ?? fleet.nodes.map(node => node.id)).find(id => id === fleet.self ||
74
+ (fleet.nodes.some(node => node.id === id && node.active !== false) && livePeer(peers[id], now)));
75
+ }