Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(eval): via-operation rows record reranked from the rerank call; summary names gbrain's own tree and commit
garrytanca1a330ac4de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f725d704d..c5bb9cb4b0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,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.+- **`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 gbrain tree, commit and dirty flag of the checkout the harness runs from (not the caller's cwd), p50/p95 latency and model calls per query, and a row's `search_meta.reranked` comes from the operation's recorded rerank call. A run that expects expansion fails when any question did not expand.- **Lean search rows drop `id` where `fetch` is not callable.** Remote `search` and `query` lean rows carry `id` (the deep-research `fetch` key, base64 of `source_id` and `slug`, so a duplicate of two fields already in the row) only when `fetch` is callable on the caller's surface at call time. MCP dispatch threads one `isCallable(op)` predicate into `OperationContext`, built from the same check tools/list uses: the stdio session's surface after any `request_tools` widening, the HTTP client's effective surface and scopes under the server ceiling. `fields: "full"`, `mcp.result_rows: full`, gbrain's thin client and the local CLI are unchanged. On the committed Cat 40 Hard transcripts (served on `starter`, 3,169 `search` calls) a keyless replay (`scripts/replay-lean-row-savings.ts`) saves 9.52% of `search` characters on the starter surface and 1.35% on the full surface, where `id` stays and only score rounding applies.- **Lean-row `score` prints 4 significant digits.** Rounding happens only in `leanRow`, so full rows and trusted local callers keep the raw float; RRF-scale scores are small, so fixed decimals would have collapsed them. Two scores print equal only when they agree to 4 significant digits, and order never inverts.- **`fetch` without an id names both routes.** The refusal says to re-run `search` once `fetch` is callable, or to pass the row's slug (accepted when unambiguous in the caller's read scope).diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.tsindex e94dce2998..b4d6b39566 100644--- a/src/commands/eval-longmemeval.ts+++ b/src/commands/eval-longmemeval.ts@@ -741,7 +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')) } : {}),+ ...(opts.viaOp.op ? { via_operation_summary: viaOperation.summarizeViaOperation(st.qaRows as never, viaOperation.gbrainBuild()) } : {}),});/**@@ -1502,7 +1502,7 @@ async function runOneQuestion(...(meta?.autocut ? { autocut: meta.autocut } : {}),};const { rerankerSkipped, vectorDegraded, expansionFailed } = classifyDegradation(searchMeta, { keywordOnly: opts.keywordOnly, expansion: ctx.expectExpansion });- searchMeta.reranked = results.some(r => Number.isFinite(r.rerank_score)) && !rerankerSkipped;+ searchMeta.reranked = (viaRow ? viaOperation.rerankCalled(viaRow) : results.some(r => Number.isFinite(r.rerank_score))) && !rerankerSkipped;const extra: Record<string, unknown> = {...extra0,diff --git a/src/eval/longmemeval/via-operation.ts b/src/eval/longmemeval/via-operation.tsindex ed14cf174d..580986d45d 100644--- a/src/eval/longmemeval/via-operation.ts+++ b/src/eval/longmemeval/via-operation.ts@@ -14,6 +14,7 @@* fails the run like `--expansion`'s `expansion_failed` (the arm is invalid* until a named repair).*/+import { execFileSync } from '../../core/spawn.ts';import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -168,6 +169,19 @@ export async function runViaOperation(};}+/** The operation's agent-facing rows never carry rerank_score, so a via-operation row's recorded rerank call is the evidence it was reranked. */+export function rerankCalled(row: ViaOperationRow): boolean {+ return (row.model_calls.rerank ?? 0) > 0;+}++/** The gbrain checkout this module runs from, not the caller's cwd (a driver may run the harness from another repository). */+export function gbrainBuild(): { tree: string; commit: string; dirty: boolean } {+ const git = (argv: string[], fallback: string) => {+ try { return execFileSync('git', argv, { cwd: join(import.meta.dir, '..', '..', '..'), encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || fallback; } catch { return fallback; }+ };+ return { tree: git(['rev-parse', 'HEAD^{tree}'], 'unknown'), commit: git(['rev-parse', 'HEAD'], 'unknown'), dirty: git(['status', '--porcelain', '--untracked-files=no'], '') !== '' };+}+/** 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`;@@ -179,7 +193,7 @@ function percentile(sorted: number[], p: number): number | null {}/** 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> {+export function summarizeViaOperation(rows: ReadonlyArray<Record<string, unknown>>, build: { tree: string; commit: string; dirty: boolean }): 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> = {};@@ -193,7 +207,9 @@ export function summarizeViaOperation(rows: ReadonlyArray<Record<string, unknown}const perQuery = Object.fromEntries(Object.entries(calls).sort().map(([t, n]) => [t, via.length ? Number((n / via.length).toFixed(3)) : 0]));return {- tree,+ tree: build.tree,+ commit: build.commit,+ dirty: build.dirty,questions: via.length,latency_ms: { p50: percentile(latencies, 0.5), p95: percentile(latencies, 0.95) },model_calls_per_query: perQuery,diff --git a/test/eval-longmemeval-via-operation.serial.test.ts b/test/eval-longmemeval-via-operation.serial.test.tsindex c5382f2a8d..acab37ec0f 100644--- a/test/eval-longmemeval-via-operation.serial.test.ts+++ b/test/eval-longmemeval-via-operation.serial.test.ts@@ -19,7 +19,8 @@ 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 { configureGateway, resetGateway, __clearQueryEmbedCacheForTests, __setEmbedTransportForTests, __setGenerateObjectTransportForTests, __setRerankTransportForTests } from '../src/core/ai/gateway.ts';+import { execFileSync } from 'node:child_process';import type { PGLiteEngine } from '../src/core/pglite-engine.ts';const FIXTURE = join(import.meta.dir, 'fixtures', 'longmemeval-mini.jsonl');@@ -42,7 +43,7 @@ function expansionTransport(behavior: 'variants' | 'throw'): void {}) as never);}-async function run(args: string[]): Promise<{ rows: any[]; summary: any; err: string; failed: boolean }> {+async function run(args: string[], runOpts: Record<string, unknown> = {}): 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.@@ -53,7 +54,7 @@ async function run(args: string[]): Promise<{ rows: any[]; summary: any; err: stprocess.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,+ engine, exitOnError: false, embedTransport, ...runOpts,});} catch (e) {if (!/longmemeval failed/.test((e as Error).message)) {@@ -72,13 +73,14 @@ async function run(args: string[]): Promise<{ rows: any[]; summary: any; err: stbeforeAll(() => {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' },+ env: { OPENAI_API_KEY: 'sk-test', ANTHROPIC_API_KEY: 'sk-ant-test', VOYAGE_API_KEY: 'pa-test' },});__setEmbedTransportForTests(embedTransport);});afterEach(() => {__setGenerateObjectTransportForTests(null);+ __setRerankTransportForTests(null);expansionCalls = 0;});@@ -115,6 +117,35 @@ describe('eval longmemeval --via-operation', () => {expect(direct.rows.every(r => !('via_operation' in r))).toBe(true);}, 120_000);+ test('search with the reranker on: rows record reranked from the operation\'s rerank call, and the summary names gbrain\'s own tree from any cwd', async () => {+ let rerankCalls = 0;+ __setRerankTransportForTests((async (_url: string, init: RequestInit) => {+ rerankCalls++;+ const docs = JSON.parse(String(init.body)).documents as string[];+ const data = docs.map((_, index) => ({ index, relevance_score: 1 - index / (docs.length + 1) }));+ return new Response(JSON.stringify({ data, usage: { total_tokens: docs.length } }), { status: 200, headers: { 'content-type': 'application/json' } });+ }) as never);+ const repo = join(import.meta.dir, '..');+ const cwd = process.cwd();+ process.chdir(tmp);+ let via: Awaited<ReturnType<typeof run>>;+ try {+ via = await run(['--via-operation', 'search', '--mode', 'balanced', '--reranker', 'on'], { rerankerReadiness: async () => ({ plane: 'db', readiness: { ready: true } }) });+ } finally {+ process.chdir(cwd);+ }+ expect(via.failed).toBe(false);+ expect(rerankCalls).toBe(QUESTIONS);+ for (const row of via.rows) {+ expect(row.via_operation.model_calls.rerank).toBe(1);+ expect(row.search_meta.reranked).toBe(true);+ }+ const summary = via.summary.run_config.via_operation_summary;+ expect(summary.tree).toBe(execFileSync('git', ['rev-parse', 'HEAD^{tree}'], { cwd: repo, encoding: 'utf8' }).trim());+ expect(summary.commit).toBe(execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim());+ expect(typeof summary.dirty).toBe('boolean');+ }, 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']);