trantor 0.18.146 → 0.18.149

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 (57) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +23 -7
  4. package/bin/capacity.mjs +18 -2
  5. package/bin/cli.mjs +6 -2
  6. package/bin/connect.mjs +10 -3
  7. package/bin/crew/state.mjs +1 -1
  8. package/bin/crew-runner.mjs +29 -4
  9. package/bin/dispatch.mjs +78 -0
  10. package/bin/docker-seat.mjs +33 -0
  11. package/bin/heavy-gate-shim/docker +2 -0
  12. package/bin/integrate.mjs +14 -2
  13. package/bin/migrate-dispatcher.mjs +50 -0
  14. package/bin/review.mjs +35 -0
  15. package/hooks/sessionstart.mjs +4 -1
  16. package/hub/auth.mjs +3 -3
  17. package/hub/routes/capacity.mjs +30 -23
  18. package/hub/routes/cards.mjs +13 -1
  19. package/hub/routes/dispatcher-operations.mjs +122 -0
  20. package/hub/routes/dispatcher.mjs +106 -0
  21. package/hub/routes/insights.mjs +68 -4
  22. package/hub/routes/worktree-status.mjs +56 -0
  23. package/hub/store.mjs +20 -0
  24. package/hub.mjs +17 -1
  25. package/kimi.plugin.json +1 -1
  26. package/lib/capacity.mjs +94 -16
  27. package/lib/dispatcher/acceptance.mjs +314 -0
  28. package/lib/dispatcher/accounts.mjs +442 -0
  29. package/lib/dispatcher/admission.mjs +731 -0
  30. package/lib/dispatcher/breakers.mjs +70 -0
  31. package/lib/dispatcher/executor.mjs +486 -0
  32. package/lib/dispatcher/forecast.mjs +391 -0
  33. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  34. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  35. package/lib/dispatcher/harness/contract.mjs +198 -0
  36. package/lib/dispatcher/harness/crew.mjs +463 -0
  37. package/lib/dispatcher/harness/publication.mjs +188 -0
  38. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  39. package/lib/dispatcher/operations.mjs +401 -0
  40. package/lib/dispatcher/planner.mjs +516 -0
  41. package/lib/dispatcher/policy.mjs +9 -0
  42. package/lib/dispatcher/preflight.mjs +249 -0
  43. package/lib/dispatcher/resources.mjs +44 -0
  44. package/lib/dispatcher/schemas.mjs +3 -1
  45. package/lib/dispatcher/snapshot.mjs +72 -1
  46. package/lib/dispatcher/spend.mjs +319 -0
  47. package/lib/dispatcher/store.mjs +207 -2
  48. package/lib/dispatcher/verifier.mjs +246 -0
  49. package/lib/docker-janitor.mjs +24 -14
  50. package/lib/fitness.mjs +227 -41
  51. package/lib/review-gate.mjs +63 -0
  52. package/lib/store-contract.mjs +57 -0
  53. package/lib/store-pg.mjs +38 -3
  54. package/lib/telemetry-ship.mjs +8 -7
  55. package/lib/worktree-status.mjs +216 -0
  56. package/mcp.mjs +53 -7
  57. package/package.json +1 -1
@@ -12,7 +12,8 @@ import { homedir } from "node:os";
12
12
  import { join } from "node:path";
13
13
  import { DEFAULT_LOW, DEFAULT_LOW_QUOTA_PCT } from "../../lib/balances.mjs";
14
14
  import { recordMachineBeat, machineHealthRows, CAPACITY_STALE_MS } from "../../lib/capacity-machines.mjs";
15
- import { budgetsView, burnView, seatsView, machineSeatCounts } from "../../lib/capacity.mjs";
15
+ import { budgetsView, burnView, seatsView, machinesView } from "../../lib/capacity.mjs";
16
+ import { readScroogeLedger, scroogeReceipts } from "../../lib/dispatcher/spend.mjs";
16
17
 
17
18
  /* oxlint-disable anti-slop/no-runtime-typeof -- SAFETY: config.json is user-editable external input; lowThresholds validates its optional number/object fields at that I/O boundary, the same guard GET /balances uses. */
18
19
  // The same low-balance thresholds GET /balances reads, so both views flag the same provider.
@@ -25,6 +26,19 @@ function lowThresholds() {
25
26
  } catch { return { low: DEFAULT_LOW, pct: DEFAULT_LOW_QUOTA_PCT }; }
26
27
  }
27
28
 
