trantor 0.18.146 → 0.18.148

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 (43) 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-runner.mjs +25 -2
  8. package/bin/dispatch.mjs +78 -0
  9. package/bin/integrate.mjs +14 -2
  10. package/bin/review.mjs +35 -0
  11. package/hooks/sessionstart.mjs +4 -1
  12. package/hub/routes/capacity.mjs +30 -23
  13. package/hub/routes/dispatcher.mjs +97 -0
  14. package/hub/routes/insights.mjs +68 -4
  15. package/hub/routes/worktree-status.mjs +56 -0
  16. package/hub.mjs +2 -1
  17. package/kimi.plugin.json +1 -1
  18. package/lib/capacity.mjs +94 -16
  19. package/lib/dispatcher/acceptance.mjs +314 -0
  20. package/lib/dispatcher/accounts.mjs +442 -0
  21. package/lib/dispatcher/admission.mjs +719 -0
  22. package/lib/dispatcher/breakers.mjs +70 -0
  23. package/lib/dispatcher/executor.mjs +486 -0
  24. package/lib/dispatcher/forecast.mjs +391 -0
  25. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  26. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  27. package/lib/dispatcher/harness/contract.mjs +198 -0
  28. package/lib/dispatcher/harness/crew.mjs +463 -0
  29. package/lib/dispatcher/harness/publication.mjs +188 -0
  30. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  31. package/lib/dispatcher/planner.mjs +516 -0
  32. package/lib/dispatcher/policy.mjs +9 -0
  33. package/lib/dispatcher/preflight.mjs +247 -0
  34. package/lib/dispatcher/resources.mjs +44 -0
  35. package/lib/dispatcher/schemas.mjs +3 -1
  36. package/lib/dispatcher/spend.mjs +319 -0
  37. package/lib/dispatcher/store.mjs +207 -2
  38. package/lib/fitness.mjs +227 -41
  39. package/lib/review-gate.mjs +63 -0
  40. package/lib/telemetry-ship.mjs +8 -7
  41. package/lib/worktree-status.mjs +216 -0
  42. package/mcp.mjs +53 -7
  43. package/package.json +1 -1
