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