29
+ // Crew USD receipts for the burn view (#14671): the scrooge one-shot ledger, mtime-cached the
30
+ // same way /economics reads it. Dispatcher usage events join the same projection when B5/B6 wire
31
+ // their store; no token-derived dollar estimates are ever fabricated here.
32
+ let spendLedgerCache = { mtimeMs: -1, receipts: [] };
33
+ function crewSpendReceipts() {
34
+ const ledger = readScroogeLedger();
35
+ if (ledger.mtimeMs == null) return [];
36
+ if (ledger.mtimeMs !== spendLedgerCache.mtimeMs) {
37
+ spendLedgerCache = { mtimeMs: ledger.mtimeMs, receipts: scroogeReceipts({ lines: ledger.rows.map((row) => row.line) }) };
38
+ }
39
+ return spendLedgerCache.receipts;
40
+ }
41
+
28
42
  export async function routeCapacity({ req, res, P, auth, ctx }) {
29
43
  const { state, body, json, now, turnTelemetry, ONLINE_MS, PEER_TTL_MS, filterReadable } = ctx;
30
44
 
@@ -43,33 +57,26 @@ export async function routeCapacity({ req, res, P, auth, ctx }) {
43
57
  const visibleSeats = filterReadable(auth, seats, (s) => s.project);
44
58
  const seatKey = (s) => `${s.persona}\u0000${s.project}`;
45
59
  const visibleKeys = new Set(visibleSeats.map(seatKey));
46
- const canSee = (s) => visibleKeys.has(seatKey(s));
60
+ // One-shot receipts have no presence seat: their visibility is project-readability of the
61
+ // receipt itself, so a project-scoped reader still sees their dollars without seeing seats.
62
+ const receipts = crewSpendReceipts();
63
+ const visibleReceiptKeys = new Set(filterReadable(auth, receipts, (r) => r.project)
64
+ .map((r) => `${r.persona || ""}\u0000${r.project || ""}`));
65
+ const canSee = (s) => visibleKeys.has(seatKey(s)) || visibleReceiptKeys.has(seatKey(s));
47
66
 
48
- // Machine rows: the beat registry joined with seat counts; a machine that only presence knows
49
- // (no runner heartbeat, e.g. the operator's Mac) still lists, with nulls and its seat count.
50
- const seatCounts = machineSeatCounts(state.peers, nowMs, { ttlMs: PEER_TTL_MS, onlineMs: ONLINE_MS });
51
- const machines = [];
52
- const seen = new Set();
53
- for (const h of machineHealthRows(nowMs)) {
54
- seen.add(h.machine);
55
- const counts = seatCounts.get(h.machine);
56
- machines.push({ ...h, seats: counts?.seats || 0, seatsOnline: counts?.seatsOnline || 0, heartbeat: true });
57
- }
58
- for (const [machine, counts] of seatCounts) {
59
- if (seen.has(machine)) continue;
60
- machines.push({
61
- machine, cpuPct: null, memUsed: null, memTotal: null, cores: null, memPressurePct: null,
62
- swapUsed: null, swapTotal: null, diskFree: null, diskTotal: null,
63
- ts: null, ageMs: null, stale: true, heartbeat: false,
64
- seats: counts.seats, seatsOnline: counts.seatsOnline,
65
- });
66
- }
67
- machines.sort((a, b) => a.machine.localeCompare(b.machine));
67
+ // Machine rows (#14702): the beat registry joined with seat counts over every machine name the
68
+ // hub knows — beat labels, presence labels, balances host names — case-insensitively, with an
69
+ // unlabeled "host:project" session attributed to a known host (the operator's Mac).
70
+ const machines = machinesView({
71
+ beats: machineHealthRows(nowMs), peers: state.peers, nowMs,
72
+ ttlMs: PEER_TTL_MS, onlineMs: ONLINE_MS,
73
+ balanceMachines: Object.keys(state.balancesByMachine || {}),
74
+ });
68
75
 
69
76
  return json(res, 200, {
70
77
  ts: nowMs,
71
78
  budgets: budgetsView({ state, nowMs, thresholds: low, quotaPct: pct }),
72
- burn: burnView({ rows: burnRows, nowMs, canSee }),
79
+ burn: burnView({ rows: burnRows, nowMs, canSee, spendReceipts: receipts }),
73
80
  machines,
74
81
  staleAfterMs: CAPACITY_STALE_MS,
75
82
  seats: visibleSeats,
@@ -206,7 +206,19 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
206
206
  markDirty(); return json(res, 200, { ok: true, task: t });
207
207
  }
208
208
  if (req.method === "POST" && P === "/task/update") { // move/edit a card
209
- const b = await body(req); const found = state.tasks.find(x => x.id === Number(b.id));
209
+ const b = await body(req);
210
+ if (ctx.dispatcher) {
211
+ try {
212
+ const guarded = crossProjectGuard(auth, P, b);
213
+ if (!guarded.ok) return json(res, guarded.code, { error: guarded.error });
214
+ const task = await ctx.mutateDispatcherCard(b, auth);
215
+ if (task) return json(res, 200, { ok: true, task });
216
+ } catch (error) {
217
+ const status = error.name === 'ZodError' ? 422 : error.status || 503;
218
+ return json(res, status, { code: error.code || 'schema_invalid' });
219
+ }
220
+ }
221
+ const found = state.tasks.find(x => x.id === Number(b.id));
210
222
  const t = found && copyTask(found);
211
223
  if (!t) return json(res, 404, { error: "no such task" });
212
224
  const cpg = crossProjectGuard(auth, P, b);
@@ -0,0 +1,122 @@
1
+ import { z } from 'zod';
2
+ import { reject } from '../../lib/dispatcher/admission.mjs';
3
+ import { requireRole } from '../../lib/dispatcher/operations.mjs';
4
+
5
+ export function dispatcherEndpoint(method, path, query) {
6
+ return path === '/dispatch' || path.startsWith('/dispatch/') || path.startsWith('/dispatcher/')
7
+ || method === 'POST' && path === '/advise'
8
+ || method === 'GET' && path === '/capacity' && query.version !== undefined;
9
+ }
10
+
11
+ export async function routeDispatcherOperations({ req, res, P, q, auth, ctx }) {
12
+ if (!dispatcherEndpoint(req.method, P, q) || P === '/dispatch' || P === '/advise'
13
+ || /^\/dispatch\/[^/]+(?:\/(heartbeat|events|stop))?$/.test(P)) return false;
14
+ try {
15
+ if (ctx.AUTH_MODE === 'off' || !ctx.dispatcher) reject('dispatch_unavailable', 503);
16
+ if (!auth?.ok || !auth.identity || !auth.pubkey || auth.warning) reject('permission_denied', 403);
17
+ const service = ctx.dispatcher;
18
+ const orgId = service.orgId(auth);
19
+ if (!orgId) reject('permission_denied', 403);
20
+ const actor = { pubkey: auth.pubkey };
21
+ if (req.method === 'POST' && P === '/dispatcher/verifiers') {
22
+ return ctx.json(res, 200, await service.verifier.registerGrant(orgId, await ctx.body(req), actor));
23
+ }
24
+ if (req.method === 'POST' && P === '/dispatcher/verification-jobs/claim') {
25
+ return ctx.json(res, 200, await service.verifier.claim(orgId, await ctx.body(req), actor));
26
+ }
27
+ const beat = /^\/dispatcher\/verification-jobs\/([^/]+)\/heartbeat$/.exec(P);
28
+ if (req.method === 'POST' && beat) {
29
+ return ctx.json(res, 200, await service.verifier.heartbeat(orgId, decodeURIComponent(beat[1]), await ctx.body(req), actor));
30
+ }
31
+ const verify = /^\/dispatch\/([^/]+)\/(verify|acceptance)$/.exec(P);
32
+ if (req.method === 'POST' && verify) {
33
+ const id = decodeURIComponent(verify[1]);
34
+ const attempt = await service.store.attempt(orgId, id);
35
+ if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
36
+ const result = verify[2] === 'verify'
37
+ ? await service.verifier.enqueue(orgId, id, await ctx.body(req), actor)
38
+ : await service.verifier.accept(orgId, id, await ctx.body(req), actor);
39
+ return ctx.json(res, verify[2] === 'verify' && !result.replayed ? 202 : 200, result);
40
+ }
41
+ const read = async (project, operation) => service.store.locked(orgId, async client => {
42
+ await requireRole(client, orgId, actor, project, ['read', 'write', 'approver', 'owner']);
43
+ return operation(client);
44
+ });
45
+ if (req.method === 'GET' && P === '/dispatcher/pacing') {
46
+ const request = z.strictObject({ project: z.string().min(1).max(8192) }).parse(q);
47
+ return ctx.json(res, 200, await service.pacing(orgId, request, actor));
48
+ }
49
+ if (req.method === 'GET' && P === '/capacity') {
50
+ if (q.version !== '1' || !q.project) reject('schema_invalid', 422);
51
+ return ctx.json(res, 200, await service.capacity(orgId, q, actor));
52
+ }
53
+ if (req.method === 'POST' && P === '/dispatcher/evidence') {
54
+ return ctx.json(res, 201, await service.registerEvidence(orgId, await ctx.body(req), actor));
55
+ }
56
+ if (req.method === 'POST' && P === '/dispatcher/cards') {
57
+ return ctx.json(res, 201, await service.registerCard(orgId, await ctx.body(req), actor));
58
+ }
59
+ if (req.method === 'POST' && P === '/dispatcher/collectors') {
60
+ return ctx.json(res, 200, await service.registerCollector(orgId, await ctx.body(req), actor));
61
+ }
62
+ if (req.method === 'POST' && P === '/dispatcher/policy/activate') {
63
+ return ctx.json(res, 200, await service.activatePolicy(orgId, await ctx.body(req), actor));
64
+ }
65
+ if (req.method === 'POST' && P === '/dispatcher/control') {
66
+ return ctx.json(res, 200, await service.executor.kill(orgId, await ctx.body(req), actor));
67
+ }
68
+ if (req.method === 'GET' && P === '/dispatcher/policy') {
69
+ const result = await service.store.locked(orgId, async client => {
70
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
71
+ return (await client.query(`SELECT p.row FROM dispatcher_policies p JOIN dispatcher_authority_state s
72
+ ON s.org_id=p.org_id AND s.policy_version=p.version WHERE p.org_id=$1`, [orgId])).rows[0]?.row || null;
73
+ });
74
+ return ctx.json(res, 200, { schemaVersion: 1, policy: result });
75
+ }
76
+ const topUp = /^\/dispatch\/([^/]+)\/top-up$/.exec(P);
77
+ const decide = /^\/dispatch\/([^/]+)\/top-ups\/([^/]+)\/decision$/.exec(P);
78
+ if (topUp || decide) {
79
+ const id = decodeURIComponent((topUp || decide)[1]);
80
+ const attempt = await service.store.attempt(orgId, id);
81
+ if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
82
+ if (topUp && req.method === 'GET') {
83
+ const asks = await read(attempt.project, async client => (await client.query(
84
+ 'SELECT row FROM dispatcher_budget_asks WHERE org_id=$1 AND attempt_id=$2 ORDER BY expires_at_ms DESC', [orgId, id])).rows.map(r => r.row));
85
+ return ctx.json(res, 200, { schemaVersion: 1, asks });
86
+ }
87
+ if (decide && req.method === 'POST') {
88
+ const result = await service.finance.topUp(orgId, id, decodeURIComponent(decide[2]), await ctx.body(req), actor);
89
+ return ctx.json(res, result.replayed ? 200 : result.state === 'cancelled' ? 200 : 202, { schemaVersion: 1, ...result });
90
+ }
91
+ }
92
+ const repair = /^\/dispatcher\/account-bindings\/([^/]+)\/repairs$/.exec(P);
93
+ if (repair && req.method === 'POST') {
94
+ const result = await service.finance.repairBinding(orgId, decodeURIComponent(repair[1]), await ctx.body(req), actor);
95
+ return ctx.json(res, result.state === 'applied' || result.replayed ? 200 : 202, { schemaVersion: 1, ...result });
96
+ }
97
+ const repairRead = /^\/dispatcher\/account-binding-repairs\/([^/]+)$/.exec(P);
98
+ if (repairRead && req.method === 'GET') {
99
+ const row = await service.store.locked(orgId, async client => {
100
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
101
+ return (await client.query('SELECT row FROM dispatcher_account_binding_repairs WHERE org_id=$1 AND id=$2',
102
+ [orgId, decodeURIComponent(repairRead[1])])).rows[0]?.row;
103
+ });
104
+ if (!row) reject('repair_missing', 404);
105
+ return ctx.json(res, 200, { schemaVersion: 1, repair: row });
106
+ }
107
+ return false;
108
+ } catch (error) {
109
+ const status = error instanceof z.ZodError || error instanceof URIError ? 422 : error.status || 503;
110
+ const code = status === 422 ? 'schema_invalid' : error.code || 'dispatch_unavailable';
111
+ return ctx.json(res, status, { schemaVersion: 1, code,
112
+ reasons: [{ code, resource: null, retryAtMs: null }], retryable: status === 429 || status === 503 });
113
+ }
114
+ }
115
+
116
+ export function dispatcherUnavailable({ req, res, P, q, ctx }) {
117
+ if (!dispatcherEndpoint(req.method, P, q)) return false;
118
+ if (ctx.AUTH_MODE !== 'off' && ctx.dispatcher) return false;
119
+ const code = 'dispatch_unavailable';
120
+ return ctx.json(res, 503, { schemaVersion: 1, code,
121
+ reasons: [{ code, resource: null, retryAtMs: null }], retryable: true });
122
+ }
@@ -0,0 +1,106 @@
1
+ import { z } from 'zod';
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
+ import { canonicalJson, verifySnapshot } from '../../lib/dispatcher/snapshot.mjs';
5
+ import { verifyPolicy } from '../../lib/dispatcher/policy.mjs';
6
+ import { plan } from '../../lib/dispatcher/planner.mjs';
7
+
8
+ const text = z.string().min(1).max(8192);
9
+ const positive = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
10
+ export const AdviceRequestSchema = z.strictObject({ schemaVersion: z.literal(1), project: text,
11
+ snapshotId: text.optional(), policyVersion: text.optional(), cards: z.array(WorkCardSchema).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
+ export const AdviceAuthoritySchema = z.strictObject({ snapshot: SnapshotSchema, policy: PolicySchema });
14
+ export const AttemptEventSchema = z.discriminatedUnion('kind', [
15
+ z.strictObject({ kind: z.literal('usage'), event: UsageEventSchema }),
16
+ z.strictObject({ kind: z.literal('artifact'), artifact: ArtifactSchema,
17
+ capability: z.strictObject({ generation: positive, launchToken: text }) }),
18
+ ]);
19
+
20
+ async function readable(client, orgId, actor, project) {
21
+ const row = (await client.query('SELECT scopes,revoked_at FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
22
+ if (!row || row.revoked_at != null || !storedScopeAllows(row, project, ['read','write','approver','owner'])) {
23
+ reject('permission_denied', 403);
24
+ }
25
+ return row;
26
+ }
27
+
28
+ async function advise(service, orgId, input, actor, auth) {
29
+ const request = AdviceRequestSchema.parse(input);
30
+ if ([...request.cards, ...request.drafts || []].some(c => c.project !== request.project)) reject('permission_denied', 403);
31
+ return service.store.locked(orgId, async client => {
32
+ const identity = await readable(client, orgId, actor, request.project);
33
+ const authority = AdviceAuthoritySchema.parse(await service.readAdvice(client, { orgId, request, actor }));
34
+ let snapshot;
35
+ try { snapshot = verifySnapshot(authority.snapshot); verifyPolicy(authority.policy); } catch { reject('snapshot_invalid'); }
36
+ if (request.snapshotId && request.snapshotId !== snapshot.id) reject('snapshot_gone', 410);
37
+ if (request.policyVersion && request.policyVersion !== authority.policy.version) reject('policy_stale');
38
+ for (const card of request.cards) {
39
+ const stored = snapshot.readyQueue.find(c => c.project === card.project && c.card === card.card);
40
+ if (!stored || canonicalJson(stored) !== canonicalJson(card)) reject('card_stale');
41
+ }
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 });
46
+ const dispatchable = !request.drafts?.length;
47
+ if (dispatchable) await client.query(`INSERT INTO dispatcher_decisions VALUES($1,$2,$3,$4,$5,$6,$7)
48
+ ON CONFLICT(org_id,id) DO NOTHING`, [orgId, decision.id, request.project, decision.snapshotId,
49
+ decision.policyVersion, decision.createdAtMs, decision]);
50
+ return { schemaVersion: 1, dispatchable, decision: service.projectDecision(decision, { ...auth, identity }) };
51
+ });
52
+ }
53
+
54
+ export async function routeDispatcher({ req, res, q: _q, P, auth, ctx }) {
55
+ const match = /^\/dispatch\/([^/]+)(?:\/(heartbeat|events|stop))?$/.exec(P);
56
+ const advice = req.method === 'POST' && P === '/advise';
57
+ const dispatch = req.method === 'POST' && P === '/dispatch';
58
+ if (!advice && !dispatch && !(match && (req.method === 'POST' && match[2] || req.method === 'GET' && !match[2]))) return false;
59
+ try {
60
+ if (ctx.AUTH_MODE === 'off' || !auth?.ok || !auth.identity || !auth.pubkey) reject('permission_denied', 403);
61
+ const service = ctx.dispatcher;
62
+ if (!service) reject('dispatch_unavailable', 503);
63
+ const orgId = service.orgId(auth);
64
+ if (!orgId) reject('permission_denied', 403);
65
+ const actor = { pubkey: auth.pubkey };
66
+ if (advice) return ctx.json(res, 200, await advise(service, orgId, await ctx.body(req), actor, auth));
67
+ if (dispatch) {
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
+ }
73
+ const result = await service.admission.dispatch(orgId, input, actor);
74
+ return ctx.json(res, result.replayed ? 200 : 202, result);
75
+ }
76
+ const attemptId = decodeURIComponent(match[1]);
77
+ const attempt = await service.store.attempt(orgId, attemptId);
78
+ if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
79
+ if (req.method === 'GET') {
80
+ await service.store.locked(orgId, client => readable(client, orgId, actor, attempt.project));
81
+ return ctx.json(res, 200, { schemaVersion: 1, attemptId, project: attempt.project, card: attempt.card,
82
+ leaseId: attempt.leaseId, state: attempt.state, generation: attempt.generation, artifact: attempt.artifact,
83
+ acceptance: attempt.acceptance, failure: attempt.failure, endedAtMs: attempt.endedAtMs });
84
+ }
85
+ const input = await ctx.body(req);
86
+ let result;
87
+ if (match[2] === 'heartbeat') result = await service.executor.heartbeat(orgId, attemptId, input, actor);
88
+ if (match[2] === 'stop') {
89
+ const stop = z.strictObject({ reason: text }).parse(input);
90
+ result = await service.executor.stop(orgId, attemptId, stop.reason, actor);
91
+ }
92
+ if (match[2] === 'events') {
93
+ const event = AttemptEventSchema.parse(input);
94
+ result = event.kind === 'usage' ? await service.executor.usage(orgId, attemptId, event.event, actor)
95
+ : await service.executor.artifact(orgId, attemptId, event.artifact, event.capability, actor);
96
+ if (event.kind === 'artifact') result = { state: result.state, generation: result.generation };
97
+ }
98
+ return ctx.json(res, 200, { schemaVersion: 1, ...result });
99
+ } catch (error) {
100
+ const status = error instanceof z.ZodError || error instanceof URIError ? 422 : error.status || 503;
101
+ const code = status === 422 ? 'schema_invalid' : error.code || 'dispatch_unavailable';
102
+ if (code === 'admission_busy') res.setHeader('Retry-After', '1');
103
+ return ctx.json(res, status, { schemaVersion: 1, code, reasons: [{ code, resource: null, retryAtMs: null }],
104
+ retryable: status === 429 || status === 503 });
105
+ }
106
+ }
@@ -2,6 +2,7 @@
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { classifyAttemptVerification, validateAcceptanceRecord } from "../../lib/dispatcher/acceptance.mjs";
5
6
 
6
7
  let ledgerCache = { mtimeMs: -1, rows: [] };
7
8
  const TURN_OUTCOMES = new Set(["completed", "asked", "blocked", "no-delivery", "empty", "stalled", "cut", "rejected", "api-error"]);
@@ -26,19 +27,34 @@ function validAttempt(attempt, row, nowMs) {
26
27
  if (attempt.commit !== "" && (typeof attempt.commit !== "string" || !/^[0-9a-f]{40}$/i.test(attempt.commit))) return null;
27
28
  if (!TURN_OUTCOMES.has(attempt.outcome) || attempt.outcome !== row.outcome || typeof attempt.infraFailure !== "boolean") return null;
28
29
  if (!(attempt.tokens === null || safeInteger(attempt.tokens))) return null;
29
- return {
30
+ // B2 (#14672): additive verification evidence, validated but NOT trusted — a producer-embedded
31
+ // acceptance is re-adjudicated on every read and never counts unless it survives independence.
32
+ const acceptance = attempt.acceptance == null ? null : validateAcceptanceRecord(attempt.acceptance);
33
+ if (attempt.acceptance != null && !acceptance) return null;
34
+ const producerIdentityIds = attempt.producerIdentityIds === undefined || attempt.producerIdentityIds === null
35
+ ? undefined : (Array.isArray(attempt.producerIdentityIds) && attempt.producerIdentityIds.length <= 100
36
+ && attempt.producerIdentityIds.every(id => stringWithin(id, 200)) ? attempt.producerIdentityIds : null);
37
+ if (producerIdentityIds === null) return null;
38
+ const cardRevision = attempt.cardRevision === undefined || attempt.cardRevision === null
39
+ ? undefined : (safeInteger(attempt.cardRevision) ? attempt.cardRevision : null);
40
+ if (cardRevision === null) return null;
41
+ const valid = {
30
42
  id: attempt.id, card: attempt.card, seat: attempt.seat, project: attempt.project,
31
43
  provider: attempt.provider, model: attempt.model, effort: attempt.effort, harness: attempt.harness,
32
44
  taskKind: attempt.taskKind, difficulty: attempt.difficulty, machine: attempt.machine,
33
45
  start: attempt.start, end: attempt.end, commit: attempt.commit, outcome: attempt.outcome,
34
46
  infraFailure: attempt.infraFailure, tokens: attempt.tokens,
35
47
  };
48
+ if (acceptance !== null) valid.acceptance = acceptance;
49
+ if (producerIdentityIds !== undefined) valid.producerIdentityIds = producerIdentityIds;
50
+ if (cardRevision !== undefined) valid.cardRevision = cardRevision;
51
+ return valid;
36
52
  }
37
53
 
38
54
  function validTurnRow(row, nowMs) {
39
55
  if (!row || typeof row !== "object" || Array.isArray(row)) return null;
40
56
  if ("prompt" in row || "output" in row || "text" in row) return null;
41
- if (typeof row.id !== "string" || !/^[0-9a-f]{32}$/i.test(row.id) || row.v !== 1) return null;
57
+ if (typeof row.id !== "string" || !/^[0-9a-f]{32}$/i.test(row.id) || (row.v !== 1 && row.v !== 2)) return null;
42
58
  if (!safeInteger(row.ts, 1) || row.ts > nowMs + 60000 || !safeInteger(row.turn, 1)) return null;
43
59
  if (!stringWithin(row.persona, 120) || !stringWithin(row.agent, 80) || !stringWithin(row.project, 80)) return null;
44
60
  // A machine with no label configured reports "" (lib/machine-label.mjs): that is a valid row, not a dropped one.
@@ -55,13 +71,55 @@ function validTurnRow(row, nowMs) {
55
71
  if (row.stderrTail !== undefined && (typeof row.stderrTail !== "string" || row.stderrTail.length > 8000)) return null;
56
72
  if (row.extensions !== undefined && !safeInteger(row.extensions)) return null;
57
73
  if (row.boxMs !== undefined && !safeInteger(row.boxMs)) return null;
74
+ // B2 (#14672, §5.2): v2 adds top-level executionAttemptId/generation/segmentId to the same v1
75
+ // fields and the same dedupe ID. Links are all-null, or a non-null attempt id with a positive
76
+ // generation (segment may stay null when unknown); unbound/forged v2 links are rejected, never
77
+ // stored, and never downgraded to v1.
78
+ if (row.v === 2) {
79
+ const attemptIdOk = row.executionAttemptId == null || stringWithin(row.executionAttemptId, 200);
80
+ const generationOk = row.executionGeneration == null || safeInteger(row.executionGeneration, 1);
81
+ const segmentOk = row.executionSegmentId == null || stringWithin(row.executionSegmentId, 200);
82
+ const linked = row.executionAttemptId != null && row.executionGeneration != null;
83
+ const unlinked = row.executionAttemptId == null && row.executionGeneration == null;
84
+ if (!attemptIdOk || !generationOk || !segmentOk || (!linked && !unlinked)) return null;
85
+ }
58
86
  const attempt = row.attempt === undefined ? null : validAttempt(row.attempt, row, nowMs);
59
87
  if (row.attempt !== undefined && !attempt) return null;
60
88
  const valid = { ...row, id: row.id.toLowerCase(), verdict: row.verdict.slice(0, 600) };
89
+ if (row.v === 1) {
90
+ delete valid.executionAttemptId;
91
+ delete valid.executionGeneration;
92
+ delete valid.executionSegmentId;
93
+ } else {
94
+ valid.executionAttemptId = row.executionAttemptId == null ? null : String(row.executionAttemptId);
95
+ valid.executionGeneration = row.executionGeneration == null ? null : Number(row.executionGeneration);
96
+ valid.executionSegmentId = row.executionSegmentId == null ? null : String(row.executionSegmentId);
97
+ }
61
98
  if (attempt) valid.attempt = attempt;
62
99
  return valid;
63
100
  }
64
101
 
102
+ // The v2 executor-attempt view (§5.2 read projection): attempts with explicit pending/legacy
103
+ // status. Only an acceptance that survives read-side re-adjudication marks accepted/failed; a
104
+ // producer-embedded acceptance is rejected and the attempt stays pending.
105
+ function executorAttemptView(row) {
106
+ const attempt = row.attempt;
107
+ const verification = classifyAttemptVerification({ ...attempt, executionAttemptId: row.executionAttemptId == null ? null : row.executionAttemptId });
108
+ return {
109
+ id: row.executionAttemptId != null ? row.executionAttemptId : attempt.id,
110
+ generation: row.executionGeneration == null ? null : row.executionGeneration,
111
+ segmentId: row.executionSegmentId == null ? null : row.executionSegmentId,
112
+ provenance: row.executionAttemptId != null ? "managed" : "legacy",
113
+ project: attempt.project, card: attempt.card, cardRevision: attempt.cardRevision === undefined ? null : attempt.cardRevision,
114
+ seat: attempt.seat, producerIdentityIds: attempt.producerIdentityIds === undefined ? [] : attempt.producerIdentityIds,
115
+ provider: attempt.provider, model: attempt.model, effort: attempt.effort, harness: attempt.harness,
116
+ taskKind: attempt.taskKind, difficulty: attempt.difficulty, machine: attempt.machine,
117
+ outcome: attempt.outcome, start: attempt.start, end: attempt.end, commit: attempt.commit,
118
+ tokens: attempt.tokens, infraFailure: attempt.infraFailure,
119
+ verification: { status: verification.status, acceptance: verification.acceptance, rejected: verification.rejected },
120
+ };
121
+ }
122
+
65
123
  export async function routeInsights({ res, q, P, req, auth, ctx }) {
66
124
  const { state, json, canon, now, body, scopeAllows, filterReadable, turnTelemetry, AUTH_MODE } = ctx;
67
125
  if (req.method === "POST" && P === "/telemetry/turns") {
@@ -101,8 +159,14 @@ export async function routeInsights({ res, q, P, req, auth, ctx }) {
101
159
  project: q.project || "", agent: q.agent || "",
102
160
  since: numberQuery(q.since, 0), until: numberQuery(q.until, Number.MAX_SAFE_INTEGER),
103
161
  });
104
- const attempts = rows.filter(row => row.attempt).map(row => row.attempt);
105
- return json(res, 200, { attempts: filterReadable(auth, attempts, attempt => attempt.project || "").slice(0, limit) });
162
+ const withAttempts = rows.filter(row => row.attempt);
163
+ // Default remains the legacy projection (§5.2); `?version=2` exposes executor attempts with
164
+ // explicit pending/legacy status. Operational "completed" stats never change here.
165
+ if (q.version === "2") {
166
+ const projected = withAttempts.map(row => executorAttemptView(row));
167
+ return json(res, 200, { attempts: filterReadable(auth, projected, attempt => attempt.project || "").slice(0, limit) });
168
+ }
169
+ return json(res, 200, { attempts: filterReadable(auth, withAttempts.map(row => row.attempt), attempt => attempt.project || "").slice(0, limit) });
106
170
  }
107
171
  if (req.method === "GET" && P === "/economics") { // the brain's books, surfaced: scrooge ledger + quota profile
108
172
  const out = { scrooge: null, lifetime: null, profile: null };
@@ -0,0 +1,56 @@
1
+ import { z } from "zod";
2
+
3
+ const name = z.string().min(1).max(80).regex(/^[A-Za-z0-9_.-]+$/);
4
+ const file = z.object({
5
+ path: z.string().min(1).max(500).refine(path => !path.includes("\0") && !path.includes("\n")),
6
+ status: z.string().length(2),
7
+ added: z.number().int().nonnegative().nullable(),
8
+ removed: z.number().int().nonnegative().nullable(),
9
+ });
10
+ const snapshot = z.object({
11
+ seat: name,
12
+ project: name,
13
+ machine: name,
14
+ branch: z.string().min(1).max(200).nullable(),
15
+ head: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),
16
+ ahead: z.number().int().nonnegative().nullable(),
17
+ fileCount: z.number().int().nonnegative(),
18
+ files: z.array(file).max(200),
19
+ observedAt: z.number().int().positive(),
20
+ sequence: z.number().int().positive(),
21
+ }).refine(status => status.fileCount >= status.files.length);
22
+
23
+ const latest = new Map();
24
+
25
+ export async function routeWorktreeStatus({ req, res, q, P, auth, ctx }) {
26
+ if (P !== "/worktree-status" || (req.method !== "GET" && req.method !== "POST")) return false;
27
+ if (req.method === "GET") {
28
+ const parsed = name.safeParse(q.project);
29
+ if (!parsed.success) return ctx.json(res, 400, { error: "project required" });
30
+ const project = ctx.canon(parsed.data);
31
+ if (!ctx.canRead(auth, project)) return ctx.json(res, 403, { error: "forbidden" });
32
+ const statuses = [...latest.values()]
33
+ .filter(status => status.project === project)
34
+ .sort((a, b) => a.seat.localeCompare(b.seat) || a.machine.localeCompare(b.machine));
35
+ return ctx.json(res, 200, { statuses });
36
+ }
37
+
38
+ const parsed = snapshot.safeParse(await ctx.body(req));
39
+ if (!parsed.success) return ctx.json(res, 400, { error: "invalid worktree status", issues: parsed.error.issues });
40
+ const status = { ...parsed.data, project: ctx.canon(parsed.data.project) };
41
+ if (ctx.AUTH_MODE === "enforce" && !ctx.scopeAllows(auth?.identity, status.project, "write")) {
42
+ return ctx.json(res, 403, { error: "forbidden" });
43
+ }
44
+ if (auth?.identity?.kind === "agent" && auth.identity.name !== `${status.seat}:${status.project}`) {
45
+ return ctx.json(res, 403, { error: "agent may report only its own seat" });
46
+ }
47
+ const key = `${status.project}\0${status.seat}\0${status.machine}`;
48
+ const previous = latest.get(key);
49
+ if (previous && (status.observedAt < previous.observedAt ||
50
+ (status.observedAt === previous.observedAt && status.sequence <= previous.sequence))) {
51
+ return ctx.json(res, 200, { ok: true, status: previous });
52
+ }
53
+ latest.set(key, status);
54
+ ctx.pushEventToStreams({ ts: ctx.now(), type: "worktree-status", project: status.project, by: status.seat, status });
55
+ return ctx.json(res, 200, { ok: true, status });
56
+ }
package/hub/store.mjs CHANGED
@@ -4,6 +4,7 @@ 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";
7
8
 
8
9
  export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics = null }) {
9
10
  function emptyState() {
@@ -351,6 +352,7 @@ const HUB_SRC = `hub-${process.pid}-${randomBytes(4).toString("hex")}`;
351
352
  if (runTaskBootMigrations()) dirty = true;
352
353
  let lastPersisted = durableStore ? snapshotState() : null;
353
354
  const recordPersistFailure = (kind, error) => {
355
+ dispatcher?.store.closeAdmission();
354
356
  dirty = true;
355
357
  const failure = persistHealth.failed(error);
356
358
  if (failure.shouldLog) {
@@ -432,7 +434,25 @@ setInterval(persist, persistTickMs).unref?.();
432
434
  }).catch(error => process.stderr.write(`[trantor] LISTEN ${error.message || error} — external writes will NOT surface until restart\n`));
433
435
  };
434
436
 
437
+ let dispatcher = null;
438
+ if (durableStore) {
439
+ 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 });
441
+ }
435
442
  return {
443
+ dispatcher,
444
+ async mutateDispatcherCard(input, auth) {
445
+ 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];
447
+ if (!managed) return null;
448
+ if (!auth?.pubkey || !auth.identity || auth.warning) throw Object.assign(new Error('permission_denied'), { status: 403, code: 'permission_denied' });
449
+ const task = await dispatcher.mutateCard(ORG_ID, input, { pubkey: auth.pubkey });
450
+ const at = state.tasks.findIndex(t => t.id === task.id);
451
+ if (at !== -1) state.tasks[at] = task;
452
+ const previous = lastPersisted.tasks.findIndex(t => t.id === task.id);
453
+ if (previous !== -1) lastPersisted.tasks[previous] = task;
454
+ return task;
455
+ },
436
456
  state, durableStore, persist, persistHealth, markDirty, copyTask, copyMessage, reload, startChangeSubscription,
437
457
  turnTelemetry, HUB_SRC, appendTaskLog, appendTaskNote, cleanChecklist, cleanDrill, hasDrillLine, stripNulText,
438
458
  };
package/hub.mjs CHANGED
@@ -22,6 +22,9 @@ import { routeReviews } from "./hub/routes/reviews.mjs";
22
22
  import { migrateReviews } from "./hub/review-store.mjs";
23
23
  import { routeDevices } from "./hub/routes/devices.mjs";
24
24
  import { createSessionRuntime } from "./hub/routes/session.mjs";
25
+ import { routeWorktreeStatus } from "./hub/routes/worktree-status.mjs";
26
+ import { routeDispatcher } from "./hub/routes/dispatcher.mjs";
27
+ import { dispatcherUnavailable, routeDispatcherOperations } from "./hub/routes/dispatcher-operations.mjs";
25
28
  import { routeCapacity } from "./hub/routes/capacity.mjs"; // #14653: registered ahead of sessionChat so the /machines/health mirror runs first
26
29
  import { createNotifier } from "./hub/notifier.mjs";
27
30
  import { createHubDiagnostics } from "./lib/hub-diagnostics.mjs";
@@ -135,12 +138,24 @@ const context = {
135
138
  hubSend: duty.hubSend, assertNoSecrets, AUTH_MODE, ONLINE_MS, PEER_TTL_MS,
136
139
  REAP_GRACE_MS, CONTRACT_WINDOW_MS, PUBLIC_URL,
137
140
  };
141
+ if (store.dispatcher && AUTH_MODE !== 'off') {
142
+ let ticking = false;
143
+ setInterval(async () => {
144
+ if (ticking) return;
145
+ ticking = true;
146
+ try { await store.dispatcher.tick(); }
147
+ catch (error) {
148
+ store.dispatcher.store.closeAdmission();
149
+ console.error(`[trantor] dispatcher unavailable: ${error.code || 'store_failure'}`);
150
+ } finally { ticking = false; }
151
+ }, 1000).unref();
152
+ }
138
153
  const sessionChat = createSessionRuntime({
139
154
  state: store.state, markDirty: store.markDirty,
140
155
  appendEvent: events.appendEvent, pushEventToStreams: events.pushEventToStreams, notifier,
141
156
  attachmentsDir: join(DATA_DIR, "attachments"),
142
157
  });
143
- const routes = [routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
158
+ const routes = [routeDispatcher, routeDispatcherOperations, routeWorktreeStatus, routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
144
159
 
145
160
  const publicAuth = createAuthRuntime({
146
161
  state: store.state, markDirty: store.markDirty, AUTH_MODE: "enforce", SUPERSEDE_GRACE_MS,
@@ -159,6 +174,7 @@ function requestHandler(runtime, ctx, gate = null) {
159
174
  const q = Object.fromEntries(u.searchParams);
160
175
  const P = u.pathname;
161
176
  if (gate && !gate.admit(req, res, P)) return;
177
+ if (dispatcherUnavailable({ req, res, P, q, ctx })) return;
162
178
  const cap = gate ? runtime.bodyCap(P) : runtime.ownerBodyCap(req, P);
163
179
  let ownerAuth;
164
180
  if (req.method === "POST") {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.146",
3
+ "version": "0.18.149",
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",