@hraness/kb 0.17.1

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 (200) hide show
  1. package/DISCLOSURE +43 -0
  2. package/LICENSE +21 -0
  3. package/README.md +545 -0
  4. package/dist/agent-context.js +35 -0
  5. package/dist/agent-guide-audit.js +18 -0
  6. package/dist/attachments.js +19 -0
  7. package/dist/authoring.js +33 -0
  8. package/dist/benchmark.js +19 -0
  9. package/dist/capture.js +49 -0
  10. package/dist/cli.js +3646 -0
  11. package/dist/clip/acquire.js +57 -0
  12. package/dist/clip/args.js +21 -0
  13. package/dist/clip/bounded-byte-buffer.js +9 -0
  14. package/dist/clip/browser-profiles.js +17 -0
  15. package/dist/clip/bundle-reader.js +11 -0
  16. package/dist/clip/cli.js +27 -0
  17. package/dist/clip/cookies.js +21 -0
  18. package/dist/clip/defuddle-worker.js +84 -0
  19. package/dist/clip/doctor.js +32 -0
  20. package/dist/clip/jobs.js +784 -0
  21. package/dist/clip/network-proxy.js +9 -0
  22. package/dist/clip/network.js +28 -0
  23. package/dist/clip/persist.js +30 -0
  24. package/dist/clip/refresh.js +11 -0
  25. package/dist/clip/terminal.js +11 -0
  26. package/dist/evaluation-builder.js +12238 -0
  27. package/dist/evaluation-kb.js +26 -0
  28. package/dist/evaluation.js +35 -0
  29. package/dist/git.js +39 -0
  30. package/dist/graph.js +39 -0
  31. package/dist/index-01jj6rbv.js +1103 -0
  32. package/dist/index-06c9ctr6.js +738 -0
  33. package/dist/index-0kavxzqj.js +2480 -0
  34. package/dist/index-1gwbassd.js +743 -0
  35. package/dist/index-1n418kb9.js +827 -0
  36. package/dist/index-1vrd1rmn.js +56 -0
  37. package/dist/index-1xxnjn0d.js +171 -0
  38. package/dist/index-3rm7cz6h.js +373 -0
  39. package/dist/index-3v2z4f0q.js +328 -0
  40. package/dist/index-48pz4jpc.js +392 -0
  41. package/dist/index-4j3tt0c3.js +234 -0
  42. package/dist/index-5n05se68.js +307 -0
  43. package/dist/index-5vwpzb5a.js +764 -0
  44. package/dist/index-6g2pv9d2.js +370 -0
  45. package/dist/index-7fzc32gf.js +712 -0
  46. package/dist/index-84x0vjjp.js +432 -0
  47. package/dist/index-adx6khj5.js +488 -0
  48. package/dist/index-b88v3vtm.js +805 -0
  49. package/dist/index-cv6fh7z5.js +462 -0
  50. package/dist/index-cxfrakt7.js +1067 -0
  51. package/dist/index-d13v9ckt.js +150 -0
  52. package/dist/index-dycjbhw2.js +1943 -0
  53. package/dist/index-dyqwejk5.js +531 -0
  54. package/dist/index-e5fbsywq.js +658 -0
  55. package/dist/index-f984hw45.js +927 -0
  56. package/dist/index-gh719d91.js +63 -0
  57. package/dist/index-hgve9rh2.js +2046 -0
  58. package/dist/index-hya40gb2.js +474 -0
  59. package/dist/index-j4zgmzjr.js +152 -0
  60. package/dist/index-jsmvyyvf.js +1166 -0
  61. package/dist/index-kh0pwvdd.js +1974 -0
  62. package/dist/index-mqx4nd6v.js +119 -0
  63. package/dist/index-mxxxytys.js +1254 -0
  64. package/dist/index-n5dd7r0v.js +711 -0
  65. package/dist/index-npg9z1a4.js +431 -0
  66. package/dist/index-pj501bh1.js +140 -0
  67. package/dist/index-qry4vhxk.js +1041 -0
  68. package/dist/index-s2gw5aw9.js +199 -0
  69. package/dist/index-vvdj6kca.js +70 -0
  70. package/dist/index-w2zc0vwa.js +571 -0
  71. package/dist/index-x3fthpsc.js +585 -0
  72. package/dist/index-zr53sf63.js +44 -0
  73. package/dist/index-zxdy5pby.js +2728 -0
  74. package/dist/index-zzhgcwyt.js +966 -0
  75. package/dist/index.js +453 -0
  76. package/dist/navigation.js +13 -0
  77. package/dist/pdf.js +85 -0
  78. package/dist/percolate.js +24 -0
  79. package/dist/portfolio.js +77 -0
  80. package/dist/query.js +29 -0
  81. package/dist/repository-memory.js +60 -0
  82. package/dist/sdk.js +36 -0
  83. package/dist/search-rules.js +34 -0
  84. package/dist/search.js +22 -0
  85. package/dist/semantic.js +39 -0
  86. package/dist/source-inbox.js +17 -0
  87. package/dist/untrusted-content.js +32 -0
  88. package/dist/url-intelligence.js +74 -0
  89. package/dist/workflow.js +23 -0
  90. package/dist/workflows/decision-context.js +20 -0
  91. package/dist/workflows/explain-change.js +8 -0
  92. package/dist/workflows/index.js +28 -0
  93. package/dist/workflows/plan-radar.js +10 -0
  94. package/package.json +409 -0
  95. package/skills/kb/AGENTS.md +19 -0
  96. package/skills/kb/SKILL.md +82 -0
  97. package/skills/kb/agents/openai.yaml +4 -0
  98. package/skills/kb/references/pdf-review.md +51 -0
  99. package/skills/kb/references/percolate.md +144 -0
  100. package/skills/kb/references/plan-structure.md +105 -0
  101. package/skills/kb/references/plan.md +115 -0
  102. package/skills/kb/references/query.md +231 -0
  103. package/skills/kb/references/refresh.md +133 -0
  104. package/skills/kb/references/save-pdf.md +125 -0
  105. package/skills/kb/references/save-url.md +178 -0
  106. package/skills/kb/references/url-authentication.md +75 -0
  107. package/skills/kb/references/url-platforms.md +25 -0
  108. package/src/agent-context.ts +1241 -0
  109. package/src/agent-guide-audit.ts +750 -0
  110. package/src/attachments.ts +723 -0
  111. package/src/authoring.ts +1725 -0
  112. package/src/benchmark.ts +362 -0
  113. package/src/capture.ts +68 -0
  114. package/src/cli.ts +3660 -0
  115. package/src/clip/acquire.ts +1273 -0
  116. package/src/clip/archive-today.ts +402 -0
  117. package/src/clip/args.ts +423 -0
  118. package/src/clip/assets.ts +262 -0
  119. package/src/clip/bounded-byte-buffer.ts +75 -0
  120. package/src/clip/browser-profiles.ts +372 -0
  121. package/src/clip/bundle-reader.ts +608 -0
  122. package/src/clip/capture.ts +1054 -0
  123. package/src/clip/cli.ts +181 -0
  124. package/src/clip/cookies.ts +512 -0
  125. package/src/clip/doctor.ts +1110 -0
  126. package/src/clip/extract.ts +868 -0
  127. package/src/clip/jobs.ts +959 -0
  128. package/src/clip/lib.ts +861 -0
  129. package/src/clip/media.ts +1474 -0
  130. package/src/clip/metadata-search-tool/Cargo.lock +2498 -0
  131. package/src/clip/metadata-search-tool/Cargo.toml +18 -0
  132. package/src/clip/metadata-search-tool/runner.ts +685 -0
  133. package/src/clip/metadata-search-tool/src/main.rs +389 -0
  134. package/src/clip/metadata-search.ts +687 -0
  135. package/src/clip/network-proxy.ts +627 -0
  136. package/src/clip/network.ts +950 -0
  137. package/src/clip/package-root.ts +54 -0
  138. package/src/clip/persist.ts +1472 -0
  139. package/src/clip/platforms.ts +1824 -0
  140. package/src/clip/refresh.ts +197 -0
  141. package/src/clip/structured.ts +432 -0
  142. package/src/clip/terminal.ts +197 -0
  143. package/src/clip/url-intelligence.ts +581 -0
  144. package/src/clip/url-metadata-backfill.ts +616 -0
  145. package/src/clip/url-metadata-cli.ts +251 -0
  146. package/src/clip/url-metadata.ts +1397 -0
  147. package/src/evaluation-analysis-v2.ts +1440 -0
  148. package/src/evaluation-builder.ts +2539 -0
  149. package/src/evaluation-corpus-authoring.ts +2052 -0
  150. package/src/evaluation-evidence.ts +1147 -0
  151. package/src/evaluation-execution-v2.ts +426 -0
  152. package/src/evaluation-implementation.ts +131 -0
  153. package/src/evaluation-kb-closure.ts +1430 -0
  154. package/src/evaluation-kb-runner-v2.ts +735 -0
  155. package/src/evaluation-kb-v2.ts +2567 -0
  156. package/src/evaluation-kb.ts +1018 -0
  157. package/src/evaluation-measurement-v2.ts +1462 -0
  158. package/src/evaluation-packing-v2.ts +452 -0
  159. package/src/evaluation-redaction.ts +28 -0
  160. package/src/evaluation-v2.ts +3857 -0
  161. package/src/evaluation.ts +1220 -0
  162. package/src/git.ts +1276 -0
  163. package/src/graph.ts +1487 -0
  164. package/src/index.ts +20 -0
  165. package/src/init.ts +123 -0
  166. package/src/navigation.ts +277 -0
  167. package/src/note-lock.ts +529 -0
  168. package/src/pdf/args.ts +202 -0
  169. package/src/pdf/capture.ts +298 -0
  170. package/src/pdf/cli.ts +159 -0
  171. package/src/pdf/extract.ts +303 -0
  172. package/src/pdf/layout.ts +618 -0
  173. package/src/pdf/markdown.ts +154 -0
  174. package/src/pdf/model.ts +234 -0
  175. package/src/pdf/ocr.ts +190 -0
  176. package/src/pdf/persist.ts +314 -0
  177. package/src/pdf/source.ts +135 -0
  178. package/src/pdf/tools.ts +146 -0
  179. package/src/pdf.ts +92 -0
  180. package/src/percolate.ts +877 -0
  181. package/src/portfolio-audit.ts +574 -0
  182. package/src/portfolio-identity.ts +162 -0
  183. package/src/portfolio-registry.ts +473 -0
  184. package/src/portfolio.ts +765 -0
  185. package/src/query.ts +646 -0
  186. package/src/repository-memory.ts +1150 -0
  187. package/src/sdk.ts +1452 -0
  188. package/src/search-rules.ts +712 -0
  189. package/src/search.ts +710 -0
  190. package/src/semantic-runtime.ts +1139 -0
  191. package/src/semantic.ts +2480 -0
  192. package/src/source-inbox.ts +232 -0
  193. package/src/untrusted-content.ts +401 -0
  194. package/src/url-intelligence.ts +104 -0
  195. package/src/vault.ts +636 -0
  196. package/src/workflow.ts +653 -0
  197. package/src/workflows/decision-context.ts +81 -0
  198. package/src/workflows/explain-change.ts +73 -0
  199. package/src/workflows/index.ts +3 -0
  200. package/src/workflows/plan-radar.ts +101 -0
