trantor 0.18.146 → 0.18.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +23 -7
  4. package/bin/capacity.mjs +18 -2
  5. package/bin/cli.mjs +6 -2
  6. package/bin/connect.mjs +10 -3
  7. package/bin/crew/state.mjs +1 -1
  8. package/bin/crew-runner.mjs +29 -4
  9. package/bin/dispatch.mjs +78 -0
  10. package/bin/docker-seat.mjs +33 -0
  11. package/bin/heavy-gate-shim/docker +2 -0
  12. package/bin/integrate.mjs +14 -2
  13. package/bin/migrate-dispatcher.mjs +50 -0
  14. package/bin/review.mjs +35 -0
  15. package/hooks/sessionstart.mjs +4 -1
  16. package/hub/auth.mjs +3 -3
  17. package/hub/routes/capacity.mjs +30 -23
  18. package/hub/routes/cards.mjs +13 -1
  19. package/hub/routes/dispatcher-operations.mjs +122 -0
  20. package/hub/routes/dispatcher.mjs +106 -0
  21. package/hub/routes/insights.mjs +68 -4
  22. package/hub/routes/worktree-status.mjs +56 -0
  23. package/hub/store.mjs +20 -0
  24. package/hub.mjs +17 -1
  25. package/kimi.plugin.json +1 -1
  26. package/lib/capacity.mjs +94 -16
  27. package/lib/dispatcher/acceptance.mjs +314 -0
  28. package/lib/dispatcher/accounts.mjs +442 -0
  29. package/lib/dispatcher/admission.mjs +731 -0
  30. package/lib/dispatcher/breakers.mjs +70 -0
  31. package/lib/dispatcher/executor.mjs +486 -0
  32. package/lib/dispatcher/forecast.mjs +391 -0
  33. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  34. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  35. package/lib/dispatcher/harness/contract.mjs +198 -0
  36. package/lib/dispatcher/harness/crew.mjs +463 -0
  37. package/lib/dispatcher/harness/publication.mjs +188 -0
  38. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  39. package/lib/dispatcher/operations.mjs +401 -0
  40. package/lib/dispatcher/planner.mjs +516 -0
  41. package/lib/dispatcher/policy.mjs +9 -0
  42. package/lib/dispatcher/preflight.mjs +249 -0
  43. package/lib/dispatcher/resources.mjs +44 -0
  44. package/lib/dispatcher/schemas.mjs +3 -1
  45. package/lib/dispatcher/snapshot.mjs +72 -1
  46. package/lib/dispatcher/spend.mjs +319 -0
  47. package/lib/dispatcher/store.mjs +207 -2
  48. package/lib/dispatcher/verifier.mjs +246 -0
  49. package/lib/docker-janitor.mjs +24 -14
  50. package/lib/fitness.mjs +227 -41
  51. package/lib/review-gate.mjs +63 -0
  52. package/lib/store-contract.mjs +57 -0
  53. package/lib/store-pg.mjs +38 -3
  54. package/lib/telemetry-ship.mjs +8 -7
  55. package/lib/worktree-status.mjs +216 -0
  56. package/mcp.mjs +53 -7
  57. package/package.json +1 -1
