trantor 0.18.146 → 0.18.148

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +23 -7
  4. package/bin/capacity.mjs +18 -2
  5. package/bin/cli.mjs +6 -2
  6. package/bin/connect.mjs +10 -3
  7. package/bin/crew-runner.mjs +25 -2
  8. package/bin/dispatch.mjs +78 -0
  9. package/bin/integrate.mjs +14 -2
  10. package/bin/review.mjs +35 -0
  11. package/hooks/sessionstart.mjs +4 -1
  12. package/hub/routes/capacity.mjs +30 -23
  13. package/hub/routes/dispatcher.mjs +97 -0
  14. package/hub/routes/insights.mjs +68 -4
  15. package/hub/routes/worktree-status.mjs +56 -0
  16. package/hub.mjs +2 -1
  17. package/kimi.plugin.json +1 -1
  18. package/lib/capacity.mjs +94 -16
  19. package/lib/dispatcher/acceptance.mjs +314 -0
  20. package/lib/dispatcher/accounts.mjs +442 -0
  21. package/lib/dispatcher/admission.mjs +719 -0
  22. package/lib/dispatcher/breakers.mjs +70 -0
  23. package/lib/dispatcher/executor.mjs +486 -0
  24. package/lib/dispatcher/forecast.mjs +391 -0
  25. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  26. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  27. package/lib/dispatcher/harness/contract.mjs +198 -0
  28. package/lib/dispatcher/harness/crew.mjs +463 -0
  29. package/lib/dispatcher/harness/publication.mjs +188 -0
  30. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  31. package/lib/dispatcher/planner.mjs +516 -0
  32. package/lib/dispatcher/policy.mjs +9 -0
  33. package/lib/dispatcher/preflight.mjs +247 -0
  34. package/lib/dispatcher/resources.mjs +44 -0
  35. package/lib/dispatcher/schemas.mjs +3 -1
  36. package/lib/dispatcher/spend.mjs +319 -0
  37. package/lib/dispatcher/store.mjs +207 -2
  38. package/lib/fitness.mjs +227 -41
  39. package/lib/review-gate.mjs +63 -0
  40. package/lib/telemetry-ship.mjs +8 -7
  41. package/lib/worktree-status.mjs +216 -0
  42. package/mcp.mjs +53 -7
  43. package/package.json +1 -1
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + context-handoff for independent AI coding agents (Claude, Codex, Gemini, …)",
9
- "version": "0.18.146"
9
+ "version": "0.18.148"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "trantor",
14
14
  "source": "./",
15
15
  "description": "The hub-world for AI agent crews. Say \"fire up the crew\" and Claude becomes the architect: a plan-aware Advisor routes the work (solo / cheap inline calls / live crew of Codex, GLM, Kimi & DeepSeek in their own terminal windows), a Kanban/flow command center with a testing gate tracks it, and an economics brain (Scrooge) keeps the receipts. Includes the relay MCP, a SessionStart auto-discovery hook, and a PreCompact context-handoff so a fresh session can take over a full window instead of compacting.",
16
- "version": "0.18.146",
16
+ "version": "0.18.148",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.146",
3
+ "version": "0.18.148",
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/bin/advise.mjs CHANGED
@@ -241,19 +241,35 @@ export function advise(input, world = loadWorld()) {
241
241
  return recommendation;
242
242
  }
243
243
 
