architecture-harness 0.27.0 → 0.28.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.
@@ -1,3 +1,5 @@
1
+ import os from "node:os";
2
+ import { sampleLoad } from "./fleet-load.mjs";
1
3
  import { hostOS } from "./legs.mjs";
2
4
  import { platformTick } from "./fleet-platform.mjs";
3
5
  import { randomUUID } from "node:crypto";
@@ -8,8 +10,9 @@ import path from "node:path";
8
10
  import { fileURLToPath } from "node:url";
9
11
  import { lookup } from "node:dns/promises";
10
12
  import { receiveTalk } from "./fleet-talk.mjs";
11
- import { assignTick } from "./fleet-assign.mjs";
13
+ import { assignTick, overloaded } from "./fleet-assign.mjs";
12
14
  import { readOpenAssignments, freeIssues } from "./fleet.mjs";
15
+ import { effectiveFleet, readDiscovered, startDiscovery } from "./fleet-discover.mjs";
13
16
  import { runGh } from "./gh-run.mjs";
14
17
  import { createMessage } from "./fleet-message.mjs";
15
18
  import { githubFallback, postGithubMessage, readGithub, receiveMessage, validBranch, validHead, validWork } from "./fleet-github.mjs";
@@ -184,7 +187,13 @@ export async function flushOutbox({ root = process.cwd(), fleet, fetch = nodeFet
184
187
  }
185
188
  }
186
189
 
