trantor 0.18.149 → 0.18.153

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 (42) 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/balances-agent.mjs +112 -0
  5. package/bin/balances.mjs +13 -11
  6. package/bin/cli.mjs +1 -1
  7. package/bin/connect.mjs +10 -1
  8. package/bin/crew-runner.mjs +27 -12
  9. package/bin/integrate.mjs +38 -9
  10. package/bin/turn-watchdog.mjs +15 -1
  11. package/bin/wake-nudge.mjs +5 -2
  12. package/deploy/restart-hub.sh +2 -0
  13. package/docs/FEATURES.md +4 -1
  14. package/hooks/sessionstart.mjs +6 -1
  15. package/hub/auth.mjs +5 -0
  16. package/hub/routes/admin.mjs +9 -1
  17. package/hub/routes/dispatcher-operations.mjs +12 -0
  18. package/hub/routes/git-policy.mjs +35 -0
  19. package/hub/startup-config.mjs +14 -0
  20. package/hub/store.mjs +32 -2
  21. package/hub.mjs +4 -2
  22. package/kimi.plugin.json +1 -1
  23. package/lib/balance-publish.mjs +22 -0
  24. package/lib/balances.mjs +28 -6
  25. package/lib/canary/canary.mjs +2 -0
  26. package/lib/canary/probes.mjs +62 -0
  27. package/lib/dispatcher/accounts.mjs +91 -1
  28. package/lib/dispatcher/admission.mjs +1 -0
  29. package/lib/dispatcher/board-bridge.mjs +82 -0
  30. package/lib/dispatcher/evidence-bridge.mjs +293 -0
  31. package/lib/dispatcher/operations.mjs +147 -20
  32. package/lib/dispatcher/planner.mjs +4 -2
  33. package/lib/dispatcher/preflight.mjs +42 -7
  34. package/lib/dispatcher/rollout.mjs +357 -0
  35. package/lib/dispatcher/schemas.mjs +2 -0
  36. package/lib/dispatcher/snapshot.mjs +18 -9
  37. package/lib/dispatcher/store.mjs +15 -0
  38. package/lib/git-guard.mjs +210 -0
  39. package/lib/integrate.mjs +10 -2
  40. package/lib/store-contract.mjs +7 -1
  41. package/mcp.mjs +4 -5
  42. package/package.json +3 -3
@@ -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,38 @@ 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
+ .map(seat => ({ ...seat, accountIdentity: state.peers[seat.session]?.accountIdentity }));
459
+ },
460
+ discovery: () => {
461
+ if (!discovery || Date.now() - discoveryAt >= CACHE_TTL_MS) {
462
+ discoveryAt = Date.now();
463
+ discovery = discoverModels(loadWorld().roster).catch(error => { discovery = null; throw error; });
464
+ }
465
+ return discovery;
466
+ },
467
+ };
468
+ dispatcher = createDispatcherOperations({ durableStore, orgId: ORG_ID, source: HUB_SRC, evidenceSources,
469
+ dispatcherBridgeGrant: process.env.RELAY_DISPATCHER_BRIDGE_GRANT || readConfig().dispatcherBridgeGrant || null });
470
+ }
441
471
  }
