architecture-harness 0.29.5 → 0.30.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.29.5",
3
+ "version": "0.30.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -0,0 +1,115 @@
1
+ import { execFile } from "node:child_process";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { runCodexImplement } from "./codex-implement.mjs";
6
+
7
+ const execute = promisify(execFile);
8
+ const runGit = (root, ...args) => execute("git", args, { cwd: root, maxBuffer: 4 * 1024 * 1024 });
9
+ const USAGE = "usage: qc codex-loop --dir <run dir> --brief <name> [--rounds <n>] [--from-review <report>] [--skip-implement] [--base <ref>]";
10
+ function parse(argv) {
11
+ const result = { rounds: 4, base: "origin/main" };
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const flag = argv[i];
14
+ if (flag === "--skip-implement") { result.skip = true; continue; }
15
+ const key = { "--dir": "dir", "--brief": "brief", "--rounds": "rounds", "--from-review": "fromReview", "--base": "base" }[flag];
16
+ if (!key || !argv[i + 1] || argv[i + 1].startsWith("--")) throw new Error(USAGE);
17
+ result[key] = argv[++i];
18
+ }
19
+ result.rounds = Number(result.rounds);
20
+ if (!result.dir || !result.brief || path.basename(result.brief) !== result.brief || !Number.isInteger(result.rounds) || result.rounds < 1 || result.rounds > 6 || !/^[A-Za-z0-9._/-]+$/.test(result.base) || result.base.startsWith("-")) throw new Error(USAGE);
21
+ result.dir = path.resolve(result.dir);
22
+ return result;
23
+ }
24
+ const read = file => readFileSync(file, "utf8");
25
+ const field = (text, name) => new RegExp(`^${name}: \x60([^\x60]+)\x60`, "m").exec(text)?.[1];
26
+ function setField(text, name, value) {
27
+ const pattern = new RegExp(`^${name}: .*`, "m"), line = `${name}: \`${value}\``;
28
+ return pattern.test(text) ? text.replace(pattern, () => line) : text.replace(/^## Task/m, () => `${line}\n## Task`);
29
+ }
30
+ function fixBrief(source, dir, name, proof) {
31
+ let text = setField(setField(source, "Report", path.join(dir, `${name}-report.md`)), "Progress", path.join(dir, `${name}-progress.md`));
32
+ text = setField(text.replace(/^Proof: .*\r?\n/gm, ""), "Proof", proof);
33
+ const start = text.indexOf("## Task"), next = text.indexOf("\n## ", start + 1);
34
+ if (start < 0) throw new Error("brief needs ## Task");
35
+ return text.slice(0, start) + "## Task\n\n1. Fix each finding in the review report named on the Proof line. Keep every product decision above.\n- Write each regression test first.\n- A finding that needs a product decision the brief does not give: write it under Questions in the report and fix the rest.\n2. Keep this run under 400 changed lines.\n\n" + (next < 0 ? "" : text.slice(next + 1));
36
+ }
37
+ async function reviewBrief(source, { dir, name, proof, base, worktree, git }) {
38
+ const head = (await git(worktree, "rev-parse", "HEAD")).stdout.trim();
39
+ const issue = /^Issue: `?#?(\d+)`?/m.exec(source)?.[1];
40
+ if (!issue || !/^[a-f0-9]{40}$/i.test(head)) throw new Error("review needs an issue and a commit head");
41
+ let text = source.replace(/^# Brief: /m, "# Brief: review ");
42
+ text = setField(setField(text, "Report", path.join(dir, `${name}-report.md`)), "Progress", path.join(dir, `${name}-progress.md`));
43
+ text = text.replace(/^Verify: .*$/m, "Verify: none").replace(/^Proof: .*\r?\n/gm, "");
44
+ text = setField(text.replace(/^Approved: .*\r?\n/gm, ""), "Proof", proof);
45
+ const start = text.indexOf("## Task");
46
+ if (start < 0) throw new Error("brief needs ## Task");
47
+ text = text.slice(0, start) + `## Task\n\n1. Review the diff \`${base}...${head}\` against issue #${issue} and the decisions above.\n2. Check correctness, security, tenant and record safety, tests that prove each decision, and removed or weakened assertions.\n3. Write each finding with file, line, severity and a concrete failure. Write \`FINDINGS: <n>\` on its own line, then \`VERDICT: APPROVED\` or \`VERDICT: CHANGES_REQUIRED\`, as the report's last block.\n\n## Run shape\n\n1. Edit no file except the report and the progress file. Make no commit and no push.\n2. Read at most 15 files. Use narrow reads and searches.\n3. Never stop to ask: write the question in the report and continue.\n\n## Commit\n\nNone. A review makes no commit and no push.\n\n## Exit criteria\n\n- The report ends with the verdict block.\n- Write the runner's marker as the last line, alone, only when the exit criteria hold.\n`;
48
+ const scope = /^Paths: (.+)$/m.exec(source)?.[1];
49
+ if (scope) {
50
+ const paths = [...scope.matchAll(/`([^`]+)`/g)].map(match => match[1]);
51
+ // Git uses NUL separators so file names with spaces stay intact.
52
+ let files;
53
+ try { files = (await git(worktree, "diff", "--name-only", "-z", `${base}...HEAD`)).stdout.split("\0").filter(Boolean); } catch { files = []; }
54
+ const extra = files.filter(file => !paths.some(p => p === "." || p === "./" || file === p || file.startsWith(p.replace(/\/$/, "") + "/")));
55
+ if (extra.length) text += `\nScope check: outside Paths (diff against ${base}): ${extra.map(file => `\`${file}\``).join(", ")}. The report must give each file a reason and the smallest change; check consumers of a shared part. Report a file without a sound reason as a P1 finding.\n`;
56
+ }
57
+ return text;
58
+ }
59
+
60
+ export async function runCodexLoop(argv, { implement = runCodexImplement, git = runGit, clock = Date.now, warn = console.error } = {}) {
61
+ let options;
62
+ try { options = parse(argv); } catch (error) { warn(error.message); return 2; }
63
+ const { dir, brief, rounds, base, fromReview, skip } = options;
64
+ const note = line => appendFileSync(path.join(dir, "loop.status"), `${line}\n`);
65
+ try {
66
+ mkdirSync(dir, { recursive: true });
67
+ const source = read(path.join(dir, brief)), worktree = field(source, "Worktree");
68
+ if (!worktree) throw new Error("brief needs Worktree");
69
+ const stem = path.parse(brief).name, suffix = stem.split("implement").at(-1) || "";
70
+ async function run(file, name, review = false) {
71
+ for (const ending of ["progress.md", "report.md"]) {
72
+ const stale = path.join(dir, `${name}-${ending}`);
73
+ if (existsSync(stale)) renameSync(stale, path.join(dir, `old-${clock()}-${name}-${ending}`));
74
+ }
75
+ const args = ["--brief", path.join(dir, file), "--worktree", worktree, "--progress", path.join(dir, `${name}-progress.md`), "--log", path.join(dir, `${name}-codex.log`), ...(review ? ["--review", "--report", path.join(dir, `${name}-report.md`)] : ["--role", "implement", "--effort", "high"])];
76
+ const wrapper = path.join(dir, `${name}.wrapper`);
77
+ writeFileSync(wrapper, "");
78
+ const output = line => appendFileSync(wrapper, `${line}\n`);
79
+ return implement(args, { out: output, warn: output, say: output });
80
+ }
81
+ function stop(code, name) {
82
+ if (code === 2) { note(`STOP LIMIT ${name}`); return 2; }
83
+ if (![0, 4, 7].includes(code)) { note(`STOP ${name} exit ${code}`); return 1; }
84
+ return null;
85
+ }
86
+ let current = brief;
87
+ if (!skip && !fromReview) {
88
+ const code = await run(brief, stem); note(`${stem} exit ${code}`);
89
+ const stopped = stop(code, stem); if (stopped !== null) return stopped;
90
+ }
91
+ if (fromReview) {
92
+ const name = `loop-fix${suffix}-0`; current = `${name}.md`;
93
+ writeFileSync(path.join(dir, current), fixBrief(source, dir, name, path.resolve(fromReview)));
94
+ const code = await run(current, name); note(`${name} exit ${code}`);
95
+ const stopped = stop(code, name); if (stopped !== null) return stopped;
96
+ }
97
+ for (let n = 1; n <= rounds; n++) {
98
+ const name = `loop-review${suffix}-${n}`, proof = path.join(dir, `${path.parse(current).name}-report.md`);
99
+ writeFileSync(path.join(dir, `${name}.md`), await reviewBrief(read(path.join(dir, current)), { dir, name, proof, base, worktree, git }));
100
+ const code = await run(`${name}.md`, name, true);
101
+ const report = path.join(dir, `${name}-report.md`);
102
+ const verdict = existsSync(report) ? [...read(report).matchAll(/^VERDICT:\s*(\S+)/gm)].at(-1)?.[1] : null;
103
+ note(`${name} exit ${code} ${verdict ?? "None"}`);
104
+ if (code === 2) { note(`STOP LIMIT ${name}`); return 2; }
105
+ if (code !== 0) { note(`STOP ${name} exit ${code}`); return 1; }
106
+ if (verdict === "APPROVED") { note("DONE APPROVED"); return 0; }
107
+ if (verdict !== "CHANGES_REQUIRED") { note(`STOP ${name} has no verdict`); return 1; }
108
+ const fix = `loop-fix${suffix}-${n}`; current = `${fix}.md`;
109
+ writeFileSync(path.join(dir, current), fixBrief(source, dir, fix, report));
110
+ const fixed = await run(current, fix); note(`${fix} exit ${fixed}`);
111
+ const stopped = stop(fixed, fix); if (stopped !== null) return stopped;
112
+ }
113
+ note(`STOP ${rounds} rounds without approval`); return 1;
114
+ } catch (error) { warn(error.message); note(`STOP ${error.message}`); return 1; }
115
+ }
@@ -0,0 +1,114 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { runCodexLoop } from "./codex-loop.mjs";
7
+
8
+ function setup(t) {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-loop-"));
10
+ t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
11
+ writeFileSync(path.join(dir, "implement.md"), `# Brief: test\nWorktree: \`${dir}\`\nIssue: \`#0\`\nPaths: \`src/\`\nReport: \`${dir}/implement-report.md\`\nProgress: \`${dir}/implement-progress.md\`\nVerify: none\nApproved: \`spec.md\`\n## Task\n1. Work.\n## Commit\nCommit only.\n`);
12
+ return dir;
13
+ }
14
+ for (const mode of ["approve", "fix", "exhaust", "limit", "from-review", "review-limit", "bad-exit"]) {
15
+ test(`codex-loop ${mode} status and exit`, async t => {
16
+ const dir = setup(t), calls = [];
17
+ const result = await runCodexLoop(["--dir", dir, "--brief", "implement.md", "--rounds", "2", "--base", "origin/topic", ...(mode === "from-review" ? ["--from-review", path.join(dir, "prior.md")] : [])], {
18
+ warn: () => {}, git: async (_root, ...args) => ({ stdout: args[0] === "rev-parse" ? "a".repeat(40) : "outside.mjs\0" }),
19
+ implement: async args => {
20
+ calls.push(args);
21
+ if (mode === "limit") return 2;
22
+ if (mode === "bad-exit") return 1;
23
+ if (args.includes("--review")) {
24
+ if (mode === "review-limit") return 2;
25
+ const changes = mode === "exhaust" || (mode === "fix" && calls.length === 2);
26
+ writeFileSync(args[args.indexOf("--report") + 1], `VERDICT: ${changes ? "CHANGES_REQUIRED" : "APPROVED"}\n`);
27
+ }
28
+ return 0;
29
+ },
30
+ });
31
+ const status = readFileSync(path.join(dir, "loop.status"), "utf8");
32
+ assert.equal(result, mode.includes("limit") ? 2 : ["exhaust", "bad-exit"].includes(mode) ? 1 : 0);
33
+ if (mode === "limit") assert.equal(status, "implement exit 2\nSTOP LIMIT implement\n");
34
+ if (mode === "exhaust") assert.match(status, /STOP 2 rounds without approval\n$/);
35
+ if (mode === "bad-exit") assert.match(status, /STOP implement exit 1/);
36
+ if (mode === "fix") assert.match(status, /loop-fix-1 exit 0\nloop-review-2 exit 0 APPROVED\nDONE APPROVED/);
37
+ if (mode === "approve") {
38
+ assert.equal(status, "implement exit 0\nloop-review-1 exit 0 APPROVED\nDONE APPROVED\n");
39
+ const review = readFileSync(path.join(dir, "loop-review-1.md"), "utf8");
40
+ assert.match(review, /origin\/topic\.\.\./);
41
+ assert.match(review, /outside.mjs/);
42
+ assert.match(review, /Make no commit and no push/);
43
+ }
44
+ if (mode === "from-review") {
45
+ assert.match(status, /^loop-fix-0 exit 0/);
46
+ assert.match(readFileSync(path.join(dir, "loop-fix-0.md"), "utf8"), /prior.md/);
47
+ }
48
+ });
49
+ }
50
+ for (const exit of [1, 2, 4, 7, 42]) test(`codex-loop rejects approval when review exits ${exit}`, async t => {
51
+ const dir = setup(t);
52
+ let calls = 0;
53
+ const code = await runCodexLoop(["--dir", dir, "--brief", "implement.md", "--skip-implement"], {
54
+ git: async (_cwd, ...args) => ({ stdout: args[0] === "rev-parse" ? "a".repeat(40) : "" }),
55
+ implement: async args => {
56
+ calls++;
57
+ assert.ok(args.includes("--review"));
58
+ writeFileSync(args[args.indexOf("--report") + 1], "VERDICT: APPROVED\n");
59
+ return exit;
60
+ },
61
+ });
62
+ assert.equal(code, exit === 2 ? 2 : 1);
63
+ assert.equal(calls, 1);
64
+ assert.equal(readFileSync(path.join(dir, "loop.status"), "utf8"),
65
+ `loop-review-1 exit ${exit} APPROVED\n${exit === 2 ? "STOP LIMIT loop-review-1" : `STOP loop-review-1 exit ${exit}`}\n`);
66
+ });
67
+ for (const mode of ["fix", "from-review"]) test(`codex-loop ${mode} links proof without approval metadata`, async t => {
68
+ const dir = setup(t), briefs = new Map();
69
+ const source = path.join(dir, "implement.md"), prior = path.join(dir, "prior.md");
70
+ writeFileSync(source, readFileSync(source, "utf8").replace(/^Approved: .*\n/m, ""));
71
+ const code = await runCodexLoop(["--dir", dir, "--brief", "implement.md",
72
+ ...(mode === "from-review" ? ["--from-review", prior] : [])], {
73
+ git: async (_cwd, ...args) => ({ stdout: args[0] === "rev-parse" ? "a".repeat(40) : "" }),
74
+ implement: async args => {
75
+ const file = args[args.indexOf("--brief") + 1], name = path.basename(file);
76
+ briefs.set(name, readFileSync(file, "utf8"));
77
+ if (args.includes("--review")) writeFileSync(args[args.indexOf("--report") + 1],
78
+ `VERDICT: ${mode === "fix" && name === "loop-review-1.md" ? "CHANGES_REQUIRED" : "APPROVED"}\n`);
79
+ return 0;
80
+ },
81
+ });
82
+ assert.equal(code, 0);
83
+ const links = mode === "fix"
84
+ ? [["loop-review-1", "implement-report.md"], ["loop-fix-1", "loop-review-1-report.md"], ["loop-review-2", "loop-fix-1-report.md"]]
85
+ : [["loop-fix-0", "prior.md"], ["loop-review-1", "loop-fix-0-report.md"]];
86
+ for (const [name, proof] of links) {
87
+ const text = briefs.get(`${name}.md`);
88
+ assert.equal(text.match(/^Proof: .*$/gm)?.length, 1, `${name} needs one Proof line`);
89
+ assert.ok(text.includes(`Proof: \`${path.join(dir, proof)}\``), name);
90
+ assert.doesNotMatch(text, /^Approved:/m);
91
+ }
92
+ });
93
+ test("codex-loop invalid arguments exit 2", async () => {
94
+ assert.equal(await runCodexLoop(["--rounds", "0"], { warn: () => {} }), 2);
95
+ });
96
+ test("skip implement archives stale proof and keeps wrapper output; review defaults to origin/main", async t => {
97
+ const dir = setup(t);
98
+ writeFileSync(path.join(dir, "loop-review-1-report.md"), "VERDICT: APPROVED\n");
99
+ writeFileSync(path.join(dir, "loop-review-1-progress.md"), "stale progress\n");
100
+ let calls = 0;
101
+ const code = await runCodexLoop(["--dir", dir, "--brief", "implement.md", "--skip-implement"], {
102
+ clock: () => 123, git: async (_cwd, ...args) => ({ stdout: args[0] === "rev-parse" ? "a".repeat(40) : "" }),
103
+ implement: async (args, options) => {
104
+ calls++; assert.ok(args.includes("--review"));
105
+ assert.equal(readFileSync(path.join(dir, "old-123-loop-review-1-report.md"), "utf8"), "VERDICT: APPROVED\n");
106
+ options.say("review output");
107
+ writeFileSync(args[args.indexOf("--report") + 1], "VERDICT: APPROVED\n");
108
+ return 0;
109
+ },
110
+ });
111
+ assert.equal(code, 0); assert.equal(calls, 1);
112
+ assert.equal(readFileSync(path.join(dir, "loop-review-1.wrapper"), "utf8"), "review output\n");
113
+ assert.match(readFileSync(path.join(dir, "loop-review-1.md"), "utf8"), /origin\/main\.\.\./);
114
+ });
@@ -0,0 +1,123 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { overloaded } from "./fleet-assign.mjs";
4
+ import { liveJob, redactJobText, tailLines, validJob, validJobId } from "./fleet-jobs.mjs";
5
+ import { createMessage } from "./fleet-message.mjs";
6
+ import { flushOutbox } from "./fleet-node.mjs";
7
+ import { validPlatformBranch } from "./fleet-platform.mjs";
8
+ import { highestTerm, livePeer, readState, writeState } from "./fleet-state.mjs";
9
+
10
+ export const DISPATCH_VERBS = ["job", "jobs", "cancel"];
11
+ export function parseDispatchArgs(verb, args) {
12
+ if (verb === "jobs" && args.length === 0) return { verb };
13
+ if (verb === "cancel" && args.length === 1 && validJobId(args[0])) return { verb, id: args[0] };
14
+ if (verb !== "job") throw new Error(`${verb} needs ${verb === "cancel" ? "a job id" : "no arguments"}`);
15
+ const options = { verb };
16
+ for (let i = 0; i < args.length; i++) {
17
+ const flag = args[i];
18
+ if (!["--brief", "--branch", "--base", "--rounds", "--node", "--id"].includes(flag) || Object.hasOwn(options, flag)) throw new Error(`invalid or duplicate argument ${flag}`);
19
+ if (!args[i + 1] || args[i + 1].startsWith("--")) throw new Error(`${flag} needs a value`);
20
+ options[flag] = args[++i];
21
+ }
22
+ if (!options["--brief"] || !validPlatformBranch(options["--branch"]) || !validPlatformBranch(options["--base"])) throw new Error("job needs --brief, --branch and --base");
23
+ const rounds = Number(options["--rounds"] ?? 3);
24
+ if (!Number.isInteger(rounds) || rounds < 1 || rounds > 6) throw new Error("--rounds must be from 1 to 6");
25
+ if (options["--id"] !== undefined && !validJobId(options["--id"])) throw new Error("invalid job id");
26
+ if (options["--node"] !== undefined && !/^[a-z0-9-]{1,32}$/.test(options["--node"])) throw new Error("invalid node id");
27
+ return options;
28
+ }
29
+ function requireLeader(root) {
30
+ const node = readState(root, "node");
31
+ if (node.leader !== true || (node.term ?? 1) < highestTerm(root)) throw new Error("only the current leader can send jobs or cancel them");
32
+ }
33
+ const pendingJob = row => row.state === "queued" || liveJob(row);
34
+ export function pickJobNode({ fleet, peers, now, node, jobs = {} }) {
35
+ const candidates = fleet.nodes.filter(row => {
36
+ const peer = peers[row.id], slots = peer?.jobs;
37
+ const pending = Object.values(jobs).filter(job => job.node === row.id && pendingJob(job)).length;
38
+ return (!node || row.id === node) && row.active !== false && row.address && livePeer(peer, now) &&
39
+ slots && Number.isSafeInteger(slots.max) && slots.max > 0 && Number.isSafeInteger(slots.live) && slots.live >= 0 &&
40
+ slots.max > Math.max(slots.live, pending) && Number.isFinite(slots.limitedUntil) && now >= slots.limitedUntil && !overloaded(peer.load).length;
41
+ }).sort((a, b) => {
42
+ const free = id => peers[id].jobs.max - Math.max(peers[id].jobs.live, Object.values(jobs).filter(job => job.node === id && pendingJob(job)).length);
43
+ return free(b.id) - free(a.id) || a.id.localeCompare(b.id);
44
+ });
45
+ if (!candidates.length) throw new Error("no live node with available job slots");
46
+ return candidates[0];
47
+ }
48
+ async function queueMessage(context, target, kind, body) {
49
+ const { root, fleet, repo, clock = Date.now, fetch, signal } = context;
50
+ requireLeader(root);
51
+ const message = createMessage({ from: fleet.self, repo, kind, body, time: new Date(clock()).toISOString() }, fleet.secret);
52
+ writeState(root, "outbox", [...readState(root, "outbox"), { node: target, message, attempts: 0, nextAttempt: 0 }]);
53
+ await flushOutbox({ root, fleet, fetch, clock, signal });
54
+ }
55
+ export async function runDispatch(options, context) {
56
+ const { root, fleet, repo, clock = Date.now, say = console.log } = context;
57
+ if (options.verb === "jobs") {
58
+ const peers = readState(root, "peers");
59
+ for (const row of Object.values(readState(root, "jobs"))) {
60
+ const step = peers[row.node]?.jobs?.steps?.find(step => step.id === row.id)?.step ?? row.step ?? "-";
61
+ say(redactJobText(`${row.id} ${row.node} ${row.state} ${row.branch} ${step} ${Math.max(0, Math.floor((clock() - row.created) / 1000))}s`, fleet.secret));
62
+ }
63
+ return 0;
64
+ }
65
+ requireLeader(root);
66
+ const jobs = readState(root, "jobs");
67
+ if (options.verb === "cancel") {
68
+ const row = jobs[options.id];
69
+ if (!row || row.repo !== repo) throw new Error("unknown job id");
70
+ await queueMessage(context, row.node, "codex-cancel", { id: row.id });
71
+ say(`cancel ${row.id}`); return 0;
72
+ }
73
+ const branch = options["--branch"], base = options["--base"], brief = readFileSync(options["--brief"], "utf8");
74
+ const slug = branch.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 35) || "job";
75
+ const id = options["--id"] ?? `${slug}-${randomBytes(2).toString("hex")}`;
76
+ const body = { id, branch, base, brief, rounds: Number(options["--rounds"] ?? 3) };
77
+ if (!validJob(body)) throw new Error("invalid job body or brief over 64 KiB");
78
+ if (redactJobText(JSON.stringify(body), fleet.secret) !== JSON.stringify(body)) throw new Error("job contains fleet secret");
79
+ if (Object.hasOwn(jobs, id)) throw new Error("job id already known");
80
+ const node = pickJobNode({ fleet, peers: readState(root, "peers"), now: clock(), jobs, node: options["--node"] });
81
+ jobs[id] = { id, node: node.id, repo, branch, base, state: "queued", created: clock(), time: clock(), step: "-" };
82
+ writeState(root, "jobs", jobs);
83
+ await queueMessage(context, node.id, "codex-job", body);
84
+ say(`job ${id} ${node.id} ${branch}`); return 0;
85
+ }
86
+ function event(root, row, state, head, now) {
87
+ writeState(root, "inbox", [...readState(root, "inbox"), { id: randomUUID(), kind: "codex-result", repo: row.repo,
88
+ time: new Date(now).toISOString(), detail: `${row.id} ${state} ${row.branch} ${head ?? "-"}` }]);
89
+ }
90
+ const states = ["started", "refused", "approved", "limit", "stopped", "failed", "cancelled"];
91
+ function validResult(body, row) {
92
+ return body && states.includes(body.state) && (body.branch === undefined || body.branch === row.branch) &&
93
+ (body.state !== "approved" || (body.branch === row.branch && /^[a-f0-9]{40}$/i.test(body.head ?? ""))) &&
94
+ (body.head === undefined || (typeof body.head === "string" && /^[a-f0-9]{40}$/i.test(body.head))) &&
95
+ ["reason", "status"].every(key => body[key] === undefined || (typeof body[key] === "string" && Buffer.byteLength(JSON.stringify(body[key])) <= 48_000)) &&
96
+ Object.keys(body).every(key => ["id", "state", "branch", "head", "reason", "status"].includes(key));
97
+ }
98
+ /** The leader owns state and watch events; only the saved worker can change a job. */
99
+ export function dispatchTick({ root, fleet, clock = Date.now }) {
100
+ const node = readState(root, "node");
101
+ if (node.leader !== true || (node.term ?? 1) < highestTerm(root)) return;
102
+ const jobs = readState(root, "jobs"), peers = readState(root, "peers"), queue = readState(root, "queue");
103
+ const messages = queue.filter(row => row.kind === "codex-result");
104
+ if (messages.length) writeState(root, "queue", queue.filter(row => row.kind !== "codex-result"));
105
+ let changed = false;
106
+ for (const message of messages) {
107
+ const row = jobs[message.body?.id], body = message.body;
108
+ if (!row || row.node !== message.from || row.repo !== message.repo || !validResult(body, row)) continue;
109
+ // A late started result must not undo a final result or a lost-node decision.
110
+ if (body.state === "started" && !["queued", "starting"].includes(row.state)) continue;
111
+ if (body.state === row.state) continue;
112
+ const status = body.status === undefined ? row.status : tailLines(body.status, fleet.secret);
113
+ Object.assign(row, { state: body.state, time: clock(), ...(body.head ? { head: body.head } : {}),
114
+ ...(status === undefined ? {} : { status, step: status.split("\n").at(-1).slice(0, 120) }),
115
+ ...(body.reason === undefined ? {} : { reason: tailLines(body.reason, fleet.secret) }) });
116
+ event(root, row, row.state, row.head, clock()); changed = true;
117
+ }
118
+ for (const row of Object.values(jobs)) {
119
+ if (!pendingJob(row) || livePeer(peers[row.node] ?? { time: row.created }, clock())) continue;
120
+ row.state = "lost"; row.time = clock(); event(root, row, "lost", row.head, clock()); changed = true;
121
+ }
122
+ if (changed) writeState(root, "jobs", jobs);
123
+ }
@@ -0,0 +1,98 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { dispatchTick, parseDispatchArgs, pickJobNode, runDispatch } from "./fleet-dispatch.mjs";
7
+ import { runWatch } from "./watch.mjs";
8
+ import { readState, writeState } from "./fleet-state.mjs";
9
+
10
+ const now = 100000, head = "a".repeat(40);
11
+ function fixture(t) {
12
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-"));
13
+ mkdirSync(path.join(root, ".git"));
14
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
15
+ const fleet = { self: "a", secret: "ab".repeat(32), nodes: ["a", "b", "c", "dead", "full", "limited", "hot", "off", "no-address"].map(id => ({ id, address: "localhost", port: 8080, active: id !== "off" })) };
16
+ delete fleet.nodes.at(-1).address;
17
+ const peer = (max, live = 0, extra = {}) => ({ time: now, load: { cpu: 0.2, mem: 0.2, rtt: 10 }, jobs: { max, live, limitedUntil: 0, steps: [] }, ...extra });
18
+ const peers = { a: peer(2), b: peer(6, 1), c: peer(6, 1), dead: peer(20, 0, { time: now - 90000 }), full: peer(2, 2), limited: peer(20, 0), hot: peer(20, 0, { load: { cpu: 0.9 } }), off: peer(20), "no-address": peer(20) };
19
+ peers.limited.jobs.limitedUntil = now + 1;
20
+ writeState(root, "node", { leader: true, term: 1 }); writeState(root, "peers", peers);
21
+ const brief = path.join(root, "brief.md"); writeFileSync(brief, "Worktree: `old`\n");
22
+ const sent = [], lines = [];
23
+ const deps = { root, fleet, repo: "o/r", clock: () => now, say: line => lines.push(line), fetch: async (_url, options) => { sent.push(JSON.parse(options.body)); return { status: 202 }; } };
24
+ const args = ["--brief", brief, "--branch", "feat/worker", "--base", "main"];
25
+ const queue = (body, from = "b", repo = "o/r") => writeState(root, "queue", [...readState(root, "queue"), { id: String(Math.random()), kind: "codex-result", from, repo, body }]);
26
+ return { root, fleet, peers, brief, sent, lines, deps, args, queue };
27
+ }
28
+ test("node pick uses free slots, load, limits, live status and id; leader can work", t => {
29
+ const f = fixture(t);
30
+ assert.equal(pickJobNode({ fleet: f.fleet, peers: f.peers, now }).id, "b");
31
+ f.peers.c.jobs.live = 0;
32
+ assert.equal(pickJobNode({ fleet: f.fleet, peers: f.peers, now }).id, "c");
33
+ for (const id of ["b", "c"]) f.peers[id].jobs.max = 0;
34
+ assert.equal(pickJobNode({ fleet: f.fleet, peers: f.peers, now }).id, "a");
35
+ assert.throws(() => pickJobNode({ fleet: f.fleet, peers: f.peers, now, node: "dead" }), /live|available/);
36
+ });
37
+ test("job and cancel require current leader; malformed arguments fail", async t => {
38
+ const f = fixture(t);
39
+ writeState(f.root, "node", { leader: false });
40
+ await assert.rejects(runDispatch(parseDispatchArgs("job", f.args), f.deps), /leader/i);
41
+ await assert.rejects(runDispatch(parseDispatchArgs("cancel", ["job"]), f.deps), /leader/i);
42
+ assert.equal(f.sent.length, 0);
43
+ for (const args of [[], [...f.args, "--rounds", "7"], [...f.args, "--id", "../bad"], [...f.args, "--node", "b", "--node", "c"]]) assert.throws(() => parseDispatchArgs("job", args));
44
+ });
45
+ test("dispatch queues job, stores row, prints state and sends cancel to saved node", async t => {
46
+ const f = fixture(t);
47
+ assert.equal(await runDispatch(parseDispatchArgs("job", f.args), f.deps), 0);
48
+ const row = Object.values(readState(f.root, "jobs"))[0];
49
+ assert.match(row.id, /^feat-worker-[0-9a-f]{4}$/); assert.equal(row.node, "b");
50
+ assert.equal(f.sent[0].kind, "codex-job"); assert.equal(f.sent[0].body.rounds, 3);
51
+ assert.equal(readState(f.root, "outbox").length, 0);
52
+ await runDispatch(parseDispatchArgs("jobs", []), f.deps);
53
+ assert.match(f.lines.at(-1), new RegExp(`${row.id} b queued feat/worker - 0s`));
54
+ await runDispatch(parseDispatchArgs("cancel", [row.id]), f.deps);
55
+ assert.deepEqual(f.sent.at(-1).body, { id: row.id }); assert.equal(f.sent.at(-1).kind, "codex-cancel");
56
+ await assert.rejects(runDispatch(parseDispatchArgs("job", [...f.args, "--id", row.id]), f.deps), /known/);
57
+ });
58
+ test("transport failure keeps dispatch in durable outbox; leader demotion blocks retry", async t => {
59
+ const f = fixture(t);
60
+ await runDispatch(parseDispatchArgs("job", f.args), { ...f.deps, fetch: async () => { throw new Error("offline"); } });
61
+ assert.equal(readState(f.root, "outbox").length, 1);
62
+ writeState(f.root, "node", { leader: false, term: 2 });
63
+ const { flushOutbox } = await import("./fleet-node.mjs");
64
+ await flushOutbox(f.deps);
65
+ assert.equal(f.sent.length, 0); assert.equal(readState(f.root, "outbox").length, 0);
66
+ });
67
+ test("result validates node, repo and fields; watch receives each event once; lost is emitted once", async t => {
68
+ const f = fixture(t);
69
+ await runDispatch(parseDispatchArgs("job", [...f.args, "--id", "job"]), f.deps);
70
+ f.queue({ id: "job", state: "approved", branch: "feat/worker", head }, "c");
71
+ f.queue({ id: "job", state: "approved", branch: "feat/worker", head }, "b", "other/repo");
72
+ f.queue({ id: "job", state: "approved", branch: "wrong", head });
73
+ f.queue({ id: "job", state: "approved", branch: "feat/worker", head: "no" });
74
+ dispatchTick(f.deps);
75
+ assert.equal(readState(f.root, "jobs").job.state, "queued");
76
+ f.queue({ id: "job", state: "started", branch: "feat/worker" }); dispatchTick(f.deps);
77
+ const events = [];
78
+ assert.equal(await runWatch(["--fleet"], { cwd: f.root, say: line => events.push(line) }), 0);
79
+ assert.deepEqual(events, ["EVENT fleet:codex-result job started feat/worker -"]);
80
+ const peers = readState(f.root, "peers"); peers.b.jobs.steps = [{ id: "job", step: "loop-review-1 exit 0 APPROVED" }]; writeState(f.root, "peers", peers);
81
+ await runDispatch(parseDispatchArgs("jobs", []), f.deps); assert.match(f.lines.at(-1), /loop-review-1 exit 0 APPROVED/);
82
+ dispatchTick({ ...f.deps, clock: () => now + 90000 }); dispatchTick({ ...f.deps, clock: () => now + 90001 });
83
+ assert.equal(readState(f.root, "jobs").job.state, "lost");
84
+ assert.equal(readState(f.root, "inbox").filter(row => row.detail?.includes(" lost ")).length, 1);
85
+ assert.equal(await runWatch(["--fleet"], { cwd: f.root, say: line => events.push(line) }), 0);
86
+ assert.equal(events.at(-1), "EVENT fleet:codex-result job lost feat/worker -");
87
+ f.queue({ id: "job", state: "approved", branch: "feat/worker", head, status: "DONE APPROVED" }); dispatchTick(f.deps);
88
+ assert.equal(readState(f.root, "jobs").job.state, "approved");
89
+ assert.equal(await runWatch(["--fleet"], { cwd: f.root, say: line => events.push(line) }), 0);
90
+ assert.equal(events.at(-1), `EVENT fleet:codex-result job approved feat/worker ${head}`);
91
+ });
92
+ test("dispatch never sends fleet secret in brief and detects folder read error", async t => {
93
+ const f = fixture(t);
94
+ writeFileSync(f.brief, f.fleet.secret);
95
+ await assert.rejects(runDispatch(parseDispatchArgs("job", f.args), f.deps), /secret/);
96
+ await assert.rejects(runDispatch(parseDispatchArgs("job", ["--brief", f.root, "--branch", "feat/x", "--base", "main"]), f.deps), /EISDIR|EPERM|EACCES/);
97
+ assert.equal(f.sent.length, 0);
98
+ });
@@ -13,7 +13,13 @@ const validLoad = load => load !== null && typeof load === "object" && !Array.is
13
13
  load[key] === null || (Number.isFinite(load[key]) && load[key] >= 0 && load[key] <= limit)) &&
14
14
  (load.platform === undefined || (typeof load.platform === "string" && load.platform.length > 0)) &&
15
15
  Object.keys(load).every(key => ["platform", "cpu", "mem", "rtt"].includes(key));
16
+ const validJobs = jobs => jobs && typeof jobs === "object" && !Array.isArray(jobs) &&
17
+ [jobs.max, jobs.live, jobs.limitedUntil].every(value => Number.isSafeInteger(value) && value >= 0) &&
18
+ Object.keys(jobs).every(key => ["max", "live", "limitedUntil", "steps"].includes(key)) && Array.isArray(jobs.steps) &&
19
+ jobs.steps.length === jobs.live && jobs.steps.every(row => row && /^[a-z0-9][a-z0-9-]{0,39}$/.test(row.id) &&
20
+ typeof row.step === "string" && row.step.length <= 120 && Object.keys(row).every(key => ["id", "step"].includes(key)));
16
21
  const validHeartbeat = body => validTerm(body.term) && typeof body.leader === "boolean" && (body.kit === null || typeof body.kit === "string") &&
22
+ (body.jobs === undefined || validJobs(body.jobs)) &&
17
23
  (body.load === undefined || validLoad(body.load)) &&
18
24
  (body.work === undefined || (Array.isArray(body.work) && body.work.every(validWork))) &&
19
25
  (body.assigned === undefined || (Array.isArray(body.assigned) && body.assigned.every(assignmentRef)));
@@ -53,6 +59,7 @@ export function receiveMessage({ root, fleet, message, clock = Date.now }) {
53
59
  ...(message.body.load === undefined ? {} : { load: message.body.load }),
54
60
  ...(message.body.os === undefined ? {} : { os: message.body.os }),
55
61
  ...(message.body.work === undefined ? {} : { work: message.body.work }),
62
+ ...(message.body.jobs === undefined ? {} : { jobs: message.body.jobs }),
56
63
  ...(message.body.assigned === undefined ? {} : { assigned: message.body.assigned }) }, enumerable: true, configurable: true, writable: true });
57
64
  for (const peer of Object.values(peers)) if ((peer.term ?? 1) < highest) peer.leader = false;
58
65
  writeState(root, "peers", peers);