@@ -0,0 +1,1430 @@
1
+ export const MAX_EXISTING_LANE_CLOSURE_RESULTS = 1_000;
2
+ export const MAX_EXISTING_LANE_CLOSURE_TOTAL_CANDIDATES = 4_096;
3
+ export const MAX_EXISTING_LANE_CLOSURE_EVIDENCE_UNITS = 100;
4
+ export const MAX_EXISTING_LANE_CLOSURE_TOTAL_EVIDENCE_UNITS = 512;
5
+ export const MAX_EXISTING_LANE_CLOSURE_PROVENANCE_BYTES = 256 * 1_024;
6
+ export const MAX_EXISTING_LANE_CLOSURE_EVIDENCE_BYTES = 8 * 1_024 * 1_024;
7
+ export const MAX_EXISTING_LANE_CLOSURE_DIAGNOSTICS = 100;
8
+ export const EXISTING_LANE_CLOSURE_FUSION = "primary-prefix-then-round-robin-v1";
9
+
10
+ export const existingLaneClosureStructuralLaneIds = Object.freeze([
11
+ "metadata",
12
+ "graph",
13
+ "path-context",
14
+ ] as const);
15
+
16
+ export type ExistingLaneClosureStructuralLaneId =
17
+ typeof existingLaneClosureStructuralLaneIds[number];
18
+ export type ExistingLaneClosureLaneId =
19
+ | "hybrid"
20
+ | ExistingLaneClosureStructuralLaneId
21
+ | "git";
22
+
23
+ export type ExistingLaneClosureVariant = Readonly<{
24
+ readonly primary: Readonly<{
25
+ readonly lane: "hybrid";
26
+ readonly retrieveLimit: number;
27
+ readonly retainLimit: number;
28
+ }> | null;
29
+ readonly structuralLanes: readonly Readonly<{
30
+ readonly lane: ExistingLaneClosureStructuralLaneId;
31
+ readonly limit: number;
32
+ }>[];
33
+ readonly git:
34
+ | Readonly<{ readonly mode: "off" }>
35
+ | Readonly<{ readonly mode: "explicit-input"; readonly limit: number }>;
36
+ readonly outputLimit: number;
37
+ }>;
38
+
39
+ export type ExistingLaneClosureMetadataFilter =
40
+ | Readonly<{ readonly kind: "exists"; readonly path: string }>
41
+ | Readonly<{
42
+ readonly kind: "equals";
43
+ readonly path: string;
44
+ readonly value: string | number | boolean | null;
45
+ }>;
46
+
47
+ export type ExistingLaneClosureHybridInput = Readonly<{ readonly text: string }>;
48
+ export type ExistingLaneClosureMetadataInput = Readonly<{
49
+ readonly filters: readonly ExistingLaneClosureMetadataFilter[];
50
+ readonly tags: readonly string[];
51
+ }>;
52
+ export type ExistingLaneClosureGraphInput = Readonly<{
53
+ readonly seeds: readonly string[];
54
+ readonly depth: 1 | 2;
55
+ }>;
56
+ export type ExistingLaneClosurePathContextInput = Readonly<{
57
+ readonly repositoryPath: string;
58
+ }>;
59
+ export type ExistingLaneClosureGitInput = Readonly<{
60
+ readonly query: string;
61
+ readonly noteIds: readonly string[];
62
+ }>;
63
+
64
+ export type ExistingLaneClosureExecutableInputs = Readonly<{
65
+ readonly hybrid?: ExistingLaneClosureHybridInput;
66
+ readonly metadata?: ExistingLaneClosureMetadataInput;
67
+ readonly graph?: ExistingLaneClosureGraphInput;
68
+ readonly pathContext?: ExistingLaneClosurePathContextInput;
69
+ readonly history?: ExistingLaneClosureGitInput;
70
+ }>;
71
+
72
+ export type ExistingLaneClosureQuery = Readonly<{
73
+ readonly inputs: ExistingLaneClosureExecutableInputs;
74
+ }>;
75
+
76
+ export type ExistingLaneClosureSourceClass =
77
+ | "authored-note"
78
+ | "captured-source"
79
+ | "git-history"
80
+ | "repository-file";
81
+
82
+ export type ExistingLaneClosureTrustClass =
83
+ | "authoritative-current"
84
+ | "authoritative-historical"
85
+ | "captured-primary"
86
+ | "captured-secondary"
87
+ | "maintained-synthesis"
88
+ | "untrusted-capture";
89
+
90
+ export type ExistingLaneClosureEvidenceLocator = Readonly<{
91
+ readonly evidenceUnitId: string;
92
+ readonly documentId: string;
93
+ readonly sourceFamilyId: string;
94
+ readonly sourceClass: ExistingLaneClosureSourceClass;
95
+ readonly trustClass: ExistingLaneClosureTrustClass;
96
+ readonly sourcePath: string;
97
+ readonly lineRange: Readonly<{ readonly start: number; readonly end: number }>;
98
+ readonly headingPath: readonly string[];
99
+ readonly sourcePage?: number;
100
+ }>;
101
+
102
+ /** Compatibility name retained for adapters; provenance is now a typed locator. */
103
+ export type ExistingLaneClosureProvenance = ExistingLaneClosureEvidenceLocator;
104
+
105
+ export type ExistingLaneClosureEvidenceRegistry = Readonly<{
106
+ readonly units: readonly ExistingLaneClosureEvidenceLocator[];
107
+ }>;
108
+
109
+ export type ExistingLaneClosureEvidenceUnit = Readonly<{
110
+ readonly id: string;
111
+ /** The ID and locator stay paired and must exactly match the injected registry. */
112
+ readonly locator: ExistingLaneClosureEvidenceLocator;
113
+ }>;
114
+
115
+ export type ExistingLaneClosureHit = Readonly<{
116
+ readonly documentId: string;
117
+ readonly canonicalDocumentId: string;
118
+ readonly rank: number;
119
+ readonly score?: number;
120
+ readonly evidenceUnits?: readonly ExistingLaneClosureEvidenceUnit[];
121
+ readonly evidence?: unknown;
122
+ }>;
123
+
124
+ export type ExistingLaneClosureDiagnostic = Readonly<{
125
+ readonly code: string;
126
+ readonly status: "degraded" | "ready" | "unavailable";
127
+ readonly message?: string;
128
+ readonly details?: Readonly<Record<string, string | number | boolean | null>>;
129
+ }>;
130
+
131
+ export type ExistingLaneClosureAccounting = Readonly<{
132
+ readonly llm: Readonly<{
133
+ readonly calls: 0;
134
+ readonly inputTokens: 0;
135
+ readonly outputTokens: 0;
136
+ }>;
137
+ readonly embedding: Readonly<{
138
+ readonly calls: number;
139
+ readonly inputTokens: number;
140
+ readonly inputTokensMeasured?: false;
141
+ readonly durationMs: number;
142
+ readonly durationScope?: "embedding-backed-search-upper-bound";
143
+ }>;
144
+ readonly packedContext: Readonly<{
145
+ readonly utf8Bytes: number;
146
+ readonly readerTokens: number;
147
+ }>;
148
+ readonly peakRssBytes: number;
149
+ readonly cacheBytes: number;
150
+ }>;
151
+
152
+ export type ExistingLaneClosureLaneResult = Readonly<{
153
+ readonly status: "degraded" | "ready" | "unavailable";
154
+ readonly hits: readonly ExistingLaneClosureHit[];
155
+ readonly diagnostics?: readonly ExistingLaneClosureDiagnostic[];
156
+ readonly timings?: Readonly<Record<string, number>>;
157
+ readonly resources?: Readonly<Record<string, number>>;
158
+ /** Required measurement boundary. Omission is never interpreted as zero. */
159
+ readonly accounting: ExistingLaneClosureAccounting;
160
+ }>;
161
+
162
+ export type ExistingLaneClosureLaneRequest<Input> = Readonly<{
163
+ readonly input: Input;
164
+ readonly limit: number;
165
+ readonly signal: AbortSignal;
166
+ }>;
167
+
168
+ export type ExistingLaneClosureBackend<Input> = Readonly<{
169
+ readonly retrieve: (
170
+ request: ExistingLaneClosureLaneRequest<Input>,
171
+ ) => Promise<ExistingLaneClosureLaneResult>;
172
+ }>;
173
+
174
+ export type ExistingLaneClosureBackends = Readonly<{
175
+ readonly hybrid?: ExistingLaneClosureBackend<ExistingLaneClosureHybridInput>;
176
+ readonly metadata?: ExistingLaneClosureBackend<ExistingLaneClosureMetadataInput>;
177
+ readonly graph?: ExistingLaneClosureBackend<ExistingLaneClosureGraphInput>;
178
+ readonly pathContext?: ExistingLaneClosureBackend<ExistingLaneClosurePathContextInput>;
179
+ readonly git?: ExistingLaneClosureBackend<ExistingLaneClosureGitInput>;
180
+ }>;
181
+
182
+ export type ExistingLaneClosureReasonCode =
183
+ | "primary"
184
+ | "appended"
185
+ | "deduplicated"
186
+ | "primary-retain-limit"
187
+ | "output-limit"
188
+ | "missing-provenance";
189
+
190
+ type ExistingLaneClosureEvidenceTrace = Readonly<{
191
+ readonly evidenceUnits: readonly ExistingLaneClosureEvidenceUnit[];
192
+ /** Compatibility projections preserve the exact paired order above. */
193
+ readonly evidenceUnitIds: readonly string[];
194
+ readonly provenance: readonly ExistingLaneClosureEvidenceLocator[];
195
+ /** Bounded, deep-snapshotted lane-native evidence retained for audit. */
196
+ readonly evidence?: unknown;
197
+ }>;
198
+
199
+ export type ExistingLaneClosureCandidateTrace = ExistingLaneClosureEvidenceTrace & Readonly<{
200
+ readonly lane: ExistingLaneClosureLaneId;
201
+ readonly decision: "accepted" | "excluded";
202
+ readonly reasonCode: ExistingLaneClosureReasonCode;
203
+ readonly documentId: string;
204
+ readonly canonicalDocumentId: string;
205
+ readonly sourceRank: number;
206
+ readonly outputRank?: number;
207
+ }>;
208
+
209
+ export type ExistingLaneClosureLaneOutcome = Readonly<{
210
+ readonly lane: ExistingLaneClosureLaneId;
211
+ readonly invocation: "disabled" | "invoked" | "skipped-missing-input";
212
+ readonly status: "degraded" | "ready" | "skipped" | "unavailable";
213
+ readonly limit?: number;
214
+ readonly diagnostics: readonly ExistingLaneClosureDiagnostic[];
215
+ readonly returned: number;
216
+ readonly accepted: number;
217
+ readonly excluded: number;
218
+ readonly candidates: readonly ExistingLaneClosureCandidateTrace[];
219
+ }>;
220
+
221
+ export type ExistingLaneClosureSourceTrace = ExistingLaneClosureEvidenceTrace & Readonly<{
222
+ readonly lane: ExistingLaneClosureLaneId;
223
+ readonly sourceRank: number;
224
+ }>;
225
+
226
+ export type ExistingLaneClosureDocumentTrace = Readonly<{
227
+ readonly documentId: string;
228
+ readonly canonicalDocumentId: string;
229
+ readonly outputRank: number;
230
+ readonly sources: readonly ExistingLaneClosureSourceTrace[];
231
+ }>;
232
+
233
+ export type ExistingLaneClosureTrace = Readonly<{
234
+ readonly variant: ExistingLaneClosureVariant;
235
+ readonly fusion: Readonly<{
236
+ readonly id: typeof EXISTING_LANE_CLOSURE_FUSION;
237
+ readonly primaryLane: "hybrid" | null;
238
+ readonly appendedLaneOrder: readonly Exclude<ExistingLaneClosureLaneId, "hybrid">[];
239
+ }>;
240
+ readonly lanes: readonly ExistingLaneClosureLaneOutcome[];
241
+ readonly documents: readonly ExistingLaneClosureDocumentTrace[];
242
+ }>;
243
+
244
+ export type ExistingLaneClosureResult = Readonly<{
245
+ readonly status: "degraded" | "ready" | "unavailable";
246
+ readonly hits: readonly ExistingLaneClosureHit[];
247
+ readonly trace: ExistingLaneClosureTrace;
248
+ readonly timings: Readonly<Record<string, number>>;
249
+ readonly resources: Readonly<Record<string, number>>;
250
+ readonly accounting: ExistingLaneClosureAccounting;
251
+ }>;
252
+
253
+ export type RunExistingLaneClosureRequest = Readonly<{
254
+ readonly variant: ExistingLaneClosureVariant;
255
+ readonly query: ExistingLaneClosureQuery;
256
+ readonly backends: ExistingLaneClosureBackends;
257
+ readonly evidenceRegistry: ExistingLaneClosureEvidenceRegistry;
258
+ readonly signal: AbortSignal;
259
+ }>;
260
+
261
+ type UnknownRecord = Readonly<Record<string, unknown>>;
262
+
263
+ type PreparedLane =
264
+ | Readonly<{ readonly kind: "disabled"; readonly lane: ExistingLaneClosureLaneId }>
265
+ | Readonly<{
266
+ readonly kind: "missing";
267
+ readonly lane: ExistingLaneClosureLaneId;
268
+ readonly limit: number;
269
+ }>
270
+ | Readonly<{
271
+ readonly kind: "invoke";
272
+ readonly lane: ExistingLaneClosureLaneId;
273
+ readonly limit: number;
274
+ readonly retainLimit?: number;
275
+ readonly invoke: () => Promise<ExistingLaneClosureLaneResult>;
276
+ }>;
277
+
278
+ type ValidatedLaneResult = Readonly<{
279
+ readonly status: ExistingLaneClosureLaneResult["status"];
280
+ readonly hits: readonly ExistingLaneClosureHit[];
281
+ readonly diagnostics: readonly ExistingLaneClosureDiagnostic[];
282
+ readonly timings: Readonly<Record<string, number>>;
283
+ readonly resources: Readonly<Record<string, number>>;
284
+ readonly accounting: ExistingLaneClosureAccounting;
285
+ readonly evidenceUnitCount: number;
286
+ readonly provenanceBytes: number;
287
+ readonly evidenceBytes: number;
288
+ }>;
289
+
290
+ type CompletedLane =
291
+ | Exclude<PreparedLane, { readonly kind: "invoke" }>
292
+ | Readonly<{
293
+ readonly kind: "complete";
294
+ readonly lane: ExistingLaneClosureLaneId;
295
+ readonly limit: number;
296
+ readonly retainLimit?: number;
297
+ readonly result: ValidatedLaneResult;
298
+ }>;
299
+
300
+ type MutableDocumentTrace = {
301
+ readonly documentId: string;
302
+ readonly canonicalDocumentId: string;
303
+ readonly outputRank: number;
304
+ readonly sources: ExistingLaneClosureSourceTrace[];
305
+ };
306
+
307
+ const structuralLaneIds = new Set<string>(existingLaneClosureStructuralLaneIds);
308
+ const sourceClasses = new Set<ExistingLaneClosureSourceClass>([
309
+ "authored-note",
310
+ "captured-source",
311
+ "git-history",
312
+ "repository-file",
313
+ ]);
314
+ const trustClasses = new Set<ExistingLaneClosureTrustClass>([
315
+ "authoritative-current",
316
+ "authoritative-historical",
317
+ "captured-primary",
318
+ "captured-secondary",
319
+ "maintained-synthesis",
320
+ "untrusted-capture",
321
+ ]);
322
+ const sourceTrustCompatibility = Object.freeze({
323
+ "authored-note": new Set<ExistingLaneClosureTrustClass>([
324
+ "authoritative-current",
325
+ "authoritative-historical",
326
+ "maintained-synthesis",
327
+ ]),
328
+ "captured-source": new Set<ExistingLaneClosureTrustClass>([
329
+ "captured-primary",
330
+ "captured-secondary",
331
+ "untrusted-capture",
332
+ ]),
333
+ "git-history": new Set<ExistingLaneClosureTrustClass>(["authoritative-historical"]),
334
+ "repository-file": new Set<ExistingLaneClosureTrustClass>(["authoritative-current"]),
335
+ } satisfies Readonly<Record<ExistingLaneClosureSourceClass, ReadonlySet<ExistingLaneClosureTrustClass>>>);
336
+ const metricKeyPattern = /^[a-z][a-z0-9_.-]{0,127}$/iu;
337
+ const windowsAbsolutePattern = /^[a-z]:[\\/]/iu;
338
+ const MAX_DESCRIPTOR_TEXT_BYTES = 16 * 1_024;
339
+ const MAX_METRICS_PER_LANE = 32;
340
+ const MAX_JSON_DEPTH = 16;
341
+ const MAX_JSON_ARRAY_ITEMS = 10_000;
342
+ const MAX_JSON_OBJECT_FIELDS = 1_000;
343
+ const MAX_JSON_STRING_BYTES = 1 * 1_024 * 1_024;
344
+
345
+ function hasUnpairedSurrogate(value: string): boolean {
346
+ for (let index = 0; index < value.length; index += 1) {
347
+ const code = value.charCodeAt(index);
348
+ if (code >= 0xd800 && code <= 0xdbff) {
349
+ const next = value.charCodeAt(index + 1);
350
+ if (next < 0xdc00 || next > 0xdfff) return true;
351
+ index += 1;
352
+ } else if (code >= 0xdc00 && code <= 0xdfff) return true;
353
+ }
354
+ return false;
355
+ }
356
+
357
+ function boundedString(
358
+ value: unknown,
359
+ label: string,
360
+ maximumBytes = MAX_DESCRIPTOR_TEXT_BYTES,
361
+ ): string {
362
+ if (
363
+ typeof value !== "string"
364
+ || value.trim() === ""
365
+ || /[\0\r\n]/u.test(value)
366
+ || hasUnpairedSurrogate(value)
367
+ || value.normalize("NFC") !== value
368
+ || Buffer.byteLength(value, "utf8") > maximumBytes
369
+ ) throw new TypeError(`${label} must be a non-empty NFC single-line bounded string.`);
370
+ return value;
371
+ }
372
+
373
+ function plainRecord(value: unknown, label: string): UnknownRecord {
374
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
375
+ throw new TypeError(`${label} must be an object.`);
376
+ }
377
+ const prototype: unknown = Object.getPrototypeOf(value);
378
+ if (prototype !== Object.prototype && prototype !== null) {
379
+ throw new TypeError(`${label} must not inherit prototype capabilities.`);
380
+ }
381
+ return value as UnknownRecord;
382
+ }
383
+
384
+ function dataRecord(
385
+ value: unknown,
386
+ required: readonly string[],
387
+ optional: readonly string[],
388
+ label: string,
389
+ ): UnknownRecord {
390
+ const input = plainRecord(value, label);
391
+ const allowed = new Set([...required, ...optional]);
392
+ const seen = new Set<string>();
393
+ for (const key of Reflect.ownKeys(input)) {
394
+ if (typeof key === "symbol") throw new TypeError(`${label} must not contain symbol fields.`);
395
+ if (!allowed.has(key)) throw new TypeError(`${label} has unknown field ${key}.`);
396
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
397
+ if (descriptor === undefined || !descriptor.enumerable || !("value" in descriptor)) {
398
+ throw new TypeError(`${label}.${key} must be an enumerable data property.`);
399
+ }
400
+ seen.add(key);
401
+ }
402
+ for (const key of required) {
403
+ if (!seen.has(key)) throw new TypeError(`${label}.${key} is required.`);
404
+ }
405
+ return input;
406
+ }
407
+
408
+ function dynamicDataEntries(value: unknown, label: string): readonly (readonly [string, unknown])[] {
409
+ const input = plainRecord(value, label);
410
+ const output: Array<readonly [string, unknown]> = [];
411
+ for (const key of Reflect.ownKeys(input)) {
412
+ if (typeof key === "symbol") throw new TypeError(`${label} must not contain symbol fields.`);
413
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
414
+ if (descriptor === undefined || !descriptor.enumerable || !("value" in descriptor)) {
415
+ throw new TypeError(`${label}.${key} must be an enumerable data property.`);
416
+ }
417
+ output.push(Object.freeze([key, descriptor.value] as const));
418
+ }
419
+ return Object.freeze(output);
420
+ }
421
+
422
+ function ownData(value: unknown, key: string, label: string): unknown {
423
+ const input = plainRecord(value, label);
424
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
425
+ if (descriptor === undefined) return undefined;
426
+ if (!descriptor.enumerable || !("value" in descriptor)) {
427
+ throw new TypeError(`${label}.${key} must be an enumerable data property.`);
428
+ }
429
+ return descriptor.value;
430
+ }
431
+
432
+ function dataArray(value: unknown, label: string, maximum: number): readonly unknown[] {
433
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) {
434
+ throw new TypeError(`${label} must be a plain array.`);
435
+ }
436
+ if (value.length > maximum) throw new TypeError(`${label} may have at most ${maximum} entries.`);
437
+ const allowed = new Set(["length", ...Array.from({ length: value.length }, (_, index) => String(index))]);
438
+ for (const key of Reflect.ownKeys(value)) {
439
+ if (typeof key === "symbol") throw new TypeError(`${label} must not contain symbol fields.`);
440
+ if (!allowed.has(key)) throw new TypeError(`${label} has an unexpected array field ${key}.`);
441
+ }
442
+ const output: unknown[] = [];
443
+ for (let index = 0; index < value.length; index += 1) {
444
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
445
+ if (descriptor === undefined || !descriptor.enumerable || !("value" in descriptor)) {
446
+ throw new TypeError(`${label}[${index}] must be an enumerable data property.`);
447
+ }
448
+ output.push(descriptor.value);
449
+ }
450
+ return Object.freeze(output);
451
+ }
452
+
453
+ function positiveLimit(value: unknown, label: string): number {
454
+ if (
455
+ !Number.isSafeInteger(value)
456
+ || (value as number) < 1
457
+ || (value as number) > MAX_EXISTING_LANE_CLOSURE_RESULTS
458
+ ) throw new TypeError(`${label} must be an integer from 1 through ${MAX_EXISTING_LANE_CLOSURE_RESULTS}.`);
459
+ return value as number;
460
+ }
461
+
462
+ function nonnegativeInteger(value: unknown, label: string): number {
463
+ if (!Number.isSafeInteger(value) || (value as number) < 0) {
464
+ throw new TypeError(`${label} must be a non-negative safe integer.`);
465
+ }
466
+ return value as number;
467
+ }
468
+
469
+ function nonnegativeNumber(value: unknown, label: string): number {
470
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
471
+ throw new TypeError(`${label} must be a non-negative finite number.`);
472
+ }
473
+ return value;
474
+ }
475
+
476
+ function finiteNumber(value: unknown, label: string): number {
477
+ if (typeof value !== "number" || !Number.isFinite(value)) {
478
+ throw new TypeError(`${label} must be a finite number.`);
479
+ }
480
+ return value;
481
+ }
482
+
483
+ function boundedPositiveInteger(value: unknown, label: string, maximum = 1_000_000): number {
484
+ if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > maximum) {
485
+ throw new TypeError(`${label} must be an integer from 1 through ${maximum}.`);
486
+ }
487
+ return value as number;
488
+ }
489
+
490
+ function confinedPath(value: unknown, label: string, allowRoot = false): string {
491
+ const path = boundedString(value, label, 4_096);
492
+ if (allowRoot && path === ".") return path;
493
+ if (
494
+ path.startsWith("/")
495
+ || windowsAbsolutePattern.test(path)
496
+ || path.includes("\\")
497
+ || path.split("/").some((part) => part === "" || part === "." || part === "..")
498
+ ) throw new TypeError(`${label} must be a confined repository-relative path.`);
499
+ return path;
500
+ }
501
+
502
+ function checkedSum(values: readonly number[], label: string): number {
503
+ const total = values.reduce((sum, value) => sum + value, 0);
504
+ if (!Number.isSafeInteger(total)) throw new TypeError(`${label} exceeds the safe integer bound.`);
505
+ return total;
506
+ }
507
+
508
+ export function freezeExistingLaneClosureVariant(value: unknown): ExistingLaneClosureVariant {
509
+ const input = dataRecord(
510
+ value,
511
+ ["primary", "structuralLanes", "git", "outputLimit"],
512
+ [],
513
+ "existing-lane closure variant",
514
+ );
515
+ let primary: ExistingLaneClosureVariant["primary"];
516
+ if (input.primary === null) primary = null;
517
+ else {
518
+ const descriptor = dataRecord(
519
+ input.primary,
520
+ ["lane", "retrieveLimit", "retainLimit"],
521
+ [],
522
+ "existing-lane closure variant primary",
523
+ );
524
+ if (descriptor.lane !== "hybrid") throw new TypeError("Closure primary.lane must be hybrid.");
525
+ const retrieveLimit = positiveLimit(descriptor.retrieveLimit, "closure primary.retrieveLimit");
526
+ const retainLimit = positiveLimit(descriptor.retainLimit, "closure primary.retainLimit");
527
+ if (retainLimit > retrieveLimit) throw new TypeError("Closure primary.retainLimit may not exceed retrieveLimit.");
528
+ primary = Object.freeze({ lane: "hybrid", retrieveLimit, retainLimit });
529
+ }
530
+
531
+ const rawStructural = dataArray(input.structuralLanes, "closure structuralLanes", 3);
532
+ const seen = new Set<string>();
533
+ const structuralLanes = rawStructural.map((value, index) => {
534
+ const descriptor = dataRecord(value, ["lane", "limit"], [], `closure structuralLanes[${index}]`);
535
+ if (typeof descriptor.lane !== "string" || !structuralLaneIds.has(descriptor.lane)) {
536
+ throw new TypeError(`closure structuralLanes[${index}].lane must be metadata, graph, or path-context.`);
537
+ }
538
+ if (seen.has(descriptor.lane)) throw new TypeError("Closure structuralLanes must be unique.");
539
+ seen.add(descriptor.lane);
540
+ return Object.freeze({
541
+ lane: descriptor.lane as ExistingLaneClosureStructuralLaneId,
542
+ limit: positiveLimit(descriptor.limit, `closure structuralLanes[${index}].limit`),
543
+ });
544
+ });
545
+
546
+ const rawGit = plainRecord(input.git, "closure git");
547
+ const mode = ownData(rawGit, "mode", "closure git");
548
+ let git: ExistingLaneClosureVariant["git"];
549
+ if (mode === "off") {
550
+ dataRecord(rawGit, ["mode"], [], "closure git");
551
+ git = Object.freeze({ mode: "off" });
552
+ } else if (mode === "explicit-input") {
553
+ const descriptor = dataRecord(rawGit, ["mode", "limit"], [], "closure git");
554
+ git = Object.freeze({
555
+ mode: "explicit-input",
556
+ limit: positiveLimit(descriptor.limit, "closure git.limit"),
557
+ });
558
+ } else throw new TypeError("Closure git.mode must be off or explicit-input.");
559
+
560
+ const outputLimit = positiveLimit(input.outputLimit, "closure outputLimit");
561
+ const candidateCapacity = checkedSum([
562
+ primary?.retrieveLimit ?? 0,
563
+ ...structuralLanes.map(({ limit }) => limit),
564
+ git.mode === "explicit-input" ? git.limit : 0,
565
+ ], "Closure candidate capacity");
566
+ if (candidateCapacity > MAX_EXISTING_LANE_CLOSURE_TOTAL_CANDIDATES) {
567
+ throw new TypeError(
568
+ `Closure candidate capacity exceeds ${MAX_EXISTING_LANE_CLOSURE_TOTAL_CANDIDATES}.`,
569
+ );
570
+ }
571
+ return Object.freeze({
572
+ primary,
573
+ structuralLanes: Object.freeze(structuralLanes),
574
+ git,
575
+ outputLimit,
576
+ });
577
+ }
578
+
579
+ function parseStringArray(
580
+ value: unknown,
581
+ label: string,
582
+ maximum: number,
583
+ options: Readonly<{ readonly confined?: boolean; readonly allowEmpty?: boolean }> = {},
584
+ ): readonly string[] {
585
+ const entries = dataArray(value, label, maximum);
586
+ if (options.allowEmpty !== true && entries.length === 0) throw new TypeError(`${label} must not be empty.`);
587
+ const output = entries.map((entry, index) => options.confined === true
588
+ ? confinedPath(entry, `${label}[${index}]`)
589
+ : boundedString(entry, `${label}[${index}]`));
590
+ if (new Set(output).size !== output.length) throw new TypeError(`${label} must not repeat entries.`);
591
+ return Object.freeze(output);
592
+ }
593
+
594
+ function copyHybridInput(value: unknown): ExistingLaneClosureHybridInput {
595
+ const input = dataRecord(value, ["text"], [], "closure hybrid input");
596
+ return Object.freeze({ text: boundedString(input.text, "closure hybrid input.text") });
597
+ }
598
+
599
+ function copyMetadataInput(value: unknown): ExistingLaneClosureMetadataInput {
600
+ const input = dataRecord(value, ["filters", "tags"], [], "closure metadata input");
601
+ const rawFilters = dataArray(input.filters, "closure metadata input.filters", 32);
602
+ const filters = rawFilters.map((value, index): ExistingLaneClosureMetadataFilter => {
603
+ const label = `closure metadata input.filters[${index}]`;
604
+ const candidate = plainRecord(value, label);
605
+ const kind = ownData(candidate, "kind", label);
606
+ if (kind === "exists") {
607
+ const filter = dataRecord(candidate, ["kind", "path"], [], label);
608
+ return Object.freeze({ kind, path: boundedString(filter.path, `${label}.path`) });
609
+ }
610
+ if (kind === "equals") {
611
+ const filter = dataRecord(candidate, ["kind", "path", "value"], [], label);
612
+ const scalar = filter.value;
613
+ if (
614
+ scalar !== null
615
+ && typeof scalar !== "string"
616
+ && typeof scalar !== "boolean"
617
+ && (typeof scalar !== "number" || !Number.isFinite(scalar))
618
+ ) throw new TypeError(`${label}.value must be a finite scalar or null.`);
619
+ return Object.freeze({
620
+ kind,
621
+ path: boundedString(filter.path, `${label}.path`),
622
+ value: scalar,
623
+ });
624
+ }
625
+ throw new TypeError(`${label}.kind must be exists or equals.`);
626
+ });
627
+ const tags = parseStringArray(input.tags, "closure metadata input.tags", 32, { allowEmpty: true });
628
+ if (filters.length === 0 && tags.length === 0) {
629
+ throw new TypeError("Closure metadata input must contain a filter or tag.");
630
+ }
631
+ return Object.freeze({ filters: Object.freeze(filters), tags });
632
+ }
633
+
634
+ function copyGraphInput(value: unknown): ExistingLaneClosureGraphInput {
635
+ const input = dataRecord(value, ["seeds", "depth"], [], "closure graph input");
636
+ if (input.depth !== 1 && input.depth !== 2) throw new TypeError("Closure graph input.depth must be 1 or 2.");
637
+ return Object.freeze({
638
+ seeds: parseStringArray(input.seeds, "closure graph input.seeds", 10, { confined: true }),
639
+ depth: input.depth,
640
+ });
641
+ }
642
+
643
+ function copyPathContextInput(value: unknown): ExistingLaneClosurePathContextInput {
644
+ const input = dataRecord(value, ["repositoryPath"], [], "closure path-context input");
645
+ return Object.freeze({
646
+ repositoryPath: confinedPath(
647
+ input.repositoryPath,
648
+ "closure path-context input.repositoryPath",
649
+ true,
650
+ ),
651
+ });
652
+ }
653
+
654
+ function copyGitInput(value: unknown): ExistingLaneClosureGitInput {
655
+ const input = dataRecord(value, ["query", "noteIds"], [], "closure Git input");
656
+ return Object.freeze({
657
+ query: boundedString(input.query, "closure Git input.query"),
658
+ noteIds: parseStringArray(input.noteIds, "closure Git input.noteIds", 100, {
659
+ confined: true,
660
+ allowEmpty: true,
661
+ }),
662
+ });
663
+ }
664
+
665
+ function parseLocator(value: unknown, label: string): ExistingLaneClosureEvidenceLocator {
666
+ const input = dataRecord(value, [
667
+ "evidenceUnitId",
668
+ "documentId",
669
+ "sourceFamilyId",
670
+ "sourceClass",
671
+ "trustClass",
672
+ "sourcePath",
673
+ "lineRange",
674
+ "headingPath",
675
+ ], ["sourcePage"], label);
676
+ if (typeof input.sourceClass !== "string" || !sourceClasses.has(input.sourceClass as ExistingLaneClosureSourceClass)) {
677
+ throw new TypeError(`${label}.sourceClass is invalid.`);
678
+ }
679
+ if (typeof input.trustClass !== "string" || !trustClasses.has(input.trustClass as ExistingLaneClosureTrustClass)) {
680
+ throw new TypeError(`${label}.trustClass is invalid.`);
681
+ }
682
+ const sourceClass = input.sourceClass as ExistingLaneClosureSourceClass;
683
+ const trustClass = input.trustClass as ExistingLaneClosureTrustClass;
684
+ if (!sourceTrustCompatibility[sourceClass].has(trustClass)) {
685
+ throw new TypeError(`${label} sourceClass and trustClass are incompatible.`);
686
+ }
687
+ const rawRange = dataRecord(input.lineRange, ["start", "end"], [], `${label}.lineRange`);
688
+ const start = boundedPositiveInteger(rawRange.start, `${label}.lineRange.start`);
689
+ const end = boundedPositiveInteger(rawRange.end, `${label}.lineRange.end`);
690
+ if (end < start) throw new TypeError(`${label}.lineRange.end may not precede start.`);
691
+ const sourcePage = input.sourcePage === undefined
692
+ ? undefined
693
+ : boundedPositiveInteger(input.sourcePage, `${label}.sourcePage`);
694
+ return Object.freeze({
695
+ evidenceUnitId: boundedString(input.evidenceUnitId, `${label}.evidenceUnitId`, 512),
696
+ documentId: confinedPath(input.documentId, `${label}.documentId`),
697
+ sourceFamilyId: boundedString(input.sourceFamilyId, `${label}.sourceFamilyId`, 512),
698
+ sourceClass,
699
+ trustClass,
700
+ sourcePath: confinedPath(input.sourcePath, `${label}.sourcePath`),
701
+ lineRange: Object.freeze({ start, end }),
702
+ headingPath: parseStringArray(input.headingPath, `${label}.headingPath`, 32, { allowEmpty: true }),
703
+ ...(sourcePage === undefined ? {} : { sourcePage }),
704
+ });
705
+ }
706
+
707
+ function locatorKey(locator: ExistingLaneClosureEvidenceLocator): string {
708
+ return JSON.stringify([
709
+ locator.evidenceUnitId,
710
+ locator.documentId,
711
+ locator.sourceFamilyId,
712
+ locator.sourceClass,
713
+ locator.trustClass,
714
+ locator.sourcePath,
715
+ locator.lineRange.start,
716
+ locator.lineRange.end,
717
+ locator.headingPath,
718
+ locator.sourcePage ?? null,
719
+ ]);
720
+ }
721
+
722
+ export function freezeExistingLaneClosureEvidenceRegistry(
723
+ value: unknown,
724
+ ): ExistingLaneClosureEvidenceRegistry {
725
+ const input = dataRecord(value, ["units"], [], "existing-lane closure evidence registry");
726
+ const rawUnits = dataArray(
727
+ input.units,
728
+ "existing-lane closure evidence registry.units",
729
+ MAX_EXISTING_LANE_CLOSURE_TOTAL_CANDIDATES * MAX_EXISTING_LANE_CLOSURE_EVIDENCE_UNITS,
730
+ );
731
+ const ids = new Set<string>();
732
+ const units = rawUnits.map((unit, index) => {
733
+ const parsed = parseLocator(unit, `existing-lane closure evidence registry.units[${index}]`);
734
+ if (ids.has(parsed.evidenceUnitId)) {
735
+ throw new TypeError(`Closure evidence registry repeats unit ${parsed.evidenceUnitId}.`);
736
+ }
737
+ ids.add(parsed.evidenceUnitId);
738
+ return parsed;
739
+ });
740
+ return Object.freeze({ units: Object.freeze(units) });
741
+ }
742
+
743
+ function parseBackend<Input>(value: unknown, lane: ExistingLaneClosureLaneId): ExistingLaneClosureBackend<Input> {
744
+ const input = dataRecord(value, ["retrieve"], [], `closure ${lane} backend`);
745
+ if (typeof input.retrieve !== "function") throw new TypeError(`Closure ${lane} backend.retrieve must be a function.`);
746
+ return Object.freeze({
747
+ retrieve: input.retrieve as ExistingLaneClosureBackend<Input>["retrieve"],
748
+ });
749
+ }
750
+
751
+ function invokedLane<Input>(options: Readonly<{
752
+ readonly lane: ExistingLaneClosureLaneId;
753
+ readonly limit: number;
754
+ readonly retainLimit?: number;
755
+ readonly input: Input;
756
+ readonly backend: ExistingLaneClosureBackend<Input>;
757
+ readonly signal: AbortSignal;
758
+ }>): PreparedLane {
759
+ const laneRequest = Object.freeze({ input: options.input, limit: options.limit, signal: options.signal });
760
+ return Object.freeze({
761
+ kind: "invoke",
762
+ lane: options.lane,
763
+ limit: options.limit,
764
+ ...(options.retainLimit === undefined ? {} : { retainLimit: options.retainLimit }),
765
+ invoke: () => options.backend.retrieve(laneRequest),
766
+ });
767
+ }
768
+
769
+ function prepareLanes(
770
+ variant: ExistingLaneClosureVariant,
771
+ query: ExistingLaneClosureQuery,
772
+ backends: ExistingLaneClosureBackends,
773
+ signal: AbortSignal,
774
+ ): readonly PreparedLane[] {
775
+ const rawInputs = ownData(query, "inputs", "existing-lane closure query");
776
+ const inputs = plainRecord(rawInputs, "existing-lane closure query.inputs");
777
+ const lanes: PreparedLane[] = [];
778
+ const prepare = <Input>(options: Readonly<{
779
+ readonly lane: ExistingLaneClosureLaneId;
780
+ readonly inputKey: string;
781
+ readonly backendKey: string;
782
+ readonly limit: number;
783
+ readonly retainLimit?: number;
784
+ readonly copy: (value: unknown) => Input;
785
+ }>): void => {
786
+ const rawInput = ownData(inputs, options.inputKey, "existing-lane closure query.inputs");
787
+ if (rawInput === undefined) {
788
+ lanes.push(Object.freeze({ kind: "missing", lane: options.lane, limit: options.limit }));
789
+ return;
790
+ }
791
+ const input = options.copy(rawInput);
792
+ const rawBackend = ownData(backends, options.backendKey, "existing-lane closure backends");
793
+ lanes.push(invokedLane({
794
+ lane: options.lane,
795
+ limit: options.limit,
796
+ ...(options.retainLimit === undefined ? {} : { retainLimit: options.retainLimit }),
797
+ input,
798
+ backend: parseBackend<Input>(rawBackend, options.lane),
799
+ signal,
800
+ }));
801
+ };
802
+
803
+ if (variant.primary === null) lanes.push(Object.freeze({ kind: "disabled", lane: "hybrid" }));
804
+ else prepare({
805
+ lane: "hybrid",
806
+ inputKey: "hybrid",
807
+ backendKey: "hybrid",
808
+ limit: variant.primary.retrieveLimit,
809
+ retainLimit: variant.primary.retainLimit,
810
+ copy: copyHybridInput,
811
+ });
812
+
813
+ for (const descriptor of variant.structuralLanes) {
814
+ if (descriptor.lane === "metadata") prepare({
815
+ lane: "metadata",
816
+ inputKey: "metadata",
817
+ backendKey: "metadata",
818
+ limit: descriptor.limit,
819
+ copy: copyMetadataInput,
820
+ });
821
+ else if (descriptor.lane === "graph") prepare({
822
+ lane: "graph",
823
+ inputKey: "graph",
824
+ backendKey: "graph",
825
+ limit: descriptor.limit,
826
+ copy: copyGraphInput,
827
+ });
828
+ else prepare({
829
+ lane: "path-context",
830
+ inputKey: "pathContext",
831
+ backendKey: "pathContext",
832
+ limit: descriptor.limit,
833
+ copy: copyPathContextInput,
834
+ });
835
+ }
836
+
837
+ if (variant.git.mode === "off") lanes.push(Object.freeze({ kind: "disabled", lane: "git" }));
838
+ else prepare({
839
+ lane: "git",
840
+ inputKey: "history",
841
+ backendKey: "git",
842
+ limit: variant.git.limit,
843
+ copy: copyGitInput,
844
+ });
845
+ return Object.freeze(lanes);
846
+ }
847
+
848
+ function copyJsonValue(
849
+ value: unknown,
850
+ label: string,
851
+ depth = 0,
852
+ ancestors = new WeakSet<object>(),
853
+ ): unknown {
854
+ if (value === null || typeof value === "boolean") return value;
855
+ if (typeof value === "number") {
856
+ if (!Number.isFinite(value)) throw new TypeError(`${label} numbers must be finite.`);
857
+ return value;
858
+ }
859
+ if (typeof value === "string") {
860
+ if (hasUnpairedSurrogate(value) || Buffer.byteLength(value, "utf8") > MAX_JSON_STRING_BYTES) {
861
+ throw new TypeError(`${label} strings must be bounded valid Unicode.`);
862
+ }
863
+ return value;
864
+ }
865
+ if (typeof value !== "object" || value === undefined) {
866
+ throw new TypeError(`${label} must contain only JSON values.`);
867
+ }
868
+ if (depth >= MAX_JSON_DEPTH) throw new TypeError(`${label} exceeds the JSON depth bound.`);
869
+ if (ancestors.has(value)) throw new TypeError(`${label} must not contain cycles.`);
870
+ ancestors.add(value);
871
+ try {
872
+ if (Array.isArray(value)) {
873
+ const entries = dataArray(value, label, MAX_JSON_ARRAY_ITEMS);
874
+ return Object.freeze(entries.map((entry, index) =>
875
+ copyJsonValue(entry, `${label}[${index}]`, depth + 1, ancestors)));
876
+ }
877
+ const entries = dynamicDataEntries(value, label);
878
+ if (entries.length > MAX_JSON_OBJECT_FIELDS) {
879
+ throw new TypeError(`${label} exceeds the JSON object-field bound.`);
880
+ }
881
+ const output: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
882
+ for (const [key, entry] of entries.toSorted(([left], [right]) => left.localeCompare(right))) {
883
+ if (hasUnpairedSurrogate(key) || Buffer.byteLength(key, "utf8") > MAX_DESCRIPTOR_TEXT_BYTES) {
884
+ throw new TypeError(`${label} has an invalid JSON field name.`);
885
+ }
886
+ output[key] = copyJsonValue(entry, `${label}.${key}`, depth + 1, ancestors);
887
+ }
888
+ return Object.freeze(output);
889
+ } finally {
890
+ ancestors.delete(value);
891
+ }
892
+ }
893
+
894
+ function parseMetricMap(value: unknown, label: string): Readonly<Record<string, number>> {
895
+ if (value === undefined) return Object.freeze({});
896
+ const entries = dynamicDataEntries(value, label);
897
+ if (entries.length > MAX_METRICS_PER_LANE) throw new TypeError(`${label} has too many entries.`);
898
+ const output: Record<string, number> = {};
899
+ for (const [key, candidate] of entries.toSorted(([left], [right]) => left.localeCompare(right))) {
900
+ if (!metricKeyPattern.test(key)) throw new TypeError(`${label} has invalid key ${JSON.stringify(key)}.`);
901
+ output[key] = nonnegativeNumber(candidate, `${label}.${key}`);
902
+ }
903
+ return Object.freeze(output);
904
+ }
905
+
906
+ function parseAccounting(value: unknown, label: string): ExistingLaneClosureAccounting {
907
+ const input = dataRecord(
908
+ value,
909
+ ["llm", "embedding", "packedContext", "peakRssBytes", "cacheBytes"],
910
+ [],
911
+ label,
912
+ );
913
+ const llm = dataRecord(input.llm, ["calls", "inputTokens", "outputTokens"], [], `${label}.llm`);
914
+ if (llm.calls !== 0 || llm.inputTokens !== 0 || llm.outputTokens !== 0) {
915
+ throw new TypeError(`${label}.llm requires literal-zero calls, inputTokens, and outputTokens.`);
916
+ }
917
+ const embedding = dataRecord(
918
+ input.embedding,
919
+ ["calls", "inputTokens", "durationMs"],
920
+ ["inputTokensMeasured", "durationScope"],
921
+ `${label}.embedding`,
922
+ );
923
+ const packedContext = dataRecord(
924
+ input.packedContext,
925
+ ["utf8Bytes", "readerTokens"],
926
+ [],
927
+ `${label}.packedContext`,
928
+ );
929
+ const embeddingCalls = nonnegativeInteger(embedding.calls, `${label}.embedding.calls`);
930
+ const embeddingInputTokens = nonnegativeInteger(
931
+ embedding.inputTokens,
932
+ `${label}.embedding.inputTokens`,
933
+ );
934
+ const embeddingDurationMs = nonnegativeNumber(
935
+ embedding.durationMs,
936
+ `${label}.embedding.durationMs`,
937
+ );
938
+ if (Object.hasOwn(embedding, "inputTokensMeasured") && embedding.inputTokensMeasured !== false) {
939
+ throw new TypeError(`${label}.embedding.inputTokensMeasured must be literal false when present.`);
940
+ }
941
+ const durationScopeValue = embedding.durationScope;
942
+ if (
943
+ Object.hasOwn(embedding, "durationScope")
944
+ && durationScopeValue !== "embedding-backed-search-upper-bound"
945
+ ) {
946
+ throw new TypeError(
947
+ `${label}.embedding.durationScope must be embedding-backed-search-upper-bound when present.`,
948
+ );
949
+ }
950
+ const durationScope: ExistingLaneClosureAccounting["embedding"]["durationScope"] =
951
+ durationScopeValue === "embedding-backed-search-upper-bound"
952
+ ? durationScopeValue
953
+ : undefined;
954
+ if (embeddingCalls === 0) {
955
+ if (
956
+ embeddingInputTokens !== 0
957
+ || embeddingDurationMs !== 0
958
+ || embedding.inputTokensMeasured !== undefined
959
+ || durationScope !== undefined
960
+ ) throw new TypeError(`${label}.embedding zero-call accounting must be the exact unannotated zero record.`);
961
+ } else if (embedding.inputTokensMeasured === false && embeddingInputTokens !== 0) {
962
+ throw new TypeError(
963
+ `${label}.embedding unmeasured input tokens must use zero only as an explicit placeholder.`,
964
+ );
965
+ }
966
+ return Object.freeze({
967
+ llm: Object.freeze({ calls: 0, inputTokens: 0, outputTokens: 0 }),
968
+ embedding: Object.freeze({
969
+ calls: embeddingCalls,
970
+ inputTokens: embeddingInputTokens,
971
+ ...(embedding.inputTokensMeasured === false ? { inputTokensMeasured: false as const } : {}),
972
+ durationMs: embeddingDurationMs,
973
+ ...(durationScope === undefined ? {} : { durationScope }),
974
+ }),
975
+ packedContext: Object.freeze({
976
+ utf8Bytes: nonnegativeInteger(packedContext.utf8Bytes, `${label}.packedContext.utf8Bytes`),
977
+ readerTokens: nonnegativeInteger(packedContext.readerTokens, `${label}.packedContext.readerTokens`),
978
+ }),
979
+ peakRssBytes: nonnegativeInteger(input.peakRssBytes, `${label}.peakRssBytes`),
980
+ cacheBytes: nonnegativeInteger(input.cacheBytes, `${label}.cacheBytes`),
981
+ });
982
+ }
983
+
984
+ function copyDiagnostic(value: unknown, label: string): ExistingLaneClosureDiagnostic {
985
+ const input = dataRecord(value, ["code", "status"], ["message", "details"], label);
986
+ if (input.status !== "ready" && input.status !== "degraded" && input.status !== "unavailable") {
987
+ throw new TypeError(`${label}.status is invalid.`);
988
+ }
989
+ let details: Readonly<Record<string, string | number | boolean | null>> | undefined;
990
+ if (input.details !== undefined) {
991
+ const entries = dynamicDataEntries(input.details, `${label}.details`);
992
+ if (entries.length > 32) throw new TypeError(`${label}.details has too many entries.`);
993
+ const output: Record<string, string | number | boolean | null> = {};
994
+ for (const [key, candidate] of entries.toSorted(([left], [right]) => left.localeCompare(right))) {
995
+ boundedString(key, `${label}.details key`, 256);
996
+ if (
997
+ candidate !== null
998
+ && typeof candidate !== "string"
999
+ && typeof candidate !== "boolean"
1000
+ && (typeof candidate !== "number" || !Number.isFinite(candidate))
1001
+ ) throw new TypeError(`${label}.details.${key} must be a finite scalar or null.`);
1002
+ output[key] = candidate;
1003
+ }
1004
+ details = Object.freeze(output);
1005
+ }
1006
+ return Object.freeze({
1007
+ code: boundedString(input.code, `${label}.code`, 256),
1008
+ status: input.status,
1009
+ ...(input.message === undefined ? {} : {
1010
+ message: boundedString(input.message, `${label}.message`),
1011
+ }),
1012
+ ...(details === undefined ? {} : { details }),
1013
+ });
1014
+ }
1015
+
1016
+ function copyHit(
1017
+ value: unknown,
1018
+ label: string,
1019
+ registry: ReadonlyMap<string, ExistingLaneClosureEvidenceLocator>,
1020
+ lane: ExistingLaneClosureLaneId,
1021
+ ): Readonly<{
1022
+ readonly hit: ExistingLaneClosureHit;
1023
+ readonly evidenceUnitCount: number;
1024
+ readonly provenanceBytes: number;
1025
+ readonly evidenceBytes: number;
1026
+ }> {
1027
+ const input = dataRecord(
1028
+ value,
1029
+ ["documentId", "canonicalDocumentId", "rank"],
1030
+ ["score", "evidenceUnits", "evidence"],
1031
+ label,
1032
+ );
1033
+ const documentId = confinedPath(input.documentId, `${label}.documentId`);
1034
+ const canonicalDocumentId = confinedPath(input.canonicalDocumentId, `${label}.canonicalDocumentId`);
1035
+ const rank = positiveLimit(input.rank, `${label}.rank`);
1036
+ const score = input.score === undefined ? undefined : finiteNumber(input.score, `${label}.score`);
1037
+ let evidenceUnits: readonly ExistingLaneClosureEvidenceUnit[] | undefined;
1038
+ let provenanceBytes = 0;
1039
+ if (input.evidenceUnits !== undefined) {
1040
+ const rawUnits = dataArray(
1041
+ input.evidenceUnits,
1042
+ `${label}.evidenceUnits`,
1043
+ MAX_EXISTING_LANE_CLOSURE_EVIDENCE_UNITS,
1044
+ );
1045
+ const ids = new Set<string>();
1046
+ evidenceUnits = Object.freeze(rawUnits.map((value, index) => {
1047
+ const unitLabel = `${label}.evidenceUnits[${index}]`;
1048
+ const rawUnit = dataRecord(value, ["id", "locator"], [], unitLabel);
1049
+ const id = boundedString(rawUnit.id, `${unitLabel}.id`, 512);
1050
+ if (ids.has(id)) throw new TypeError(`${label}.evidenceUnits must not repeat IDs.`);
1051
+ ids.add(id);
1052
+ const parsedLocator = parseLocator(rawUnit.locator, `${unitLabel}.locator`);
1053
+ if (parsedLocator.evidenceUnitId !== id) {
1054
+ throw new TypeError(`${unitLabel} must pair its ID with the same locator evidenceUnitId.`);
1055
+ }
1056
+ const bound = registry.get(id);
1057
+ if (bound === undefined || locatorKey(bound) !== locatorKey(parsedLocator)) {
1058
+ throw new TypeError(`${unitLabel}.locator does not exactly match the frozen registry binding.`);
1059
+ }
1060
+ if (bound.documentId !== canonicalDocumentId && lane !== "graph") {
1061
+ throw new TypeError(`${unitLabel}.locator belongs to a different canonical document.`);
1062
+ }
1063
+ provenanceBytes += Buffer.byteLength(locatorKey(bound), "utf8");
1064
+ return Object.freeze({ id, locator: bound });
1065
+ }));
1066
+ }
1067
+ const evidence = input.evidence === undefined
1068
+ ? undefined
1069
+ : copyJsonValue(input.evidence, `${label}.evidence`);
1070
+ const evidenceBytes = evidence === undefined
1071
+ ? 0
1072
+ : Buffer.byteLength(JSON.stringify(evidence), "utf8");
1073
+ const hit: ExistingLaneClosureHit = Object.freeze({
1074
+ documentId,
1075
+ canonicalDocumentId,
1076
+ rank,
1077
+ ...(score === undefined ? {} : { score }),
1078
+ ...(evidenceUnits === undefined ? {} : { evidenceUnits }),
1079
+ ...(evidence === undefined ? {} : { evidence }),
1080
+ });
1081
+ return Object.freeze({
1082
+ hit,
1083
+ evidenceUnitCount: evidenceUnits?.length ?? 0,
1084
+ provenanceBytes,
1085
+ evidenceBytes,
1086
+ });
1087
+ }
1088
+
1089
+ function validateLaneResult(
1090
+ value: unknown,
1091
+ lane: ExistingLaneClosureLaneId,
1092
+ limit: number,
1093
+ registry: ReadonlyMap<string, ExistingLaneClosureEvidenceLocator>,
1094
+ ): ValidatedLaneResult {
1095
+ const input = dataRecord(
1096
+ value,
1097
+ ["status", "hits", "accounting"],
1098
+ ["diagnostics", "timings", "resources"],
1099
+ `closure ${lane} result`,
1100
+ );
1101
+ if (input.status !== "ready" && input.status !== "degraded" && input.status !== "unavailable") {
1102
+ throw new TypeError(`Closure ${lane} result.status is invalid.`);
1103
+ }
1104
+ const rawHits = dataArray(input.hits, `closure ${lane} result.hits`, limit);
1105
+ const copied = rawHits.map((hit, index) =>
1106
+ copyHit(hit, `closure ${lane} result.hits[${index}]`, registry, lane));
1107
+ const ranks = copied.map(({ hit }) => hit.rank);
1108
+ if (new Set(ranks).size !== ranks.length) throw new TypeError(`Closure ${lane} result ranks must be unique.`);
1109
+ if (input.status === "unavailable" && copied.length > 0) {
1110
+ throw new TypeError(`Closure ${lane} unavailable results may not contain hits.`);
1111
+ }
1112
+ const rawDiagnostics = input.diagnostics === undefined
1113
+ ? Object.freeze([])
1114
+ : dataArray(
1115
+ input.diagnostics,
1116
+ `closure ${lane} result.diagnostics`,
1117
+ MAX_EXISTING_LANE_CLOSURE_DIAGNOSTICS,
1118
+ );
1119
+ return Object.freeze({
1120
+ status: input.status,
1121
+ hits: Object.freeze(copied.map(({ hit }) => hit).toSorted((left, right) => left.rank - right.rank)),
1122
+ diagnostics: Object.freeze(rawDiagnostics.map((diagnostic, index) =>
1123
+ copyDiagnostic(diagnostic, `closure ${lane} result.diagnostics[${index}]`))),
1124
+ timings: parseMetricMap(input.timings, `closure ${lane} result.timings`),
1125
+ resources: parseMetricMap(input.resources, `closure ${lane} result.resources`),
1126
+ accounting: parseAccounting(input.accounting, `closure ${lane} result.accounting`),
1127
+ evidenceUnitCount: copied.reduce((total, candidate) => total + candidate.evidenceUnitCount, 0),
1128
+ provenanceBytes: copied.reduce((total, candidate) => total + candidate.provenanceBytes, 0),
1129
+ evidenceBytes: copied.reduce((total, candidate) => total + candidate.evidenceBytes, 0),
1130
+ });
1131
+ }
1132
+
1133
+ function aggregateAccounting(
1134
+ values: readonly ExistingLaneClosureAccounting[],
1135
+ ): ExistingLaneClosureAccounting {
1136
+ const durationMs = values.reduce((total, value) => total + value.embedding.durationMs, 0);
1137
+ if (!Number.isFinite(durationMs)) throw new TypeError("Closure embedding duration exceeds its finite bound.");
1138
+ const inputTokensMeasured = values.some(({ embedding }) => embedding.inputTokensMeasured === false)
1139
+ ? false as const
1140
+ : undefined;
1141
+ const durationScope = values.some(
1142
+ ({ embedding }) => embedding.durationScope === "embedding-backed-search-upper-bound",
1143
+ ) ? "embedding-backed-search-upper-bound" as const : undefined;
1144
+ const cacheValues = new Set(values.map(({ cacheBytes }) => cacheBytes));
1145
+ if (cacheValues.size > 1) {
1146
+ throw new TypeError("Closure lanes must report one identical shared-cache byte count.");
1147
+ }
1148
+ return Object.freeze({
1149
+ llm: Object.freeze({ calls: 0, inputTokens: 0, outputTokens: 0 }),
1150
+ embedding: Object.freeze({
1151
+ calls: checkedSum(values.map(({ embedding }) => embedding.calls), "Closure embedding calls"),
1152
+ inputTokens: inputTokensMeasured === false
1153
+ ? 0
1154
+ : checkedSum(
1155
+ values.map(({ embedding }) => embedding.inputTokens),
1156
+ "Closure embedding input tokens",
1157
+ ),
1158
+ ...(inputTokensMeasured === false ? { inputTokensMeasured } : {}),
1159
+ durationMs,
1160
+ ...(durationScope === undefined ? {} : { durationScope }),
1161
+ }),
1162
+ packedContext: Object.freeze({
1163
+ utf8Bytes: checkedSum(
1164
+ values.map(({ packedContext }) => packedContext.utf8Bytes),
1165
+ "Closure packed-context bytes",
1166
+ ),
1167
+ readerTokens: checkedSum(
1168
+ values.map(({ packedContext }) => packedContext.readerTokens),
1169
+ "Closure packed-context reader tokens",
1170
+ ),
1171
+ }),
1172
+ peakRssBytes: Math.max(0, ...values.map(({ peakRssBytes }) => peakRssBytes)),
1173
+ cacheBytes: values[0]?.cacheBytes ?? 0,
1174
+ });
1175
+ }
1176
+
1177
+ function throwIfAborted(signal: AbortSignal): void {
1178
+ if (!signal.aborted) return;
1179
+ if (signal.reason instanceof Error) throw signal.reason;
1180
+ throw new Error("Existing-lane closure was aborted.");
1181
+ }
1182
+
1183
+ function evidenceTrace(hit: ExistingLaneClosureHit): ExistingLaneClosureEvidenceTrace {
1184
+ const evidenceUnits = hit.evidenceUnits ?? Object.freeze([]);
1185
+ return Object.freeze({
1186
+ evidenceUnits,
1187
+ evidenceUnitIds: Object.freeze(evidenceUnits.map(({ id }) => id)),
1188
+ provenance: Object.freeze(evidenceUnits.map(({ locator }) => locator)),
1189
+ ...(hit.evidence === undefined ? {} : { evidence: hit.evidence }),
1190
+ });
1191
+ }
1192
+
1193
+ function sourceTrace(
1194
+ lane: ExistingLaneClosureLaneId,
1195
+ hit: ExistingLaneClosureHit,
1196
+ evidence: ExistingLaneClosureEvidenceTrace,
1197
+ ): ExistingLaneClosureSourceTrace {
1198
+ return Object.freeze({ lane, sourceRank: hit.rank, ...evidence });
1199
+ }
1200
+
1201
+ export async function runExistingLaneClosure(
1202
+ request: RunExistingLaneClosureRequest,
1203
+ ): Promise<ExistingLaneClosureResult> {
1204
+ const variant = freezeExistingLaneClosureVariant(request.variant);
1205
+ const evidenceRegistry = freezeExistingLaneClosureEvidenceRegistry(request.evidenceRegistry);
1206
+ const registryById = new Map(evidenceRegistry.units.map((unit) => [unit.evidenceUnitId, unit]));
1207
+ const lanes = prepareLanes(variant, request.query, request.backends, request.signal);
1208
+ throwIfAborted(request.signal);
1209
+
1210
+ const completed: CompletedLane[] = [];
1211
+ const timings: Record<string, number> = {};
1212
+ const resources: Record<string, number> = {};
1213
+ const invokedAccounting: ExistingLaneClosureAccounting[] = [];
1214
+ let totalCandidates = 0;
1215
+ let totalEvidenceUnits = 0;
1216
+ let totalProvenanceBytes = 0;
1217
+ let totalEvidenceBytes = 0;
1218
+
1219
+ for (const lane of lanes) {
1220
+ throwIfAborted(request.signal);
1221
+ if (lane.kind !== "invoke") {
1222
+ completed.push(lane);
1223
+ continue;
1224
+ }
1225
+ const result = validateLaneResult(
1226
+ await lane.invoke(),
1227
+ lane.lane,
1228
+ lane.limit,
1229
+ registryById,
1230
+ );
1231
+ throwIfAborted(request.signal);
1232
+ totalCandidates += result.hits.length;
1233
+ totalEvidenceUnits += result.evidenceUnitCount;
1234
+ totalProvenanceBytes += result.provenanceBytes;
1235
+ totalEvidenceBytes += result.evidenceBytes;
1236
+ if (totalCandidates > MAX_EXISTING_LANE_CLOSURE_TOTAL_CANDIDATES) {
1237
+ throw new TypeError("Closure results exceed the aggregate candidate bound.");
1238
+ }
1239
+ if (totalEvidenceUnits > MAX_EXISTING_LANE_CLOSURE_TOTAL_EVIDENCE_UNITS) {
1240
+ throw new TypeError("Closure results exceed the aggregate evidence-unit bound.");
1241
+ }
1242
+ if (totalProvenanceBytes > MAX_EXISTING_LANE_CLOSURE_PROVENANCE_BYTES) {
1243
+ throw new TypeError("Closure results exceed the aggregate provenance-byte bound.");
1244
+ }
1245
+ if (totalEvidenceBytes > MAX_EXISTING_LANE_CLOSURE_EVIDENCE_BYTES) {
1246
+ throw new TypeError("Closure results exceed the aggregate opaque-evidence byte bound.");
1247
+ }
1248
+ for (const [key, value] of Object.entries(result.timings)) timings[`${lane.lane}.${key}`] = value;
1249
+ for (const [key, value] of Object.entries(result.resources)) resources[`${lane.lane}.${key}`] = value;
1250
+ invokedAccounting.push(result.accounting);
1251
+ completed.push(Object.freeze({
1252
+ kind: "complete",
1253
+ lane: lane.lane,
1254
+ limit: lane.limit,
1255
+ ...(lane.retainLimit === undefined ? {} : { retainLimit: lane.retainLimit }),
1256
+ result,
1257
+ }));
1258
+ }
1259
+
1260
+ const outputHits: ExistingLaneClosureHit[] = [];
1261
+ const laneOutcomes: ExistingLaneClosureLaneOutcome[] = [];
1262
+ const documentOrder: MutableDocumentTrace[] = [];
1263
+ const documentsById = new Map<string, MutableDocumentTrace>();
1264
+ const invokedStatuses: ExistingLaneClosureLaneResult["status"][] = [];
1265
+ let missingProvenance = false;
1266
+
1267
+ type MergeState = {
1268
+ readonly lane: Extract<CompletedLane, { readonly kind: "complete" }>;
1269
+ readonly candidateTraces: ExistingLaneClosureCandidateTrace[];
1270
+ accepted: number;
1271
+ };
1272
+ const mergeStates = new Map<ExistingLaneClosureLaneId, MergeState>();
1273
+ for (const lane of completed) {
1274
+ if (lane.kind !== "complete") continue;
1275
+ invokedStatuses.push(lane.result.status);
1276
+ mergeStates.set(lane.lane, { lane, candidateTraces: [], accepted: 0 });
1277
+ }
1278
+
1279
+ const mergeCandidate = (state: MergeState, sourceIndex: number): void => {
1280
+ const { lane } = state;
1281
+ const hit = lane.result.hits[sourceIndex];
1282
+ if (hit === undefined) return;
1283
+ const evidence = evidenceTrace(hit);
1284
+ const existing = documentsById.get(hit.canonicalDocumentId);
1285
+ let reasonCode: ExistingLaneClosureReasonCode;
1286
+ let outputRank: number | undefined;
1287
+ let decision: ExistingLaneClosureCandidateTrace["decision"];
1288
+ if (evidence.evidenceUnits.length === 0) {
1289
+ reasonCode = "missing-provenance";
1290
+ decision = "excluded";
1291
+ missingProvenance = true;
1292
+ } else if (
1293
+ lane.lane === "hybrid"
1294
+ && lane.retainLimit !== undefined
1295
+ && sourceIndex >= lane.retainLimit
1296
+ ) {
1297
+ reasonCode = "primary-retain-limit";
1298
+ decision = "excluded";
1299
+ } else if (existing !== undefined) {
1300
+ reasonCode = "deduplicated";
1301
+ decision = "excluded";
1302
+ outputRank = existing.outputRank;
1303
+ existing.sources.push(sourceTrace(lane.lane, hit, evidence));
1304
+ } else if (outputHits.length >= variant.outputLimit) {
1305
+ reasonCode = "output-limit";
1306
+ decision = "excluded";
1307
+ } else {
1308
+ reasonCode = lane.lane === "hybrid" ? "primary" : "appended";
1309
+ decision = "accepted";
1310
+ outputHits.push(hit);
1311
+ outputRank = outputHits.length;
1312
+ state.accepted += 1;
1313
+ const document: MutableDocumentTrace = {
1314
+ documentId: hit.documentId,
1315
+ canonicalDocumentId: hit.canonicalDocumentId,
1316
+ outputRank,
1317
+ sources: [sourceTrace(lane.lane, hit, evidence)],
1318
+ };
1319
+ documentOrder.push(document);
1320
+ documentsById.set(hit.canonicalDocumentId, document);
1321
+ }
1322
+ state.candidateTraces.push(Object.freeze({
1323
+ lane: lane.lane,
1324
+ decision,
1325
+ reasonCode,
1326
+ documentId: hit.documentId,
1327
+ canonicalDocumentId: hit.canonicalDocumentId,
1328
+ sourceRank: hit.rank,
1329
+ ...evidence,
1330
+ ...(outputRank === undefined ? {} : { outputRank }),
1331
+ }));
1332
+ };
1333
+
1334
+ const primary = mergeStates.get("hybrid");
1335
+ if (primary !== undefined) {
1336
+ for (const sourceIndex of primary.lane.result.hits.keys()) {
1337
+ mergeCandidate(primary, sourceIndex);
1338
+ }
1339
+ }
1340
+ const appended = completed
1341
+ .filter((lane): lane is Extract<CompletedLane, { readonly kind: "complete" }> =>
1342
+ lane.kind === "complete" && lane.lane !== "hybrid")
1343
+ .map((lane) => mergeStates.get(lane.lane))
1344
+ .filter((state): state is MergeState => state !== undefined);
1345
+ for (let sourceIndex = 0; ; sourceIndex += 1) {
1346
+ let visited = false;
1347
+ for (const state of appended) {
1348
+ if (state.lane.result.hits[sourceIndex] === undefined) continue;
1349
+ visited = true;
1350
+ mergeCandidate(state, sourceIndex);
1351
+ }
1352
+ if (!visited) break;
1353
+ }
1354
+
1355
+ for (const lane of completed) {
1356
+ if (lane.kind === "disabled") {
1357
+ laneOutcomes.push(Object.freeze({
1358
+ lane: lane.lane,
1359
+ invocation: "disabled",
1360
+ status: "skipped",
1361
+ diagnostics: Object.freeze([]),
1362
+ returned: 0,
1363
+ accepted: 0,
1364
+ excluded: 0,
1365
+ candidates: Object.freeze([]),
1366
+ }));
1367
+ continue;
1368
+ }
1369
+ if (lane.kind === "missing") {
1370
+ laneOutcomes.push(Object.freeze({
1371
+ lane: lane.lane,
1372
+ invocation: "skipped-missing-input",
1373
+ status: "skipped",
1374
+ limit: lane.limit,
1375
+ diagnostics: Object.freeze([]),
1376
+ returned: 0,
1377
+ accepted: 0,
1378
+ excluded: 0,
1379
+ candidates: Object.freeze([]),
1380
+ }));
1381
+ continue;
1382
+ }
1383
+ const state = mergeStates.get(lane.lane);
1384
+ if (state === undefined) throw new Error(`Closure merge state for ${lane.lane} is missing.`);
1385
+ laneOutcomes.push(Object.freeze({
1386
+ lane: lane.lane,
1387
+ invocation: "invoked",
1388
+ status: lane.result.status,
1389
+ limit: lane.limit,
1390
+ diagnostics: lane.result.diagnostics,
1391
+ returned: lane.result.hits.length,
1392
+ accepted: state.accepted,
1393
+ excluded: lane.result.hits.length - state.accepted,
1394
+ candidates: Object.freeze(state.candidateTraces),
1395
+ }));
1396
+ }
1397
+
1398
+ const status: ExistingLaneClosureResult["status"] = invokedStatuses.length === 0
1399
+ ? "unavailable"
1400
+ : invokedStatuses.every((candidate) => candidate === "unavailable")
1401
+ ? "unavailable"
1402
+ : missingProvenance || invokedStatuses.some((candidate) => candidate !== "ready")
1403
+ ? "degraded"
1404
+ : "ready";
1405
+ const documents = Object.freeze(documentOrder.map((document) => Object.freeze({
1406
+ documentId: document.documentId,
1407
+ canonicalDocumentId: document.canonicalDocumentId,
1408
+ outputRank: document.outputRank,
1409
+ sources: Object.freeze([...document.sources]),
1410
+ })));
1411
+ return Object.freeze({
1412
+ status,
1413
+ hits: Object.freeze(outputHits),
1414
+ trace: Object.freeze({
1415
+ variant,
1416
+ fusion: Object.freeze({
1417
+ id: EXISTING_LANE_CLOSURE_FUSION,
1418
+ primaryLane: variant.primary === null ? null : "hybrid",
1419
+ appendedLaneOrder: Object.freeze(completed
1420
+ .filter(({ kind, lane }) => kind !== "disabled" && lane !== "hybrid")
1421
+ .map(({ lane }) => lane as Exclude<ExistingLaneClosureLaneId, "hybrid">)),
1422
+ }),
1423
+ lanes: Object.freeze(laneOutcomes),
1424
+ documents,
1425
+ }),
1426
+ timings: Object.freeze(timings),
1427
+ resources: Object.freeze(resources),
1428
+ accounting: aggregateAccounting(invokedAccounting),
1429
+ });
1430
+ }