trantor 0.18.148 → 0.18.152

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 (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +11 -8
  4. package/bin/cli.mjs +1 -1
  5. package/bin/connect.mjs +10 -1
  6. package/bin/crew/state.mjs +1 -1
  7. package/bin/crew-runner.mjs +9 -6
  8. package/bin/docker-seat.mjs +33 -0
  9. package/bin/heavy-gate-shim/docker +2 -0
  10. package/bin/integrate.mjs +38 -9
  11. package/bin/migrate-dispatcher.mjs +50 -0
  12. package/bin/turn-watchdog.mjs +15 -1
  13. package/deploy/restart-hub.sh +2 -0
  14. package/docs/FEATURES.md +4 -1
  15. package/hooks/sessionstart.mjs +6 -1
  16. package/hub/auth.mjs +8 -3
  17. package/hub/routes/cards.mjs +13 -1
  18. package/hub/routes/dispatcher-operations.mjs +134 -0
  19. package/hub/routes/dispatcher.mjs +18 -9
  20. package/hub/routes/git-policy.mjs +35 -0
  21. package/hub/startup-config.mjs +14 -0
  22. package/hub/store.mjs +49 -0
  23. package/hub.mjs +19 -2
  24. package/kimi.plugin.json +1 -1
  25. package/lib/canary/canary.mjs +2 -0
  26. package/lib/canary/probes.mjs +62 -0
  27. package/lib/dispatcher/admission.mjs +16 -3
  28. package/lib/dispatcher/board-bridge.mjs +82 -0
  29. package/lib/dispatcher/evidence-bridge.mjs +283 -0
  30. package/lib/dispatcher/operations.mjs +527 -0
  31. package/lib/dispatcher/planner.mjs +4 -2
  32. package/lib/dispatcher/preflight.mjs +44 -7
  33. package/lib/dispatcher/rollout.mjs +357 -0
  34. package/lib/dispatcher/schemas.mjs +1 -0
  35. package/lib/dispatcher/snapshot.mjs +76 -1
  36. package/lib/dispatcher/store.mjs +15 -0
  37. package/lib/dispatcher/verifier.mjs +246 -0
  38. package/lib/docker-janitor.mjs +24 -14
  39. package/lib/git-guard.mjs +181 -0
  40. package/lib/integrate.mjs +10 -2
  41. package/lib/store-contract.mjs +63 -0
  42. package/lib/store-pg.mjs +38 -3
  43. package/mcp.mjs +4 -5
  44. package/package.json +3 -3
@@ -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.148"
9
+ "version": "0.18.152"
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.148",
16
+ "version": "0.18.152",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.148",
3
+ "version": "0.18.152",
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,16 +241,19 @@ export function advise(input, world = loadWorld()) {
241
241
  return recommendation;
242
242
  }
243
243
 
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.
244
+ // #14678: stdin carrying {cards|drafts}, or --card/--snapshot/--policy, asks the hub's planner (POST /advise);
245
+ // {task, packages} keeps the legacy advisor above, usable in shadow mode. #14742: cards may be card
246
+ // numbers (--card N, repeatable, or {cards:[N]}); the hub's own WorkCard for each is fetched first.
247
+ export const cardFlags = (argv) => argv.flatMap((a, i) => (a === "--card" ? [Number(argv[i + 1])] : []));
246
248
  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 { signedGet, signedPost, sessionContext } = await import("../hooks/lib/api.mjs");
250
+ const { adviseCards, renderAdvice } = await import("../lib/dispatcher/preflight.mjs");
249
251
  const flag = (name) => { const i = argv.indexOf(name); return i > -1 ? argv[i + 1] : undefined; };
250
252
  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 });
253
+ const result = await adviseCards({ project, cards: [...(input.cards || []), ...cardFlags(argv)], drafts: input.drafts || [],
254
+ snapshotId: flag("--snapshot") || input.snapshotId, policyVersion: flag("--policy") || input.policyVersion,
255
+ get: (path) => signedGet(path, { project, timeoutMs: 5000 }),
256
+ post: (path, body) => signedPost(path, body, { project, timeoutMs: 10000 }), busDir: busDir() });
254
257
  console.log(argv.includes("--json") ? JSON.stringify(result, null, 2) : renderAdvice(result));
255
258
  return result.source === "refused" ? 1 : 0;
256
259
  }
