Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

think: configurable pages budget, evidence_truncated and source-qualified citations (#5461)

garrytan8117e9812e78
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index 6dc0cd8469..c67094fa0e 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -5,6 +5,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/think/index.ts` — `runThink` builds its internal `LLMClient` via a small adapter wrapping `gateway.chat()` from `src/core/ai/gateway.ts` (not `new Anthropic()` directly) so stdio MCP launches (Claude Desktop, Cursor) that don't inherit shell env still find a key set via `gbrain config set anthropic_api_key` (the gateway reads `~/.gbrain/config.json` AND env). Test seam: `opts.client?: ThinkLLMClient` injection works (`test/think-pipeline.test.ts`, `test/think-gateway-adapter.test.ts`); `opts.stubResponse` short-circuits before any LLM call. When neither key nor client is available, the "no LLM available" stub fires with `NO_ANTHROPIC_API_KEY`. Trajectory injection (default ON): `runThink` orchestrates `classifyIntent(question)` → `extractCandidateEntities(question, retrievedSlugs)` → `findTrajectory` (5s `Promise.race` timeout per candidate, concurrency cap 3) → `formatTrajectoryBlock`. `buildThinkUserMessage` (in `src/core/think/prompt.ts`) has a `trajectory?: ThinkTrajectoryBlockOpts` slot honoring BOTH prompt orderings (calibration mode: retrieval → calibration → trajectory → question; default mode: question → retrieval → trajectory → instruction). The MCP `think` op handler maps `sourceScopeOpts(ctx)` onto `RunThinkOpts` via `thinkSourceScopeOpts(ctx)` (operations.ts), and `runThink` threads the scope into `runGather` (`src/core/think/gather.ts`) — so every gather stream (hybrid retrieval, takes keyword + vector via the engines' scoped `searchTakes`/`searchTakesVector`, graph walk via `traversePaths`) AND trajectory resolution stay within the caller's source grant (federated `sourceIds[]` wins over scalar `sourceId`); pinned by `test/e2e/think-source-isolation-pglite.test.ts`. Config key `think.trajectory_enabled` (default `true`). Any error in the trajectory path degrades to "no block injected" + `TRAJECTORY_INJECTION_FAILED` warning — the think call never crashes from trajectory. Production path skips `fallback_slugify` resolutions (avoid querying invented slugs); the LongMemEval harness accepts them. Pinned by `test/think-trajectory-injection.test.ts`. Debug: `GBRAIN_THINK_DEBUG=1 gbrain think "..."` prints the spliced prompt to stderr. System One (`think/decide.ts`, no work when S2 and S4 are off): S2 decides the trajectory-gating intent (regex `classifyIntent` is the fallback and tie source) and hands gather one precomputed search-intent answer; S4 may return an abstention after gather and before synthesis (`ThinkResult.abstained`, warning `DECIDE_ABSTAINED`, `synthesisOk: false`, synthesis call skipped). Quote grounding (`think.quote_verify`, default on): after a real synthesis, every quoted span in the answer is grounded against exactly the evidence blocks the prompt carried (pages, takes, graph, trajectory; no refetch) with `groundAnswerQuotes`; when the answer had quotes, `answer` becomes the safe version (near matches repaired, quotes found nowhere unquoted and marked `[unverified]`, warning `QUOTE_NOT_IN_EVIDENCE`), `answer_raw`/`quote_check`/`unverified_quotes` are added, and `persist` (internal; stripped by the MCP `think` op) holds the raw answer run through `verifyBody(…, { checks: 'quotes' })`, which `persistSynthesis` saves with failing units in frontmatter `unverified_claims`. The `synthesize` verb returns the same additive fields. Pinned by `test/think-quote-verify.test.ts`.
+- `src/core/think/pages-budget.ts` + `pagesBlockExcerptLen` / `renderPagesBlockDetailed` in `think/gather.ts` (#5461) — the synthesize pages-block budget as configuration. `readThinkPagesBudget(engine, warnings)` reads `think.pages_budget_chars` (4 000-200 000, default 12 000) and `think.excerpt_ceiling_chars` (600-200 000, default 2 400) once per `runThink`; a stored out-of-range or non-integer value keeps the default and warns `THINK_BUDGET_CONFIG_IGNORED:<key>`, and `gbrain config set` refuses it up front (`commands/config.ts`, same hook shape as `cycle.consolidate.cluster_threshold`). The per-page excerpt is `max(600, min(ceiling, floor(total / pages)))`, so the total is SOFT (the floor wins) and whole pages are never promised while the ceiling holds; the unit shown is the gathered chunk or compiled text. `renderPagesBlockDetailed` returns `{ text, truncated }` (`truncated` = any excerpt cut at either end, or a delivered block over its cap / cut to its window) and `runThink` reports it as `ThinkResult.evidence_truncated`; the `synthesize` verb adds `evidence_truncated` and `citations[] { slug, source_id, row_num }` (source-qualified `sources[]`, `source_id` null for a slug outside the gather; `sources[]` stays frozen). Conversation-type pages go through evidence delivery (`think.return_unit`) and its token budget instead. Pinned by `test/think-pages-budget-5461.test.ts`.
+
- `src/core/think/temporal-window.ts` — the evidence window. `parseTemporalWindow(since, until)` validates caller bounds (inclusive UTC days or months); `filterPagesToWindow` keeps undated pages and counts the dated ones it drops. PR #5086 (wave 14): `parseQuestionWindow(question)` returns the one explicit date a question names (ISO day, ISO month, English month name + year) as bounds spanning it, null on no token, a bare year, two distinct tokens, an invalid token or a relative phrase; `resolveThinkWindow(question, since, until)` is what `runThink` calls: caller bounds first (`source: 'caller'`), else the question's (`source: 'question'`, `WINDOW_FROM_QUESTION` warning), surfaced as `ThinkResult.window_source` and fed to the system prompt's since/until.
- `src/core/think/temporal-context.ts` + the date-frame parts of `think/{index,prompt,gather}.ts` — `runThink` reads in a date frame: `resolveThinkTemporalContext` returns the reference day (caller `referenceDate` / MCP `reference_date` / CLI `--reference-date`, validated by `parseReferenceDate` as a real past-or-current YYYY-MM-DD, else today) in `brain.timezone` (UTC when unset or invalid); the user message carries `Current date: <day> (<zone>)` just before the question in both message shapes, and the system prompt carries the date-reading rules without the date itself (stable system text). `renderPagesBlock` adds `date="YYYY-MM-DD"` only when `effective_date_source` is a content date (`event_date|date|published|filename`); the day renders through `formatBrainDay` (`effective-date.ts`, shared with C1's evidence headers): a midnight-UTC value is a day-only date and renders as written, any other instant renders in the brain zone. `ReferenceDateError` maps to `invalid_params` in the op. Test: `test/think-reading.test.ts`.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 20f70c9757..0fbf8d36cf 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -546,6 +546,36 @@ purpose, no dedicated status); a `max_tokens`-cut envelope parses as
`output_truncated` (warning `LLM_OUTPUT_TRUNCATED`) so a too-small output
budget is distinguishable from malformed model output.
+#### synthesize evidence budget and provenance (additive, #5461)
+
+The pages the model reads are excerpts, not whole pages. Each gathered page
+gets `min(ceiling, floor(total / pages_gathered))` characters, never fewer
+than 600, with `total` from `think.pages_budget_chars` (4 000-200 000,
+default 12 000) and `ceiling` from `think.excerpt_ceiling_chars`
+(600-200 000, default 2 400), both set with `gbrain config set` on the brain
+host (the verb surface stays frozen: no new parameter). The total is a SOFT
+bound: the 600-character floor wins, so 40 pages at the default read 24 000
+characters. Raising the total alone never delivers whole pages while the
+ceiling holds, and even with both raised the unit shown is the gathered
+chunk or compiled text, so full pages are not promised. A value outside its
+range is refused at set time; a stored bad value is ignored for the call,
+the default applies and `warnings` carries
+`THINK_BUDGET_CONFIG_IGNORED:<key>`. Conversation-type pages (meetings,
+chats, transcripts) travel through evidence delivery instead, under
+`think.return_unit` and its token budget; the character budget does not
+apply to them.
+
+Two optional response fields report what happened:
+
+- `evidence_truncated: boolean` — true when at least one gathered page
+ reached the model in part (an excerpt cut at either end, or a delivered
+ block cut to its window). False means every gathered unit was shown whole.
+- `citations: [{ slug, source_id, row_num }]` — `sources[]` with
+ provenance, same order and length: `source_id` is the source the cited
+ page was gathered from (the highest-ranked gathered page with that slug);
+ `null` when the model cited a slug outside the gather (the response also
+ warns `CITATION_NOT_IN_GATHER:<slug>`). `sources: string[]` is unchanged.
+
#### Answer feedback fields (additive)
`recall` (when its `query` arm searched pages on the hybrid path) and
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index fdb52303c2..982303d901 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1931 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 1953 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts)
+src/core/config.ts 1955 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts)
src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
@@ -44,3 +44,4 @@ src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset
src/commands/eval-longmemeval.ts 1519 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts)
src/commands/doctor/checks/extraction-sync.ts 1512 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)
src/core/search/evidence-delivery.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8)
+src/commands/config.ts 1511 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
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 6ba7df4552..125fa5a95d 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1264,6 +1264,17 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }
}
+ // #5461: think falls back to the default budget on a malformed value
+ // (and warns); refuse it here, where the operator can fix it.
+ if (key === 'think.pages_budget_chars' || key === 'think.excerpt_ceiling_chars') {
+ const { parsePagesBudgetValue, THINK_PAGES_BUDGET_BOUNDS } = await import('../core/think/pages-budget.ts');
+ if (parsePagesBudgetValue(key, value) === null) {
+ const { min, max } = THINK_PAGES_BUDGET_BOUNDS[key];
+ console.error(`[config] ${key} must be an integer between ${min} and ${max} (characters); got ${JSON.stringify(value)}`);
+ process.exit(1);
+ }
+ }
+
// Validate sources.default at set time. This key is read by
// source-resolver.ts tier 5 on EVERY unqualified call, and tier 5 calls
// assertSourceExists — so a syntactically valid but non-existent id set
diff --git a/src/core/config.ts b/src/core/config.ts
index f43d5f437f..89a0df2925 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1411,6 +1411,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.query_facts_arm', // query adds matching active facts as rows in spare capacity (default on; search/facts-arm.ts)
'search.temporal_fact_reserve', // temporal-cue queries reserve up to 15% of the token budget for question-ranked dated facts (default off; search/facts-arm.ts)
'think.return_unit',
+ 'think.pages_budget_chars', // #5461: total chars for the synthesize pages block (4000-200000, default 12000; soft: the 600-char floor wins); think/pages-budget.ts
+ 'think.excerpt_ceiling_chars', // #5461: per-page excerpt cap for the synthesize pages block (600-200000, default 2400); think/pages-budget.ts
// Models tier system (v0.31.12)
'models.default',
'models.tier.utility',
diff --git a/src/core/think/cite-render.ts b/src/core/think/cite-render.ts
index 114510558c..80b488f079 100644
--- a/src/core/think/cite-render.ts
+++ b/src/core/think/cite-render.ts
@@ -21,6 +21,13 @@ export interface ParsedCitation {
page_slug: string;
row_num: number | null; // null = page-level citation, set = take citation
citation_index: number; // 1-based order in the body
+ /**
+ * #5461: the source the cited page was gathered from (highest-ranked gathered
+ * page with this slug); `null` when the slug was in no gather stream (the
+ * result also warns CITATION_NOT_IN_GATHER). Stamped by runThink; absent on
+ * citations straight out of the parser.
+ */
+ source_id?: string | null;
}
/**
diff --git a/src/core/think/gather.ts b/src/core/think/gather.ts
index 69f4b2ffc0..b19669dd4d 100644
--- a/src/core/think/gather.ts
+++ b/src/core/think/gather.ts
@@ -22,6 +22,7 @@ import { hybridSearch } from '../search/hybrid.ts';
import { INTERNAL_BREADTH_SEARCH_OPTS } from '../search/internal-breadth.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
import type { Page, SearchResult } from '../types.ts';
+import { DEFAULT_PAGES_BUDGET, PAGES_BLOCK_EXCERPT_FLOOR_CHARS, type PagesBudget } from './pages-budget.ts';
import { filterPagesToWindow, type TemporalWindow } from './temporal-window.ts';
import { pageContentDate } from './temporal-context.ts';
import { sanitizeQueryForPrompt } from '../search/expansion.ts';
@@ -587,17 +588,17 @@ export function selectRelevantExcerptDetailed(
* budget-aware: `min(ceiling, totalBudget / pageCount)` with the caller's
* `floor` as the guaranteed minimum, so a big gather never collapses each
* page below the floor, and a small gather delivers each page in a much
- * larger (often complete) window instead of wasting the budget.
+ * larger (often complete) window instead of wasting the budget. The total
+ * is therefore a SOFT bound (40 pages × the 600 floor = 24 000 at the
+ * 12 000 default). #5461: `budget` comes from `think.pages_budget_chars` /
+ * `think.excerpt_ceiling_chars` (pages-budget.ts); the defaults are the
+ * historical constants.
*/
-const PAGES_BLOCK_TOTAL_BUDGET_CHARS = 12_000;
-const PAGES_BLOCK_EXCERPT_CEILING_CHARS = 2_400;
-
-/** Budget-aware per-page excerpt length for the pages block (#4510). */
-export function pagesBlockExcerptLen(pageCount: number, floor = 600): number {
+export function pagesBlockExcerptLen(pageCount: number, floor = PAGES_BLOCK_EXCERPT_FLOOR_CHARS, budget: PagesBudget = DEFAULT_PAGES_BUDGET): number {
if (pageCount <= 0) return floor;
return Math.max(floor, Math.min(
- PAGES_BLOCK_EXCERPT_CEILING_CHARS,
- Math.floor(PAGES_BLOCK_TOTAL_BUDGET_CHARS / pageCount),
+ budget.ceilingChars,
+ Math.floor(budget.totalChars / pageCount),
));
}
@@ -623,7 +624,22 @@ export function renderPagesBlock(
query = '',
opts: { verbatim?: boolean | ((p: SearchResult) => boolean); verbatimLen?: number; timeZone?: string } = {},
): string {
- return pages.map((p, idx) => {
+ return renderPagesBlockDetailed(pages, excerptLen, query, opts).text;
+}
+
+/**
+ * `renderPagesBlock` plus `truncated`: true when any page was shown in part
+ * (an excerpt cut at either end, or a verbatim block over its cap). #5461:
+ * the think result reports it as `evidence_truncated`.
+ */
+export function renderPagesBlockDetailed(
+ pages: SearchResult[],
+ excerptLen = 600,
+ query = '',
+ opts: { verbatim?: boolean | ((p: SearchResult) => boolean); verbatimLen?: number; timeZone?: string } = {},
+): { text: string; truncated: boolean } {
+ let truncated = false;
+ const text = pages.map((p, idx) => {
const day = pageContentDate(p, opts.timeZone ?? 'UTC');
const dateAttr = day ? ` date="${day}"` : '';
const page = p as unknown as {
@@ -643,7 +659,9 @@ export function renderPagesBlock(
// Evidence delivery: the block was already budgeted and cut around its
// hits; render it whole (capped only by excerptLen).
if (typeof opts.verbatim === 'function' ? opts.verbatim(p) : opts.verbatim) {
- return `<page slug="${slug}" rank="${idx + 1}"${dateAttr}${trustAttr}>\n${flag}${content.slice(0, opts.verbatimLen ?? excerptLen)}\n</page>`;
+ const cap = opts.verbatimLen ?? excerptLen;
+ if (content.length > cap || (p as { delivered?: { truncated?: boolean } }).delivered?.truncated === true) truncated = true;
+ return `<page slug="${slug}" rank="${idx + 1}"${dateAttr}${trustAttr}>\n${flag}${content.slice(0, cap)}\n</page>`;
}
const excerpt = selectRelevantExcerptDetailed(
content,
@@ -651,12 +669,14 @@ export function renderPagesBlock(
excerptLen,
`${title} ${slugIdentity}`,
);
+ if (excerpt.truncatedStart || excerpt.truncatedEnd) truncated = true;
const body =
(excerpt.truncatedStart ? `${EXCERPT_CUT_START_MARKER}\n` : '') +
excerpt.text +
(excerpt.truncatedEnd ? `\n${EXCERPT_CUT_END_MARKER}` : '');
return `<page slug="${slug}" rank="${idx + 1}"${dateAttr}${trustAttr}>\n${flag}${body}\n</page>`;
}).join('\n\n');
+ return { text, truncated };
}
/** One line naming the typed links that put a chain row in the context (slugs and link types only). */
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index b3338800d4..996a849adc 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -21,7 +21,8 @@ import type Anthropic from '@anthropic-ai/sdk';
import { OperationTimeoutError, withTimeout } from '../timeout.ts';
import type { BrainEngine, SynthesisEvidenceInput } from '../engine.ts';
import type { SearchResult } from '../types.ts';
-import { runGather, renderPagesBlock, pagesBlockExcerptLen, takesHitToTakeForPrompt, selectRelevantExcerpt } from './gather.ts';
+import { runGather, renderPagesBlockDetailed, pagesBlockExcerptLen, takesHitToTakeForPrompt, selectRelevantExcerpt } from './gather.ts';
+import { readThinkPagesBudget } from './pages-budget.ts';
import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';
import { renderTakesBlock } from './sanitize.ts';
import { buildThinkSystemPrompt, buildThinkUserMessage } from './prompt.ts';
@@ -218,6 +219,13 @@ export interface ThinkResult {
usage?: { input_tokens: number; output_tokens: number } | null;
/** Evidence delivery meta, present only when think.return_unit is not chunk. */
evidence_delivery?: import('../search/evidence-delivery.ts').DeliveryMeta;
+ /**
+ * #5461: true when at least one gathered page reached the model in part (an
+ * excerpt cut by the pages budget / excerpt ceiling, or a delivered block
+ * over its cap). The budget is configurable (`think.pages_budget_chars`,
+ * `think.excerpt_ceiling_chars`) and soft; see think/pages-budget.ts.
+ */
+ evidence_truncated?: boolean;
/** Gathered pages with the revision retrieved, for retrieval-feedback recording; the op layer strips it. */
feedback_evidence?: Array<{ source_id: string; slug: string; content_hash: string | null }>;
/** #5575 I2: every page, take and trajectory fact placed in the synthesis prompt; `persistSynthesis` taints from them. The op layer strips it. */
@@ -456,7 +464,7 @@ export function composeExtractiveFallback(
const excerpt = selectRelevantExcerpt(
content, question, EXTRACTIVE_EXCERPT_LEN, `${title} ${slugIdentity}`,
).trim();
- citations.push({ page_slug: slug, row_num: null, citation_index: idx + 1 });
+ citations.push({ page_slug: slug, row_num: null, citation_index: idx + 1, source_id: p.source_id ?? 'default' });
return excerpt ? `- ${title} [${slug}]: ${excerpt}` : `- ${title} [${slug}]`;
});
return {
@@ -528,23 +536,30 @@ async function persistCitations(
* the renderer passes through whole instead of cutting its own excerpts;
* auto's unchanged chunks keep the usual excerpts.
*/
-async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[], timeZone: string): Promise<{ pagesBlock: string; evidenceDelivery?: DeliveryMeta }> {
- const plan = await resolveEvidencePlan(engine, {
- remote: opts.remote, returnUnit: undefined, returnWindow: undefined, budget: undefined,
- snippetChars: undefined, snippetCap: 0, configKey: THINK_RETURN_UNIT_CONFIG_KEY, op: 'think',
- });
+async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[], timeZone: string, warnings: string[]): Promise<{ pagesBlock: string; evidenceTruncated: boolean; evidenceDelivery?: DeliveryMeta }> {
+ const [plan, budget] = await Promise.all([
+ resolveEvidencePlan(engine, {
+ remote: opts.remote, returnUnit: undefined, returnWindow: undefined, budget: undefined,
+ snippetChars: undefined, snippetCap: 0, configKey: THINK_RETURN_UNIT_CONFIG_KEY, op: 'think',
+ }),
+ readThinkPagesBudget(engine, warnings), // #5461
+ ]);
+ const excerptLen = pagesBlockExcerptLen(pages.length, undefined, budget);
const applied = effectivePlan(plan, pages);
- if (!applied) return { pagesBlock: renderPagesBlock(pages, pagesBlockExcerptLen(pages.length), opts.question, { timeZone }) };
+ if (!applied) {
+ const rendered = renderPagesBlockDetailed(pages, excerptLen, opts.question, { timeZone });
+ return { pagesBlock: rendered.text, evidenceTruncated: rendered.truncated };
+ }
const delivered = await deliverEvidence(engine, pages, applied, {
...(opts.allowedSources !== undefined && opts.allowedSources.length > 0 ? { sourceIds: opts.allowedSources } : opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),
excludePrivate: opts.excludePrivate ?? await resolveExcludePrivatePages(engine, opts.remote),
requireSafeChunks: opts.remote !== false,
});
- const pagesBlock = applied.unit === 'auto'
- ? renderPagesBlock(delivered.results, pagesBlockExcerptLen(pages.length), opts.question,
+ const rendered = applied.unit === 'auto'
+ ? renderPagesBlockDetailed(delivered.results, excerptLen, opts.question,
{ verbatim: r => r.delivered?.reason !== 'not_conversation' && r.delivered?.reason !== 'conversation_over_budget', verbatimLen: EVIDENCE_BLOCK_CHAR_CAP, timeZone })
- : renderPagesBlock(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true, timeZone });
- return { pagesBlock, evidenceDelivery: delivered.delivery };
+ : renderPagesBlockDetailed(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true, timeZone });
+ return { pagesBlock: rendered.text, evidenceTruncated: rendered.truncated, evidenceDelivery: delivered.delivery };
}
/**
@@ -638,7 +653,7 @@ export async function runThink(
// budget-aware — 600 chars is the FLOOR (a big gather never collapses each
// page below it) and a small gather spreads the block budget into much
// larger, often complete, per-page windows.
- const { pagesBlock, evidenceDelivery } = await renderThinkPages(engine, opts, gather.pages, temporal.timeZone);
+ const { pagesBlock, evidenceTruncated, evidenceDelivery } = await renderThinkPages(engine, opts, gather.pages, temporal.timeZone, warnings);
const takesForPrompt = gather.takes.map(takesHitToTakeForPrompt);
const { rendered: takesBlock, sanitizedCount } = renderTakesBlock(takesForPrompt);
if (sanitizedCount > 0) {
@@ -970,6 +985,10 @@ export async function runThink(
for (const slug of new Set(resolved.citations.map(c => c.page_slug))) {
if (!gatheredSlugs.has(slug)) warnings.push(`CITATION_NOT_IN_GATHER:${slug}`);
}
+ // #5461: source-qualify each citation from the gather (highest-ranked page with that slug).
+ const sourceOfSlug = new Map<string, string>();
+ for (const pg of gather.pages) if (!sourceOfSlug.has(pg.slug)) sourceOfSlug.set(pg.slug, pg.source_id ?? 'default');
+ for (const c of resolved.citations) c.source_id = sourceOfSlug.get(c.page_slug) ?? null;
// Round-loop scaffolding (rounds > 1 currently re-runs without gap-driven retrieval).
// The loop is in place so the v0.29 gap-fill heuristic doesn't change the call site.
@@ -1005,6 +1024,7 @@ export async function runThink(
// ANDs the not-JSON/sentinel flag with a content check (catches valid-but-empty JSON).
synthesisOk: synthesisOk && response.answer.trim().length > 0,
synthesis_status: synthesisStatus,
+ evidence_truncated: evidenceTruncated,
feedback_evidence: gather.pages.map(pg => ({ source_id: pg.source_id ?? 'default', slug: pg.slug, content_hash: pg.content_hash ?? null })),
taint_refs: [...gather.pages.map(pg => ({ table: 'pages' as const, sourceId: pg.source_id ?? 'default', slug: pg.slug })),
...gather.takes.map(t => ({ table: 'takes' as const, id: t.take_id })), ...trajectoryFactIds.map(id => ({ table: 'facts' as const, id }))],
diff --git a/src/core/think/pages-budget.ts b/src/core/think/pages-budget.ts
new file mode 100644
index 0000000000..535737c5fd
--- /dev/null
+++ b/src/core/think/pages-budget.ts
@@ -0,0 +1,69 @@
+/**
+ * #5461: the think / synthesize pages-block budget, as configuration.
+ *
+ * `renderThinkPages` renders every gathered page as one excerpt. The per-page
+ * excerpt length is `min(ceiling, floor(total / pageCount))` but never below
+ * the 600-character floor (`pagesBlockExcerptLen` in gather.ts), so the total
+ * is a SOFT bound: 40 pages at the 12 000 default render 40 × 600 = 24 000
+ * characters. Raising `think.pages_budget_chars` alone does not deliver whole
+ * pages either: `think.excerpt_ceiling_chars` (2 400 by default) still caps
+ * each excerpt. A caller who wants whole pages raises both.
+ *
+ * Both keys are DB-plane (`gbrain config set`). A value outside its range, or
+ * not an integer, is ignored for that call: the default applies and the
+ * result warns `THINK_BUDGET_CONFIG_IGNORED:<key>`, so a typo never silently
+ * changes what the model sees.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export const THINK_PAGES_BUDGET_KEY = 'think.pages_budget_chars';
+export const THINK_EXCERPT_CEILING_KEY = 'think.excerpt_ceiling_chars';
+
+export const PAGES_BLOCK_TOTAL_BUDGET_CHARS = 12_000;
+export const PAGES_BLOCK_EXCERPT_CEILING_CHARS = 2_400;
+/** The per-page minimum a big gather never collapses below (#4510). */
+export const PAGES_BLOCK_EXCERPT_FLOOR_CHARS = 600;
+
+export const THINK_PAGES_BUDGET_BOUNDS = {
+ [THINK_PAGES_BUDGET_KEY]: { min: 4_000, max: 200_000, fallback: PAGES_BLOCK_TOTAL_BUDGET_CHARS },
+ [THINK_EXCERPT_CEILING_KEY]: { min: PAGES_BLOCK_EXCERPT_FLOOR_CHARS, max: 200_000, fallback: PAGES_BLOCK_EXCERPT_CEILING_CHARS },
+} as const;
+
+export interface PagesBudget {
+ totalChars: number;
+ ceilingChars: number;
+}
+
+export const DEFAULT_PAGES_BUDGET: PagesBudget = {
+ totalChars: PAGES_BLOCK_TOTAL_BUDGET_CHARS,
+ ceilingChars: PAGES_BLOCK_EXCERPT_CEILING_CHARS,
+};
+
+/** Parse one budget value: a base-10 integer inside the key's range, else null. */
+export function parsePagesBudgetValue(key: keyof typeof THINK_PAGES_BUDGET_BOUNDS, raw: string | null | undefined): number | null {
+ if (raw == null || raw.trim() === '') return null;
+ if (!/^\s*\d+\s*$/.test(raw)) return null;
+ const n = Number.parseInt(raw, 10);
+ const { min, max } = THINK_PAGES_BUDGET_BOUNDS[key];
+ return n >= min && n <= max ? n : null;
+}
+
+/**
+ * The budget for one synthesize call: two config reads, each falling back to
+ * its default (with a warning on an explicit bad value; a read failure keeps
+ * the default silently so a config-plane blip never changes the evidence).
+ */
+export async function readThinkPagesBudget(engine: Pick<BrainEngine, 'getConfig'>, warnings: string[]): Promise<PagesBudget> {
+ const read = async (key: keyof typeof THINK_PAGES_BUDGET_BOUNDS): Promise<number> => {
+ const raw = await engine.getConfig(key).catch(() => null);
+ if (raw == null || raw.trim() === '') return THINK_PAGES_BUDGET_BOUNDS[key].fallback;
+ const value = parsePagesBudgetValue(key, raw);
+ if (value === null) {
+ warnings.push(`THINK_BUDGET_CONFIG_IGNORED:${key}`);
+ return THINK_PAGES_BUDGET_BOUNDS[key].fallback;
+ }
+ return value;
+ };
+ const [totalChars, ceilingChars] = await Promise.all([read(THINK_PAGES_BUDGET_KEY), read(THINK_EXCERPT_CEILING_KEY)]);
+ return { totalChars, ceilingChars };
+}
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 8bb4a37b4e..b823f7eab3 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -372,11 +372,13 @@ const synthesize: Operation = {
return {
answer: result.extractive.answer,
sources: result.extractive.citations.map(c => c.page_slug),
+ citations: sourceQualifiedCitations(result.extractive.citations),
gaps: result.gaps,
cost,
synthesis_status: 'extractive_fallback',
pages_gathered: result.pagesGathered,
takes_gathered: result.takesGathered,
+ evidence_truncated: result.evidence_truncated ?? false,
warnings: result.warnings,
...feedbackMeta,
protocol_version: MEMORY_VERBS_VERSION,
@@ -394,11 +396,13 @@ const synthesize: Operation = {
answer: result.answer,
...(result.answer_raw !== undefined ? { answer_raw: result.answer_raw, quote_check: result.quote_check, unverified_quotes: result.unverified_quotes } : {}),
sources: result.citations.map(c => c.page_slug),
+ citations: sourceQualifiedCitations(result.citations),
gaps: result.gaps,
cost,
synthesis_status: 'ok',
pages_gathered: result.pagesGathered,
takes_gathered: result.takesGathered,
+ evidence_truncated: result.evidence_truncated ?? false,
warnings: result.warnings,
...feedbackMeta,
protocol_version: MEMORY_VERBS_VERSION,
@@ -407,6 +411,11 @@ const synthesize: Operation = {
cliHints: { name: 'synthesize', positional: ['question'] },
};
+/** #5461: `sources[]` stays slugs (frozen); `citations[]` is the same list, source-qualified. */
+function sourceQualifiedCitations(citations: Array<{ page_slug: string; row_num: number | null; source_id?: string | null }>) {
+ return citations.map(c => ({ slug: c.page_slug, source_id: c.source_id ?? null, row_num: c.row_num }));
+}
+
// ─── forget ──────────────────────────────────────────────────────────────────
const forget: Operation = {
@@ -730,6 +739,17 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
pages_gathered: { type: 'integer', description: 'Pages retrieved by the gather phase behind this answer.' },
takes_gathered: { type: 'integer', description: 'Takes retrieved by the gather phase behind this answer.' },
warnings: { type: 'array', items: { type: 'string' }, description: 'Machine-stable pipeline warning codes (e.g. LLM_OUTPUT_NOT_JSON, LLM_CALL_FAILED: <class> where <class> is timeout | rate_limited | network | provider_error).' },
+ // #5461 additive: the pages budget is configurable and soft; callers learn when evidence was cut and which source each cited page came from.
+ evidence_truncated: { type: 'boolean', description: 'true when at least one gathered page reached the model as a cut excerpt (think.pages_budget_chars / think.excerpt_ceiling_chars, both soft bounds).' },
+ citations: {
+ type: 'array',
+ description: 'sources[] with provenance, same order and length: the gathered source each cited slug came from (null when the model cited a slug outside the gather).',
+ items: {
+ type: 'object',
+ required: ['slug', 'source_id'],
+ properties: { slug: { type: 'string' }, source_id: { type: ['string', 'null'] }, row_num: { type: ['integer', 'null'] } },
+ },
+ },
},
},
forget: {
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index dc4ca93222..fa77bba4b3 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -7737,6 +7737,7 @@
"cost_usd?: number | undefined",
"diagnostics: { pagesFromHybrid: number; takesFromKeyword: number; takesFromVector: number; graphHits: number; }",
"evidence_delivery?: DeliveryMeta | undefined",
+ "evidence_truncated?: boolean | undefined",
"extractive?: ExtractiveFallback | undefined",
"feedback_evidence?: { source_id: string; slug: string; content_hash: string | null; }[] | undefined",
"gaps: string[]",
diff --git a/test/think-pages-budget-5461.test.ts b/test/think-pages-budget-5461.test.ts
new file mode 100644
index 0000000000..0a4e34b1de
--- /dev/null
+++ b/test/think-pages-budget-5461.test.ts
@@ -0,0 +1,202 @@
+/**
+ * #5461 (wave 15 P7.4): the think / synthesize pages-block budget becomes
+ * configuration (`think.pages_budget_chars`, `think.excerpt_ceiling_chars`),
+ * a truncated evidence block is reported (`evidence_truncated`), and the
+ * synthesize verb adds source-qualified `citations[]` next to the frozen
+ * `sources[]`.
+ *
+ * The budget is SOFT: the 600-character floor can push the total over the
+ * budget, and the excerpt ceiling still cuts a long page when only the total
+ * is raised. The assertions below pin that documented contract, not a hard
+ * bound.
+ *
+ * Protects: what the model is shown and what the caller is told about it.
+ * Fails when: the keys are ignored (default sizes with the key set), when a
+ * cut block reports `evidence_truncated: false`, or when citations lose
+ * their source. Why new: `test/think-pages-block.test.ts` covers the fixed
+ * default sizing only. Seam: the existing stub client / chat transport.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runThink, type ThinkLLMClient } from '../src/core/think/index.ts';
+import { pagesBlockExcerptLen, EXCERPT_CUT_END_MARKER, EXCERPT_CUT_START_MARKER } from '../src/core/think/gather.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __setChatTransportForTests } from '../src/core/ai/gateway.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { runConfig } from '../src/commands/config.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+
+const PAGES_BUDGET_KEY = 'think.pages_budget_chars';
+const EXCERPT_CEILING_KEY = 'think.excerpt_ceiling_chars';
+const PAGE_COUNT = 20;
+const PAGE_CHARS = 10_000;
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (let i = 0; i < PAGE_COUNT; i++) {
+ const body = `Quarterly roadmap review ${i}. ${'Roadmap review notes and decisions for the platform team. '.repeat(Math.ceil(PAGE_CHARS / 58))}`.slice(0, PAGE_CHARS);
+ const imported = await importFromContent(engine, `notes/roadmap-review-${i}`,
+ `---\ntitle: Roadmap review ${i}\ntype: note\n---\n\n${body}\n`, { noEmbed: true, sourceId: 'default' });
+ if (imported.status !== 'imported') throw new Error(`fixture import failed: ${imported.status}`);
+ }
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+afterEach(async () => {
+ __setChatTransportForTests(null);
+ await engine.unsetConfig(PAGES_BUDGET_KEY);
+ await engine.unsetConfig(EXCERPT_CEILING_KEY);
+});
+
+const QUESTION = 'What did the quarterly roadmap review decide for the platform team?';
+
+function stubClient(capture: { prompt: string }, response: Record<string, unknown>): ThinkLLMClient {
+ return {
+ create: async (params: { messages?: Array<{ content: unknown }> }) => {
+ const user = params.messages?.[0]?.content;
+ capture.prompt = typeof user === 'string' ? user : JSON.stringify(user);
+ return {
+ id: 'msg_budget', type: 'message', role: 'assistant', model: 'stub', stop_reason: 'end_turn', stop_sequence: null,
+ usage: { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null },
+ content: [{ type: 'text', text: JSON.stringify(response) }],
+ } as never;
+ },
+ } as unknown as ThinkLLMClient;
+}
+
+function pagesBlockOf(prompt: string): string {
+ const start = prompt.indexOf('<pages>');
+ const end = prompt.indexOf('</pages>');
+ if (start < 0 || end < 0) throw new Error('prompt carried no <pages> block');
+ return prompt.slice(start, end);
+}
+
+describe('pagesBlockExcerptLen with a configurable budget (#5461)', () => {
+ test('defaults are unchanged: 18 pages → 666 chars each, 40 pages → the 600 floor (soft total)', () => {
+ expect(pagesBlockExcerptLen(18)).toBe(666);
+ expect(pagesBlockExcerptLen(40)).toBe(600);
+ expect(40 * pagesBlockExcerptLen(40)).toBeGreaterThan(12_000);
+ });
+
+ test('a bigger total alone is still capped per page by the excerpt ceiling', () => {
+ expect(pagesBlockExcerptLen(18, 600, { totalChars: 60_000, ceilingChars: 2_400 })).toBe(2_400);
+ expect(pagesBlockExcerptLen(18, 600, { totalChars: 60_000, ceilingChars: 60_000 })).toBe(3_333);
+ });
+});
+
+describe('runThink honors think.pages_budget_chars / think.excerpt_ceiling_chars and reports truncation (#5461)', () => {
+ test('default budget: 20 pages of 10 000 chars are cut and evidence_truncated is true', async () => {
+ const capture = { prompt: '' };
+ const result = await runThink(engine, { question: QUESTION, client: stubClient(capture, { answer: 'cut', citations: [], gaps: [] }), withTrajectory: false });
+ // Hybrid keyword retrieval returns most, not necessarily all, of the fixture pages.
+ const gathered = result.pagesGathered;
+ expect(gathered).toBeGreaterThanOrEqual(12);
+ expect(result.evidence_truncated).toBe(true);
+ const block = pagesBlockOf(capture.prompt);
+ expect(block).toContain(EXCERPT_CUT_END_MARKER);
+ expect(block.length).toBeLessThan(gathered * 1_100);
+ });
+
+ test('budget 60 000 over 200 000 chars of pages: more evidence, still truncated by the 2 400 ceiling', async () => {
+ await engine.setConfig(PAGES_BUDGET_KEY, '60000');
+ const capture = { prompt: '' };
+ const result = await runThink(engine, { question: QUESTION, client: stubClient(capture, { answer: 'cut', citations: [], gaps: [] }), withTrajectory: false });
+ expect(result.evidence_truncated).toBe(true);
+ const block = pagesBlockOf(capture.prompt);
+ expect(block.length).toBeGreaterThan(result.pagesGathered * 2_000);
+ expect(block.length).toBeLessThan(result.pagesGathered * 3_000);
+ expect(result.warnings.some(w => w.startsWith('THINK_BUDGET_CONFIG_IGNORED'))).toBe(false);
+ });
+
+ // The gather hands think one chunk per page (chunk_text first), so a raised
+ // ceiling shows each gathered chunk whole, not the 10 000-char page: [R38]
+ // full pages are not promised while an excerpt ceiling exists.
+ test('budget and ceiling both raised: whole gathered chunks, evidence_truncated false, no cut markers', async () => {
+ await engine.setConfig(PAGES_BUDGET_KEY, '200000');
+ await engine.setConfig(EXCERPT_CEILING_KEY, '200000');
+ const capture = { prompt: '' };
+ const result = await runThink(engine, { question: QUESTION, client: stubClient(capture, { answer: 'whole', citations: [], gaps: [] }), withTrajectory: false });
+ expect(result.evidence_truncated).toBe(false);
+ const block = pagesBlockOf(capture.prompt);
+ expect(block).not.toContain(EXCERPT_CUT_START_MARKER);
+ expect(block).not.toContain(EXCERPT_CUT_END_MARKER);
+ expect(block.length).toBeGreaterThan(result.pagesGathered * 2_400);
+ });
+
+ test('an out-of-range or non-integer value is ignored with a warning and the default applies', async () => {
+ await engine.setConfig(PAGES_BUDGET_KEY, '999999');
+ await engine.setConfig(EXCERPT_CEILING_KEY, 'large');
+ const capture = { prompt: '' };
+ const result = await runThink(engine, { question: QUESTION, client: stubClient(capture, { answer: 'cut', citations: [], gaps: [] }), withTrajectory: false });
+ expect(result.warnings).toContain(`THINK_BUDGET_CONFIG_IGNORED:${PAGES_BUDGET_KEY}`);
+ expect(result.warnings).toContain(`THINK_BUDGET_CONFIG_IGNORED:${EXCERPT_CEILING_KEY}`);
+ expect(result.evidence_truncated).toBe(true);
+ expect(pagesBlockOf(capture.prompt).length).toBeLessThan(result.pagesGathered * 1_100);
+ });
+
+ test('citations carry the gathered source id; a slug outside the gather carries null', async () => {
+ const capture = { prompt: '' };
+ const result = await runThink(engine, { question: QUESTION, remote: false, client: stubClient(capture, {
+ answer: 'Decided [notes/roadmap-review-3] and elsewhere [people/nobody].',
+ citations: [
+ { page_slug: 'notes/roadmap-review-3', row_num: null, citation_index: 1 },
+ { page_slug: 'people/nobody', row_num: null, citation_index: 2 },
+ ],
+ gaps: [],
+ }), withTrajectory: false });
+ expect(result.citations.map(c => [c.page_slug, c.source_id])).toEqual([
+ ['notes/roadmap-review-3', 'default'],
+ ['people/nobody', null],
+ ]);
+ });
+});
+
+describe('synthesize verb: additive evidence_truncated and citations[] (#5461)', () => {
+ test('the frozen sources[] stays; citations[] is parallel to it and source-qualified', async () => {
+ __setChatTransportForTests(async () => ({
+ text: JSON.stringify({ answer: 'Decided [notes/roadmap-review-3].', citations: [{ page_slug: 'notes/roadmap-review-3', row_num: null, citation_index: 1 }], gaps: [] }),
+ blocks: [], stopReason: 'end' as const,
+ usage: { input_tokens: 10, output_tokens: 5, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5-20251001', providerId: 'anthropic',
+ }));
+ const res = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () =>
+ dispatchToolCall(engine, 'synthesize', { question: QUESTION }, { remote: true, takesHoldersAllowList: ['world'], sourceId: 'default' }));
+ expect(res.isError).not.toBe(true);
+ const body = JSON.parse(res.content[0].text);
+ expect(body.sources).toEqual(['notes/roadmap-review-3']);
+ expect(body.citations).toEqual([{ slug: 'notes/roadmap-review-3', source_id: 'default', row_num: null }]);
+ expect(body.evidence_truncated).toBe(true);
+ expect(body.protocol_version).toBe(1);
+ });
+});
+
+describe('gbrain config set refuses an out-of-range budget up front (#5461)', () => {
+ async function configSet(args: string[]) {
+ const errs: string[] = [];
+ let exit: number | null = null;
+ const logSpy = spyOn(console, 'log').mockImplementation(() => {});
+ const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
+ const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);
+ try { await runConfig(engine, ['set', ...args]); }
+ catch (e) { if (!(e as Error).message.startsWith('EXIT:')) throw e; }
+ finally { logSpy.mockRestore(); errSpy.mockRestore(); exitSpy.mockRestore(); }
+ return { err: errs.join('\n'), exit: exit as number | null };
+ }
+
+ test('both keys are registered; a bad value exits 1 and is not stored; a good one is', async () => {
+ expect(KNOWN_CONFIG_KEYS).toContain(PAGES_BUDGET_KEY);
+ expect(KNOWN_CONFIG_KEYS).toContain(EXCERPT_CEILING_KEY);
+ for (const [key, bad] of [[PAGES_BUDGET_KEY, '999'], [PAGES_BUDGET_KEY, '12k'], [EXCERPT_CEILING_KEY, '500'], [EXCERPT_CEILING_KEY, '300000']]) {
+ const r = await configSet([key, bad]);
+ expect(r.exit).toBe(1);
+ expect(r.err).toContain(key);
+ expect(r.err).toContain('between');
+ expect(await engine.getConfig(key)).toBeNull();
+ }
+ expect((await configSet([PAGES_BUDGET_KEY, '30000'])).exit).toBeNull();
+ expect(await engine.getConfig(PAGES_BUDGET_KEY)).toBe('30000');
+ });
+});