@@ -0,0 +1,731 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { SnapshotSchema, PolicySchema, WorkCardSchema, DecisionSchema, ChargeSchema,
4
+ UsageEventSchema, ActualChargeSchema } from './schemas.mjs';
5
+ import { canonicalHash, canonicalJson, createSnapshot, verifySnapshot, hashDecision } from './snapshot.mjs';
6
+ import { verifyPolicy, projectMode } from './policy.mjs';
7
+ import { nextAdmission } from './planner.mjs';
8
+ import { canonicalResource, conflictingResources } from './resources.mjs';
9
+ import { admitCharges, activeOverride, validateBindingRepairEvidence } from './accounts.mjs';
10
+ import { heldLiability } from './spend.mjs';
11
+ import { CREW_ADAPTER_VERSION, LaunchInputSchema, normalizeLaunch } from './harness/contract.mjs';
12
+ import { DispatcherStoreError } from './store.mjs';
13
+ import { blockingBreakers } from './breakers.mjs';
14
+ import { executionRows, saveExecution, fenceExecution, finishStop, usageSummary } from './executor.mjs';
15
+
16
+ const text = z.string().min(1).max(8192);
17
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
18
+ const unit = z.enum(['usdMicros', 'quotaMillionths']);
19
+ const windowKey = value => JSON.stringify([value.accountId, value.windowId, value.unit]);
20
+ export const DispatchRequestSchema = z.strictObject({ schemaVersion: z.literal(1), project: text,
21
+ decisionId: text, card: integer.min(1), cardRevision: integer, idempotencyKey: text, expectedPolicyVersion: text });
22
+ export const WindowLedgerSchema = z.strictObject({ accountId: text, windowId: text, unit,
23
+ availableBeforeReserve: integer.nullable(), externalHold: integer,
24
+ reflection: z.array(z.strictObject({ attemptId: text, amount: integer })), evidenceId: text });
25
+ export const AdmissionAuthoritySchema = z.strictObject({
26
+ snapshot: SnapshotSchema, policy: PolicySchema, card: WorkCardSchema,
27
+ binding: z.strictObject({ accountId: text.nullable(), revision: text, frozen: z.boolean() }),
28
+ windowLedgers: z.array(WindowLedgerSchema),
29
+ adapter: z.strictObject({ version: text, qualified: z.boolean(), generationFencing: z.boolean(),
30
+ heartbeat: z.boolean(), boundedSpend: z.boolean(), writeBoundary: z.boolean(),
31
+ effectClasses: z.array(text), inFlightBounds: z.array(z.strictObject({ accountId: text, windowId: text, unit, amount: integer })) }),
32
+ launch: LaunchInputSchema.omit({ launchToken: true, generation: true, attemptId: true, resume: true }),
33
+ producerIdentityIds: z.array(text).min(1), orchestrator: z.boolean(),
34
+ });
35
+
36
+ export const TopUpRequestSchema = z.strictObject({ schemaVersion: z.literal(1), idempotencyKey: text,
37
+ action: z.enum(['approve', 'stop']), expectedLeaseRevision: integer.min(1), expectedGeneration: integer.min(1),
38
+ expectedAccountBindingRevision: text, expectedPolicyVersion: text, spendEvidenceHash: text,
39
+ newEstimates: z.array(z.strictObject({ accountId: text, windowId: text, unit, totalEstimate: integer })), reason: text });
40
+ export const BindingRepairRequestSchema = z.strictObject({ schemaVersion: z.literal(1), idempotencyKey: text,
41
+ expectedBindingRevision: text, expectedFromAccountId: text.nullable(), toAccountId: text, identityEvidenceId: text,
42
+ expectedAffectedLeaseSetHash: text, expectedPolicyVersion: text, outstandingLeaseAction: z.literal('stop-settle-reacquire'), reason: text });
43
+ export const RepairAuthoritySchema = z.strictObject({
44
+ seat: z.strictObject({ seatId: text, machine: text, accountId: text.nullable(), bindingRevision: text,
45
+ credentialFingerprint: text, credentialRevision: text }),
46
+ evidence: z.strictObject({ id: text, collectorPubkey: text, signature: text, seatId: text, machine: text,
47
+ provider: text, billingSubject: text, toAccountId: text, credentialFingerprint: text, credentialRevision: text, observedAtMs: integer }),
48
+ accounts: z.array(z.strictObject({ id: text, provider: text, subject: text, status: z.enum(['verified','unmapped']) })),
49
+ policyVersion: text, collectorAuthorized: z.boolean(), unaccountedUsage: z.boolean(),
50
+ uncertainCharges: z.array(z.strictObject({ id: text, leaseId: text, accountId: text, windowId: text, unit, amount: integer, evidenceRef: text })),
51
+ });
52
+ export const BindingSettlementSchema = z.strictObject({ id: text, leaseId: text, evidenceRef: text,
53
+ events: z.array(UsageEventSchema).min(1), actualCharges: z.array(ActualChargeSchema).min(1), settledHoldIds: z.array(text) });
54
+ export const ReplacementAuthoritySchema = z.strictObject({ verified: z.literal(true), previousAttemptId: text,
55
+ checkpointRef: text, baseSha: z.string().regex(/^[0-9a-f]{40}$/), targetMachine: text, receiptId: text });
56
+
57
+ export function reject(code, status = 409, resource = null, retryAtMs = null) {
58
+ const error = new DispatcherStoreError(code, status);
59
+ error.reasons = [{ code, resource, retryAtMs }];
60
+ throw error;
61
+ }
62
+
63
+ const RoleSchema = z.enum(['read', 'write', 'approver', 'owner']);
64
+ const StoredScopesSchema = z.union([z.array(z.strictObject({ project: text, role: RoleSchema })),
65
+ z.record(text, RoleSchema)]);
66
+
67
+ export function storedScopeAllows(identity, project, roles, wildcardOnly = false) {
68
+ const parsed = StoredScopesSchema.safeParse(identity?.scopes);
69
+ if (!parsed.success) return false;
70
+ const scopes = Array.isArray(parsed.data) ? parsed.data
71
+ : Object.entries(parsed.data).map(([project, role]) => ({ project, role }));
72
+ return scopes.some(scope => roles.includes(scope.role)
73
+ && (scope.project === '*' || !wildcardOnly && scope.project === project));
74
+ }
75
+
76
+ export async function requireIdentity(client, orgId, actor, project, financial = false, producers = []) {
77
+ const identity = (await client.query('SELECT * FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
78
+ if (!identity || identity.revoked_at != null) reject('permission_denied', 403);
79
+ if (financial) {
80
+ if (identity.kind !== 'human' || !storedScopeAllows(identity, project, ['owner'], true) || producers.includes(identity.pubkey)) {
81
+ reject('permission_denied', 403);
82
+ }
83
+ } else if (!storedScopeAllows(identity, project, ['write', 'approver', 'owner'])) reject('permission_denied', 403);
84
+ return identity;
85
+ }
86
+
87
+ export async function activeLeases(client, orgId) {
88
+ const leases = (await client.query("SELECT row FROM dispatcher_leases WHERE org_id=$1 AND state IN ('held','quarantined','reconciled')",
89
+ [orgId])).rows.map(row => row.row);
90
+ const uncertain = (await client.query("SELECT id,row FROM dispatcher_binding_liabilities WHERE org_id=$1 AND state='held'", [orgId])).rows;
91
+ const escrow = (await client.query('SELECT row FROM dispatcher_escrow_reservations WHERE org_id=$1', [orgId])).rows;
92
+ return leases.concat(uncertain.map(r => ({ attemptId: `binding-liability:${r.id}`, charges: [], holds: [r.row], reflected: {} })),
93
+ escrow.map(r => ({ attemptId: `escrow:${r.row.override.id}`, charges: [], holds: [r.row.hold], reflected: {} })));
94
+ }
95
+
96
+ async function reserveOverrides(client, orgId, authority, charges, leases, nowMs) {
97
+ for (const charge of charges) {
98
+ const override = activeOverride({ overrides: authority.policy.accountOverrides, accountId: charge.accountId, windowId: charge.windowId, nowMs });
99
+ if (!override) continue;
100
+ const pools = authority.snapshot.accounts.flatMap(a => a.windows.filter(w => w.id === override.escrowPoolId)
101
+ .map(w => ({ account: a, window: w })));
102
+ if (pools.length !== 1 || override.unit !== charge.unit || pools[0].window.unit !== override.unit
103
+ || pools[0].account.status !== 'verified' || pools[0].account.id === charge.accountId && pools[0].window.id === charge.windowId) reject('escrow_unavailable', 429);
104
+ const { account, window } = pools[0];
105
+ const previous = (await client.query('SELECT row FROM dispatcher_escrow_reservations WHERE org_id=$1 AND override_id=$2', [orgId, override.id])).rows[0]?.row;
106
+ if (previous && canonicalHash(previous.override) !== canonicalHash(override)) reject('idempotency_conflict');
107
+ const accounts = ledgerAccounts(authority, leases);
108
+ const debit = { accountId: account.id, windowId: window.id, unit: window.unit, estimate: 0,
109
+ maxLiability: previous ? 0 : override.amount, source: override.approvalId };
110
+ const funding = admitCharges({ accounts, charges: [debit], policy: authority.policy, nowMs });
111
+ if (!funding.admit) reject('escrow_unavailable', 429);
112
+ if (previous) continue;
113
+ const hold = { accountId: account.id, windowId: window.id, unit: window.unit, amount: override.amount };
114
+ await client.query('INSERT INTO dispatcher_escrow_reservations VALUES($1,$2,$3,$4,$5,$6,$7)',
115
+ [orgId, override.id, account.id, window.id, window.unit, override.amount, { override, hold }]);
116
+ leases.push({ attemptId: `escrow:${override.id}`, charges: [], holds: [hold], reflected: {} });
117
+ }
118
+ }
119
+
120
+ // Ledgers are conservative epoch/watermark balances before dispatcher holds. Reflection can reduce only proved-included spend.
121
+ export function ledgerAccounts(authority, leases, excludingAttempt = null) {
122
+ const accounts = structuredClone(authority.snapshot.accounts);
123
+ const ledgers = new Map(authority.windowLedgers.map(row => [windowKey(row), row]));
124
+ if (ledgers.size !== authority.windowLedgers.length) reject('schema_invalid', 422);
125
+ for (const account of accounts) for (const window of account.windows) {
126
+ const key = windowKey({ accountId: account.id, windowId: window.id, unit: window.unit });
127
+ const ledger = ledgers.get(key);
128
+ if (!ledger) {
129
+ window.remaining.value = null;
130
+ window.remaining.status = 'unknown';
131
+ continue;
132
+ }
133
+ window.remaining.value = ledger.availableBeforeReserve;
134
+ window.heldLiability = ledger.externalHold;
135
+ for (const lease of leases) {
136
+ if (lease.attemptId === excludingAttempt) continue;
137
+ for (const charge of lease.holds || lease.charges.map(c => ({ ...c, amount: c.maxLiability }))) {
138
+ if (windowKey(charge) !== key) continue;
139
+ const reflected = ledger.reflection.find(row => row.attemptId === lease.attemptId)?.amount || 0;
140
+ const held = charge.amount;
141
+ window.heldLiability += Math.max(0, held - Math.max(0, reflected - (lease.reflected?.[key] || 0)));
142
+ }
143
+ }
144
+ }
145
+ return accounts;
146
+ }
147
+
148
+ export async function requireUnfrozen(client, orgId, candidate, binding) {
149
+ const freeze = (await client.query('SELECT account_id FROM dispatcher_account_freezes WHERE org_id=$1 AND account_id=$2',
150
+ [orgId, candidate.accountId])).rows[0];
151
+ const persisted = (await client.query('SELECT account_id,frozen,row FROM dispatcher_account_bindings WHERE org_id=$1 AND seat_id=$2',
152
+ [orgId, candidate.seatId])).rows[0];
153
+ if (freeze || persisted && (persisted.frozen || persisted.account_id !== candidate.accountId
154
+ || persisted.row.bindingRevision !== binding.revision)) reject('account_binding_changed');
155
+ }
156
+
157
+ export async function killed(client, orgId, project) {
158
+ return (await client.query(`SELECT scope FROM dispatcher_control WHERE org_id=$1 AND enabled
159
+ AND scope=ANY($2::text[])`, [orgId, ['*', project]])).rows.length > 0;
160
+ }
161
+
162
+ function launchLimits(charges, authority) {
163
+ const dollars = charges.filter(c => c.unit === 'usdMicros');
164
+ if (!dollars.length || dollars.length !== charges.length) reject('spend_unbounded', 429);
165
+ return { ...authority.launch.limits, maxSpendMicros: Math.min(...dollars.map(c => c.maxLiability)),
166
+ estimateMicros: Math.min(...dollars.map(c => c.estimate)), windows: dollars.map(c => ({
167
+ accountId: c.accountId, windowId: c.windowId, unit: c.unit,
168
+ maxInFlightCharge: authority.adapter.inFlightBounds.find(b => windowKey(b) === windowKey(c)).amount })) };
169
+ }
170
+
171
+ export function boundedCharges(estimates, authority) {
172
+ const bounds = new Map(authority.adapter.inFlightBounds.map(bound => [windowKey(bound), bound.amount]));
173
+ if (bounds.size !== authority.adapter.inFlightBounds.length) reject('schema_invalid', 422);
174
+ return estimates.map(input => {
175
+ const charge = ChargeSchema.parse(input);
176
+ const bound = bounds.get(windowKey(charge));
177
+ if (bound === undefined) reject('spend_unbounded', 429, charge.windowId);
178
+ const maxLiability = heldLiability(charge.estimate, bound);
179
+ if (!Number.isSafeInteger(maxLiability)) reject('spend_unbounded', 429, charge.windowId);
180
+ return { ...charge, maxLiability };
181
+ });
182
+ }
183
+
184
+ export function requireQualified(authority) {
185
+ const adapter = authority.adapter;
186
+ if (!adapter.qualified || adapter.version !== CREW_ADAPTER_VERSION || !adapter.boundedSpend
187
+ || !adapter.generationFencing || !adapter.heartbeat || !adapter.effectClasses.includes(authority.card.effectClass)
188
+ || (authority.card.effectClass === 'workspace' && !adapter.writeBoundary)) reject('dispatch_unavailable', 503);
189
+ }
190
+
191
+ export async function persistAttempt(client, orgId, attempt, lease, generation) {
192
+ await client.query(`INSERT INTO dispatcher_attempts(org_id,id,project,card,card_revision,decision_id,
193
+ lease_id,generation,idempotency_key,request_hash,launch_token,state,row)
194
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
195
+ [orgId, attempt.id, attempt.project, attempt.card, attempt.cardRevision, attempt.decisionId, lease.id,
196
+ attempt.generation, attempt.idempotencyKey, attempt.requestHash, attempt.launchToken, attempt.state, attempt]);
197
+ await client.query('INSERT INTO dispatcher_leases(org_id,id,attempt_id,generation,state,row) VALUES($1,$2,$3,$4,$5,$6)',
198
+ [orgId, lease.id, attempt.id, lease.generation, lease.state, lease]);
199
+ await client.query(`INSERT INTO dispatcher_attempt_generations(org_id,attempt_id,generation,launch_token,fenced,row)
200
+ VALUES($1,$2,$3,$4,false,$5)`, [orgId, attempt.id, attempt.generation, attempt.launchToken, generation]);
201
+ for (const claim of lease.claims) await client.query(`INSERT INTO dispatcher_claims
202
+ (org_id,id,attempt_id,generation,repo_id,kind,key,mode,state,row) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
203
+ [orgId, claim.id, attempt.id, claim.generation, claim.repoId, claim.kind, claim.key, claim.mode, claim.state, claim]);
204
+ }
205
+
206
+ export async function enqueue(client, orgId, attempt, command, payload, nowMs) {
207
+ const id = randomUUID();
208
+ await client.query(`INSERT INTO dispatcher_outbox(org_id,id,attempt_id,generation,launch_token,command,state,
209
+ delivery_count,next_at_ms,payload_hash,row) VALUES($1,$2,$3,$4,$5,$6,'ready',0,$7,$8,$9)
210
+ ON CONFLICT(org_id,launch_token,command) WHERE state IN ('ready','claimed') DO NOTHING`,
211
+ [orgId, id, attempt.id, attempt.generation, attempt.launchToken, command, nowMs, canonicalHash(payload), payload]);
212
+ return id;
213
+ }
214
+
215
+ function response(attempt, replayed) {
216
+ return { schemaVersion: 1, attemptId: attempt.id, leaseId: attempt.leaseId, state: attempt.state,
217
+ generation: attempt.generation, replayed };
218
+ }
219
+
220
+ async function decisionFor(client, orgId, request) {
221
+ const persisted = (await client.query('SELECT row FROM dispatcher_decisions WHERE org_id=$1 AND id=$2 AND project=$3',
222
+ [orgId, request.decisionId, request.project])).rows[0]?.row;
223
+ if (!persisted) reject('decision_stale');
224
+ const decision = DecisionSchema.parse(persisted);
225
+ if (decision.id !== `d-${hashDecision(decision).slice(7)}`) reject('decision_stale');
226
+ const stored = (await client.query('SELECT row FROM dispatcher_snapshots WHERE org_id=$1 AND id=$2',
227
+ [orgId, decision.snapshotId])).rows[0]?.row;
228
+ if (!stored) reject('snapshot_gone', 410);
229
+ let snapshot;
230
+ try { snapshot = verifySnapshot(stored); } catch { reject('snapshot_invalid'); }
231
+ if (snapshot.hash !== decision.snapshotHash) reject('snapshot_invalid');
232
+ return { decision, snapshot };
233
+ }
234
+
235
+ function checkAuthority(authority, request, snapshot, decision) {
236
+ verifyPolicy(authority.policy);
237
+ verifySnapshot(authority.snapshot);
238
+ if (authority.policy.kill.fleet || authority.policy.kill.projects.includes(request.project)) reject('kill_switch', 503);
239
+ if (projectMode(authority.policy, request.project) !== 'admit') reject('dispatch_unavailable', 503);
240
+ if (authority.policy.version !== request.expectedPolicyVersion || decision.policyVersion !== authority.policy.version) reject('policy_stale');
241
+ if (authority.card.project !== request.project || authority.card.card !== request.card
242
+ || authority.card.revision !== request.cardRevision) reject('card_stale');
243
+ if (authority.snapshot.revision !== snapshot.revision
244
+ || authority.snapshot.policyVersion !== authority.policy.version) reject('snapshot_stale');
245
+ if (authority.binding.frozen) reject('account_binding_changed');
246
+ requireQualified(authority);
247
+ }
248
+
249
+ function ensureBudget(authority, accounts, charges, nowMs) {
250
+ const result = admitCharges({ accounts, charges, policy: authority.policy, nowMs, orchestrator: authority.orchestrator,
251
+ overrides: authority.policy.accountOverrides });
252
+ if (!result.admit) reject('budget_deferred', 429, result.reasons.join(','));
253
+ }
254
+
255
+ export function createAdmission({ store, readAuthority, readReplacement, clock = Date.now }) {
256
+ const admission = {
257
+ readAuthority,
258
+ async dispatch(orgId, input, actor, previousAttemptId = null) {
259
+ const request = DispatchRequestSchema.parse(input);
260
+ const requestHash = canonicalHash(previousAttemptId ? { ...request, previousAttemptId } : request);
261
+ return store.locked(orgId, async client => {
262
+ const nowMs = clock();
263
+ await requireIdentity(client, orgId, actor, request.project);
264
+ const prior = (await client.query(`SELECT row FROM dispatcher_attempts
265
+ WHERE org_id=$1 AND project=$2 AND idempotency_key=$3`, [orgId, request.project, request.idempotencyKey])).rows[0]?.row;
266
+ if (prior) {
267
+ if (prior.requestHash !== requestHash) reject('idempotency_conflict');
268
+ return response(prior, true);
269
+ }
270
+ if (!store.isReady(orgId)) reject('dispatch_unavailable', 503);
271
+ if (await killed(client, orgId, request.project)) reject('kill_switch', 503);
272
+ const { decision, snapshot } = await decisionFor(client, orgId, request);
273
+ const assignment = decision.assignments.find(a => a.project === request.project && a.card === request.card);
274
+ if (!assignment?.candidate || assignment.cardRevision !== request.cardRevision) reject('decision_stale');
275
+ const authority = AdmissionAuthoritySchema.parse(await readAuthority(client, { orgId, request, actor, nowMs }));
276
+ checkAuthority(authority, request, snapshot, decision);
277
+ const candidate = assignment.candidate;
278
+ let parent = null, handoff = null;
279
+ if (!previousAttemptId && (await client.query(`SELECT id FROM dispatcher_attempts
280
+ WHERE org_id=$1 AND project=$2 AND card=$3 AND card_revision=$4
281
+ AND state IN ('accepted','failed','cancelled','expired') LIMIT 1`,
282
+ [orgId, request.project, request.card, request.cardRevision])).rows.length) reject('handoff_required');
283
+ if (previousAttemptId) {
284
+ parent = await executionRows(client, orgId, previousAttemptId);
285
+ if (parent.attempt.project !== request.project || parent.attempt.card !== request.card
286
+ || !['failed','cancelled','expired'].includes(parent.attempt.state) || !parent.fenced
287
+ || !parent.generation.stopProof || !parent.generation.usageSettled || !parent.generation.checkpointRef
288
+ || parent.lease.claims.length || parent.lease.unresolvedLiability.length) reject('handoff_unresolved');
289
+ if (parent.attempt.swapCount >= 2) reject('swap_limit');
290
+ const child = (await client.query(`SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND row->>'parentAttemptId'=$2`,
291
+ [orgId, previousAttemptId])).rows[0];
292
+ if (child) reject('attempt_conflict');
293
+ handoff = ReplacementAuthoritySchema.parse(await readReplacement(client, { orgId, request, previousAttemptId, candidate, actor }));
294
+ if (handoff.previousAttemptId !== previousAttemptId || handoff.checkpointRef !== parent.generation.checkpointRef
295
+ || handoff.targetMachine !== candidate.machine || handoff.baseSha !== authority.launch.baseSha) reject('handoff_unresolved');
296
+ }
297
+ await requireUnfrozen(client, orgId, candidate, authority.binding);
298
+ const persistedBreakers = (await client.query('SELECT row FROM dispatcher_breakers WHERE org_id=$1', [orgId])).rows.map(r => r.row);
299
+ const blocked = blockingBreakers(persistedBreakers, candidate);
300
+ if (blocked.length) reject('breaker_deferred', 429, null, Math.max(...blocked.map(b => b.retryAtMs || 0)));
301
+ const account = authority.snapshot.accounts.find(a => a.id === candidate.accountId);
302
+ if (authority.binding.accountId !== candidate.accountId || account?.bindingRevision !== authority.binding.revision
303
+ || snapshot.accounts.find(a => a.id === candidate.accountId)?.bindingRevision !== authority.binding.revision) reject('account_binding_changed');
304
+ const live = (await client.query(`SELECT row FROM dispatcher_attempts WHERE org_id=$1
305
+ AND state NOT IN ('accepted','failed','cancelled','expired')`, [orgId])).rows.map(row => row.row);
306
+ if (live.some(a => a.project === request.project && a.card === request.card)) reject('attempt_conflict');
307
+ const leases = await activeLeases(client, orgId);
308
+ const claims = (await client.query('SELECT row FROM dispatcher_claims WHERE org_id=$1', [orgId])).rows.map(row => row.row);
309
+ if (conflictingResources(assignment.claims, claims).length) reject('resource_conflict');
310
+ const counters = (await client.query('SELECT revision,admissions,row FROM dispatcher_scheduling WHERE org_id=$1', [orgId])).rows[0];
311
+ if (!counters) reject('dispatch_unavailable', 503);
312
+ if (Number(counters.revision) !== snapshot.schedulingCounters.schedulingRevision
313
+ || Number(counters.admissions) + 1 !== assignment.expectedAdmissionCounter) reject('schedule_changed');
314
+ const charges = boundedCharges(assignment.estimates, authority);
315
+ await reserveOverrides(client, orgId, authority, charges, leases, nowMs);
316
+ const accounts = ledgerAccounts(authority, leases);
317
+ if (account.windows.some(window => !charges.some(c => c.accountId === account.id
318
+ && c.windowId === window.id && c.unit === window.unit))) reject('snapshot_stale');
319
+ ensureBudget(authority, accounts, charges, nowMs);
320
+ const current = { ...authority.snapshot, asOfMs: nowMs, accounts,
321
+ claims: [...new Map([...authority.snapshot.claims, ...claims].map(c => [c.id, c])).values()],
322
+ readyQueue: authority.snapshot.readyQueue.filter(card => !live.some(a => a.project === card.project && a.card === card.card)),
323
+ schedulingCounters: { ...counters.row, admissions: Number(counters.admissions), schedulingRevision: Number(counters.revision) } };
324
+ delete current.id;
325
+ delete current.hash;
326
+ const next = nextAdmission({ snapshot: createSnapshot(current), policy: authority.policy, cards: current.readyQueue });
327
+ if (!next || next.project !== request.project || next.card !== request.card || next.candidate.id !== candidate.id
328
+ || canonicalJson(next.estimates) !== canonicalJson(assignment.estimates)) reject('schedule_changed');
329
+ const attemptId = randomUUID(), leaseId = randomUUID(), launchToken = randomUUID();
330
+ const requests = assignment.claims.map(canonicalResource);
331
+ const manifest = authority.launch.manifest.map(r => canonicalResource({ ...r, repoId: authority.launch.repoId || null }));
332
+ if (canonicalJson(manifest) !== canonicalJson(requests.filter(r => ['file', 'tree'].includes(r.kind)))) reject('claims_invalid', 422);
333
+ const generation = parent ? parent.attempt.generation + 1 : 1;
334
+ const launch = normalizeLaunch({ ...authority.launch, attemptId, generation, launchToken,
335
+ limits: launchLimits(charges, authority) });
336
+ if (launch.accountBindingRef !== authority.binding.revision || launch.host !== candidate.machine
337
+ || launch.project !== request.project) reject('account_binding_changed');
338
+ const attempt = { schemaVersion: 1, id: attemptId, project: request.project, card: request.card,
339
+ cardRevision: request.cardRevision, decisionId: decision.id, leaseId, generation,
340
+ idempotencyKey: request.idempotencyKey, requestHash, launchToken, producerIdentityIds: authority.producerIdentityIds,
341
+ candidate, actualModel: null, actualEffort: null, state: 'reserved', createdAtMs: nowMs,
342
+ startedAtMs: null, endedAtMs: null, failure: null, turns: [], usage: [], baseSha: launch.baseSha,
343
+ artifact: null, acceptance: null, swapCount: parent ? parent.attempt.swapCount + 1 : 0, parentAttemptId: previousAttemptId };
344
+ const lease = { schemaVersion: 1, id: leaseId, attemptId, generation, revision: 1,
345
+ accountBindingRevision: authority.binding.revision, charges,
346
+ claims: requests.map(r => ({ ...r, id: randomUUID(), attemptId, generation, state: 'held' })),
347
+ state: 'held', acquiredAtMs: nowMs, lastBeatMs: null, expiresAtMs: nowMs + authority.policy.leaseSilenceMs,
348
+ stopReason: null, stopProofId: null, actualCharges: [], unresolvedLiability: [],
349
+ holds: charges.map(c => ({ accountId: c.accountId, windowId: c.windowId, unit: c.unit, amount: c.maxLiability })),
350
+ reflected: {}, beatSequence: -1 };
351
+ await persistAttempt(client, orgId, attempt, lease, { launch, processIdentity: null,
352
+ heartbeatSequence: -1, stopProof: null, usageSettled: false, policyVersion: authority.policy.version, handoff });
353
+ await enqueue(client, orgId, attempt, 'launch', launch, nowMs);
354
+ const updated = structuredClone(counters.row);
355
+ updated.admissions = Number(counters.admissions) + (parent ? 0 : 1);
356
+ for (const counter of updated.accounts) if (!parent && counter.accountId === candidate.accountId) {
357
+ const identity = canonicalJson([request.project, request.card, request.cardRevision]);
358
+ if (!counter.admittedCardRevisions.includes(identity)) {
359
+ counter.admittedCardRevisions.push(identity);
360
+ if (authority.card.difficulty === 'easy' && authority.card.effectClass !== 'external') counter.lowRiskCards24h++;
361
+ if (assignment.exploration) counter.explorationAdmissions24h++;
362
+ }
363
+ }
364
+ await client.query('UPDATE dispatcher_scheduling SET admissions=$2,row=$3 WHERE org_id=$1', [orgId, updated.admissions, updated]);
365
+ await store.audit(client, orgId, { atMs: nowMs, action: 'admitted', actor: actor.pubkey,
366
+ attemptId, requestHash, charges, admissionCounter: updated.admissions, exploration: assignment.exploration });
367
+ return response(attempt, false);
368
+ });
369
+ },
370
+ replace(orgId, input, previousAttemptId, actor) { return admission.dispatch(orgId, input, actor, previousAttemptId); },
371
+ };
372
+ return admission;
373
+ }
374
+
375
+ async function receipt(client, orgId, project, route, request) {
376
+ const row = (await client.query(`SELECT request_hash,response FROM dispatcher_idempotency
377
+ WHERE org_id=$1 AND project=$2 AND route=$3 AND key=$4`, [orgId, project, route, request.idempotencyKey])).rows[0];
378
+ if (!row) return null;
379
+ if (row.request_hash !== canonicalHash(request)) reject('idempotency_conflict');
380
+ return { status: row.response.status >= 400 ? row.response.status : 200, body: { ...row.response.body, replayed: true } };
381
+ }
382
+
383
+ async function recordReceipt(client, orgId, project, route, request, result, nowMs) {
384
+ await client.query('INSERT INTO dispatcher_idempotency VALUES($1,$2,$3,$4,$5,$6,$7)',
385
+ [orgId, project, route, request.idempotencyKey, canonicalHash(request), result, nowMs]);
386
+ }
387
+
388
+ async function stopBudgetAsk(client, orgId, rows, ask, state, nowMs) {
389
+ ask.state = state;
390
+ rows.lease.stopReason = state === 'expired' ? 'budget-ask-expired' : 'budget-ask-stopped';
391
+ if (!rows.generation.stopReceipt || !await finishStop(client, orgId, rows, rows.generation.stopReceipt, nowMs)) {
392
+ await fenceExecution(client, orgId, rows, rows.lease.stopReason, nowMs);
393
+ rows.attempt.state = 'reconciling';
394
+ await saveExecution(client, orgId, rows);
395
+ }
396
+ await client.query('UPDATE dispatcher_budget_asks SET state=$3,row=$4 WHERE org_id=$1 AND id=$2',
397
+ [orgId, ask.id, ask.state, ask]);
398
+ }
399
+
400
+ export function createFinancialOperations({ store, readAuthority, readRepairAuthority, readSettlement, clock = Date.now }) {
401
+ async function audited(action, orgId, actor, operation) {
402
+ try { return await store.locked(orgId, operation); }
403
+ catch (error) {
404
+ if (error.status && error.status < 500) await store.locked(orgId, client => store.audit(client, orgId,
405
+ { atMs: clock(), action: `${action}-denied`, actor: actor.pubkey, code: error.code }));
406
+ throw error;
407
+ }
408
+ }
409
+ return {
410
+ async topUp(orgId, attemptId, askId, input, actor) {
411
+ const request = TopUpRequestSchema.parse(input);
412
+ return audited('top-up', orgId, actor, async client => {
413
+ const nowMs = clock();
414
+ const rows = await executionRows(client, orgId, attemptId);
415
+ await requireIdentity(client, orgId, actor, rows.attempt.project, true, rows.attempt.producerIdentityIds);
416
+ const route = `/dispatch/${attemptId}/top-ups/${askId}/decision`;
417
+ const replay = await receipt(client, orgId, rows.attempt.project, route, request);
418
+ if (replay) return replay;
419
+ const ask = (await client.query(`SELECT row FROM dispatcher_budget_asks
420
+ WHERE org_id=$1 AND id=$2 AND attempt_id=$3`, [orgId, askId, attemptId])).rows[0]?.row;
421
+ if (!ask) reject('ask_missing', 404);
422
+ if (ask.state === 'expired' || (ask.expiresAtMs <= nowMs && ['pending', 'stopping'].includes(ask.state))) reject('ask_expired', 410);
423
+ if (!['pending', 'stopping'].includes(ask.state) || request.expectedLeaseRevision !== rows.lease.revision
424
+ || request.expectedGeneration !== rows.attempt.generation || request.spendEvidenceHash !== ask.spendEvidenceHash
425
+ || request.expectedAccountBindingRevision !== rows.lease.accountBindingRevision
426
+ || request.expectedPolicyVersion !== ask.policyVersion) reject('ask_stale');
427
+ const old = { charges: rows.lease.charges, holds: rows.lease.holds, generation: rows.attempt.generation,
428
+ revision: rows.lease.revision, stopProof: rows.generation.stopProof, launchToken: rows.attempt.launchToken };
429
+ if (request.action === 'stop') {
430
+ if (request.newEstimates.length) reject('schema_invalid', 422);
431
+ await stopBudgetAsk(client, orgId, rows, ask, 'stopped', nowMs);
432
+ } else {
433
+ if (!store.isReady(orgId)) reject('dispatch_unavailable', 503);
434
+ if (await killed(client, orgId, rows.attempt.project)) reject('kill_switch', 503);
435
+ if (rows.attempt.state !== 'paused' || ask.state !== 'pending' || !rows.generation.stopReceipt
436
+ || !rows.generation.usageSettled || !rows.lease.stopProofId || rows.lease.unresolvedLiability.length) reject('attempt_conflict');
437
+ const authority = AdmissionAuthoritySchema.parse(await readAuthority(client, { orgId,
438
+ request: { project: rows.attempt.project, card: rows.attempt.card }, actor, nowMs }));
439
+ verifyPolicy(authority.policy);
440
+ requireQualified(authority);
441
+ await requireUnfrozen(client, orgId, rows.attempt.candidate, authority.binding);
442
+ if (authority.policy.kill.fleet || authority.policy.kill.projects.includes(rows.attempt.project)) reject('kill_switch', 503);
443
+ if (authority.policy.version !== request.expectedPolicyVersion) reject('policy_stale');
444
+ if (authority.binding.frozen || authority.binding.revision !== rows.lease.accountBindingRevision
445
+ || authority.binding.accountId !== rows.attempt.candidate.accountId) reject('account_binding_changed');
446
+ const held = (await client.query('SELECT row FROM dispatcher_claims WHERE org_id=$1', [orgId])).rows.map(r => r.row);
447
+ if (rows.lease.claims.some(c => !held.some(h => h.id === c.id && h.attemptId === attemptId && h.generation === rows.attempt.generation))
448
+ || conflictingResources(rows.lease.claims, held.filter(c => c.attemptId !== attemptId)).length) reject('resource_conflict');
449
+ const summary = usageSummary(rows.attempt, rows.lease);
450
+ if (summary.stopNewCalls) reject('usage_unknown');
451
+ const estimates = new Map(request.newEstimates.map(e => [windowKey(e), e.totalEstimate]));
452
+ if (estimates.size !== request.newEstimates.length || estimates.size !== rows.lease.charges.length
453
+ || rows.lease.charges.some(c => !estimates.has(windowKey(c)))) reject('schema_invalid', 422);
454
+ if (!rows.lease.charges.some(c => estimates.get(windowKey(c)) > c.estimate)) reject('schema_invalid', 422);
455
+ const charges = boundedCharges(rows.lease.charges.map(c => {
456
+ const estimate = estimates.get(windowKey(c));
457
+ if (estimate < c.estimate || estimate < (summary.windows[c.windowId]?.S || 0)) reject('schema_invalid', 422);
458
+ return { ...c, estimate, maxLiability: Math.max(estimate, c.maxLiability) };
459
+ }), authority);
460
+ const reflected = {};
461
+ const holds = charges.map((c, i) => {
462
+ if (c.maxLiability < rows.lease.charges[i].maxLiability) reject('schema_invalid', 422);
463
+ const key = windowKey(c);
464
+ const ledger = authority.windowLedgers.find(w => windowKey(w) === key);
465
+ if (!ledger) reject('budget_deferred', 429);
466
+ const included = ledger.reflection.find(r => r.attemptId === attemptId)?.amount || 0;
467
+ if (included > (summary.windows[c.windowId]?.S || 0)) reject('reflection_invalid');
468
+ reflected[key] = included;
469
+ const oldHold = rows.lease.holds.find(h => windowKey(h) === key)?.amount || 0;
470
+ const amount = Math.max(oldHold, Math.max(c.maxLiability, summary.windows[c.windowId]?.S || 0) - included, 0);
471
+ return { accountId: c.accountId, windowId: c.windowId, unit: c.unit, amount };
472
+ });
473
+ const liveLeases = await activeLeases(client, orgId);
474
+ await reserveOverrides(client, orgId, authority, charges, liveLeases, nowMs);
475
+ ensureBudget(authority, ledgerAccounts(authority, liveLeases, attemptId),
476
+ charges.map((c, i) => ({ ...c, maxLiability: holds[i].amount })), nowMs);
477
+ const dollars = charges.filter(c => c.unit === 'usdMicros');
478
+ if (!dollars.length) reject('spend_unbounded', 429);
479
+ const predecessor = rows.generation.stopReceipt;
480
+ const spentMicros = Math.max(predecessor.spentMicros, ...dollars.map(c => summary.windows[c.windowId]?.S || 0));
481
+ const checkpointRef = rows.generation.checkpointRef;
482
+ if (!checkpointRef) reject('checkpoint_missing');
483
+ const resume = { previousGeneration: rows.attempt.generation, previousLaunchToken: rows.attempt.launchToken,
484
+ checkpointRef, cumulative: { spentMicros, calls: predecessor.calls } };
485
+ rows.attempt.generation++;
486
+ rows.attempt.launchToken = randomUUID();
487
+ rows.attempt.state = 'reserved';
488
+ rows.lease.generation = rows.attempt.generation;
489
+ rows.lease.revision++;
490
+ rows.lease.charges = charges;
491
+ rows.lease.holds = holds;
492
+ rows.lease.reflected = reflected;
493
+ rows.lease.state = 'held';
494
+ rows.lease.stopReason = null;
495
+ rows.lease.stopProofId = null;
496
+ rows.lease.lastBeatMs = null;
497
+ rows.lease.beatSequence = -1;
498
+ rows.lease.expiresAtMs = nowMs + 600_000;
499
+ rows.lease.claims = rows.lease.claims.map(c => ({ ...c, generation: rows.attempt.generation, state: 'held' }));
500
+ const launch = normalizeLaunch({ ...authority.launch, attemptId, generation: rows.attempt.generation,
501
+ launchToken: rows.attempt.launchToken, resume, limits: launchLimits(charges, authority) });
502
+ rows.generation = { launch, processIdentity: null, stopProof: null, usageSettled: false, policyVersion: authority.policy.version };
503
+ rows.fenced = false;
504
+ await client.query(`INSERT INTO dispatcher_attempt_generations VALUES($1,$2,$3,$4,false,$5)`,
505
+ [orgId, attemptId, rows.attempt.generation, rows.attempt.launchToken, rows.generation]);
506
+ await saveExecution(client, orgId, rows);
507
+ await enqueue(client, orgId, rows.attempt, 'resume', launch, nowMs);
508
+ ask.state = 'approved';
509
+ }
510
+ ask.decisionId = randomUUID();
511
+ await client.query('UPDATE dispatcher_budget_asks SET state=$3,row=$4 WHERE org_id=$1 AND id=$2', [orgId, ask.id, ask.state, ask]);
512
+ const result = { status: request.action === 'approve' || rows.attempt.state === 'reconciling' ? 202 : 200,
513
+ body: { schemaVersion: 1, decisionId: ask.decisionId, askId, attemptId, leaseId: rows.lease.id,
514
+ leaseRevision: rows.lease.revision, generation: rows.attempt.generation, state: rows.attempt.state,
515
+ charges: rows.lease.charges, unreflectedHolds: rows.lease.holds, replayed: false } };
516
+ await recordReceipt(client, orgId, rows.attempt.project, route, request, result, nowMs);
517
+ await store.audit(client, orgId, { atMs: nowMs, action: 'top-up-decision', actor: actor.pubkey, reason: request.reason,
518
+ askId, attemptId, requestHash: canonicalHash(request), evidenceHash: ask.spendEvidenceHash, old,
519
+ result, policyVersion: ask.policyVersion, bindingRevision: ask.accountBindingRevision, stopProof: rows.generation.stopProof });
520
+ return result;
521
+ });
522
+ },
523
+ async expireAsks(orgId) {
524
+ return store.locked(orgId, async client => {
525
+ const asks = (await client.query(`SELECT row FROM dispatcher_budget_asks WHERE org_id=$1
526
+ AND state IN ('stopping','pending') AND expires_at_ms <= $2`, [orgId, clock()])).rows.map(r => r.row);
527
+ for (const ask of asks) {
528
+ await stopBudgetAsk(client, orgId, await executionRows(client, orgId, ask.attemptId), ask, 'expired', clock());
529
+ await store.audit(client, orgId, { atMs: clock(), action: 'top-up-expired', askId: ask.id, attemptId: ask.attemptId });
530
+ }
531
+ return asks.length;
532
+ });
533
+ },
534
+ async repairBinding(orgId, seatId, input, actor) {
535
+ const request = BindingRepairRequestSchema.parse(input);
536
+ return audited('binding-repair', orgId, actor, async client => {
537
+ await requireIdentity(client, orgId, actor, '', true);
538
+ const route = `/dispatcher/account-bindings/${seatId}/repairs`;
539
+ const replay = await receipt(client, orgId, '', route, request);
540
+ if (replay) return replay;
541
+ if (!store.isReady(orgId)) reject('dispatch_unavailable', 503);
542
+ const authority = RepairAuthoritySchema.parse(await readRepairAuthority(client, { orgId, seatId, request, nowMs: clock() }));
543
+ await requireCollector(client, orgId, authority);
544
+ if (authority.seat.seatId !== seatId) reject('schema_invalid', 422);
545
+ const binding = await bindingRow(client, orgId, authority.seat);
546
+ const leases = await seatLeases(client, orgId, seatId);
547
+ const active = leases.filter(l => !['accepted','failed','cancelled','expired'].includes(l.attemptState));
548
+ if (active.some(l => l.producers.includes(actor.pubkey))) reject('permission_denied', 403);
549
+ const check = validateBindingRepairEvidence({ request, evidence: authority.evidence,
550
+ seat: { ...authority.seat, accountId: binding.account_id, bindingRevision: binding.row.bindingRevision },
551
+ accounts: authority.accounts, policyVersion: authority.policyVersion,
552
+ activeLeaseSetHash: affectedLeaseSetHash(active), nowMs: clock() });
553
+ if (!check.ok) {
554
+ if (check.code !== 'account_subject_conflict') reject(check.code, check.status);
555
+ for (const accountId of check.implicatedAccountIds) await client.query(`INSERT INTO dispatcher_account_freezes
556
+ VALUES($1,$2,'account_subject_conflict',$3) ON CONFLICT(org_id,account_id) DO NOTHING`,
557
+ [orgId, accountId, { evidenceId: check.evidenceId, seatId }]);
558
+ await client.query('UPDATE dispatcher_account_bindings SET frozen=true WHERE org_id=$1 AND seat_id=$2', [orgId, seatId]);
559
+ const result = { status: 409, body: { schemaVersion: 1, code: check.code, replayed: false } };
560
+ await store.audit(client, orgId, { atMs: clock(), action: 'binding-conflict', actor: actor.pubkey, seatId, evidenceId: check.evidenceId });
561
+ await recordReceipt(client, orgId, '', route, request, result, clock());
562
+ return result;
563
+ }
564
+ const existing = (await client.query("SELECT id FROM dispatcher_account_binding_repairs WHERE org_id=$1 AND seat_id=$2 AND state='reconciling'",
565
+ [orgId, seatId])).rows[0];
566
+ if (existing) reject('repair_conflict');
567
+ const repair = { id: randomUUID(), ...check.repair, request, actor: actor.pubkey, oldBindingRevision: binding.row.bindingRevision,
568
+ newBindingRevision: null, affectedLeaseIds: active.map(l => l.id), createdAtMs: clock(), expiresAtMs: clock() + 1800_000,
569
+ state: 'reconciling', reasons: [], credentialRevision: authority.seat.credentialRevision };
570
+ await client.query('UPDATE dispatcher_account_bindings SET frozen=true WHERE org_id=$1 AND seat_id=$2', [orgId, seatId]);
571
+ for (const lease of active) {
572
+ const rows = await executionRows(client, orgId, lease.attemptId);
573
+ rows.lease.stopReason = 'binding-repair';
574
+ await fenceExecution(client, orgId, rows, 'binding-repair', clock());
575
+ await client.query(`UPDATE dispatcher_budget_asks SET state='superseded',row=row || '{"state":"superseded"}'::jsonb
576
+ WHERE org_id=$1 AND attempt_id=$2 AND state IN ('stopping','pending')`, [orgId, lease.attemptId]);
577
+ }
578
+ for (const charge of authority.uncertainCharges) {
579
+ if (!leases.some(l => l.id === charge.leaseId)) reject('lease_set_changed');
580
+ await client.query(`INSERT INTO dispatcher_binding_liabilities VALUES($1,$2,$3,'held',$4)
581
+ ON CONFLICT(org_id,id) DO NOTHING`, [orgId, charge.id, charge.leaseId, charge]);
582
+ }
583
+ const unsettled = (await client.query(`SELECT id FROM dispatcher_binding_liabilities
584
+ WHERE org_id=$1 AND lease_id=ANY($2::text[]) AND state='held'`, [orgId, leases.map(l => l.id)])).rows;
585
+ if (!active.length && !authority.unaccountedUsage && !unsettled.length) await applyRepair(client, orgId, repair, binding);
586
+ await client.query('INSERT INTO dispatcher_account_binding_repairs VALUES($1,$2,$3,$4,$5,$6)',
587
+ [orgId, repair.id, seatId, repair.state, repair.expiresAtMs, repair]);
588
+ const result = { status: repair.state === 'applied' ? 200 : 202, body: repairResponse(repair) };
589
+ await recordReceipt(client, orgId, '', route, request, result, clock());
590
+ await store.audit(client, orgId, { atMs: clock(), action: 'binding-repair', actor: actor.pubkey,
591
+ requestHash: canonicalHash(request), repair, leaseDisposition: leases.map(l => ({ leaseId: l.id, charges: l.charges, holds: l.holds })) });
592
+ return result;
593
+ });
594
+ },
595
+ async reconcileRepair(orgId, repairId) {
596
+ return store.locked(orgId, async client => {
597
+ const repair = (await client.query('SELECT row FROM dispatcher_account_binding_repairs WHERE org_id=$1 AND id=$2',
598
+ [orgId, repairId])).rows[0]?.row;
599
+ if (!repair) reject('repair_missing', 404);
600
+ if (repair.state !== 'reconciling') return repairResponse(repair);
601
+ const leases = await seatLeases(client, orgId, repair.seatId);
602
+ if (clock() >= repair.expiresAtMs) {
603
+ repair.state = 'expired';
604
+ repair.reasons = ['repair_expired'];
605
+ } else {
606
+ const authority = RepairAuthoritySchema.parse(await readRepairAuthority(client,
607
+ { orgId, seatId: repair.seatId, request: repair.request, nowMs: clock() }));
608
+ const binding = await bindingRow(client, orgId, authority.seat);
609
+ const check = validateBindingRepairEvidence({ request: repair.request, evidence: authority.evidence,
610
+ seat: { ...authority.seat, accountId: binding.account_id, bindingRevision: binding.row.bindingRevision },
611
+ accounts: authority.accounts, policyVersion: authority.policyVersion,
612
+ activeLeaseSetHash: repair.request.expectedAffectedLeaseSetHash, nowMs: clock() });
613
+ const collector = await collectorAllowed(client, orgId, authority);
614
+ const unexpected = leases.some(l => !repair.affectedLeaseIds.includes(l.id)
615
+ && !['accepted','failed','cancelled','expired'].includes(l.attemptState));
616
+ if (!check.ok || !collector || unexpected || authority.seat.credentialRevision !== repair.credentialRevision) {
617
+ repair.state = 'conflicted';
618
+ repair.reasons = [check.code || (unexpected ? 'lease_set_changed' : 'credential_changed')];
619
+ } else {
620
+ const unsettled = (await client.query(`SELECT id FROM dispatcher_binding_liabilities
621
+ WHERE org_id=$1 AND lease_id=ANY($2::text[]) AND state='held'`, [orgId, leases.map(l => l.id)])).rows;
622
+ const safe = repair.affectedLeaseIds.every(id => leases.some(l => l.id === id && l.usageSettled
623
+ && l.stopProofId && ['accepted','failed','cancelled','expired'].includes(l.attemptState)));
624
+ if (safe && !authority.unaccountedUsage && !unsettled.length) await applyRepair(client, orgId, repair, binding);
625
+ }
626
+ }
627
+ await client.query('UPDATE dispatcher_account_binding_repairs SET state=$3,row=$4 WHERE org_id=$1 AND id=$2',
628
+ [orgId, repair.id, repair.state, repair]);
629
+ await store.audit(client, orgId, { atMs: clock(), action: 'binding-reconciled', repairId, state: repair.state,
630
+ leaseDisposition: leases.map(l => ({ leaseId: l.id, holds: l.holds, stopProofId: l.stopProofId })) });
631
+ return repairResponse(repair);
632
+ });
633
+ },
634
+ async settleBinding(orgId, settlementId, actor) {
635
+ return audited('binding-settlement', orgId, actor, async client => {
636
+ await requireIdentity(client, orgId, actor, '', true);
637
+ const evidence = await readSettlement(client, { orgId, settlementId });
638
+ if (!evidence?.verified) reject('evidence_unverified', 422);
639
+ const settlement = BindingSettlementSchema.parse(evidence.settlement);
640
+ if (settlement.id !== settlementId) reject('evidence_unverified', 422);
641
+ const hash = canonicalHash(settlement);
642
+ const previous = (await client.query('SELECT evidence_hash FROM dispatcher_reconciliations WHERE org_id=$1 AND id=$2',
643
+ [orgId, settlementId])).rows[0];
644
+ if (previous) {
645
+ if (previous.evidence_hash !== hash) reject('idempotency_conflict');
646
+ return { replayed: true };
647
+ }
648
+ const leaseRow = (await client.query('SELECT attempt_id FROM dispatcher_leases WHERE org_id=$1 AND id=$2',
649
+ [orgId, settlement.leaseId])).rows[0];
650
+ if (!leaseRow) reject('lease_set_changed');
651
+ const rows = await executionRows(client, orgId, leaseRow.attempt_id);
652
+ if (!rows.fenced || !rows.generation.stopReceipt || !rows.generation.usageSettled) reject('attempt_conflict');
653
+ if (rows.attempt.producerIdentityIds.includes(actor.pubkey)) reject('permission_denied', 403);
654
+ const shadows = (await client.query(`SELECT id,row FROM dispatcher_binding_liabilities
655
+ WHERE org_id=$1 AND lease_id=$2 AND state='held'`, [orgId, settlement.leaseId])).rows;
656
+ if (settlement.settledHoldIds.some(id => !shadows.some(s => s.id === id))) reject('lease_set_changed');
657
+ const keys = new Set([...rows.lease.charges, ...shadows.map(s => s.row)].map(windowKey));
658
+ if (settlement.actualCharges.some(c => c.amount === null || c.confidence !== 'billed' || !keys.has(windowKey(c)))
659
+ || new Set(settlement.actualCharges.map(windowKey)).size !== keys.size) reject('schema_invalid', 422);
660
+ for (const event of settlement.events) {
661
+ if (event.attemptId !== rows.attempt.id || event.generation > rows.attempt.generation
662
+ || event.charges.some(c => c.confidence !== 'billed' || c.amount === null || !keys.has(windowKey(c)))
663
+ || event.replacesEventId && !rows.attempt.usage.some(e => e.id === event.replacesEventId)) reject('evidence_unverified', 422);
664
+ const previousEvent = (await client.query('SELECT row FROM dispatcher_usage WHERE org_id=$1 AND event_id=$2', [orgId, event.id])).rows[0]?.row;
665
+ if (previousEvent && canonicalHash(previousEvent) !== canonicalHash(event)) reject('idempotency_conflict');
666
+ if (!previousEvent) {
667
+ await client.query('INSERT INTO dispatcher_usage VALUES($1,$2,$3,$4,$5,$6,$7)',
668
+ [orgId, event.id, event.attemptId, event.accountId, event.requestId, event.generation, event]);
669
+ rows.attempt.usage.push(event);
670
+ }
671
+ }
672
+ rows.lease.actualCharges = settlement.actualCharges;
673
+ rows.lease.holds = settlement.actualCharges.map(c => ({ accountId: c.accountId, windowId: c.windowId, unit: c.unit, amount: c.amount }));
674
+ rows.lease.reflected = {};
675
+ rows.lease.revision++;
676
+ await saveExecution(client, orgId, rows);
677
+ await client.query("UPDATE dispatcher_binding_liabilities SET state='settled' WHERE org_id=$1 AND id=ANY($2::text[])",
678
+ [orgId, settlement.settledHoldIds]);
679
+ await client.query('INSERT INTO dispatcher_reconciliations VALUES($1,$2,$3,$4)', [orgId, settlementId, hash, settlement]);
680
+ await store.audit(client, orgId, { atMs: clock(), action: 'binding-settlement', actor: actor.pubkey,
681
+ settlementId, evidenceRef: settlement.evidenceRef, actualCharges: settlement.actualCharges });
682
+ return { replayed: false };
683
+ });
684
+ },
685
+ };
686
+ }
687
+
688
+ export function affectedLeaseSetHash(leases) {
689
+ return canonicalHash(leases.map(l => ({ id: l.id, revision: l.revision })).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
690
+ }
691
+
692
+ async function collectorAllowed(client, orgId, authority) {
693
+ const row = (await client.query('SELECT kind,revoked_at FROM identities WHERE org_id=$1 AND pubkey=$2',
694
+ [orgId, authority.evidence.collectorPubkey])).rows[0];
695
+ return authority.collectorAuthorized && row?.kind === 'tool' && row.revoked_at == null
696
+ && authority.evidence.machine === authority.seat.machine;
697
+ }
698
+
699
+ async function requireCollector(client, orgId, authority) {
700
+ if (!await collectorAllowed(client, orgId, authority)) reject('evidence_unverified', 422);
701
+ }
702
+
703
+ async function bindingRow(client, orgId, seat) {
704
+ await client.query(`INSERT INTO dispatcher_account_bindings VALUES($1,$2,1,$3,false,$4)
705
+ ON CONFLICT(org_id,seat_id) DO NOTHING`, [orgId, seat.seatId, seat.accountId, { bindingRevision: seat.bindingRevision, history: [] }]);
706
+ return (await client.query('SELECT * FROM dispatcher_account_bindings WHERE org_id=$1 AND seat_id=$2', [orgId, seat.seatId])).rows[0];
707
+ }
708
+
709
+ async function seatLeases(client, orgId, seatId) {
710
+ const result = await client.query(`SELECT l.row,a.state,a.row AS attempt,g.row AS generation
711
+ FROM dispatcher_leases l JOIN dispatcher_attempts a ON a.org_id=l.org_id AND a.id=l.attempt_id
712
+ JOIN dispatcher_attempt_generations g ON g.org_id=a.org_id AND g.attempt_id=a.id AND g.generation=a.generation
713
+ WHERE a.org_id=$1 AND a.row->'candidate'->>'seatId'=$2`, [orgId, seatId]);
714
+ return result.rows.map(r => ({ ...r.row, attemptState: r.state, producers: r.attempt.producerIdentityIds, usageSettled: r.generation.usageSettled }));
715
+ }
716
+
717
+ async function applyRepair(client, orgId, repair, binding) {
718
+ repair.state = 'applied';
719
+ repair.newBindingRevision = `binding-${randomUUID()}`;
720
+ const row = { bindingRevision: repair.newBindingRevision,
721
+ history: [...binding.row.history, { accountId: binding.account_id, bindingRevision: binding.row.bindingRevision, repairId: repair.id }] };
722
+ await client.query(`UPDATE dispatcher_account_bindings SET account_id=$3,revision=revision+1,frozen=false,row=$4
723
+ WHERE org_id=$1 AND seat_id=$2`, [orgId, repair.seatId, repair.toAccountId, row]);
724
+ }
725
+
726
+ function repairResponse(repair) {
727
+ return { schemaVersion: 1, repairId: repair.id, state: repair.state, seatId: repair.seatId,
728
+ oldBindingRevision: repair.oldBindingRevision, newBindingRevision: repair.newBindingRevision,
729
+ fromAccountId: repair.fromAccountId, toAccountId: repair.toAccountId, affectedLeaseIds: repair.affectedLeaseIds,
730
+ expiresAtMs: repair.expiresAtMs, reasons: repair.reasons, replayed: false };
731
+ }