442
472
  return {
443
473
  dispatcher,
444
474
  async mutateDispatcherCard(input, auth) {
445
475
  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];
476
+ 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
477
  if (!managed) return null;
448
478
  if (!auth?.pubkey || !auth.identity || auth.warning) throw Object.assign(new Error('permission_denied'), { status: 403, code: 'permission_denied' });
449
479
  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.153",
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",
@@ -0,0 +1,22 @@
1
+ import { signedPost } from "../hooks/lib/api.mjs";
2
+
3
+ export async function publishBalanceSnapshot(snapshot, { post = signedPost, required = false } = {}) {
4
+ const failures = [];
5
+ let accepted = false;
6
+ let projectAccepted = false;
7
+ for (const target of ["/balances", "http://127.0.0.1:4477/balances"]) {
8
+ try {
9
+ const result = await post(target, snapshot, { timeoutMs: 2500 });
10
+ if (result?.ok) {
11
+ accepted = true;
12
+ if (target === "/balances") projectAccepted = true;
13
+ continue;
14
+ }
15
+ failures.push(`${target}: hub ${result?.status ?? 0}`);
16
+ } catch (error) {
17
+ failures.push(`${target}: ${error.message}`);
18
+ }
19
+ }
20
+ if (required && !projectAccepted) throw new Error(`snapshot was not accepted by the project hub (${failures.join("; ")})`);
21
+ return accepted;
22
+ }
package/lib/balances.mjs CHANGED
@@ -5,6 +5,8 @@ import { readFileSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
 
8
+ import { readProviderIdentity } from "./dispatcher/accounts.mjs";
9
+
8
10
  const TIMEOUT = 8000;
9
11
 
10
12
  async function getJSON(url, key, extraHeaders = {}) {
@@ -113,12 +115,16 @@ export const ADAPTERS = [
113
115
  },
114
116
  {
115
117
  provider: "kimi", label: "Kimi Code", kind: "quota", match: ["kimi"], envKeys: ["KIMI_API_KEY"], keyless: true,
116
- async fetch(key, env = {}) {
118
+ async fetch(key, env = {}, options = {}) {
117
119
  // Prefer the explicit API key; OAuth is read-only and never refreshes Kimi's credentials.
118
120
  let oauthCredentials = null;
119
121
  if (!key) {
120
122
  try {
121
- oauthCredentials = JSON.parse(readFileSync(join(homedir(), ".kimi-code", "credentials", "kimi-code.json"), "utf8"));
123
+ for (const directory of [".kimi-code", ".kimi"]) {
124
+ try { oauthCredentials = JSON.parse(readFileSync(join(options.home ?? homedir(), directory, "credentials", "kimi-code.json"), "utf8")); }
125
+ catch { continue; }
126
+ if (oauthCredentials?.access_token) break;
127
+ }
122
128
  key = oauthCredentials?.access_token;
123
129
  } catch { /* absent or unreadable login is handled as no token below */ }
124
130
  }
@@ -255,26 +261,30 @@ async function claudeOAuthToken() {
255
261
  }
256
262
 
257
263
  export async function fetchBalances(env = process.env, opts = {}) {
264
+ const identities = new Map();
265
+ const identityFor = provider => readProviderIdentity({ provider, env, home: opts.home ?? homedir() });
258
266
  const only = Array.isArray(opts.only) ? new Set(opts.only.map((s) => String(s).toLowerCase())) : null;
259
267
  const jobs = ADAPTERS.map(async (a) => {
260
268
  const names = (a.match || [a.provider]).map((s) => s.toLowerCase());
261
269
  if (!only || !names.some((n) => only.has(n))) return null; // not a Trantor-configured provider → skip
262
270
  const envKey = a.envKeys.find((k) => env[k]);
263
271
  if (!envKey && !a.keyless) return null; // configured but no key in env → can't query
272
+ identities.set(a.provider, identityFor(a.provider));
264
273
  const base = { provider: a.provider, label: a.label, kind: a.kind, via: envKey || "oauth" };
265
274
  // `env` rides along for adapters that read more than a key (Qwen's base URL); the rest ignore it.
266
- try { return { ...base, ok: true, ...(await a.fetch(envKey ? env[envKey] : undefined, env)) }; }
275
+ try { return { ...base, ok: true, ...(await a.fetch(envKey ? env[envKey] : undefined, env, opts)) }; }
267
276
  catch (e) { return { ...base, ok: false, error: String(e?.message || e) }; }
268
277
  });
269
278
  const rows = (await Promise.all(jobs)).filter(Boolean);
270
279
  // Codex: no public balance API, so the CLI's own token reads the ChatGPT usage windows (#5570);
271
280
  // unreachable → the flat subscription row. Profile-gated like every adapter: no profile, no row.
272
281
  if (only && (only.has("codex") || only.has("openai"))) {
282
+ identities.set("codex", identityFor("codex"));
273
283
  try {
274
284
  const { existsSync, readFileSync } = await import("node:fs");
275
285
  const { join } = await import("node:path");
276
286
  const { homedir } = await import("node:os");
277
- const authPath = join(homedir(), ".codex", "auth.json");
287
+ const authPath = join(env.CODEX_HOME || join(opts.home ?? homedir(), ".codex"), "auth.json");
278
288
  if (existsSync(authPath)) {
279
289
  const base = { provider: "codex", label: "Codex", via: "codex login", ok: true };
280
290
  try {
@@ -308,7 +318,14 @@ export async function fetchBalances(env = process.env, opts = {}) {
308
318
  }
309
319
  } catch { /* no fs access → no row, never an error */ }
310
320
  }
311
- return rows;
321
+ return rows.map(row => {
322
+ const identity = identityFor(row.provider);
323
+ const subject = identities.get(row.provider)?.subject === identity.subject ? identity.subject : null;
324
+ const entry = { ...row, subjectReason: subject ? null : `subject_unavailable:${row.provider}` };
325
+ // Public CLI/provider JSON must omit subjects; only snapshotPayload publishes them to the bridge.
326
+ Object.defineProperty(entry, 'subject', { value: subject, enumerable: false });
327
+ return entry;
328
+ });
312
329
  }
313
330
 
314
331
  // human one-liner for a credit entry (CLI + warning line)
@@ -346,7 +363,12 @@ export function fmtReset(t) {
346
363
  // The snapshot a machine pushes to a hub: its balances plus the machine key and the provider
347
364
  // profile, so a shared hub can keep one snapshot per machine and filter by that machine's profile.
348
365
  export function snapshotPayload(balances, { machine, profile, by, ts = Date.now() }) {
349
- const snap = { balances, ts, machine: String(machine || ""), profile: profile ?? {} };
366
+ const entries = balances.map(entry => {
367
+ const row = { ...entry };
368
+ if (Object.hasOwn(entry, 'subject')) row.subject = entry.subject;
369
+ return row;
370
+ });
371
+ const snap = { balances: entries, ts, machine: String(machine || ""), profile: profile ?? {} };
350
372
  if (by) snap.by = by;
351
373
  return snap;
352
374
  }
@@ -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
  };
@@ -1,9 +1,87 @@
1
1
  // #14671 (B1): dispatcher accounts — the pure accounting core for §5 of docs/TDD-dispatcher.md:
2
2
  // binding provider subjects to opaque account IDs, window freshness, the shared protected
3
3
  // reserve, the admission inequality, watermark-less epochs, daily/reset rollover, escrow.
4
- // Pure: callers pass nowMs. USD is integer microdollars, quota millionths; unknown stays null.
4
+ // Accounting callers pass nowMs. USD is integer microdollars, quota millionths; unknown stays null.
5
5
 
6
6
  import { createHash, createPublicKey, verify as cryptoVerify } from 'node:crypto';
7
+ import { readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { homedir } from 'node:os';
10
+
11
+ // Stable IDs and internal key fingerprints become subjects; credentials never leave the reader.
12
+ // no zod here: lib/balances.mjs pulls this into the hook snapshot, which ships no node_modules (#14754)
13
+ const isLoginId = value => typeof value === 'string' && value.length >= 1 && value.length <= 512
14
+ && value === value.trim() && !value.includes('@');
15
+ export function providerSubject({ provider, loginId }) {
16
+ if (!isLoginId(loginId) || !provider) return null;
17
+ return `s-${createHash('sha256').update(`${provider}\u0000${loginId}`).digest('hex').slice(0, 32)}`;
18
+ }
19
+
20
+ function loginFile(path) {
21
+ try { return JSON.parse(readFileSync(path, 'utf8')); }
22
+ catch { return null; }
23
+ }
24
+
25
+ function oneLoginId(values) {
26
+ const ids = [...new Set(values.filter(value => value != null && value !== ''))];
27
+ return ids.length === 1 ? ids[0] : null;
28
+ }
29
+
30
+ function tokenIdentity(token) {
31
+ if (typeof token !== 'string') return null;
32
+ try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()); }
33
+ catch { return null; }
34
+ }
35
+
36
+ function credentialLogin(key) {
37
+ return typeof key === 'string' && key.length > 0 ? `key:${createHash('sha256').update(key).digest('hex')}` : null;
38
+ }
39
+
40
+ export function readProviderIdentity({ provider, home = homedir(), env = process.env }) {
41
+ let loginId = null;
42
+ const keyNames = { zai: ['ZAI_API_KEY', 'GLM_API_KEY'], kimi: ['KIMI_API_KEY'],
43
+ deepseek: ['DEEPSEEK_API_KEY'], openrouter: ['OPENROUTER_API_KEY'],
44
+ moonshot: ['MOONSHOT_API_KEY'], qwen: ['QWEN_API_KEY'] };
45
+ const key = (keyNames[provider] || []).map(name => env[name]).find(Boolean);
46
+ if (key) {
47
+ loginId = credentialLogin(key);
48
+ } else if (provider === 'codex') {
49
+ const auth = loginFile(join(env.CODEX_HOME || join(home, '.codex'), 'auth.json'));
50
+ if (!auth?.OPENAI_API_KEY && auth?.tokens?.access_token) {
51
+ loginId = auth.tokens.account_id || tokenIdentity(auth.tokens.id_token)?.sub;
52
+ }
53
+ } else if (provider === 'claude') {
54
+ if (!env.ANTHROPIC_API_KEY && !env.ANTHROPIC_AUTH_TOKEN) {
55
+ const auth = loginFile(join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), '.credentials.json'));
56
+ const config = loginFile(env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, '.claude.json') : join(home, '.claude.json'));
57
+ loginId = oneLoginId([auth?.claudeAiOauth?.accountUuid, config?.oauthAccount?.accountUuid]);
58
+ }
59
+ } else if (provider === 'kimi' && !env.KIMI_API_KEY) {
60
+ const auth = ['.kimi-code', '.kimi'].map(directory => loginFile(join(home, directory, 'credentials', 'kimi-code.json')))
61
+ .find(value => value?.access_token);
62
+ if (auth) {
63
+ const token = tokenIdentity(auth.access_token);
64
+ const ids = [auth.user_id, auth.userId, auth.user?.id, token?.user_id].filter(value => value != null && value !== '');
65
+ loginId = ids.length ? oneLoginId(ids) : token?.sub;
66
+ }
67
+ } else {
68
+ const auth = loginFile(join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'opencode', 'auth.json'));
69
+ const names = provider === 'zai' ? ['zai', 'zai-coding-plan'] : [provider];
70
+ const entries = names.map(name => auth?.[name]).filter(Boolean);
71
+ if (entries.length === 1) {
72
+ const ids = [entries[0].userId, entries[0].user_id, entries[0].accountId].filter(value => value != null && value !== '');
73
+ loginId = ids.length ? oneLoginId(ids) : credentialLogin(entries[0].key);
74
+ }
75
+ }
76
+ const subject = providerSubject({ provider, loginId });
77
+ return { provider, subject, reason: subject ? null : `subject_unavailable:${provider}` };
78
+ }
79
+
80
+ export function runnerAccountIdentity({ harness, model = '', ...options }) {
81
+ const selected = harness === 'opencode' ? model.split('/')[0] : harness;
82
+ const provider = ({ glm: 'zai', dsh: 'deepseek', 'zai-coding-plan': 'zai' })[selected] || selected;
83
+ return readProviderIdentity({ ...options, provider });
84
+ }
7
85
 
8
86
  const compare = (a, b) => Buffer.compare(Buffer.from(String(a)), Buffer.from(String(b)));
9
87
 
@@ -56,6 +134,18 @@ export function bindAccounts({ org, bindings = [], orchestrators = [] }) {
56
134
  return { accounts, unmapped };
57
135
  }
58
136
 
137
+ export function resolveSeatAccount({ identity, accounts }) {
138
+ const provider = identity?.provider || 'unknown';
139
+ if (!/^s-[a-f0-9]{32}$/.test(identity?.subject)) {
140
+ return { accountId: null, reason: `subject_unavailable:${provider}` };
141
+ }
142
+ const matching = accounts.filter(account => account.status === 'verified'
143
+ && account.provider === provider && account.subject === identity.subject);
144
+ if (matching.length !== 1) return { accountId: null,
145
+ reason: `${matching.length ? 'subject_ambiguous' : 'subject_unmatched'}:${provider}` };
146
+ return { accountId: matching[0].id, reason: null };
147
+ }
148
+
59
149
  // Freshness of a remaining observation (§5: admission uses a shorter balance TTL than display).
60
150
  // A null value stays unknown regardless of age — Number(null) must never read as a zero balance.
61
151
  // A source-declared status wins; an ok observation older than the TTL is stale by age.
@@ -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;
@@ -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
+ }