Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

eval longmemeval: --mode tokenmax builds production per-chunk synopsis vectors

garrytan89ad936a5d69
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 8b1547dd20..9bea697168 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -41,4 +41,4 @@ src/core/bootstrap/harness.ts 2711 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 663 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)
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 1520 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); +2 P6: eval-only retrieval arms wiring (logic in eval/longmemeval/retrieval-arms.ts)
+src/commands/eval-longmemeval.ts 1525 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); +2 P6: eval-only retrieval arms wiring (logic in eval/longmemeval/retrieval-arms.ts); +5 tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)
diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.ts
index ec3ad639dd..35f4ad53a7 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 synopsisTier from '../eval/longmemeval/synopsis-tier.ts';
import { resolveModel } from '../core/model-config.ts';
import type { ThinkLLMClient } from '../core/think/index.ts';
import { createProgress } from '../core/progress.ts';
@@ -213,7 +214,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;
+ decide: decideLane.DecideEvalOptions; evalPoolDepth?: number; arms: retrievalArms.RetrievalArmOptions; synopsis: synopsisTier.SynopsisTierOptions;
}
interface LmeFlag {
@@ -393,7 +394,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,
+ ...retrievalArms.LME_RETRIEVAL_ARM_FLAGS, ...synopsisTier.LME_SYNOPSIS_FLAGS,
];
function parseArgs(args: string[]): ParsedArgs {
@@ -418,7 +419,7 @@ function parseArgs(args: string[]): ParsedArgs {
yes: false,
judgeConcurrency: 1,
allowIncompleteJudgments: false,
- decide: decideLane.newDecideEvalOptions(), arms: retrievalArms.newRetrievalArmOptions(),
+ decide: decideLane.newDecideEvalOptions(), arms: retrievalArms.newRetrievalArmOptions(), synopsis: synopsisTier.newSynopsisTierOptions(),
};
const byName = new Map(LME_FLAGS.map(f => [f.name, f]));
for (let i = 0; i < args.length; i++) {
@@ -552,7 +553,7 @@ interface RunContext {
*/
embedTxn: <T>(fn: () => Promise<T>) => Promise<T>;
decide: decideLane.DecideEvalRun | null;
- factKeys: { arm: retrievalArms.FactKeyArm; spend: retrievalArms.FactKeySpend } | null;
+ factKeys: { arm: retrievalArms.FactKeyArm; spend: retrievalArms.FactKeySpend } | null; synopsis: synopsisTier.SynopsisTier | null;
}
interface QuestionOutcome {
@@ -678,6 +679,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
const trajectoryEnabled = !opts.noTrajectory;
const { pins, knobs } = resolvePins(opts, runOpts, trajectoryEnabled, decideRun);
+ const synopsis = await synopsisTier.resolveSynopsisTier(knobs, opts.keywordOnly, opts.synopsis, pins);
const knobsHashValue = knobsHash(knobs);
// 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.
@@ -767,6 +769,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
const c = st.cacheReceipt;
process.stderr.write(`[longmemeval] embed cache: ${c.hits} hits, ${c.misses} misses, ${c.bypassed} bypassed, ${c.infra_faults} infra fault(s) (canonical ${c.canonical_sha256.slice(0, 12)})\n`);
}
+ if (synopsisTier.reportSynopsisRunEnd(synopsis, st.questionsRun)) exitCode = 1;
const incomplete = st.qaRows.filter(row => typeof row.error === 'string' && String(row.error).startsWith('reader_')).length;
if (incomplete > 0) {
process.stderr.write(`[longmemeval] ${incomplete} incomplete reader completion(s); partial, empty or unknown answers are errors and cannot count as completed.\n`);
@@ -1121,7 +1124,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
const ctx: RunContext = {
opts, model, readerConfig, readerHash, client, trajectoryEnabled, extractorClient, extractorModel, decide: decideRun,
- factKeys: await retrievalArms.resolveFactKeyArm(opts.arms, extractorClient),
+ factKeys: await retrievalArms.resolveFactKeyArm(opts.arms, extractorClient), synopsis,
expandFn: runOpts.expandFn ?? expandQuery,
replay,
retrievalConfigHash: retrievalHash,
@@ -1289,6 +1292,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):
if (process.env.GBRAIN_LME_DEBUG === '1') {
process.stderr.write(`[longmemeval] ${q.question_id} ${Date.now() - qStart}ms\n`);
}
+ if (synopsis?.spend.exhausted()) { synopsis.stoppedAtCap = true; break; }
}
} finally {
await brains.close();
@@ -1422,6 +1426,7 @@ 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.keywordOnly) return engine.searchKeyword(q.question, { limit: opts.topK });
const searchOpts: HybridSearchOpts = {
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index a065002b34..cc35873b31 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -55,7 +55,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', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--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', '--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', '--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'],
'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-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--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', '--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-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index e982d953f8..fb48e054cf 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -288,6 +288,8 @@ export interface ReembedPageArgs {
* calls. Embedding remains one batch after all synopses succeed.
*/
chunkConcurrency?: number;
+ /** @internal Synopsis generator seam (benchmark caching/metering); production callers omit this. */
+ generateSynopsis?: typeof generatePerChunkSynopsis;
}
/**
@@ -625,7 +627,7 @@ async function buildWrappedChunkText(opts: {
}
leaseAcquired = true;
}
- synopsisResult = await generatePerChunkSynopsis({
+ synopsisResult = await (args.generateSynopsis ?? generatePerChunkSynopsis)({
documentText: sourceText,
chunkText: c.chunk_text,
pageTitle: page.title,
diff --git a/src/core/minions/handlers/contextual-reindex-per-chunk.ts b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
index c3b64cb4c7..27832a3ed7 100644
--- a/src/core/minions/handlers/contextual-reindex-per-chunk.ts
+++ b/src/core/minions/handlers/contextual-reindex-per-chunk.ts
@@ -104,7 +104,7 @@ export interface MakeContextualReindexHandlerOpts {
}
export async function resolveContextualSynopsisModel(
- engine: BrainEngine,
+ engine: BrainEngine | null,
explicitModel?: string,
): Promise<string> {
return resolveModel(engine, {
diff --git a/src/core/page-summary.ts b/src/core/page-summary.ts
index e50e052eec..a4370c753f 100644
--- a/src/core/page-summary.ts
+++ b/src/core/page-summary.ts
@@ -139,8 +139,8 @@ export interface GeneratePerChunkSynopsisArgs {
* - failure variants → see D27 P1-2 dispatch in the service layer
*/
export type GeneratePerChunkSynopsisResult =
- | { kind: 'success'; synopsis: string }
- | { kind: SynopsisFailureKind; detail?: string };
+ | { kind: 'success'; synopsis: string; usage?: ChatResult['usage'] }
+ | { kind: SynopsisFailureKind; detail?: string; usage?: ChatResult['usage'] };
/**
* Generate one synopsis for one chunk. ~$0.00006 per call at Haiku 4.5
@@ -206,7 +206,7 @@ export async function generatePerChunkSynopsis(
detail: `stop_reason=${result.stopReason}`,
pageLevelFallback: true,
});
- return { kind: 'refusal', detail: `stop_reason=${result.stopReason}` };
+ return { kind: 'refusal', detail: `stop_reason=${result.stopReason}`, usage: result.usage };
}
// #3883: stop_reason 'length' means the model hit maxTokens mid-sentence —
@@ -224,7 +224,7 @@ export async function generatePerChunkSynopsis(
detail,
pageLevelFallback: true,
});
- return { kind: 'malformed', detail };
+ return { kind: 'malformed', detail, usage: result.usage };
}
const synopsis = sanitizeSynopsis(result.text);
@@ -237,7 +237,7 @@ export async function generatePerChunkSynopsis(
detail: `length=${result.text.length}`,
pageLevelFallback: true,
});
- return { kind: 'empty', detail: `length=${result.text.length}` };
+ return { kind: 'empty', detail: `length=${result.text.length}`, usage: result.usage };
}
// Content-shape malformed detection stays minimal: synopses are plain
@@ -246,7 +246,7 @@ export async function generatePerChunkSynopsis(
// stop_reason==='length' check above, #3883). Future extension could
// parse a JSON-shaped response with `{synopsis, confidence}`.
- return { kind: 'success', synopsis };
+ return { kind: 'success', synopsis, usage: result.usage };
}
function buildUserPrompt(
diff --git a/src/eval/longmemeval/run-config.ts b/src/eval/longmemeval/run-config.ts
index 3938f2a4e6..fde2b6d1c6 100644
--- a/src/eval/longmemeval/run-config.ts
+++ b/src/eval/longmemeval/run-config.ts
@@ -54,6 +54,8 @@ export interface RetrievalPins {
decide?: Record<string, unknown>;
/** Eval-only fact-key / time-scope arms (retrieval-arms.ts). Present only when an arm is on. */
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>;
}
/** Stable JSON: sorted keys at every level so key order can never move the hash. */
@@ -187,6 +189,7 @@ export function buildRunConfig(input: RunConfigInput): Record<string, unknown> {
...(p.search_pins && Object.keys(p.search_pins).length > 0 ? { search_pins: p.search_pins } : {}),
...(p.eval_pool_depth ? { eval_pool_depth: p.eval_pool_depth } : {}),
...(p.decide ? { decide: p.decide } : {}),
+ ...(p.contextual_synopsis ? { contextual_synopsis: p.contextual_synopsis } : {}),
dataset_sha256: input.dataset_sha256,
dataset_questions: input.dataset_questions,
question_ids_file: input.question_ids_file,
diff --git a/src/eval/longmemeval/synopsis-tier.ts b/src/eval/longmemeval/synopsis-tier.ts
new file mode 100644
index 0000000000..e69e39d2e8
--- /dev/null
+++ b/src/eval/longmemeval/synopsis-tier.ts
@@ -0,0 +1,249 @@
+/**
+ * synopsis-tier.ts — makes `gbrain eval longmemeval --mode tokenmax` measure
+ * the vectors production builds for that mode.
+ *
+ * Production imports every page at the free title tier and leaves the
+ * `per_chunk_synopsis` tier to the contextual-reindex backfill, which calls
+ * `reembedPageWithContextualRetrieval` per page with the resolved
+ * contextual-synopsis model. The benchmark imports the same way, so without
+ * this step a tokenmax run scores title-tier vectors. When the resolved mode's
+ * tier is `per_chunk_synopsis`, the harness runs that same service on every
+ * imported session (same model resolution, prompt, page-level fall-back and
+ * guarded install), with two eval-only additions:
+ *
+ * - a content-addressed on-disk synopsis cache keyed by the service's own
+ * cache-key shape (`buildSynopsisCacheKey`), so shards and reruns never
+ * pay twice; only answers the model actually returned are cached;
+ * - a spend meter and cap over uncached synopsis calls, priced from the
+ * provider-reported usage.
+ */
+
+import { createHash } from 'node:crypto';
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { homedir } from 'node:os';
+import type { BrainEngine } from '../../core/engine.ts';
+import {
+ computeCorpusGeneration,
+ computeSourceTextHash,
+ reembedPageWithContextualRetrieval,
+ resolveContextualChunkConcurrency,
+} from '../../core/contextual-retrieval-service.ts';
+import { resolveContextualSynopsisModel } from '../../core/minions/handlers/contextual-reindex-per-chunk.ts';
+import {
+ buildSynopsisCacheKey,
+ generatePerChunkSynopsis,
+ SYNOPSIS_DOC_MAX_CHARS,
+ SYNOPSIS_MAX_TOKENS,
+ SYNOPSIS_PROMPT_VERSION,
+ type GeneratePerChunkSynopsisArgs,
+ type GeneratePerChunkSynopsisResult,
+} from '../../core/page-summary.ts';
+import { canonicalLookup } from '../../core/model-pricing.ts';
+import type { ResolvedSearchKnobs } from '../../core/search/mode.ts';
+import type { RetrievalPins } from './run-config.ts';
+
+const TRANSIENT_ATTEMPTS = 5;
+
+export interface SynopsisTierOptions {
+ maxUsd: number;
+ concurrency: number;
+ cachePath?: string;
+}
+
+export function newSynopsisTierOptions(): SynopsisTierOptions {
+ return { maxUsd: 20, concurrency: 8 };
+}
+
+export const LME_SYNOPSIS_FLAGS: Array<{ name: string; arg?: string; help: string[]; apply: (o: { synopsis: SynopsisTierOptions }, value: string) => void }> = [
+ { name: '--synopsis-max-usd', arg: 'N', help: [
+ 'Spend cap for uncached per-chunk synopses when the resolved mode\'s tier is',
+ 'per_chunk_synopsis (tokenmax; default 20). At the cap the run stops after',
+ 'the current question; cached synopses are free.'],
+ apply: (o, v) => { const n = Number(v); if (!Number.isFinite(n) || n <= 0) throw new Error(`--synopsis-max-usd must be a positive number (got: ${v})`); o.synopsis.maxUsd = n; } },
+ { name: '--synopsis-concurrency', arg: 'N', help: ['Sessions synopsized in parallel per question (default 8; chunks within a session follow GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY).'],
+ apply: (o, v) => { const n = Number(v); if (!Number.isInteger(n) || n < 1 || n > 64) throw new Error(`--synopsis-concurrency must be an integer from 1 to 64 (got: ${v})`); o.synopsis.concurrency = n; } },
+ { name: '--synopsis-cache', arg: 'FILE', help: ['Synopsis cache (JSONL). Default: ~/.cache/gbrain-eval/synopsis-<model>.jsonl.'],
+ apply: (o, v) => { o.synopsis.cachePath = v; } },
+];
+
+export function defaultSynopsisCachePath(model: string): string {
+ return join(homedir(), '.cache', 'gbrain-eval', `synopsis-${model.replace(/[^a-z0-9.-]+/gi, '_')}.jsonl`);
+}
+
+export class SynopsisSpendCapReached extends Error {
+ constructor(readonly maxUsd: number, readonly cachePath: string) {
+ super(`synopsis spend reached its cap ($${maxUsd.toFixed(2)}); raise --synopsis-max-usd or reuse the cache at ${cachePath}`);
+ this.name = 'SynopsisSpendCapReached';
+ }
+}
+
+export class SynopsisSpend {
+ usd = 0;
+ calls = 0;
+ cacheHits = 0;
+ inputTokens = 0;
+ outputTokens = 0;
+ constructor(readonly maxUsd: number) {}
+ add(model: string, usage: { input_tokens?: number; output_tokens?: number } | undefined): number {
+ this.calls++;
+ if (!usage) return 0;
+ this.inputTokens += usage.input_tokens ?? 0;
+ this.outputTokens += usage.output_tokens ?? 0;
+ const p = canonicalLookup(model);
+ if (!p) return 0;
+ const usd = ((usage.input_tokens ?? 0) * p.input + (usage.output_tokens ?? 0) * p.output) / 1_000_000;
+ this.usd += usd;
+ return usd;
+ }
+ exhausted(): boolean {
+ return this.usd >= this.maxUsd;
+ }
+}
+
+type CachedSynopsis = { kind: GeneratePerChunkSynopsisResult['kind']; synopsis?: string; detail?: string };
+
+class SynopsisCache {
+ private readonly map = new Map<string, CachedSynopsis>();
+ constructor(readonly path: string) {
+ if (!existsSync(path)) return;
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
+ if (!line.trim()) continue;
+ try {
+ const row = JSON.parse(line) as { key: string; value: CachedSynopsis };
+ if (row && typeof row.key === 'string' && row.value && typeof row.value.kind === 'string') this.map.set(row.key, row.value);
+ } catch { /* a torn final line is skipped */ }
+ }
+ }
+ get(key: string): CachedSynopsis | undefined { return this.map.get(key); }
+ set(key: string, value: CachedSynopsis): void {
+ this.map.set(key, value);
+ mkdirSync(dirname(this.path), { recursive: true });
+ appendFileSync(this.path, `${JSON.stringify({ key, value })}\n`);
+ }
+}
+
+const caches = new Map<string, SynopsisCache>();
+function cacheFor(path: string): SynopsisCache {
+ let c = caches.get(path);
+ if (!c) { c = new SynopsisCache(path); caches.set(path, c); }
+ return c;
+}
+
+export interface SynopsisTier {
+ model: string;
+ maxTokens: number;
+ cachePath: string;
+ concurrency: number;
+ chunkConcurrency: number;
+ spend: SynopsisSpend;
+ /** Set when the run stopped early because the spend cap was reached. */
+ stoppedAtCap: boolean;
+}
+
+/** Pins folded into retrieval_config_hash for a synopsis-tier run. */
+export function synopsisPins(tier: SynopsisTier): Record<string, unknown> {
+ return { model: tier.model, prompt_version: SYNOPSIS_PROMPT_VERSION, doc_max_chars: SYNOPSIS_DOC_MAX_CHARS, max_tokens: tier.maxTokens };
+}
+
+/**
+ * The synopsis tier for this run, or null when the resolved mode does not
+ * build synopsis vectors (or the run never embeds). The model resolves the
+ * way the production backfill resolves it on a brain with no override, and
+ * its pins join the run's retrieval pins (so retrieval_config_hash covers it).
+ */
+export async function resolveSynopsisTier(knobs: ResolvedSearchKnobs, keywordOnly: boolean, o: SynopsisTierOptions, pins: RetrievalPins): Promise<SynopsisTier | null> {
+ if (keywordOnly || knobs.contextual_retrieval_disabled || knobs.contextual_retrieval !== 'per_chunk_synopsis') return null;
+ const model = await resolveContextualSynopsisModel(null);
+ const tier: SynopsisTier = {
+ model,
+ maxTokens: SYNOPSIS_MAX_TOKENS,
+ cachePath: o.cachePath ?? defaultSynopsisCachePath(model),
+ concurrency: o.concurrency,
+ chunkConcurrency: resolveContextualChunkConcurrency(),
+ spend: new SynopsisSpend(o.maxUsd),
+ stoppedAtCap: false,
+ };
+ pins.contextual_synopsis = synopsisPins(tier);
+ return tier;
+}
+
+/** Run-end stderr lines for the synopsis tier; true when the run stopped at the spend cap (a failed run). */
+export function reportSynopsisRunEnd(tier: SynopsisTier | null, questionsRun: number): boolean {
+ if (!tier || questionsRun === 0) return false;
+ const sp = tier.spend;
+ process.stderr.write(`[longmemeval] synopsis tier: ${tier.model}, ${sp.calls} call(s), ${sp.cacheHits} cache hit(s), ${sp.inputTokens} in / ${sp.outputTokens} out tokens, $${sp.usd.toFixed(4)} (cap $${sp.maxUsd.toFixed(2)}; cache ${tier.cachePath})\n`);
+ if (!tier.stoppedAtCap) return false;
+ process.stderr.write(`[longmemeval] FAIL --synopsis-max-usd: synopsis spend reached $${sp.maxUsd.toFixed(2)}; the run stopped early. Resume with a higher cap (cached synopses are free).\n`);
+ return true;
+}
+
+function cacheKey(args: GeneratePerChunkSynopsisArgs, model: string, maxTokens: number): string {
+ return buildSynopsisCacheKey({
+ contentHash: createHash('sha256').update(`${args.pageTitle}\n${maxTokens}\n${args.chunkText}`).digest('hex'),
+ chunkIndex: args.chunkIndex,
+ corpusGeneration: computeCorpusGeneration({ crMode: 'per_chunk_synopsis', synopsisModel: model, synopsisDocMaxChars: SYNOPSIS_DOC_MAX_CHARS }),
+ sourceTextHash: computeSourceTextHash(args.documentText),
+ });
+}
+
+export interface SynopsisTierResult {
+ pages: number;
+ pages_synopsis: number;
+ pages_fallback: number;
+ chunks: number;
+ calls: number;
+ cache_hits: number;
+ usd: number;
+}
+
+/**
+ * Re-embed every imported session at the synopsis tier through the
+ * production service. A transient provider failure retries with backoff; one
+ * that persists, a permanent failure, or the spend cap fails the question.
+ */
+export async function applySynopsisTier(
+ engine: BrainEngine,
+ pages: ReadonlyArray<{ slug: string }>,
+ tier: SynopsisTier,
+ generate: typeof generatePerChunkSynopsis = generatePerChunkSynopsis,
+): Promise<SynopsisTierResult> {
+ const cache = cacheFor(tier.cachePath);
+ const out: SynopsisTierResult = { pages: pages.length, pages_synopsis: 0, pages_fallback: 0, chunks: 0, calls: 0, cache_hits: 0, usd: 0 };
+ const cachedGenerate: typeof generatePerChunkSynopsis = async (args) => {
+ const key = cacheKey(args, tier.model, tier.maxTokens);
+ const hit = cache.get(key);
+ if (hit) {
+ tier.spend.cacheHits++;
+ out.cache_hits++;
+ return hit.kind === 'success' ? { kind: 'success', synopsis: hit.synopsis ?? '' } : { kind: hit.kind, detail: hit.detail };
+ }
+ if (tier.spend.exhausted()) throw new SynopsisSpendCapReached(tier.spend.maxUsd, tier.cachePath);
+ const res = await generate(args);
+ if (!res.usage) return res;
+ out.calls++;
+ out.usd += tier.spend.add(tier.model, res.usage);
+ cache.set(key, res.kind === 'success' ? { kind: 'success', synopsis: res.synopsis } : { kind: res.kind, detail: res.detail });
+ return res;
+ };
+ const queue = [...pages];
+ await Promise.all(Array.from({ length: Math.min(tier.concurrency, queue.length) }, async () => {
+ for (let page = queue.shift(); page; page = queue.shift()) {
+ for (let attempt = 1; ; attempt++) {
+ const r = await reembedPageWithContextualRetrieval({
+ engine, pageSlug: page.slug, sourceId: 'default', globalMode: 'per_chunk_synopsis',
+ synopsisModel: tier.model, synopsisMaxTokens: tier.maxTokens, chunkConcurrency: tier.chunkConcurrency, generateSynopsis: cachedGenerate,
+ });
+ if (r.kind === 'success') { out.pages_synopsis++; out.chunks += r.chunks_embedded; break; }
+ if (r.kind === 'page_fallback') { out.pages_fallback++; out.chunks += r.chunks_embedded; break; }
+ if (r.kind === 'skipped') break;
+ if (r.kind === 'transient_error' && attempt < TRANSIENT_ATTEMPTS) {
+ await new Promise(res => setTimeout(res, 1000 * 2 ** attempt));
+ continue;
+ }
+ throw new Error(`synopsis tier ${r.kind} for ${page.slug} (${r.cause}): ${r.detail}`);
+ }
+ }
+ }));
+ return out;
+}
diff --git a/test/eval-longmemeval-synopsis-tier.serial.test.ts b/test/eval-longmemeval-synopsis-tier.serial.test.ts
new file mode 100644
index 0000000000..85b07c59a2
--- /dev/null
+++ b/test/eval-longmemeval-synopsis-tier.serial.test.ts
@@ -0,0 +1,120 @@
+/**
+ * `gbrain eval longmemeval --mode tokenmax` builds the per-chunk synopsis
+ * vectors production builds for that mode (fake chat + embed transports; no
+ * provider is called).
+ *
+ * Protects: a tokenmax run re-embeds every imported session through the
+ * production contextual-retrieval service, so the embedded inputs carry the
+ * generated synopsis and each row reports the tier it built; the synopsis
+ * model folds into run_config and retrieval_config_hash; balanced makes no
+ * synopsis call; a rerun is served from the on-disk synopsis cache with no
+ * chat call; the spend cap stops the run after the question that reached it
+ * and fails the run.
+ * Serial: mutates the process-global gateway, its transports and an env var.
+ */
+import { afterAll, beforeAll, beforeEach, 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, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+
+const FIXTURE = join(import.meta.dir, 'fixtures', 'longmemeval-mini.jsonl');
+const DIMS = 1536;
+const MODEL = 'anthropic:claude-haiku-4-5-20251001';
+const tmp = mkdtempSync(join(tmpdir(), 'lme-synopsis-'));
+const prevModelEnv = process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL;
+
+let embedInputs: string[] = [];
+let chatModels: string[] = [];
+const embedTransport = (async (p: { values: string[] }) => {
+ embedInputs.push(...p.values);
+ return { 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];
+
+async function run(args: string[]): Promise<{ rows: any[]; summary: any; err: string; threw: boolean }> {
+ const out = join(tmp, `out-${Math.random().toString(36).slice(2)}.jsonl`);
+ const engine = await createBenchmarkBrain();
+ const write = process.stderr.write.bind(process.stderr);
+ let err = '';
+ let threw = 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 {
+ threw = true;
+ } finally {
+ 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, threw };
+}
+
+beforeAll(() => {
+ process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL = MODEL;
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests(embedTransport);
+ __setChatTransportForTests(async (opts) => {
+ chatModels.push(String(opts.model));
+ const user = String(opts.messages[0]?.content ?? '');
+ const chunk = user.slice(user.indexOf('<chunk>') + 8, user.indexOf('</chunk>')).trim();
+ return {
+ text: `Synopsis: ${chunk.split(/\s+/).slice(0, 4).join(' ')}`, blocks: [], stopReason: 'end',
+ usage: { input_tokens: 1000, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: MODEL, providerId: 'anthropic',
+ };
+ });
+});
+
+beforeEach(() => { embedInputs = []; chatModels = []; });
+
+afterAll(() => {
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ if (prevModelEnv === undefined) delete process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL;
+ else process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL = prevModelEnv;
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe('eval longmemeval tokenmax synopsis tier', () => {
+ test('tokenmax embeds production synopses, pins the model, and reruns from the cache', async () => {
+ const cache = join(tmp, 'synopsis.jsonl');
+ const balanced = await run(['--mode', 'balanced', '--limit', '2']);
+ expect(chatModels).toHaveLength(0);
+ expect(balanced.rows.every((r) => !('contextual_synopsis' in r))).toBe(true);
+ expect(balanced.summary.run_config.contextual_synopsis).toBeUndefined();
+
+ const tm = await run(['--mode', 'tokenmax', '--limit', '2', '--synopsis-cache', cache]);
+ expect(tm.threw).toBe(false);
+ expect(chatModels.length).toBeGreaterThan(0);
+ expect(new Set(chatModels)).toEqual(new Set([MODEL]));
+ expect(embedInputs.some((t) => /^<context>[^\n]*\nSynopsis: /.test(t))).toBe(true);
+ for (const r of tm.rows) {
+ expect(r.contextual_synopsis.pages).toBeGreaterThan(0);
+ expect(r.contextual_synopsis.pages_synopsis).toBe(r.contextual_synopsis.pages);
+ expect(r.contextual_synopsis.calls).toBe(r.contextual_synopsis.chunks);
+ expect(r.contextual_synopsis.usd).toBeCloseTo(r.contextual_synopsis.calls * 0.0011, 6);
+ }
+ expect(tm.summary.run_config.contextual_synopsis).toMatchObject({ model: MODEL, prompt_version: 1, max_tokens: 200 });
+ expect(tm.rows[0].retrieval_config_hash).not.toBe(balanced.rows[0].retrieval_config_hash);
+ expect(tm.err).toContain('[longmemeval] synopsis tier:');
+
+ chatModels = [];
+ const again = await run(['--mode', 'tokenmax', '--limit', '2', '--synopsis-cache', cache]);
+ expect(chatModels).toHaveLength(0);
+ expect(again.rows.map((r) => r.contextual_synopsis.cache_hits)).toEqual(tm.rows.map((r) => r.contextual_synopsis.chunks));
+ expect(again.rows.map((r) => r.retrieved_session_ids)).toEqual(tm.rows.map((r) => r.retrieved_session_ids));
+ }, 120_000);
+
+ test('the spend cap stops the run after the question that reached it and fails the run', async () => {
+ const capped = await run(['--mode', 'tokenmax', '--synopsis-max-usd', '0.0005', '--synopsis-concurrency', '1', '--synopsis-cache', join(tmp, 'capped.jsonl')]);
+ expect(capped.threw).toBe(true);
+ expect(capped.rows).toHaveLength(1);
+ expect(String(capped.rows[0].error)).toContain('synopsis spend reached its cap');
+ expect(capped.err).toContain('FAIL --synopsis-max-usd');
+ }, 120_000);
+});