trantor 0.18.157 → 0.18.160

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.
@@ -72,7 +72,11 @@ export function deriveCandidates(snapshot, policy) {
72
72
  for (const modelId of identities) {
73
73
  if (modelId === null && (seat.model !== null || model.liveUse?.seatId !== seat.id
74
74
  || model.liveUse.harness !== seat.harness)) continue;
75
- for (const effort of model.efforts) {
75
+ const efforts = new Set(model.efforts);
76
+ if (policy.qualityPriors.some(prior => prior.provider === account.provider && prior.model === modelId
77
+ && prior.effort === 'default' && (prior.harness === undefined || prior.harness === seat.harness)
78
+ && (prior.seatId === undefined || prior.seatId === seat.id))) efforts.add('default');
79
+ for (const effort of efforts) {
76
80
  const identity = { provider: account.provider, model: modelId, effort, accountId: account.id,
77
81
  harness: seat.harness, machine: seat.machine, seatId: seat.id };
78
82
  const candidate = { id: candidateId(identity), ...identity };
@@ -84,11 +88,16 @@ export function deriveCandidates(snapshot, policy) {
84
88
  return [...candidates.values()].sort((a, b) => compare(a.id, b.id));
85
89
  }
86
90
 
87
- function priorFor(candidate, card, policy) {
91
+ function priorFor(candidate, card, policy, snapshot) {
92
+ if (candidate.model === null && !snapshot.seats.some(seat => seat.id === candidate.seatId
93
+ && seat.harness === candidate.harness && seat.model === null)) return null;
88
94
  const matching = policy.qualityPriors.filter(prior => prior.provider === candidate.provider
89
95
  && prior.model === candidate.model && prior.effort === candidate.effort
96
+ && (prior.seatId === undefined || prior.seatId === candidate.seatId)
97
+ && (prior.harness === undefined || prior.harness === candidate.harness)
90
98
  && 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)
99
+ return matching.sort((a, b) => Number(b.harness === candidate.harness) - Number(a.harness === candidate.harness)
100
+ || Number(b.kind === card.kind) - Number(a.kind === card.kind)
92
101
  || b.sourceDateMs - a.sourceDateMs || compare(canonicalJson(a), canonicalJson(b)))[0] ?? null;
93
102
  }
94
103
 
@@ -120,11 +129,13 @@ export function fitnessEstimate(candidate, card, snapshot, policy) {
120
129
  expectedMs: ceilRatio(BigInt(cell.medianDurationMs) * denominator, numerator) };
121
130
  }
122
131
  }
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,
132
+ const prior = priorFor(candidate, card, policy, snapshot);
133
+ if (!prior) return null;
134
+ const measured = prior.judged !== undefined && prior.passes !== undefined;
135
+ if (!measured && prior.successPseudoCount === 0) return null;
136
+ const numerator = measured ? BigInt(prior.passes) + 1n : BigInt(prior.successPseudoCount);
137
+ const denominator = measured ? BigInt(prior.judged) + 2n : numerator + BigInt(prior.failurePseudoCount);
138
+ return { poolLevel: 'prior', sampleCount: measured ? prior.judged : 0, exactSamples: exact?.judged ?? 0,
128
139
  qualityProbabilityPpm: safeNumber(numerator * PPM / denominator),
129
140
  time: { numerator: BigInt(prior.durationMs) * denominator, denominator: numerator },
130
141
  expectedMs: ceilRatio(BigInt(prior.durationMs) * denominator, numerator) };
@@ -222,7 +233,7 @@ function rankCandidates(entries, policy) {
222
233
  }
223
234
 
224
235
  export function estimateCharges(candidate, card, snapshot, policy) {
225
- const prior = priorFor(candidate, card, policy);
236
+ const prior = priorFor(candidate, card, policy, snapshot);
226
237
  const account = snapshot.accounts.find(entry => entry.id === candidate.accountId);
227
238
  if (!prior || prior.rateAsOfMs > snapshot.asOfMs || !account?.windows.length) return null;
228
239
  const charges = [];
@@ -296,7 +307,7 @@ function assess(card, candidates, snapshot, policy, state) {
296
307
  excluded.push({ candidateId: candidate.id, reasons: [...new Set(reasons)].sort(compare) });
297
308
  continue;
298
309
  }
299
- const prior = priorFor(candidate, card, policy);
310
+ const prior = priorFor(candidate, card, policy, snapshot);
300
311
  const floor = policy.capabilityFloors.filter(entry => entry.difficulty === card.difficulty
301
312
  && [card.kind, 'code', '*'].includes(entry.kind));
302
313
  if (!floor.length || !prior || floor.some(entry => prior.capabilityScorePpm < entry.minimumScorePpm)) reasons.push('capability_floor');
@@ -0,0 +1,201 @@
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
+ import { isInfraFailure } from '../fitness.mjs';
6
+
7
+ const text = z.string().min(1).max(8192);
8
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
9
+ const difficulty = z.enum(['easy', 'medium', 'hard']);
10
+ const SampleSchema = z.object({ id: text, project: text, ts: integer, duration_ms: integer,
11
+ card: integer.optional(), persona: text.optional(), agent: text.optional(), model: text.nullable().optional(),
12
+ attempt: z.object({ id: text, provider: text, harness: text, model: text.nullable(),
13
+ seat: text.optional(), effort: text.nullable().optional(), difficulty: text, infraFailure: z.boolean() }).passthrough().nullish(),
14
+ usage: z.unknown().optional(), executionAttemptId: text.nullable().optional(),
15
+ }).passthrough();
16
+ const UsageSchema = z.object({ input: integer, output: integer, cacheRead: integer.optional(),
17
+ cacheWrite: integer.optional(), priceVersion: text.nullable().optional() }).passthrough();
18
+ export const PolicyDraftRequestSchema = z.strictObject({ project: text, version: text.optional() });
19
+ const key = row => JSON.stringify([row.provider, row.harness, row.model, row.difficulty, row.effort, row.seatId ?? null]);
20
+ const median = values => {
21
+ const sorted = [...values].sort((a, b) => a - b);
22
+ const middle = Math.floor(sorted.length / 2);
23
+ return sorted.length % 2 ? sorted[middle] : Math.ceil(sorted[middle - 1] / 2 + sorted[middle] / 2);
24
+ };
25
+
26
+ function supportsModel(seat, model, snapshot, policy) {
27
+ if (seat.model === model) return true;
28
+ return model !== null && snapshot.models.some(entry => entry.invocation.status === 'ok'
29
+ && entry.invocation.value?.seatId === seat.id && entry.invocation.value?.model === model
30
+ && entry.invocation.observedAtMs !== null
31
+ && entry.invocation.observedAtMs <= snapshot.asOfMs
32
+ && snapshot.asOfMs - entry.invocation.observedAtMs <= policy.invocationTtlMs);
33
+ }
34
+
35
+ const increment = (counts, reason) => { counts[reason] = (counts[reason] || 0) + 1; };
36
+
37
+ function collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances, cards) {
38
+ const groups = new Map();
39
+ const seen = new Set();
40
+ const excluded = {};
41
+ const tokenExcluded = {};
42
+ const recovered = { withoutAttempt: 0, cardDifficulty: 0 };
43
+ for (const input of turns) {
44
+ const parsed = SampleSchema.safeParse(input);
45
+ if (!parsed.success) {
46
+ const issue = parsed.error.issues[0];
47
+ increment(excluded, `invalid_${issue.path.join('_') || 'row'}_${issue.code}`);
48
+ continue;
49
+ }
50
+ const row = parsed.data;
51
+ if (row.project !== project) continue;
52
+ if (seen.has(row.id)) { increment(excluded, 'duplicate'); continue; }
53
+ seen.add(row.id);
54
+ if (row.ts > nowMs) { increment(excluded, 'future'); continue; }
55
+ if (row.attempt?.infraFailure || isInfraFailure(row.outcome)) { increment(excluded, 'infrastructure'); continue; }
56
+ const card = cards.find(card => card.project === project && card.card === row.card);
57
+ const recordedDifficulty = difficulty.safeParse(row.attempt?.difficulty);
58
+ const cardDifficulty = difficulty.safeParse(card?.difficulty);
59
+ if (!recordedDifficulty.success && !cardDifficulty.success) { increment(excluded, 'difficulty_unknown'); continue; }
60
+ const seatId = row.attempt?.seat ?? (row.persona ? `${row.persona}:${project}` : null);
61
+ const recordedModel = row.attempt?.model ?? row.model ?? null;
62
+ const harness = row.attempt?.harness ?? row.agent;
63
+ const seat = bound.find(entry => entry.id === seatId
64
+ && (entry.harness === harness || entry.harness === 'crew' && entry.agent === harness)
65
+ && (entry.model === null || supportsModel(entry, recordedModel, snapshot, policy)));
66
+ if (!seat) { increment(excluded, 'no_bound_seat'); continue; }
67
+ if (recordedModel === 'unknown' && seat.model !== null) { increment(excluded, 'unknownModel'); continue; }
68
+ const account = snapshot.accounts.find(entry => entry.id === seat.accountId);
69
+ const effort = row.attempt?.effort;
70
+ const identity = { provider: account.provider, harness: seat.harness, model: seat.model === null ? null : recordedModel,
71
+ difficulty: recordedDifficulty.success ? recordedDifficulty.data : cardDifficulty.data,
72
+ effort: !effort || effort === 'unknown' ? 'default' : effort };
73
+ if (seat.model === null) identity.seatId = seat.id;
74
+ if (!row.attempt) recovered.withoutAttempt++;
75
+ if (!recordedDifficulty.success) recovered.cardDifficulty++;
76
+ const groupKey = key(identity);
77
+ if (!groups.has(groupKey)) groups.set(groupKey, { ...identity, rows: [], tokens: [], cacheReads: [],
78
+ tokenExcluded: {}, durations: [], judged: 0, passes: 0, acceptances: new Set() });
79
+ const group = groups.get(groupKey);
80
+ group.rows.push(row);
81
+ const usage = UsageSchema.safeParse(row.usage);
82
+ const tokens = usage.success ? usage.data.input + usage.data.output : null;
83
+ const tokenReason = row.usage == null ? 'no_structured_usage' : !usage.success ? 'invalid_structured_usage'
84
+ : !Number.isSafeInteger(tokens) ? 'token_sum_overflow' : null;
85
+ if (tokenReason) { increment(tokenExcluded, tokenReason); increment(group.tokenExcluded, tokenReason); }
86
+ else {
87
+ group.tokens.push(tokens);
88
+ if (usage.data.cacheRead !== undefined) group.cacheReads.push(usage.data.cacheRead);
89
+ }
90
+ if (row.duration_ms > 0) group.durations.push(row.duration_ms);
91
+ if (!row.attempt) continue;
92
+ const acceptance = acceptances.find(record => record.attemptId === (row.executionAttemptId ?? row.attempt.id)
93
+ && record.atMs <= nowMs);
94
+ const verification = classifyAttemptVerification({ ...row.attempt, acceptance, executionAttemptId: row.executionAttemptId });
95
+ if (['accepted', 'failed'].includes(verification.status) && !group.acceptances.has(verification.acceptance.id)) {
96
+ group.acceptances.add(verification.acceptance.id);
97
+ group.judged++;
98
+ if (verification.status === 'accepted') group.passes++;
99
+ }
100
+ }
101
+ return { groups, excluded, tokenExcluded, recovered };
102
+ }
103
+
104
+ function ratesFor(group, policy) {
105
+ const prior = policy.qualityPriors.filter(row => row.provider === group.provider && row.model === group.model
106
+ && (row.harness === undefined || row.harness === group.harness) && row.difficulty === group.difficulty
107
+ && (row.seatId === undefined || row.seatId === group.seatId))
108
+ .sort((a, b) => b.rateAsOfMs - a.rateAsOfMs || canonicalJson(a).localeCompare(canonicalJson(b)))[0];
109
+ if (prior) return { rates: prior.rates, priceVersion: prior.priceVersion,
110
+ rateSource: `policy:${policy.version}:${prior.rateSource}`, rateAsOfMs: prior.rateAsOfMs };
111
+ const seed = LEGACY_RATE_INPUTS.find(row => row.model === group.model);
112
+ return seed ? { rates: seed.rates, priceVersion: null, rateSource: seed.rateSource, rateAsOfMs: seed.rateAsOfMs }
113
+ : { rates: { usdMicrosPerMTok: null, quotaMillionthsPerMTok: null }, priceVersion: null,
114
+ rateSource: 'unobserved: no active policy rate or legacy model rate', rateAsOfMs: 0 };
115
+ }
116
+
117
+ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turns, acceptances = [], cards, project, version, createdBy, nowMs }) {
118
+ const policy = verifyPolicy(inputPolicy);
119
+ const snapshot = verifySnapshot(inputSnapshot);
120
+ if (snapshot.policyVersion !== policy.version) throw new Error('policy_stale');
121
+ const bound = snapshot.seats.filter(seat => (seat.project === project || seat.project === undefined)
122
+ && snapshot.accounts.some(account => account.id === seat.accountId && account.status === 'verified')
123
+ && snapshot.machines.some(machine => machine.id === seat.machine));
124
+ const roster = bound.map(seat => {
125
+ const entry = { seatId: seat.id, harness: seat.harness, enabled: true, host: seat.machine, model: seat.model,
126
+ adapterVersions: snapshot.machines.find(machine => machine.id === seat.machine).adapterVersions };
127
+ if (seat.agent !== undefined) entry.agent = seat.agent;
128
+ return entry;
129
+ });
130
+ const { groups, excluded, tokenExcluded, recovered } = collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances, cards ?? snapshot.readyQueue);
131
+ const qualityPriors = [];
132
+ const samples = [];
133
+ for (const group of [...groups.values()].sort((a, b) => key(a).localeCompare(key(b)))) {
134
+ const sampleCount = group.rows.length;
135
+ const priceVersions = [...new Set(group.rows.map(row => { const usage = UsageSchema.safeParse(row.usage); return usage.success ? usage.data.priceVersion ?? null : null; }))]
136
+ .sort((a, b) => String(a).localeCompare(String(b)));
137
+ const sample = { provider: group.provider, harness: group.harness, model: group.model, difficulty: group.difficulty,
138
+ effort: group.effort,
139
+ sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
140
+ tokenExcluded: group.tokenExcluded, cacheReadSampleCount: group.cacheReads.length,
141
+ medianCacheReadTokens: group.cacheReads.length ? median(group.cacheReads) : null,
142
+ judged: group.judged, passes: group.passes, priceVersions,
143
+ recordedProviders: [...new Set(group.rows.map(row => row.attempt?.provider ?? null))].sort(),
144
+ recordedHarnesses: [...new Set(group.rows.map(row => row.attempt?.harness ?? row.agent ?? null))].sort(),
145
+ recordedModels: [...new Set(group.rows.map(row => row.attempt?.model ?? row.model ?? null))].sort(),
146
+ medianTokens: group.tokens.length ? median(group.tokens) : null,
147
+ medianDurationMs: group.durations.length ? median(group.durations) : null };
148
+ if (group.seatId) sample.seatId = group.seatId;
149
+ const reason = !group.tokens.length || !group.durations.length ? 'no_measurements' : null;
150
+ samples.push({ ...sample, reason });
151
+ if (reason) continue;
152
+ const qualityPpm = Number((BigInt(group.passes) + 1n) * 1_000_000n / (BigInt(group.judged) + 2n));
153
+ const rates = ratesFor(group, policy);
154
+ const prior = { provider: group.provider, harness: group.harness,
155
+ model: group.model, effort: group.effort, kind: '*', difficulty: group.difficulty,
156
+ durationMs: sample.medianDurationMs, tokenEstimate: sample.medianTokens,
157
+ capabilityScorePpm: qualityPpm, successPseudoCount: group.passes, failurePseudoCount: group.judged - group.passes,
158
+ sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
159
+ judged: group.judged, passes: group.passes, priceVersions,
160
+ source: `turn-history:${project}:${canonicalHash(group.rows.map(row => row.id).sort())}; pooled across kind`,
161
+ sourceDateMs: group.rows.reduce((latest, row) => Math.max(latest, row.ts), 0), ...rates };
162
+ if (group.seatId) prior.seatId = group.seatId;
163
+ qualityPriors.push(prior);
164
+ }
165
+ const { hash: _hash, ...previous } = policy;
166
+ const draft = createPolicy({ ...previous, parentVersion: policy.version,
167
+ version: version || `${policy.version}-draft-${nowMs}`, createdAtMs: nowMs, createdBy,
168
+ roster: [...policy.roster.filter(row => !snapshot.seats.some(seat => seat.id === row.seatId
169
+ && (seat.project === project || seat.project === undefined))), ...roster],
170
+ qualityPriors: [...policy.qualityPriors.filter(prior => !bound.some(seat => (prior.harness === undefined || prior.harness === seat.harness)
171
+ && snapshot.accounts.find(account => account.id === seat.accountId)?.provider === prior.provider)), ...qualityPriors] });
172
+ if (draft.version === policy.version) throw new Error('draft_version_must_change');
173
+ return { policy: draft, summary: { project, snapshotId: snapshot.id, parentVersion: policy.version,
174
+ rosterEntries: roster.length, priorsDerived: qualityPriors.length, rowsRead: turns.length,
175
+ verifiedAcceptancesRead: acceptances.length, excluded, tokenExcluded, recovered, samples,
176
+ tokenBasis: 'non-cache input + output',
177
+ seatsWithoutSamples: roster.filter(seat => !qualityPriors.some(prior => prior.harness === seat.harness && prior.model === seat.model
178
+ && (prior.seatId === undefined || prior.seatId === seat.seatId)))
179
+ .map(seat => seat.seatId),
180
+ priorsWithUnknownRates: qualityPriors.filter(prior => Object.values(prior.rates).some(rate => rate === null)).length } };
181
+ }
182
+
183
+ export async function draftPolicyFromStore({ service, orgId, input, actor, requireRole, clock = Date.now }) {
184
+ const request = PolicyDraftRequestSchema.parse(input);
185
+ return service.store.locked(orgId, async client => {
186
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
187
+ const authority = await service.readAdvice(client, { orgId, request: { project: request.project } });
188
+ const turns = (await client.query("SELECT row FROM turns WHERE org_id=$1 AND row->>'project'=$2 ORDER BY ts,id",
189
+ [orgId, request.project])).rows.map(row => row.row);
190
+ const ids = [...new Set(turns.map(row => row.card).filter(id => Number.isSafeInteger(id) && id > 0))];
191
+ const cards = (await client.query(`SELECT id AS card,project,difficulty FROM tasks
192
+ WHERE org_id=$1 AND project=$2 AND id=ANY($3::bigint[])`, [orgId, request.project, ids])).rows
193
+ .map(row => ({ ...row, card: Number(row.card) }));
194
+ for (const card of authority.snapshot.readyQueue) if (!cards.some(row => row.card === card.card)) cards.push(card);
195
+ const acceptances = (await client.query(`SELECT a.row FROM dispatcher_acceptances a
196
+ JOIN dispatcher_verification_jobs j ON j.org_id=a.org_id AND j.id=a.job_id AND j.acceptance_id=a.id
197
+ WHERE a.org_id=$1 AND j.project=$2 AND j.state IN ('passed','failed') ORDER BY (a.row->>'atMs')::bigint DESC,a.id`,
198
+ [orgId, request.project])).rows.map(row => row.row);
199
+ return draftPolicy({ ...authority, ...request, turns, acceptances, cards, createdBy: actor.pubkey, nowMs: clock() });
200
+ });
201
+ }
@@ -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(), seatId: 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,
@@ -4,6 +4,7 @@ import { spawnSync } from "node:child_process";
4
4
  import { readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { createHash } from "node:crypto";
7
+ import { createConnection } from "node:net";
7
8
  import { codexRolloutCwd } from "./turn-usage.mjs";
8
9
 
9
10
  export const HERDR_CLAUDE_INSTALL = "herdr integration install claude";
@@ -37,6 +38,67 @@ const validArgv = (args) => args.length > 0 && args.length <= 64
37
38
  && args.every(validArg)
38
39
  && Buffer.byteLength(args.join("\0")) <= 8192;
39
40
 
41
+ function herdrSocketAttempt(wire, socketPath, timeoutMs) {
42
+ return new Promise(resolve => {
43
+ let done = false, timeout;
44
+ const socket = createConnection(socketPath);
45
+ const finish = delivered => {
46
+ if (done) return;
47
+ done = true;
48
+ clearTimeout(timeout);
49
+ socket.destroy();
50
+ resolve(delivered);
51
+ };
52
+ socket.on("error", () => finish(false));
53
+ socket.on("connect", () => socket.write(wire));
54
+ socket.on("data", () => finish(true));
55
+ socket.on("end", () => finish(false));
56
+ timeout = setTimeout(() => finish(false), timeoutMs);
57
+ });
58
+ }
59
+
60
+ function herdrRequestWire(request) {
61
+ const seq = request.params.seq;
62
+ const json = JSON.stringify({ ...request, params: { ...request.params, seq: seq.toString() } });
63
+ return `${json.replace(`"seq":"${seq}"`, `"seq":${seq}`)}\n`;
64
+ }
65
+
66
+ async function herdrSocketRequest(request, wire = herdrRequestWire(request)) {
67
+ const socketPath = process.env.HERDR_SOCKET_PATH || "";
68
+ if (!socketPath) return false;
69
+ if (await herdrSocketAttempt(wire, socketPath, 500)) return true;
70
+ return herdrSocketAttempt(wire, socketPath, 1500);
71
+ }
72
+
73
+ function reportedHerdrSession(pane) {
74
+ try {
75
+ const result = spawnSync("herdr", ["agent", "get", pane], { encoding: "utf8", timeout: 1500 });
76
+ if (result.status !== 0) return "";
77
+ return JSON.parse(result.stdout || "{}")?.result?.agent?.agent_session?.value || "";
78
+ } catch { return ""; }
79
+ }
80
+
81
+ const herdrClockWall = BigInt(Date.now()) * 1_000_000n;
82
+ const herdrClockMono = process.hrtime.bigint();
83
+ let herdrReportSeq = 0n;
84
+ function nextHerdrReportSeq() {
85
+ const wall = herdrClockWall + process.hrtime.bigint() - herdrClockMono;
86
+ herdrReportSeq = wall > herdrReportSeq ? wall : herdrReportSeq + 1n;
87
+ return herdrReportSeq;
88
+ }
89
+
90
+ export async function reportHerdrSessionResume({ pane, sessionId, transcriptPath = "", resumeArgv = [] }, transport = herdrSocketRequest, readSession = reportedHerdrSession) {
91
+ if (!pane || !sessionId || !validArgv(resumeArgv)) return false;
92
+ // #14774: herdr orders reports by time_ns; BigInt keeps the ns integer exact.
93
+ const params = { pane_id: pane, source: "herdr:claude", agent: "claude", seq: nextHerdrReportSeq(),
94
+ agent_session_id: sessionId, session_start_source: "resume", resume_argv: resumeArgv };
95
+ if (transcriptPath) params.agent_session_path = transcriptPath;
96
+ const request = { id: `herdr:claude:${Date.now()}:${Math.random().toString(36).slice(2)}`,
97
+ method: "pane.report_agent_session", params };
98
+ if (!await transport(request, herdrRequestWire(request))) return false;
99
+ return await readSession(pane) === sessionId;
100
+ }
101
+
40
102
  export function runnerResumeArgv({ agent, driver = agent, persona = agent, dir, runnerPath, model = "", effort = null, project, hub, sessionId }) {
41
103
  if (!sessionId || !RESUMABLE.has(driver)) return [];
42
104
  const args = ["node", runnerPath, persona, dir, "--agent", agent, "--persona", persona,
@@ -19,7 +19,8 @@ export function seatProvider(agent) {
19
19
  }
20
20
 
21
21
  /** null when label and live model agree; else { label, model, expected, actual } for the refusal. */
22
- export function providerMismatch(label, model) {
22
+ export function providerMismatch(label, model, modelSource = "") {
23
+ if (modelSource === "cli-default") return null;
23
24
  const m = String(model || "");
24
25
  const actual = m.split("/")[0];
25
26
  if (!actual) return null;
@@ -145,6 +145,7 @@ CREATE TABLE IF NOT EXISTS peers (
145
145
  llm TEXT,
146
146
  model TEXT,
147
147
  account_identity JSONB,
148
+ adapter_version TEXT,
148
149
  PRIMARY KEY (org_id, session)
149
150
  );
150
151
  -- additive migrations for hubs whose peers table predates these columns
@@ -153,6 +154,7 @@ ALTER TABLE peers ADD COLUMN IF NOT EXISTS machine TEXT;
153
154
  ALTER TABLE peers ADD COLUMN IF NOT EXISTS llm TEXT;
154
155
  ALTER TABLE peers ADD COLUMN IF NOT EXISTS model TEXT;
155
156
  ALTER TABLE peers ADD COLUMN IF NOT EXISTS account_identity JSONB;
157
+ ALTER TABLE peers ADD COLUMN IF NOT EXISTS adapter_version TEXT;
156
158
  -- DELIBERATELY no CHECK on peers.kind, unlike identities.kind above. The hub accepts whatever a
157
159
  -- client stamps (hub.mjs /register takes any string up to 40 chars) and the vocabulary grows with
158
160
  -- the product — 'genesis' arrived in #6068, 'orch' in #6075. #6169 is the cost of getting this