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
@@ -1,6 +1,6 @@
1
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';
2
+ import { WorkCardSchema, UsageEventSchema, ArtifactSchema, SnapshotSchema, PolicySchema, MAX_ADVISE_CARDS } from '../../lib/dispatcher/schemas.mjs';
3
+ import { DispatchRequestSchema, reject, storedScopeAllows } from '../../lib/dispatcher/admission.mjs';
4
4
  import { canonicalJson, verifySnapshot } from '../../lib/dispatcher/snapshot.mjs';
5
5
  import { verifyPolicy } from '../../lib/dispatcher/policy.mjs';
6
6
  import { plan } from '../../lib/dispatcher/planner.mjs';
@@ -8,8 +8,8 @@ import { plan } from '../../lib/dispatcher/planner.mjs';
8
8
  const text = z.string().min(1).max(8192);
9
9
  const positive = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
10
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() });
11
+ snapshotId: text.optional(), policyVersion: text.optional(), cards: z.array(WorkCardSchema).max(MAX_ADVISE_CARDS),
12
+ drafts: z.array(WorkCardSchema).max(MAX_ADVISE_CARDS).optional() }).refine(r => r.cards.length + (r.drafts?.length || 0) <= MAX_ADVISE_CARDS);
13
13
  export const AdviceAuthoritySchema = z.strictObject({ snapshot: SnapshotSchema, policy: PolicySchema });
