@tangle-network/agent-knowledge 4.0.1 → 5.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.
Files changed (37) hide show
  1. package/AGENTS.md +35 -19
  2. package/CHANGELOG.md +48 -0
  3. package/README.md +220 -943
  4. package/dist/benchmarks/index.d.ts +3 -2
  5. package/dist/benchmarks/index.js +1 -1
  6. package/dist/{chunk-EUAXSBMH.js → chunk-AKYJG2MR.js} +224 -224
  7. package/dist/chunk-AKYJG2MR.js.map +1 -0
  8. package/dist/{chunk-BBCIB4UL.js → chunk-EYIA5PLQ.js} +27 -195
  9. package/dist/chunk-EYIA5PLQ.js.map +1 -0
  10. package/dist/{chunk-3CAAGJCE.js → chunk-LMR53POQ.js} +1227 -574
  11. package/dist/chunk-LMR53POQ.js.map +1 -0
  12. package/dist/{chunk-WCYW2GDA.js → chunk-MYFM6LKH.js} +2 -2
  13. package/dist/chunk-MYFM6LKH.js.map +1 -0
  14. package/dist/cli.js +1 -1
  15. package/dist/index-Cf7txrYP.d.ts +790 -0
  16. package/dist/index.d.ts +252 -73
  17. package/dist/index.js +2813 -2229
  18. package/dist/index.js.map +1 -1
  19. package/dist/memory/index.d.ts +8 -709
  20. package/dist/memory/index.js +2 -2
  21. package/dist/sources/index.d.ts +17 -33
  22. package/dist/sources/index.js +1 -1
  23. package/dist/{types-ZzY_x0r7.d.ts → types-BY-xLVw-.d.ts} +28 -67
  24. package/docs/eval/investment-material-facts.md +28 -29
  25. package/docs/eval/rag-eval-roadmap.md +21 -17
  26. package/docs/results/adaptive.md +13 -13
  27. package/docs/results/claim-grounding.md +11 -11
  28. package/docs/results/cost-quality.md +4 -4
  29. package/docs/results/investment-thesis.md +56 -56
  30. package/docs/results/research-driving.md +54 -54
  31. package/docs/two-agent-research-ab.md +94 -94
  32. package/package.json +11 -11
  33. package/skills/build-with-agent-knowledge/SKILL.md +97 -0
  34. package/dist/chunk-3CAAGJCE.js.map +0 -1
  35. package/dist/chunk-BBCIB4UL.js.map +0 -1
  36. package/dist/chunk-EUAXSBMH.js.map +0 -1
  37. package/dist/chunk-WCYW2GDA.js.map +0 -1
@@ -24,7 +24,7 @@ import {
24
24
  runAgentMemoryExperiment,
25
25
  runAgentMemoryImprovement,
26
26
  toOffPolicyTrajectory
27
- } from "../chunk-3CAAGJCE.js";
27
+ } from "../chunk-LMR53POQ.js";
28
28
  import {
29
29
  AgentMemoryLifecycleTimeoutError,
30
30
  AgentMemoryLifecycleUnsafeError,
@@ -37,7 +37,7 @@ import {
37
37
  resolveMemoryCleanupTimeoutMs,
38
38
  runBoundedMemoryLifecycle,
39
39
  sleepForMemoryRecovery
40
- } from "../chunk-BBCIB4UL.js";
40
+ } from "../chunk-EYIA5PLQ.js";
41
41
  import "../chunk-DQ3PDMDP.js";
42
42
  import "../chunk-YMKHCTS2.js";
