Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(query): facts block needs a caller budget, respects --limit, never outscores pages; CLI names fact rows (#8411)
garrytan1243bc9d3329
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c8dbf61be9..c20abf9b79 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**`gbrain query --limit N` returns N rows again, the facts block never outscores the pages, and the CLI names fact rows instead of printing `undefined` (#8411).** Since the facts block went on by default (v0.60.491.0), it also ran on queries that passed no budget, because the shipped no-budget evidence plan carries an implicit 24,000-token budget. Its 22% share let up to 40 fact rows in ahead of the pages, so `--limit 3` could print more than a dozen fact rows before the 3 pages. Each block row was scored a hair above the top page, so they all showed the same score and outranked every hit, and the human CLI printed them as `[0.84xx] undefined -- …` because fact rows have no page slug.++### What changed++| Situation | Before | Now |+|---|---|---|+| `query` without `token_budget` (CLI or MCP) | the facts block ran on the implicit budget: up to 40 fact rows on top of `limit` pages | the block does not run; the facts arm fills only free slots, so `limit` caps the whole result |+| `query` with `token_budget` | up to 40 block rows (22% of the budget), whatever the `limit` | up to 40 block rows, 22% of the budget and at most `limit` rows, still oldest first ahead of the pages |+| Block row `score` | top page score + n × 1e-6: above every page | the top page's score: placed first, never ranked above a page |+| Human CLI line for a fact row | `[0.84xx] undefined -- [observed …]` and the fact text on a second line | `[0.84xx] fact:<fact_id> <entity slug> -- [observed …] <fact text>` on one line |++The contract: `limit` caps the page rows. Without `token_budget`, saved facts only fill free rows, so the result never exceeds `limit`. With `token_budget`, the facts block adds at most `limit` rows (and at most 40, within 22% of the budget) ahead of the pages. `--json` rows already carried `fact_id` and keep it. The held-out arm that earned the default (`token_budget` 5,500, `limit` 25, a mean of 7.5 fact rows) runs the same block. `search.query_facts_block` stays on by default.+## [0.60.552.0] - 2026-11-02**A master-red flake in the deferred-publish synthesis test is fixed.** `test/managed-synthesis-postprocess.test.ts` "#5854: a postprocess publish still pending after its wait is deferred, then finished by the next ordinary cycle" released the writer lock before disposing the in-process persistence consumer. Whenever the consumer drained the deferred publish in that gap, the "next ordinary cycle" found nothing left to write, and `written_slugs` came back `[]` (master run 41476223139, shard 14). The test now disposes the consumer before it releases the lock, so the next cycle is the only thing that can finish the publish. The assertions are unchanged. Forced probe: a 1.5 s pause after the lock release fails the old order with the exact CI diff and passes the new order (3 of 3).diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex 359cb3c1eb..e424f2407b 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -389,9 +389,12 @@ Two cross-cutting seams sit around the pipeline rather than inside it:after the pages, in place of the facts arm. No model call. Gates:`docs/eval/decisions/temporal-fact-reserve/`.- **Facts block (default on) and fact source pages (default off), GBRA-205.**- Every `query` with a token budget gets the reserve's dated facts, up to 22%- of the budget and 40 rows, oldest first ahead of the pages, in place of the- facts arm and the temporal reserve. On the sealed held-out set it answered+ Every `query` whose caller passes `token_budget` gets the reserve's dated+ facts, up to 22% of the budget, 40 rows and the caller's `limit`, oldest+ first ahead of the pages, in place of the facts arm and the temporal+ reserve. The no-budget evidence plan's implicit budget does not run it, so an+ unbudgeted `query` returns at most `limit` rows (#8411). Block rows take the+ top page's score: they are placed ahead, not ranked above the pages. On the sealed held-out set it answered183 of 200 questions against 151 without it (gbrain-evals`docs/benchmarks/2026-10-26-gbrain-8k-conversion.md`).`search.query_facts_block=false` turns it off; a config read error alsodiff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 0d5527639a..c84e82b0b7 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -15,6 +15,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.- `src/cli/flag-values.ts` — strict numeric values for CLI-only flags (D4): `intFlagValue` / `numberFlagValue` (digits only, safe integer, `[min, max]`) and `flagValueError` raise `invalid_params` usage errors (exit 2) naming the flag, what it accepts and an example. Used by jobs submit, extract-conversation-facts, eval run-all, sync `--interval`, connectors sync, book-mirror (the absorbed community fixes #5936 #5934 #5933 #5931 #5930 #5909). Tests: each command's `*-numeric-flags`/`*-flags` test.- `src/cli/flag-equals.ts` — `--flag=value` on CLI_ONLY commands (#7619). `cliOnlyFlagArgs` in `src/cli/main.ts` runs `splitFlagEquals` once after routing and the help printers that run no handler, before the self-help handlers' help path, strict arguments, flag validation and dispatch, so no `=` token reaches a handler that would drop it. It also covers the hand-parsed `search modes|stats|tune|diagnose` subcommands, the validation-exempt paths (`jobs submit`, whose consent check reads the `=` spending cap, and `config` except `set`) and the direct `bun run src/commands/auth.ts` entry (which strips and applies the global flags, hands `auth local-writer` to its own parser and runs the unknown-flag validator, `findUnknownFlag` with the same `unknown_flag` envelope and legacy keys, all as main does). Per registered `--flag=value` token: a switch refuses (`invalid_params`, exit 2: a boolean in the command's own table, curated help or `SYNC_FLAGS` for sync, a `--no-` negation, the command's `COMMAND_SWITCHES`, or a name `knownSwitches()` finds boolean in the handler-free `OPERATION_MANIFEST` or any curated help, so `--yes=n` is never answered with `--yes <value>`); `EQUALS_READERS`, keyed by command or `command sub` (the `sync --status` alias reads as `sync status`, `forget --purge` is its own path, and `repos` reads the `sources` keys through `READER_ALIASES`), keeps the token where the handler on that path reads the `=` form itself, empty values included (that handler owns refusing them); elsewhere an empty or flag-like value refuses; the token splits into `--flag value` only when the command's own table declares a value; every other `=` form refuses with the two-argument spelling. Splitting a flag the subcommand never reads leaves its value as a stray positional that handlers taking the first numeric or non-flag token act on (`forget --purge --reason=3 34` purging fact 3), and a reader key wider than its path drops the token in sibling subcommands (`extract links --source-id=x` walked every source), so keys name the narrowest path. A short flag never takes `=` (`-y=n` refuses). A bare `--` ends the scan only on `END_OF_OPTIONS` paths (`agent run`, `frontmatter validate`), whose handler stops there; `serve`, `auth`, `frontmatter generate`, `questions` and `agent logs` read flags after it, so past `--` an `=` token that is not a registered flag refuses (the unknown-flag validator stops at `--`). A true/false word or 0/1 on a flag with no table entry (`--apply=false`, `--expect=on`) refuses naming both readings, never `--apply <value>`, and says a value never turns a switch off. `sources pull --path=` refuses, because main's database-free route matches only the exact token. On the hand-parsed `search` subcommands, which have no registry row, every `=` token but `--json=true` refuses with a neutral message that names the subcommand, echoes no value and vouches for no switch. `--json=true` becomes `--json`. Refusals name `--flag=…`, never the value. `OWN_EQUALS_PARSERS` (own `=`-aware parsers on every path that refuse `=` on their switches, `retrieval-upgrade` and `migrate embeddings` included; not the sources lifecycle subcommands, whose unmanaged fallback reads exact tokens), `call`, `config set`, `eval brainbench` and every subcommand `src/cli/strict-args.ts` governs (`strictSpecFor`) keep their argv. `scripts/generate-flag-registry.ts` skips this module. Pinned by `test/cli-flag-equals.test.ts` (a table over every registered CLI_ONLY flag, both-direction pins of `EQUALS_READERS` against every `=` reader in `src` and of `OWN_EQUALS_PARSERS` against every `=` option parser, stray-positional, dropped-scope, consent and `--` rows, own-parser switch refusals) and `test/serve-flag-equals.test.ts` (real CLI processes on PGLite, `--json` envelope, the direct `auth.ts` entry, `serve -- --access=` and `frontmatter generate` behind `--help` or `--` included).+- `src/cli/search-row-format.ts` — `formatSearchRow`: the human `gbrain search|query` line per row (`[score] slug -- preview`); a saved-fact row prints `fact:<fact_id> <entity>` and its date header and text on one line, never a page slug (#8411).- `src/cli/search-timings.ts` — `gbrain search|query --timings` (#7158; global flag claimed by search/query/ask in `cli-options.ts`): `timeCliPhase` books `connect`, `context` and `remote` in `runSharedOperation`/`runThinClientRouted`; `searchTimingsDocument` makes `--json` print `{results, timings_ms, cost}` (bare array without the flag) and `searchTimingsLine` the stderr line. Absent phase = did not run. Guide: `docs/guides/search-explain.md`. Test: `test/cli-search-timings.test.ts`.- `src/cli/op-param-values.ts` — `opParamValue`: typed values for shared ops from `ParamDef` inside `parseOpArgs` (number → finite, string enum → declared values), `invalid_params` with an example otherwise; mirrors MCP `validateParams`. `opStructuredValue` turns object/array flag text into its value: JSON, or for a string-item array a bare value or comma list (`--types company`, `--types person,company`, #7173); `test/cli-types-param.test.ts`. `parseOpArgs` also honours a bare `--` (D6). Test: `test/cli-op-typed-args.test.ts`.- `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `writeback`, `harness_wiring`, `skills_scaffold`); the stdio onboarding cache reuses it with writeback and skills only, and `setupFirstRunNotices` is `gbrain setup`'s form (from `init --json`: `harness_wiring` dropped, `why`/`user_message` framed as settings in effect that the agent relays in the install reply instead of a reply-to-continue question; Cat 41 wave 2, pinned by `test/init-first-run.test.ts`). `firstRunBundle`/`harnessRegistrationCommand` take `gbrain init --surface`. Tests: `test/cli-json-guard.test.ts`.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 6f6feca751..4e261a2612 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it by a ranking link type or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.- The facts arm, temporal fact reserve, facts block and fact source pages (`search/facts-arm.ts`): [Core Search (evidence blocks)](core-search-evidence.md).- `src/core/search/fact-relevance.ts` — question relevance for saved facts, shared by recall's `question` (`facts/question-recall.ts`), the temporal fact reserve and (pool only) the facts arm. `collectFactCandidates`: one bounded pool under recall's read policy (source scope, active and not superseded, audit rows excluded, quarantine and rederive hiding through `projectionEligibleSql`, the trust floor, remote world-only, `privateProvenanceFilterFragment` when `excludePrivate`) plus recall's filters inside every arm before its LIMIT (`(source_id, entity_slug)` pairs, `source_session`, event-time since, escaped `ILIKE` grep); arms, run concurrently and merged in a fixed order, are keyword FTS (`factsFtsDocument`, served by `idx_facts_fts`), cosine (cast to the facts column type, filtered on model only so the HNSW index serves it, a stale hash or other dimensions yielding no similarity; `ef_search` sized to the depth and pgvector's iterative scan when `hnswIterativeScan` is set) and the named entity page's facts in its own source; depths are bound parameters; `cosineForAll` scores every candidate's cosine whichever arm found it. A missing embedding column or other dimensions skips the cosine arm; any other DB error throws. `scoreFactCandidates`: cosine + whole-word term share + 0.1 when dated, the share's denominator growing past `TERM_STUFFING_RATIO` times the question's terms for a long fact; order score, newest valid_from, id. `admitted`: the `reserve` rule (cosine >= 0.5 or share >= 0.34) or the `facts_arm` rule (cosine >= 0.6, half the terms, or the named entity). `countUncomparableFacts` counts the pool's facts the cosine arm cannot compare, per source: candidates from `idx_facts_unembedded` and `idx_facts_embedding_model` first, the read policy on those rows only. The keyword arm and the count run under `customPlan` (`plan_cache_mode = force_custom_plan` in a transaction): a cached generic plan cannot see the source arrays and nests the policy anti-joins over every match. p95 at 100k facts: Postgres 51 ms local / 65 ms remote, PGLite 152 / 139 ms. Tests: `test/fact-relevance.test.ts`, `test/recall-question.test.ts`.-- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, fact source pages, then the facts arm), each behind its own key (the facts arm default on, the rest off); a query with a token budget takes the facts block (`search.query_facts_block`, default on) or, with a temporal cue, the temporal fact reserve (`search.temporal_fact_reserve`) instead of the facts arm; with all off it returns the rows untouched.+- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, fact source pages, then the facts arm), each behind its own key (the facts arm default on, the rest off); a query whose caller passed `token_budget` takes the facts block (`search.query_facts_block`, default on; at most `limit` rows, scored at the top page's score; #8411) or, with a temporal cue, the temporal fact reserve (`search.temporal_fact_reserve`) instead of the facts arm; with all off it returns the rows untouched.- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns; a segmented page's row says `segmented` and carries no body) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction. Chunk rows carry `projected_byte_start/end` when recorded, and on a segmented page their `occurrence_id` (the span is relative to that occurrence's projection), the references `search/segmented-evidence.ts` reads windows around.diff --git a/docs/mcp/README.md b/docs/mcp/README.mdindex 2b7e0025cd..64062b1461 100644--- a/docs/mcp/README.md+++ b/docs/mcp/README.md@@ -208,10 +208,14 @@ pass it to `get_page`.{"result_type":"fact","fact_id":"412","page_slug":"companies/acme-example","follow_up":{"op":"recall","args":{"entity":"companies/acme-example"}},"title":"Saved fact about companies/acme-example","chunk_text":"Saved fact (fact; valid from 2026-09-01; provenance: user update): The billing contact for Acme Example is Bob.","score":0.42,"source_id":"default"}```-`search.query_facts_arm=false` turns these rows off. A `query` with a token-budget instead gets the facts block (on by default): up to 40 dated fact rows,-oldest first, ahead of the pages and within 22% of the budget, in place of the-facts arm. `search.query_facts_block=false` restores the arm.+`search.query_facts_arm=false` turns these rows off. A `query` that passes+`token_budget` instead gets the facts block (on by default): dated fact rows,+oldest first, ahead of the pages, within 22% of the budget and at most 40 rows+and at most `limit` rows, in place of the facts arm. Block rows carry the top+page's `score`: they are placed first, not ranked above the pages, so read+`result_type` rather than comparing scores. Without `token_budget`, fact+rows only fill free slots, so `limit` caps the whole result.+`search.query_facts_block=false` restores the arm.## Recent facts in `_meta.brain_hot_memory`diff --git a/src/cli/main.ts b/src/cli/main.tsindex 674037abc6..629a13a1bf 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -1696,9 +1696,7 @@ export function formatResult(// (autocut decision, `degraded: reranker_skipped (no_key)`) render.return formatResultsExplain(results, meta ?? undefined);}- return retrievalIncompleteLine(meta) + results.map(r =>- `[${r.score?.toFixed(4) || '?'}] ${r.slug} -- ${require('../core/search/transcript-quote.ts').rowPreview(r, 100)}${r.stale ? ' (stale)' : ''}`,- ).join('\n') + '\n';+ return retrievalIncompleteLine(meta) + results.map(require('./search-row-format.ts').formatSearchRow).join('\n') + '\n';}case 'get_tags': {const tags = result as string[];diff --git a/src/cli/search-row-format.ts b/src/cli/search-row-format.tsnew file mode 100644index 0000000000..a83f17ad34--- /dev/null+++ b/src/cli/search-row-format.ts@@ -0,0 +1,13 @@+/** One human line per `search` / `query` row; a saved-fact row is named by its fact id and entity, never a page slug (#8411). */+import type { SearchResult } from '../core/types.ts';+import { rowPreview } from '../core/search/transcript-quote.ts';++type Row = SearchResult & { fact_id?: string; page_slug?: string; follow_up?: { args?: Record<string, string> } };++export function formatSearchRow(r: Row): string {+ const score = `[${r.score?.toFixed(4) || '?'}]`;+ const preview = rowPreview(r, 100);+ if (r.result_type !== 'fact') return `${score} ${r.slug} -- ${preview}${r.stale ? ' (stale)' : ''}`;+ const entity = r.page_slug ?? r.follow_up?.args?.entity;+ return `${score} fact:${r.fact_id}${entity ? ` ${entity}` : ''} -- ${preview.replace(/\s*\n\s*/g, ' ')}`;+}diff --git a/src/core/search/facts-arm.ts b/src/core/search/facts-arm.tsindex 1f84004be6..b29f242686 100644--- a/src/core/search/facts-arm.ts+++ b/src/core/search/facts-arm.ts@@ -46,7 +46,7 @@ export const MAX_RESERVE_ROWS = 20;/** Share of the caller's row count reserved facts may take (at least one row). */export const TEMPORAL_RESERVE_ROW_SHARE = 0.3;-/** GBRA-205 facts block (`search.query_facts_block`, default off): every budgeted query, ahead of the pages. */+/** GBRA-205 facts block (`search.query_facts_block`, default on): every query with a caller token budget, ahead of the pages. */export const QUERY_FACTS_BLOCK_KEY = 'search.query_facts_block';/** Share of the caller's token budget the facts block may take (about 1,800 of 8,100, as the measured combined lane). */export const QUERY_FACTS_BLOCK_SHARE = 0.22;@@ -219,10 +219,13 @@ export function applyTemporalFactReserve(engine: BrainEngine, query: string, res/*** Facts block (GBRA-205): the same question-ranked, dated facts as the- * temporal reserve, for every budgeted query, up to QUERY_FACTS_BLOCK_SHARE- * of the budget and MAX_FACTS_BLOCK_ROWS rows, oldest first ahead of the- * pages. The facts add rows (every page row stays) and pages fill the rest of- * the budget. No match or any error: the results unchanged.+ * temporal reserve, for every query whose caller passed a token budget, up to+ * QUERY_FACTS_BLOCK_SHARE of the budget and MAX_FACTS_BLOCK_ROWS rows and+ * never more rows than the caller's row count (#8411), oldest first ahead of+ * the pages. Block rows take the top page's score: they are placed, not+ * ranked against the pages, and never outscore them. The facts add rows+ * (every page row stays) and pages fill the rest of the budget. No match or+ * any error: the results unchanged.*/export function applyFactsBlock(engine: BrainEngine, query: string, results: SearchResult[], opts: FactsArmOpts & { budget: number }): Promise<SearchResult[]> {return applyFactReserve(engine, query, results, opts, FACTS_BLOCK);@@ -235,7 +238,7 @@ async function applyFactReserve(engine: BrainEngine, query: string, results: Seaconst scored = scoreFactCandidates(query, candidates).filter(s => admitted(s, 'reserve')).map(s => ({ c: s.candidate }));if (!scored.length) return results;const rowCap = Math.max(results.length, (await opts.rowCap?.().catch(() => 0)) ?? 0);- const maxRows = policy.rowShare === null ? policy.maxRows : Math.min(policy.maxRows, Math.max(1, Math.floor(rowCap * policy.rowShare)));+ const maxRows = policy.rowShare === null ? Math.min(policy.maxRows, rowCap) : Math.min(policy.maxRows, Math.max(1, Math.floor(rowCap * policy.rowShare)));const pageSlugs = await readableEntityPages(engine, scored.map(x => x.c), opts.readScope).catch(() => new Set<string>());const fromQuoted = await factsFromQuotedPages(engine, scored.map(x => Number(x.c.id)));let left = Math.floor(opts.budget * policy.share);@@ -255,7 +258,7 @@ async function applyFactReserve(engine: BrainEngine, query: string, results: Seaconst pagesTop = results.reduce((m, r) => (Number.isFinite(r.score) && r.score > m ? r.score : m), results[0]?.score ?? 1);const rows = policy.position === 'after'? chosen.map(({ row }, i) => ({ ...row, score: pagesFloor - (i + 1) * 1e-6 }))- : chosen.map(({ row }, i) => ({ ...row, score: pagesTop + (chosen.length - i) * 1e-6 }));+ : chosen.map(({ row }) => ({ ...row, score: pagesTop }));let pages = (policy.rowShare === null ? results : results.slice(0, Math.max(0, Math.min(results.length, rowCap - rows.length)))).map(r => ({ ...r }));if (opts.tokenBudget) pages = enforceTokenBudget(pages, Math.max(1, opts.tokenBudget - rows.reduce((n, r) => n + resultTokens(r), 0))).results;const merged = policy.position === 'after' ? [...pages, ...rows] : [...rows, ...pages];diff --git a/src/core/search/query-arms.ts b/src/core/search/query-arms.tsindex e022b16ad9..f63d69f576 100644--- a/src/core/search/query-arms.ts+++ b/src/core/search/query-arms.ts@@ -4,8 +4,9 @@* (`search.entity_anchoring`, default off, search/entity-anchor.ts), fact* source pages (`search.fact_source_pages`, default off) and then the facts* arm (`search.query_facts_arm`, default on, search/facts-arm.ts), or in its- * place, for a query with a token budget, the facts block- * (`search.query_facts_block`, default on) or, with a temporal cue, the+ * place, for a query whose caller passed a token budget, the facts block+ * (`search.query_facts_block`, default on; the no-budget evidence plan's+ * implicit budget does not count, #8411) or, with a temporal cue, the* temporal fact reserve (`search.temporal_fact_reserve`, default off). With* all off the rows pass through unchanged; the facts block is checked first, so* turning it off restores the temporal reserve or the facts arm.@@ -30,7 +31,8 @@ async function applyFactsStage(engine: BrainEngine, p: Record<string, unknown>,const opts = { sourceId: scope.sourceId, sourceIds: scope.sourceIds, remote: scope.remote, minTrust: scope.minTrust, suppressFlagged: scope.suppressFlagged, queryEmbedding: scope.queryEmbedding, rowCap: scope.rowCap, readScope: scope, tokenBudget };const pages = await factSourcePagesEnabled(engine) ? await applyFactSourcePages(engine, query, anchored, opts) : anchored;const budget = scope.evidencePlan ? scope.evidenceBudget : tokenBudget;- if (budget && await queryFactsBlockEnabled(engine)) return applyFactsBlock(engine, query, pages, { ...opts, budget });+ const callerBudget = typeof p.token_budget === 'number' && p.token_budget > 0;+ if (budget && callerBudget && await queryFactsBlockEnabled(engine)) return applyFactsBlock(engine, query, pages, { ...opts, budget });if (budget && hasTemporalCue(query) && await temporalFactReserveEnabled(engine)) return applyTemporalFactReserve(engine, query, pages, { ...opts, budget });if (!await queryFactsArmEnabled(engine)) return pages;return applyFactsArm(engine, query, pages, opts);diff --git a/test/query-facts-block-8411.test.ts b/test/query-facts-block-8411.test.tsnew file mode 100644index 0000000000..e42e320acd--- /dev/null+++ b/test/query-facts-block-8411.test.ts@@ -0,0 +1,114 @@+/**+ * #8411: `query` with the facts block on (the default). An unbudgeted query+ * (the shipped no-budget `auto` plan) must not run the block, so `limit`+ * caps the rows; a budgeted query's block is capped at the caller's row count+ * and never scores above the top page; the CLI prints a fact row's identity,+ * never `undefined`. PGLite, keyword-only, no network. Placeholders only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { handleToolCall } from '../src/mcp/server.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { formatResult } from '../src/cli/main.ts';+import type { SearchResult } from '../src/core/types.ts';+import { newSource, page, putPage } from './helpers/pinned-questions-fixture.ts';++type Row = SearchResult & { fact_id?: string; page_slug?: string };++let engine: PGLiteEngine;+let sourceId: string;+const Q = 'Where is the acme-example widget launch venue?';+const FACTS = 12;+const local = async (params: Record<string, unknown>) =>+ await handleToolCall(engine, 'query', { query: Q, expand: false, use_cache: false, source_id: sourceId, ...params }) as Row[];+const remote = async (params: Record<string, unknown>) => {+ const auth = { token: 't', clientId: 'gbrain-8411-probe', scopes: ['read'], sourceId, allowedSources: [sourceId] };+ const res = await dispatchToolCall(engine, 'query', { query: Q, expand: false, ...params },+ { remote: true, transport: 'stdio', sourceId, auth, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} } });+ return JSON.parse((res.content[0] as { text: string }).text) as Row[];+};+const isFact = (r: Row) => r.result_type === 'fact';++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ sourceId = await newSource(engine);+ await putPage(engine, sourceId, 'companies/acme-example', page('company', 'Acme example', 'Acme example plans a widget launch at a venue.'));+ for (let i = 0; i < 6; i++) {+ await putPage(engine, sourceId, `conversations/launch-${i}`, page('conversation', `Launch chat ${i}`,+ `**User:** acme-example widget launch venue, chat ${i}. The widget launch venue moved again.\n\n**Assistant:** Noted the acme-example launch venue.`, `date: 2026-07-0${i + 1}\n`));+ }+ for (let i = 0; i < FACTS; i++) {+ await engine.executeRaw(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence, valid_from)+ VALUES ($1, 'companies/acme-example', $2, 'event', 'conversation', 'world', 1, $3::timestamptz)`,+ [sourceId, `The acme-example widget launch venue changed to hall ${i}.`, `2026-06-${String(i + 1).padStart(2, '0')}T00:00:00Z`]);+ }+}, 120_000);+afterAll(async () => { await engine?.disconnect(); }, 60_000);++describe('#8411 limit: an unbudgeted query returns at most limit rows', () => {+ test('MCP local (the CLI path): limit 3 gives 3 rows', async () => {+ const rows = await local({ limit: 3 });+ expect(rows.length).toBeLessThanOrEqual(3);+ expect(rows.filter(r => !isFact(r)).length).toBeGreaterThan(0);+ });++ test('MCP remote: limit 3 gives 3 rows', async () => {+ const rows = await remote({ limit: 3 });+ expect(rows.length).toBeLessThanOrEqual(3);+ expect(rows.filter(r => !isFact(r)).length).toBeGreaterThan(0);+ });+});++describe('#8411 budgeted query: the facts block is capped by limit and never outscores the pages', () => {+ for (const [name, run] of [['local', local], ['remote', remote]] as const) {+ test(`${name}: block rows lead, at most limit of them, scores not above the top page`, async () => {+ const rows = await run({ limit: 3, token_budget: 4000 });+ const facts = rows.filter(isFact);+ const pages = rows.filter(r => !isFact(r));+ expect(facts.length).toBeGreaterThanOrEqual(1);+ expect(facts.length).toBeLessThanOrEqual(3);+ expect(pages.length).toBeLessThanOrEqual(3);+ expect(rows.slice(0, facts.length).every(isFact)).toBe(true);+ const topPage = Math.max(...pages.map(r => r.score));+ for (const f of facts) expect(f.score).toBeLessThanOrEqual(topPage);+ });+ }++ test('a budget with a large limit still delivers the whole block (the measured arm is unchanged)', async () => {+ const rows = await local({ limit: 25, token_budget: 4000 });+ expect(rows.filter(isFact).length).toBe(FACTS);+ });+});++describe('#8411 CLI rendering', () => {+ test('human output names each fact row (fact id and entity page), never undefined', async () => {+ const rows = await local({ limit: 3, token_budget: 4000 });+ const facts = rows.filter(isFact);+ expect(facts.length).toBeGreaterThan(0);+ const out = formatResult('query', rows, {});+ expect(out).not.toContain('undefined');+ for (const f of facts) expect(out).toContain(`fact:${f.fact_id} companies/acme-example -- [observed unknown; valid `);+ expect(out.split('\n').filter(l => l.includes(' fact:')).length).toBe(facts.length);+ expect(out.split('\n').filter(l => l.startsWith('The acme-example')).length).toBe(0);+ expect(out.split('\n').filter(l => /^\[\d/.test(l)).length).toBe(rows.length);+ });++ test('--json: every fact row carries fact_id', async () => {+ const rows = await local({ limit: 3, token_budget: 4000 });+ const parsed = JSON.parse(formatResult('query', rows, { json: true }));+ const out = (Array.isArray(parsed) ? parsed : parsed.results) as Row[];+ const facts = out.filter(isFact);+ expect(facts.length).toBeGreaterThan(0);+ for (const f of facts) expect(f.fact_id).toMatch(/^\d+$/);+ });++ test('unbudgeted --limit 3 prints exactly the returned rows, none undefined', async () => {+ const rows = await local({ limit: 3 });+ const out = formatResult('query', rows, {});+ expect(out).not.toContain('undefined');+ expect(out.split('\n').filter(l => /^\[\d/.test(l)).length).toBeLessThanOrEqual(3);+ });+});