@@ -0,0 +1,442 @@
1
+ // #14671 (B1): dispatcher accounts — the pure accounting core for §5 of docs/TDD-dispatcher.md:
2
+ // binding provider subjects to opaque account IDs, window freshness, the shared protected
3
+ // reserve, the admission inequality, watermark-less epochs, daily/reset rollover, escrow.
4
+ // Pure: callers pass nowMs. USD is integer microdollars, quota millionths; unknown stays null.
5
+
6
+ import { createHash, createPublicKey, verify as cryptoVerify } from 'node:crypto';
7
+
8
+ const compare = (a, b) => Buffer.compare(Buffer.from(String(a)), Buffer.from(String(b)));
9
+
10
+ // An account ID is a hub-scoped opaque ID derived from a stable provider subject — never the
11
+ // subject, key, email or token hash itself. Same (org, provider, subject) always maps to the
12
+ // same account; different subjects never merge, even on one provider or one machine.
13
+ export function accountId({ org, provider, subject }) {
14
+ return `a-${createHash('sha256').update(`${String(org)}\u0000${String(provider)}\u0000${String(subject)}`).digest('hex').slice(0, 24)}`;
15
+ }
16
+
17
+ // Bind observed provider subjects to accounts (§2 Snapshot.accounts, §5). Bindings from several
18
+ // machines that share one login dedupe to ONE account; distinct subjects stay distinct accounts.
19
+ // A binding without a usable subject is ambiguous and stays unmapped — display-only, never a
20
+ // fresh allowance. Orchestrator registrations only COUNT here; they never mint new accounts.
21
+ export function bindAccounts({ org, bindings = [], orchestrators = [] }) {
22
+ const bySubject = new Map();
23
+ const unmapped = [];
24
+ let unmappedSeq = 0;
25
+ for (const binding of bindings) {
26
+ const provider = String(binding?.provider || '');
27
+ const subject = binding?.subject == null ? '' : String(binding.subject);
28
+ if (!provider || !subject) {
29
+ unmapped.push({ id: `unmapped-${provider || 'none'}-${++unmappedSeq}`, provider,
30
+ bindingRevision: String(binding?.bindingRevision || ''), status: 'unmapped',
31
+ orchestratorCount: 0, windows: [] });
32
+ continue;
33
+ }
34
+ const id = accountId({ org, provider, subject });
35
+ const existing = bySubject.get(`${provider}\u0000${subject}`);
36
+ if (existing) {
37
+ existing.machines.add(String(binding?.machine || ''));
38
+ continue;
39
+ }
40
+ bySubject.set(`${provider}\u0000${subject}`, { id, provider, subject,
41
+ bindingRevision: String(binding?.bindingRevision || ''), status: 'verified',
42
+ orchestratorCount: 0, windows: [], machines: new Set([String(binding?.machine || '')]) });
43
+ }
44
+ const orchestratorCounts = new Map();
45
+ for (const registration of orchestrators) {
46
+ const key = String(registration?.accountId || '');
47
+ if (key) orchestratorCounts.set(key, (orchestratorCounts.get(key) || 0) + 1);
48
+ }
49
+ const accounts = [...bySubject.values()].map((account) => ({
50
+ id: account.id, provider: account.provider, bindingRevision: account.bindingRevision,
51
+ status: account.status, orchestratorCount: orchestratorCounts.get(account.id) || 0,
52
+ windows: [], machines: [...account.machines], subject: account.subject,
53
+ }));
54
+ accounts.sort((a, b) => compare(a.id, b.id));
55
+ unmapped.sort((a, b) => compare(a.id, b.id));
56
+ return { accounts, unmapped };
57
+ }
58
+
59
+ // Freshness of a remaining observation (§5: admission uses a shorter balance TTL than display).
60
+ // A null value stays unknown regardless of age — Number(null) must never read as a zero balance.
61
+ // A source-declared status wins; an ok observation older than the TTL is stale by age.
62
+ export function observationFreshness(observation, { nowMs, ttlMs }) {
63
+ const status = observation?.status || 'unknown';
64
+ if (observation?.value == null) return { fresh: false, status: 'unknown' };
65
+ if (status !== 'ok') return { fresh: false, status };
66
+ const observedAtMs = Number(observation.observedAtMs);
67
+ if (!Number.isFinite(observedAtMs)) return { fresh: false, status: 'unknown' };
68
+ if (nowMs - observedAtMs > ttlMs) return { fresh: false, status: 'stale' };
69
+ return { fresh: true, status: 'ok' };
70
+ }
71
+
72
+ // The shared protected reserve (§5). One reserve per account/window no matter how many
73
+ // orchestrators are registered — they share it, none of them stack it; an account with no
74
+ // registered orchestrator holds none. Subscriptions reserve a fraction of full capacity; prepaid
75
+ // reserves max(fraction × daily limit, floor), capped by the allowance and the cash balance.
76
+ export function protectedReserve({ window, policy, orchestratorCount }) {
77
+ if (!window) return null;
78
+ if (!Number.isFinite(Number(orchestratorCount)) || orchestratorCount < 1) return 0;
79
+ const ppm = Number(policy?.reserveFractionPpm) || 0;
80
+ const fractionOf = (amount) => Math.floor((Number(amount) * ppm) / 1e6);
81
+ const windowCapacity = window.capacity == null ? null : Number(window.capacity);
82
+ if (window.unit === 'usdMicros') {
83
+ const floor = Number(policy?.prepaidReserveFloorMicros) || 0;
84
+ if (windowCapacity == null) return null;
85
+ const reserve = Math.max(fractionOf(windowCapacity), floor);
86
+ const caps = [windowCapacity];
87
+ if (window.remaining?.value != null && window.remaining.status === 'ok') {
88
+ caps.push(Math.max(0, Number(window.remaining.value)));
89
+ }
90
+ return Math.min(reserve, ...caps);
91
+ }
92
+ if (windowCapacity == null) return null;
93
+ return fractionOf(windowCapacity);
94
+ }
95
+
96
+ // The single active escrow override for one account/window (§5). Operator repair grants a
97
+ // signed, expiring, amount-limited allowance charged to one specified real/shared escrow pool;
98
+ // it can never mint per-seat pools, so only ONE bounded override is active per deficit — older
99
+ // overlapping ones are superseded and debit nothing.
100
+ export function activeOverride({ overrides = [], accountId: id, windowId, nowMs }) {
101
+ const matching = overrides.filter((o) => String(o?.accountId) === String(id)
102
+ && String(o?.windowId) === String(windowId)
103
+ && Number(o?.expiresAtMs) > nowMs
104
+ && String(o?.approvalId || '') !== '');
105
+ if (!matching.length) return null;
106
+ matching.sort((a, b) => (Number(b.expiresAtMs) - Number(a.expiresAtMs)) || compare(a.id, b.id));
107
+ return matching[0];
108
+ }
109
+
110
+ // Escrow debits per pool: each active override debits exactly its own named pool (§5, D4).
111
+ export function escrowDebits({ overrides = [], nowMs }) {
112
+ const debits = new Map();
113
+ for (const override of overrides) {
114
+ if (Number(override?.expiresAtMs) <= nowMs || String(override?.approvalId || '') === '') continue;
115
+ const pool = String(override.escrowPoolId);
116
+ debits.set(pool, (debits.get(pool) || 0) + (Number(override?.amount) || 0));
117
+ }
118
+ return [...debits.entries()].sort((a, b) => compare(a[0], b[0]))
119
+ .map(([escrowPoolId, amount]) => ({ escrowPoolId, amount }));
120
+ }
121
+
122
+ // Admission for one window (§5): fresh remaining - protected reserve - unreflected liability
123
+ // >= new max liability. Orchestrator-bound admissions may draw the protected portion; ordinary
124
+ // crew attempts may not. Unmapped account, stale/unknown balance, missing reset on a limited
125
+ // window and unknown price each defer with their own reason; available never goes negative.
126
+ export function windowAdmission({ window, account, policy, nowMs, orchestrator = false, maxLiability, overrides = [] }) {
127
+ const reasons = [];
128
+ if (!window || !account) return { admit: false, available: 0, reserve: 0, reasons: ['window_missing'] };
129
+ if (account.status !== 'verified') reasons.push('account_unmapped');
130
+ const freshness = observationFreshness(window.remaining, { nowMs, ttlMs: Number(policy?.balanceTtlMs) || 0 });
131
+ if (!freshness.fresh) {
132
+ reasons.push(freshness.status === 'unknown' ? 'balance_unknown' : `balance_${freshness.status}`);
133
+ }
134
+ const remaining = window.remaining?.value == null ? null : Number(window.remaining.value);
135
+ const reserve = protectedReserve({ window, policy, orchestratorCount: account.orchestratorCount });
136
+ if (reserve == null && account.orchestratorCount > 0) reasons.push('reserve_unknown');
137
+ if (maxLiability == null) reasons.push('price_unknown');
138
+ const limited = window.kind === 'quota';
139
+ if (limited && window.resetsAtMs == null) reasons.push('reset_missing');
140
+ const held = Number(window.heldLiability) || 0;
141
+ const override = activeOverride({ overrides, accountId: account.id, windowId: window.id, nowMs });
142
+ const overrideAmount = override ? Number(override.amount) || 0 : 0;
143
+ let available = null;
144
+ if (remaining != null && reserve != null) {
145
+ available = Math.max(0, remaining - (orchestrator ? 0 : reserve) - held + overrideAmount);
146
+ }
147
+ const admit = reasons.length === 0 && available != null && maxLiability != null && available >= maxLiability;
148
+ if (!admit && reasons.length === 0 && maxLiability != null && available != null) reasons.push('insufficient');
149
+ return { admit, available: available == null ? null : available, reserve: reserve || 0,
150
+ override: override ? { id: override.id, escrowPoolId: override.escrowPoolId, amount: overrideAmount } : null,
151
+ reasons: [...new Set(reasons)] };
152
+ }
153
+
154
+ // All-or-nothing admission across every window a charge set touches (§5, D3): reserve every
155
+ // required window or defer all of them. Charges on the same window sum before the check so one
156
+ // plan cannot double-book its own proposals; unit mismatches never add dollars to quota shares.
157
+ export function admitCharges({ accounts, charges, policy, nowMs, orchestrator = false, overrides = [] }) {
158
+ const windows = new Map();
159
+ for (const account of accounts || []) {
160
+ for (const window of account.windows || []) windows.set(`${account.id}\u0000${window.id}`, { window, account });
161
+ }
162
+ const needed = new Map();
163
+ for (const charge of charges || []) {
164
+ const key = `${String(charge?.accountId)}\u0000${String(charge?.windowId)}`;
165
+ const entry = needed.get(key) || { key, accountId: String(charge?.accountId), windowId: String(charge?.windowId),
166
+ unit: charge?.unit, estimate: 0, maxLiability: 0, priceKnown: true };
167
+ if (charge?.estimate == null || charge?.maxLiability == null) entry.priceKnown = false;
168
+ if (entry.unit == null) entry.unit = charge?.unit;
169
+ else if (String(entry.unit) !== String(charge?.unit)) entry.unit = 'mismatch';
170
+ entry.estimate += Number(charge?.estimate) || 0;
171
+ entry.maxLiability += Number(charge?.maxLiability) || 0;
172
+ needed.set(key, entry);
173
+ }
174
+ const results = [];
175
+ const reasons = [];
176
+ for (const entry of needed.values()) {
177
+ const target = windows.get(entry.key);
178
+ if (!target) { reasons.push('window_unknown'); results.push({ ...entry, admit: false, reasons: ['window_unknown'] }); continue; }
179
+ const { window, account } = target;
180
+ if (entry.unit === 'mismatch' || String(entry.unit) !== String(window.unit)) {
181
+ reasons.push('unit_mismatch');
182
+ results.push({ ...entry, windowId: window.id, admit: false, reasons: ['unit_mismatch'] });
183
+ continue;
184
+ }
185
+ const result = windowAdmission({ window, account, policy, nowMs, orchestrator,
186
+ maxLiability: entry.priceKnown ? entry.maxLiability : null, overrides });
187
+ results.push({ ...entry, windowId: window.id, ...result });
188
+ if (!result.admit) reasons.push(...result.reasons);
189
+ }
190
+ const admit = results.length > 0 && results.every((result) => result.admit);
191
+ return { admit, results, reasons: [...new Set(reasons)] };
192
+ }
193
+
194
+ // ---- watermark-less epochs (§5) ---------------------------------------------------------------
195
+
196
+ // U over the requests since the anchor: a settled request keeps its accounted charge; an
197
+ // unresolved one contributes the larger of known usage and its still-unresolved upper bound
198
+ // (unknown retains its bound). Every request appears once; replacements are the caller's
199
+ // resolved per-request values (spend.mjs never sums a request's estimate and its billing twice).
200
+ export function epochUsage(requests = []) {
201
+ let usage = 0;
202
+ let unresolvedUpperBounds = 0;
203
+ let reconciled = true;
204
+ for (const request of requests) {
205
+ const upper = Number(request?.upperBound);
206
+ if (request?.settled) {
207
+ const accounted = request.accountedCharge == null ? (Number.isFinite(upper) ? upper : null) : Number(request.accountedCharge);
208
+ if (accounted == null) { usage = null; } else if (usage != null) usage += accounted;
209
+ } else {
210
+ reconciled = false;
211
+ const known = Number(request?.knownUsage);
212
+ if (!Number.isFinite(upper)) { usage = null; continue; }
213
+ const contribution = Number.isFinite(known) ? Math.max(known, upper) : upper;
214
+ if (usage != null) usage += contribution;
215
+ unresolvedUpperBounds += upper;
216
+ }
217
+ }
218
+ return { usage, unresolvedUpperBounds, reconciled };
219
+ }
220
+
221
+ // Available before reserve for a watermark-less window: min(R0 - U, latestFreshRemaining -
222
+ // unresolvedUpperBounds), clamped at zero. A higher observation never replenishes R0 during the
223
+ // epoch — the latest observation only SUBTRACTS, so an unwatermarked refill cannot double-credit.
224
+ export function epochAvailability({ anchorRemaining, requests, latestRemaining }) {
225
+ const { usage, unresolvedUpperBounds } = epochUsage(requests);
226
+ const terms = [];
227
+ if (anchorRemaining != null && usage != null) terms.push(Math.max(0, anchorRemaining - usage));
228
+ if (latestRemaining != null) terms.push(Math.max(0, latestRemaining - unresolvedUpperBounds));
229
+ if (!terms.length) return { available: null, usage, unresolvedUpperBounds };
230
+ return { available: Math.min(...terms), usage, unresolvedUpperBounds };
231
+ }
232
+
233
+ // A new anchor requires every request reconciled AND a fresh observation known to include their
234
+ // billing, or a PROVED provider reset with old liabilities separately carried (§5, D17). A
235
+ // missing proof keeps the conservative epoch — defer, never guess capacity back.
236
+ export function canReanchor({ requests, observation, resetProof }) {
237
+ const { reconciled } = epochUsage(requests);
238
+ const observationCovers = observation?.status === 'ok' && observation?.value != null
239
+ && observation.observedAtMs != null && Number.isFinite(Number(observation.observedAtMs));
240
+ if (reconciled && observationCovers) return { reanchor: true, reason: 'settled_and_observed' };
241
+ if (resetProof?.proved && resetProof?.oldLiabilitiesCarried === true) {
242
+ return { reanchor: true, reason: 'proved_reset' };
243
+ }
244
+ return { reanchor: false, reason: reconciled ? 'observation_not_covering' : 'requests_unreconciled' };
245
+ }
246
+
247
+ // ---- daily windows, reset and boundary holds (§5.6, D17) --------------------------------------
248
+
249
+ const DAY_MS = 86400e3;
250
+
251
+ function civilDay(ms, timeZone) {
252
+ const formatter = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' });
253
+ return formatter.format(new Date(ms));
254
+ }
255
+
256
+ // The daily window for an instant in a zone (§5: UTC calendar days by default; a time-zone
257
+ // change takes effect at the next boundary). The window id names zone + civil date so a zone
258
+ // switch mid-day cannot mint a second allowance for the same civil date.
259
+ export function dailyWindow({ nowMs, timeZone = 'UTC' }) {
260
+ const date = civilDay(nowMs, timeZone);
261
+ const dayIndex = Math.floor(nowMs / DAY_MS);
262
+ return {
263
+ id: `daily:${timeZone}:${date}`,
264
+ startsAtMs: timeZone === 'UTC' ? dayIndex * DAY_MS : null,
265
+ resetsAtMs: timeZone === 'UTC' ? (dayIndex + 1) * DAY_MS : null,
266
+ date,
267
+ timeZone,
268
+ };
269
+ }
270
+
271
+ // A zone change takes effect at the next boundary and cannot create a second allowance for the
272
+ // current day (§2 Policy defaults): the debited window keeps running — same civil date, or the
273
+ // window is simply still open. Only a genuinely crossed boundary starts the next window.
274
+ export function zoneChangeKeepsAllowance({ window, newTimeZone, nowMs }) {
275
+ const current = dailyWindow({ nowMs, timeZone: newTimeZone });
276
+ if (window?.date != null && window.date === current.date) return true;
277
+ return Number.isFinite(Number(window?.resetsAtMs)) && Number(window.resetsAtMs) > nowMs;
278
+ }
279
+
280
+ // Rollover into the next daily window (§5.6): a new day (or a proved provider reset) creates a
281
+ // fresh allowance but NEVER clears old leases — unresolved liability carries across, so a reset
282
+ // cannot launder an unresolved request into free capacity, and the new allowance cannot
283
+ // double-pay work the old window already holds.
284
+ export function applyRollover({ window, freshRemaining, capacity, resetsAtMs, nowMs }) {
285
+ return {
286
+ ...window,
287
+ remaining: freshRemaining,
288
+ capacity: capacity ?? window.capacity ?? null,
289
+ resetsAtMs: resetsAtMs ?? null,
290
+ startsAtMs: nowMs,
291
+ heldLiability: Number(window?.heldLiability) || 0,
292
+ accountedThroughEvent: window?.accountedThroughEvent ?? null,
293
+ };
294
+ }
295
+
296
+ // A request that can cross a boundary reserves its max unresolved charge against the next daily
297
+ // window too (§5.6). A delayed receipt debits the occurrence day's ledger; a request with an
298
+ // UNKNOWN occurrence time holds in BOTH possible days until reconciled — never only the current
299
+ // one, and never neither.
300
+ export function boundaryHolds({ occurredAtMs, nowMs, timeZone = 'UTC', unresolvedCharge }) {
301
+ const charge = Number(unresolvedCharge) || 0;
302
+ const holds = [];
303
+ const hold = (window) => holds.push({ windowId: window.id, amount: charge });
304
+ if (occurredAtMs == null) {
305
+ hold(dailyWindow({ nowMs: nowMs - DAY_MS, timeZone }));
306
+ hold(dailyWindow({ nowMs, timeZone }));
307
+ return { holds, occurrence: 'unknown' };
308
+ }
309
+ const occurrence = dailyWindow({ nowMs: occurredAtMs, timeZone });
310
+ hold(occurrence);
311
+ if (occurredAtMs <= nowMs && occurrence.date !== dailyWindow({ nowMs, timeZone }).date) {
312
+ hold(dailyWindow({ nowMs, timeZone }));
313
+ }
314
+ return { holds, occurrence: 'known' };
315
+ }
316
+
317
+ // ---- binding-repair evidence (§5.6, D10) --------------------------------------------------------
318
+
319
+ // A collector identity observation is a signed document: the collector (a hub identity, never the
320
+ // seat and never the operator) signs exactly evidenceString() with its trantor Ed25519 key. Same
321
+ // discipline as identity.mjs's endorsementString: newline-joined, fixed arity, no field may
322
+ // contain a newline. The credential fingerprint inside is internal — no validator result returns it.
323
+ const EVIDENCE_SCHEME = 'trantor-evidence-v1';
324
+ export const EVIDENCE_FRESH_MS = 5 * 60_000;
325
+ const EVIDENCE_SKEW_MS = 120_000;
326
+ const HEX64 = /^[0-9a-f]{64}$/i;
327
+
328
+ export function evidenceString(evidence) {
329
+ return [EVIDENCE_SCHEME, String(evidence?.collectorPubkey ?? ''), String(evidence?.seatId ?? ''),
330
+ String(evidence?.machine ?? ''), String(evidence?.provider ?? ''),
331
+ String(evidence?.billingSubject ?? ''), String(evidence?.toAccountId ?? ''),
332
+ String(evidence?.credentialFingerprint ?? ''), String(evidence?.credentialRevision ?? ''),
333
+ String(evidence?.observedAtMs ?? '')].join('\n');
334
+ }
335
+
336
+ const b64u = (buf) => buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
337
+ const evidencePubKey = (hex) => createPublicKey({
338
+ key: { kty: 'OKP', crv: 'Ed25519', x: b64u(Buffer.from(hex, 'hex')) }, format: 'jwk' });
339
+
340
+ // Pure Ed25519 check of the observation's own signature over identity.mjs's raw-hex key format.
341
+ function verifyEvidenceSignature(evidence) {
342
+ const pubkey = String(evidence?.collectorPubkey || '');
343
+ if (!HEX64.test(pubkey)) return false;
344
+ try {
345
+ return cryptoVerify(null, Buffer.from(evidenceString(evidence), 'utf8'), evidencePubKey(pubkey),
346
+ Buffer.from(String(evidence?.signature || ''), 'base64'));
347
+ } catch { return false; }
348
+ }
349
+
350
+ // Validate collector evidence and canonical account identity for an account-binding repair
351
+ // (§5.6): a signed, 5m-fresh collector observation bound to the seat's credential
352
+ // fingerprint/revision, a registered canonical target resolving to the observed subject, and
353
+ // unique provider-subject + expected-revision checks against the caller's rows.
354
+ export function validateBindingRepairEvidence({ request, evidence, seat, accounts = [], policyVersion,
355
+ activeLeaseSetHash, nowMs, verifySignature = verifyEvidenceSignature }) {
356
+ const finish = (ok, status, code, reasons, extra = {}) => ({ ok, status, code, reasons, evidenceId: evidence?.id ?? null, ...extra });
357
+ const req = (field) => String(request?.[field] ?? '');
358
+ if (!request || !req('idempotencyKey') || !req('expectedBindingRevision') || !req('toAccountId')
359
+ || !req('identityEvidenceId') || !req('expectedPolicyVersion') || !req('reason')
360
+ || request.expectedFromAccountId != null && !String(request.expectedFromAccountId)
361
+ || request.expectedAffectedLeaseSetHash == null) {
362
+ return finish(false, 422, 'schema_invalid', ['request_malformed']);
363
+ }
364
+ if (String(request.outstandingLeaseAction) !== 'stop-settle-reacquire') {
365
+ return finish(false, 422, 'schema_invalid', ['unsupported_lease_action']);
366
+ }
367
+ const fields = ['id', 'collectorPubkey', 'signature', 'seatId', 'machine', 'provider',
368
+ 'billingSubject', 'toAccountId', 'credentialFingerprint', 'credentialRevision'];
369
+ if (!evidence || fields.some((f) => !String(evidence[f] ?? '')) || !Number.isFinite(Number(evidence.observedAtMs))
370
+ || Number(evidence.observedAtMs) <= 0) {
371
+ return finish(false, 422, 'schema_invalid', ['evidence_malformed']);
372
+ }
373
+ if (String(evidence.id) !== req('identityEvidenceId')) {
374
+ return finish(false, 422, 'schema_invalid', ['evidence_id_mismatch']);
375
+ }
376
+ if (!verifySignature(evidence)) {
377
+ return finish(false, 422, 'schema_invalid', ['evidence_unverified']);
378
+ }
379
+ const observedAtMs = Number(evidence.observedAtMs);
380
+ if (observedAtMs > nowMs + EVIDENCE_SKEW_MS || nowMs - observedAtMs > EVIDENCE_FRESH_MS) {
381
+ return finish(false, 422, 'schema_invalid', ['evidence_stale']);
382
+ }
383
+ if (String(evidence.seatId) !== String(seat?.seatId ?? '')) {
384
+ return finish(false, 422, 'schema_invalid', ['evidence_seat_mismatch']);
385
+ }
386
+ if (String(evidence.credentialFingerprint) !== String(seat?.credentialFingerprint ?? '')
387
+ || String(evidence.credentialRevision) !== String(seat?.credentialRevision ?? '')) {
388
+ return finish(false, 409, 'credential_changed', ['credential_changed']);
389
+ }
390
+ const target = accounts.find((a) => String(a?.id) === req('toAccountId'));
391
+ if (!target) return finish(false, 422, 'schema_invalid', ['target_not_registered']);
392
+ if (String(target.status) !== 'verified') return finish(false, 422, 'schema_invalid', ['target_not_canonical']);
393
+ if (String(evidence.toAccountId) !== req('toAccountId')) {
394
+ return finish(false, 422, 'schema_invalid', ['evidence_target_mismatch']);
395
+ }
396
+ if (String(evidence.provider) !== String(target.provider ?? '') || String(evidence.billingSubject) !== String(target.subject ?? '')) {
397
+ return finish(false, 422, 'schema_invalid', ['evidence_subject_mismatch']);
398
+ }
399
+ if (request.expectedFromAccountId != null
400
+ && !accounts.some((a) => String(a?.id) === String(request.expectedFromAccountId))) {
401
+ return finish(false, 422, 'schema_invalid', ['source_not_registered']);
402
+ }
403
+ const implicated = accounts.filter((a) => String(a?.id) !== String(target.id)
404
+ && String(a?.provider ?? '') === String(target.provider ?? '')
405
+ && String(a?.subject ?? '') === String(target.subject ?? ''));
406
+ if (implicated.length) {
407
+ return finish(false, 409, 'account_subject_conflict', ['account_subject_conflict'], {
408
+ implicatedAccountIds: [...new Set([String(target.id), ...implicated.map((a) => String(a.id))])].sort(compare),
409
+ seatId: String(seat?.seatId ?? ''),
410
+ });
411
+ }
412
+ if (String(request.expectedBindingRevision) !== String(seat?.bindingRevision ?? '')) {
413
+ return finish(false, 409, 'binding_stale', ['binding_stale']);
414
+ }
415
+ if ((seat?.accountId ?? null) !== (request.expectedFromAccountId ?? null)) {
416
+ return finish(false, 409, 'binding_from_mismatch', ['binding_from_mismatch']);
417
+ }
418
+ if (String(request.expectedPolicyVersion) !== String(policyVersion ?? '')) {
419
+ return finish(false, 409, 'policy_stale', ['policy_stale']);
420
+ }
421
+ if (String(request.expectedAffectedLeaseSetHash) !== String(activeLeaseSetHash ?? '')) {
422
+ return finish(false, 409, 'lease_set_changed', ['lease_set_changed']);
423
+ }
424
+ return finish(true, 200, null, [], {
425
+ repair: {
426
+ idempotencyKey: req('idempotencyKey'),
427
+ seatId: String(seat.seatId),
428
+ fromAccountId: seat.accountId ?? null,
429
+ toAccountId: String(target.id),
430
+ bindingRevision: String(seat.bindingRevision ?? ''),
431
+ identityEvidenceId: String(evidence.id),
432
+ evidenceHash: `sha256:${createHash('sha256').update(evidenceString(evidence)).digest('hex')}`,
433
+ policyVersion: String(policyVersion ?? ''),
434
+ leaseSetHash: String(activeLeaseSetHash ?? ''),
435
+ outstandingLeaseAction: String(request.outstandingLeaseAction),
436
+ reason: req('reason'),
437
+ },
438
+ collectorPubkey: String(evidence.collectorPubkey),
439
+ observedMachine: String(evidence.machine),
440
+ observedAtMs,
441
+ });
442
+ }