43
43
  export {
@@ -15,9 +15,9 @@
15
15
  * Sources MUST be pure with respect to local filesystem state outside the
16
16
  * cache directory the caller hands them — they read remote authorities and
17
17
  * return data. They MUST mark `verifiable: false` on any fragment they could
18
- * not authenticate (block page, 4xx, parse failure) rather than silently
19
- * substituting empty/partial content. The control loop downstream uses
20
- * `verifiable` to refuse promotion of un-grounded content.
18
+ * not fetch and extract (block page, 4xx, parse failure) rather than silently
19
+ * substituting empty or partial content. The control loop downstream uses
20
+ * `verifiable` to refuse promotion of unusable content.
21
21
  *
22
22
  * @stable
23
23
  */
@@ -77,10 +77,11 @@ interface FragmentProvenance {
77
77
  */
78
78
  jurisdiction?: string;
79
79
  /**
80
- * True iff the source could authenticate the fetched content (HTTP 200,
81
- * expected selectors present, parse succeeded). False on any block page,
82
- * rate-limit response, 4xx/5xx, or selector miss. Consumers MUST refuse
83
- * to promote `verifiable: false` fragments into citable knowledge.
80
+ * True iff the configured URL returned an acceptable response and the
81
+ * expected content was extracted. False on a block page, rate-limit
82
+ * response, 4xx/5xx, or selector miss. This is not publisher authentication
83
+ * or cryptographic content verification. Consumers MUST refuse to promote
84
+ * `verifiable: false` fragments into citable knowledge.
84
85
  */
85
86
  verifiable: boolean;
86
87
  /** If `verifiable === false`, the reason — surfaced to operators. */
@@ -222,33 +223,16 @@ declare function extractLinks(html: string, hrefPattern: RegExp, baseUrl: string
222
223
  }[];
223
224
 
224
225
  /**
225
- * Polite HTTP fetcher used by every shipped source.
226
+ * Polite HTTP fetcher shared by remote sources.
226
227
  *
227
- * Three invariants this enforces — each was a bug found while wiring real
228
- * authorities; do not regress:
229
- *
230
- * 1. Per-host throttling. Cornell LII serves under 1 req/s/origin
231
- * politely and will start serving block pages above that. The lock
232
- * is per-host (`hostThrottle`) rather than per-source so that two
233
- * independent sources targeting the same authority still cooperate.
234
- *
235
- * 2. On-disk content cache keyed by URL. Production sources are called
236
- * from a cron loop; without a cache, every run re-hits the same
237
- * pages and inflates change-detection false-positives (the authority
238
- * occasionally serves slightly different boilerplate). The cache is
239
- * content-addressed by URL, not by ETag — authorities like IRS.gov
240
- * do not consistently send ETag/Last-Modified.
241
- *
242
- * 3. Block-page detection on success. A 200 with a captcha body still
243
- * means "we couldn't authenticate." Sources downstream rely on
244
- * `verifiable` to refuse promotion — losing that signal because the
245
- * fetcher said "well, the status code was 200" is the bug class
246
- * this exists to prevent.
247
- *
248
- * @stable
228
+ * Independent sources share a per-origin throttle because rate-limited sites
229
+ * may return block pages instead of 429 responses. Responses are cached by URL
230
+ * because many publishers omit reliable ETag and Last-Modified headers. Bodies
231
+ * are checked even after a 2xx response because captcha and block pages often
232
+ * use successful status codes.
249
233
  */
250
234
  /** User-Agent string sent on every outbound request. */
251
- declare const POLITE_USER_AGENT = "agent-knowledge/0.2.0 (+https://github.com/tangle-network/agent-knowledge)";
235
+ declare const POLITE_USER_AGENT = "agent-knowledge (+https://github.com/tangle-network/agent-knowledge)";
252
236
  /** Minimum gap between successive requests to the same origin (ms). */
253
237
  declare const MIN_REQUEST_GAP_MS = 1000;
254
238
  /** Maximum response body we will buffer in memory (bytes). */
@@ -257,7 +241,7 @@ interface PoliteFetchOptions {
257
241
  signal?: AbortSignal;
258
242
  cacheDir?: string;
259
243
  /**
260
- * Cache age beyond which we re-fetch. Default 1 hour long enough to
244
+ * Cache age beyond which we re-fetch. Default 1 hour, long enough to
261
245
  * batch a cron sweep across many selectors, short enough that hourly
262
246
  * authoritative-page changes get picked up next tick.
263
247
  */
@@ -291,7 +275,7 @@ interface PoliteFetchResult {
291
275
  }
292
276
  /**
293
277
  * Fetch one URL with per-host throttling, on-disk cache, and block-page
294
- * detection. Never throws on network/HTTP failure returns a result with
278
+ * detection. Never throws on network/HTTP failure. It returns a result with
295
279
  * `verifiable: false` and `unverifiableReason` set so the caller can decide
296
280
  * whether to skip, retry, or surface.
297
281
  *
@@ -13,7 +13,7 @@ import {
13
13
  innerHtmlById,
14
14
  looksLikeBlockPage,
15
15
  politeFetch
16
- } from "../chunk-WCYW2GDA.js";
16
+ } from "../chunk-MYFM6LKH.js";
17
17
  import "../chunk-YMKHCTS2.js";
18
18
  export {
19
19
  IRS_DIMENSION_HINTS,
@@ -1,8 +1,8 @@
1
- import { JsonValue, Scenario, DispatchContext, RunImprovementLoopResult, ParameterCandidate, JudgeConfig, Gate, RunImprovementLoopOptions, MutableSurface, SurfaceProposer, CampaignStorage, CostLedgerHandle, CampaignResult } from '@tangle-network/agent-eval/campaign';
1
+ import { Scenario, DispatchContext, MutableSurface, JudgeConfig, CampaignStorage, CostLedgerHandle, CampaignResult } from '@tangle-network/agent-eval/campaign';
2
2
  import { c as KnowledgeIndex, S as SourceRecord } from './types-6x0OpfW6.js';
3
+ import { AgentCandidateJsonValue } from '@tangle-network/agent-interface';
3
4
 
4
- type RetrievalConfig = Record<string, JsonValue>;
5
- type RetrievalParameterSearchSpace = Record<string, readonly JsonValue[]>;
5
+ type RetrievalConfig = Record<string, AgentCandidateJsonValue>;
6
6
  type RetrievalGoldTarget = {
7
7
  kind: 'page';
8
8
  pageId: string;
@@ -44,7 +44,7 @@ interface RetrievedKnowledgeHit {
44
44
  sourceIds?: readonly string[];
45
45
  sourceSpans?: readonly RetrievedSourceSpan[];
46
46
  snippet?: string;
47
- metadata?: Record<string, JsonValue>;
47
+ metadata?: Record<string, AgentCandidateJsonValue>;
48
48
  }
49
49
  interface RetrievalEvalArtifact {
50
50
  config: RetrievalConfig;
@@ -54,7 +54,7 @@ interface RetrievalEvalArtifact {
54
54
  durationMs: number;
55
55
  /** Informational copy. Billable retrievers account through context.cost.runPaidCall. */
56
56
  costUsd?: number;
57
- metadata?: Record<string, JsonValue>;
57
+ metadata?: Record<string, AgentCandidateJsonValue>;
58
58
  }
59
59
  interface RetrievalMetricSummary {
60
60
  recall: number;
@@ -79,7 +79,7 @@ interface RetrievalEvalRetrieverResult {
79
79
  hits: readonly RetrievedKnowledgeHit[];
80
80
  /** Informational copy. Billable retrievers account through context.cost.runPaidCall. */
81
81
  costUsd?: number;
82
- metadata?: Record<string, JsonValue>;
82
+ metadata?: Record<string, AgentCandidateJsonValue>;
83
83
  }
84
84
  type RetrievalEvalRetriever = (input: RetrievalEvalRetrieverInput) => Promise<readonly RetrievedKnowledgeHit[] | RetrievalEvalRetrieverResult>;
85
85
  interface BuildRetrievalEvalDispatchOptions {
@@ -97,65 +97,22 @@ interface RetrievalRecallJudgeOptions {
97
97
  name?: string;
98
98
  weights?: RetrievalMetricWeights;
99
99
  }
100
- interface BuildRetrievalParameterCandidatesOptions {
101
- baseline?: RetrievalConfig;
102
- }
103
- interface RetrievalParameterSweepProposerOptions {
104
- candidates?: readonly ParameterCandidate[];
105
- searchSpace?: RetrievalParameterSearchSpace;
106
- baseline?: RetrievalConfig;
100
+ interface PartitionRetrievalScenariosOptions {
101
+ selectionFraction?: number;
102
+ finalFraction?: number;
103
+ seed?: number;
107
104
  }
108
- type RetrievalLoopBaseOptions = RunImprovementLoopOptions<RetrievalEvalScenario, RetrievalEvalArtifact>;
109
- interface RunRetrievalImprovementLoopOptions {
110
- baseline: RetrievalConfig;
111
- scenarios: readonly RetrievalEvalScenario[];
112
- holdoutScenarios?: readonly RetrievalEvalScenario[];
113
- index?: KnowledgeIndex;
114
- defaultK?: number;
115
- retrieve?: RetrievalEvalRetriever;
116
- candidates?: readonly ParameterCandidate[];
117
- searchSpace?: RetrievalParameterSearchSpace;
118
- judges?: readonly JudgeConfig<RetrievalEvalArtifact, RetrievalEvalScenario>[];
119
- gate?: Gate<RetrievalEvalArtifact, RetrievalEvalScenario>;
120
- metricWeights?: RetrievalMetricWeights;
121
- targetRecall?: number;
122
- holdoutFraction?: number;
123
- splitSeed?: number;
124
- deltaThreshold?: number;
125
- runDir?: RetrievalLoopBaseOptions['runDir'];
126
- seed?: RetrievalLoopBaseOptions['seed'];
127
- reps?: RetrievalLoopBaseOptions['reps'];
128
- resumable?: RetrievalLoopBaseOptions['resumable'];
129
- costCeiling?: RetrievalLoopBaseOptions['costCeiling'];
130
- maxConcurrency?: RetrievalLoopBaseOptions['maxConcurrency'];
131
- dispatchTimeoutMs?: RetrievalLoopBaseOptions['dispatchTimeoutMs'];
132
- expectUsage?: RetrievalLoopBaseOptions['expectUsage'];
133
- tracing?: RetrievalLoopBaseOptions['tracing'];
134
- storage?: RetrievalLoopBaseOptions['storage'];
135
- populationSize?: RetrievalLoopBaseOptions['populationSize'];
136
- maxGenerations?: RetrievalLoopBaseOptions['maxGenerations'];
137
- promoteTopK?: RetrievalLoopBaseOptions['promoteTopK'];
138
- maxImprovementShots?: RetrievalLoopBaseOptions['maxImprovementShots'];
139
- report?: RetrievalLoopBaseOptions['report'];
140
- findings?: RetrievalLoopBaseOptions['findings'];
141
- now?: RetrievalLoopBaseOptions['now'];
142
- }
143
- interface RunRetrievalImprovementLoopResult extends RunImprovementLoopResult<RetrievalEvalArtifact, RetrievalEvalScenario> {
144
- baselineConfig: RetrievalConfig;
145
- winnerConfig: RetrievalConfig;
146
- trainScenarios: readonly RetrievalEvalScenario[];
147
- holdoutScenarios: readonly RetrievalEvalScenario[];
148
- candidates: readonly ParameterCandidate[];
149
- targetRecall?: number;
105
+ interface RetrievalScenarioPartitions {
106
+ trainScenarios: RetrievalEvalScenario[];
107
+ selectionScenarios: RetrievalEvalScenario[];
108
+ finalScenarios: RetrievalEvalScenario[];
150
109
  }
151
110
  declare function retrievalConfigSurface(config: RetrievalConfig): string;
152
111
  declare function retrievalConfigFromSurface(surface: MutableSurface): RetrievalConfig;
153
112
  declare function buildRetrievalEvalDispatch(options: BuildRetrievalEvalDispatchOptions): (surface: MutableSurface, scenario: RetrievalEvalScenario, context: DispatchContext) => Promise<RetrievalEvalArtifact>;
154
113
  declare function retrievalRecallJudge(options?: RetrievalRecallJudgeOptions): JudgeConfig<RetrievalEvalArtifact, RetrievalEvalScenario>;
155
114
  declare function scoreRetrievalArtifact(artifact: RetrievalEvalArtifact, scenario: RetrievalEvalScenario): RetrievalMetricSummary;
156
- declare function buildRetrievalParameterCandidates(searchSpace: RetrievalParameterSearchSpace, options?: BuildRetrievalParameterCandidatesOptions): ParameterCandidate[];
157
- declare function retrievalParameterSweepProposer(options: RetrievalParameterSweepProposerOptions): SurfaceProposer;
158
- declare function runRetrievalImprovementLoop(options: RunRetrievalImprovementLoopOptions): Promise<RunRetrievalImprovementLoopResult>;
115
+ declare function partitionRetrievalScenarios(scenarios: readonly RetrievalEvalScenario[], options?: PartitionRetrievalScenariosOptions): RetrievalScenarioPartitions;
159
116
 
160
117
  type AgentMemoryKind = 'message' | 'entity' | 'fact' | 'preference' | 'observation' | 'reasoning-trace';
161
118
  interface AgentMemoryScope {
@@ -252,6 +209,11 @@ interface AgentMemoryAdapter {
252
209
  flush?(): Promise<void>;
253
210
  close?(): Promise<void>;
254
211
  }
212
+ /**
213
+ * Optional session-level retrieval dropout for estimating whether delivered memories affect
214
+ * task outcomes. The feature is disabled unless configured, and consumers persist events
215
+ * through `onEvent`.
216
+ */
255
217
  interface RetrievalHoldoutConfig {
256
218
  /** Per-session probability that one eligible watchlist item is suppressed. 0 logs the full schema without ever dropping. */
257
219
  epsilon: number;
@@ -268,20 +230,20 @@ interface RetrievalHoldoutConfig {
268
230
  * sessionIdHash/scopeHash, so PII-bearing identifiers (tenantId/userId/tags) never reach a
269
231
  * consumer-controlled sink unless the consumer explicitly owns that decision. Note that
270
232
  * replaying assignment draws from logs alone needs the plaintext sessionId, so
271
- * privacy-default logs require the consumer's own sessionId mapping for replay audits.
233
+ * privacy-preserving logs require the consumer's own sessionId mapping for replay.
272
234
  */
273
235
  includePlaintextIdentifiers?: boolean;
274
236
  /**
275
237
  * Cap on tracked sessions per experiment config in the sticky wrapper's registry.
276
- * Exists so tests can exercise eviction; production should keep the default (10,000).
238
+ * The default is 10,000.
277
239
  */
278
240
  maxTrackedSessions?: number;
279
241
  /**
280
242
  * Uniform-[0,1) generator keyed by a string. Defaults to a sha256-derived deterministic
281
- * generator so every assignment is replayable from the logged keys alone (design rule D5).
243
+ * generator so every assignment is replayable from the logged keys alone.
282
244
  */
283
245
  rng?: (key: string) => number;
284
- /** Receives one event per retrieval call, INCLUDING no-drop calls: control-arm membership is half the data. */
246
+ /** Receives one event per retrieval call, including calls where nothing is dropped. */
285
247
  onEvent: (event: RetrievalHoldoutEvent) => void;
286
248
  }
287
249
  interface RetrievalHoldoutEligibleItem {
@@ -298,19 +260,18 @@ interface RetrievalHoldoutEvent {
298
260
  eventId: string;
299
261
  ts: string;
300
262
  adapterId?: string;
301
- /** Plaintext session id emitted ONLY when config.includePlaintextIdentifiers is true. */
263
+ /** Plaintext session id, emitted only when `includePlaintextIdentifiers` is true. */
302
264
  sessionId?: string;
303
265
  /** Consumer-supplied experiment/outcome join id (scope.tags.taskId); deliberately plaintext. */
304
266
  taskId?: string;
305
267
  /** 1-based call counter within the session; 0 when the call is outside session randomization. */
306
268
  callIndex: number;
307
269
  /**
308
- * sha256(sessionId) prefix the default privacy-preserving session join key AND the seed-key
309
- * reference for the assignment draws (previously named rngKey; identical derivation, deduped).
270
+ * sha256(sessionId) prefix used as the privacy-preserving join key and assignment seed.
310
271
  */
311
272
  sessionIdHash?: string;
312
273
  queryHash?: string;
313
- /** Verbatim scope emitted ONLY when config.includePlaintextIdentifiers is true (PII risk). */
274
+ /** Verbatim scope, emitted only when `includePlaintextIdentifiers` is true. */
314
275
  scope?: AgentMemoryScope;
315
276
  /** sha256 prefix of the canonical-JSON scope (keys sorted, undefined stripped). */
316
277
  scopeHash?: string;
@@ -658,4 +619,4 @@ interface BuildRetrievalBenchmarkCasesFromQrelsOptions {
658
619
  splitOf?: (queryId: string) => KnowledgeBenchmarkSplit;
659
620
  }
660
621
 
661
- export { type RetrievalHoldoutConfig as $, type AgentMemoryAcquireRunLease as A, type BuildRetrievalBenchmarkCasesFromQrelsOptions as B, type KnowledgeBenchmarkSpec as C, type KnowledgeBenchmarkSplit as D, type KnowledgeBenchmarkTaskKind as E, type KnowledgeClaimMatcher as F, type KnowledgeMemoryBenchmarkCase as G, type KnowledgeMemoryBenchmarkTaskKind as H, type KnowledgeMemoryEvent as I, type KnowledgeMemoryFactMatcher as J, type KnowledgeAnswerBenchmarkCase as K, type KnowledgeRetrievalBenchmarkCase as L, type KnowledgeRetrievalBenchmarkQrel as M, type KnowledgeRetrievalBenchmarkQuery as N, type MemoryAdapterBenchmarkCandidate as O, type MemoryAdapterBenchmarkRankingRow as P, type OwnedAgentMemoryRunLease as Q, type RunRetrievalImprovementLoopResult as R, type RetrievalConfig as S, type RetrievalEvalArtifact as T, type RetrievalEvalRetriever as U, type RetrievalEvalRetrieverInput as V, type RetrievalEvalRetrieverResult as W, type RetrievalEvalScenario as X, type RetrievalGoldTarget as Y, type RetrievalHoldoutBypassReason as Z, type RetrievalHoldoutCallContext as _, type RunRetrievalImprovementLoopOptions as a, type RetrievalHoldoutEligibleItem as a0, type RetrievalHoldoutEvent as a1, type RetrievalHoldoutResult as a2, type RetrievalHoldoutSessionState as a3, type RetrievalMetricSummary as a4, type RetrievalMetricWeights as a5, type RetrievalParameterSearchSpace as a6, type RetrievalParameterSweepProposerOptions as a7, type RetrievalRecallJudgeOptions as a8, type RetrievedKnowledgeHit as a9, type RetrievedSourceSpan as aa, type RunKnowledgeBenchmarkSuiteOptions as ab, type RunKnowledgeBenchmarkSuiteResult as ac, type RunMemoryAdapterBenchmarkOptions as ad, type RunMemoryAdapterBenchmarkResult as ae, acquireAgentMemoryRunLease as af, buildRetrievalEvalDispatch as ag, buildRetrievalParameterCandidates as ah, retrievalConfigFromSurface as ai, retrievalConfigSurface as aj, retrievalParameterSweepProposer as ak, retrievalRecallJudge as al, runRetrievalImprovementLoop as am, scoreRetrievalArtifact as an, type AgentMemoryAdapter as b, type AgentMemoryBranchIsolation as c, type AgentMemoryContext as d, type AgentMemoryControllerMode as e, type AgentMemoryHit as f, type AgentMemoryKind as g, type AgentMemoryRunLease as h, type AgentMemoryScope as i, type AgentMemorySearchOptions as j, type AgentMemoryWriteInput as k, type AgentMemoryWriteResult as l, type BuildRetrievalEvalDispatchOptions as m, type BuildRetrievalParameterCandidatesOptions as n, type KnowledgeAnswerBenchmarkTaskKind as o, type KnowledgeBenchmarkArtifact as p, type KnowledgeBenchmarkCase as q, type KnowledgeBenchmarkCaseBase as r, type KnowledgeBenchmarkDistribution as s, type KnowledgeBenchmarkEvaluation as t, type KnowledgeBenchmarkFamily as u, type KnowledgeBenchmarkReport as v, type KnowledgeBenchmarkResponder as w, type KnowledgeBenchmarkScenario as x, type KnowledgeBenchmarkSliceSummary as y, type KnowledgeBenchmarkSource as z };
622
+ export { type RetrievalHoldoutConfig as $, type AgentMemoryAcquireRunLease as A, type BuildRetrievalBenchmarkCasesFromQrelsOptions as B, type KnowledgeBenchmarkScenario as C, type KnowledgeBenchmarkSliceSummary as D, type KnowledgeBenchmarkSource as E, type KnowledgeBenchmarkSpec as F, type KnowledgeBenchmarkSplit as G, type KnowledgeBenchmarkTaskKind as H, type KnowledgeClaimMatcher as I, type KnowledgeMemoryBenchmarkCase as J, type KnowledgeAnswerBenchmarkCase as K, type KnowledgeMemoryBenchmarkTaskKind as L, type KnowledgeMemoryEvent as M, type KnowledgeMemoryFactMatcher as N, type KnowledgeRetrievalBenchmarkCase as O, type KnowledgeRetrievalBenchmarkQrel as P, type KnowledgeRetrievalBenchmarkQuery as Q, type RetrievalConfig as R, type MemoryAdapterBenchmarkCandidate as S, type MemoryAdapterBenchmarkRankingRow as T, type OwnedAgentMemoryRunLease as U, type PartitionRetrievalScenariosOptions as V, type RetrievalEvalRetrieverInput as W, type RetrievalEvalRetrieverResult as X, type RetrievalGoldTarget as Y, type RetrievalHoldoutBypassReason as Z, type RetrievalHoldoutCallContext as _, type RetrievalEvalScenario as a, type RetrievalHoldoutEligibleItem as a0, type RetrievalHoldoutEvent as a1, type RetrievalHoldoutResult as a2, type RetrievalHoldoutSessionState as a3, type RetrievalMetricSummary as a4, type RetrievalRecallJudgeOptions as a5, type RetrievalScenarioPartitions as a6, type RetrievedSourceSpan as a7, type RunKnowledgeBenchmarkSuiteOptions as a8, type RunKnowledgeBenchmarkSuiteResult as a9, type RunMemoryAdapterBenchmarkOptions as aa, type RunMemoryAdapterBenchmarkResult as ab, acquireAgentMemoryRunLease as ac, buildRetrievalEvalDispatch as ad, partitionRetrievalScenarios as ae, retrievalConfigFromSurface as af, retrievalConfigSurface as ag, retrievalRecallJudge as ah, scoreRetrievalArtifact as ai, type RetrievalEvalArtifact as b, type RetrievalEvalRetriever as c, type RetrievalMetricWeights as d, type RetrievedKnowledgeHit as e, type AgentMemoryAdapter as f, type AgentMemoryBranchIsolation as g, type AgentMemoryContext as h, type AgentMemoryControllerMode as i, type AgentMemoryHit as j, type AgentMemoryKind as k, type AgentMemoryRunLease as l, type AgentMemoryScope as m, type AgentMemorySearchOptions as n, type AgentMemoryWriteInput as o, type AgentMemoryWriteResult as p, type BuildRetrievalEvalDispatchOptions as q, type KnowledgeAnswerBenchmarkTaskKind as r, type KnowledgeBenchmarkArtifact as s, type KnowledgeBenchmarkCase as t, type KnowledgeBenchmarkCaseBase as u, type KnowledgeBenchmarkDistribution as v, type KnowledgeBenchmarkEvaluation as w, type KnowledgeBenchmarkFamily as x, type KnowledgeBenchmarkReport as y, type KnowledgeBenchmarkResponder as z };
@@ -1,10 +1,10 @@
1
- # Held-out investment-research eval set material facts + provenance
1
+ # Held-out investment-research eval set: material facts + provenance
2
2
 
3
3
  This is the answer key and the provenance ledger for `tests/eval/investment-thesis-set.ts`.
4
4
 
5
5
  **What the set measures.** Give a research loop a company + ticker + an as-of
6
6
  **cutoff** date and ask it to write an investment thesis. Then grade that thesis
7
- against the held-out **material facts** below facts the loop never saw. A high
7
+ against the held-out **material facts** below, facts the loop never saw. A high
8
8
  score means the thesis surfaced the buried, material, non-obvious drivers a
9
9
  thorough analyst would flag and a single ticker search would miss; it is **not**
10
10
  teaching-to-the-test, because the answer key is firewalled from every loop and
@@ -20,14 +20,13 @@ the grader is a `$0`, model-free substring check (`gradeFactAgainstText`).
20
20
  guessed (see the drop log).
21
21
  3. **Knowable at the cutoff.** Every value was disclosed in, or computable from, a
22
22
  filing available on or before the cutoff. The eventual collapse is **not** a
23
- checklist item it is recorded as `knownOutcome`, for the reader only, and is
24
- never graded.
23
+ checklist item. It is recorded as `knownOutcome` for the reader and is never graded.
25
24
 
26
25
  All five primary documents were fetched live from `https://www.sec.gov/Archives/`
27
26
  during curation (a `curl` with a descriptive `User-Agent`, per SEC fair-access
28
27
  rules). Every dollar figure below was read directly out of the de-tagged filing
29
- text. Provenance is verifiable: each `sourceUrl` contains the company's SEC CIK,
30
- and `tests/eval/investment-thesis-set.test.ts` asserts that invariant.
28
+ text. Each `sourceUrl` contains the company's SEC CIK, and
29
+ `tests/eval/investment-thesis-set.test.ts` checks that invariant.
31
30
 
32
31
  ---
33
32
 
@@ -47,7 +46,7 @@ set was curated (June 2026); `investment-thesis-set.test.ts` asserts this.
47
46
 
48
47
  ---
49
48
 
50
- ## SIVB SVB Financial Group (cutoff 2023-02-24)
49
+ ## SIVB: SVB Financial Group (cutoff 2023-02-24)
51
50
 
52
51
  Source: [FY2022 10-K (`sivb-20221231.htm`)](https://www.sec.gov/Archives/edgar/data/719739/000071973923000021/sivb-20221231.htm)
53
52
  **Known outcome (not graded):** FDIC receivership March 10, 2023; holding-company Chapter 11 March 17, 2023.
@@ -59,14 +58,14 @@ Source: [FY2022 10-K (`sivb-20221231.htm`)](https://www.sec.gov/Archives/edgar/d
59
58
  | SIVB/f3 | concentration | Run-prone uninsured deposit base | "estimated uninsured deposits in U.S. offices that exceed the FDIC insurance limit were **$151.5 billion**" |
60
59
  | SIVB/f4 | margin-trend | Cheap deposits fleeing → funding cost set to rise | "Noninterest-bearing demand deposits to total deposits decreased by **20 percentage points to 47 percent**" |
61
60
  | SIVB/f5 | concentration | Single-client-type (innovation-economy) deposit + credit base | 10-K frames the franchise around "the innovation economy" (technology, life-science, venture) |
62
- | SIVB/f6 | off-balance-sheet | AFS loss in AOCI the visible, smaller tip | "Available-for-sale securities, at fair value (cost of $ **28,602**) **26,069**" → ~$2.5B AFS loss in AOCI |
61
+ | SIVB/f6 | off-balance-sheet | AFS loss in AOCI; the visible, smaller tip | "Available-for-sale securities, at fair value (cost of $ **28,602**) **26,069**" → ~$2.5B AFS loss in AOCI |
63
62
 
64
63
  The decisive, non-obvious fact is SIVB/f1+f2: an interest-rate loss roughly equal
65
64
  to all of equity, sitting in the footnotes because HTM accounting keeps it out of
66
65
  both earnings and book equity. A ticker search shows a profitable bank; the
67
66
  filing shows a mark-to-market hole the size of its capital.
68
67
 
69
- ## BBBY Bed Bath & Beyond Inc. (cutoff 2022-04-21)
68
+ ## BBBY: Bed Bath & Beyond Inc. (cutoff 2022-04-21)
70
69
 
71
70
  Source: [FY2021 10-K (`bbby-20220226.htm`)](https://www.sec.gov/Archives/edgar/data/886158/000088615822000047/bbby-20220226.htm)
72
71
  **Known outcome (not graded):** Chapter 11 on April 23, 2023; equity wiped out.
@@ -80,11 +79,11 @@ Source: [FY2021 10-K (`bbby-20220226.htm`)](https://www.sec.gov/Archives/edgar/d
80
79
  | BBBY/f5 | margin-trend | Inventory building into a demand decline | "Merchandise inventories **1,725,410** 1,671,909" ($ thousands) |
81
80
 
82
81
  The non-obvious fact is BBBY/f1+f2+f4 together: in FY2021 the company **lost $560M,
83
- generated only $18M of operating cash, and still spent $575M buying back stock** —
82
+ generated only $18M of operating cash, and still spent $575M buying back stock**,
84
83
  returning more cash than it had. The buyback, not the income statement alone, is
85
84
  why a $1.3B equity base became $174M.
86
85
 
87
- ## CVNA Carvana Co. (cutoff 2023-02-23)
86
+ ## CVNA: Carvana Co. (cutoff 2023-02-23)
88
87
 
89
88
  Source: [FY2022 10-K (`cvna-20221231.htm`)](https://www.sec.gov/Archives/edgar/data/1690820/000169082023000052/cvna-20221231.htm)
90
89
  **Known outcome (not graded):** Stock fell ~98% from its 2021 peak; a 2023 debt exchange cut and extended obligations, narrowly avoiding bankruptcy.
@@ -97,18 +96,18 @@ Source: [FY2022 10-K (`cvna-20221231.htm`)](https://www.sec.gov/Archives/edgar/d
97
96
  | CVNA/f4 | governance | Recurring related-party leases with the founder's family | Related-Party note: DriveTime, controlled by "Ernest Garcia II, Ernest Garcia III, and entities controlled by one or both of them" |
98
97
  | CVNA/f5 | liquidity | A wide loss showing unit economics had not turned | "Net loss $ (**2,894**)" ($ millions) |
99
98
 
100
- The non-obvious facts are CVNA/f2 (interest expense up 2.8x the debt was now
101
- expensive, not just large) and CVNA/f4 (the controlling Garcia family on both
99
+ The non-obvious facts are CVNA/f2 (interest expense up 2.8x, making the debt expensive
100
+ as well as large) and CVNA/f4 (the controlling Garcia family on both
102
101
  sides of material leases via DriveTime), neither of which a ticker quote shows.
103
102
 
104
- ## PTON Peloton Interactive, Inc. (cutoff 2022-09-07)
103
+ ## PTON: Peloton Interactive, Inc. (cutoff 2022-09-07)
105
104
 
106
105
  Source: [FY2022 10-K (`pton-20220630.htm`)](https://www.sec.gov/Archives/edgar/data/1639825/000163982522000117/pton-20220630.htm)
107
106
  **Known outcome (not graded):** Stock fell ~95% from its 2021 peak; founder-CEO departed; mass layoffs and a multi-year turnaround.
108
107
 
109
108
  | ID | Lens | Material fact | Value read from the filing |
110
109
  |---|---|---|---|
111
- | PTON/f1 | margin-trend | Hardware gross margin turned **negative** | Connected Fitness "Gross Margin decreased to (**11**)" percent losing money per unit sold |
110
+ | PTON/f1 | margin-trend | Hardware gross margin turned **negative** | Connected Fitness "Gross Margin decreased to (**11**)" percent; losing money per unit sold |
112
111
  | PTON/f2 | liquidity | Inventory glut as pandemic demand normalized | "Inventories, net **1,104.5** 937" ($ millions) |
113
112
  | PTON/f3 | governance | Dual-class super-voting control | "Class B common stock has **20 votes per share** and our Class A common stock has one vote per share" |
114
113
  | PTON/f4 | liquidity | An order-of-magnitude wider loss | "Net loss $ (**2,827**)" ($ millions) |
@@ -116,11 +115,11 @@ Source: [FY2022 10-K (`pton-20220630.htm`)](https://www.sec.gov/Archives/edgar/d
116
115
  | PTON/f6 | leverage | Locked-in purchase commitments into falling demand | "purchase commitments related to the manufacture of Peloton products were estimated to be approximately **$334**" million |
117
116
 
118
117
  The non-obvious fact is PTON/f1: revenue was still large, but the **hardware was
119
- sold below cost** (−11% gross margin) the unit economics, not just the growth
120
- rate, had broken. PTON/f6 compounds it: the company was contractually obliged to
118
+ sold below cost** (−11% gross margin). The unit economics had broken despite the
119
+ top-line growth. PTON/f6 compounds it: the company was contractually obliged to
121
120
  buy more inventory it could not sell.
122
121
 
123
- ## SI Silvergate Capital Corporation (cutoff 2022-02-28)
122
+ ## SI: Silvergate Capital Corporation (cutoff 2022-02-28)
124
123
 
125
124
  Source: [FY2021 10-K (`si-20211231.htm`)](https://www.sec.gov/Archives/edgar/data/1312109/000131210922000051/si-20211231.htm)
126
125
  **Known outcome (not graded):** After the FTX collapse triggered a deposit run, Silvergate announced a voluntary wind-down and liquidation of Silvergate Bank in March 2023.
@@ -134,7 +133,7 @@ Source: [FY2021 10-K (`si-20211231.htm`)](https://www.sec.gov/Archives/edgar/dat
134
133
  | SI/f5 | concentration | The moat AND the funding are the same crypto-only bet | "Silvergate Exchange Network ('SEN'), our proprietary ... payment network for participants in the digital currency industry" |
135
134
 
136
135
  The non-obvious fact is SI/f1+f2 together: **99.5% noninterest-bearing deposits,
137
- ~58% from crypto exchanges** a funding base with no contractual term and a
136
+ ~58% from crypto exchanges**, a funding base with no contractual term and a
138
137
  single correlated counterparty type. A ticker quote shows a fast-growing,
139
138
  low-cost-funding bank; the filing shows a bank that could be emptied in days if
140
139
  crypto sentiment turned.
@@ -176,8 +175,8 @@ should not be read as a general "investment-research quality" number. The biases
176
175
 
177
176
  3. **Sector skew toward financials + distressed consumer.** Two of five are banks
178
177
  (SIVB, SI). The two banks are deliberately given **different** buried-risk
179
- lenses SIVB is an interest-rate / duration / off-balance-sheet story, SI is a
180
- single-industry deposit-concentration story so they are not redundant, but
178
+ lenses, SIVB is an interest-rate / duration / off-balance-sheet story, SI is a
179
+ single-industry deposit-concentration story, so they are not redundant, but
181
180
  the set still over-indexes on balance-sheet fragility and under-tests, e.g.,
182
181
  technology platform risk, supply-chain concentration, or accounting-policy
183
182
  aggressiveness in a healthy grower.
@@ -197,33 +196,33 @@ should not be read as a general "investment-research quality" number. The biases
197
196
  required a second independent source to establish was dropped (below) rather
198
197
  than sourced to the filing alone.
199
198
 
200
- ## Drop log items considered and NOT included (honesty over coverage)
199
+ ## Drop log: excluded items
201
200
 
202
201
  These were candidate facts I could not independently ground to a primary source
203
202
  available at the cutoff, so I **dropped them rather than guess**:
204
203
 
205
- - **First Republic Bank (FRC)** dropped as a company entirely. First Republic
204
+ - **First Republic Bank (FRC)**: dropped as a company entirely. First Republic
206
205
  was a state-chartered bank that filed its annual reports with the **FDIC**, not
207
206
  on SEC EDGAR, so its 10-K is not at a `sec.gov/Archives` URL and I could not give
208
- it the same clean, CIK-verifiable provenance as the other five. Its widely cited
207
+ it the same CIK-matched provenance as the other five. Its widely cited
209
208
  figures (~$15B HTM-style loss, ~$119.5B uninsured deposits) are real but are best
210
- sourced from the FDIC OIG Material Loss Review, a **post**-cutoff document using
209
+ sourced from the FDIC OIG Material Loss Review, a **post**-cutoff document, using
211
210
  it would violate rule 3. Replaced with Silvergate, whose 10-K is on EDGAR.
212
211
 
213
- - **SIVB exact total unrealized-loss footnote line** I report the HTM gap as the
212
+ - **SIVB exact total unrealized-loss footnote line**: I report the HTM gap as the
214
213
  arithmetic difference of two figures printed on the balance sheet
215
214
  ($91,321M − $76,169M), which is exact and on-cutoff. I did **not** include a
216
215
  separately-quoted "$15.1B net unrealized loss" sentence because I did not locate
217
216
  that exact phrasing in the de-tagged text; quoting a number I could not point to
218
217
  verbatim would break rule 2. The computed value is conservative and checkable.
219
218
 
220
- - **CVNA negative gross-profit-per-unit** a frequently-cited Carvana red flag,
219
+ - **CVNA negative gross-profit-per-unit**: a frequently-cited Carvana red flag,
221
220
  but the per-unit figure I could find cleanly was a derived/analyst number, not a
222
221
  single line item I could quote verbatim from the 10-K at the cutoff. Dropped in
223
222
  favor of the directly-quoted total debt, interest expense, ADESA price, related
224
223
  party, and net loss.
225
224
 
226
- - **PTON / SI specific debt-covenant or going-concern language** I searched for
225
+ - **PTON / SI specific debt-covenant or going-concern language**: I searched for
227
226
  explicit "substantial doubt / going concern" wording in both filings and did
228
227
  **not** find it at these cutoffs (it came later). I did not invent it. The facts
229
228
  included are the ones actually present in the cutoff-date document.
@@ -248,5 +247,5 @@ for (const company of investmentThesisSet) {
248
247
  ```
249
248
 
250
249
  The grader is deterministic and model-free, so the same thesis always scores the
251
- same and the answer key never reaches a model the loop could observe the same
250
+ same and the answer key never reaches a model the loop could observe, the same
252
251
  firewall the deep-question exam (`tests/loops/held-out-exam.ts`) uses.
@@ -1,6 +1,6 @@
1
1
  # RAG Eval Completion Roadmap
2
2
 
3
- Verdict: `runRetrievalImprovementLoop()` is the right first loop, but it is only the retrieval layer.
3
+ Verdict: use retrieval-only optimization when the retriever is the only changing component, and full RAG optimization when retrieval and answer behavior must move together.
4
4
  SOTA RAG evaluation requires retrieval quality, context quality, generated-answer quality, abstention behavior, robustness, and operating budgets.
5
5
 
6
6
  ## Research Basis
@@ -12,30 +12,34 @@ SOTA RAG evaluation requires retrieval quality, context quality, generated-answe
12
12
  | [TruLens RAG Triad](https://www.trulens.org/getting_started/core_concepts/rag_triad/) | The minimal end-to-end triad is context relevance, groundedness, and answer relevance. |
13
13
  | [RAGChecker](https://papers.nips.cc/paper_files/paper/2024/hash/27245589131d17368cccdfa990cbf16e-Abstract-Datasets_and_Benchmarks_Track.html) | Fine-grained diagnosis should separate retrieval misses, noisy context, and unsupported generated claims. |
14
14
  | [BEIR](https://arxiv.org/abs/2104.08663) / TREC-style retrieval | Retrieval still needs classical rank metrics: Recall@k, Precision@k, MRR, MAP, and nDCG. |
15
- | [CRAG](https://arxiv.org/abs/2406.04744) | Real RAG evals must include long-tail, dynamic, multi-hop, and unanswerable questions, not only easy static facts. |
15
+ | [CRAG](https://arxiv.org/abs/2406.04744) | Real RAG evals must include long-tail, dynamic, multi-hop, and unanswerable questions alongside easy static facts. |
16
16
  | [DeepEval RAG metrics](https://deepeval.com/docs/metrics-faithfulness) | Production tools converge on faithfulness, answer relevance, and context relevance as generator/retriever checks. |
17
17
 
18
18
  ## Current Repo Status
19
19
 
20
20
  Done:
21
21
 
22
- - `runRetrievalImprovementLoop()` auto-searches retrieval configs through `agent-eval`.
22
+ - `runRetrievalImprovementLoop()` runs a complete `agent-eval` optimization method over retrieval configs.
23
+ - `runRagOptimization()` does the same for a serialized retrieval and answer configuration.
23
24
  - `runRagKnowledgeImprovementLoop()` exposes the whole RAG lifecycle as typed phases:
24
25
  retrieval tuning, gap diagnosis, knowledge acquisition, knowledge update, answer-quality eval, and promotion.
25
26
  - Retrieval scenarios can label pages, page paths, sources, source anchors, and source spans.
26
- - The retrieval judge reports recall, MRR, nDCG, precision@k, cost, and held-out promotion.
27
- - The loop is tested with a real `agent-eval` run where `{ k: 2 }` beats `{ k: 1 }`.
27
+ - The retrieval judge reports recall, MRR, nDCG, and precision@k; `agent-eval` reports cost separately.
28
+ - Selection and final data remain independent, and the optimization method never receives final cases.
29
+ - Every reusable optimization requires an immutable execution reference covering retrieval, index, model, judge, and external-service behavior.
30
+ - The integration is tested with complete methods for retrieval and full RAG configuration.
28
31
  - The lifecycle loop is tested both with pluggable phase hooks and with a real local KB update through `runKnowledgeResearchLoop()`.
29
32
  - `ragAnswerQualityJudge()` and `createRagAnswerQualityHook()` score context precision/recall/relevance/sufficiency, faithfulness, answer relevance/correctness, citation support, abstention, and unsupported-answer rate.
30
33
  - `normalizeExternalRagScores()` and the row exporters make Ragas, DeepEval, TruLens, RAGChecker, and custom evaluator outputs pluggable instead of hard dependencies.
31
34
  - `scoreKnowledgeBaseIndex()` validates generic wiki/KB health: citation coverage, source-backed pages, stale sources, duplicate source hashes, and lint/validation errors.
32
35
  - `calibrateRagAnswerJudge()` enforces the strong-vs-weak metric check before trusting a RAG answer metric.
36
+ - `runKnowledgeImprovementJob()` in `@tangle-network/agent-runtime` connects runtime backends and worker factories to candidate KB creation, readiness checks, frozen comparisons, spend measurement, and explicit activation.
37
+ - `agent-knowledge` remains runtime-free; applications with their own agent runner pass an `updateKnowledge` callback directly.
33
38
 
34
39
  Not done:
35
40
 
36
41
  - Slice-level reporting for freshness, distractors, multi-hop, and long-tail cases.
37
- - Packaged runtime adapters for browser/coding/research agents.
38
- The lifecycle API accepts those agents as hooks today; it does not hardcode provider-specific workers.
42
+ - A maintained, public benchmark pack with at least 100 labeled scenarios and published baseline results.
39
43
 
40
44
  ## Completion Criteria
41
45
 
@@ -55,9 +59,9 @@ Required slices:
55
59
 
56
60
  Ship criteria:
57
61
 
58
- - Holdout source-span Recall@5 is at least 0.90.
59
- - Holdout nDCG@5 is at least 0.80.
60
- - Train-to-holdout recall gap is at most 0.08.
62
+ - Final source-span Recall@5 is at least 0.90.
63
+ - Final nDCG@5 is at least 0.80.
64
+ - Train-to-final recall gap is at most 0.08.
61
65
  - Stale or forbidden source hit rate is at most 0.02.
62
66
  - p95 retrieval latency and cost do not regress by more than 10 percent versus baseline.
63
67
 
@@ -68,9 +72,9 @@ Score it with deterministic checks first and LLM judges only for semantic qualit
68
72
 
69
73
  Ship criteria:
70
74
 
71
- - Faithfulness or groundedness is at least 0.95 on holdout.
72
- - Answer relevance is at least 0.90 on holdout.
73
- - Answer correctness is at least 0.85 on human-labeled holdout.
75
+ - Faithfulness or groundedness is at least 0.95 on final cases.
76
+ - Answer relevance is at least 0.90 on final cases.
77
+ - Answer correctness is at least 0.85 on human-labeled final cases.
74
78
  - Citation support is at least 0.95 for claims that cite sources.
75
79
  - Unsupported-answer rate on unanswerable questions is at most 0.05.
76
80
 
@@ -95,13 +99,13 @@ Ship criteria:
95
99
 
96
100
  - Every failed eval has one primary failure class.
97
101
  - At least 95 percent of generated claims can be mapped to supporting context, contradicted context, or no context.
98
- - Reports show metrics by slice and by failure class, not only the aggregate score.
102
+ - Reports show metrics by slice and failure class as well as the aggregate score.
99
103
 
100
104
  ### Phase 4: Production Loop
101
105
 
102
106
  Run the same eval pack on every retrieval or prompt change.
103
- Keep train/dev/holdout isolated.
104
- Never tune on holdout.
107
+ Keep train, selection, and final data isolated.
108
+ Never tune on final data.
105
109
 
106
110
  Ship criteria:
107
111
 
@@ -115,5 +119,5 @@ Ship criteria:
115
119
 
116
120
  1. Add slice-level aggregation helpers for freshness, distractors, multi-hop, long-tail, and unanswerable cases.
117
121
  2. Add forbidden/stale source targets to retrieval scenarios.
118
- 3. Add packaged adapters that turn `agent-runtime` browser, research, and coding agents into `runRagKnowledgeImprovementLoop()` hooks.
122
+ 3. Add a maintained benchmark pack with at least 100 labeled scenarios and a reproducible baseline report.
119
123
  4. Add a CLI command that runs the lifecycle loop and writes a reproducible report under `.agent-knowledge/eval/`.