trantor 0.18.149 → 0.18.152

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }
@@ -0,0 +1,283 @@
1
+ import { bindAccounts } 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, nowMs, policy }) {
180
+ const evidence = [];
181
+ for (const row of Array.isArray(rows) ? rows : []) {
182
+ const id = text(row?.session, 200);
183
+ const machine = text(row?.machine, 60);
184
+ const harness = text(row?.llm, 200);
185
+ const observedAtMs = timestamp(row?.lastSeen);
186
+ if (!id || !machine || !harness || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
187
+ const lastTurnMs = timestamp(row?.lastTurn?.ts);
188
+ evidence.push({ kind: 'seat', id, source: 'presence', sourceRef: `presence:${id}:${observedAtMs}`,
189
+ observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
190
+ record: { id, machine, accountId: null, harness, model: text(row.model, 512) || null,
191
+ busy: row.online === true && /^(working|busy)$/i.test(text(row.status, 100)),
192
+ lastBeatMs: observedAtMs, lastTurnMs } });
193
+ }
194
+ return evidence;
195
+ }
196
+
197
+ function modelEnvelope({ provider, model, observedAtMs, expiresAtMs, nowMs, catalog }) {
198
+ const details = model ? lookup(model, catalog) : null;
199
+ const source = `discovery:${provider}`;
200
+ const unknown = (field, value = null) => observation({ value, observedAtMs: null, receivedAtMs: nowMs,
201
+ source, status: 'unknown', reason: `no fresh ${field} observation` });
202
+ return { kind: 'model', id: `model:${provider}:${model || 'unknown'}`, source: 'discovery-catalog',
203
+ sourceRef: `discovery:${provider}:${model || 'unknown'}:${observedAtMs}`, observedAtMs, expiresAtMs,
204
+ record: { provider, model, accountId: null, catalog: unknown('catalog'),
205
+ entitlement: unknown('entitlement'), invocation: unknown('invocation'), liveUse: null,
206
+ capabilities: details?.found && Array.isArray(details.modalities) ? details.modalities.map(value => text(value, 100)) : [],
207
+ efforts: details?.found && details.effort ? Object.keys(details.effort).sort() : [], breakerId: null } };
208
+ }
209
+
210
+ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
211
+ const models = new Map();
212
+ for (const row of Array.isArray(rows) ? rows : []) {
213
+ const provider = text(row?.provider, 200);
214
+ if (!provider) continue;
215
+ for (const item of Array.isArray(row.models) ? row.models : []) {
216
+ const observedAtMs = timestamp(Date.parse(item?.checkedAt));
217
+ const model = item?.id == null ? null : text(item.id, 512) || null;
218
+ if (!fresh(observedAtMs, nowMs, policy.discoveryTtlMs)) continue;
219
+ const key = `${provider}\0${model || ''}`;
220
+ const envelope = modelEnvelope({ provider, model, observedAtMs,
221
+ expiresAtMs: observedAtMs + policy.discoveryTtlMs, nowMs, catalog });
222
+ const known = ['listed', 'entitled', 'callable'].includes(item.state);
223
+ envelope.record.catalog = observation({ value: known ? true : null, observedAtMs, receivedAtMs: nowMs,
224
+ source: item.source, status: known ? 'ok' : 'unknown', reason: item.reason, sourceRevision: item.checkedAt });
225
+ if (['entitled', 'callable'].includes(item.state)) {
226
+ envelope.record.entitlement = observation({ value: true, observedAtMs, receivedAtMs: nowMs,
227
+ source: item.source, status: 'ok', reason: item.reason, sourceRevision: item.checkedAt });
228
+ }
229
+ models.set(key, envelope);
230
+ }
231
+ }
232
+ for (const seat of Array.isArray(seats) ? seats : []) {
233
+ const model = text(seat?.lastTurn?.model, 512);
234
+ const seatId = text(seat?.session, 200);
235
+ const harness = text(seat?.llm, 200);
236
+ const observedAtMs = timestamp(seat?.lastTurn?.ts);
237
+ if (!model || !seatId || !harness || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
238
+ const provider = model.includes('/') ? text(model.split('/')[0], 200) : harness;
239
+ const key = `${provider}\0${model}`;
240
+ const envelope = models.get(key) || modelEnvelope({ provider, model, observedAtMs,
241
+ expiresAtMs: observedAtMs + policy.invocationTtlMs, nowMs, catalog });
242
+ envelope.record.invocation = observation({ value: { model, seatId, harness }, observedAtMs,
243
+ receivedAtMs: nowMs, source: 'presence:last-turn', status: 'ok', sourceRevision: observedAtMs });
244
+ envelope.observedAtMs = Math.max(envelope.observedAtMs, observedAtMs);
245
+ envelope.expiresAtMs = Math.max(envelope.expiresAtMs, observedAtMs + policy.invocationTtlMs);
246
+ envelope.sourceRef = `presence:${seatId}:${observedAtMs}`;
247
+ models.set(key, envelope);
248
+ }
249
+ return [...models.values()];
250
+ }
251
+
252
+ export function buildEvidence({ balances = [], machines = [], seats = [], discovery = [], orgId, nowMs,
253
+ policy = DEFAULT_POLICY, catalog = loadCatalog() }) {
254
+ const presentSeats = presenceMachines({ rows: machines, seats });
255
+ return [
256
+ ...balanceEvidence({ snapshots: balances, orgId, nowMs, policy }),
257
+ ...machineEvidence({ rows: machines, seats: presentSeats, nowMs, policy }),
258
+ ...seatEvidence({ rows: presentSeats, nowMs, policy }),
259
+ ...modelEvidence({ rows: discovery, seats: presentSeats, nowMs, policy, catalog }),
260
+ ];
261
+ }
262
+
263
+ export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
264
+ clock = Date.now, policy = DEFAULT_POLICY, catalog = loadCatalog() }) {
265
+ if (!service || !orgId || !grantId || !sources) {
266
+ throw new TypeError('evidence bridge requires service, orgId, grant and sources');
267
+ }
268
+ async function tick() {
269
+ const nowMs = clock();
270
+ const [balances, machines, seats, discovery] = await Promise.all([
271
+ sources.balances(), sources.machines(), sources.seats(), sources.discovery(),
272
+ ]);
273
+ const pending = buildEvidence({ balances, machines, seats, discovery, orgId, nowMs, policy, catalog })
274
+ .filter(envelope => envelope.expiresAtMs > clock());
275
+ let written = 0;
276
+ for (const envelope of pending) {
277
+ const result = await service.registerEvidence(orgId, envelope, { grant: grantId });
278
+ if (!result.replayed) written++;
279
+ }
280
+ return { observed: pending.length, written, skipped: pending.length - written };
281
+ }
282
+ return { tick, build: input => buildEvidence({ ...input, orgId, nowMs: clock(), policy, catalog }) };
283
+ }
@@ -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) {
@@ -262,24 +309,59 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
262
309
  if (!sources[request.kind].includes(request.source) || request.observedAtMs > clock()
263
310
  || request.expiresAtMs <= clock() || request.expiresAtMs <= request.observedAtMs) reject('evidence_unverified', 422);
264
311
  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
312
+ const nowMs = clock();
313
+ const { approvedBy, grantId } = await evidenceActor(client, orgId, actor, request, nowMs);
314
+ if (request.expiresAtMs <= nowMs) reject('evidence_unverified', 422);
315
+ const previous = (await client.query(`SELECT * FROM dispatcher_evidence WHERE org_id=$1 AND kind=$2 AND id=$3
267
316
  ORDER BY revision DESC LIMIT 1`, [orgId, request.kind, request.id])).rows[0];
268
- if (Number(previous?.revision || 0) !== request.expectedRevision) reject('evidence_stale');
317
+ const previousRevision = Number(previous?.revision || 0);
318
+ if (request.expectedRevision !== undefined && previousRevision !== request.expectedRevision) reject('evidence_stale');
269
319
  if (record.id !== undefined && record.id !== request.id) reject('schema_invalid', 422);
320
+ if (grantId && previous) {
321
+ if (request.observedAtMs < Number(previous.observed_at_ms)) reject('evidence_stale');
322
+ if (request.observedAtMs === Number(previous.observed_at_ms)) {
323
+ if (previous.grant_id !== grantId || previous.registered_by !== approvedBy || previous.source !== request.source
324
+ || previous.source_ref !== request.sourceRef
325
+ || canonicalHash(observationContent(request.kind, previous.row)) !== canonicalHash(observationContent(request.kind, record))) reject('evidence_conflict');
326
+ return { id: request.id, revision: previousRevision, replayed: true };
327
+ }
328
+ }
270
329
  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)`,
330
+ if (request.kind === 'promotion') {
331
+ if (record.approvalId !== request.id) reject('evidence_unverified', 422);
332
+ const validated = await validateRolloutApproval(client, orgId, record);
333
+ await store.audit(client, orgId, { action: 'rollout-approved', atMs: clock(), actor: actor.pubkey,
334
+ approvalId: request.id, approvalHash: canonicalHash(record), ...validated });
335
+ }
336
+ const revision = previousRevision + 1;
337
+ await client.query(`INSERT INTO dispatcher_evidence
338
+ (org_id,kind,id,revision,source,source_ref,observed_at_ms,expires_at_ms,registered_by,registered_at_ms,hash,row,grant_id)
339
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
273
340
  [orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
274
- request.expiresAtMs, actor.pubkey, clock(), canonicalHash(record), record]);
341
+ request.expiresAtMs, approvedBy, nowMs, canonicalHash(record), record, grantId]);
275
342
  if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
