-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongMemEvalS.ts
More file actions
2904 lines (2799 loc) · 123 KB
/
Copy pathLongMemEvalS.ts
File metadata and controls
2904 lines (2799 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file LongMemEvalS.ts
* @description LongMemEval-S benchmark adapter.
*
* Drives AgentOS memory through the canonical 500-case LongMemEval-S
* set (~115k-token haystacks). Each case:
*
* 1. Build a fresh memory instance for this run's memory mode.
* 2. Replay `case.haystack` via {@link ConversationReplay} (observe
* for cognitive, ingest for base, no-op for none).
* 3. Recall the top-K traces relevant to `case.question`.
* 4. Invoke the reader with a system prompt composed of the
* retrieved context plus the question as the user message.
* 5. Return the answer text.
*
* Scoring uses {@link LongMemEvalJudge} with GPT-4o. Per-type accuracy
* breakdown is emitted in {@link BenchResult.byType}.
*
* This adapter pins against the public facade APIs (`Memory`,
* `CognitiveMemoryManager`) so internal memory refactors don't break
* the benchmark harness.
*
* @module agentos-bench/benchmarks/longmemeval/LongMemEvalS
*/
import path from 'node:path';
import { promises as fs } from 'node:fs';
import { Memory } from '@framers/agentos';
import type { MemoryRetrievalPolicy } from '@framers/agentos';
import type { ScoredTrace } from '@framers/agentos';
import type { IEmbeddingManager } from '@framers/agentos/core/embeddings/IEmbeddingManager';
import type {
BenchCase,
BenchContext,
BenchResult,
CaseResult,
CaseRun,
IBenchmark,
ReaderModel,
} from '../../core/IBenchmark.js';
import {
buildHaystackContext,
replayViaIngest,
} from '../../core/ConversationReplay.js';
import { mean, percentile, stdDev } from '../../core/statsUtil.js';
import {
computeRetrievalMetrics,
computeRetrievalStageMetrics,
type RetrievalStageMetrics,
computeEvidenceProvenance,
type EvidenceTrace,
computeLatencyBreakdown,
computePolicyRouterStats,
computeStratifiedAccuracy,
computeTokenEfficiency,
computeTokenRetention,
LONGMEMEVAL_S_PRIORS,
type MemoryFootprint,
type PolicyRouterStats,
} from '../../core/metrics/index.js';
import type { IReader } from '../../readers/IReader.js';
import { createReader } from '../../readers/createReader.js';
import type { SessionSummarizer } from '@framers/agentos/memory';
import { extractEntities } from '@framers/agentos/memory';
import { twoCallRead, type RetrievedPassage } from '../../readers/twoCallReader.js';
import {
ingestSessions,
buildOmReaderSystemPrompt,
classifyQuestion,
routeQuestion,
DEFAULT_ROUTE,
extractPerSessionBlocks,
scoreSessionsByQueryRelevance,
pickCandidateSessions,
CONDITIONAL_VERBATIM_CITATION,
type OmSession,
type QuestionCategory,
type RouterConfig,
} from '../../observational-memory/index.js';
import { createCognitiveManager } from '../../cognitive/createCognitiveManager.js';
import {
DEFAULT_BACKEND_COSTS,
PRESET_TABLES,
selectBackend,
type PolicyBackend,
type PolicyRouterConfig,
type PolicyRouterDecision,
} from '../../core/policyRouter.js';
import {
selectReader,
type ReaderRouterPreset,
} from '../../core/readerRouter.js';
import {
MINIMIZE_COST_AUGMENTED_TABLE,
S_BEST_CAT_HYDE_MS_2026_04_28_TABLE,
S_BEST_CAT_TOPK50_MULT5_MS_2026_04_29_TABLE,
RETRIEVAL_CONFIG_SPECS,
selectAugmentedDispatch,
type AugmentedRoutingTable,
type MemoryQueryCategory,
type RetrievalConfigId,
} from '@framers/agentos/memory-router';
import { loadLongMemEvalDataset, type LongMemEvalVariant } from './dataset.js';
import {
BENCH_SESSION_TAG_PREFIX,
extractBenchSessionTag,
} from './extractBenchSessionTag.js';
/**
* Configuration specific to the LongMemEval adapter. Separate from
* {@link RunConfig} because the reader and the (optional) memory
* provider live outside the general bench context.
*/
export interface LongMemEvalAdapterOptions {
/** Reader LLM for answering questions. Bench tests inject a MockReader. */
reader: IReader;
/**
* Optional auxiliary reader pool for the per-category reader-tier router
* ({@link ../../core/readerRouter.ts}). Required only when
* `ctx.config.readerRouter` is set; supplies the reader instances the
* router can dispatch to (e.g. `{ 'gpt-4o': IReader, 'gpt-5-mini':
* IReader }`). When the dispatched tier is missing from this pool, the
* router silently falls back to {@link reader} for that case.
*/
readerByTier?: Partial<Record<import('../../core/readerRouter.js').ReaderTier, IReader>>;
/** Variant — `s`, `m`, or `oracle`. */
variant: LongMemEvalVariant;
/** Maximum reader answer tokens. Defaults to 256 — answers are usually short. */
maxAnswerTokens?: number;
/** How many recalled memory traces to fold into the reader's prompt. */
recallTopK?: number;
/**
* Optional {@link IEmbeddingManager} for the full-cognitive path.
* Defaults to the CharHashEmbedder stub (offline, deterministic
* lexical only). Production / publishable runs should inject an
* OpenAIEmbedder or equivalent so the cognitive retrieval path sees
* real semantic similarity.
*/
embedder?: IEmbeddingManager;
/**
* Optional session-level contextual-retrieval summarizer
* (Anthropic Sep 2024 variant, `@framers/agentos/memory`). When set,
* every chunk fed to the cognitive memory's embedder is prepended
* with a 50-100 token LLM-generated summary of its source session,
* giving the embedding session-wide context it would otherwise miss.
* The CLI constructs this from `--context-summary <model>` and
* passes it here so the adapter stays framework-agnostic.
*/
sessionSummarizer?: SessionSummarizer;
/**
* Step-2 session-level retrieval store. When set, summaries
* produced by `sessionSummarizer` are indexed into this store during
* replay, and the runFullCognitive path uses a `SessionRetriever`
* backed by this store instead of single-stage `manager.retrieve`.
*/
sessionSummaryStore?: import('@framers/agentos/memory').SessionSummaryStore;
/** Step-2: K sessions for Stage 1 (default 5). */
sessionRetrievalTopSessions?: number;
/** Step-2: M chunks per session for Stage 2 (default 3). */
sessionRetrievalChunksPerSession?: number;
/**
* Step-3: enable hybrid BM25 + dense RRF retrieval. The per-case
* `HybridRetriever` is constructed inside `runFullCognitiveCase`
* using the manager's `MemoryStore`. Mutually exclusive with
* `sessionSummaryStore` in MVP — throws a runtime error if both
* are set.
*/
hybridRetrievalEnabled?: boolean;
/**
* Step-4: enable HyDE (Hypothetical Document Embedding). When
* true, the adapter builds a cheap LLM invoker wrapping the main
* `reader` and passes it to `createCognitiveManager` as
* `hydeLlmInvoker`. On the baseline branch it sets `hyde: true`
* in the `manager.retrieve(...)` options. On the hybrid branch it
* passes `manager.getHydeRetriever()` into the `HybridRetriever`
* constructor so the hypothesis queries BOTH dense and sparse.
*/
hydeEnabled?: boolean;
/**
* Step-5: enable FactSupersession post-retrieval filter. Adapter
* constructs a cheap LLM invoker around the main `reader` and
* runs `FactSupersession.resolve()` on the retrieved traces
* before feeding them to the reader's system prompt.
*/
factSupersessionEnabled?: boolean;
/**
* Step-6: threshold for split-on-ambiguous rerank refinement. When
* > 0 and `hybridRetrievalEnabled` is true, the adapter passes this
* to the `HybridRetriever` constructor. Typical: 0.3.
*/
splitAmbiguousThreshold?: number;
/**
* Step-7 (Tier 2): enable Observer/Reflector pipeline. Adapter builds
* a gpt-5-mini invoker, passes to `createCognitiveManager` as
* `observerReflectorLlmInvoker`, and calls `manager.observe(...)` on
* each conversation turn during `replayForCognitive`. At end of each
* benchmark case, force-drains buffered notes through compression
* and reflection cycles.
*/
observerReflectorEnabled?: boolean;
/**
* Step-8: REPLACEMENT semantics. When true (requires
* `observerReflectorEnabled`), adapter skips raw chunk encoding,
* forces reflection at session boundaries via
* `manager.flushReflection()`, and indexes reflection-derived trace
* IDs into BM25.
*/
observerReflectorReplaceEnabled?: boolean;
/**
* Step-9 (Tier 3): when true, the adapter constructs a cost-tracked
* gpt-5-mini invoker and wires Mem0-style fact-graph ingest through
* `createCognitiveManager`. Per-session fact extraction runs at
* ingest boundaries; synthetic fact-graph traces are prepended to
* the `HybridRetriever` merged pool. Mutually exclusive with
* `observerReflectorEnabled` (enforced in resolveRunConfig).
*/
factGraphIngestEnabled?: boolean;
/**
* Step-13: enable graph-activation wire-up. When true, the bench runs
* heuristic entity extraction at every `manager.encode` call
* (populating `trace.entities`) and passes
* `enableGraphActivation: true` to `createCognitiveManager` so ingest
* creates entity nodes + co-occurrence edges and retrieve computes
* per-candidate spreading-activation scores (sixth composite signal).
*/
graphActivationEnabled?: boolean;
/**
* Step-15: enable Mastra-style Observational Memory. When true, the
* retrieval pipeline is bypassed entirely. Each haystack session
* is processed by an Observer LLM into dated priority-tagged
* observations. A single Reflector pass consolidates if the log
* exceeds 40k tokens. The reader sees the consolidated observation
* log as its system prompt plus the question.
*/
observationalMemoryEnabled?: boolean;
}
/**
* LongMemEval-S benchmark adapter.
*
* Memory-mode handling:
*
* - `none` → haystack is concatenated into the reader's system prompt.
* - `base-memory` → standalone `Memory` facade with per-case ingest + recall.
* - `full-cognitive` → scratch `CognitiveMemoryManager` replay + retrieval,
* with optional observer / reflector variants.
*/
export class LongMemEvalS implements IBenchmark {
readonly id: string;
readonly version = '1.0.0';
readonly family = 'external' as const;
readonly passThreshold = 0.5;
constructor(private readonly opts: LongMemEvalAdapterOptions) {
this.id = `longmemeval-${opts.variant}`;
}
async setup(_ctx: BenchContext): Promise<void> {
// The dataset must be pre-placed in <dataDir>/longmemeval/. The
// setup CLI command handles download/extract; this method is a no-op.
}
async loadTestCases(ctx: BenchContext): Promise<BenchCase[]> {
const allCases = await loadLongMemEvalDataset(ctx.dataDir, this.opts.variant);
const perType = ctx.config.samplePerType;
// Stratified sampling: take up to `samplePerType` cases from each
// case type, preserving dataset order within a type. Caps at the
// available case count when the type has fewer than N cases.
if (ctx.config.stratified && typeof perType === 'number' && perType > 0) {
const groups = new Map<string, BenchCase[]>();
for (const c of allCases) {
const g = groups.get(c.type) ?? [];
if (g.length < perType) g.push(c);
groups.set(c.type, g);
}
// Flatten, preserving a stable type-order by case-type name.
return Array.from(groups.entries())
.sort(([a], [b]) => a.localeCompare(b))
.flatMap(([, cases]) => cases);
}
return allCases;
}
async runCase(c: BenchCase, ctx: BenchContext): Promise<CaseRun> {
const start = Date.now();
const mode = ctx.config.memoryMode;
let system: string;
const retrievalPolicy = buildBenchRetrievalPolicy(ctx);
const runMetadata: Record<string, unknown> = {
memoryMode: mode,
replayMode: ctx.config.replayMode,
caseType: c.type,
// Step 18: carry gold answer + canonical-name category for the
// token-retention metric. The aggregator reads these without
// needing the original BenchmarkCase object.
expected: c.expected,
type: c.type,
};
// Step 16c v2: per-question dynamic router. When --om-dynamic-router
// is on (and --observational-memory is on), classify the question
// first and route to either canonical Step 3 HybridRetriever (no OM)
// or v5 OM (gpt-4o observer + scaffold + dual-path) based on the
// per-category Phase A best. Routing table is grounded in v5 Phase
// A N=102 results: SSU/SSA/SSP/TR → canonical; KU/MS → v5 OM.
//
// ARCHITECTURE ASSUMPTION (router caller's responsibility):
// For 16c v2 to reproduce its theoretical 79.2% Phase A ceiling,
// the run command MUST include the v5/canonical-compatible flags:
// --memory full-cognitive --replay ingest
// --om-mode dual-path --om-batch-tokens 24000
// --om-observer-model gpt-4o
// --rerank cohere --context-summary gpt-5-mini --hybrid-retrieval
// The router does NOT validate these flags. Running with non-Phase-A
// settings (e.g., --om-mode batched, --om-observer-model gpt-5-mini,
// missing --hybrid-retrieval) means the OM and canonical routes
// reflect those alternative configurations, NOT the empirical
// Phase-A-grounded routing table this design encodes.
// See docs/specs/2026-04-22-step-16c-llm-judge-router-design.md §8
// for the canonical Tier A and Phase A commands.
let routerCategory: QuestionCategory | null = null;
let routerDecision: RouterConfig | null = null;
// Tier 3 policy router state. Populated only when `policyRouter === true`.
// Mutually exclusive with `dynamicRouterOn` (validated at CLI layer).
let policyRouterDecision: PolicyRouterDecision | null = null;
const policyRouterOn = Boolean(ctx.config.policyRouter);
if (policyRouterOn) {
// Tier 3 policy router. Dispatch per-query based on the v10
// classifier's predicted category + the routing table for the
// selected preset. Backend selection {tier_1_canonical, tier_2a_v10,
// tier_2b_v11} drives whether to use OM path or canonical path; for
// OM-backend picks, it also controls whether conditional verbatim
// fires (pass routerCategory only for tier_2b, undefined for tier_2a).
const presetName = ctx.config.policyRouterPreset ?? 'maximize-accuracy';
const table = PRESET_TABLES[presetName];
const classifierModelName = (ctx.config.omClassifierModel ?? 'gpt-5-mini') as ReaderModel;
const classifierReader = createReader(classifierModelName);
let classifierTokensIn = 0;
let classifierTokensOut = 0;
let classifierModel: string = 'gpt-5-mini';
let predictedCategory: QuestionCategory = 'multi-session';
try {
const result = await classifyQuestion({
reader: classifierReader,
question: c.question,
useFewshotPrompt: Boolean(ctx.config.omClassifierFewshot),
});
predictedCategory = result.category;
classifierTokensIn = result.tokensIn;
classifierTokensOut = result.tokensOut;
classifierModel = result.model;
} catch {
// Classifier errored: fall back to multi-session (routes to an OM
// backend under every shipping preset, preserving OM's cross-
// session signal). Same fallback posture as the v10 dynamic router.
predictedCategory = 'multi-session';
}
if (classifierTokensIn > 0 || classifierTokensOut > 0) {
ctx.costTracker.record({
category: 'reader',
model: classifierModel,
tokensIn: classifierTokensIn,
tokensOut: classifierTokensOut,
tag: `${c.id}:policy-router-classifier`,
});
}
const policyConfig: PolicyRouterConfig = {
table,
budgetPerQuery: ctx.config.policyRouterBudgetPerQuery ?? null,
budgetMode: ctx.config.policyRouterBudgetMode ?? 'hard',
backendCosts: DEFAULT_BACKEND_COSTS,
};
// c.type is the ground-truth LongMemEval category. Cast because the
// caseType metadata is loosely typed upstream.
const groundTruthCategory = (c.type as QuestionCategory | undefined) ?? null;
policyRouterDecision = selectBackend({
predictedCategory,
groundTruthCategory,
config: policyConfig,
});
runMetadata.policyRouter = true;
runMetadata.policyRouterDecision = policyRouterDecision;
// Mirror v10 router's pattern so downstream retention / graphing tools
// that consume metadata.omRouterCategory still see the classifier's
// prediction. Policy router is a superset of v10.
runMetadata.omRouterCategory = predictedCategory;
}
const dynamicRouterOn = Boolean(
this.opts.observationalMemoryEnabled && ctx.config.omDynamicRouter,
);
if (dynamicRouterOn) {
const classifierModelName = (ctx.config.omClassifierModel ?? 'gpt-5-mini') as ReaderModel;
const classifierReader = createReader(classifierModelName);
let classifierTokensIn = 0;
let classifierTokensOut = 0;
let classifierModel: string = 'gpt-5-mini';
try {
const result = await classifyQuestion({
reader: classifierReader,
question: c.question,
useFewshotPrompt: Boolean(ctx.config.omClassifierFewshot),
});
routerCategory = result.category;
routerDecision = routeQuestion(routerCategory);
classifierTokensIn = result.tokensIn;
classifierTokensOut = result.tokensOut;
classifierModel = result.model;
} catch {
// Classifier errored: fall back to the static DEFAULT_ROUTE
// (multi-session / runOM=true) so behavior degrades to v5 OM-only
// semantics rather than to the canonical retriever (which would
// bypass OM entirely and lose the cross-session signal).
// The 'multi-session' default category is intentional and pinned
// — if DEFAULT_ROUTE ever changes to a category not represented
// in the v11 routing table, revisit this default to ensure the
// fallback still routes through OM.
routerCategory = 'multi-session';
routerDecision = DEFAULT_ROUTE;
// Skip cost record: no tokens were consumed by us (the error came
// from the reader), so recording zeros is the honest accounting.
}
if (classifierTokensIn > 0 || classifierTokensOut > 0) {
ctx.costTracker.record({
category: 'reader',
model: classifierModel,
tokensIn: classifierTokensIn,
tokensOut: classifierTokensOut,
tag: `${c.id}:om-classifier`,
});
}
runMetadata.omDynamicRouter = true;
runMetadata.omRouterCategory = routerCategory;
runMetadata.omRouterRunOM = routerDecision.runOM;
runMetadata.omRouterScaffold = routerDecision.useScaffold;
runMetadata.omRouterRetrieval = routerDecision.runRetrieval;
}
// RetrievalConfigRouter: per-case retrieval-config dispatch on
// canonical-hybrid. Classifies the question via gpt-5-mini, looks
// up the chosen preset's table, and produces a per-case override
// spec that supersedes the run-level --hyde / --reader-top-k /
// --rerank-candidate-multiplier flags for this case only. Reuses
// the policy-router's classifier output when both flags are on
// (saves one LLM call per case). Backend axis of the augmented
// table is ignored on this path — the backend stays canonical-
// hybrid and only the retrieval-config axis is applied.
//
// Presets:
// - minimize-cost-augmented (v2 calibration; LongMemEval-M Phase A
// N=54 ablation matrix per category).
// - s-best-cat-hyde-ms-2026-04-28 (S Pareto-win pre-validation
// hypothesis; canonical everywhere except multi-session → HyDE).
let retrievalConfigOverride:
| {
hyde?: boolean;
readerTopK?: number;
rerankCandidateMultiplier?: number;
}
| undefined;
let retrievalConfigDispatchedId: RetrievalConfigId | undefined;
let retrievalConfigClassifierCategory: MemoryQueryCategory | undefined;
const rcrPreset = ctx.config.retrievalConfigRouter;
if (rcrPreset) {
const augmentedTable: AugmentedRoutingTable | undefined =
rcrPreset === 'minimize-cost-augmented'
? MINIMIZE_COST_AUGMENTED_TABLE
: rcrPreset === 's-best-cat-hyde-ms-2026-04-28'
? S_BEST_CAT_HYDE_MS_2026_04_28_TABLE
: rcrPreset === 's-best-cat-topk50-mult5-ms-2026-04-29'
? S_BEST_CAT_TOPK50_MULT5_MS_2026_04_29_TABLE
: undefined;
if (!augmentedTable) {
throw new Error(
`[longmemeval] retrievalConfigRouter='${rcrPreset}' is not a registered preset.`,
);
}
// Reuse the policy-router classifier when active (predictedCategory
// populated above). When neither policy nor om-dynamic router fired,
// run a fresh classifier call using gpt-5-mini with the same
// few-shot prompt variant the existing routers use.
let predictedCategory: QuestionCategory;
if (policyRouterOn && policyRouterDecision) {
predictedCategory = policyRouterDecision.predictedCategory;
} else if (dynamicRouterOn && routerCategory) {
predictedCategory = routerCategory;
} else {
const classifierModelName = (ctx.config.omClassifierModel ??
'gpt-5-mini') as ReaderModel;
const classifierReader = createReader(classifierModelName);
let cTokensIn = 0;
let cTokensOut = 0;
let cModel = 'gpt-5-mini';
try {
const result = await classifyQuestion({
reader: classifierReader,
question: c.question,
useFewshotPrompt: Boolean(ctx.config.omClassifierFewshot),
});
predictedCategory = result.category;
cTokensIn = result.tokensIn;
cTokensOut = result.tokensOut;
cModel = result.model;
} catch {
// Classifier errored: fall back to multi-session — every
// shipped preset's MS dispatch is the most-coverage retrieval
// config (HyDE on s-best-cat-hyde-ms-2026-04-28; combined on
// minimize-cost-augmented), the safest default for an
// unknown query.
predictedCategory = 'multi-session';
}
if (cTokensIn > 0 || cTokensOut > 0) {
ctx.costTracker.record({
category: 'reader',
model: cModel,
tokensIn: cTokensIn,
tokensOut: cTokensOut,
tag: `${c.id}:retrieval-config-classifier`,
});
}
}
// QuestionCategory and MemoryQueryCategory are structurally identical
// (same six string-literal members); cast through unknown so the
// bench's local type aligns with the agentos memory-router type.
const memoryCategory = predictedCategory as unknown as MemoryQueryCategory;
const dispatchKey = selectAugmentedDispatch(memoryCategory, augmentedTable);
const spec = RETRIEVAL_CONFIG_SPECS[dispatchKey.retrievalConfig];
retrievalConfigOverride = {
hyde: spec.hyde,
readerTopK: spec.readerTopK,
rerankCandidateMultiplier: spec.rerankCandidateMultiplier,
};
retrievalConfigDispatchedId = dispatchKey.retrievalConfig;
retrievalConfigClassifierCategory = memoryCategory;
runMetadata.retrievalConfigRouter = rcrPreset;
runMetadata.retrievalConfigDispatched = retrievalConfigDispatchedId;
runMetadata.retrievalConfigCategory = retrievalConfigClassifierCategory;
runMetadata.retrievalConfigBackendIgnored = dispatchKey.backend;
}
// Effective branch decision:
// - Tier 3 policy router ON: use OM branch iff chosenBackend != tier_1_canonical
// - Legacy v10 router ON: use OM branch per routerDecision.runOM
// - Both OFF: static --observational-memory flag
const useOmBranch = policyRouterOn
? policyRouterDecision!.chosenBackend !== 'tier_1_canonical'
: dynamicRouterOn
? routerDecision!.runOM
: Boolean(this.opts.observationalMemoryEnabled);
// Step 15: Observational Memory bypasses ALL retrieval. When the flag
// is on we ignore `mode` and run a dedicated OM ingest + single-call
// reader path. Mastra's published 84.23% at gpt-4o uses this shape.
if (useOmBranch) {
// Step 15 v5: Observer/Reflector model selectable. Default
// gpt-5-mini (consistent with v1-v4); --om-observer-model upgrades
// to a stronger model (e.g. gpt-4o) when the caller wants to test
// the observer-tier hypothesis.
const observerModel = (ctx.config.omObserverModel ?? 'gpt-5-mini') as ReaderModel;
const observerReader = createReader(observerModel);
const sessions: OmSession[] = c.haystack.map((s) => ({
sessionId: s.sessionId,
date: s.date,
turns: s.turns.map((t) => ({
role: t.role,
content: t.content,
timestamp: t.timestamp,
})),
}));
// Step 15 v4b: hierarchical mode uses a separate synthesis reader
// (typically a stronger model like gpt-4o) for the single cross-
// session synthesis call over the per-session observation log. Not
// instantiated outside hierarchical mode to avoid unnecessary
// client overhead.
const synthesisReader =
ctx.config.omMode === 'hierarchical' && ctx.config.omSynthesisModel
? createReader(ctx.config.omSynthesisModel as ReaderModel)
: undefined;
const ingest = await ingestSessions({
observerReader,
sessions,
observerConcurrency: 6,
batchTokenTarget: ctx.config.omBatchTokenTarget ?? 24_000,
omMode: ctx.config.omMode ?? 'dual-path',
synthesisReader,
});
// Cost-track observer + reflector calls, tagged so run JSON
// attributions separate OM ingest spend from the main reader.
ctx.costTracker.record({
category: 'reader',
model: observerModel,
tokensIn: ingest.observerTokensIn,
tokensOut: ingest.observerTokensOut,
tag: `${c.id}:om-observer`,
});
if (ingest.reflectorTokensIn > 0 || ingest.reflectorTokensOut > 0) {
ctx.costTracker.record({
category: 'reader',
model: observerModel,
tokensIn: ingest.reflectorTokensIn,
tokensOut: ingest.reflectorTokensOut,
tag: `${c.id}:om-reflector`,
});
}
// Step 16: when --om-with-retrieval is on, ALSO run the full-
// cognitive HybridRetriever pipeline to produce top-K retrieved
// passages, then fuse into the reader's system prompt alongside
// OM's observation log. Both ingest pipelines run; reader sees
// dense cross-session synthesis + per-chunk verbatim specifics.
//
// Step 17: when --om-guided-retrieval is on, also run Step-16-
// shaped retrieval but POST-HOC FILTER the evidence to candidate
// sessions identified by OM-vs-question relevance scoring. This
// is the architectural alternative to Step 16c routing: instead
// of choosing canonical-or-OM per question, always run BOTH but
// scope retrieval by OM relevance.
//
// When the Step 16c v2 router OR the Tier 3 policy router is on AND
// the dispatch routed to an OM-using backend (we're here), retrieval
// is FORCED OFF: router-picked OM paths go through OM-only because
// the Step 16 family was RED. Step 16 logic is preserved for non-
// router runs via the static --om-with-retrieval flag.
const effectiveRetrieval = policyRouterOn || dynamicRouterOn
? false
: Boolean(ctx.config.omWithRetrieval);
const guidedRetrievalOn =
!policyRouterOn && !dynamicRouterOn && Boolean(ctx.config.omGuidedRetrieval);
let retrievedPassages: { id: string; content: string }[] | undefined;
if (effectiveRetrieval || guidedRetrievalOn) {
const finalK = ctx.config.readerTopK ?? this.opts.recallTopK ?? 10;
// Step 17: when guided retrieval is on, over-fetch by 6x so the
// post-hoc session filter has enough headroom to find candidate-
// session traces. Step 16 path uses finalK directly.
const retrievalRecallTopK = guidedRetrievalOn ? finalK * 6 : finalK;
// Step 19: hybridSparseWeightOverride and hybridOverFetchMultiplier
// are intentionally NOT passed here. The Step 19 conditional retriever
// knobs are scoped to the canonical `runFullCognitiveCase` callsite
// below (line ~622) which serves the v10 router's canonical-route
// path. This OM-with-retrieval branch (Step 16 family, RED at Tier A)
// is reached only via static --om-with-retrieval, where the multi-
// session knob overrides have no validated effect.
const fullCog = await runFullCognitiveCase(
c,
ctx,
retrievalRecallTopK,
'longmemeval-s',
retrievalPolicy,
this.opts.embedder,
this.opts.sessionSummarizer,
this.opts.sessionSummaryStore,
ctx.config.sessionRetrievalTopSessions,
ctx.config.sessionRetrievalChunksPerSession,
this.opts.hybridRetrievalEnabled ?? true,
this.opts.hydeEnabled,
this.opts.reader,
this.opts.factSupersessionEnabled,
this.opts.splitAmbiguousThreshold,
this.opts.observerReflectorEnabled,
this.opts.observerReflectorReplaceEnabled,
this.opts.factGraphIngestEnabled,
this.opts.graphActivationEnabled,
);
let evidenceForReader = fullCog.retrievedEvidence ?? [];
// Step 17: score sessions by OM-vs-question relevance, pick
// top-K candidates, filter retrieved evidence to those sessions.
if (guidedRetrievalOn) {
const guidedK = ctx.config.omGuidedRetrievalK ?? 5;
if (this.opts.embedder) {
// Step 17 v2: pass perSessionBatches directly (each has
// {sessionId, rawOutput}). v1 parsed finalLog but the
// observation log uses date-based headers that don't include
// session IDs, so the parser returned empty for every case.
const perSessionBlocks = extractPerSessionBlocks(ingest.perSessionBatches);
if (perSessionBlocks.size > 0) {
const sessionScores = await scoreSessionsByQueryRelevance({
question: c.question,
perSessionBlocks,
embedder: this.opts.embedder,
});
const candidateSessionIds = pickCandidateSessions(sessionScores, guidedK);
const beforeFilter = evidenceForReader.length;
// Keep traces with NO sessionId (untagged corpus content);
// only EXCLUDE traces whose sessionId is known and not in
// the candidate set. This avoids dropping useful retrieved
// chunks that happen to lack session-tag metadata.
const filtered = evidenceForReader.filter((ev) =>
ev.sessionId ? candidateSessionIds.has(ev.sessionId) : true,
);
// Defensive fallback: if filter would return zero, fall
// back to unfiltered (top-K) to avoid catastrophic recall
// loss from session-scoping going wrong.
evidenceForReader = filtered.length > 0 ? filtered : evidenceForReader;
runMetadata.omGuidedCandidateSessionCount = candidateSessionIds.size;
runMetadata.omGuidedEvidenceFilteredFrom = beforeFilter;
runMetadata.omGuidedEvidenceFilteredTo = filtered.length;
runMetadata.omGuidedSessionScores = sessionScores
.slice(0, Math.min(guidedK, sessionScores.length))
.map((s) => ({ sessionId: s.sessionId, score: s.score }));
} else {
// No per-session blocks parseable; skip filter.
runMetadata.omGuidedCandidateSessionCount = 0;
runMetadata.omGuidedEvidenceFilteredFrom = evidenceForReader.length;
runMetadata.omGuidedEvidenceFilteredTo = evidenceForReader.length;
}
} else {
// No embedder configured; skip filter, behave like Step 16.
runMetadata.omGuidedCandidateSessionCount = 0;
runMetadata.omGuidedEvidenceFilteredFrom = evidenceForReader.length;
runMetadata.omGuidedEvidenceFilteredTo = evidenceForReader.length;
}
// Take final top-K of the filtered (or unfiltered fallback) set.
evidenceForReader = evidenceForReader.slice(0, finalK);
}
retrievedPassages = evidenceForReader.map((ev, idx) => ({
id: ev.id ?? `P${idx}`,
content: ev.content ?? '',
}));
runMetadata.omRetrievedPassagesCount = retrievedPassages?.length ?? 0;
runMetadata.replayStats = fullCog.replayStats;
runMetadata.recalledTraces = fullCog.recallCount;
runMetadata.omGuidedRetrieval = guidedRetrievalOn;
}
// Effective scaffold: policy router → always true on OM-route picks
// (both Tier 2a and Tier 2b ship with the scaffold); legacy v10 router
// → use routerDecision.useScaffold; otherwise → static CLI flag.
const effectiveScaffold = policyRouterOn
? true
: dynamicRouterOn
? routerDecision!.useScaffold
: Boolean(ctx.config.omReaderScaffold);
// Router category passthrough for conditional verbatim (Step 18 v2
// rule fires only on KU/SSU when passed):
// - Policy router tier_2b_v11 → pass predictedCategory (verbatim fires
// if it's KU/SSU; otherwise noop).
// - Policy router tier_2a_v10 → pass undefined (no verbatim — Tier 2a
// is defined as v10 router WITHOUT conditional verbatim).
// - Legacy v10 router → pass existing routerCategory (unchanged).
// - Neither router on → routerCategory is null → pass undefined.
const effectiveRouterCategory: QuestionCategory | undefined = policyRouterOn
? policyRouterDecision!.chosenBackend === 'tier_2b_v11'
? policyRouterDecision!.predictedCategory
: undefined
: routerCategory ?? undefined;
system = buildOmReaderSystemPrompt(ingest.finalLog, {
includeScaffold: effectiveScaffold,
retrievedPassages,
routerCategory: effectiveRouterCategory,
});
runMetadata.omBatchTokenTarget = ctx.config.omBatchTokenTarget ?? 24_000;
runMetadata.omMode = ctx.config.omMode ?? 'dual-path';
runMetadata.omReaderScaffold = effectiveScaffold;
runMetadata.omObserverModel = observerModel;
runMetadata.omWithRetrieval = effectiveRetrieval;
runMetadata.omSynthesisModel = ingest.synthesisModel;
runMetadata.omSynthesisFired = ingest.synthesisOutput !== null;
runMetadata.omObservationBatches = ingest.observationBatches.length;
runMetadata.omPerSessionBatches = ingest.perSessionBatches.length;
runMetadata.omBatchedBatches = ingest.batchedBatches.length;
runMetadata.omReflectionsFired = ingest.reflections.length;
runMetadata.omFinalLogChars = ingest.finalLog.length;
// Step 18: capture full text for the token-retention metric.
// Default behavior captures the full log so the per-stage retention
// rates are computable; opt out via --no-capture-retention-inputs
// when running benchmarks that don't consume the metric (saves
// ~10-20MB per cached run JSON at N=500).
if (ctx.config.captureRetentionInputs !== false) {
runMetadata.omFinalLog = ingest.finalLog;
}
runMetadata.omObserverTokensIn = ingest.observerTokensIn;
runMetadata.omObserverTokensOut = ingest.observerTokensOut;
runMetadata.omReflectorTokensIn = ingest.reflectorTokensIn;
runMetadata.omReflectorTokensOut = ingest.reflectorTokensOut;
} else if (mode === 'none') {
system = buildNoMemorySystemPrompt(c, { noAbstention: ctx.config.noAbstention });
} else if (mode === 'base-memory') {
// Resolution priority for K:
// 1. ctx.config.readerTopK (from --reader-top-k CLI flag)
// 2. this.opts.recallTopK (from adapter construction)
// 3. 10 (hardcoded fallback)
// `??` propagates only on null/undefined, so an explicit 0 from
// ctx.config would stick — but parsePositiveInteger at the CLI
// layer rejects 0, so this branch can't actually produce K=0.
const effectiveRecallTopK =
ctx.config.readerTopK ?? this.opts.recallTopK ?? 10;
const { prompt, replayStats, recallCount } = await runBaseMemoryCase(
c,
ctx,
effectiveRecallTopK,
retrievalPolicy,
);
system = prompt;
runMetadata.replayStats = replayStats;
runMetadata.recalledTraces = recallCount;
runMetadata.retrievalPolicy = retrievalPolicy;
} else {
// full-cognitive — real CognitiveMemoryManager, optional observer/
// reflector pipeline depending on replayMode.
//
// Resolution priority for K mirrors the base-memory branch:
// 1. ctx.config.readerTopK (from --reader-top-k CLI flag)
// 2. this.opts.recallTopK (from adapter construction)
// 3. 10 (hardcoded fallback)
const baseRecallTopK =
ctx.config.readerTopK ?? this.opts.recallTopK ?? 10;
// Step 19A/B/C: per-case retriever overrides for MS questions.
// GROUND TRUTH category (c.type) is used, not router output —
// because v10's router sends MS to the OM path (where there is
// no retriever to tune), so the overrides would never fire if
// gated on routerCategory. Canonical-only mode (no router) is
// the intended target: MS cases flow through HybridRetriever
// and the override applies. Under v10 with --observational-memory,
// MS cases hit the OM branch and skip this code path entirely
// (this whole `else` block is the canonical-route branch).
const isMsCase = c.type === 'multi-session';
const effectiveRecallTopK =
isMsCase && typeof ctx.config.omRetrieverMsKOverride === 'number'
? ctx.config.omRetrieverMsKOverride
: baseRecallTopK;
if (isMsCase && typeof ctx.config.omRetrieverMsKOverride === 'number') {
runMetadata.omRetrieverMsKApplied = ctx.config.omRetrieverMsKOverride;
}
// Step 19B: per-case BM25 weight override for MS questions.
const hybridSparseWeightForCase =
isMsCase && typeof ctx.config.omRetrieverMsBm25Weight === 'number'
? ctx.config.omRetrieverMsBm25Weight
: undefined;
if (hybridSparseWeightForCase !== undefined) {
runMetadata.omRetrieverMsBm25Applied = hybridSparseWeightForCase;
}
// Step 19C: per-case over-fetch multiplier for MS questions.
const hybridOverFetchForCase =
isMsCase && typeof ctx.config.omRetrieverMsOverFetchMultiplier === 'number'
? ctx.config.omRetrieverMsOverFetchMultiplier
: undefined;
if (hybridOverFetchForCase !== undefined) {
runMetadata.omRetrieverMsOverFetchApplied = hybridOverFetchForCase;
}
const out = await runFullCognitiveCase(
c,
ctx,
effectiveRecallTopK,
'longmemeval-s',
retrievalPolicy,
this.opts.embedder,
this.opts.sessionSummarizer,
this.opts.sessionSummaryStore,
ctx.config.sessionRetrievalTopSessions,
ctx.config.sessionRetrievalChunksPerSession,
this.opts.hybridRetrievalEnabled,
this.opts.hydeEnabled,
this.opts.reader,
this.opts.factSupersessionEnabled,
this.opts.splitAmbiguousThreshold,
this.opts.observerReflectorEnabled,
this.opts.observerReflectorReplaceEnabled,
this.opts.factGraphIngestEnabled,
this.opts.graphActivationEnabled,
hybridSparseWeightForCase,
hybridOverFetchForCase,
retrievalConfigOverride,
);
system = out.prompt;
// Step 18 v2 + Step 19 stacked test (NULL at Tier A): the
// canonical-verbatim wiring added briefly here did not move
// accuracy on canonical mode. Reverted to keep Phase B v2
// confirmation exact to the variant that hit 78.4% Phase A.
// (Step 18 v2's verbatim rule fires only via the OM reader
// path, gated by routerCategory inside buildOmReaderSystemPrompt.)
runMetadata.replayStats = out.replayStats;
runMetadata.recalledTraces = out.recallCount;
runMetadata.workingMemorySlots = out.workingMemorySlots;
runMetadata.observationsEmitted = out.observationsEmitted;
runMetadata.retrievedEvidence = out.retrievedEvidence;
runMetadata.retrievalPolicy = retrievalPolicy;
// v2 metric inputs — consumed by scoreCase via attachPerCaseMetrics.
runMetadata.encodeMsSamples = out.encodeMsSamples;
runMetadata.peakWorkingMemorySlots = out.peakWorkingMemorySlots;
runMetadata.retrieveDiagnostics = out.retrieveDiagnostics;
runMetadata.traceIdToSessionId = out.traceIdToSessionId;
runMetadata.traceCount = out.traceCount;
runMetadata.brainBytes = out.brainBytes;
// Stage C / Tier 4a: session-level NDCG retrieval post-process
// (Emergence AI "Simple" recipe). After HybridRetriever returns top-K
// traces, group by sessionId, compute NDCG per session from trace
// ranks, pick top-K sessions, expand to ALL turns from haystack.
// Reader sees full session conversations for the highest-scored
// sessions rather than scattered top-K chunks.
if (
ctx.config.sessionLevelNdcg &&
out.retrievedEvidence &&
out.retrievedEvidence.length > 0
) {
const topK = ctx.config.sessionLevelNdcgTopK ?? 3;
const sessionScores = new Map<string, number>();
out.retrievedEvidence.forEach((ev, rank) => {
const sid = ev.sessionId;
if (!sid) return;
const ndcgWeight = 1 / Math.log2(rank + 2);
sessionScores.set(sid, (sessionScores.get(sid) ?? 0) + ndcgWeight);
});
const topSessionIds = new Set(
[...sessionScores.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, topK)
.map(([sid]) => sid),
);
// Expand to full session turns from the case haystack
const expandedEvidence: Array<{
id: string;
content: string;
sessionId: string;
retrievalScore: number;
}> = [];
for (const session of c.haystack) {
if (!topSessionIds.has(session.sessionId)) continue;
const turns = session.turns
.filter((t) => t.content.trim().length > 0)
.map((t) => `${t.role}: ${t.content}`)
.join('\n');
const dateBracket = session.date ? `[${session.date}]` : '';
expandedEvidence.push({
id: session.sessionId,
content: `${dateBracket} ${turns}`.trim(),
sessionId: session.sessionId,
retrievalScore: sessionScores.get(session.sessionId) ?? 0,
});
}
// Sort sessions by NDCG score descending
expandedEvidence.sort(
(a, b) => (b.retrievalScore ?? 0) - (a.retrievalScore ?? 0),
);
if (expandedEvidence.length > 0) {
runMetadata.retrievedEvidence = expandedEvidence;
runMetadata.sessionLevelNdcgActive = true;
runMetadata.sessionLevelNdcgTopSessionIds = [...topSessionIds];
runMetadata.sessionLevelNdcgExpandedCount = expandedEvidence.length;
// Rebuild the reader system prompt with expanded evidence
system = buildFullCognitivePrompt(c, expandedEvidence, {
noAbstention: ctx.config.noAbstention,
});
}
}
}
let actualOutput: string;
let tokensIn: number;
let tokensOut: number;
let usd: number;
// Reader-router dispatch (2026-04-28). When `--reader-router <preset>` is
// active, pick the answer reader per case from `this.opts.readerByTier`
// based on the predicted question category. Reuses the classifier output
// already produced by policyRouter / omDynamicRouter / retrievalConfigRouter
// when any of them ran (zero extra LLM calls). When NO other router fired
// the classifier (canonical-only run), fall back to a standalone gpt-5-mini
// few-shot classifier call here — the reader-router still needs the
// predicted category to dispatch. Falls back to `this.opts.reader` when (a)
// the router is off, (b) the dispatched tier isn't in the auxiliary pool,
// or (c) the classifier errored.
let dispatchedReader: IReader = this.opts.reader;
if (ctx.config.readerRouter && this.opts.readerByTier) {
let dispatchCategory: QuestionCategory | null =
policyRouterDecision?.predictedCategory ??
routerCategory ??
// retrievalConfigClassifierCategory is MemoryQueryCategory which is
// structurally identical to QuestionCategory (same six string-literal
// members); cast through unknown so the router types align.
((retrievalConfigClassifierCategory ?? null) as unknown as
| QuestionCategory
| null);
// Standalone classifier fallback: when no other router ran, fire a
// fresh classify call so the reader router can dispatch. Cost is a
// single ~$0.000138 gpt-5-mini call per case (default classifier).
if (!dispatchCategory) {
const classifierModelName = (ctx.config.omClassifierModel ??
'gpt-5-mini') as ReaderModel;
const classifierReader = createReader(classifierModelName);
try {
const result = await classifyQuestion({
reader: classifierReader,
question: c.question,
useFewshotPrompt: Boolean(ctx.config.omClassifierFewshot),
});
dispatchCategory = result.category;
if (result.tokensIn > 0 || result.tokensOut > 0) {
ctx.costTracker.record({
category: 'reader',
model: result.model,
tokensIn: result.tokensIn,
tokensOut: result.tokensOut,