@@ -263,7 +266,7 @@ if (import.meta.url === pathToFileURL(process.argv[1]).href) {
263
266
  if (!argv.includes("--demo")) {
264
267
  const stdin = process.stdin.isTTY ? "" : readFileSync(0, "utf8").trim();
265
268
  input = stdin ? JSON.parse(stdin) : { packages: [] };
266
- if (input.cards || input.drafts || argv.includes("--snapshot") || argv.includes("--policy")) process.exit(await hubAdvice(input, argv));
269
+ if (input.cards || input.drafts || ["--card", "--snapshot", "--policy"].some((f) => argv.includes(f))) process.exit(await hubAdvice(input, argv));
267
270
  }
268
271
  if (argv.includes("--demo")) {
269
272
  input = { task: "neon asteroids game", packages: [
package/bin/cli.mjs CHANGED
@@ -320,7 +320,7 @@ switch (cmd) {
320
320
  trantor capacity the live ledger: budgets and resets, burn rate, machines, seats — [--json] [--version 1 [--snapshot <id>]]
321
321
  trantor recost recompute sub-agent notional cost from on-disk transcripts + reseed the board (repair after upgrade) — [--dry-run]
322
322
  trantor handoff finish this session NOW: write a handoff, open a fresh session that takes over, and close this one (manual baton)
323
- trantor advise ask the Advisor directly (JSON on stdin; --demo to see it); {"cards":[...]} asks the hub planner — [--json] [--snapshot <id>] [--policy <v>]
323
+ trantor advise ask the Advisor directly (JSON on stdin; --demo to see it); --card <n> (repeatable) or {"cards":[<n>]} asks the hub planner — [--json] [--snapshot <id>] [--policy <v>]
324
324
  trantor dispatch admit planned cards through the hub: --decision <id> [--card <n>] · status <attemptId> · preflight — [--json]
325
325
  trantor project this checkout's identity: project [<id>] — records .trantor/project.json so a directory rename cannot orphan the board, pin and sessions
326
326
  project permissions <name> [ask|bypass] — whether <name>'s agents ask before acting or act without asking; no value prints it
package/bin/connect.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // trantor connect — wire every AI coding CLI on this machine to the bus, in one shot (idempotent;
3
3
  // --dry-run touches nothing). Writes the one "relay" MCP entry into each CLI's own config format,
4
4
  // with a timestamped .bak backup on first change. Claude Code rides the plugin: verified, not patched.
5
- import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync } from "node:fs";
5
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync, realpathSync, statSync } from "node:fs";
6
6
  import { join, dirname } from "node:path";
7
7
  import { homedir } from "node:os";
8
8
  import { execSync } from "node:child_process";
@@ -296,6 +296,15 @@ const found = out.length;
296
296
  if (!DRY) writeProjectId(root, PROJECT_AT_CONNECT, "trantor connect");
297
297
  report("project", `id ${PROJECT_AT_CONNECT} recorded in ${PROJECT_MARKER} — commit it so worktrees and clones carry the identity`, root);
298
298
  }
299
+ // Linked worktrees must not register themselves as the operator's checkout.
300
+ if (root && ["marker", "git"].includes(PROJECT_INFO.via) && statSync(join(root, ".git")).isDirectory()) {
301
+ if (!DRY) {
302
+ const path = join(root, PROJECT_MARKER);
303
+ const marker = JSON.parse(readFileSync(path, "utf8"));
304
+ writeFileSync(path, JSON.stringify({ ...marker, operatorCheckout: realpathSync(root) }, null, 2) + "\n");
305
+ }
306
+ report("project", `${DRY ? "would record" : "recorded"} operator checkout`, root);
307
+ }
299
308
  }
300
309
  console.log(`trantor connect${DRY ? " (dry run)" : ""} — project: ${PROJECT_AT_CONNECT}, hub: ${URL_}`);
301
310
  for (const r of out) console.log(` ${r.cli.padEnd(9)} ${r.status}${r.detail ? ` (${r.detail})` : ""}`);
@@ -53,7 +53,7 @@ export function dropState(ctx, project, kind, agent = "", handle = "") {
53
53
  // never rm, never volumes; docker absent skips silently. Same kill-switch as the process kill.
54
54
  async function stopSeatContainers(ctx, project, agent) {
55
55
  if (ctx.dry || ctx.env?.CREW_NO_PROC_KILL === "1" || !project || !agent) return;
56
- const r = dockerSweep({ path: dockerStatePathFor(agent, project) });
56
+ const r = dockerSweep({ path: dockerStatePathFor(agent, project), owner: `${agent}:${project}` });
57
57
  if (r.skipped || !r.stopped.length) return;
58
58
  console.log(` 🧹 ${agent}:${project} — stopped ${r.stopped.length} container(s): ${r.stopped.join(", ")}`);
59
59
  try {
@@ -226,7 +226,7 @@ async function api(path, body) {
226
226
  let payload;
227
227
  if (body) {
228
228
  payload = { ...body };
229
- if (path === "/register" && MACHINE_LABEL) payload.machine = MACHINE_LABEL;
229
+ if (path === "/register") payload.machine = MACHINE_LABEL || hostId().toLowerCase();
230
230
  }
231
231
  const opts = body
232
232
  ? { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body: JSON.stringify(payload) }
@@ -414,9 +414,10 @@ const PARKF = join(homedir(), ".agent-bus", `park-${PERSONA}-${PROJ}.json`);
414
414
  // #9778: the seat's recorded containers, persisted per seat so a card close, a park or
415
415
  // `trantor down <seat>` can stop what the seat started even after this runner is gone.
416
416
  const DOCKERF = dockerStatePathFor(PERSONA, PROJ);
417
+ const DOCKER_SEAT = `${PERSONA}:${PROJ}`;
417
418
  // One bus line per sweep, naming what was stopped; docker absent sweeps stay silent by contract.
418
419
  async function janitorStop(why, card) {
419
- const r = dockerSweep({ path: DOCKERF, card });
420
+ const r = dockerSweep({ path: DOCKERF, card, owner: DOCKER_SEAT });
420
421
  if (r.skipped || !r.stopped.length) return;
421
422
  const text = `🧹 ${SESSION} stopped ${r.stopped.length} container(s) (${why}): ${r.stopped.join(", ")}${r.failed.length ? ` · could not stop: ${r.failed.join(", ")}` : ""}`;
422
423
  log(text);
@@ -686,7 +687,7 @@ async function registerStatus(status, extra = {}) {
686
687
  }
687
688
  const url = HUB + "/register";
688
689
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
689
- if (MACHINE_LABEL) payload.machine = MACHINE_LABEL;
690
+ payload.machine = MACHINE_LABEL || hostId().toLowerCase();
690
691
  const body = JSON.stringify(payload);
691
692
  try {
692
693
  const opts = { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body };
@@ -1050,9 +1051,10 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
1050
1051
  } : undefined;
1051
1052
  const presencePayload = { session: SESSION, project: PROJ, status: `working · ${trigger}`, persona: PERSONA,
1052
1053
  agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
1053
- if (MACHINE_LABEL) presencePayload.machine = MACHINE_LABEL;
1054
+ presencePayload.machine = MACHINE_LABEL || hostId().toLowerCase();
1054
1055
  writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
1055
- presence: { intervalMs: PRESENCE_MS, payload: presencePayload } }));
1056
+ presence: { intervalMs: PRESENCE_MS, payload: presencePayload },
1057
+ worktree: { cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: presencePayload.machine } }));
1056
1058
  const wd = spawn(process.execPath, [join(import.meta.dirname, "turn-watchdog.mjs"), STAMPF, ERRF, String(WD_MS), SESSION, PROJ, HUB, TRANSCRIPT_DIR, TURN_DIR,
1057
1059
  // #7752: the stall marker only exists when a box does — with no box there is no sweep to
1058
1060
  // end the turn, so the watchdog stays report-only (reporting is the whole job, boxless).
@@ -1121,6 +1123,7 @@ exit $turn_exit`;
1121
1123
  // so a handoff spawn would only leak an unmanaged interactive window.
1122
1124
  TRANTOR_NO_HANDOFF_SPAWN: "1", TRANTOR_NO_BATON_SPAWN: "1",
1123
1125
  TRANTOR_HEAVY_GATE_WAIT_DIR: HEAVY_WAIT_DIR,
1126
+ TRANTOR_DOCKER_SEAT: `${PERSONA}:${PROJ}`,
1124
1127
  // Spelled out here, not HEAVY_SHIM_DIR: the turn drills run this function alone, without the module's constants (#14048).
1125
1128
  PATH: `${join(import.meta.dirname, "heavy-gate-shim")}:${process.env.PATH || ""}`,
1126
1129
  // #6206: the seat's transcript dir — a real CLI ignores it, a drill's fake CLI writes
@@ -1250,7 +1253,7 @@ exit $turn_exit`;
1250
1253
  const busActive = await busActivitySince(busSeqBefore);
1251
1254
  // #9778: containers this turn created are recorded against its card — and land on the telemetry
1252
1255
  // row, which is the ledger the seat record (#7762) is derived from.
1253
- const dockerNew = newContainers(dockerBefore, listContainers());
1256
+ const dockerNew = newContainers(dockerBefore, listContainers(), `${PERSONA}:${PROJ}`);
1254
1257
  if (dockerNew.length) {
1255
1258
  recordContainers({ path: DOCKERF, card: sessionCard || 0, containers: dockerNew });
1256
1259
  log(`turn started ${dockerNew.length} container(s) — recorded against #${sessionCard || 0}: ${dockerNew.map(c => c.name || c.id).join(", ")}`);
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import { accessSync, constants } from "node:fs";
4
+ import { delimiter, join, resolve } from "node:path";
5
+ import { SEAT_LABEL } from "../lib/docker-janitor.mjs";
6
+
7
+ const shim = resolve(import.meta.dirname, "heavy-gate-shim", "docker");
8
+ let binary = "";
9
+ for (const dir of String(process.env.PATH || "").split(delimiter)) {
10
+ if (!dir) continue;
11
+ const candidate = resolve(dir, "docker");
12
+ if (candidate === shim) continue;
13
+ try {
14
+ accessSync(candidate, constants.X_OK);
15
+ binary = candidate;
16
+ break;
17
+ } catch {}
18
+ }
19
+
20
+ if (!binary) {
21
+ console.error("docker: executable not found");
22
+ process.exit(127);
23
+ }
24
+
25
+ const args = process.argv.slice(2);
26
+ const owner = process.env.TRANTOR_DOCKER_SEAT || "";
27
+ const command = args[0] === "container" ? 1 : 0;
28
+ if (owner && ["run", "create"].includes(args[command])) {
29
+ args.splice(command + 1, 0, "--label", `${SEAT_LABEL}=${owner}`);
30
+ }
31
+ const result = spawnSync(binary, args, { stdio: "inherit" });
32
+ if (result.error) console.error(`docker: ${result.error.message}`);
33
+ process.exit(result.status ?? 1);
@@ -0,0 +1,2 @@
1
+ #!/bin/sh
2
+ exec node "$(dirname "$0")/../docker-seat.mjs" "$@"
package/bin/integrate.mjs CHANGED
@@ -8,7 +8,8 @@ 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
10
  import { ownerIdentity } from "../lib/enroll.mjs";
11
- import { checkSeatReview } from "../lib/review-gate.mjs";
11
+ import { readGitPolicy, cacheGitPolicy, checkoutRole, installGitGuard, landingVerdict } from "../lib/git-guard.mjs";
12
+ import { checkSeatReview, publishSeatReview } from "../lib/review-gate.mjs";
12
13
 
13
14
  const D = "\x1b[2m", B = "\x1b[1m", G = "\x1b[32m", Y = "\x1b[33m", RED = "\x1b[31m", R = "\x1b[0m";
14
15
  const args = process.argv.slice(2);
@@ -16,6 +17,19 @@ const dry = args.includes("--dry-run");
16
17
  const repo = process.cwd();
17
18
  const project = resolveProject(repo);
18
19
  const a = resolveAutonomy(project);
20
+ const hub = resolveHub(project);
21
+ const identity = ownerIdentity();
22
+ const role = checkoutRole(repo);
23
+ const requiresLandingPolicy = role !== "seat" && role !== "integration";
24
+ const policy = await readGitPolicy({ hub, identity, project });
25
+ if (requiresLandingPolicy) {
26
+ if (!dry) { installGitGuard(repo, project); cacheGitPolicy(repo, project, policy); }
27
+ for (const action of ["land", "integrate"]) {
28
+ if (policy.effective[action] !== "click") continue;
29
+ console.error(landingVerdict(policy, { action }).reason);
30
+ process.exit(1);
31
+ }
32
+ }
19
33
 
20
34
  console.log(`${B}integrate${R} · ${project} ${D}commit=${a.commit ? "on" : "off"} push=${a.push ? "on" : "off"} deploy=${a.deploy ? "on" : "off"}${R}`);
21
35
 
@@ -42,24 +56,34 @@ for (const w of seats) {
42
56
  console.log(` ${G}${w.agent}: committed ${r.sha}${R}`);
43
57
  }
44
58
 
45
- // 2. Merge what each seat is ahead by. A conflict stops the pass: two seats on the same lines is
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.
59
+ // Review is tied to the seat tip; a changed tip must be reviewed again before landing.
49
60
  const merged = [];
50
- const hub = resolveHub(project);
51
- const identity = ownerIdentity();
52
61
  for (const w of seats) {
53
62
  const { branch, ahead } = seatAhead(w, base);
54
63
  if (!ahead) continue;
55
- const review = await checkSeatReview({ hub, identity, project, seat: w.agent, dir: w.dir, base, tip: branch, publish: !dry });
64
+ const tip = git(w.dir, ["rev-parse", branch]);
65
+ let review = { reviewed: false, merge: true };
66
+ if (requiresLandingPolicy) {
67
+ const required = policy.effective.land === "review" || policy.effective.integrate === "review";
68
+ if (required && !dry) await publishSeatReview({ hub, identity, project, seat: w.agent, dir: w.dir, base, tip });
69
+ review = await checkSeatReview({ hub, identity, project, seat: w.agent, dir: w.dir, base, tip, publish: !dry });
70
+ if (required && !review.reviewed) review = { merge: false, reason: "Mixed mode: review required at the current tip" };
71
+ review = { ...review, tip };
72
+ }
56
73
  if (!review.merge) {
57
74
  console.log(` ${Y}${w.agent}: skipped, ${review.reason}${R}`);
58
75
  continue;
59
76
  }
60
77
  if (review.reviewed) console.log(` ${D}${w.agent}: ${review.reason}${R}`);
61
78
  if (dry) { console.log(` ${D}[dry] would merge ${branch} (${ahead} commit(s))${R}`); merged.push(branch); continue; }
62
- const m = mergeSeat(repo, branch);
79
+ const current = await readGitPolicy({ hub, identity, project });
80
+ if (requiresLandingPolicy) cacheGitPolicy(repo, project, current);
81
+ const m = mergeSeat(repo, tip, { policy: current, review, action: "integrate" });
82
+ if (m.refused) {
83
+ console.log(` ${Y}${branch}: ${m.detail}${R}`);
84
+ blocked = true;
85
+ continue;
86
+ }
63
87
  if (m.conflict) {
64
88
  console.log(` ${RED}${branch}: CONFLICT — left untouched${R}\n${D}${m.detail}${R}`);
65
89
  blocked = true;
@@ -100,6 +124,11 @@ if (!a.push) {
100
124
  console.log(`${D}push is off — integrated and verified locally (trantor autonomy set push on)${R}`);
101
125
  process.exit(0);
102
126
  }
127
+ const shippingPolicy = await readGitPolicy({ hub, identity, project });
128
+ if (shippingPolicy.effective.push !== "autonomy") {
129
+ console.log(`${Y}${shippingPolicy.mode} mode: push from the sidebar${R}`);
130
+ process.exit(1);
131
+ }
103
132
  git(repo, ["push"]);
104
133
  console.log(`${G}pushed ${base}${R}`);
105
134
  if (a.deploy) console.log(`${D}deploy is on, but this project has no deploy step wired here yet${R}`);
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { PgStore } from '../lib/store-pg.mjs';
5
+ import { DISPATCHER_MIGRATION_ID, DISPATCHER_MIGRATION_LOCK_SQL,
6
+ DISPATCHER_SCHEMA_SQL, DISPATCHER_SCHEMA_VERSION } from '../lib/dispatcher/store.mjs';
7
+ import { backfillAttempts } from '../lib/dispatcher/migrate-attempts.mjs';
8
+ import { DISPATCHER_INTEGRATION_SQL } from '../lib/store-contract.mjs';
9
+
10
+ export async function migrateDispatcher({ store, batchSize = 1000, onCheckpoint = () => {} }) {
11
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1000) {
12
+ throw new RangeError('batch size must be between 1 and 1000');
13
+ }
14
+ const transaction = store.transaction.bind(store);
15
+ await transaction(async client => {
16
+ await client.query(DISPATCHER_MIGRATION_LOCK_SQL);
17
+ await client.query(DISPATCHER_SCHEMA_SQL);
18
+ await client.query(DISPATCHER_INTEGRATION_SQL);
19
+ await client.query(`INSERT INTO dispatcher_migrations(id,schema_version,checkpoint,completed_at_ms)
20
+ VALUES($1,$2,$3,NULL) ON CONFLICT(id) DO NOTHING`,
21
+ [DISPATCHER_MIGRATION_ID, DISPATCHER_SCHEMA_VERSION, { lastKey: null, scanned: 0 }]);
22
+ });
23
+ let checkpoint;
24
+ do {
25
+ checkpoint = await backfillAttempts({ transaction, batchSize });
26
+ await onCheckpoint(checkpoint);
27
+ } while (!checkpoint.complete);
28
+ return checkpoint;
29
+ }
30
+
31
+ async function main() {
32
+ const { values } = parseArgs({ options: { 'batch-size': { type: 'string', default: '1000' },
33
+ help: { type: 'boolean', default: false } } });
34
+ if (values.help) {
35
+ process.stdout.write('Usage: node bin/migrate-dispatcher.mjs [--batch-size 1..1000]\nUses RELAY_DATABASE_URL or DATABASE_URL for an initialized PostgreSQL hub.\n');
36
+ return;
37
+ }
38
+ const url = process.env.RELAY_DATABASE_URL || process.env.DATABASE_URL;
39
+ if (!url) throw new Error('RELAY_DATABASE_URL or DATABASE_URL is required');
40
+ const { default: pg } = await import('pg');
41
+ const pool = new pg.Pool({ connectionString: url });
42
+ try {
43
+ await migrateDispatcher({ store: new PgStore({ pool }), batchSize: Number(values['batch-size']),
44
+ onCheckpoint: checkpoint => process.stdout.write(`${JSON.stringify(checkpoint)}\n`) });
45
+ } finally { await pool.end(); }
46
+ }
47
+
48
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
49
+ main().catch(error => { process.stderr.write(`Dispatcher migration failed: ${error.message}\n`); process.exitCode = 1; });
50
+ }
@@ -10,6 +10,7 @@ import { hostId } from "../lib/project.mjs";
10
10
  import { signedPost } from "../hooks/lib/api.mjs";
11
11
  import { refreshTurnLiveness } from "../lib/turnstate.mjs";
12
12
  import { readHeavyGateWait } from "../lib/heavy-gate-wait.mjs";
13
+ import { createWorktreeStatusReporter } from "../lib/worktree-status.mjs";
13
14
 
14
15
  const [stampFile, errFile, windowMsRaw, session, project, hub, transcriptDir = "", workDir = "", stallFile = "", turnStateFile = "", heavyWaitDir = ""] = process.argv.slice(2);
15
16
  // SAFETY: the 10-minute floor lives in crew-runner.mjs (the default when TRANTOR_TURN_WATCHDOG_MS
@@ -56,6 +57,15 @@ const runnerAlive = () => {
56
57
  // The runner is blocked in spawnSync for the whole turn, so presence beats from this helper.
57
58
  // The stamp check pins every beat to this runner and turn; killing the watchdog clears the timer.
58
59
  const presence = armed.presence;
60
+ const worktree = armed.worktree;
61
+ const worktreeStatus = worktree ? createWorktreeStatusReporter({
62
+ ...worktree,
63
+ post: async status => {
64
+ const result = await signedPost(`${hub}/worktree-status`, status, { session, timeoutMs: 5000 });
65
+ if (!result.ok || !result.json?.ok) throw new Error(result.json?.error || `hub ${result.status}`);
66
+ },
67
+ }) : null;
68
+ worktreeStatus?.start();
59
69
  let presenceBusy = false;
60
70
  async function beatPresence() {
61
71
  if (!presence || presenceBusy) return;
@@ -64,10 +74,14 @@ async function beatPresence() {
64
74
  presenceBusy = true;
65
75
  try {
66
76
  await signedPost(`${hub}/register`, presence.payload, { session, timeoutMs: 5000 });
77
+ await worktreeStatus?.heartbeat();
67
78
  } catch {} finally { presenceBusy = false; }
68
79
  }
69
80
  const presenceTimer = presence ? setInterval(beatPresence, Math.max(100, Number(presence.intervalMs) || 60000)) : null;
70
- process.on("exit", () => { if (presenceTimer) clearInterval(presenceTimer); });
81
+ process.on("exit", () => {
82
+ if (presenceTimer) clearInterval(presenceTimer);
83
+ worktreeStatus?.stop();
84
+ });
71
85
 
72
86
  // One observation of every liveness channel: stderr growth, transcript mtime, worktree mtime.
73
87
  const ago = (t) => (t > 0 ? `${Math.max(1, Math.round((Date.now() - t) / 60000))}m ago` : "never");
@@ -8,6 +8,8 @@ if [ ! -d "$REPO_ROOT/hub" ]; then
8
8
  exit 1
9
9
  fi
10
10
 
11
+ node "$REPO_ROOT/hub/startup-config.mjs"
12
+
11
13
  FORCE=0
12
14
  if [ "${1:-}" = "--force" ]; then
13
15
  FORCE=1
package/docs/FEATURES.md CHANGED
@@ -11,7 +11,8 @@ Rules for this file:
11
11
  - One row per feature. The `id` column is the probe's name in `lib/canary/probes.mjs`; a row whose
12
12
  id has no probe fails the canary, so the table and the code cannot drift apart.
13
13
  - A probe only reads: files, `git log`, `herdr agent list` / `herdr pane read`, the hub's public
14
- `/health`, the npm registry, GitHub releases and the app's read socket. It never writes, sends,
14
+ `/health`, `trantor capacity --version 1 --json` (one signed GET of the planning view), the npm
15
+ registry, GitHub releases and the app's read socket. It never writes, sends,
15
16
  clicks, navigates, stages or commits.
16
17
  - A probe says `skip` when the thing it reads is not on this machine (no app running, no idle
17
18
  Claude pane, not macOS). A skip is never posted, and it neither opens nor closes an episode.
@@ -43,3 +44,5 @@ Rules for this file:
43
44
  | `workspace-layouts` | The Workspace layouts render | the running app's read socket returns the main window's text, non-empty and without an error screen | #14618 | `desktop/src/v2/shell/`, `desktop/src/v2/screens/Workspace/` | `workspace-layouts` | mac | yes |
44
45
  | `file-actions-no-commit` | File actions in the operator's own checkout don't commit | each known project's main checkout HEAD reflog for the last 7 days has no `create … in the app` / `delete … in the app` / `rename … in the app` commit | #14639 | `desktop/src-tauri/src/file_ops.rs` | `file-actions-no-commit` | mac | yes |
45
46
  | `launchers` | Every com.trantor.* launcher's program path exists | each `~/Library/LaunchAgents/com.trantor.*.plist`'s pinned paths exist and none is a versioned Homebrew Cellar path | #14646 | `lib/launchd.mjs`, `lib/launch-node.mjs` | `launchers` | mac | yes |
47
+ | `dispatcher-runbook` | The dispatcher runbook names only commands and routes this tree serves (runbook: `docs/RUNBOOK-dispatcher.md`; drill: D15 in `test/dispatcher/test-rollout.mjs`) | every `trantor <cmd>` in `docs/RUNBOOK-dispatcher.md` is a subcommand in `bin/cli.mjs`, every `/dispatcher/…` route it names is in `hub/routes/dispatcher-operations.mjs` or `hub/routes/dispatcher.mjs`, and every `bin/*.mjs` it names exists; skips where the runbook is not shipped | #14682 | `docs/RUNBOOK-dispatcher.md`, `bin/cli.mjs`, `hub/routes/dispatcher-operations.mjs`, `hub/routes/dispatcher.mjs` | `dispatcher-runbook` | any | yes |
48
+ | `dispatcher-fail-closed` | The planner's capacity view fails closed (runbook: `docs/RUNBOOK-dispatcher.md` "What failing closed looks like"; drill: D16 in `test/dispatcher/test-feature-wiring.mjs`) | `trantor capacity --version 1 --json` answers a planning view with a snapshot id and policy version, or a hub refusal with its code, or local-only with a named cause and no dispatch token | #14678 | `bin/capacity.mjs`, `lib/dispatcher/preflight.mjs`, `lib/dispatcher/snapshot.mjs` | `dispatcher-fail-closed` | any | yes |
@@ -2,7 +2,7 @@
2
2
  // trantor SessionStart hook — every session registers with the hub and gets a roster of OTHER live
3
3
  // sessions injected, so independent sessions discover each other. Config: env RELAY_URL →
4
4
  // ~/.agent-bus/config.json → http://127.0.0.1:4477. Identity: RELAY_SESSION → "<hostname>:<basename(cwd)>".
5
- import { readFileSync, existsSync } from "node:fs";
5
+ import { readFileSync, existsSync, appendFileSync } from "node:fs";
6
6
  import { join, basename, dirname } from "node:path";
7
7
  import { homedir, hostname } from "node:os";
8
8
  import { execSync, spawn } from "node:child_process";
@@ -167,6 +167,11 @@ try {
167
167
  sessionTitle = project; // baseline — enriched with the current work item after the catch-up fetch below
168
168
  const session = process.env.RELAY_SESSION
169
169
  || (process.env.RELAY_AGENT ? `${process.env.RELAY_AGENT}:${project}` : `${hostId()}:${project}`);
170
+ // #14750: hook subprocess env cannot reach Bash; Claude sources this file for later tools.
171
+ if (project && process.env.TRANTOR_ORCH === project && process.env.CLAUDE_ENV_FILE) {
172
+ const quotedSession = "'" + session.replaceAll("'", "'\\''") + "'";
173
+ appendFileSync(process.env.CLAUDE_ENV_FILE, `\nexport TRANTOR_AGENT_IDENTITY=${quotedSession}\n`);
174
+ }
170
175
  // relayUrl() with no project resolves from the hook process's cwd, which is not always the
171
176
  // project the session is about. Pass it, or every call below can address the wrong hub.
172
177
  // resolveHubInfo carries HOW the hub was chosen so an unpinned project can be flagged below
package/hub/auth.mjs CHANGED
@@ -17,7 +17,7 @@ const OWNER_BODY_CAPS = new Map([
17
17
  ["/session/chat", BODY_CAP_OWNER_CHAT],
18
18
  ["/handoff", BODY_CAP_DEFAULT], ["/task", BODY_CAP_DEFAULT], ["/task/update", BODY_CAP_DEFAULT],
19
19
  ]);
20
- function bodyCap(P) { return P === "/session/prompt" ? BODY_CAP_PROMPT : BODY_CAP_DEFAULT; }
20
+ function bodyCap(P) { return P === "/advise" ? 1024 * 1024 : P === "/session/prompt" ? BODY_CAP_PROMPT : BODY_CAP_DEFAULT; }
21
21
  function ownerBodyCap(req, P) {
22
22
  const cap = OWNER_BODY_CAPS.get(P) || bodyCap(P);
23
23
  if (cap <= bodyCap(P) || !Object.values(HDR).every(h => req.headers[h])) return bodyCap(P);
@@ -141,6 +141,11 @@ const canRead = (auth, project) => AUTH_MODE !== "enforce" && !auth?.identity
141
141
  ? true
142
142
  : isDutyIdentity(auth) || scopeAllows(auth?.identity, project, "read");
143
143
  function projectFromRequest(P, q, b, method) {
144
+ const gitPolicyPath = /^\/projects\/([^/]+)\/git-policy$/.exec(P);
145
+ if (gitPolicyPath) {
146
+ try { return canon(decodeURIComponent(gitPolicyPath[1])); }
147
+ catch { return ""; }
148
+ }
144
149
  if (P === "/task/update" || P === "/card") {
145
150
  const t = state.tasks.find(x => x.id === Number(b?.id ?? q?.id));
146
151
  return t?.project || "";
@@ -170,7 +175,7 @@ function projectFromRequest(P, q, b, method) {
170
175
  return canon(String(b?.project || q?.project || "").slice(0, 80));
171
176
  }
172
177
  // Cross-project actions require a declared link or the operator identity, even with wildcard scopes (#6228).
173
- const CROSS_PROJECT_ENDPOINTS = new Set(["/send", "/task", "/task/update", "/register", "/invite"]);
178
+ const CROSS_PROJECT_ENDPOINTS = new Set(["/send", "/task", "/task/update", "/register", "/invite", "/dispatch"]);
174
179
  function projectsLinked(a, b) {
175
180
  if (!a || !b || a === b) return true;
176
181
  return overseerPolicy().links.some(l => {
@@ -204,7 +209,7 @@ function crossProjectTarget(P, b) {
204
209
  const to = String(b.to);
205
210
  return canon(state.peers[to]?.project || (to.includes(":") ? to.slice(to.lastIndexOf(":") + 1) : ""));
206
211
  }
207
- if (P === "/task" || P === "/register") return canon(String(b?.project || "").slice(0, 80));
212
+ if (P === "/task" || P === "/register" || P === "/dispatch") return canon(String(b?.project || "").slice(0, 80));
208
213
  if (P === "/task/update") {
209
214
  const t = state.tasks.find(x => x.id === Number(b?.id));
210
215
  return t?.project || "";
@@ -206,7 +206,19 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
206
206
  markDirty(); return json(res, 200, { ok: true, task: t });
207
207
  }
208
208
  if (req.method === "POST" && P === "/task/update") { // move/edit a card
209
- const b = await body(req); const found = state.tasks.find(x => x.id === Number(b.id));
209
+ const b = await body(req);
210
+ if (ctx.dispatcher) {
211
+ try {
212
+ const guarded = crossProjectGuard(auth, P, b);
213
+ if (!guarded.ok) return json(res, guarded.code, { error: guarded.error });
214
+ const task = await ctx.mutateDispatcherCard(b, auth);
215
+ if (task) return json(res, 200, { ok: true, task });
216
+ } catch (error) {
217
+ const status = error.name === 'ZodError' ? 422 : error.status || 503;
218
+ return json(res, status, { code: error.code || 'schema_invalid' });
219
+ }
220
+ }
221
+ const found = state.tasks.find(x => x.id === Number(b.id));
210
222
  const t = found && copyTask(found);
211
223
  if (!t) return json(res, 404, { error: "no such task" });
212
224
  const cpg = crossProjectGuard(auth, P, b);
@@ -0,0 +1,134 @@
1
+ import { z } from 'zod';
2
+ import { reject } from '../../lib/dispatcher/admission.mjs';
3
+ import { requireRole } from '../../lib/dispatcher/operations.mjs';
4
+
5
+ export function dispatcherEndpoint(method, path, query) {
6
+ return path === '/dispatch' || path.startsWith('/dispatch/') || path.startsWith('/dispatcher/')
7
+ || method === 'POST' && path === '/advise'
8
+ || method === 'GET' && path === '/capacity' && query.version !== undefined;
9
+ }
10
+
11
+ export async function routeDispatcherOperations({ req, res, P, q, auth, ctx }) {
12
+ if (!dispatcherEndpoint(req.method, P, q) || P === '/dispatch' || P === '/advise'
13
+ || /^\/dispatch\/[^/]+(?:\/(heartbeat|events|stop))?$/.test(P)) return false;
14
+ try {
15
+ if (ctx.AUTH_MODE === 'off' || !ctx.dispatcher) reject('dispatch_unavailable', 503);
16
+ if (!auth?.ok || !auth.identity || !auth.pubkey || auth.warning) reject('permission_denied', 403);
17
+ const service = ctx.dispatcher;
18
+ const orgId = service.orgId(auth);
19
+ if (!orgId) reject('permission_denied', 403);
20
+ const actor = { pubkey: auth.pubkey };
21
+ const rolloutRoutes = { '/dispatcher/rollout/shadow': 'shadowTick', '/dispatcher/rollout/rating': 'rateShadow',
22
+ '/dispatcher/rollout/freeze': 'freezeRollout', '/dispatcher/rollout/baseline': 'freezeBaseline', '/dispatcher/rollout/drill': 'recordDrill',
23
+ '/dispatcher/policy/rollback': 'rollbackPolicy' };
24
+ if (req.method === 'POST' && Object.hasOwn(rolloutRoutes, P)) {
25
+ return ctx.json(res, 200, await service[rolloutRoutes[P]](orgId, await ctx.body(req), actor));
26
+ }
27
+ if (req.method === 'GET' && P === '/dispatcher/rollout') {
28
+ return ctx.json(res, 200, await service.rolloutReport(orgId, q, actor));
29
+ }
30
+ if (req.method === 'POST' && P === '/dispatcher/verifiers') {
31
+ return ctx.json(res, 200, await service.verifier.registerGrant(orgId, await ctx.body(req), actor));
32
+ }
33
+ if (req.method === 'POST' && P === '/dispatcher/verification-jobs/claim') {
34
+ return ctx.json(res, 200, await service.verifier.claim(orgId, await ctx.body(req), actor));
35
+ }
36
+ const beat = /^\/dispatcher\/verification-jobs\/([^/]+)\/heartbeat$/.exec(P);
37
+ if (req.method === 'POST' && beat) {
38
+ return ctx.json(res, 200, await service.verifier.heartbeat(orgId, decodeURIComponent(beat[1]), await ctx.body(req), actor));
39
+ }
40
+ const verify = /^\/dispatch\/([^/]+)\/(verify|acceptance)$/.exec(P);
41
+ if (req.method === 'POST' && verify) {
42
+ const id = decodeURIComponent(verify[1]);
43
+ const attempt = await service.store.attempt(orgId, id);
44
+ if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
45
+ const result = verify[2] === 'verify'
46
+ ? await service.verifier.enqueue(orgId, id, await ctx.body(req), actor)
47
+ : await service.verifier.accept(orgId, id, await ctx.body(req), actor);
48
+ return ctx.json(res, verify[2] === 'verify' && !result.replayed ? 202 : 200, result);
49
+ }
50
+ const read = async (project, operation) => service.store.locked(orgId, async client => {
51
+ await requireRole(client, orgId, actor, project, ['read', 'write', 'approver', 'owner']);
52
+ return operation(client);
53
+ });
54
+ if (req.method === 'GET' && P === '/dispatcher/pacing') {
55
+ const request = z.strictObject({ project: z.string().min(1).max(8192) }).parse(q);
56
+ return ctx.json(res, 200, await service.pacing(orgId, request, actor));
57
+ }
58
+ if (req.method === 'GET' && P === '/capacity') {
59
+ if (q.version !== '1' || !q.project) reject('schema_invalid', 422);
60
+ return ctx.json(res, 200, await service.capacity(orgId, q, actor));
61
+ }
62
+ if (req.method === 'POST' && P === '/dispatcher/evidence') {
63
+ return ctx.json(res, 201, await service.registerEvidence(orgId, await ctx.body(req), actor));
64
+ }
65
+ if (req.method === 'POST' && P === '/dispatcher/cards') {
66
+ return ctx.json(res, 201, await service.registerCard(orgId, await ctx.body(req), actor));
67
+ }
68
+ if (req.method === 'POST' && P === '/dispatcher/collectors') {
69
+ return ctx.json(res, 200, await service.registerCollector(orgId, await ctx.body(req), actor));
70
+ }
71
+ if (req.method === 'POST' && P === '/dispatcher/bridge-grants') {
72
+ return ctx.json(res, 200, await service.registerBridgeGrant(orgId, await ctx.body(req), actor));
73
+ }
74
+ if (req.method === 'POST' && P === '/dispatcher/policy/activate') {
75
+ return ctx.json(res, 200, await service.activatePolicy(orgId, await ctx.body(req), actor));
76
+ }
77
+ if (req.method === 'POST' && P === '/dispatcher/control') {
78
+ return ctx.json(res, 200, await service.executor.kill(orgId, await ctx.body(req), actor));
79
+ }
80
+ if (req.method === 'GET' && P === '/dispatcher/policy') {
81
+ const result = await service.store.locked(orgId, async client => {
82
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
83
+ return (await client.query(`SELECT p.row FROM dispatcher_policies p JOIN dispatcher_authority_state s
84
+ ON s.org_id=p.org_id AND s.policy_version=p.version WHERE p.org_id=$1`, [orgId])).rows[0]?.row || null;
85
+ });
86
+ return ctx.json(res, 200, { schemaVersion: 1, policy: result });
87
+ }
88
+ const topUp = /^\/dispatch\/([^/]+)\/top-up$/.exec(P);
89
+ const decide = /^\/dispatch\/([^/]+)\/top-ups\/([^/]+)\/decision$/.exec(P);
90
+ if (topUp || decide) {
91
+ const id = decodeURIComponent((topUp || decide)[1]);
92
+ const attempt = await service.store.attempt(orgId, id);
93
+ if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
94
+ if (topUp && req.method === 'GET') {
95
+ const asks = await read(attempt.project, async client => (await client.query(
96
+ 'SELECT row FROM dispatcher_budget_asks WHERE org_id=$1 AND attempt_id=$2 ORDER BY expires_at_ms DESC', [orgId, id])).rows.map(r => r.row));
97
+ return ctx.json(res, 200, { schemaVersion: 1, asks });
98
+ }
99
+ if (decide && req.method === 'POST') {
100
+ const result = await service.finance.topUp(orgId, id, decodeURIComponent(decide[2]), await ctx.body(req), actor);
101
+ return ctx.json(res, result.replayed ? 200 : result.state === 'cancelled' ? 200 : 202, { schemaVersion: 1, ...result });
102
+ }
103
+ }
104
+ const repair = /^\/dispatcher\/account-bindings\/([^/]+)\/repairs$/.exec(P);
105
+ if (repair && req.method === 'POST') {
106
+ const result = await service.finance.repairBinding(orgId, decodeURIComponent(repair[1]), await ctx.body(req), actor);
107
+ return ctx.json(res, result.state === 'applied' || result.replayed ? 200 : 202, { schemaVersion: 1, ...result });
108
+ }
109
+ const repairRead = /^\/dispatcher\/account-binding-repairs\/([^/]+)$/.exec(P);
110
+ if (repairRead && req.method === 'GET') {
111
+ const row = await service.store.locked(orgId, async client => {
112
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
113
+ return (await client.query('SELECT row FROM dispatcher_account_binding_repairs WHERE org_id=$1 AND id=$2',
114
+ [orgId, decodeURIComponent(repairRead[1])])).rows[0]?.row;
115
+ });
116
+ if (!row) reject('repair_missing', 404);
117
+ return ctx.json(res, 200, { schemaVersion: 1, repair: row });
118
+ }
119
+ return false;
120
+ } catch (error) {
121
+ const status = error instanceof z.ZodError || error instanceof URIError ? 422 : error.status || 503;
122
+ const code = status === 422 ? 'schema_invalid' : error.code || 'dispatch_unavailable';
123
+ return ctx.json(res, status, { schemaVersion: 1, code,
124
+ reasons: [{ code, resource: null, retryAtMs: null }], retryable: status === 429 || status === 503 });
125
+ }
126
+ }
127
+
128
+ export function dispatcherUnavailable({ req, res, P, q, ctx }) {
129
+ if (!dispatcherEndpoint(req.method, P, q)) return false;
130
+ if (ctx.AUTH_MODE !== 'off' && ctx.dispatcher) return false;
131
+ const code = 'dispatch_unavailable';
132
+ return ctx.json(res, 503, { schemaVersion: 1, code,
133
+ reasons: [{ code, resource: null, retryAtMs: null }], retryable: true });
134
+ }