Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(eval): one gateway bootstrap (configureEvalGateway) for eval runners that bring their own brain
garrytanb57e28c7af81
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex 16e19c7d5e..a98ea987a8 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -49,4 +49,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/eval/shared/embed-cache.ts` — content-addressed embedding cache for fixed-corpus evals (dataset-agnostic; the LongMemEval harness is its first consumer). INVARIANT: a cached vector is served ONLY for the exact `(model@dims, text, side)` it was computed for, and every row is integrity-checked on read (declared dims == stored bytes / 4 == vector length); a mismatch is a HARD `EmbedCacheIntegrityError` naming the file and the key — never a silent re-embed, because a silently corrupted cache makes every arm's vectors non-comparable. Key = `${model}@${dims}` (+ `#query` for query-side asymmetric embeds, so asymmetric query vectors can never be served a document-side row) + `:` + sha256(text). Storage: `bun:sqlite`, WAL journal + `synchronous=NORMAL`, busy retry; local filesystem only. A question's writes are buffered in memory (reads see them) and written in one short `BEGIN IMMEDIATE` transaction when its `withTransaction` unit ends, so no SQLite lock is held across embed round-trips and concurrent runs sharing one cache file neither lose writes to `SQLITE_BUSY_SNAPSHOT` nor stall behind each other's questions. `installEmbedCache` installs it through the gateway's `__setEmbedTransportForTests` seam (gateway.ts sits at its module-size ceiling; a named `setEmbedTransport()` hook is a filed follow-up) and restores the caller-supplied `realTransport ?? null` on uninstall. Stats: `hits`, `misses` (genuine misses PLUS every value of a batch that fell open on an infrastructure fault), `bypassed` (SDK model id ≠ the installed model — never cached), `infra_faults` (file deleted mid-run / table dropped / disk error → uncached re-embed or lost write-back, so a run that lost its cache can never show a clean `misses: 0`). The canonical hash (`PRAGMA wal_checkpoint(TRUNCATE)` then sha256 over the sorted `(key, dims, sha256(vector))` rows) goes into `run_config.cache.canonical_sha256` so two runs can prove they saw the same vectors. Pinned by `test/longmemeval-embed-cache.test.ts`.+- `src/eval/shared/gateway-bootstrap.ts` — `configureEvalGateway({ chatModel? })`, the one AI-gateway bootstrap for eval runners that bring their own brain instead of calling `connectEngine`: `configureGateway(buildGatewayConfig(loadConfig() ?? env))`, where env supplies `GBRAIN_EMBEDDING_MODEL` / `GBRAIN_EMBEDDING_DIMENSIONS` and provider keys fold from both planes. `chatModel` fills in only when the brain configures no `chat_model`. Consumers: the `gbrain eval longmemeval` branch of cli.ts, `scripts/r1-namedthing-rerank-ab.ts`, `scripts/lme-miss-diagnostics.ts`, `scripts/eval-answer-packet.ts`, `evals/functional-area-resolver/harness-runner.ts` and `evals/takes-bootstrap/harness.mjs`.+- `src/eval/shared/judge-runner.ts` + `src/eval/shared/bootstrap.ts` — dataset-agnostic judge mechanics shared by the LongMemEval lane and any later judged eval. **judge-runner.ts** owns the chat-client seam (`JudgeChatFn` — the gateway `chat` in production, a canned fn in tests), bounded retries with exponential backoff (default 2 retries, base 500 ms, `sleep` seam), the closed `judge_error` vocabulary (`timeout | rate_limit | empty | refusal | malformed | provider_error`, exported as `JUDGE_ERROR_CLASSES`), usage summed over every attempt, per-call cost through the ONE canonical pricing table (`canonicalLookup`; an unpriced model yields `cost_usd: null`, never 0, and `isJudgeModelPriced` lets a budget refuse it), and the `BudgetLedger` (`maxUsd === null` = no cap; `canAfford(next)` is PROJECTED so a run never overshoots by more than the calls already in flight; unpriced calls are counted, not summed; `snapshot()` for receipts). INVARIANT: a judge malfunction is an error outcome, never a `verdict: 'incorrect'` — `runJudge` never throws on a transport failure (only an already-aborted `AbortSignal` or a bug in the caller's `parse` can), classifies 429 / rate-limit prose → `rate_limit`, abort / timeout → `timeout`, everything else → `provider_error`, and maps a `refusal` / `content_filter` stop, an empty completion and a null from `parse` to `refusal` / `empty` / `malformed`; the caller decides how the headline scores them. It passes `temperature` and `maxTokens` through `ChatOpts` and records `ChatResult.responseModel` as `response_model`. **bootstrap.ts**: `bootstrapMeanCi(xs, {resamples = 10000, seed = 42, alpha = 0.05})` is a seeded (mulberry32) percentile bootstrap of the mean, byte-reproducible; n = 0 → nulls, n = 1 → a degenerate `[x, x]`. INVARIANT: every block carries `label: 'question-sampling only'` — the interval quantifies how much the number would move under a different draw of questions and says nothing about reader / judge nondeterminism, dataset revision or prompt drift. Pinned by `test/longmemeval-judge.test.ts`.diff --git a/evals/functional-area-resolver/harness-runner.ts b/evals/functional-area-resolver/harness-runner.tsindex 6fadff510d..b92222346f 100644--- a/evals/functional-area-resolver/harness-runner.ts+++ b/evals/functional-area-resolver/harness-runner.ts@@ -25,8 +25,8 @@ import { fileURLToPath } from 'node:url';import { createHash } from 'node:crypto';import { execSync } from 'node:child_process';-import { configureGateway, chat } from '../../src/core/ai/gateway.ts';-import { loadConfig } from '../../src/core/config.ts';+import { chat } from '../../src/core/ai/gateway.ts';+import { configureEvalGateway } from '../../src/eval/shared/gateway-bootstrap.ts';import { ANTHROPIC_PRICING } from '../../src/core/anthropic-pricing.ts';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -406,18 +406,7 @@ export async function main(argv: string[]): Promise<number> {const { full: modelFull, bare: modelBare } = resolveModel(args.model);- // Self-configure the gateway (matches src/commands/eval-cross-modal.ts:195-220).- const config = loadConfig();- configureGateway({- embedding_model: config?.embedding_model,- embedding_dimensions: config?.embedding_dimensions,- expansion_model: config?.expansion_model,- chat_model: config?.chat_model ?? modelFull,- chat_fallback_chain: config?.chat_fallback_chain,- base_urls: config?.provider_base_urls,- provider_chat_options: config?.provider_chat_options,- env: { ...process.env } as Record<string, string>,- });+ configureEvalGateway({ chatModel: modelFull });// Provider-aware auth check (codex review P2-3). The CLI advertises full// provider:model support and the test suite covers `openai:gpt-4o`, so thediff --git a/scripts/eval-answer-packet.ts b/scripts/eval-answer-packet.tsindex 52b8d6d161..2784d36e05 100644--- a/scripts/eval-answer-packet.ts+++ b/scripts/eval-answer-packet.ts@@ -1,6 +1,6 @@import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';import { join, resolve } from 'node:path';-import { chat, configureGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';+import { chat, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';import { withAIInvocationGuard, type AIInvocationUsage } from '../src/core/ai/invocation-guard.ts';import { BudgetTracker } from '../src/core/budget/budget-tracker.ts';import { canonicalLookup } from '../src/core/model-pricing.ts';@@ -10,6 +10,7 @@ import { buildReaderUserText, READER_SYSTEM_TEXT, READER_MAX_TOKENS, READER_MAX_import { sanitizeChatContent } from '../src/eval/longmemeval/sanitize.ts';import { buildJudgePrompt, classifyJudgeResponse, DEFAULT_JUDGE_MODEL, JUDGE_MAX_TOKENS, JUDGE_TEMPERATURE } from '../src/eval/longmemeval/judge.ts';import { runJudge } from '../src/eval/shared/judge-runner.ts';+import { configureEvalGateway } from '../src/eval/shared/gateway-bootstrap.ts';import { bootstrapMeanCi } from '../src/eval/shared/bootstrap.ts';import { redactSecrets, sha256Hex, stableStringify } from '../src/eval/longmemeval/run-config.ts';@@ -300,7 +301,7 @@ async function main(args: string[]) {if (frozen.variant !== variant || frozen.manifest_sha !== sha256Hex(stableStringify(pins))) throw new Error('Holdout differs from frozen algorithm');}if (!process.env.ANTHROPIC_API_KEY || !process.env.OPENAI_API_KEY) throw new Error('Both reader and judge credentials are required');- configureGateway({ env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, OPENAI_API_KEY: process.env.OPENAI_API_KEY } });+ configureEvalGateway();appendRecord(journal, { event: 'phase_start', phase, variant, timestamp: new Date().toISOString() });for (const [index, id] of cohorts[phase].entries()) {if (readRecords(pairsPath).some(r => r.phase === phase && r.variant === variant && r.question_id === id)) continue;diff --git a/scripts/lme-miss-diagnostics.ts b/scripts/lme-miss-diagnostics.tsindex 1443bfd195..4a6b6f016f 100644--- a/scripts/lme-miss-diagnostics.ts+++ b/scripts/lme-miss-diagnostics.ts@@ -33,11 +33,9 @@import { existsSync, readFileSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';import { join } from 'node:path';-import { buildGatewayConfig } from '../src/core/ai/build-gateway-config.ts';-import { configureGateway, getEmbeddingDimensions, getEmbeddingModel, isAvailable } from '../src/core/ai/gateway.ts';+import { getEmbeddingDimensions, getEmbeddingModel, isAvailable } from '../src/core/ai/gateway.ts';import { rerankerReadinessForEngine } from '../src/core/ai/reranker-readiness-engine.ts';import { describeRerankerFix } from '../src/core/ai/reranker-readiness.ts';-import { loadConfig, type GBrainConfig } from '../src/core/config.ts';import { isSearchMode, type SearchMode } from '../src/core/search/mode.ts';import type { LongMemEvalQuestion } from '../src/eval/longmemeval/adapter.ts';import {@@ -51,6 +49,7 @@ import {} from '../src/eval/longmemeval/diagnostics.ts';import { withBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';import { loadQuestionIds } from '../src/eval/longmemeval/run-config.ts';+import { configureEvalGateway } from '../src/eval/shared/gateway-bootstrap.ts';const DEFAULT_EMBED_CACHE_PATH = join(homedir(), '.cache', 'gbrain-eval', 'longmemeval-embed.sqlite');@@ -161,13 +160,7 @@ async function main(): Promise<void> {usage(2);}- // Gateway bootstrap — the cli.ts longmemeval path verbatim: ~/.gbrain/config.json- // when present, else env (OPENAI_API_KEY / GBRAIN_EMBEDDING_MODEL / _DIMENSIONS).- const config = loadConfig() ?? ({- embedding_model: process.env.GBRAIN_EMBEDDING_MODEL,- embedding_dimensions: process.env.GBRAIN_EMBEDDING_DIMENSIONS ? Number(process.env.GBRAIN_EMBEDDING_DIMENSIONS) : undefined,- } as GBrainConfig);- configureGateway(buildGatewayConfig(config));+ configureEvalGateway();if (!isAvailable('embedding')) {process.stderr.write('Error: no embedding provider is configured (set OPENAI_API_KEY + GBRAIN_EMBEDDING_MODEL / GBRAIN_EMBEDDING_DIMENSIONS, or a ~/.gbrain/config.json).\n');process.exit(2);diff --git a/scripts/r1-namedthing-rerank-ab.ts b/scripts/r1-namedthing-rerank-ab.tsindex 5308ebd49c..470aa6c87b 100644--- a/scripts/r1-namedthing-rerank-ab.ts+++ b/scripts/r1-namedthing-rerank-ab.ts@@ -67,13 +67,11 @@ import { hybridSearch } from '../src/core/search/hybrid.ts';import {__setEmbedTransportForTests,__setRerankTransportForTests,- configureGateway,embed,getEmbeddingDimensions,getEmbeddingModel,} from '../src/core/ai/gateway.ts';-import { buildGatewayConfig } from '../src/core/ai/build-gateway-config.ts';-import { loadConfig, type GBrainConfig } from '../src/core/config.ts';+import { configureEvalGateway } from '../src/eval/shared/gateway-bootstrap.ts';import { rerankerReadinessForEngine } from '../src/core/ai/reranker-readiness-engine.ts';import { describeRerankerFix, type RerankerReadiness } from '../src/core/ai/reranker-readiness.ts';import { EmbeddingCache, installEmbedCache, type EmbedCacheStats, type InstalledEmbedCache } from '../src/eval/shared/embed-cache.ts';@@ -573,17 +571,6 @@ export function buildOverlay(args: Pick<Args, 'autocut' | 'relationalPin' | 'sea};}-/** Mirror of cli.ts's `eval longmemeval` bootstrap: config file when present, env otherwise. */-function configureGatewayFromEnv(): void {- const config =- loadConfig() ??- ({- embedding_model: process.env.GBRAIN_EMBEDDING_MODEL,- embedding_dimensions: process.env.GBRAIN_EMBEDDING_DIMENSIONS ? Number(process.env.GBRAIN_EMBEDDING_DIMENSIONS) : undefined,- } as GBrainConfig);- configureGateway(buildGatewayConfig(config));-}-async function main(): Promise<void> {const args = parseArgs(process.argv.slice(2));const log = (s: string): void => { process.stderr.write(`[r1] ${s}\n`); };@@ -610,7 +597,7 @@ async function main(): Promise<void> {// The CI gate's stub: embed throws → hybrid falls open to keyword + title + alias.__setEmbedTransportForTests(() => { throw new Error('stub: no embed in R1 dry run'); });} else {- configureGatewayFromEnv();+ configureEvalGateway();embedder = `${getEmbeddingModel()}@${getEmbeddingDimensions()}`;log(`embedder ${embedder}`);if (args.embedCache) {diff --git a/src/cli.ts b/src/cli.tsindex ad39bb129f..3446092a7a 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2154,20 +2154,13 @@ async function routeEngineFreeSubcommands(command: string, args: string[]): Prom// connectEngine here keeps `gbrain eval longmemeval --help` and benchmark// runs working on machines that have no `~/.gbrain/config.json` configured.//- // v0.35.1.1: still need to configureGateway() so the in-memory brain's- // import + hybridSearch can embed via the configured provider. Reads- // ~/.gbrain/config.json when present; falls back to env vars otherwise- // (GBRAIN_EMBEDDING_MODEL / GBRAIN_EMBEDDING_DIMENSIONS).+ // The in-memory brain's import + hybridSearch still embed through the+ // configured provider, so the shared eval gateway bootstrap runs first.if (command === 'eval' && args[0] === 'longmemeval') {const { runEvalLongMemEval } = await import('./commands/eval-longmemeval.ts');if (!(args.length > 1 && (args[1] === '--help' || args[1] === '-h'))) {- const config = loadConfig() ?? ({- embedding_model: process.env.GBRAIN_EMBEDDING_MODEL,- embedding_dimensions: process.env.GBRAIN_EMBEDDING_DIMENSIONS- ? Number(process.env.GBRAIN_EMBEDDING_DIMENSIONS) : undefined,- } as GBrainConfig);- const { configureGateway } = await import('./core/ai/gateway.ts');- configureGateway(buildGatewayConfig(config));+ const { configureEvalGateway } = await import('./eval/shared/gateway-bootstrap.ts');+ configureEvalGateway();}await runEvalLongMemEval(args.slice(1));return true;diff --git a/src/eval/shared/gateway-bootstrap.ts b/src/eval/shared/gateway-bootstrap.tsnew file mode 100644index 0000000000..f666d67d46--- /dev/null+++ b/src/eval/shared/gateway-bootstrap.ts@@ -0,0 +1,24 @@+/**+ * The one AI-gateway bootstrap for eval runners that bring their own brain+ * (in-memory PGLite) instead of going through `connectEngine`.+ *+ * Reads `~/.gbrain/config.json` when present, else the environment+ * (`GBRAIN_EMBEDDING_MODEL` / `GBRAIN_EMBEDDING_DIMENSIONS`), and folds provider+ * keys from both planes through `buildGatewayConfig`, so an eval sees the same+ * models, keys and base URLs the user's brain uses. `chatModel` is the runner's+ * default for brains with no configured `chat_model`; a configured one wins.+ */+import { buildGatewayConfig } from '../../core/ai/build-gateway-config.ts';+import { configureGateway } from '../../core/ai/gateway.ts';+import { loadConfig, type GBrainConfig } from '../../core/config.ts';++export function configureEvalGateway(opts: { chatModel?: string } = {}): void {+ const config = loadConfig() ?? ({+ embedding_model: process.env.GBRAIN_EMBEDDING_MODEL,+ embedding_dimensions: process.env.GBRAIN_EMBEDDING_DIMENSIONS+ ? Number(process.env.GBRAIN_EMBEDDING_DIMENSIONS) : undefined,+ } as GBrainConfig);+ const gateway = buildGatewayConfig(config);+ if (!gateway.chat_model && opts.chatModel) gateway.chat_model = opts.chatModel;+ configureGateway(gateway);+}