-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
1704 lines (1620 loc) · 72.3 KB
/
Copy pathcli.ts
File metadata and controls
1704 lines (1620 loc) · 72.3 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
#!/usr/bin/env node
/**
* @file cli.ts
* @description Command-line interface for `@framers/agentos-bench`.
*
* Subcommands:
* - `run <benchmark-id> [--reader <model>] [--memory <mode>] [--replay <mode>] [--sample N]`
* - `list` — enumerate built-in benchmarks
* - `setup` — prepare dataset caches (placeholder — downloads via HF hub in v2)
* - `leaderboard` — regenerate results/LEADERBOARD.md (stub until leaderboard generator ships)
*
* Environment variables:
* - `AGENTOS_BENCH_DATA_DIR` (default: ./data)
* - `AGENTOS_BENCH_RESULTS_DIR` (default: ./results)
* - `AGENTOS_BENCH_TIER` micro | s | m | full (informational for now)
* - `OPENAI_API_KEY` / `ANTHROPIC_API_KEY`
*
* @module agentos-bench/cli
*/
import path from 'node:path';
import { Command } from 'commander';
import {
Beam,
BenchmarkRunner,
ConsolidationSignalPreservation,
DecayFidelity,
HexacoEncodingBias,
Locomo,
LongMemEvalJudge,
LongMemEvalM,
LongMemEvalOracle,
LongMemEvalS,
MockReader,
ScalingProfile,
SignalAblation,
SpreadingActivationPrecision,
WorkingMemoryCapacity,
CachedEmbedder,
createOpenAIEmbedderFromEnv,
createReader,
estimateRunCost,
type IBenchmark,
type IReader,
type MemoryMode,
type ReaderModel,
type ReplayMode,
type RunConfig,
} from './index.js';
import type { IEmbeddingManager } from '@framers/agentos/core/embeddings/IEmbeddingManager';
import type { MemoryRetrievalProfile } from '@framers/agentos';
import { SessionSummarizer } from '@framers/agentos/memory';
interface BenchEntry {
id: string;
family: 'external' | 'micro';
description: string;
/**
* Build the benchmark instance. `reader` is an already-constructed
* {@link IReader} — real (OpenAI / Anthropic HTTP client) in
* production runs, {@link MockReader} under `--dry-run`.
* `embedder`, when provided, replaces the CharHashEmbedder stub in
* the full-cognitive path so retrieval exercises real semantic
* similarity.
*/
build: (ctx: {
reader: IReader;
/**
* Optional auxiliary reader pool for the per-category reader-tier
* router (`--reader-router`). When set, the bench dispatches the
* answer reader per case based on the gpt-5-mini classifier's
* predicted category. Falls back to {@link reader} when the
* dispatched tier isn't in the pool.
*/
readerByTier?: Partial<Record<'gpt-4o' | 'gpt-5-mini', IReader>>;
embedder?: IEmbeddingManager;
/**
* Optional session-level contextual-retrieval summarizer. When
* `--context-summary` is set on the CLI, the CLI constructs a
* {@link SessionSummarizer} (from `@framers/agentos/memory`) and
* passes it here so the adapter can thread it through its ingest
* path. Most adapters (micro-benchmarks, LongMemEval-none) ignore it.
*/
sessionSummarizer?: SessionSummarizer;
/**
* Step-2: optional session-level retrieval store. When
* `--session-retrieval` is set, the CLI constructs a
* {@link SessionSummaryStore} and passes it here so the adapter
* indexes summaries during replay AND constructs a
* {@link SessionRetriever} per-case for the retrieval step.
*/
sessionSummaryStore?: import('@framers/agentos/memory').SessionSummaryStore;
/** Step-2: Stage-1 session count (default 5 on the adapter side). */
sessionRetrievalTopSessions?: number;
/** Step-2: Stage-2 chunks-per-session (default 3 on the adapter side). */
sessionRetrievalChunksPerSession?: number;
/**
* Step-3: when true, the adapter constructs a per-case
* `HybridRetriever` and uses it in place of `manager.retrieve`.
* Mutually exclusive with `sessionSummaryStore`.
*/
hybridRetrievalEnabled?: boolean;
/**
* Step-4: when true, the adapter constructs a cheap LLM invoker
* (reuses the main reader) and wires HyDE through the manager
* and, if applicable, through the `HybridRetriever`.
*/
hydeEnabled?: boolean;
/**
* Step-5: when true, the adapter constructs a `FactSupersession`
* (using the main reader as the LLM invoker) and runs it on
* retrieved traces before feeding them to the reader.
*/
factSupersessionEnabled?: boolean;
/**
* Step-6: threshold for split-on-ambiguous rerank refinement. When
* > 0, the adapter passes this to `HybridRetriever`'s
* `splitAmbiguousThreshold` option. Typical: 0.3. Requires
* `hybridRetrievalEnabled: true`.
*/
splitAmbiguousThreshold?: number;
/**
* Step-7 (Tier 2): when true, the adapter constructs a cost-tracked
* gpt-5-mini invoker and wires Observer/Reflector through
* `createCognitiveManager`, then routes each conversation turn
* through `manager.observe()` in addition to `manager.encode()`.
*/
observerReflectorEnabled?: boolean;
/**
* Step-8: REPLACEMENT semantics for Observer/Reflector (Tier 2 fix).
* Requires `observerReflectorEnabled: true`. When true, adapter skips
* raw chunk encoding, calls `manager.flushReflection()` at session
* boundaries, and indexes reflection-trace IDs into BM25.
*/
observerReflectorReplaceEnabled?: boolean;
/**
* Step-9 (Tier 3): when true, the adapter constructs a cost-tracked
* gpt-5-mini invoker and wires a Mem0-style fact-graph through
* `createCognitiveManager`. Per-session fact extraction runs at
* ingest; synthetic fact-graph traces (retrievalScore: 1.0,
* sourceType: 'fact_graph') are prepended to the HybridRetriever
* merged pool BEFORE rerank. Mutually exclusive with
* `observerReflectorEnabled` (enforced at RunConfig level).
*/
factGraphIngestEnabled?: boolean;
/**
* Step-13: when true, the adapter extracts entities via regex at
* every `manager.encode` call (populating `trace.entities`) and
* passes `enableGraphActivation: true` to `createCognitiveManager`
* so the internal `MemoryStore` upserts entity nodes + co-occurrence
* edges and computes spreading activation at retrieve.
*/
graphActivationEnabled?: boolean;
/**
* Step-15: when true, the adapter bypasses retrieval entirely and
* runs Mastra-style Observational Memory ingest (Observer LLM per
* session + optional Reflector pass) before each case query. The
* reader sees the consolidated observation log + question in a
* single call.
*/
observationalMemoryEnabled?: boolean;
}) => IBenchmark;
}
const BENCHMARKS: BenchEntry[] = [
{
id: 'decay-fidelity',
family: 'micro',
description: 'Ebbinghaus decay curve conformance at 1d/5d/10d/30d/60d probes',
build: () => new DecayFidelity(),
},
{
id: 'hexaco-encoding-bias',
family: 'micro',
description: 'HEXACO traits bias encoding in the documented direction',
build: () => new HexacoEncodingBias(),
},
{
id: 'working-memory-capacity',
family: 'micro',
description: 'Baddeley 5-9 slot capacity + LRU-by-activation eviction',
build: () => new WorkingMemoryCapacity(),
},
{
id: 'spreading-activation-precision',
family: 'micro',
description: 'Anderson spreading activation contains ≥80% of seed cluster',
build: () => new SpreadingActivationPrecision(),
},
{
id: 'consolidation-signal-preservation',
family: 'micro',
description: 'Flashbulb-immunity invariant across reconsolidation, RIF, emotion regulation',
build: () => new ConsolidationSignalPreservation(),
},
{
id: 'scaling-profile',
family: 'micro',
description: 'Retrieval scoring P50/P95 at 1k/10k (100k with AGENTOS_BENCH_SCALING_FULL)',
build: () => new ScalingProfile(),
},
{
id: 'signal-ablation',
family: 'micro',
description: 'Prove each of the 6 retrieval signals is load-bearing (NDCG delta per ablation)',
build: () => new SignalAblation(),
},
{
id: 'longmemeval-s',
family: 'external',
description: 'LongMemEval-S (500 cases, ~115k-token haystacks)',
build: ({
reader,
readerByTier,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}) =>
new LongMemEvalS({
reader,
readerByTier,
variant: 's',
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}),
},
{
id: 'longmemeval-m',
family: 'external',
description: 'LongMemEval-M (~500 sessions per haystack) — medium-difficulty variant',
build: ({
reader,
readerByTier,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}) =>
new LongMemEvalM({
reader,
readerByTier,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}),
},
{
id: 'longmemeval-oracle',
family: 'external',
description: 'LongMemEval-Oracle (evidence-only) — isolates reader quality from retrieval',
build: ({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}) =>
new LongMemEvalOracle({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}),
},
{
id: 'locomo',
family: 'external',
description: 'LOCOMO (Maharana et al. 2024, 10 convos × ~300 turns, QA task only in v1)',
build: ({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}) =>
new Locomo({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
observationalMemoryEnabled,
}),
},
{
id: 'beam-100k',
family: 'external',
description:
'BEAM 100K tier (Beyond a Million Tokens, ICLR 2026): 400 queries × 10 categories over 170 documents per user-haystack, 2.6M total tokens. Source: github.com/vectorize-io/agent-memory-benchmark.',
build: ({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}) =>
new Beam({
reader,
tier: '100k',
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}),
},
{
id: 'beam-500k',
family: 'external',
description: 'BEAM 500K tier (download upstream first; 100K-tier-equivalent adapter wired)',
build: ({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}) =>
new Beam({
reader,
tier: '500k',
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}),
},
{
id: 'beam-1m',
family: 'external',
description:
'BEAM 1M tier (download upstream first; queued for remote-machine execution due to memory budget)',
build: ({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}) =>
new Beam({
reader,
tier: '1m',
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}),
},
{
id: 'beam-10m',
family: 'external',
description:
'BEAM 10M tier — frontier, Hindsight SOTA (download upstream first; remote-machine only)',
build: ({
reader,
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}) =>
new Beam({
reader,
tier: '10m',
embedder,
sessionSummarizer,
sessionSummaryStore,
sessionRetrievalTopSessions,
sessionRetrievalChunksPerSession,
hybridRetrievalEnabled,
hydeEnabled,
factSupersessionEnabled,
splitAmbiguousThreshold,
observerReflectorEnabled,
observerReflectorReplaceEnabled,
factGraphIngestEnabled,
graphActivationEnabled,
}),
},
];
function resolveDataDir(override?: string): string {
return path.resolve(
override ?? process.env.AGENTOS_BENCH_DATA_DIR ?? path.join(process.cwd(), 'data')
);
}
function resolveResultsDir(override?: string): string {
return path.resolve(
override ?? process.env.AGENTOS_BENCH_RESULTS_DIR ?? path.join(process.cwd(), 'results')
);
}
function parseInteger(v: string): number {
const n = Number.parseInt(v, 10);
if (!Number.isFinite(n) || n < 0) throw new Error(`Expected non-negative integer, got ${v}`);
return n;
}
/**
* Like {@link parseInteger} but rejects 0. Used for CLI flags that
* cascade into `slice(0, N)` downstream where N=0 would degrade into
* empty-pool behavior (e.g., `--reader-top-k 0` would zero out the
* reader's retrieved-chunk window and fall through to a 1-chunk
* fallback, producing bogus answers rather than crashing).
*/
function parsePositiveInteger(v: string): number {
const n = Number.parseInt(v, 10);
if (!Number.isFinite(n) || n < 1) {
throw new Error(`Expected positive integer (>= 1), got ${v}`);
}
return n;
}
function parseFloatArg(v: string): number {
const n = Number.parseFloat(v);
if (!Number.isFinite(n) || n < 0) throw new Error(`Expected non-negative number, got ${v}`);
return n;
}
/**
* Parse a closed-interval [0, 1] weight. Used by RRF blend weights where
* `denseWeight = 1 - sparseWeight` must stay in [0, 1] to avoid producing
* negative ranks at fusion time. Both endpoints are accepted (0 = pure
* dense, 1 = pure sparse) but anything outside the unit interval errors.
*/
function parseUnitIntervalWeight(v: string): number {
const n = Number.parseFloat(v);
if (!Number.isFinite(n) || n < 0 || n > 1) {
throw new Error(`Expected weight in [0, 1], got ${v}`);
}
return n;
}
function parseRetrievalProfile(v: string): MemoryRetrievalProfile {
if (v === 'fast' || v === 'balanced' || v === 'max-recall') return v;
throw new Error(`Expected retrieval profile fast | balanced | max-recall, got ${v}`);
}
function parseAdaptiveMode(v: string): boolean {
if (v === 'on') return true;
if (v === 'off') return false;
throw new Error(`Expected adaptive mode on | off, got ${v}`);
}
const VALID_ABLATE_SIGNALS = [
'strength',
'similarity',
'recency',
'emotionalCongruence',
'graphActivation',
'importance',
] as const;
function parseAblateSignal(v: string): (typeof VALID_ABLATE_SIGNALS)[number] {
if ((VALID_ABLATE_SIGNALS as readonly string[]).includes(v)) {
return v as (typeof VALID_ABLATE_SIGNALS)[number];
}
throw new Error(`Expected one of ${VALID_ABLATE_SIGNALS.join(' | ')}, got ${v}`);
}
const VALID_ABLATE_MECHANISMS = [
'reconsolidation',
'retrievalInducedForgetting',
'involuntaryRecall',
'metacognitiveFOK',
'temporalGist',
'schemaEncoding',
'sourceConfidenceDecay',
'emotionRegulation',
] as const;
function parseAblateMechanism(v: string): (typeof VALID_ABLATE_MECHANISMS)[number] {
if ((VALID_ABLATE_MECHANISMS as readonly string[]).includes(v)) {
return v as (typeof VALID_ABLATE_MECHANISMS)[number];
}
throw new Error(`Expected one of ${VALID_ABLATE_MECHANISMS.join(' | ')}, got ${v}`);
}
/**
* Default case count for the cost preflight when `--sample` is not set.
* Hardcoded so we don't have to load the dataset just to estimate cost.
* Matches the published dataset sizes.
*/
function defaultCaseCountForBenchmark(id: string): number {
switch (id) {
case 'longmemeval-s':
case 'longmemeval-m':
case 'longmemeval-oracle':
return 500;
case 'locomo':
// 10 conversations × ~200 QA pairs each in the upstream dump.
return 2_000;
case 'beam-100k':
return 400;
case 'beam-500k':
case 'beam-1m':
case 'beam-10m':
return 400;
default:
return 100;
}
}
/**
* Pretty-print a completed run's headline numbers plus a per-type
* accuracy breakdown when the benchmark produced one. Keeping this in
* the CLI (not the BenchmarkRunner) so the underlying run result stays
* a plain data object.
*/
function printRunSummary(result: import('./core/IBenchmark.js').BenchResult): void {
const acc = (result.accuracy * 100).toFixed(1);
const cpc = Number.isFinite(result.costPerCorrect)
? `$${result.costPerCorrect.toFixed(4)}`
: '$∞';
console.log(
`Done. accuracy=${acc}% passed=${result.passedCases}/${result.totalCases} ` +
`avg=${result.avgLatencyMs.toFixed(0)}ms p50=${result.p50LatencyMs.toFixed(0)}ms ` +
`p95=${result.p95LatencyMs.toFixed(0)}ms totalUsd=$${result.totalUsd.toFixed(4)} ` +
`costPerCorrect=${cpc}`
);
const typeEntries = Object.entries(result.byType);
if (typeEntries.length > 1) {
console.log('By type:');
const pad = Math.max(...typeEntries.map(([t]) => t.length));
for (const [type, stats] of typeEntries.sort((a, b) => b[1].accuracy - a[1].accuracy)) {
console.log(
` ${type.padEnd(pad)} n=${String(stats.n).padStart(3)} acc=${(stats.accuracy * 100)
.toFixed(1)
.padStart(5)}% avgScore=${stats.avgScore.toFixed(3)}`
);
}
}
}
export function buildCli(): Command {
const program = new Command();
program
.name('agentos-bench')
.description(
'Benchmark AgentOS memory against LongMemEval, LOCOMO, BEAM, and micro-benchmarks.'
)
.version('0.1.0');
program
.command('list')
.description('List built-in benchmarks with their families.')
.action(() => {
const pad = Math.max(...BENCHMARKS.map((b) => b.id.length));
for (const b of BENCHMARKS) {
console.log(`${b.id.padEnd(pad)} [${b.family}] ${b.description}`);
}
});
program
.command('run <benchmarkId>')
.description('Run a benchmark and persist results.')
.option(
'-r, --reader <model>',
'Reader model (e.g. claude-sonnet-4-6, gpt-4o)',
'claude-sonnet-4-6'
)
.option('-m, --memory <mode>', 'Memory mode: full-cognitive | base-memory | none', 'none')
.option('-p, --replay <mode>', 'Replay mode: observe | ingest', 'ingest')
.option('-n, --sample <n>', 'Run only the first N cases', parseInteger)
.option('-c, --concurrency <n>', 'Parallel case execution', parseInteger, 3)
.option(
'--profile <profile>',
'Retrieval profile: fast | balanced | max-recall',
parseRetrievalProfile,
'balanced'
)
.option('--adaptive <mode>', 'Adaptive retrieval: on | off', parseAdaptiveMode, true)
.option('--max-usd <amount>', 'Abort if projected USD exceeds this cap', parseFloatArg)
.option('--data-dir <path>', 'Dataset cache directory')
.option('--results-dir <path>', 'Results directory')
.option('--judge-model <model>', 'Judge LLM (external benchmarks only)', 'gpt-4o')
.option(
'--embedder-model <model>',
'Embedder model for the full-cognitive path (e.g. openai:text-embedding-3-small). Falls back to the CharHash stub when omitted.'
)
.option(
'--reader-router <preset>',
"Per-category reader-tier router: dispatch the answer reader per case based on the gpt-5-mini classifier's predicted category. Presets: min-cost-best-cat-2026-04-28 (gpt-4o for TR/SSU, gpt-5-mini for SSP/SSA/KU/MS; oracle 87.0% on S Phase B); min-cost-best-cat-gpt5-tr-2026-04-29 (replaces gpt-4o with gpt-5 for TR/SSU; Phase A small-sample signal of +4 pp on TR). When unset the bench uses the single --reader for every case.",
(value: string) => {
const allowed = ['min-cost-best-cat-2026-04-28', 'min-cost-best-cat-gpt5-tr-2026-04-29'];
if (!allowed.includes(value)) {
throw new Error(`--reader-router must be one of ${allowed.join(' | ')}, got '${value}'`);
}
return value;
}
)
.option(
'--retrieval-k <n>',
'K for retrieval-quality metrics (Recall/Precision/NDCG@K)',
parseInteger,
10
)
.option('--stratified', 'Enable stratified sampling + weighted accuracy aggregation')
.option('--sample-per-type <n>', 'Cases per case-type (implies --stratified)', parseInteger)
.option('--track-footprint', 'Capture brain bytes + trace counts (default: on)', true)
.option('--no-footprint', 'Disable footprint tracking for maximum-throughput runs')
.option(
'--ablate-signal <signal>',
'Zero one retrieval signal: strength | similarity | recency | emotionalCongruence | graphActivation | importance',
parseAblateSignal
)
.option(
'--ablate-mechanism <mechanism>',
'Disable one cognitive mechanism: reconsolidation | retrievalInducedForgetting | involuntaryRecall | metacognitiveFOK | temporalGist | schemaEncoding | sourceConfidenceDecay | emotionRegulation',
parseAblateMechanism
)
.option(
'--rerank <provider>',
'Enable neural reranker. Only "cohere" is wired today. Needs COHERE_API_KEY (or --rerank-api-key).'
)
.option(
'--rerank-model <id>',
'Cohere rerank model id (e.g. rerank-v3.5, rerank-v4.0-pro, rerank-v4.0-fast). Default: rerank-v3.5.'
)
.option('--rerank-api-key <key>', 'Cohere API key override. Falls back to COHERE_API_KEY env.')
.option(
'--rerank-candidate-multiplier <n>',
'Retrieve topK × N candidates before the reranker re-sorts; reader still sees topK after rerank. Default: 3 when rerank is on.',
parseInteger
)
.option(
'--reader-top-k <n>',
'How many retrieved chunks the reader sees after rerank and score-floor filtering (must be >= 1; adapter default is 10). Candidate pool for rerank scales as K × rerank.candidateMultiplier, so K=15 at the default 3× multiplier re-ranks a 45-chunk pool. Use to investigate multi-session coverage trade-offs.',
parsePositiveInteger
)
.option(
'--context-summary <model>',
'Enable session-level contextual retrieval (Anthropic Sep 2024). An LLM generates a dense per-session summary that is prepended to every chunk before embedding. Value is the model id used to generate summaries (e.g. "gpt-5-mini", "claude-haiku-4-5"). Cached on disk under <dataDir>/.session-summary-cache/.'
)
.option(
'--judge-adversarial',
'Enable judge-adversarial probe: synthesize topically-adjacent wrong answers, score with the same judge, report judge false-positive rate (noise floor). Adds one cheap synth call + one judge call per probed case. Cost bounded by --judge-adversarial-max-probes.'
)
.option(
'--judge-adversarial-max-probes <n>',
'Max cases probed when --judge-adversarial is set. Default: 50.',
parsePositiveInteger,
50
)
.option(
'--judge-adversarial-synth-model <model>',
'Cheap LLM for synthesizing adversarial distractors. Default: gpt-5-mini.',
'gpt-5-mini'
)
.option(
'--bootstrap-resamples <n>',
'Bootstrap resamples for accuracy confidence intervals. Default: 10000.',
parsePositiveInteger,
10_000
)
.option(
'--session-retrieval',
'Enable Step-2 session-level hierarchical retrieval (xMemory / TACITREE pattern). Stage 1 selects top-K sessions by summary similarity; Stage 2 takes top-M chunks per session. Requires --context-summary to be set so session summaries exist.'
)
.option(
'--session-retrieval-top-sessions <n>',
'K for Stage 1: number of sessions selected by summary similarity. Default: 5.',
parsePositiveInteger,
5
)
.option(
'--session-retrieval-chunks-per-session <n>',
'M for Stage 2: chunks kept per session after post-filter. Default: 3.',
parsePositiveInteger,
3
)
.option(
'--hybrid-retrieval',
'Enable Step-3 hybrid BM25 + dense RRF retrieval. Mutually exclusive with --session-retrieval in Step 3 MVP. Preserves cognitive scoring on the dense side; reranker (if --rerank set) runs over the merged pool.'
)
.option(
'--hyde',
'Enable Step-4 HyDE (Hypothetical Document Embedding) retrieval. Cheap LLM generates a hypothetical answer used as the search query; improves recall on vague/abstract queries. Orthogonal to --session-retrieval and --hybrid-retrieval. When combined with --hybrid-retrieval, the hypothesis is used for BOTH dense and sparse; rerank keeps the ORIGINAL user query.'
)
.option(
'--fact-supersession',
'Enable Step-5 FactSupersession post-retrieval filter. One gpt-5-mini LLM call per query identifies superseded traces (contradictory claims about the same subject) and drops them before the reader sees them. Targets the knowledge-update ceiling. Orthogonal to other retrieval flags.'
)
.option(
'--split-ambiguous <n>',
'Enable Step-6 split-on-ambiguous rerank refinement. Bottom fraction (0-1) of traces by first-pass rerank score get split at sentence boundaries and rescored; replaced only if the better half outscores the original. Monotonic. Typical: 0.3. Requires --hybrid-retrieval.',
parseFloatArg
)
.option(
'--observer-reflector',
'Enable Step-7 Observer/Reflector pipeline (Tier 2 progressive enhancement). Adds personality-biased observation-note extraction at 30k-token intervals, compression at 50-note intervals, and reflector-driven trace consolidation + supersession. Matches Mastra "Observational Memory" pattern. Uses gpt-5-mini as the observer/reflector invoker by default.'
)
.option(
'--observer-reflector-replace',
'Enable Step-8 REPLACEMENT semantics for Observer/Reflector (Tier 2 fix). Skips raw chunk encoding during ingest, forces reflection at session boundaries via manager.flushReflection(), indexes reflection-derived trace IDs into hybrid BM25. Requires --observer-reflector. Addresses Step 7 RED (additive overlay dilutes retrieval).'
)
.option(
'--fact-graph-ingest',
'Enable Step-9 Mem0-style fact-graph ingest (Tier 3). Per-session gpt-5-mini extractor emits closed-schema (subject, predicate, object, timestamp) tuples; synthetic fact-graph traces with retrievalScore:1.0 are prepended to the HybridRetriever merged pool BEFORE rerank. Preserves literal object tokens where Steps 5/7/8 paraphrased them away. Mutually exclusive with --observer-reflector / --observer-reflector-replace.'
)
.option(
'--graph-activation',
'Enable Step-13 graph activation wire-up. Heuristic regex entity extraction (zero LLM) at ingest populates trace.entities and creates co-occurrence edges in SqlKnowledgeGraph. At retrieve, Anderson spreading activation seeded from query entities computes the sixth composite-score signal (weight 0.10 in RetrievalPriorityScorer, previously hardcoded to 0). Additive, deterministic, dodges the n=8 LLM-mediated-content RED pattern by construction.'
)
.option(
'--two-call-reader',
'Enable Step-14 Emergence-style two-call reader. First call extracts a JSON fact scratchpad from top-K retrieved passages with passage-id citations; second call answers from the scratchpad only (no raw passages in final context). Both calls use --reader. Targets reader-conversion headroom (~83% at single-call baseline) to close the gap toward competitor systems that publish 80%+. Default: off.'
)
.option(
'--observational-memory',
'Enable Step-15 Mastra-style Observational Memory. DISABLES the retrieval pipeline (no HybridRetriever, no rerank, no top-K). Observer LLM extracts dated priority-tagged observations over token-bounded batches of sessions (Step 15 v2 default: 24k-token batches); Reflector consolidates when the log exceeds 40k tokens. Reader sees the full observation log + question in a single call. Verbatim port of Mastra OM prompts (Apache-2.0). Observer model: gpt-5-mini (substituted for Mastra\u2019s gemini-2.5-flash because the bench ships with OpenAI keys only). Default: off.'
)
.option(
'--om-batch-tokens <n>',
'Step 15 v2: token target per Observer batch in OM ingest (default 24000). Sessions are grouped in haystack order until cumulative tokens exceed this target; a single session exceeding the target becomes its own batch (no mid-session split). Matches Mastra\u2019s messageTokens \u00D7 bufferActivation = 30000 \u00D7 0.8 = 24000 default. Only effective with --observational-memory. Lower values (e.g. 12000) produce more, smaller batches; higher values (e.g. 40000) produce fewer, larger batches up to the observer\u2019s input budget.',
parsePositiveInteger
)
.option(
'--om-mode <mode>',
'Step 15 observer ingest mode. Values: per-session (v1, one Observer call per session, preserves per-session fidelity), batched (v2, one call per 24k-token batch, encodes cross-session patterns but compresses per-session detail), dual-path (v3 default, both passes concatenated), hierarchical (v4b, per-session Observer + one synthesis call over the per-session log using --om-synthesis-model — compact synthesis block appended to the per-session log). Only effective with --observational-memory.',
(value: string) => {
if (
value !== 'per-session' &&
value !== 'batched' &&
value !== 'dual-path' &&
value !== 'hierarchical'
) {
throw new Error(
`--om-mode must be 'per-session' | 'batched' | 'dual-path' | 'hierarchical', got "${value}"`
);
}
return value;
}
)
.option(
'--om-synthesis-model <model>',
'Step 15 v4b: model identifier for the hierarchical-mode synthesis call over the per-session observation log. Typically a stronger reasoning model (e.g. gpt-4o) than the observer model. Only consulted when --om-mode is hierarchical. Default: same as the observer model (gpt-5-mini).'
)
.option(
'--om-observer-model <model>',
'Step 15 v5: model identifier for the Observer and Reflector LLM calls in OM ingest. Default gpt-5-mini. Provider-agnostic via prefix routing in createReader: gpt-* (OpenAI), claude-* (Anthropic), gemini-* (Google AI Studio). Setting --om-observer-model gemini-2.5-flash reproduces Mastra\u2019s published 94.9% LongMemEval-S stack (gpt-5-mini reader + gemini-2.5-flash observer). Only effective with --observational-memory.'
)
.option(
'--om-with-retrieval',
'Step 16: combine OM observation log with HybridRetriever top-K passages (BM25 + dense + RRF + Cohere rerank) in a single reader context. The reader sees both the dense cross-session synthesis (from OM) AND the per-chunk verbatim specifics (from retrieval), addressing multi-session gaps that neither layer solves alone. Runs both ingest pipelines. Only effective with --observational-memory.'
)
.option(
'--om-dynamic-router',
'Step 16c v2: classify each question via gpt-5-mini, then 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 (SSU/SSA/SSP/TR \u2192 canonical; KU/MS \u2192 v5 OM). Overrides --om-reader-scaffold and --om-with-retrieval per-case based on classification. Only effective with --observational-memory.'
)
.option(
'--om-classifier-model <model>',
"Step 16c v2: model identifier for the dynamic router's classification call. Default `gpt-5-mini` (cheap, fast). Set to `gpt-4o` when classifier accuracy at gpt-5-mini is too low (initial Tier A measured 37.5%). Only effective with --om-dynamic-router."
)
.option(
'--om-classifier-fewshot',
'Step 16c v10: use the few-shot variant of the classifier prompt. Adds explicit Question/Category pairs after category definitions to disambiguate SSU-vs-SSA, SSP-vs-SSA, MS-vs-KU confusion patterns. Only effective with --om-dynamic-router.'
)
.option(
'--om-guided-retrieval',
'Step 17: scope HybridRetriever to OM-identified candidate sessions. The OM observation log is used to score each session by query-relevance, then post-hoc filter retrieved evidence to top-K candidates. Reader sees OM log + scoped passages. Architectural alternative to Step 16c routing. Only effective with --observational-memory.'
)
.option(
'--om-guided-retrieval-k <n>',
'Step 17: number of candidate sessions to keep when --om-guided-retrieval is on. Default 5. Smaller K narrows scope (less pollution) but risks missing the gold session.',
parsePositiveInteger
)
.option(
'--om-retriever-ms-k <n>',
'Step 19A: per-case readerTopK override for MS-classified cases (v10 router only). Default 10. Set to 30 for K=30 retrieval on multi-session questions; preserves baseline K for all other categories.',
parsePositiveInteger
)
.option(
'--om-retriever-ms-bm25-weight <w>',
'Step 19B: per-case BM25 sparse weight in RRF for MS-classified cases (v10 router only). Must be in [0, 1] (denseWeight = 1 - sparseWeight). Default RRF dense=0.7/sparse=0.3. Set to 0.7 for BM25-heavy fusion (dense=0.3/sparse=0.7) on multi-session questions only; preserves baseline weights for all other categories.',
parseUnitIntervalWeight
)
.option(
'--om-retriever-ms-overfetch <m>',
'Step 19C: per-case over-fetch multiplier (positive integer) for MS-classified cases (v10 router only). Default 3 (over-fetch K = recallTopK * 3). Set to 6 for K=60 over-fetch on multi-session questions only; preserves baseline over-fetch for all other categories.',
parsePositiveInteger
)
.option(
'--no-capture-retention-inputs',
'Step 18: opt OUT of capturing the post-Observer compressed observation log (omFinalLog) into per-case metadata. Default ON (the token-retention metric needs the log to compute per-stage rates). Disable when running benchmarks that do NOT consume the retention metric (saves ~10-20MB per cached run JSON at N=500).'
)
.option(
'--om-reader-scaffold',
'Step 15 v4a: append a cross-session reasoning scaffold to the OM reader system prompt. The scaffold walks the reader through multi-step synthesis (scan all date-grouped sections, extract per-session facts, order chronologically, synthesize). Targets the v3 failure mode where the reader fixates on the most-recent-date observation block and misses cross-session synthesis. Only effective with --observational-memory. Default off.'
)
.option(
'--policy-router',
'Tier 3 policy router: dispatch per-query to tier_1_canonical / tier_2a_v10 / tier_2b_v11 based on the v10 classifier prediction + routing table. Mutually exclusive with --om-dynamic-router. See --policy-router-preset for preset selection; see --policy-router-budget-per-query for optional budget envelope.'
)
.option(
'--policy-router-preset <preset>',
'Tier 3 routing preset: maximize-accuracy (default, realistic 75.3% at $0.357/correct = 1.22x cheaper vs Tier 2b flat), balanced (74.5% at $0.205/correct = 2.12x cheaper), minimize-cost (73.9% at $0.092/correct = 4.77x cheaper). Only effective with --policy-router.',
(value: string) => {
if (value !== 'maximize-accuracy' && value !== 'balanced' && value !== 'minimize-cost') {
throw new Error(
`--policy-router-preset must be 'maximize-accuracy' | 'balanced' | 'minimize-cost', got '${value}'`
);
}
return value;
}
)
.option(
'--policy-router-budget-per-query <USD>',
'Tier 3 per-query USD ceiling. Unbounded when omitted. Combined with --policy-router-budget-mode to control exceed behavior. Only effective with --policy-router.',
parseFloatArg
)
.option(
'--policy-router-budget-mode <mode>',
'Tier 3 budget mode: hard (default, throws on exceed) | soft (exceed only when better $/correct) | cheapest-fallback (downgrade to cheapest-that-fits). Only effective with --policy-router AND --policy-router-budget-per-query set.',
(value: string) => {
if (value !== 'hard' && value !== 'soft' && value !== 'cheapest-fallback') {
throw new Error(
`--policy-router-budget-mode must be 'hard' | 'soft' | 'cheapest-fallback', got '${value}'`
);
}
return value;
}
)
.option(
'--retrieval-config-router <preset>',
"RetrievalConfigRouter: per-case retrieval-config dispatch on canonical-hybrid. Classifies each query via gpt-5-mini, looks up the chosen preset's table, and overrides the run-level --hyde / --reader-top-k / --rerank-candidate-multiplier flags for that case. Presets: minimize-cost-augmented (2026-04-26 v2 calibration; LongMemEval-M Phase A N=54 ablation matrix; orthogonal to --policy-router); s-best-cat-hyde-ms-2026-04-28 (S Pareto-win pre-validation: canonical everywhere except multi-session → HyDE; refuted at Phase A); s-best-cat-topk50-mult5-ms-2026-04-29 (follow-up: canonical everywhere except multi-session → topk50-mult5 wider rerank pool). Cache fingerprint: stage-rcr:<preset>:v1.",
(value: string) => {
const allowed = [
'minimize-cost-augmented',
's-best-cat-hyde-ms-2026-04-28',
's-best-cat-topk50-mult5-ms-2026-04-29',
];
if (!allowed.includes(value)) {
throw new Error(
`--retrieval-config-router must be one of ${allowed.join(' | ')}, got '${value}'`
);
}
return value;
}
)
.option(
'--session-level-ndcg',
'Stage C / Tier 4a: session-level NDCG retrieval post-process. After canonical HybridRetriever returns top-K traces, group them by sessionId, compute NDCG per session, pick top-K sessions (see --session-level-ndcg-top-k), and expand evidence to ALL turns of those sessions from the haystack. Matches Emergence AI Simple recipe. Applies to canonical path only; ignored on OM branches.'
)
.option(
'--session-level-ndcg-top-k <n>',
'Stage C: number of top-NDCG sessions to expand. Default 3. Only effective with --session-level-ndcg.',
parsePositiveInteger
)