Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(eval): longmemeval --via-operation query|search (GBRA-81 harness)

garrytan97fad0f76476
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 38ba3de259..c9278303a7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ identifiers and attribution are available in the pre-removal Git revision
- **`gbrain init` reads keys the way the gateway does.** Provider keys are read through `mergedProviderEnv`, so a key saved in `~/.gbrain/config.json` counts, and a brain with a ready reranker but no chat key gets `balanced` instead of `conservative` (the reranker branch uses `rerankerReadiness`, not a key name); `conservative` stays for a Haiku subagent or when neither a chat key nor a ready reranker exists.
- **`gbrain init --search-mode <mode>` and `search.mode_source`.** An agent that knows the operator's choice records it at install time: no recommendation, no first-run `search_mode` ask, `search.mode_source: operator`. On a brain with a different mode it refuses unless `--force`. Picker choices record `auto`; `gbrain config set search.mode` records `operator`.
- **One source for the mode advice.** `src/core/search/mode-advice.ts` holds the recommendation, its reasons and evidence, the `[AGENT]` and upgrade banners, init's first-run decision text and the cost matrix, now priced for Haiku 5.5, Sonnet 5.5 and Opus 5.5 from `src/core/model-pricing.ts` (about a 200x corner-to-corner spread). `INSTALL_FOR_AGENTS.md` Step 3.5 carries the generated matrix, kept in sync by a test. Switching modes no longer promises a cache refill while semantic result caching is off.
+- **`gbrain eval longmemeval --via-operation query|search`.** Runs each question through the real operation with an agent's stdio MCP context (remote, stdio, source `default`) at the operation's default limit, with `--op-expand on|off` for `query`. Rows record the context, the `expand` sent, model calls per touchpoint, latency, the CRAG grade and the expansion outcome; `run_config.via_operation_summary` has the tree, p50/p95 latency and model calls per query. A run that expects expansion fails when any question did not expand.
## [0.60.178.0] - 2026-10-12
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.md
index 041e1bebb8..dcfa74038f 100644
--- a/docs/architecture/key-files/evaluation.md
+++ b/docs/architecture/key-files/evaluation.md
@@ -60,6 +60,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/eval/longmemeval/retrieval-arms.ts` — eval-only retrieval arms for `gbrain eval longmemeval`, flags spread into the harness flag table. `--fact-keys chunk|page` extracts each imported session's facts (`--fact-extractor paper` = the benchmark's published user-turn fact prompt, `production` = `extractFactsFromTurnWithOutcome` as shipped; `--fact-keys-model`, `--fact-keys-max-usd` cap on uncached spend, default 20) through a content-hash JSONL cache under `~/.cache/gbrain-eval/`, then re-embeds that session's chunks with `factKeyedEmbeddingInput` inside the embed-cache transaction (row field `fact_keys`). `--time-scope reserved|partition` widens the search limit to `--time-scope-pool` (default 50), parses the question against `question_date`, re-orders by each session's observation + mentioned dates, and records `time_scope` plus the unscoped top-k's `unscoped_recall_all_hit` / `unscoped_recall_any_hit` from the same pool (a paired control inside one run). Active arms fold into `retrieval_config_hash` as `retrieval_arms`; with no arm on the hash is unchanged. Test: `test/fact-keys.test.ts`.
- `src/eval/longmemeval/synopsis-tier.ts` — makes `--mode tokenmax` measure the production per-chunk synopsis tier: when the resolved tier is `per_chunk_synopsis`, every imported session is re-embedded through `reembedPageWithContextualRetrieval` with the backfill's synopsis model (`resolveContextualSynopsisModel`), behind a JSONL cache keyed by `buildSynopsisCacheKey` (only answers the model returned are cached) and a `--synopsis-max-usd` cap metered from provider usage (default 20; the run stops after the question that reached it and exits 1). Transient service errors retry with backoff. Row field `contextual_synopsis`; pins in `run_config.contextual_synopsis` and `retrieval_config_hash`. Test: `test/eval-longmemeval-synopsis-tier.serial.test.ts`.
+- `src/eval/longmemeval/via-operation.ts` — `gbrain eval longmemeval --via-operation query|search` (`--op-expand on|off`): runs each question through the real operation handler with an agent's stdio MCP context (`buildOperationContext`, remote, stdio, source `default`) at the operation's default limit, records `via_operation` per row (context, `expand` sent, model calls per touchpoint from a per-question BudgetTracker, latency, CRAG grade, expansion outcome) and `run_config.via_operation_summary` (tree, p50/p95 latency, model calls per query); folds the op and context into `retrieval_config_hash`; a run that expects expansion pushes `expansion_not_applied` on any row that did not expand, which `resume.ts` counts as an expansion failure (exit 1). Pinned by `test/eval-longmemeval-via-operation.serial.test.ts`.
- `src/eval/longmemeval/locomo.ts` + `scripts/locomo-to-longmemeval.ts` — LoCoMo `locomo10.json` → LongMemEval-format questions for an explicit conversation list: one question per QA except category 5, the conversation's sessions as the haystack (stable ids `conv-N_sK`, LongMemEval-format dates, the last session's date as the question date), gold sessions from evidence dialog ids, speaker names as turn roles. Sealed conversations (`LOCOMO_SEALED_CONVERSATIONS`) convert only with `custodian`. Test: `test/longmemeval-locomo.test.ts`.
diff --git a/docs/eval-bench.md b/docs/eval-bench.md
index 3c6f4ffe92..aa883753cd 100644
--- a/docs/eval-bench.md
+++ b/docs/eval-bench.md
@@ -563,6 +563,22 @@ gbrain eval longmemeval ~/datasets/longmemeval/longmemeval_s_cleaned.json \
--mode balanced --reranker on --autocut off \
--output ~/lme-receipts/default.ndjson
+# Through the real operation instead of the core library: --via-operation query|search
+# runs each question as an agent's stdio MCP call would (remote, stdio, source
+# `default`), at the operation's own default limit and under the brain's resolved
+# search mode, so a receipt reproduces from a tagged gbrain. `query` expands by the
+# mode (on only in tokenmax) unless --op-expand on|off says otherwise. Each row's
+# `via_operation` records the context, the `expand` sent, model calls per
+# touchpoint, latency, the CRAG grade and the expansion outcome;
+# run_config.via_operation_summary has the tree, p50/p95 latency and model calls
+# per query. A run that expects expansion fails (exit 1) when any question did
+# not expand (`expansion_not_applied`); --expansion, --keyword-only and
+# --capture-pool are refused with it.
+gbrain eval longmemeval ~/datasets/longmemeval/longmemeval_s_cleaned.json \
+ --retrieval-only --top-k 5 --by-type --no-trajectory \
+ --mode balanced --reranker on --via-operation query --op-expand off \
+ --output ~/lme-receipts/query-balanced-noexpand.ndjson
+
# Embeddings are cached content-addressed at ~/.cache/gbrain-eval/longmemeval-embed.sqlite
# (--embed-cache FILE to relocate, --no-embed-cache to disable), so every arm after
# the first sees byte-identical vectors; run_config.cache.misses must be 0 for a
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 87664f434c..e426205282 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -41,7 +41,7 @@ src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERV
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)
-src/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)
+src/commands/eval-longmemeval.ts 1532 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts)
src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts
src/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)
src/commands/config.ts 1508 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 GBRA-81 item 1: config set search.mode records search.mode_source operator
diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.ts
index 80ab0a6bdd..e94dce2998 100644
--- a/src/commands/eval-longmemeval.ts
+++ b/src/commands/eval-longmemeval.ts
@@ -130,6 +130,7 @@ import {
import { buildCaptureExtras } from '../eval/longmemeval/capture.ts';
import * as decideLane from '../eval/longmemeval/decide-lane.ts';
import * as retrievalArms from '../eval/longmemeval/retrieval-arms.ts';
+import * as viaOperation from '../eval/longmemeval/via-operation.ts';
import * as synopsisTier from '../eval/longmemeval/synopsis-tier.ts';
import { resolveModel } from '../core/model-config.ts';
import type { ThinkLLMClient } from '../core/think/index.ts';
@@ -208,7 +209,7 @@ interface ParsedArgs {
judgeConcurrency: number;
allowIncompleteJudgments: boolean;
/** System One arm (`--decide*`, src/eval/decide-eval-flags.ts) and the eval-only `--eval-pool-depth`. */
- decide: decideLane.DecideEvalOptions; evalPoolDepth?: number; arms: retrievalArms.RetrievalArmOptions; synopsis: synopsisTier.SynopsisTierOptions;
+ decide: decideLane.DecideEvalOptions; evalPoolDepth?: number; arms: retrievalArms.RetrievalArmOptions; synopsis: synopsisTier.SynopsisTierOptions; viaOp: viaOperation.ViaOperationOptions;
}
interface LmeFlag {
@@ -388,7 +389,7 @@ const LME_FLAGS: LmeFlag[] = [
'--judge --resume-from FILE until all three are 0.'],
apply: (o) => { o.allowIncompleteJudgments = true; } },
...decideLane.LME_DECIDE_FLAGS,
- ...retrievalArms.LME_RETRIEVAL_ARM_FLAGS, ...synopsisTier.LME_SYNOPSIS_FLAGS,
+ ...retrievalArms.LME_RETRIEVAL_ARM_FLAGS, ...synopsisTier.LME_SYNOPSIS_FLAGS, ...viaOperation.LME_VIA_OPERATION_FLAGS,
];
function parseArgs(args: string[]): ParsedArgs {
@@ -413,7 +414,7 @@ function parseArgs(args: string[]): ParsedArgs {
yes: false,
judgeConcurrency: 1,
allowIncompleteJudgments: false,
- decide: decideLane.newDecideEvalOptions(), arms: retrievalArms.newRetrievalArmOptions(), synopsis: synopsisTier.newSynopsisTierOptions(),
+ decide: decideLane.newDecideEvalOptions(), arms: retrievalArms.newRetrievalArmOptions(), synopsis: synopsisTier.newSynopsisTierOptions(), viaOp: viaOperation.newViaOperationOptions(),
};
const byName = new Map(LME_FLAGS.map(f => [f.name, f]));
for (let i = 0; i < args.length; i++) {
@@ -438,6 +439,7 @@ function parseArgs(args: string[]): ParsedArgs {
if (out.judge && out.retrievalOnly) {
throw new Error('--judge cannot be combined with --retrieval-only (there is no reader hypothesis to judge)');
}
+ viaOperation.validateViaOperation(out);
return out;
}
@@ -540,6 +542,8 @@ interface RunContext {
expandFn: (query: string) => Promise<string[]>;
replay: Map<string, string[]> | null;
retrievalConfigHash: string;
+ /** The run's resolved expansion expectation (pins.expansion): the degradation gate's `expansion` input. */
+ expectExpansion: boolean;
/**
* Wraps the embed-producing section of one question (import + search) in
* ONE embed-cache transaction (eng D7) — and nothing after it, so a reader
@@ -566,7 +570,7 @@ function resolvePins(opts: ParsedArgs, runOpts: RunOpts, trajectoryEnabled: bool
mode: opts.mode ?? snapshot['search.mode'],
overrides: loadOverridesFromConfig(snapshot),
perCall: {
- expansion: opts.expansion,
+ expansion: opts.viaOp.op ? opts.viaOp.expand : opts.expansion,
...(opts.expansionVariantBudget !== undefined ? { expansion_variant_budget: opts.expansionVariantBudget } : {}),
...(opts.reranker !== undefined ? { reranker_enabled: opts.reranker } : {}),
...(opts.autocut !== undefined ? { autocut: opts.autocut } : {}),
@@ -584,14 +588,14 @@ function resolvePins(opts: ParsedArgs, runOpts: RunOpts, trajectoryEnabled: bool
keyword_only: opts.keywordOnly,
reranker: { enabled: opts.keywordOnly ? false : knobs.reranker_enabled, model: knobs.reranker_model },
autocut: opts.keywordOnly ? false : knobs.autocut,
- expansion: opts.keywordOnly ? false : opts.expansion,
+ expansion: opts.viaOp.op ? opts.viaOp.op === 'query' && knobs.expansion : opts.keywordOnly ? false : opts.expansion,
expansion_variant_budget: knobs.expansion_variant_budget,
embedder,
top_k: opts.topK,
trajectory: trajectoryEnabled,
...(searchPins ? { search_pins: searchPins } : {}),
...(opts.evalPoolDepth ? { eval_pool_depth: opts.evalPoolDepth } : {}), ...(decide ? { decide: decide.runConfig } : {}),
- ...retrievalArms.armPins(opts.arms),
+ ...retrievalArms.armPins(opts.arms), ...viaOperation.viaOperationPins(opts.viaOp),
};
return { pins, knobs };
}
@@ -678,7 +682,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
// D33 + review: the hash covers the pins AND the resolved knobs hash, so a
// resume cannot merge runs whose injected snapshot differs in a non-pin knob.
const retrievalHash = retrievalConfigHash(pins, { knobs_hash: knobsHashValue, knobs_hash_version: KNOBS_HASH_VERSION });
- const degradeOpts = { keywordOnly: opts.keywordOnly, expansion: opts.expansion };
+ const degradeOpts = { keywordOnly: opts.keywordOnly, expansion: pins.expansion };
// Resolved BEFORE the resume block: the reader model is half of every
// row's judge_config_hash (D33), which the --judge backfill gate needs.
@@ -737,6 +741,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
errors: st.errorCount,
reader: { mode: readerConfig.mode, prompt_version: readerConfig.promptVersion, prompt_sha: readerConfig.promptSha, max_tokens: readerConfig.maxTokens, model: normalizeModelId(model), config_hash: readerHash },
...(decideRun ? { decide_summary: decideLane.summarizeDecideReceipts(st.qaRows.map((r) => r.decide as never)) } : {}),
+ ...(opts.viaOp.op ? { via_operation_summary: viaOperation.summarizeViaOperation(st.qaRows as never, gitShort(['rev-parse', 'HEAD^{tree}'], 'unknown')) } : {}),
});
/**
@@ -840,8 +845,9 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
process.stderr.write(`[longmemeval] FAIL vector arm: ${st.vectorDegradedRows} row(s) scored keyword-only after a silent embed failure (vector_enabled:false / embed_unavailable / embed_timeout) — vector_degraded_rows\n`);
exitCode = 1;
}
- if (!opts.keywordOnly && opts.expansion && st.expansionFailedRows > 0) {
- process.stderr.write(`[longmemeval] FAIL --expansion: ${st.expansionFailedRows} row(s) did not expand as configured (expansion_failed / expansion_partial) — expansion_failed_rows\n`);
+ if (!opts.keywordOnly && pins.expansion && st.expansionFailedRows > 0) {
+ process.stderr.write(opts.viaOp.op ? viaOperation.expansionFailLine(st.expansionFailedRows)
+ : `[longmemeval] FAIL --expansion: ${st.expansionFailedRows} row(s) did not expand as configured (expansion_failed / expansion_partial) — expansion_failed_rows\n`);
exitCode = 1;
}
if (st.expansionReplayMiss > 0) {
@@ -1121,7 +1127,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
factKeys: await retrievalArms.resolveFactKeyArm(opts.arms, extractorClient), synopsis,
expandFn: runOpts.expandFn ?? expandQuery,
replay,
- retrievalConfigHash: retrievalHash,
+ retrievalConfigHash: retrievalHash, expectExpansion: pins.expansion,
embedTxn: (fn) => fn(),
};
@@ -1398,6 +1404,7 @@ async function runOneQuestion(
const decideBefore = await decideLane.lmeSpendBefore(engine, ctx.decide);
let pool: SearchResult[] | undefined;
let preRerank: SearchResult[] | undefined;
+ let viaRow: viaOperation.ViaOperationRow | undefined;
// The embed-producing section (import + search) runs in ONE embed-cache
// transaction and COMMITS before the trajectory lookup / reader call.
const results: SearchResult[] = await ctx.embedTxn(async () => {
@@ -1422,6 +1429,11 @@ async function runOneQuestion(
}
if (ctx.synopsis) Object.assign(extra0, { contextual_synopsis: await synopsisTier.applySynopsisTier(engine, adapterPages, ctx.synopsis) });
if (ctx.factKeys) Object.assign(extra0, { fact_keys: await retrievalArms.applyFactKeyArm(engine, adapterPages, ctx.factKeys.arm, ctx.factKeys.spend) });
+ if (opts.viaOp.op) {
+ const via = await viaOperation.runViaOperation(engine, q.question, { ...opts.viaOp, op: opts.viaOp.op }, ctx.expectExpansion);
+ meta = via.meta; viaRow = via.row;
+ return via.results;
+ }
if (opts.keywordOnly) return engine.searchKeyword(q.question, { limit: opts.topK });
const searchOpts: HybridSearchOpts = {
limit: opts.arms.timeScope ? Math.max(opts.topK, opts.arms.timeScopePool) : opts.topK,
@@ -1489,7 +1501,7 @@ async function runOneQuestion(
reranked: false,
...(meta?.autocut ? { autocut: meta.autocut } : {}),
};
- const { rerankerSkipped, vectorDegraded, expansionFailed } = classifyDegradation(searchMeta, { keywordOnly: opts.keywordOnly, expansion: opts.expansion });
+ const { rerankerSkipped, vectorDegraded, expansionFailed } = classifyDegradation(searchMeta, { keywordOnly: opts.keywordOnly, expansion: ctx.expectExpansion });
searchMeta.reranked = results.some(r => Number.isFinite(r.rerank_score)) && !rerankerSkipped;
const extra: Record<string, unknown> = {
@@ -1498,7 +1510,7 @@ async function runOneQuestion(
...readerFields,
search_meta: searchMeta,
...(expansionVariants ? { expansion_variants: expansionVariants } : {}),
- ...(expansionReplayed ? { expansion_replayed: true } : {}),
+ ...(expansionReplayed ? { expansion_replayed: true } : {}), ...(viaRow ? { via_operation: viaRow } : {}),
...(ctx.trajectoryEnabled ? {
intent,
trajectory_points: route.points,
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 3c180c8c6a..a4756aa020 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -56,7 +56,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
- 'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],
+ 'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
diff --git a/src/eval/longmemeval/resume.ts b/src/eval/longmemeval/resume.ts
index a328af2bee..8ab97cea04 100644
--- a/src/eval/longmemeval/resume.ts
+++ b/src/eval/longmemeval/resume.ts
@@ -317,7 +317,8 @@ export interface RowSearchMeta {
}
const VECTOR_DEGRADED_STAGES: ReadonlySet<string> = new Set(['embed_unavailable', 'embed_timeout']);
-const EXPANSION_FAILED_STAGES: ReadonlySet<string> = new Set(['expansion_failed', 'expansion_partial']);
+/** `expansion_not_applied`: a `--via-operation query` row the run expected to expand that did not (via-operation.ts). */
+const EXPANSION_FAILED_STAGES: ReadonlySet<string> = new Set(['expansion_failed', 'expansion_partial', 'expansion_not_applied']);
const RERANKER_SKIPPED_STAGES: ReadonlySet<string> = new Set(['reranker_skipped', 'rerank_passthrough', 'rerank_failed']);
/**
diff --git a/src/eval/longmemeval/run-config.ts b/src/eval/longmemeval/run-config.ts
index fde2b6d1c6..e308a3226b 100644
--- a/src/eval/longmemeval/run-config.ts
+++ b/src/eval/longmemeval/run-config.ts
@@ -56,6 +56,8 @@ export interface RetrievalPins {
retrieval_arms?: Record<string, unknown>;
/** Per-chunk synopsis tier pins (model, prompt version, doc cap, max tokens). Present only when the resolved mode builds synopsis vectors. */
contextual_synopsis?: Record<string, unknown>;
+ /** `--via-operation`: the operation, the `expand` sent and the agent-shaped context (via-operation.ts). Present only on that path. */
+ via_operation?: Record<string, unknown>;
}
/** Stable JSON: sorted keys at every level so key order can never move the hash. */
@@ -170,6 +172,8 @@ export interface RunConfigInput {
reader?: { mode: string; prompt_version: string; prompt_sha: string; max_tokens: number; model: string; config_hash: string };
/** Run-level roll-up of the rows' `decide` receipts (System One arms only). */
decide_summary?: Record<string, unknown>;
+ /** `--via-operation` per-arm roll-up: tree, latency p50/p95, model calls per query, CRAG grades, expansion outcomes. */
+ via_operation_summary?: Record<string, unknown>;
}
/** The `run_config` object stamped on the by_type_summary (schema v2). */
@@ -190,6 +194,7 @@ export function buildRunConfig(input: RunConfigInput): Record<string, unknown> {
...(p.eval_pool_depth ? { eval_pool_depth: p.eval_pool_depth } : {}),
...(p.decide ? { decide: p.decide } : {}),
...(p.contextual_synopsis ? { contextual_synopsis: p.contextual_synopsis } : {}),
+ ...(p.via_operation ? { via_operation: p.via_operation } : {}),
dataset_sha256: input.dataset_sha256,
dataset_questions: input.dataset_questions,
question_ids_file: input.question_ids_file,
@@ -208,6 +213,7 @@ export function buildRunConfig(input: RunConfigInput): Record<string, unknown> {
errors: input.errors,
...(input.reader ? { reader: input.reader } : {}),
...(input.decide_summary ? { decide_summary: input.decide_summary } : {}),
+ ...(input.via_operation_summary ? { via_operation_summary: input.via_operation_summary } : {}),
};
}
diff --git a/src/eval/longmemeval/via-operation.ts b/src/eval/longmemeval/via-operation.ts
new file mode 100644
index 0000000000..ed14cf174d
--- /dev/null
+++ b/src/eval/longmemeval/via-operation.ts
@@ -0,0 +1,204 @@
+/**
+ * `gbrain eval longmemeval --via-operation query|search`: run each question
+ * through the real `query` or `search` operation with the context an agent's
+ * stdio MCP call gets (remote, stdio transport, the owner source id), instead
+ * of calling hybridSearch from the core library. Each operation runs at its own
+ * default limit and resolves the brain's search mode itself, so a receipt
+ * reproduces from a tagged gbrain. `--op-expand on|off` passes `expand` to
+ * `query`; without it the mode decides.
+ *
+ * Every row records the operation context, the `expand` sent, the expansion
+ * outcome, model calls per touchpoint, operation latency and the CRAG
+ * confidence grade. When the run expects expansion and a question did not
+ * expand, the row carries the `expansion_not_applied` degraded stage, which
+ * fails the run like `--expansion`'s `expansion_failed` (the arm is invalid
+ * until a named repair).
+ */
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../core/engine.ts';
+import type { GBrainConfig } from '../../core/config.ts';
+import type { HybridSearchMeta, SearchResult } from '../../core/types.ts';
+import type { ModelTouchpoint } from '../../core/budget/models-used.ts';
+import { BudgetTracker } from '../../core/budget/budget-tracker.ts';
+import { withBudgetTracker } from '../../core/ai/gateway.ts';
+import { operationsByName } from '../../core/operations.ts';
+import { buildOperationContext } from '../../mcp/dispatch.ts';
+
+export type ViaOperation = 'query' | 'search';
+
+export interface ViaOperationOptions {
+ op?: ViaOperation;
+ /** `--op-expand on|off`: the `expand` param sent to `query`; undefined = unset (the mode decides). */
+ expand?: boolean;
+}
+
+export function newViaOperationOptions(): ViaOperationOptions {
+ return {};
+}
+
+/** The agent-shaped context every question runs under (recorded in the pins). */
+export const VIA_OPERATION_CONTEXT = { remote: true, transport: 'stdio', source_id: 'default' } as const;
+
+export const LME_VIA_OPERATION_FLAGS: Array<{ name: string; arg?: string; help: string[]; apply: (o: { viaOp: ViaOperationOptions }, value: string) => void }> = [
+ { name: '--via-operation', arg: 'query|search', help: [
+ 'Run each question through the real `query` or `search` operation with an',
+ 'agent\'s stdio MCP context (remote, stdio, source `default`) at the',
+ 'operation\'s default limit, instead of the core-library hybridSearch call.',
+ 'Rows record the context, model calls, latency, expansion outcome and CRAG',
+ 'grade; run_config.via_operation_summary has p50/p95 latency per arm.'],
+ apply: (o, v) => { if (v !== 'query' && v !== 'search') throw new Error(`--via-operation must be query|search (got: ${v})`); o.viaOp.op = v; } },
+ { name: '--op-expand', arg: 'on|off', help: [
+ 'With --via-operation query: send `expand: true|false`. Omitted = unset, so',
+ 'the resolved search mode decides (on only in tokenmax). A run that expects',
+ 'expansion fails when any question did not expand (expansion_not_applied).'],
+ apply: (o, v) => {
+ const s = v.trim().toLowerCase();
+ if (s !== 'on' && s !== 'off') throw new Error(`--op-expand must be on|off (got: ${v})`);
+ o.viaOp.expand = s === 'on';
+ } },
+];
+
+/** Refuse flag combinations the via-operation path would silently ignore. */
+export function validateViaOperation(o: {
+ viaOp: ViaOperationOptions; keywordOnly: boolean; expansion: boolean; expansionVariantBudget?: number | null; capturePool: boolean;
+}): void {
+ if (!o.viaOp.op) {
+ if (o.viaOp.expand !== undefined) throw new Error('--op-expand needs --via-operation query');
+ return;
+ }
+ if (o.viaOp.op === 'search' && o.viaOp.expand !== undefined) throw new Error('--op-expand applies to --via-operation query only (`search` never expands)');
+ const ignored = [
+ o.keywordOnly && '--keyword-only',
+ o.expansion && '--expansion / --expansion-replay (use --op-expand)',
+ o.expansionVariantBudget !== undefined && '--expansion-variant-budget (use --search-pin search.expansion_variant_budget=…)',
+ o.capturePool && '--capture-pool',
+ ].filter((x): x is string => typeof x === 'string');
+ if (ignored.length > 0) throw new Error(`--via-operation cannot be combined with ${ignored.join(', ')}`);
+}
+
+/** The pin folded into retrieval_config_hash, so a resume never merges via-operation and direct rows. */
+export function viaOperationPins(v: ViaOperationOptions): { via_operation?: Record<string, unknown> } {
+ if (!v.op) return {};
+ return { via_operation: { op: v.op, expand: v.expand ?? null, limit: 'operation_default', context: { ...VIA_OPERATION_CONTEXT } } };
+}
+
+export type ExpansionOutcome = 'applied' | 'failed' | 'not_attempted' | 'no_variants' | 'not_expected';
+
+export interface ViaOperationRow {
+ op: ViaOperation;
+ expand: boolean | null;
+ latency_ms: number;
+ rows_returned: number;
+ /** Recorded gateway calls by touchpoint (expansion / embedding / rerank / chat …) for this question. */
+ model_calls: Partial<Record<ModelTouchpoint, number>>;
+ failed_model_calls: number;
+ expansion: { expected: boolean; outcome: ExpansionOutcome };
+ crag_confidence: string | null;
+}
+
+export interface ViaOperationResult {
+ results: SearchResult[];
+ meta: HybridSearchMeta;
+ row: ViaOperationRow;
+}
+
+let auditDir: string | null = null;
+
+/**
+ * One question through the operation. `expectExpansion` is the resolved
+ * expectation for the run (op query and expand on, or unset with the mode's
+ * expansion on). Never throws for a degraded call; an operation error throws.
+ */
+export async function runViaOperation(
+ engine: BrainEngine,
+ question: string,
+ v: ViaOperationOptions & { op: ViaOperation },
+ expectExpansion: boolean,
+): Promise<ViaOperationResult> {
+ const meta: Record<string, unknown> = {};
+ const ctx = buildOperationContext(engine, {}, {
+ remote: VIA_OPERATION_CONTEXT.remote, transport: VIA_OPERATION_CONTEXT.transport, sourceId: VIA_OPERATION_CONTEXT.source_id,
+ config: { engine: 'pglite' } as GBrainConfig,
+ });
+ ctx.emitResponseMeta = (key, value) => { meta[key] = value; };
+ const params: Record<string, unknown> = { query: question, ...(v.op === 'query' && v.expand !== undefined ? { expand: v.expand } : {}) };
+
+ auditDir ??= mkdtempSync(join(tmpdir(), 'gbrain-lme-via-op-'));
+ const tracker = new BudgetTracker({ label: 'longmemeval.via_operation', auditPath: join(auditDir, 'budget.jsonl') });
+ const started = performance.now();
+ const results = await withBudgetTracker(tracker, () => operationsByName[v.op].handler(ctx, params)) as SearchResult[];
+ const latency_ms = Math.round(performance.now() - started);
+
+ const modelCalls: Partial<Record<ModelTouchpoint, number>> = {};
+ let failed = 0;
+ let expansionCalls = 0;
+ let expansionFailures = 0;
+ for (const m of tracker.snapshot().models) {
+ modelCalls[m.touchpoint] = (modelCalls[m.touchpoint] ?? 0) + m.calls;
+ failed += m.failed_calls;
+ if (m.touchpoint === 'expansion') { expansionCalls += m.calls; expansionFailures += m.failed_calls; }
+ }
+
+ const retrieval = (meta.retrieval ?? {}) as HybridSearchMeta & { crag?: { confidence?: string } };
+ const applied = retrieval.expansion_applied === true;
+ const outcome: ExpansionOutcome = !expectExpansion ? (applied ? 'applied' : 'not_expected')
+ : applied ? 'applied'
+ : expansionFailures > 0 ? 'failed'
+ : expansionCalls === 0 ? 'not_attempted'
+ : 'no_variants';
+ const degraded = [...(retrieval.degraded ?? [])];
+ // An eval-only stage (the outcome itself rides `via_operation.expansion`); resume.ts counts it as an expansion failure.
+ if (expectExpansion && outcome !== 'applied') degraded.push({ stage: 'expansion_not_applied' } as never);
+
+ return {
+ results: Array.isArray(results) ? results : [],
+ meta: { ...retrieval, vector_enabled: retrieval.vector_enabled ?? false, expansion_applied: applied, degraded } as HybridSearchMeta,
+ row: {
+ op: v.op,
+ expand: v.op === 'query' ? v.expand ?? null : false,
+ latency_ms,
+ rows_returned: Array.isArray(results) ? results.length : 0,
+ model_calls: modelCalls,
+ failed_model_calls: failed,
+ expansion: { expected: expectExpansion, outcome },
+ crag_confidence: retrieval.crag?.confidence ?? null,
+ },
+ };
+}
+
+/** The run-end FAIL line when a run that expects expansion has rows that did not expand. */
+export function expansionFailLine(rows: number): string {
+ return `[longmemeval] FAIL --via-operation query (expansion expected): ${rows} row(s) did not expand (expansion_not_applied / expansion_failed); this arm is invalid until a named repair — expansion_failed_rows\n`;
+}
+
+function percentile(sorted: number[], p: number): number | null {
+ if (sorted.length === 0) return null;
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
+}
+
+/** The per-arm block on run_config: latency p50/p95, mean model calls per query by touchpoint, CRAG grades, expansion outcomes. */
+export function summarizeViaOperation(rows: ReadonlyArray<Record<string, unknown>>, tree: string): Record<string, unknown> {
+ const via = rows.map(r => r.via_operation as ViaOperationRow | undefined).filter((x): x is ViaOperationRow => !!x && typeof x.latency_ms === 'number');
+ const latencies = via.map(r => r.latency_ms).sort((a, b) => a - b);
+ const calls: Record<string, number> = {};
+ const crag: Record<string, number> = {};
+ const expansion: Record<string, number> = {};
+ for (const r of via) {
+ for (const [t, n] of Object.entries(r.model_calls)) calls[t] = (calls[t] ?? 0) + (n ?? 0);
+ const grade = r.crag_confidence ?? 'none';
+ crag[grade] = (crag[grade] ?? 0) + 1;
+ expansion[r.expansion.outcome] = (expansion[r.expansion.outcome] ?? 0) + 1;
+ }
+ const perQuery = Object.fromEntries(Object.entries(calls).sort().map(([t, n]) => [t, via.length ? Number((n / via.length).toFixed(3)) : 0]));
+ return {
+ tree,
+ questions: via.length,
+ latency_ms: { p50: percentile(latencies, 0.5), p95: percentile(latencies, 0.95) },
+ model_calls_per_query: perQuery,
+ failed_model_calls: via.reduce((s, r) => s + r.failed_model_calls, 0),
+ crag_confidence: crag,
+ expansion_outcomes: expansion,
+ };
+}
diff --git a/test/eval-longmemeval-via-operation.serial.test.ts b/test/eval-longmemeval-via-operation.serial.test.ts
new file mode 100644
index 0000000000..c5382f2a8d
--- /dev/null
+++ b/test/eval-longmemeval-via-operation.serial.test.ts
@@ -0,0 +1,198 @@
+/**
+ * `gbrain eval longmemeval --via-operation query|search`: each question runs
+ * through the real operation with an agent's stdio MCP context, keyless (fixture
+ * embed and expansion transports; no provider is called).
+ *
+ * Protects: rows record the operation context, the `expand` sent, model calls
+ * per touchpoint, latency, the CRAG grade and the expansion outcome; the
+ * pins (and so retrieval_config_hash) carry the via-operation context; the
+ * summary's run_config has `via_operation_summary` (tree, p50/p95 latency,
+ * model calls per query); `query` expands by the resolved mode unless
+ * `--op-expand` says otherwise; a run that expects expansion fails when a
+ * question did not expand (the throwing-provider fixture); and flags the path
+ * would ignore are refused.
+ * Serial: mutates the process-global gateway and its transports.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runEvalLongMemEval } from '../src/commands/eval-longmemeval.ts';
+import { createBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';
+import { configureGateway, resetGateway, __clearQueryEmbedCacheForTests, __setEmbedTransportForTests, __setGenerateObjectTransportForTests } from '../src/core/ai/gateway.ts';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+
+const FIXTURE = join(import.meta.dir, 'fixtures', 'longmemeval-mini.jsonl');
+const QUESTIONS = readFileSync(FIXTURE, 'utf8').split('\n').filter(l => l.trim()).length;
+const DIMS = 1536;
+const tmp = mkdtempSync(join(tmpdir(), 'lme-via-op-'));
+const embedTransport = (async (p: { values: string[] }) => ({
+ embeddings: p.values.map(v => Array.from({ length: DIMS }, (_, j) => (j === v.length % DIMS ? 1 : 0.01))), values: p.values, warnings: [], usage: { tokens: p.values.length },
+})) as unknown as Parameters<typeof __setEmbedTransportForTests>[0];
+
+/** tokenmax builds per-chunk synopses with a chat model; title context keeps these runs keyless. */
+const NO_SYNOPSIS = ['--search-pin', 'search.contextual_retrieval=title'];
+
+let expansionCalls = 0;
+function expansionTransport(behavior: 'variants' | 'throw'): void {
+ __setGenerateObjectTransportForTests((async () => {
+ expansionCalls++;
+ if (behavior === 'throw') throw new Error('provider exploded');
+ return { object: { queries: ['an alternate phrasing of the question', 'another framing of it'] }, usage: { inputTokens: 50, outputTokens: 10 } };
+ }) as never);
+}
+
+async function run(args: string[]): Promise<{ rows: any[]; summary: any; err: string; failed: boolean }> {
+ const out = join(tmp, `out-${Math.random().toString(36).slice(2)}.jsonl`);
+ const engine: PGLiteEngine = await createBenchmarkBrain();
+ // Query embeddings are cached per process; each run starts cold so its model calls are its own.
+ __clearQueryEmbedCacheForTests();
+ const write = process.stderr.write.bind(process.stderr);
+ let err = '';
+ let failed = false;
+ process.stderr.write = ((s: string) => { err += s; return true; }) as typeof process.stderr.write;
+ try {
+ await runEvalLongMemEval([FIXTURE, '--no-embed-cache', '--by-type', '--retrieval-only', '--no-trajectory', '--reranker', 'off', '--output', out, ...args], {
+ engine, exitOnError: false, embedTransport,
+ });
+ } catch (e) {
+ if (!/longmemeval failed/.test((e as Error).message)) {
+ process.stderr.write = write;
+ await engine.disconnect();
+ throw Object.assign(e as Error, { stderr: err });
+ }
+ failed = true;
+ }
+ process.stderr.write = write;
+ await engine.disconnect();
+ const lines = readFileSync(out, 'utf8').split('\n').filter(l => l.trim()).map(l => JSON.parse(l));
+ return { rows: lines.filter(l => l.kind !== 'by_type_summary'), summary: lines.find(l => l.kind === 'by_type_summary'), err, failed };
+}
+
+beforeAll(() => {
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, expansion_model: 'anthropic:claude-haiku-5-5',
+ env: { OPENAI_API_KEY: 'sk-test', ANTHROPIC_API_KEY: 'sk-ant-test' },
+ });
+ __setEmbedTransportForTests(embedTransport);
+});
+
+afterEach(() => {
+ __setGenerateObjectTransportForTests(null);
+ expansionCalls = 0;
+});
+
+afterAll(() => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe('eval longmemeval --via-operation', () => {
+ test('search: rows and run_config record the agent-shaped context, latency and model calls; the hash differs from the direct path', async () => {
+ expansionTransport('variants');
+ const direct = await run(['--mode', 'balanced']);
+ const via = await run(['--via-operation', 'search', '--mode', 'balanced']);
+ expect(via.failed).toBe(false);
+ expect(via.rows).toHaveLength(QUESTIONS);
+ for (const row of via.rows) {
+ expect(row.via_operation).toMatchObject({ op: 'search', expand: false, expansion: { expected: false, outcome: 'not_expected' } });
+ expect(row.via_operation.latency_ms).toBeGreaterThanOrEqual(0);
+ expect(row.via_operation.model_calls.embedding).toBeGreaterThanOrEqual(1);
+ expect(row.via_operation.model_calls.expansion).toBeUndefined();
+ expect(Array.isArray(row.retrieved_session_ids)).toBe(true);
+ }
+ expect(expansionCalls).toBe(0);
+ const rc = via.summary.run_config;
+ expect(rc.via_operation).toEqual({ op: 'search', expand: null, limit: 'operation_default', context: { remote: true, transport: 'stdio', source_id: 'default' } });
+ expect(rc.via_operation_summary).toMatchObject({ questions: QUESTIONS, expansion_outcomes: { not_expected: QUESTIONS } });
+ expect(typeof rc.via_operation_summary.tree).toBe('string');
+ expect(rc.via_operation_summary.latency_ms.p50).toBeGreaterThanOrEqual(0);
+ expect(rc.via_operation_summary.latency_ms.p95).toBeGreaterThanOrEqual(rc.via_operation_summary.latency_ms.p50);
+ expect(rc.via_operation_summary.model_calls_per_query.embedding).toBeGreaterThanOrEqual(1);
+ expect(rc.retrieval_config_hash).not.toBe(direct.summary.run_config.retrieval_config_hash);
+ expect(direct.summary.run_config.via_operation).toBeUndefined();
+ expect(direct.rows.every(r => !('via_operation' in r))).toBe(true);
+ }, 120_000);
+
+ test('query under balanced: the mode decides, so nothing expands; the CRAG grade is recorded', async () => {
+ expansionTransport('variants');
+ const via = await run(['--via-operation', 'query', '--mode', 'balanced']);
+ expect(via.failed).toBe(false);
+ expect(expansionCalls).toBe(0);
+ expect(via.summary.run_config.expansion).toBe(false);
+ for (const row of via.rows) {
+ expect(row.via_operation).toMatchObject({ op: 'query', expand: null, expansion: { expected: false, outcome: 'not_expected' } });
+ expect(typeof row.via_operation.crag_confidence).toBe('string');
+ expect(row.search_meta.expansion_applied).toBe(false);
+ }
+ expect(Object.values(via.summary.run_config.via_operation_summary.crag_confidence).reduce((a: number, b) => a + (b as number), 0)).toBe(QUESTIONS);
+ }, 120_000);
+
+ test('query --op-expand on: every question expands once and the run passes', async () => {
+ expansionTransport('variants');
+ const via = await run(['--via-operation', 'query', '--mode', 'balanced', '--op-expand', 'on']);
+ expect(via.failed).toBe(false);
+ expect(expansionCalls).toBe(QUESTIONS);
+ expect(via.summary.run_config.expansion).toBe(true);
+ expect(via.summary.run_config.via_operation.expand).toBe(true);
+ for (const row of via.rows) {
+ expect(row.via_operation).toMatchObject({ expand: true, expansion: { expected: true, outcome: 'applied' } });
+ expect(row.via_operation.model_calls.expansion).toBe(1);
+ expect(row.search_meta.expansion_applied).toBe(true);
+ }
+ expect(via.summary.run_config.via_operation_summary.model_calls_per_query.expansion).toBe(1);
+ }, 120_000);
+
+ test('query under tokenmax with no --op-expand: the mode turns expansion on', async () => {
+ expansionTransport('variants');
+ const via = await run(['--via-operation', 'query', '--mode', 'tokenmax', ...NO_SYNOPSIS]);
+ expect(via.failed).toBe(false);
+ expect(expansionCalls).toBe(QUESTIONS);
+ expect(via.summary.run_config.expansion).toBe(true);
+ expect(via.rows.every(r => r.via_operation.expansion.outcome === 'applied')).toBe(true);
+ }, 120_000);
+
+ test('a throwing expansion provider invalidates the arm: every row says failed and the run fails', async () => {
+ expansionTransport('throw');
+ const via = await run(['--via-operation', 'query', '--mode', 'balanced', '--op-expand', 'on']);
+ expect(via.failed).toBe(true);
+ expect(expansionCalls).toBeGreaterThanOrEqual(QUESTIONS);
+ for (const row of via.rows) {
+ expect(row.via_operation.expansion).toEqual({ expected: true, outcome: 'failed' });
+ expect(row.search_meta.degraded.map((d: { stage: string }) => d.stage)).toContain('expansion_not_applied');
+ }
+ expect(via.summary.run_config.expansion_failed_rows).toBe(QUESTIONS);
+ expect(via.err).toContain(`FAIL --via-operation query (expansion expected): ${QUESTIONS} row(s) did not expand`);
+ }, 120_000);
+
+ test('--op-expand off under tokenmax skips expansion', async () => {
+ expansionTransport('variants');
+ const via = await run(['--via-operation', 'query', '--mode', 'tokenmax', ...NO_SYNOPSIS, '--op-expand', 'off']);
+ expect(via.failed).toBe(false);
+ expect(expansionCalls).toBe(0);
+ expect(via.rows.every(r => r.via_operation.expand === false && r.via_operation.expansion.outcome === 'not_expected')).toBe(true);
+ }, 120_000);
+
+ test('flags the via-operation path would ignore are refused', async () => {
+ const refused = async (args: string[]) => {
+ const engine = await createBenchmarkBrain();
+ try {
+ return await runEvalLongMemEval([FIXTURE, '--retrieval-only', ...args], { engine, exitOnError: false }).then(() => 'ran', (e: Error) => e.message);
+ } finally { await engine.disconnect(); }
+ };
+ const write = process.stderr.write.bind(process.stderr);
+ let err = '';
+ process.stderr.write = ((s: string) => { err += s; return true; }) as typeof process.stderr.write;
+ try {
+ for (const args of [['--op-expand', 'on'], ['--via-operation', 'search', '--op-expand', 'on'], ['--via-operation', 'query', '--expansion'], ['--via-operation', 'query', '--keyword-only'], ['--via-operation', 'think']]) {
+ expect(await refused(args)).not.toBe('ran');
+ }
+ } finally { process.stderr.write = write; }
+ expect(err).toContain('--op-expand needs --via-operation query');
+ expect(err).toContain('--op-expand applies to --via-operation query only');
+ expect(err).toContain('--via-operation cannot be combined with --expansion');
+ expect(err).toContain('--via-operation cannot be combined with --keyword-only');
+ expect(err).toContain('--via-operation must be query|search');
+ }, 120_000);
+});