244
- // ---- CLI ----
245
- // is-main guard via PROPERLY ENCODED file URL — a hand-built `file://${argv[1]}` silently no-ops when the
246
- // install path contains a URL-reserved char (e.g. a SPACE in ".../Application Support/..."). See profile.mjs.
244
+ // #14678: stdin carrying {cards|drafts}, or --snapshot/--policy, asks the hub's planner (POST /advise);
245
+ // {task, packages} keeps the legacy advisor above, usable in shadow mode.
246
+ async function hubAdvice(input, argv) {
247
+ const { signedPost, sessionContext } = await import("../hooks/lib/api.mjs");
248
+ const { buildAdviceRequest, requestAdvice, renderAdvice } = await import("../lib/dispatcher/preflight.mjs");
249
+ const flag = (name) => { const i = argv.indexOf(name); return i > -1 ? argv[i + 1] : undefined; };
250
+ const project = input.project || sessionContext().project;
251
+ const request = await buildAdviceRequest({ project, cards: input.cards || [], drafts: input.drafts || [],
252
+ snapshotId: flag("--snapshot") || input.snapshotId, policyVersion: flag("--policy") || input.policyVersion });
253
+ const result = await requestAdvice({ post: (path, body) => signedPost(path, body, { project, timeoutMs: 10000 }), busDir: busDir(), request });
254
+ console.log(argv.includes("--json") ? JSON.stringify(result, null, 2) : renderAdvice(result));
255
+ return result.source === "refused" ? 1 : 0;
256
+ }
257
+
258
+ // ---- CLI ---- is-main guard via an ENCODED file URL: a hand-built `file://${argv[1]}` no-ops when the
259
+ // install path holds a URL-reserved char (a SPACE in ".../Application Support/..."). See profile.mjs.
247
260
  if (import.meta.url === pathToFileURL(process.argv[1]).href) {
248
261
  let input;
249
- if (process.argv.includes("--demo")) {
262
+ const argv = process.argv.slice(2);
263
+ if (!argv.includes("--demo")) {
264
+ const stdin = process.stdin.isTTY ? "" : readFileSync(0, "utf8").trim();
265
+ input = stdin ? JSON.parse(stdin) : { packages: [] };
266
+ if (input.cards || input.drafts || argv.includes("--snapshot") || argv.includes("--policy")) process.exit(await hubAdvice(input, argv));
267
+ }
268
+ if (argv.includes("--demo")) {
250
269
  input = { task: "neon asteroids game", packages: [
251
270
  { title: "engine+integration", difficulty: "hard" }, { title: "render/bloom", difficulty: "hard" },
252
271
  { title: "combat+ui", difficulty: "medium" }, { title: "audio", difficulty: "medium" },
253
272
  { title: "readme+badges", difficulty: "easy" } ] };
254
- } else {
255
- const stdin = readFileSync(0, "utf8").trim();
256
- input = stdin ? JSON.parse(stdin) : { packages: [] };
257
273
  }
258
274
  const world = loadWorld();
259
275
  // #7762: fold this project's seat record into the routing (fail-open — no hub, no record,
package/bin/capacity.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  // Degraded by design: when the hub is unreachable the CLI falls back to the LOCAL provider
7
7
  // balances (same sources `trantor balances` reads) and says it is local-only — machines, seats and
8
8
  // burn rate print unknown, never a guess.
9
- // Usage: trantor capacity [--json]
9
+ // Usage: trantor capacity [--json] [--version 1 [--snapshot <id>]]
10
10
  import { signedGet, sessionContext, relayUrl } from "../hooks/lib/api.mjs";
11
11
  import { fetchBalances, fmtBalance } from "../lib/balances.mjs";
12
12
  import { loadProfile } from "./profile.mjs";
@@ -19,6 +19,22 @@ const asJson = args.includes("--json");
19
19
  const { project } = sessionContext();
20
20
  const hub = relayUrl(project);
21
21
 
22
+ // #14678: --version 1 is the planner's envelope; an unreachable hub gives the cached one, localOnly, no token.
23
+ const versionAt = args.indexOf("--version");
24
+ if (versionAt > -1 && args[versionAt + 1] === "1") {
25
+ const { readCapacity } = await import("../lib/dispatcher/preflight.mjs");
26
+ const { busDir } = await import("../lib/project.mjs");
27
+ const snapshotAt = args.indexOf("--snapshot");
28
+ const envelope = await readCapacity({ get: (path) => signedGet(path, { timeoutMs: 5000, project }), busDir: busDir(), project,
29
+ snapshotId: snapshotAt > -1 ? args[snapshotAt + 1] : null });
30
+ if (asJson) console.log(JSON.stringify(envelope, null, 2));
31
+ else if (envelope.refused) console.log(`hub refused the planning view: ${envelope.code}`);
32
+ else if (envelope.localOnly) console.log(`hub unreachable (${envelope.reason}) — LOCAL ONLY: ${envelope.envelope ? `cached planning view ${Math.round(envelope.sourceAgeMs / 1000)}s old` : "no cached planning view"}; no dispatch token.`);
33
+ else if (!envelope.versioned) console.log("this hub has no planning view yet (it answered with the display ledger); run trantor capacity for that view");
34
+ else console.log(`planning snapshot ${envelope.snapshotId} · policy ${envelope.policyVersion ?? "unknown"}${envelope.degraded?.length ? ` · degraded: ${envelope.degraded.join(", ")}` : ""}`);
35
+ process.exit(envelope.refused ? 1 : 0);
36
+ }
37
+
22
38
  const response = await signedGet(`/capacity?project=${encodeURIComponent(project)}`, { timeoutMs: 5000, project });
23
39
 
24
40
  if (!response.ok && response.status !== 0) {
@@ -36,7 +52,7 @@ if (!response.ok) {
36
52
  const balances = [...detected, ...profileScoped];
37
53
  const reason = response.reason || "unreachable";
38
54
  if (asJson) {
39
- console.log(JSON.stringify({ degraded: "local-only", reason, hub, balances, budgets: null, burn: null, machines: null, seats: null }, null, 2));
55
+ console.log(JSON.stringify({ degraded: "local-only", localOnly: true, reason, hub, balances, budgets: null, burn: null, machines: null, seats: null }, null, 2));
40
56
  } else {
41
57
  console.log(`hub unreachable (${reason}) — LOCAL BALANCES ONLY; machines, seats and burn rate unknown.`);
42
58
  console.log(`hub: ${hub}\n`);
package/bin/cli.mjs CHANGED
@@ -30,6 +30,7 @@ switch (cmd) {
30
30
  case "models": run("bin/models.mjs"); break;
31
31
  case "memory": run("bin/memory.mjs"); break;
32
32
  case "advise": run("bin/advise.mjs"); break;
33
+ case "dispatch": run("bin/dispatch.mjs"); break;
33
34
  case "verify": run("bin/crew-verify.mjs"); break;
34
35
  case "up": runCrew(); break;
35
36
  case "open": runCrew(); break;
@@ -38,6 +39,7 @@ switch (cmd) {
38
39
  case "agent-settings": run("bin/agent-settings.mjs"); break;
39
40
  case "adopt": spawn(process.execPath, [join(ROOT, "bin/adopt.mjs"), ...args], { stdio: "inherit", cwd: process.cwd() }).on("exit", c => process.exit(c ?? 0)); break;
40
41
  case "integrate": spawn(process.execPath, [join(ROOT, "bin/integrate.mjs"), ...args], { stdio: "inherit", cwd: process.cwd() }).on("exit", c => process.exit(c ?? 0)); break;
42
+ case "review": spawn(process.execPath, [join(ROOT, "bin/review.mjs"), ...args], { stdio: "inherit", cwd: process.cwd() }).on("exit", c => process.exit(c ?? 0)); break;
41
43
  case "attribution": run("bin/attribution.mjs"); break;
42
44
  case "harvest": run("bin/harvest.mjs"); break;
43
45
  case "sync": run("bin/sync.mjs"); break;
@@ -297,6 +299,7 @@ switch (cmd) {
297
299
  trantor adopt take over a session already running in a Terminal, then open it here
298
300
  trantor takeover the whole move in one command: idle-gate the Terminal session, end it gracefully, adopt, open in the pane — [--force] [--session <id>] [--dry-run]
299
301
  trantor integrate collect the crew's work, merge it, verify it, push it (--dry-run to rehearse)
302
+ trantor review publish publish each seat's diff to the hub for per-hunk review (Mixed mode)
300
303
  trantor harvest receipt for a seat commit you landed on main by hand: harvest <seat-sha> <main-sha> [--card N]
301
304
  trantor sync realign a seat branch with main from the receipts: sync [<seat>] [--dry-run] — refuses and names unharvested commits
302
305
  trantor down tear the crew down (kills processes, closes windows, no dialogs)
@@ -314,10 +317,11 @@ switch (cmd) {
314
317
  trantor new project genesis: new <name> [--from <git-url>] [--brief <file>] [--dir <parent>] [--adopt] [--json] — creates <parent>/<name>, git main, docs/PRD.md + small CLAUDE.md, hooks, hub brief + first card (never spawns a session)
315
318
  trantor genesis-kickoff internal wake prompt selector from the checkout + signed project board
316
319
  trantor balances how much credit is left on each CONFIGURED provider (from your profile) — refill before you stall — [--json]
317
- trantor capacity the live ledger: budgets and resets, burn rate, machines, seats — [--json]
320
+ trantor capacity the live ledger: budgets and resets, burn rate, machines, seats — [--json] [--version 1 [--snapshot <id>]]
318
321
  trantor recost recompute sub-agent notional cost from on-disk transcripts + reseed the board (repair after upgrade) — [--dry-run]
319
322
  trantor handoff finish this session NOW: write a handoff, open a fresh session that takes over, and close this one (manual baton)
320
- trantor advise ask the Advisor directly (JSON on stdin; --demo to see it)
323
+ trantor advise ask the Advisor directly (JSON on stdin; --demo to see it); {"cards":[...]} asks the hub planner — [--json] [--snapshot <id>] [--policy <v>]
324
+ trantor dispatch admit planned cards through the hub: --decision <id> [--card <n>] · status <attemptId> · preflight — [--json]
321
325
  trantor project this checkout's identity: project [<id>] — records .trantor/project.json so a directory rename cannot orphan the board, pin and sessions
322
326
  project permissions <name> [ask|bypass] — whether <name>'s agents ask before acting or act without asking; no value prints it
323
327
  trantor hub run the hub in the foreground (setup installs it as a service instead)
package/bin/connect.mjs CHANGED
@@ -9,6 +9,7 @@ import { execSync } from "node:child_process";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { parseJsonc } from "../lib/jsonc.mjs";
11
11
  import { resolveProjectInfo, resolveHubInfo, gitRoot, writeProjectId, PROJECT_MARKER } from "../lib/project.mjs";
12
+ import { BRIEF_MARKER, upsertBriefBlock } from "../lib/dispatcher/preflight.mjs";
12
13
 
13
14
  const DRY = process.argv.includes("--dry-run");
14
15
  const MCP = join(dirname(dirname(fileURLToPath(import.meta.url))), "mcp.mjs");
@@ -19,9 +20,7 @@ const MCP = join(dirname(dirname(fileURLToPath(import.meta.url))), "mcp.mjs");
19
20
  const PROJECT_INFO = resolveProjectInfo(process.cwd());
20
21
  const PROJECT_AT_CONNECT = PROJECT_INFO.project;
21
22
  const URL_ = resolveHubInfo(PROJECT_AT_CONNECT).url;
22
- // #14536: graft is no longer an agent MCP server (0 calls from Claude sessions in 30 days, a handful
23
- // from seats, ~900 tokens of tool list per turn). The desktop app still runs the graft CLI itself.
24
- // Connect removes the entries older versions wrote.
23
+ // #14536: graft is no longer an agent MCP server; connect removes the entries older versions wrote.
25
24
  // The [mcp_servers.graft] table up to the next table, and the comment line connect wrote for it,
26
25
  // which a later relay env refresh can leave separated from the table.
27
26
  function removeCodexGraft(toml) {
@@ -107,6 +106,14 @@ if (has("codex")) {
107
106
  }
108
107
  report("codex", note, p);
109
108
  }
109
+ // #14678: Codex has no session hook, so the shared orchestrator brief goes in its global instructions file.
110
+ const agentsMd = join(homedir(), ".codex", "AGENTS.md");
111
+ const curMd = existsSync(agentsMd) ? readFileSync(agentsMd, "utf8") : "";
112
+ const nextMd = upsertBriefBlock(curMd);
113
+ if (nextMd !== curMd) {
114
+ if (!DRY) { if (existsSync(agentsMd)) backup(agentsMd); else mkdirSync(dirname(agentsMd), { recursive: true }); writeFileSync(agentsMd, nextMd); }
115
+ report("codex", curMd.includes(BRIEF_MARKER) ? "orchestrator brief refreshed" : "orchestrator brief written", agentsMd);
116
+ }
110
117
  const g = existsSync(p) ? readFileSync(p, "utf8") : "";
111
118
  const ungrafted = removeCodexGraft(g);
112
119
  if (ungrafted !== g) {
@@ -59,6 +59,7 @@ import {
59
59
  } from "../lib/state/driver.mjs";
60
60
  import { costLine } from "../lib/state/cost.mjs";
61
61
  import { resolveStateFlags, stateFeatureOn } from "../lib/state/flags.mjs";
62
+ import { createWorktreeStatusReporter } from "../lib/worktree-status.mjs";
62
63
 
63
64
  import { awaitSwapRelease } from "./crew/stage.mjs";
64
65
  import { codexRelayFlags } from "./crew/codex-relay.mjs";
@@ -132,6 +133,8 @@ function seatWorktree(sourceDir) {
132
133
  }
133
134
 
134
135
  const TURN_DIR = seatWorktree(DIR);
136
+ const TEST_SANDBOX = /(?:^|\/)test-home-[^/]+(?:\/|$)/.test(DIR);
137
+ const TEST_HUB_DEAD_AFTER_MS = Math.max(100, Number(process.env.TRANTOR_TEST_HUB_DEAD_AFTER_MS) || 120000);
135
138
 
136
139
  // #13921: an explicit contract base wins; without one, fetch the current origin/main instead of
137
140
  // trusting a cached local ref from when this seat worktree was created.
@@ -674,8 +677,8 @@ async function balanceRows() {
674
677
  // ---- activity truth (#5965): the RUNNER is the source for this seat ----------------
675
678
  // The runner reports `working · <trigger>` at start and `idle` on a clean landing, bounded to 5s.
676
679
  // #7749: the live phase + its start ride the same call, so /peers answers what the seat does NOW.
677
- // The detached watchdog repeats the working payload once a minute: runTurn blocks this event loop.
678
- const PRESENCE_MS = Math.max(100, Number(process.env.RUNNER_PRESENCE_MS) || 60_000);
680
+ // The detached watchdog repeats the working payload every 30s: runTurn blocks this event loop.
681
+ const PRESENCE_MS = Math.max(100, Number(process.env.RUNNER_PRESENCE_MS) || 30_000);
679
682
  async function registerStatus(status, extra = {}) {
680
683
  if (extra.phase === "working") {
681
684
  lastTurnStartedAt = Number(extra.phaseSince) || Date.now();
@@ -1696,6 +1699,16 @@ async function resolveWakeCard(messages, { session }) {
1696
1699
  askReleased = releaseState?.askReleased || false;
1697
1700
  if (pendingWake.length) log(`\x1b[33m${pendingWake.length} message(s) survived from a previous run — redelivering\x1b[0m`);
1698
1701
 
1702
+ const worktreeStatus = createWorktreeStatusReporter({
1703
+ cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: MACHINE_LABEL || hostId(),
1704
+ post: async status => {
1705
+ const result = await api("/worktree-status", status);
1706
+ if (!result?.ok) throw new Error(result?.error || "hub rejected snapshot");
1707
+ },
1708
+ log,
1709
+ });
1710
+ worktreeStatus.start();
1711
+
1699
1712
  // #7060: the turn the boot line was read as a promise about. It is a transcript turn by
1700
1713
  // construction and now says so, in the same breath as the line that armed the mode.
1701
1714
  if (!releaseState) {
@@ -1797,6 +1810,7 @@ async function resolveWakeCard(messages, { session }) {
1797
1810
  log(`machine health heartbeat armed as ${MACHINE_LABEL} every ${Math.round(HEALTH_BEAT_MS / 1000)}s`);
1798
1811
  }
1799
1812
 
1813
+ let hubUnreachableSince = 0;
1800
1814
  while (true) {
1801
1815
  restartForRelease();
1802
1816
  // pulse first: a due mission beat runs even on a silent bus. Measured from the END of the
@@ -1838,9 +1852,18 @@ async function resolveWakeCard(messages, { session }) {
1838
1852
  // response (stalled event loop, napped machine, dead socket). Reconnect immediately and say
1839
1853
  // so calmly; reserve the scary "hub unreachable" + 5s backoff for real connection failures.
1840
1854
  const expired = e && (e.name === "TimeoutError" || /abort/i.test(String(e.message)));
1855
+ if (TEST_SANDBOX) {
1856
+ hubUnreachableSince ||= Date.now();
1857
+ if (Date.now() - hubUnreachableSince >= TEST_HUB_DEAD_AFTER_MS) {
1858
+ log(`test hub unreachable for ${Math.round((Date.now() - hubUnreachableSince) / 1000)}s — exiting`);
1859
+ process.exit(0);
1860
+ }
1861
+ }
1841
1862
  log(expired ? `long-poll hold expired with no hub response — reconnecting` : `hub unreachable (${e.message}) — retrying in 5s`);
1842
1863
  await new Promise(s => setTimeout(s, expired ? 250 : 5000)); continue;
1843
1864
  }
1865
+ hubUnreachableSince = 0;
1866
+ await worktreeStatus.heartbeat();
1844
1867
  if (!msgs.length) continue; // heartbeat tick, nothing for us
1845
1868
  // never wake on your own broadcasts: a claude seat's report contains "claude:" and matched the
1846
1869
  // @mention filter, buying one echo turn per report (seen live on the first pulsed orchestrator)
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+ // #14678: trantor dispatch admits planned cards through the hub (POST /dispatch); the hub admits or refuses.
3
+ // --decision <id> [--card <n>]... [--json] · --json < {decisionId,card,cardRevision,expectedPolicyVersion}
4
+ // status <attemptId> [--json] · preflight [--json] [--snapshot <id>] with optional {"cards":[...]} on stdin
5
+ import { readFileSync } from "node:fs";
6
+ import { signedGet, signedPost, sessionContext } from "../hooks/lib/api.mjs";
7
+ import { busDir } from "../lib/project.mjs";
8
+ import { loadRegistry } from "../lib/canary/registry.mjs";
9
+ import {
10
+ dispatchDecision, idempotencyKey, parseCards, preflight, readCachedAdvice, renderDispatch, requestDispatch,
11
+ } from "../lib/dispatcher/preflight.mjs";
12
+
13
+ const args = process.argv.slice(2);
14
+ const asJson = args.includes("--json");
15
+ const flag = (name) => { const i = args.indexOf(name); return i > -1 ? args[i + 1] : null; };
16
+ const flags = (name) => args.flatMap((a, i) => (a === name ? [args[i + 1]] : []));
17
+ const { project } = sessionContext();
18
+ const BUS = busDir();
19
+ const get = (path) => signedGet(path, { project, timeoutMs: 5000 });
20
+ const post = (path, body) => signedPost(path, body, { project, timeoutMs: 10000 });
21
+ const print = (value, text) => console.log(asJson ? JSON.stringify(value, null, 2) : text);
22
+ const stdinJson = () => {
23
+ if (process.stdin.isTTY) return null;
24
+ const raw = readFileSync(0, "utf8").trim();
25
+ return raw ? JSON.parse(raw) : null;
26
+ };
27
+
28
+ async function status(attemptId) {
29
+ const r = await get(`/dispatch/${encodeURIComponent(attemptId)}`);
30
+ if (!r.ok) {
31
+ print({ ok: false, status: r.status, code: r.json?.code || (r.status === 0 ? "hub_unreachable" : `http_${r.status}`) },
32
+ `attempt ${attemptId}: ${r.status === 0 ? `hub unreachable (${r.reason})` : r.json?.code || `HTTP ${r.status}`}`);
33
+ return r.status === 0 ? 3 : 1;
34
+ }
35
+ const a = r.json;
36
+ print(a, `attempt ${a.attemptId}: #${a.card} ${a.state} · generation ${a.generation} · lease ${a.leaseId}${a.failure ? ` · failed ${a.failure.code}` : ""}`);
37
+ return 0;
38
+ }
39
+
40
+ async function runPreflight() {
41
+ const input = stdinJson();
42
+ const cards = await parseCards(input?.cards || []);
43
+ const out = await preflight({ get, busDir: BUS, project, cards, rows: loadRegistry(), snapshotId: flag("--snapshot") });
44
+ print(out, out.lines.join("\n") || "preflight: nothing open");
45
+ return out.ok ? 0 : 1;
46
+ }
47
+
48
+ async function admit() {
49
+ const decisionId = flag("--decision");
50
+ if (decisionId) {
51
+ const cached = readCachedAdvice(BUS, project);
52
+ if (cached?.decision?.id !== decisionId) {
53
+ print({ ok: false, code: "decision_unknown", decisionId },
54
+ `decision ${decisionId} is not the last hub decision for ${project}; run trantor advise --json first`);
55
+ return 1;
56
+ }
57
+ const only = flags("--card").map(Number);
58
+ const outcome = await dispatchDecision({ post, decision: cached.decision, project, only: only.length ? only : null });
59
+ print(outcome, renderDispatch(outcome));
60
+ return outcome.admitted === outcome.results.length && outcome.results.length ? 0 : 3;
61
+ }
62
+ const input = stdinJson();
63
+ if (!input?.decisionId) {
64
+ console.error("usage: trantor dispatch --decision <id> [--card <n>]... [--json] | --json < request | status <attemptId> | preflight");
65
+ return 2;
66
+ }
67
+ const request = { schemaVersion: 1, project, decisionId: input.decisionId, card: input.card, cardRevision: input.cardRevision,
68
+ expectedPolicyVersion: input.expectedPolicyVersion,
69
+ idempotencyKey: input.idempotencyKey || idempotencyKey({ project, decisionId: input.decisionId, card: input.card, cardRevision: input.cardRevision }) };
70
+ const result = await requestDispatch({ post, request });
71
+ const outcome = { decisionId: request.decisionId, admitted: result.admitted ? 1 : 0, results: [result] };
72
+ print(outcome, renderDispatch(outcome));
73
+ return result.admitted ? 0 : 3;
74
+ }
75
+
76
+ const sub = args[0];
77
+ const code = sub === "status" ? await status(args[1]) : sub === "preflight" ? await runPreflight() : await admit();
78
+ process.exit(code);
package/bin/integrate.mjs CHANGED
@@ -3,10 +3,12 @@
3
3
  // The steps are the ones the orchestrator already performs by hand. The dials decide how far it is
4
4
  // allowed to go on its own, and every stop says which dial stopped it, so "why didn't it push"
5
5
  // always has an answer.
6
- import { resolveProject } from "../lib/project.mjs";
6
+ import { resolveProject, resolveHub } from "../lib/project.mjs";
7
7
  import { resolveAutonomy } from "../lib/autonomy.mjs";
8
8
  import { seatWorktrees, commitSeatWork, seatAhead, mergeSeat, verify, git } from "../lib/integrate.mjs";
9
9
  import { recordHarvest } from "../lib/harvest.mjs";
10
+ import { ownerIdentity } from "../lib/enroll.mjs";
11
+ import { checkSeatReview } from "../lib/review-gate.mjs";
10
12
 
11
13
  const D = "\x1b[2m", B = "\x1b[1m", G = "\x1b[32m", Y = "\x1b[33m", RED = "\x1b[31m", R = "\x1b[0m";
12
14
  const args = process.argv.slice(2);
@@ -41,11 +43,21 @@ for (const w of seats) {
41
43
  }
42
44
 
43
45
  // 2. Merge what each seat is ahead by. A conflict stops the pass: two seats on the same lines is
44
- // the collision the overseer exists to surface, not something to resolve silently.
46
+ // the collision the overseer exists to surface, not something to resolve silently. A seat under
47
+ // per-hunk review merges only when every hunk is approved at its current tip
48
+ // (docs/CONTRACT-review.md rule 5); otherwise it is skipped with its pending count.
45
49
  const merged = [];
50
+ const hub = resolveHub(project);
51
+ const identity = ownerIdentity();
46
52
  for (const w of seats) {
47
53
  const { branch, ahead } = seatAhead(w, base);
48
54
  if (!ahead) continue;
55
+ const review = await checkSeatReview({ hub, identity, project, seat: w.agent, dir: w.dir, base, tip: branch, publish: !dry });
56
+ if (!review.merge) {
57
+ console.log(` ${Y}${w.agent}: skipped, ${review.reason}${R}`);
58
+ continue;
59
+ }
60
+ if (review.reviewed) console.log(` ${D}${w.agent}: ${review.reason}${R}`);
49
61
  if (dry) { console.log(` ${D}[dry] would merge ${branch} (${ahead} commit(s))${R}`); merged.push(branch); continue; }
50
62
  const m = mergeSeat(repo, branch);
51
63
  if (m.conflict) {
package/bin/review.mjs ADDED
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ // `trantor review publish [--json]`: run from the project checkout, it publishes every seat's
3
+ // committed diff against the checkout's branch (the branch `trantor integrate` merges into) to the
4
+ // hub, so Mixed mode can decide its hunks (docs/CONTRACT-review.md). It never merges or edits.
5
+ import { resolveProject, resolveHub } from "../lib/project.mjs";
6
+ import { seatWorktrees, seatAhead, git } from "../lib/integrate.mjs";
7
+ import { ownerIdentity } from "../lib/enroll.mjs";
8
+ import { publishSeatReview } from "../lib/review-gate.mjs";
9
+
10
+ const args = process.argv.slice(2);
11
+ const json = args.includes("--json");
12
+ if (args[0] !== "publish") {
13
+ console.error("usage: trantor review publish [--json]");
14
+ process.exit(2);
15
+ }
16
+ const repo = process.cwd();
17
+ const project = resolveProject(repo);
18
+ const base = git(repo, ["rev-parse", "--abbrev-ref", "HEAD"]);
19
+ const hub = resolveHub(project);
20
+ const identity = ownerIdentity();
21
+ const seats = [];
22
+ for (const w of seatWorktrees(project)) {
23
+ const { branch, ahead } = seatAhead(w, base);
24
+ if (!ahead) continue;
25
+ try {
26
+ const review = await publishSeatReview({ hub, identity, project, seat: w.agent, dir: w.dir, base, tip: branch });
27
+ seats.push({ seat: w.agent, tip: review.tip, hunks: review.hunks.length, pending: review.pendingCount });
28
+ } catch (e) {
29
+ seats.push({ seat: w.agent, error: e.message });
30
+ }
31
+ }
32
+ if (json) console.log(JSON.stringify({ project, base, seats }));
33
+ else for (const s of seats) console.log(s.error ? `${s.seat}: ${s.error}` : `${s.seat}: ${s.pending} of ${s.hunks} hunks pending`);
34
+ // --json reports per-seat errors in the payload, so the desktop can show each one beside its seat.
35
+ process.exit(!json && seats.some(s => s.error) ? 1 : 0);
@@ -7,7 +7,7 @@ import { join, basename, dirname } from "node:path";
7
7
  import { homedir, hostname } from "node:os";
8
8
  import { execSync, spawn } from "node:child_process";
9
9
  import { fileURLToPath } from "node:url";
10
- import { resolveProject, hostId, resolveHubInfo, knownProjects, nonSeatReason, nestedProjects, readConfig as readBusConfig, handoffDir, readOrchSession, writeOrchSession } from "../lib/project.mjs";
10
+ import { resolveProject, hostId, resolveHubInfo, knownProjects, nonSeatReason, nestedProjects, readConfig as readBusConfig, handoffDir, readOrchSession, writeOrchSession, busDirFor } from "../lib/project.mjs";
11
11
  import { formatSubagentManifest } from "../lib/subagent-manifest.mjs";
12
12
  import { updateAvailable, maybeNotifyDesktop, readConfig } from "./lib/update-check.mjs";
13
13
  import { renderStateBlock, capSummary } from "./lib/handoff.mjs";
@@ -372,6 +372,9 @@ try {
372
372
  `- Dispatch rule: the target project is confirmed from the session's badge and cwd before any relay_send, relay_task_add or \`trantor up\` — an ambiguous instruction is not a project name; and a session asking the operator a question never triggers a wake (its messages batch until the answer).\n` +
373
373
  `</trantor-orchestrator-role>\n`;
374
374
  if (wantsBuildDoctrine(readBusConfig())) additionalContext += buildDoctrineShortForm();
375
+ // #14678: the shared dispatch brief, open regressions first; Codex gets the same text via connect.
376
+ const { sessionBrief } = await import("../lib/dispatcher/preflight.mjs");
377
+ additionalContext += `<trantor-dispatch-brief project="${sanitize(project)}">\n${sanitize(sessionBrief({ busDir: busDirFor() }))}\n</trantor-dispatch-brief>\n`;
375
378
  process.stderr.write(`[trantor] injected orchestrator-role doctrine for ${project}\n`);
376
379
  }
377
380
  } catch {}
@@ -12,7 +12,8 @@ import { homedir } from "node:os";
12
12
  import { join } from "node:path";
13
13
  import { DEFAULT_LOW, DEFAULT_LOW_QUOTA_PCT } from "../../lib/balances.mjs";
14
14
  import { recordMachineBeat, machineHealthRows, CAPACITY_STALE_MS } from "../../lib/capacity-machines.mjs";
15
- import { budgetsView, burnView, seatsView, machineSeatCounts } from "../../lib/capacity.mjs";
15
+ import { budgetsView, burnView, seatsView, machinesView } from "../../lib/capacity.mjs";
16
+ import { readScroogeLedger, scroogeReceipts } from "../../lib/dispatcher/spend.mjs";
16
17
 
17
18
  /* oxlint-disable anti-slop/no-runtime-typeof -- SAFETY: config.json is user-editable external input; lowThresholds validates its optional number/object fields at that I/O boundary, the same guard GET /balances uses. */
18
19
  // The same low-balance thresholds GET /balances reads, so both views flag the same provider.
@@ -25,6 +26,19 @@ function lowThresholds() {
25
26
  } catch { return { low: DEFAULT_LOW, pct: DEFAULT_LOW_QUOTA_PCT }; }
26
27
  }
27
28
 
29
+ // Crew USD receipts for the burn view (#14671): the scrooge one-shot ledger, mtime-cached the
30
+ // same way /economics reads it. Dispatcher usage events join the same projection when B5/B6 wire
31
+ // their store; no token-derived dollar estimates are ever fabricated here.
32
+ let spendLedgerCache = { mtimeMs: -1, receipts: [] };
33
+ function crewSpendReceipts() {
34
+ const ledger = readScroogeLedger();
35
+ if (ledger.mtimeMs == null) return [];
36
+ if (ledger.mtimeMs !== spendLedgerCache.mtimeMs) {
37
+ spendLedgerCache = { mtimeMs: ledger.mtimeMs, receipts: scroogeReceipts({ lines: ledger.rows.map((row) => row.line) }) };
38
+ }
39
+ return spendLedgerCache.receipts;
40
+ }
41
+
28
42
  export async function routeCapacity({ req, res, P, auth, ctx }) {
29
43
  const { state, body, json, now, turnTelemetry, ONLINE_MS, PEER_TTL_MS, filterReadable } = ctx;
30
44
 
@@ -43,33 +57,26 @@ export async function routeCapacity({ req, res, P, auth, ctx }) {
43
57
  const visibleSeats = filterReadable(auth, seats, (s) => s.project);
44
58
  const seatKey = (s) => `${s.persona}\u0000${s.project}`;
45
59
  const visibleKeys = new Set(visibleSeats.map(seatKey));
46
- const canSee = (s) => visibleKeys.has(seatKey(s));
60
+ // One-shot receipts have no presence seat: their visibility is project-readability of the
61
+ // receipt itself, so a project-scoped reader still sees their dollars without seeing seats.
62
+ const receipts = crewSpendReceipts();
63
+ const visibleReceiptKeys = new Set(filterReadable(auth, receipts, (r) => r.project)
64
+ .map((r) => `${r.persona || ""}\u0000${r.project || ""}`));
65
+ const canSee = (s) => visibleKeys.has(seatKey(s)) || visibleReceiptKeys.has(seatKey(s));
47
66
 
48
- // Machine rows: the beat registry joined with seat counts; a machine that only presence knows
49
- // (no runner heartbeat, e.g. the operator's Mac) still lists, with nulls and its seat count.
50
- const seatCounts = machineSeatCounts(state.peers, nowMs, { ttlMs: PEER_TTL_MS, onlineMs: ONLINE_MS });
51
- const machines = [];
52
- const seen = new Set();
53
- for (const h of machineHealthRows(nowMs)) {
54
- seen.add(h.machine);
55
- const counts = seatCounts.get(h.machine);
56
- machines.push({ ...h, seats: counts?.seats || 0, seatsOnline: counts?.seatsOnline || 0, heartbeat: true });
57
- }
58
- for (const [machine, counts] of seatCounts) {
59
- if (seen.has(machine)) continue;
60
- machines.push({
61
- machine, cpuPct: null, memUsed: null, memTotal: null, cores: null, memPressurePct: null,
62
- swapUsed: null, swapTotal: null, diskFree: null, diskTotal: null,
63
- ts: null, ageMs: null, stale: true, heartbeat: false,
64
- seats: counts.seats, seatsOnline: counts.seatsOnline,
65
- });
66
- }
67
- machines.sort((a, b) => a.machine.localeCompare(b.machine));
67
+ // Machine rows (#14702): the beat registry joined with seat counts over every machine name the
68
+ // hub knows — beat labels, presence labels, balances host names — case-insensitively, with an
69
+ // unlabeled "host:project" session attributed to a known host (the operator's Mac).
70
+ const machines = machinesView({
71
+ beats: machineHealthRows(nowMs), peers: state.peers, nowMs,
72
+ ttlMs: PEER_TTL_MS, onlineMs: ONLINE_MS,
73
+ balanceMachines: Object.keys(state.balancesByMachine || {}),
74
+ });
68
75
 
69
76
  return json(res, 200, {
70
77
  ts: nowMs,
71
78
  budgets: budgetsView({ state, nowMs, thresholds: low, quotaPct: pct }),
72
- burn: burnView({ rows: burnRows, nowMs, canSee }),
79
+ burn: burnView({ rows: burnRows, nowMs, canSee, spendReceipts: receipts }),
73
80
  machines,
74
81
  staleAfterMs: CAPACITY_STALE_MS,
75
82
  seats: visibleSeats,
@@ -0,0 +1,97 @@
1
+ import { z } from 'zod';
2
+ import { WorkCardSchema, UsageEventSchema, ArtifactSchema, SnapshotSchema, PolicySchema } from '../../lib/dispatcher/schemas.mjs';
3
+ import { DispatchRequestSchema, reject } from '../../lib/dispatcher/admission.mjs';
4
+ import { canonicalJson, verifySnapshot } from '../../lib/dispatcher/snapshot.mjs';
5
+ import { verifyPolicy } from '../../lib/dispatcher/policy.mjs';
6
+ import { plan } from '../../lib/dispatcher/planner.mjs';
7
+
8
+ const text = z.string().min(1).max(8192);
9
+ const positive = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
10
+ export const AdviceRequestSchema = z.strictObject({ schemaVersion: z.literal(1), project: text,
11
+ snapshotId: text.optional(), policyVersion: text.optional(), cards: z.array(WorkCardSchema),
12
+ drafts: z.array(WorkCardSchema).optional() });
13
+ export const AdviceAuthoritySchema = z.strictObject({ snapshot: SnapshotSchema, policy: PolicySchema });
14
+ export const AttemptEventSchema = z.discriminatedUnion('kind', [
15
+ z.strictObject({ kind: z.literal('usage'), event: UsageEventSchema }),
16
+ z.strictObject({ kind: z.literal('artifact'), artifact: ArtifactSchema,
17
+ capability: z.strictObject({ generation: positive, launchToken: text }) }),
18
+ ]);
19
+
20
+ async function readable(client, orgId, actor, project) {
21
+ const row = (await client.query('SELECT scopes,revoked_at FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
22
+ if (!row || row.revoked_at != null || !['read','write','approver','owner'].includes(row.scopes[project])
23
+ && !['read','write','approver','owner'].includes(row.scopes['*'])) reject('permission_denied', 403);
24
+ }
25
+
26
+ async function advise(service, orgId, input, actor, auth) {
27
+ const request = AdviceRequestSchema.parse(input);
28
+ if ([...request.cards, ...request.drafts || []].some(c => c.project !== request.project)) reject('permission_denied', 403);
29
+ return service.store.locked(orgId, async client => {
30
+ await readable(client, orgId, actor, request.project);
31
+ const authority = AdviceAuthoritySchema.parse(await service.readAdvice(client, { orgId, request, actor }));
32
+ let snapshot;
33
+ try { snapshot = verifySnapshot(authority.snapshot); verifyPolicy(authority.policy); } catch { reject('snapshot_invalid'); }
34
+ if (request.snapshotId && request.snapshotId !== snapshot.id) reject('snapshot_gone', 410);
35
+ if (request.policyVersion && request.policyVersion !== authority.policy.version) reject('policy_stale');
36
+ for (const card of request.cards) {
37
+ const stored = snapshot.readyQueue.find(c => c.project === card.project && c.card === card.card);
38
+ if (!stored || canonicalJson(stored) !== canonicalJson(card)) reject('card_stale');
39
+ }
40
+ const decision = plan({ ...authority, cards: [...request.cards, ...request.drafts || []] });
41
+ const dispatchable = !request.drafts?.length;
42
+ if (dispatchable) await client.query(`INSERT INTO dispatcher_decisions VALUES($1,$2,$3,$4,$5,$6,$7)
43
+ ON CONFLICT(org_id,id) DO NOTHING`, [orgId, decision.id, request.project, decision.snapshotId,
44
+ decision.policyVersion, decision.createdAtMs, decision]);
45
+ return { schemaVersion: 1, dispatchable, decision: service.projectDecision(decision, auth) };
46
+ });
47
+ }
48
+
49
+ export async function routeDispatcher({ req, res, q: _q, P, auth, ctx }) {
50
+ const match = /^\/dispatch\/([^/]+)(?:\/(heartbeat|events|stop))?$/.exec(P);
51
+ const advice = req.method === 'POST' && P === '/advise';
52
+ const dispatch = req.method === 'POST' && P === '/dispatch';
53
+ if (!advice && !dispatch && !(match && (req.method === 'POST' && match[2] || req.method === 'GET' && !match[2]))) return false;
54
+ try {
55
+ if (ctx.AUTH_MODE === 'off' || !auth?.ok || !auth.identity || !auth.pubkey) reject('permission_denied', 403);
56
+ const service = ctx.dispatcher;
57
+ if (!service) reject('dispatch_unavailable', 503);
58
+ const orgId = service.orgId(auth);
59
+ if (!orgId) reject('permission_denied', 403);
60
+ const actor = { pubkey: auth.pubkey };
61
+ if (advice) return ctx.json(res, 200, await advise(service, orgId, await ctx.body(req), actor, auth));
62
+ if (dispatch) {
63
+ const input = DispatchRequestSchema.parse(await ctx.body(req));
64
+ const result = await service.admission.dispatch(orgId, input, actor);
65
+ return ctx.json(res, result.replayed ? 200 : 202, result);
66
+ }
67
+ const attemptId = decodeURIComponent(match[1]);
68
+ const attempt = await service.store.attempt(orgId, attemptId);
69
+ if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
70
+ if (req.method === 'GET') {
71
+ await service.store.locked(orgId, client => readable(client, orgId, actor, attempt.project));
72
+ return ctx.json(res, 200, { schemaVersion: 1, attemptId, project: attempt.project, card: attempt.card,
73
+ leaseId: attempt.leaseId, state: attempt.state, generation: attempt.generation, artifact: attempt.artifact,
74
+ acceptance: attempt.acceptance, failure: attempt.failure, endedAtMs: attempt.endedAtMs });
75
+ }
76
+ const input = await ctx.body(req);
77
+ let result;
78
+ if (match[2] === 'heartbeat') result = await service.executor.heartbeat(orgId, attemptId, input, actor);
79
+ if (match[2] === 'stop') {
80
+ const stop = z.strictObject({ reason: text }).parse(input);
81
+ result = await service.executor.stop(orgId, attemptId, stop.reason, actor);
82
+ }
83
+ if (match[2] === 'events') {
84
+ const event = AttemptEventSchema.parse(input);
85
+ result = event.kind === 'usage' ? await service.executor.usage(orgId, attemptId, event.event, actor)
86
+ : await service.executor.artifact(orgId, attemptId, event.artifact, event.capability, actor);
87
+ if (event.kind === 'artifact') result = { state: result.state, generation: result.generation };
88
+ }
89
+ return ctx.json(res, 200, { schemaVersion: 1, ...result });
90
+ } catch (error) {
91
+ const status = error instanceof z.ZodError || error instanceof URIError ? 422 : error.status || 503;
92
+ const code = status === 422 ? 'schema_invalid' : error.code || 'dispatch_unavailable';
93
+ if (code === 'admission_busy') res.setHeader('Retry-After', '1');
94
+ return ctx.json(res, status, { schemaVersion: 1, code, reasons: [{ code, resource: null, retryAtMs: null }],
95
+ retryable: status === 429 || status === 503 });
96
+ }
97
+ }