187
- export async function heartbeat({ root = process.cwd(), fleet, repo, kit = null, leader = false, clock = Date.now, fetch = nodeFetch, signal }) {
190
+ const loadRounds = new Map();
191
+
192
+ export async function heartbeat({ root = process.cwd(), fleet, repo, kit = null, leader = false, os: host = os, clock = Date.now, fetch = nodeFetch, signal }) {
193
+ const previous = loadRounds.get(root);
194
+ const { cpu, mem, sample } = sampleLoad({ os: host, previous: previous?.sample });
195
+ const load = { cpu, mem, rtt: previous?.rtt ?? null };
196
+ const durations = [];
188
197
  // No snapshot survives a network await: confirmation may rebuild assignments during a send.
189
198
  const bodyFor = id => {
190
199
  const role = savedRole(root, leader);
@@ -194,7 +203,7 @@ export async function heartbeat({ root = process.cwd(), fleet, repo, kit = null,
194
203
  return { repo: row.repo, issue: row.issue, epoch: row.epoch, step: current.step ?? null,
195
204
  branch: current.branch ?? row.branch ?? null, head: current.head ?? row.head ?? null };
196
205
  });
197
- return { kit, os: hostOS(), ...role, work, ...(role.leader ? { assigned: assignments.filter(row => row.node === id)
206
+ return { kit, os: hostOS(), load, ...role, work, ...(role.leader ? { assigned: assignments.filter(row => row.node === id)
198
207
  .map(({ repo, issue, epoch }) => ({ repo, issue, epoch })) } : {}) };
199
208
  };
200
209
  const local = bodyFor(fleet.self);
@@ -204,11 +213,24 @@ export async function heartbeat({ root = process.cwd(), fleet, repo, kit = null,
204
213
  writeState(root, "peers", peers);
205
214
  }
206
215
  for (const node of fleet.nodes) {
207
- if (signal?.aborted) return;
216
+ if (signal?.aborted) break;
208
217
  if (node.id === fleet.self || node.active === false || !node.address) continue;
209
218
  const message = createMessage({ from: fleet.self, repo, kind: "heartbeat", body: bodyFor(node.id),
210
219
  time: new Date(clock()).toISOString() }, fleet.secret);
211
- await sendMessage({ root, fleet, node, message, clock, fetch, signal });
220
+ const started = clock();
221
+ if (await sendMessage({ root, fleet, node, message, clock, fetch, signal })) {
222
+ durations.push(Math.min(600_000, Math.max(0, clock() - started)));
223
+ }
224
+ }
225
+ durations.sort((a, b) => a - b);
226
+ const middle = Math.floor(durations.length / 2);
227
+ const rtt = durations.length ? (durations.length % 2 ? durations[middle] : (durations[middle - 1] + durations[middle]) / 2) : null;
228
+ loadRounds.set(root, { sample, rtt });
229
+ const latest = bodyFor(fleet.self);
230
+ if (latest.leader) {
231
+ const peers = readState(root, "peers");
232
+ peers[fleet.self] = { time: clock(), ...latest, load: { cpu, mem, rtt } };
233
+ writeState(root, "peers", peers);
212
234
  }
213
235
  }
214
236
 
@@ -308,8 +330,13 @@ export async function nodeStatus({ root = process.cwd(), fleet, fetch = nodeFetc
308
330
  const recent = others.filter(node => Number.isFinite(peers[node.id]?.time) && time - peers[node.id].time >= 0 && time - peers[node.id].time <= 90_000);
309
331
  const leader = running && record.leader ? fleet.self : recent.find(node => peers[node.id].leader === true && (peers[node.id].term ?? 1) >= highestTerm(root))?.id ?? "unknown";
310
332
  const proposal = readState(root, "proposal");
311
- return `node=${status} leader=${leader} peers=${recent.length}/${others.length}` +
312
- (proposal.id && validTerm(proposal.term) ? `\nproposed Leader ${proposal.id} term ${proposal.term}: run qc fleet confirm-leader` : "");
333
+ const loads = recent.map(node => {
334
+ const load = peers[node.id].load;
335
+ const percent = value => value == null ? "-" : `${Math.round(value * 100)}%`;
336
+ return `\nload ${node.id} cpu=${percent(load?.cpu)} mem=${percent(load?.mem)} rtt=${load?.rtt == null ? "-" : `${load.rtt}ms`}${overloaded(load).length ? " overloaded" : ""}`;
337
+ }).join("");
338
+ return `node=${status} leader=${leader} peers=${recent.length}/${others.length}` + loads +
339
+ (proposal.id && validTerm(proposal.term) ? `\nproposed Leader ${proposal.id} term ${proposal.term}: run npx architecture-harness fleet confirm-leader` : "");
313
340
  }
314
341
 
315
342
  /** Consume assignments only after checking the sender's latest leadership claim. */
@@ -474,15 +501,28 @@ export function confirmLeader({ root, fleet, clock = Date.now }) {
474
501
  }
475
502
 
476
503
  /** One serial tick avoids overlapping network retries and heartbeats. */
477
- export async function serveNode({ root = process.cwd(), fleet, repo, kit = null, leader = false, clock = Date.now,
504
+ export async function serveNode({ root = process.cwd(), fleet, repo, kit = null, leader = false, os: host = os, clock = Date.now,
505
+ configuredFleet = fleet, interfaces, discovery = {},
478
506
  fetch = nodeFetch, gh = runGh, git, platform = {}, holdLabel = "hold", listen, instance = process.env.QC_FLEET_INSTANCE || randomUUID(), pid = process.pid, timer = setInterval, clearTimer = clearInterval,
479
507
  onSignal = (name, fn) => process.once(name, fn), offSignal = (name, fn) => process.off(name, fn), warn = console.error }) {
508
+ const configured = { ...configuredFleet, nodes: configuredFleet.nodes.map(node => ({ ...node })) };
509
+ const refreshFleet = () => {
510
+ if (!configured.discover) return;
511
+ const current = effectiveFleet(configured, readDiscovered(root, configured.secret), clock(), interfaces);
512
+ fleet.nodes = current.nodes;
513
+ fleet.leaders = current.leaders;
514
+ };
515
+ refreshFleet();
480
516
  const server = await createNodeServer({ root, fleet, clock, listen, instance });
517
+ let discoverySocket;
518
+ try { if (fleet.discover) discoverySocket = await startDiscovery({ ...discovery, root, fleet, address: server.address().address, clock, interfaces, warn }); }
519
+ catch (error) { server.close(); throw error; }
481
520
  const sends = new AbortController();
482
521
  let interval, forceClose, busy = false, closing = false, nextHeartbeat = clock() + 30_000, nextAssign = clock() + 60_000, nextGithub = clock();
483
522
  const shutdown = () => {
484
523
  if (closing) return;
485
524
  closing = true;
525
+ discoverySocket?.close();
486
526
  clearTimer(interval);
487
527
  sends.abort();
488
528
  server.close();
@@ -495,11 +535,12 @@ export async function serveNode({ root = process.cwd(), fleet, repo, kit = null,
495
535
  writeState(root, "node", { pid, leader, instance, term: previous.term ?? highestTerm(root) });
496
536
  writeState(root, "election", { ...election, started: election.started ?? clock(), highest: highestTerm(root) });
497
537
  }
498
- catch (error) { server.close(); throw error; }
538
+ catch (error) { discoverySocket?.close(); server.close(); throw error; }
499
539
  interval = timer(async () => {
500
540
  if (busy || closing) return;
501
541
  busy = true;
502
542
  try {
543
+ refreshFleet();
503
544
  if (clock() >= nextGithub) {
504
545
  nextGithub = clock() + 120_000;
505
546
  readGithub({ root, fleet, repo, clock, gh });
@@ -533,7 +574,7 @@ export async function serveNode({ root = process.cwd(), fleet, repo, kit = null,
533
574
  if (!closing && clock() >= nextHeartbeat) {
534
575
  nextHeartbeat = clock() + 30_000;
535
576
  leader = savedRole(root).leader;
536
- await heartbeat({ root, fleet, repo, kit, leader, clock, fetch, signal: sends.signal });
577
+ await heartbeat({ root, fleet, repo, kit, leader, os: host, clock, fetch, signal: sends.signal });
537
578
  }
538
579
  } catch (error) { warn(`fleet node: ${error.message}`); }
539
580
  finally { busy = false; }
@@ -542,6 +583,7 @@ export async function serveNode({ root = process.cwd(), fleet, repo, kit = null,
542
583
  onSignal("SIGTERM", shutdown);
543
584
  onSignal("SIGINT", shutdown);
544
585
  server.once("close", () => {
586
+ discoverySocket?.close();
545
587
  clearTimeout(forceClose);
546
588
  if (!closing) clearTimer(interval);
547
589
  closing = true;
@@ -3,16 +3,23 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { test } from "node:test";
6
+ import { getDefaultResultOrder, setDefaultResultOrder } from "node:dns";
6
7
  import { connect } from "node:net";
7
8
  import { once } from "node:events";
9
+ import { EventEmitter } from "node:events";
8
10
  import { createServer } from "node:http";
9
11
  import { spawn } from "node:child_process";
10
12
  import { createMessage, verifyMessage } from "./fleet-message.mjs";
11
13
  import { readState, stateDir, writeState } from "./fleet-state.mjs";
12
- import { createNodeServer, sendMessage, flushOutbox, heartbeat, startNode, stopNode, nodeStatus, serveNode } from "./fleet-node.mjs";
14
+ import { createNodeServer, sendMessage, flushOutbox, heartbeat as sendHeartbeat, startNode, stopNode, nodeStatus, serveNode as runNode } from "./fleet-node.mjs";
13
15
  import { runFleet } from "./fleet.mjs";
14
16
  import { assignTick } from "./fleet-assign.mjs";
15
17
 
18
+ const idleOS = { cpus: () => [{ times: { user: 10, idle: 90 } }], freemem: () => 50, totalmem: () => 100 };
19
+ const serveNode = options => runNode({ os: idleOS, ...options });
20
+ const heartbeat = options => sendHeartbeat({ os: idleOS, ...options });
21
+ const initialLoad = { cpu: null, mem: 0.5, rtt: null };
22
+
16
23
  const host = process.platform === "win32" ? "windows" : process.platform;
17
24
  const apiResponse = args => JSON.stringify(args[1] === "user" ? { login: "me" } : []);
18
25
  const secret = "ab".repeat(32);
@@ -121,13 +128,13 @@ test("heartbeat targets only other active addressed nodes and records receipt ti
121
128
  assert.equal(received[0].url, "http://127.0.0.1:8081/message");
122
129
  assert.equal(received[0].message.kind, "heartbeat");
123
130
  assert.equal(received[0].message.body.os, process.platform === "win32" ? "windows" : process.platform);
124
- assert.deepEqual(received[0].message.body, { kit: "commit", os: process.platform === "win32" ? "windows" : process.platform, term: 1, leader: true, work: [], assigned: [] });
131
+ assert.deepEqual(received[0].message.body, { load: initialLoad, kit: "commit", os: process.platform === "win32" ? "windows" : process.platform, term: 1, leader: true, work: [], assigned: [] });
125
132
  const server = await createNodeServer({ root, fleet, clock: () => now, listen: { port: 0 } });
126
133
  t.after(() => new Promise(resolve => server.close(resolve)));
127
134
  const post = body => fetch(`http://127.0.0.1:${server.address().port}/message`, { method: "POST", body: JSON.stringify(body) });
128
135
  const beat = message({ kind: "heartbeat", body: { kit: null, term: 1, leader: false } });
129
136
  assert.equal((await post(beat)).status, 202);
130
- assert.deepEqual(readState(root, "peers"), { a: { time: now, os: host, kit: "commit", term: 1, leader: true, work: [], assigned: [] }, b: { time: now, messageTime: beat.time, kit: null, term: 1, leader: false } });
137
+ assert.deepEqual(readState(root, "peers"), { a: { load: { ...initialLoad, rtt: 0 }, time: now, os: host, kit: "commit", term: 1, leader: true, work: [], assigned: [] }, b: { time: now, messageTime: beat.time, kit: null, term: 1, leader: false } });
131
138
  assert.equal((await post(message({ kind: "heartbeat", body: { leader: "yes" } }))).status, 400);
132
139
  assert.deepEqual(readState(root, "queue"), []);
133
140
  });
@@ -299,7 +306,7 @@ test("start detaches with a log, start twice is idempotent, stop keeps state and
299
306
  assert.equal(readFileSync(path.join(stateDir(root), "node.log"), "utf8"), "");
300
307
  assert.deepEqual(await startNode(p.deps), { running: true, already: true });
301
308
  assert.equal(p.spawned.length, 1);
302
- assert.equal(await nodeStatus(p.deps), "node=running leader=a peers=1/3");
309
+ assert.equal(await nodeStatus(p.deps), "node=running leader=a peers=1/3\nload b cpu=- mem=- rtt=-");
303
310
  assert.deepEqual(await stopNode(p.deps), { stopped: true, already: false });
304
311
  assert.ok(p.signals.includes("SIGTERM"));
305
312
  assert.equal(existsSync(path.join(stateDir(root), "node.json")), false);
@@ -308,7 +315,7 @@ test("start detaches with a log, start twice is idempotent, stop keeps state and
308
315
  assert.equal(readState(root, "peers").b.leader, true);
309
316
  assert.equal(existsSync(path.join(stateDir(root), "node.log")), true);
310
317
  assert.deepEqual(await stopNode(p.deps), { stopped: true, already: true });
311
- assert.equal(await nodeStatus(p.deps), "node=stopped leader=b peers=1/3");
318
+ assert.equal(await nodeStatus(p.deps), "node=stopped leader=b peers=1/3\nload b cpu=- mem=- rtt=-");
312
319
  assert.equal(await nodeStatus({ ...p.deps, clock: () => now + 90_001 }), "node=stopped leader=unknown peers=0/3");
313
320
  });
314
321
 
@@ -338,7 +345,9 @@ test("status counts only known other senders in the inclusive 90-second window",
338
345
  const root = fixture(t), p = processDeps(root);
339
346
  writeState(root, "peers", { a: { time: now, leader: true }, b: { time: now - 90000, leader: true },
340
347
  inactive: { time: now - 90001, leader: true }, unaddressed: { time: now + 1, leader: true }, unknown: { time: now, leader: true } });
341
- assert.equal(await nodeStatus(p.deps), "node=stopped leader=b peers=1/3");
348
+ assert.equal(await nodeStatus(p.deps), "node=stopped leader=b peers=1/3\nload b cpu=- mem=- rtt=-");
349
+ writeState(root, "proposal", { id: "b", term: 2 });
350
+ assert.match(await nodeStatus(p.deps), /proposed Leader b term 2: run npx architecture-harness fleet confirm-leader/);
342
351
  });
343
352
 
344
353
  test("serve schedules heartbeats every 30 seconds, retries every second and closes cleanly", async t => {
@@ -357,7 +366,7 @@ test("serve schedules heartbeats every 30 seconds, retries every second and clos
357
366
  time += 1000;
358
367
  await timers[0].fn();
359
368
  assert.equal(sent.length, 1);
360
- assert.deepEqual(sent[0].body, { os: host, kit: null, term: 1, leader: true, work: [], assigned: [] });
369
+ assert.deepEqual(sent[0].body, { load: initialLoad, os: host, kit: null, term: 1, leader: true, work: [], assigned: [] });
361
370
  assert.equal(readState(root, "node").leader, true);
362
371
  const closed = new Promise(resolve => server.once("close", resolve));
363
372
  signals.get("SIGTERM")();
@@ -367,6 +376,66 @@ test("serve schedules heartbeats every 30 seconds, retries every second and clos
367
376
  assert.equal(existsSync(path.join(stateDir(root), "node.json")), false);
368
377
  });
369
378
 
379
+ test("serve advertises a hostname as its bound IPv4 to a receiver, refreshes the same fleet for HTTP, heartbeats and expiry, and closes discovery on shutdown", async t => {
380
+ const { createBeacon, readDiscovered, startDiscovery } = await import("./fleet-discover.mjs");
381
+ const order = getDefaultResultOrder();
382
+ setDefaultResultOrder("ipv4first");
383
+ t.after(() => setDefaultResultOrder(order));
384
+ const root = fixture(t), signals = new Map(), sent = [], beacons = [];
385
+ const current = { self: "a", secret, discover: true, nodes: [{ id: "a", address: "localhost", weight: 1, maxSize: "L", port: 8080 }], leaders: ["a"] };
386
+ const { createHash } = await import("node:crypto");
387
+ mkdirSync(stateDir(root), { recursive: true });
388
+ writeFileSync(path.join(stateDir(root), "discovered.json"), JSON.stringify({
389
+ fleet: createHash("sha256").update(`${secret}a`, "utf8").digest("hex").slice(0, 16),
390
+ nodes: { stale: { address: "127.0.0.1", port: 9091, weight: 1, maxSize: "L", seen: now } },
391
+ }));
392
+ let time = now, tick, closed = false;
393
+ const socket = new EventEmitter();
394
+ socket.bind = (_port, _host, ready) => ready();
395
+ socket.setBroadcast = () => {};
396
+ socket.send = (data, _port, _address, callback) => { beacons.push(JSON.parse(data)); callback?.(); };
397
+ socket.close = () => { closed = true; };
398
+ const interfaces = () => ({ test: [{ address: "127.0.0.1", family: "IPv4", internal: false, netmask: "255.0.0.0" }] });
399
+ const server = await serveNode({ root, fleet: current, repo: "o/r", clock: () => time, listen: { port: 0 },
400
+ interfaces, discovery: { createSocket: () => socket, timer: () => 42, clearTimer() {} },
401
+ gh: apiResponse, timer: fn => { tick = fn; }, clearTimer() {},
402
+ onSignal: (name, fn) => signals.set(name, fn), offSignal: name => signals.delete(name),
403
+ fetch: async (url, options) => { sent.push({ url, message: JSON.parse(options.body) }); return { status: 202 }; } });
404
+ t.after(() => new Promise(resolve => server.close(resolve)));
405
+ assert.equal(current.nodes[0].address, "localhost");
406
+ assert.equal(server.address().address, "127.0.0.1");
407
+ assert.ok(beacons.length > 0);
408
+ assert.deepEqual(beacons[0].addresses, [server.address().address]);
409
+ const receiverRoot = fixture(t), receiver = new EventEmitter();
410
+ receiver.bind = (_port, _host, ready) => ready();
411
+ receiver.setBroadcast = receiver.send = receiver.close = () => {};
412
+ const discovery = await startDiscovery({ root: receiverRoot,
413
+ fleet: { self: "b", secret, nodes: [{ id: "b", port: 9090 }] }, address: "127.0.0.1", interfaces,
414
+ clock: () => time, createSocket: () => receiver, timer: () => 42, clearTimer() {} });
415
+ t.after(() => discovery.close());
416
+ receiver.emit("message", Buffer.from(JSON.stringify(beacons[0])), { address: server.address().address });
417
+ assert.equal(readDiscovered(receiverRoot, secret).a.address, "127.0.0.1");
418
+ assert.deepEqual(current.nodes.map(node => node.id), ["a"]);
419
+ const remote = { self: "b", secret, nodes: [{ id: "b", address: "127.0.0.1", port: 9090, weight: 2, maxSize: "M" }] };
420
+ socket.emit("message", Buffer.from(JSON.stringify(createBeacon({ fleet: remote, address: "127.0.0.1", clock: () => time }))), { address: "127.0.0.1" });
421
+ time += 30_000;
422
+ await tick();
423
+ assert.deepEqual(current.leaders, ["a", "b"]);
424
+ assert.equal(current.nodes.find(node => node.id === "b").port, 9090);
425
+ assert.ok(sent.some(row => row.url === "http://127.0.0.1:9090/message" && row.message.kind === "heartbeat"));
426
+ const body = createMessage({ from: "b", repo: "o/r", kind: "heartbeat", body: { term: 1, leader: false, kit: null }, time: new Date(time).toISOString() }, secret);
427
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/message`, { method: "POST", body: JSON.stringify(body) });
428
+ assert.equal(response.status, 202);
429
+ time = now + 300_001;
430
+ await tick();
431
+ assert.deepEqual(current.nodes.map(node => node.id), ["a"]);
432
+ assert.deepEqual(current.leaders, ["a"]);
433
+ const stopped = once(server, "close");
434
+ signals.get("SIGTERM")();
435
+ await stopped;
436
+ assert.equal(closed, true);
437
+ });
438
+
370
439
  test("server refuses addresses that resolve to wildcard interfaces", async t => {
371
440
  const root = fixture(t);
372
441
  for (const address of ["0.0.0.0", "::", "0", "0:0:0:0:0:0:0:0"]) {
@@ -713,13 +782,13 @@ test("heartbeats carry own work, per-recipient Leader assignments, and replace p
713
782
  const fetcher = async (_url, options) => { received.push(JSON.parse(options.body)); return { status: 202 }; };
714
783
  await heartbeat({ root, fleet: nodes, repo: "o/r", leader: true, clock: () => now, fetch: fetcher });
715
784
  assert.deepEqual(received.map(row => row.body), [
716
- { os: host, kit: null, term: 1, leader: true, work: [work], assigned: [{ repo: "o/r", issue: 2, epoch: 1 }] },
717
- { os: host, kit: null, term: 1, leader: true, work: [work], assigned: [{ repo: "o/r", issue: 3, epoch: 1 }] },
785
+ { load: initialLoad, os: host, kit: null, term: 1, leader: true, work: [work], assigned: [{ repo: "o/r", issue: 2, epoch: 1 }] },
786
+ { load: initialLoad, os: host, kit: null, term: 1, leader: true, work: [work], assigned: [{ repo: "o/r", issue: 3, epoch: 1 }] },
718
787
  ]);
719
788
  received.length = 0;
720
789
  writeState(root, "assignments", { "o/r#1": held(1, "a", 2) });
721
790
  await heartbeat({ root, fleet: nodes, repo: "o/r", clock: () => now, fetch: fetcher });
722
- assert.deepEqual(received[0].body, { os: host, kit: null, term: 1, leader: false, work: [{ repo: "o/r", issue: 1, epoch: 2, step: null, branch: null, head: null }] });
791
+ assert.deepEqual(received[0].body, { load: { ...initialLoad, rtt: 0 }, os: host, kit: null, term: 1, leader: false, work: [{ repo: "o/r", issue: 1, epoch: 2, step: null, branch: null, head: null }] });
723
792
  const server = await createNodeServer({ root, fleet: nodes, clock: () => now, listen: { port: 0 } });
724
793
  t.after(() => new Promise(resolve => server.close(resolve)));
725
794
  let sentTime = now;
@@ -1005,7 +1074,7 @@ test("promotion during the heartbeat send to A gives C the rebuilt assignment at
1005
1074
  } });
1006
1075
  assert.equal(sent.length, 2);
1007
1076
  assert.equal(sent[1].url, "http://127.0.0.1:18082/message");
1008
- assert.deepEqual(sent[1].body, { os: host, kit: null, leader: true, term: 2, work: [],
1077
+ assert.deepEqual(sent[1].body, { load: initialLoad, os: host, kit: null, leader: true, term: 2, work: [],
1009
1078
  assigned: [{ repo: "o/r", issue: 7, epoch: 3 }] });
1010
1079
  });
1011
1080
 
@@ -1280,3 +1349,36 @@ test("platform child checks leave serve ticks free to heartbeat and retain the p
1280
1349
  await fetch(`http://127.0.0.1:${server.address().port}/message`, { method: "POST", body: JSON.stringify(beat) });
1281
1350
  assert.equal(readState(root, "peers").b.os, "windows");
1282
1351
  });
1352
+
1353
+ test("heartbeat samples fake OS and publishes the successful prior round median, including Leader load", async t => {
1354
+ const root = fixture(t);
1355
+ let time = now, busy = 10;
1356
+ const fakeOS = { cpus: () => [{ times: { user: busy, idle: 90 } }], freemem: () => 20, totalmem: () => 100 };
1357
+ const nodes = { ...fleet, nodes: [fleet.nodes[0], ...["b", "c", "d", "e", "f"].map(id => ({ id, address: "localhost" }))] };
1358
+ const received = [];
1359
+ let index = 0;
1360
+ const durations = [10, 30, 900, 20, 40];
1361
+ const deps = { root, fleet: nodes, repo: "o/r", leader: true, os: fakeOS, clock: () => time,
1362
+ fetch: async (_url, options) => { received.push(JSON.parse(options.body).body.load); time += durations[index % 5]; return { status: index++ % 5 === 2 ? 503 : 202 }; } };
1363
+ await heartbeat(deps);
1364
+ assert.deepEqual(received, Array(5).fill({ cpu: null, mem: 0.8, rtt: null }));
1365
+ assert.deepEqual(readState(root, "peers").a.load, { cpu: null, mem: 0.8, rtt: 25 });
1366
+ received.length = 0;
1367
+ busy = 110;
1368
+ await heartbeat(deps);
1369
+ assert.deepEqual(received, Array(5).fill({ cpu: 1, mem: 0.8, rtt: 25 }));
1370
+ await heartbeat({ ...deps, fetch: async () => { time += 50; return { status: 503 }; } });
1371
+ assert.equal(readState(root, "peers").a.load.rtt, null);
1372
+ received.length = 0;
1373
+ await heartbeat(deps);
1374
+ assert.equal(received[0].rtt, null);
1375
+ });
1376
+
1377
+ test("status prints recent peer load with null markers and overload reasons", async t => {
1378
+ const root = fixture(t);
1379
+ const nodes = { ...fleet, nodes: [...fleet.nodes, { id: "c" }] };
1380
+ writeState(root, "peers", { b: { time: now, load: { cpu: 0.95, mem: 0.5, rtt: 2000 } },
1381
+ c: { time: now - 90000 }, inactive: { time: now - 90001 }, unaddressed: { time: now + 1 } });
1382
+ assert.equal(await nodeStatus({ root, fleet: nodes, clock: () => now }),
1383
+ "node=stopped leader=unknown peers=2/4\nload b cpu=95% mem=50% rtt=2000ms overloaded\nload c cpu=- mem=- rtt=-");
1384
+ });
package/src/cli/fleet.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // A static fleet shares node settings across PCs; only the local self id differs.
1
+ // Fleets share a secret and either discover LAN peers or use a static node list.
2
2
  import { createHash, randomBytes } from "node:crypto";
3
3
  import { closeSync, fchmodSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { isIP } from "node:net";
@@ -13,9 +13,10 @@ import { sendPushed, validPlatformBranch } from "./fleet-platform.mjs";
13
13
  import { TALK_VERBS, parseTalkArgs, runTalk } from "./fleet-talk.mjs";
14
14
  import { highestTerm, latestLeader, readState, writeState } from "./fleet-state.mjs";
15
15
  import { confirmLeader, nodeStatus, serveNode, startNode, stopNode } from "./fleet-node.mjs";
16
+ import { effectiveFleet, readDiscovered } from "./fleet-discover.mjs";
16
17
 
17
18
  const SIZES = ["S", "M", "L"];
18
- const USAGE = "usage: qc fleet init --self <id> --nodes <id:weight:size,...> [--secret <hex>] [--addresses <id@host:port,...>] [--force] | next [--repo <o/r>] [--all] | status [--repo <o/r>] | plan <issue> --file <path> | ask <issue> --file <path> | approve <message-id> [--changes] [--file <path>] | answer <message-id> --file <path> | show <message-id> | start [--leader] | serve [--leader] | stop | confirm-leader | progress <issue> --step plan|code|review|merge [--branch <b>] [--head <sha40>] | owns <issue> | pushed <issue> --branch <b> --head <sha40>";
19
+ const USAGE = "usage: qc fleet init [--self <id>] [--nodes <id:weight:size,...>] [--port <port>] [--secret <hex>] [--addresses <id@host:port,...>] [--force] | next [--repo <o/r>] [--all] | status [--repo <o/r>] | plan <issue> --file <path> | ask <issue> --file <path> | approve <message-id> [--changes] [--file <path>] | answer <message-id> --file <path> | show <message-id> | start [--leader] | serve [--leader] | stop | confirm-leader | progress <issue> --step plan|code|review|merge [--branch <b>] [--head <sha40>] | owns <issue> | pushed <issue> --branch <b> --head <sha40>";
19
20
 
20
21
  function validAddress(address) {
21
22
  if (typeof address !== "string" || !address || address.trim() !== address || address === "0.0.0.0") return false;
@@ -56,7 +57,11 @@ export function validateFleet(value) {
56
57
  if (value.secret !== undefined && (typeof value.secret !== "string" || value.secret.length < 64 || /[^0-9a-f]/i.test(value.secret))) throw new Error("secret must be hex with at least 64 characters");
57
58
  const leaders = value.leaders === undefined ? nodes.map(node => node.id) : value.leaders;
58
59
  if (!Array.isArray(leaders) || !leaders.length || leaders.some(id => !seen.has(id)) || new Set(leaders).size !== leaders.length) throw new Error("leaders must be a nonempty list of unique node IDs");
59
- return { self: value.self, nodes, leaders: [...leaders], ...(value.secret === undefined ? {} : { secret: value.secret }) };
60
+ if (value.discover !== undefined && typeof value.discover !== "boolean") throw new Error("discover must be a boolean");
61
+ if (value.discoveryPort !== undefined && (!Number.isInteger(value.discoveryPort) || value.discoveryPort < 1024 || value.discoveryPort > 65535)) throw new Error("discoveryPort must be an integer from 1024 to 65535");
62
+ return { self: value.self, nodes, leaders: [...leaders], ...(value.secret === undefined ? {} : { secret: value.secret }),
63
+ ...(value.discover === undefined ? {} : { discover: value.discover }),
64
+ ...(value.discoveryPort === undefined && value.discover === undefined ? {} : { discoveryPort: value.discoveryPort ?? 47913 }) };
60
65
  }
61
66
 
62
67
  /** Weighted rendezvous hashing keeps other owners stable when a PC goes inactive. */
@@ -136,7 +141,7 @@ function parseArgs(argv) {
136
141
  if (TALK_VERBS.includes(verb)) return parseTalkArgs(verb, args);
137
142
  const hasIssue = ["progress", "owns", "pushed"].includes(verb);
138
143
  const rest = hasIssue ? args.slice(1) : args;
139
- const allowed = verb === "init" ? ["--self", "--nodes", "--secret", "--addresses", "--force"] : verb === "next" ? ["--repo", "--all"] : verb === "status" ? ["--repo"] : ["start", "serve"].includes(verb) ? ["--leader"] : verb === "pushed" ? ["--branch", "--head"] : verb === "progress" ? ["--step", "--branch", "--head"] : ["stop", "owns", "confirm-leader"].includes(verb) ? [] : null;
144
+ const allowed = verb === "init" ? ["--self", "--nodes", "--port", "--secret", "--addresses", "--force"] : verb === "next" ? ["--repo", "--all"] : verb === "status" ? ["--repo"] : ["start", "serve"].includes(verb) ? ["--leader"] : verb === "pushed" ? ["--branch", "--head"] : verb === "progress" ? ["--step", "--branch", "--head"] : ["stop", "owns", "confirm-leader"].includes(verb) ? [] : null;
140
145
  if (!allowed) throw new Error(USAGE);
141
146
  const options = { verb };
142
147
  if (hasIssue) {
@@ -165,12 +170,19 @@ function parseArgs(argv) {
165
170
  }
166
171
 
167
172
  function initialize(options, file, say) {
168
- if (!options["--self"] || !options["--nodes"]) throw new Error("init needs --self and --nodes");
169
- const nodes = options["--nodes"].split(",").map(entry => {
173
+ if (options["--nodes"] !== undefined && options["--self"] === undefined) throw new Error("init needs --self with --nodes");
174
+ const self = options["--self"] ?? randomBytes(2).toString("hex");
175
+ const port = Number(options["--port"] ?? 8080);
176
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error("--port must be an integer from 1024 to 65535");
177
+ const nodes = options["--nodes"] === undefined ? [{ id: self, weight: 1, maxSize: "L", port }] : options["--nodes"].split(",").map(entry => {
170
178
  const [id, weight, maxSize, ...extra] = entry.split(":");
171
179
  if (extra.length) throw new Error("--nodes needs id:weight:size entries");
172
180
  return { id, weight: Number(weight), maxSize };
173
181
  });
182
+ if (options["--nodes"] !== undefined && options["--port"] !== undefined) {
183
+ const local = nodes.find(node => node.id === self);
184
+ if (local) local.port = port;
185
+ }
174
186
  if (options["--addresses"]) {
175
187
  const addressed = new Set();
176
188
  for (const entry of options["--addresses"].split(",")) {
@@ -184,7 +196,7 @@ function initialize(options, file, say) {
184
196
  }
185
197
  }
186
198
  const secret = options["--secret"] ?? randomBytes(32).toString("hex");
187
- const fleet = validateFleet({ self: options["--self"], nodes, secret });
199
+ const fleet = validateFleet({ self, nodes, secret, ...(options["--nodes"] === undefined ? { discover: true } : {}) });
188
200
  mkdirSync(path.dirname(file), { recursive: true });
189
201
  let fd;
190
202
  try {
@@ -198,7 +210,8 @@ function initialize(options, file, say) {
198
210
  if (fd !== undefined) closeSync(fd);
199
211
  }
200
212
  say(`fleet initialized: ${file}`);
201
- if (!options["--secret"]) say(`pass the same secret on the other PCs: --secret ${secret}`);
213
+ say(`fleet name: ${self}`);
214
+ if (!options["--secret"]) say(`run on the other PCs: npx architecture-harness fleet init --secret ${secret}`);
202
215
  return 0;
203
216
  }
204
217
 
@@ -215,9 +228,11 @@ export function runFleet(argv, { cwd = process.cwd(), env = process.env, gh = ru
215
228
  }
216
229
  let value;
217
230
  try { value = JSON.parse(text); } catch { throw new Error(`fleet file has invalid JSON: ${file}`); }
218
- const fleet = validateFleet(value);
231
+ const configuredFleet = validateFleet(value);
232
+ const fleet = effectiveFleet(configuredFleet, configuredFleet.discover ? readDiscovered(cwd, configuredFleet.secret) : {}, node.clock?.() ?? Date.now(), node.interfaces);
233
+ if (options.verb === "status") say(`name=${fleet.self} discover=${fleet.discover ? "on" : "off"}`);
219
234
  if (["start", "stop", "serve"].includes(options.verb)) {
220
- return runNodeVerb(options, { root: cwd, fleet, env, gh, git, origin, say, warn, node }).catch(error => { warn(error.message); return 1; });
235
+ return runNodeVerb(options, { root: cwd, fleet, configuredFleet, env, gh, git, origin, say, warn, node }).catch(error => { warn(error.message); return 1; });
221
236
  }
222
237
  if (options.verb === "confirm-leader") {
223
238
  const term = confirmLeader({ ...node, root: cwd, fleet });
@@ -289,8 +304,8 @@ export function runFleet(argv, { cwd = process.cwd(), env = process.env, gh = ru
289
304
  }
290
305
  }
291
306
 
292
- async function runNodeVerb(options, { root, fleet, env, gh, git, origin, say, warn, node }) {
293
- const deps = { gh, git, ...node, root, fleet, env, leader: options["--leader"] === true };
307
+ async function runNodeVerb(options, { root, fleet, configuredFleet, env, gh, git, origin, say, warn, node }) {
308
+ const deps = { gh, git, ...node, root, fleet, configuredFleet, env, leader: options["--leader"] === true };
294
309
  if (options.verb === "serve") {
295
310
  const kitRoot = fileURLToPath(new URL("../../../../", import.meta.url));
296
311
  const kit = gitOut(kitRoot, "rev-parse", "HEAD")?.trim() || null;
@@ -1,13 +1,13 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import { test } from "node:test";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { fleetPath, validateFleet, ownerOf, freeIssues, runFleet } from "./fleet.mjs";
10
- import { readState, writeState } from "./fleet-state.mjs";
10
+ import { readState, stateDir, writeState } from "./fleet-state.mjs";
11
11
 
12
12
  const nodes = [
13
13
  { id: "a1", weight: 1, maxSize: "L", active: true },
@@ -123,12 +123,77 @@ test("init accepts explicit secrets and addresses and generates a reusable secre
123
123
  assert.match(saved.secret, /^[0-9a-f]{64}$/);
124
124
  const instruction = generated.lines.filter(line => line.includes(saved.secret));
125
125
  assert.equal(instruction.length, 1);
126
- assert.match(instruction[0], /pass the same secret on the other PCs/);
127
- assert.match(instruction[0], /--secret/);
126
+ assert.equal(instruction[0], `run on the other PCs: npx architecture-harness fleet init --secret ${saved.secret}`);
128
127
  assert.equal(f.run([...args, "--force"]).code, 0);
129
128
  assert.notEqual(JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8")).secret, saved.secret);
130
129
  });
131
130
 
131
+ test("init without flags chooses a random hex name, enables discovery and prints the shared secret command", t => {
132
+ const f = fixture(t);
133
+ const result = f.run(["init"]);
134
+ assert.equal(result.code, 0, result.errors.join("\n"));
135
+ const saved = JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8"));
136
+ assert.match(saved.self, /^[0-9a-f]{4}$/);
137
+ assert.equal(saved.discover, true);
138
+ assert.deepEqual(saved.nodes.map(({ id, port, weight, maxSize }) => ({ id, port, weight, maxSize })),
139
+ [{ id: saved.self, port: 8080, weight: 1, maxSize: "L" }]);
140
+ assert.ok(result.lines.includes(`fleet name: ${saved.self}`));
141
+ assert.ok(result.lines.includes(`run on the other PCs: npx architecture-harness fleet init --secret ${saved.secret}`));
142
+ const other = fixture(t);
143
+ const joined = other.run(["init", "--secret", saved.secret, "--port", "9090", "--self", "custom"]);
144
+ assert.equal(joined.code, 0, joined.errors.join("\n"));
145
+ const second = JSON.parse(readFileSync(other.env.QC_FLEET_FILE, "utf8"));
146
+ assert.equal(second.self, "custom");
147
+ assert.equal(second.secret, saved.secret);
148
+ assert.equal(second.nodes[0].port, 9090);
149
+ assert.ok(!joined.lines.join("\n").includes(saved.secret));
150
+ for (const port of ["1023", "65536", "1.5", "no"]) assert.equal(other.run(["init", "--force", "--port", port]).code, 1);
151
+ const staticPeers = fixture(t);
152
+ const rejected = staticPeers.run(["init", "--nodes", "peer:2:M"]);
153
+ assert.equal(rejected.code, 1);
154
+ assert.deepEqual(rejected.errors, ["init needs --self with --nodes"]);
155
+ assert.equal(existsSync(staticPeers.env.QC_FLEET_FILE), false);
156
+ });
157
+
158
+ test("validateFleet accepts optional discovery settings and rejects invalid types and ports", () => {
159
+ const old = { self: "a1", nodes: [nodes[0]] };
160
+ assert.equal(validateFleet({ ...old, discover: true }).discoveryPort, 47913);
161
+ assert.equal(validateFleet({ ...old, discover: false }).discover, false);
162
+ assert.equal(validateFleet({ ...old, discoveryPort: 49000 }).discoveryPort, 49000);
163
+ for (const discover of [null, "true", 0]) assert.throws(() => validateFleet({ ...old, discover }), /discover/);
164
+ for (const discoveryPort of [null, 1023, 65536, 1.5, "47913"]) assert.throws(() => validateFleet({ ...old, discoveryPort }), /discoveryPort/);
165
+ });
166
+
167
+ test("status and assignment use the discoveries saved on disk", async t => {
168
+ const f = fixture(t);
169
+ assert.equal(f.run(["init", "--self", "a1"]).code, 0);
170
+ mkdirSync(stateDir(f.cwd), { recursive: true });
171
+ const configured = JSON.parse(readFileSync(f.env.QC_FLEET_FILE, "utf8"));
172
+ writeFileSync(path.join(stateDir(f.cwd), "discovered.json"), JSON.stringify({
173
+ fleet: createHash("sha256").update(configured.secret, "utf8").digest("hex").slice(0, 16), nodes: { b2: {
174
+ address: "192.168.1.20", port: 8080, weight: 2, maxSize: "L", seen: Date.now(),
175
+ } },
176
+ }));
177
+ const extra = { gh: fakeGh([]), git: () => "", origin: () => "o/r" };
178
+ const status = await f.run(["status"], extra);
179
+ assert.equal(status.code, 0, status.errors.join("\n"));
180
+ assert.equal(status.lines[0], "name=a1 discover=on");
181
+ assert.ok(status.lines.some(line => /^b2 weight=2/.test(line)));
182
+ const issues = Array.from({ length: 100 }, (_, i) => issue(i + 1));
183
+ const currentNodes = [nodes[0], { ...nodes[1], weight: 2 }];
184
+ const mine = issues.filter(row => ownerOf("o/r", row.number, "M", currentNodes) === "a1").map(row => String(row.number));
185
+ const next = f.run(["next", "--all"], { ...extra, gh: fakeGh(issues) });
186
+ assert.equal(next.code, 0);
187
+ assert.deepEqual(next.lines, mine);
188
+ writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify({ ...configured, secret: `${configured.secret}a` }));
189
+ const changed = await f.run(["status"], extra);
190
+ assert.equal(changed.code, 0, changed.errors.join("\n"));
191
+ assert.ok(!changed.lines.some(line => /^b2 weight=2/.test(line)));
192
+ const reassigned = f.run(["next", "--all"], { ...extra, gh: fakeGh(issues) });
193
+ assert.equal(reassigned.code, 0);
194
+ assert.deepEqual(reassigned.lines, issues.map(row => String(row.number)));
195
+ });
196
+
132
197
  test("ownerOf repeats across calls and repo case, using the specified SHA-256 score", () => {
133
198
  for (let number = 1; number <= 100; number++) {
134
199
  const expected = [...nodes].sort((a, b) => {
@@ -227,15 +292,16 @@ test("next prints the oldest five or all, exits 3 when empty, and status adds th
227
292
  assert.deepEqual(empty, { code: 3, lines: [], errors: ["no free issue for a1"] });
228
293
  const status = await f.run(["status", "--repo", "o/r"], extra);
229
294
  assert.equal(status.code, 0);
230
- assert.equal(status.lines.length, 4);
231
- assert.match(status.lines[0], /a1.*1.*L.*true.*12.*12,11,10,9,8,7,6,5,4,3$/);
232
- assert.match(status.lines[1], /b2.*1.*S.*true.*0/);
233
- assert.match(status.lines[2], /taken.*0.*unassigned.*0/);
234
- assert.equal(status.lines[3], "node=stopped leader=unknown peers=0/1");
295
+ assert.equal(status.lines.length, 5);
296
+ assert.equal(status.lines[0], "name=a1 discover=off");
297
+ assert.match(status.lines[1], /a1.*1.*L.*true.*12.*12,11,10,9,8,7,6,5,4,3$/);
298
+ assert.match(status.lines[2], /b2.*1.*S.*true.*0/);
299
+ assert.match(status.lines[3], /taken.*0.*unassigned.*0/);
300
+ assert.equal(status.lines[4], "node=stopped leader=unknown peers=0/1");
235
301
  const many = Array.from({ length: 20 }, (_, i) => ({ id: `pc${i}`, weight: 1, maxSize: "L", active: true }));
236
302
  writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify({ self: "pc0", nodes: many }));
237
303
  const capped = await f.run(["status", "--repo", "o/r"], extra);
238
- assert.equal(capped.lines.length, 16);
304
+ assert.equal(capped.lines.length, 17);
239
305
  assert.match(capped.lines.at(-2), /6 more nodes/);
240
306
  assert.equal(capped.lines.at(-1), "node=stopped leader=unknown peers=0/19");
241
307
  writeFileSync(f.env.QC_FLEET_FILE, JSON.stringify({ self: "a1", nodes: [{ ...nodes[0], active: false }] }));
@@ -281,7 +347,7 @@ test("CLI starts, starts twice, reports running and stops without reading GitHub
281
347
  assert.equal(readState(f.cwd, "node").leader, true);
282
348
  writeState(f.cwd, "peers", { b2: { time: 999999, kit: null, leader: false } });
283
349
  assert.equal(await runFleet(["status", "--repo", "o/r"], { ...deps, gh: fakeGh([]), git: () => "" }), 0);
284
- assert.equal(lines.splice(0).at(-1), "node=running leader=a1 peers=1/1");
350
+ assert.deepEqual(lines.splice(0).slice(-2), ["node=running leader=a1 peers=1/1", "load b2 cpu=- mem=- rtt=-"]);
285
351
  assert.equal(await runFleet(["stop"], deps), 0);
286
352
  assert.deepEqual(lines.splice(0), ["fleet node stopped: a1"]);
287
353
  assert.equal(await runFleet(["stop"], deps), 0);
@@ -486,7 +552,7 @@ test("status prints the pending Leader proposal", async t => {
486
552
  writeState(f.cwd, "proposal", { id: "b2", term: 2 });
487
553
  const result = await f.run(["status"], { origin: () => "o/r", gh: fakeGh([]), git: () => "" });
488
554
  assert.equal(result.code, 0);
489
- assert.ok(result.lines.includes("proposed Leader b2 term 2: run qc fleet confirm-leader"));
555
+ assert.ok(result.lines.includes("proposed Leader b2 term 2: run npx architecture-harness fleet confirm-leader"));
490
556
  });
491
557
 
492
558