14
14
  export const AttemptEventSchema = z.discriminatedUnion('kind', [
15
15
  z.strictObject({ kind: z.literal('usage'), event: UsageEventSchema }),
@@ -19,15 +19,17 @@ export const AttemptEventSchema = z.discriminatedUnion('kind', [
19
19
 
20
20
  async function readable(client, orgId, actor, project) {
21
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);
22
+ if (!row || row.revoked_at != null || !storedScopeAllows(row, project, ['read','write','approver','owner'])) {
23
+ reject('permission_denied', 403);
24
+ }
25
+ return row;
24
26
  }
25
27
 
26
28
  async function advise(service, orgId, input, actor, auth) {
27
29
  const request = AdviceRequestSchema.parse(input);
28
30
  if ([...request.cards, ...request.drafts || []].some(c => c.project !== request.project)) reject('permission_denied', 403);
29
31
  return service.store.locked(orgId, async client => {
30
- await readable(client, orgId, actor, request.project);
32
+ const identity = await readable(client, orgId, actor, request.project);
31
33
  const authority = AdviceAuthoritySchema.parse(await service.readAdvice(client, { orgId, request, actor }));
32
34
  let snapshot;
33
35
  try { snapshot = verifySnapshot(authority.snapshot); verifyPolicy(authority.policy); } catch { reject('snapshot_invalid'); }
@@ -37,12 +39,15 @@ async function advise(service, orgId, input, actor, auth) {
37
39
  const stored = snapshot.readyQueue.find(c => c.project === card.project && c.card === card.card);
38
40
  if (!stored || canonicalJson(stored) !== canonicalJson(card)) reject('card_stale');
39
41
  }
40
- const decision = plan({ ...authority, cards: [...request.cards, ...request.drafts || []] });
42
+ const cards = [...request.cards, ...request.drafts || []].sort((a,b) => a.project < b.project ? -1 : a.project > b.project ? 1 : a.card - b.card);
43
+ if (new Set(cards.map(c => `${c.project}:${c.card}`)).size !== cards.length
44
+ || request.drafts?.some(c => snapshot.readyQueue.some(s => s.project === c.project && s.card === c.card))) reject('schema_invalid', 422);
45
+ const decision = plan({ ...authority, cards });
41
46
  const dispatchable = !request.drafts?.length;
42
47
  if (dispatchable) await client.query(`INSERT INTO dispatcher_decisions VALUES($1,$2,$3,$4,$5,$6,$7)
43
48
  ON CONFLICT(org_id,id) DO NOTHING`, [orgId, decision.id, request.project, decision.snapshotId,
44
49
  decision.policyVersion, decision.createdAtMs, decision]);
45
- return { schemaVersion: 1, dispatchable, decision: service.projectDecision(decision, auth) };
50
+ return { schemaVersion: 1, dispatchable, decision: service.projectDecision(decision, { ...auth, identity }) };
46
51
  });
47
52
  }
48
53
 
@@ -61,6 +66,10 @@ export async function routeDispatcher({ req, res, q: _q, P, auth, ctx }) {
61
66
  if (advice) return ctx.json(res, 200, await advise(service, orgId, await ctx.body(req), actor, auth));
62
67
  if (dispatch) {
63
68
  const input = DispatchRequestSchema.parse(await ctx.body(req));
69
+ if (ctx.crossProjectGuard) {
70
+ const cross = ctx.crossProjectGuard(auth, '/dispatch', input);
71
+ if (!cross.ok) reject('permission_denied', 403);
72
+ }
64
73
  const result = await service.admission.dispatch(orgId, input, actor);
65
74
  return ctx.json(res, result.replayed ? 200 : 202, result);
66
75
  }
@@ -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
@@ -4,6 +4,12 @@ import { randomBytes } from "node:crypto";
4
4
  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
+ 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";
7
13
 
8
14
  export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics = null }) {
9
15
  function emptyState() {
@@ -351,6 +357,7 @@ const HUB_SRC = `hub-${process.pid}-${randomBytes(4).toString("hex")}`;
351
357
  if (runTaskBootMigrations()) dirty = true;
352
358
  let lastPersisted = durableStore ? snapshotState() : null;
353
359
  const recordPersistFailure = (kind, error) => {
360
+ dispatcher?.store.closeAdmission();
354
361
  dirty = true;
355
362
  const failure = persistHealth.failed(error);
356
363
  if (failure.shouldLog) {
@@ -432,7 +439,49 @@ setInterval(persist, persistTickMs).unref?.();
432
439
  }).catch(error => process.stderr.write(`[trantor] LISTEN ${error.message || error} — external writes will NOT surface until restart\n`));
433
440
  };
434
441
 
442
+ let dispatcher = null;
443
+ if (durableStore) {
444
+ const migrated = (await durableStore.pool.query("SELECT to_regclass('dispatcher_integration_migrations') AS name")).rows[0]?.name;
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
+ }
470
+ }
435
471
  return {
472
+ dispatcher,
473
+ async mutateDispatcherCard(input, auth) {
474
+ if (!dispatcher) return null;
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];
476
+ if (!managed) return null;
477
+ if (!auth?.pubkey || !auth.identity || auth.warning) throw Object.assign(new Error('permission_denied'), { status: 403, code: 'permission_denied' });
478
+ const task = await dispatcher.mutateCard(ORG_ID, input, { pubkey: auth.pubkey });
479
+ const at = state.tasks.findIndex(t => t.id === task.id);
480
+ if (at !== -1) state.tasks[at] = task;
481
+ const previous = lastPersisted.tasks.findIndex(t => t.id === task.id);
482
+ if (previous !== -1) lastPersisted.tasks[previous] = task;
483
+ return task;
484
+ },
436
485
  state, durableStore, persist, persistHealth, markDirty, copyTask, copyMessage, reload, startChangeSubscription,
437
486
  turnTelemetry, HUB_SRC, appendTaskLog, appendTaskNote, cleanChecklist, cleanDrill, hasDrillLine, stripNulText,
438
487
  };
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,11 +19,14 @@ 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";
24
26
  import { createSessionRuntime } from "./hub/routes/session.mjs";
25
27
  import { routeWorktreeStatus } from "./hub/routes/worktree-status.mjs";
28
+ import { routeDispatcher } from "./hub/routes/dispatcher.mjs";
29
+ import { dispatcherUnavailable, routeDispatcherOperations } from "./hub/routes/dispatcher-operations.mjs";
26
30
  import { routeCapacity } from "./hub/routes/capacity.mjs"; // #14653: registered ahead of sessionChat so the /machines/health mirror runs first
27
31
  import { createNotifier } from "./hub/notifier.mjs";
28
32
  import { createHubDiagnostics } from "./lib/hub-diagnostics.mjs";
@@ -136,12 +140,24 @@ const context = {
136
140
  hubSend: duty.hubSend, assertNoSecrets, AUTH_MODE, ONLINE_MS, PEER_TTL_MS,
137
141
  REAP_GRACE_MS, CONTRACT_WINDOW_MS, PUBLIC_URL,
138
142
  };
143
+ if (store.dispatcher && AUTH_MODE !== 'off') {
144
+ let ticking = false;
145
+ setInterval(async () => {
146
+ if (ticking) return;
147
+ ticking = true;
148
+ try { await store.dispatcher.tick(); }
149
+ catch (error) {
150
+ store.dispatcher.store.closeAdmission();
151
+ console.error(`[trantor] dispatcher unavailable: ${error.code || 'store_failure'}`);
152
+ } finally { ticking = false; }
153
+ }, 1000).unref();
154
+ }
139
155
  const sessionChat = createSessionRuntime({
140
156
  state: store.state, markDirty: store.markDirty,
141
157
  appendEvent: events.appendEvent, pushEventToStreams: events.pushEventToStreams, notifier,
142
158
  attachmentsDir: join(DATA_DIR, "attachments"),
143
159
  });
144
- const routes = [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];
145
161
 
146
162
  const publicAuth = createAuthRuntime({
147
163
  state: store.state, markDirty: store.markDirty, AUTH_MODE: "enforce", SUPERSEDE_GRACE_MS,
@@ -160,9 +176,10 @@ function requestHandler(runtime, ctx, gate = null) {
160
176
  const q = Object.fromEntries(u.searchParams);
161
177
  const P = u.pathname;
162
178
  if (gate && !gate.admit(req, res, P)) return;
179
+ if (dispatcherUnavailable({ req, res, P, q, ctx })) return;
163
180
  const cap = gate ? runtime.bodyCap(P) : runtime.ownerBodyCap(req, P);
164
181
  let ownerAuth;
165
- if (req.method === "POST") {
182
+ if (req.method === "POST" || req.method === "PUT") {
166
183
  const raw = await runtime.rawBody(req, cap);
167
184
  if (raw === undefined) return runtime.json(res, 413, { error: `request body over the ${cap} byte cap` });
168
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.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). 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
  };
@@ -60,15 +60,27 @@ export function reject(code, status = 409, resource = null, retryAtMs = null) {
60
60
  throw error;
61
61
  }
62
62
 
63
+ const RoleSchema = z.enum(['read', 'write', 'approver', 'owner']);
64
+ const StoredScopesSchema = z.union([z.array(z.strictObject({ project: text, role: RoleSchema })),
65
+ z.record(text, RoleSchema)]);
66
+
67
+ export function storedScopeAllows(identity, project, roles, wildcardOnly = false) {
68
+ const parsed = StoredScopesSchema.safeParse(identity?.scopes);
69
+ if (!parsed.success) return false;
70
+ const scopes = Array.isArray(parsed.data) ? parsed.data
71
+ : Object.entries(parsed.data).map(([project, role]) => ({ project, role }));
72
+ return scopes.some(scope => roles.includes(scope.role)
73
+ && (scope.project === '*' || !wildcardOnly && scope.project === project));
74
+ }
75
+
63
76
  export async function requireIdentity(client, orgId, actor, project, financial = false, producers = []) {
64
77
  const identity = (await client.query('SELECT * FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
65
78
  if (!identity || identity.revoked_at != null) reject('permission_denied', 403);
66
79
  if (financial) {
67
- if (identity.kind !== 'human' || identity.scopes['*'] !== 'owner' || producers.includes(identity.pubkey)) {
80
+ if (identity.kind !== 'human' || !storedScopeAllows(identity, project, ['owner'], true) || producers.includes(identity.pubkey)) {
68
81
  reject('permission_denied', 403);
69
82
  }
70
- } else if (!['write', 'approver', 'owner'].includes(identity.scopes[project])
71
- && !['write', 'approver', 'owner'].includes(identity.scopes['*'])) reject('permission_denied', 403);
83
+ } else if (!storedScopeAllows(identity, project, ['write', 'approver', 'owner'])) reject('permission_denied', 403);
72
84
  return identity;
73
85
  }
74
86
 
@@ -261,6 +273,7 @@ export function createAdmission({ store, readAuthority, readReplacement, clock =
261
273
  const assignment = decision.assignments.find(a => a.project === request.project && a.card === request.card);
262
274
  if (!assignment?.candidate || assignment.cardRevision !== request.cardRevision) reject('decision_stale');
263
275
  const authority = AdmissionAuthoritySchema.parse(await readAuthority(client, { orgId, request, actor, nowMs }));
276
+ if (authority.card.depsBasis === 'board') reject('board_projection_only');
264
277
  checkAuthority(authority, request, snapshot, decision);
265
278
  const candidate = assignment.candidate;
266
279
  let parent = null, handoff = null;
@@ -0,0 +1,82 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { WorkCardSchema } from './schemas.mjs';
4
+ import { canonicalHash } from './snapshot.mjs';
5
+ import { loadRegistry, registryHash } from '../canary/registry.mjs';
6
+
7
+ function currentRegistryHash() {
8
+ try { return registryHash(loadRegistry()); }
9
+ catch (error) {
10
+ if (error.code === 'ENOENT') return 'unregistered';
11
+ throw error;
12
+ }
13
+ }
14
+
15
+ function closedAt(task) {
16
+ const closed = (task.history || []).filter(entry => entry.to === 'done').at(-1);
17
+ return closed?.ts ?? null;
18
+ }
19
+
20
+ function projectCard(task, tasks, featureRegistryHash) {
21
+ const parsedDrill = z.string().min(1).refine(value => value.trim().length > 0).safeParse(task.extra?.drill);
22
+ if (task.status !== 'todo' || !parsedDrill.success) return null;
23
+ const deps = (task.deps || []).map(id => tasks.get(Number(id)));
24
+ if (deps.some(dep => !dep || dep.project !== task.project || dep.status !== 'done')) return null;
25
+ const closeTimes = deps.map(closedAt);
26
+ if (closeTimes.some(time => time == null)) return null;
27
+ const drill = parsedDrill.data;
28
+ const row = {
29
+ project: task.project, card: Number(task.id), revision: 0,
30
+ kind: task.extra.kind || 'unknown', difficulty: task.difficulty,
31
+ subsystem: task.extra.subsystem || 'unknown', size: { easy: 's', medium: 'm', hard: 'l' }[task.difficulty],
32
+ deps: deps.map(dep => ({ project: dep.project, card: Number(dep.id) })), depsBasis: 'board',
33
+ resources: [], needs: [], features: [], effectClass: 'workspace', artifactKind: 'commit',
34
+ drillSpecId: `board:${task.project}#${task.id}:${createHash('sha256').update(drill).digest('hex').slice(0, 16)}`,
35
+ featureRegistryHash, drill, readySinceMs: deps.length ? Math.max(...closeTimes) : Number(task.created), pin: null,
36
+ };
37
+ const parsed = WorkCardSchema.safeParse(row);
38
+ return parsed.success ? parsed.data : null;
39
+ }
40
+
41
+ export async function projectBoardCards(client, orgId, policy, { featureRegistryHash = currentRegistryHash() } = {}) {
42
+ const projects = Object.entries(policy.modeByProject).filter(([, mode]) => mode === 'shadow' || mode === 'admit').map(([project]) => project);
43
+ if (!projects.length) return 0;
44
+ const tasks = (await client.query('SELECT * FROM tasks WHERE org_id=$1 AND project=ANY($2::text[])', [orgId, projects])).rows;
45
+ const byId = new Map(tasks.map(task => [Number(task.id), task]));
46
+ const records = (await client.query('SELECT * FROM dispatcher_cards WHERE org_id=$1 AND project=ANY($2::text[])', [orgId, projects])).rows;
47
+ const existing = new Map(records.map(record => [Number(record.card), record]));
48
+ const revisions = (await client.query('SELECT * FROM dispatcher_board_revisions WHERE org_id=$1 AND project=ANY($2::text[])', [orgId, projects])).rows;
49
+ const prior = new Map(revisions.map(record => [Number(record.card), record]));
50
+ const retained = new Set();
51
+ let changed = 0;
52
+ for (const task of tasks) {
53
+ const id = Number(task.id);
54
+ const managed = existing.get(id);
55
+ if (managed && managed.row.depsBasis !== 'board') continue;
56
+ const card = projectCard(task, byId, featureRegistryHash);
57
+ if (!card) continue;
58
+ retained.add(id);
59
+ const contentHash = canonicalHash(card);
60
+ const previous = prior.get(id);
61
+ const revision = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).safeParse(task.extra?.revision);
62
+ const sourceRevision = Math.max(task.history?.length || 0, revision.success ? revision.data : 0);
63
+ card.revision = Math.max(sourceRevision, previous ? Number(previous.revision) + (previous.content_hash === contentHash ? 0 : 1) : 0);
64
+ if (managed && canonicalHash(managed.row) === canonicalHash(card)) continue;
65
+ await client.query(`INSERT INTO dispatcher_board_revisions VALUES($1,$2,$3,$4,$5)
66
+ ON CONFLICT(org_id,project,card) DO UPDATE SET revision=EXCLUDED.revision,content_hash=EXCLUDED.content_hash`,
67
+ [orgId, task.project, id, card.revision, contentHash]);
68
+ await client.query(`INSERT INTO dispatcher_cards VALUES($1,$2,$3,$4,'todo',$5,$6)
69
+ ON CONFLICT(org_id,project,card) DO UPDATE SET revision=EXCLUDED.revision,status='todo',ready_since_ms=EXCLUDED.ready_since_ms,row=EXCLUDED.row`,
70
+ [orgId, task.project, id, card.revision, card.readySinceMs, card]);
71
+ changed++;
72
+ }
73
+ for (const record of records) {
74
+ if (record.row.depsBasis !== 'board' || retained.has(Number(record.card))) continue;
75
+ await client.query('DELETE FROM dispatcher_cards WHERE org_id=$1 AND project=$2 AND card=$3', [orgId, record.project, record.card]);
76
+ await client.query(`UPDATE dispatcher_board_revisions SET revision=revision+1,content_hash='removed'
77
+ WHERE org_id=$1 AND project=$2 AND card=$3`, [orgId, record.project, record.card]);
78
+ changed++;
79
+ }
80
+ if (changed) await client.query('UPDATE dispatcher_authority_state SET revision=revision+1 WHERE org_id=$1', [orgId]);
81
+ return changed;
82
+ }