trantor 0.18.155 → 0.18.159

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.
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { projectBoardCards } from './board-bridge.mjs';
3
- import { createRolloutOperations, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
3
+ import { createRolloutOperations, createShadowScheduler, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
4
4
  import { AccountSchema, MachineSchema, SeatSchema, ModelEvidenceSchema, FitnessCellSchema,
5
5
  ProjectScheduleSchema, WorkCardSchema, PolicySchema } from './schemas.mjs';
6
6
  import { createAdmission, createFinancialOperations, AdmissionAuthoritySchema, WindowLedgerSchema,
@@ -82,6 +82,53 @@ export async function requireRole(client, orgId, actor, project, roles, wildcard
82
82
  export function createDispatcherOperations({ durableStore, orgId: configuredOrg, adapters = new Map(), clock = Date.now, source = '', advisorWorld,
83
83
  evidenceSources, dispatcherBridgeGrant = process.env.RELAY_DISPATCHER_BRIDGE_GRANT || null }) {
84
84
  const store = durableStore.createDispatcherStore();
85
+ function prepareEvidence(input) {
86
+ const request = RegisterEvidenceSchema.parse(input);
87
+ const record = EvidenceSchemas[request.kind].parse(request.record);
88
+ if (!sources[request.kind].includes(request.source) || request.observedAtMs > clock()
89
+ || request.expiresAtMs <= clock() || request.expiresAtMs <= request.observedAtMs) reject('evidence_unverified', 422);
90
+ return { request, record };
91
+ }
92
+ async function registerEvidenceWithClient(client, orgId, { request, record }, actor) {
93
+ const nowMs = clock();
94
+ const { approvedBy, grantId } = await evidenceActor(client, orgId, actor, request, nowMs);
95
+ if (request.expiresAtMs <= nowMs) reject('evidence_unverified', 422);
96
+ const previous = (await client.query(`SELECT * FROM dispatcher_evidence WHERE org_id=$1 AND kind=$2 AND id=$3
97
+ ORDER BY revision DESC LIMIT 1`, [orgId, request.kind, request.id])).rows[0];
98
+ const previousRevision = Number(previous?.revision || 0);
99
+ if (request.expectedRevision !== undefined && previousRevision !== request.expectedRevision) reject('evidence_stale');
100
+ if (record.id !== undefined && record.id !== request.id) reject('schema_invalid', 422);
101
+ if (grantId && previous) {
102
+ if (request.observedAtMs < Number(previous.observed_at_ms)) reject('evidence_stale');
103
+ if (request.observedAtMs === Number(previous.observed_at_ms)) {
104
+ if (previous.grant_id !== grantId || previous.registered_by !== approvedBy || previous.source !== request.source
105
+ || previous.source_ref !== request.sourceRef
106
+ || canonicalHash(observationContent(request.kind, previous.row)) !== canonicalHash(observationContent(request.kind, record))) reject('evidence_conflict');
107
+ return { id: request.id, revision: previousRevision, replayed: true };
108
+ }
109
+ }
110
+ if (request.kind === 'launch' && record.adapter.version !== CREW_ADAPTER_VERSION) reject('adapter_unqualified', 422);
111
+ if (request.kind === 'promotion') {
112
+ if (record.approvalId !== request.id) reject('evidence_unverified', 422);
113
+ const validated = await validateRolloutApproval(client, orgId, record);
114
+ await store.audit(client, orgId, { action: 'rollout-approved', atMs: clock(), actor: actor.pubkey,
115
+ approvalId: request.id, approvalHash: canonicalHash(record), ...validated });
116
+ }
117
+ const revision = previousRevision + 1;
118
+ await client.query(`INSERT INTO dispatcher_evidence
119
+ (org_id,kind,id,revision,source,source_ref,observed_at_ms,expires_at_ms,registered_by,registered_at_ms,hash,row,grant_id)
120
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
121
+ [orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
122
+ request.expiresAtMs, approvedBy, nowMs, canonicalHash(record), record, grantId]);
123
+ if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
124
+ ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
125
+ [orgId, record.accountId, record.windowId, revision, record]);
126
+ await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
127
+ ON CONFLICT(org_id) DO UPDATE SET revision=dispatcher_authority_state.revision+1`, [orgId]);
128
+ await store.audit(client, orgId, { action: 'evidence-registered', actor: approvedBy, approvedBy, grantId, atMs: nowMs,
129
+ kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
130
+ return grantId ? { id: request.id, revision, replayed: false } : { id: request.id, revision };
131
+ }
85
132
  const configuredGrant = text.nullable().parse(dispatcherBridgeGrant);
86
133
  const bridgeBinding = async (client, orgId, nowMs) => {
87
134
  const active = (await client.query(`SELECT grant_id FROM dispatcher_bridge_grants
@@ -305,49 +352,36 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
305
352
  });
306
353
  },
307
354
  async registerEvidence(orgId, input, actor) {
308
- const request = RegisterEvidenceSchema.parse(input);
309
- const record = EvidenceSchemas[request.kind].parse(request.record);
310
- if (!sources[request.kind].includes(request.source) || request.observedAtMs > clock()
311
- || request.expiresAtMs <= clock() || request.expiresAtMs <= request.observedAtMs) reject('evidence_unverified', 422);
355
+ const prepared = prepareEvidence(input);
356
+ return store.locked(orgId, client => registerEvidenceWithClient(client, orgId, prepared, actor));
357
+ },
358
+ async registerEvidenceBatch(orgId, entries, actor) {
359
+ if (!entries.length) return [];
312
360
  return store.locked(orgId, async client => {
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
317
- ORDER BY revision DESC LIMIT 1`, [orgId, request.kind, request.id])).rows[0];
318
- const previousRevision = Number(previous?.revision || 0);
319
- if (request.expectedRevision !== undefined && previousRevision !== request.expectedRevision) reject('evidence_stale');
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 };
361
+ const outcomes = [];
362
+ for (const { envelope, retryObservedAtMs } of entries) {
363
+ let input = envelope;
364
+ await client.query('SAVEPOINT bridge_envelope');
365
+ try {
366
+ let result;
367
+ try {
368
+ result = await registerEvidenceWithClient(client, orgId, prepareEvidence(input), actor);
369
+ } catch (error) {
370
+ if (retryObservedAtMs === undefined || !['evidence_conflict', 'evidence_stale'].includes(error.code)) throw error;
371
+ await client.query('ROLLBACK TO SAVEPOINT bridge_envelope');
372
+ input = { ...envelope, observedAtMs: retryObservedAtMs };
373
+ result = await registerEvidenceWithClient(client, orgId, prepareEvidence(input), actor);
374
+ }
375
+ outcomes.push({ result, observedAtMs: input.observedAtMs });
376
+ } catch (error) {
377
+ // Transient database failures retry/abort the whole transaction, never individual evidence.
378
+ if (!error.status && !(error instanceof z.ZodError) || error.status >= 500) throw error;
379
+ await client.query('ROLLBACK TO SAVEPOINT bridge_envelope');
380
+ outcomes.push({ error });
328
381
  }
382
+ await client.query('RELEASE SAVEPOINT bridge_envelope');
329
383
  }
330
- if (request.kind === 'launch' && record.adapter.version !== CREW_ADAPTER_VERSION) reject('adapter_unqualified', 422);
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)`,
341
- [orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
342
- request.expiresAtMs, approvedBy, nowMs, canonicalHash(record), record, grantId]);
343
- if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
344
- ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
345
- [orgId, record.accountId, record.windowId, revision, record]);
346
- await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
347
- ON CONFLICT(org_id) DO UPDATE SET revision=dispatcher_authority_state.revision+1`, [orgId]);
348
- await store.audit(client, orgId, { action: 'evidence-registered', actor: approvedBy, approvedBy, grantId, atMs: nowMs,
349
- kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
350
- return grantId ? { id: request.id, revision, replayed: false } : { id: request.id, revision };
384
+ return outcomes;
351
385
  });
352
386
  },
353
387
  async registerBridgeGrant(orgId, input, actor) {
@@ -455,6 +489,7 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
455
489
  },
456
490
  };
457
491
  Object.assign(service, createRolloutOperations({ service, requireRole, clock, advisorWorld }));
492
+ service.tickShadow = createShadowScheduler({ service, orgId: configuredOrg, clock });
458
493
  service.executor = { ...executor, kill(orgId, input, actor) {
459
494
  const control = KillSchema.parse(input);
460
495
  return control.enabled ? executor.kill(orgId, control, actor) : service.clearControl(orgId, control, actor);
@@ -84,11 +84,15 @@ export function deriveCandidates(snapshot, policy) {
84
84
  return [...candidates.values()].sort((a, b) => compare(a.id, b.id));
85
85
  }
86
86
 
87
- function priorFor(candidate, card, policy) {
87
+ function priorFor(candidate, card, policy, snapshot) {
88
+ if (candidate.model === null && !snapshot.seats.some(seat => seat.id === candidate.seatId
89
+ && seat.harness === candidate.harness && seat.model === null)) return null;
88
90
  const matching = policy.qualityPriors.filter(prior => prior.provider === candidate.provider
89
91
  && prior.model === candidate.model && prior.effort === candidate.effort
92
+ && (prior.harness === undefined || prior.harness === candidate.harness)
90
93
  && prior.difficulty === card.difficulty && ((kinds.has(card.kind) && prior.kind === card.kind) || prior.kind === '*'));
91
- return matching.sort((a, b) => Number(b.kind === card.kind) - Number(a.kind === card.kind)
94
+ return matching.sort((a, b) => Number(b.harness === candidate.harness) - Number(a.harness === candidate.harness)
95
+ || Number(b.kind === card.kind) - Number(a.kind === card.kind)
92
96
  || b.sourceDateMs - a.sourceDateMs || compare(canonicalJson(a), canonicalJson(b)))[0] ?? null;
93
97
  }
94
98
 
@@ -120,11 +124,13 @@ export function fitnessEstimate(candidate, card, snapshot, policy) {
120
124
  expectedMs: ceilRatio(BigInt(cell.medianDurationMs) * denominator, numerator) };
121
125
  }
122
126
  }
123
- const prior = priorFor(candidate, card, policy);
124
- if (!prior || prior.successPseudoCount === 0) return null;
125
- const numerator = BigInt(prior.successPseudoCount);
126
- const denominator = numerator + BigInt(prior.failurePseudoCount);
127
- return { poolLevel: 'prior', sampleCount: 0, exactSamples: exact?.judged ?? 0,
127
+ const prior = priorFor(candidate, card, policy, snapshot);
128
+ if (!prior) return null;
129
+ const measured = prior.judged !== undefined && prior.passes !== undefined;
130
+ if (!measured && prior.successPseudoCount === 0) return null;
131
+ const numerator = measured ? BigInt(prior.passes) + 1n : BigInt(prior.successPseudoCount);
132
+ const denominator = measured ? BigInt(prior.judged) + 2n : numerator + BigInt(prior.failurePseudoCount);
133
+ return { poolLevel: 'prior', sampleCount: measured ? prior.judged : 0, exactSamples: exact?.judged ?? 0,
128
134
  qualityProbabilityPpm: safeNumber(numerator * PPM / denominator),
129
135
  time: { numerator: BigInt(prior.durationMs) * denominator, denominator: numerator },
130
136
  expectedMs: ceilRatio(BigInt(prior.durationMs) * denominator, numerator) };
@@ -222,7 +228,7 @@ function rankCandidates(entries, policy) {
222
228
  }
223
229
 
224
230
  export function estimateCharges(candidate, card, snapshot, policy) {
225
- const prior = priorFor(candidate, card, policy);
231
+ const prior = priorFor(candidate, card, policy, snapshot);
226
232
  const account = snapshot.accounts.find(entry => entry.id === candidate.accountId);
227
233
  if (!prior || prior.rateAsOfMs > snapshot.asOfMs || !account?.windows.length) return null;
228
234
  const charges = [];
@@ -296,7 +302,7 @@ function assess(card, candidates, snapshot, policy, state) {
296
302
  excluded.push({ candidateId: candidate.id, reasons: [...new Set(reasons)].sort(compare) });
297
303
  continue;
298
304
  }
299
- const prior = priorFor(candidate, card, policy);
305
+ const prior = priorFor(candidate, card, policy, snapshot);
300
306
  const floor = policy.capabilityFloors.filter(entry => entry.difficulty === card.difficulty
301
307
  && [card.kind, 'code', '*'].includes(entry.kind));
302
308
  if (!floor.length || !prior || floor.some(entry => prior.capabilityScorePpm < entry.minimumScorePpm)) reasons.push('capability_floor');
@@ -0,0 +1,158 @@
1
+ import { z } from 'zod';
2
+ import { createPolicy, verifyPolicy, LEGACY_RATE_INPUTS } from './policy.mjs';
3
+ import { verifySnapshot, canonicalHash, canonicalJson } from './snapshot.mjs';
4
+ import { classifyAttemptVerification } from './acceptance.mjs';
5
+
6
+ const text = z.string().min(1).max(8192);
7
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
8
+ const SampleSchema = z.object({ id: text, project: text, ts: integer,
9
+ duration_ms: integer, tokens: integer.nullable(),
10
+ attempt: z.object({ id: text, provider: text, harness: text, model: text.nullable(),
11
+ difficulty: z.enum(['easy', 'medium', 'hard']), infraFailure: z.boolean() }).passthrough(),
12
+ usage: z.object({ priceVersion: text.nullable().optional() }).passthrough().optional(),
13
+ executionAttemptId: text.nullable().optional(),
14
+ }).passthrough();
15
+ export const PolicyDraftRequestSchema = z.strictObject({ project: text, version: text.optional() });
16
+ const key = row => JSON.stringify([row.provider, row.harness, row.model, row.difficulty]);
17
+ const median = values => {
18
+ const sorted = [...values].sort((a, b) => a - b);
19
+ const middle = Math.floor(sorted.length / 2);
20
+ return sorted.length % 2 ? sorted[middle] : Math.ceil(sorted[middle - 1] / 2 + sorted[middle] / 2);
21
+ };
22
+
23
+ function supportsModel(seat, model, snapshot, policy) {
24
+ if (seat.model === model) return true;
25
+ return model !== null && snapshot.models.some(entry => entry.invocation.status === 'ok'
26
+ && entry.invocation.value?.seatId === seat.id && entry.invocation.value?.model === model
27
+ && entry.invocation.observedAtMs !== null
28
+ && entry.invocation.observedAtMs <= snapshot.asOfMs
29
+ && snapshot.asOfMs - entry.invocation.observedAtMs <= policy.invocationTtlMs);
30
+ }
31
+
32
+ function collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances) {
33
+ const groups = new Map();
34
+ const seen = new Set();
35
+ const excluded = { invalid: 0, duplicate: 0, future: 0, unknownModel: 0, infrastructure: 0 };
36
+ for (const input of turns) {
37
+ const parsed = SampleSchema.safeParse(input);
38
+ if (!parsed.success) { excluded.invalid++; continue; }
39
+ const row = parsed.data;
40
+ if (row.project !== project) continue;
41
+ if (seen.has(row.id)) { excluded.duplicate++; continue; }
42
+ seen.add(row.id);
43
+ if (row.ts > nowMs) { excluded.future++; continue; }
44
+ if (row.attempt.model === 'unknown') { excluded.unknownModel++; continue; }
45
+ if (row.attempt.infraFailure) { excluded.infrastructure++; continue; }
46
+ const seat = bound.find(entry => entry.id === row.attempt.seat
47
+ && (entry.harness === row.attempt.harness || entry.harness === 'crew' && entry.agent === row.attempt.harness)
48
+ && supportsModel(entry, row.attempt.model, snapshot, policy));
49
+ const account = seat && snapshot.accounts.find(entry => entry.id === seat.accountId);
50
+ const identity = { provider: account?.provider ?? row.attempt.provider, harness: seat?.harness ?? row.attempt.harness,
51
+ model: row.attempt.model, difficulty: row.attempt.difficulty };
52
+ const groupKey = key(identity);
53
+ if (!groups.has(groupKey)) groups.set(groupKey, { ...identity, rows: [], tokens: [], durations: [], judged: 0, passes: 0, acceptances: new Set() });
54
+ const group = groups.get(groupKey);
55
+ group.rows.push(row);
56
+ if (row.tokens !== null) group.tokens.push(row.tokens);
57
+ if (row.duration_ms > 0) group.durations.push(row.duration_ms);
58
+ const acceptance = acceptances.find(record => record.attemptId === (row.executionAttemptId ?? row.attempt.id)
59
+ && record.atMs <= nowMs);
60
+ const verification = classifyAttemptVerification({ ...row.attempt, acceptance, executionAttemptId: row.executionAttemptId });
61
+ if (['accepted', 'failed'].includes(verification.status) && !group.acceptances.has(verification.acceptance.id)) {
62
+ group.acceptances.add(verification.acceptance.id);
63
+ group.judged++;
64
+ if (verification.status === 'accepted') group.passes++;
65
+ }
66
+ }
67
+ return { groups, excluded };
68
+ }
69
+
70
+ function ratesFor(group, policy) {
71
+ const prior = policy.qualityPriors.filter(row => row.provider === group.provider && row.model === group.model
72
+ && (row.harness === undefined || row.harness === group.harness) && row.difficulty === group.difficulty)
73
+ .sort((a, b) => b.rateAsOfMs - a.rateAsOfMs || canonicalJson(a).localeCompare(canonicalJson(b)))[0];
74
+ if (prior) return { rates: prior.rates, priceVersion: prior.priceVersion,
75
+ rateSource: `policy:${policy.version}:${prior.rateSource}`, rateAsOfMs: prior.rateAsOfMs };
76
+ const seed = LEGACY_RATE_INPUTS.find(row => row.model === group.model);
77
+ return seed ? { rates: seed.rates, priceVersion: null, rateSource: seed.rateSource, rateAsOfMs: seed.rateAsOfMs }
78
+ : { rates: { usdMicrosPerMTok: null, quotaMillionthsPerMTok: null }, priceVersion: null,
79
+ rateSource: 'unobserved: no active policy rate or legacy model rate', rateAsOfMs: 0 };
80
+ }
81
+
82
+ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turns, acceptances = [], project, version, createdBy, nowMs }) {
83
+ const policy = verifyPolicy(inputPolicy);
84
+ const snapshot = verifySnapshot(inputSnapshot);
85
+ if (snapshot.policyVersion !== policy.version) throw new Error('policy_stale');
86
+ const bound = snapshot.seats.filter(seat => (seat.project === project || seat.project === undefined)
87
+ && snapshot.accounts.some(account => account.id === seat.accountId && account.status === 'verified')
88
+ && snapshot.machines.some(machine => machine.id === seat.machine));
89
+ const roster = bound.map(seat => {
90
+ const entry = { seatId: seat.id, harness: seat.harness, enabled: true, host: seat.machine, model: seat.model,
91
+ adapterVersions: snapshot.machines.find(machine => machine.id === seat.machine).adapterVersions };
92
+ if (seat.agent !== undefined) entry.agent = seat.agent;
93
+ return entry;
94
+ });
95
+ const { groups, excluded } = collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances);
96
+ const qualityPriors = [];
97
+ const samples = [];
98
+ for (const group of [...groups.values()].sort((a, b) => key(a).localeCompare(key(b)))) {
99
+ const sampleCount = group.rows.length;
100
+ const priceVersions = [...new Set(group.rows.map(row => row.usage?.priceVersion ?? null))]
101
+ .sort((a, b) => String(a).localeCompare(String(b)));
102
+ const sample = { provider: group.provider, harness: group.harness, model: group.model, difficulty: group.difficulty,
103
+ sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
104
+ judged: group.judged, passes: group.passes, priceVersions,
105
+ recordedProviders: [...new Set(group.rows.map(row => row.attempt.provider))].sort(),
106
+ recordedHarnesses: [...new Set(group.rows.map(row => row.attempt.harness))].sort(),
107
+ medianTokens: group.tokens.length ? median(group.tokens) : null,
108
+ medianDurationMs: group.durations.length ? median(group.durations) : null };
109
+ const matchingSeats = bound.filter(seat => seat.harness === group.harness && supportsModel(seat, group.model, snapshot, policy)
110
+ && snapshot.accounts.find(account => account.id === seat.accountId)?.provider === group.provider);
111
+ const efforts = [...new Set(snapshot.models.filter(model => model.provider === group.provider && model.model === group.model
112
+ && matchingSeats.some(seat => model.accountId === null || model.accountId === seat.accountId))
113
+ .flatMap(model => model.efforts))].sort();
114
+ const reason = !group.tokens.length || !group.durations.length ? 'no_measurements'
115
+ : !matchingSeats.length ? 'no_bound_seat' : !efforts.length ? 'no_effort_evidence' : null;
116
+ samples.push({ ...sample, reason });
117
+ if (reason) continue;
118
+ const qualityPpm = Number((BigInt(group.passes) + 1n) * 1_000_000n / (BigInt(group.judged) + 2n));
119
+ const rates = ratesFor(group, policy);
120
+ for (const effort of efforts) qualityPriors.push({ provider: group.provider, harness: group.harness,
121
+ model: group.model, effort, kind: '*', difficulty: group.difficulty,
122
+ durationMs: sample.medianDurationMs, tokenEstimate: sample.medianTokens,
123
+ capabilityScorePpm: qualityPpm, successPseudoCount: group.passes, failurePseudoCount: group.judged - group.passes,
124
+ sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
125
+ judged: group.judged, passes: group.passes, priceVersions,
126
+ source: `turn-history:${project}:${canonicalHash(group.rows.map(row => row.id).sort())}; pooled across effort and kind`,
127
+ sourceDateMs: group.rows.reduce((latest, row) => Math.max(latest, row.ts), 0), ...rates });
128
+ }
129
+ const { hash: _hash, ...previous } = policy;
130
+ const draft = createPolicy({ ...previous, parentVersion: policy.version,
131
+ version: version || `${policy.version}-draft-${nowMs}`, createdAtMs: nowMs, createdBy,
132
+ roster: [...policy.roster.filter(row => !snapshot.seats.some(seat => seat.id === row.seatId
133
+ && (seat.project === project || seat.project === undefined))), ...roster],
134
+ qualityPriors: [...policy.qualityPriors.filter(prior => !bound.some(seat => (prior.harness === undefined || prior.harness === seat.harness)
135
+ && snapshot.accounts.find(account => account.id === seat.accountId)?.provider === prior.provider)), ...qualityPriors] });
136
+ if (draft.version === policy.version) throw new Error('draft_version_must_change');
137
+ return { policy: draft, summary: { project, snapshotId: snapshot.id, parentVersion: policy.version,
138
+ rosterEntries: roster.length, priorsDerived: qualityPriors.length, rowsRead: turns.length,
139
+ verifiedAcceptancesRead: acceptances.length, excluded, samples,
140
+ seatsWithoutSamples: roster.filter(seat => !qualityPriors.some(prior => prior.harness === seat.harness && prior.model === seat.model))
141
+ .map(seat => seat.seatId),
142
+ priorsWithUnknownRates: qualityPriors.filter(prior => Object.values(prior.rates).some(rate => rate === null)).length } };
143
+ }
144
+
145
+ export async function draftPolicyFromStore({ service, orgId, input, actor, requireRole, clock = Date.now }) {
146
+ const request = PolicyDraftRequestSchema.parse(input);
147
+ return service.store.locked(orgId, async client => {
148
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
149
+ const authority = await service.readAdvice(client, { orgId, request: { project: request.project } });
150
+ const turns = (await client.query("SELECT row FROM turns WHERE org_id=$1 AND row->>'project'=$2 ORDER BY ts,id",
151
+ [orgId, request.project])).rows.map(row => row.row);
152
+ const acceptances = (await client.query(`SELECT a.row FROM dispatcher_acceptances a
153
+ JOIN dispatcher_verification_jobs j ON j.org_id=a.org_id AND j.id=a.job_id AND j.acceptance_id=a.id
154
+ WHERE a.org_id=$1 AND j.project=$2 AND j.state IN ('passed','failed') ORDER BY (a.row->>'atMs')::bigint DESC,a.id`,
155
+ [orgId, request.project])).rows.map(row => row.row);
156
+ return draftPolicy({ ...authority, ...request, turns, acceptances, createdBy: actor.pubkey, nowMs: clock() });
157
+ });
158
+ }
@@ -11,6 +11,9 @@ import { executionRows, fenceExecution, KillSchema } from './executor.mjs';
11
11
  const text = z.string().min(1).max(8192);
12
12
  const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
13
13
  const DAY = 86400_000;
14
+ export const SHADOW_INTERVAL_MS = 30 * 60_000;
15
+ export const ShadowGrantSchema = z.strictObject({ grantId: text, projects: z.array(text).min(1).max(1000),
16
+ expiresAtMs: integer.nullable().optional(), revoked: z.boolean() });
14
17
  export const FIRST_WAVE_DRILLS = Array.from({ length: 25 }, (_, i) => `D${i + 1}`).filter(id => id !== 'D12');
15
18
  export const RolloutApprovalSchema = z.strictObject({ cohortId: text, testedSha: z.string().regex(/^[a-f0-9]{40}$/),
16
19
  baselineId: text, checks: z.strictObject({ crewMatrix: text, healthyCanaries: text, accountMappings: text, spendReconciliation: text }) });
@@ -22,16 +25,26 @@ const key = card => `${card.project}:${card.card}`;
22
25
  const sanitize = value => JSON.parse(redactKeys(JSON.stringify(value, (name, item) =>
23
26
  /secret|password|api.?key|(?:access|refresh).?token|authorization|^token$/i.test(name) ? '<redacted>' : item)));
24
27
 
25
- export function captureShadow({ snapshot, policy, cards, packages, world }) {
28
+ export function captureShadow({ snapshot, policy, cards, packages, world, project = cards[0]?.project }) {
26
29
  if (cards.some(card => policy.modeByProject[card.project] !== 'shadow')) reject('shadow_required');
27
30
  if (packages.length !== cards.length) reject('card_stale');
28
31
  const decision = plan({ snapshot, policy, cards });
29
32
  const legacy = advise({ packages }, world);
30
33
  const bindings = Object.fromEntries(Object.entries(world.roster).map(([executor, entry]) => {
31
- const seats = snapshot.seats.filter(seat => seat.harness === 'crew' && seat.id === entry.session);
32
- return [executor, seats.length === 1 ? { seatId: seats[0].id, harness: seats[0].harness, machine: seats[0].machine } : null];
34
+ const scoped = snapshot.seats.filter(seat => seat.harness === 'crew'
35
+ && (seat.project === undefined || seat.project === project));
36
+ const exact = scoped.filter(seat => seat.id === entry.session || seat.id === `${entry.session}:${project}`);
37
+ const matching = scoped.filter(seat => policy.roster.some(row => row.enabled
38
+ && row.seatId === seat.id && row.host === seat.machine && row.harness === seat.harness)
39
+ && [entry.cli, executor].includes(seat.agent)
40
+ && snapshot.accounts.some(account => account.id === seat.accountId && account.status === 'verified'
41
+ && account.provider === entry.provider));
42
+ const seats = matching.length ? matching : exact;
43
+ const identities = seats.map(seat => ({ seatId: seat.id, harness: seat.harness, machine: seat.machine }));
44
+ return [executor, identities.length === 1 ? { ...identities[0], matchBy: 'seat' }
45
+ : identities.length > 1 ? { matchBy: 'cli', agent: executor, seats: identities } : null];
33
46
  }));
34
- const mapping = { version: 1, bindings };
47
+ const mapping = { version: 2, bindings };
35
48
  const policyFingerprint = rolloutPolicyHash(policy);
36
49
  const companion = sanitize({ snapshotId: snapshot.id, policyVersion: policy.version,
37
50
  input: { packages }, world, output: legacy, mapping: { ...mapping, hash: canonicalHash(mapping) } });
@@ -40,7 +53,7 @@ export function captureShadow({ snapshot, policy, cards, packages, world }) {
40
53
  const old = legacy.routing[index];
41
54
  const assignment = decision.assignments.find(a => key(a) === key(card));
42
55
  const candidate = assignment?.candidate || null;
43
- const binding = ['orchestrator', 'scrooge'].includes(old.executor) ? null : bindings[old.executor];
56
+ const binding = ['orchestrator', 'scrooge', 'sub-agent'].includes(old.executor) ? null : bindings[old.executor];
44
57
  const comparable = Boolean(binding);
45
58
  const costByAccount = new Map();
46
59
  for (const charge of assignment?.estimates || []) if (charge.unit === 'usdMicros') {
@@ -49,7 +62,11 @@ export function captureShadow({ snapshot, policy, cards, packages, world }) {
49
62
  const plannerUsd = costByAccount.size ? [...costByAccount.values()].reduce((a, b) => a + b, 0) / 1_000_000 : null;
50
63
  const differences = [];
51
64
  if (comparable) {
52
- for (const field of ['seatId', 'harness', 'machine']) if (binding[field] !== candidate?.[field]) differences.push(field);
65
+ if (binding.matchBy === 'cli') {
66
+ if (!binding.seats.some(seat => ['seatId', 'harness', 'machine'].every(field => seat[field] === candidate?.[field]))) differences.push('cli');
67
+ } else {
68
+ for (const field of ['seatId', 'harness', 'machine']) if (binding[field] !== candidate?.[field]) differences.push(field);
69
+ }
53
70
  if (old.model != null && old.model !== candidate?.model) differences.push('model');
54
71
  const effort = z.string().safeParse(old.effort?.params?.reasoning_effort ?? old.effort);
55
72
  if (effort.success && effort.data !== candidate?.effort) differences.push('effort');
@@ -148,21 +165,73 @@ export function createRolloutOperations({ service, requireRole, clock, advisorWo
148
165
  for (const { id } of live) await fenceExecution(client, orgId, await executionRows(client, orgId, id), reason, clock());
149
166
  return live.length;
150
167
  };
168
+ const capture = async (client, orgId, request, actor, provenance = {}) => {
169
+ const authority = await service.readAdvice(client, { orgId, request });
170
+ if (authority.policy.modeByProject[request.project] !== 'shadow') reject('shadow_required');
171
+ const cards = authority.snapshot.readyQueue.filter(c => c.project === request.project);
172
+ const tasks = (await client.query('SELECT id,title FROM tasks WHERE org_id=$1 AND project=$2', [orgId, request.project])).rows;
173
+ const packages = cards.map(card => {
174
+ const task = tasks.find(t => Number(t.id) === card.card);
175
+ if (!task) reject('card_stale');
176
+ return { title: task.title, difficulty: card.difficulty, kind: card.kind };
177
+ });
178
+ const captured = captureShadow({ ...authority, cards, packages, world: await advisorWorld(request.project), project: request.project });
179
+ return audit(client, orgId, 'rollout-shadow', { project: request.project, ...captured, ...provenance }, actor);
180
+ };
151
181
  return {
182
+ async registerShadowGrant(orgId, input, actor) {
183
+ const grant = ShadowGrantSchema.parse(input);
184
+ return store.locked(orgId, async client => {
185
+ await owner(client, orgId, actor);
186
+ await client.query(`INSERT INTO dispatcher_shadow_grants VALUES($1,$2,$3,$4)
187
+ ON CONFLICT(org_id,grant_id) DO UPDATE SET approved_by=EXCLUDED.approved_by,row=EXCLUDED.row`,
188
+ [orgId, grant.grantId, actor.pubkey, grant]);
189
+ await audit(client, orgId, 'shadow-grant-registered', { ...grant, approvedBy: actor.pubkey }, actor);
190
+ return grant;
191
+ });
192
+ },
193
+ async shadowProjects(orgId) {
194
+ const policy = (await store.pool.query(`SELECT p.row FROM dispatcher_authority_state a
195
+ JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`, [orgId])).rows[0]?.row;
196
+ return Object.entries(policy?.modeByProject || {}).filter(([, mode]) => mode === 'shadow')
197
+ .map(([project]) => ({ project, policyVersion: policy.version }));
198
+ },
199
+ async scheduledShadowTick(orgId, project) {
200
+ return store.locked(orgId, async client => {
201
+ const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
202
+ JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`, [orgId])).rows[0]?.row;
203
+ if (policy?.modeByProject[project] !== 'shadow') return { skipped: 'shadow_required' };
204
+ const grants = (await client.query('SELECT * FROM dispatcher_shadow_grants WHERE org_id=$1 ORDER BY grant_id', [orgId])).rows;
205
+ let reason = grants.length ? 'shadow_grant_wrong_project' : 'shadow_grant_missing';
206
+ let selected;
207
+ for (const grant of grants.filter(g => g.row.projects.includes(project))) {
208
+ if (grant.row.revoked) { reason = 'shadow_grant_revoked'; continue; }
209
+ if (grant.row.expiresAtMs != null && grant.row.expiresAtMs <= clock()) { reason = 'shadow_grant_expired'; continue; }
210
+ try { await owner(client, orgId, { pubkey: grant.approved_by }); }
211
+ catch (error) {
212
+ if (error.code !== 'permission_denied') throw error;
213
+ reason = 'shadow_grant_owner_revoked';
214
+ continue;
215
+ }
216
+ selected = grant;
217
+ break;
218
+ }
219
+ if (!selected) return { skipped: reason };
220
+ const last = (await client.query(`SELECT at_ms FROM dispatcher_audit WHERE org_id=$1
221
+ AND row->>'action'='rollout-shadow' AND row->>'project'=$2 ORDER BY at_ms DESC LIMIT 1`, [orgId, project])).rows[0];
222
+ const intervalMs = policy.shadowIntervalMs ?? SHADOW_INTERVAL_MS;
223
+ const nextAtMs = last ? Number(last.at_ms) + intervalMs : clock();
224
+ if (nextAtMs > clock()) return { nextAtMs };
225
+ const tick = await capture(client, orgId, { project }, { pubkey: selected.approved_by },
226
+ { approvedBy: selected.approved_by, grantId: selected.grant_id });
227
+ return { tickId: tick.id, nextAtMs: tick.atMs + intervalMs };
228
+ });
229
+ },
152
230
  async shadowTick(orgId, input, actor) {
153
231
  const request = z.strictObject({ project: text, snapshotId: text.optional() }).parse(input);
154
232
  return store.locked(orgId, async client => {
155
233
  await owner(client, orgId, actor);
156
- const authority = await service.readAdvice(client, { orgId, request });
157
- const cards = authority.snapshot.readyQueue.filter(c => c.project === request.project);
158
- const tasks = (await client.query('SELECT id,title FROM tasks WHERE org_id=$1 AND project=$2', [orgId, request.project])).rows;
159
- const packages = cards.map(card => {
160
- const task = tasks.find(t => Number(t.id) === card.card);
161
- if (!task) reject('card_stale');
162
- return { title: task.title, difficulty: card.difficulty, kind: card.kind };
163
- });
164
- const captured = captureShadow({ ...authority, cards, packages, world: await advisorWorld(request.project) });
165
- return audit(client, orgId, 'rollout-shadow', { project: request.project, ...captured }, actor);
234
+ return capture(client, orgId, request, actor);
166
235
  });
167
236
  },
168
237
  async rolloutReport(orgId, input, actor) {
@@ -355,3 +424,48 @@ async function storedCohort(client, orgId, project, period) {
355
424
  return acceptedCohort(rows.map(row => ({ attempt: row.attempt, policy: row.policy,
356
425
  card: row.snapshot.readyQueue.find(c => key(c) === key(row.attempt)) })), period);
357
426
  }
427
+
428
+ export function createShadowScheduler({ service, orgId, clock = Date.now, log = console.error }) {
429
+ const states = new Map();
430
+ let running = false;
431
+ let discoveryRetryAtMs = 0;
432
+ let discoveryFailures = 0;
433
+ let discoveryReason = null;
434
+ const backoff = failures => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
435
+ return async () => {
436
+ if (running || clock() < discoveryRetryAtMs) return;
437
+ running = true;
438
+ try {
439
+ const projects = await service.shadowProjects(orgId);
440
+ discoveryFailures = 0;
441
+ discoveryReason = null;
442
+ const active = new Set(projects.map(entry => entry.project));
443
+ for (const project of states.keys()) if (!active.has(project)) states.delete(project);
444
+ for (const { project, policyVersion } of projects) {
445
+ let state = states.get(project);
446
+ if (!state || state.policyVersion !== policyVersion) {
447
+ state = { policyVersion, nextAtMs: 0, failures: 0, reason: null };
448
+ states.set(project, state);
449
+ }
450
+ if (clock() < state.nextAtMs) continue;
451
+ try {
452
+ const result = await service.scheduledShadowTick(orgId, project);
453
+ if (result.skipped && state.reason !== result.skipped) log(`[trantor] shadow ${project}: ${result.skipped}`);
454
+ state.reason = result.skipped || null;
455
+ state.failures = 0;
456
+ state.nextAtMs = result.nextAtMs ?? clock() + 30_000;
457
+ } catch (error) {
458
+ const reason = error.code || 'shadow_tick_failed';
459
+ if (state.reason !== reason) log(`[trantor] shadow ${project}: ${reason}`);
460
+ state.reason = reason;
461
+ state.nextAtMs = clock() + backoff(++state.failures);
462
+ }
463
+ }
464
+ } catch (error) {
465
+ const reason = error.code || 'shadow_schedule_failed';
466
+ if (discoveryReason !== reason) log(`[trantor] shadow schedule: ${reason}`);
467
+ discoveryReason = reason;
468
+ discoveryRetryAtMs = clock() + backoff(++discoveryFailures);
469
+ } finally { running = false; }
470
+ };
471
+ }
@@ -104,6 +104,7 @@ export const MachineSchema = object({
104
104
  });
105
105
  export const SeatSchema = object({
106
106
  project: text.optional(), accountBindingReason: nullable(text).optional(),
107
+ agent: text.optional(),
107
108
  id: text, machine: text, accountId: nullable(text), harness: text, model: nullable(text),
108
109
  busy: z.boolean(), lastBeatMs: nullable(integer), lastTurnMs: nullable(integer),
109
110
  });
@@ -124,18 +125,24 @@ export const AccountOverrideSchema = object({
124
125
  expiresAtMs: integer, approvalId: text, reason: text,
125
126
  });
126
127
  export const QualityPriorSchema = object({
127
- provider: text, model: text, effort: text, kind: text, difficulty: text,
128
+ provider: text, model: nullable(text), effort: text, kind: text, difficulty: text,
129
+ harness: text.optional(), sampleCount: integer.optional(), tokenSampleCount: integer.optional(),
130
+ durationSampleCount: integer.optional(), judged: integer.optional(), passes: integer.optional(),
131
+ priceVersions: list(nullable(text)).optional(),
128
132
  durationMs: positive, tokenEstimate: integer, capabilityScorePpm: ppm,
129
133
  successPseudoCount: integer, failurePseudoCount: integer,
130
134
  priceVersion: nullable(text), source: text, sourceDateMs: integer,
131
135
  rates: object({ usdMicrosPerMTok: nullable(integer), quotaMillionthsPerMTok: nullable(integer) }),
132
136
  rateSource: text, rateAsOfMs: integer,
133
- });
137
+ }).refine(prior => (prior.judged === undefined) === (prior.passes === undefined)
138
+ && (prior.judged === undefined || prior.passes <= prior.judged), { message: 'Measured quality requires passes <= judged' });
134
139
  export const PolicySchema = object({
135
140
  schemaVersion: version, version: text, parentVersion: nullable(text), hash: text,
136
141
  createdAtMs: integer, createdBy: text, plannerVersion: text,
137
142
  modeByProject: record(z.enum(['off', 'shadow', 'admit'])),
138
- roster: list(object({ seatId: text, harness: text, enabled: z.boolean(), host: text })),
143
+ shadowIntervalMs: positive.optional(),
144
+ roster: list(object({ seatId: text, harness: text, enabled: z.boolean(), host: text,
145
+ model: nullable(text).optional(), adapterVersions: strings.optional(), agent: text.optional() })),
139
146
  placementByKind: record(text), discoveryTtlMs: positive, invocationTtlMs: positive,
140
147
  balanceTtlMs: positive, machineTtlMs: positive, heartbeatMs: positive, leaseSilenceMs: positive,
141
148
  reserveFractionPpm: ppm, prepaidReserveFloorMicros: integer,
@@ -191,6 +191,11 @@ CREATE TABLE IF NOT EXISTS dispatcher_bridge_grants (
191
191
  PRIMARY KEY(org_id, grant_id),
192
192
  FOREIGN KEY(org_id, approved_by) REFERENCES identities(org_id, pubkey)
193
193
  );
194
+ CREATE TABLE IF NOT EXISTS dispatcher_shadow_grants (
195
+ org_id TEXT NOT NULL, grant_id TEXT NOT NULL, approved_by TEXT NOT NULL,
196
+ row JSONB NOT NULL, PRIMARY KEY(org_id, grant_id),
197
+ FOREIGN KEY(org_id, approved_by) REFERENCES identities(org_id, pubkey)
198
+ );
194
199
  CREATE TABLE IF NOT EXISTS dispatcher_evidence (
195
200
  org_id TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, revision BIGINT NOT NULL CHECK(revision>0),
196
201
  source TEXT NOT NULL, source_ref TEXT NOT NULL, observed_at_ms BIGINT NOT NULL,
@@ -329,3 +334,30 @@ export function createDispatcherStore({ pool, transaction }) {
329
334
  },
330
335
  };
331
336
  }
337
+
338
+ // Busy ticks leave readiness alone: every admission still obtains its own bounded lock.
339
+ export function createDispatcherTick({ dispatcher, clock = Date.now, log = console.error }) {
340
+ let ticking = false;
341
+ let busySince = null;
342
+ return async () => {
343
+ if (ticking) return;
344
+ ticking = true;
345
+ try {
346
+ await dispatcher.tick();
347
+ if (busySince !== null) {
348
+ log(`[trantor] dispatcher contention recovered after ${clock() - busySince}ms`);
349
+ busySince = null;
350
+ }
351
+ } catch (error) {
352
+ if (error.code === 'admission_busy') {
353
+ if (busySince === null) {
354
+ busySince = clock();
355
+ log('[trantor] dispatcher contention started: admission_busy');
356
+ }
357
+ } else {
358
+ dispatcher.store.closeAdmission();
359
+ log(`[trantor] dispatcher unavailable: ${error.code || 'store_failure'}`);
360
+ }
361
+ } finally { ticking = false; }
362
+ };
363
+ }