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
@@ -0,0 +1,293 @@
1
+ import { bindAccounts, resolveSeatAccount } from './accounts.mjs';
2
+ import { heldLiability } from './spend.mjs';
3
+ import { DEFAULT_POLICY } from './policy.mjs';
4
+ import { loadCatalog, lookup } from '../model-catalog.mjs';
5
+
6
+ const text = (value, max = 8192) => String(value ?? '').slice(0, max);
7
+ const numberOrNull = value => value == null || value === '' || !Number.isFinite(Number(value)) ? null : Number(value);
8
+ const integerOrNull = value => {
9
+ const number = numberOrNull(value);
10
+ return number == null || number < 0 ? null : Math.round(number);
11
+ };
12
+ const timestamp = value => Number.isSafeInteger(value) && value >= 0 ? value : null;
13
+ const fresh = (observedAtMs, nowMs, ttlMs) => observedAtMs != null && observedAtMs <= nowMs && observedAtMs + ttlMs > nowMs;
14
+ const sourceName = value => text(value || 'unknown', 200);
15
+
16
+ function observation({ value = null, observedAtMs = null, receivedAtMs, source, status = 'unknown', reason = null, sourceRevision = null }) {
17
+ return { value, observedAtMs, receivedAtMs, source: sourceName(source), status,
18
+ reason: reason == null ? null : text(reason, 500), sourceRevision: sourceRevision == null ? null : text(sourceRevision, 200) };
19
+ }
20
+
21
+ function windowRecord({ accountId, id, kind, unit, value, observedAtMs, receivedAtMs, source, sourceRevision, resetsAtMs = null, reason = null }) {
22
+ const known = value != null;
23
+ return {
24
+ id: text(id), accountId, kind, unit, startsAtMs: null,
25
+ resetsAtMs: integerOrNull(resetsAtMs), capacity: unit === 'quotaMillionths' && known ? 1_000_000 : null,
26
+ remaining: observation({ value, observedAtMs, receivedAtMs, source, sourceRevision,
27
+ status: known ? 'ok' : 'unknown', reason }),
28
+ accountedThroughEvent: null, reserve: 0, heldLiability: heldLiability(0), dailyTimeZone: null,
29
+ };
30
+ }
31
+
32
+ function entryWindows({ accountId, entry, snapshot, nowMs }) {
33
+ const observedAtMs = timestamp(snapshot.ts);
34
+ const receivedAtMs = nowMs;
35
+ const source = `balances:${text(snapshot.machine || 'legacy', 60)}`;
36
+ const sourceRevision = text(snapshot.ts, 200);
37
+ const windows = [];
38
+ if (entry.kind === 'prepaid') {
39
+ const amount = numberOrNull(entry.remaining);
40
+ const supported = entry.currency === 'USD' && !entry.unlimited;
41
+ windows.push(windowRecord({ accountId, id: 'prepaid:USD', kind: 'prepaid', unit: 'usdMicros',
42
+ value: supported && amount != null && amount >= 0 ? Math.round(amount * 1_000_000) : null,
43
+ observedAtMs, receivedAtMs, source, sourceRevision,
44
+ reason: supported ? entry.error || null : 'only observed USD prepaid balances have a canonical microdollar unit' }));
45
+ }
46
+ if (entry.kind === 'quota') {
47
+ const percentage = numberOrNull(entry.remainingPct);
48
+ windows.push(windowRecord({ accountId, id: 'quota:default', kind: 'quota', unit: 'quotaMillionths',
49
+ value: percentage != null && percentage >= 0 && percentage <= 100 ? Math.round(percentage * 10_000) : null,
50
+ observedAtMs, receivedAtMs, source, sourceRevision, resetsAtMs: entry.resetTime,
51
+ reason: entry.error || entry.detail || null }));
52
+ }
53
+ if (entry.kind === 'windows') {
54
+ for (const row of Array.isArray(entry.windows) ? entry.windows : []) {
55
+ const name = text(row?.name, 200);
56
+ if (!name) continue;
57
+ const used = numberOrNull(row.usedPct);
58
+ windows.push(windowRecord({ accountId, id: `quota:${name}`, kind: 'quota', unit: 'quotaMillionths',
59
+ value: used != null && used >= 0 && used <= 100 ? Math.round((100 - used) * 10_000) : null,
60
+ observedAtMs, receivedAtMs, source, sourceRevision, resetsAtMs: row.resetsAt,
61
+ reason: row.locked ? text(row.locked, 500) : null }));
62
+ }
63
+ }
64
+ return windows;
65
+ }
66
+
67
+ function balanceEvidence({ snapshots, orgId, nowMs, policy }) {
68
+ const freshRows = [];
69
+ for (const snapshot of Array.isArray(snapshots) ? snapshots : []) {
70
+ const observedAtMs = timestamp(snapshot?.ts);
71
+ if (!fresh(observedAtMs, nowMs, policy.balanceTtlMs)) continue;
72
+ for (const entry of Array.isArray(snapshot.entries) ? snapshot.entries : []) {
73
+ const provider = text(entry?.provider, 200);
74
+ if (!provider) continue;
75
+ freshRows.push({ snapshot, entry, provider, observedAtMs });
76
+ }
77
+ }
78
+ const bindings = freshRows.map(({ snapshot, entry, provider, observedAtMs }) => ({
79
+ provider, machine: text(snapshot.machine || 'legacy', 60), subject: entry.subject ?? entry.billingSubject ?? null,
80
+ bindingRevision: text(observedAtMs, 200),
81
+ }));
82
+ const bound = bindAccounts({ org: orgId, bindings });
83
+ const evidence = [];
84
+ for (const account of [...bound.accounts, ...bound.unmapped]) {
85
+ const matching = freshRows.filter(({ entry, provider }) => provider === account.provider
86
+ && (account.status !== 'verified' || (entry.subject ?? entry.billingSubject) === account.subject));
87
+ const observedAtMs = Math.max(...matching.map(row => row.observedAtMs));
88
+ const windows = account.status === 'verified' ? matching.flatMap(({ entry, snapshot }) =>
89
+ entryWindows({ accountId: account.id, entry, snapshot, nowMs })) : [];
90
+ windows.sort((a, b) => a.id.localeCompare(b.id));
91
+ const record = { id: account.id, provider: account.provider, bindingRevision: account.bindingRevision,
92
+ status: account.status, orchestratorCount: 0, windows };
93
+ evidence.push({ kind: 'account', id: account.id, source: 'balances',
94
+ sourceRef: `balances:${account.provider}:${observedAtMs}`, observedAtMs,
95
+ expiresAtMs: observedAtMs + policy.balanceTtlMs, record });
96
+ for (const window of windows) {
97
+ evidence.push({ kind: 'ledger', id: `${account.id}:${window.id}`, source: 'balances',
98
+ sourceRef: `balances:${account.id}:${window.id}:${observedAtMs}`, observedAtMs,
99
+ expiresAtMs: observedAtMs + policy.balanceTtlMs,
100
+ record: { accountId: account.id, windowId: window.id, unit: window.unit,
101
+ availableBeforeReserve: null, externalHold: 0, reflection: [], evidenceId: account.id } });
102
+ }
103
+ }
104
+ return evidence;
105
+ }
106
+
107
+ function presenceMachines({ rows, seats }) {
108
+ const display = new Map();
109
+ const learn = value => {
110
+ const name = text(value, 60).trim();
111
+ if (!name) return;
112
+ const key = name.toLowerCase();
113
+ const current = display.get(key);
114
+ if (current == null || (current === current.toLowerCase() && name !== name.toLowerCase())) display.set(key, name);
115
+ };
116
+ for (const row of Array.isArray(rows) ? rows : []) learn(row?.machine);
117
+ for (const seat of Array.isArray(seats) ? seats : []) learn(seat?.machine);
118
+ for (const seat of Array.isArray(seats) ? seats : []) {
119
+ if (text(seat?.machine, 60).trim()) continue;
120
+ const session = text(seat?.session, 200);
121
+ const host = session.includes(':') ? session.slice(0, session.indexOf(':')) : '';
122
+ if (display.has(host.toLowerCase())) learn(host);
123
+ }
124
+ return (Array.isArray(seats) ? seats : []).map(seat => {
125
+ const label = text(seat?.machine, 60).trim();
126
+ if (label) return { ...seat, machine: display.get(label.toLowerCase()) || label };
127
+ const session = text(seat?.session, 200);
128
+ const host = session.includes(':') ? session.slice(0, session.indexOf(':')) : '';
129
+ const machine = display.get(host.toLowerCase()) || '';
130
+ return machine ? { ...seat, machine } : seat;
131
+ });
132
+ }
133
+
134
+ function activeSeats(seats, id) {
135
+ return seats.filter(seat => seat?.online && text(seat.machine, 60).toLowerCase() === id.toLowerCase()).length;
136
+ }
137
+
138
+ function machineEvidence({ rows, seats, nowMs, policy }) {
139
+ const evidence = [];
140
+ const emitted = new Set();
141
+ for (const row of Array.isArray(rows) ? rows : []) {
142
+ const id = text(row?.machine, 60);
143
+ const observedAtMs = timestamp(row?.ts);
144
+ if (!id || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
145
+ const key = id.toLowerCase();
146
+ if (emitted.has(key)) continue;
147
+ emitted.add(key);
148
+ const seatCount = activeSeats(seats, id);
149
+ const cpu = numberOrNull(row.cpuPct);
150
+ const health = {
151
+ cores: integerOrNull(row.cores), cpuPct: cpu != null && cpu >= 0 && cpu <= 100 ? Math.round(cpu) : null,
152
+ memUsed: integerOrNull(row.memUsed), memTotal: integerOrNull(row.memTotal),
153
+ memPressurePct: integerOrNull(row.memPressurePct), swapUsed: integerOrNull(row.swapUsed),
154
+ swapTotal: integerOrNull(row.swapTotal), diskFree: integerOrNull(row.diskFree),
155
+ diskTotal: integerOrNull(row.diskTotal), seatsRunning: seatCount,
156
+ };
157
+ evidence.push({ kind: 'machine', id, source: 'machine-beats', sourceRef: `machine-beats:${id}:${observedAtMs}`,
158
+ observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
159
+ record: { id, health: observation({ value: health, observedAtMs, receivedAtMs: nowMs,
160
+ source: 'machine-beats', status: 'ok', sourceRevision: observedAtMs }),
161
+ tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: [] } });
162
+ }
163
+ for (const seat of seats) {
164
+ const id = text(seat?.machine, 60);
165
+ const observedAtMs = timestamp(seat?.lastSeen);
166
+ const key = id.toLowerCase();
167
+ if (!id || emitted.has(key) || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
168
+ emitted.add(key);
169
+ const seatCount = activeSeats(seats, id);
170
+ evidence.push({ kind: 'machine', id, source: 'machine-beats', sourceRef: `presence:${id}:${observedAtMs}`,
171
+ observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
172
+ record: { id, health: observation({ value: null, observedAtMs, receivedAtMs: nowMs,
173
+ source: 'presence', status: 'unknown', reason: 'no fresh machine health beat', sourceRevision: observedAtMs }),
174
+ tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: [] } });
175
+ }
176
+ return evidence;
177
+ }
178
+
179
+ function seatEvidence({ rows, balances, orgId, nowMs, policy }) {
180
+ const bindings = balances.filter(snapshot => fresh(timestamp(snapshot?.ts), nowMs, policy.balanceTtlMs))
181
+ .flatMap(snapshot => (Array.isArray(snapshot.entries) ? snapshot.entries : []).map(entry => ({
182
+ provider: entry?.provider, subject: entry?.subject ?? entry?.billingSubject,
183
+ machine: snapshot.machine, bindingRevision: String(snapshot.ts),
184
+ })));
185
+ const { accounts } = bindAccounts({ org: orgId, bindings });
186
+ const evidence = [];
187
+ for (const row of Array.isArray(rows) ? rows : []) {
188
+ const id = text(row?.session, 200);
189
+ const machine = text(row?.machine, 60);
190
+ const harness = text(row?.llm, 200);
191
+ const observedAtMs = timestamp(row?.lastSeen);
192
+ if (!id || !machine || !harness || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
193
+ const lastTurnMs = timestamp(row?.lastTurn?.ts);
194
+ const binding = resolveSeatAccount({ identity: row.accountIdentity, accounts });
195
+ const record = { id, machine, accountId: binding.accountId, accountBindingReason: binding.reason,
196
+ harness, model: text(row.model, 512) || null,
197
+ busy: row.online === true && /^(working|busy)$/i.test(text(row.status, 100)),
198
+ lastBeatMs: observedAtMs, lastTurnMs };
199
+ if (row.project) record.project = text(row.project, 200);
200
+ evidence.push({ kind: 'seat', id, source: 'presence', sourceRef: `presence:${id}:${observedAtMs}`,
201
+ observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
202
+ record });
203
+ }
204
+ return evidence;
205
+ }
206
+
207
+ function modelEnvelope({ provider, model, observedAtMs, expiresAtMs, nowMs, catalog }) {
208
+ const details = model ? lookup(model, catalog) : null;
209
+ const source = `discovery:${provider}`;
210
+ const unknown = (field, value = null) => observation({ value, observedAtMs: null, receivedAtMs: nowMs,
211
+ source, status: 'unknown', reason: `no fresh ${field} observation` });
212
+ return { kind: 'model', id: `model:${provider}:${model || 'unknown'}`, source: 'discovery-catalog',
213
+ sourceRef: `discovery:${provider}:${model || 'unknown'}:${observedAtMs}`, observedAtMs, expiresAtMs,
214
+ record: { provider, model, accountId: null, catalog: unknown('catalog'),
215
+ entitlement: unknown('entitlement'), invocation: unknown('invocation'), liveUse: null,
216
+ capabilities: details?.found && Array.isArray(details.modalities) ? details.modalities.map(value => text(value, 100)) : [],
217
+ efforts: details?.found && details.effort ? Object.keys(details.effort).sort() : [], breakerId: null } };
218
+ }
219
+
220
+ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
221
+ const models = new Map();
222
+ for (const row of Array.isArray(rows) ? rows : []) {
223
+ const provider = text(row?.provider, 200);
224
+ if (!provider) continue;
225
+ for (const item of Array.isArray(row.models) ? row.models : []) {
226
+ const observedAtMs = timestamp(Date.parse(item?.checkedAt));
227
+ const model = item?.id == null ? null : text(item.id, 512) || null;
228
+ if (!fresh(observedAtMs, nowMs, policy.discoveryTtlMs)) continue;
229
+ const key = `${provider}\0${model || ''}`;
230
+ const envelope = modelEnvelope({ provider, model, observedAtMs,
231
+ expiresAtMs: observedAtMs + policy.discoveryTtlMs, nowMs, catalog });
232
+ const known = ['listed', 'entitled', 'callable'].includes(item.state);
233
+ envelope.record.catalog = observation({ value: known ? true : null, observedAtMs, receivedAtMs: nowMs,
234
+ source: item.source, status: known ? 'ok' : 'unknown', reason: item.reason, sourceRevision: item.checkedAt });
235
+ if (['entitled', 'callable'].includes(item.state)) {
236
+ envelope.record.entitlement = observation({ value: true, observedAtMs, receivedAtMs: nowMs,
237
+ source: item.source, status: 'ok', reason: item.reason, sourceRevision: item.checkedAt });
238
+ }
239
+ models.set(key, envelope);
240
+ }
241
+ }
242
+ for (const seat of Array.isArray(seats) ? seats : []) {
243
+ const model = text(seat?.lastTurn?.model, 512);
244
+ const seatId = text(seat?.session, 200);
245
+ const harness = text(seat?.llm, 200);
246
+ const observedAtMs = timestamp(seat?.lastTurn?.ts);
247
+ if (!model || !seatId || !harness || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
248
+ const provider = model.includes('/') ? text(model.split('/')[0], 200) : harness;
249
+ const key = `${provider}\0${model}`;
250
+ const envelope = models.get(key) || modelEnvelope({ provider, model, observedAtMs,
251
+ expiresAtMs: observedAtMs + policy.invocationTtlMs, nowMs, catalog });
252
+ envelope.record.invocation = observation({ value: { model, seatId, harness }, observedAtMs,
253
+ receivedAtMs: nowMs, source: 'presence:last-turn', status: 'ok', sourceRevision: observedAtMs });
254
+ envelope.observedAtMs = Math.max(envelope.observedAtMs, observedAtMs);
255
+ envelope.expiresAtMs = Math.max(envelope.expiresAtMs, observedAtMs + policy.invocationTtlMs);
256
+ envelope.sourceRef = `presence:${seatId}:${observedAtMs}`;
257
+ models.set(key, envelope);
258
+ }
259
+ return [...models.values()];
260
+ }
261
+
262
+ export function buildEvidence({ balances = [], machines = [], seats = [], discovery = [], orgId, nowMs,
263
+ policy = DEFAULT_POLICY, catalog = loadCatalog() }) {
264
+ const presentSeats = presenceMachines({ rows: machines, seats });
265
+ return [
266
+ ...balanceEvidence({ snapshots: balances, orgId, nowMs, policy }),
267
+ ...machineEvidence({ rows: machines, seats: presentSeats, nowMs, policy }),
268
+ ...seatEvidence({ rows: presentSeats, balances, orgId, nowMs, policy }),
269
+ ...modelEvidence({ rows: discovery, seats: presentSeats, nowMs, policy, catalog }),
270
+ ];
271
+ }
272
+
273
+ export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
274
+ clock = Date.now, policy = DEFAULT_POLICY, catalog = loadCatalog() }) {
275
+ if (!service || !orgId || !grantId || !sources) {
276
+ throw new TypeError('evidence bridge requires service, orgId, grant and sources');
277
+ }
278
+ async function tick() {
279
+ const nowMs = clock();
280
+ const [balances, machines, seats, discovery] = await Promise.all([
281
+ sources.balances(), sources.machines(), sources.seats(), sources.discovery(),
282
+ ]);
283
+ const pending = buildEvidence({ balances, machines, seats, discovery, orgId, nowMs, policy, catalog })
284
+ .filter(envelope => envelope.expiresAtMs > clock());
285
+ let written = 0;
286
+ for (const envelope of pending) {
287
+ const result = await service.registerEvidence(orgId, envelope, { grant: grantId });
288
+ if (!result.replayed) written++;
289
+ }
290
+ return { observed: pending.length, written, skipped: pending.length - written };
291
+ }
292
+ return { tick, build: input => buildEvidence({ ...input, orgId, nowMs: clock(), policy, catalog }) };
293
+ }
@@ -1,10 +1,12 @@
1
1
  import { z } from 'zod';
2
+ import { projectBoardCards } from './board-bridge.mjs';
3
+ import { createRolloutOperations, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
2
4
  import { AccountSchema, MachineSchema, SeatSchema, ModelEvidenceSchema, FitnessCellSchema,
3
5
  ProjectScheduleSchema, WorkCardSchema, PolicySchema } from './schemas.mjs';
4
6
  import { createAdmission, createFinancialOperations, AdmissionAuthoritySchema, WindowLedgerSchema,
5
7
  RepairAuthoritySchema, BindingSettlementSchema, ReplacementAuthoritySchema, requireIdentity,
6
8
  storedScopeAllows, reject } from './admission.mjs';
7
- import { createExecutor, executionRows } from './executor.mjs';
9
+ import { createExecutor, executionRows, KillSchema } from './executor.mjs';
8
10
  import { canonicalHash, canonicalJson, currentEvidence, buildStoredSnapshot, verifySnapshot, projectSnapshot } from './snapshot.mjs';
9
11
  import { verifyPolicy } from './policy.mjs';
10
12
  import { CREW_ADAPTER_VERSION } from './harness/contract.mjs';
@@ -31,15 +33,45 @@ export const EvidenceSchemas = {
31
33
  settlement: BindingSettlementSchema, replacement: ReplacementAuthoritySchema,
32
34
  drill: DrillSpecSchema,
33
35
  promotion: z.strictObject({ policyHash: text, result: z.literal('pass'), approvalId: text,
34
- drills: z.array(z.strictObject({ id: text, result: z.literal('pass'), evidenceRef: text })) }),
36
+ drills: z.array(z.strictObject({ id: text, result: z.literal('pass'), evidenceRef: text })),
37
+ rollout: RolloutApprovalSchema }),
35
38
  };
