trantor 0.18.149 → 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.
@@ -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.149"
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.149",
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.149",
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})` : ""}`);
@@ -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) }
@@ -687,7 +687,7 @@ async function registerStatus(status, extra = {}) {
687
687
  }
688
688
  const url = HUB + "/register";
689
689
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
690
- if (MACHINE_LABEL) payload.machine = MACHINE_LABEL;
690
+ payload.machine = MACHINE_LABEL || hostId().toLowerCase();
691
691
  const body = JSON.stringify(payload);
692
692
  try {
693
693
  const opts = { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body };
@@ -1051,9 +1051,10 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
1051
1051
  } : undefined;
1052
1052
  const presencePayload = { session: SESSION, project: PROJ, status: `working · ${trigger}`, persona: PERSONA,
1053
1053
  agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
1054
- if (MACHINE_LABEL) presencePayload.machine = MACHINE_LABEL;
1054
+ presencePayload.machine = MACHINE_LABEL || hostId().toLowerCase();
1055
1055
  writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
1056
- 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 } }));
1057
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,
1058
1059
  // #7752: the stall marker only exists when a box does — with no box there is no sweep to
1059
1060
  // end the turn, so the watchdog stays report-only (reporting is the whole job, boxless).
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}`);
@@ -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
@@ -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 || "";
@@ -18,6 +18,15 @@ export async function routeDispatcherOperations({ req, res, P, q, auth, ctx }) {
18
18
  const orgId = service.orgId(auth);
19
19
  if (!orgId) reject('permission_denied', 403);
20
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
+ }
21
30
  if (req.method === 'POST' && P === '/dispatcher/verifiers') {
22
31
  return ctx.json(res, 200, await service.verifier.registerGrant(orgId, await ctx.body(req), actor));
23
32
  }
@@ -59,6 +68,9 @@ export async function routeDispatcherOperations({ req, res, P, q, auth, ctx }) {
59
68
  if (req.method === 'POST' && P === '/dispatcher/collectors') {
60
69
  return ctx.json(res, 200, await service.registerCollector(orgId, await ctx.body(req), actor));
61
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
+ }
62
74
  if (req.method === 'POST' && P === '/dispatcher/policy/activate') {
63
75
  return ctx.json(res, 200, await service.activatePolicy(orgId, await ctx.body(req), actor));
64
76
  }
@@ -0,0 +1,35 @@
1
+ import { z } from "zod";
2
+ import { gitPolicy, gitPolicyUpdate, refreshLocalGitPolicy } from "../../lib/git-guard.mjs";
3
+
4
+ const projectName = z.string().min(1).max(80).regex(/^[A-Za-z0-9_.-]+$/)
5
+ .refine(s => !["__proto__", "constructor", "prototype"].includes(s));
6
+
7
+ export async function routeGitPolicy({ req, res, P, auth, ctx }) {
8
+ const match = /^\/projects\/([^/]+)\/git-policy$/.exec(P);
9
+ if (!match || !["GET", "PUT"].includes(req.method)) return false;
10
+ let decoded;
11
+ try { decoded = decodeURIComponent(match[1]); }
12
+ catch { return ctx.json(res, 400, { error: "invalid project" }); }
13
+ const parsedProject = projectName.safeParse(ctx.canon(decoded));
14
+ if (!parsedProject.success) return ctx.json(res, 400, { error: "invalid project" });
15
+ const project = parsedProject.data;
16
+ const role = req.method === "PUT" ? "owner" : "read";
17
+ if (!auth?.ok || !ctx.scopeAllows(auth.identity, project, role)) {
18
+ return ctx.json(res, 403, { error: `project ${role} permission required` });
19
+ }
20
+ if (req.method === "GET") {
21
+ const policy = gitPolicy(ctx.state.projectMeta[project]?.gitPolicy);
22
+ refreshLocalGitPolicy(project, policy);
23
+ return ctx.json(res, 200, policy);
24
+ }
25
+ const input = gitPolicyUpdate.safeParse(await ctx.body(req));
26
+ if (!input.success) return ctx.json(res, 400, { error: "invalid git policy", issues: input.error.issues });
27
+ const meta = ctx.state.projectMeta[project] ?? {};
28
+ const previous = gitPolicy(meta.gitPolicy);
29
+ if (input.data.revision !== previous.revision) return ctx.json(res, 409, { error: "stale git policy", policy: previous });
30
+ const next = { ...input.data, revision: previous.revision + 1, updatedBy: auth.identity.pubkey, updatedAtMs: Date.now() };
31
+ refreshLocalGitPolicy(project, gitPolicy(next));
32
+ ctx.state.projectMeta[project] = { ...meta, gitPolicy: next };
33
+ ctx.markDirty();
34
+ return ctx.json(res, 200, gitPolicy(next));
35
+ }
@@ -0,0 +1,14 @@
1
+ import { accessSync, constants } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ // Run before dispatcher imports read these files, including during restart preflight.
5
+ for (const name of ['dispatcher-policy.json', 'model-catalog.json']) {
6
+ const path = fileURLToPath(new URL(`../configs/${name}`, import.meta.url));
7
+ try {
8
+ accessSync(path, constants.R_OK);
9
+ } catch (error) {
10
+ if (error.code !== 'ENOENT') throw error;
11
+ process.stderr.write(`[trantor] hub startup failed: missing ${path}; restore configs/ from the same Trantor release alongside hub.mjs (or reinstall the npm package).\n`);
12
+ process.exit(1);
13
+ }
14
+ }
package/hub/store.mjs CHANGED
@@ -5,6 +5,11 @@ import { dirname, join } from "node:path";
5
5
  import { createPersistHealth } from "../lib/persist-health.mjs";
6
6
  import { DEFAULT_ORG } from "../lib/store-contract.mjs";
7
7
  import { createDispatcherOperations } from "../lib/dispatcher/operations.mjs";
8
+ import { machineHealthRows } from "../lib/capacity-machines.mjs";
9
+ import { seatsView } from "../lib/capacity.mjs";
10
+ import { discoverModels, CACHE_TTL_MS } from "../lib/discovery/index.mjs";
11
+ import { readConfig } from "../lib/project.mjs";
12
+ import { loadWorld } from "../bin/advise.mjs";
8
13
 
9
14
  export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics = null }) {
10
15
  function emptyState() {
@@ -437,13 +442,37 @@ setInterval(persist, persistTickMs).unref?.();
437
442
  let dispatcher = null;
438
443
  if (durableStore) {
439
444
  const migrated = (await durableStore.pool.query("SELECT to_regclass('dispatcher_integration_migrations') AS name")).rows[0]?.name;
440
- if (migrated) dispatcher = createDispatcherOperations({ durableStore, orgId: ORG_ID, source: HUB_SRC });
445
+ if (migrated) {
446
+ let discovery = null;
447
+ let discoveryAt = 0;
448
+ const evidenceSources = {
449
+ balances: () => Object.keys(state.balancesByMachine).length
450
+ ? Object.entries(state.balancesByMachine).map(([machine, snapshot]) => ({ ...snapshot, machine }))
451
+ : [state.balances],
452
+ machines: () => machineHealthRows(Date.now()),
453
+ seats: () => {
454
+ const nowMs = Date.now();
455
+ return seatsView({ peers: state.peers, messages: state.messages, nowMs,
456
+ onlineMs: Number(process.env.RELAY_ONLINE_MS || 5 * 60 * 1000),
457
+ lastRows: turnTelemetry.readRows({ since: nowMs - 7 * 86400e3 }) });
458
+ },
459
+ discovery: () => {
460
+ if (!discovery || Date.now() - discoveryAt >= CACHE_TTL_MS) {
461
+ discoveryAt = Date.now();
462
+ discovery = discoverModels(loadWorld().roster).catch(error => { discovery = null; throw error; });
463
+ }
464
+ return discovery;
465
+ },
466
+ };
467
+ dispatcher = createDispatcherOperations({ durableStore, orgId: ORG_ID, source: HUB_SRC, evidenceSources,
468
+ dispatcherBridgeGrant: process.env.RELAY_DISPATCHER_BRIDGE_GRANT || readConfig().dispatcherBridgeGrant || null });
469
+ }
441
470
  }
442
471
  return {
443
472
  dispatcher,
444
473
  async mutateDispatcherCard(input, auth) {
445
474
  if (!dispatcher) return null;
446
- const managed = (await durableStore.pool.query('SELECT card FROM dispatcher_cards WHERE org_id=$1 AND card=$2', [ORG_ID, input.id])).rows[0];
475
+ const managed = (await durableStore.pool.query("SELECT card FROM dispatcher_cards WHERE org_id=$1 AND card=$2 AND row->>'depsBasis' IS DISTINCT FROM 'board'", [ORG_ID, input.id])).rows[0];
447
476
  if (!managed) return null;
448
477
  if (!auth?.pubkey || !auth.identity || auth.warning) throw Object.assign(new Error('permission_denied'), { status: 403, code: 'permission_denied' });
449
478
  const task = await dispatcher.mutateCard(ORG_ID, input, { pubkey: auth.pubkey });
package/hub.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import "./hub/startup-config.mjs";
2
3
  import http from "node:http";
3
4
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
4
5
  import { homedir } from "node:os";
@@ -18,6 +19,7 @@ import { routeAdmin } from "./hub/routes/admin.mjs";
18
19
  import { routeCards } from "./hub/routes/cards.mjs";
19
20
  import { routeInsights } from "./hub/routes/insights.mjs";
20
21
  import { routeMessages } from "./hub/routes/messages.mjs";
22
+ import { routeGitPolicy } from "./hub/routes/git-policy.mjs";
21
23
  import { routeReviews } from "./hub/routes/reviews.mjs";
22
24
  import { migrateReviews } from "./hub/review-store.mjs";
23
25
  import { routeDevices } from "./hub/routes/devices.mjs";
@@ -155,7 +157,7 @@ const sessionChat = createSessionRuntime({
155
157
  appendEvent: events.appendEvent, pushEventToStreams: events.pushEventToStreams, notifier,
156
158
  attachmentsDir: join(DATA_DIR, "attachments"),
157
159
  });
158
- const routes = [routeDispatcher, routeDispatcherOperations, routeWorktreeStatus, routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
160
+ const routes = [routeGitPolicy, routeDispatcher, routeDispatcherOperations, routeWorktreeStatus, routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
159
161
 
160
162
  const publicAuth = createAuthRuntime({
161
163
  state: store.state, markDirty: store.markDirty, AUTH_MODE: "enforce", SUPERSEDE_GRACE_MS,
@@ -177,7 +179,7 @@ function requestHandler(runtime, ctx, gate = null) {
177
179
  if (dispatcherUnavailable({ req, res, P, q, ctx })) return;
178
180
  const cap = gate ? runtime.bodyCap(P) : runtime.ownerBodyCap(req, P);
179
181
  let ownerAuth;
180
- if (req.method === "POST") {
182
+ if (req.method === "POST" || req.method === "PUT") {
181
183
  const raw = await runtime.rawBody(req, cap);
182
184
  if (raw === undefined) return runtime.json(res, 413, { error: `request body over the ${cap} byte cap` });
183
185
  if (req._bodyBytes > runtime.bodyCap(P)) {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.149",
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). This manifest makes Kimi Code CLI a first-class ORCHESTRATOR, mirroring .claude-plugin/plugin.json. Hooks are the CANONICAL hooks/** executed through the kimi dialect bridge (kimi/bridge.mjs) — docs/KIMI-BRIDGE-CONTRACT.md.",
5
5
  "interface": {
6
6
  "displayName": "Trantor",
@@ -143,6 +143,8 @@ export function defaultContext({ busDir, hub, knownProjects, checkoutFor, appRea
143
143
  const read = (p) => { try { return readFileSync(p, "utf8"); } catch { return null; } };
144
144
  return {
145
145
  home: env.HOME || homedir(),
146
+ root: ROOT,
147
+ node: process.execPath,
146
148
  busDir,
147
149
  hub,
148
150
  now,
@@ -184,6 +184,66 @@ export async function launchers(ctx) {
184
184
  return pass(`${plists.length} launch agent(s), every program path exists`);
185
185
  }
186
186
 
187
+ // #14682: the dispatcher runbook may only name commands and routes the installed tree serves, so a
188
+ // renamed route or dropped subcommand fails the canary instead of leaving the operator a dead step.
189
+ const RUNBOOK = join("docs", "RUNBOOK-dispatcher.md");
190
+ const DISPATCHER_ROUTES = [join("hub", "routes", "dispatcher-operations.mjs"), join("hub", "routes", "dispatcher.mjs")];
191
+
192
+ export function runbookReferences(markdown) {
193
+ const commands = new Set();
194
+ const routes = new Set();
195
+ const scripts = new Set();
196
+ for (const [, span] of markdown.matchAll(/`([^`\n]+)`/g)) {
197
+ const command = /^trantor ([a-z][a-z-]*)/.exec(span);
198
+ if (command) commands.add(command[1]);
199
+ const route = /^(?:(?:GET|POST) )?(\/dispatch(?:er)?\/[a-z/-]*[a-z])(?:[?*].*)?$/.exec(span);
200
+ if (route && !route[1].includes("<")) routes.add(route[1]);
201
+ const script = /^(?:node )?(bin\/[a-z-]+\.mjs)/.exec(span);
202
+ if (script) scripts.add(script[1]);
203
+ }
204
+ return { commands: [...commands], routes: [...routes], scripts: [...scripts] };
205
+ }
206
+
207
+ export async function dispatcherRunbook(ctx) {
208
+ const markdown = ctx.readText(join(ctx.root, RUNBOOK));
209
+ if (markdown == null) return skip("the dispatcher runbook ships with the repo checkout, not the npm package");
210
+ const cli = ctx.readText(join(ctx.root, "bin", "cli.mjs")) || "";
211
+ const routeSource = DISPATCHER_ROUTES.map((p) => ctx.readText(join(ctx.root, p)) || "").join("\n");
212
+ const { commands, routes, scripts } = runbookReferences(markdown);
213
+ const missing = [
214
+ ...commands.filter((c) => !cli.includes(`case "${c}"`)).map((c) => `trantor ${c}`),
215
+ ...routes.filter((r) => !routeSource.includes(`'${r}'`)).map((r) => `route ${r}`),
216
+ ...scripts.filter((s) => !ctx.exists(join(ctx.root, s))),
217
+ ];
218
+ if (missing.length) return fail(`the runbook names what this tree does not serve: ${missing.join(", ")}`);
219
+ return pass(`${commands.length} command(s), ${routes.length} route(s) and ${scripts.length} script(s) in the runbook all exist`);
220
+ }
221
+
222
+ // #14682: the planner's view fails closed. A reachable hub plans under a named policy; anything else
223
+ // is local-only with a named cause and no dispatch token, never a default that reads as a plan.
224
+ export async function dispatcherFailClosed(ctx) {
225
+ let out;
226
+ try { out = ctx.exec(ctx.node, [join(ctx.root, "bin", "capacity.mjs"), "--version", "1", "--json"]); } catch (error) {
227
+ // A refusal exits 1 with its JSON on stdout; only a run with no output is a broken command.
228
+ if (!error.stdout) return fail(`trantor capacity --version 1 --json did not answer: ${error.message.split("\n")[0]}`);
229
+ out = String(error.stdout);
230
+ }
231
+ let view;
232
+ try { view = JSON.parse(out); } catch { return fail("trantor capacity --version 1 --json printed something that is not JSON"); }
233
+ if (view?.refused) return view.code ? pass(`the hub refused (${view.code}) and nothing was planned`) : fail("the hub refused the planning view without a code");
234
+ if (view?.versioned === false && view.localOnly === false) return pass(`the hub has no planning view yet (${view.code || "display ledger only"}), nothing planned`);
235
+ if (view?.localOnly === false) {
236
+ if (!view.snapshotId || !view.policyVersion) return fail("the hub answered a planning view with no snapshot id or policy version");
237
+ return pass(`hub plans under ${view.policyVersion} (snapshot ${String(view.snapshotId).slice(0, 14)})`);
238
+ }
239
+ if (view?.localOnly === true) {
240
+ if (!view.reason) return fail("local-only capacity names no cause");
241
+ if (view.dispatchToken) return fail(`local-only capacity (${view.reason}) still carries a dispatch token`);
242
+ return pass(`local-only (${view.reason}), no dispatch token: fails closed`);
243
+ }
244
+ return fail("trantor capacity --version 1 --json answered neither a planning view nor a named local-only cause");
245
+ }
246
+
187
247
  export const PROBES = {
188
248
  "duty-turns": dutyTurns,
189
249
  "wake-nudge": wakeNudge,
@@ -194,4 +254,6 @@ export const PROBES = {
194
254
  "workspace-layouts": workspaceLayouts,
195
255
  "file-actions-no-commit": fileActionsNoCommit,
196
256
  launchers,
257
+ "dispatcher-runbook": dispatcherRunbook,
258
+ "dispatcher-fail-closed": dispatcherFailClosed,
197
259
  };
@@ -273,6 +273,7 @@ export function createAdmission({ store, readAuthority, readReplacement, clock =
273
273
  const assignment = decision.assignments.find(a => a.project === request.project && a.card === request.card);
274
274
  if (!assignment?.candidate || assignment.cardRevision !== request.cardRevision) reject('decision_stale');
275
275
  const authority = AdmissionAuthoritySchema.parse(await readAuthority(client, { orgId, request, actor, nowMs }));
276
+ if (authority.card.depsBasis === 'board') reject('board_projection_only');
276
277
  checkAuthority(authority, request, snapshot, decision);
277
278
  const candidate = assignment.candidate;
278
279
  let parent = null, handoff = null;