276
343
  ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
277
344
  [orgId, record.accountId, record.windowId, revision, record]);
278
345
  await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
279
346
  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(),
347
+ await store.audit(client, orgId, { action: 'evidence-registered', actor: approvedBy, approvedBy, grantId, atMs: nowMs,
281
348
  kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
282
- return { id: request.id, revision };
349
+ return grantId ? { id: request.id, revision, replayed: false } : { id: request.id, revision };
350
+ });
351
+ },
352
+ async registerBridgeGrant(orgId, input, actor) {
353
+ const request = BridgeGrantSchema.parse(input);
354
+ return store.locked(orgId, async client => {
355
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
356
+ const nowMs = clock();
357
+ if (!request.revoked && request.expiresAtMs != null && request.expiresAtMs <= nowMs) reject('grant_expired', 422);
358
+ const row = { ...request, expiresAtMs: request.expiresAtMs ?? null, approvedBy: actor.pubkey };
359
+ await client.query(`INSERT INTO dispatcher_bridge_grants VALUES($1,$2,$3,$4,$5,$6)
360
+ ON CONFLICT(org_id,grant_id) DO UPDATE SET approved_by=EXCLUDED.approved_by,expires_at_ms=EXCLUDED.expires_at_ms,
361
+ revoked_at_ms=EXCLUDED.revoked_at_ms,row=EXCLUDED.row`,
362
+ [orgId, row.grantId, row.approvedBy, row.expiresAtMs, row.revoked ? nowMs : null, row]);
363
+ await store.audit(client, orgId, { action: 'bridge-grant-registered', actor: actor.pubkey, atMs: nowMs, ...row });
364
+ return row;
283
365
  });
284
366
  },