36
- const sources = { account: ['balances'], ledger: ['balances', 'attempt-receipt'], machine: ['machine-beat'],
37
- seat: ['machine-beat'], model: ['machine-beat'], fitness: ['acceptance'], projectSchedule: ['owner'],
39
+ const sources = { account: ['balances'], ledger: ['balances', 'attempt-receipt'], machine: ['machine-beat', 'machine-beats'],
40
+ seat: ['machine-beat', 'machine-beats', 'presence'], model: ['machine-beat', 'machine-beats', 'presence', 'discovery-catalog'], fitness: ['acceptance'], projectSchedule: ['owner'],
38
41
  launch: ['adapter-record'], repair: ['collector'], settlement: ['adapter-record'],
39
42
  replacement: ['adapter-record'], drill: ['owner'], promotion: ['owner'] };
40
43
  export const RegisterEvidenceSchema = z.strictObject({ kind: z.enum(Object.keys(EvidenceSchemas)), id: text,
41
- expectedRevision: integer, source: z.enum(['balances', 'attempt-receipt', 'machine-beat', 'adapter-record', 'acceptance', 'collector', 'owner']),
44
+ expectedRevision: integer.optional(), source: z.enum(['balances', 'attempt-receipt', 'machine-beat', 'machine-beats', 'presence', 'discovery-catalog', 'adapter-record', 'acceptance', 'collector', 'owner']),
42
45
  sourceRef: text, observedAtMs: integer, expiresAtMs: integer, record: z.json() });
46
+ export const BridgeGrantSchema = z.strictObject({ grantId: text, scope: z.literal('org'),
47
+ kinds: z.array(z.enum(['account-window', 'machine', 'seat', 'model', 'card'])).min(1).max(5),
48
+ sources: z.array(z.enum(['balances', 'machine-beats', 'presence', 'discovery-catalog', 'board'])).min(1).max(5),
49
+ expiresAtMs: integer.nullable().optional(), revoked: z.boolean() });
50
+
51
+ async function evidenceActor(client, orgId, actor, request, nowMs) {
52
+ if (!actor?.grant) {
53
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
54
+ if (request.expectedRevision === undefined) reject('schema_invalid', 422);
55
+ return { approvedBy: actor.pubkey, grantId: null };
56
+ }
57
+ const { grant: grantId } = z.strictObject({ grant: text }).parse(actor);
58
+ const grant = (await client.query('SELECT * FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
59
+ [orgId, grantId])).rows[0];
60
+ const kind = ['account', 'ledger'].includes(request.kind) ? 'account-window' : request.kind;
61
+ if (!grant || grant.revoked_at_ms != null || grant.expires_at_ms != null && Number(grant.expires_at_ms) <= nowMs
62
+ || grant.row.scope !== 'org' || !grant.row.kinds.includes(kind) || !grant.row.sources.includes(request.source)) reject('permission_denied', 403);
63
+ await requireRole(client, orgId, { pubkey: grant.approved_by }, '*', ['owner'], true);
64
+ return { approvedBy: grant.approved_by, grantId };
65
+ }
66
+
67
+ function observationContent(kind, row) {
68
+ const record = structuredClone(row);
69
+ const observations = kind === 'account' ? record.windows.map(window => window.remaining)
70
+ : kind === 'machine' ? [record.health]
71
+ : kind === 'model' ? [record.catalog, record.entitlement, record.invocation] : [];
72
+ for (const observation of observations) delete observation.receivedAtMs;
73
+ return record;
74
+ }
43
75
 
44
76
  export async function requireRole(client, orgId, actor, project, roles, wildcardOnly = false) {
45
77
  const identity = (await client.query('SELECT * FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
@@ -47,8 +79,22 @@ export async function requireRole(client, orgId, actor, project, roles, wildcard
47
79
  return identity;
48
80
  }
49
81
 
50
- export function createDispatcherOperations({ durableStore, orgId: configuredOrg, adapters = new Map(), clock = Date.now, source = '' }) {
82
+ export function createDispatcherOperations({ durableStore, orgId: configuredOrg, adapters = new Map(), clock = Date.now, source = '', advisorWorld,
83
+ evidenceSources, dispatcherBridgeGrant = process.env.RELAY_DISPATCHER_BRIDGE_GRANT || null }) {
51
84
  const store = durableStore.createDispatcherStore();
85
+ const configuredGrant = text.nullable().parse(dispatcherBridgeGrant);
86
+ const bridgeBinding = async (client, orgId, nowMs) => {
87
+ const active = (await client.query(`SELECT grant_id FROM dispatcher_bridge_grants
88
+ WHERE org_id=$1 AND revoked_at_ms IS NULL AND (expires_at_ms IS NULL OR expires_at_ms>$2)
89
+ AND ($3::text IS NULL OR grant_id=$3) ORDER BY grant_id`,
90
+ [orgId, nowMs, configuredGrant])).rows;
91
+ if (active.length === 1) return { grant: active[0].grant_id, degraded: [] };
92
+ return { grant: null, degraded: [active.length ? 'bridge_grant_ambiguous' : 'bridge_grant_missing'] };
93
+ };
94
+ const snapshot = async (client, orgId, nowMs) => {
95
+ const binding = await bridgeBinding(client, orgId, nowMs);
96
+ return buildStoredSnapshot(client, orgId, nowMs, binding.degraded);
97
+ };
52
98
  const evidence = async (client, orgId, kind, id) => {
53
99
  const record = (await currentEvidence(client, orgId, clock())).find(e => e.kind === kind && e.id === id);
54
100
  if (!record) reject(`${kind}_unknown`, 503);
@@ -63,10 +109,10 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
63
109
  [orgId, snapshot.policyVersion])).rows[0]?.row);
64
110
  return { snapshot, policy };
65
111
  }
66
- return buildStoredSnapshot(client, orgId, clock());
112
+ return snapshot(client, orgId, clock());
67
113
  };
68
114
  const readAuthority = async (client, { orgId, request }) => {
69
- const authority = await buildStoredSnapshot(client, orgId, clock());
115
+ const authority = await snapshot(client, orgId, clock());
70
116
  const card = authority.snapshot.readyQueue.find(c => c.project === request.project && c.card === request.card);
71
117
  if (!card) reject('card_stale');
72
118
  const records = await currentEvidence(client, orgId, clock());
@@ -138,6 +184,7 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
138
184
  },
139
185
  async registerCard(orgId, input, actor) {
140
186
  const request = z.strictObject({ card: WorkCardSchema, expectedRevision: integer.nullable() }).parse(input);
187
+ if (request.card.depsBasis === 'board') reject('board_projection_only');
141
188
  return store.locked(orgId, async client => {
142
189
  await requireIdentity(client, orgId, actor, request.card.project);
143
190
  const task = (await client.query('SELECT * FROM tasks WHERE org_id=$1 AND id=$2 FOR UPDATE', [orgId, request.card.card])).rows[0];
@@ -170,7 +217,7 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
170
217
  await requireIdentity(client, orgId, actor, task.project);
171
218
  const managed = (await client.query('SELECT * FROM dispatcher_cards WHERE org_id=$1 AND project=$2 AND card=$3',
172
219
  [orgId, task.project, request.id])).rows[0];
173
- if (!managed || Number(managed.revision) !== request.expectedRevision) reject('card_stale');
220
+ if (!managed || managed.row.depsBasis === 'board' || Number(managed.revision) !== request.expectedRevision) reject('card_stale');
174
221
  const active = (await client.query(`SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND project=$2 AND card=$3
175
222
  AND state NOT IN ('accepted','failed','cancelled','expired')`, [orgId, task.project, request.id])).rows;
176
223
  for (const { id } of active) {
@@ -222,7 +269,8 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
222
269
  return store.locked(orgId, async client => {
223
270
  const identity = await requireRole(client, orgId, actor, request.project, ['read', 'write', 'approver', 'owner']);
224
271
  const { snapshot } = await readAdvice(client, { orgId, request });
225
- const projects = [...new Set(snapshot.projectScheduling.map(p => p.project).concat(snapshot.readyQueue.map(c => c.project)))];
272
+ const projects = [...new Set(snapshot.projectScheduling.map(p => p.project).concat(snapshot.readyQueue.map(c => c.project),
273
+ snapshot.seats.map(seat => seat.project).filter(Boolean)))];
226
274
  return projectSnapshot(snapshot, projects.filter(p => storedScopeAllows(identity, p, ['read', 'write', 'approver', 'owner'])));
227
275
  });
228
276
  },
@@ -262,24 +310,59 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
262
310
  if (!sources[request.kind].includes(request.source) || request.observedAtMs > clock()
263
311
  || request.expiresAtMs <= clock() || request.expiresAtMs <= request.observedAtMs) reject('evidence_unverified', 422);
264
312
  return store.locked(orgId, async client => {
265
- await requireRole(client, orgId, actor, '*', ['owner'], true);
266
- const previous = (await client.query(`SELECT revision,hash FROM dispatcher_evidence WHERE org_id=$1 AND kind=$2 AND id=$3
313
+ const nowMs = clock();
314
+ const { approvedBy, grantId } = await evidenceActor(client, orgId, actor, request, nowMs);
315
+ if (request.expiresAtMs <= nowMs) reject('evidence_unverified', 422);
316
+ const previous = (await client.query(`SELECT * FROM dispatcher_evidence WHERE org_id=$1 AND kind=$2 AND id=$3
267
317
  ORDER BY revision DESC LIMIT 1`, [orgId, request.kind, request.id])).rows[0];
268
- if (Number(previous?.revision || 0) !== request.expectedRevision) reject('evidence_stale');
318
+ const previousRevision = Number(previous?.revision || 0);
319
+ if (request.expectedRevision !== undefined && previousRevision !== request.expectedRevision) reject('evidence_stale');
269
320
  if (record.id !== undefined && record.id !== request.id) reject('schema_invalid', 422);
321
+ if (grantId && previous) {
322
+ if (request.observedAtMs < Number(previous.observed_at_ms)) reject('evidence_stale');
323
+ if (request.observedAtMs === Number(previous.observed_at_ms)) {
324
+ if (previous.grant_id !== grantId || previous.registered_by !== approvedBy || previous.source !== request.source
325
+ || previous.source_ref !== request.sourceRef
326
+ || canonicalHash(observationContent(request.kind, previous.row)) !== canonicalHash(observationContent(request.kind, record))) reject('evidence_conflict');
327
+ return { id: request.id, revision: previousRevision, replayed: true };
328
+ }
329
+ }
270
330
  if (request.kind === 'launch' && record.adapter.version !== CREW_ADAPTER_VERSION) reject('adapter_unqualified', 422);
271
- const revision = request.expectedRevision + 1;
272
- await client.query(`INSERT INTO dispatcher_evidence VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,
331
+ if (request.kind === 'promotion') {
332
+ if (record.approvalId !== request.id) reject('evidence_unverified', 422);
333
+ const validated = await validateRolloutApproval(client, orgId, record);
334
+ await store.audit(client, orgId, { action: 'rollout-approved', atMs: clock(), actor: actor.pubkey,
335
+ approvalId: request.id, approvalHash: canonicalHash(record), ...validated });
336
+ }
337
+ const revision = previousRevision + 1;
338
+ await client.query(`INSERT INTO dispatcher_evidence
339
+ (org_id,kind,id,revision,source,source_ref,observed_at_ms,expires_at_ms,registered_by,registered_at_ms,hash,row,grant_id)
340
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
273
341
  [orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
274
- request.expiresAtMs, actor.pubkey, clock(), canonicalHash(record), record]);
342
+ request.expiresAtMs, approvedBy, nowMs, canonicalHash(record), record, grantId]);
275
343
  if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
276
344
  ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
277
345
  [orgId, record.accountId, record.windowId, revision, record]);
278
346
  await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
279
347
  ON CONFLICT(org_id) DO UPDATE SET revision=dispatcher_authority_state.revision+1`, [orgId]);
280
- await store.audit(client, orgId, { action: 'evidence-registered', actor: actor.pubkey, atMs: clock(),
348
+ await store.audit(client, orgId, { action: 'evidence-registered', actor: approvedBy, approvedBy, grantId, atMs: nowMs,
281
349
  kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
282
- return { id: request.id, revision };
350
+ return grantId ? { id: request.id, revision, replayed: false } : { id: request.id, revision };
351
+ });
352
+ },
353
+ async registerBridgeGrant(orgId, input, actor) {
354
+ const request = BridgeGrantSchema.parse(input);
355
+ return store.locked(orgId, async client => {
356
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
357
+ const nowMs = clock();
358
+ if (!request.revoked && request.expiresAtMs != null && request.expiresAtMs <= nowMs) reject('grant_expired', 422);
359
+ const row = { ...request, expiresAtMs: request.expiresAtMs ?? null, approvedBy: actor.pubkey };
360
+ await client.query(`INSERT INTO dispatcher_bridge_grants VALUES($1,$2,$3,$4,$5,$6)
361
+ ON CONFLICT(org_id,grant_id) DO UPDATE SET approved_by=EXCLUDED.approved_by,expires_at_ms=EXCLUDED.expires_at_ms,
362
+ revoked_at_ms=EXCLUDED.revoked_at_ms,row=EXCLUDED.row`,
363
+ [orgId, row.grantId, row.approvedBy, row.expiresAtMs, row.revoked ? nowMs : null, row]);
364
+ await store.audit(client, orgId, { action: 'bridge-grant-registered', actor: actor.pubkey, atMs: nowMs, ...row });
365
+ return row;
283
366
  });
284
367
  },
285
368
  async registerCollector(orgId, input, actor) {
@@ -304,6 +387,12 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
304
387
  if ((current?.policy_version || null) !== request.expectedVersion) reject('policy_stale');
305
388
  if (Object.values(policy.modeByProject).includes('admit')) {
306
389
  const approval = await evidence(client, orgId, 'promotion', request.approvalId);
390
+ const validated = await service.checkApproval(client, orgId, approval, request.approvalId);
391
+ const cohort = (await client.query("SELECT row FROM dispatcher_audit WHERE org_id=$1 AND row->>'action'='rollout-frozen' AND row->>'id'=$2",
392
+ [orgId, validated.cohortId])).rows[0]?.row;
393
+ if (cohort?.summary.policyFingerprint !== rolloutPolicyHash(policy)) reject('shadow_policy_mismatch', 403);
394
+ if (policy.roster.some(r => r.enabled && r.harness !== 'crew')) reject('promotion_scope_invalid', 403);
395
+ if (Object.entries(policy.modeByProject).some(([project, mode]) => mode === 'admit' && project !== cohort?.project)) reject('promotion_scope_invalid', 403);
307
396
  const required = ['D1','D2','D3','D4','D5','D6','D7','D8','D9','D10','D11','D13','D14','D15','D16','D17','D18','D19','D20','D21','D22','D23','D24','D25'];
308
397
  if (approval.policyHash !== policy.hash || required.some(id => !approval.drills.some(d => d.id === id))) reject('promotion_unapproved', 403);
309
398
  }
@@ -322,16 +411,54 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
322
411
  async recover(orgId) {
323
412
  const complete = (await store.pool.query(`SELECT completed_at_ms FROM dispatcher_migrations WHERE id='dispatcher-v1'`)).rows[0];
324
413
  if (!complete?.completed_at_ms) reject('migration_incomplete', 503);
325
- const { snapshot, policy } = await store.locked(orgId, client => buildStoredSnapshot(client, orgId, clock()));
326
- return executor.recover(orgId, { snapshotId: snapshot.id, policyVersion: policy.version });
414
+ const authority = await store.locked(orgId, client => snapshot(client, orgId, clock()));
415
+ return executor.recover(orgId, { snapshotId: authority.snapshot.id, policyVersion: authority.policy.version });
327
416
  },
328
417
  async tick() {
418
+ await store.locked(configuredOrg, async client => {
419
+ const binding = await bridgeBinding(client, configuredOrg, clock());
420
+ if (!binding.grant) return;
421
+ const grant = (await client.query('SELECT row FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
422
+ [configuredOrg, binding.grant])).rows[0]?.row;
423
+ if (!grant?.kinds.includes('card') || !grant.sources.includes('board')) return;
424
+ const actor = await evidenceActor(client, configuredOrg, { grant: binding.grant }, { kind: 'card', source: 'board' }, clock());
425
+ const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
426
+ JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`, [configuredOrg])).rows[0]?.row;
427
+ if (!policy) reject('policy_missing', 503);
428
+ const changed = await projectBoardCards(client, configuredOrg, verifyPolicy(policy));
429
+ if (changed) await store.audit(client, configuredOrg, { action: 'board-projected', actor: actor.approvedBy,
430
+ grantId: binding.grant, atMs: clock(), changed });
431
+ });
432
+ if (evidenceSources) {
433
+ const binding = await store.locked(configuredOrg, async client => {
434
+ const selected = await bridgeBinding(client, configuredOrg, clock());
435
+ if (!selected.grant) return selected;
436
+ const grant = (await client.query('SELECT row FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
437
+ [configuredOrg, selected.grant])).rows[0]?.row;
438
+ if (grant?.kinds.every(kind => kind === 'card')) return { ...selected, grant: null };
439
+ const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
440
+ JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`,
441
+ [configuredOrg])).rows[0]?.row;
442
+ if (!policy) reject('policy_missing', 503);
443
+ return { ...selected, policy: verifyPolicy(policy) };
444
+ });
445
+ if (binding.grant) {
446
+ const { createEvidenceBridge } = await import('./evidence-bridge.mjs');
447
+ await createEvidenceBridge({ service, orgId: configuredOrg, grant: binding.grant,
448
+ sources: evidenceSources, clock, policy: binding.policy }).tick();
449
+ }
450
+ }
329
451
  await verifier.reconcile(configuredOrg);
330
452
  await finance.expireAsks(configuredOrg);
331
453
  await executor.expire(configuredOrg);
332
454
  if (adapters.size && store.isReady(configuredOrg)) await executor.runOnce(configuredOrg, `hub:${process.pid}`);
333
455
  },
334
456
  };
457
+ Object.assign(service, createRolloutOperations({ service, requireRole, clock, advisorWorld }));
458
+ service.executor = { ...executor, kill(orgId, input, actor) {
459
+ const control = KillSchema.parse(input);
460
+ return control.enabled ? executor.kill(orgId, control, actor) : service.clearControl(orgId, control, actor);
461
+ } };
335
462
  service.admission = { ...admission, async dispatch(orgId, input, actor) {
336
463
  const replay = await store.locked(orgId, async client => {
337
464
  await requireIdentity(client, orgId, actor, input.project);
@@ -169,8 +169,9 @@ function validateQueue(snapshot, cards) {
169
169
  return [...queue.values()];
170
170
  }
171
171
 
172
- function readiness(card, snapshot, queue) {
172
+ function readiness(card, snapshot, queue, allowBoard) {
173
173
  if (card.readySinceMs === null || card.readySinceMs > snapshot.asOfMs) return ['not_ready'];
174
+ if (allowBoard && card.depsBasis === 'board') return [];
174
175
  return card.deps.filter(dep => !snapshot.acceptedDependencies.some(accepted =>
175
176
  keyOf(dep) === keyOf(accepted) && (!queue.has(keyOf(dep))
176
177
  || queue.get(keyOf(dep)).revision === accepted.revision))).map(dep => `dependency_pending:${keyOf(dep)}`);
@@ -447,7 +448,8 @@ function solve(input, firstOnly) {
447
448
  const assessments = new Map();
448
449
  const schedules = new Map(snapshot.projectScheduling.map(project => [project.project, project]));
449
450
  for (const card of queue) {
450
- const reasons = readiness(card, snapshot, byKey);
451
+ const reasons = readiness(card, snapshot, byKey, !firstOnly && policy.modeByProject[card.project] === 'shadow');
452
+ if (firstOnly && card.depsBasis === 'board') reasons.push('board_projection_only');
451
453
  if (!schedules.has(card.project)) reasons.push('project_schedule_unknown');
452
454
  if (!Object.hasOwn(policy.modeByProject, card.project) || policy.modeByProject[card.project] === 'off') reasons.push('project_off');
453
455
  if (policy.kill.fleet || policy.kill.projects.includes(card.project)) reasons.push('kill_switch');