@tangle-network/agent-knowledge 5.0.4 → 6.1.0

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 (60) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +2 -2
  3. package/dist/benchmarks/index.d.ts +2 -53
  4. package/dist/benchmarks/index.js +2 -49
  5. package/dist/benchmarks-CmW6iORW.js +2718 -0
  6. package/dist/benchmarks-CmW6iORW.js.map +1 -0
  7. package/dist/cli.d.ts +1 -1
  8. package/dist/cli.js +180 -274
  9. package/dist/cli.js.map +1 -1
  10. package/dist/ids-DRqPZ42_.js +15 -0
  11. package/dist/ids-DRqPZ42_.js.map +1 -0
  12. package/dist/index-CGBctbit.d.ts +857 -0
  13. package/dist/index-CGBctbit.d.ts.map +1 -0
  14. package/dist/index-CIW3G4s_.d.ts +680 -0
  15. package/dist/index-CIW3G4s_.d.ts.map +1 -0
  16. package/dist/index.d.ts +1671 -1876
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +5836 -6530
  19. package/dist/index.js.map +1 -1
  20. package/dist/inspect-D5iarJc2.js +1864 -0
  21. package/dist/inspect-D5iarJc2.js.map +1 -0
  22. package/dist/memory/index.d.ts +3 -8
  23. package/dist/memory/index.js +3 -81
  24. package/dist/memory-C6KPRhoU.js +4494 -0
  25. package/dist/memory-C6KPRhoU.js.map +1 -0
  26. package/dist/search-CP0QtBJZ.js +113 -0
  27. package/dist/search-CP0QtBJZ.js.map +1 -0
  28. package/dist/sources/index.d.ts +212 -205
  29. package/dist/sources/index.d.ts.map +1 -0
  30. package/dist/sources/index.js +614 -33
  31. package/dist/sources/index.js.map +1 -1
  32. package/dist/types-DcCCzreS.d.ts +175 -0
  33. package/dist/types-DcCCzreS.d.ts.map +1 -0
  34. package/dist/viz/index.d.ts +23 -22
  35. package/dist/viz/index.d.ts.map +1 -0
  36. package/dist/viz/index.js +134 -10
  37. package/dist/viz/index.js.map +1 -1
  38. package/docs/results/investment-thesis.md +1 -1
  39. package/docs/results/research-driving.md +1 -1
  40. package/docs/{two-agent-research-ab.md → verified-research-ab.md} +2 -2
  41. package/package.json +22 -11
  42. package/dist/benchmarks/index.js.map +0 -1
  43. package/dist/chunk-4PNXQ2NT.js +0 -147
  44. package/dist/chunk-4PNXQ2NT.js.map +0 -1
  45. package/dist/chunk-AKYJG2MR.js +0 -2183
  46. package/dist/chunk-AKYJG2MR.js.map +0 -1
  47. package/dist/chunk-DQ3PDMDP.js +0 -115
  48. package/dist/chunk-DQ3PDMDP.js.map +0 -1
  49. package/dist/chunk-EYIA5PLQ.js +0 -3153
  50. package/dist/chunk-EYIA5PLQ.js.map +0 -1
  51. package/dist/chunk-LMR53POQ.js +0 -5437
  52. package/dist/chunk-LMR53POQ.js.map +0 -1
  53. package/dist/chunk-MYFM6LKH.js +0 -551
  54. package/dist/chunk-MYFM6LKH.js.map +0 -1
  55. package/dist/chunk-YMKHCTS2.js +0 -19
  56. package/dist/chunk-YMKHCTS2.js.map +0 -1
  57. package/dist/index-Cf7txrYP.d.ts +0 -790
  58. package/dist/memory/index.js.map +0 -1
  59. package/dist/types-6x0OpfW6.d.ts +0 -173
  60. package/dist/types-BY-xLVw-.d.ts +0 -622