285
367
  async registerCollector(orgId, input, actor) {
@@ -304,6 +386,12 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
304
386
  if ((current?.policy_version || null) !== request.expectedVersion) reject('policy_stale');
305
387
  if (Object.values(policy.modeByProject).includes('admit')) {
306
388
  const approval = await evidence(client, orgId, 'promotion', request.approvalId);
389
+ const validated = await service.checkApproval(client, orgId, approval, request.approvalId);
390
+ const cohort = (await client.query("SELECT row FROM dispatcher_audit WHERE org_id=$1 AND row->>'action'='rollout-frozen' AND row->>'id'=$2",
391
+ [orgId, validated.cohortId])).rows[0]?.row;
392
+ if (cohort?.summary.policyFingerprint !== rolloutPolicyHash(policy)) reject('shadow_policy_mismatch', 403);
393
+ if (policy.roster.some(r => r.enabled && r.harness !== 'crew')) reject('promotion_scope_invalid', 403);
394
+ if (Object.entries(policy.modeByProject).some(([project, mode]) => mode === 'admit' && project !== cohort?.project)) reject('promotion_scope_invalid', 403);
307
395
  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
396
  if (approval.policyHash !== policy.hash || required.some(id => !approval.drills.some(d => d.id === id))) reject('promotion_unapproved', 403);
309
397
  }
@@ -322,16 +410,54 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
322
410
  async recover(orgId) {
323
411
  const complete = (await store.pool.query(`SELECT completed_at_ms FROM dispatcher_migrations WHERE id='dispatcher-v1'`)).rows[0];
324
412
  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 });
