trantor 0.18.130 → 0.18.131

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,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.130",
3
+ "version": "0.18.131",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek)",
5
5
  "mcpServers": {
6
6
  "relay": {
package/README.md CHANGED
@@ -535,6 +535,15 @@ The default is `max(1, floor(cores / 4))` slots; set `"heavyGateSlots": 4` in
535
535
  `~/.agent-bus/config.json` to override it. Crew runners wire Cargo and package-runner shims into
536
536
  each seat. For a heavy command outside a runner, use `node bin/heavy-gate.mjs -- <command> …`.
537
537
 
538
+ Seats share one build cache per project under `~/.agent-bus/cache/<project>/`: Cargo builds go to
539
+ `cargo-target` there (an explicit `CARGO_TARGET_DIR` still wins) and the iOS drills put Xcode's
540
+ DerivedData beside it. The disk janitor prunes it under the same thresholds as other build output.
541
+
542
+ A machine that hosts seats can report its load: set `"healthHeartbeat": true` (plus a
543
+ `"machineLabel"`) in its `~/.agent-bus/config.json`, and its crew runners post CPU and memory to
544
+ the hub every 30 seconds. The desktop bottom bar shows each reporting machine, greyed once its last
545
+ report is older than 90 seconds.
546
+
538
547
  ## License
539
548
 
540
549
  [MIT](./LICENSE) © 2026 Sasha Bogojevic · Built with [Claude Code](https://claude.com/claude-code) ·
package/bin/cli.mjs CHANGED
@@ -45,6 +45,7 @@ switch (cmd) {
45
45
  case "prune": runCrew(); break;
46
46
  case "hub": {
47
47
  const sub = args[0];
48
+ if (sub === "timeouts") { args.splice(0, 1); run("bin/hub-timeouts.mjs", process.execPath); break; }
48
49
  // Per-project hub routing (TDD §12.1): a project lives on exactly ONE hub; codependent
49
50
  // projects MUST share one. The mapping lives in ~/.agent-bus/config.json `hubs`.
50
51
  if (sub === "list" || sub === "set" || sub === "unset") {
@@ -7,7 +7,9 @@ import { join, basename } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  import { resolveProject, resolveHub, withEnvFiles, hostId } from "../lib/project.mjs";
9
9
  import { machineLabel } from "../lib/machine-label.mjs";
10
+ import { healthPayload, defaultOs, HEALTH_BEAT_MS } from "../lib/machine-health.mjs";
10
11
  import { resolveSecrets, shadowEnv, withSecretExports } from "../lib/secrets.mjs";
12
+ import { seatBuildCacheEnv } from "../lib/seat-cache.mjs";
11
13
  import { runnerPersona } from "../lib/persona.mjs";
12
14
  import { loadOrCreate } from "../lib/identity.mjs";
13
15
  import { signedHeaders } from "../lib/signed-fetch.mjs";
@@ -26,6 +28,7 @@ import { capWake, capBcast, pickLessons, composePrompt, contractBase, baseLine }
26
28
  import {
27
29
  cardRefs, servedContractCard, carriesWork, parseTurnTokens, parseResetAt, reasonWithBalances, quotaResetAt, queuedWording, turnDelivered, budgetPause, PARKING_REASONS,
28
30
  senderProjectOf, isLinkedProject, stateSkipReason, isMessageCardTitle, OPEN_CARD_STATUSES,
31
+ ownCardForInstance, contractedCardIds,
29
32
  CUT_CHAIN_PARK_MIN, cutChainEvidence, isBoundedPark, askDuringTurn, askedVerdict,
30
33
  } from "../lib/turn-policy.mjs";
31
34
  import { snapshotBeforeCut } from "./cut-snapshot.mjs";
@@ -174,6 +177,11 @@ const log = (s) => console.log(`\x1b[38;5;43m[runner]\x1b[0m ${redactKeys(String
174
177
  const LOGDIR = join(homedir(), ".agent-bus", "logs");
175
178
  try { mkdirSync(LOGDIR, { recursive: true }); } catch {}
176
179
  let TURN = releaseState?.turn || 0;
180
+ // #13923: when THIS seat instance started. A seat name is reused across instances and the board's
181
+ // assignee only knows the name, so the my-cards surfaces (relay_board mine, the own-card reroute)
182
+ // fence assignments against this stamp — cards assigned before it are a predecessor's (#12138).
183
+ // Carried across the in-place release restart; a swap or a fresh `trantor up` stamps anew.
184
+ const BOOT_TS = releaseState?.bootTs || Date.now();
177
185
  const telemetry = (rec) => { try { appendFileSync(join(LOGDIR, `${PERSONA}-${PROJ}.jsonl`), JSON.stringify(rec) + "\n"); } catch {} };
178
186
  // The boot line records the HUB this runner bound to, so a split-brain is diagnosable from disk.
179
187
  telemetry({ ts: Date.now(), persona: PERSONA, agent: AGENT, project: PROJ, boot: true, hub: HUB, pid: process.pid, version: bootVersion });
@@ -312,7 +320,7 @@ const EFFORT_FLAG = EFFORT ? cliEffortFlag(DRIVER, EFFORT) : { flag: "", text: "
312
320
 
313
321
  // RUNNER_RULES / RUNNER_KICKOFF env overrides: the runner is also the substrate for non-crew
314
322
  // always-on seats (the fleet DUTY agent, bin/duty.mjs) whose doctrine is not "work your card".
315
- const RULES = process.env.RUNNER_RULES || `Rules: you are ${SESSION} on the trantor crew. Before starting a card, read YOUR card: relay_board with card:<id> (the card, its deps, its notes, and the last five done cards whose title shares a word); never the whole board. If your wake names no card id (or cites only a message-card), make relay_board with mine:true your FIRST call — it lists the cards assigned to you (doing/testing/todo, newest first, full card shape); work your newest one (#7763). After long read-only recon, commit a WIP note with findings so the turn leaves evidence. Work your assigned file(s), report on the bus (relay_send, <280 chars), move your Kanban card as you go with a NOTE saying what you did (doing -> testing, then STOP: you never close your own card to done — the orchestrator runs the card's drill on the built artifact and closes it, and the hub refuses a move to done on a card with no drill line anyway; in 'testing' run YOUR OWN test file — never the full npm test, suites collide across seats — plus \`node bin/slop-gate.mjs\` when the repo has one: it lints ONLY your changed files against the anti-slop rules, and a card must not reach testing with slop-gate failing; use 'failed' + a report if anything breaks). If your work starts containers or a dev server (\`supabase start\`, \`docker run\`, a watch process), stop them before moving your card to testing and name them in the note — the runner also stops containers it saw your turn create when the card closes, but the first responsibility is yours (#9778). If a contract omits a fact you cannot proceed without, ASK — never invent the value: relay_ask(<card>, <question>) blocks the card with your question, keeps the turn owed (no park, no failure), and resumes you when the assigner's answer lands; an invented value that reads as reasoned is the worst outcome this crew ships (#7756). If you need something from another session, message THAT SESSION (relay_peers to find its id, relay_send to reach it) — never ask the human to pass it along; carrying messages between agents is the job this bus exists to remove. When your work for THIS message is finished, END YOUR TURN — do NOT park, do NOT loop relay_wait; the runner waits for you and will wake you with the next message. Path discipline: build/test from your worktree root ${TURN_DIR} with absolute paths or --manifest-path/--prefix instead of cd-ing into subdirs, and put anything that must land outside the repo under ${TURN_DIR}/.agent-bus-out/ (gitignored) — never ~/.agent-bus. Realigning your seat branch after the orchestrator harvested your commits is \`trantor sync\` run from your worktree: it reads the harvest receipts and refuses when an unharvested commit would be lost, so never reset or rebase onto main by hand. A contract's \`base: <sha>\` line is the integration head: start your seat branch at that sha (\`git reset --hard <sha>\` on the fresh branch), never at origin/main, which trails the orchestrator's unpushed integration commits; the object is already here as the ref \`main\`. If \`git cat-file -e <sha>\` fails, say \`cannot resolve base <sha>\` on the bus and move the card to blocked instead of reasoning from origin/main. Every testing/done note names the sha you verified against as \`verified at <sha>\`; a note without it is flagged HOLLOW. Cross-project action is a breach: never \`trantor up\` a crew, register a seat, or send a card/contract into a project other than ${PROJ} unless the operator ran \`trantor policy link ${PROJ} <other> --reason "<why>"\` first — the hub, the CLI and this runner all refuse it mechanically, so ask the operator to link the projects instead of routing around the refusal.`;
323
+ const RULES = process.env.RUNNER_RULES || `Rules: you are ${SESSION} on the trantor crew. Before starting a card, read YOUR card: relay_board with card:<id> (the card, its deps, its notes, and the last five done cards whose title shares a word); never the whole board. If your wake names no card id (or cites only a message-card), make relay_board with mine:true your FIRST call — it lists the cards assigned to you (doing/testing/todo, newest first, full card shape); work your newest one (#7763). After long read-only recon, commit a WIP note with findings so the turn leaves evidence. Work your assigned file(s), report on the bus (relay_send, <280 chars), move your Kanban card as you go with a NOTE saying what you did (doing -> testing, then STOP: you never close your own card to done — the orchestrator runs the card's drill on the built artifact and closes it, and the hub refuses a move to done on a card with no drill line anyway; in 'testing' run YOUR OWN test file — never the full npm test, suites collide across seats — plus \`node bin/slop-gate.mjs\` when the repo has one: it lints ONLY your changed files against the anti-slop rules, and a card must not reach testing with slop-gate failing; use 'failed' + a report if anything breaks). If your work starts containers or a dev server (\`supabase start\`, \`docker run\`, a watch process), stop them before moving your card to testing and name them in the note — the runner also stops containers it saw your turn create when the card closes, but the first responsibility is yours (#9778). If a contract omits a fact you cannot proceed without, ASK — never invent the value: relay_ask(<card>, <question>) blocks the card with your question, keeps the turn owed (no park, no failure), and resumes you when the assigner's answer lands; an invented value that reads as reasoned is the worst outcome this crew ships (#7756). If you need something from another session, message THAT SESSION (relay_peers to find its id, relay_send to reach it) — never ask the human to pass it along; carrying messages between agents is the job this bus exists to remove. When your work for THIS message is finished, END YOUR TURN — do NOT park, do NOT loop relay_wait; the runner waits for you and will wake you with the next message. Path discipline: build/test from your worktree root ${TURN_DIR} with absolute paths or --manifest-path/--prefix instead of cd-ing into subdirs, and put anything that must land outside the repo under ${TURN_DIR}/.agent-bus-out/ (gitignored) — never ~/.agent-bus. Realigning your seat branch after the orchestrator harvested your commits is \`trantor sync\` run from your worktree: it reads the harvest receipts and refuses when an unharvested commit would be lost, so never reset or rebase onto main by hand. A contract's \`base: <sha>\` line is the integration head, and the runner has already aligned your seat branch to it before your turn starts, saving any unharvested commit to harvest/<card> first (#13961). Never \`git reset\`, \`rebase\` or \`checkout\` your seat branch yourself: a hand reset skips that save and silently drops finished work. If HEAD doesn't contain the base (\`git merge-base --is-ancestor <sha> HEAD\` fails), say \`cannot resolve base <sha>\` on the bus and move the card to blocked instead of working from somewhere else. Every testing/done note names the sha you verified against as \`verified at <sha>\`; a note without it is flagged HOLLOW. Cross-project action is a breach: never \`trantor up\` a crew, register a seat, or send a card/contract into a project other than ${PROJ} unless the operator ran \`trantor policy link ${PROJ} <other> --reason "<why>"\` first — the hub, the CLI and this runner all refuse it mechanically, so ask the operator to link the projects instead of routing around the refusal.`;
316
324
 
317
325
  // ---- the pulse --------------------------------------------------------------
318
326
  // RUNNER_PULSE_MS re-runs an orchestrator seat's mission note on a cadence when the bus is silent;
@@ -933,7 +941,10 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
933
941
  // #6393: the store's keys ride the spawn env under shadow names and the shell re-exports them
934
942
  // AFTER the sources ran, so the keychain wins over a stale .env line and no file is ever copied.
935
943
  const secrets = resolveSecrets(process.env);
936
- cmd = withEnvFiles(withSecretExports(seatSignalPrefix(TURN_DIR) + cmd, Object.keys(secrets)), envs);
944
+ // #13923: the instance stamp rides the turn shell so the CLI's own MCP server (relay_board mine)
945
+ // fences inherited assignments with the SAME clock the runner's own-card resolution uses.
946
+ const bootStamp = `export TRANTOR_SEAT_BOOT_TS=${BOOT_TS}\n`;
947
+ cmd = withEnvFiles(withSecretExports(seatSignalPrefix(TURN_DIR) + bootStamp + cmd, Object.keys(secrets)), envs);
937
948
  log(`turn starting (${isFirst ? "fresh session" : "resume"})${MODEL ? ` · model=${MODEL}` : ""}`);
938
949
  // #7777: the one effort line — which effort parameters were set, or that the model is uncatalogued.
939
950
  if (turnEffort.changed) log(`effort: ${turnEffort.effort.difficulty} for #${sessionCard} (launch ${EFFORT?.difficulty || "none"}) — ${turnEffort.text}`);
@@ -1057,7 +1068,7 @@ exit $turn_exit`;
1057
1068
  detached: true,
1058
1069
  cwd: TURN_DIR, encoding: "utf8", stdio: cli.sid ? ["ignore", "pipe", "inherit"] : ["ignore", "inherit", "inherit"],
1059
1070
  };
1060
- const spawnEnv = { ...process.env, ...shadowEnv(secrets), RELAY_URL: HUB, RELAY_AGENT: AGENT, RELAY_SESSION: SESSION, RELAY_PROJECT: PROJ,
1071
+ const spawnEnv = { ...seatBuildCacheEnv(process.env, PROJ), ...shadowEnv(secrets), RELAY_URL: HUB, RELAY_AGENT: AGENT, RELAY_SESSION: SESSION, RELAY_PROJECT: PROJ,
1061
1072
  // #6228: marks this env as belonging to PROJ, unlike a one-off RELAY_PROJECT override; crew.mjs's
1062
1073
  // `up` guard refuses to bring up another project's crew from a shell carrying this badge.
1063
1074
  TRANTOR_SEAT: PROJ,
@@ -1508,15 +1519,29 @@ function askedExcerpt(message) {
1508
1519
  // bus message parked on the board is never work, and chasing one (or a phantom id) is how a turn
1509
1520
  // burns on bookkeeping. Only a CONFIRMED message-card title reroutes, to the seat's OWN newest
1510
1521
  // open card (same statuses/ordering as relay_board's mine view); a phantom binds nothing.
1511
- async function newestOwnCard(session, why) {
1522
+
1523
+ // #13923: the reroute lands only on a card THIS instance may work (newer than its start, or
1524
+ // contracted to it after) — never an assignment the reused name inherited from a predecessor.
1525
+ async function newestOwnCard(session, why, messages = []) {
1512
1526
  try {
1513
1527
  const { tasks } = await api(`/tasks?project=${encodeURIComponent(PROJ)}`);
1514
1528
  const own = (Array.isArray(tasks) ? tasks : [])
1515
- .filter((t) => t.assignee === session && OPEN_CARD_STATUSES.includes(t.status) && !isMessageCardTitle(t.title))
1516
- .sort((a, b) => (b.updated || b.ts || 0) - (a.updated || a.ts || 0));
1517
- if (own.length) log(`${why} — resolved to the seat's own #${own[0].id} (${own[0].status})`);
1529
+ .filter((t) => t.assignee === session && OPEN_CARD_STATUSES.includes(t.status) && !isMessageCardTitle(t.title));
1530
+ let eligible = own;
1531
+ if (own.some((t) => (Number(t.ts) || 0) < BOOT_TS)) {
1532
+ // Contracts in hand (this wake batch) plus everything the hub still shows as delivered to
1533
+ // this session — a contract consumed turns ago still counts, so long as it is post-boot.
1534
+ const contracted = contractedCardIds(messages, { session, bootTs: BOOT_TS });
1535
+ try {
1536
+ const r = await api(`/inbox?session=${encodeURIComponent(session)}&since=0&peek=1`);
1537
+ for (const id of contractedCardIds(r?.messages, { session, bootTs: BOOT_TS })) contracted.add(id);
1538
+ } catch { /* inbox unreadable: the in-hand batch still decides; the fence holds */ }
1539
+ eligible = own.filter((t) => ownCardForInstance(t, { bootTs: BOOT_TS, contractedIds: contracted }));
1540
+ }
1541
+ const list = eligible.sort((a, b) => (b.updated || b.ts || 0) - (a.updated || a.ts || 0));
1542
+ if (list.length) log(`${why} — resolved to the seat's own #${list[0].id} (${list[0].status})`);
1518
1543
  else log(`${why} — and the seat has no open card, so this turn carries no card binding`);
1519
- return own.length ? own[0].id : 0;
1544
+ return list.length ? list[0].id : 0;
1520
1545
  } catch { return 0; } // board unreadable: no binding beats a guessed one
1521
1546
  }
1522
1547
  async function resolveWakeCard(messages, { session }) {
@@ -1527,7 +1552,7 @@ async function resolveWakeCard(messages, { session }) {
1527
1552
  try {
1528
1553
  const { task } = await api(`/card?project=${encodeURIComponent(PROJ)}&id=${cited}`);
1529
1554
  if (!task) { log(`#${cited}: the wake cites a card this board does not have — no card binding; the mine view is the first call`); return 0; }
1530
- if (isMessageCardTitle(task.title)) return newestOwnCard(session, `#${cited} is a message-card ("${String(task.title).slice(0, 60)}")`);
1555
+ if (isMessageCardTitle(task.title)) return newestOwnCard(session, `#${cited} is a message-card ("${String(task.title).slice(0, 60)}")`, messages);
1531
1556
  return cited;
1532
1557
  } catch { return cited; } // hub unreachable: keep the pre-#7763 reading rather than drop a contract
1533
1558
  }
@@ -1626,7 +1651,7 @@ async function resolveWakeCard(messages, { session }) {
1626
1651
  writeFileSync(PENDF, JSON.stringify({ persona: PERSONA, agent: AGENT, project: PROJ, ts: Date.now(),
1627
1652
  wake: pendingWake, bcast: pendingBcast, seen: seenLedger, ask: awaitingAsk?.id || 0, askTo: awaitingAsk?.to || "" }));
1628
1653
  const state = { cursor, turn: TURN, sid, sessionCard, retryAt, deliveryFails,
1629
- noDeliveryRetry, askReleased, lastTurnAt, attempted: [...attemptedVersions],
1654
+ noDeliveryRetry, askReleased, lastTurnAt, attempted: [...attemptedVersions], bootTs: BOOT_TS,
1630
1655
  cardTokens, cardCommits, cardStartedAt, budgetStop, budgetRetryAt,
1631
1656
  capHandoffs, capLogged, capArmed, capFreshTurn };
1632
1657
  process.execve(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)],
@@ -1636,6 +1661,17 @@ async function resolveWakeCard(messages, { session }) {
1636
1661
  if (PULSE_MS) log(`pulse armed — mission re-read every ${Math.round(PULSE_MS / 1000)}s (${MISSION_FILE})`);
1637
1662
  log(`parked — long-polling the bus as ${SESSION} (free; this poll is also the heartbeat)`);
1638
1663
 
1664
+ // #13920: machine health heartbeat — opt-in via config.json healthHeartbeat:true (plus a valid
1665
+ // machineLabel, read at boot). One small signed POST every HEALTH_BEAT_MS; failures stay silent
1666
+ // by the monitoring doctrine (state not event — a machine that stops beating reads stale on the
1667
+ // hub, which IS the honest "unreachable" signal, not an error to alert on).
1668
+ if (machineConfig.healthHeartbeat === true && MACHINE_LABEL) {
1669
+ const beat = () => api("/machines/health", { ...healthPayload(defaultOs, MACHINE_LABEL), project: PROJ }).catch(() => {});
1670
+ beat();
1671
+ setInterval(beat, HEALTH_BEAT_MS).unref?.();
1672
+ log(`machine health heartbeat armed as ${MACHINE_LABEL} every ${Math.round(HEALTH_BEAT_MS / 1000)}s`);
1673
+ }
1674
+
1639
1675
  while (true) {
1640
1676
  restartForRelease();
1641
1677
  // pulse first: a due mission beat runs even on a silent bus. Measured from the END of the
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { execFileSync } from "node:child_process";
6
+
7
+ const args = process.argv.slice(2);
8
+ let since = "1h";
9
+ for (let i = 0; i < args.length; i++) {
10
+ if (args[i] === "--since" && args[i + 1]) since = args[++i];
11
+ else { console.error("usage: trantor hub timeouts [--since 1h]"); process.exit(2); }
12
+ }
13
+ const match = since.match(/^(\d+)(m|h|d)$/);
14
+ if (!match) { console.error("--since must be a duration such as 30m, 1h, or 2d"); process.exit(2); }
15
+ const amount = Number(match[1]);
16
+ const ageMs = amount * ({ m: 60_000, h: 3_600_000, d: 86_400_000 })[match[2]];
17
+ const cutoff = Date.now() - ageMs;
18
+ const sinceArg = `${amount} ${match[2] === "m" ? "minute" : match[2] === "h" ? "hour" : "day"}${amount === 1 ? "" : "s"} ago`;
19
+ const busDir = process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
20
+ const receiptFile = process.env.TRANTOR_HUB_TIMEOUTS_FILE || join(busDir, "hub-timeouts.jsonl");
21
+ let receipts = [];
22
+ if (existsSync(receiptFile)) {
23
+ receipts = readFileSync(receiptFile, "utf8").split("\n").filter(Boolean).flatMap(line => {
24
+ try {
25
+ const row = JSON.parse(line);
26
+ return Date.parse(row.ts) >= cutoff ? [{ time: Date.parse(row.ts), kind: "client timeout", text: `${row.route} op=${row.op} elapsed=${row.elapsedMs}ms hub=${row.hubUrl}` }] : [];
27
+ } catch { return []; }
28
+ });
29
+ }
30
+
31
+ let journal = "";
32
+ const remote = process.env.TRANTOR_HUB_SSH;
33
+ if (process.env.TRANTOR_HUB_JOURNAL_FILE) {
34
+ journal = readFileSync(process.env.TRANTOR_HUB_JOURNAL_FILE, "utf8");
35
+ } else {
36
+ const command = ["journalctl", "-u", "trantor-hub", "--since", sinceArg, "--output=short-iso", "--no-pager"];
37
+ try {
38
+ journal = remote
39
+ ? execFileSync("ssh", [remote, "journalctl", "-u", "trantor-hub", "--since", sinceArg, "--output=short-iso", "--no-pager"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
40
+ : execFileSync(command[0], command.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
41
+ } catch { journal = ""; }
42
+ }
43
+ const journalRows = journal.split("\n").filter(line => /\[trantor\] (event-loop stall|slow request)/.test(line)).flatMap(line => {
44
+ const iso = line.match(/^(\d{4}-\d\d-\d\d[T ][0-9:.+-]+Z?)/)?.[1];
45
+ const time = Date.parse(iso || "");
46
+ return Number.isFinite(time) && time >= cutoff ? [{ time, kind: "hub", text: line }] : [];
47
+ });
48
+ const rows = [...receipts, ...journalRows].sort((a, b) => a.time - b.time);
49
+ console.log(`Hub diagnostics for the last ${since}${remote ? ` (journal via ssh ${remote})` : " (local journal only; set TRANTOR_HUB_SSH to include the remote hub journal)"}`);
50
+ if (!rows.length) console.log("No matching hub timeouts, event-loop stalls, or slow requests in this window.");
51
+ for (const row of rows) console.log(`${new Date(row.time).toISOString()} [${row.kind}] ${row.text}`);
package/hooks/lib/api.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // Wraps lib/signed-fetch.mjs (#3916) with hub URL resolution per project (§12.1), session identity
3
3
  // (the same derivation mcp.mjs uses) and the Ed25519 keypair. FAIL-OPEN IS A CONTRACT (acceptance §9
4
4
  // #10): getJSON/signedPost never throw; no key means unsigned, and only the hub knows its RELAY_AUTH policy.
5
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
5
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  import { resolveProject, hostId, resolveHub } from "../../lib/project.mjs";
@@ -12,6 +12,22 @@ import { sfetchJson } from "../../lib/signed-fetch.mjs";
12
12
  export const DEFAULT_TIMEOUT_MS = 1500;
13
13
  export const WRITE_TIMEOUT_MS = 8000; // #7755: writes get their own budget above the read default
14
14
 
15
+ function recordAmbiguousTimeout(pathOrUrl, op, elapsedMs, project) {
16
+ const busDir = process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
17
+ const file = join(busDir, "hub-timeouts.jsonl");
18
+ const row = {
19
+ ts: new Date().toISOString(),
20
+ route: String(pathOrUrl),
21
+ op,
22
+ elapsedMs,
23
+ hubUrl: relayUrl(project),
24
+ };
25
+ try {
26
+ mkdirSync(busDir, { recursive: true });
27
+ appendFileSync(file, `${JSON.stringify(row)}\n`, { mode: 0o600 });
28
+ } catch { /* timeout reporting must never change the fail-open result */ }
29
+ }
30
+
15
31
  // Hub URL, PER-PROJECT (TDD §12.1): env RELAY_URL, then config `hubs[project]`, then the legacy global
16
32
  // `url`, then the local default. Never throws, keeping hooks fail-open.
17
33
  export function relayUrl(project) {
@@ -180,6 +196,7 @@ export async function signedGet(pathOrUrl, { timeoutMs = DEFAULT_TIMEOUT_MS, ses
180
196
  // one GET /_op — committed returns the stored body as success, rejected returns the stored refusal,
181
197
  // unknown reads "ambiguous: timed out, outcome unknown". Never a bare failure for a write that landed.
182
198
  export async function signedPost(pathOrUrl, payload, { timeoutMs = WRITE_TIMEOUT_MS, session, instance, project } = {}) {
199
+ const startedAt = Date.now();
183
200
  const proj = projectOf(project, payload, pathOrUrl);
184
201
  const sess = session || sessionFor(proj);
185
202
  const durable = loadIdentity(sess);
@@ -193,6 +210,7 @@ export async function signedPost(pathOrUrl, payload, { timeoutMs = WRITE_TIMEOUT
193
210
  const st = q.ok ? q.json?.status : "unknown";
194
211
  if (st === "committed") return { ok: true, status: q.json.code || 200, json: q.json.body, resolved: "committed" };
195
212
  if (st === "rejected") return { ok: false, status: q.json.code || 400, json: q.json.body, resolved: "rejected" };
213
+ recordAmbiguousTimeout(pathOrUrl, op, Date.now() - startedAt, proj);
196
214
  return { ...f, ambiguous: true, reason: "ambiguous: timed out, outcome unknown" };
197
215
  };
198
216
  try {
package/hub/auth.mjs CHANGED
@@ -6,7 +6,7 @@ import { timingSafeEqual, randomBytes } from "node:crypto";
6
6
  import { publicView } from "../lib/identity.mjs";
7
7
  import { IDENTITY_KINDS } from "../lib/store-contract.mjs";
8
8
 
9
- export function createAuthRuntime({ state, markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS, LOOPBACK_BIND, ENROLL_MODE, seenNonces = new Map() }) {
9
+ export function createAuthRuntime({ state, markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS, LOOPBACK_BIND, ENROLL_MODE, seenNonces = new Map(), diagnostics = null }) {
10
10
  const now = () => Date.now();
11
11
  // Route measurements and supported envelopes: docs/REQUEST-BODY-LIMITS.md.
12
12
  const BODY_CAP_DEFAULT = 4 * 1024 * 1024;
@@ -61,7 +61,9 @@ async function body(req, maxBytes = BODY_CAP_DEFAULT) {
61
61
  function json(res, code, obj) {
62
62
  if (res.headersSent || res.writableEnded || res.destroyed) return false;
63
63
  res.writeHead(code, { "content-type": "application/json", "access-control-allow-origin": "*" });
64
- res.end(JSON.stringify(obj));
64
+ const payload = JSON.stringify(obj);
65
+ diagnostics?.recordStep("response.serialize", Buffer.byteLength(payload));
66
+ res.end(payload);
65
67
  return true;
66
68
  }
67
69
  // Canonical project name: follow the alias chain so historically-divergent keys
@@ -96,7 +98,7 @@ const AUTH_HEADERS = ["x-trantor-pubkey", "x-trantor-sig", "x-trantor-ts", "x-tr
96
98
  const PUBLIC_ENDPOINTS = new Set(["/", "/ui", "/health", "/enroll"]);
97
99
  const OWNER_ENDPOINTS = new Set(["/project/delete", "/sweep", "/reconcile", "/invite", "/import", "/policy", "/session/prompts", "/session/prompt/claim", "/session/prompt/ack", "/session/attachment"]);
98
100
  const DEVICE_ENDPOINTS = new Set(["/device/register", "/device/unregister", "/devices"]);
99
- const READ_ENDPOINTS = new Set(["/peers", "/tasks", "/events", "/inbox", "/peer", "/card", "/stream", "/history", "/projects", "/catchup", "/phases", "/recent", "/handoffs", "/verify-gates", "/claims", "/proposals", "/grants", "/overseer/context", "/overseer/status", "/session/chat", "/session/prompt", "/crew/roster"]);
101
+ const READ_ENDPOINTS = new Set(["/peers", "/tasks", "/events", "/inbox", "/peer", "/card", "/stream", "/history", "/projects", "/catchup", "/phases", "/recent", "/handoffs", "/verify-gates", "/claims", "/proposals", "/grants", "/overseer/context", "/overseer/status", "/session/chat", "/session/prompt", "/crew/roster", "/machines/health"]);
100
102
  const roleRank = { read: 1, write: 2, approver: 3, owner: 4 };
101
103
  const hasAuthHeaders = (req) => AUTH_HEADERS.some(h => !!req.headers[h]);
102
104
  const authPath = (u) => `${u.pathname}${u.search || ""}`;
package/hub/public.mjs CHANGED
@@ -4,7 +4,8 @@ import { HDR } from "../lib/identity.mjs";
4
4
  const ALLOWED = new Set([
5
5
  ...["/health", "/projects", "/catchup", "/tasks", "/card", "/events", "/stream",
6
6
  "/inbox", "/poll", "/recent", "/peers", "/holds", "/verify-gates", "/proposals",
7
- "/balances", "/economics", "/session/chat", "/session/prompt", "/crew/roster", "/_op"]
7
+ "/balances", "/economics", "/session/chat", "/session/prompt", "/crew/roster",
8
+ "/machines/health", "/_op"]
8
9
  .map(path => `GET ${path}`),
9
10
  ...["/enroll", "/task/update", "/task/checklist-toggle", "/send", "/delivered",
10
11
  "/verify-gate", "/hold/decide", "/proposal/decide", "/session/prompt", "/session/answer",
@@ -34,6 +34,12 @@ export async function routeMessages({ req, res, q, P, auth, ctx }) {
34
34
  // it (#6134). Stored only when false — absent means wake, so every older client is unchanged.
35
35
  const wake = b.wake === false ? { wake: false } : {};
36
36
  const msg = { id: ++state.seq, ts: now(), from: b.from || "anon", to: b.to || "all", text, project: String(b.project || fromProj || "").slice(0, 80), ...(re ? { re } : {}), ...(kind ? { kind } : {}), ...wake };
37
+ const peer = state.peers[msg.from];
38
+ if (msg.to === "all" && msg.kind === "status" && peer?.status === "crew member booting" && /^[A-Za-z0-9_.-]+ reporting — ready for a contract\b/.test(msg.text.trim())) {
39
+ peer.status = "idle";
40
+ peer.phase = "idle";
41
+ peer.phaseSince = msg.ts;
42
+ }
37
43
  state.messages.push(msg); if (state.messages.length > 5000) state.messages.splice(0, 1000);
38
44
  markDirty(); pushToStreams(msg); // <-- instant push to live watchers
39
45
  // Mirror onto the unified log. `refs` = the card ids this message cites (#3701), which is what
@@ -217,10 +217,23 @@ export function createSessionRuntime({ state, markDirty, appendEvent, pushEventT
217
217
  }
218
218
  }
219
219
 
220
- // #12140: the desktop publishes the seats its Mac can spawn (from `trantor provider status
221
- // --json`) at boot and every 10 minutes. Memory-only like the chat mirror — a restarted hub
222
- // has no roster until the desktop republishes.
223
- const roster = new Map(); // machine -> { machine, updatedAt, seats }
220
+ // #12140: the desktop publishes the seats its Mac can spawn (from `trantor provider status
221
+ // --json`) at boot and every 10 minutes. Memory-only like the chat mirror — a restarted hub
222
+ // has no roster until the desktop republishes.
223
+ const roster = new Map(); // machine -> { machine, updatedAt, seats }
224
+
225
+ // #13920: machine health heartbeat — the crew-runner on each seat-hosting machine POSTs its
226
+ // loadavg/memory every ~30s (config healthHeartbeat:true). Memory-only like the roster; the ts is
227
+ // the hub's RECEIVE time, never the sender's clock, so a skewed machine clock cannot poison the
228
+ // staleness math. Rows older than a day are pruned: a decommissioned machine must not read
229
+ // "stale" forever. State, not events — nothing here is appended to the audit log.
230
+ const machinesHealth = new Map(); // machine -> { machine, cpuPct, memUsed, memTotal, ts }
231
+ const HEALTH_STALE_MS = Number(process.env.RELAY_HEALTH_STALE_MS || 90_000);
232
+ const HEALTH_KEEP_MS = 24 * 60 * 60 * 1000;
233
+ function pruneMachinesHealth() {
234
+ const cut = now() - HEALTH_KEEP_MS;
235
+ for (const [m, h] of machinesHealth) if (h.ts < cut) machinesHealth.delete(m);
236
+ }
224
237
 
225
238
  async function route({ req, res, q, P, auth, ctx }) {
226
239
  const isChat = P === "/session/chat";
@@ -230,7 +243,8 @@ export function createSessionRuntime({ state, markDirty, appendEvent, pushEventT
230
243
  const isAnswer = P === "/session/answer";
231
244
  const isCrewCommand = P === "/crew/command";
232
245
  const isCrewRoster = P === "/crew/roster";
233
- if (!isChat && !isPrompts && !isPrompt && !isAttachment && !isAnswer && !isCrewCommand && !isCrewRoster) return false;
246
+ const isMachinesHealth = P === "/machines/health";
247
+ if (!isChat && !isPrompts && !isPrompt && !isAttachment && !isAnswer && !isCrewCommand && !isCrewRoster && !isMachinesHealth) return false;
234
248
  const { body, json, canon, scopeAllows } = ctx;
235
249
 
236
250
  // #12137: the phone's answer to an AskUserQuestion joins the SAME queue as a plain prompt,
@@ -346,6 +360,33 @@ export function createSessionRuntime({ state, markDirty, appendEvent, pushEventT
346
360
  return json(res, 200, { machines: [...roster.values()] });
347
361
  }
348
362
 
363
+ // #13920: a seat-signed POST (write on its own project, machine label from the body — the
364
+ // signer is a seat like "glm:trantor", not a machine, so the roster's signer-keying cannot
365
+ // apply). The label is held to the machineLabel grammar and every number is validated; the
366
+ // payload ts is ignored in favour of the hub's receive time.
367
+ if (req.method === "POST" && isMachinesHealth) {
368
+ const b = await body(req);
369
+ const machine = String(b.machine || "");
370
+ if (!/^[a-z0-9-]{1,24}$/.test(machine)) return json(res, 400, { error: "machine must match ^[a-z0-9-]{1,24}$" });
371
+ const cpuPct = Number(b.cpuPct);
372
+ if (!Number.isFinite(cpuPct) || cpuPct < 0 || cpuPct > 100000) return json(res, 400, { error: "cpuPct must be a finite percent (load can exceed 100)" });
373
+ const memUsed = Number(b.memUsed);
374
+ const memTotal = Number(b.memTotal);
375
+ if (!Number.isFinite(memUsed) || !Number.isFinite(memTotal) || memUsed < 0 || memTotal <= 0 || memUsed > memTotal) {
376
+ return json(res, 400, { error: "memUsed/memTotal must be bytes with used <= total" });
377
+ }
378
+ machinesHealth.set(machine, { machine, cpuPct: Math.round(cpuPct), memUsed: Math.round(memUsed), memTotal: Math.round(memTotal), ts: now() });
379
+ return json(res, 200, { ok: true, machine });
380
+ }
381
+
382
+ if (req.method === "GET" && isMachinesHealth) {
383
+ pruneMachinesHealth();
384
+ const machines = [...machinesHealth.values()]
385
+ .map(h => ({ ...h, stale: now() - h.ts > HEALTH_STALE_MS }))
386
+ .sort((a, b) => a.machine.localeCompare(b.machine));
387
+ return json(res, 200, { machines, staleAfterMs: HEALTH_STALE_MS });
388
+ }
389
+
349
390
  if (req.method === "POST" && isChat) {
350
391
  const b = await body(req);
351
392
  // the same canon the GET reads with, or a publish and a read could name two mirrors
package/hub/store.mjs CHANGED
@@ -4,7 +4,7 @@ import { randomBytes } from "node:crypto";
4
4
  import { createPersistHealth } from "../lib/persist-health.mjs";
5
5
  import { DEFAULT_ORG } from "../lib/store-contract.mjs";
6
6
 
7
- export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA }) {
7
+ export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics = null }) {
8
8
  function emptyState() {
9
9
  return { messages: [], peers: {}, seq: 0, tasks: [], taskSeq: 0, projectMeta: {}, lessons: [], events: [], cardEventsBackfilled: false, aliases: {}, phaseMeta: {}, verifyGates: [], verifyGateSeq: 0, proposals: [], proposalSeq: 0, balances: { ts: 0, by: "", entries: [] }, balancesByMachine: {}, subagentCostReset: false, handoffLog: [], identities: {}, devices: [], inviteTokens: {}, focus: {}, orgPolicy: {}, overseerState: {}, instances: {}, dutySession: "", contractReap: {}, eventSeq: 0, sessionPrompts: [], sessionPromptSeq: 0 };
10
10
  }
@@ -195,7 +195,9 @@ const snapshotState = () => {
195
195
  const cardEvents = events.filter(e => ["created", "moved", "updated"].includes(e?.type));
196
196
  const messages = state.messages.slice();
197
197
  const tasks = state.tasks.slice();
198
- const snapshot = JSON.parse(JSON.stringify({ ...state, events: [], cardEvents: [], messages: [], tasks: [] }));
198
+ const serialized = JSON.stringify({ ...state, events: [], cardEvents: [], messages: [], tasks: [] });
199
+ diagnostics?.recordStep("snapshot.serialize", Buffer.byteLength(serialized));
200
+ const snapshot = JSON.parse(serialized);
199
201
  snapshot.events = events;
200
202
  snapshot.cardEvents = cardEvents;
201
203
  snapshot.messages = messages;
@@ -233,7 +235,9 @@ const persist = () => {
233
235
  return;
234
236
  }
235
237
  try {
236
- writeFileSync(DATA, JSON.stringify(snapshotState()));
238
+ const serialized = JSON.stringify(snapshotState());
239
+ diagnostics?.recordStep("json.persist.serialize", Buffer.byteLength(serialized));
240
+ writeFileSync(DATA, serialized);
237
241
  dirty = false;
238
242
  persistHealth.succeeded();
239
243
  } catch (e) {
package/hub.mjs CHANGED
@@ -21,6 +21,7 @@ import { routeMessages } from "./hub/routes/messages.mjs";
21
21
  import { routeDevices } from "./hub/routes/devices.mjs";
22
22
  import { createSessionRuntime } from "./hub/routes/session.mjs";
23
23
  import { createNotifier } from "./hub/notifier.mjs";
24
+ import { createHubDiagnostics } from "./lib/hub-diagnostics.mjs";
24
25
 
25
26
  const PORT = Number(process.env.RELAY_PORT || 4477);
26
27
  const HOST = process.env.RELAY_HOST || "127.0.0.1";
@@ -65,11 +66,12 @@ if (!LOOPBACK_BIND && AUTH_MODE !== "enforce") {
65
66
  process.exit(1);
66
67
  }
67
68
 
68
- const store = await createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA });
69
+ const diagnostics = createHubDiagnostics();
70
+ const store = await createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics });
69
71
  const seenNonces = new Map();
70
72
  const authRuntime = createAuthRuntime({
71
73
  state: store.state, markDirty: store.markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS,
72
- LOOPBACK_BIND, ENROLL_MODE, seenNonces,
74
+ LOOPBACK_BIND, ENROLL_MODE, seenNonces, diagnostics,
73
75
  });
74
76
  const notifier = createNotifier({ state: store.state, markDirty: store.markDirty, canRead: authRuntime.canRead });
75
77
  const events = createEventRuntime({ state: store.state, markDirty: store.markDirty, AUTH_MODE, ONLINE_MS, canon: authRuntime.canon, notifier });
@@ -140,12 +142,16 @@ const routes = [routeDevices, routeAdmin, routeCards, routeInsights, routeMessag
140
142
 
141
143
  const publicAuth = createAuthRuntime({
142
144
  state: store.state, markDirty: store.markDirty, AUTH_MODE: "enforce", SUPERSEDE_GRACE_MS,
143
- LOOPBACK_BIND: true, ENROLL_MODE: "invite", seenNonces,
145
+ LOOPBACK_BIND: true, ENROLL_MODE: "invite", seenNonces, diagnostics,
144
146
  });
145
147
  const publicContext = { ...context, ...publicAuth, AUTH_MODE: "enforce" };
146
148
 
147
149
  function requestHandler(runtime, ctx, gate = null) {
148
150
  return async (req, res) => {
151
+ diagnostics.beginRequest(req);
152
+ const finish = () => diagnostics.endRequest(req, res);
153
+ res.once("finish", finish);
154
+ res.once("close", finish);
149
155
  try {
150
156
  const u = new URL(req.url, "http://x");
151
157
  const q = Object.fromEntries(u.searchParams);
@@ -190,6 +196,7 @@ function requestHandler(runtime, ctx, gate = null) {
190
196
  };
191
197
  }
192
198
 
199
+ diagnostics.start();
193
200
  const server = http.createServer(requestHandler(authRuntime, context));
194
201
  server.listen(PORT, HOST, () => console.error(`[trantor] hub on http://${HOST}:${PORT} (auth: ${AUTH_MODE}; data: ${DATA})`));
195
202
 
package/lib/disk.mjs CHANGED
@@ -26,7 +26,7 @@ export const JUNK_DIRS = ["node_modules", ".next", "target", "dist", "build", ".
26
26
  export const DRILL_DIR = ".agent-bus-out";
27
27
  export const LOW_SPACE_BYTES = 50 * 1024 ** 3;
28
28
  export const ALARM_SPACE_BYTES = 15 * 1024 ** 3;
29
- const ON_DISK_TYPES = ["build-dir", "scratch-entry", "seat-worktree", "build-output", "build-junk", "drill-output"];
29
+ const ON_DISK_TYPES = ["build-dir", "scratch-entry", "seat-worktree", "build-output", "build-junk", "drill-output", "shared-cache"];
30
30
 
31
31
  const GB = 1024 ** 3;
32
32
  const KB = 1024;
@@ -84,6 +84,7 @@ function defaults(d = {}) {
84
84
  now: d.now || Date.now(),
85
85
  worktreesRoot: d.worktreesRoot || null,
86
86
  cwds: d.cwds || memoCwds(d.exec),
87
+ isPidAlive: d.isPidAlive,
87
88
  log: d.log || console.log,
88
89
  entryBudget: d.entryBudget || 400_000,
89
90
  };
@@ -95,6 +96,56 @@ export function worktreesRootFor(d) {
95
96
  return d.worktreesRoot || join(d.home || homedir(), ".agent-bus", "worktrees");
96
97
  }
97
98
 
99
+ export function cacheRootFor(d) {
100
+ return join(d.home || homedir(), ".agent-bus", "cache");
101
+ }
102
+
103
+ export function hasActiveHeavyGate({ fs = nodeFs, home = homedir(), isPidAlive = (pid) => {
104
+ try { process.kill(pid, 0); return true; } catch (error) { return error?.code !== "ESRCH"; }
105
+ } } = {}) {
106
+ const lockDir = join(home, ".agent-bus", "heavy-gate");
107
+ let entries;
108
+ try { entries = fs.readdirSync(lockDir, { withFileTypes: true }); } catch { return false; }
109
+ return entries.some((entry) => {
110
+ if (!entry.isFile() || !/^slot-\d+\.json$/.test(entry.name)) return false;
111
+ try {
112
+ const row = JSON.parse(fs.readFileSync(join(lockDir, entry.name), "utf8"));
113
+ return Number.isSafeInteger(row.pid) && isPidAlive(row.pid);
114
+ } catch { return false; }
115
+ });
116
+ }
117
+
118
+ // Shared cache output uses the same three-day idle window as per-seat build output. A gate
119
+ // can compile from any project's cache, so an active slot protects every shared cache.
120
+ export function scanSharedBuildCache(d) {
121
+ const dep = defaults(d);
122
+ const { fs, home, now } = dep;
123
+ if (hasActiveHeavyGate({ fs, home, isPidAlive: d.isPidAlive }))
124
+ return { plan: [], kept: [{ path: cacheRootFor(d), reason: "KEPT: a heavy-gate slot is active" }] };
125
+ const root = cacheRootFor(d), plan = [], kept = [];
126
+ let projects;
127
+ try { projects = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()); }
128
+ catch { return { plan, kept }; }
129
+ for (const project of projects) {
130
+ const projectDir = join(root, project.name);
131
+ for (const name of ["cargo-target", "DerivedData"]) {
132
+ const path = join(projectDir, name);
133
+ let stat;
134
+ try { stat = fs.statSync(path); } catch { continue; }
135
+ if (!stat.isDirectory()) continue;
136
+ const size = dirSize(fs, path, d);
137
+ if (size.partial) { kept.push({ path, reason: "KEPT: size walk exceeded entry budget" }); continue; }
138
+ if (size.maxMtime > now - BUILD_OUTPUT_IDLE_MAX) {
139
+ kept.push({ path, reason: `KEPT: cache was touched within ${BUILD_OUTPUT_IDLE_MAX / DAY} days` });
140
+ continue;
141
+ }
142
+ plan.push({ type: "shared-cache", path, project: project.name, bytes: size.bytes });
143
+ }
144
+ }
145
+ plan.sort((a, b) => b.bytes - a.bytes);
146
+ return { plan, kept };
147
+ }
148
+
98
149
  // Recursive size walk. Skips symlinks entirely — a worktree symlink must not make
99
150
  // us measure (or later rm) outside its root. Budget caps pathological trees. Dirs are
100
151
  // statted too: a rename into an old tree updates the DIR mtime, not the file's, and
@@ -533,6 +584,7 @@ export function buildDiskReport(d) {
533
584
  const seats = scanSeatWorktrees({ ...dep, entryBudget: dep.entryBudget });
534
585
  const stale = scanStaleWorktrees({ ...dep, entryBudget: dep.entryBudget });
535
586
  const nested = scanNestedBuildOutput({ ...dep, entryBudget: dep.entryBudget });
587
+ const sharedCache = scanSharedBuildCache({ ...dep, entryBudget: dep.entryBudget });
536
588
  const junk = scanDeadWorktreeOutput({ ...dep, entryBudget: dep.entryBudget });
537
589
  const sessions = scanOpencodeSessions(dep);
538
590
  const sims = scanSimulators(dep);
@@ -549,8 +601,8 @@ export function buildDiskReport(d) {
549
601
  hf: reportHfCache(dep),
550
602
  claudeWorktrees: reportClaudeWorktrees(dep),
551
603
  bigFiles: collectBigFiles(dep),
552
- plan: mergePlans([...sims.plan, ...seats.plan, ...stale.plan, ...nested.plan], stale.plan, junk.plan).concat(sessions.plan),
553
- kept: [...seats.kept, ...stale.kept, ...nested.kept].filter((k) => !junk.plan.some((j) => isUnder(k.path, j.path))).concat(junk.kept, sessions.kept),
604
+ plan: mergePlans([...sims.plan, ...seats.plan, ...stale.plan, ...nested.plan, ...sharedCache.plan], stale.plan, junk.plan).concat(sessions.plan),
605
+ kept: [...seats.kept, ...stale.kept, ...nested.kept, ...sharedCache.kept].filter((k) => !junk.plan.some((j) => isUnder(k.path, j.path))).concat(junk.kept, sessions.kept),
554
606
  };
555
607
  return report;
556
608
  }
@@ -624,11 +676,19 @@ export async function runClean(r, d) {
624
676
  try {
625
677
  if (item.path) {
626
678
  const p = assertUnderHome(item.path, home);
627
- if (!isUnder(p, root)) throw new Error(`refused: ${p} is not under the seat worktrees root`);
628
- const [project, seat] = relative(root, p).split(sep);
629
- if (!project || !seat) throw new Error("refused: path does not identify a seat worktree");
630
- const reason = seatRetentionReason(dep, project, seat, join(root, project, seat));
631
- if (reason) throw new Error(reason);
679
+ if (item.type === "shared-cache") {
680
+ const cacheRoot = cacheRootFor(dep);
681
+ const cacheParts = relative(cacheRoot, p).split(sep);
682
+ if (!isUnder(p, cacheRoot) || cacheParts.length !== 2 || !["cargo-target", "DerivedData"].includes(cacheParts[1]))
683
+ throw new Error(`refused: ${p} is not a project cache directory`);
684
+ if (hasActiveHeavyGate({ fs: dep.fs, home, isPidAlive: dep.isPidAlive })) throw new Error("refused: a heavy-gate slot is active");
685
+ } else {
686
+ if (!isUnder(p, root)) throw new Error(`refused: ${p} is not under the seat worktrees root`);
687
+ const [project, seat] = relative(root, p).split(sep);
688
+ if (!project || !seat) throw new Error("refused: path does not identify a seat worktree");
689
+ const reason = seatRetentionReason(dep, project, seat, join(root, project, seat));
690
+ if (reason) throw new Error(reason);
691
+ }
632
692
  }
633
693
  if (item.type === "simulators") {
634
694
  exec("xcrun", ["simctl", "delete", "unavailable"]);
@@ -643,6 +703,12 @@ export async function runClean(r, d) {
643
703
  const g = exec("git", ["-C", p, "worktree", "remove", p]);
644
704
  if (g.status !== 0) throw new Error(String(g.stderr || "git worktree remove failed").trim().split("\n")[0] || "git worktree remove failed");
645
705
  results.push({ type: item.type, path: p, bytes: item.bytes || 0, ok: true });
706
+ } else if (item.type === "shared-cache") {
707
+ if (hasActiveHeavyGate({ fs: dep.fs, home, isPidAlive: dep.isPidAlive })) throw new Error("refused: a heavy-gate slot is active");
708
+ const stat = dirSize(dep.fs, item.path, dep);
709
+ if (stat.partial || stat.maxMtime > dep.now - BUILD_OUTPUT_IDLE_MAX) throw new Error("refused: cache changed or is too recent");
710
+ remove(item.path, { recursive: true, force: true });
711
+ results.push({ type: item.type, path: item.path, bytes: item.bytes || 0, ok: true });
646
712
  } else if (["build-dir", "build-output", "scratch-entry", "build-junk", "drill-output"].includes(item.type)) {
647
713
  const p = assertUnderHome(item.path, home);
648
714
  if (!isUnder(p, root)) throw new Error(`refused: ${p} is not under the seat worktrees root`);
@@ -0,0 +1,81 @@
1
+ import { monitorEventLoopDelay } from "node:perf_hooks";
2
+
3
+ // Long-lived by design (long-poll, SSE): never "slow", and never the cause of a stall.
4
+ const LONG_LIVED = new Set(["/poll", "/stream"]);
5
+
6
+ const clean = value => String(value || "unknown").replace(/[\r\n]/g, " ").slice(0, 160);
7
+
8
+ export function createHubDiagnostics({
9
+ lagThresholdMs = 500,
10
+ slowRequestThresholdMs = 1000,
11
+ sampleIntervalMs = 100,
12
+ logIntervalMs = 1000,
13
+ now = Date.now,
14
+ log = line => process.stdout.write(`${line}\n`),
15
+ histogram = null,
16
+ } = {}) {
17
+ const delay = histogram || monitorEventLoopDelay({ resolution: 20 });
18
+ const inFlight = new Map();
19
+ let lastStep = null;
20
+ let lastLagLog = -Infinity;
21
+ let lastSlowLog = -Infinity;
22
+ let timer = null;
23
+
24
+ const recordStep = (name, bytes) => {
25
+ lastStep = { name: clean(name), bytes: Math.max(0, Number(bytes) || 0), at: now() };
26
+ };
27
+
28
+ const checkLag = () => {
29
+ const durationMs = delay.max / 1e6;
30
+ delay.reset();
31
+ const at = now();
32
+ const requests = [...inFlight.values()];
33
+ for (const [req, detail] of inFlight) if (detail.endedAt) inFlight.delete(req);
34
+ if (durationMs <= lagThresholdMs || at - lastLagLog < logIntervalMs) return;
35
+ lastLagLog = at;
36
+ const routes = requests
37
+ .map(req => `${req.method} ${req.path} (${Math.max(0, Math.round((req.endedAt || at) - req.startedAt))}ms)`)
38
+ .slice(0, 3)
39
+ .join(", ");
40
+ const step = lastStep
41
+ ? `${lastStep.name} bytes=${lastStep.bytes} age=${Math.max(0, at - lastStep.at)}ms`
42
+ : "none";
43
+ log(`[trantor] event-loop stall ${Math.round(durationMs)}ms (>${lagThresholdMs}ms); inFlight=${routes || "none"}; lastStep=${step}`);
44
+ };
45
+
46
+ return {
47
+ recordStep,
48
+ checkLag,
49
+ beginRequest(req) {
50
+ let path = "unknown";
51
+ try { path = new URL(req.url, "http://x").pathname; } catch {}
52
+ if (LONG_LIVED.has(path)) return;
53
+ const key = String(req.headers?.["x-trantor-pubkey"] || "").slice(0, 8);
54
+ const who = clean(`${req.socket?.remoteAddress || "unknown"}${key ? ` key:${key}` : ""}`);
55
+ inFlight.set(req, { method: clean(req.method), path: clean(path), who, startedAt: now() });
56
+ },
57
+ endRequest(req, res) {
58
+ const detail = inFlight.get(req);
59
+ if (!detail) return;
60
+ const endedAt = now();
61
+ detail.endedAt = endedAt;
62
+ const durationMs = endedAt - detail.startedAt;
63
+ if (durationMs > slowRequestThresholdMs && endedAt - lastSlowLog >= logIntervalMs) {
64
+ lastSlowLog = endedAt;
65
+ const bodyBytes = Math.max(0, Number(req._bodyBytes ?? req.headers?.["content-length"]) || 0);
66
+ log(`[trantor] slow request ${detail.method} ${detail.path} ${Math.round(durationMs)}ms (>${slowRequestThresholdMs}ms) body=${bodyBytes}B status=${res?.statusCode || 0} from=${detail.who}`);
67
+ }
68
+ },
69
+ start() {
70
+ if (timer) return;
71
+ delay.enable();
72
+ timer = setInterval(checkLag, sampleIntervalMs);
73
+ timer.unref?.();
74
+ },
75
+ stop() {
76
+ if (timer) clearInterval(timer);
77
+ timer = null;
78
+ delay.disable();
79
+ },
80
+ };
81
+ }
@@ -0,0 +1,27 @@
1
+ // #13920: machine health heartbeat payload — one source for the shape the runner posts and the
2
+ // hub validates. Pure functions over an os-like module so tests feed a fake os (no /proc reads,
3
+ // no shell-outs); the runner passes Node's own os functions.
4
+ import { cpus, freemem, loadavg, totalmem } from "node:os";
5
+
6
+ export const HEALTH_BEAT_MS = 30_000; // heartbeat cadence; three beats fit the stale window
7
+ export const HEALTH_STALE_MS = Number(process.env.RELAY_HEALTH_STALE_MS || 90_000);
8
+
9
+ // cpuPct is the 1-min loadavg over the core count, as a percent — it CAN exceed 100 (a machine
10
+ // oversubscribed past its cores must not read as a capped, calm 100). Memory is used/total bytes;
11
+ // "used" is total minus free, the same arithmetic every system monitor shows.
12
+ export function healthPayload(osLike, machine, now = Date.now()) {
13
+ const cores = Math.max(1, (Array.isArray(osLike.cpus()) ? osLike.cpus() : []).length);
14
+ const load = Number(osLike.loadavg()?.[0]);
15
+ const total = Number(osLike.totalmem());
16
+ const free = Number(osLike.freemem());
17
+ const cpuPct = Number.isFinite(load) && load >= 0 ? Math.round((load / cores) * 100) : null;
18
+ return {
19
+ machine: String(machine || ""),
20
+ cpuPct,
21
+ memUsed: Number.isFinite(total) && Number.isFinite(free) ? Math.max(0, total - free) : null,
22
+ memTotal: Number.isFinite(total) ? total : null,
23
+ ts: now(),
24
+ };
25
+ }
26
+
27
+ export const defaultOs = { cpus, freemem, loadavg, totalmem };
@@ -0,0 +1,16 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+
4
+ export function sharedCacheDir(project, home = homedir()) {
5
+ const safeProject = String(project).replace(/\.{2,}/g, "_").replace(/[^A-Za-z0-9_.-]/g, "_");
6
+ return join(home, ".agent-bus", "cache", safeProject);
7
+ }
8
+
9
+ export function seatBuildCacheEnv(env, project, home = homedir()) {
10
+ const cache = sharedCacheDir(project, home);
11
+ return {
12
+ ...env,
13
+ CARGO_TARGET_DIR: env.CARGO_TARGET_DIR || join(cache, "cargo-target"),
14
+ TRANTOR_SHARED_CACHE: cache,
15
+ };
16
+ }
@@ -46,6 +46,33 @@ export function isMessageCardTitle(title) {
46
46
  return MESSAGE_CARD_PREFIXES.some((p) => t.startsWith(p));
47
47
  }
48
48
 
49
+ /// #13923: may THIS seat instance work a card its name owns? A seat NAME is reused across
50
+ /// instances but the board's assignee only knows the name, so without a fence a fresh instance
51
+ /// inherits the name's old cards at kickoff (#12138). This instance's work: a card newer than its
52
+ /// start, or contracted after it. bootTs 0 fails OPEN; old assignments stay on the board, untouched.
53
+ export function ownCardForInstance(card, { bootTs = 0, contractedIds = null } = {}) {
54
+ if (!(Number(bootTs) > 0)) return true;
55
+ if ((Number(card?.ts) || 0) >= bootTs) return true;
56
+ return !!contractedIds && contractedIds.has(Number(card?.id));
57
+ }
58
+
59
+ /// #13923: the card ids a direct post-start message contracted to this session — the ids its text
60
+ /// cites plus a hub-stamped `card` field. Direct only (a broadcast @mention contracts nothing),
61
+ /// from someone else, and meant to wake: `wake: false` is context by the sender's own word and
62
+ /// kind "status" is chatter — the same demotions the runner's shouldWake applies.
63
+ export function contractedCardIds(messages, { session = "", bootTs = 0 } = {}) {
64
+ const ids = new Set();
65
+ for (const m of Array.isArray(messages) ? messages : []) {
66
+ if (!m || m.to !== session || m.from === session) continue;
67
+ if (m.wake === false || m.kind === "status") continue;
68
+ if (Number(bootTs) > 0 && !(Number(m.ts) >= bootTs)) continue;
69
+ const stamped = Number(m.card);
70
+ if (Number.isFinite(stamped) && stamped > 0) ids.add(stamped);
71
+ for (const id of cardRefs(m.text)) ids.add(id);
72
+ }
73
+ return ids;
74
+ }
75
+
49
76
  /// The card this text ASSIGNS, or 0 when it only mentions cards. Leftmost assignment wins: an
50
77
  /// order says what it wants first and explains itself after.
51
78
  export function assignedCardRef(text) {
package/mcp.mjs CHANGED
@@ -15,7 +15,7 @@ import { signedPost, signedGet } from "./hooks/lib/api.mjs";
15
15
  import { anchorCursor } from "./hooks/lib/inbox-ledger.mjs";
16
16
  import { formatInboxPage, fmtMessage } from "./hooks/lib/inbox-page.mjs";
17
17
  import { assertNoSecrets } from "./lib/scrub.mjs";
18
- import { isMessageCardTitle, OPEN_CARD_STATUSES } from "./lib/turn-policy.mjs";
18
+ import { isMessageCardTitle, OPEN_CARD_STATUSES, ownCardForInstance, contractedCardIds } from "./lib/turn-policy.mjs";
19
19
  import { markDoing, hollowVerdict, blastRadius, blastLine } from "./hooks/lib/hollow-move.mjs";
20
20
 
21
21
  import { dep } from "./lib/dep.mjs";
@@ -44,6 +44,11 @@ let cursor = 0;
44
44
  // BOOT, never to the first call — a "now" seed swallowed #7282. PEEK only: the hooks own the
45
45
  // delivery ledger; a non-peek seed here marked unseen messages delivered.
46
46
  const BOOT_TS = Date.now();
47
+ // #13923: when the SEAT INSTANCE (the runner) started, stamped into the turn shell's env. A seat
48
+ // name is reused across instances, so "cards assigned to my name" must not cross this line: an
49
+ // assignment made before it belongs to a predecessor that happened to wear the same name. 0 = no
50
+ // runner over us (a solo session, or an old runner) — the fence fails open.
51
+ const SEAT_BOOT_TS = Number(process.env.TRANTOR_SEAT_BOOT_TS) || 0;
47
52
  let cursorSeeded = false;
48
53
  async function seedCursor() {
49
54
  if (cursorSeeded) return;
@@ -393,11 +398,28 @@ server.tool("relay_board", "Show a project's Kanban board (cards, status, assign
393
398
  const own = (slim.tasks || [])
394
399
  .filter(t => t.assignee === SESSION && OPEN_CARD_STATUSES.includes(t.status) && !isMessageCardTitle(t.title))
395
400
  .sort((a, b) => (b.updated || b.ts || 0) - (a.updated || a.ts || 0));
396
- if (!own.length) return { content: [{ type: "text", text: `${proj}: no cards assigned to ${SESSION} in doing/testing/todo` }] };
401
+ // #13923: the instance fence. Cards whose assignment predates this seat instance's start are
402
+ // passed over (they stay on the board, untouched) unless a direct post-start message contracted
403
+ // them. This is the kickoff's first call, so it is exactly where a reused name used to inherit
404
+ // its predecessor's cards (#12138). Only spend the inbox peek when there is something to fence.
405
+ let list = own, ignored = 0;
406
+ if (SEAT_BOOT_TS > 0 && own.some(t => (Number(t.ts) || 0) < SEAT_BOOT_TS)) {
407
+ let contracted = new Set();
408
+ try {
409
+ const r = await api("GET", `/inbox?session=${encodeURIComponent(SESSION)}&since=0&peek=1`);
410
+ contracted = contractedCardIds(r?.messages, { session: SESSION, bootTs: SEAT_BOOT_TS });
411
+ } catch { /* inbox unreadable: the fence holds — an explicit contract still wakes the seat */ }
412
+ list = own.filter(t => ownCardForInstance(t, { bootTs: SEAT_BOOT_TS, contractedIds: contracted }));
413
+ ignored = own.length - list.length;
414
+ }
415
+ // Say what was passed over in BOTH shapes: the seat that sees nothing must know there is
416
+ // nothing to fetch, and the seat holding a fresh card must not sweep the board for the rest.
417
+ const ignoredNote = ignored ? ` (${ignored} assignment(s) made before this seat instance started — old assignments stay on the board until a contract cites them)` : "";
418
+ if (!list.length) return { content: [{ type: "text", text: `${proj}: no cards assigned to ${SESSION} in doing/testing/todo${ignoredNote}` }] };
397
419
  // Re-attach the full card for each id in ONE request (hub honors a comma-separated card= list;
398
420
  // an older hub returns everything slim, which cardView still renders — notes just stay folded).
399
- const { tasks } = await api("GET", `/tasks?project=${encodeURIComponent(proj)}&fields=slim&card=${encodeURIComponent(own.map(t => t.id).join(","))}`);
400
- return { content: [{ type: "text", text: own.map(t => cardView(tasks || [], t.id, proj)).join("\n\n") }] };
421
+ const { tasks } = await api("GET", `/tasks?project=${encodeURIComponent(proj)}&fields=slim&card=${encodeURIComponent(list.map(t => t.id).join(","))}`);
422
+ return { content: [{ type: "text", text: list.map(t => cardView(tasks || [], t.id, proj)).join("\n\n") + ignoredNote }] };
401
423
  }
402
424
  const { tasks } = await api("GET", `/tasks?project=${encodeURIComponent(proj)}&fields=slim${card ? `&card=${encodeURIComponent(card)}` : ""}`);
403
425
  if (!tasks.length) return { content: [{ type: "text", text: `${proj}: no cards yet` }] };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.130",
3
+ "version": "0.18.131",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"