@opengeni/contracts 0.18.0 → 0.19.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1405 @@
1
+ /**
2
+ * Adaptive Codex fleet policy, replay contract, and shadow evaluator.
3
+ *
4
+ * This module is deliberately pure and browser-safe. It accepts only bounded,
5
+ * metadata-only snapshots whose candidate keys are opaque aliases assigned by
6
+ * the caller. It never accepts credential ids, account emails, labels, token
7
+ * material, prompts, or tenant activity. The same normalized snapshot can be
8
+ * persisted in a session event, replayed offline, and compared byte-for-byte.
9
+ *
10
+ * V1 is shadow-only at the runtime integration boundary. The evaluator models
11
+ * later placement, admission, manager priority, borrowing, emergency-fuse, and
12
+ * named-overlay semantics so they can be proven with deterministic simulations
13
+ * before any independent kill switch is allowed to affect a live allocation.
14
+ */
15
+
16
+ import { sha256 } from "@noble/hashes/sha256";
17
+ import { bytesToHex } from "@noble/hashes/utils";
18
+
19
+ export const CODEX_FLEET_POLICY_SCHEMA_VERSION = 1 as const;
20
+ export const CODEX_FLEET_POLICY_VERSION = "adaptive-shadow-v1" as const;
21
+ export const CODEX_FLEET_POLICY_MAX_CANDIDATES = 32;
22
+ export const CODEX_FLEET_POLICY_MAX_OVERLAYS_PER_CANDIDATE = 4;
23
+
24
+ const MAX_DURATION_MS = 31 * 24 * 60 * 60_000;
25
+ const MAX_COUNT = 1_000_000;
26
+ const SCORE_SCALE = 100;
27
+
28
+ /**
29
+ * Replay-integrity ordering for bounded ASCII-safe fleet keys and aliases.
30
+ *
31
+ * Locale-aware collation is intentionally forbidden here because its result
32
+ * can depend on locale and ICU data. Relational string comparison uses
33
+ * ECMAScript UTF-16 code-unit ordering and is therefore identical in Bun,
34
+ * Node, and browsers.
35
+ */
36
+ export function compareCodexFleetCanonicalStringsV1(left: string, right: string): number {
37
+ return left < right ? -1 : left > right ? 1 : 0;
38
+ }
39
+
40
+ export type CodexFleetConfidence = "unknown" | "low" | "medium" | "high";
41
+ export type CodexFleetCandidateStatus = "active" | "needs_relogin" | "error" | "unknown";
42
+ export type CodexFleetCacheState = "unknown" | "healthy" | "collapsed";
43
+ export type CodexFleetPriority = "standard" | "manager";
44
+ export type CodexFleetPlacementKind = "new" | "fenced_in_flight";
45
+ export type CodexFleetOverlayMode = "none" | "prefer" | "isolate";
46
+
47
+ export type CodexFleetQuotaWindowV1 = {
48
+ /** Provider-reported percentage from a workspace-local cache, never inferred tenant truth. */
49
+ usedPercent: number | null;
50
+ /** Relative to input.observedAtMs. Zero means the reported window has reset. */
51
+ resetRemainingMs: number | null;
52
+ };
53
+
54
+ export type CodexFleetCandidateV1 = {
55
+ /** Opaque, event-local alias such as c00. Never a credential/account id. */
56
+ key: string;
57
+ status: CodexFleetCandidateStatus;
58
+ allocatorEnabled: boolean;
59
+ /** Relative cooldown. A positive value excludes only NEW placements. */
60
+ cooldownRemainingMs: number | null;
61
+ activeLeaseCount: number;
62
+ quota: {
63
+ primary: CodexFleetQuotaWindowV1;
64
+ secondary: CodexFleetQuotaWindowV1;
65
+ checkedAgeMs: number | null;
66
+ confidence: CodexFleetConfidence;
67
+ };
68
+ /**
69
+ * Runtime-observed cache evidence. It may be absent because the production
70
+ * baseline currently exists as aggregate metrics/logs rather than allocator
71
+ * state. Absence is explicit uncertainty, not a zero cache hit.
72
+ */
73
+ cache: {
74
+ hitRatio: number | null;
75
+ sampledTokens: number | null;
76
+ checkedAgeMs: number | null;
77
+ confidence: CodexFleetConfidence;
78
+ /** Previously latched state; the evaluator applies dwell and recovery thresholds. */
79
+ state: CodexFleetCacheState;
80
+ /** Duration of the current continuous below/above-threshold observation. */
81
+ thresholdObservedForMs: number | null;
82
+ };
83
+ /** Workspace-local observed burn, separate from unexplained/external inference. */
84
+ observedBurn: {
85
+ primaryPercentPerHour: number | null;
86
+ secondaryPercentPerHour: number | null;
87
+ confidence: CodexFleetConfidence;
88
+ };
89
+ /**
90
+ * Unexplained/external burn is an inference only. The name and confidence are
91
+ * load-bearing: consumers must never relabel it as provider or tenant truth.
92
+ */
93
+ inferredUnexplainedBurn: {
94
+ primaryPercentPerHour: number | null;
95
+ secondaryPercentPerHour: number | null;
96
+ confidence: CodexFleetConfidence;
97
+ };
98
+ /** Opaque named-policy keys. Ignored unless overlaysEnabled is independently true. */
99
+ overlayKeys: string[];
100
+ };
101
+
102
+ export type CodexFleetAdmissionSnapshotV1 = {
103
+ /** Dynamically observed capacity, not a static per-account slot allocation. */
104
+ dynamicCapacityUnits: number | null;
105
+ inUseUnits: number;
106
+ queuedManagerCount: number;
107
+ emergencyFuseActive: boolean;
108
+ };
109
+
110
+ export type CodexFleetDecisionInputV1 = {
111
+ observedAtMs: number;
112
+ request: {
113
+ placement: CodexFleetPlacementKind;
114
+ priority: CodexFleetPriority;
115
+ currentCandidateKey: string | null;
116
+ waitAgeMs: number;
117
+ overlayKey: string | null;
118
+ overlayMode: CodexFleetOverlayMode;
119
+ };
120
+ admission: CodexFleetAdmissionSnapshotV1;
121
+ candidates: CodexFleetCandidateV1[];
122
+ };
123
+
124
+ export type CodexFleetPolicyConfigV1 = {
125
+ maxCandidates: number;
126
+ quotaFreshForMs: number;
127
+ quotaStaleAfterMs: number;
128
+ placementUsageCeilingPercent: number;
129
+ cacheFreshForMs: number;
130
+ cacheCollapseThreshold: number;
131
+ cacheCollapseRecoveryThreshold: number;
132
+ cacheMinimumSampledTokens: number;
133
+ cacheCollapseDwellMs: number;
134
+ cacheRecoveryDwellMs: number;
135
+ activeLeaseScore: number;
136
+ unknownQuotaScore: number;
137
+ lowQuotaConfidenceScore: number;
138
+ mediumQuotaConfidenceScore: number;
139
+ inferredBurnScorePerPercentHour: number;
140
+ observedBurnScorePerPercentHour: number;
141
+ /** Maximum exhaustion-before-reset gap that contributes placement pressure. */
142
+ runwayRiskCapHours: number;
143
+ runwayScorePerAtRiskHour: number;
144
+ healthyCacheAffinityBenefit: number;
145
+ unknownCacheAffinityBenefit: number;
146
+ collapsedCacheAffinityBenefit: number;
147
+ switchHysteresisScore: number;
148
+ admissionPacingEnabled: boolean;
149
+ managerPriorityEnabled: boolean;
150
+ managerStandardStarvationMs: number;
151
+ emergencyFuseEnabled: boolean;
152
+ overlaysEnabled: boolean;
153
+ overlayPreferenceScore: number;
154
+ };
155
+
156
+ /**
157
+ * Experimental shadow defaults. None of the boolean control fields is enabled;
158
+ * production behavior therefore remains sticky-sharded until operators enable
159
+ * each independently after shadow acceptance.
160
+ */
161
+ export const DEFAULT_CODEX_FLEET_POLICY_V1: CodexFleetPolicyConfigV1 = Object.freeze({
162
+ maxCandidates: CODEX_FLEET_POLICY_MAX_CANDIDATES,
163
+ quotaFreshForMs: 15 * 60_000,
164
+ quotaStaleAfterMs: 60 * 60_000,
165
+ placementUsageCeilingPercent: 90,
166
+ cacheFreshForMs: 30 * 60_000,
167
+ cacheCollapseThreshold: 0.4,
168
+ cacheCollapseRecoveryThreshold: 0.65,
169
+ cacheMinimumSampledTokens: 4_096,
170
+ cacheCollapseDwellMs: 5 * 60_000,
171
+ cacheRecoveryDwellMs: 10 * 60_000,
172
+ activeLeaseScore: 8 * SCORE_SCALE,
173
+ unknownQuotaScore: 16 * SCORE_SCALE,
174
+ lowQuotaConfidenceScore: 10 * SCORE_SCALE,
175
+ mediumQuotaConfidenceScore: 4 * SCORE_SCALE,
176
+ inferredBurnScorePerPercentHour: 0.2 * SCORE_SCALE,
177
+ observedBurnScorePerPercentHour: 0.1 * SCORE_SCALE,
178
+ runwayRiskCapHours: 2,
179
+ runwayScorePerAtRiskHour: 8 * SCORE_SCALE,
180
+ healthyCacheAffinityBenefit: 32 * SCORE_SCALE,
181
+ unknownCacheAffinityBenefit: 24 * SCORE_SCALE,
182
+ collapsedCacheAffinityBenefit: 6 * SCORE_SCALE,
183
+ switchHysteresisScore: 8 * SCORE_SCALE,
184
+ admissionPacingEnabled: false,
185
+ managerPriorityEnabled: false,
186
+ managerStandardStarvationMs: 2 * 60_000,
187
+ emergencyFuseEnabled: false,
188
+ overlaysEnabled: false,
189
+ overlayPreferenceScore: 12 * SCORE_SCALE,
190
+ });
191
+
192
+ export type CodexFleetScoreV1 = {
193
+ candidateKey: string;
194
+ eligible: boolean;
195
+ rejectionReason:
196
+ | "allocator_disabled"
197
+ | "unavailable"
198
+ | "cooling"
199
+ | "quota_ceiling"
200
+ | "overlay_isolation"
201
+ | null;
202
+ quotaPressure: number;
203
+ leasePressure: number;
204
+ observedBurnPressure: number;
205
+ inferredBurnPressure: number;
206
+ runwayPressure: number;
207
+ uncertaintyPressure: number;
208
+ cacheAffinityBenefit: number;
209
+ cacheState: CodexFleetCacheState;
210
+ overlayPreferenceBenefit: number;
211
+ total: number;
212
+ confidence: CodexFleetConfidence;
213
+ };
214
+
215
+ export type CodexFleetAdmissionDecisionV1 = {
216
+ outcome: "admit" | "pace";
217
+ reason:
218
+ | "fenced_in_flight"
219
+ | "pacing_disabled"
220
+ | "capacity_unknown"
221
+ | "capacity_available"
222
+ | "work_conserving_borrow"
223
+ | "manager_priority"
224
+ | "standard_starvation_bound"
225
+ | "capacity_saturated"
226
+ | "emergency_fuse";
227
+ /** True only when standard work uses otherwise-idle capacity with no manager backlog. */
228
+ borrowedIdleCapacity: boolean;
229
+ };
230
+
231
+ export type CodexFleetDecisionV1 = {
232
+ outcome: "selected" | "paced" | "none";
233
+ selectedCandidateKey: string | null;
234
+ reason:
235
+ | "fenced_in_flight"
236
+ | "fenced_candidate_missing"
237
+ | "admission_paced"
238
+ | "no_eligible_candidate"
239
+ | "overlay_isolated_empty"
240
+ | "best_score"
241
+ | "affinity_best"
242
+ | "hysteresis_hold";
243
+ admission: CodexFleetAdmissionDecisionV1;
244
+ borrowedOverlayCapacity: boolean;
245
+ strandedEligibleCount: number;
246
+ confidence: CodexFleetConfidence;
247
+ scores: CodexFleetScoreV1[];
248
+ };
249
+
250
+ export type CodexFleetReplayRecordV1 = {
251
+ schemaVersion: typeof CODEX_FLEET_POLICY_SCHEMA_VERSION;
252
+ policyVersion: typeof CODEX_FLEET_POLICY_VERSION;
253
+ mode: "shadow";
254
+ policy: CodexFleetPolicyConfigV1;
255
+ input: CodexFleetDecisionInputV1;
256
+ truncatedCandidateCount: number;
257
+ policyFingerprint: string;
258
+ inputFingerprint: string;
259
+ decision: CodexFleetDecisionV1;
260
+ decisionFingerprint: string;
261
+ };
262
+
263
+ export type CodexFleetReplayVerdictV1 = {
264
+ matches: boolean;
265
+ policyFingerprintMatches: boolean;
266
+ inputFingerprintMatches: boolean;
267
+ decisionFingerprintMatches: boolean;
268
+ recordedDecisionFingerprintMatches: boolean;
269
+ decision: CodexFleetDecisionV1;
270
+ };
271
+
272
+ type NormalizedInput = {
273
+ input: CodexFleetDecisionInputV1;
274
+ truncatedCandidateCount: number;
275
+ };
276
+
277
+ export function createCodexFleetReplayRecordV1(
278
+ input: CodexFleetDecisionInputV1,
279
+ policy: CodexFleetPolicyConfigV1 = DEFAULT_CODEX_FLEET_POLICY_V1,
280
+ ): CodexFleetReplayRecordV1 {
281
+ const normalizedPolicy = normalizePolicy(policy);
282
+ const normalized = normalizeInput(input, normalizedPolicy.maxCandidates);
283
+ const decision = evaluateCodexFleetDecisionV1(normalized.input, normalizedPolicy);
284
+ return {
285
+ schemaVersion: CODEX_FLEET_POLICY_SCHEMA_VERSION,
286
+ policyVersion: CODEX_FLEET_POLICY_VERSION,
287
+ mode: "shadow",
288
+ policy: normalizedPolicy,
289
+ input: normalized.input,
290
+ truncatedCandidateCount: normalized.truncatedCandidateCount,
291
+ policyFingerprint: fingerprint(normalizedPolicy),
292
+ inputFingerprint: fingerprintReplayInput(normalized.input, normalized.truncatedCandidateCount),
293
+ decision,
294
+ decisionFingerprint: fingerprint(decision),
295
+ };
296
+ }
297
+
298
+ export function replayCodexFleetDecisionV1(value: unknown): CodexFleetReplayVerdictV1 {
299
+ const record = readCodexFleetReplayRecordV1(value);
300
+ const policyFingerprintMatches = fingerprint(record.policy) === record.policyFingerprint;
301
+ const inputFingerprintMatches =
302
+ fingerprintReplayInput(record.input, record.truncatedCandidateCount) ===
303
+ record.inputFingerprint;
304
+ const decision = evaluateCodexFleetDecisionV1(record.input, record.policy);
305
+ const replayedDecisionFingerprint = fingerprint(decision);
306
+ const recordedDecisionFingerprintMatches =
307
+ fingerprint(record.decision) === record.decisionFingerprint;
308
+ const decisionFingerprintMatches =
309
+ recordedDecisionFingerprintMatches &&
310
+ replayedDecisionFingerprint === record.decisionFingerprint;
311
+ return {
312
+ matches:
313
+ policyFingerprintMatches &&
314
+ inputFingerprintMatches &&
315
+ decisionFingerprintMatches &&
316
+ canonicalJson(decision) === canonicalJson(record.decision),
317
+ policyFingerprintMatches,
318
+ inputFingerprintMatches,
319
+ decisionFingerprintMatches,
320
+ recordedDecisionFingerprintMatches,
321
+ decision,
322
+ };
323
+ }
324
+
325
+ /**
326
+ * Canonical replay bytes for already-bounded, identity-free fleet values.
327
+ * This is exported so offline tools can prove the exact bytes across runtimes;
328
+ * it performs no redaction and must not be used with raw account metadata.
329
+ */
330
+ export function canonicalCodexFleetReplayJsonV1(value: CodexFleetReplayRecordV1): string {
331
+ return canonicalJson(value);
332
+ }
333
+
334
+ /**
335
+ * Strict reader for durable/offline replay. Unknown fields, lossy normalization,
336
+ * malformed decisions, and non-SHA-256 digests are rejected before comparison.
337
+ */
338
+ export function readCodexFleetReplayRecordV1(value: unknown): CodexFleetReplayRecordV1 {
339
+ const record = strictRecord(value, [
340
+ "schemaVersion",
341
+ "policyVersion",
342
+ "mode",
343
+ "policy",
344
+ "input",
345
+ "truncatedCandidateCount",
346
+ "policyFingerprint",
347
+ "inputFingerprint",
348
+ "decision",
349
+ "decisionFingerprint",
350
+ ]);
351
+ if (
352
+ record.schemaVersion !== CODEX_FLEET_POLICY_SCHEMA_VERSION ||
353
+ record.policyVersion !== CODEX_FLEET_POLICY_VERSION ||
354
+ record.mode !== "shadow"
355
+ ) {
356
+ throw new Error("Unsupported Codex fleet replay envelope");
357
+ }
358
+
359
+ const policy = normalizePolicy(record.policy as CodexFleetPolicyConfigV1);
360
+ if (canonicalJson(policy) !== canonicalJson(record.policy)) {
361
+ throw new Error("Codex fleet replay policy is not in canonical bounded form");
362
+ }
363
+ const normalizedInput = normalizeInput(
364
+ record.input as CodexFleetDecisionInputV1,
365
+ policy.maxCandidates,
366
+ );
367
+ if (
368
+ normalizedInput.truncatedCandidateCount !== 0 ||
369
+ canonicalJson(normalizedInput.input) !== canonicalJson(record.input)
370
+ ) {
371
+ throw new Error("Codex fleet replay input is not in canonical bounded form");
372
+ }
373
+
374
+ return {
375
+ schemaVersion: CODEX_FLEET_POLICY_SCHEMA_VERSION,
376
+ policyVersion: CODEX_FLEET_POLICY_VERSION,
377
+ mode: "shadow",
378
+ policy,
379
+ input: normalizedInput.input,
380
+ truncatedCandidateCount: strictInteger(record.truncatedCandidateCount, 0, MAX_COUNT),
381
+ policyFingerprint: strictSha256(record.policyFingerprint),
382
+ inputFingerprint: strictSha256(record.inputFingerprint),
383
+ decision: readCodexFleetDecisionV1(
384
+ record.decision,
385
+ new Set(normalizedInput.input.candidates.map((candidate) => candidate.key)),
386
+ ),
387
+ decisionFingerprint: strictSha256(record.decisionFingerprint),
388
+ };
389
+ }
390
+
391
+ export function evaluateCodexFleetDecisionV1(
392
+ input: CodexFleetDecisionInputV1,
393
+ policy: CodexFleetPolicyConfigV1 = DEFAULT_CODEX_FLEET_POLICY_V1,
394
+ ): CodexFleetDecisionV1 {
395
+ const admission = evaluateAdmission(input, policy);
396
+ const current = input.request.currentCandidateKey
397
+ ? input.candidates.find((candidate) => candidate.key === input.request.currentCandidateKey)
398
+ : undefined;
399
+
400
+ // A fenced turn is immutable under every overlay, pacing rule, manager class,
401
+ // or emergency fuse. If its candidate vanished, fail closed instead of moving.
402
+ if (input.request.placement === "fenced_in_flight") {
403
+ if (!current) {
404
+ return emptyDecision("fenced_candidate_missing", admission, "unknown");
405
+ }
406
+ return {
407
+ outcome: "selected",
408
+ selectedCandidateKey: current.key,
409
+ reason: "fenced_in_flight",
410
+ admission,
411
+ borrowedOverlayCapacity: false,
412
+ strandedEligibleCount: 0,
413
+ confidence: candidateConfidence(current, policy),
414
+ scores: [scoreCandidate(current, input, policy, false)],
415
+ };
416
+ }
417
+
418
+ if (admission.outcome === "pace") {
419
+ return emptyDecision("admission_paced", admission, "unknown");
420
+ }
421
+
422
+ const scored = input.candidates.map((candidate) =>
423
+ scoreCandidate(candidate, input, policy, false),
424
+ );
425
+ const baseEligibleKeys = new Set(
426
+ scored.filter((candidate) => candidate.eligible).map((candidate) => candidate.candidateKey),
427
+ );
428
+ const overlay = selectOverlayScope(input, policy, baseEligibleKeys);
429
+ const scopedScores = input.candidates
430
+ .map((candidate) =>
431
+ scoreCandidate(
432
+ candidate,
433
+ input,
434
+ policy,
435
+ overlay.rejectedByIsolation.has(candidate.key),
436
+ overlay.preferredMembers.has(candidate.key),
437
+ ),
438
+ )
439
+ .sort((a, b) => compareCodexFleetCanonicalStringsV1(a.candidateKey, b.candidateKey));
440
+ const eligible = scopedScores
441
+ .filter((candidate) => candidate.eligible)
442
+ .sort(
443
+ (a, b) =>
444
+ a.total - b.total || compareCodexFleetCanonicalStringsV1(a.candidateKey, b.candidateKey),
445
+ );
446
+
447
+ if (eligible.length === 0) {
448
+ return {
449
+ ...emptyDecision(
450
+ overlay.isolatedEmpty ? "overlay_isolated_empty" : "no_eligible_candidate",
451
+ admission,
452
+ aggregateConfidence(scopedScores),
453
+ ),
454
+ strandedEligibleCount: overlay.strandedEligibleCount,
455
+ scores: scopedScores,
456
+ };
457
+ }
458
+
459
+ let selected = eligible[0]!;
460
+ let reason: CodexFleetDecisionV1["reason"] = "best_score";
461
+ const currentScore = input.request.currentCandidateKey
462
+ ? eligible.find((candidate) => candidate.candidateKey === input.request.currentCandidateKey)
463
+ : undefined;
464
+ if (currentScore) {
465
+ if (selected.candidateKey === currentScore.candidateKey) {
466
+ reason = "affinity_best";
467
+ } else if (selected.total + policy.switchHysteresisScore >= currentScore.total) {
468
+ selected = currentScore;
469
+ reason = "hysteresis_hold";
470
+ }
471
+ }
472
+
473
+ return {
474
+ outcome: "selected",
475
+ selectedCandidateKey: selected.candidateKey,
476
+ reason,
477
+ admission,
478
+ borrowedOverlayCapacity:
479
+ policy.overlaysEnabled &&
480
+ input.request.overlayMode === "prefer" &&
481
+ input.request.overlayKey !== null &&
482
+ !overlay.preferredMembers.has(selected.candidateKey),
483
+ strandedEligibleCount: overlay.strandedEligibleCount,
484
+ confidence: aggregateConfidence(eligible),
485
+ scores: scopedScores,
486
+ };
487
+ }
488
+
489
+ function evaluateAdmission(
490
+ input: CodexFleetDecisionInputV1,
491
+ policy: CodexFleetPolicyConfigV1,
492
+ ): CodexFleetAdmissionDecisionV1 {
493
+ if (input.request.placement === "fenced_in_flight") {
494
+ return {
495
+ outcome: "admit",
496
+ reason: "fenced_in_flight",
497
+ borrowedIdleCapacity: false,
498
+ };
499
+ }
500
+ if (policy.emergencyFuseEnabled && input.admission.emergencyFuseActive) {
501
+ return {
502
+ outcome: "pace",
503
+ reason: "emergency_fuse",
504
+ borrowedIdleCapacity: false,
505
+ };
506
+ }
507
+ if (!policy.admissionPacingEnabled) {
508
+ return {
509
+ outcome: "admit",
510
+ reason: "pacing_disabled",
511
+ borrowedIdleCapacity: false,
512
+ };
513
+ }
514
+ if (input.admission.dynamicCapacityUnits === null) {
515
+ // Observability-first fail-open: unknown soft capacity never invents a hard slot.
516
+ return {
517
+ outcome: "admit",
518
+ reason: "capacity_unknown",
519
+ borrowedIdleCapacity: false,
520
+ };
521
+ }
522
+ const available = Math.max(0, input.admission.dynamicCapacityUnits - input.admission.inUseUnits);
523
+ if (available === 0) {
524
+ return {
525
+ outcome: "pace",
526
+ reason: "capacity_saturated",
527
+ borrowedIdleCapacity: false,
528
+ };
529
+ }
530
+ if (
531
+ policy.managerPriorityEnabled &&
532
+ input.request.priority === "standard" &&
533
+ input.admission.queuedManagerCount > 0 &&
534
+ available <= input.admission.queuedManagerCount
535
+ ) {
536
+ if (input.request.waitAgeMs >= policy.managerStandardStarvationMs) {
537
+ return {
538
+ outcome: "admit",
539
+ reason: "standard_starvation_bound",
540
+ borrowedIdleCapacity: false,
541
+ };
542
+ }
543
+ return {
544
+ outcome: "pace",
545
+ reason: "manager_priority",
546
+ borrowedIdleCapacity: false,
547
+ };
548
+ }
549
+ if (input.request.priority === "standard" && input.admission.queuedManagerCount === 0) {
550
+ return {
551
+ outcome: "admit",
552
+ reason: "work_conserving_borrow",
553
+ borrowedIdleCapacity: true,
554
+ };
555
+ }
556
+ return {
557
+ outcome: "admit",
558
+ reason: "capacity_available",
559
+ borrowedIdleCapacity: false,
560
+ };
561
+ }
562
+
563
+ function scoreCandidate(
564
+ candidate: CodexFleetCandidateV1,
565
+ input: CodexFleetDecisionInputV1,
566
+ policy: CodexFleetPolicyConfigV1,
567
+ rejectedByIsolation: boolean,
568
+ preferredOverlayMember = false,
569
+ ): CodexFleetScoreV1 {
570
+ const confidence = candidateConfidence(candidate, policy);
571
+ const bindingUsed = bindingUsedPercent(candidate);
572
+ const hardQuotaKnown = confidence === "high" || confidence === "medium";
573
+ const rejectionReason: CodexFleetScoreV1["rejectionReason"] = !candidate.allocatorEnabled
574
+ ? "allocator_disabled"
575
+ : candidate.status !== "active"
576
+ ? "unavailable"
577
+ : (candidate.cooldownRemainingMs ?? 0) > 0
578
+ ? "cooling"
579
+ : hardQuotaKnown &&
580
+ bindingUsed !== null &&
581
+ bindingUsed >= policy.placementUsageCeilingPercent
582
+ ? "quota_ceiling"
583
+ : rejectedByIsolation
584
+ ? "overlay_isolation"
585
+ : null;
586
+
587
+ const confidenceFactor = confidenceWeight(confidence);
588
+ // Missing quota is not treated as pristine 0% or as a hard exclusion. Blend
589
+ // toward neutral 50% and add an explicit uncertainty component instead.
590
+ const quotaPressure = Math.round(
591
+ ((bindingUsed ?? 50) * confidenceFactor + 50 * (1 - confidenceFactor)) * SCORE_SCALE,
592
+ );
593
+ const leasePressure = candidate.activeLeaseCount * policy.activeLeaseScore;
594
+ const observedBurnConfidence = confidenceWeight(candidate.observedBurn.confidence);
595
+ const observedBurn = maximumWindowBurn(candidate.observedBurn);
596
+ const observedBurnPressure = Math.round(
597
+ observedBurn * policy.observedBurnScorePerPercentHour * observedBurnConfidence,
598
+ );
599
+ const burnConfidence = confidenceWeight(candidate.inferredUnexplainedBurn.confidence);
600
+ const inferredBurn = maximumWindowBurn(candidate.inferredUnexplainedBurn);
601
+ const inferredBurnPressure = Math.round(
602
+ inferredBurn * policy.inferredBurnScorePerPercentHour * burnConfidence,
603
+ );
604
+ const runwayPressure = runwayRiskPressure(candidate, confidence, policy);
605
+ const uncertaintyPressure = quotaUncertaintyScore(confidence, policy);
606
+ const cacheState = effectiveCodexFleetCacheStateV1(candidate.cache, policy);
607
+ const cacheAffinityBenefit =
608
+ candidate.key === input.request.currentCandidateKey
609
+ ? cacheAffinityBenefitFor(cacheState, policy)
610
+ : 0;
611
+ const overlayPreferenceBenefit = preferredOverlayMember ? policy.overlayPreferenceScore : 0;
612
+ return {
613
+ candidateKey: candidate.key,
614
+ eligible: rejectionReason === null,
615
+ rejectionReason,
616
+ quotaPressure,
617
+ leasePressure,
618
+ observedBurnPressure,
619
+ inferredBurnPressure,
620
+ runwayPressure,
621
+ uncertaintyPressure,
622
+ cacheAffinityBenefit,
623
+ cacheState,
624
+ overlayPreferenceBenefit,
625
+ total:
626
+ quotaPressure +
627
+ leasePressure +
628
+ observedBurnPressure +
629
+ inferredBurnPressure +
630
+ runwayPressure +
631
+ uncertaintyPressure -
632
+ cacheAffinityBenefit -
633
+ overlayPreferenceBenefit,
634
+ confidence,
635
+ };
636
+ }
637
+
638
+ type CodexFleetBurnSnapshotV1 = CodexFleetCandidateV1["observedBurn"];
639
+ type CodexFleetWindowKey = "primary" | "secondary";
640
+
641
+ function maximumWindowBurn(burn: CodexFleetBurnSnapshotV1): number {
642
+ return Math.max(burn.primaryPercentPerHour ?? 0, burn.secondaryPercentPerHour ?? 0);
643
+ }
644
+
645
+ function windowBurn(burn: CodexFleetBurnSnapshotV1, window: CodexFleetWindowKey): number {
646
+ return window === "primary"
647
+ ? (burn.primaryPercentPerHour ?? 0)
648
+ : (burn.secondaryPercentPerHour ?? 0);
649
+ }
650
+
651
+ /**
652
+ * Score only a confidence-bounded exhaustion risk that occurs before the
653
+ * corresponding provider reset. Each quota window has its own percentage burn
654
+ * denominator and reset horizon; the highest-risk complete window binds.
655
+ * Missing/stale observations contribute uncertainty elsewhere, never invented
656
+ * burn. A zero reset horizon means that reported window has already reset.
657
+ */
658
+ function runwayRiskPressure(
659
+ candidate: CodexFleetCandidateV1,
660
+ quotaConfidence: CodexFleetConfidence,
661
+ policy: CodexFleetPolicyConfigV1,
662
+ ): number {
663
+ if (quotaConfidence === "unknown") return 0;
664
+ const windows: Array<[CodexFleetWindowKey, CodexFleetQuotaWindowV1]> = [
665
+ ["primary", candidate.quota.primary],
666
+ ["secondary", candidate.quota.secondary],
667
+ ];
668
+ let maximumPressure = 0;
669
+ for (const [windowKey, window] of windows) {
670
+ if (
671
+ window.usedPercent === null ||
672
+ window.resetRemainingMs === null ||
673
+ window.resetRemainingMs === 0
674
+ ) {
675
+ continue;
676
+ }
677
+ const observedConfidence = confidenceWeight(
678
+ lowerConfidence(candidate.observedBurn.confidence, quotaConfidence),
679
+ );
680
+ const inferredConfidence = confidenceWeight(
681
+ lowerConfidence(candidate.inferredUnexplainedBurn.confidence, quotaConfidence),
682
+ );
683
+ const confidenceBoundedBurn =
684
+ windowBurn(candidate.observedBurn, windowKey) * observedConfidence +
685
+ windowBurn(candidate.inferredUnexplainedBurn, windowKey) * inferredConfidence;
686
+ if (confidenceBoundedBurn <= 0) continue;
687
+
688
+ const exhaustionRunwayHours = Math.max(0, 100 - window.usedPercent) / confidenceBoundedBurn;
689
+ const resetHorizonHours = window.resetRemainingMs / 60 / 60_000;
690
+ const atRiskHours = Math.min(
691
+ policy.runwayRiskCapHours,
692
+ Math.max(0, resetHorizonHours - exhaustionRunwayHours),
693
+ );
694
+ maximumPressure = Math.max(
695
+ maximumPressure,
696
+ Math.round(atRiskHours * policy.runwayScorePerAtRiskHour),
697
+ );
698
+ }
699
+ return maximumPressure;
700
+ }
701
+
702
+ function selectOverlayScope(
703
+ input: CodexFleetDecisionInputV1,
704
+ policy: CodexFleetPolicyConfigV1,
705
+ baseEligibleKeys: Set<string>,
706
+ ): {
707
+ rejectedByIsolation: Set<string>;
708
+ preferredMembers: Set<string>;
709
+ isolatedEmpty: boolean;
710
+ strandedEligibleCount: number;
711
+ } {
712
+ if (
713
+ !policy.overlaysEnabled ||
714
+ input.request.overlayMode === "none" ||
715
+ input.request.overlayKey === null
716
+ ) {
717
+ return {
718
+ rejectedByIsolation: new Set(),
719
+ preferredMembers: new Set(),
720
+ isolatedEmpty: false,
721
+ strandedEligibleCount: 0,
722
+ };
723
+ }
724
+ const members = new Set(
725
+ input.candidates
726
+ .filter(
727
+ (candidate) =>
728
+ baseEligibleKeys.has(candidate.key) &&
729
+ candidate.overlayKeys.includes(input.request.overlayKey!),
730
+ )
731
+ .map((candidate) => candidate.key),
732
+ );
733
+ if (input.request.overlayMode === "prefer") {
734
+ if (members.size === 0) {
735
+ return {
736
+ rejectedByIsolation: new Set(),
737
+ preferredMembers: members,
738
+ isolatedEmpty: false,
739
+ strandedEligibleCount: 0,
740
+ };
741
+ }
742
+ return {
743
+ // Preference is a bounded score benefit, never a hard partition. Healthy
744
+ // authorized outsiders remain eligible and borrowable.
745
+ rejectedByIsolation: new Set(),
746
+ preferredMembers: members,
747
+ isolatedEmpty: false,
748
+ strandedEligibleCount: 0,
749
+ };
750
+ }
751
+ const outside = [...baseEligibleKeys].filter((candidateKey) => !members.has(candidateKey));
752
+ return {
753
+ rejectedByIsolation: new Set(outside),
754
+ preferredMembers: members,
755
+ isolatedEmpty: members.size === 0,
756
+ strandedEligibleCount: outside.length,
757
+ };
758
+ }
759
+
760
+ function candidateConfidence(
761
+ candidate: CodexFleetCandidateV1,
762
+ policy: CodexFleetPolicyConfigV1,
763
+ ): CodexFleetConfidence {
764
+ const age = candidate.quota.checkedAgeMs;
765
+ if (age === null || age > policy.quotaStaleAfterMs) return "unknown";
766
+ const windows = [candidate.quota.primary, candidate.quota.secondary];
767
+ const completeWindowCount = windows.filter(
768
+ (window) => window.usedPercent !== null && window.resetRemainingMs !== null,
769
+ ).length;
770
+ const hasPartialWindow = windows.some(
771
+ (window) => (window.usedPercent === null) !== (window.resetRemainingMs === null),
772
+ );
773
+ if (completeWindowCount === 0) return "unknown";
774
+ const completenessCeiling: CodexFleetConfidence = hasPartialWindow
775
+ ? "low"
776
+ : completeWindowCount === windows.length
777
+ ? "high"
778
+ : "medium";
779
+ const completeConfidence = lowerConfidence(candidate.quota.confidence, completenessCeiling);
780
+ if (age > policy.quotaFreshForMs) {
781
+ return lowerConfidence(completeConfidence, "low");
782
+ }
783
+ return completeConfidence;
784
+ }
785
+
786
+ export function effectiveCodexFleetCacheStateV1(
787
+ cache: CodexFleetCandidateV1["cache"],
788
+ policy: CodexFleetPolicyConfigV1,
789
+ ): CodexFleetCacheState {
790
+ const { hitRatio, sampledTokens, checkedAgeMs, confidence, state, thresholdObservedForMs } =
791
+ cache;
792
+ if (
793
+ hitRatio === null ||
794
+ sampledTokens === null ||
795
+ sampledTokens < policy.cacheMinimumSampledTokens ||
796
+ checkedAgeMs === null ||
797
+ checkedAgeMs > policy.cacheFreshForMs ||
798
+ confidenceWeight(confidence) < confidenceWeight("medium")
799
+ ) {
800
+ return "unknown";
801
+ }
802
+ const observedForMs = thresholdObservedForMs ?? 0;
803
+ if (state === "healthy") {
804
+ return hitRatio < policy.cacheCollapseThreshold && observedForMs >= policy.cacheCollapseDwellMs
805
+ ? "collapsed"
806
+ : "healthy";
807
+ }
808
+ if (state === "collapsed") {
809
+ return hitRatio >= policy.cacheCollapseRecoveryThreshold &&
810
+ observedForMs >= policy.cacheRecoveryDwellMs
811
+ ? "healthy"
812
+ : "collapsed";
813
+ }
814
+ if (hitRatio < policy.cacheCollapseThreshold && observedForMs >= policy.cacheCollapseDwellMs) {
815
+ return "collapsed";
816
+ }
817
+ if (
818
+ hitRatio >= policy.cacheCollapseRecoveryThreshold &&
819
+ observedForMs >= policy.cacheRecoveryDwellMs
820
+ ) {
821
+ return "healthy";
822
+ }
823
+ return "unknown";
824
+ }
825
+
826
+ function cacheAffinityBenefitFor(
827
+ state: CodexFleetCacheState,
828
+ policy: CodexFleetPolicyConfigV1,
829
+ ): number {
830
+ if (state === "healthy") return policy.healthyCacheAffinityBenefit;
831
+ if (state === "collapsed") return policy.collapsedCacheAffinityBenefit;
832
+ return policy.unknownCacheAffinityBenefit;
833
+ }
834
+
835
+ function bindingUsedPercent(candidate: CodexFleetCandidateV1): number | null {
836
+ const windows = [candidate.quota.primary, candidate.quota.secondary]
837
+ .filter((window) => window.usedPercent !== null && window.resetRemainingMs !== null)
838
+ .map((window) => (window.resetRemainingMs === 0 ? 0 : window.usedPercent))
839
+ .filter((used): used is number => used !== null);
840
+ return windows.length > 0 ? Math.max(...windows) : null;
841
+ }
842
+
843
+ function quotaUncertaintyScore(
844
+ confidence: CodexFleetConfidence,
845
+ policy: CodexFleetPolicyConfigV1,
846
+ ): number {
847
+ if (confidence === "unknown") return policy.unknownQuotaScore;
848
+ if (confidence === "low") return policy.lowQuotaConfidenceScore;
849
+ if (confidence === "medium") return policy.mediumQuotaConfidenceScore;
850
+ return 0;
851
+ }
852
+
853
+ function emptyDecision(
854
+ reason: CodexFleetDecisionV1["reason"],
855
+ admission: CodexFleetAdmissionDecisionV1,
856
+ confidence: CodexFleetConfidence,
857
+ ): CodexFleetDecisionV1 {
858
+ return {
859
+ outcome: admission.outcome === "pace" ? "paced" : "none",
860
+ selectedCandidateKey: null,
861
+ reason,
862
+ admission,
863
+ borrowedOverlayCapacity: false,
864
+ strandedEligibleCount: 0,
865
+ confidence,
866
+ scores: [],
867
+ };
868
+ }
869
+
870
+ function aggregateConfidence(scores: CodexFleetScoreV1[]): CodexFleetConfidence {
871
+ if (scores.length === 0) return "unknown";
872
+ return scores.reduce<CodexFleetConfidence>(
873
+ (lowest, score) =>
874
+ confidenceWeight(score.confidence) < confidenceWeight(lowest) ? score.confidence : lowest,
875
+ "high",
876
+ );
877
+ }
878
+
879
+ function normalizeInput(input: CodexFleetDecisionInputV1, maxCandidates: number): NormalizedInput {
880
+ const currentCandidateKey = normalizeOptionalKey(input.request.currentCandidateKey);
881
+ const candidates = input.candidates
882
+ .map(normalizeCandidate)
883
+ .sort((a, b) => compareCodexFleetCanonicalStringsV1(a.key, b.key));
884
+ for (let index = 1; index < candidates.length; index += 1) {
885
+ if (candidates[index - 1]!.key === candidates[index]!.key) {
886
+ throw new Error(`Duplicate Codex fleet candidate key: ${candidates[index]!.key}`);
887
+ }
888
+ }
889
+ let bounded = candidates.slice(0, maxCandidates);
890
+ if (
891
+ currentCandidateKey &&
892
+ candidates.some((candidate) => candidate.key === currentCandidateKey) &&
893
+ !bounded.some((candidate) => candidate.key === currentCandidateKey)
894
+ ) {
895
+ bounded = [
896
+ ...bounded.slice(0, Math.max(0, maxCandidates - 1)),
897
+ candidates.find((candidate) => candidate.key === currentCandidateKey)!,
898
+ ].sort((a, b) => compareCodexFleetCanonicalStringsV1(a.key, b.key));
899
+ }
900
+ return {
901
+ input: {
902
+ observedAtMs: normalizeInteger(input.observedAtMs, 0, Number.MAX_SAFE_INTEGER),
903
+ request: {
904
+ placement: input.request.placement === "fenced_in_flight" ? "fenced_in_flight" : "new",
905
+ priority: input.request.priority === "manager" ? "manager" : "standard",
906
+ currentCandidateKey,
907
+ waitAgeMs: normalizeInteger(input.request.waitAgeMs, 0, MAX_DURATION_MS),
908
+ overlayKey: normalizeOptionalKey(input.request.overlayKey),
909
+ overlayMode:
910
+ input.request.overlayMode === "isolate"
911
+ ? "isolate"
912
+ : input.request.overlayMode === "prefer"
913
+ ? "prefer"
914
+ : "none",
915
+ },
916
+ admission: {
917
+ dynamicCapacityUnits:
918
+ input.admission.dynamicCapacityUnits === null
919
+ ? null
920
+ : normalizeInteger(input.admission.dynamicCapacityUnits, 0, MAX_COUNT),
921
+ inUseUnits: normalizeInteger(input.admission.inUseUnits, 0, MAX_COUNT),
922
+ queuedManagerCount: normalizeInteger(input.admission.queuedManagerCount, 0, MAX_COUNT),
923
+ emergencyFuseActive: input.admission.emergencyFuseActive === true,
924
+ },
925
+ candidates: bounded,
926
+ },
927
+ truncatedCandidateCount: candidates.length - bounded.length,
928
+ };
929
+ }
930
+
931
+ function normalizeCandidate(candidate: CodexFleetCandidateV1): CodexFleetCandidateV1 {
932
+ return {
933
+ key: normalizeKey(candidate.key),
934
+ status:
935
+ candidate.status === "active" ||
936
+ candidate.status === "needs_relogin" ||
937
+ candidate.status === "error"
938
+ ? candidate.status
939
+ : "unknown",
940
+ allocatorEnabled: candidate.allocatorEnabled === true,
941
+ cooldownRemainingMs: normalizeNullableInteger(
942
+ candidate.cooldownRemainingMs,
943
+ 0,
944
+ MAX_DURATION_MS,
945
+ ),
946
+ activeLeaseCount: normalizeInteger(candidate.activeLeaseCount, 0, MAX_COUNT),
947
+ quota: {
948
+ primary: normalizeQuotaWindow(candidate.quota.primary),
949
+ secondary: normalizeQuotaWindow(candidate.quota.secondary),
950
+ checkedAgeMs: normalizeNullableInteger(candidate.quota.checkedAgeMs, 0, MAX_DURATION_MS),
951
+ confidence: normalizeConfidence(candidate.quota.confidence),
952
+ },
953
+ cache: {
954
+ hitRatio: normalizeNullableNumber(candidate.cache.hitRatio, 0, 1, 4),
955
+ sampledTokens: normalizeNullableInteger(candidate.cache.sampledTokens, 0, MAX_COUNT),
956
+ checkedAgeMs: normalizeNullableInteger(candidate.cache.checkedAgeMs, 0, MAX_DURATION_MS),
957
+ confidence: normalizeConfidence(candidate.cache.confidence),
958
+ state: normalizeCacheState(candidate.cache.state),
959
+ thresholdObservedForMs: normalizeNullableInteger(
960
+ candidate.cache.thresholdObservedForMs,
961
+ 0,
962
+ MAX_DURATION_MS,
963
+ ),
964
+ },
965
+ observedBurn: {
966
+ primaryPercentPerHour: normalizeNullableNumber(
967
+ candidate.observedBurn.primaryPercentPerHour,
968
+ 0,
969
+ 100,
970
+ 3,
971
+ ),
972
+ secondaryPercentPerHour: normalizeNullableNumber(
973
+ candidate.observedBurn.secondaryPercentPerHour,
974
+ 0,
975
+ 100,
976
+ 3,
977
+ ),
978
+ confidence: normalizeConfidence(candidate.observedBurn.confidence),
979
+ },
980
+ inferredUnexplainedBurn: {
981
+ primaryPercentPerHour: normalizeNullableNumber(
982
+ candidate.inferredUnexplainedBurn.primaryPercentPerHour,
983
+ 0,
984
+ 100,
985
+ 3,
986
+ ),
987
+ secondaryPercentPerHour: normalizeNullableNumber(
988
+ candidate.inferredUnexplainedBurn.secondaryPercentPerHour,
989
+ 0,
990
+ 100,
991
+ 3,
992
+ ),
993
+ confidence: normalizeConfidence(candidate.inferredUnexplainedBurn.confidence),
994
+ },
995
+ overlayKeys: [...new Set(candidate.overlayKeys.map(normalizeKey))]
996
+ .sort(compareCodexFleetCanonicalStringsV1)
997
+ .slice(0, CODEX_FLEET_POLICY_MAX_OVERLAYS_PER_CANDIDATE),
998
+ };
999
+ }
1000
+
1001
+ function normalizeQuotaWindow(window: CodexFleetQuotaWindowV1): CodexFleetQuotaWindowV1 {
1002
+ return {
1003
+ usedPercent: normalizeNullableNumber(window.usedPercent, 0, 100, 3),
1004
+ resetRemainingMs: normalizeNullableInteger(window.resetRemainingMs, 0, MAX_DURATION_MS),
1005
+ };
1006
+ }
1007
+
1008
+ function normalizePolicy(policy: CodexFleetPolicyConfigV1): CodexFleetPolicyConfigV1 {
1009
+ const quotaFreshForMs = normalizeInteger(policy.quotaFreshForMs, 1, MAX_DURATION_MS);
1010
+ const cacheCollapseThreshold = normalizeNumber(policy.cacheCollapseThreshold, 0, 1, 4);
1011
+ return {
1012
+ maxCandidates: normalizeInteger(policy.maxCandidates, 1, CODEX_FLEET_POLICY_MAX_CANDIDATES),
1013
+ quotaFreshForMs,
1014
+ quotaStaleAfterMs: normalizeInteger(policy.quotaStaleAfterMs, quotaFreshForMs, MAX_DURATION_MS),
1015
+ placementUsageCeilingPercent: normalizeNumber(policy.placementUsageCeilingPercent, 1, 100, 3),
1016
+ cacheFreshForMs: normalizeInteger(policy.cacheFreshForMs, 1, MAX_DURATION_MS),
1017
+ cacheCollapseThreshold,
1018
+ cacheCollapseRecoveryThreshold: normalizeNumber(
1019
+ policy.cacheCollapseRecoveryThreshold,
1020
+ cacheCollapseThreshold,
1021
+ 1,
1022
+ 4,
1023
+ ),
1024
+ cacheMinimumSampledTokens: normalizeInteger(policy.cacheMinimumSampledTokens, 1, MAX_COUNT),
1025
+ cacheCollapseDwellMs: normalizeInteger(policy.cacheCollapseDwellMs, 1, MAX_DURATION_MS),
1026
+ cacheRecoveryDwellMs: normalizeInteger(policy.cacheRecoveryDwellMs, 1, MAX_DURATION_MS),
1027
+ activeLeaseScore: normalizeNumber(policy.activeLeaseScore, 0, MAX_COUNT, 3),
1028
+ unknownQuotaScore: normalizeNumber(policy.unknownQuotaScore, 0, MAX_COUNT, 3),
1029
+ lowQuotaConfidenceScore: normalizeNumber(policy.lowQuotaConfidenceScore, 0, MAX_COUNT, 3),
1030
+ mediumQuotaConfidenceScore: normalizeNumber(policy.mediumQuotaConfidenceScore, 0, MAX_COUNT, 3),
1031
+ inferredBurnScorePerPercentHour: normalizeNumber(
1032
+ policy.inferredBurnScorePerPercentHour,
1033
+ 0,
1034
+ MAX_COUNT,
1035
+ 3,
1036
+ ),
1037
+ observedBurnScorePerPercentHour: normalizeNumber(
1038
+ policy.observedBurnScorePerPercentHour,
1039
+ 0,
1040
+ MAX_COUNT,
1041
+ 3,
1042
+ ),
1043
+ runwayRiskCapHours: normalizeNumber(policy.runwayRiskCapHours, 0, 24 * 31, 3),
1044
+ runwayScorePerAtRiskHour: normalizeNumber(policy.runwayScorePerAtRiskHour, 0, MAX_COUNT, 3),
1045
+ healthyCacheAffinityBenefit: normalizeNumber(
1046
+ policy.healthyCacheAffinityBenefit,
1047
+ 0,
1048
+ MAX_COUNT,
1049
+ 3,
1050
+ ),
1051
+ unknownCacheAffinityBenefit: normalizeNumber(
1052
+ policy.unknownCacheAffinityBenefit,
1053
+ 0,
1054
+ MAX_COUNT,
1055
+ 3,
1056
+ ),
1057
+ collapsedCacheAffinityBenefit: normalizeNumber(
1058
+ policy.collapsedCacheAffinityBenefit,
1059
+ 0,
1060
+ MAX_COUNT,
1061
+ 3,
1062
+ ),
1063
+ switchHysteresisScore: normalizeNumber(policy.switchHysteresisScore, 0, MAX_COUNT, 3),
1064
+ admissionPacingEnabled: policy.admissionPacingEnabled === true,
1065
+ managerPriorityEnabled: policy.managerPriorityEnabled === true,
1066
+ managerStandardStarvationMs: normalizeInteger(
1067
+ policy.managerStandardStarvationMs,
1068
+ 1,
1069
+ MAX_DURATION_MS,
1070
+ ),
1071
+ emergencyFuseEnabled: policy.emergencyFuseEnabled === true,
1072
+ overlaysEnabled: policy.overlaysEnabled === true,
1073
+ overlayPreferenceScore: normalizeNumber(policy.overlayPreferenceScore, 0, MAX_COUNT, 3),
1074
+ };
1075
+ }
1076
+
1077
+ function normalizeConfidence(value: CodexFleetConfidence): CodexFleetConfidence {
1078
+ return value === "high" || value === "medium" || value === "low" ? value : "unknown";
1079
+ }
1080
+
1081
+ function normalizeCacheState(value: CodexFleetCacheState): CodexFleetCacheState {
1082
+ return value === "healthy" || value === "collapsed" ? value : "unknown";
1083
+ }
1084
+
1085
+ function confidenceWeight(confidence: CodexFleetConfidence): number {
1086
+ if (confidence === "high") return 1;
1087
+ if (confidence === "medium") return 0.6;
1088
+ if (confidence === "low") return 0.25;
1089
+ return 0;
1090
+ }
1091
+
1092
+ function lowerConfidence(
1093
+ value: CodexFleetConfidence,
1094
+ ceiling: CodexFleetConfidence,
1095
+ ): CodexFleetConfidence {
1096
+ return confidenceWeight(value) < confidenceWeight(ceiling) ? value : ceiling;
1097
+ }
1098
+
1099
+ function normalizeKey(value: string): string {
1100
+ if (!/^[a-zA-Z0-9._:-]{1,32}$/.test(value)) {
1101
+ throw new Error("Codex fleet candidate/overlay keys must be 1-32 opaque safe characters");
1102
+ }
1103
+ return value;
1104
+ }
1105
+
1106
+ function normalizeOptionalKey(value: string | null): string | null {
1107
+ return value === null ? null : normalizeKey(value);
1108
+ }
1109
+
1110
+ function normalizeNullableNumber(
1111
+ value: number | null,
1112
+ min: number,
1113
+ max: number,
1114
+ decimals: number,
1115
+ ): number | null {
1116
+ return value === null ? null : normalizeNumber(value, min, max, decimals);
1117
+ }
1118
+
1119
+ function normalizeNumber(value: number, min: number, max: number, decimals: number): number {
1120
+ const finite = Number.isFinite(value) ? value : min;
1121
+ const clamped = Math.min(max, Math.max(min, finite));
1122
+ const scale = 10 ** decimals;
1123
+ return Math.round(clamped * scale) / scale;
1124
+ }
1125
+
1126
+ function normalizeNullableInteger(value: number | null, min: number, max: number): number | null {
1127
+ return value === null ? null : normalizeInteger(value, min, max);
1128
+ }
1129
+
1130
+ function normalizeInteger(value: number, min: number, max: number): number {
1131
+ return Math.round(normalizeNumber(value, min, max, 0));
1132
+ }
1133
+
1134
+ function readCodexFleetDecisionV1(
1135
+ value: unknown,
1136
+ candidateKeys: ReadonlySet<string>,
1137
+ ): CodexFleetDecisionV1 {
1138
+ const decision = strictRecord(value, [
1139
+ "outcome",
1140
+ "selectedCandidateKey",
1141
+ "reason",
1142
+ "admission",
1143
+ "borrowedOverlayCapacity",
1144
+ "strandedEligibleCount",
1145
+ "confidence",
1146
+ "scores",
1147
+ ]);
1148
+ const outcome = strictEnum(decision.outcome, ["selected", "paced", "none"] as const);
1149
+ const selectedCandidateKey = strictOptionalKey(decision.selectedCandidateKey);
1150
+ const reason = strictEnum(decision.reason, [
1151
+ "fenced_in_flight",
1152
+ "fenced_candidate_missing",
1153
+ "admission_paced",
1154
+ "no_eligible_candidate",
1155
+ "overlay_isolated_empty",
1156
+ "best_score",
1157
+ "affinity_best",
1158
+ "hysteresis_hold",
1159
+ ] as const);
1160
+ const admissionRecord = strictRecord(decision.admission, [
1161
+ "outcome",
1162
+ "reason",
1163
+ "borrowedIdleCapacity",
1164
+ ]);
1165
+ const admission: CodexFleetAdmissionDecisionV1 = {
1166
+ outcome: strictEnum(admissionRecord.outcome, ["admit", "pace"] as const),
1167
+ reason: strictEnum(admissionRecord.reason, [
1168
+ "fenced_in_flight",
1169
+ "pacing_disabled",
1170
+ "capacity_unknown",
1171
+ "capacity_available",
1172
+ "work_conserving_borrow",
1173
+ "manager_priority",
1174
+ "standard_starvation_bound",
1175
+ "capacity_saturated",
1176
+ "emergency_fuse",
1177
+ ] as const),
1178
+ borrowedIdleCapacity: strictBoolean(admissionRecord.borrowedIdleCapacity),
1179
+ };
1180
+ if (!Array.isArray(decision.scores) || decision.scores.length > candidateKeys.size) {
1181
+ throw new Error("Codex fleet replay decision scores are not a bounded array");
1182
+ }
1183
+ const scores = decision.scores.map(readCodexFleetScoreV1);
1184
+ if (
1185
+ new Set(scores.map((score) => score.candidateKey)).size !== scores.length ||
1186
+ scores.some((score) => !candidateKeys.has(score.candidateKey))
1187
+ ) {
1188
+ throw new Error("Codex fleet replay decision has invalid candidate scores");
1189
+ }
1190
+ const borrowedOverlayCapacity = strictBoolean(decision.borrowedOverlayCapacity);
1191
+ const strandedEligibleCount = strictInteger(decision.strandedEligibleCount, 0, MAX_COUNT);
1192
+
1193
+ const selectedReasons = [
1194
+ "fenced_in_flight",
1195
+ "best_score",
1196
+ "affinity_best",
1197
+ "hysteresis_hold",
1198
+ ] as const;
1199
+ const noneReasons = [
1200
+ "fenced_candidate_missing",
1201
+ "no_eligible_candidate",
1202
+ "overlay_isolated_empty",
1203
+ ] as const;
1204
+ const paceReasons = ["manager_priority", "capacity_saturated", "emergency_fuse"] as const;
1205
+ const consistent =
1206
+ outcome === "selected"
1207
+ ? selectedCandidateKey !== null &&
1208
+ admission.outcome === "admit" &&
1209
+ selectedReasons.includes(reason as (typeof selectedReasons)[number]) &&
1210
+ scores.some((score) => score.candidateKey === selectedCandidateKey)
1211
+ : outcome === "paced"
1212
+ ? selectedCandidateKey === null &&
1213
+ reason === "admission_paced" &&
1214
+ admission.outcome === "pace" &&
1215
+ paceReasons.includes(admission.reason as (typeof paceReasons)[number])
1216
+ : selectedCandidateKey === null &&
1217
+ admission.outcome === "admit" &&
1218
+ noneReasons.includes(reason as (typeof noneReasons)[number]);
1219
+ if (
1220
+ !consistent ||
1221
+ strandedEligibleCount > candidateKeys.size ||
1222
+ admission.borrowedIdleCapacity !== (admission.reason === "work_conserving_borrow") ||
1223
+ (borrowedOverlayCapacity && (outcome !== "selected" || strandedEligibleCount !== 0))
1224
+ ) {
1225
+ throw new Error("Codex fleet replay decision is internally inconsistent");
1226
+ }
1227
+
1228
+ return {
1229
+ outcome,
1230
+ selectedCandidateKey,
1231
+ reason,
1232
+ admission,
1233
+ borrowedOverlayCapacity,
1234
+ strandedEligibleCount,
1235
+ confidence: strictConfidence(decision.confidence),
1236
+ scores,
1237
+ };
1238
+ }
1239
+
1240
+ function readCodexFleetScoreV1(value: unknown): CodexFleetScoreV1 {
1241
+ const score = strictRecord(value, [
1242
+ "candidateKey",
1243
+ "eligible",
1244
+ "rejectionReason",
1245
+ "quotaPressure",
1246
+ "leasePressure",
1247
+ "observedBurnPressure",
1248
+ "inferredBurnPressure",
1249
+ "runwayPressure",
1250
+ "uncertaintyPressure",
1251
+ "cacheAffinityBenefit",
1252
+ "cacheState",
1253
+ "overlayPreferenceBenefit",
1254
+ "total",
1255
+ "confidence",
1256
+ ]);
1257
+ const parsed: CodexFleetScoreV1 = {
1258
+ candidateKey: normalizeKey(strictString(score.candidateKey)),
1259
+ eligible: strictBoolean(score.eligible),
1260
+ rejectionReason:
1261
+ score.rejectionReason === null
1262
+ ? null
1263
+ : strictEnum(score.rejectionReason, [
1264
+ "allocator_disabled",
1265
+ "unavailable",
1266
+ "cooling",
1267
+ "quota_ceiling",
1268
+ "overlay_isolation",
1269
+ ] as const),
1270
+ quotaPressure: strictFiniteNumber(score.quotaPressure, 0, Number.MAX_SAFE_INTEGER),
1271
+ leasePressure: strictFiniteNumber(score.leasePressure, 0, Number.MAX_SAFE_INTEGER),
1272
+ observedBurnPressure: strictFiniteNumber(
1273
+ score.observedBurnPressure,
1274
+ 0,
1275
+ Number.MAX_SAFE_INTEGER,
1276
+ ),
1277
+ inferredBurnPressure: strictFiniteNumber(
1278
+ score.inferredBurnPressure,
1279
+ 0,
1280
+ Number.MAX_SAFE_INTEGER,
1281
+ ),
1282
+ runwayPressure: strictFiniteNumber(score.runwayPressure, 0, Number.MAX_SAFE_INTEGER),
1283
+ uncertaintyPressure: strictFiniteNumber(score.uncertaintyPressure, 0, Number.MAX_SAFE_INTEGER),
1284
+ cacheAffinityBenefit: strictFiniteNumber(
1285
+ score.cacheAffinityBenefit,
1286
+ 0,
1287
+ Number.MAX_SAFE_INTEGER,
1288
+ ),
1289
+ cacheState: strictEnum(score.cacheState, ["unknown", "healthy", "collapsed"] as const),
1290
+ overlayPreferenceBenefit: strictFiniteNumber(
1291
+ score.overlayPreferenceBenefit,
1292
+ 0,
1293
+ Number.MAX_SAFE_INTEGER,
1294
+ ),
1295
+ total: strictFiniteNumber(score.total, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),
1296
+ confidence: strictConfidence(score.confidence),
1297
+ };
1298
+ const expectedTotal =
1299
+ parsed.quotaPressure +
1300
+ parsed.leasePressure +
1301
+ parsed.observedBurnPressure +
1302
+ parsed.inferredBurnPressure +
1303
+ parsed.runwayPressure +
1304
+ parsed.uncertaintyPressure -
1305
+ parsed.cacheAffinityBenefit -
1306
+ parsed.overlayPreferenceBenefit;
1307
+ if (parsed.eligible !== (parsed.rejectionReason === null) || parsed.total !== expectedTotal) {
1308
+ throw new Error("Codex fleet replay score is internally inconsistent");
1309
+ }
1310
+ return parsed;
1311
+ }
1312
+
1313
+ function strictRecord(value: unknown, expectedKeys: readonly string[]): Record<string, unknown> {
1314
+ if (
1315
+ value === null ||
1316
+ typeof value !== "object" ||
1317
+ Array.isArray(value) ||
1318
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value))
1319
+ ) {
1320
+ throw new Error("Codex fleet replay value must be a plain object");
1321
+ }
1322
+ const record = value as Record<string, unknown>;
1323
+ const actualKeys = Object.keys(record).sort(compareCodexFleetCanonicalStringsV1);
1324
+ const canonicalExpected = [...expectedKeys].sort(compareCodexFleetCanonicalStringsV1);
1325
+ if (canonicalJson(actualKeys) !== canonicalJson(canonicalExpected)) {
1326
+ throw new Error("Codex fleet replay object has missing or unknown fields");
1327
+ }
1328
+ return record;
1329
+ }
1330
+
1331
+ function strictEnum<const T extends readonly string[]>(value: unknown, values: T): T[number] {
1332
+ if (typeof value !== "string" || !values.includes(value)) {
1333
+ throw new Error("Codex fleet replay enum value is invalid");
1334
+ }
1335
+ return value as T[number];
1336
+ }
1337
+
1338
+ function strictConfidence(value: unknown): CodexFleetConfidence {
1339
+ return strictEnum(value, ["unknown", "low", "medium", "high"] as const);
1340
+ }
1341
+
1342
+ function strictString(value: unknown): string {
1343
+ if (typeof value !== "string") throw new Error("Codex fleet replay value must be a string");
1344
+ return value;
1345
+ }
1346
+
1347
+ function strictOptionalKey(value: unknown): string | null {
1348
+ return value === null ? null : normalizeKey(strictString(value));
1349
+ }
1350
+
1351
+ function strictBoolean(value: unknown): boolean {
1352
+ if (typeof value !== "boolean") throw new Error("Codex fleet replay value must be boolean");
1353
+ return value;
1354
+ }
1355
+
1356
+ function strictFiniteNumber(value: unknown, min: number, max: number): number {
1357
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
1358
+ throw new Error("Codex fleet replay numeric value is invalid");
1359
+ }
1360
+ return value;
1361
+ }
1362
+
1363
+ function strictInteger(value: unknown, min: number, max: number): number {
1364
+ const number = strictFiniteNumber(value, min, max);
1365
+ if (!Number.isInteger(number)) throw new Error("Codex fleet replay value must be an integer");
1366
+ return number;
1367
+ }
1368
+
1369
+ function strictSha256(value: unknown): string {
1370
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) {
1371
+ throw new Error("Codex fleet replay fingerprint must be lowercase SHA-256");
1372
+ }
1373
+ return value;
1374
+ }
1375
+
1376
+ function fingerprint(value: unknown): string {
1377
+ const serialized = canonicalJson(value);
1378
+ return bytesToHex(sha256(new TextEncoder().encode(serialized)));
1379
+ }
1380
+
1381
+ function fingerprintReplayInput(
1382
+ input: CodexFleetDecisionInputV1,
1383
+ truncatedCandidateCount: number,
1384
+ ): string {
1385
+ // Truncation affects actual-vs-shadow comparability and the UI explanation,
1386
+ // so it is part of the replay input's integrity boundary rather than mutable
1387
+ // envelope metadata.
1388
+ return fingerprint({ input, truncatedCandidateCount });
1389
+ }
1390
+
1391
+ function canonicalJson(value: unknown): string {
1392
+ return JSON.stringify(sortJson(value));
1393
+ }
1394
+
1395
+ function sortJson(value: unknown): unknown {
1396
+ if (Array.isArray(value)) return value.map(sortJson);
1397
+ if (value && typeof value === "object") {
1398
+ return Object.fromEntries(
1399
+ Object.entries(value as Record<string, unknown>)
1400
+ .sort(([left], [right]) => compareCodexFleetCanonicalStringsV1(left, right))
1401
+ .map(([key, child]) => [key, sortJson(child)]),
1402
+ );
1403
+ }
1404
+ return value;
1405
+ }