413
+ const authority = await store.locked(orgId, client => snapshot(client, orgId, clock()));
414
+ return executor.recover(orgId, { snapshotId: authority.snapshot.id, policyVersion: authority.policy.version });
327
415
  },
328
416
  async tick() {
417
+ await store.locked(configuredOrg, async client => {
418
+ const binding = await bridgeBinding(client, configuredOrg, clock());
419
+ if (!binding.grant) return;
420
+ const grant = (await client.query('SELECT row FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
421
+ [configuredOrg, binding.grant])).rows[0]?.row;
422
+ if (!grant?.kinds.includes('card') || !grant.sources.includes('board')) return;
423
+ const actor = await evidenceActor(client, configuredOrg, { grant: binding.grant }, { kind: 'card', source: 'board' }, clock());
424
+ const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
425
+ 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;
426
+ if (!policy) reject('policy_missing', 503);
427
+ const changed = await projectBoardCards(client, configuredOrg, verifyPolicy(policy));
428
+ if (changed) await store.audit(client, configuredOrg, { action: 'board-projected', actor: actor.approvedBy,
429
+ grantId: binding.grant, atMs: clock(), changed });
430
+ });
431
+ if (evidenceSources) {
432
+ const binding = await store.locked(configuredOrg, async client => {
433
+ const selected = await bridgeBinding(client, configuredOrg, clock());
434
+ if (!selected.grant) return selected;
435
+ const grant = (await client.query('SELECT row FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
436
+ [configuredOrg, selected.grant])).rows[0]?.row;
437
+ if (grant?.kinds.every(kind => kind === 'card')) return { ...selected, grant: null };
438
+ const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
439
+ JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`,
440
+ [configuredOrg])).rows[0]?.row;
441
+ if (!policy) reject('policy_missing', 503);
442
+ return { ...selected, policy: verifyPolicy(policy) };
443
+ });
444
+ if (binding.grant) {
445
+ const { createEvidenceBridge } = await import('./evidence-bridge.mjs');
446
+ await createEvidenceBridge({ service, orgId: configuredOrg, grant: binding.grant,
447
+ sources: evidenceSources, clock, policy: binding.policy }).tick();
448
+ }
449
+ }
329
450
  await verifier.reconcile(configuredOrg);
330
451
  await finance.expireAsks(configuredOrg);
331
452
  await executor.expire(configuredOrg);
332
453
  if (adapters.size && store.isReady(configuredOrg)) await executor.runOnce(configuredOrg, `hub:${process.pid}`);
333
454
  },
334
455
  };
456
+ Object.assign(service, createRolloutOperations({ service, requireRole, clock, advisorWorld }));
457
+ service.executor = { ...executor, kill(orgId, input, actor) {
458
+ const control = KillSchema.parse(input);
459
+ return control.enabled ? executor.kill(orgId, control, actor) : service.clearControl(orgId, control, actor);
460
+ } };
335
461
  service.admission = { ...admission, async dispatch(orgId, input, actor) {
336
462
  const replay = await store.locked(orgId, async client => {
337
463
  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');