architecture-harness 0.28.0 → 0.29.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.
@@ -22,6 +22,10 @@ function fixture(t, { checkout = true, checkoutName = "project" } = {}) {
22
22
  const nodeFile = path.join(cwd, ".git", "qc", "fleet", "node.json");
23
23
  return {
24
24
  fleet, cwd, root, home,
25
+ pairing(value) {
26
+ mkdirSync(path.dirname(nodeFile), { recursive: true });
27
+ writeFileSync(path.join(path.dirname(nodeFile), "pairing.json"), JSON.stringify(value));
28
+ },
25
29
  node(value) {
26
30
  mkdirSync(path.dirname(nodeFile), { recursive: true });
27
31
  writeFileSync(nodeFile, JSON.stringify(value));
@@ -80,6 +84,78 @@ test("marks a live leader", t => {
80
84
  assert.match(f.run(), /fleet dev-1 leader /);
81
85
  });
82
86
 
87
+ test("shows a pending join request for a fleet with a secret", t => {
88
+ const f = fixture(t);
89
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1", secret: "test-secret" }));
90
+ f.pairing({ requests: { "dev-2": { code: "012345", seen: Date.now(), allowed: false } } });
91
+ assert.match(f.run(), /fleet dev-1 off join\? dev-2 012345 /);
92
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1" }));
93
+ assert.doesNotMatch(f.run(), /join\?/);
94
+ });
95
+
96
+ test("shows the newest request and counts the other pending requests", t => {
97
+ const f = fixture(t);
98
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1", secret: "test-secret" }));
99
+ f.pairing({ requests: {
100
+ "dev-2": { code: "123456", seen: Date.now() - 1000 },
101
+ "dev-3": { code: "234567", seen: Date.now() },
102
+ } });
103
+ assert.match(f.run(), /join\? dev-3 234567 \+1 /);
104
+ });
105
+
106
+ test("omits allowed join requests", t => {
107
+ const f = fixture(t);
108
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1", secret: "test-secret" }));
109
+ f.pairing({ requests: { "dev-2": { code: "123456", seen: Date.now(), allowed: true } } });
110
+ assert.doesNotMatch(f.run(), /join\?/);
111
+ });
112
+
113
+ test("omits pairing entries older than ten minutes", t => {
114
+ const f = fixture(t);
115
+ for (const secret of ["test-secret", undefined]) {
116
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1", secret }));
117
+ const entry = { code: "123456", seen: Date.now() - 600001 };
118
+ f.pairing({ requests: { "dev-2": entry }, offers: { "dev-3": entry } });
119
+ assert.doesNotMatch(f.run(), /join\?|joining/);
120
+ }
121
+ });
122
+
123
+ test("shows the newest pending offer for a fleet without a secret", t => {
124
+ const f = fixture(t);
125
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1" }));
126
+ f.pairing({ offers: {
127
+ "dev-2": { code: "123456", seen: Date.now() - 1000, accepted: false },
128
+ "dev-3": { code: "012345", seen: Date.now(), accepted: false },
129
+ } });
130
+ assert.match(f.run(), /fleet dev-1 off joining dev-3 012345 /);
131
+ assert.doesNotMatch(f.run(), /\+1/);
132
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1", secret: "test-secret" }));
133
+ assert.doesNotMatch(f.run(), /joining/);
134
+ });
135
+
136
+ test("omits accepted offers", t => {
137
+ const f = fixture(t);
138
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1" }));
139
+ f.pairing({ offers: { "dev-2": { code: "123456", seen: Date.now(), accepted: true } } });
140
+ assert.doesNotMatch(f.run(), /joining/);
141
+ });
142
+
143
+ test("silently ignores missing, malformed, and invalid pairing files", t => {
144
+ const f = fixture(t);
145
+ writeFileSync(f.fleet, JSON.stringify({ self: "dev-1", secret: "test-secret" }));
146
+ assert.match(f.run(), /fleet dev-1 off /);
147
+ f.pairing(null);
148
+ const pairingFile = path.join(f.cwd, ".git", "qc", "fleet", "pairing.json");
149
+ for (const value of ["{", "null", "{}", '{"requests":null}', '{"requests":{"dev-2":null}}']) {
150
+ writeFileSync(pairingFile, value);
151
+ assert.match(f.run(), /fleet dev-1 off /);
152
+ }
153
+ rmSync(pairingFile);
154
+ mkdirSync(pairingFile);
155
+ assert.throws(() => readFileSync(pairingFile, "utf8"), /EISDIR|EPERM|EACCES/);
156
+ assert.match(f.run(), /fleet dev-1 off /);
157
+ });
158
+
83
159
  test("marks a live leader in a checkout whose path contains a newline", { skip: process.platform === "win32" }, t => {
84
160
  const f = fixture(t, { checkoutName: "project\ncheckout" });
85
161
  writeFileSync(f.fleet, JSON.stringify({ self: "dev-1" }));
package/src/cli/watch.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  // `qc watch`: block until the first event among the pull requests, Codex jobs and workflow runs it watches.
2
2
  // The wait is a shell command, so it costs no model tokens, and its exit is the event.
3
3
 
4
- import { readState, writeState } from "./fleet-state.mjs";
5
- import { closeSync, fstatSync, openSync, readSync } from "node:fs";
4
+ import { readState, stateDir, writeState } from "./fleet-state.mjs";
5
+ import { closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { parseApiList, runGhResult } from "./gh-run.mjs";
8
8
  import { checkVerdict, pendingCiReason } from "./check-verdict.mjs";
@@ -143,6 +143,29 @@ function codexWatcher(file) {
143
143
  };
144
144
  }
145
145
 
146
+ function pairingMessages(cwd, leader, at) {
147
+ let pairing;
148
+ try {
149
+ pairing = JSON.parse(readFileSync(path.join(stateDir(cwd), "pairing.json"), "utf8"));
150
+ } catch {
151
+ return [];
152
+ }
153
+ if (!pairing || typeof pairing !== "object" || Array.isArray(pairing)) return [];
154
+ const messages = [];
155
+ for (const [collection, kind, flag] of [
156
+ [leader ? pairing.requests : {}, "join-request", "allowed"],
157
+ [pairing.offers, "join-offer", "accepted"],
158
+ ]) {
159
+ if (!collection || typeof collection !== "object" || Array.isArray(collection)) continue;
160
+ for (const [id, entry] of Object.entries(collection)) {
161
+ if (!entry || entry[flag] || !Number.isFinite(entry.seen) || at - entry.seen > 600_000 ||
162
+ typeof entry.code !== "string" || entry.code.length !== 6 || !/^\d{6}$/.test(entry.code)) continue;
163
+ messages.push({ id: JSON.stringify([kind, id, entry.code]), kind, detail: `${id} ${entry.code}` });
164
+ }
165
+ }
166
+ return messages;
167
+ }
168
+
146
169
  /**
147
170
  * Watches one workflow on one branch. Only a run of the armed head counts: the head the branch has at each poll,
148
171
  * or the one that `@<sha>` pins. A run of an earlier head never fires.
@@ -227,9 +250,11 @@ export async function runWatch(argv, { gh = readGh, say = console.log, warn = co
227
250
  if (parsed.fleet) {
228
251
  try {
229
252
  const watched = readState(cwd, "watched");
230
- const messages = readState(cwd, "node").leader === true
253
+ const leader = readState(cwd, "node").leader === true;
254
+ const messages = leader
231
255
  ? readState(cwd, "queue").filter(message => ["plan", "question"].includes(message.kind))
232
256
  : readState(cwd, "inbox");
257
+ messages.push(...pairingMessages(cwd, leader, now()));
233
258
  const proposal = readState(cwd, "proposal");
234
259
  if (Number.isSafeInteger(proposal.term) && proposal.term > 0) {
235
260
  messages.push({ id: `propose-leader:${proposal.term}`, kind: "propose-leader", term: proposal.term });
@@ -239,7 +264,7 @@ export async function runWatch(argv, { gh = readGh, say = console.log, warn = co
239
264
  for (const message of fresh) {
240
265
  if (Object.hasOwn(watched, message.id)) continue;
241
266
  Object.defineProperty(watched, message.id, { value: true, enumerable: true, configurable: true });
242
- say(`EVENT fleet:${message.kind} ${message.term ?? message.id}`);
267
+ say(`EVENT fleet:${message.kind} ${message.detail ?? message.term ?? message.id}`);
243
268
  }
244
269
  writeState(cwd, "watched", watched);
245
270
  return EXIT.PASSED;
@@ -556,3 +556,111 @@ test("fleet watch announces each proposed Leader term once", async t => {
556
556
  assert.equal(await runWatch(["--fleet"], { cwd: root, say: text => lines.push(text), sleep: async () => { throw new Error("proposal event missing"); } }), 0);
557
557
  assert.deepEqual(lines, ["EVENT fleet:propose-leader 2", "EVENT fleet:propose-leader 3"]);
558
558
  });
559
+
560
+ for (const [label, contents] of [
561
+ ["truncated JSON", '{"requests":'],
562
+ ["null", "null"],
563
+ ["an array", "[]"],
564
+ ["primitive collections", '{"requests":42,"offers":"bad"}'],
565
+ ["array collections", JSON.stringify({ requests: [{ code: "123456", seen: 0 }], offers: [{ code: "654321", seen: 0 }] })],
566
+ ]) {
567
+ test(`fleet watch skips ${label} in pairing.json and reports queued questions`, async t => {
568
+ const { stateDir, writeState } = await import("./fleet-state.mjs");
569
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-bad-pairing-"));
570
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
571
+ mkdirSync(path.join(root, ".git"));
572
+ writeState(root, "node", { leader: true });
573
+ writeState(root, "queue", [{ id: "question", kind: "question" }]);
574
+ writeFileSync(path.join(stateDir(root), "pairing.json"), contents);
575
+ const result = await watch(["--fleet", "--max", "1"], { cwd: root, time: fakeClock(), requiredChecks: [] });
576
+ assert.equal(result.code, 0);
577
+ assert.deepEqual(result.lines, ["EVENT fleet:question question"]);
578
+ });
579
+ }
580
+
581
+ test("fleet watch skips a pairing.json read error and reports queued questions", async t => {
582
+ const { stateDir, writeState } = await import("./fleet-state.mjs");
583
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-pairing-read-error-"));
584
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
585
+ mkdirSync(path.join(root, ".git"));
586
+ writeState(root, "node", { leader: true });
587
+ writeState(root, "queue", [{ id: "question", kind: "question" }]);
588
+ const pairingFile = path.join(stateDir(root), "pairing.json");
589
+ mkdirSync(pairingFile);
590
+ assert.throws(() => readFileSync(pairingFile, "utf8"), /EISDIR|EPERM|EACCES/);
591
+ const result = await watch(["--fleet", "--max", "1"], { cwd: root, time: fakeClock(), requiredChecks: [] });
592
+ assert.equal(result.code, 0);
593
+ assert.deepEqual(result.lines, ["EVENT fleet:question question"]);
594
+ });
595
+
596
+ for (const [kind, collection, flag, leader] of [
597
+ ["join-request", "requests", "allowed", true],
598
+ ["join-offer", "offers", "accepted", false],
599
+ ]) {
600
+ test(`fleet ${kind} reports each ID and code once across watcher restarts`, async t => {
601
+ const { readState, stateDir, writeState } = await import("./fleet-state.mjs");
602
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-pairing-"));
603
+ mkdirSync(path.join(root, ".git"));
604
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
605
+ writeState(root, "node", { leader });
606
+ const time = fakeClock();
607
+ time.clock.now = 1_000_000;
608
+ const pairingFile = path.join(stateDir(root), "pairing.json");
609
+ const entry = { code: "012345", address: "192.0.2.1", port: 8080, hostname: "new-pc", os: "linux", seen: time.now(), [flag]: false };
610
+ const save = entries => writeFileSync(pairingFile, JSON.stringify({ requests: {}, offers: {}, [collection]: entries }));
611
+ save({ pc: entry, other: { ...entry, code: "654321", seen: time.now() - 600_000 } });
612
+ const deps = { cwd: root, ...time, requiredChecks: [], gh: () => { throw new Error("unexpected gh"); } };
613
+ const run = () => watch(["--fleet", "--max", "1"], { ...deps, time });
614
+ assert.deepEqual((await run()).lines, [`EVENT fleet:${kind} pc 012345`, `EVENT fleet:${kind} other 654321`]);
615
+ assert.equal(Object.keys(readState(root, "watched")).length, 2);
616
+ assert.deepEqual((await run()).lines, ["EVENT timeout"]);
617
+ save({ pc: { ...entry, code: "234567", seen: time.now() } });
618
+ assert.deepEqual((await run()).lines, [`EVENT fleet:${kind} pc 234567`]);
619
+ assert.equal(Object.keys(readState(root, "watched")).length, 3);
620
+ });
621
+
622
+ test(`fleet ${kind} ignores old, flagged, and malformed entries`, async t => {
623
+ const { stateDir, writeState } = await import("./fleet-state.mjs");
624
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-pairing-ignore-"));
625
+ mkdirSync(path.join(root, ".git"));
626
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
627
+ writeState(root, "node", { leader });
628
+ const time = fakeClock();
629
+ time.clock.now = 1_000_000;
630
+ const entry = { code: "012345", seen: time.now(), [flag]: false };
631
+ writeFileSync(path.join(stateDir(root), "pairing.json"), JSON.stringify({ [collection]: {
632
+ old: { ...entry, seen: time.now() - 600_001 },
633
+ flagged: { ...entry, [flag]: true },
634
+ missingTime: { code: "123456" },
635
+ badTime: { ...entry, seen: "1000000" },
636
+ badCode: { ...entry, code: "12345\n" },
637
+ numericCode: { ...entry, code: 123456 },
638
+ empty: null,
639
+ } }));
640
+ const result = await watch(["--fleet", "--max", "1"], { cwd: root, time, requiredChecks: [] });
641
+ assert.equal(result.code, 4);
642
+ assert.deepEqual(result.lines, ["EVENT timeout"]);
643
+ });
644
+ }
645
+
646
+ test("a follower ignores Leader pairing requests", async t => {
647
+ const { stateDir, writeState } = await import("./fleet-state.mjs");
648
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-watch-pairing-role-"));
649
+ mkdirSync(path.join(root, ".git"));
650
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
651
+ writeState(root, "node", { leader: false });
652
+ writeFileSync(path.join(stateDir(root), "pairing.json"), JSON.stringify({ requests: { pc: { code: "123456", seen: 0, allowed: false } } }));
653
+ assert.equal((await watch(["--fleet", "--max", "1"], { cwd: root, time: fakeClock(), requiredChecks: [] })).code, 4);
654
+ });
655
+
656
+ test("the fleet command documents startup, monitoring, pairing decisions, and secret handling", () => {
657
+ const command = readFileSync(new URL("../../../../commands/fleet.md", import.meta.url), "utf8").replace(/\r\n/g, "\n");
658
+ assert.match(command, /^---\ndescription: .+\nargument-hint: .+\n---/);
659
+ for (const text of ["$ARGUMENTS", "npx --yes architecture-harness fleet", "npx --yes architecture-harness watch --fleet", "Monitor", "AskUserQuestion", "fleet allow <code>", "fleet deny <code>", "fleet accept <code>", "fleet status", "--leader", "QC_FLEET_FILE"]) {
660
+ assert.ok(command.includes(text), text);
661
+ }
662
+ assert.match(command, /after each exit/);
663
+ assert.match(command, /Never print the secret/);
664
+ const readme = readFileSync(new URL("../../../../README.md", import.meta.url), "utf8");
665
+ assert.match(readme, /`\/fleet start` runs the fleet from Claude/);
666
+ });
@@ -113,7 +113,8 @@ function fleetSegment(dir) {
113
113
  const base = process.platform === 'win32' && process.env.APPDATA
114
114
  ? process.env.APPDATA : process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
115
115
  const file = process.env.QC_FLEET_FILE || path.join(base, 'qc', 'fleet.json');
116
- const self = JSON.parse(fs.readFileSync(file, 'utf8'))?.self;
116
+ const fleet = JSON.parse(fs.readFileSync(file, 'utf8'));
117
+ const self = fleet?.self;
117
118
  if (typeof self !== 'string' || !/^[a-z0-9-]{1,32}$/.test(self)) return null;
118
119
  let mark = '';
119
120
  const commonDir = gitCommonDir(dir);
@@ -128,6 +129,22 @@ function fleetSegment(dir) {
128
129
  if (alive) mark = node.leader === true ? ' leader' : '';
129
130
  }
130
131
  } catch { /* missing or invalid node state means off */ }
132
+ try {
133
+ const pairing = JSON.parse(fs.readFileSync(path.join(commonDir, 'qc', 'fleet', 'pairing.json'), 'utf8'));
134
+ const entries = fleet.secret ? pairing?.requests : pairing?.offers;
135
+ const completed = fleet.secret ? 'allowed' : 'accepted';
136
+ const now = Date.now();
137
+ const pending = Object.entries(entries || {}).filter(([id, entry]) =>
138
+ /^[a-z0-9-]{1,32}$/.test(id) && entry && !entry[completed] &&
139
+ typeof entry.code === 'string' && /^\d{6}$/.test(entry.code) &&
140
+ Number.isFinite(entry.seen) && entry.seen >= now - 10 * 60 * 1000
141
+ ).sort((a, b) => b[1].seen - a[1].seen);
142
+ if (pending.length) {
143
+ const [id, entry] = pending[0];
144
+ mark += fleet.secret ? ` join? ${id} ${entry.code}` : ` joining ${id} ${entry.code}`;
145
+ if (fleet.secret && pending.length > 1) mark += ` +${pending.length - 1}`;
146
+ }
147
+ } catch { /* missing or invalid pairing state adds nothing */ }
131
148
  }
132
149
  return { text: `fleet ${self}${mark}`, color: TEAL };
133
150
  } catch { return null; }