@@ -0,0 +1,2718 @@
1
+ import { r as stableId, t as sha256 } from "./ids-DRqPZ42_.js";
2
+ import { n as searchKnowledge } from "./search-CP0QtBJZ.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { join } from "node:path";
5
+ import { canonicalJson } from "@tangle-network/agent-eval";
6
+ import { acquireSingleRunLock, createRunCostLedger, fsCampaignStorage, resolveRunDir, runCampaign } from "@tangle-network/agent-eval/campaign";
7
+ //#region src/retrieval-eval.ts
8
+ function retrievalConfigSurface(config) {
9
+ return canonicalJson(config);
10
+ }
11
+ function retrievalConfigFromSurface(surface) {
12
+ if (typeof surface !== "string") throw new Error(`retrievalConfigFromSurface expected a JSON string surface, got ${typeof surface}`);
13
+ let parsed;
14
+ try {
15
+ parsed = JSON.parse(surface);
16
+ } catch (error) {
17
+ throw new Error(`retrievalConfigFromSurface could not parse JSON: ${error.message}`);
18
+ }
19
+ if (!isJsonObject(parsed)) throw new Error("retrievalConfigFromSurface expected a JSON object");
20
+ return parsed;
21
+ }
22
+ function buildRetrievalEvalDispatch(options) {
23
+ if (!options.retrieve && !options.index) throw new Error("buildRetrievalEvalDispatch requires either index or retrieve");
24
+ const defaultK = options.defaultK ?? 5;
25
+ const retrieve = options.retrieve ?? defaultSearchRetriever;
26
+ return async (surface, scenario, context) => {
27
+ const config = retrievalConfigFromSurface(surface);
28
+ const k = retrievalK(config, scenario, defaultK);
29
+ const startedAt = Date.now();
30
+ const normalized = normalizeRetrieverResult(await retrieve({
31
+ index: options.index,
32
+ config,
33
+ scenario,
34
+ k,
35
+ signal: context.signal,
36
+ context
37
+ }));
38
+ return {
39
+ config,
40
+ query: scenario.query,
41
+ requestedK: k,
42
+ hits: normalized.hits,
43
+ durationMs: Date.now() - startedAt,
44
+ costUsd: normalized.costUsd,
45
+ metadata: normalized.metadata
46
+ };
47
+ };
48
+ }
49
+ function retrievalRecallJudge(options = {}) {
50
+ const weights = normalizeWeights(options.weights ?? { recall: 1 });
51
+ return {
52
+ name: options.name ?? "retrieval-recall",
53
+ dimensions: [
54
+ {
55
+ key: "recall",
56
+ description: "fraction of expected knowledge targets retrieved"
57
+ },
58
+ {
59
+ key: "mrr",
60
+ description: "reciprocal rank of the first matching hit"
61
+ },
62
+ {
63
+ key: "ndcg",
64
+ description: "rank-aware gain for newly matched targets"
65
+ },
66
+ {
67
+ key: "precision_at_k",
68
+ description: "share of returned hits that match at least one target"
69
+ }
70
+ ],
71
+ appliesTo: (scenario) => scenario.kind === "retrieval-eval",
72
+ async score({ artifact, scenario }) {
73
+ const metrics = scoreRetrievalArtifact(artifact, scenario);
74
+ const composite = (metrics.recall * weights.recall + metrics.mrr * weights.mrr + metrics.ndcg * weights.ndcg + metrics.precisionAtK * weights.precisionAtK) / (weights.recall + weights.mrr + weights.ndcg + weights.precisionAtK);
75
+ return {
76
+ dimensions: {
77
+ recall: metrics.recall,
78
+ mrr: metrics.mrr,
79
+ ndcg: metrics.ndcg,
80
+ precision_at_k: metrics.precisionAtK
81
+ },
82
+ composite,
83
+ notes: `matched ${metrics.matchedCount}/${metrics.expectedCount}; first_hit_rank=${metrics.firstHitRank ?? "none"}`
84
+ };
85
+ }
86
+ };
87
+ }
88
+ function scoreRetrievalArtifact(artifact, scenario) {
89
+ const targets = normalizeTargets(scenario.expected);
90
+ if (targets.length === 0) throw new Error(`retrieval eval scenario ${scenario.id} has no expected targets`);
91
+ const matchedTargetIds = /* @__PURE__ */ new Set();
92
+ let firstHitRank = null;
93
+ let relevantHitCount = 0;
94
+ let dcg = 0;
95
+ for (const hit of artifact.hits) {
96
+ const newlyMatched = targets.filter((target) => {
97
+ const targetId = retrievalTargetId(target);
98
+ return !matchedTargetIds.has(targetId) && hitMatchesTarget(hit, target);
99
+ });
100
+ if (newlyMatched.length === 0) continue;
101
+ relevantHitCount += 1;
102
+ if (firstHitRank === null) firstHitRank = hit.rank;
103
+ dcg += 1 / Math.log2(hit.rank + 1);
104
+ for (const target of newlyMatched) matchedTargetIds.add(retrievalTargetId(target));
105
+ }
106
+ const expectedCount = targets.length;
107
+ const matchedCount = matchedTargetIds.size;
108
+ const idcg = idealDcg(Math.min(expectedCount, Math.max(1, artifact.requestedK)));
109
+ return {
110
+ recall: matchedCount / expectedCount,
111
+ mrr: firstHitRank === null ? 0 : 1 / firstHitRank,
112
+ ndcg: idcg === 0 ? 0 : dcg / idcg,
113
+ precisionAtK: artifact.hits.length === 0 ? 0 : relevantHitCount / artifact.hits.length,
114
+ expectedCount,
115
+ matchedCount,
116
+ relevantHitCount,
117
+ firstHitRank,
118
+ matchedTargetIds: [...matchedTargetIds].sort()
119
+ };
120
+ }
121
+ function partitionRetrievalScenarios(scenarios, options = {}) {
122
+ if (scenarios.length < 4) throw new Error("partitionRetrievalScenarios requires at least 4 scenarios for non-empty train and selection partitions plus 2 final scenarios");
123
+ const selectionFraction = options.selectionFraction ?? .2;
124
+ const finalFraction = options.finalFraction ?? .2;
125
+ assertPartitionFraction(selectionFraction, "selectionFraction");
126
+ assertPartitionFraction(finalFraction, "finalFraction");
127
+ if (selectionFraction + finalFraction >= 1) throw new Error("selectionFraction + finalFraction must be less than 1");
128
+ const shuffled = seededShuffle(scenarios, options.seed ?? 42);
129
+ const finalCount = Math.max(2, Math.round(shuffled.length * finalFraction));
130
+ const selectionCount = Math.max(1, Math.round(shuffled.length * selectionFraction));
131
+ if (finalCount + selectionCount >= shuffled.length) throw new Error("retrieval scenario fractions leave no training scenarios");
132
+ const trainEnd = shuffled.length - selectionCount - finalCount;
133
+ return {
134
+ trainScenarios: shuffled.slice(0, trainEnd),
135
+ selectionScenarios: shuffled.slice(trainEnd, trainEnd + selectionCount),
136
+ finalScenarios: shuffled.slice(trainEnd + selectionCount)
137
+ };
138
+ }
139
+ function assertPartitionFraction(value, name) {
140
+ if (!Number.isFinite(value) || value <= 0 || value >= 1) throw new Error(`${name} must be greater than 0 and less than 1`);
141
+ }
142
+ function retrievalK(config, scenario, defaultK) {
143
+ const rawK = config.k ?? config.topK ?? scenario.k ?? defaultK;
144
+ if (typeof rawK !== "number" || !Number.isFinite(rawK) || rawK <= 0) throw new Error(`retrieval k must be a positive number, got ${String(rawK)}`);
145
+ return Math.floor(rawK);
146
+ }
147
+ async function defaultSearchRetriever(input) {
148
+ if (!input.index) throw new Error("default retrieval eval search requires an index");
149
+ return { hits: searchKnowledge(input.index, input.scenario.query, input.k).map(hitFromSearchResult) };
150
+ }
151
+ function hitFromSearchResult(result) {
152
+ return {
153
+ pageId: result.page.id,
154
+ path: result.page.path,
155
+ title: result.page.title,
156
+ rank: result.rank,
157
+ score: result.score,
158
+ normalizedScore: result.normalizedScore,
159
+ sourceIds: result.page.sourceIds,
160
+ snippet: result.snippet
161
+ };
162
+ }
163
+ function normalizeRetrieverResult(result) {
164
+ if (isHitArray(result)) return { hits: result };
165
+ return result;
166
+ }
167
+ function normalizeTargets(expected) {
168
+ return isTargetArray(expected) ? [...expected] : [expected];
169
+ }
170
+ function isHitArray(result) {
171
+ return Array.isArray(result);
172
+ }
173
+ function isTargetArray(expected) {
174
+ return Array.isArray(expected);
175
+ }
176
+ function hitMatchesTarget(hit, target) {
177
+ switch (target.kind) {
178
+ case "page": return hit.pageId === target.pageId;
179
+ case "page-path": return hit.path === target.path;
180
+ case "source": return Boolean(hit.sourceIds?.includes(target.sourceId));
181
+ case "source-anchor": return Boolean(hit.sourceSpans?.some((span) => span.sourceId === target.sourceId && span.anchorId === target.anchorId));
182
+ case "source-span": return Boolean(hit.sourceSpans?.some((span) => span.sourceId === target.sourceId && spanOverlaps(span, target)));
183
+ }
184
+ }
185
+ function spanOverlaps(hit, target) {
186
+ if (typeof hit.charStart !== "number" || typeof hit.charEnd !== "number") return false;
187
+ return hit.charStart < target.charEnd && target.charStart < hit.charEnd;
188
+ }
189
+ function retrievalTargetId(target) {
190
+ switch (target.kind) {
191
+ case "page": return `page:${target.pageId}`;
192
+ case "page-path": return `page-path:${target.path}`;
193
+ case "source": return `source:${target.sourceId}`;
194
+ case "source-anchor": return `source-anchor:${target.sourceId}:${target.anchorId}`;
195
+ case "source-span": return `source-span:${target.sourceId}:${target.charStart}:${target.charEnd}`;
196
+ }
197
+ }
198
+ function idealDcg(count) {
199
+ let score = 0;
200
+ for (let i = 1; i <= count; i += 1) score += 1 / Math.log2(i + 1);
201
+ return score;
202
+ }
203
+ function normalizeWeights(weights) {
204
+ const normalized = {
205
+ recall: normalizeWeight(weights.recall),
206
+ mrr: normalizeWeight(weights.mrr),
207
+ ndcg: normalizeWeight(weights.ndcg),
208
+ precisionAtK: normalizeWeight(weights.precisionAtK)
209
+ };
210
+ if (normalized.recall + normalized.mrr + normalized.ndcg + normalized.precisionAtK <= 0) throw new Error("retrievalRecallJudge requires at least one positive metric weight");
211
+ return normalized;
212
+ }
213
+ function normalizeWeight(value) {
214
+ if (value === void 0) return 0;
215
+ if (!Number.isFinite(value) || value < 0) throw new Error(`retrievalRecallJudge metric weights must be non-negative finite numbers, got ${String(value)}`);
216
+ return value;
217
+ }
218
+ function isJsonObject(value) {
219
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
220
+ }
221
+ function seededShuffle(items, seed) {
222
+ const out = [...items];
223
+ let state = seed >>> 0;
224
+ for (let i = out.length - 1; i > 0; i -= 1) {
225
+ state = state * 1664525 + 1013904223 >>> 0;
226
+ const j = state % (i + 1);
227
+ [out[i], out[j]] = [out[j], out[i]];
228
+ }
229
+ return out;
230
+ }
231
+ //#endregion
232
+ //#region src/memory/source-record.ts
233
+ function memoryHitToSourceRecord(hit, options = {}) {
234
+ const contentHash = sha256(`${hit.uri}\n${hit.text}`);
235
+ return {
236
+ id: stableId("src", `${hit.uri}:${contentHash}`),
237
+ uri: hit.uri,
238
+ title: hit.title ?? `${hit.kind}:${hit.id}`,
239
+ mediaType: "text/plain",
240
+ contentHash,
241
+ text: hit.text,
242
+ validUntil: hit.validUntil,
243
+ lastVerifiedAt: hit.lastVerifiedAt,
244
+ createdAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
245
+ metadata: {
246
+ ...hit.metadata ?? {},
247
+ source: "agent-memory",
248
+ memoryId: hit.id,
249
+ memoryKind: hit.kind,
250
+ score: hit.score,
251
+ normalizedScore: hit.normalizedScore,
252
+ confidence: hit.confidence,
253
+ scope: options.scope
254
+ }
255
+ };
256
+ }
257
+ function memoryWriteResultToSourceRecord(result, text, options = {}) {
258
+ return memoryHitToSourceRecord({
259
+ id: result.id,
260
+ uri: result.uri,
261
+ kind: result.kind,
262
+ text,
263
+ metadata: result.metadata
264
+ }, options);
265
+ }
266
+ //#endregion
267
+ //#region src/benchmarks/adapters.ts
268
+ function createNoopMemoryBenchmarkAdapter(id = "no-memory") {
269
+ return {
270
+ id,
271
+ branchIsolation: { mode: "scoped" },
272
+ async search() {
273
+ return [];
274
+ },
275
+ async getContext(query) {
276
+ return {
277
+ query,
278
+ text: "",
279
+ hits: [],
280
+ sourceRecords: []
281
+ };
282
+ },
283
+ async write(input) {
284
+ return {
285
+ accepted: false,
286
+ id: input.id ?? `${id}:ignored`,
287
+ uri: `memory://${id}/ignored`,
288
+ kind: input.kind
289
+ };
290
+ },
291
+ async clear() {},
292
+ async flush() {}
293
+ };
294
+ }
295
+ function createInMemoryBenchmarkAdapter(options = {}) {
296
+ const id = options.id ?? "in-memory";
297
+ const rows = [];
298
+ let seq = 0;
299
+ const adapter = {
300
+ id,
301
+ branchIsolation: { mode: "scoped" },
302
+ async search(query, searchOptions = {}) {
303
+ return rows.filter((row) => memoryScopeMatches(row.input.scope, searchOptions.scope)).filter((row) => !searchOptions.kinds?.length || searchOptions.kinds.includes(row.hit.kind)).map((row) => {
304
+ const lexical = tokenOverlap(query, row.hit.text);
305
+ const recency = row.seq / Math.max(1, seq);
306
+ return {
307
+ ...row.hit,
308
+ score: lexical + recency * .01,
309
+ normalizedScore: lexical
310
+ };
311
+ }).filter((hit) => searchOptions.minScore === void 0 ? true : hit.score >= searchOptions.minScore).sort((a, b) => (b.score ?? 0) - (a.score ?? 0)).slice(0, searchOptions.limit ?? 5);
312
+ },
313
+ async getContext(query, searchOptions = {}) {
314
+ const hits = await adapter.search(query, searchOptions);
315
+ return {
316
+ query,
317
+ hits,
318
+ sourceRecords: hits.map((hit) => memoryHitToSourceRecord(hit, { scope: searchOptions.scope })),
319
+ text: renderMemoryHits(hits)
320
+ };
321
+ },
322
+ async write(input) {
323
+ seq += 1;
324
+ const memoryId = input.id ?? `${id}:${seq}`;
325
+ const hit = {
326
+ id: memoryId,
327
+ uri: `memory://${id}/${encodeURIComponent(memoryId)}`,
328
+ kind: input.kind,
329
+ text: input.text,
330
+ title: input.title,
331
+ score: 1,
332
+ normalizedScore: 1,
333
+ createdAt: input.metadata?.timestamp,
334
+ metadata: {
335
+ ...input.metadata ?? {},
336
+ scope: input.scope
337
+ }
338
+ };
339
+ rows.push({
340
+ seq,
341
+ input,
342
+ hit
343
+ });
344
+ return {
345
+ accepted: true,
346
+ id: memoryId,
347
+ uri: hit.uri,
348
+ kind: input.kind,
349
+ sourceRecord: memoryWriteResultToSourceRecord({
350
+ accepted: true,
351
+ id: memoryId,
352
+ uri: hit.uri,
353
+ kind: input.kind,
354
+ metadata: hit.metadata
355
+ }, input.text, { scope: input.scope }),
356
+ metadata: hit.metadata
357
+ };
358
+ },
359
+ async clear(scope) {
360
+ for (let index = rows.length - 1; index >= 0; index -= 1) if (memoryScopeMatches(rows[index].input.scope, scope)) rows.splice(index, 1);
361
+ },
362
+ async flush() {}
363
+ };
364
+ return adapter;
365
+ }
366
+ function memoryEventId(hit) {
367
+ const eventId = hit.metadata?.eventId;
368
+ return typeof eventId === "string" ? eventId : void 0;
369
+ }
370
+ function memoryActorId(hit) {
371
+ const actorId = hit.metadata?.actorId;
372
+ return typeof actorId === "string" ? actorId : void 0;
373
+ }
374
+ function memoryScopeMatches(stored, requested) {
375
+ if (!requested) return true;
376
+ if (requested.tenantId !== void 0 && stored?.tenantId !== requested.tenantId) return false;
377
+ if (requested.userId !== void 0 && stored?.userId !== requested.userId) return false;
378
+ if (requested.agentId !== void 0 && stored?.agentId !== requested.agentId) return false;
379
+ if (requested.teamId !== void 0 && stored?.teamId !== requested.teamId) return false;
380
+ if (requested.runId !== void 0 && stored?.runId !== requested.runId) return false;
381
+ if (requested.sessionId !== void 0 && stored?.sessionId !== requested.sessionId) return false;
382
+ if (requested.namespace !== void 0 && stored?.namespace !== requested.namespace) return false;
383
+ for (const [key, value] of Object.entries(requested.tags ?? {})) if (stored?.tags?.[key] !== value) return false;
384
+ return true;
385
+ }
386
+ function tokenOverlap(query, text) {
387
+ const queryTokens = new Set(tokenize(query));
388
+ if (queryTokens.size === 0) return 0;
389
+ const textTokens = new Set(tokenize(text));
390
+ let matched = 0;
391
+ for (const token of queryTokens) if (textTokens.has(token)) matched += 1;
392
+ return matched / queryTokens.size;
393
+ }
394
+ function tokenize(text) {
395
+ const stop = /* @__PURE__ */ new Set([
396
+ "the",
397
+ "and",
398
+ "for",
399
+ "this",
400
+ "that",
401
+ "with",
402
+ "what",
403
+ "should",
404
+ "agent",
405
+ "user",
406
+ "current",
407
+ "now",
408
+ "use"
409
+ ]);
410
+ return text.toLowerCase().split(/[^a-z0-9/]+/).filter((token) => token.length > 2 && !stop.has(token));
411
+ }
412
+ function renderMemoryHits(hits) {
413
+ return hits.map((hit, index) => {
414
+ const eventId = memoryEventId(hit);
415
+ const actorId = memoryActorId(hit);
416
+ return [
417
+ `[${index + 1}] ${hit.title ?? hit.id}`,
418
+ eventId ? `event=${eventId}` : "",
419
+ actorId ? `actor=${actorId}` : "",
420
+ hit.text
421
+ ].filter(Boolean).join("\n");
422
+ }).join("\n\n");
423
+ }
424
+ //#endregion
425
+ //#region src/benchmarks/utils.ts
426
+ function mean(values) {
427
+ const finite = values.filter(Number.isFinite);
428
+ if (finite.length === 0) return 0;
429
+ return finite.reduce((sum, value) => sum + value, 0) / finite.length;
430
+ }
431
+ function unique(values) {
432
+ return [...new Set(values.filter(Boolean))];
433
+ }
434
+ function formatNumber(value) {
435
+ if (!Number.isFinite(value)) return "0";
436
+ return value.toFixed(value === 0 || Math.abs(value) >= 10 ? 0 : 3);
437
+ }
438
+ function normalizeUsd(value) {
439
+ return Number(value.toFixed(12));
440
+ }
441
+ function compactObject(value) {
442
+ if (Array.isArray(value)) return value.map(compactObject);
443
+ if (!value || typeof value !== "object") return value;
444
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, compactObject(entry)]));
445
+ }
446
+ //#endregion
447
+ //#region src/benchmarks/validation.ts
448
+ function isKnowledgeMemoryBenchmarkCase(testCase) {
449
+ return testCase.taskKind.startsWith("memory-");
450
+ }
451
+ function assertKnowledgeBenchmarkCases(cases) {
452
+ if (cases.length === 0) throw new Error("knowledge benchmark requires cases");
453
+ assertUniqueNonEmptyStrings(cases.map((testCase) => testCase.id), "knowledge benchmark case id");
454
+ for (const testCase of cases) {
455
+ if (typeof testCase.family !== "string" || !testCase.family.trim()) throw new Error(`knowledge benchmark case ${testCase.id} requires a family`);
456
+ if (testCase.taskKind === "retrieval") continue;
457
+ if (isKnowledgeMemoryBenchmarkCase(testCase)) {
458
+ assertUniqueNonEmptyStrings(testCase.events.map((event) => event.id), `${testCase.id} memory event id`);
459
+ for (const event of testCase.events) assertNonEmptyBenchmarkString(event.text, `${testCase.id} memory event ${event.id} text`);
460
+ assertClaimMatchers(testCase.requiredFacts ?? [], `${testCase.id} requiredFacts`);
461
+ assertClaimMatchers(testCase.forbiddenFacts ?? [], `${testCase.id} forbiddenFacts`);
462
+ assertUniqueNonEmptyStrings(testCase.expectedEventIds ?? [], `${testCase.id} expected event id`);
463
+ assertUniqueNonEmptyStrings(testCase.expectedActorIds ?? [], `${testCase.id} expected actor id`);
464
+ } else {
465
+ assertClaimMatchers(testCase.requiredClaims ?? [], `${testCase.id} requiredClaims`);
466
+ assertClaimMatchers(testCase.forbiddenClaims ?? [], `${testCase.id} forbiddenClaims`);
467
+ assertUniqueNonEmptyStrings(testCase.expectedSourceIds ?? [], `${testCase.id} source id`);
468
+ }
469
+ }
470
+ }
471
+ function assertClaimMatchers(claims, label) {
472
+ assertUniqueNonEmptyStrings(claims.map((claim) => claim.id), `${label} matcher id`);
473
+ for (const claim of claims) {
474
+ if (claim.anyOf.length === 0) throw new Error(`${label} matcher ${claim.id} requires anyOf`);
475
+ assertUniqueNonEmptyStrings(claim.anyOf, `${label} matcher ${claim.id} anyOf`);
476
+ if (claim.weight !== void 0 && (!Number.isFinite(claim.weight) || claim.weight <= 0)) throw new Error(`${label} matcher ${claim.id} weight must be a positive finite number`);
477
+ const sourceEventIds = claim.sourceEventIds;
478
+ if (sourceEventIds !== void 0) assertUniqueNonEmptyStrings(sourceEventIds, `${label} matcher ${claim.id} source event id`);
479
+ }
480
+ }
481
+ function assertUniqueNonEmptyStrings(values, label) {
482
+ const seen = /* @__PURE__ */ new Set();
483
+ for (const value of values) {
484
+ assertNonEmptyBenchmarkString(value, label);
485
+ if (seen.has(value)) throw new Error(`duplicate ${label}: ${value}`);
486
+ seen.add(value);
487
+ }
488
+ }
489
+ function assertNonEmptyBenchmarkString(value, label) {
490
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${label} must be non-empty`);
491
+ }
492
+ //#endregion
493
+ //#region src/benchmarks/catalog.ts
494
+ const INDUSTRY_RAG_BENCHMARKS = [
495
+ {
496
+ id: "beir",
497
+ family: "beir",
498
+ taskKind: "retrieval",
499
+ primaryMetrics: [
500
+ "nDCG@10",
501
+ "Recall@100",
502
+ "MRR@10"
503
+ ],
504
+ adapter: "buildRetrievalBenchmarkCasesFromQrels",
505
+ notes: "Classic zero-shot retrieval suites using query/corpus/qrels files."
506
+ },
507
+ {
508
+ id: "mteb-retrieval",
509
+ family: "mteb-retrieval",
510
+ taskKind: "retrieval",
511
+ primaryMetrics: ["nDCG@10", "Recall@100"],
512
+ adapter: "buildRetrievalBenchmarkCasesFromQrels",
513
+ notes: "MTEB retrieval task shape; same qrels bridge, different dataset provenance."
514
+ },
515
+ {
516
+ id: "msmarco",
517
+ family: "msmarco",
518
+ taskKind: "retrieval",
519
+ primaryMetrics: ["MRR@10", "Recall@100"],
520
+ adapter: "buildRetrievalBenchmarkCasesFromQrels",
521
+ notes: "Passage retrieval and reranking smoke for web-style questions."
522
+ },
523
+ {
524
+ id: "trec-dl",
525
+ family: "trec-dl",
526
+ taskKind: "retrieval",
527
+ primaryMetrics: [
528
+ "nDCG@10",
529
+ "MAP",
530
+ "Recall@100"
531
+ ],
532
+ adapter: "buildRetrievalBenchmarkCasesFromQrels",
533
+ notes: "Deep Learning Track judgments over MS MARCO-derived corpora."
534
+ },
535
+ {
536
+ id: "miracl",
537
+ family: "miracl",
538
+ taskKind: "retrieval",
539
+ primaryMetrics: ["nDCG@10", "Recall@100"],
540
+ adapter: "buildRetrievalBenchmarkCasesFromQrels",
541
+ notes: "Multilingual retrieval; use language tags on cases."
542
+ },
543
+ {
544
+ id: "lotte",
545
+ family: "lotte",
546
+ taskKind: "retrieval",
547
+ primaryMetrics: ["Success@5", "Recall@100"],
548
+ adapter: "buildRetrievalBenchmarkCasesFromQrels",
549
+ notes: "Long-tail search tasks; map collection/domain into tags."
550
+ },
551
+ {
552
+ id: "bright",
553
+ family: "bright",
554
+ taskKind: "retrieval",
555
+ primaryMetrics: ["nDCG@10", "Recall@100"],
556
+ adapter: "buildRetrievalBenchmarkCasesFromQrels",
557
+ notes: "Reasoning-heavy retrieval; preserve domain tags for slice reporting."
558
+ },
559
+ {
560
+ id: "crag",
561
+ family: "crag",
562
+ taskKind: "rag-answer",
563
+ primaryMetrics: [
564
+ "claim_recall",
565
+ "citation_recall",
566
+ "hallucination_safe"
567
+ ],
568
+ adapter: "KnowledgeAnswerBenchmarkCase",
569
+ notes: "Answer quality and freshness cases; use required/forbidden claims plus citations."
570
+ },
571
+ {
572
+ id: "hotpotqa",
573
+ family: "hotpotqa",
574
+ taskKind: "rag-answer",
575
+ primaryMetrics: ["claim_recall", "citation_recall"],
576
+ adapter: "KnowledgeAnswerBenchmarkCase",
577
+ notes: "Multihop QA; encode each supporting fact as a required claim."
578
+ },
579
+ {
580
+ id: "kilt",
581
+ family: "kilt",
582
+ taskKind: "rag-answer",
583
+ primaryMetrics: ["claim_recall", "citation_recall"],
584
+ adapter: "KnowledgeAnswerBenchmarkCase",
585
+ notes: "Knowledge-intensive generation with provenance; encode expected pages/sources."
586
+ },
587
+ {
588
+ id: "ragtruth",
589
+ family: "ragtruth",
590
+ taskKind: "hallucination",
591
+ primaryMetrics: ["hallucination_safe", "forbidden_claim_rate"],
592
+ adapter: "KnowledgeAnswerBenchmarkCase",
593
+ notes: "Hallucination detection; encode hallucinated spans as forbidden claims."
594
+ },
595
+ {
596
+ id: "faithbench",
597
+ family: "faithbench",
598
+ taskKind: "hallucination",
599
+ primaryMetrics: ["hallucination_safe", "forbidden_claim_rate"],
600
+ adapter: "KnowledgeAnswerBenchmarkCase",
601
+ notes: "Faithfulness benchmark; score unsupported claims as forbidden claims."
602
+ },
603
+ {
604
+ id: "first-party/kb-improvement",
605
+ family: "first-party",
606
+ taskKind: "kb-improvement",
607
+ primaryMetrics: [
608
+ "claim_recall",
609
+ "hallucination_safe",
610
+ "score"
611
+ ],
612
+ adapter: "KnowledgeAnswerBenchmarkCase",
613
+ notes: "Project-owned candidate-KB validation; grade the produced KB text or answer bundle."
614
+ }
615
+ ];
616
+ const INDUSTRY_MEMORY_BENCHMARKS = [
617
+ {
618
+ id: "locomo/qa",
619
+ family: "locomo",
620
+ taskKind: "memory-recall",
621
+ primaryMetrics: ["memory_fact_recall", "memory_event_recall"],
622
+ adapter: "KnowledgeMemoryBenchmarkCase",
623
+ notes: "Long-term conversational QA over multi-session histories."
624
+ },
625
+ {
626
+ id: "locomo/event-summary",
627
+ family: "locomo",
628
+ taskKind: "memory-summarization",
629
+ primaryMetrics: ["memory_fact_recall", "memory_event_recall"],
630
+ adapter: "KnowledgeMemoryBenchmarkCase",
631
+ notes: "Event summarization over long conversational histories."
632
+ },
633
+ {
634
+ id: "longmemeval",
635
+ family: "longmemeval",
636
+ taskKind: "memory-temporal",
637
+ primaryMetrics: [
638
+ "memory_fact_recall",
639
+ "memory_stale_safe",
640
+ "memory_event_recall"
641
+ ],
642
+ adapter: "KnowledgeMemoryBenchmarkCase",
643
+ notes: "Long-term assistant memory with temporal and update-sensitive probes."
644
+ },
645
+ {
646
+ id: "longmemeval-v2",
647
+ family: "longmemeval-v2",
648
+ taskKind: "memory-reasoning",
649
+ primaryMetrics: [
650
+ "memory_fact_recall",
651
+ "memory_event_recall",
652
+ "score"
653
+ ],
654
+ adapter: "KnowledgeMemoryBenchmarkCase",
655
+ notes: "Experience reuse from long agent histories; track accuracy and latency."
656
+ },
657
+ {
658
+ id: "memora",
659
+ family: "memora",
660
+ taskKind: "memory-update",
661
+ primaryMetrics: [
662
+ "memory_fact_recall",
663
+ "memory_stale_safe",
664
+ "memory_stale_rate"
665
+ ],
666
+ adapter: "KnowledgeMemoryBenchmarkCase",
667
+ notes: "Forgetting-aware memory accuracy: reward current facts and penalize obsolete ones."
668
+ },
669
+ {
670
+ id: "memoryagentbench",
671
+ family: "memoryagentbench",
672
+ taskKind: "memory-ingest",
673
+ primaryMetrics: ["memory_fact_recall", "memory_event_recall"],
674
+ adapter: "KnowledgeMemoryBenchmarkCase",
675
+ notes: "Incremental multi-turn information intake before later recall."
676
+ },
677
+ {
678
+ id: "memorybank",
679
+ family: "memorybank",
680
+ taskKind: "memory-recommendation",
681
+ primaryMetrics: ["memory_fact_recall", "memory_stale_safe"],
682
+ adapter: "KnowledgeMemoryBenchmarkCase",
683
+ notes: "Personalized memory use for preference-aware downstream choices."
684
+ },
685
+ {
686
+ id: "groupmembench",
687
+ family: "groupmembench",
688
+ taskKind: "memory-multiparty",
689
+ primaryMetrics: [
690
+ "memory_fact_recall",
691
+ "memory_actor_recall",
692
+ "memory_stale_safe"
693
+ ],
694
+ adapter: "KnowledgeMemoryBenchmarkCase",
695
+ notes: "Multi-party memory with speaker attribution, update, and term ambiguity pressure."
696
+ },
697
+ {
698
+ id: "first-party/memory-lifecycle",
699
+ family: "first-party",
700
+ taskKind: "memory-forgetting",
701
+ primaryMetrics: [
702
+ "memory_fact_recall",
703
+ "memory_stale_safe",
704
+ "memory_event_recall"
705
+ ],
706
+ adapter: "KnowledgeMemoryBenchmarkCase",
707
+ notes: "Project-owned lifecycle pack for ingest, recall, update, forgetting, and ambiguity."
708
+ }
709
+ ];
710
+ function buildIndustryRagBenchmarkSmokeCases(specs = INDUSTRY_RAG_BENCHMARKS) {
711
+ return specs.map((spec) => {
712
+ const source = {
713
+ name: spec.id,
714
+ version: "smoke"
715
+ };
716
+ const split = spec.taskKind === "retrieval" ? "search" : "holdout";
717
+ const tags = unique([
718
+ "industry-smoke",
719
+ spec.id,
720
+ spec.family,
721
+ spec.taskKind
722
+ ]);
723
+ if (spec.taskKind === "retrieval") return {
724
+ id: `${spec.id}/smoke:q1`,
725
+ family: spec.family,
726
+ taskKind: "retrieval",
727
+ split,
728
+ tags,
729
+ source,
730
+ query: `${spec.id} smoke retrieval query`,
731
+ expected: [{
732
+ kind: "page",
733
+ pageId: `${spec.id}:doc-1`
734
+ }],
735
+ k: 5,
736
+ metadata: {
737
+ adapter: spec.adapter,
738
+ primaryMetrics: spec.primaryMetrics
739
+ }
740
+ };
741
+ return {
742
+ id: `${spec.id}/smoke:q1`,
743
+ family: spec.family,
744
+ taskKind: spec.taskKind,
745
+ split,
746
+ tags,
747
+ source,
748
+ prompt: `${spec.id} smoke benchmark prompt`,
749
+ requiredClaims: [{
750
+ id: `${spec.id}:required`,
751
+ anyOf: [`${spec.id} supported answer`]
752
+ }],
753
+ forbiddenClaims: [{
754
+ id: `${spec.id}:unsupported`,
755
+ anyOf: [`${spec.id} unsupported claim`]
756
+ }],
757
+ expectedSourceIds: [`${spec.id}:source-1`],
758
+ referenceAnswer: `${spec.id} supported answer`,
759
+ metadata: {
760
+ adapter: spec.adapter,
761
+ primaryMetrics: spec.primaryMetrics
762
+ }
763
+ };
764
+ });
765
+ }
766
+ function respondToIndustryRagBenchmarkSmokeCase(input) {
767
+ const testCase = input.case;
768
+ if (isKnowledgeMemoryBenchmarkCase(testCase)) return respondToIndustryMemoryBenchmarkSmokeCase({ case: testCase });
769
+ if (testCase.taskKind === "retrieval") return {
770
+ hits: [hitForExpectedTarget(Array.isArray(testCase.expected) ? testCase.expected[0] : testCase.expected, testCase.id)],
771
+ durationMs: 1,
772
+ metadata: { smoke: true }
773
+ };
774
+ return {
775
+ answer: (testCase.requiredClaims ?? []).map((claim) => claim.anyOf[0]).filter((fragment) => Boolean(fragment)).join(" "),
776
+ citedSourceIds: testCase.expectedSourceIds ?? [],
777
+ durationMs: 1,
778
+ metadata: { smoke: true }
779
+ };
780
+ }
781
+ function buildIndustryMemoryBenchmarkSmokeCases(specs = INDUSTRY_MEMORY_BENCHMARKS) {
782
+ return specs.map((spec) => {
783
+ const currentEventId = `${spec.id}:event-current`;
784
+ const staleEventId = `${spec.id}:event-stale`;
785
+ const actorId = spec.taskKind === "memory-multiparty" ? "teammate-ada" : "user";
786
+ const currentFact = `${spec.id} current memory`;
787
+ const staleFact = `${spec.id} stale memory`;
788
+ return {
789
+ id: `${spec.id}/smoke:q1`,
790
+ family: spec.family,
791
+ taskKind: spec.taskKind,
792
+ split: spec.taskKind === "memory-forgetting" ? "holdout" : "dev",
793
+ tags: unique([
794
+ "memory-smoke",
795
+ spec.id,
796
+ spec.family,
797
+ spec.taskKind
798
+ ]),
799
+ source: {
800
+ name: spec.id,
801
+ version: "smoke"
802
+ },
803
+ events: [{
804
+ id: staleEventId,
805
+ actorId,
806
+ sessionId: `${spec.id}:session-1`,
807
+ timestamp: "2026-01-01T00:00:00.000Z",
808
+ text: `${actorId} once had this obsolete fact: ${staleFact}.`
809
+ }, {
810
+ id: currentEventId,
811
+ actorId,
812
+ sessionId: `${spec.id}:session-2`,
813
+ timestamp: "2026-02-01T00:00:00.000Z",
814
+ text: `${actorId} updated the durable fact to: ${currentFact}.`
815
+ }],
816
+ prompt: `Use memory to answer the ${spec.id} smoke probe.`,
817
+ requiredFacts: [{
818
+ id: `${spec.id}:current`,
819
+ anyOf: [currentFact],
820
+ sourceEventIds: [currentEventId]
821
+ }],
822
+ forbiddenFacts: [{
823
+ id: `${spec.id}:stale`,
824
+ anyOf: [staleFact],
825
+ sourceEventIds: [staleEventId],
826
+ obsolete: true
827
+ }],
828
+ expectedEventIds: [currentEventId],
829
+ expectedActorIds: [actorId],
830
+ referenceAnswer: currentFact,
831
+ metadata: {
832
+ adapter: spec.adapter,
833
+ primaryMetrics: spec.primaryMetrics
834
+ }
835
+ };
836
+ });
837
+ }
838
+ function respondToIndustryMemoryBenchmarkSmokeCase(input) {
839
+ const testCase = input.case;
840
+ const facts = testCase.requiredFacts?.map((fact) => fact.anyOf[0]).filter((fragment) => Boolean(fragment));
841
+ return {
842
+ answer: facts?.join(" ") ?? "",
843
+ rememberedFacts: facts ?? [],
844
+ citedEventIds: testCase.expectedEventIds ?? [],
845
+ actorIds: testCase.expectedActorIds ?? [],
846
+ durationMs: 1,
847
+ metadata: { smoke: true }
848
+ };
849
+ }
850
+ function buildFirstPartyMemoryLifecycleBenchmarkCases() {
851
+ const base = {
852
+ family: "first-party",
853
+ source: {
854
+ name: "first-party/memory-lifecycle",
855
+ version: "real-v1"
856
+ }
857
+ };
858
+ return [
859
+ memoryLifecycleCase({
860
+ ...base,
861
+ id: "first-party/memory-lifecycle:allergy",
862
+ taskKind: "memory-ingest",
863
+ split: "dev",
864
+ actorId: "user",
865
+ prompt: "What food restriction should catering remember for this user?",
866
+ staleText: "The user said they had no food allergies on the first onboarding form.",
867
+ currentText: "The user later corrected the profile: they have a severe peanut allergy.",
868
+ required: "severe peanut allergy",
869
+ forbidden: "no food allergies"
870
+ }),
871
+ memoryLifecycleCase({
872
+ ...base,
873
+ id: "first-party/memory-lifecycle:account-tier",
874
+ taskKind: "memory-recall",
875
+ split: "dev",
876
+ actorId: "sales-ops",
877
+ prompt: "What is the customer account tier now?",
878
+ staleText: "Sales ops originally marked the customer as starter tier.",
879
+ currentText: "Sales ops updated the customer to enterprise tier after procurement approval.",
880
+ required: "enterprise tier",
881
+ forbidden: "starter tier"
882
+ }),
883
+ memoryLifecycleCase({
884
+ ...base,
885
+ id: "first-party/memory-lifecycle:launch-date",
886
+ taskKind: "memory-temporal",
887
+ split: "holdout",
888
+ actorId: "pm",
889
+ prompt: "What launch date should the agent use?",
890
+ staleText: "The PM first planned the launch for April 3.",
891
+ currentText: "The PM moved the launch date to April 17 after legal review.",
892
+ required: "April 17",
893
+ forbidden: "April 3"
894
+ }),
895
+ memoryLifecycleCase({
896
+ ...base,
897
+ id: "first-party/memory-lifecycle:briefing-channel",
898
+ taskKind: "memory-update",
899
+ split: "holdout",
900
+ actorId: "user",
901
+ prompt: "How should daily briefings be delivered now?",
902
+ staleText: "The user used to want daily briefings by SMS.",
903
+ currentText: "The user changed daily briefings to email only.",
904
+ required: "email only",
905
+ forbidden: "SMS"
906
+ }),
907
+ memoryLifecycleCase({
908
+ ...base,
909
+ id: "first-party/memory-lifecycle:shipping-address",
910
+ taskKind: "memory-forgetting",
911
+ split: "holdout",
912
+ actorId: "user",
913
+ prompt: "What shipping address is current?",
914
+ staleText: "The old shipping address was 14 Pine Street, Apartment 2.",
915
+ currentText: "The current shipping address is 88 Cedar Avenue, Suite 9.",
916
+ required: "88 Cedar Avenue, Suite 9",
917
+ forbidden: "14 Pine Street"
918
+ }),
919
+ memoryLifecycleCase({
920
+ ...base,
921
+ id: "first-party/memory-lifecycle:approval-owner",
922
+ taskKind: "memory-reasoning",
923
+ split: "holdout",
924
+ actorId: "finance",
925
+ prompt: "Who owns travel approval now?",
926
+ staleText: "Finance said Liam owned travel approvals last quarter.",
927
+ currentText: "Finance reassigned travel approvals to Maya this quarter.",
928
+ required: "Maya",
929
+ forbidden: "Liam"
930
+ }),
931
+ memoryLifecycleCase({
932
+ ...base,
933
+ id: "first-party/memory-lifecycle:project-summary",
934
+ taskKind: "memory-summarization",
935
+ split: "dev",
936
+ actorId: "pm",
937
+ prompt: "Summarize the current Project Orion risks.",
938
+ staleText: "The old Project Orion risk was logo color churn.",
939
+ currentText: "The current Project Orion risks are vendor delay and a QA staffing gap.",
940
+ required: "vendor delay",
941
+ extraRequired: "QA staffing gap",
942
+ forbidden: "logo color churn"
943
+ }),
944
+ memoryLifecycleCase({
945
+ ...base,
946
+ id: "first-party/memory-lifecycle:meeting-format",
947
+ taskKind: "memory-recommendation",
948
+ split: "holdout",
949
+ actorId: "user",
950
+ prompt: "What meeting format should the agent recommend?",
951
+ staleText: "The user previously preferred long video calls for planning.",
952
+ currentText: "The user now prefers async docs for planning instead of video calls.",
953
+ required: "async docs",
954
+ forbidden: "long video calls"
955
+ }),
956
+ memoryLifecycleCase({
957
+ ...base,
958
+ id: "first-party/memory-lifecycle:multiparty-ada",
959
+ taskKind: "memory-multiparty",
960
+ split: "holdout",
961
+ actorId: "ada",
962
+ prompt: "Which SDK language did Ada ask for?",
963
+ staleText: "Ben asked for a Python notebook example.",
964
+ currentText: "Ada asked for a Rust SDK example.",
965
+ required: "Rust SDK",
966
+ forbidden: "Python notebook"
967
+ }),
968
+ memoryLifecycleCase({
969
+ ...base,
970
+ id: "first-party/memory-lifecycle:timezone",
971
+ taskKind: "memory-recall",
972
+ split: "dev",
973
+ actorId: "user",
974
+ prompt: "What timezone should scheduling use for this user?",
975
+ staleText: "The user profile originally listed Pacific time.",
976
+ currentText: "The user corrected scheduling to America/Denver time.",
977
+ required: "America/Denver",
978
+ forbidden: "Pacific time"
979
+ }),
980
+ memoryLifecycleCase({
981
+ ...base,
982
+ id: "first-party/memory-lifecycle:dinner-preference",
983
+ taskKind: "memory-update",
984
+ split: "holdout",
985
+ actorId: "user",
986
+ prompt: "What dinner preference should the assistant use?",
987
+ staleText: "The user was previously vegetarian for team dinners.",
988
+ currentText: "The user updated dinner restrictions to no shellfish.",
989
+ required: "no shellfish",
990
+ forbidden: "vegetarian"
991
+ }),
992
+ memoryLifecycleCase({
993
+ ...base,
994
+ id: "first-party/memory-lifecycle:support-sla",
995
+ taskKind: "memory-temporal",
996
+ split: "holdout",
997
+ actorId: "support-lead",
998
+ prompt: "What support SLA is current?",
999
+ staleText: "Support used to promise a 24 hour response SLA.",
1000
+ currentText: "Support changed the current response SLA to 2 business hours.",
1001
+ required: "2 business hours",
1002
+ forbidden: "24 hour"
1003
+ })
1004
+ ];
1005
+ }
1006
+ function hitForExpectedTarget(expected, fallbackId) {
1007
+ if (!expected) return {
1008
+ pageId: fallbackId,
1009
+ path: `${fallbackId}.md`,
1010
+ rank: 1
1011
+ };
1012
+ switch (expected.kind) {
1013
+ case "page": return {
1014
+ pageId: expected.pageId,
1015
+ path: `${expected.pageId}.md`,
1016
+ rank: 1
1017
+ };
1018
+ case "page-path": return {
1019
+ pageId: expected.path,
1020
+ path: expected.path,
1021
+ rank: 1
1022
+ };
1023
+ case "source": return {
1024
+ pageId: expected.sourceId,
1025
+ path: `${expected.sourceId}.md`,
1026
+ sourceIds: [expected.sourceId],
1027
+ rank: 1
1028
+ };
1029
+ case "source-anchor": return {
1030
+ pageId: expected.sourceId,
1031
+ path: `${expected.sourceId}.md`,
1032
+ sourceIds: [expected.sourceId],
1033
+ sourceSpans: [{
1034
+ sourceId: expected.sourceId,
1035
+ anchorId: expected.anchorId
1036
+ }],
1037
+ rank: 1
1038
+ };
1039
+ case "source-span": return {
1040
+ pageId: expected.sourceId,
1041
+ path: `${expected.sourceId}.md`,
1042
+ sourceIds: [expected.sourceId],
1043
+ sourceSpans: [{
1044
+ sourceId: expected.sourceId,
1045
+ charStart: expected.charStart,
1046
+ charEnd: expected.charEnd
1047
+ }],
1048
+ rank: 1
1049
+ };
1050
+ }
1051
+ }
1052
+ function memoryLifecycleCase(input) {
1053
+ const staleEventId = `${input.id}:stale`;
1054
+ const currentEventId = `${input.id}:current`;
1055
+ return {
1056
+ id: input.id,
1057
+ family: input.family,
1058
+ taskKind: input.taskKind,
1059
+ split: input.split,
1060
+ tags: unique([
1061
+ "first-party-memory-lifecycle",
1062
+ input.taskKind,
1063
+ input.split
1064
+ ]),
1065
+ source: input.source,
1066
+ events: [{
1067
+ id: staleEventId,
1068
+ actorId: input.actorId,
1069
+ sessionId: `${input.id}:session-1`,
1070
+ timestamp: "2026-01-01T00:00:00.000Z",
1071
+ text: input.staleText
1072
+ }, {
1073
+ id: currentEventId,
1074
+ actorId: input.actorId,
1075
+ sessionId: `${input.id}:session-2`,
1076
+ timestamp: "2026-02-01T00:00:00.000Z",
1077
+ text: input.currentText
1078
+ }],
1079
+ prompt: input.prompt,
1080
+ requiredFacts: [{
1081
+ id: `${input.id}:required-1`,
1082
+ anyOf: [input.required],
1083
+ sourceEventIds: [currentEventId]
1084
+ }, ...input.extraRequired ? [{
1085
+ id: `${input.id}:required-2`,
1086
+ anyOf: [input.extraRequired],
1087
+ sourceEventIds: [currentEventId]
1088
+ }] : []],
1089
+ forbiddenFacts: [{
1090
+ id: `${input.id}:stale`,
1091
+ anyOf: [input.forbidden],
1092
+ sourceEventIds: [staleEventId],
1093
+ obsolete: true
1094
+ }],
1095
+ expectedEventIds: [currentEventId],
1096
+ expectedActorIds: [input.actorId],
1097
+ referenceAnswer: input.required
1098
+ };
1099
+ }
1100
+ //#endregion
1101
+ //#region src/memory/attempt-log.ts
1102
+ const journalByteLengths = /* @__PURE__ */ new WeakMap();
1103
+ const MEMORY_PROVIDER_ACTOR_PREFIXES = [
1104
+ "agent-knowledge:memory-adapter:",
1105
+ "agent-knowledge:memory-adapter-recovery:",
1106
+ "agent-knowledge:memory-experiment:",
1107
+ "agent-knowledge:memory-recovery:"
1108
+ ];
1109
+ function reconcileInterruptedMemoryPaidCalls(costLedger) {
1110
+ reconcileInterruptedPaidCallsAtMaximum(costLedger, (actor) => isMemoryProviderActor(actor), "external memory provider");
1111
+ }
1112
+ function reconcileInterruptedPaidCallsAtMaximum(costLedger, ownsActor, label) {
1113
+ if (costLedger.summary().unresolvedCalls === 0) return;
1114
+ const pending = requirePendingCostCallInspection(costLedger);
1115
+ for (const call of pending) {
1116
+ if (call.state !== "interrupted" || !ownsActor(call.actor)) continue;
1117
+ if (call.maximumCostUsd === void 0) throw new Error(`cannot recover unbounded interrupted ${label} call '${call.callId}' for '${call.actor}'`);
1118
+ try {
1119
+ costLedger.reconcile(call.callId, {
1120
+ model: call.model,
1121
+ inputTokens: 0,
1122
+ outputTokens: 0,
1123
+ actualCostUsd: call.maximumCostUsd
1124
+ }, { error: `process exited before the ${label} receipt for '${call.actor}' was recorded; charged the reserved maximum` });
1125
+ } catch (error) {
1126
+ if (isMissingPendingCostCall(error, call.callId)) continue;
1127
+ throw error;
1128
+ }
1129
+ }
1130
+ }
1131
+ function assertNoInterruptedPaidCalls(costLedger, label) {
1132
+ const unresolved = costLedger.summary().unresolvedCalls;
1133
+ if (unresolved === 0) return;
1134
+ const blocked = requirePendingCostCallInspection(costLedger).filter((call) => call.state !== "active");
1135
+ throw new Error(`${label} has ${unresolved} unresolved paid call(s) that cannot be resumed: ${blocked.map((call) => `${call.callId} (${call.actor}, ${call.state})`).join(", ")}`);
1136
+ }
1137
+ function hasSettledPaidCall(costLedger, callId) {
1138
+ return costLedger.list().some((receipt) => receipt.callId === callId);
1139
+ }
1140
+ function appendAttemptJournalEvent(input) {
1141
+ appendDurableJournalEvent(input);
1142
+ }
1143
+ function appendDurableJournalEvent(input) {
1144
+ const { storage, path, event, label } = input;
1145
+ if (!storage.append) throw new Error(`${label} requires CampaignStorage.append`);
1146
+ const line = `${JSON.stringify(event)}\n`;
1147
+ const byteLengths = journalByteLengths.get(storage) ?? /* @__PURE__ */ new Map();
1148
+ journalByteLengths.set(storage, byteLengths);
1149
+ for (let retry = 0; retry < 100; retry += 1) {
1150
+ let expectedBytes = byteLengths.get(path);
1151
+ if (expectedBytes === void 0) {
1152
+ const current = storage.read(path);
1153
+ if (current === void 0 && storage.exists(path)) throw new Error(`cannot read ${label} '${path}'`);
1154
+ expectedBytes = new TextEncoder().encode(current ?? "").byteLength;
1155
+ byteLengths.set(path, expectedBytes);
1156
+ }
1157
+ const appendedBytes = storage.append(path, line, expectedBytes);
1158
+ if (appendedBytes !== void 0) {
1159
+ byteLengths.set(path, appendedBytes);
1160
+ return;
1161
+ }
1162
+ byteLengths.delete(path);
1163
+ }
1164
+ throw new Error(`${label} '${path}' remained contended after 100 retries`);
1165
+ }
1166
+ /** Reserves one durable recovery generation per attempt before provider work starts. */
1167
+ function reserveRecoveryAttempts(input) {
1168
+ const { storage, path, attemptIds, maxRetriesPerAttempt, label } = input;
1169
+ if (!Number.isSafeInteger(maxRetriesPerAttempt) || maxRetriesPerAttempt <= 0) throw new Error(`${label} maxRetriesPerAttempt must be a positive safe integer`);
1170
+ if (new Set(attemptIds).size !== attemptIds.length || attemptIds.some((id) => !id.trim())) throw new Error(`${label} attempt ids must be unique non-empty strings`);
1171
+ const generations = readRecoveryAttemptGenerations(storage, path, label);
1172
+ for (const attemptId of attemptIds) if ((generations.get(attemptId) ?? 0) >= maxRetriesPerAttempt) throw new Error(`${label} '${attemptId}' exhausted ${maxRetriesPerAttempt} recovery attempts; increase maxRecoveryRetriesPerAttempt only after inspecting provider state`);
1173
+ const reserved = /* @__PURE__ */ new Map();
1174
+ for (const attemptId of attemptIds) {
1175
+ const generation = (generations.get(attemptId) ?? 0) + 1;
1176
+ appendDurableJournalEvent({
1177
+ storage,
1178
+ path,
1179
+ label,
1180
+ event: {
1181
+ attemptId,
1182
+ generation,
1183
+ recordedAt: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString()
1184
+ }
1185
+ });
1186
+ generations.set(attemptId, generation);
1187
+ reserved.set(attemptId, generation);
1188
+ }
1189
+ return reserved;
1190
+ }
1191
+ function readActiveAttemptJournal(input) {
1192
+ const { storage, path, label, parse, id, sameAttempt } = input;
1193
+ const stored = storage.read(path);
1194
+ if (stored === void 0) {
1195
+ if (storage.exists(path)) throw new Error(`cannot read ${label} '${path}'`);
1196
+ return [];
1197
+ }
1198
+ const active = /* @__PURE__ */ new Map();
1199
+ const completed = /* @__PURE__ */ new Map();
1200
+ for (const [index, line] of stored.split("\n").entries()) {
1201
+ if (!line) continue;
1202
+ let raw;
1203
+ try {
1204
+ raw = JSON.parse(line);
1205
+ } catch (error) {
1206
+ throw new Error(`invalid ${label} '${path}' line ${index + 1}`, { cause: error });
1207
+ }
1208
+ const event = parse(raw, path, index + 1);
1209
+ const attemptId = id(event);
1210
+ if (event.status === "started") {
1211
+ if (active.has(attemptId) || completed.has(attemptId)) throw new Error(`${label} '${path}' repeats attempt '${attemptId}'`);
1212
+ active.set(attemptId, event);
1213
+ continue;
1214
+ }
1215
+ const started = active.get(attemptId);
1216
+ if (started && sameAttempt(started, event)) {
1217
+ active.delete(attemptId);
1218
+ completed.set(attemptId, started);
1219
+ continue;
1220
+ }
1221
+ const prior = completed.get(attemptId);
1222
+ if (prior && sameAttempt(prior, event)) continue;
1223
+ throw new Error(`${label} '${path}' has an unmatched cleanup for '${attemptId}'`);
1224
+ }
1225
+ return [...active.values()];
1226
+ }
1227
+ function readRecoveryAttemptGenerations(storage, path, label) {
1228
+ const stored = storage.read(path);
1229
+ if (stored === void 0) {
1230
+ if (storage.exists(path)) throw new Error(`cannot read ${label} '${path}'`);
1231
+ return /* @__PURE__ */ new Map();
1232
+ }
1233
+ const generations = /* @__PURE__ */ new Map();
1234
+ for (const [index, line] of stored.split("\n").entries()) {
1235
+ if (!line) continue;
1236
+ let raw;
1237
+ try {
1238
+ raw = JSON.parse(line);
1239
+ } catch (error) {
1240
+ throw new Error(`invalid ${label} '${path}' line ${index + 1}`, { cause: error });
1241
+ }
1242
+ const event = parseRecoveryAttemptEvent(raw, path, index + 1, label);
1243
+ const expected = (generations.get(event.attemptId) ?? 0) + 1;
1244
+ if (event.generation !== expected) throw new Error(`${label} '${path}' has recovery generation ${event.generation} for '${event.attemptId}', expected ${expected}`);
1245
+ generations.set(event.attemptId, event.generation);
1246
+ }
1247
+ return generations;
1248
+ }
1249
+ function parseRecoveryAttemptEvent(value, path, line, label) {
1250
+ const event = value;
1251
+ if (!(typeof event === "object" && event !== null && typeof event.attemptId === "string" && event.attemptId.length > 0 && Number.isSafeInteger(event.generation) && event.generation > 0 && typeof event.recordedAt === "string" && !Number.isNaN(Date.parse(event.recordedAt)))) throw new Error(`invalid ${label} '${path}' line ${line}`);
1252
+ return value;
1253
+ }
1254
+ function isMissingPendingCostCall(error, callId) {
1255
+ return error instanceof Error && error.message === `CostLedger: no pending call '${callId}'`;
1256
+ }
1257
+ function requirePendingCostCallInspection(costLedger) {
1258
+ if (!costLedger.listPending) throw new Error("interrupted memory recovery requires CostLedger.listPending() support");
1259
+ return costLedger.listPending();
1260
+ }
1261
+ function isMemoryProviderActor(actor) {
1262
+ return MEMORY_PROVIDER_ACTOR_PREFIXES.some((prefix) => actor.startsWith(prefix));
1263
+ }
1264
+ //#endregion
1265
+ //#region src/memory/lifecycle.ts
1266
+ const DEFAULT_MEMORY_CLEANUP_TIMEOUT_MS = 18e4;
1267
+ var AgentMemoryLifecycleTimeoutError = class extends Error {
1268
+ operation;
1269
+ timeoutMs;
1270
+ constructor(operation, timeoutMs) {
1271
+ super(`${operation} did not finish within ${timeoutMs}ms`);
1272
+ this.operation = operation;
1273
+ this.timeoutMs = timeoutMs;
1274
+ this.name = "AgentMemoryLifecycleTimeoutError";
1275
+ }
1276
+ };
1277
+ var AgentMemoryLifecycleUnsafeError = class extends Error {
1278
+ operation;
1279
+ priorTimeout;
1280
+ constructor(operation, priorTimeout) {
1281
+ super(`${operation} cannot start because '${priorTimeout.operation}' is still running after its ${priorTimeout.timeoutMs}ms timeout`, { cause: priorTimeout });
1282
+ this.operation = operation;
1283
+ this.priorTimeout = priorTimeout;
1284
+ this.name = "AgentMemoryLifecycleUnsafeError";
1285
+ }
1286
+ };
1287
+ const timedOutResources = /* @__PURE__ */ new WeakMap();
1288
+ function releaseMemoryAdapterCreatedAfterAbort(input) {
1289
+ input.creation.then(async (adapter) => {
1290
+ if (!adapter || !input.signal.aborted) return;
1291
+ try {
1292
+ await adapter.close?.();
1293
+ } catch {}
1294
+ try {
1295
+ await input.dispose?.(adapter);
1296
+ } catch {}
1297
+ }, () => void 0);
1298
+ }
1299
+ function resolveMemoryCleanupTimeoutMs(value, label) {
1300
+ const timeoutMs = value ?? 18e4;
1301
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new Error(`${label} cleanupTimeoutMs must be a positive safe integer`);
1302
+ return timeoutMs;
1303
+ }
1304
+ async function runBoundedMemoryLifecycle(input) {
1305
+ const priorTimeout = input.resource ? timedOutResources.get(input.resource) : void 0;
1306
+ if (priorTimeout) throw new AgentMemoryLifecycleUnsafeError(input.operation, priorTimeout);
1307
+ let timeout;
1308
+ let timeoutError;
1309
+ const work = Promise.resolve().then(input.run);
1310
+ if (input.resource) {
1311
+ const resource = input.resource;
1312
+ work.then(() => {
1313
+ if (timeoutError && timedOutResources.get(resource) === timeoutError) timedOutResources.delete(resource);
1314
+ }, () => {
1315
+ if (timeoutError && timedOutResources.get(resource) === timeoutError) timedOutResources.delete(resource);
1316
+ });
1317
+ }
1318
+ const deadline = new Promise((_, reject) => {
1319
+ timeout = setTimeout(() => {
1320
+ timeoutError = new AgentMemoryLifecycleTimeoutError(input.operation, input.timeoutMs);
1321
+ if (input.resource) timedOutResources.set(input.resource, timeoutError);
1322
+ input.abortController?.abort(timeoutError);
1323
+ reject(timeoutError);
1324
+ }, input.timeoutMs);
1325
+ });
1326
+ try {
1327
+ return await Promise.race([work, deadline]);
1328
+ } finally {
1329
+ if (timeout) clearTimeout(timeout);
1330
+ }
1331
+ }
1332
+ function memoryRecoveryDelayMs(adapter) {
1333
+ const isolation = adapter.branchIsolation;
1334
+ if (isolation?.mode !== "scoped" || isolation.processExitSafe !== false) return 0;
1335
+ const delayMs = isolation.recoveryDelayMs;
1336
+ if (typeof delayMs !== "number" || !Number.isSafeInteger(delayMs) || delayMs <= 0) throw new Error(`${adapter.id}: processExitSafe=false requires a positive recoveryDelayMs for abandoned writes`);
1337
+ return delayMs;
1338
+ }
1339
+ async function sleepForMemoryRecovery(delayMs, assertOwned, timeoutMs = delayMs, operation = "memory recovery visibility wait") {
1340
+ if (delayMs <= 0) return;
1341
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw new Error(`${operation} timeout must be a positive safe integer`);
1342
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, timeoutMs)));
1343
+ await assertOwned();
1344
+ if (delayMs > timeoutMs) throw new AgentMemoryLifecycleTimeoutError(operation, timeoutMs);
1345
+ }
1346
+ function createMemoryExecutionPool(limit) {
1347
+ let active = 0;
1348
+ const waiters = [];
1349
+ return { async run(operation) {
1350
+ if (active >= limit) await new Promise((resolve) => waiters.push(resolve));
1351
+ active += 1;
1352
+ try {
1353
+ return await operation();
1354
+ } finally {
1355
+ active -= 1;
1356
+ waiters.shift()?.();
1357
+ }
1358
+ } };
1359
+ }
1360
+ //#endregion
1361
+ //#region src/memory/run-control.ts
1362
+ const activeProcessLocalRuns = /* @__PURE__ */ new Set();
1363
+ async function acquireAgentMemoryRunLease(input) {
1364
+ if (input.acquireRunLease && input.controllerMode) throw new Error(`${input.label} cannot combine acquireRunLease with controllerMode`);
1365
+ if (input.acquireRunLease) {
1366
+ const lease = await input.acquireRunLease({
1367
+ experimentId: input.experimentId,
1368
+ runDir: input.runDir
1369
+ });
1370
+ if (!lease || typeof lease.assertOwned !== "function" || typeof lease.release !== "function") throw new Error(`${input.label} acquireRunLease must return assertOwned and release`);
1371
+ return {
1372
+ async assertOwned() {
1373
+ await lease.assertOwned();
1374
+ },
1375
+ async release() {
1376
+ await lease.release();
1377
+ }
1378
+ };
1379
+ }
1380
+ if (!input.customStorage) {
1381
+ if (input.controllerMode) throw new Error(`${input.label} controllerMode is only valid with custom storage`);
1382
+ const lock = acquireSingleRunLock({
1383
+ lockPath: join(input.runDir, input.lockFileName),
1384
+ releaseOnExit: false
1385
+ });
1386
+ return {
1387
+ async assertOwned() {},
1388
+ async release() {
1389
+ lock.release();
1390
+ }
1391
+ };
1392
+ }
1393
+ if (input.controllerMode !== "process-local") throw new Error(`${input.label} custom storage requires acquireRunLease or controllerMode='process-local'`);
1394
+ const runKey = `${input.label}:${input.runDir}`;
1395
+ if (activeProcessLocalRuns.has(runKey)) throw new Error(`${input.label} run '${input.runDir}' already has an active controller`);
1396
+ activeProcessLocalRuns.add(runKey);
1397
+ let released = false;
1398
+ return {
1399
+ async assertOwned() {
1400
+ if (released || !activeProcessLocalRuns.has(runKey)) throw new Error(`${input.label} run '${input.runDir}' controller lease was lost`);
1401
+ },
1402
+ async release() {
1403
+ if (released) return;
1404
+ released = true;
1405
+ activeProcessLocalRuns.delete(runKey);
1406
+ }
1407
+ };
1408
+ }
1409
+ //#endregion
1410
+ //#region src/benchmarks/memory-recovery.ts
1411
+ function memoryAdapterBenchmarkExpectedId(candidate) {
1412
+ return candidate.adapterId ?? candidate.id;
1413
+ }
1414
+ async function recoverMemoryAdapterBenchmarkAttempts(input) {
1415
+ let attempts = readActiveMemoryBenchmarkAttempts(input.storage, input.attemptLogPath);
1416
+ if (attempts.length > input.maxRecoveryAttempts) throw new Error(`memory adapter benchmark has ${attempts.length} unfinished attempts; maxRecoveryAttempts is ${input.maxRecoveryAttempts}`);
1417
+ const candidateById = new Map(input.candidates.map((candidate) => [candidate.id, candidate]));
1418
+ for (const attempt of attempts) {
1419
+ const candidate = candidateById.get(attempt.candidateId);
1420
+ if (!candidate) throw new Error(`cannot recover memory benchmark attempts: candidate '${attempt.candidateId}' is missing; pass it in recoveryCandidates`);
1421
+ assertMemoryBenchmarkAttemptCandidateMatches(attempt, candidate);
1422
+ }
1423
+ reconcileInterruptedMemoryPaidCalls(input.costLedger);
1424
+ assertNoInterruptedPaidCalls(input.costLedger, "memory adapter benchmark recovery");
1425
+ for (const attempt of attempts) if ((candidateById.get(attempt.candidateId).costUsdPerCase ?? 0) > 0 && !hasSettledPaidCall(input.costLedger, memoryBenchmarkCostCallId(attempt, "execute", 0))) appendMemoryBenchmarkAttemptEvent(input.storage, input.attemptLogPath, {
1426
+ ...attempt,
1427
+ status: "cleaned",
1428
+ recovery: true,
1429
+ recordedAt: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString()
1430
+ });
1431
+ attempts = readActiveMemoryBenchmarkAttempts(input.storage, input.attemptLogPath);
1432
+ const recoveryGenerations = reserveRecoveryAttempts({
1433
+ storage: input.storage,
1434
+ path: input.recoveryLogPath,
1435
+ attemptIds: attempts.map((attempt) => attempt.attemptId),
1436
+ maxRetriesPerAttempt: input.maxRecoveryRetriesPerAttempt,
1437
+ label: "memory benchmark recovery attempt log",
1438
+ now: input.now
1439
+ });
1440
+ const grouped = groupMemoryBenchmarkAttempts(attempts);
1441
+ const pool = createMemoryExecutionPool(input.maxConcurrency);
1442
+ const failures = (await Promise.allSettled([...grouped].sort(([left], [right]) => left.localeCompare(right)).map(([candidateId, candidateAttempts]) => pool.run(async () => {
1443
+ await input.lease.assertOwned();
1444
+ const candidate = candidateById.get(candidateId);
1445
+ if (!candidate) throw new Error(`cannot recover memory benchmark attempts: candidate '${candidateId}' is missing; pass it in recoveryCandidates`);
1446
+ for (const attempt of candidateAttempts) {
1447
+ assertMemoryBenchmarkAttemptCandidateMatches(attempt, candidate);
1448
+ if (recoveryGenerations.get(attempt.attemptId) === void 0) throw new Error(`missing recovery generation for memory benchmark attempt '${attempt.attemptId}'`);
1449
+ }
1450
+ let recoveryAttemptsStarted = 0;
1451
+ let adapterCreationExternalCallAttempted = false;
1452
+ const cleared = [];
1453
+ const recover = async () => {
1454
+ let adapter;
1455
+ let primaryError;
1456
+ try {
1457
+ const abortController = new AbortController();
1458
+ const creation = Promise.resolve().then(() => candidate.createAdapter({
1459
+ purpose: "recovery",
1460
+ signal: abortController.signal,
1461
+ markExternalCall: () => {
1462
+ adapterCreationExternalCallAttempted = true;
1463
+ }
1464
+ }));
1465
+ releaseMemoryAdapterCreatedAfterAbort({
1466
+ creation,
1467
+ signal: abortController.signal
1468
+ });
1469
+ adapter = await runBoundedMemoryLifecycle({
1470
+ operation: `${candidate.id}: benchmark recovery adapter creation`,
1471
+ timeoutMs: input.cleanupTimeoutMs,
1472
+ abortController,
1473
+ run: () => creation
1474
+ });
1475
+ assertScopedMemoryBenchmarkAdapter(adapter);
1476
+ for (const attempt of candidateAttempts) if (adapter.id !== attempt.adapterId) throw new Error(`cannot recover memory benchmark attempt '${attempt.attemptId}': adapter changed from '${attempt.adapterId}' to '${adapter.id}'`);
1477
+ await sleepForMemoryRecovery(memoryRecoveryDelayMs(adapter), () => input.lease.assertOwned(), input.cleanupTimeoutMs, `${candidate.id}: benchmark recovery visibility wait`);
1478
+ for (const attempt of candidateAttempts.sort((left, right) => left.attemptId.localeCompare(right.attemptId))) {
1479
+ await input.lease.assertOwned();
1480
+ try {
1481
+ recoveryAttemptsStarted += 1;
1482
+ await runBoundedMemoryLifecycle({
1483
+ operation: `${candidate.id}: abandoned benchmark attempt cleanup`,
1484
+ timeoutMs: input.cleanupTimeoutMs,
1485
+ resource: adapter,
1486
+ run: () => adapter.clear(attempt.scope)
1487
+ });
1488
+ await input.lease.assertOwned();
1489
+ cleared.push(attempt);
1490
+ } catch (error) {
1491
+ primaryError = primaryError ? new AggregateError([primaryError, error], `${candidate.id}: multiple benchmark attempts failed recovery`) : error;
1492
+ }
1493
+ }
1494
+ } catch (error) {
1495
+ primaryError = primaryError ? new AggregateError([primaryError, error], `${candidate.id}: benchmark recovery failed in multiple operations`) : error;
1496
+ }
1497
+ let closeError;
1498
+ if (adapter) try {
1499
+ await runBoundedMemoryLifecycle({
1500
+ operation: `${candidate.id}: benchmark recovery adapter close`,
1501
+ timeoutMs: input.cleanupTimeoutMs,
1502
+ resource: adapter,
1503
+ run: () => adapter.close?.()
1504
+ });
1505
+ } catch (error) {
1506
+ closeError = error;
1507
+ }
1508
+ let journalError;
1509
+ if (!closeError) try {
1510
+ for (const attempt of cleared) {
1511
+ await input.lease.assertOwned();
1512
+ appendMemoryBenchmarkAttemptEvent(input.storage, input.attemptLogPath, {
1513
+ ...attempt,
1514
+ status: "cleaned",
1515
+ recovery: true,
1516
+ recordedAt: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString()
1517
+ });
1518
+ }
1519
+ } catch (error) {
1520
+ journalError = error;
1521
+ }
1522
+ const failures = [
1523
+ primaryError,
1524
+ closeError,
1525
+ journalError
1526
+ ].filter((error) => error !== void 0);
1527
+ if (failures.length > 1) throw new AggregateError(failures, `${candidate.id}: benchmark attempt recovery, adapter close, or cleanup journal failed`);
1528
+ if (primaryError) throw primaryError;
1529
+ if (closeError) throw closeError;
1530
+ if (journalError) throw journalError;
1531
+ };
1532
+ const recoveryCostUsd = candidate.recoveryCostUsdPerAttempt ?? 0;
1533
+ const adapterCreationCostUsd = candidate.adapterCreationCostUsd ?? 0;
1534
+ const maximumCostUsd = adapterCreationCostUsd + recoveryCostUsd * candidateAttempts.length;
1535
+ const actualCostUsd = () => (adapterCreationExternalCallAttempted ? adapterCreationCostUsd : 0) + recoveryCostUsd * recoveryAttemptsStarted;
1536
+ let recoveryError;
1537
+ if (maximumCostUsd === 0) try {
1538
+ await recover();
1539
+ } catch (error) {
1540
+ recoveryError = error;
1541
+ }
1542
+ else {
1543
+ const receipt = {
1544
+ model: candidate.id,
1545
+ inputTokens: 0,
1546
+ outputTokens: 0
1547
+ };
1548
+ const tags = memoryBenchmarkRecoveryCostTags(input.runDir, candidate.id);
1549
+ const paid = await input.costLedger.runPaidCall({
1550
+ callId: memoryBenchmarkRecoveryCostCallId(candidate, candidateAttempts, recoveryGenerations),
1551
+ channel: "driver",
1552
+ phase: `${input.costPhase}.${candidate.id}.recovery`,
1553
+ actor: `agent-knowledge:memory-adapter-recovery:${candidate.id}`,
1554
+ model: candidate.id,
1555
+ tags,
1556
+ maximumCharge: { externallyEnforcedMaximumUsd: maximumCostUsd },
1557
+ execute: recover,
1558
+ receipt: () => ({
1559
+ ...receipt,
1560
+ actualCostUsd: actualCostUsd()
1561
+ }),
1562
+ receiptFromError: () => ({
1563
+ ...receipt,
1564
+ actualCostUsd: actualCostUsd()
1565
+ })
1566
+ });
1567
+ if (!paid.succeeded) recoveryError = paid.error;
1568
+ }
1569
+ if (recoveryError) throw recoveryError;
1570
+ })))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
1571
+ if (failures.length === 1) throw failures[0];
1572
+ if (failures.length > 1) throw new AggregateError(failures, "multiple memory benchmark candidates failed recovery");
1573
+ }
1574
+ function groupMemoryBenchmarkAttempts(attempts) {
1575
+ const grouped = /* @__PURE__ */ new Map();
1576
+ for (const attempt of attempts) {
1577
+ const group = grouped.get(attempt.candidateId) ?? [];
1578
+ group.push(attempt);
1579
+ grouped.set(attempt.candidateId, group);
1580
+ }
1581
+ return grouped;
1582
+ }
1583
+ function memoryBenchmarkCostCallId(attempt, purpose, generation) {
1584
+ return stableId("memory_benchmark_cost_call", canonicalJson({
1585
+ purpose,
1586
+ generation,
1587
+ attemptId: attempt.attemptId,
1588
+ candidateId: attempt.candidateId,
1589
+ candidateRef: attempt.candidateRef,
1590
+ adapterId: attempt.adapterId,
1591
+ adapterCreationCostUsd: attempt.adapterCreationCostUsd,
1592
+ costUsdPerCase: attempt.costUsdPerCase,
1593
+ recoveryCostUsdPerAttempt: attempt.recoveryCostUsdPerAttempt,
1594
+ caseId: attempt.caseId,
1595
+ cellId: attempt.cellId
1596
+ }));
1597
+ }
1598
+ function memoryBenchmarkRecoveryCostCallId(candidate, attempts, generations) {
1599
+ return stableId("memory_benchmark_recovery_cost_call", canonicalJson({
1600
+ candidateId: candidate.id,
1601
+ candidateRef: candidate.ref,
1602
+ adapterCreationCostUsd: candidate.adapterCreationCostUsd ?? 0,
1603
+ recoveryCostUsdPerAttempt: candidate.recoveryCostUsdPerAttempt ?? 0,
1604
+ attempts: attempts.map((attempt) => ({
1605
+ attemptId: attempt.attemptId,
1606
+ generation: generations.get(attempt.attemptId)
1607
+ })).sort((left, right) => left.attemptId.localeCompare(right.attemptId))
1608
+ }));
1609
+ }
1610
+ function memoryBenchmarkRecoveryCostTags(runDir, candidateId) {
1611
+ return {
1612
+ runDir: join(runDir, candidateId),
1613
+ candidateId,
1614
+ memoryRecovery: "benchmark"
1615
+ };
1616
+ }
1617
+ function appendMemoryBenchmarkAttemptEvent(storage, path, event) {
1618
+ appendAttemptJournalEvent({
1619
+ storage,
1620
+ path,
1621
+ event,
1622
+ label: "memory benchmark attempt log"
1623
+ });
1624
+ }
1625
+ function readActiveMemoryBenchmarkAttempts(storage, path) {
1626
+ return readActiveAttemptJournal({
1627
+ storage,
1628
+ path,
1629
+ label: "memory benchmark attempt log",
1630
+ parse: parseMemoryBenchmarkAttemptEvent,
1631
+ id: (event) => event.attemptId,
1632
+ sameAttempt: sameMemoryBenchmarkAttempt
1633
+ });
1634
+ }
1635
+ function parseMemoryBenchmarkAttemptEvent(value, path, line) {
1636
+ const event = value;
1637
+ if (!(typeof event === "object" && event !== null && (event.status === "started" || event.status === "cleaned") && isNonEmptyString(event.attemptId) && isNonEmptyString(event.candidateId) && isNonEmptyString(event.candidateRef) && isNonEmptyString(event.adapterId) && isNonEmptyString(event.caseId) && isNonEmptyString(event.cellId) && isAgentMemoryScope(event.scope) && typeof event.adapterCreationCostUsd === "number" && Number.isFinite(event.adapterCreationCostUsd) && event.adapterCreationCostUsd >= 0 && typeof event.costUsdPerCase === "number" && Number.isFinite(event.costUsdPerCase) && event.costUsdPerCase >= 0 && typeof event.recoveryCostUsdPerAttempt === "number" && Number.isFinite(event.recoveryCostUsdPerAttempt) && event.recoveryCostUsdPerAttempt >= 0 && typeof event.recordedAt === "string" && !Number.isNaN(Date.parse(event.recordedAt)) && typeof event.recovery === "boolean")) throw new Error(`invalid memory benchmark attempt event in '${path}' line ${line}`);
1638
+ return value;
1639
+ }
1640
+ function sameMemoryBenchmarkAttempt(left, right) {
1641
+ return left.attemptId === right.attemptId && left.candidateId === right.candidateId && left.candidateRef === right.candidateRef && left.adapterId === right.adapterId && left.caseId === right.caseId && left.cellId === right.cellId && canonicalJson(left.scope) === canonicalJson(right.scope) && left.adapterCreationCostUsd === right.adapterCreationCostUsd && left.costUsdPerCase === right.costUsdPerCase && left.recoveryCostUsdPerAttempt === right.recoveryCostUsdPerAttempt;
1642
+ }
1643
+ function assertMemoryBenchmarkAttemptCandidateMatches(attempt, candidate) {
1644
+ if (attempt.candidateRef !== candidate.ref) throw new Error(`cannot recover memory benchmark attempt '${attempt.attemptId}': candidate ref changed from '${attempt.candidateRef}' to '${candidate.ref}'`);
1645
+ const expectedAdapterId = memoryAdapterBenchmarkExpectedId(candidate);
1646
+ if (attempt.adapterId !== expectedAdapterId) throw new Error(`cannot recover memory benchmark attempt '${attempt.attemptId}': adapter id changed from '${attempt.adapterId}' to '${expectedAdapterId}'`);
1647
+ const executionCost = candidate.costUsdPerCase ?? 0;
1648
+ const adapterCreationCost = candidate.adapterCreationCostUsd ?? 0;
1649
+ const recoveryCost = candidate.recoveryCostUsdPerAttempt ?? 0;
1650
+ if (adapterCreationCost !== attempt.adapterCreationCostUsd || executionCost !== attempt.costUsdPerCase || recoveryCost !== attempt.recoveryCostUsdPerAttempt) throw new Error(`cannot recover memory benchmark attempt '${attempt.attemptId}': candidate cost settings changed; start a new run or restore the recorded costs`);
1651
+ }
1652
+ function assertScopedMemoryBenchmarkAdapter(adapter) {
1653
+ if (adapter.branchIsolation?.mode !== "scoped") throw new Error(`${adapter.id}: direct memory benchmark requires branchIsolation mode scoped; use runAgentMemoryExperiment for dedicated instances`);
1654
+ if (!adapter.clear) throw new Error(`${adapter.id}: direct memory benchmark requires exact scoped clear`);
1655
+ }
1656
+ function isAgentMemoryScope(value) {
1657
+ if (!isRecordValue(value)) return false;
1658
+ const allowed = /* @__PURE__ */ new Set([
1659
+ "tenantId",
1660
+ "userId",
1661
+ "agentId",
1662
+ "teamId",
1663
+ "runId",
1664
+ "sessionId",
1665
+ "namespace",
1666
+ "tags"
1667
+ ]);
1668
+ if (Object.keys(value).some((key) => !allowed.has(key))) return false;
1669
+ for (const key of [
1670
+ "tenantId",
1671
+ "userId",
1672
+ "agentId",
1673
+ "teamId",
1674
+ "runId",
1675
+ "sessionId",
1676
+ "namespace"
1677
+ ]) if (value[key] !== void 0 && typeof value[key] !== "string") return false;
1678
+ if (value.tags === void 0) return true;
1679
+ return isRecordValue(value.tags) && Object.values(value.tags).every((entry) => typeof entry === "string");
1680
+ }
1681
+ function isNonEmptyString(value) {
1682
+ return typeof value === "string" && value.trim().length > 0;
1683
+ }
1684
+ function isRecordValue(value) {
1685
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1686
+ }
1687
+ //#endregion
1688
+ //#region src/benchmarks/memory-responder.ts
1689
+ function createMemoryAdapterBenchmarkResponder(options) {
1690
+ assertScopedMemoryBenchmarkAdapter(options.adapter);
1691
+ return async ({ case: testCase, context: dispatchContext }) => {
1692
+ if (!isKnowledgeMemoryBenchmarkCase(testCase)) return {
1693
+ answer: "",
1694
+ metadata: {
1695
+ candidateId: options.candidateId,
1696
+ skipped: true
1697
+ }
1698
+ };
1699
+ const costUsd = options.costUsdPerCase ?? 0;
1700
+ if (!Number.isFinite(costUsd) || costUsd < 0) throw new Error(`memory adapter costUsdPerCase must be non-negative finite, got ${costUsd}`);
1701
+ dispatchContext.signal.throwIfAborted();
1702
+ await options.lease.assertOwned();
1703
+ const startedAt = Date.now();
1704
+ const attemptId = randomUUID();
1705
+ const scope = benchmarkMemoryScope(options.candidateId, testCase, dispatchContext.cellId, attemptId, options.scope);
1706
+ const attempt = {
1707
+ status: "started",
1708
+ attemptId,
1709
+ candidateId: options.candidateId,
1710
+ candidateRef: options.candidateRef,
1711
+ adapterId: options.adapter.id,
1712
+ caseId: testCase.id,
1713
+ cellId: dispatchContext.cellId,
1714
+ scope,
1715
+ adapterCreationCostUsd: options.adapterCreationCostUsd ?? 0,
1716
+ costUsdPerCase: costUsd,
1717
+ recoveryCostUsdPerAttempt: options.recoveryCostUsdPerAttempt ?? 0,
1718
+ recordedAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
1719
+ recovery: false
1720
+ };
1721
+ appendMemoryBenchmarkAttemptEvent(options.storage, options.attemptLogPath, attempt);
1722
+ let externalCallAttempted = false;
1723
+ const appendCleanedAttempt = (priorError) => {
1724
+ try {
1725
+ appendMemoryBenchmarkAttemptEvent(options.storage, options.attemptLogPath, {
1726
+ ...attempt,
1727
+ status: "cleaned",
1728
+ recordedAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString()
1729
+ });
1730
+ } catch (error) {
1731
+ throw new MemoryAdapterBenchmarkCleanupError([...priorError ? [priorError] : [], error], `${options.candidateId}: memory benchmark cleanup could not be recorded`);
1732
+ }
1733
+ };
1734
+ const execute = async () => {
1735
+ dispatchContext.signal.throwIfAborted();
1736
+ await options.lease.assertOwned();
1737
+ let artifact;
1738
+ let primaryError;
1739
+ try {
1740
+ for (const event of testCase.events) {
1741
+ dispatchContext.signal.throwIfAborted();
1742
+ await options.lease.assertOwned();
1743
+ externalCallAttempted = true;
1744
+ await options.adapter.write({
1745
+ id: event.id,
1746
+ kind: "message",
1747
+ text: event.text,
1748
+ role: event.actorId === "user" ? "user" : "assistant",
1749
+ title: `${testCase.id}:${event.id}`,
1750
+ scope,
1751
+ metadata: compactObject({
1752
+ benchmarkCaseId: testCase.id,
1753
+ benchmarkCellId: dispatchContext.cellId,
1754
+ benchmarkAttemptId: attemptId,
1755
+ eventId: event.id,
1756
+ actorId: event.actorId,
1757
+ sessionId: event.sessionId,
1758
+ timestamp: event.timestamp,
1759
+ ...event.metadata
1760
+ })
1761
+ });
1762
+ dispatchContext.signal.throwIfAborted();
1763
+ await options.lease.assertOwned();
1764
+ }
1765
+ externalCallAttempted = true;
1766
+ await options.adapter.flush?.();
1767
+ dispatchContext.signal.throwIfAborted();
1768
+ await options.lease.assertOwned();
1769
+ externalCallAttempted = true;
1770
+ const adapterContext = await options.adapter.getContext(testCase.prompt, {
1771
+ scope,
1772
+ limit: options.searchLimit ?? 1,
1773
+ metadata: {
1774
+ benchmarkCaseId: testCase.id,
1775
+ benchmarkCellId: dispatchContext.cellId,
1776
+ benchmarkAttemptId: attemptId,
1777
+ candidateId: options.candidateId
1778
+ }
1779
+ });
1780
+ dispatchContext.signal.throwIfAborted();
1781
+ await options.lease.assertOwned();
1782
+ const hits = adapterContext.hits;
1783
+ artifact = {
1784
+ answer: adapterContext.text,
1785
+ rememberedFacts: hits.map((hit) => hit.text),
1786
+ citedEventIds: unique(hits.map(memoryEventId).filter((id) => Boolean(id))),
1787
+ usedMemoryIds: hits.map((hit) => hit.id),
1788
+ actorIds: unique(hits.map(memoryActorId).filter((id) => Boolean(id))),
1789
+ costUsd,
1790
+ durationMs: Math.max(0, Date.now() - startedAt),
1791
+ metadata: {
1792
+ candidateId: options.candidateId,
1793
+ adapterId: options.adapter.id,
1794
+ hitCount: hits.length
1795
+ }
1796
+ };
1797
+ } catch (error) {
1798
+ primaryError = error;
1799
+ }
1800
+ const cleanupErrors = [];
1801
+ let cleanupOwned = true;
1802
+ try {
1803
+ await options.lease.assertOwned();
1804
+ } catch (error) {
1805
+ cleanupOwned = false;
1806
+ cleanupErrors.push(error);
1807
+ }
1808
+ if (cleanupOwned) {
1809
+ try {
1810
+ await runBoundedMemoryLifecycle({
1811
+ operation: `${options.candidateId}: benchmark attempt flush`,
1812
+ timeoutMs: options.cleanupTimeoutMs,
1813
+ resource: options.adapter,
1814
+ run: () => {
1815
+ externalCallAttempted = true;
1816
+ return options.adapter.flush?.();
1817
+ }
1818
+ });
1819
+ } catch (error) {
1820
+ cleanupErrors.push(error);
1821
+ }
1822
+ try {
1823
+ await runBoundedMemoryLifecycle({
1824
+ operation: `${options.candidateId}: benchmark attempt cleanup`,
1825
+ timeoutMs: options.cleanupTimeoutMs,
1826
+ resource: options.adapter,
1827
+ run: () => {
1828
+ externalCallAttempted = true;
1829
+ return options.adapter.clear(scope);
1830
+ }
1831
+ });
1832
+ } catch (error) {
1833
+ cleanupErrors.push(error);
1834
+ }
1835
+ }
1836
+ if (cleanupOwned && cleanupErrors.length === 0) appendCleanedAttempt(primaryError);
1837
+ if (cleanupErrors.length > 0) throw new MemoryAdapterBenchmarkCleanupError([...primaryError ? [primaryError] : [], ...cleanupErrors], `${options.candidateId}: memory benchmark attempt cleanup failed`);
1838
+ if (primaryError) throw primaryError;
1839
+ if (!artifact) throw new Error(`${options.candidateId}: memory benchmark produced no artifact`);
1840
+ return artifact;
1841
+ };
1842
+ if (costUsd === 0) {
1843
+ let artifact;
1844
+ let error;
1845
+ try {
1846
+ artifact = await execute();
1847
+ } catch (caught) {
1848
+ error = caught;
1849
+ }
1850
+ if (error) throw error;
1851
+ if (!artifact) throw new Error(`${options.candidateId}: memory benchmark produced no artifact`);
1852
+ return artifact;
1853
+ }
1854
+ const receipt = {
1855
+ model: options.adapter.id,
1856
+ inputTokens: 0,
1857
+ outputTokens: 0,
1858
+ actualCostUsd: costUsd
1859
+ };
1860
+ const paid = await dispatchContext.cost.runPaidCall({
1861
+ callId: memoryBenchmarkCostCallId(attempt, "execute", 0),
1862
+ actor: `agent-knowledge:memory-adapter:${options.adapter.id}`,
1863
+ model: options.adapter.id,
1864
+ maximumCharge: { externallyEnforcedMaximumUsd: costUsd },
1865
+ execute,
1866
+ receipt: () => receipt,
1867
+ receiptFromError: () => ({
1868
+ ...receipt,
1869
+ actualCostUsd: externalCallAttempted ? costUsd : 0
1870
+ })
1871
+ });
1872
+ if (!paid.succeeded) throw paid.error;
1873
+ return paid.value;
1874
+ };
1875
+ }
1876
+ var MemoryAdapterBenchmarkCleanupError = class extends AggregateError {};
1877
+ function benchmarkMemoryScope(candidateId, testCase, cellId, attemptId, scope = {}) {
1878
+ return {
1879
+ ...scope,
1880
+ namespace: `${scope.namespace ?? "agent-knowledge-memory-benchmark"}:${attemptId}`,
1881
+ tags: {
1882
+ ...scope.tags ?? {},
1883
+ benchmarkCandidateId: candidateId,
1884
+ benchmarkCaseId: testCase.id,
1885
+ benchmarkCellId: cellId,
1886
+ benchmarkAttemptId: attemptId
1887
+ }
1888
+ };
1889
+ }
1890
+ //#endregion
1891
+ //#region src/benchmarks/metrics.ts
1892
+ function summarizeKnowledgeBenchmarkCampaign(input) {
1893
+ const scenariosById = new Map(input.scenarios.map((scenario) => [scenario.id, scenario]));
1894
+ const successful = input.campaign.cells.map((cell) => {
1895
+ const score = Object.values(cell.judgeScores)[0];
1896
+ return {
1897
+ cell,
1898
+ scenario: scenariosById.get(cell.scenarioId),
1899
+ composite: score?.composite ?? 0,
1900
+ passed: (score?.dimensions.passed ?? 0) >= 1,
1901
+ dimensions: score?.dimensions ?? {}
1902
+ };
1903
+ }).filter((row) => !row.cell.error);
1904
+ return {
1905
+ totalCases: input.scenarios.length,
1906
+ totalCells: input.campaign.cells.length,
1907
+ cellsFailed: input.campaign.aggregates.cellsFailed,
1908
+ cellsCached: input.campaign.aggregates.cellsCached,
1909
+ totalCostUsd: input.campaign.aggregates.cost.totalCostUsd,
1910
+ bySplit: summarizeSlices(successful, (row) => row.scenario?.splitTag ?? "unknown"),
1911
+ byFamily: summarizeSlices(successful, (row) => row.scenario?.family ?? "unknown"),
1912
+ byTaskKind: summarizeSlices(successful, (row) => row.scenario?.taskKind ?? "unknown"),
1913
+ dimensions: summarizeDimensions(successful.map((row) => row.dimensions)),
1914
+ score: distribution(successful.map((row) => row.composite))
1915
+ };
1916
+ }
1917
+ function summarizeDimensions(rows) {
1918
+ const values = /* @__PURE__ */ new Map();
1919
+ for (const row of rows) for (const [key, value] of Object.entries(row)) {
1920
+ if (!Number.isFinite(value)) continue;
1921
+ const list = values.get(key) ?? [];
1922
+ list.push(value);
1923
+ values.set(key, list);
1924
+ }
1925
+ return Object.fromEntries([...values.entries()].map(([key, vals]) => [key, distribution(vals)]));
1926
+ }
1927
+ function summarizeSlices(rows, keyOf) {
1928
+ const grouped = /* @__PURE__ */ new Map();
1929
+ for (const row of rows) {
1930
+ const key = keyOf(row);
1931
+ const list = grouped.get(key) ?? [];
1932
+ list.push(row);
1933
+ grouped.set(key, list);
1934
+ }
1935
+ return Object.fromEntries([...grouped.entries()].map(([key, list]) => {
1936
+ const withShape = list;
1937
+ return [key, {
1938
+ n: list.length,
1939
+ meanScore: mean(withShape.map((row) => row.composite)),
1940
+ passRate: mean(withShape.map((row) => row.passed ? 1 : 0)),
1941
+ score: distribution(withShape.map((row) => row.composite))
1942
+ }];
1943
+ }));
1944
+ }
1945
+ function distribution(values) {
1946
+ const finite = [...values].filter(Number.isFinite).sort((a, b) => a - b);
1947
+ if (finite.length === 0) return {
1948
+ n: 0,
1949
+ min: 0,
1950
+ mean: 0,
1951
+ median: 0,
1952
+ p90: 0,
1953
+ max: 0
1954
+ };
1955
+ return {
1956
+ n: finite.length,
1957
+ min: finite[0],
1958
+ mean: mean(finite),
1959
+ median: percentile(finite, .5),
1960
+ p90: percentile(finite, .9),
1961
+ max: finite[finite.length - 1]
1962
+ };
1963
+ }
1964
+ function percentile(sortedValues, p) {
1965
+ if (sortedValues.length === 0) return 0;
1966
+ return sortedValues[Math.min(sortedValues.length - 1, Math.max(0, Math.ceil(p * sortedValues.length) - 1))];
1967
+ }
1968
+ function renderSliceTable(slices) {
1969
+ const rows = Object.entries(slices).map(([key, slice]) => `| ${key} | ${slice.n} | ${formatNumber(slice.meanScore)} | ${formatNumber(slice.passRate)} | ${formatNumber(slice.score.p90)} |`);
1970
+ return [
1971
+ "| slice | n | mean score | pass rate | score p90 |",
1972
+ "| --- | ---: | ---: | ---: | ---: |",
1973
+ ...rows.length ? rows : ["| none | 0 | 0 | 0 | 0 |"]
1974
+ ].join("\n");
1975
+ }
1976
+ //#endregion
1977
+ //#region src/benchmarks/scoring.ts
1978
+ function scoreKnowledgeBenchmarkArtifact(testCase, artifact) {
1979
+ if (testCase.taskKind === "retrieval") {
1980
+ const metrics = scoreRetrievalArtifact(normalizeRetrievalArtifact(testCase, artifact), retrievalScenarioForCase(testCase));
1981
+ return {
1982
+ score: metrics.recall,
1983
+ passed: metrics.recall >= 1,
1984
+ dimensions: {
1985
+ recall: metrics.recall,
1986
+ mrr: metrics.mrr,
1987
+ ndcg: metrics.ndcg,
1988
+ precision_at_k: metrics.precisionAtK,
1989
+ expected_count: metrics.expectedCount,
1990
+ matched_count: metrics.matchedCount
1991
+ },
1992
+ notes: `matched ${metrics.matchedCount}/${metrics.expectedCount}; first_hit_rank=${metrics.firstHitRank ?? "none"}`,
1993
+ raw: { matchedTargetIds: metrics.matchedTargetIds }
1994
+ };
1995
+ }
1996
+ if (isKnowledgeMemoryBenchmarkCase(testCase)) return scoreMemoryBenchmarkArtifact(testCase, artifact);
1997
+ const answerArtifact = artifact;
1998
+ const text = answerArtifact.text ?? answerArtifact.answer ?? "";
1999
+ const required = scoreClaims(text, testCase.requiredClaims ?? []);
2000
+ const forbidden = scoreForbiddenClaims(text, testCase.forbiddenClaims ?? []);
2001
+ const citation = scoreCitationRecall(answerArtifact.citedSourceIds ?? [], testCase.expectedSourceIds ?? []);
2002
+ const score = mean([
2003
+ required.totalWeight > 0 ? required.recall : void 0,
2004
+ testCase.expectedSourceIds && testCase.expectedSourceIds.length > 0 ? citation : void 0,
2005
+ forbidden.safe
2006
+ ].filter((value) => value !== void 0));
2007
+ return {
2008
+ score,
2009
+ passed: score >= 1,
2010
+ dimensions: {
2011
+ claim_recall: required.recall,
2012
+ citation_recall: citation,
2013
+ hallucination_safe: forbidden.safe,
2014
+ forbidden_claim_rate: forbidden.rate,
2015
+ required_claim_count: required.total,
2016
+ matched_claim_count: required.matched,
2017
+ forbidden_claim_count: forbidden.total,
2018
+ matched_forbidden_claim_count: forbidden.matched
2019
+ },
2020
+ notes: `required=${required.matched}/${required.total}; forbidden=${forbidden.matched}/${forbidden.total}; citation_recall=${citation.toFixed(3)}`,
2021
+ raw: {
2022
+ matchedRequiredClaimIds: required.matchedIds,
2023
+ matchedForbiddenClaimIds: forbidden.matchedIds
2024
+ }
2025
+ };
2026
+ }
2027
+ function scoreMemoryBenchmarkArtifact(testCase, artifact) {
2028
+ const memoryArtifact = artifact;
2029
+ const text = [
2030
+ memoryArtifact.text,
2031
+ memoryArtifact.answer,
2032
+ ...memoryArtifact.rememberedFacts ?? []
2033
+ ].filter((part) => typeof part === "string" && part.length > 0).join("\n");
2034
+ const required = scoreClaims(text, testCase.requiredFacts ?? []);
2035
+ const forbidden = scoreForbiddenClaims(text, testCase.forbiddenFacts ?? []);
2036
+ const eventIds = unique([...memoryArtifact.citedEventIds ?? [], ...memoryArtifact.usedMemoryIds ?? []]);
2037
+ const eventRecall = scoreCitationRecall(eventIds, testCase.expectedEventIds ?? []);
2038
+ const actorRecall = scoreCitationRecall(memoryArtifact.actorIds ?? [], testCase.expectedActorIds ?? []);
2039
+ const score = mean([
2040
+ required.totalWeight > 0 ? required.recall : void 0,
2041
+ testCase.expectedEventIds && testCase.expectedEventIds.length > 0 ? eventRecall : void 0,
2042
+ testCase.expectedActorIds && testCase.expectedActorIds.length > 0 ? actorRecall : void 0,
2043
+ testCase.forbiddenFacts && testCase.forbiddenFacts.length > 0 ? forbidden.safe : void 0
2044
+ ].filter((value) => value !== void 0));
2045
+ const dimensions = {};
2046
+ if (required.totalWeight > 0) {
2047
+ dimensions.memory_fact_recall = required.recall;
2048
+ dimensions.memory_required_fact_count = required.total;
2049
+ dimensions.memory_matched_fact_count = required.matched;
2050
+ }
2051
+ if (testCase.expectedEventIds && testCase.expectedEventIds.length > 0) dimensions.memory_event_recall = eventRecall;
2052
+ if (testCase.expectedActorIds && testCase.expectedActorIds.length > 0) dimensions.memory_actor_recall = actorRecall;
2053
+ if (testCase.forbiddenFacts && testCase.forbiddenFacts.length > 0) {
2054
+ dimensions.memory_stale_safe = forbidden.safe;
2055
+ dimensions.memory_stale_rate = forbidden.rate;
2056
+ dimensions.memory_forbidden_fact_count = forbidden.total;
2057
+ dimensions.memory_matched_forbidden_fact_count = forbidden.matched;
2058
+ }
2059
+ return {
2060
+ score,
2061
+ passed: score >= 1,
2062
+ dimensions,
2063
+ applicableDimensions: Object.keys(dimensions),
2064
+ notes: `memory required=${required.matched}/${required.total}; stale=${forbidden.matched}/${forbidden.total}; event_recall=${eventRecall.toFixed(3)}; actor_recall=${actorRecall.toFixed(3)}`,
2065
+ raw: {
2066
+ matchedRequiredFactIds: required.matchedIds,
2067
+ matchedForbiddenFactIds: forbidden.matchedIds,
2068
+ citedEventIds: eventIds,
2069
+ actorIds: memoryArtifact.actorIds ?? []
2070
+ }
2071
+ };
2072
+ }
2073
+ function retrievalScenarioForCase(testCase) {
2074
+ return {
2075
+ id: testCase.id,
2076
+ kind: "retrieval-eval",
2077
+ query: testCase.query,
2078
+ expected: testCase.expected,
2079
+ ...testCase.k !== void 0 ? { k: testCase.k } : {}
2080
+ };
2081
+ }
2082
+ function normalizeRetrievalArtifact(testCase, artifact) {
2083
+ const maybe = artifact;
2084
+ const hits = maybe.hits ?? [];
2085
+ if (Array.isArray(maybe.hits) && maybe.query && maybe.requestedK !== void 0) return maybe;
2086
+ return {
2087
+ config: {},
2088
+ query: testCase.query,
2089
+ requestedK: testCase.k ?? Math.max(1, hits.length),
2090
+ hits,
2091
+ durationMs: maybe.durationMs ?? 0,
2092
+ ...maybe.costUsd !== void 0 ? { costUsd: maybe.costUsd } : {},
2093
+ ...maybe.metadata ? { metadata: maybe.metadata } : {}
2094
+ };
2095
+ }
2096
+ function scoreClaims(text, claims) {
2097
+ let matched = 0;
2098
+ let matchedWeight = 0;
2099
+ let totalWeight = 0;
2100
+ const matchedIds = [];
2101
+ const haystack = text.toLowerCase();
2102
+ for (const claim of claims) {
2103
+ if (!claim.id.trim() || claim.anyOf.length === 0 || claim.anyOf.some((value) => !value.trim())) throw new Error("claim matchers require a non-empty id and at least one non-empty alternative");
2104
+ const weight = claim.weight ?? 1;
2105
+ if (!Number.isFinite(weight) || weight <= 0) throw new Error(`claim matcher ${claim.id} weight must be a positive finite number`);
2106
+ totalWeight += weight;
2107
+ if (claim.anyOf.some((fragment) => haystack.includes(fragment.toLowerCase()))) {
2108
+ matched += 1;
2109
+ matchedWeight += weight;
2110
+ matchedIds.push(claim.id);
2111
+ }
2112
+ }
2113
+ return {
2114
+ total: claims.length,
2115
+ matched,
2116
+ totalWeight,
2117
+ recall: totalWeight === 0 ? 1 : matchedWeight / totalWeight,
2118
+ matchedIds
2119
+ };
2120
+ }
2121
+ function scoreForbiddenClaims(text, claims) {
2122
+ const matched = scoreClaims(text, claims);
2123
+ return {
2124
+ total: claims.length,
2125
+ matched: matched.matched,
2126
+ matchedIds: matched.matchedIds,
2127
+ rate: claims.length === 0 ? 0 : matched.matched / claims.length,
2128
+ safe: matched.matched === 0 ? 1 : 0
2129
+ };
2130
+ }
2131
+ function scoreCitationRecall(citedSourceIds, expectedSourceIds) {
2132
+ if (expectedSourceIds.length === 0) return 1;
2133
+ const cited = new Set(citedSourceIds);
2134
+ return expectedSourceIds.filter((sourceId) => cited.has(sourceId)).length / expectedSourceIds.length;
2135
+ }
2136
+ //#endregion
2137
+ //#region src/benchmarks/suite.ts
2138
+ const KNOWLEDGE_BENCHMARK_IMPLEMENTATION_REF = "agent-knowledge:benchmark-suite:v2";
2139
+ async function runKnowledgeBenchmarkSuite(options) {
2140
+ assertKnowledgeBenchmarkCases(options.cases);
2141
+ if (options.respondRef !== void 0) assertNonEmptyBenchmarkString(options.respondRef, "knowledge benchmark respondRef");
2142
+ else if (options.resumable !== false) throw new Error("knowledge benchmark respondRef is required when resumable is enabled");
2143
+ const storage = options.storage ?? fsCampaignStorage();
2144
+ const costCeiling = options.costCeiling ?? options.costLedger?.costCeilingUsd ?? 0;
2145
+ if (options.costLedger && options.costLedger.costCeilingUsd !== costCeiling) throw new Error("knowledge benchmark costCeiling must match the shared cost ledger ceiling");
2146
+ const scenarios = buildKnowledgeBenchmarkScenarios(options.cases, options.splits);
2147
+ const dispatch = async (scenario, context) => {
2148
+ return await options.respond({
2149
+ case: scenario.case,
2150
+ scenario,
2151
+ context
2152
+ });
2153
+ };
2154
+ const campaign = await runCampaign({
2155
+ scenarios,
2156
+ dispatch,
2157
+ dispatchRef: stableId("knowledge_benchmark", canonicalJson({
2158
+ implementationRef: KNOWLEDGE_BENCHMARK_IMPLEMENTATION_REF,
2159
+ respondRef: options.respondRef ?? "non-resumable"
2160
+ })),
2161
+ judges: [knowledgeBenchmarkJudge()],
2162
+ runDir: options.runDir,
2163
+ repo: options.repo,
2164
+ seed: options.seed,
2165
+ reps: options.reps,
2166
+ resumable: options.resumable,
2167
+ costCeiling,
2168
+ costLedger: options.costLedger,
2169
+ costPhase: options.costPhase,
2170
+ maxConcurrency: options.maxConcurrency,
2171
+ dispatchTimeoutMs: options.dispatchTimeoutMs,
2172
+ expectUsage: options.expectUsage ?? "off",
2173
+ storage,
2174
+ now: options.now
2175
+ });
2176
+ const report = summarizeKnowledgeBenchmarkCampaign({
2177
+ scenarios,
2178
+ campaign
2179
+ });
2180
+ const reportJsonPath = join(campaign.runDir, "knowledge-benchmark-report.json");
2181
+ const reportMarkdownPath = join(campaign.runDir, "knowledge-benchmark-report.md");
2182
+ storage.write(reportJsonPath, `${JSON.stringify(report, null, 2)}\n`);
2183
+ storage.write(reportMarkdownPath, renderKnowledgeBenchmarkReportMarkdown(report));
2184
+ return {
2185
+ scenarios,
2186
+ campaign,
2187
+ report,
2188
+ reportJsonPath,
2189
+ reportMarkdownPath
2190
+ };
2191
+ }
2192
+ function renderKnowledgeBenchmarkReportMarkdown(report) {
2193
+ return [
2194
+ "# Knowledge Benchmark Report",
2195
+ "",
2196
+ `- cases: ${report.totalCases}`,
2197
+ `- cells: ${report.totalCells} total, ${report.cellsFailed} failed, ${report.cellsCached} cached`,
2198
+ `- cost: $${formatNumber(report.totalCostUsd)}`,
2199
+ `- score: mean ${formatNumber(report.score.mean)}, median ${formatNumber(report.score.median)}, p90 ${formatNumber(report.score.p90)}, n=${report.score.n}`,
2200
+ "",
2201
+ "## Task Kinds",
2202
+ "",
2203
+ renderSliceTable(report.byTaskKind),
2204
+ "",
2205
+ "## Splits",
2206
+ "",
2207
+ renderSliceTable(report.bySplit),
2208
+ "",
2209
+ "## Dimensions",
2210
+ "",
2211
+ "| dimension | n | mean | p90 |",
2212
+ "| --- | ---: | ---: | ---: |",
2213
+ ...Object.entries(report.dimensions).sort(([a], [b]) => a.localeCompare(b)).map(([key, dist]) => `| ${key} | ${dist.n} | ${formatNumber(dist.mean)} | ${formatNumber(dist.p90)} |`),
2214
+ ""
2215
+ ].join("\n");
2216
+ }
2217
+ function buildKnowledgeBenchmarkScenarios(cases, splits) {
2218
+ const splitSet = splits ? new Set(splits) : null;
2219
+ return cases.flatMap((testCase) => {
2220
+ const splitTag = testCase.split ?? "dev";
2221
+ if (splitSet && !splitSet.has(splitTag)) return [];
2222
+ return [compactObject({
2223
+ id: testCase.id,
2224
+ kind: "knowledge-benchmark",
2225
+ family: testCase.family,
2226
+ taskKind: testCase.taskKind,
2227
+ splitTag,
2228
+ tags: unique([splitTag, ...testCase.tags ?? []]),
2229
+ case: compactObject(testCase)
2230
+ })];
2231
+ });
2232
+ }
2233
+ function knowledgeBenchmarkJudge() {
2234
+ return {
2235
+ name: "knowledge-benchmark",
2236
+ judgeVersion: "agent-knowledge:knowledge-benchmark:v2",
2237
+ dimensions: [
2238
+ {
2239
+ key: "score",
2240
+ description: "primary knowledge benchmark score"
2241
+ },
2242
+ {
2243
+ key: "passed",
2244
+ description: "1 when the benchmark case passes"
2245
+ },
2246
+ {
2247
+ key: "claim_recall",
2248
+ description: "required claim coverage"
2249
+ },
2250
+ {
2251
+ key: "citation_recall",
2252
+ description: "expected citation/source coverage"
2253
+ },
2254
+ {
2255
+ key: "hallucination_safe",
2256
+ description: "1 when no forbidden claim appears"
2257
+ },
2258
+ {
2259
+ key: "memory_fact_recall",
2260
+ description: "current memory fact coverage"
2261
+ },
2262
+ {
2263
+ key: "memory_event_recall",
2264
+ description: "expected memory event/source coverage"
2265
+ },
2266
+ {
2267
+ key: "memory_stale_safe",
2268
+ description: "1 when obsolete memory is not reused"
2269
+ },
2270
+ {
2271
+ key: "memory_actor_recall",
2272
+ description: "expected speaker/user attribution coverage"
2273
+ }
2274
+ ],
2275
+ appliesTo: (scenario) => scenario.kind === "knowledge-benchmark",
2276
+ score({ artifact, scenario }) {
2277
+ const evaluation = scoreKnowledgeBenchmarkArtifact(scenario.case, artifact);
2278
+ return {
2279
+ dimensions: {
2280
+ score: evaluation.score,
2281
+ passed: evaluation.passed ? 1 : 0,
2282
+ ...evaluation.dimensions
2283
+ },
2284
+ composite: evaluation.score,
2285
+ notes: evaluation.notes
2286
+ };
2287
+ }
2288
+ };
2289
+ }
2290
+ //#endregion
2291
+ //#region src/benchmarks/memory-runner.ts
2292
+ const MEMORY_ADAPTER_BENCHMARK_IMPLEMENTATION_REF = "agent-knowledge:memory-adapter-benchmark:v7";
2293
+ async function runMemoryAdapterBenchmark(options) {
2294
+ if (options.candidates.length === 0) throw new Error("memory adapter benchmark requires candidates");
2295
+ const allCandidates = [...options.candidates, ...options.recoveryCandidates ?? []];
2296
+ assertUniqueNonEmptyStrings(allCandidates.map((candidate) => candidate.id), "memory adapter candidate id");
2297
+ for (const candidate of allCandidates) {
2298
+ assertNonEmptyBenchmarkString(candidate.ref, `memory adapter candidate ${candidate.id} ref`);
2299
+ if (candidate.adapterId !== void 0) assertNonEmptyBenchmarkString(candidate.adapterId, `memory adapter candidate ${candidate.id} adapterId`);
2300
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(candidate.id)) throw new Error(`memory adapter candidate id '${candidate.id}' must be a safe directory segment`);
2301
+ if (candidate.adapterCreationCostUsd !== void 0 && (!Number.isFinite(candidate.adapterCreationCostUsd) || candidate.adapterCreationCostUsd < 0)) throw new Error(`${candidate.id}: adapterCreationCostUsd must be a non-negative finite number`);
2302
+ if (candidate.costUsdPerCase !== void 0 && (!Number.isFinite(candidate.costUsdPerCase) || candidate.costUsdPerCase < 0)) throw new Error(`${candidate.id}: costUsdPerCase must be a non-negative finite number`);
2303
+ if (candidate.recoveryCostUsdPerAttempt !== void 0 && (!Number.isFinite(candidate.recoveryCostUsdPerAttempt) || candidate.recoveryCostUsdPerAttempt < 0)) throw new Error(`${candidate.id}: recoveryCostUsdPerAttempt must be a non-negative finite number`);
2304
+ }
2305
+ const storage = options.storage ?? fsCampaignStorage();
2306
+ if (!storage.append) throw new Error("memory adapter benchmark requires CampaignStorage.append");
2307
+ const runDir = resolveRunDir(options.runDir, options.repo);
2308
+ const cleanupTimeoutMs = resolveMemoryCleanupTimeoutMs(options.cleanupTimeoutMs, "memory adapter benchmark");
2309
+ const maxRecoveryAttempts = options.maxRecoveryAttempts ?? 1e3;
2310
+ if (!Number.isSafeInteger(maxRecoveryAttempts) || maxRecoveryAttempts <= 0) throw new Error("memory adapter benchmark maxRecoveryAttempts must be a positive safe integer");
2311
+ const maxRecoveryRetriesPerAttempt = options.maxRecoveryRetriesPerAttempt ?? 3;
2312
+ if (!Number.isSafeInteger(maxRecoveryRetriesPerAttempt) || maxRecoveryRetriesPerAttempt <= 0) throw new Error("memory adapter benchmark maxRecoveryRetriesPerAttempt must be a positive safe integer");
2313
+ storage.ensureDir(runDir);
2314
+ const lease = await acquireAgentMemoryRunLease({
2315
+ experimentId: `memory-adapter-benchmark:${runDir}`,
2316
+ runDir,
2317
+ storage,
2318
+ customStorage: options.storage !== void 0,
2319
+ lockFileName: "memory-adapter-benchmark.lock",
2320
+ label: "memory adapter benchmark",
2321
+ controllerMode: options.controllerMode,
2322
+ acquireRunLease: options.acquireRunLease
2323
+ });
2324
+ let result;
2325
+ let primaryError;
2326
+ try {
2327
+ result = await runOwnedMemoryAdapterBenchmark(options, storage, runDir, lease, cleanupTimeoutMs, maxRecoveryAttempts, maxRecoveryRetriesPerAttempt);
2328
+ } catch (error) {
2329
+ primaryError = error;
2330
+ }
2331
+ let releaseError;
2332
+ try {
2333
+ await lease.release();
2334
+ } catch (error) {
2335
+ releaseError = error;
2336
+ }
2337
+ if (primaryError && releaseError) throw new AggregateError([primaryError, releaseError], "memory adapter benchmark failed and its controller lease could not be released");
2338
+ if (primaryError) throw primaryError;
2339
+ if (releaseError) throw releaseError;
2340
+ if (!result) throw new Error("memory adapter benchmark produced no result");
2341
+ return result;
2342
+ }
2343
+ async function runOwnedMemoryAdapterBenchmark(options, storage, runDir, lease, cleanupTimeoutMs, maxRecoveryAttempts, maxRecoveryRetriesPerAttempt) {
2344
+ const maxConcurrency = options.maxConcurrency ?? 2;
2345
+ if (!Number.isSafeInteger(maxConcurrency) || maxConcurrency <= 0) throw new Error("memory adapter benchmark maxConcurrency must be a positive safe integer");
2346
+ const costCeiling = options.costCeiling ?? options.costLedger?.costCeilingUsd ?? 0;
2347
+ const costLedger = options.costLedger ?? createRunCostLedger({
2348
+ storage,
2349
+ runDir,
2350
+ costCeilingUsd: costCeiling
2351
+ });
2352
+ if (costLedger.costCeilingUsd !== costCeiling) throw new Error("memory adapter benchmark costCeiling must match the shared cost ledger ceiling");
2353
+ const attemptLogPath = join(runDir, "memory-adapter-attempts.jsonl");
2354
+ const recoveryLogPath = join(runDir, "memory-adapter-recovery-attempts.jsonl");
2355
+ await recoverMemoryAdapterBenchmarkAttempts({
2356
+ candidates: [...options.candidates, ...options.recoveryCandidates ?? []],
2357
+ storage,
2358
+ attemptLogPath,
2359
+ lease,
2360
+ cleanupTimeoutMs,
2361
+ maxConcurrency,
2362
+ now: options.now,
2363
+ runDir,
2364
+ costLedger,
2365
+ costPhase: options.costPhase ?? "memory.adapter-benchmark",
2366
+ maxRecoveryAttempts,
2367
+ recoveryLogPath,
2368
+ maxRecoveryRetriesPerAttempt
2369
+ });
2370
+ await lease.assertOwned();
2371
+ const rows = [];
2372
+ for (const candidate of options.candidates) {
2373
+ await lease.assertOwned();
2374
+ const expectedAdapterId = memoryAdapterBenchmarkExpectedId(candidate);
2375
+ let adapter;
2376
+ let adapterPromise;
2377
+ let adapterCreationError;
2378
+ const getAdapter = () => {
2379
+ if (!adapterPromise) {
2380
+ const abortController = new AbortController();
2381
+ const creation = createMemoryAdapterBenchmarkAdapter({
2382
+ candidate,
2383
+ purpose: "execute",
2384
+ signal: abortController.signal,
2385
+ costLedger,
2386
+ runDir,
2387
+ costPhase: options.costPhase ?? "memory.adapter-benchmark"
2388
+ });
2389
+ releaseMemoryAdapterCreatedAfterAbort({
2390
+ creation,
2391
+ signal: abortController.signal
2392
+ });
2393
+ adapterPromise = runBoundedMemoryLifecycle({
2394
+ operation: `${candidate.id}: benchmark execute adapter creation`,
2395
+ timeoutMs: Math.min(cleanupTimeoutMs, options.dispatchTimeoutMs ?? cleanupTimeoutMs),
2396
+ abortController,
2397
+ run: () => creation
2398
+ }).then((created) => {
2399
+ adapter = created;
2400
+ if (created.id !== expectedAdapterId) throw new Error(`${candidate.id}: createAdapter returned id '${created.id}', expected '${expectedAdapterId}'`);
2401
+ assertScopedMemoryBenchmarkAdapter(created);
2402
+ return created;
2403
+ }).catch((error) => {
2404
+ adapterCreationError = error;
2405
+ throw error;
2406
+ });
2407
+ }
2408
+ return adapterPromise;
2409
+ };
2410
+ const dispatchedExecutions = [];
2411
+ let run;
2412
+ let primaryError;
2413
+ try {
2414
+ await lease.assertOwned();
2415
+ let respond;
2416
+ run = await runKnowledgeBenchmarkSuite({
2417
+ cases: options.cases,
2418
+ respond(input) {
2419
+ const operation = getAdapter().then((activeAdapter) => {
2420
+ respond ??= createMemoryAdapterBenchmarkResponder({
2421
+ adapter: activeAdapter,
2422
+ candidateId: candidate.id,
2423
+ candidateRef: candidate.ref,
2424
+ storage,
2425
+ attemptLogPath,
2426
+ lease,
2427
+ cleanupTimeoutMs,
2428
+ searchLimit: candidate.searchLimit,
2429
+ scope: candidate.scope,
2430
+ adapterCreationCostUsd: candidate.adapterCreationCostUsd,
2431
+ costUsdPerCase: candidate.costUsdPerCase,
2432
+ recoveryCostUsdPerAttempt: candidate.recoveryCostUsdPerAttempt,
2433
+ now: options.now
2434
+ });
2435
+ return respond(input);
2436
+ });
2437
+ dispatchedExecutions.push(operation);
2438
+ return operation;
2439
+ },
2440
+ respondRef: stableId("memory_adapter_benchmark", canonicalJson({
2441
+ implementationRef: MEMORY_ADAPTER_BENCHMARK_IMPLEMENTATION_REF,
2442
+ candidateRef: candidate.ref,
2443
+ adapterId: expectedAdapterId,
2444
+ searchLimit: candidate.searchLimit ?? null,
2445
+ adapterCreationCostUsd: candidate.adapterCreationCostUsd ?? 0,
2446
+ costUsdPerCase: candidate.costUsdPerCase ?? 0,
2447
+ recoveryCostUsdPerAttempt: candidate.recoveryCostUsdPerAttempt ?? 0,
2448
+ scope: candidate.scope ?? null
2449
+ })),
2450
+ runDir: join(runDir, candidate.id),
2451
+ storage,
2452
+ seed: options.seed,
2453
+ reps: options.reps,
2454
+ resumable: options.resumable,
2455
+ costCeiling,
2456
+ costLedger,
2457
+ costPhase: `${options.costPhase ?? "memory.adapter-benchmark"}.${candidate.id}`,
2458
+ maxConcurrency: options.maxConcurrency,
2459
+ dispatchTimeoutMs: options.dispatchTimeoutMs,
2460
+ expectUsage: options.expectUsage ?? "off",
2461
+ now: options.now
2462
+ });
2463
+ } catch (error) {
2464
+ primaryError = error;
2465
+ }
2466
+ const dispatchCleanupErrors = (await Promise.allSettled(dispatchedExecutions)).flatMap((settled) => settled.status === "rejected" && settled.reason instanceof MemoryAdapterBenchmarkCleanupError ? [settled.reason] : []);
2467
+ if (!primaryError && adapterCreationError) primaryError = adapterCreationError;
2468
+ if (run) rows.push({
2469
+ rank: 0,
2470
+ candidateId: candidate.id,
2471
+ label: candidate.label ?? candidate.id,
2472
+ adapterId: expectedAdapterId,
2473
+ scoreMean: run.report.score.mean,
2474
+ passRate: run.report.dimensions.passed?.mean ?? 0,
2475
+ totalCases: run.report.totalCases,
2476
+ totalCells: run.report.totalCells,
2477
+ cellsFailed: run.report.cellsFailed,
2478
+ totalCostUsd: run.report.totalCostUsd,
2479
+ reportJsonPath: run.reportJsonPath,
2480
+ reportMarkdownPath: run.reportMarkdownPath,
2481
+ report: run.report
2482
+ });
2483
+ const cleanupErrors = [];
2484
+ let cleanupOwned = true;
2485
+ try {
2486
+ await lease.assertOwned();
2487
+ } catch (error) {
2488
+ cleanupOwned = false;
2489
+ cleanupErrors.push(error);
2490
+ }
2491
+ if (cleanupOwned && adapter && !adapterCreationError) {
2492
+ const activeAdapter = adapter;
2493
+ try {
2494
+ await runBoundedMemoryLifecycle({
2495
+ operation: `${candidate.id}: benchmark adapter flush`,
2496
+ timeoutMs: cleanupTimeoutMs,
2497
+ resource: activeAdapter,
2498
+ run: () => activeAdapter.flush?.()
2499
+ });
2500
+ } catch (error) {
2501
+ cleanupErrors.push(error);
2502
+ }
2503
+ }
2504
+ if (adapter) try {
2505
+ await runBoundedMemoryLifecycle({
2506
+ operation: `${candidate.id}: benchmark adapter close`,
2507
+ timeoutMs: cleanupTimeoutMs,
2508
+ resource: adapter,
2509
+ run: () => adapter.close?.()
2510
+ });
2511
+ } catch (error) {
2512
+ cleanupErrors.push(error);
2513
+ }
2514
+ if (primaryError || dispatchCleanupErrors.length > 0 || cleanupErrors.length > 0) {
2515
+ const errors = [
2516
+ ...primaryError ? [primaryError] : [],
2517
+ ...dispatchCleanupErrors,
2518
+ ...cleanupErrors
2519
+ ];
2520
+ if (errors.length === 1) throw errors[0];
2521
+ throw new AggregateError(errors, `${candidate.id}: memory adapter benchmark cleanup failed`);
2522
+ }
2523
+ await lease.assertOwned();
2524
+ }
2525
+ const costByCandidate = memoryAdapterBenchmarkCostByCandidate(costLedger, runDir, [...options.candidates, ...options.recoveryCandidates ?? []]);
2526
+ const ranked = rows.map((row) => {
2527
+ const totalCostUsd = normalizeUsd(costByCandidate.get(row.candidateId) ?? 0);
2528
+ return {
2529
+ ...row,
2530
+ totalCostUsd
2531
+ };
2532
+ }).sort((a, b) => Number(a.cellsFailed > 0) - Number(b.cellsFailed > 0) || b.scoreMean - a.scoreMean || b.passRate - a.passRate || a.totalCostUsd - b.totalCostUsd || a.candidateId.localeCompare(b.candidateId)).map((row, index) => ({
2533
+ ...row,
2534
+ rank: index + 1
2535
+ }));
2536
+ const rankingJsonPath = join(runDir, "memory-adapter-ranking.json");
2537
+ const rankingMarkdownPath = join(runDir, "memory-adapter-ranking.md");
2538
+ const unrankedRecoveryCostUsd = normalizeUsd((options.recoveryCandidates ?? []).reduce((sum, candidate) => sum + (costByCandidate.get(candidate.id) ?? 0), 0));
2539
+ const totalCostUsd = normalizeUsd([...costByCandidate.values()].reduce((sum, cost) => sum + cost, 0));
2540
+ storage.write(rankingJsonPath, `${JSON.stringify({
2541
+ totalCostUsd,
2542
+ unrankedRecoveryCostUsd,
2543
+ rows: ranked
2544
+ }, null, 2)}\n`);
2545
+ storage.write(rankingMarkdownPath, renderMemoryAdapterRankingMarkdown(ranked, totalCostUsd, unrankedRecoveryCostUsd));
2546
+ return {
2547
+ rows: ranked,
2548
+ totalCostUsd,
2549
+ unrankedRecoveryCostUsd,
2550
+ rankingJsonPath,
2551
+ rankingMarkdownPath,
2552
+ attemptLogPath,
2553
+ recoveryLogPath
2554
+ };
2555
+ }
2556
+ async function createMemoryAdapterBenchmarkAdapter(input) {
2557
+ const { candidate, purpose, signal, costLedger, runDir, costPhase } = input;
2558
+ const costUsd = candidate.adapterCreationCostUsd ?? 0;
2559
+ let externalCallAttempted = false;
2560
+ const create = async () => {
2561
+ const adapter = await candidate.createAdapter({
2562
+ purpose,
2563
+ signal,
2564
+ markExternalCall: () => {
2565
+ externalCallAttempted = true;
2566
+ }
2567
+ });
2568
+ if (!adapter || typeof adapter !== "object") throw new Error(`${candidate.id}: createAdapter returned no ${purpose} adapter`);
2569
+ return adapter;
2570
+ };
2571
+ if (costUsd === 0) return create();
2572
+ const tags = memoryAdapterCreationCostTags(runDir, candidate.id, purpose);
2573
+ const generation = costLedger.list({ tags }).length;
2574
+ const receipt = {
2575
+ model: candidate.id,
2576
+ inputTokens: 0,
2577
+ outputTokens: 0,
2578
+ actualCostUsd: costUsd
2579
+ };
2580
+ const paid = await costLedger.runPaidCall({
2581
+ callId: memoryAdapterCreationCostCallId(candidate, purpose, generation),
2582
+ channel: "driver",
2583
+ phase: `${costPhase}.${candidate.id}.adapter-${purpose}`,
2584
+ actor: `agent-knowledge:memory-adapter:${candidate.id}`,
2585
+ model: candidate.id,
2586
+ tags,
2587
+ maximumCharge: { externallyEnforcedMaximumUsd: costUsd },
2588
+ execute: create,
2589
+ receipt: () => ({
2590
+ ...receipt,
2591
+ actualCostUsd: externalCallAttempted ? costUsd : 0
2592
+ }),
2593
+ receiptFromError: () => ({
2594
+ ...receipt,
2595
+ actualCostUsd: externalCallAttempted ? costUsd : 0
2596
+ })
2597
+ });
2598
+ if (!paid.succeeded) throw paid.error;
2599
+ return paid.value;
2600
+ }
2601
+ function memoryAdapterCreationCostTags(runDir, candidateId, purpose) {
2602
+ return {
2603
+ runDir: join(runDir, candidateId),
2604
+ candidateId,
2605
+ memoryAdapterCreation: purpose
2606
+ };
2607
+ }
2608
+ function memoryAdapterCreationCostCallId(candidate, purpose, generation) {
2609
+ return stableId("memory_adapter_creation_cost_call", canonicalJson({
2610
+ purpose,
2611
+ generation,
2612
+ candidateId: candidate.id,
2613
+ candidateRef: candidate.ref,
2614
+ adapterCreationCostUsd: candidate.adapterCreationCostUsd ?? 0
2615
+ }));
2616
+ }
2617
+ function memoryAdapterBenchmarkCostByCandidate(costLedger, runDir, candidates) {
2618
+ const candidateByRunDir = new Map(candidates.map((candidate) => [join(runDir, candidate.id), candidate.id]));
2619
+ const totals = /* @__PURE__ */ new Map();
2620
+ for (const receipt of costLedger.list()) {
2621
+ const candidateId = receipt.tags?.runDir ? candidateByRunDir.get(receipt.tags.runDir) : void 0;
2622
+ if (!candidateId) continue;
2623
+ totals.set(candidateId, (totals.get(candidateId) ?? 0) + receipt.costUsd);
2624
+ }
2625
+ return totals;
2626
+ }
2627
+ function renderMemoryAdapterRankingMarkdown(rows, totalCostUsd, unrankedRecoveryCostUsd) {
2628
+ return [
2629
+ "# Memory Adapter Ranking",
2630
+ "",
2631
+ `- total cost: $${formatNumber(totalCostUsd)}`,
2632
+ `- retired-candidate recovery cost: $${formatNumber(unrankedRecoveryCostUsd)}`,
2633
+ "",
2634
+ "| rank | candidate | adapter | cases | cells | failed | mean score | pass rate | cost |",
2635
+ "| ---: | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |",
2636
+ ...rows.map((row) => `| ${row.rank} | ${row.label} | ${row.adapterId} | ${row.totalCases} | ${row.totalCells} | ${row.cellsFailed} | ${formatNumber(row.scoreMean)} | ${formatNumber(row.passRate)} | $${formatNumber(row.totalCostUsd)} |`),
2637
+ ""
2638
+ ].join("\n");
2639
+ }
2640
+ //#endregion
2641
+ //#region src/benchmarks/retrieval.ts
2642
+ function parseKnowledgeBenchmarkJsonl(text) {
2643
+ return text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line, index) => {
2644
+ try {
2645
+ return JSON.parse(line);
2646
+ } catch (error) {
2647
+ throw new Error(`invalid JSONL row ${index + 1}: ${error.message}`);
2648
+ }
2649
+ });
2650
+ }
2651
+ function parseKnowledgeBenchmarkQrels(text) {
2652
+ return text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).flatMap((line, index) => {
2653
+ const parts = line.split(/\t|\s+/);
2654
+ if (parts.length < 3) return [];
2655
+ const [queryId, maybeZeroOrDocId, maybeDocIdOrScore, maybeScore] = parts;
2656
+ if (!queryId || !maybeZeroOrDocId || !maybeDocIdOrScore) return [];
2657
+ if (queryId.toLowerCase() === "qid" || queryId.toLowerCase() === "query-id") return [];
2658
+ const documentId = maybeScore === void 0 ? maybeZeroOrDocId : maybeDocIdOrScore;
2659
+ const score = Number(maybeScore === void 0 ? maybeDocIdOrScore : maybeScore);
2660
+ if (!documentId || !Number.isFinite(score)) throw new Error(`invalid qrels row ${index + 1}: expected query id, doc id, score`);
2661
+ return [{
2662
+ queryId,
2663
+ documentId,
2664
+ score
2665
+ }];
2666
+ });
2667
+ }
2668
+ function buildRetrievalBenchmarkCasesFromQrels(options) {
2669
+ const qrelsByQuery = /* @__PURE__ */ new Map();
2670
+ for (const qrel of options.qrels) {
2671
+ if (qrel.score <= 0) continue;
2672
+ const list = qrelsByQuery.get(qrel.queryId) ?? [];
2673
+ list.push(qrel);
2674
+ qrelsByQuery.set(qrel.queryId, list);
2675
+ }
2676
+ return options.queries.flatMap((query) => {
2677
+ const qrels = qrelsByQuery.get(query.id) ?? [];
2678
+ if (qrels.length === 0) return [];
2679
+ const split = query.split ?? options.splitOf?.(query.id);
2680
+ const expected = qrels.map((qrel) => options.documentTarget ? options.documentTarget(qrel.documentId, qrel) : defaultDocumentTarget(qrel.documentId, options.targetKind ?? "page"));
2681
+ return [compactObject({
2682
+ id: `${options.benchmarkId}:${query.id}`,
2683
+ family: options.family,
2684
+ taskKind: "retrieval",
2685
+ query: query.text,
2686
+ expected,
2687
+ k: options.k,
2688
+ split,
2689
+ tags: unique([
2690
+ ...options.tags ?? [],
2691
+ ...query.tags ?? [],
2692
+ ...split ? [split] : []
2693
+ ]),
2694
+ source: options.source,
2695
+ metadata: query.metadata
2696
+ })];
2697
+ });
2698
+ }
2699
+ function defaultDocumentTarget(documentId, targetKind) {
2700
+ switch (targetKind) {
2701
+ case "page": return {
2702
+ kind: "page",
2703
+ pageId: documentId
2704
+ };
2705
+ case "page-path": return {
2706
+ kind: "page-path",
2707
+ path: documentId
2708
+ };
2709
+ case "source": return {
2710
+ kind: "source",
2711
+ sourceId: documentId
2712
+ };
2713
+ }
2714
+ }
2715
+ //#endregion
2716
+ export { INDUSTRY_RAG_BENCHMARKS as A, memoryWriteResultToSourceRecord as B, appendDurableJournalEvent as C, reconcileInterruptedMemoryPaidCalls as D, readActiveAttemptJournal as E, respondToIndustryRagBenchmarkSmokeCase as F, retrievalRecallJudge as G, partitionRetrievalScenarios as H, isKnowledgeMemoryBenchmarkCase as I, scoreRetrievalArtifact as K, createInMemoryBenchmarkAdapter as L, buildIndustryMemoryBenchmarkSmokeCases as M, buildIndustryRagBenchmarkSmokeCases as N, reserveRecoveryAttempts as O, respondToIndustryMemoryBenchmarkSmokeCase as P, createNoopMemoryBenchmarkAdapter as R, appendAttemptJournalEvent as S, hasSettledPaidCall as T, retrievalConfigFromSurface as U, buildRetrievalEvalDispatch as V, retrievalConfigSurface as W, memoryRecoveryDelayMs as _, buildKnowledgeBenchmarkScenarios as a, runBoundedMemoryLifecycle as b, runKnowledgeBenchmarkSuite as c, summarizeKnowledgeBenchmarkCampaign as d, acquireAgentMemoryRunLease as f, createMemoryExecutionPool as g, DEFAULT_MEMORY_CLEANUP_TIMEOUT_MS as h, runMemoryAdapterBenchmark as i, buildFirstPartyMemoryLifecycleBenchmarkCases as j, INDUSTRY_MEMORY_BENCHMARKS as k, scoreKnowledgeBenchmarkArtifact as l, AgentMemoryLifecycleUnsafeError as m, parseKnowledgeBenchmarkJsonl as n, knowledgeBenchmarkJudge as o, AgentMemoryLifecycleTimeoutError as p, parseKnowledgeBenchmarkQrels as r, renderKnowledgeBenchmarkReportMarkdown as s, buildRetrievalBenchmarkCasesFromQrels as t, scoreMemoryBenchmarkArtifact as u, releaseMemoryAdapterCreatedAfterAbort as v, assertNoInterruptedPaidCalls as w, sleepForMemoryRecovery as x, resolveMemoryCleanupTimeoutMs as y, memoryHitToSourceRecord as z };
2717
+
2718
+ //# sourceMappingURL=benchmarks-CmW6iORW.js.map