Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(eval): gbrain eval longmemeval --call-plan writes the gstack eval call plan
garrytan98badb4d94d8
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.mdindex dcfa74038f..14aaac0219 100644--- a/docs/architecture/key-files/evaluation.md+++ b/docs/architecture/key-files/evaluation.md@@ -61,6 +61,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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/call-plan.ts` — `gbrain eval longmemeval --call-plan FILE` (`--call-plan-gate CMD`): writes gstack's eval call plan (GSTACK_EVAL_CALLS v1, gstack `docs/eval-calls.md`; `formatEvalCalls` copied from its reference emitter) for the run the other flags describe and exits 0. The command hands over right after flags, pins, mode knobs, models and the question filters resolve — before the resume skip, any client, engine or embed call — so the plan describes the same run. One row per active lane (`expansion`, `embed_doc`, `embed_query`, `rerank`, `trajectory_extract`, `synopsis`, `fact_keys`, `reader`, `judge`; lanes the flags turn off are absent, so `calls` is never 0). Haystacks are chunked offline with the importer's pure functions (`screenImportContent`, `prepareMarkdownChunks` at `resolveMaxChunkTokens()`), so `trajectory_extract` (distinct page contents) and `synopsis` (non-code chunks) counts are exact; reader (the K largest rendered sessions plus a worst-case trajectory block), rerank (the top_n_in largest chunks, each with the query) and judge (a reader-max-tokens hypothesis) inputs are upper bounds. ONE token rule, `ceil(chars / CALL_PLAN_CHARS_PER_TOKEN)` (3), over the real prompt text each lane builds (`buildExpansionPrompt`, `SYNOPSIS_SYSTEM_PROMPT` + `buildPagePrompt`/`buildChunkPrompt`, `EXTRACTOR_SYSTEM_PROMPT`, `paperFactUserPrompt`, `buildReaderUserText`, `buildJudgePrompt`); out_tokens = calls × the per-call cap sent (expansion sends none, so the AI SDK default for claude-haiku-4-5, 64000, is used and any other expansion model refuses). Caches, the resume skip and retries are not subtracted; `--expansion-replay` drops the expansion lane and its file sets the query-embed count. GATE = the command minus `--call-plan`, POSIX-quoted only where needed; HEAD = gbrain's own checkout; a tracked, unmodified dataset / `--question-ids` / replay file is an INPUT line, any other file a PRECONDITION with its sha256 and basename. Preconditions name the token rule, the uncached worst case, each lane's model source and env, and the spend caps. Refuses (exit 1, nothing written; FILE.tmp then rename) on `--decide*` / an inherited `GBRAIN_DECIDE_SLOTS`, `--via-operation`, `search.cross_modal.llm_intent=true` and an unconfigured embedding model. Tests: `test/eval-longmemeval-call-plan.test.ts` (throwing RunOpts seams, local v1 grammar check, lane matrix, GATE round trip, refusals), `test/eval-longmemeval-call-plan.serial.test.ts` (exact counts and token bounds against an instrumented run).- `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.mdindex aa883753cd..1e7c6b5e92 100644--- a/docs/eval-bench.md+++ b/docs/eval-bench.md@@ -605,6 +605,22 @@ gbrain eval longmemeval ~/datasets/longmemeval/longmemeval_s_cleaned.json \# (not bundled): python evaluate_qa.py ~/lme-receipts/judged.ndjson```+### Pricing a run before it starts (`--call-plan`)++`--call-plan FILE` writes gstack's eval call plan (wire format GSTACK_EVAL_CALLS v1)+for the exact run the other flags describe and exits 0, with no provider call and+no brain: one line per active lane (model, calls, input and output tokens, the+per-call output cap), the gate command, the commit, and the preconditions the+numbers rest on. `gstack-eval-plan price-gate` prices it. Counts are exact for the+claim extractor and synopsis lanes and upper bounds elsewhere (reader context =+the K largest sessions of each haystack); caches and retries are not subtracted.+Lanes it cannot bound (`--decide*`, `--via-operation`) refuse.++```bash+gbrain eval longmemeval ~/datasets/longmemeval/longmemeval_s_cleaned.json \+ --mode tokenmax --judge --call-plan ~/lme-receipts/tokenmax-judge.calls+```+### Judged answer accuracy (`--judge`)**Protocol (v0.48.4.0).** Retrieval = the release default (`balanced`,diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 4067ab06e8..62a0d1f8b4 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2075 ratchet grown v0.46.x per-providsrc/commands/extract.ts 2637 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baselinesrc/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codessrc/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)-src/core/ai/gateway.ts 4528 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base)+src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same textsrc/commands/sync.ts 519 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts)src/core/cycle.ts 3303 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts)src/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)@@ -41,7 +41,7 @@ src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVsrc/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 optionsrc/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 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +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); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)-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/eval-longmemeval.ts 1544 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); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)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.tssrc/core/search/evidence-delivery.ts 1537 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); 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 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts)diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 3836a8904f..3f7317adf4 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -162,6 +162,7 @@ test/embedding-rejection-refund.serial.test.ts global-state global-state: procestest/embedding-truth-predicates.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/embedding-zero-norm-4616.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gatewaytest/eval-brainbench-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)+test/eval-longmemeval-call-plan.serial.test.ts R1 R1: mutates process.env (GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL); process-wide gateway transports (__setChatTransportForTests, __setEmbedTransportForTests, __setRerankTransportForTests)test/eval-longmemeval-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)test/eval-longmemeval-synopsis-tier.serial.test.ts R1 R1: mutates process.env (GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL)test/eval-retrieval-quality-decide.serial.test.ts R1 R1: mutates process.env (GBRAIN_DECIDE_SLOTS)diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.tsindex b4d6b39566..3954ada315 100644--- a/src/commands/eval-longmemeval.ts+++ b/src/commands/eval-longmemeval.ts@@ -26,6 +26,9 @@* back committed vectors and never holds the cache write lock across a* network round-trip.* - `LME_FLAGS` drives parsing and help from the same table.+ * - `--call-plan FILE` returns right after the run's flags, pins and models+ * resolve: before the resume skip, any client, engine or embed call+ * (src/eval/longmemeval/call-plan.ts writes the plan).* - `--judge` (Phase D) judges the reader's answer with the official* LongMemEval prompts (src/eval/longmemeval/judge.ts) through the shared* judge runner; a judge malfunction is a `judge_error`, never an@@ -132,6 +135,7 @@ 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 * as callPlan from '../eval/longmemeval/call-plan.ts';import { resolveModel } from '../core/model-config.ts';import type { ThinkLLMClient } from '../core/think/index.ts';import { createProgress } from '../core/progress.ts';@@ -210,6 +214,8 @@ interface ParsedArgs {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; viaOp: viaOperation.ViaOperationOptions;+ /** `--call-plan FILE` / `--call-plan-gate CMD`: write the gstack eval call plan instead of running (src/eval/longmemeval/call-plan.ts). */+ callPlanPath?: string; callPlanGate?: string;}interface LmeFlag {@@ -388,6 +394,13 @@ const LME_FLAGS: LmeFlag[] = ['such a run is NOT publishable (stderr FAIL line + exit 1) — re-run with','--judge --resume-from FILE until all three are 0.'],apply: (o) => { o.allowIncompleteJudgments = true; } },+ { name: '--call-plan', arg: 'FILE', help: [+ 'Write the gstack eval call plan (GSTACK_EVAL_CALLS v1) for the run these',+ 'flags describe to FILE and exit 0: per-lane calls and token bounds, no',+ 'provider call, no brain. A lane it cannot bound refuses (exit 1).'],+ apply: (o, v) => { o.callPlanPath = v; } },+ { name: '--call-plan-gate', arg: 'CMD', help: ['The GSTACK_EVAL_GATE line for --call-plan (default: this command without --call-plan).'],+ apply: (o, v) => { o.callPlanGate = v; } },...decideLane.LME_DECIDE_FLAGS,...retrievalArms.LME_RETRIEVAL_ARM_FLAGS, ...synopsisTier.LME_SYNOPSIS_FLAGS, ...viaOperation.LME_VIA_OPERATION_FLAGS,];@@ -440,6 +453,7 @@ function parseArgs(args: string[]): ParsedArgs {throw new Error('--judge cannot be combined with --retrieval-only (there is no reader hypothesis to judge)');}viaOperation.validateViaOperation(out);+ if (out.callPlanGate !== undefined && !out.callPlanPath) throw new Error('--call-plan-gate needs --call-plan FILE');return out;}@@ -666,9 +680,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):}let decideRun: decideLane.DecideEvalRun | null;try { ({ run: decideRun, questions } = decideLane.prepareLmeDecide(opts, questions)); } catch (err: any) { process.stderr.write(`Error: ${err.message ?? err}\n`); return fail(1); }- if (opts.limit && opts.limit < questions.length) {- questions = questions.slice(0, opts.limit);- }+ if (opts.limit && opts.limit < questions.length) questions = questions.slice(0, opts.limit);if (questions.length === 0) {process.stderr.write(`Error: dataset contains no questions.\n`);fail(1);@@ -692,10 +704,18 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):envVar: 'GBRAIN_MODEL',fallback: 'sonnet',});+ const extractorModel = trajectoryEnabled+ ? await resolveModel(null, {+ cliFlag: runOpts.extractorModel,+ tier: 'utility',+ fallback: 'haiku',+ })+ : '';const readerHash = readerConfigHash(readerConfig, normalizeModelId(model));const judgeHashFor = makeJudgeConfigHasher(opts.judgeModel, { model, prompt_sha: readerConfig.promptSha, max_tokens: readerConfig.maxTokens, k: opts.topK });/** This run's judge_config_hash (live rows; prior rows hash from their own recorded reader pins). */const runJudgeHash = judgeHashFor({});+ if (opts.callPlanPath) return callPlan.runLmeCallPlan({ args, opts, questions, questionByQid, pins, knobs, synopsis, model, extractorModel, readerConfig, decide: decideRun, judgeHashFor }, fail);/** Everything the run-end block needs; filled by the main path or the no-op resume path. */interface RunEndState {@@ -1014,13 +1034,6 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):const gatewayClient: ThinkLLMClient = makeGatewayThinkClient();const client: ThinkLLMClient = runOpts.client ?? gatewayClient;const extractorClient: ThinkLLMClient = runOpts.extractorClient ?? gatewayClient;- const extractorModel = trajectoryEnabled- ? await resolveModel(null, {- cliFlag: runOpts.extractorModel,- tier: 'utility',- fallback: 'haiku',- })- : '';if (runOpts.exitOnError === false) {if (!opts.retrievalOnly && !runOpts.client && !isAvailable('chat', model)) {diff --git a/src/core/ai/expansion-prompt.ts b/src/core/ai/expansion-prompt.tsnew file mode 100644index 0000000000..80dae1fb90--- /dev/null+++ b/src/core/ai/expansion-prompt.ts@@ -0,0 +1,14 @@+/**+ * The query-expansion prompt `gateway.expand()` sends. Peeled from gateway.ts+ * so the eval call planner (src/eval/longmemeval/call-plan.ts) measures the+ * same template text the call sends, without importing the call itself.+ */+export function buildExpansionPrompt(query: string): string {+ return [+ 'Rewrite the search query below into 3-4 different, related queries that would help find relevant documents. Respond with a JSON object in exactly this shape: {"queries": ["rewrite1", "rewrite2", "rewrite3"]}. The JSON key MUST be exactly "queries" (not "rewrites" or any other variation).',+ 'Return ONLY the JSON object. Do NOT include the original query in the result.',+ 'Each rewrite should emphasize different aspects, synonyms, or framings.',+ '',+ `Query: ${query}`,+ ].join('\n');+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 74d5845506..32cb27905f 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -51,6 +51,7 @@ import type {} from './types.ts';import { resolveRecipe, assertTouchpoint, parseModelId, embeddingDimsForModel } from './model-resolver.ts';import { recordChatUsage } from './chat-usage.ts';+import { buildExpansionPrompt } from './expansion-prompt.ts';import {OPENROUTER_CACHE_HEADER,openrouterRequiresExplicitPromptCache,@@ -2494,13 +2495,7 @@ export async function expand(query: string): Promise<string[]> {metadata: { query_chars: query.length },});- const expansionPrompt = [- 'Rewrite the search query below into 3-4 different, related queries that would help find relevant documents. Respond with a JSON object in exactly this shape: {"queries": ["rewrite1", "rewrite2", "rewrite3"]}. The JSON key MUST be exactly "queries" (not "rewrites" or any other variation).',- 'Return ONLY the JSON object. Do NOT include the original query in the result.',- 'Each rewrite should emphasize different aspects, synonyms, or framings.',- '',- `Query: ${query}`,- ].join('\n');+ const expansionPrompt = buildExpansionPrompt(query);// #4121: expand() calls generateObject/generateText directly and never// goes through chat()'s _recordBudget closure, so every expansion LLMdiff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex bd69138a31..357bcedf71 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', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--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', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--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', '--call-plan', '--call-plan-gate', '--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', '--error-unmatch', '--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', '--porcelain', '--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', '--untracked-files', '--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/core/page-summary.ts b/src/core/page-summary.tsindex 838b106081..7e75c38ab4 100644--- a/src/core/page-summary.ts+++ b/src/core/page-summary.ts@@ -92,7 +92,7 @@ export const SYNOPSIS_DOC_MAX_CHARS = (() => {*/export const SYNOPSIS_PROMPT_VERSION = 1;-const SYSTEM_PROMPT = [+export const SYNOPSIS_SYSTEM_PROMPT = ['You generate one-sentence chunk synopses for a personal knowledge brain.','','Given a document (the FULL_DOCUMENT block) and a chunk from it (the CHUNK',@@ -168,7 +168,7 @@ export async function generatePerChunkSynopsis(// #3813: key-aware tier default, not the hardcoded hash anchor above —// an OPENAI_API_KEY-only install must not route to Anthropic.model: args.model ?? resolveTierDefault('utility'),- system: SYSTEM_PROMPT,+ system: SYNOPSIS_SYSTEM_PROMPT,// PR #6341: the title + document block is the only prefix every chunk of// a page shares (the ~190-token system prompt is below every published// minimum cacheable length), so it rides on its own `cache: true` block@@ -262,7 +262,7 @@ export async function generatePerChunkSynopsis(return { kind: 'success', synopsis, usage: result.usage };}-function buildPagePrompt(pageTitle: string, documentText: string): string {+export function buildPagePrompt(pageTitle: string, documentText: string): string {// Tail-truncate `documentText` to `SYNOPSIS_DOC_MAX_CHARS` so small local// chat models don't stall on >100KB pages. Head preserved (title block,// frontmatter, intro paragraphs carry the document-level anchor).@@ -281,7 +281,7 @@ function buildPagePrompt(pageTitle: string, documentText: string): string {].join('\n');}-function buildChunkPrompt(chunkText: string): string {+export function buildChunkPrompt(chunkText: string): string {return ['','<chunk>',diff --git a/src/eval/longmemeval/call-plan.ts b/src/eval/longmemeval/call-plan.tsnew file mode 100644index 0000000000..9b2773edcd--- /dev/null+++ b/src/eval/longmemeval/call-plan.ts@@ -0,0 +1,403 @@+/**+ * call-plan.ts — `gbrain eval longmemeval --call-plan FILE`: writes gstack's+ * eval call plan (wire format GSTACK_EVAL_CALLS v1, gstack docs/eval-calls.md)+ * for the exact run the other flags describe, then exits 0. No provider is+ * called and no brain is opened: the command parses and resolves the run+ * (flags, pins, mode knobs, models, question filters) exactly as a real run+ * does, then hands the result here before any engine or client exists.+ *+ * One row per active lane (purposes from the lane inventory: expansion,+ * embed_doc, embed_query, rerank, trajectory_extract, synopsis, fact_keys,+ * reader, judge). Haystacks are chunked offline with the importer's pure+ * functions, so trajectory_extract and synopsis call counts are exact; every+ * other count is exact or an upper bound, never an estimate below the run.+ * Token counts use ONE rule, `ceil(chars / CALL_PLAN_CHARS_PER_TOKEN)`, on+ * the real prompt text each lane builds. out_tokens = calls × max_out_tokens.+ *+ * INVARIANTS:+ * - A lane the planner cannot bound (`--decide*`, `--via-operation`, an+ * expansion model with no known output default, the LLM intent tie-break)+ * refuses with a message and a non-zero exit; nothing is written.+ * - The file is complete or absent: FILE.tmp is written, then renamed.+ * - Caches and the resume skip are not subtracted (they live outside the+ * repository and cannot be bound to HEAD); `--expansion-replay` turns the+ * expansion lane off, and its file sets the query-embed count.+ */++import { createHash } from 'node:crypto';+import { execFileSync } from '../../core/spawn.ts';+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { basename, isAbsolute, relative, resolve } from 'node:path';+import { haystackToPages } from './adapter.ts';+import { EXTRACTOR_MAX_TOKENS, EXTRACTOR_SYSTEM_PROMPT } from './extract.ts';+import { buildJudgePrompt, JUDGE_MAX_TOKENS } from './judge.ts';+import { selectBackfillRows, type RowLike } from './judge-lane.ts';+import { classifyIntent } from './intent.ts';+import { sessionIdFromSlug } from './metrics.ts';+import { buildReaderUserText, READER_MAX_SESSION_CHARS, type ReaderConfig } from './reader.ts';+import { loadExpansionReplay, readJsonlRows } from './resume.ts';+import { bodyOf, PAPER_FACT_MAX_TOKENS, PAPER_USER_FACT_SYSTEM, paperFactUserPrompt, resolveFactKeyArm, userTurns, type RetrievalArmOptions } from './retrieval-arms.ts';+import type { DatasetQuestion, RetrievalPins } from './run-config.ts';+import { renderChatBlock } from './sanitize.ts';+import type { SynopsisTier, SynopsisTierOptions } from './synopsis-tier.ts';+import type { DecideEvalRun } from '../decide-eval-flags.ts';+import { buildExpansionPrompt } from '../../core/ai/expansion-prompt.ts';+import { embedRequestCeilings, EMBED_MAX_CHARS } from '../../core/ai/embed-batch-plan.ts';+import { getEmbeddingModel, getExpansionModel, thinkingOffOutputCap } from '../../core/ai/gateway.ts';+import { resolveRecipe } from '../../core/ai/model-resolver.ts';+import { observationDateLine } from '../../core/ai/date-grounding.ts';+import { sanitizeText } from '../../core/batch-rows.ts';+import { countCJKAwareWords } from '../../core/cjk.ts';+import { resolveContextualRetrievalMode } from '../../core/contextual-retrieval-resolver.ts';+import { buildContextualPrefix, wrapChunkForEmbedding } from '../../core/embedding-context.ts';+import { resolveMaxChunkTokens } from '../../core/embedding-input-limit.ts';+import { buildExtractorSystem, DEFAULT_EXTRACTION_MAX_TOKENS, MAX_TURN_TEXT_CHARS } from '../../core/facts/extract.ts';+import { screenImportContent } from '../../core/import-screen.ts';+import { prepareMarkdownChunks } from '../../core/markdown-chunks.ts';+import { normalizeModelId } from '../../core/model-id.ts';+import { buildChunkPrompt, buildPagePrompt, SYNOPSIS_SYSTEM_PROMPT } from '../../core/page-summary.ts';+import { capRerankDoc } from '../../core/search/rerank.ts';+import { sanitizeQueryForPrompt } from '../../core/search/expansion.ts';+import type { ResolvedSearchKnobs } from '../../core/search/mode.ts';+import { INJECTION_PATTERNS } from '../../core/think/sanitize.ts';+import { formatTrajectoryBlock } from '../../core/trajectory-format.ts';+import type { ThinkLLMClient } from '../../core/think/index.ts';+import type { ChunkInput } from '../../core/types.ts';++/** The ONE token rule: no provider tokenizer exists in the repo, so every lane counts `ceil(chars / 3)`. */+export const CALL_PLAN_CHARS_PER_TOKEN = 3;+export const planTokens = (text: string): number => Math.ceil(text.length / CALL_PLAN_CHARS_PER_TOKEN);++/** Budget for the structured-output tool block the native expansion path adds (schema + tool-use system text); not in the prompt string. */+export const EXPANSION_TOOL_ALLOWANCE_TOKENS = 1024;+/** Output defaults the AI SDK applies when expansion sends no max_tokens (@ai-sdk/anthropic getModelCapabilities). */+const EXPANSION_DEFAULT_MAX_OUT: ReadonlyArray<{ provider: string; match: string; maxOut: number }> = [+ { provider: 'anthropic', match: 'claude-haiku-4-5', maxOut: 64_000 },+];+const EXPANSION_MAX_VARIANT_CHARS = 500;+/** The longest synopsis the wrapper keeps (embedding-context.ts SUMMARY_HARD_CAP_CHARS). */+const SYNOPSIS_BOUND = 'x'.repeat(300);++const KEYS = ['purpose', 'model', 'calls', 'in_tokens', 'out_tokens', 'max_out_tokens', 'scope'] as const;+export type CallPlanRow = { purpose: string; model: string; calls: number; in_tokens: number; out_tokens: number; max_out_tokens: number; scope: 'full' | 'smoke' };+export interface CallPlan { gate: string; head: string; inputs: { path: string; sha256: string }[]; preconditions: string[]; rows: CallPlanRow[] }++/** gstack's reference emitter (docs/eval-calls.md `formatEvalCalls`), copied. */+export function formatEvalCalls(p: CallPlan): string {+ return [+ '# gstack eval call plan, wire format v1 (docs/eval-calls.md); priced by `gstack-eval-plan price-gate`, never executed',+ `GSTACK_EVAL_GATE v1: ${p.gate}`,+ `GSTACK_EVAL_HEAD v1: ${p.head}`,+ ...p.inputs.map(i => `GSTACK_EVAL_INPUT v1: sha256=${i.sha256} path=${i.path}`),+ ...p.preconditions.map(t => `GSTACK_EVAL_PRECONDITION: ${t}`),+ ...p.rows.map(r => `GSTACK_EVAL_CALLS v1: ${KEYS.map(k => `${k}=${r[k]}`).join(' ')}`),+ `GSTACK_EVAL_CALLS v1 end: lines=${p.rows.length}`,+ ].join('\n') + '\n';+}++/** POSIX shell quoting, applied only when the word needs it. */+export function shellQuote(arg: string): string {+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;+}++/** The gate command: `gbrain eval longmemeval` + argv without `--call-plan FILE` / `--call-plan-gate CMD`. */+export function gateCommand(args: readonly string[]): string {+ const kept: string[] = [];+ for (let i = 0; i < args.length; i++) {+ const a = args[i]!;+ if (a === '--call-plan' || a === '--call-plan-gate') { i++; continue; }+ if (a.startsWith('--call-plan=') || a.startsWith('--call-plan-gate=')) continue;+ kept.push(a);+ }+ return ['gbrain', 'eval', 'longmemeval', ...kept.map(shellQuote)].join(' ');+}++export class CallPlanRefusal extends Error {+ constructor(message: string) { super(message); this.name = 'CallPlanRefusal'; }+}++/** The parsed run (structurally the command's ParsedArgs). */+export interface CallPlanArgs {+ datasetPath?: string;+ questionIdsPath?: string;+ callPlanPath?: string;+ callPlanGate?: string;+ model?: string;+ retrievalOnly: boolean;+ keywordOnly: boolean;+ expansion: boolean;+ expansionReplayPath?: string;+ topK: number;+ noTrajectory: boolean;+ resumeFromPath?: string;+ judge: boolean;+ judgeModel: string;+ maxUsd: number | null;+ arms: RetrievalArmOptions;+ synopsis: SynopsisTierOptions;+ viaOp: { op?: string };+}++export interface LmeCallPlanInput {+ args: readonly string[];+ opts: CallPlanArgs;+ questions: DatasetQuestion[];+ questionByQid: ReadonlyMap<string, DatasetQuestion>;+ pins: RetrievalPins;+ knobs: ResolvedSearchKnobs;+ synopsis: SynopsisTier | null;+ model: string;+ extractorModel: string;+ readerConfig: ReaderConfig;+ decide: DecideEvalRun | null;+ judgeHashFor: (row: RowLike) => string;+}++interface PlannedPage { slug: string; content: string; date?: string; title: string; chunks: ChunkInput[] }++const NO_CLIENT: ThinkLLMClient = { create: async () => { throw new Error('call plan: no provider call is allowed'); } } as unknown as ThinkLLMClient;++function git(root: string, argv: string[]): Buffer {+ return execFileSync('git', ['-C', root, ...argv], { stdio: ['ignore', 'pipe', 'ignore'] });+}++function envState(names: string[]): string {+ return names.map(n => `${n} ${process.env[n]?.trim() ? 'set' : 'unset'}`).join(', ');+}++/** An INPUT line for a tracked, unmodified repo file; otherwise a PRECONDITION with its sha256 and basename. */+function bindInput(root: string, path: string, label: string, plan: CallPlan): void {+ const abs = resolve(path);+ const rel = relative(root, abs);+ if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {+ try {+ git(root, ['ls-files', '--error-unmatch', '--', rel]);+ git(root, ['diff', '--quiet', 'HEAD', '--', rel]);+ plan.inputs.push({ path: rel.split('\\').join('/'), sha256: createHash('sha256').update(git(root, ['cat-file', 'blob', `HEAD:${rel}`])).digest('hex') });+ return;+ } catch { /* untracked or modified: not bindable */ }+ }+ const sha = createHash('sha256').update(readFileSync(abs)).digest('hex');+ plan.preconditions.push(`${label} ${basename(abs)} sha256=${sha} is not a tracked unmodified file of this repository, so it is not bound to HEAD; the run must read these bytes`);+}++async function planPages(q: DatasetQuestion, maxTokens: number): Promise<PlannedPage[]> {+ const dates = q.haystack_dates ?? [];+ return Promise.all(haystackToPages(q).map(async (p, i) => {+ const screen = screenImportContent({ content: p.content, path: `${p.slug}.md`, fences: 'lenient' });+ if (screen.status !== 'importable' || !screen.parsed) return { ...p, date: dates[i], title: '', chunks: [] };+ const parsed = screen.parsed;+ const body = screen.fences?.fixes.length ? screen.fences.after : { compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '' };+ const chunks = await prepareMarkdownChunks({ compiled_truth: sanitizeText(body.compiled_truth), timeline: sanitizeText(body.timeline), frontmatter: parsed.frontmatter }, maxTokens);+ return { ...p, date: dates[i], title: sanitizeText(parsed.title), chunks };+ }));+}++/** Requests and input tokens `embedBatch(texts)` sends (100-text slices, then the gateway's request plan). */+function embedCost(texts: string[], model: string): { calls: number; tokens: number } {+ const envCap = parseInt(process.env.GBRAIN_EMBED_MAX_BATCH_TOKENS ?? '', 10);+ let calls = 0;+ let tokens = 0;+ for (let i = 0; i < texts.length; i += 100) {+ const slice = texts.slice(i, i + 100).map(t => t.slice(0, EMBED_MAX_CHARS));+ calls += embedRequestCeilings(slice, model, Number.isFinite(envCap) && envCap > 0 ? envCap : undefined).length;+ tokens += slice.reduce((s, t) => s + planTokens(t), 0);+ }+ return { calls, tokens };+}++/** The largest trajectory block the reader can see: 100 one-row groups, every field at its assumed cap. */+function trajectoryBlockBound(): string {+ const field = 'x'.repeat(64);+ const points = Array.from({ length: 100 }, (_, i) => ({+ fact_id: i, valid_from: new Date('2000-01-01T00:00:00Z'), metric: `${field}${i}`, value: -1.2345678901234567e-300, unit: field, period: field,+ event_type: null, text: 'x'.repeat(600), source_session: null, source_markdown_slug: `chat/s-${'0'.repeat(10)}`, embedding: null,+ }));+ return formatTrajectoryBlock(points, `${field}/${field}`, { intent: 'knowledge_update' }).rendered;+}++export async function buildLmeCallPlan(input: LmeCallPlanInput): Promise<CallPlan> {+ const { opts, questions, pins, knobs, synopsis, readerConfig } = input;+ if (input.decide) throw new CallPlanRefusal('--call-plan cannot bound the decide lane (--decide or an inherited GBRAIN_DECIDE_SLOTS): its TypeSafe request shape is not inventoried; plan the run without decide slots');+ if (opts.viaOp.op) throw new CallPlanRefusal('--call-plan cannot bound --via-operation: the operation\'s own expansion, embed and rerank calls are not inventoried');+ if (!opts.keywordOnly && knobs.cross_modal_llm_intent) throw new CallPlanRefusal('--call-plan cannot bound search.cross_modal.llm_intent=true (an LLM intent tie-break per ambiguous question); plan with it off');+ const root = (() => {+ try { return git(import.meta.dir, ['rev-parse', '--show-toplevel']).toString().trim(); } catch { throw new CallPlanRefusal('--call-plan needs gbrain running from a git checkout (GSTACK_EVAL_HEAD binds the plan to a commit)'); }+ })();+ const plan: CallPlan = {+ gate: opts.callPlanGate ?? gateCommand(input.args),+ head: git(root, ['rev-parse', 'HEAD']).toString().trim(),+ inputs: [], preconditions: [], rows: [],+ };+ if (/[\r\n]/.test(plan.gate)) throw new CallPlanRefusal('--call-plan-gate must be one line');+ bindInput(root, opts.datasetPath!, 'dataset', plan);+ if (opts.questionIdsPath) bindInput(root, opts.questionIdsPath, '--question-ids file', plan);+ const replay = opts.expansion && !opts.keywordOnly && opts.expansionReplayPath ? loadExpansionReplay(opts.expansionReplayPath) : null;+ if (replay) bindInput(root, opts.expansionReplayPath!, '--expansion-replay file', plan);++ const rows = new Map<string, CallPlanRow>();+ const add = (purpose: string, model: string, calls: number, inTokens: number, maxOut: number): void => {+ if (calls === 0) return;+ if (/\s/.test(model) || !model) throw new CallPlanRefusal(`--call-plan: lane ${purpose} resolved an unusable model id "${model}"`);+ const r = rows.get(purpose) ?? { purpose, model, calls: 0, in_tokens: 0, out_tokens: 0, max_out_tokens: maxOut, scope: 'full' as const };+ r.calls += calls; r.in_tokens += inTokens; r.out_tokens += calls * maxOut;+ rows.set(purpose, r);+ };++ const embeds = !opts.keywordOnly;+ const factArm = await resolveFactKeyArm(opts.arms, NO_CLIENT);+ const embedModel = embeds || factArm ? (() => { try { return getEmbeddingModel(); } catch { throw new CallPlanRefusal('--call-plan: no embedding model is configured (embedding_model in ~/.gbrain/config.json or GBRAIN_EMBEDDING_MODEL); pass --keyword-only without --fact-keys, or configure one'); } })() : '';+ const maxChunkTokens = resolveMaxChunkTokens();+ const importTitleTier = resolveContextualRetrievalMode({ pageFrontmatter: {}, source: { id: 'default', contextual_retrieval_mode: null, trust_frontmatter_overrides: false },+ globalMode: knobs.contextual_retrieval, killSwitchDisabled: knobs.contextual_retrieval_disabled }).mode !== 'none';+ const expansionLive = opts.expansion && !opts.keywordOnly && !replay;+ let expansionMaxOut = 0;+ const expansionModel = expansionLive ? getExpansionModel() : '';+ if (expansionLive) {+ const { parsed } = resolveRecipe(expansionModel);+ const hit = EXPANSION_DEFAULT_MAX_OUT.find(d => d.provider === parsed.providerId && parsed.modelId.includes(d.match));+ if (!hit) throw new CallPlanRefusal(`--call-plan cannot bound expansion on ${expansionModel}: expansion sends no max_tokens and the provider's output default for that model is not known to the planner; use expansion_model anthropic:claude-haiku-4-5-20251001 or --expansion-replay FILE`);+ expansionMaxOut = hit.maxOut;+ }+ const topNIn = Math.max(knobs.reranker_top_n_in, knobs.diverse_pool_depth);+ const readerModel = normalizeModelId(input.model);+ const trajectoryBound = trajectoryBlockBound();+ const seenExtract = new Set<string>();+ const seenFactBodies = new Set<string>();+ let readerTrajectoryQuestions = 0;++ for (const q of questions) {+ const pages = await planPages(q, maxChunkTokens);+ const question = q.question;+ if (embeds) {+ for (const p of pages) {+ const prefix = importTitleTier ? buildContextualPrefix(p.title, null) : null;+ const doc = embedCost(p.chunks.map(c => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source)), embedModel);+ add('embed_doc', embedModel, doc.calls, doc.tokens, 0);+ if (synopsis && p.chunks.length > 0) {+ const synopsisPrefix = buildContextualPrefix(p.title, SYNOPSIS_BOUND);+ const re = embedCost(p.chunks.map(c => wrapChunkForEmbedding(c.chunk_text, synopsisPrefix, c.chunk_source)), embedModel);+ add('embed_doc', embedModel, re.calls, re.tokens, 0);+ }+ }+ const variants = replay+ ? [question, ...new Set((replay.get(q.question_id) ?? []).filter(v => v !== question))]+ : expansionLive && countCJKAwareWords(question) >= 3 ? [question, 'x'.repeat(EXPANSION_MAX_VARIANT_CHARS), 'x'.repeat(EXPANSION_MAX_VARIANT_CHARS)] : [question];+ add('embed_query', embedModel, variants.length, variants.reduce((s, v) => s + planTokens(v), 0), 0);+ }+ if (expansionLive && countCJKAwareWords(question) >= 3) {+ const sanitized = sanitizeQueryForPrompt(question);+ if (sanitized) add('expansion', expansionModel, 1, planTokens(buildExpansionPrompt(sanitized)) + EXPANSION_TOOL_ALLOWANCE_TOKENS, expansionMaxOut);+ }+ if (pins.reranker.enabled) {+ const docs = pages.flatMap(p => p.chunks.map(c => capRerankDoc(c.chunk_text || p.title || ''))).sort((a, b) => b.length - a.length).slice(0, topNIn);+ add('rerank', pins.reranker.model, docs.length > 0 ? 1 : 0, docs.reduce((s, d) => s + planTokens(question) + planTokens(d), 0), 0);+ }+ if (!opts.noTrajectory) {+ for (const p of pages) {+ const key = createHash('sha256').update(p.content).digest('hex');+ if (seenExtract.has(key)) continue;+ seenExtract.add(key);+ add('trajectory_extract', input.extractorModel, 1, planTokens(EXTRACTOR_SYSTEM_PROMPT) + planTokens(p.content), EXTRACTOR_MAX_TOKENS);+ }+ }+ if (synopsis) {+ const maxOut = thinkingOffOutputCap(synopsis.model, synopsis.maxTokens);+ for (const p of pages) {+ if (p.chunks.length === 0) continue;+ const pagePrompt = planTokens(buildPagePrompt(p.title, p.chunks.filter(c => c.chunk_source !== 'image_asset').map(c => c.chunk_text).join('\n\n')));+ for (const c of p.chunks) {+ if (c.chunk_source === 'fenced_code') continue;+ add('synopsis', synopsis.model, 1, planTokens(SYNOPSIS_SYSTEM_PROMPT) + pagePrompt + planTokens(buildChunkPrompt(c.chunk_text)), maxOut);+ }+ }+ }+ if (factArm) {+ const arm = factArm.arm;+ const thisQuestion = new Set<string>();+ for (const p of pages) {+ const body = bodyOf(p.content);+ let call: { system: string; user: string; maxOut: number } | null = null;+ if (arm.extractor === 'paper') {+ const turns = userTurns(body);+ if (turns) call = { system: PAPER_USER_FACT_SYSTEM, user: paperFactUserPrompt(turns), maxOut: PAPER_FACT_MAX_TOKENS };+ } else {+ let cleaned = body.slice(0, MAX_TURN_TEXT_CHARS);+ for (const pat of INJECTION_PATTERNS) cleaned = cleaned.replace(pat.rx, pat.replacement);+ cleaned = cleaned.trim();+ if (cleaned) call = { system: buildExtractorSystem(true, { dateGrounding: true, attribution: true }), user: `${observationDateLine(null)}\n<turn>\n${cleaned}\n</turn>\n\nExtract up to 10 facts.`, maxOut: DEFAULT_EXTRACTION_MAX_TOKENS };+ }+ if (!call) continue;+ if (!seenFactBodies.has(body)) add('fact_keys', arm.model, 1, planTokens(call.system) + planTokens(call.user), call.maxOut);+ thisQuestion.add(body);+ if (p.chunks.length > 0) {+ const re = embedCost(p.chunks.map(() => 'x'.repeat(EMBED_MAX_CHARS)), embedModel);+ add('embed_doc', embedModel, re.calls, re.tokens, 0);+ }+ }+ for (const b of thisQuestion) seenFactBodies.add(b);+ }+ if (!opts.retrievalOnly) {+ const bySlug = new Map(pages.map(p => [p.slug, p]));+ const rendered = [...bySlug.values()]+ .map(p => ({ s: { session_id: sessionIdFromSlug(p.slug), date: p.date, body: p.content }, n: renderChatBlock([{ session_id: sessionIdFromSlug(p.slug), date: p.date, body: p.content }], { maxSessionChars: READER_MAX_SESSION_CHARS }).rendered.length }))+ .sort((a, b) => b.n - a.n).slice(0, opts.topK).map(x => x.s);+ const routed = !opts.noTrajectory && classifyIntent(q) !== 'other';+ if (routed) readerTrajectoryQuestions++;+ const user = buildReaderUserText({ question, questionDate: typeof q.question_date === 'string' ? q.question_date : undefined, trajectoryBlock: routed ? trajectoryBound : '', rendered: renderChatBlock(rendered, { maxSessionChars: READER_MAX_SESSION_CHARS }).rendered });+ add('reader', readerModel, 1, planTokens(readerConfig.system) + planTokens(user), readerConfig.maxTokens);+ }+ if (opts.judge) {+ const prompt = buildJudgePrompt({ question_id: q.question_id, question_type: q.question_type, question, answer: String(q.answer ?? ''), hypothesis: '' }).prompt;+ add('judge', opts.judgeModel, 1, planTokens(prompt) + readerConfig.maxTokens, JUDGE_MAX_TOKENS);+ }+ }+ if (opts.judge && opts.resumeFromPath && existsSync(opts.resumeFromPath)) {+ const sel = selectBackfillRows(readJsonlRows(opts.resumeFromPath), { questionByQid: input.questionByQid, hashFor: input.judgeHashFor });+ for (const r of sel.candidates) {+ const q = input.questionByQid.get(String(r.question_id))!;+ add('judge', opts.judgeModel, 1, planTokens(buildJudgePrompt({ question_id: q.question_id, question_type: q.question_type, question: q.question, answer: String(q.answer ?? ''), hypothesis: String(r.hypothesis ?? '') }).prompt), JUDGE_MAX_TOKENS);+ }+ if (sel.candidates.length > 0) bindInput(root, opts.resumeFromPath, '--resume-from file (judge backfill rows)', plan);+ }++ const order = ['expansion', 'embed_doc', 'embed_query', 'rerank', 'trajectory_extract', 'synopsis', 'fact_keys', 'reader', 'judge'];+ plan.rows = order.flatMap(p => (rows.has(p) ? [rows.get(p)!] : []));+ const has = (p: string): boolean => rows.has(p);+ const pre = plan.preconditions;+ pre.push(`in_tokens count ceil(chars / ${CALL_PLAN_CHARS_PER_TOKEN}) (CALL_PLAN_CHARS_PER_TOKEN, src/eval/longmemeval/call-plan.ts) over each call's real prompt text and template; no provider tokenizer is in the repo, so text denser than ${CALL_PLAN_CHARS_PER_TOKEN} characters per token (CJK, hex) can exceed it`);+ pre.push('the price is the uncached worst case: the embed, synopsis and fact-key caches under ~/.cache/gbrain-eval and the --resume-from skip are not subtracted; retries and failure-path calls are excluded (AI SDK transport retries, judge timeout/429 retries, synopsis transient retries and title-tier fallback re-embeds, production fact-extractor truncation/malformed retries)');+ pre.push('out_tokens = calls x max_out_tokens, where max_out_tokens is the per-call cap each lane sends: an upper bound');+ if (git(root, ['status', '--porcelain', '--untracked-files=no']).toString().trim()) pre.push('computed from a working tree with uncommitted changes to tracked files; recompute from a clean checkout of HEAD before committing this plan');+ const providers = [...new Set(plan.rows.map(r => r.model.split(':')[0]!))].sort();+ if (providers.length > 0) pre.push(`provider keys for ${providers.join(', ')} set at run time`);+ pre.push('the reader, claim extractor, embedding and rerank lanes have no spend cap in this command');+ pre.push(`${questions.length} question(s) after --question-ids / --limit; haystacks chunked offline at ${maxChunkTokens} max chunk tokens (GBRAIN_MAX_CHUNK_TOKENS or the embedding model's limit), the same functions the import uses`);+ if (has('expansion')) pre.push(`expansion model ${expansionModel} from expansion_model in ~/.gbrain/config.json (default anthropic:claude-haiku-4-5-20251001); expansion sends no max_tokens, so max_out_tokens=${expansionMaxOut} is the AI SDK's default for that model; the structured-output tool block is budgeted at ${EXPANSION_TOOL_ALLOWANCE_TOKENS} tokens per call`);+ if (has('embed_doc') || has('embed_query')) pre.push(`embedding model ${embedModel} from embedding_model in ~/.gbrain/config.json or GBRAIN_EMBEDDING_MODEL (${envState(['GBRAIN_EMBEDDING_MODEL'])}); embed_query counts ${replay ? 'the recorded --expansion-replay variants' : expansionLive ? '3 query variants (the question + 2 rewrites of at most 500 characters) per expanded question' : 'one query per question'}${synopsis ? '; embed_doc includes the synopsis re-embed with a 300-character synopsis per chunk' : ''}${factArm ? '; embed_doc includes a fact-keyed re-embed of every chunk of each extractable session at the 8000-character input cap' : ''}`);+ if (has('rerank')) pre.push(`reranker ${pins.reranker.model} (search.reranker.model pin or snapshot, else the default); rerank in_tokens bound each question's ${topNIn} largest chunks, each sent with the query`);+ if (has('trajectory_extract')) pre.push(`trajectory_extract model ${input.extractorModel} from env GBRAIN_MODEL, else the utility tier default keyed on provider keys (${envState(['GBRAIN_MODEL', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY'])}; ~/.gbrain/config.json keys also count); one call per distinct session page`);+ if (has('synopsis')) pre.push(`synopsis model ${synopsis!.model} from env GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL, else the utility tier default (${envState(['GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY'])}); the synopsis lane honours chat_fallback_chain, whose fallback models are not priced here; spend cap --synopsis-max-usd ${opts.synopsis.maxUsd} stops the run early`);+ if (has('fact_keys')) pre.push(`fact_keys model ${factArm!.arm.model} (${factArm!.arm.extractor} extractor) from --fact-keys-model, else ${factArm!.arm.extractor === 'paper' ? 'env GBRAIN_MODEL or the utility tier default' : 'the facts extraction model'} (${envState(['GBRAIN_MODEL'])}); spend cap --fact-keys-max-usd ${opts.arms.factKeysMaxUsd} errors later questions`);+ if (has('reader')) pre.push(`reader model ${readerModel} from ${opts.model ? '--model' : `env GBRAIN_MODEL, else alias sonnet (${envState(['GBRAIN_MODEL'])})`}; reader in_tokens bound each question's ${opts.topK} largest rendered sessions${readerTrajectoryQuestions > 0 ? ` plus a full trajectory block (100 one-row groups, 500-character row text, 64-character entity/metric/unit/period) on ${readerTrajectoryQuestions} routed question(s)` : ''}`);+ if (has('judge')) pre.push(`judge model ${opts.judgeModel} (--judge-model, default openai:gpt-4o); live hypotheses are bounded at the reader's ${readerConfig.maxTokens} max tokens; spend cap --max-usd ${opts.maxUsd === null ? 'off' : opts.maxUsd} soft-stops judging`);+ return plan;+}++/** `--call-plan FILE`: build, write FILE.tmp, rename; a refusal prints and fails with nothing written. */+export async function runLmeCallPlan(input: LmeCallPlanInput, fail: (code: number) => never): Promise<void> {+ const path = input.opts.callPlanPath!;+ let text: string;+ let plan: CallPlan;+ try {+ plan = await buildLmeCallPlan(input);+ text = formatEvalCalls(plan);+ writeFileSync(`${path}.tmp`, text);+ renameSync(`${path}.tmp`, path);+ } catch (err: any) {+ process.stderr.write(`Error: ${err?.message ?? err}\n`);+ fail(1);+ return;+ }+ process.stderr.write(`[longmemeval] call plan: wrote ${path} (${plan.rows.length} call line(s): ${plan.rows.map(r => `${r.purpose}=${r.calls}`).join(', ') || 'none'}); no provider was called\n`);+}diff --git a/src/eval/longmemeval/extract.ts b/src/eval/longmemeval/extract.tsindex 2ea5b22d12..2138949b57 100644--- a/src/eval/longmemeval/extract.ts+++ b/src/eval/longmemeval/extract.ts@@ -140,7 +140,10 @@ export function trajectoryMethodologyNote(extractorModel: string): string {return `extractor=${name}-preprocess-full-haystack-v1`;}-const EXTRACTOR_SYSTEM_PROMPT = `You extract typed claims and events from a single chat-session transcript.+/** Output cap the extractor call sends. */+export const EXTRACTOR_MAX_TOKENS = 2000;++export const EXTRACTOR_SYSTEM_PROMPT = `You extract typed claims and events from a single chat-session transcript.Output a JSON array of records. Each record has these fields:- entity: The thing the claim is ABOUT (person name, company, place, object).@@ -269,7 +272,7 @@ async function callExtractor(try {response = await client.create({model,- max_tokens: 2000,+ max_tokens: EXTRACTOR_MAX_TOKENS,system: EXTRACTOR_SYSTEM_PROMPT,messages: [{ role: 'user', content: body }],});diff --git a/src/eval/longmemeval/retrieval-arms.ts b/src/eval/longmemeval/retrieval-arms.tsindex 3b5cd94626..5a9181eb07 100644--- a/src/eval/longmemeval/retrieval-arms.ts+++ b/src/eval/longmemeval/retrieval-arms.ts@@ -55,6 +55,11 @@ export interface FactKeyArm {/** The benchmark's published user-fact extraction instruction (zero-shot form). */export const PAPER_USER_FACT_SYSTEM = 'You will be given a list of messages from a human user to an AI assistant. Extract all the personal information, life events, experience, and preferences related to the user. Make sure you include all details such as life events, personal experience, preferences, specific numbers, locations, or dates. State each piece of information in a simple sentence. Put these sentences in a json list, each element being a standalone personal fact about the user. Minimize the coreference across the facts, e.g., replace pronouns with actual entities. If there is no specific events, personal information, or preference mentioned, just generate an empty list.';+/** Output cap and user message of the paper extractor call. */+export const PAPER_FACT_MAX_TOKENS = 2000;+export const paperFactUserPrompt = (turns: string): string =>+ `Human user messages:\n${turns}\n\nPersonal facts about the user (a list of strings in json format; do not generate anything else):`;+export function defaultFactCachePath(extractor: FactExtractor, model: string): string {return join(homedir(), '.cache', 'gbrain-eval', `fact-keys-${extractor}-${model.replace(/[^a-z0-9.-]+/gi, '_')}.jsonl`);}@@ -103,11 +108,11 @@ function cacheFor(path: string): FactCache {}/** Session body without frontmatter. */-function bodyOf(content: string): string {+export function bodyOf(content: string): string {return content.replace(/^---\n[\s\S]*?\n---\n/, '').trim();}-function userTurns(body: string): string {+export function userTurns(body: string): string {return body.split(/\n\n(?=\*\*(?:user|assistant):\*\*)/).filter(t => t.startsWith('**user:**')).map(t => `user: ${t.slice('**user:**'.length).trim()}`)@@ -137,8 +142,8 @@ async function extractItems(engine: BrainEngine, arm: FactKeyArm, body: string,const turns = userTurns(body);if (!turns) { cache.set(key, []); return []; }const res = await arm.client.create({- model: arm.model, max_tokens: 2000, system: PAPER_USER_FACT_SYSTEM,- messages: [{ role: 'user', content: `Human user messages:\n${turns}\n\nPersonal facts about the user (a list of strings in json format; do not generate anything else):` }],+ model: arm.model, max_tokens: PAPER_FACT_MAX_TOKENS, system: PAPER_USER_FACT_SYSTEM,+ messages: [{ role: 'user', content: paperFactUserPrompt(turns) }],});spend.add(arm.model, (res as { usage?: { input_tokens?: number; output_tokens?: number } }).usage);const block = res.content.find(b => b.type === 'text');diff --git a/test/eval-longmemeval-call-plan.serial.test.ts b/test/eval-longmemeval-call-plan.serial.test.tsnew file mode 100644index 0000000000..854b8e6eb7--- /dev/null+++ b/test/eval-longmemeval-call-plan.serial.test.ts@@ -0,0 +1,153 @@+/**+ * `--call-plan` counts against an instrumented real run: the same flags run+ * end to end on the fixture with every provider stubbed (reader, extractor+ * and judge clients through the RunOpts seams; synopsis chat, embeddings and+ * the reranker through the gateway test transports), and the plan for those+ * flags is written with every global transport throwing.+ *+ * Protects: the exact lanes (trajectory_extract, synopsis, reader, judge,+ * rerank) plan the call counts the run makes; every lane's planned+ * in_tokens, under the planner's own token rule, is at least what the run+ * sent; embedding requests stay within the embed_doc + embed_query plan;+ * writing the plan reaches no global transport.+ * Serial: mutates the process-global gateway, its transports and an env var.+ */+import { afterAll, 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 type Anthropic from '@anthropic-ai/sdk';+import { runEvalLongMemEval } from '../src/commands/eval-longmemeval.ts';+import { createBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';+import { planTokens } from '../src/eval/longmemeval/call-plan.ts';+import {+ configureGateway, resetGateway, __clearQueryEmbedCacheForTests, __setChatTransportForTests, __setEmbedTransportForTests, __setRerankTransportForTests,+ type ChatResult,+} from '../src/core/ai/gateway.ts';+import type { ThinkLLMClient } from '../src/core/think/index.ts';+import type { JudgeChatFn } from '../src/eval/shared/judge-runner.ts';++const FIXTURE = join(import.meta.dir, 'fixtures', 'longmemeval-mini.jsonl');+const DIMS = 1536;+const SYNOPSIS_MODEL = 'anthropic:claude-haiku-4-5-20251001';+const tmp = mkdtempSync(join(tmpdir(), 'lme-call-plan-serial-'));+const prevSynopsisModel = process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL;++interface Lane { calls: number; tokens: number }+const lane = (): Lane => ({ calls: 0, tokens: 0 });+let seen: Record<'extract' | 'synopsis' | 'reader' | 'judge' | 'rerank' | 'embed', Lane>;+const resetSeen = () => { seen = { extract: lane(), synopsis: lane(), reader: lane(), judge: lane(), rerank: lane(), embed: lane() }; };+const textOf = (content: unknown): string[] => typeof content === 'string' ? [content]+ : (content as Array<{ type: string; text?: string }>).map(b => (b.type === 'text' ? b.text ?? '' : ''));++const message = (model: string, text: string) => ({+ id: 'stub', type: 'message', role: 'assistant', model, content: [{ type: 'text', text, citations: null }], stop_reason: 'end_turn', stop_sequence: null,+ usage: { input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: null, cache_read_input_tokens: null, server_tool_use: null, service_tier: null }, container: null,+}) as unknown as Anthropic.Message;++const stubClient = (into: 'extract' | 'reader', answer: string): ThinkLLMClient => ({+ async create(params: Anthropic.MessageCreateParamsNonStreaming) {+ seen[into].calls++;+ seen[into].tokens += planTokens(typeof params.system === 'string' ? params.system : '') + params.messages.flatMap(m => textOf(m.content)).reduce((s, t) => s + planTokens(t), 0);+ return message(params.model, answer);+ },+}) as ThinkLLMClient;++const judge: JudgeChatFn = async (opts) => {+ seen.judge.calls++;+ seen.judge.tokens += opts.messages.flatMap(m => textOf(m.content)).reduce((s, t) => s + planTokens(t), 0);+ return { text: 'yes', blocks: [{ type: 'text', text: 'yes' }], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: opts.model ?? '', providerId: 'openai' } as ChatResult;+};++function installCountingTransports(): void {+ __setEmbedTransportForTests((async (p: { values: string[] }) => {+ seen.embed.calls++;+ seen.embed.tokens += p.values.reduce((s, v) => s + planTokens(v), 0);+ 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 never);+ __setChatTransportForTests(async (opts) => {+ seen.synopsis.calls++;+ const blocks = opts.messages.flatMap(m => textOf(m.content));+ seen.synopsis.tokens += planTokens(opts.system ?? '') + blocks.reduce((s, t) => s + planTokens(t), 0);+ const user = blocks.join('\n');+ 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: 100, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: SYNOPSIS_MODEL, providerId: 'anthropic' };+ });+ __setRerankTransportForTests((async (_url: string, init: RequestInit) => {+ const body = JSON.parse(String(init.body)) as { query: string; documents: string[] };+ seen.rerank.calls++;+ seen.rerank.tokens += body.documents.reduce((s, d) => s + planTokens(body.query) + planTokens(d), 0);+ const data = body.documents.map((_, index) => ({ index, relevance_score: 1 - index / (body.documents.length + 1) }));+ return new Response(JSON.stringify({ data, usage: { total_tokens: body.documents.length } }), { status: 200, headers: { 'content-type': 'application/json' } });+ }) as never);+}++function installThrowingTransports(): void {+ const boom = (name: string) => async () => { throw new Error(`${name} reached during --call-plan`); };+ __setEmbedTransportForTests(boom('embed transport') as never);+ __setChatTransportForTests(boom('chat transport') as never);+ __setRerankTransportForTests(boom('rerank transport') as never);+}++async function quiet<T>(fn: () => Promise<T>): Promise<T> {+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = (() => true) as typeof process.stderr.write;+ try { return await fn(); } finally { process.stderr.write = write; }+}++beforeAll(() => {+ process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL = SYNOPSIS_MODEL;+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test', ANTHROPIC_API_KEY: 'sk-ant-test', VOYAGE_API_KEY: 'pa-test' } });+});++afterAll(() => {+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+ __setRerankTransportForTests(null);+ resetGateway();+ if (prevSynopsisModel === undefined) delete process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL;+ else process.env.GBRAIN_CONTEXTUAL_SYNOPSIS_MODEL = prevSynopsisModel;+ rmSync(tmp, { recursive: true, force: true });+});++describe('eval longmemeval --call-plan vs an instrumented run', () => {+ test('tokenmax + judge: exact lanes match the run, every planned in_tokens covers what the run sent', async () => {+ const flags = ['--mode', 'tokenmax', '--judge', '--no-embed-cache', '--synopsis-cache', join(tmp, 'synopsis.jsonl')];+ const seams = { client: stubClient('reader', 'The answer.'), extractorClient: stubClient('extract', '[]'), judgeClient: judge, rerankerReadiness: async () => ({ plane: 'db', readiness: { ready: true } }) };++ resetSeen();+ installThrowingTransports();+ const planPath = join(tmp, 'plan.calls');+ await quiet(() => runEvalLongMemEval([FIXTURE, ...flags, '--call-plan', planPath], { exitOnError: false, ...seams, createBrain: async () => { throw new Error('no brain for --call-plan'); } } as never));+ expect(Object.values(seen).every(l => l.calls === 0)).toBe(true);+ const rows = Object.fromEntries(readFileSync(planPath, 'utf8').split('\n').filter(l => l.startsWith('GSTACK_EVAL_CALLS v1: ')).map((l) => {+ const r = Object.fromEntries(l.slice('GSTACK_EVAL_CALLS v1: '.length).split(' ').map(kv => kv.split('=') as [string, string]));+ return [r.purpose!, { calls: Number(r.calls), in: Number(r.in_tokens) }];+ }));++ resetSeen();+ installCountingTransports();+ __clearQueryEmbedCacheForTests();+ const engine = await createBenchmarkBrain();+ try {+ await quiet(() => runEvalLongMemEval([FIXTURE, ...flags, '--output', join(tmp, 'out.jsonl')], { exitOnError: false, engine, ...seams } as never));+ } finally {+ await engine.disconnect();+ }++ expect(seen.extract.calls).toBeGreaterThan(0);+ expect(rows.trajectory_extract!.calls).toBe(seen.extract.calls);+ expect(rows.trajectory_extract!.in).toBe(seen.extract.tokens);+ expect(seen.synopsis.calls).toBeGreaterThan(0);+ expect(rows.synopsis!.calls).toBe(seen.synopsis.calls);+ expect(rows.synopsis!.in).toBeGreaterThanOrEqual(seen.synopsis.tokens);+ expect(rows.reader!.calls).toBe(seen.reader.calls);+ expect(rows.reader!.in).toBeGreaterThanOrEqual(seen.reader.tokens);+ expect(rows.judge!.calls).toBe(seen.judge.calls);+ expect(rows.judge!.in).toBeGreaterThanOrEqual(seen.judge.tokens);+ expect(rows.rerank!.calls).toBe(seen.rerank.calls);+ expect(rows.rerank!.in).toBeGreaterThanOrEqual(seen.rerank.tokens);+ expect(rows.embed_doc!.calls + rows.embed_query!.calls).toBeGreaterThanOrEqual(seen.embed.calls);+ expect(rows.embed_doc!.in + rows.embed_query!.in).toBeGreaterThanOrEqual(seen.embed.tokens);+ }, 120_000);+});diff --git a/test/eval-longmemeval-call-plan.test.ts b/test/eval-longmemeval-call-plan.test.tsnew file mode 100644index 0000000000..5affcd7be7--- /dev/null+++ b/test/eval-longmemeval-call-plan.test.ts@@ -0,0 +1,241 @@+/**+ * `gbrain eval longmemeval --call-plan FILE` writes gstack's eval call plan+ * (GSTACK_EVAL_CALLS v1) for the run its flags describe, with no provider+ * call and no brain.+ *+ * Protects: every run seam throws and none is reached (no client, embed,+ * readiness probe or benchmark brain); the file passes a local+ * re-implementation of the gstack v1 grammar checks; flags turn lanes on and+ * off; `--expansion-replay` turns expansion off and sets the query-embed+ * count from its file; the GATE line round-trips argv quoting and+ * `--call-plan-gate` replaces it; the tracked fixture binds as an INPUT line;+ * lanes the planner cannot bound refuse and write nothing.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runEvalLongMemEval } from '../src/commands/eval-longmemeval.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { countCJKAwareWords } from '../src/core/cjk.ts';+import { CALL_PLAN_CHARS_PER_TOKEN, gateCommand, shellQuote } from '../src/eval/longmemeval/call-plan.ts';+import { withEnv } from './helpers/with-env.ts';++const FIXTURE = join(import.meta.dir, 'fixtures', 'longmemeval-mini.jsonl');+const QUESTIONS = readFileSync(FIXTURE, 'utf8').split('\n').filter(l => l.trim()).map(l => JSON.parse(l) as { question_id: string; question: string });+const tmp = mkdtempSync(join(tmpdir(), 'lme-call-plan-'));+const GATEWAY = { embedding_model: 'voyage:voyage-4', embedding_dimensions: 1024, expansion_model: 'anthropic:claude-haiku-4-5-20251001', env: {} };++const KEYS = ['purpose', 'model', 'calls', 'in_tokens', 'out_tokens', 'max_out_tokens', 'scope'];+type Row = Record<string, string>;++/** Local re-implementation of gstack's v1 parse checks (docs/eval-calls.md): kinds, keys, counts, end line, nothing after it. */+function parseGstackV1(text: string): { gate: string; head: string; inputs: string[]; preconditions: string[]; rows: Row[] } {+ let gate: string | null = null;+ let head: string | null = null;+ let endAt = -1;+ const inputs: string[] = [];+ const preconditions: string[] = [];+ const rows: Row[] = [];+ const seen = new Set<string>();+ text.split('\n').forEach((line, n) => {+ const fail = (why: string): never => { throw new Error(`EVAL_DRY_RUN_FAILED line ${n + 1}: ${why}: ${line}`); };+ if (endAt >= 0 && line.trim() !== '') fail('content after the end line');+ if (line.trim() === '' || line.startsWith('#')) return;+ let m: RegExpExecArray | null;+ if ((m = /^GSTACK_EVAL_GATE v1: (.+)$/.exec(line))) { if (gate !== null) fail('second GATE'); gate = m[1]!; return; }+ if ((m = /^GSTACK_EVAL_HEAD v1: ([0-9a-f]{40})$/.exec(line))) { if (head !== null) fail('second HEAD'); head = m[1]!; return; }+ if ((m = /^GSTACK_EVAL_INPUT v1: sha256=([0-9a-f]{64}) path=(\S+)$/.exec(line))) {+ if (m[2]!.startsWith('/') || m[2]!.split('/').includes('..')) fail('input path not repo-relative');+ inputs.push(m[2]!); return;+ }+ if ((m = /^GSTACK_EVAL_PRECONDITION: (.+)$/.exec(line))) { preconditions.push(m[1]!); return; }+ if ((m = /^GSTACK_EVAL_CALLS v1 end: lines=(\d+)$/.exec(line))) {+ if (Number(m[1]) !== rows.length) fail(`end line counts ${m[1]}, file has ${rows.length}`);+ endAt = n; return;+ }+ if ((m = /^GSTACK_EVAL_CALLS v1: (.+)$/.exec(line))) {+ const row: Row = {};+ for (const tok of m[1]!.split(' ')) {+ const eq = tok.indexOf('=');+ const k = tok.slice(0, eq);+ if (eq <= 0 || !KEYS.includes(k)) fail(`unknown key ${tok}`);+ if (k in row) fail(`duplicate key ${k}`);+ row[k] = tok.slice(eq + 1);+ }+ if (Object.keys(row).length !== KEYS.length) fail('missing key');+ if (!/^[A-Za-z0-9._:-]+$/.test(row.purpose!)) fail('bad purpose');+ for (const k of ['calls', 'in_tokens', 'out_tokens', 'max_out_tokens']) if (!/^\d+$/.test(row[k]!)) fail(`non-integer ${k}`);+ if (Number(row.calls) < 1) fail('calls=0');+ if (row.scope !== 'full' && row.scope !== 'smoke') fail('bad scope');+ const id = `${row.purpose}\u0000${row.model}`;+ if (seen.has(id)) fail('duplicate purpose+model');+ seen.add(id);+ rows.push(row);+ return;+ }+ fail('unknown line kind');+ });+ if (gate === null || head === null || endAt < 0) throw new Error('EVAL_DRY_RUN_FAILED: missing GATE, HEAD or end line');+ return { gate, head, inputs, preconditions, rows };+}++/** POSIX shell word splitting (single quotes, backslash escapes, whitespace). */+function shellWords(s: string): string[] {+ const words: string[] = [];+ let cur: string | null = null;+ for (let i = 0; i < s.length; i++) {+ const c = s[i]!;+ if (c === "'") { const j = s.indexOf("'", i + 1); cur = (cur ?? '') + s.slice(i + 1, j); i = j; continue; }+ if (c === '\\') { cur = (cur ?? '') + s[++i]; continue; }+ if (/\s/.test(c)) { if (cur !== null) words.push(cur); cur = null; continue; }+ cur = (cur ?? '') + c;+ }+ if (cur !== null) words.push(cur);+ return words;+}++const called: string[] = [];+const boom = (name: string): never => { called.push(name); throw new Error(`${name} must not be called by --call-plan`); };+const THROWING_SEAMS = {+ exitOnError: false,+ client: { create: async () => boom('reader client') },+ extractorClient: { create: async () => boom('extractor client') },+ judgeClient: async () => boom('judge client'),+ expandFn: async () => boom('expandFn'),+ embedTransport: (async () => boom('embed transport')) as never,+ rerankerReadiness: async () => boom('reranker readiness'),+ createBrain: async () => boom('createBrain (benchmark brain)'),+} as unknown as Parameters<typeof runEvalLongMemEval>[1];++async function plan(args: string[]): Promise<{ text: string; parsed: ReturnType<typeof parseGstackV1>; rows: Record<string, Row>; err: string; path: string }> {+ const path = join(tmp, `plan-${Math.random().toString(36).slice(2)}.calls`);+ 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 {+ await runEvalLongMemEval([FIXTURE, ...args, '--call-plan', path], THROWING_SEAMS);+ } catch (e) {+ throw Object.assign(e as Error, { message: `${(e as Error).message}\n${err}` });+ } finally {+ process.stderr.write = write;+ }+ expect(called).toEqual([]);+ expect(existsSync(`${path}.tmp`)).toBe(false);+ const text = readFileSync(path, 'utf8');+ const parsed = parseGstackV1(text);+ return { text, parsed, rows: Object.fromEntries(parsed.rows.map(r => [r.purpose, r])), err, path };+}++async function refusal(args: string[]): Promise<string> {+ const path = join(tmp, `refused-${Math.random().toString(36).slice(2)}.calls`);+ 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 {+ await expect(runEvalLongMemEval([FIXTURE, ...args, '--call-plan', path], THROWING_SEAMS)).rejects.toThrow(/longmemeval failed \(exit 1\)/);+ } finally {+ process.stderr.write = write;+ }+ expect(called).toEqual([]);+ expect(existsSync(path)).toBe(false);+ expect(existsSync(`${path}.tmp`)).toBe(false);+ return err;+}++const purposes = (r: Record<string, Row>) => Object.keys(r).sort();++beforeAll(() => { configureGateway(GATEWAY); });+afterAll(() => {+ resetGateway();+ rmSync(tmp, { recursive: true, force: true });+});++describe('eval longmemeval --call-plan', () => {+ test('writes a gstack v1 plan with no provider call and no brain; the tracked fixture binds as INPUT', async () => {+ const p = await plan(['--mode', 'tokenmax', '--judge', '--expansion', '--fact-keys', 'chunk']);+ expect(purposes(p.rows)).toEqual(['embed_doc', 'embed_query', 'expansion', 'fact_keys', 'judge', 'reader', 'rerank', 'synopsis', 'trajectory_extract']);+ expect(p.parsed.inputs).toEqual(['test/fixtures/longmemeval-mini.jsonl']);+ expect(p.parsed.head).toMatch(/^[0-9a-f]{40}$/);+ expect(p.parsed.preconditions.some(t => t.includes(`ceil(chars / ${CALL_PLAN_CHARS_PER_TOKEN})`))).toBe(true);+ expect(p.parsed.preconditions.some(t => t.includes('uncached worst case') && t.includes('retries'))).toBe(true);+ for (const r of p.parsed.rows) {+ expect(Number(r.out_tokens)).toBe(Number(r.calls) * Number(r.max_out_tokens));+ expect(r.scope).toBe('full');+ expect(r.model).toMatch(/^[a-z-]+:/);+ }+ expect(p.rows.reader).toMatchObject({ calls: String(QUESTIONS.length), max_out_tokens: '1024', model: 'anthropic:claude-sonnet-4-6' });+ expect(p.rows.judge).toMatchObject({ calls: String(QUESTIONS.length), max_out_tokens: '16', model: 'openai:gpt-4o' });+ expect(p.rows.expansion).toMatchObject({ model: 'anthropic:claude-haiku-4-5-20251001', max_out_tokens: '64000' });+ expect(p.rows.synopsis!.max_out_tokens).toBe('200');+ expect(p.rows.trajectory_extract!.max_out_tokens).toBe('2000');+ expect(p.rows.rerank).toMatchObject({ model: 'voyage:rerank-2.5', calls: String(QUESTIONS.length), max_out_tokens: '0' });+ expect(p.text.endsWith(`GSTACK_EVAL_CALLS v1 end: lines=${p.parsed.rows.length}\n`)).toBe(true);+ expect(p.err).toContain('no provider was called');+ }, 60_000);++ test('flags turn lanes on and off', async () => {+ const base = await plan([]);+ expect(purposes(base.rows)).toEqual(['embed_doc', 'embed_query', 'reader', 'rerank', 'trajectory_extract']);+ expect(purposes((await plan(['--no-trajectory'])).rows)).toEqual(['embed_doc', 'embed_query', 'reader', 'rerank']);+ expect(purposes((await plan(['--keyword-only'])).rows)).toEqual(['reader', 'trajectory_extract']);+ expect(purposes((await plan(['--retrieval-only'])).rows)).toEqual(['embed_doc', 'embed_query', 'rerank', 'trajectory_extract']);+ expect(purposes((await plan(['--judge'])).rows)).toContain('judge');+ expect(purposes((await plan(['--mode', 'conservative'])).rows)).not.toContain('rerank');+ expect(purposes((await plan(['--reranker', 'off'])).rows)).not.toContain('rerank');+ const tm = await plan(['--mode', 'tokenmax']);+ expect(purposes(tm.rows)).toContain('synopsis');+ expect(Number(tm.rows.embed_doc!.calls)).toBeGreaterThan(Number(base.rows.embed_doc!.calls));+ expect(purposes((await plan(['--mode', 'tokenmax', '--keyword-only'])).rows)).not.toContain('synopsis');+ expect(purposes((await plan(['--fact-keys', 'page'])).rows)).toContain('fact_keys');+ expect(purposes((await plan(['--fact-keys', 'page', '--fact-extractor', 'production'])).rows)).toContain('fact_keys');+ expect(purposes((await plan(['--keyword-only', '--fact-keys', 'page'])).rows)).toEqual(['embed_doc', 'fact_keys', 'reader', 'trajectory_extract']);+ const none = await plan(['--keyword-only', '--retrieval-only', '--no-trajectory']);+ expect(none.parsed.rows).toEqual([]);+ expect(none.text).toContain('GSTACK_EVAL_CALLS v1 end: lines=0');+ const limited = await plan(['--limit', '2']);+ expect(limited.rows.reader!.calls).toBe('2');+ }, 120_000);++ test('--expansion calls once per question of 3+ words and embeds 3 variants; --expansion-replay drops the lane and counts the file', async () => {+ const expanding = QUESTIONS.filter(q => countCJKAwareWords(q.question) >= 3).length;+ const live = await plan(['--expansion']);+ expect(live.rows.expansion!.calls).toBe(String(expanding));+ expect(Number(live.rows.embed_query!.calls)).toBe(QUESTIONS.length + 2 * expanding);++ const replayFile = join(tmp, 'replay.jsonl');+ const recorded = { [QUESTIONS[0]!.question_id]: [QUESTIONS[0]!.question, 'alt one', 'alt two'], [QUESTIONS[1]!.question_id]: [QUESTIONS[1]!.question, 'alt one'] };+ writeFileSync(replayFile, Object.entries(recorded).map(([question_id, expansion_variants]) => JSON.stringify({ question_id, expansion_variants })).join('\n') + '\n');+ const replay = await plan(['--expansion-replay', replayFile]);+ expect(replay.rows.expansion).toBeUndefined();+ expect(replay.rows.embed_query!.calls).toBe(String(3 + 2 + (QUESTIONS.length - 2)));+ expect(replay.parsed.preconditions.some(t => t.startsWith('--expansion-replay file replay.jsonl sha256='))).toBe(true);+ expect(replay.parsed.preconditions.join('\n')).not.toContain(tmp);+ }, 60_000);++ test('the GATE line is the command minus --call-plan, quoted only where needed; --call-plan-gate replaces it', async () => {+ const out = join(tmp, 'a b', "it's.jsonl");+ const args = ['--limit', '2', '--output', out, '--search-pin', 'search.metadata_boost_gate=lexical', '--keyword-only'];+ const p = await plan(args);+ expect(shellWords(p.parsed.gate)).toEqual(['gbrain', 'eval', 'longmemeval', FIXTURE, ...args]);+ expect(p.parsed.gate).toContain('--limit 2 --output ');+ expect(gateCommand([FIXTURE, '--call-plan=x.calls', '--call-plan-gate', 'y', '--limit', '1'])).toBe(`gbrain eval longmemeval ${shellQuote(FIXTURE)} --limit 1`);+ expect(shellQuote('')).toBe("''");+ expect(shellWords(shellQuote(`a'b "c" $d`))).toEqual([`a'b "c" $d`]);+ const custom = await plan(['--keyword-only', '--call-plan-gate', 'bun run eval:lme --questions 5']);+ expect(custom.parsed.gate).toBe('bun run eval:lme --questions 5');+ }, 60_000);++ test('lanes it cannot bound refuse with nothing written', async () => {+ expect(await refusal(['--via-operation', 'query'])).toContain('cannot bound --via-operation');+ expect(await withEnv({ GBRAIN_DECIDE_SLOTS: undefined }, () => refusal(['--decide', 'intent=on', '--no-trajectory']))).toContain('cannot bound the decide lane');+ expect(await refusal(['--search-pin', 'search.cross_modal.llm_intent=true'])).toContain('llm_intent');+ configureGateway({ ...GATEWAY, expansion_model: 'openai:gpt-5.6' });+ try {+ expect(await refusal(['--expansion'])).toContain('cannot bound expansion on openai:gpt-5.6');+ } finally {+ configureGateway(GATEWAY);+ }+ await expect(runEvalLongMemEval([FIXTURE, '--call-plan-gate', 'x'], THROWING_SEAMS)).rejects.toThrow(/exit 1/);+ }, 60_000);+});