hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3

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 (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +89 -2
  3. package/dist/adapter-kit.d.ts +37 -0
  4. package/dist/adapter-kit.js +34 -0
  5. package/dist/adapter-kit.js.map +1 -0
  6. package/dist/agent-Bj5YPrO7.d.ts +169 -0
  7. package/dist/agent-D6OXR7UF.js +24 -0
  8. package/dist/agent-D6OXR7UF.js.map +1 -0
  9. package/dist/agent-readiness-KSGNKTGK.js +19 -0
  10. package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
  11. package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
  12. package/dist/chunk-2RK74GCA.js +2397 -0
  13. package/dist/chunk-2RK74GCA.js.map +1 -0
  14. package/dist/chunk-3TIYA3K5.js +55 -0
  15. package/dist/chunk-3TIYA3K5.js.map +1 -0
  16. package/dist/chunk-6FIXXWNM.js +1 -0
  17. package/dist/chunk-6FIXXWNM.js.map +1 -0
  18. package/dist/chunk-6XIJW65Q.js +52 -0
  19. package/dist/chunk-6XIJW65Q.js.map +1 -0
  20. package/dist/chunk-7LDQKJKI.js +248 -0
  21. package/dist/chunk-7LDQKJKI.js.map +1 -0
  22. package/dist/chunk-CPN4DOXH.js +115 -0
  23. package/dist/chunk-CPN4DOXH.js.map +1 -0
  24. package/dist/chunk-DAXPAV2L.js +810 -0
  25. package/dist/chunk-DAXPAV2L.js.map +1 -0
  26. package/dist/chunk-DQEMIGKC.js +291 -0
  27. package/dist/chunk-DQEMIGKC.js.map +1 -0
  28. package/dist/chunk-DZFFGUIA.js +81 -0
  29. package/dist/chunk-DZFFGUIA.js.map +1 -0
  30. package/dist/chunk-EEUYQFCP.js +106 -0
  31. package/dist/chunk-EEUYQFCP.js.map +1 -0
  32. package/dist/chunk-G6JV7WV6.js +521 -0
  33. package/dist/chunk-G6JV7WV6.js.map +1 -0
  34. package/dist/chunk-GFVYNPLS.js +118 -0
  35. package/dist/chunk-GFVYNPLS.js.map +1 -0
  36. package/dist/chunk-GS5U3KUN.js +201 -0
  37. package/dist/chunk-GS5U3KUN.js.map +1 -0
  38. package/dist/chunk-HB7FBSH2.js +960 -0
  39. package/dist/chunk-HB7FBSH2.js.map +1 -0
  40. package/dist/chunk-HZFZX5A3.js +21 -0
  41. package/dist/chunk-HZFZX5A3.js.map +1 -0
  42. package/dist/chunk-J7VAYJKM.js +595 -0
  43. package/dist/chunk-J7VAYJKM.js.map +1 -0
  44. package/dist/chunk-NCNSHOF7.js +52 -0
  45. package/dist/chunk-NCNSHOF7.js.map +1 -0
  46. package/dist/chunk-RH5A5U7G.js +202 -0
  47. package/dist/chunk-RH5A5U7G.js.map +1 -0
  48. package/dist/chunk-RX3XZENU.js +385 -0
  49. package/dist/chunk-RX3XZENU.js.map +1 -0
  50. package/dist/chunk-RXU2Q2HF.js +49 -0
  51. package/dist/chunk-RXU2Q2HF.js.map +1 -0
  52. package/dist/chunk-TG7NTMTR.js +208 -0
  53. package/dist/chunk-TG7NTMTR.js.map +1 -0
  54. package/dist/chunk-TWGEYWMO.js +1217 -0
  55. package/dist/chunk-TWGEYWMO.js.map +1 -0
  56. package/dist/chunk-UZPDDQVJ.js +2910 -0
  57. package/dist/chunk-UZPDDQVJ.js.map +1 -0
  58. package/dist/chunk-WMKO5XOE.js +601 -0
  59. package/dist/chunk-WMKO5XOE.js.map +1 -0
  60. package/dist/chunk-WOQBVJH5.js +175 -0
  61. package/dist/chunk-WOQBVJH5.js.map +1 -0
  62. package/dist/chunk-WVT5SEKC.js +581 -0
  63. package/dist/chunk-WVT5SEKC.js.map +1 -0
  64. package/dist/cli.d.ts +1 -0
  65. package/dist/cli.js +26 -0
  66. package/dist/cli.js.map +1 -0
  67. package/dist/errors-BNHvvjn9.d.ts +98 -0
  68. package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
  69. package/dist/execution-types-ClYYqPQP.d.ts +239 -0
  70. package/dist/host-ledger-VPRWVVOS.js +25 -0
  71. package/dist/host-ledger-VPRWVVOS.js.map +1 -0
  72. package/dist/hosted-runtime.d.ts +168 -0
  73. package/dist/hosted-runtime.js +858 -0
  74. package/dist/hosted-runtime.js.map +1 -0
  75. package/dist/index-B86C6VAD.d.ts +41 -0
  76. package/dist/index.d.ts +344 -0
  77. package/dist/index.js +8825 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/memory-items-BSTC0_R0.d.ts +28 -0
  80. package/dist/memory-tools.d.ts +222 -0
  81. package/dist/memory-tools.js +923 -0
  82. package/dist/memory-tools.js.map +1 -0
  83. package/dist/orchestration/dynamic.d.ts +854 -0
  84. package/dist/orchestration/dynamic.js +3150 -0
  85. package/dist/orchestration/dynamic.js.map +1 -0
  86. package/dist/orchestration/graph.d.ts +11 -0
  87. package/dist/orchestration/graph.js +9 -0
  88. package/dist/orchestration/graph.js.map +1 -0
  89. package/dist/orchestration/index.d.ts +2385 -0
  90. package/dist/orchestration/index.js +6409 -0
  91. package/dist/orchestration/index.js.map +1 -0
  92. package/dist/orchestration/log.d.ts +301 -0
  93. package/dist/orchestration/log.js +3058 -0
  94. package/dist/orchestration/log.js.map +1 -0
  95. package/dist/orchestration/memory.d.ts +711 -0
  96. package/dist/orchestration/memory.js +27 -0
  97. package/dist/orchestration/memory.js.map +1 -0
  98. package/dist/provider-DX5Mf0uq.d.ts +151 -0
  99. package/dist/routing/index.d.ts +29 -0
  100. package/dist/routing/index.js +386 -0
  101. package/dist/routing/index.js.map +1 -0
  102. package/dist/routing/learning/index.d.ts +433 -0
  103. package/dist/routing/learning/index.js +2502 -0
  104. package/dist/routing/learning/index.js.map +1 -0
  105. package/dist/runtime-BSjrnxeF.d.ts +283 -0
  106. package/dist/runtime-OISPXS4I.js +19 -0
  107. package/dist/runtime-OISPXS4I.js.map +1 -0
  108. package/dist/store-types-2YdceOMy.d.ts +78 -0
  109. package/dist/types-BB7KqceP.d.ts +52 -0
  110. package/dist/types-CIqkKXix.d.ts +86 -0
  111. package/dist/types-DTFc1qO6.d.ts +1065 -0
  112. package/dist/types-DYex3p7_.d.ts +88 -0
  113. package/docs/licenses/ruflo-memory-MIT.txt +21 -0
  114. package/docs/releases/0.1.0-beta.3.md +13 -0
  115. package/package.json +114 -4
@@ -0,0 +1,2502 @@
1
+ import {
2
+ normalize
3
+ } from "../../chunk-RH5A5U7G.js";
4
+ import {
5
+ Agent
6
+ } from "../../chunk-UZPDDQVJ.js";
7
+ import "../../chunk-HZFZX5A3.js";
8
+ import "../../chunk-WVT5SEKC.js";
9
+ import "../../chunk-3TIYA3K5.js";
10
+ import "../../chunk-2RK74GCA.js";
11
+ import "../../chunk-J7VAYJKM.js";
12
+ import {
13
+ OperationScope,
14
+ authenticationState
15
+ } from "../../chunk-G6JV7WV6.js";
16
+ import "../../chunk-6FIXXWNM.js";
17
+ import {
18
+ runObservedTask
19
+ } from "../../chunk-GFVYNPLS.js";
20
+ import "../../chunk-DAXPAV2L.js";
21
+ import "../../chunk-6XIJW65Q.js";
22
+ import "../../chunk-RXU2Q2HF.js";
23
+ import "../../chunk-TWGEYWMO.js";
24
+ import "../../chunk-GS5U3KUN.js";
25
+ import {
26
+ canonical,
27
+ digest,
28
+ freeze,
29
+ hash,
30
+ identifier,
31
+ jsonClone,
32
+ method,
33
+ object,
34
+ ownObject,
35
+ snapshot,
36
+ strings
37
+ } from "../../chunk-EEUYQFCP.js";
38
+ import "../../chunk-RX3XZENU.js";
39
+ import "../../chunk-7LDQKJKI.js";
40
+ import {
41
+ isExecutionHalted,
42
+ rethrowExecutionHalt
43
+ } from "../../chunk-NCNSHOF7.js";
44
+ import {
45
+ AbortError,
46
+ TimeoutError
47
+ } from "../../chunk-TG7NTMTR.js";
48
+
49
+ // src/routing/learning/factory-context.ts
50
+ import { resolve } from "node:path";
51
+ import { randomUUID } from "node:crypto";
52
+ import { types } from "node:util";
53
+
54
+ // src/routing/learning/features.ts
55
+ import { createHash } from "node:crypto";
56
+ function textInput(text) {
57
+ if (typeof text !== "string" || text.length > 5e4)
58
+ throw new TypeError("Task text must contain at most 50000 characters");
59
+ }
60
+ function inputDigest(text) {
61
+ textInput(text);
62
+ return createHash("sha256").update(text, "utf8").digest("hex");
63
+ }
64
+ function hashTaskFeatures(text) {
65
+ textInput(text);
66
+ const values = Array(128).fill(0);
67
+ const normalized = text.normalize("NFKC").toLocaleLowerCase("en-US").replace(/\s+/gu, " ").trim();
68
+ const words = normalized.match(/[\p{L}\p{N}_]+/gu) ?? [];
69
+ const add = (token, weight) => {
70
+ const hash2 = createHash("sha256").update(token).digest();
71
+ const bucket = hash2.readUInt32LE(0) % 128;
72
+ values[bucket] = values[bucket] + (hash2[4] & 1 ? -weight : weight);
73
+ };
74
+ for (let i = 0; i < words.length; i++) {
75
+ add(`w:${words[i]}`, 2);
76
+ if (i)
77
+ add(`b:${words[i - 1]} ${words[i]}`, 1);
78
+ }
79
+ for (let n = 3; n <= 5; n++)
80
+ for (let i = 0; i + n <= normalized.length; i++)
81
+ add(`c:${normalized.slice(i, i + n)}`, 0.25);
82
+ const norm = Math.hypot(...values);
83
+ if (norm)
84
+ for (let i = 0; i < values.length; i++)
85
+ values[i] = values[i] / norm;
86
+ return freeze({ schema: "oar-hash-ngrams-v1", values });
87
+ }
88
+
89
+ // src/routing/learning/validation-shapes.ts
90
+ function exact(v, required, optional = []) {
91
+ object(v, [...required, ...optional]);
92
+ for (const k of required)
93
+ if (!Object.hasOwn(v, k))
94
+ throw new TypeError(`Missing ${k}`);
95
+ }
96
+ function integer(v, min = 0, max = Number.MAX_SAFE_INTEGER) {
97
+ if (!Number.isSafeInteger(v) || v < min || v > max)
98
+ throw new TypeError("Invalid integer");
99
+ }
100
+ function number(v, min = 0, max = Number.MAX_VALUE) {
101
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max)
102
+ throw new TypeError("Invalid number");
103
+ }
104
+ function choice(v, choices) {
105
+ if (!choices.includes(v))
106
+ throw new TypeError("Invalid enum");
107
+ }
108
+ function list(v, max = 32768) {
109
+ if (!Array.isArray(v) || v.length > max)
110
+ throw new TypeError("Invalid list");
111
+ }
112
+ function ref(v) {
113
+ if (v !== null)
114
+ hash(v);
115
+ }
116
+ function features(v) {
117
+ exact(v, ["schema", "values"]);
118
+ identifier(v.schema);
119
+ list(v.values, 512);
120
+ if (!v.values.length)
121
+ throw new TypeError("Empty vector");
122
+ for (const x of v.values)
123
+ number(x, -1, 1);
124
+ const n = Math.hypot(...v.values);
125
+ if (n !== 0 && Math.abs(n - 1) > 1e-6)
126
+ throw new TypeError("Unnormalized features");
127
+ }
128
+ function config(v) {
129
+ exact(v, ["objective", "minDistinctTasks", "minSimilarity", "maxAgeMs", "halfLifeMs", "qualityFloor", "maxRows", "alpha", "minImprovement", "minFreshTasks"]);
130
+ choice(v.objective, ["quality", "latency", "cost"]);
131
+ integer(v.minDistinctTasks, 1, 1e5);
132
+ number(v.minSimilarity, 0, 1);
133
+ integer(v.maxAgeMs, 1);
134
+ integer(v.halfLifeMs, 1);
135
+ number(v.qualityFloor, 0, 1);
136
+ integer(v.maxRows, 1, 32768);
137
+ number(v.alpha, Number.MIN_VALUE, 0.5);
138
+ number(v.minImprovement, 0, 1);
139
+ integer(v.minFreshTasks, 1, 1e5);
140
+ }
141
+ function action(v) {
142
+ exact(v, ["id", "model", "provider", "modelId", "optionsDigest", "executionDigest", "evidenceScope", "key"]);
143
+ choice(v.evidenceScope, ["model", "requested-system"]);
144
+ for (const k of ["id", "model", "provider", "modelId"])
145
+ identifier(v[k]);
146
+ for (const k of ["optionsDigest", "executionDigest", "key"])
147
+ hash(v[k]);
148
+ const { id: _, key: __, ...body } = v;
149
+ if (digest(body) !== v.key)
150
+ throw new TypeError("Action key mismatch");
151
+ }
152
+ function pointer(v) {
153
+ exact(v, ["generation", "active", "previous"]);
154
+ integer(v.generation);
155
+ ref(v.active);
156
+ ref(v.previous);
157
+ if (v.generation === 0 && (v.active !== null || v.previous !== null))
158
+ throw new TypeError("Initial pointer mismatch");
159
+ }
160
+ function quality(v) {
161
+ object(v);
162
+ if (v.state === "verified") {
163
+ exact(v, ["state", "value", "passed"]);
164
+ number(v.value, 0, 1);
165
+ if (typeof v.passed !== "boolean")
166
+ throw new TypeError("Invalid pass");
167
+ } else {
168
+ exact(v, ["state", "reason"]);
169
+ choice(v.state, ["unknown"]);
170
+ identifier(v.reason);
171
+ }
172
+ }
173
+ function latency(v) {
174
+ object(v);
175
+ if (v.state === "unknown") {
176
+ exact(v, ["state"]);
177
+ } else {
178
+ exact(v, ["state", "durationMs"]);
179
+ choice(v.state, ["observed", "right-censored"]);
180
+ number(v.durationMs);
181
+ }
182
+ }
183
+ function usage(v) {
184
+ exact(v, ["costMeaning"], ["inputTokens", "outputTokens", "cachedInputTokens", "cacheCreationTokens", "reportedCostUsd", "perModel"]);
185
+ choice(v.costMeaning, ["provider-reported", "api-equivalent", "estimate", "unavailable"]);
186
+ for (const k of ["inputTokens", "outputTokens", "cachedInputTokens", "cacheCreationTokens"])
187
+ if (k in v)
188
+ integer(v[k]);
189
+ if ("reportedCostUsd" in v)
190
+ number(v.reportedCostUsd);
191
+ if ("perModel" in v) {
192
+ object(v.perModel);
193
+ if (Object.keys(v.perModel).length > 64)
194
+ throw new TypeError("Too many per-model usage entries");
195
+ for (const [k, m] of Object.entries(v.perModel)) {
196
+ identifier(k);
197
+ exact(m, [], ["inputTokens", "outputTokens", "cachedInputTokens", "cacheCreationTokens", "reportedCostUsd"]);
198
+ for (const [n, x] of Object.entries(m))
199
+ n === "reportedCostUsd" ? number(x) : integer(x);
200
+ }
201
+ }
202
+ }
203
+ function prediction(v) {
204
+ exact(v, ["actionKey", "support", "effectiveSupport", "reason"], ["meanQuality", "lowerQuality", "upperQuality", "latencyMs", "costUsd", "costMeaning"]);
205
+ hash(v.actionKey);
206
+ integer(v.support);
207
+ number(v.effectiveSupport, 0, v.support);
208
+ choice(v.reason, ["supported", "cold-start", "out-of-distribution", "stale", "unknown-metric"]);
209
+ for (const k of ["meanQuality", "lowerQuality", "upperQuality"])
210
+ if (k in v)
211
+ number(v[k], 0, 1);
212
+ for (const k of ["latencyMs", "costUsd"])
213
+ if (k in v)
214
+ number(v[k]);
215
+ if ("costMeaning" in v)
216
+ choice(v.costMeaning, ["provider-reported", "api-equivalent", "estimate"]);
217
+ }
218
+ function assessment(v) {
219
+ exact(v, ["episodeId", "episodeDigest", "observationDigests", "expectedCells", "verifiedCells", "tasks", "wins", "losses", "ties"], ["pValue", "meanGain"]);
220
+ identifier(v.episodeId);
221
+ hash(v.episodeDigest);
222
+ list(v.observationDigests);
223
+ for (const d of v.observationDigests)
224
+ hash(d);
225
+ integer(v.expectedCells);
226
+ integer(v.verifiedCells, 0, v.expectedCells);
227
+ for (const k of ["wins", "losses", "ties"])
228
+ integer(v[k]);
229
+ if ("pValue" in v)
230
+ number(v.pValue, 0, 1);
231
+ if ("meanGain" in v)
232
+ number(v.meanGain, -Number.MAX_VALUE);
233
+ list(v.tasks);
234
+ for (const t of v.tasks) {
235
+ exact(t, ["taskDigest", "fromAction", "toAction"], ["qualityDelta", "passRateDelta", "objectiveGain"]);
236
+ hash(t.taskDigest);
237
+ hash(t.fromAction);
238
+ hash(t.toAction);
239
+ for (const k of ["qualityDelta", "passRateDelta", "objectiveGain"])
240
+ if (k in t)
241
+ number(t[k], -Number.MAX_VALUE);
242
+ }
243
+ }
244
+ function binding(v) {
245
+ exact(v, ["definitionDigest", "actions", "features"], ["fallbackId"]);
246
+ hash(v.definitionDigest);
247
+ list(v.actions, 64);
248
+ if (!v.actions.length)
249
+ throw new TypeError("Empty policy binding actions");
250
+ v.actions.forEach(action);
251
+ if (new Set(v.actions.map((a) => a.id)).size !== v.actions.length || new Set(v.actions.map((a) => a.key)).size !== v.actions.length)
252
+ throw new TypeError("Duplicate policy binding action");
253
+ if (v.fallbackId !== void 0) {
254
+ identifier(v.fallbackId);
255
+ if (!v.actions.some((a) => a.id === v.fallbackId))
256
+ throw new TypeError("Policy binding fallback missing");
257
+ }
258
+ exact(v.features, ["schema", "dimensions"]);
259
+ identifier(v.features.schema);
260
+ integer(v.features.dimensions, 1, 512);
261
+ }
262
+
263
+ // src/routing/learning/validation.ts
264
+ function learningDomainDigest(value) {
265
+ const v = jsonClone(value);
266
+ exact(v, ["id", "sourceDigest", "scorerDigest", "protocolDigest"]);
267
+ identifier(v.id);
268
+ hash(v.sourceDigest);
269
+ hash(v.scorerDigest);
270
+ hash(v.protocolDigest);
271
+ return digest(v);
272
+ }
273
+ function validateFeatures(value) {
274
+ const v = jsonClone(value);
275
+ features(v);
276
+ return freeze(v);
277
+ }
278
+ function validatePolicyConfig(value) {
279
+ const v = jsonClone(value);
280
+ config(v);
281
+ return freeze(v);
282
+ }
283
+ var validatedRecords = /* @__PURE__ */ new WeakMap();
284
+ var headers = ["format", "domain", "digest"];
285
+ function base(v, id = true) {
286
+ if (v.format !== 1)
287
+ throw new TypeError("Invalid learning format");
288
+ hash(v.domain);
289
+ hash(v.digest);
290
+ if (id)
291
+ identifier(v.id);
292
+ }
293
+ function cells(v) {
294
+ list(v.arms, 64);
295
+ if (!v.arms.length)
296
+ throw new TypeError("No episode arms");
297
+ v.arms.forEach(action);
298
+ if (new Set(v.arms.map((a) => a.key)).size !== v.arms.length || new Set(v.arms.map((a) => a.id)).size !== v.arms.length)
299
+ throw new TypeError("Duplicate episode arm");
300
+ if ("fallbackId" in v) {
301
+ identifier(v.fallbackId);
302
+ if (!v.arms.some((a) => a.id === v.fallbackId))
303
+ throw new TypeError("Unknown fallback");
304
+ }
305
+ list(v.tasks, 1024);
306
+ if (!v.tasks.length)
307
+ throw new TypeError("No episode tasks");
308
+ for (const t of v.tasks) {
309
+ exact(t, ["taskDigest", "features"]);
310
+ hash(t.taskDigest);
311
+ features(t.features);
312
+ }
313
+ if (new Set(v.tasks.map((t) => t.taskDigest)).size !== v.tasks.length)
314
+ throw new TypeError("Duplicate task");
315
+ if (new Set(v.tasks.map((t) => `${t.features.schema}:${t.features.values.length}`)).size !== 1)
316
+ throw new TypeError("Mixed feature schema");
317
+ integer(v.repetitions, 1, 1e3);
318
+ list(v.cells, 4096);
319
+ if (v.cells.length !== v.tasks.length * v.arms.length * v.repetitions)
320
+ throw new TypeError("Incomplete Cartesian cells");
321
+ const unique = /* @__PURE__ */ new Set(), attempts = /* @__PURE__ */ new Set(), observations = /* @__PURE__ */ new Set();
322
+ for (const c of v.cells) {
323
+ exact(c, ["taskDigest", "actionKey", "repetition", "attemptId", "observationId"]);
324
+ hash(c.taskDigest);
325
+ hash(c.actionKey);
326
+ integer(c.repetition, 0, v.repetitions - 1);
327
+ identifier(c.attemptId);
328
+ identifier(c.observationId);
329
+ if (!v.tasks.some((t) => t.taskDigest === c.taskDigest) || !v.arms.some((a) => a.key === c.actionKey))
330
+ throw new TypeError("Unknown cell");
331
+ const key = `${c.taskDigest}:${c.actionKey}:${c.repetition}`;
332
+ if (unique.has(key) || attempts.has(c.attemptId) || observations.has(c.observationId))
333
+ throw new TypeError("Duplicate cell");
334
+ unique.add(key);
335
+ attempts.add(c.attemptId);
336
+ observations.add(c.observationId);
337
+ }
338
+ }
339
+ function check(kind, v) {
340
+ switch (kind) {
341
+ case "observation":
342
+ case "attempt": {
343
+ const terminal = kind === "observation";
344
+ exact(v, [...headers, "id", "decisionId", "decisionDigest", "action", "taskDigest", "features", "split", ...terminal ? ["attemptId", "outcome", "quality", "latency", "createdAt"] : ["startedAt", "observationId"]], ["episodeId", "repetition", ...terminal ? ["usage", "observedModels", "identityAfter"] : []]);
345
+ base(v);
346
+ hash(v.decisionDigest);
347
+ identifier(v.decisionId);
348
+ action(v.action);
349
+ hash(v.taskDigest);
350
+ features(v.features);
351
+ choice(v.split, ["train", "fixed", "fresh"]);
352
+ integer(terminal ? v.createdAt : v.startedAt);
353
+ if (!terminal)
354
+ identifier(v.observationId);
355
+ if (v.split === "train") {
356
+ if ("episodeId" in v || "repetition" in v)
357
+ throw new TypeError("Training cannot claim holdout");
358
+ } else {
359
+ identifier(v.episodeId);
360
+ integer(v.repetition);
361
+ }
362
+ if (terminal) {
363
+ identifier(v.attemptId);
364
+ choice(v.outcome, ["completed", "refused", "failed", "aborted", "timeout", "verifier-error", "identity-drift"]);
365
+ quality(v.quality);
366
+ latency(v.latency);
367
+ if (v.quality.state === "verified" && v.outcome !== "completed")
368
+ throw new TypeError("Only completed observations may be verified");
369
+ if ("usage" in v)
370
+ usage(v.usage);
371
+ if ("observedModels" in v) {
372
+ list(v.observedModels, 64);
373
+ for (const m of v.observedModels)
374
+ identifier(m);
375
+ }
376
+ if ("identityAfter" in v)
377
+ hash(v.identityAfter);
378
+ if (v.observedModels !== void 0 && v.usage?.perModel !== void 0) {
379
+ const normalize3 = (model) => model === v.action.model ? v.action.modelId : model;
380
+ const observed = new Set(v.observedModels.map(normalize3)), usageModels = new Set(Object.keys(v.usage.perModel).map(normalize3));
381
+ if (observed.size !== usageModels.size || [...observed].some((model) => !usageModels.has(model)))
382
+ throw new TypeError("Inconsistent observed model sets");
383
+ }
384
+ if (v.quality.state === "verified") {
385
+ const matches = (model) => model === v.action.modelId || model === v.action.model;
386
+ if (v.identityAfter !== void 0 && v.identityAfter !== v.action.executionDigest || v.action.evidenceScope === "model" && (v.observedModels?.some((model) => !matches(model)) || Object.keys(v.usage?.perModel ?? {}).some((model) => !matches(model)))) {
387
+ throw new TypeError("Verified observation contains model or execution identity drift");
388
+ }
389
+ }
390
+ }
391
+ break;
392
+ }
393
+ case "snapshot": {
394
+ exact(v, [...headers, "config", "through", "rows", "createdAt"], ["binding"]);
395
+ if (v.binding !== void 0)
396
+ binding(v.binding);
397
+ base(v, false);
398
+ config(v.config);
399
+ integer(v.through);
400
+ integer(v.createdAt);
401
+ list(v.rows, v.config.maxRows);
402
+ let last = 0;
403
+ let schema;
404
+ let dimensions;
405
+ for (const r of v.rows) {
406
+ exact(r, ["sequence", "observation"]);
407
+ integer(r.sequence, 1, v.through);
408
+ if (r.sequence <= last)
409
+ throw new TypeError("Unordered snapshot");
410
+ last = r.sequence;
411
+ const o = validateLearningRecord("observation", r.observation);
412
+ if (o.domain !== v.domain || o.split !== "train" || o.quality.state !== "verified" || o.createdAt > v.createdAt)
413
+ throw new TypeError("Invalid snapshot training row");
414
+ if (schema && (schema !== o.features.schema || dimensions !== o.features.values.length))
415
+ throw new TypeError("Mixed feature schema");
416
+ if (v.binding && (v.binding.features.schema !== o.features.schema || v.binding.features.dimensions !== o.features.values.length || !v.binding.actions.some((a) => a.key === o.action.key)))
417
+ throw new TypeError("Snapshot row outside bound feature/action scope");
418
+ schema = o.features.schema;
419
+ dimensions = o.features.values.length;
420
+ }
421
+ break;
422
+ }
423
+ case "decision": {
424
+ exact(v, [...headers, "id", "createdAt", "taskDigest", "featuresDigest", "definitionDigest", "policy", "mode", "reason", "candidates", "predictions", "nativeDispatches"], ["selected"]);
425
+ base(v);
426
+ integer(v.createdAt);
427
+ for (const k of ["taskDigest", "featuresDigest", "definitionDigest"])
428
+ hash(v[k]);
429
+ ref(v.policy);
430
+ choice(v.mode, ["fixed", "auto", "matrix"]);
431
+ choice(v.reason, ["FIXED", "INCUMBENT", "LEARNED", "MATRIX", "FALLBACK", "NO_ROUTE", "ABORTED", "TIMEOUT"]);
432
+ if (v.nativeDispatches !== 0)
433
+ throw new TypeError("Proposal cannot dispatch");
434
+ list(v.candidates, 64);
435
+ list(v.predictions, 64);
436
+ v.predictions.forEach(prediction);
437
+ const ids = /* @__PURE__ */ new Set(), keys = /* @__PURE__ */ new Set();
438
+ for (const c of v.candidates) {
439
+ exact(c, ["id", "model", "provider", "modelId", "status", "code"], ["action"]);
440
+ for (const k of ["id", "model", "provider", "modelId"])
441
+ identifier(c[k]);
442
+ if (ids.has(c.id))
443
+ throw new TypeError("Duplicate candidate");
444
+ ids.add(c.id);
445
+ choice(c.status, ["eligible", "excluded", "not-evaluated"]);
446
+ choice(c.code, ["READY", "NOT_NEEDED", "NOT_IN_RULE", "PROVIDER_NOT_ALLOWED", "MODEL_UNAVAILABLE", "MODEL_UNVERIFIED", "CLI_MISSING", "AUTH_REQUIRED", "AUTH_UNKNOWN", "SUBSCRIPTION_REQUIRED", "CLI_UNSUPPORTED", "POLICY_UNSUPPORTED", "PROBE_FAILED", "ABORTED", "TIMEOUT"]);
447
+ if (c.action) {
448
+ action(c.action);
449
+ if (c.action.id !== c.id || c.action.model !== c.model || c.action.provider !== c.provider || c.action.modelId !== c.modelId || keys.has(c.action.key))
450
+ throw new TypeError("Candidate action mismatch");
451
+ keys.add(c.action.key);
452
+ }
453
+ if (c.status === "eligible" && (!c.action || c.code !== "READY"))
454
+ throw new TypeError("Eligible action missing");
455
+ }
456
+ if (v.selected) {
457
+ action(v.selected);
458
+ if (!v.candidates.some((c) => c.status === "eligible" && c.action?.key === v.selected.key && digest(c.action) === digest(v.selected)))
459
+ throw new TypeError("Selected action outside candidates");
460
+ }
461
+ break;
462
+ }
463
+ case "episode": {
464
+ exact(v, [...headers, "id", "kind", "createdAt", "definitionDigest", "protocolDigest", "afterSequence", "arms", "tasks", "repetitions", "cells"], ["comparison", "fallbackId"]);
465
+ base(v);
466
+ integer(v.createdAt);
467
+ integer(v.afterSequence);
468
+ hash(v.definitionDigest);
469
+ hash(v.protocolDigest);
470
+ choice(v.kind, ["fixed", "fresh"]);
471
+ cells(v);
472
+ if (v.kind === "fresh" && !v.comparison || v.kind === "fixed" && v.comparison)
473
+ throw new TypeError("Episode comparison mismatch");
474
+ if (v.comparison) {
475
+ const c = v.comparison;
476
+ exact(c, ["expectedGeneration", "from", "to", "operation", "fixedEpisodeId", "config", "configDigest"]);
477
+ integer(c.expectedGeneration);
478
+ ref(c.from);
479
+ ref(c.to);
480
+ choice(c.operation, ["promote", "rollback"]);
481
+ identifier(c.fixedEpisodeId);
482
+ config(c.config);
483
+ hash(c.configDigest);
484
+ if (digest(c.config) !== c.configDigest || c.from === c.to)
485
+ throw new TypeError("Invalid comparison");
486
+ }
487
+ break;
488
+ }
489
+ case "gate": {
490
+ exact(v, [...headers, "id", "createdAt", "mode", "expectedGeneration", "from", "to", "definitionDigest", "configDigest", "outcome", "reason", "fixed", "fresh"]);
491
+ base(v);
492
+ integer(v.createdAt);
493
+ integer(v.expectedGeneration);
494
+ ref(v.from);
495
+ ref(v.to);
496
+ hash(v.definitionDigest);
497
+ hash(v.configDigest);
498
+ choice(v.mode, ["promote", "rollback"]);
499
+ choice(v.outcome, ["keep", "promote", "rollback"]);
500
+ choice(v.reason, ["SUPPORTED", "INCOMPLETE", "REGRESSION", "INSUFFICIENT", "INCOMPARABLE"]);
501
+ assessment(v.fixed);
502
+ assessment(v.fresh);
503
+ if (v.outcome !== "keep" && v.outcome !== v.mode)
504
+ throw new TypeError("Gate outcome mismatch");
505
+ break;
506
+ }
507
+ default:
508
+ throw new TypeError("Unknown learning record kind");
509
+ case "gate-commit":
510
+ exact(v, [...headers, "id", "gateDigest", "status", "before", "after", "createdAt"]);
511
+ base(v);
512
+ hash(v.gateDigest);
513
+ choice(v.status, ["kept", "promoted", "rolled-back", "stale"]);
514
+ pointer(v.before);
515
+ pointer(v.after);
516
+ integer(v.createdAt);
517
+ break;
518
+ }
519
+ const { digest: claimed, ...body } = v;
520
+ if (digest(body) !== claimed)
521
+ throw new TypeError("Learning record digest mismatch");
522
+ }
523
+ function validateLearningRecord(kind, value) {
524
+ if (value && typeof value === "object" && validatedRecords.get(value) === kind)
525
+ return value;
526
+ const v = jsonClone(value);
527
+ exact(v, [], Object.keys(v));
528
+ check(kind, v);
529
+ const result = freeze(v);
530
+ validatedRecords.set(result, kind);
531
+ return result;
532
+ }
533
+ function sealLearningRecord(kind, body) {
534
+ const v = jsonClone(body);
535
+ return validateLearningRecord(kind, { ...v, digest: digest(v) });
536
+ }
537
+
538
+ // src/routing/learning/factory-context.ts
539
+ var CONTEXT_KEYS = ["runtime", "task", "id", "signal", "timeoutMs", "evaluationArmId"];
540
+ function captureSelection(definition, context) {
541
+ const c = ownObject(context, CONTEXT_KEYS);
542
+ if (!c.runtime || typeof c.runtime !== "object" || types.isProxy(c.runtime))
543
+ throw new TypeError("A Runtime is required");
544
+ method(c.runtime, "resolveModel");
545
+ method(c.runtime, "registration");
546
+ definition = snapshot(definition, true);
547
+ object(definition);
548
+ const task = snapshot(c.task);
549
+ object(task, ["id", "version", "inputDigest", "text", "features"]);
550
+ identifier(task.id);
551
+ identifier(task.version);
552
+ hash(task.inputDigest);
553
+ if (typeof task.text !== "string" || task.text.length > 5e4 || inputDigest(task.text) !== task.inputDigest)
554
+ throw new TypeError("Task input digest mismatch");
555
+ const features2 = task.features === void 0 ? hashTaskFeatures(task.text) : task.features;
556
+ validateFeatures(features2);
557
+ const id = c.id ?? randomUUID();
558
+ identifier(id);
559
+ const timeoutMs = c.timeoutMs ?? 3e4;
560
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
561
+ throw new RangeError("Invalid timeoutMs");
562
+ if (c.signal !== void 0 && (types.isProxy(c.signal) || !(c.signal instanceof AbortSignal)))
563
+ throw new TypeError("Invalid AbortSignal");
564
+ if (c.evaluationArmId !== void 0)
565
+ identifier(c.evaluationArmId);
566
+ const fixed = typeof definition.model === "string";
567
+ const rawArms = fixed ? [{ id: "fixed", model: definition.model }] : (() => {
568
+ const auto2 = definition.model;
569
+ object(auto2, ["mode", "candidates", "fallback", "providers", "allowUnverifiedModels", "allowUnknownAuth"]);
570
+ if (auto2.mode !== "auto" || !Array.isArray(auto2.candidates) || !auto2.candidates.length || auto2.candidates.length > 64)
571
+ throw new TypeError("Invalid learning arms");
572
+ for (const name of ["allowUnverifiedModels", "allowUnknownAuth"])
573
+ if (auto2[name] !== void 0 && typeof auto2[name] !== "boolean")
574
+ throw new TypeError("Invalid learning filter");
575
+ if (auto2.providers !== void 0) {
576
+ strings(auto2.providers, 64);
577
+ for (const provider of auto2.providers)
578
+ c.runtime.registration(provider);
579
+ }
580
+ return auto2.candidates;
581
+ })();
582
+ const ids = /* @__PURE__ */ new Set(), optionKeys = /* @__PURE__ */ new Set();
583
+ const { model: _model, ...common } = definition;
584
+ const arms = rawArms.map((arm) => {
585
+ object(arm, ["id", "model", "effort", "evidenceScope"]);
586
+ identifier(arm.id);
587
+ if (ids.has(arm.id))
588
+ throw new TypeError("Duplicate arm ID");
589
+ ids.add(arm.id);
590
+ if (arm.effort !== void 0 && (typeof arm.effort !== "string" || !arm.effort.trim()))
591
+ throw new TypeError("Invalid effort");
592
+ const normalized = normalize({ ...common, ...arm.effort === void 0 ? {} : { effort: arm.effort }, model: arm.model }, c.runtime);
593
+ const model = snapshot(normalized.models[0]);
594
+ const name = `${model.provider}/${model.id}`;
595
+ const evidenceScope = arm.evidenceScope ?? "model";
596
+ if (!["model", "requested-system"].includes(evidenceScope))
597
+ throw new TypeError("Invalid evidence scope");
598
+ const optionsDigest = digest({ normalizedOptionsDigest: normalized.configDigest, evidenceScope });
599
+ const canonical2 = digest({ model: name, optionsDigest });
600
+ if (optionKeys.has(canonical2))
601
+ throw new TypeError("Duplicate canonical action");
602
+ optionKeys.add(canonical2);
603
+ return freeze({ id: arm.id, model, options: normalized.options, optionsDigest, evidenceScope });
604
+ });
605
+ const auto = fixed ? void 0 : definition.model;
606
+ if (auto?.fallback !== void 0 && !ids.has(auto.fallback))
607
+ throw new TypeError("Fallback outside candidate universe");
608
+ if (c.evaluationArmId !== void 0 && !ids.has(c.evaluationArmId))
609
+ throw new TypeError("Evaluation arm outside candidate universe");
610
+ const filters = auto === void 0 ? void 0 : { ...auto.providers === void 0 ? {} : { providers: auto.providers }, allowUnknownAuth: auto.allowUnknownAuth ?? false, allowUnverifiedModels: auto.allowUnverifiedModels ?? false };
611
+ const definitionDigest = digest({ mode: fixed ? "fixed" : "auto", arms: arms.map((a) => ({ id: a.id, model: `${a.model.provider}/${a.model.id}`, optionsDigest: a.optionsDigest })), fallback: auto?.fallback ?? null, filters: filters ?? null, featureSchema: features2.schema });
612
+ return {
613
+ runtime: c.runtime,
614
+ id,
615
+ taskDigest: task.inputDigest,
616
+ text: task.text,
617
+ features: freeze(snapshot(features2)),
618
+ timeoutMs,
619
+ cwd: resolve(common.cwd ?? process.cwd()),
620
+ mode: fixed ? "fixed" : "auto",
621
+ arms,
622
+ definitionDigest,
623
+ ...filters === void 0 ? {} : { auto: freeze(filters) },
624
+ ...auto?.fallback === void 0 ? {} : { fallbackId: auto.fallback },
625
+ ...c.signal === void 0 ? {} : { signal: c.signal },
626
+ ...c.evaluationArmId === void 0 ? {} : { evaluationArmId: c.evaluationArmId }
627
+ };
628
+ }
629
+ function createScope(captured, startedAt) {
630
+ const remaining = Math.floor(captured.timeoutMs - (performance.now() - startedAt));
631
+ if (remaining < 1)
632
+ throw new TimeoutError({ retryable: true }, "Learning operation deadline exceeded");
633
+ return new OperationScope({ timeoutMs: remaining, ...captured.signal === void 0 ? {} : { signal: captured.signal } });
634
+ }
635
+ function assertActive(scope) {
636
+ if (scope.signal.aborted)
637
+ throw scope.signal.reason;
638
+ if (scope.remainingMs() < 1)
639
+ throw new TimeoutError({ retryable: true }, "Learning operation deadline exceeded");
640
+ }
641
+ function safeCode(error) {
642
+ if (!error || typeof error !== "object" || types.isProxy(error))
643
+ return void 0;
644
+ const descriptor = Object.getOwnPropertyDescriptor(error, "code");
645
+ if (descriptor)
646
+ return Object.hasOwn(descriptor, "value") && typeof descriptor.value === "string" ? descriptor.value : void 0;
647
+ return void 0;
648
+ }
649
+
650
+ // src/routing/learning/estimator.ts
651
+ var DEFAULT_LEARNING_POLICY = freeze({ objective: "quality", minDistinctTasks: 3, minSimilarity: 0.2, maxAgeMs: 90 * 864e5, halfLifeMs: 30 * 864e5, qualityFloor: 0.5, maxRows: 512, alpha: 0.05, minImprovement: 0.01, minFreshTasks: 6 });
652
+ function buildSnapshot(domain, config2, through, rows, createdAt, binding2) {
653
+ hash(domain);
654
+ const cfg = validatePolicyConfig(config2);
655
+ if (!Number.isSafeInteger(through) || through < 0)
656
+ throw new TypeError("Invalid cutoff");
657
+ const sorted = jsonClone([...rows]).sort((a, b) => a.sequence - b.sequence);
658
+ let schema, dimensions, last = 0;
659
+ for (const r of sorted) {
660
+ const o = validateLearningRecord("observation", r.observation);
661
+ if (!Number.isSafeInteger(r.sequence) || r.sequence <= last || r.sequence > through || o.domain !== domain || o.split !== "train" || o.quality.state !== "verified" || o.createdAt > createdAt)
662
+ throw new TypeError("Invalid training row");
663
+ last = r.sequence;
664
+ if (schema && (schema !== o.features.schema || dimensions !== o.features.values.length))
665
+ throw new TypeError("Mixed schemas");
666
+ schema = o.features.schema;
667
+ dimensions = o.features.values.length;
668
+ }
669
+ return sealLearningRecord("snapshot", { format: 1, domain, config: cfg, through, rows: sorted.slice(-cfg.maxRows), createdAt, ...binding2 ? { binding: binding2 } : {} });
670
+ }
671
+ function cosine(a, b) {
672
+ return a.length === b.length ? a.reduce((n, x, i) => n + x * b[i], 0) : 0;
673
+ }
674
+ function predict(snapshot2, features2, actions, asOf) {
675
+ const s = validateLearningRecord("snapshot", snapshot2), f = validateFeatures(features2), cfg = s.config;
676
+ actions = jsonClone(actions);
677
+ actions.forEach(action);
678
+ if (!Number.isSafeInteger(asOf) || asOf < 0)
679
+ throw new TypeError("Invalid prediction time");
680
+ return freeze(actions.map((a) => {
681
+ const base2 = { actionKey: a.key, support: 0, effectiveSupport: 0 };
682
+ if (!Math.hypot(...f.values))
683
+ return { ...base2, reason: "cold-start" };
684
+ const all = s.rows.filter((r) => r.observation.action.key === a.key && r.observation.features.schema === f.schema && r.observation.features.values.length === f.values.length && r.observation.createdAt <= asOf);
685
+ if (!all.length)
686
+ return { ...base2, reason: "cold-start" };
687
+ const recent = all.filter((r) => asOf - r.observation.createdAt <= cfg.maxAgeMs);
688
+ if (!recent.length)
689
+ return { ...base2, reason: "stale" };
690
+ const groups = /* @__PURE__ */ new Map();
691
+ for (const r of recent) {
692
+ if (cosine(f.values, r.observation.features.values) < cfg.minSimilarity)
693
+ continue;
694
+ const list2 = groups.get(r.observation.taskDigest) ?? [];
695
+ list2.push(r);
696
+ groups.set(r.observation.taskDigest, list2);
697
+ }
698
+ if (!groups.size)
699
+ return { ...base2, reason: "out-of-distribution" };
700
+ const neighbors = [];
701
+ for (const rs of groups.values()) {
702
+ const weights = rs.map((r) => Math.max(0, cosine(f.values, r.observation.features.values)) * Math.pow(2, -(asOf - r.observation.createdAt) / cfg.halfLifeMs));
703
+ const total2 = weights.reduce((x, y) => x + y, 0);
704
+ if (!total2)
705
+ continue;
706
+ const n = { weight: Math.max(...weights), quality: rs.reduce((sum, r, i) => sum + (r.observation.quality.state === "verified" ? r.observation.quality.value : 0) * weights[i], 0) / total2 };
707
+ if (rs.every((r) => r.observation.latency.state === "observed"))
708
+ n.latency = rs.reduce((sum, r, i) => sum + (r.observation.latency.state === "observed" ? r.observation.latency.durationMs : 0) * weights[i], 0) / total2;
709
+ const meanings2 = new Set(rs.map((r) => r.observation.usage?.costMeaning));
710
+ if (meanings2.size === 1 && !meanings2.has(void 0) && !meanings2.has("unavailable") && rs.every((r) => r.observation.usage?.reportedCostUsd !== void 0)) {
711
+ n.meaning = rs[0].observation.usage.costMeaning;
712
+ n.cost = rs.reduce((sum, r, i) => sum + r.observation.usage.reportedCostUsd * weights[i], 0) / total2;
713
+ }
714
+ neighbors.push(n);
715
+ }
716
+ const total = neighbors.reduce((sum, n) => sum + n.weight, 0), squares = neighbors.reduce((sum, n) => sum + n.weight * n.weight, 0);
717
+ if (!total)
718
+ return { ...base2, reason: "stale" };
719
+ const effectiveSupport = Math.min(total, total * total / squares), support = neighbors.length;
720
+ const meanQuality = neighbors.reduce((sum, n) => sum + n.weight * n.quality, 0) / total;
721
+ const radius = Math.sqrt(Math.log(2 / cfg.alpha) / (2 * Math.max(effectiveSupport, Number.EPSILON)));
722
+ const result = { actionKey: a.key, support, effectiveSupport, meanQuality, lowerQuality: Math.max(0, meanQuality - radius), upperQuality: Math.min(1, meanQuality + radius), reason: support >= cfg.minDistinctTasks && effectiveSupport >= cfg.minDistinctTasks ? "supported" : "cold-start" };
723
+ if (neighbors.every((n) => n.latency !== void 0))
724
+ result.latencyMs = neighbors.reduce((sum, n) => sum + n.weight * n.latency, 0) / total;
725
+ const meanings = new Set(neighbors.map((n) => n.meaning));
726
+ if (meanings.size === 1 && !meanings.has(void 0) && neighbors.every((n) => n.cost !== void 0)) {
727
+ result.costUsd = neighbors.reduce((sum, n) => sum + n.weight * n.cost, 0) / total;
728
+ result.costMeaning = neighbors[0].meaning;
729
+ }
730
+ if (result.reason === "supported" && (cfg.objective === "latency" && result.latencyMs === void 0 || cfg.objective === "cost" && result.costUsd === void 0))
731
+ result.reason = "unknown-metric";
732
+ return result;
733
+ }));
734
+ }
735
+ function selectPolicyDecision(snapshot2, orderedActions, features2, asOf, fallbackId) {
736
+ orderedActions = jsonClone(orderedActions);
737
+ orderedActions.forEach(action);
738
+ features2 = validateFeatures(features2);
739
+ if (!Number.isSafeInteger(asOf) || asOf < 0)
740
+ throw new TypeError("Invalid prediction time");
741
+ const primary = orderedActions.filter((a) => a.id !== fallbackId), pool = primary.length ? primary : orderedActions.filter((a) => a.id === fallbackId);
742
+ const incumbent = { ...pool[0] === void 0 ? {} : { action: pool[0] }, reason: "incumbent" };
743
+ if (!snapshot2)
744
+ return incumbent;
745
+ const ps = predict(snapshot2, features2, pool, asOf);
746
+ const eligible = pool.map((a, i) => ({ a, p: ps[i] })).filter(({ p }) => p.reason === "supported" && p.lowerQuality !== void 0 && p.lowerQuality >= snapshot2.config.qualityFloor);
747
+ if (!eligible.length)
748
+ return incumbent;
749
+ const cfg = snapshot2.config;
750
+ if (cfg.objective === "cost" && new Set(eligible.map(({ p }) => p.costMeaning)).size !== 1)
751
+ return incumbent;
752
+ eligible.sort((x, y) => cfg.objective === "quality" ? y.p.lowerQuality - x.p.lowerQuality : cfg.objective === "latency" ? x.p.latencyMs - y.p.latencyMs : x.p.costUsd - y.p.costUsd);
753
+ const action2 = eligible[0]?.a;
754
+ return action2 === void 0 ? incumbent : { action: action2, reason: "supported" };
755
+ }
756
+ function selectPolicy(snapshot2, orderedActions, features2, asOf, fallbackId) {
757
+ return selectPolicyDecision(snapshot2, orderedActions, features2, asOf, fallbackId).action;
758
+ }
759
+
760
+ // src/routing/learning/factory-binding.ts
761
+ function policyBinding(captured, preflight) {
762
+ return freeze({
763
+ definitionDigest: captured.definitionDigest,
764
+ actions: preflight.actions,
765
+ ...preflight.fallbackId === void 0 ? {} : { fallbackId: preflight.fallbackId },
766
+ features: { schema: captured.features.schema, dimensions: captured.features.values.length }
767
+ });
768
+ }
769
+ function appliesTo(binding2, current) {
770
+ if (!binding2 || binding2.definitionDigest !== current.definitionDigest || binding2.fallbackId !== current.fallbackId || digest(binding2.features) !== digest(current.features))
771
+ return false;
772
+ let previous = -1;
773
+ for (const action2 of current.actions) {
774
+ const index = binding2.actions.findIndex((a) => digest(a) === digest(action2));
775
+ if (index <= previous)
776
+ return false;
777
+ previous = index;
778
+ }
779
+ return true;
780
+ }
781
+
782
+ // src/routing/learning/factory.ts
783
+ function probeCode(error) {
784
+ switch (safeCode(error)) {
785
+ case "CLI_NOT_INSTALLED":
786
+ return "CLI_MISSING";
787
+ case "NOT_AUTHENTICATED":
788
+ return "AUTH_REQUIRED";
789
+ case "UNEXPECTED_AUTH_SOURCE":
790
+ return "SUBSCRIPTION_REQUIRED";
791
+ case "UNSUPPORTED_CLI_VERSION":
792
+ return "CLI_UNSUPPORTED";
793
+ case "UNSUPPORTED_CAPABILITY":
794
+ case "REQUIRED_TRANSPORT_UNAVAILABLE":
795
+ return "POLICY_UNSUPPORTED";
796
+ default:
797
+ return "PROBE_FAILED";
798
+ }
799
+ }
800
+ function modelMatches(actual, expected) {
801
+ const a = snapshot(actual);
802
+ return a.provider === expected.provider && a.id === expected.id && a.availability === expected.availability;
803
+ }
804
+ function executionDigest(readiness) {
805
+ const ready = snapshot(readiness);
806
+ const { authorityEpoch: _epoch, ...envelope } = ready.plan.envelope;
807
+ return digest({
808
+ provider: ready.provider,
809
+ model: `${ready.model.provider}/${ready.model.id}`,
810
+ transport: ready.plan.transport,
811
+ fingerprint: ready.plan.fingerprint,
812
+ capabilities: ready.plan.capabilities,
813
+ envelope,
814
+ auth: { source: ready.auth.source, state: authenticationState(ready.auth) }
815
+ });
816
+ }
817
+ async function prepareSelection(captured, domain, scope) {
818
+ const candidates = captured.arms.map((a) => ({ id: a.id, model: `${a.model.provider}/${a.model.id}`, provider: a.model.provider, modelId: a.model.id, status: "not-evaluated", code: "NOT_NEEDED" }));
819
+ const agents = /* @__PURE__ */ new Map(), readiness = /* @__PURE__ */ new Map();
820
+ candidates.forEach((candidate, index) => {
821
+ const arm = captured.arms[index];
822
+ let code;
823
+ if (captured.auto?.providers && !captured.auto.providers.includes(candidate.provider))
824
+ code = "PROVIDER_NOT_ALLOWED";
825
+ else if (arm.model.availability === "unavailable")
826
+ code = "MODEL_UNAVAILABLE";
827
+ else if (captured.auto && arm.model.availability === "unverified" && !captured.auto.allowUnverifiedModels)
828
+ code = "MODEL_UNVERIFIED";
829
+ if (code) {
830
+ candidate.status = "excluded";
831
+ candidate.code = code;
832
+ }
833
+ });
834
+ assertActive(scope);
835
+ for (let index = 0; index < candidates.length; index++) {
836
+ const candidate = candidates[index], arm = captured.arms[index];
837
+ if (candidate.status === "excluded")
838
+ continue;
839
+ assertActive(scope);
840
+ try {
841
+ const agent = new Agent({ ...arm.options, model: candidate.model }, captured.runtime);
842
+ if (!modelMatches(agent.model, arm.model)) {
843
+ candidate.status = "excluded";
844
+ candidate.code = "PROBE_FAILED";
845
+ continue;
846
+ }
847
+ const ready = snapshot(await agent.ready({ signal: scope.signal, timeoutMs: Math.max(1, scope.remainingMs()), awaitSettlement: true }));
848
+ assertActive(scope);
849
+ if (!modelMatches(agent.model, arm.model) || !modelMatches(ready.model, arm.model) || ready.provider !== candidate.provider)
850
+ throw new TypeError("Readiness model changed");
851
+ const auth = authenticationState(ready.auth);
852
+ let code;
853
+ if (ready.capabilities.unsupported.length)
854
+ code = "POLICY_UNSUPPORTED";
855
+ else if (auth === "not-authenticated")
856
+ code = "AUTH_REQUIRED";
857
+ else if (captured.auto && auth === "unknown" && !captured.auto.allowUnknownAuth)
858
+ code = "AUTH_UNKNOWN";
859
+ else if (!ready.ready || !ready.installation.installed)
860
+ code = "CLI_MISSING";
861
+ if (code) {
862
+ candidate.status = "excluded";
863
+ candidate.code = code;
864
+ continue;
865
+ }
866
+ const identity = { model: candidate.model, provider: candidate.provider, modelId: candidate.modelId, optionsDigest: arm.optionsDigest, executionDigest: executionDigest(ready), evidenceScope: arm.evidenceScope };
867
+ const action2 = freeze({ id: candidate.id, ...identity, key: digest(identity) });
868
+ candidate.action = action2;
869
+ candidate.status = "eligible";
870
+ candidate.code = "READY";
871
+ agents.set(action2.key, agent);
872
+ readiness.set(action2.key, ready);
873
+ } catch (error) {
874
+ rethrowExecutionHalt(error);
875
+ assertActive(scope);
876
+ candidate.status = "excluded";
877
+ candidate.code = probeCode(error);
878
+ }
879
+ }
880
+ assertActive(scope);
881
+ const actions = candidates.flatMap((c) => c.action ? [c.action] : []);
882
+ if (new Set(actions.map((a) => a.key)).size !== actions.length)
883
+ throw new TypeError("Duplicate canonical action");
884
+ return { preflight: freeze({ domain, definitionDigest: captured.definitionDigest, candidates, actions, ...captured.fallbackId === void 0 ? {} : { fallbackId: captured.fallbackId } }), agents, readiness };
885
+ }
886
+
887
+ // src/routing/learning/router-state.ts
888
+ function captureRouter(options) {
889
+ options = ownObject(options, ["store", "domain", "policy"]);
890
+ const domain = learningDomainDigest(options.domain);
891
+ const protocolDigest = snapshot(options.domain).protocolDigest;
892
+ const policy = validatePolicyConfig({ ...DEFAULT_LEARNING_POLICY, ...options.policy === void 0 ? {} : snapshot(options.policy) });
893
+ const store = /* @__PURE__ */ Object.create(null);
894
+ for (const key of ["put", "get", "highWater", "observations", "appendObservation", "pointer", "commitGate", "pending", "close"]) {
895
+ Object.defineProperty(store, key, { value: method(options.store, key), enumerable: true });
896
+ }
897
+ return freeze({ store, domain, protocolDigest, policy });
898
+ }
899
+ function scopedPointer(value) {
900
+ const p = snapshot(value);
901
+ ownObject(p, ["generation", "active", "previous"]);
902
+ const pointer2 = p;
903
+ if (!Number.isSafeInteger(pointer2.generation) || pointer2.generation < 0 || ![pointer2.active, pointer2.previous].every((x) => x === null || typeof x === "string" && /^[a-f0-9]{64}$/.test(x)))
904
+ throw new TypeError("Invalid learning pointer");
905
+ return freeze(pointer2);
906
+ }
907
+
908
+ // src/routing/learning/factory-decision.ts
909
+ var LearningSelectionError = class extends Error {
910
+ constructor(code, receipt) {
911
+ super(`Learning selection ${code}`);
912
+ this.code = code;
913
+ this.receipt = receipt;
914
+ this.name = "LearningSelectionError";
915
+ }
916
+ code;
917
+ receipt;
918
+ };
919
+ async function decide(state, captured, scope) {
920
+ let prepared;
921
+ let active;
922
+ let failure2;
923
+ const cancellation = () => scope.signal.aborted || scope.remainingMs() < 1 ? safeCode(scope.signal.reason) === "TIMEOUT" || scope.remainingMs() < 1 ? "TIMEOUT" : "ABORTED" : void 0;
924
+ try {
925
+ prepared = await prepareSelection(captured, state.domain, scope);
926
+ } catch (error) {
927
+ rethrowExecutionHalt(error);
928
+ failure2 = cancellation();
929
+ if (!failure2)
930
+ throw error;
931
+ }
932
+ failure2 ??= cancellation();
933
+ if (!failure2 && captured.mode === "auto" && captured.evaluationArmId === void 0) {
934
+ const pointer2 = scopedPointer(await state.store.pointer(state.domain));
935
+ failure2 = cancellation();
936
+ if (!failure2 && pointer2.active !== null) {
937
+ const value = await state.store.get("snapshot", pointer2.active);
938
+ if (!value)
939
+ throw new Error("Active learning snapshot is missing");
940
+ active = validateLearningRecord("snapshot", value);
941
+ if (active.domain !== state.domain || active.digest !== pointer2.active)
942
+ throw new TypeError("Active snapshot binding mismatch");
943
+ if (digest(active.config) !== digest(state.policy))
944
+ throw new TypeError("Active policy configuration differs from the declared router config");
945
+ if (!appliesTo(active.binding, policyBinding(captured, prepared.preflight)))
946
+ active = void 0;
947
+ failure2 = cancellation();
948
+ }
949
+ }
950
+ const preflight = prepared?.preflight;
951
+ const actions = preflight?.actions ?? [];
952
+ const asOf = Date.now();
953
+ const policyDecision = !failure2 && captured.evaluationArmId === void 0 ? selectPolicyDecision(active, actions, captured.features, asOf, captured.fallbackId) : void 0;
954
+ const selected = failure2 ? void 0 : captured.evaluationArmId === void 0 ? policyDecision?.action : actions.find((a) => a.id === captured.evaluationArmId);
955
+ const predictions = active && !failure2 ? predict(active, captured.features, actions, asOf) : [];
956
+ const supported = policyDecision?.reason === "supported";
957
+ const reason = failure2 ?? (!selected ? "NO_ROUTE" : captured.evaluationArmId !== void 0 ? "MATRIX" : captured.mode === "fixed" ? "FIXED" : selected.id === captured.fallbackId ? "FALLBACK" : supported ? "LEARNED" : "INCUMBENT");
958
+ const candidates = preflight?.candidates ?? captured.arms.map((a) => ({ id: a.id, model: `${a.model.provider}/${a.model.id}`, provider: a.model.provider, modelId: a.model.id, status: "excluded", code: failure2 ?? "PROBE_FAILED" }));
959
+ const receipt = sealLearningRecord("decision", {
960
+ format: 1,
961
+ id: captured.id,
962
+ domain: state.domain,
963
+ createdAt: asOf,
964
+ taskDigest: captured.taskDigest,
965
+ featuresDigest: digest(captured.features),
966
+ definitionDigest: captured.definitionDigest,
967
+ policy: active?.digest ?? null,
968
+ mode: captured.evaluationArmId !== void 0 ? "matrix" : captured.mode,
969
+ reason,
970
+ candidates,
971
+ predictions,
972
+ ...selected === void 0 ? {} : { selected },
973
+ nativeDispatches: 0
974
+ });
975
+ await state.store.put("decision", receipt.id, receipt);
976
+ const cancelledAfterSave = cancellation();
977
+ if (cancelledAfterSave)
978
+ throw new LearningSelectionError(cancelledAfterSave, receipt);
979
+ const agent = selected && prepared?.agents.get(selected.key);
980
+ if (!selected || !agent)
981
+ throw new LearningSelectionError(failure2 ?? "NO_ROUTE", receipt);
982
+ const expected = captured.arms.find((a) => a.id === selected.id);
983
+ if (!modelMatches(agent.model, expected.model))
984
+ throw new LearningSelectionError("NO_ROUTE", receipt);
985
+ return { agent, receipt, prepared };
986
+ }
987
+
988
+ // src/routing/learning/evidence.ts
989
+ function empty(e, rows = []) {
990
+ const lookup = new Map(rows.map((r) => [r.observation.id, r.observation.digest]));
991
+ return { episodeId: e.id, episodeDigest: e.digest, observationDigests: e.cells.flatMap((c) => lookup.has(c.observationId) ? [lookup.get(c.observationId)] : []), expectedCells: e.cells.length, verifiedCells: 0, tasks: [], wins: 0, losses: 0, ties: 0 };
992
+ }
993
+ function signP(wins, losses) {
994
+ const n = wins + losses;
995
+ if (!n)
996
+ return 1;
997
+ if (n > 1e4)
998
+ return 1;
999
+ let logTerm = 0, sum = 0;
1000
+ for (let k = 0; k <= n; k++) {
1001
+ if (k >= wins)
1002
+ sum += Math.exp(logTerm - n * Math.LN2);
1003
+ if (k < n)
1004
+ logTerm += Math.log(n - k) - Math.log(k + 1);
1005
+ }
1006
+ return Math.min(1, sum);
1007
+ }
1008
+ function mean(xs) {
1009
+ return xs.reduce((n, x) => n + x, 0) / xs.length;
1010
+ }
1011
+ function assess(e, rows, input, selections) {
1012
+ const result = empty(e), lookup = new Map(rows.map((r) => [r.observation.id, r]));
1013
+ let incomplete = false, regression = false, unknown = false;
1014
+ const byTaskAction = /* @__PURE__ */ new Map();
1015
+ const digests = [];
1016
+ for (const cell of e.cells) {
1017
+ const row = lookup.get(cell.observationId), o = row?.observation;
1018
+ if (o)
1019
+ digests.push(o.digest);
1020
+ if (!o || !row || row.sequence <= e.afterSequence || o.domain !== e.domain || o.split !== e.kind || o.episodeId !== e.id || o.attemptId !== cell.attemptId || o.taskDigest !== cell.taskDigest || o.action.key !== cell.actionKey || o.repetition !== cell.repetition || o.quality.state !== "verified" || o.outcome !== "completed" || digest(o.action) !== digest(e.arms.find((a) => a.key === cell.actionKey)) || digest(o.features) !== digest(e.tasks.find((t) => t.taskDigest === cell.taskDigest).features)) {
1021
+ incomplete = true;
1022
+ continue;
1023
+ }
1024
+ result.verifiedCells++;
1025
+ const key = `${cell.taskDigest}:${cell.actionKey}`;
1026
+ const rs = byTaskAction.get(key) ?? [];
1027
+ rs.push(o);
1028
+ byTaskAction.set(key, rs);
1029
+ }
1030
+ result.observationDigests = digests;
1031
+ if (incomplete)
1032
+ return { assessment: result, incomplete, regression, unknown };
1033
+ const tasks = [], cfg = input.fresh.comparison.config;
1034
+ for (const task of e.tasks) {
1035
+ const featureKey = digest(task.features);
1036
+ let selected = selections.get(featureKey);
1037
+ if (!selected) {
1038
+ const from2 = selectPolicy(input.fromSnapshot, e.arms, task.features, input.fresh.createdAt, e.fallbackId), to2 = selectPolicy(input.toSnapshot, e.arms, task.features, input.fresh.createdAt, e.fallbackId);
1039
+ selected = { ...from2 ? { from: from2.key } : {}, ...to2 ? { to: to2.key } : {} };
1040
+ selections.set(featureKey, selected);
1041
+ }
1042
+ const from = selected.from, to = selected.to;
1043
+ if (!from || !to) {
1044
+ unknown = true;
1045
+ continue;
1046
+ }
1047
+ const a = byTaskAction.get(`${task.taskDigest}:${from}`), b = byTaskAction.get(`${task.taskDigest}:${to}`);
1048
+ const qa = mean(a.map((o) => o.quality.state === "verified" ? o.quality.value : NaN)), qb = mean(b.map((o) => o.quality.state === "verified" ? o.quality.value : NaN));
1049
+ const pa = mean(a.map((o) => o.quality.state === "verified" && o.quality.passed ? 1 : 0)), pb = mean(b.map((o) => o.quality.state === "verified" && o.quality.passed ? 1 : 0));
1050
+ const pair = { taskDigest: task.taskDigest, fromAction: from, toAction: to, qualityDelta: qb - qa, passRateDelta: pb - pa };
1051
+ if (qb + 1e-12 < qa || pb + 1e-12 < pa)
1052
+ regression = true;
1053
+ if (cfg.objective === "quality")
1054
+ pair.objectiveGain = qb - qa;
1055
+ else if (qa < cfg.qualityFloor || qb < cfg.qualityFloor)
1056
+ unknown = true;
1057
+ else if (cfg.objective === "latency") {
1058
+ if ([...a, ...b].every((o) => o.latency.state === "observed")) {
1059
+ const av = mean(a.map((o) => o.latency.state === "observed" ? o.latency.durationMs : NaN)), bv = mean(b.map((o) => o.latency.state === "observed" ? o.latency.durationMs : NaN));
1060
+ if (av > 0)
1061
+ pair.objectiveGain = (av - bv) / av;
1062
+ else
1063
+ unknown = true;
1064
+ } else
1065
+ unknown = true;
1066
+ } else {
1067
+ const meaning = new Set([...a, ...b].map((o) => o.usage?.costMeaning));
1068
+ if (meaning.size === 1 && !meaning.has(void 0) && !meaning.has("unavailable") && [...a, ...b].every((o) => o.usage?.reportedCostUsd !== void 0)) {
1069
+ const av = mean(a.map((o) => o.usage.reportedCostUsd)), bv = mean(b.map((o) => o.usage.reportedCostUsd));
1070
+ if (av > 0)
1071
+ pair.objectiveGain = (av - bv) / av;
1072
+ else
1073
+ unknown = true;
1074
+ } else
1075
+ unknown = true;
1076
+ }
1077
+ if (pair.objectiveGain !== void 0) {
1078
+ if (pair.objectiveGain > 1e-12)
1079
+ result.wins++;
1080
+ else if (pair.objectiveGain < -1e-12) {
1081
+ result.losses++;
1082
+ regression = true;
1083
+ } else
1084
+ result.ties++;
1085
+ }
1086
+ tasks.push(pair);
1087
+ }
1088
+ result.tasks = tasks;
1089
+ const gains = tasks.flatMap((t) => t.objectiveGain === void 0 ? [] : [t.objectiveGain]);
1090
+ if (gains.length === tasks.length && gains.length) {
1091
+ result.meanGain = mean(gains);
1092
+ result.pValue = signP(result.wins, result.losses);
1093
+ }
1094
+ return { assessment: result, incomplete, regression, unknown };
1095
+ }
1096
+ function assessGateEvidence(value) {
1097
+ const input = ownObject(value, ["id", "createdAt", "domain", "fresh", "fixed", "fromSnapshot", "toSnapshot", "observations"]);
1098
+ const fresh = validateLearningRecord("episode", input.fresh), fixed = validateLearningRecord("episode", input.fixed), c = fresh.comparison;
1099
+ if (!c)
1100
+ throw new TypeError("Fresh comparison missing");
1101
+ const from = input.fromSnapshot ? validateLearningRecord("snapshot", input.fromSnapshot) : void 0, to = input.toSnapshot ? validateLearningRecord("snapshot", input.toSnapshot) : void 0;
1102
+ if (!Array.isArray(input.observations) || input.observations.length > 8192)
1103
+ throw new TypeError("Gate observation union exceeds 8192 rows");
1104
+ const observations = jsonClone(input.observations).map((value2) => {
1105
+ const r = ownObject(value2, ["sequence", "observation"]);
1106
+ return { sequence: r.sequence, observation: validateLearningRecord("observation", r.observation) };
1107
+ });
1108
+ if (input.createdAt < Math.max(fresh.createdAt, fixed.createdAt, from?.createdAt ?? 0, to?.createdAt ?? 0, observations.reduce((at, r) => Math.max(at, r.observation.createdAt), 0)))
1109
+ throw new TypeError("Gate timestamp violates evidence causal order");
1110
+ let incomparable = fresh.domain !== input.domain || fixed.domain !== input.domain || fresh.kind !== "fresh" || fixed.kind !== "fixed" || c.fixedEpisodeId !== fixed.id || fresh.definitionDigest !== fixed.definitionDigest || fresh.protocolDigest !== fixed.protocolDigest || digest(fresh.arms) !== digest(fixed.arms) || fresh.fallbackId !== fixed.fallbackId || fresh.repetitions !== fixed.repetitions || c.from !== (from?.digest ?? null) || c.to !== (to?.digest ?? null) || c.from === c.to;
1111
+ for (const snapshot2 of [from, to])
1112
+ if (snapshot2) {
1113
+ const b = snapshot2.binding;
1114
+ if (!b || b.definitionDigest !== fresh.definitionDigest || digest(b.actions) !== digest(fresh.arms) || b.fallbackId !== fresh.fallbackId || b.features.schema !== fresh.tasks[0].features.schema || b.features.dimensions !== fresh.tasks[0].features.values.length)
1115
+ incomparable = true;
1116
+ }
1117
+ if (fresh.createdAt < fixed.createdAt)
1118
+ incomparable = true;
1119
+ const featureIdentities = new Set([...fresh.tasks, ...fixed.tasks, ...from?.rows.map((r) => r.observation) ?? [], ...to?.rows.map((r) => r.observation) ?? []].map((t) => `${t.features.schema}:${t.features.values.length}`));
1120
+ if (featureIdentities.size !== 1)
1121
+ incomparable = true;
1122
+ const manifests = /* @__PURE__ */ new Map([[fresh.id, fresh], [fixed.id, fixed]]);
1123
+ if (observations.some((r) => {
1124
+ const e = manifests.get(r.observation.episodeId ?? "");
1125
+ return e && (r.observation.createdAt < e.createdAt || r.sequence <= e.afterSequence);
1126
+ }))
1127
+ incomparable = true;
1128
+ const heldout = new Set([...fresh.tasks, ...fixed.tasks].map((t) => t.taskDigest));
1129
+ if (new Set([...fresh.tasks, ...fixed.tasks].map((t) => t.taskDigest)).size !== fresh.tasks.length + fixed.tasks.length)
1130
+ incomparable = true;
1131
+ for (const s of [from, to])
1132
+ if (s && (s.domain !== input.domain || s.through > fresh.afterSequence || s.createdAt > fresh.createdAt || digest(s.config) !== c.configDigest || s.rows.some((r) => heldout.has(r.observation.taskDigest))))
1133
+ incomparable = true;
1134
+ if (new Set(observations.map((r) => r.observation.id)).size !== observations.length || new Set(observations.map((r) => r.sequence)).size !== observations.length || observations.some((r) => !Number.isSafeInteger(r.sequence) || r.sequence < 1))
1135
+ incomparable = true;
1136
+ const normalized = { ...input, fresh, fixed, observations, ...from ? { fromSnapshot: from } : {}, ...to ? { toSnapshot: to } : {} };
1137
+ const selections = /* @__PURE__ */ new Map();
1138
+ const fa = incomparable ? { assessment: empty(fixed, observations), incomplete: false, regression: false, unknown: false } : assess(fixed, observations, normalized, selections), fr = incomparable ? { assessment: empty(fresh, observations), incomplete: false, regression: false, unknown: false } : assess(fresh, observations, normalized, selections);
1139
+ let reason = "SUPPORTED";
1140
+ if (incomparable)
1141
+ reason = "INCOMPARABLE";
1142
+ else if (fa.incomplete || fr.incomplete)
1143
+ reason = "INCOMPLETE";
1144
+ else if (fa.regression || fr.regression)
1145
+ reason = "REGRESSION";
1146
+ else if (fa.unknown || fr.unknown || fr.assessment.tasks.length < c.config.minFreshTasks || fr.assessment.pValue === void 0 || fr.assessment.pValue > c.config.alpha || fr.assessment.meanGain === void 0 || fr.assessment.meanGain < c.config.minImprovement || fr.assessment.meanGain <= 0)
1147
+ reason = "INSUFFICIENT";
1148
+ return sealLearningRecord("gate", { format: 1, id: input.id, domain: input.domain, createdAt: input.createdAt, mode: c.operation, expectedGeneration: c.expectedGeneration, from: c.from, to: c.to, definitionDigest: fresh.definitionDigest, configDigest: c.configDigest, outcome: reason === "SUPPORTED" ? c.operation : "keep", reason, fixed: fa.assessment, fresh: fr.assessment });
1149
+ }
1150
+
1151
+ // src/routing/learning/gate.ts
1152
+ async function improvePolicy(state, options) {
1153
+ options = ownObject(options, ["id", "freshEpisodeId"]);
1154
+ const { id, freshEpisodeId } = options;
1155
+ identifier(id);
1156
+ identifier(freshEpisodeId);
1157
+ const previousGate = await state.store.get("gate", id);
1158
+ const previousCommit = previousGate ? await state.store.get("gate-commit", id) : void 0;
1159
+ const rawFresh = await state.store.get("episode", freshEpisodeId);
1160
+ if (!rawFresh)
1161
+ throw new Error("Fresh learning episode is missing");
1162
+ const fresh = validateLearningRecord("episode", rawFresh);
1163
+ if (fresh.domain !== state.domain || fresh.kind !== "fresh" || !fresh.comparison || fresh.protocolDigest !== state.protocolDigest || digest(fresh.comparison.config) !== digest(state.policy) || fresh.comparison.configDigest !== digest(state.policy))
1164
+ throw new TypeError("Invalid fresh episode protocol or configuration scope");
1165
+ const rawFixed = await state.store.get("episode", fresh.comparison.fixedEpisodeId);
1166
+ if (!rawFixed)
1167
+ throw new Error("Fixed learning episode is missing");
1168
+ const fixed = validateLearningRecord("episode", rawFixed);
1169
+ if (fixed.domain !== state.domain || fixed.kind !== "fixed" || fixed.protocolDigest !== state.protocolDigest)
1170
+ throw new TypeError("Invalid fixed episode protocol scope");
1171
+ const replay = (rawGate, rawCommit) => {
1172
+ const gate2 = validateLearningRecord("gate", rawGate);
1173
+ if (!rawCommit)
1174
+ throw new Error("Stored gate commit is missing");
1175
+ const commit = validateLearningRecord("gate-commit", rawCommit);
1176
+ if (gate2.id !== id || gate2.domain !== state.domain || gate2.fresh.episodeId !== freshEpisodeId || gate2.fresh.episodeDigest !== fresh.digest || gate2.fixed.episodeDigest !== fixed.digest || gate2.definitionDigest !== fresh.definitionDigest || gate2.expectedGeneration !== fresh.comparison.expectedGeneration || gate2.from !== fresh.comparison.from || gate2.to !== fresh.comparison.to || gate2.mode !== fresh.comparison.operation || gate2.configDigest !== digest(state.policy) || commit.id !== id || commit.domain !== state.domain || commit.gateDigest !== gate2.digest)
1177
+ throw new TypeError("Immutable gate replay binding mismatch");
1178
+ return commit;
1179
+ };
1180
+ if (previousGate) return replay(previousGate, previousCommit);
1181
+ const loadSnapshot = async (ref2) => {
1182
+ if (ref2 === null)
1183
+ return void 0;
1184
+ const row = await state.store.get("snapshot", ref2);
1185
+ if (!row)
1186
+ throw new Error("Comparison snapshot is missing");
1187
+ const snapshot2 = validateLearningRecord("snapshot", row);
1188
+ if (snapshot2.domain !== state.domain || snapshot2.digest !== ref2 || digest(snapshot2.config) !== digest(state.policy))
1189
+ throw new TypeError("Comparison snapshot binding or config mismatch");
1190
+ return snapshot2;
1191
+ };
1192
+ const fromSnapshot = await loadSnapshot(fresh.comparison.from), toSnapshot = await loadSnapshot(fresh.comparison.to);
1193
+ const observationIds = [...new Set([...fixed.cells, ...fresh.cells].map((c) => c.observationId))];
1194
+ const observations = await state.store.observations(state.domain, { observationIds });
1195
+ const gate = assessGateEvidence({
1196
+ id,
1197
+ createdAt: Date.now(),
1198
+ domain: state.domain,
1199
+ fresh,
1200
+ fixed,
1201
+ ...fromSnapshot === void 0 ? {} : { fromSnapshot },
1202
+ ...toSnapshot === void 0 ? {} : { toSnapshot },
1203
+ observations
1204
+ });
1205
+ try {
1206
+ return await state.store.commitGate(gate);
1207
+ } catch (error) {
1208
+ if (safeCode(error) !== "LEARNING_GATE_EXISTS") throw error;
1209
+ const committedGate = await state.store.get("gate", id);
1210
+ if (!committedGate) throw error;
1211
+ const committedReceipt = await state.store.get("gate-commit", id);
1212
+ return replay(committedGate, committedReceipt);
1213
+ }
1214
+ }
1215
+
1216
+ // src/routing/learning/run-context.ts
1217
+ import { randomUUID as randomUUID2 } from "node:crypto";
1218
+ import { types as types2 } from "node:util";
1219
+ function captureRun(definition, context) {
1220
+ const c = ownObject(context, [...CONTEXT_KEYS, "input", "verify", "split", "episodeId", "repetition", "attemptId", "observationId", "budget", "maintenance", "maintenanceTimeoutMs", "expectedBinding"]);
1221
+ const base2 = /* @__PURE__ */ Object.create(null);
1222
+ for (const key of CONTEXT_KEYS)
1223
+ if (Object.hasOwn(c, key))
1224
+ Object.defineProperty(base2, key, { value: c[key], enumerable: true });
1225
+ const selection = captureSelection(definition, base2);
1226
+ const expectedBinding = c.expectedBinding === void 0 ? void 0 : freeze(snapshot(c.expectedBinding));
1227
+ if (expectedBinding !== void 0) {
1228
+ binding(expectedBinding);
1229
+ if (expectedBinding.definitionDigest !== selection.definitionDigest || digest(expectedBinding.features) !== digest({ schema: selection.features.schema, dimensions: selection.features.values.length }))
1230
+ throw new TypeError("Expected learning binding does not match the request scope or features");
1231
+ }
1232
+ if (typeof c.input !== "string" || c.input !== selection.text)
1233
+ throw new TypeError("Executable input must equal task text");
1234
+ if (typeof c.verify !== "function" || types2.isProxy(c.verify))
1235
+ throw new TypeError("A trusted verifier is required");
1236
+ if (c.maintenance !== void 0 && (typeof c.maintenance !== "function" || types2.isProxy(c.maintenance)))
1237
+ throw new TypeError("Invalid maintenance hook");
1238
+ const maintenanceTimeoutMs = c.maintenanceTimeoutMs ?? 3e4;
1239
+ if (!Number.isInteger(maintenanceTimeoutMs) || maintenanceTimeoutMs < 1 || maintenanceTimeoutMs > 2147483647)
1240
+ throw new RangeError("Invalid maintenanceTimeoutMs");
1241
+ const acquire = method(c.budget, "acquire");
1242
+ const split = c.split ?? "train";
1243
+ if (!["train", "fixed", "fresh"].includes(split))
1244
+ throw new TypeError("Invalid learning split");
1245
+ if (c.episodeId !== void 0)
1246
+ identifier(c.episodeId);
1247
+ if (split === "train" && (c.episodeId !== void 0 || c.repetition !== void 0))
1248
+ throw new TypeError("Training cannot claim heldout episode metadata");
1249
+ if (split !== "train" && (c.episodeId === void 0 || c.repetition === void 0))
1250
+ throw new TypeError("Heldout runs require a prospective episode and repetition");
1251
+ if (c.repetition !== void 0 && (!Number.isSafeInteger(c.repetition) || c.repetition < 0))
1252
+ throw new TypeError("Invalid repetition");
1253
+ const attemptId = c.attemptId ?? randomUUID2(), observationId = c.observationId ?? randomUUID2();
1254
+ identifier(attemptId);
1255
+ identifier(observationId);
1256
+ return {
1257
+ selection,
1258
+ input: c.input,
1259
+ verify: c.verify,
1260
+ acquire,
1261
+ maintenanceTimeoutMs,
1262
+ split,
1263
+ attemptId,
1264
+ observationId,
1265
+ attemptIdProvided: c.attemptId !== void 0,
1266
+ observationIdProvided: c.observationId !== void 0,
1267
+ ...c.episodeId === void 0 ? {} : { episodeId: c.episodeId },
1268
+ ...c.repetition === void 0 ? {} : { repetition: c.repetition },
1269
+ ...c.maintenance === void 0 ? {} : { maintenance: c.maintenance },
1270
+ ...expectedBinding === void 0 ? {} : { expectedBinding }
1271
+ };
1272
+ }
1273
+
1274
+ // src/routing/learning/run-maintenance.ts
1275
+ function assertCallerActive(signal) {
1276
+ if (signal?.aborted) throw new AbortError({ retryable: true }, "Learning operation aborted");
1277
+ }
1278
+ async function runMaintenance(captured) {
1279
+ if (!captured.maintenance) return { status: "not-requested" };
1280
+ const scope = new OperationScope({
1281
+ timeoutMs: captured.maintenanceTimeoutMs,
1282
+ ...captured.selection.signal === void 0 ? {} : { signal: captured.selection.signal }
1283
+ });
1284
+ let failed = false;
1285
+ try {
1286
+ try {
1287
+ assertActive(scope);
1288
+ await captured.maintenance({ signal: scope.signal });
1289
+ } catch {
1290
+ failed = true;
1291
+ }
1292
+ assertCallerActive(captured.selection.signal);
1293
+ if (scope.signal.aborted || scope.remainingMs() < 1)
1294
+ return { status: "failed", code: "MAINTENANCE_TIMEOUT" };
1295
+ return failed ? { status: "failed", code: "MAINTENANCE_FAILED" } : { status: "completed" };
1296
+ } finally {
1297
+ scope.dispose();
1298
+ }
1299
+ }
1300
+
1301
+ // src/routing/learning/run-plan.ts
1302
+ async function assertEpisodeGeneration(state, episode) {
1303
+ const comparison = episode.comparison;
1304
+ if (!comparison)
1305
+ return;
1306
+ const pointer2 = scopedPointer(await state.store.pointer(state.domain));
1307
+ if (pointer2.generation !== comparison.expectedGeneration || pointer2.active !== comparison.from || comparison.operation === "rollback" && (pointer2.generation < 1 || pointer2.previous !== comparison.to))
1308
+ throw new Error("Prospective learning episode generation is stale");
1309
+ }
1310
+ async function inspectRunPlan(state, captured) {
1311
+ let attemptId = captured.attemptId, observationId = captured.observationId;
1312
+ let episode;
1313
+ if (captured.split !== "train") {
1314
+ const row = await state.store.get("episode", captured.episodeId);
1315
+ if (!row)
1316
+ throw new Error("Prospective learning episode is missing");
1317
+ episode = validateLearningRecord("episode", row);
1318
+ const c = captured.selection;
1319
+ if (episode.domain !== state.domain || episode.kind !== captured.split || episode.definitionDigest !== c.definitionDigest || episode.protocolDigest !== state.protocolDigest)
1320
+ throw new TypeError("Prospective episode scope mismatch");
1321
+ if (episode.comparison && digest(episode.comparison.config) !== digest(state.policy))
1322
+ throw new TypeError("Prospective policy configuration mismatch");
1323
+ const action2 = episode.arms.find((a) => a.id === c.evaluationArmId);
1324
+ const task = episode.tasks.find((t) => t.taskDigest === c.taskDigest);
1325
+ if (!action2 || !task || digest(task.features) !== digest(c.features))
1326
+ throw new TypeError("Task or evaluation arm outside prospective episode");
1327
+ const cell = episode.cells.find((cell2) => cell2.taskDigest === c.taskDigest && cell2.actionKey === action2.key && cell2.repetition === captured.repetition);
1328
+ if (!cell || captured.attemptIdProvided && cell.attemptId !== attemptId || captured.observationIdProvided && cell.observationId !== observationId)
1329
+ throw new TypeError("Attempt or observation ID outside reserved matrix cell");
1330
+ attemptId = cell.attemptId;
1331
+ observationId = cell.observationId;
1332
+ await assertEpisodeGeneration(state, episode);
1333
+ }
1334
+ if (await state.store.get("attempt", attemptId))
1335
+ throw new Error("Duplicate durable learning attempt ID");
1336
+ if (await state.store.get("observation", observationId))
1337
+ throw new Error("Duplicate terminal learning observation ID");
1338
+ if (await state.store.get("decision", captured.selection.id))
1339
+ throw new Error("Duplicate learning decision ID");
1340
+ return { attemptId, observationId, ...episode === void 0 ? {} : { episode } };
1341
+ }
1342
+ async function validatePreparedPlan(state, plan, preflight) {
1343
+ if (!plan.episode)
1344
+ return;
1345
+ const e = plan.episode;
1346
+ if (e.definitionDigest !== preflight.definitionDigest || e.fallbackId !== preflight.fallbackId || digest(e.arms) !== digest(preflight.actions))
1347
+ throw new TypeError("Prospective episode does not cover the full prepared action universe");
1348
+ await assertEpisodeGeneration(state, e);
1349
+ }
1350
+
1351
+ // src/routing/learning/run-evidence.ts
1352
+ import { types as types3 } from "node:util";
1353
+ import { resolve as resolve2 } from "node:path";
1354
+ function immutableTurn(turn) {
1355
+ return freeze(snapshot(turn));
1356
+ }
1357
+ function turnEvidence(turn, action2, ready, cwd) {
1358
+ const safe = ownObject(turn, ["id", "session", "status", "text", "output", "usage", "events", "warnings", "providerMetadata"]);
1359
+ if (!["completed", "refused", "failed", "interrupted"].includes(safe.status))
1360
+ throw new TypeError("Invalid turn status");
1361
+ const usage2 = safe.usage === void 0 ? void 0 : snapshot(safe.usage);
1362
+ if (usage2 !== void 0)
1363
+ usage(usage2);
1364
+ const observedModels = usage2?.perModel === void 0 ? void 0 : Object.keys(usage2.perModel);
1365
+ const mismatch = observedModels?.some((model) => model !== action2.modelId && model !== action2.model) ?? false;
1366
+ const session = snapshot(safe.session);
1367
+ const preparedCwd = ready.plan.envelope.filesystem?.readonlyRoots[0] ?? cwd;
1368
+ const sessionMismatch = session.provider !== action2.provider || session.model !== void 0 && session.model !== action2.modelId && session.model !== action2.model || session.transport !== void 0 && session.transport !== ready.plan.transport || session.cliVersion !== void 0 && session.cliVersion !== ready.plan.fingerprint.cliVersion || session.cwd !== void 0 && resolve2(session.cwd) !== resolve2(preparedCwd);
1369
+ return { status: safe.status, ...usage2 === void 0 ? {} : { usage: usage2 }, ...observedModels === void 0 ? {} : { observedModels }, mismatch: action2.evidenceScope === "model" && mismatch || sessionMismatch };
1370
+ }
1371
+ function errorUsage(error) {
1372
+ if (!error || typeof error !== "object" || types3.isProxy(error))
1373
+ return void 0;
1374
+ const descriptor = Object.getOwnPropertyDescriptor(error, "observedUsage");
1375
+ if (!descriptor || !Object.hasOwn(descriptor, "value"))
1376
+ return void 0;
1377
+ try {
1378
+ const value = snapshot(descriptor.value);
1379
+ usage(value);
1380
+ return value;
1381
+ } catch {
1382
+ return void 0;
1383
+ }
1384
+ }
1385
+ function combineFailure(previous, next) {
1386
+ return { error: previous === void 0 ? next : new AggregateError([previous.error, next], "Learning operation and evidence/cleanup both failed") };
1387
+ }
1388
+
1389
+ // src/routing/learning/snapshot.ts
1390
+ async function saveShadow(state, captured, preflight, scope) {
1391
+ const through = await state.store.highWater(state.domain);
1392
+ if (scope)
1393
+ assertActive(scope);
1394
+ const keys = preflight.actions.map((a) => a.key);
1395
+ const rows = await state.store.observations(state.domain, {
1396
+ through,
1397
+ split: "train",
1398
+ verifiedOnly: true,
1399
+ schema: captured.features.schema,
1400
+ dimensions: captured.features.values.length,
1401
+ actionKeys: keys,
1402
+ limit: state.policy.maxRows
1403
+ });
1404
+ if (scope)
1405
+ assertActive(scope);
1406
+ const relevant = rows.filter((r) => r.observation.features.schema === captured.features.schema && r.observation.features.values.length === captured.features.values.length && keys.includes(r.observation.action.key));
1407
+ const snapshot2 = buildSnapshot(state.domain, state.policy, through, relevant, Date.now(), policyBinding(captured, preflight));
1408
+ const exact2 = (value) => {
1409
+ const verified = validateLearningRecord("snapshot", value);
1410
+ if (canonical(verified) !== canonical(snapshot2))
1411
+ throw new TypeError("Shadow snapshot binding mismatch");
1412
+ return verified;
1413
+ };
1414
+ const existing = await state.store.get("snapshot", snapshot2.digest);
1415
+ if (existing) {
1416
+ const value = exact2(existing);
1417
+ if (scope)
1418
+ assertActive(scope);
1419
+ return value;
1420
+ }
1421
+ try {
1422
+ await state.store.put("snapshot", snapshot2.digest, snapshot2);
1423
+ } catch (error) {
1424
+ if (safeCode(error) !== "LEARNING_RECORD_EXISTS")
1425
+ throw error;
1426
+ const raced = await state.store.get("snapshot", snapshot2.digest);
1427
+ if (!raced)
1428
+ throw error;
1429
+ const value = exact2(raced);
1430
+ if (scope)
1431
+ assertActive(scope);
1432
+ return value;
1433
+ }
1434
+ if (scope)
1435
+ assertActive(scope);
1436
+ return snapshot2;
1437
+ }
1438
+
1439
+ // src/routing/learning/run.ts
1440
+ async function executeRun(state, captured, startedAt) {
1441
+ const c = captured.selection, scope = createScope(c, startedAt);
1442
+ let release;
1443
+ let agent, receipt, attempt;
1444
+ let turn, shadow, observation;
1445
+ let failure2, outcome = "failed";
1446
+ let quality2 = { state: "unknown", reason: "RUN_FAILED" };
1447
+ let nativeCompleted = false, admissionRefused = false;
1448
+ let preflight;
1449
+ let dispatchedAt, durationMs, identityAfter;
1450
+ let usage2, observedModels;
1451
+ const splitMetadata = { ...captured.episodeId === void 0 ? {} : { episodeId: captured.episodeId }, ...captured.repetition === void 0 ? {} : { repetition: captured.repetition } };
1452
+ const settleReservation = async () => {
1453
+ const settle = release;
1454
+ release = void 0;
1455
+ try {
1456
+ await settle?.();
1457
+ } catch (error) {
1458
+ failure2 = combineFailure(failure2, error);
1459
+ outcome = "failed";
1460
+ quality2 = { state: "unknown", reason: "RELEASE_FAILED" };
1461
+ }
1462
+ };
1463
+ try {
1464
+ assertActive(scope);
1465
+ const plan = await inspectRunPlan(state, captured);
1466
+ assertActive(scope);
1467
+ const reservation = await captured.acquire(scope.signal);
1468
+ release = method(reservation, "release");
1469
+ assertActive(scope);
1470
+ const chosen = await decide(state, c, scope);
1471
+ agent = chosen.agent;
1472
+ receipt = chosen.receipt;
1473
+ preflight = chosen.prepared.preflight;
1474
+ await validatePreparedPlan(state, plan, preflight);
1475
+ assertActive(scope);
1476
+ if (captured.expectedBinding !== void 0 && digest(captured.expectedBinding) !== digest(policyBinding(c, preflight)))
1477
+ throw new TypeError("Expected learning binding differs from the prepared action universe");
1478
+ const action2 = receipt.selected;
1479
+ attempt = sealLearningRecord("attempt", {
1480
+ format: 1,
1481
+ id: plan.attemptId,
1482
+ observationId: plan.observationId,
1483
+ domain: state.domain,
1484
+ decisionId: receipt.id,
1485
+ decisionDigest: receipt.digest,
1486
+ action: action2,
1487
+ taskDigest: c.taskDigest,
1488
+ features: c.features,
1489
+ split: captured.split,
1490
+ ...splitMetadata,
1491
+ startedAt: Date.now()
1492
+ });
1493
+ await state.store.put("attempt", attempt.id, attempt);
1494
+ try {
1495
+ assertActive(scope);
1496
+ outcome = "identity-drift";
1497
+ const before = snapshot(await agent.ready({ signal: scope.signal, timeoutMs: Math.max(1, scope.remainingMs()), awaitSettlement: true }));
1498
+ assertActive(scope);
1499
+ const expected = c.arms.find((a) => a.id === action2.id);
1500
+ if (!modelMatches(agent.model, expected.model) || !modelMatches(before.model, expected.model) || before.provider !== action2.provider || before.ready !== true || before.installation.installed !== true || before.capabilities.unsupported.length > 0 || executionDigest(before) !== action2.executionDigest) {
1501
+ outcome = "identity-drift";
1502
+ throw new Error("Learning action identity changed before execution");
1503
+ }
1504
+ if (before.plan.transport !== "exec")
1505
+ throw new Error("Learning runs require exec transport");
1506
+ outcome = "failed";
1507
+ if (plan.episode) {
1508
+ await assertEpisodeGeneration(state, plan.episode);
1509
+ assertActive(scope);
1510
+ }
1511
+ const owner = agent;
1512
+ const starter = { stream(input, options) {
1513
+ assertActive(scope);
1514
+ dispatchedAt = performance.now();
1515
+ return (async function* () {
1516
+ let invalidTerminal;
1517
+ try {
1518
+ for await (const event of owner.stream(input, options)) {
1519
+ if (event.type !== "turn.completed") {
1520
+ yield event;
1521
+ continue;
1522
+ }
1523
+ let frozen;
1524
+ try {
1525
+ frozen = immutableTurn(event.turn);
1526
+ } catch (error) {
1527
+ invalidTerminal = combineFailure(invalidTerminal, error);
1528
+ continue;
1529
+ }
1530
+ yield { type: "turn.completed", turn: frozen };
1531
+ }
1532
+ } catch (error) {
1533
+ if (invalidTerminal) throw new AggregateError([error, invalidTerminal.error], "Provider stream and terminal snapshot failed");
1534
+ throw error;
1535
+ }
1536
+ if (invalidTerminal) throw invalidTerminal.error;
1537
+ })();
1538
+ } };
1539
+ const completed = await runObservedTask(starter, captured.input, { signal: scope.signal, timeoutMs: Math.max(1, scope.remainingMs()), awaitSettlement: true });
1540
+ durationMs = Math.max(0, performance.now() - dispatchedAt);
1541
+ nativeCompleted = true;
1542
+ turn = completed;
1543
+ assertActive(scope);
1544
+ const evidence = turnEvidence(turn, action2, before, c.cwd);
1545
+ if (evidence.status === "interrupted")
1546
+ nativeCompleted = false;
1547
+ usage2 = evidence.usage;
1548
+ observedModels = evidence.observedModels;
1549
+ outcome = "identity-drift";
1550
+ const after = snapshot(await agent.ready({ signal: scope.signal, timeoutMs: Math.max(1, scope.remainingMs()), awaitSettlement: true }));
1551
+ identityAfter = executionDigest(after);
1552
+ assertActive(scope);
1553
+ if (!modelMatches(agent.model, expected.model) || !modelMatches(after.model, expected.model) || after.provider !== action2.provider || after.ready !== true || after.installation.installed !== true || after.capabilities.unsupported.length > 0 || identityAfter !== action2.executionDigest || evidence.mismatch) {
1554
+ outcome = "identity-drift";
1555
+ throw new Error("Learning action identity changed after execution");
1556
+ }
1557
+ if (evidence.status !== "completed") {
1558
+ outcome = evidence.status === "refused" ? "refused" : evidence.status === "interrupted" ? "aborted" : "failed";
1559
+ throw new Error(`Learning turn ${outcome}`);
1560
+ }
1561
+ outcome = "verifier-error";
1562
+ const verified = ownObject(snapshot(await captured.verify(turn)), ["value", "passed"]);
1563
+ assertActive(scope);
1564
+ if (typeof verified.value !== "number" || !Number.isFinite(verified.value) || verified.value < 0 || verified.value > 1 || typeof verified.passed !== "boolean")
1565
+ throw new TypeError("Invalid verifier result");
1566
+ quality2 = { state: "verified", value: verified.value, passed: verified.passed };
1567
+ outcome = "completed";
1568
+ } catch (error) {
1569
+ failure2 = { error };
1570
+ admissionRefused = safeCode(error) === "ADMISSION_REFUSED";
1571
+ usage2 ??= errorUsage(error);
1572
+ if (!nativeCompleted && safeCode(error) === "TIMEOUT")
1573
+ outcome = "timeout";
1574
+ else if (!nativeCompleted && ["ABORTED", "CANCELLED"].includes(safeCode(error) ?? ""))
1575
+ outcome = "aborted";
1576
+ if (scope.signal.aborted || scope.remainingMs() < 1)
1577
+ outcome = safeCode(scope.signal.reason) === "TIMEOUT" || scope.remainingMs() < 1 ? "timeout" : "aborted";
1578
+ quality2 = { state: "unknown", reason: outcome.toUpperCase().replaceAll("-", "_") };
1579
+ if (dispatchedAt !== void 0 && durationMs === void 0)
1580
+ durationMs = Math.max(0, performance.now() - dispatchedAt);
1581
+ } finally {
1582
+ try {
1583
+ await agent.close();
1584
+ } catch (error) {
1585
+ failure2 = combineFailure(failure2, error);
1586
+ quality2 = { state: "unknown", reason: "CLEANUP_FAILED" };
1587
+ if (outcome === "completed")
1588
+ outcome = "failed";
1589
+ }
1590
+ }
1591
+ if (scope.signal.aborted || scope.remainingMs() < 1) {
1592
+ failure2 ??= { error: scope.signal.reason ?? new Error("Learning operation deadline exceeded") };
1593
+ outcome = safeCode(scope.signal.reason) === "TIMEOUT" || scope.remainingMs() < 1 ? "timeout" : "aborted";
1594
+ quality2 = { state: "unknown", reason: outcome.toUpperCase() };
1595
+ }
1596
+ await scope.drain();
1597
+ await settleReservation();
1598
+ const infrastructureHalted = failure2 !== void 0 && isExecutionHalted(failure2.error);
1599
+ if (infrastructureHalted) {
1600
+ outcome = "failed";
1601
+ quality2 = { state: "unknown", reason: "EXECUTION_HALTED" };
1602
+ }
1603
+ if (!infrastructureHalted && admissionRefused) {
1604
+ outcome = "failed";
1605
+ quality2 = { state: "unknown", reason: "ADMISSION_REFUSED" };
1606
+ }
1607
+ observation = sealLearningRecord("observation", {
1608
+ format: 1,
1609
+ id: plan.observationId,
1610
+ domain: state.domain,
1611
+ attemptId: attempt.id,
1612
+ decisionId: receipt.id,
1613
+ decisionDigest: receipt.digest,
1614
+ action: action2,
1615
+ taskDigest: c.taskDigest,
1616
+ features: c.features,
1617
+ split: captured.split,
1618
+ ...splitMetadata,
1619
+ outcome,
1620
+ quality: quality2,
1621
+ latency: infrastructureHalted || admissionRefused || dispatchedAt === void 0 ? { state: "unknown" } : { state: !nativeCompleted && (outcome === "timeout" || outcome === "aborted") ? "right-censored" : "observed", durationMs: durationMs ?? Math.max(0, performance.now() - dispatchedAt) },
1622
+ ...usage2 === void 0 ? {} : { usage: usage2 },
1623
+ ...observedModels === void 0 ? {} : { observedModels },
1624
+ ...identityAfter === void 0 ? {} : { identityAfter },
1625
+ createdAt: Date.now()
1626
+ });
1627
+ try {
1628
+ await state.store.appendObservation(observation);
1629
+ } catch (error) {
1630
+ failure2 = combineFailure(failure2, error);
1631
+ }
1632
+ if (failure2 === void 0) {
1633
+ try {
1634
+ shadow = await saveShadow(state, c, preflight, scope);
1635
+ } catch (error) {
1636
+ failure2 = { error };
1637
+ }
1638
+ }
1639
+ } catch (error) {
1640
+ failure2 = combineFailure(failure2, error);
1641
+ } finally {
1642
+ await scope.drain();
1643
+ await settleReservation();
1644
+ }
1645
+ let maintenance = { status: "not-requested" };
1646
+ try {
1647
+ if (failure2 !== void 0)
1648
+ throw failure2.error;
1649
+ assertActive(scope);
1650
+ if (captured.maintenance && c.evaluationArmId === void 0 && captured.split === "train") {
1651
+ scope.dispose();
1652
+ maintenance = await runMaintenance(captured);
1653
+ assertCallerActive(c.signal);
1654
+ } else {
1655
+ assertActive(scope);
1656
+ }
1657
+ return { turn, receipt, observation, shadow, maintenance };
1658
+ } finally {
1659
+ scope.dispose();
1660
+ }
1661
+ }
1662
+
1663
+ // src/routing/learning/router.ts
1664
+ var LearningRouter = class {
1665
+ #state;
1666
+ constructor(options) {
1667
+ this.#state = captureRouter(options);
1668
+ }
1669
+ async preflight(definition, context) {
1670
+ const started = performance.now(), captured = captureSelection(definition, context), scope = createScope(captured, started);
1671
+ try {
1672
+ const prepared = await prepareSelection(captured, this.#state.domain, scope);
1673
+ await scope.drain();
1674
+ assertActive(scope);
1675
+ scope.dispose();
1676
+ return prepared.preflight;
1677
+ } catch (error) {
1678
+ await scope.drain();
1679
+ scope.dispose();
1680
+ throw error;
1681
+ }
1682
+ }
1683
+ async createAgent(definition, context) {
1684
+ const started = performance.now(), captured = captureSelection(definition, context), scope = createScope(captured, started);
1685
+ try {
1686
+ const { agent, receipt } = await decide(this.#state, captured, scope);
1687
+ await scope.drain();
1688
+ assertActive(scope);
1689
+ scope.dispose();
1690
+ return { agent, receipt };
1691
+ } catch (error) {
1692
+ await scope.drain();
1693
+ scope.dispose();
1694
+ throw error;
1695
+ }
1696
+ }
1697
+ async run(definition, context) {
1698
+ const started = performance.now(), captured = captureRun(definition, context);
1699
+ return executeRun(this.#state, captured, started);
1700
+ }
1701
+ async shadow(definition, context) {
1702
+ const started = performance.now(), captured = captureSelection(definition, context), scope = createScope(captured, started);
1703
+ try {
1704
+ const prepared = await prepareSelection(captured, this.#state.domain, scope);
1705
+ const value = await saveShadow(this.#state, captured, prepared.preflight, scope);
1706
+ await scope.drain();
1707
+ assertActive(scope);
1708
+ scope.dispose();
1709
+ return value;
1710
+ } catch (error) {
1711
+ await scope.drain();
1712
+ scope.dispose();
1713
+ throw error;
1714
+ }
1715
+ }
1716
+ async improve(options) {
1717
+ return improvePolicy(this.#state, options);
1718
+ }
1719
+ async inspect() {
1720
+ return scopedPointer(await this.#state.store.pointer(this.#state.domain));
1721
+ }
1722
+ };
1723
+
1724
+ // src/routing/learning/store-sqlite.ts
1725
+ import { randomUUID as randomUUID3 } from "node:crypto";
1726
+ import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, fstatSync as fstatSync2, linkSync, lstatSync as lstatSync2, mkdirSync, openSync as openSync2, readSync as readSync2 } from "node:fs";
1727
+ import { dirname as dirname2, isAbsolute, normalize as normalize2 } from "node:path";
1728
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
1729
+
1730
+ // src/routing/learning/store-publication.ts
1731
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readSync, readdirSync, unlinkSync } from "node:fs";
1732
+ import { basename, dirname, join } from "node:path";
1733
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
1734
+
1735
+ // src/routing/learning/store-schema.ts
1736
+ import { DatabaseSync } from "node:sqlite";
1737
+ var LEARNING_APPLICATION_ID = 1329680972;
1738
+ var V1_SCHEMA = `
1739
+ CREATE TABLE records(kind TEXT NOT NULL,id TEXT NOT NULL,domain TEXT NOT NULL,digest TEXT NOT NULL,json TEXT NOT NULL,PRIMARY KEY(kind,id)) STRICT;
1740
+ CREATE INDEX records_domain ON records(domain,kind);
1741
+ CREATE TABLE observations(sequence INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,domain TEXT NOT NULL,attempt_id TEXT NOT NULL UNIQUE,task_digest TEXT NOT NULL,split TEXT NOT NULL,digest TEXT NOT NULL,json TEXT NOT NULL) STRICT;
1742
+ CREATE INDEX observations_domain ON observations(domain,sequence);
1743
+ CREATE TABLE task_claims(domain TEXT NOT NULL,task_digest TEXT NOT NULL,split TEXT NOT NULL,episode_id TEXT,PRIMARY KEY(domain,task_digest)) STRICT;
1744
+ CREATE TABLE pointers(domain TEXT PRIMARY KEY,generation INTEGER NOT NULL,active TEXT,previous TEXT) STRICT;
1745
+ CREATE TABLE consumed(domain TEXT NOT NULL,episode_id TEXT NOT NULL,gate_id TEXT NOT NULL,PRIMARY KEY(domain,episode_id)) STRICT;
1746
+ PRAGMA application_id=${LEARNING_APPLICATION_ID}; PRAGMA user_version=1;`;
1747
+ var V2_ADDITIONS = `
1748
+ CREATE TABLE cell_ids(kind TEXT NOT NULL CHECK(kind IN ('attempt','observation')),id TEXT NOT NULL,domain TEXT NOT NULL,episode_id TEXT NOT NULL,PRIMARY KEY(kind,id)) STRICT;
1749
+ CREATE INDEX observations_ids_domain ON observations(id,domain,sequence);
1750
+ CREATE INDEX observations_quality ON observations(domain,split,json_extract(json,'$.quality.state'),sequence DESC);
1751
+ CREATE INDEX observations_features ON observations(domain,split,json_extract(json,'$.quality.state'),json_extract(json,'$.features.schema'),json_array_length(json_extract(json,'$.features.values')),sequence DESC);
1752
+ CREATE INDEX observations_actions ON observations(domain,split,json_extract(json,'$.quality.state'),json_extract(json,'$.features.schema'),json_array_length(json_extract(json,'$.features.values')),json_extract(json,'$.action.key'),sequence DESC);
1753
+ CREATE INDEX observations_schema ON observations(domain,json_extract(json,'$.features.schema'),json_array_length(json_extract(json,'$.features.values')),sequence DESC);
1754
+ CREATE INDEX committed_generations ON records(domain,json_extract(json,'$.after.generation')) WHERE kind='gate-commit' AND json_extract(json,'$.status') IN ('promoted','rolled-back');
1755
+ PRAGMA user_version=2;`;
1756
+ var LEARNING_SCHEMA = V1_SCHEMA + V2_ADDITIONS;
1757
+ function learningCatalog(db) {
1758
+ return canonical(db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY name").all());
1759
+ }
1760
+ function catalogFor(sql) {
1761
+ const db = new DatabaseSync(":memory:");
1762
+ try {
1763
+ db.exec(sql);
1764
+ return learningCatalog(db);
1765
+ } finally {
1766
+ db.close();
1767
+ }
1768
+ }
1769
+ var LEARNING_CATALOG = catalogFor(LEARNING_SCHEMA);
1770
+ var LEARNING_V1_CATALOG = catalogFor(V1_SCHEMA);
1771
+ function migrateLearningDatabase(db) {
1772
+ db.exec("BEGIN IMMEDIATE");
1773
+ try {
1774
+ const version = db.prepare("PRAGMA user_version").get()?.user_version;
1775
+ const schema = learningCatalog(db);
1776
+ if (version === 2) {
1777
+ if (schema !== LEARNING_CATALOG)
1778
+ throw new Error("Learning database integrity/version/schema failure");
1779
+ } else if (version === 1) {
1780
+ if (schema !== LEARNING_V1_CATALOG)
1781
+ throw new Error("Learning database integrity/version/schema failure");
1782
+ db.exec(V2_ADDITIONS);
1783
+ for (const row of db.prepare("SELECT id,domain,digest,json FROM records WHERE kind='episode'").all()) {
1784
+ const e = validateLearningRecord("episode", JSON.parse(String(row.json)));
1785
+ if (e.id !== row.id || e.domain !== row.domain || e.digest !== row.digest)
1786
+ throw new Error("Invalid historic episode identity");
1787
+ for (const cell of e.cells)
1788
+ for (const kind of ["attempt", "observation"]) {
1789
+ const id = kind === "attempt" ? cell.attemptId : cell.observationId;
1790
+ const existing = kind === "attempt" ? db.prepare("SELECT json FROM records WHERE kind='attempt' AND id=?").get(id) : db.prepare("SELECT json FROM observations WHERE id=?").get(id);
1791
+ if (existing) {
1792
+ const record = validateLearningRecord(kind, JSON.parse(String(existing.json)));
1793
+ if (record.domain !== e.domain || record.episodeId !== e.id || record.taskDigest !== cell.taskDigest || record.action.key !== cell.actionKey || record.repetition !== cell.repetition)
1794
+ throw new Error("Conflicting historic cell reservation");
1795
+ }
1796
+ db.prepare("INSERT INTO cell_ids(kind,id,domain,episode_id) VALUES (?,?,?,?)").run(kind, id, e.domain, e.id);
1797
+ }
1798
+ }
1799
+ for (const row of db.prepare("SELECT json FROM records WHERE kind='attempt'").all()) {
1800
+ const a = validateLearningRecord("attempt", JSON.parse(String(row.json)));
1801
+ if (a.split === "train") {
1802
+ const terminal = db.prepare("SELECT id FROM observations WHERE attempt_id=?").get(a.id);
1803
+ if (terminal && terminal.id !== a.observationId)
1804
+ throw new Error("Conflicting historic planned terminal ID");
1805
+ db.prepare("INSERT INTO cell_ids(kind,id,domain,episode_id) VALUES ('observation',?,?,?)").run(a.observationId, a.domain, "");
1806
+ }
1807
+ }
1808
+ } else
1809
+ throw new Error("Learning database integrity/version/schema failure");
1810
+ db.exec("COMMIT");
1811
+ } catch (error) {
1812
+ db.exec("ROLLBACK");
1813
+ throw error;
1814
+ }
1815
+ }
1816
+
1817
+ // src/routing/learning/store-publication.ts
1818
+ function exists(path) {
1819
+ try {
1820
+ lstatSync(path);
1821
+ return true;
1822
+ } catch (error) {
1823
+ if (error.code === "ENOENT")
1824
+ return false;
1825
+ throw error;
1826
+ }
1827
+ }
1828
+ function recoverPublishedDatabase(path) {
1829
+ const current = lstatSync(path);
1830
+ if (!current.isFile() || current.isSymbolicLink() || current.nlink !== 2 || current.uid !== process.getuid?.() || (current.mode & 511) !== 384)
1831
+ return false;
1832
+ const parent = dirname(path), prefix = basename(path) + ".";
1833
+ const candidates = readdirSync(parent).filter((name) => name.startsWith(prefix) && /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}\.initializing$/.test(name.slice(prefix.length)));
1834
+ for (const name of candidates) {
1835
+ const temporary = join(parent, name);
1836
+ let staging;
1837
+ try {
1838
+ staging = lstatSync(temporary);
1839
+ } catch (error) {
1840
+ if (error.code === "ENOENT")
1841
+ continue;
1842
+ throw error;
1843
+ }
1844
+ if (!staging.isFile() || staging.isSymbolicLink() || staging.nlink !== 2 || staging.uid !== current.uid || (staging.mode & 511) !== 384 || staging.dev !== current.dev || staging.ino !== current.ino)
1845
+ continue;
1846
+ if ([path, temporary].some((file) => ["-wal", "-shm", "-journal"].some((suffix) => exists(file + suffix))))
1847
+ return false;
1848
+ let fd;
1849
+ try {
1850
+ fd = openSync(temporary, constants.O_RDONLY | constants.O_NOFOLLOW);
1851
+ } catch (error) {
1852
+ if (error.code === "ENOENT")
1853
+ return false;
1854
+ throw error;
1855
+ }
1856
+ let valid = false;
1857
+ try {
1858
+ const stat = fstatSync(fd), header = Buffer.alloc(100);
1859
+ valid = stat.dev === current.dev && stat.ino === current.ino && stat.nlink === 2 && readSync(fd, header, 0, 100, 0) === 100 && header.subarray(0, 16).toString() === "SQLite format 3\0" && header[18] === 1 && header[19] === 1 && header.readUInt32BE(68) === LEARNING_APPLICATION_ID && [1, 2].includes(header.readUInt32BE(60));
1860
+ } finally {
1861
+ closeSync(fd);
1862
+ }
1863
+ if (!valid)
1864
+ return false;
1865
+ let candidate;
1866
+ try {
1867
+ candidate = new DatabaseSync2(temporary, { readOnly: true });
1868
+ const version = candidate.prepare("PRAGMA user_version").get()?.user_version;
1869
+ const catalog = learningCatalog(candidate);
1870
+ if (candidate.prepare("PRAGMA application_id").get()?.application_id !== LEARNING_APPLICATION_ID || (version === 1 ? catalog !== LEARNING_V1_CATALOG : version === 2 ? catalog !== LEARNING_CATALOG : true) || candidate.prepare("PRAGMA quick_check(1)").get()?.quick_check !== "ok" || candidate.prepare("PRAGMA foreign_key_check").get() !== void 0)
1871
+ return false;
1872
+ } catch (error) {
1873
+ if (!exists(temporary))
1874
+ return false;
1875
+ throw error;
1876
+ } finally {
1877
+ candidate?.close();
1878
+ }
1879
+ let final;
1880
+ try {
1881
+ final = lstatSync(temporary);
1882
+ } catch (error) {
1883
+ if (error.code === "ENOENT")
1884
+ return false;
1885
+ throw error;
1886
+ }
1887
+ if (final.dev !== current.dev || final.ino !== current.ino || !final.isFile() || final.isSymbolicLink())
1888
+ return false;
1889
+ try {
1890
+ unlinkSync(temporary);
1891
+ } catch (error) {
1892
+ if (error.code !== "ENOENT")
1893
+ throw error;
1894
+ }
1895
+ const dir = openSync(parent, "r");
1896
+ try {
1897
+ fsyncSync(dir);
1898
+ } finally {
1899
+ closeSync(dir);
1900
+ }
1901
+ return true;
1902
+ }
1903
+ return false;
1904
+ }
1905
+ function unlinkPublicationTemp(path) {
1906
+ try {
1907
+ unlinkSync(path);
1908
+ } catch (error) {
1909
+ if (error.code !== "ENOENT")
1910
+ throw error;
1911
+ }
1912
+ }
1913
+
1914
+ // src/routing/learning/store-sqlite.ts
1915
+ function statFile(path) {
1916
+ const s = lstatSync2(path);
1917
+ if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1 || (s.mode & 511) !== 384 || s.uid !== process.getuid?.())
1918
+ throw new Error("Learning database must be a private regular owned file");
1919
+ return s;
1920
+ }
1921
+ function exists2(path) {
1922
+ try {
1923
+ lstatSync2(path);
1924
+ return true;
1925
+ } catch (e) {
1926
+ if (e.code === "ENOENT")
1927
+ return false;
1928
+ throw e;
1929
+ }
1930
+ }
1931
+ function directory(path, create = false) {
1932
+ if (!isAbsolute(path) || normalize2(path) !== path)
1933
+ throw new TypeError("Learning database requires normalized absolute path");
1934
+ const parent = dirname2(path), missing = [];
1935
+ for (let current = parent; ; current = dirname2(current)) {
1936
+ if (!exists2(current)) {
1937
+ if (!create)
1938
+ throw new Error("Learning directory removed");
1939
+ missing.push(current);
1940
+ } else {
1941
+ const s2 = lstatSync2(current);
1942
+ if (!s2.isDirectory()) {
1943
+ const container = lstatSync2(dirname2(current));
1944
+ if (!(s2.isSymbolicLink() && s2.uid === 0 && current !== parent && container.uid === 0 && (container.mode & 18) === 0))
1945
+ throw new Error("Unsafe learning directory");
1946
+ }
1947
+ }
1948
+ if (current === dirname2(current))
1949
+ break;
1950
+ }
1951
+ for (const current of missing.reverse()) {
1952
+ try {
1953
+ mkdirSync(current, { mode: 448 });
1954
+ } catch (e) {
1955
+ if (e.code !== "EEXIST")
1956
+ throw e;
1957
+ }
1958
+ const s2 = lstatSync2(current);
1959
+ if (!s2.isDirectory() || s2.isSymbolicLink() || s2.uid !== process.getuid?.() || (s2.mode & 511) !== 448)
1960
+ throw new Error("Unsafe new learning directory");
1961
+ }
1962
+ const s = lstatSync2(parent);
1963
+ if ((s.mode & 511) !== 448 || s.uid !== process.getuid?.())
1964
+ throw new Error("Learning directory must be private (0700) and owned");
1965
+ }
1966
+ function publish(path) {
1967
+ const temp = `${path}.${randomUUID3()}.initializing`;
1968
+ closeSync2(openSync2(temp, "wx", 384));
1969
+ let db;
1970
+ try {
1971
+ db = new DatabaseSync3(temp);
1972
+ db.exec(`PRAGMA synchronous=FULL; BEGIN IMMEDIATE;${LEARNING_SCHEMA} COMMIT;`);
1973
+ db.close();
1974
+ db = void 0;
1975
+ const fd = openSync2(temp, "r");
1976
+ try {
1977
+ fsyncSync2(fd);
1978
+ } finally {
1979
+ closeSync2(fd);
1980
+ }
1981
+ try {
1982
+ linkSync(temp, path);
1983
+ } catch (e) {
1984
+ if (e.code !== "EEXIST")
1985
+ throw e;
1986
+ }
1987
+ unlinkPublicationTemp(temp);
1988
+ const dir = openSync2(dirname2(path), "r");
1989
+ try {
1990
+ fsyncSync2(dir);
1991
+ } finally {
1992
+ closeSync2(dir);
1993
+ }
1994
+ } finally {
1995
+ db?.close();
1996
+ unlinkPublicationTemp(temp);
1997
+ }
1998
+ }
1999
+ function retryBusy(work, timeout) {
2000
+ const until = Date.now() + timeout;
2001
+ for (; ; ) {
2002
+ try {
2003
+ return work();
2004
+ } catch (error) {
2005
+ const code = error && typeof error === "object" && "errcode" in error ? error.errcode : void 0;
2006
+ if (typeof code !== "number" || ![5, 6].includes(code & 255) || Date.now() >= until)
2007
+ throw error;
2008
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2);
2009
+ }
2010
+ }
2011
+ }
2012
+ var LearningDatabase = class {
2013
+ db;
2014
+ path;
2015
+ identity;
2016
+ constructor(path, timeout) {
2017
+ if (!Number.isSafeInteger(timeout) || timeout < 0 || timeout > 6e4)
2018
+ throw new TypeError("Invalid busy timeout");
2019
+ this.path = path;
2020
+ directory(path, true);
2021
+ if (!exists2(path))
2022
+ publish(path);
2023
+ let before;
2024
+ for (; ; ) {
2025
+ try {
2026
+ before = statFile(path);
2027
+ break;
2028
+ } catch (error) {
2029
+ if (recoverPublishedDatabase(path))
2030
+ continue;
2031
+ before = statFile(path);
2032
+ break;
2033
+ }
2034
+ }
2035
+ this.identity = { dev: before.dev, ino: before.ino };
2036
+ for (const ext of ["-wal", "-shm", "-journal"])
2037
+ if (exists2(path + ext))
2038
+ statFile(path + ext);
2039
+ const fd = openSync2(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
2040
+ try {
2041
+ const s = fstatSync2(fd), header = Buffer.alloc(100);
2042
+ if (s.dev !== before.dev || s.ino !== before.ino || readSync2(fd, header, 0, 100, 0) !== 100 || header.subarray(0, 16).toString() !== "SQLite format 3\0" || header.readUInt32BE(68) !== LEARNING_APPLICATION_ID || ![1, 2].includes(header.readUInt32BE(60)))
2043
+ throw new Error("Unrecognized learning database");
2044
+ } finally {
2045
+ closeSync2(fd);
2046
+ }
2047
+ this.db = new DatabaseSync3(path);
2048
+ try {
2049
+ this.db.exec(`PRAGMA busy_timeout=${timeout}`);
2050
+ retryBusy(() => {
2051
+ migrateLearningDatabase(this.db);
2052
+ this.verify(true);
2053
+ this.db.exec("PRAGMA foreign_keys=ON;PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL;");
2054
+ this.verify();
2055
+ }, timeout);
2056
+ } catch (e) {
2057
+ this.db.close();
2058
+ throw e;
2059
+ }
2060
+ }
2061
+ verify(full = false) {
2062
+ directory(this.path);
2063
+ const s = statFile(this.path);
2064
+ if (s.dev !== this.identity.dev || s.ino !== this.identity.ino)
2065
+ throw new Error("Learning database replaced");
2066
+ for (const ext of ["-wal", "-shm", "-journal"])
2067
+ if (exists2(this.path + ext))
2068
+ statFile(this.path + ext);
2069
+ if (this.db.prepare("PRAGMA application_id").get()?.application_id !== LEARNING_APPLICATION_ID || this.db.prepare("PRAGMA user_version").get()?.user_version !== 2 || learningCatalog(this.db) !== LEARNING_CATALOG || full && (this.db.prepare("PRAGMA quick_check(1)").get()?.quick_check !== "ok" || this.db.prepare("PRAGMA foreign_key_check").get()))
2070
+ throw new Error("Learning database integrity/version/schema failure");
2071
+ }
2072
+ transaction(fn) {
2073
+ this.verify();
2074
+ this.db.exec("BEGIN IMMEDIATE");
2075
+ try {
2076
+ const result = fn(this.db);
2077
+ this.verify();
2078
+ this.db.exec("COMMIT");
2079
+ return result;
2080
+ } catch (e) {
2081
+ try {
2082
+ this.db.exec("ROLLBACK");
2083
+ } catch {
2084
+ }
2085
+ throw e;
2086
+ }
2087
+ }
2088
+ close() {
2089
+ this.db.close();
2090
+ }
2091
+ };
2092
+
2093
+ // src/routing/learning/store-history.ts
2094
+ var LearningHistory = class {
2095
+ #version = -1;
2096
+ #cache = /* @__PURE__ */ new Map();
2097
+ invalidate() {
2098
+ this.#cache.clear();
2099
+ }
2100
+ pointer(db, domain, read) {
2101
+ const version = Number(db.prepare("PRAGMA data_version").get().data_version);
2102
+ if (version !== this.#version) {
2103
+ this.#cache.clear();
2104
+ this.#version = version;
2105
+ }
2106
+ const row = db.prepare("SELECT generation,active,previous FROM pointers WHERE domain=?").get(domain);
2107
+ const value = row ? { generation: Number(row.generation), active: row.active === null ? null : String(row.active), previous: row.previous === null ? null : String(row.previous) } : { generation: 0, active: null, previous: null };
2108
+ pointer(value);
2109
+ const cached = this.#cache.get(domain);
2110
+ if (cached) {
2111
+ if (digest(cached) !== digest(value))
2112
+ throw new Error("Pointer generation changed without committed history");
2113
+ return cached;
2114
+ }
2115
+ let derived = { generation: 0, active: null, previous: null }, lastAt = 0;
2116
+ const commits = db.prepare("SELECT id FROM records WHERE domain=? AND kind='gate-commit' AND json_extract(json,'$.status') IN ('promoted','rolled-back') ORDER BY json_extract(json,'$.after.generation')").all(domain);
2117
+ for (const row2 of commits) {
2118
+ const c = read("gate-commit", String(row2.id)), gate = c ? read("gate", c.id) : void 0;
2119
+ if (!c || !gate || c.domain !== domain || gate.domain !== domain || c.gateDigest !== gate.digest || digest(c.before) !== digest(derived) || gate.expectedGeneration !== derived.generation || gate.from !== derived.active || gate.outcome === "keep" || gate.outcome !== gate.mode || c.status !== (gate.mode === "promote" ? "promoted" : "rolled-back") || c.createdAt < gate.createdAt || c.createdAt < lastAt || gate.mode === "rollback" && (derived.generation === 0 || gate.to !== derived.previous) || gate.mode === "promote" && gate.to === null)
2120
+ throw new Error("Invalid committed pointer generation history");
2121
+ const next = { generation: derived.generation + 1, active: gate.to, previous: derived.active };
2122
+ if (digest(c.after) !== digest(next))
2123
+ throw new Error("Invalid committed pointer transition");
2124
+ const consumed = db.prepare("SELECT gate_id FROM consumed WHERE domain=? AND episode_id=?").get(domain, gate.fresh.episodeId);
2125
+ if (consumed?.gate_id !== gate.id)
2126
+ throw new Error("Pointer gate has no consumed fresh evidence");
2127
+ for (const id of [next.active, next.previous])
2128
+ if (id !== null && read("snapshot", id)?.domain !== domain)
2129
+ throw new Error("Pointer references missing domain snapshot");
2130
+ derived = next;
2131
+ lastAt = c.createdAt;
2132
+ }
2133
+ if (digest(value) !== digest(derived) || row && derived.generation === 0)
2134
+ throw new Error("Pointer has no matching committed generation history");
2135
+ const result = freeze(derived);
2136
+ this.#cache.set(domain, result);
2137
+ return result;
2138
+ }
2139
+ };
2140
+
2141
+ // src/routing/learning/store.ts
2142
+ var LearningRecordExistsError = class extends Error {
2143
+ code = "LEARNING_RECORD_EXISTS";
2144
+ constructor() {
2145
+ super("Immutable learning record already exists");
2146
+ this.name = "LearningRecordExistsError";
2147
+ }
2148
+ };
2149
+ function failure(message) {
2150
+ throw new Error(message);
2151
+ }
2152
+ var SqliteLearningStore = class {
2153
+ #database;
2154
+ #history = new LearningHistory();
2155
+ #cache = /* @__PURE__ */ new Map();
2156
+ #revision = -1;
2157
+ #verifiedSnapshots = /* @__PURE__ */ new Set();
2158
+ constructor(path, options = {}) {
2159
+ this.#database = new LearningDatabase(path, options.busyTimeoutMs ?? 5e3);
2160
+ }
2161
+ #read(db, kind, id) {
2162
+ const revision = Number(db.prepare("PRAGMA data_version").get().data_version);
2163
+ if (revision !== this.#revision) {
2164
+ this.#cache.clear();
2165
+ this.#verifiedSnapshots.clear();
2166
+ this.#revision = revision;
2167
+ }
2168
+ const cacheKey = `${kind}:${id}`, cached = this.#cache.get(cacheKey);
2169
+ if (cached)
2170
+ return cached;
2171
+ const row = kind === "observation" ? db.prepare("SELECT * FROM observations WHERE id=?").get(id) : db.prepare("SELECT * FROM records WHERE kind=? AND id=?").get(kind, id);
2172
+ if (!row)
2173
+ return void 0;
2174
+ const value = validateLearningRecord(kind, JSON.parse(String(row.json)));
2175
+ if (value.digest !== row.digest || value.domain !== row.domain || ("id" in value ? value.id : value.digest) !== id)
2176
+ failure("Stored learning identity mismatch");
2177
+ if (kind === "observation") {
2178
+ const o = value;
2179
+ if (o.attemptId !== row.attempt_id || o.taskDigest !== row.task_digest || o.split !== row.split)
2180
+ failure("Stored observation column mismatch");
2181
+ }
2182
+ this.#cache.set(cacheKey, value);
2183
+ if (this.#cache.size > 64)
2184
+ this.#cache.delete(this.#cache.keys().next().value);
2185
+ return value;
2186
+ }
2187
+ #insert(db, kind, id, row) {
2188
+ db.prepare("INSERT INTO records(kind,id,domain,digest,json) VALUES (?,?,?,?,?)").run(kind, id, row.domain, row.digest, JSON.stringify(row));
2189
+ }
2190
+ #water(db, domain) {
2191
+ return Number(db.prepare("SELECT COALESCE(MAX(sequence),0) AS n FROM observations WHERE domain=?").get(domain).n);
2192
+ }
2193
+ #pointer(db, domain) {
2194
+ return this.#history.pointer(db, domain, (kind, id) => {
2195
+ const v = this.#read(db, kind, id);
2196
+ if (kind === "snapshot" && v)
2197
+ this.#snapshot(db, v);
2198
+ return v;
2199
+ });
2200
+ }
2201
+ #snapshot(db, s, force = false) {
2202
+ if (!force && this.#verifiedSnapshots.has(s.digest))
2203
+ return;
2204
+ if (s.through > this.#water(db, s.domain))
2205
+ failure("Snapshot cutoff exceeds domain evidence");
2206
+ for (const r of s.rows) {
2207
+ const row = db.prepare("SELECT id,digest,domain FROM observations WHERE sequence=? AND domain=?").get(r.sequence, s.domain);
2208
+ if (!row || row.id !== r.observation.id || row.digest !== r.observation.digest || this.#read(db, "observation", String(row.id))?.digest !== r.observation.digest)
2209
+ failure("Snapshot row is not actual persisted evidence");
2210
+ }
2211
+ this.#verifiedSnapshots.add(s.digest);
2212
+ if (this.#verifiedSnapshots.size > 64)
2213
+ this.#verifiedSnapshots.delete(this.#verifiedSnapshots.values().next().value);
2214
+ }
2215
+ #claim(db, domain, task, split, episode) {
2216
+ const row = db.prepare("SELECT split,episode_id FROM task_claims WHERE domain=? AND task_digest=?").get(domain, task);
2217
+ if (row) {
2218
+ if (row.split !== split || split === "fresh" && row.episode_id !== episode)
2219
+ failure("Task split is already protected");
2220
+ return;
2221
+ }
2222
+ db.prepare("INSERT INTO task_claims(domain,task_digest,split,episode_id) VALUES (?,?,?,?)").run(domain, task, split, episode ?? null);
2223
+ }
2224
+ #episode(db, e) {
2225
+ if (this.#water(db, e.domain) !== e.afterSequence)
2226
+ failure("Episode must reserve the current domain cutoff");
2227
+ if (e.kind === "fresh") {
2228
+ const c = e.comparison, current = this.#pointer(db, e.domain), fixed = this.#read(db, "episode", c.fixedEpisodeId);
2229
+ if (c.expectedGeneration !== current.generation || c.from !== current.active || c.operation === "rollback" && (current.generation < 1 || c.to !== current.previous))
2230
+ failure("Fresh comparison must match the current pointer generation");
2231
+ if (!fixed || fixed.kind !== "fixed" || fixed.domain !== e.domain || e.createdAt < fixed.createdAt)
2232
+ failure("Missing fixed suite");
2233
+ if (e.definitionDigest !== fixed.definitionDigest || e.protocolDigest !== fixed.protocolDigest || digest(e.arms) !== digest(fixed.arms) || e.fallbackId !== fixed.fallbackId || e.repetitions !== fixed.repetitions)
2234
+ failure("Incomparable fixed suite");
2235
+ if (c.operation === "promote" && c.to === null)
2236
+ failure("Promotion requires a snapshot");
2237
+ for (const ref2 of [c.from, c.to])
2238
+ if (ref2 !== null) {
2239
+ const s = this.#read(db, "snapshot", ref2);
2240
+ if (!s || s.domain !== e.domain || s.through > e.afterSequence || s.createdAt > e.createdAt || digest(s.config) !== c.configDigest)
2241
+ failure("Missing/incomparable policy snapshot");
2242
+ const b = s.binding;
2243
+ if (!b || b.definitionDigest !== e.definitionDigest || digest(b.actions) !== digest(e.arms) || b.fallbackId !== e.fallbackId || b.features.schema !== e.tasks[0].features.schema || b.features.dimensions !== e.tasks[0].features.values.length)
2244
+ failure("Policy binding does not match prospective episode");
2245
+ this.#snapshot(db, s);
2246
+ }
2247
+ const identities = new Set([...fixed.tasks, ...e.tasks].map((t) => `${t.features.schema}:${t.features.values.length}`));
2248
+ for (const ref2 of [c.from, c.to])
2249
+ if (ref2) {
2250
+ const s = this.#read(db, "snapshot", ref2);
2251
+ for (const r of s.rows)
2252
+ identities.add(`${r.observation.features.schema}:${r.observation.features.values.length}`);
2253
+ }
2254
+ if (identities.size !== 1)
2255
+ failure("Incomparable episode feature schema or dimensions");
2256
+ const previous = new Set(fixed.tasks.map((t) => t.taskDigest));
2257
+ if (e.tasks.some((t) => previous.has(t.taskDigest)))
2258
+ failure("Fresh/fixed task overlap");
2259
+ }
2260
+ for (const c of e.cells)
2261
+ for (const kind of ["attempt", "observation"]) {
2262
+ const id = kind === "attempt" ? c.attemptId : c.observationId;
2263
+ if (this.#read(db, kind, id) || db.prepare("SELECT 1 FROM cell_ids WHERE kind=? AND id=?").get(kind, id))
2264
+ failure("Cell ID is already used or reserved");
2265
+ db.prepare("INSERT INTO cell_ids(kind,id,domain,episode_id) VALUES (?,?,?,?)").run(kind, id, e.domain, e.id);
2266
+ }
2267
+ for (const t of e.tasks) {
2268
+ if (e.kind === "fresh" && (db.prepare("SELECT 1 FROM task_claims WHERE domain=? AND task_digest=?").get(e.domain, t.taskDigest) || db.prepare("SELECT 1 FROM observations WHERE domain=? AND task_digest=?").get(e.domain, t.taskDigest)))
2269
+ failure("Fresh input was already used");
2270
+ this.#claim(db, e.domain, t.taskDigest, e.kind, e.id);
2271
+ }
2272
+ }
2273
+ #attempt(db, a) {
2274
+ const reservation = db.prepare("SELECT domain,episode_id FROM cell_ids WHERE kind='attempt' AND id=?").get(a.id);
2275
+ if (reservation && (a.split === "train" || reservation.domain !== a.domain || reservation.episode_id !== a.episodeId))
2276
+ failure("Attempt ID is exclusively reserved to another episode");
2277
+ if (a.split !== "train" && !reservation)
2278
+ failure("Episode attempt ID is not reserved");
2279
+ const d = this.#read(db, "decision", a.decisionId);
2280
+ if (!d || d.domain !== a.domain || d.digest !== a.decisionDigest || d.taskDigest !== a.taskDigest || d.featuresDigest !== digest(a.features) || !d.selected || digest(d.selected) !== digest(a.action) || a.startedAt < d.createdAt)
2281
+ failure("Attempt must match its durable decision");
2282
+ if (a.split === "train") {
2283
+ if (this.#read(db, "observation", a.observationId) || db.prepare("SELECT 1 FROM cell_ids WHERE kind='observation' AND id=?").get(a.observationId))
2284
+ failure("Planned observation ID is already used or reserved");
2285
+ db.prepare("INSERT INTO cell_ids(kind,id,domain,episode_id) VALUES ('observation',?,?,?)").run(a.observationId, a.domain, "");
2286
+ this.#claim(db, a.domain, a.taskDigest, "train");
2287
+ } else {
2288
+ const e = this.#read(db, "episode", a.episodeId);
2289
+ if (!e || e.domain !== a.domain || e.kind !== a.split || d.mode !== "matrix" || e.definitionDigest !== d.definitionDigest || a.startedAt < e.createdAt)
2290
+ failure("Missing/mismatched prospective episode");
2291
+ const c = e.cells.find((c2) => c2.attemptId === a.id);
2292
+ if (!c || c.observationId !== a.observationId || c.taskDigest !== a.taskDigest || c.actionKey !== a.action.key || c.repetition !== a.repetition || digest(e.tasks.find((t) => t.taskDigest === a.taskDigest).features) !== digest(a.features) || digest(e.arms.find((x) => x.key === a.action.key)) !== digest(a.action))
2293
+ failure("Attempt outside reserved matrix cell");
2294
+ }
2295
+ }
2296
+ async put(kind, id, value) {
2297
+ const row = validateLearningRecord(kind, value);
2298
+ if (kind === "snapshot") {
2299
+ hash(id);
2300
+ if (row.digest !== id)
2301
+ failure("Snapshot ID must equal digest");
2302
+ } else {
2303
+ identifier(id);
2304
+ if (!("id" in row) || row.id !== id)
2305
+ failure("Record ID mismatch");
2306
+ }
2307
+ this.#database.transaction((db) => {
2308
+ if (this.#read(db, kind, id))
2309
+ throw new LearningRecordExistsError();
2310
+ if (kind === "decision") {
2311
+ const d = row;
2312
+ if (d.policy !== null) {
2313
+ const s = this.#read(db, "snapshot", d.policy);
2314
+ if (!s || s.domain !== d.domain)
2315
+ failure("Decision references missing policy");
2316
+ }
2317
+ } else if (kind === "attempt")
2318
+ this.#attempt(db, row);
2319
+ else if (kind === "snapshot")
2320
+ this.#snapshot(db, row);
2321
+ else
2322
+ this.#episode(db, row);
2323
+ this.#insert(db, kind, id, row);
2324
+ });
2325
+ }
2326
+ async get(kind, id) {
2327
+ identifier(id);
2328
+ return this.#database.transaction((db) => {
2329
+ const v = this.#read(db, kind, id);
2330
+ if (kind === "snapshot" && v)
2331
+ this.#snapshot(db, v);
2332
+ return v;
2333
+ });
2334
+ }
2335
+ async highWater(domain) {
2336
+ hash(domain);
2337
+ return this.#database.transaction((db) => this.#water(db, domain));
2338
+ }
2339
+ async observations(domain, options = {}) {
2340
+ hash(domain);
2341
+ const through = options.through ?? Number.MAX_SAFE_INTEGER, limit = options.limit ?? Number.MAX_SAFE_INTEGER;
2342
+ if (!Number.isSafeInteger(through) || through < 0 || !Number.isSafeInteger(limit) || limit < 0 || options.split !== void 0 && !["train", "fixed", "fresh"].includes(options.split) || options.verifiedOnly !== void 0 && typeof options.verifiedOnly !== "boolean")
2343
+ throw new TypeError("Invalid observation query");
2344
+ if (options.schema !== void 0)
2345
+ identifier(options.schema);
2346
+ if (options.dimensions !== void 0 && (!Number.isSafeInteger(options.dimensions) || options.dimensions < 1 || options.dimensions > 512))
2347
+ throw new TypeError("Invalid feature dimensions");
2348
+ const actionKeys = options.actionKeys === void 0 ? void 0 : jsonClone(options.actionKeys);
2349
+ if (actionKeys !== void 0 && (!Array.isArray(actionKeys) || actionKeys.length > 64 || new Set(actionKeys).size !== actionKeys.length))
2350
+ throw new TypeError("Invalid action key filter");
2351
+ actionKeys?.forEach(hash);
2352
+ const observationIds = options.observationIds === void 0 ? void 0 : jsonClone(options.observationIds);
2353
+ if (observationIds !== void 0 && (!Array.isArray(observationIds) || observationIds.length > 8192 || new Set(observationIds).size !== observationIds.length))
2354
+ throw new TypeError("Invalid observation ID filter");
2355
+ observationIds?.forEach(identifier);
2356
+ return this.#database.transaction((db) => {
2357
+ if (actionKeys?.length === 0 || observationIds?.length === 0 || limit === 0)
2358
+ return freeze([]);
2359
+ const where = ["domain=?", "sequence<=?"], params = [domain, through];
2360
+ if (options.split !== void 0) {
2361
+ where.push("split=?");
2362
+ params.push(options.split);
2363
+ }
2364
+ if (options.verifiedOnly)
2365
+ where.push("json_extract(json,'$.quality.state')='verified'");
2366
+ if (options.schema !== void 0) {
2367
+ where.push("json_extract(json,'$.features.schema')=?");
2368
+ params.push(options.schema);
2369
+ }
2370
+ if (options.dimensions !== void 0) {
2371
+ where.push("json_array_length(json_extract(json,'$.features.values'))=?");
2372
+ params.push(options.dimensions);
2373
+ }
2374
+ if (actionKeys !== void 0) {
2375
+ where.push(`json_extract(json,'$.action.key') IN (${actionKeys.map(() => "?").join(",")})`);
2376
+ params.push(...actionKeys);
2377
+ }
2378
+ const batches = observationIds ? Array.from({ length: Math.ceil(observationIds.length / 256) }, (_, i) => observationIds.slice(i * 256, (i + 1) * 256)) : [void 0];
2379
+ const matches = batches.flatMap((ids) => {
2380
+ const filters = [...where], args = [...params];
2381
+ if (ids) {
2382
+ filters.push(`id IN (${ids.map(() => "?").join(",")})`);
2383
+ args.push(...ids);
2384
+ }
2385
+ args.push(limit);
2386
+ return db.prepare(`SELECT sequence,id FROM observations ${ids ? "INDEXED BY observations_ids_domain" : ""} WHERE ${filters.join(" AND ")} ORDER BY sequence DESC LIMIT ?`).all(...args);
2387
+ }).sort((a, b) => Number(a.sequence) - Number(b.sequence));
2388
+ return freeze(matches.slice(-limit).map((row) => ({ sequence: Number(row.sequence), observation: this.#read(db, "observation", String(row.id)) })));
2389
+ });
2390
+ }
2391
+ async appendObservation(value) {
2392
+ const o = validateLearningRecord("observation", value);
2393
+ return this.#database.transaction((db) => {
2394
+ const old = this.#read(db, "observation", o.id);
2395
+ if (old) {
2396
+ if (old.digest !== o.digest)
2397
+ failure("Conflicting terminal observation");
2398
+ const row = db.prepare("SELECT sequence FROM observations WHERE id=?").get(o.id);
2399
+ return freeze({ sequence: Number(row.sequence), observation: old });
2400
+ }
2401
+ const reservation = db.prepare("SELECT domain,episode_id FROM cell_ids WHERE kind='observation' AND id=?").get(o.id);
2402
+ if (reservation && (reservation.domain !== o.domain || reservation.episode_id !== (o.split === "train" ? "" : o.episodeId)))
2403
+ failure("Observation ID is exclusively reserved to another episode");
2404
+ if (!reservation)
2405
+ failure("Episode terminal ID is not reserved");
2406
+ const a = this.#read(db, "attempt", o.attemptId);
2407
+ if (!a || a.observationId !== o.id || a.domain !== o.domain || a.decisionId !== o.decisionId || a.decisionDigest !== o.decisionDigest || digest(a.action) !== digest(o.action) || a.taskDigest !== o.taskDigest || digest(a.features) !== digest(o.features) || a.split !== o.split || a.episodeId !== o.episodeId || a.repetition !== o.repetition || o.createdAt < a.startedAt)
2408
+ failure("Terminal observation must match durable start");
2409
+ if (o.split !== "train") {
2410
+ const e = this.#read(db, "episode", o.episodeId), c = e.cells.find((c2) => c2.attemptId === a.id);
2411
+ if (c.observationId !== o.id)
2412
+ failure("Terminal observation ID is not reserved");
2413
+ }
2414
+ const r = db.prepare("INSERT INTO observations(id,domain,attempt_id,task_digest,split,digest,json) VALUES (?,?,?,?,?,?,?)").run(o.id, o.domain, o.attemptId, o.taskDigest, o.split, o.digest, JSON.stringify(o));
2415
+ return freeze({ sequence: Number(r.lastInsertRowid), observation: o });
2416
+ });
2417
+ }
2418
+ async pointer(domain) {
2419
+ hash(domain);
2420
+ return this.#database.transaction((db) => this.#pointer(db, domain));
2421
+ }
2422
+ async pending(domain) {
2423
+ hash(domain);
2424
+ return this.#database.transaction((db) => freeze(db.prepare("SELECT id FROM records WHERE kind='attempt' AND domain=? AND id NOT IN (SELECT attempt_id FROM observations WHERE domain=?) ORDER BY id").all(domain, domain).map((r) => this.#read(db, "attempt", String(r.id)))));
2425
+ }
2426
+ async commitGate(value) {
2427
+ const gate = validateLearningRecord("gate", value);
2428
+ return this.#database.transaction((db) => {
2429
+ const old = this.#read(db, "gate", gate.id);
2430
+ if (old) {
2431
+ if (old.digest !== gate.digest)
2432
+ throw Object.assign(new Error("Conflicting gate replay"), { code: "LEARNING_GATE_EXISTS" });
2433
+ const commit2 = this.#read(db, "gate-commit", gate.id);
2434
+ return commit2 ?? failure("Missing gate commit");
2435
+ }
2436
+ const fresh = this.#read(db, "episode", gate.fresh.episodeId), fixed = this.#read(db, "episode", gate.fixed.episodeId);
2437
+ if (!fresh || !fixed || fresh.domain !== gate.domain || fixed.domain !== gate.domain || !fresh.comparison)
2438
+ failure("Gate episodes missing");
2439
+ if (db.prepare("SELECT 1 FROM consumed WHERE domain=? AND episode_id=?").get(gate.domain, fresh.id))
2440
+ failure("Fresh episode already consumed");
2441
+ const observations = [];
2442
+ for (const e of [fixed, fresh])
2443
+ for (const c of e.cells) {
2444
+ const o = this.#read(db, "observation", c.observationId);
2445
+ if (o) {
2446
+ const r = db.prepare("SELECT sequence FROM observations WHERE id=? AND domain=?").get(o.id, gate.domain);
2447
+ if (!r)
2448
+ failure("Cross-domain cell");
2449
+ observations.push({ sequence: Number(r.sequence), observation: o });
2450
+ }
2451
+ }
2452
+ const fromSnapshot = gate.from === null ? void 0 : this.#read(db, "snapshot", gate.from), toSnapshot = gate.to === null ? void 0 : this.#read(db, "snapshot", gate.to);
2453
+ for (const policy of [fromSnapshot, toSnapshot])
2454
+ if (policy)
2455
+ this.#snapshot(db, policy, true);
2456
+ const recomputed = assessGateEvidence({ id: gate.id, createdAt: gate.createdAt, domain: gate.domain, fresh, fixed, ...fromSnapshot ? { fromSnapshot } : {}, ...toSnapshot ? { toSnapshot } : {}, observations });
2457
+ if (recomputed.digest !== gate.digest)
2458
+ failure("Gate is not authorized by stored paired evidence");
2459
+ const before = this.#pointer(db, gate.domain);
2460
+ const prior = db.prepare("SELECT json_extract(json,'$.createdAt') AS created_at FROM records WHERE domain=? AND kind='gate-commit' AND json_extract(json,'$.status') IN ('promoted','rolled-back') ORDER BY json_extract(json,'$.after.generation') DESC LIMIT 1").get(gate.domain);
2461
+ const committedAt = Math.max(Date.now(), gate.createdAt, Number(prior?.created_at ?? 0));
2462
+ let after = before, status = "kept";
2463
+ const matches = before.generation === gate.expectedGeneration && before.active === gate.from && (gate.mode !== "rollback" || before.generation >= 1 && before.previous === gate.to);
2464
+ if (!matches)
2465
+ status = "stale";
2466
+ else if (gate.outcome !== "keep") {
2467
+ if (gate.mode === "promote" && gate.to === null)
2468
+ failure("Cannot promote null policy");
2469
+ after = freeze({ generation: before.generation + 1, active: gate.to, previous: before.active });
2470
+ status = gate.outcome === "promote" ? "promoted" : "rolled-back";
2471
+ db.prepare("INSERT INTO pointers(domain,generation,active,previous) VALUES (?,?,?,?) ON CONFLICT(domain) DO UPDATE SET generation=excluded.generation,active=excluded.active,previous=excluded.previous").run(gate.domain, after.generation, after.active, after.previous);
2472
+ }
2473
+ db.prepare("INSERT INTO consumed(domain,episode_id,gate_id) VALUES (?,?,?)").run(gate.domain, fresh.id, gate.id);
2474
+ const commit = sealLearningRecord("gate-commit", { format: 1, id: gate.id, domain: gate.domain, gateDigest: gate.digest, status, before, after, createdAt: committedAt });
2475
+ this.#insert(db, "gate", gate.id, gate);
2476
+ this.#insert(db, "gate-commit", gate.id, commit);
2477
+ this.#history.invalidate();
2478
+ return commit;
2479
+ });
2480
+ }
2481
+ close() {
2482
+ this.#database.close();
2483
+ }
2484
+ };
2485
+ export {
2486
+ DEFAULT_LEARNING_POLICY,
2487
+ LearningRouter,
2488
+ SqliteLearningStore,
2489
+ assessGateEvidence,
2490
+ buildSnapshot,
2491
+ hashTaskFeatures,
2492
+ inputDigest,
2493
+ digest as learningDigest,
2494
+ learningDomainDigest,
2495
+ predict,
2496
+ sealLearningRecord,
2497
+ selectPolicy,
2498
+ validateFeatures,
2499
+ validateLearningRecord,
2500
+ validatePolicyConfig
2501
+ };
2502
+ //# sourceMappingURL=index.js.map