Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): bounded keyword OR fallback, title-only title arm, vector walk widening, per-call CPU cuts; retrieval-scale bench; gbrain-first guidance
garrytan9fcb90f17c1a
diff --git a/AGENTS.md b/AGENTS.mdindex 7aa11956b6..d878104033 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -57,6 +57,14 @@ Bun blocks gbrain's postinstall on `bun install -g` (`Blocked 1 postinstall`); a## Memory operating protocol+**Retrieval: gbrain first.** For anything in the brain, run `gbrain search` (names,+codes, phrases) or `gbrain query` (questions), then `gbrain get <slug>` on a hit.+Don't grep, cat or SQL the brain checkout first. Filters agents miss:+`--types '["meeting"]'`, `--match keyword` (every matching page), `--since`/`--until`+on `query`, `--source <id>`, `--limit`, `--json`; `gbrain backlinks <slug>` and+`gbrain timeline <slug>` for links and dated events. Copyable examples:+[brain-first](skills/conventions/brain-first.md#retrieval-gbrain-first).+Recall relevant saved context before answering. Save explicit requests to remember with provenance; confirm corrections against the stored record. Automatic capture requires opt-in. Withdrawal (`forget`) removes a fact from active memory; history, source material, and private backups may remain. Never promise physical erasure. Verify changes with actual GBrain calls and distinguish a local test from a new-conversation test in the harness.Durable preferences and facts belong in shared memory when the user wants themdiff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex 57d3185d67..897da9257a 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -341,6 +341,11 @@ Only after enabling the selected embedding provider, run `gbrain embed --stale`.Use `gbrain query` for expanded retrieval only when its provider use is intended;`--no-expand` opts out of expansion independently of the mode.+Once imported, retrieve through gbrain rather than the files: search, then+`gbrain get <slug>`. Filters (`--types`, `--match keyword`, `query --since/--until`,+`--source`, `--json`) are in+[Retrieval: gbrain first](skills/conventions/brain-first.md#retrieval-gbrain-first).+## Step 4.5: Wire the Knowledge GraphIf the user already had a brain repo (Step 3 imported existing markdown), backfilldiff --git a/llms-full.txt b/llms-full.txtindex 876bf92711..3014927d8b 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1805,6 +1805,14 @@ Bun blocks gbrain's postinstall on `bun install -g` (`Blocked 1 postinstall`); a## Memory operating protocol+**Retrieval: gbrain first.** For anything in the brain, run `gbrain search` (names,+codes, phrases) or `gbrain query` (questions), then `gbrain get <slug>` on a hit.+Don't grep, cat or SQL the brain checkout first. Filters agents miss:+`--types '["meeting"]'`, `--match keyword` (every matching page), `--since`/`--until`+on `query`, `--source <id>`, `--limit`, `--json`; `gbrain backlinks <slug>` and+`gbrain timeline <slug>` for links and dated events. Copyable examples:+[brain-first](skills/conventions/brain-first.md#retrieval-gbrain-first).+Recall relevant saved context before answering. Save explicit requests to remember with provenance; confirm corrections against the stored record. Automatic capture requires opt-in. Withdrawal (`forget`) removes a fact from active memory; history, source material, and private backups may remain. Never promise physical erasure. Verify changes with actual GBrain calls and distinguish a local test from a new-conversation test in the harness.Durable preferences and facts belong in shared memory when the user wants them@@ -2952,6 +2960,11 @@ Only after enabling the selected embedding provider, run `gbrain embed --stale`.Use `gbrain query` for expanded retrieval only when its provider use is intended;`--no-expand` opts out of expansion independently of the mode.+Once imported, retrieve through gbrain rather than the files: search, then+`gbrain get <slug>`. Filters (`--types`, `--match keyword`, `query --since/--until`,+`--source`, `--json`) are in+[Retrieval: gbrain first](skills/conventions/brain-first.md#retrieval-gbrain-first).+## Step 4.5: Wire the Knowledge GraphIf the user already had a brain repo (Step 3 imported existing markdown), backfill@@ -4803,7 +4816,7 @@ When multiple skills could match:These apply to ALL brain-writing skills:- `skills/conventions/quality.md` — citations, back-links, notability gate-- `skills/conventions/brain-first.md` — check brain before external APIs+- `skills/conventions/brain-first.md` — search gbrain before external APIs, brain files or SQL; copyable retrieval filters- `skills/conventions/brain-routing.md` — which brain (DB) and which source (repo) to target; cross-brain federation is latent-space only- `skills/conventions/schema-evolution.md` — when to add a type vs alias vs prefix (read before `schema-author`)- `skills/conventions/line-grammar.md` — typed relation lines (`- works_at [[companies/x]]`), fact lines and `@effective[...)` ranges in compiled truthdiff --git a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.mdindex cadb44bdc8..ad98da1d90 100644--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md@@ -36,7 +36,7 @@ provenance; automatic capture is off until the user opts in. Reading this skilldoes not enable capture, delegation, or paid enrichment. A chat-only instructionsuppresses writes for that turn, including when standing capture is enabled.-> **Convention:** See `skills/conventions/brain-first.md` for the 5-step lookup protocol.+> **Convention:** See `skills/conventions/brain-first.md` for the lookup chain and copyable retrieval filters.> **Convention:** See `skills/conventions/quality.md` for citation and back-link rules.> **Memory verbs (MEMORY_VERBS v1, gbrain ≥ 0.43).** Over MCP, prefer the five@@ -132,6 +132,9 @@ Before using ANY external API to research a person, company, or topic:6. Check timeline: recent events involving this entityThe brain almost always has something. External APIs fill gaps, not start from scratch.+Search gbrain before reading, grepping or querying brain files directly; filters+(`--types`, `--match keyword`, `query --since/--until`, `--source`, `--json`) are+in the brain-first convention's "Retrieval: gbrain first" block.**⚠️ NEVER scope/count a corpus with shallow `ls` — query gbrain or `find`.** Federated sources often carry MULTIPLE coexisting directory conventions — a flat legacy layer AND a date-nested `meetings/YYYY/MM/` layer. A non-recursive `ls dir/*.md` sees only one and undercounts massively. Real example: a shallow `ls` of one source's `meetings/` counted 132 files, almost all the user's, and concluded that WAS the corpus — missing thousands of transcripts nested under `meetings/YYYY/MM/`. To count/scope a brain corpus:- **Best:** `gbrain sources list` (shows per-source indexed page counts) + `gbrain query`. gbrain indexes ALL federated sources correctly; trust its index, not the filesystem.diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md b/plugin-variants/gbrain-coding/skills/conventions/brain-first.mdindex 844840fbad..5cc243e58f 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md@@ -5,6 +5,38 @@Sub-agents and fresh sessions inherit gbrain tools but not the knowledge ofwhen and how to use them. This file is that knowledge.+## Retrieval: gbrain first++For anything in the brain, search gbrain, then read the page a hit names. Don't+`grep`, `rg` or `cat` the brain checkout, or run SQL over pages and+frontmatter, before gbrain: gbrain reads the index across sources, ranks results,+filters by type, date and source, and returns the slug to read next. Use the+files only when gbrain is unreachable or for an edit not yet synced.++```bash+gbrain search "Acme Example" # names, codes, exact phrases+gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)+gbrain query "why did the launch move" # questions and concepts+gbrain search "launch" --types '["meeting","person"]' # only these page types+gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)+gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'+gbrain get companies/acme-example # read the page a hit points to+gbrain recall "Alice Example" # facts saved with remember+gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)+gbrain timeline companies/acme-example --since 2026-10-01 # dated events on one page+gbrain list --type meeting --limit 50 # enumerate by type or --tag (instead of SQL)+```++- `--types` takes a JSON array. `--since`/`--until` are `query` flags+ (YYYY-MM-DD or 7d/2w/1y) and match each page's effective date: its+ frontmatter date, else when it was imported.+- Keyword search matches words, not slugs: search `"Acme Example"`, and use+ `backlinks` to find pages linking to `companies/acme-example`.+- Without `--source`, a search reads the resolved source (a notice names it+ when it routes); `--source __all__` searches every source.+- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.+ Read a degraded notice before concluding the brain has nothing.+## Available GBrain ToolsYour tool inventory includes these (prefixed `gbrain__` in OpenClaw):diff --git a/plugin-variants/gbrain-coding/skills/correction-pipeline/SKILL.md b/plugin-variants/gbrain-coding/skills/correction-pipeline/SKILL.mdindex c98df21a00..fc49553e2e 100644--- a/plugin-variants/gbrain-coding/skills/correction-pipeline/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/correction-pipeline/SKILL.md@@ -59,10 +59,12 @@ gbrain search "<relevant terms>" --limit 10```For concept-shaped or synonym-phrased claims, escalate to `gbrain query-"<question>"` (LLM expansion recovers phrasings `search` misses). Also grep-the brain repo checkout directly — resolve it once from config:+"<question>"` (LLM expansion recovers phrasings `search` misses). To list+every indexed page carrying the claim, use a keyword search (it pages every+match); grep the checkout only for edits not yet synced:```bash+gbrain search '"<wrong claim terms>"' --match keywordBRAIN_DIR=$(gbrain config get sync.repo_path)grep -ri "<wrong claim terms>" "$BRAIN_DIR/people/" "$BRAIN_DIR/companies/" "$BRAIN_DIR/concepts/" 2>/dev/null```@@ -167,8 +169,8 @@ The wrong fact may have propagated into OTHER brain pages, synthesis output,or memory files.```bash-grep -ri "<wrong claim terms>" "$BRAIN_DIR" 2>/dev/null | grep -v ".git"-gbrain search "<wrong claim terms>" --limit 20+gbrain search '"<wrong claim terms>"' --match keyword+grep -ri "<wrong claim terms>" "$BRAIN_DIR" 2>/dev/null | grep -v ".git" # edits not yet synced```Fix ALL instances, not just the first one found. Re-sync after repo edits.diff --git a/plugin-variants/gbrain-coding/skills/query/SKILL.md b/plugin-variants/gbrain-coding/skills/query/SKILL.mdindex 6469a19517..0ac43a80ee 100644--- a/plugin-variants/gbrain-coding/skills/query/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/query/SKILL.md@@ -69,6 +69,9 @@ This skill guarantees:- Cheap-hybrid search gbrain for exact tokens / known names (search)- Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)- List pages in gbrain by type or check backlinks for structural queries+ - Narrow with filters instead of grepping the brain checkout: `--types '["meeting"]'`,+ `--match keyword`, `gbrain query "<q>" --since 2026-09-01 --until 2026-09-30`, `--source <id>`.+ Copyable examples: "Retrieval: gbrain first" in `skills/conventions/brain-first.md`.3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.5. **Flag gaps.** If the brain doesn't have info, say "the brain doesn't have information on X" rather than hallucinating. Read the result's notices first (see "When it fails"): a degraded or truncated result is not a gap.diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md b/plugin-variants/gbrain-daily/skills/conventions/brain-first.mdindex 844840fbad..5cc243e58f 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md@@ -5,6 +5,38 @@Sub-agents and fresh sessions inherit gbrain tools but not the knowledge ofwhen and how to use them. This file is that knowledge.+## Retrieval: gbrain first++For anything in the brain, search gbrain, then read the page a hit names. Don't+`grep`, `rg` or `cat` the brain checkout, or run SQL over pages and+frontmatter, before gbrain: gbrain reads the index across sources, ranks results,+filters by type, date and source, and returns the slug to read next. Use the+files only when gbrain is unreachable or for an edit not yet synced.++```bash+gbrain search "Acme Example" # names, codes, exact phrases+gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)+gbrain query "why did the launch move" # questions and concepts+gbrain search "launch" --types '["meeting","person"]' # only these page types+gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)+gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'+gbrain get companies/acme-example # read the page a hit points to+gbrain recall "Alice Example" # facts saved with remember+gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)+gbrain timeline companies/acme-example --since 2026-10-01 # dated events on one page+gbrain list --type meeting --limit 50 # enumerate by type or --tag (instead of SQL)+```++- `--types` takes a JSON array. `--since`/`--until` are `query` flags+ (YYYY-MM-DD or 7d/2w/1y) and match each page's effective date: its+ frontmatter date, else when it was imported.+- Keyword search matches words, not slugs: search `"Acme Example"`, and use+ `backlinks` to find pages linking to `companies/acme-example`.+- Without `--source`, a search reads the resolved source (a notice names it+ when it routes); `--source __all__` searches every source.+- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.+ Read a degraded notice before concluding the brain has nothing.+## Available GBrain ToolsYour tool inventory includes these (prefixed `gbrain__` in OpenClaw):diff --git a/plugin-variants/gbrain-daily/skills/query/SKILL.md b/plugin-variants/gbrain-daily/skills/query/SKILL.mdindex 6469a19517..0ac43a80ee 100644--- a/plugin-variants/gbrain-daily/skills/query/SKILL.md+++ b/plugin-variants/gbrain-daily/skills/query/SKILL.md@@ -69,6 +69,9 @@ This skill guarantees:- Cheap-hybrid search gbrain for exact tokens / known names (search)- Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)- List pages in gbrain by type or check backlinks for structural queries+ - Narrow with filters instead of grepping the brain checkout: `--types '["meeting"]'`,+ `--match keyword`, `gbrain query "<q>" --since 2026-09-01 --until 2026-09-30`, `--source <id>`.+ Copyable examples: "Retrieval: gbrain first" in `skills/conventions/brain-first.md`.3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.5. **Flag gaps.** If the brain doesn't have info, say "the brain doesn't have information on X" rather than hallucinating. Read the result's notices first (see "When it fails"): a degraded or truncated result is not a gap.diff --git a/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.mdindex cadb44bdc8..ad98da1d90 100644--- a/plugin/skills/brain-ops/SKILL.md+++ b/plugin/skills/brain-ops/SKILL.md@@ -36,7 +36,7 @@ provenance; automatic capture is off until the user opts in. Reading this skilldoes not enable capture, delegation, or paid enrichment. A chat-only instructionsuppresses writes for that turn, including when standing capture is enabled.-> **Convention:** See `skills/conventions/brain-first.md` for the 5-step lookup protocol.+> **Convention:** See `skills/conventions/brain-first.md` for the lookup chain and copyable retrieval filters.> **Convention:** See `skills/conventions/quality.md` for citation and back-link rules.> **Memory verbs (MEMORY_VERBS v1, gbrain ≥ 0.43).** Over MCP, prefer the five@@ -132,6 +132,9 @@ Before using ANY external API to research a person, company, or topic:6. Check timeline: recent events involving this entityThe brain almost always has something. External APIs fill gaps, not start from scratch.+Search gbrain before reading, grepping or querying brain files directly; filters+(`--types`, `--match keyword`, `query --since/--until`, `--source`, `--json`) are+in the brain-first convention's "Retrieval: gbrain first" block.**⚠️ NEVER scope/count a corpus with shallow `ls` — query gbrain or `find`.** Federated sources often carry MULTIPLE coexisting directory conventions — a flat legacy layer AND a date-nested `meetings/YYYY/MM/` layer. A non-recursive `ls dir/*.md` sees only one and undercounts massively. Real example: a shallow `ls` of one source's `meetings/` counted 132 files, almost all the user's, and concluded that WAS the corpus — missing thousands of transcripts nested under `meetings/YYYY/MM/`. To count/scope a brain corpus:- **Best:** `gbrain sources list` (shows per-source indexed page counts) + `gbrain query`. gbrain indexes ALL federated sources correctly; trust its index, not the filesystem.diff --git a/plugin/skills/conventions/brain-first.md b/plugin/skills/conventions/brain-first.mdindex 844840fbad..5cc243e58f 100644--- a/plugin/skills/conventions/brain-first.md+++ b/plugin/skills/conventions/brain-first.md@@ -5,6 +5,38 @@Sub-agents and fresh sessions inherit gbrain tools but not the knowledge ofwhen and how to use them. This file is that knowledge.+## Retrieval: gbrain first++For anything in the brain, search gbrain, then read the page a hit names. Don't+`grep`, `rg` or `cat` the brain checkout, or run SQL over pages and+frontmatter, before gbrain: gbrain reads the index across sources, ranks results,+filters by type, date and source, and returns the slug to read next. Use the+files only when gbrain is unreachable or for an edit not yet synced.++```bash+gbrain search "Acme Example" # names, codes, exact phrases+gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)+gbrain query "why did the launch move" # questions and concepts+gbrain search "launch" --types '["meeting","person"]' # only these page types+gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)+gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'+gbrain get companies/acme-example # read the page a hit points to+gbrain recall "Alice Example" # facts saved with remember+gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)+gbrain timeline companies/acme-example --since 2026-10-01 # dated events on one page+gbrain list --type meeting --limit 50 # enumerate by type or --tag (instead of SQL)+```++- `--types` takes a JSON array. `--since`/`--until` are `query` flags+ (YYYY-MM-DD or 7d/2w/1y) and match each page's effective date: its+ frontmatter date, else when it was imported.+- Keyword search matches words, not slugs: search `"Acme Example"`, and use+ `backlinks` to find pages linking to `companies/acme-example`.+- Without `--source`, a search reads the resolved source (a notice names it+ when it routes); `--source __all__` searches every source.+- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.+ Read a degraded notice before concluding the brain has nothing.+## Available GBrain ToolsYour tool inventory includes these (prefixed `gbrain__` in OpenClaw):diff --git a/plugin/skills/correction-pipeline/SKILL.md b/plugin/skills/correction-pipeline/SKILL.mdindex c98df21a00..fc49553e2e 100644--- a/plugin/skills/correction-pipeline/SKILL.md+++ b/plugin/skills/correction-pipeline/SKILL.md@@ -59,10 +59,12 @@ gbrain search "<relevant terms>" --limit 10```For concept-shaped or synonym-phrased claims, escalate to `gbrain query-"<question>"` (LLM expansion recovers phrasings `search` misses). Also grep-the brain repo checkout directly — resolve it once from config:+"<question>"` (LLM expansion recovers phrasings `search` misses). To list+every indexed page carrying the claim, use a keyword search (it pages every+match); grep the checkout only for edits not yet synced:```bash+gbrain search '"<wrong claim terms>"' --match keywordBRAIN_DIR=$(gbrain config get sync.repo_path)grep -ri "<wrong claim terms>" "$BRAIN_DIR/people/" "$BRAIN_DIR/companies/" "$BRAIN_DIR/concepts/" 2>/dev/null```@@ -167,8 +169,8 @@ The wrong fact may have propagated into OTHER brain pages, synthesis output,or memory files.```bash-grep -ri "<wrong claim terms>" "$BRAIN_DIR" 2>/dev/null | grep -v ".git"-gbrain search "<wrong claim terms>" --limit 20+gbrain search '"<wrong claim terms>"' --match keyword+grep -ri "<wrong claim terms>" "$BRAIN_DIR" 2>/dev/null | grep -v ".git" # edits not yet synced```Fix ALL instances, not just the first one found. Re-sync after repo edits.diff --git a/plugin/skills/query/SKILL.md b/plugin/skills/query/SKILL.mdindex 6469a19517..0ac43a80ee 100644--- a/plugin/skills/query/SKILL.md+++ b/plugin/skills/query/SKILL.md@@ -69,6 +69,9 @@ This skill guarantees:- Cheap-hybrid search gbrain for exact tokens / known names (search)- Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)- List pages in gbrain by type or check backlinks for structural queries+ - Narrow with filters instead of grepping the brain checkout: `--types '["meeting"]'`,+ `--match keyword`, `gbrain query "<q>" --since 2026-09-01 --until 2026-09-30`, `--source <id>`.+ Copyable examples: "Retrieval: gbrain first" in `skills/conventions/brain-first.md`.3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.5. **Flag gaps.** If the brain doesn't have info, say "the brain doesn't have information on X" rather than hallucinating. Read the result's notices first (see "When it fails"): a degraded or truncated result is not a gap.diff --git a/scripts/bench/retrieval-scale/corpus.ts b/scripts/bench/retrieval-scale/corpus.tsnew file mode 100644index 0000000000..729c8d9ecb--- /dev/null+++ b/scripts/bench/retrieval-scale/corpus.ts@@ -0,0 +1,162 @@+#!/usr/bin/env bun+/**+ * Retrieval scale bench, step 1: a large synthetic Postgres brain (GBRA-156).+ * Opt-in bench code, never run in CI (the CI latency check is+ * test/e2e/retrieval-latency.test.ts at a size CI can afford).+ *+ * bun scripts/bench/retrieval-scale/corpus.ts --url postgresql://postgres:[email protected]:5434/postgres \+ * --db bench_retrieval_300k --pages 300000 [--workers 8] [--seed 7] [--out manifest.json]+ *+ * Builds a fresh database with initSchema, then streams brain-shaped pages+ * into two large sources and one small one (52% / 43% / 5%), with a share of+ * cross-source twins (the same slug in two sources), page types, dated+ * frontmatter, links and timeline rows, and chunks with real-width unit+ * vectors from the synthetic-latent geometry of hnsw-latent-corpus.ts (no+ * network or model calls). Chunk-table indexes are dropped for the load and+ * rebuilt afterwards with the exact definitions initSchema created, so the+ * served brain matches a migrated one. Everything is generated words and+ * placeholder names; nothing comes from a real brain.+ */+import { writeFileSync } from 'node:fs';+import postgres from '#postgres';+import { buildBasis, hash32, LATENT_DEFAULTS, planPages, Rng, type LatentParams, loadLatentCorpus, chunkText } from '../hnsw-latent-corpus.ts';++const argv = process.argv.slice(2);+const flag = (name: string, fallback?: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : fallback; };+const adminUrl = flag('--url');+const dbName = flag('--db', 'bench_retrieval');+const pagesWanted = Number(flag('--pages', '30000'));+const workers = Number(flag('--workers', '4'));+const seed = Number(flag('--seed', '7'));+const out = flag('--out');+const model = flag('--model', 'openai:text-embedding-3-large')!;+if (!adminUrl) { console.error('--url <postgres admin url> is required'); process.exit(2); }+if (!/^[a-z0-9_]+$/.test(dbName!)) { console.error('--db must be [a-z0-9_]+'); process.exit(2); }++const t0 = performance.now();+const log = (m: string) => console.error('[retrieval-corpus +' + ((performance.now() - t0) / 1000).toFixed(1) + 's] ' + m);++export const SOURCES = ['default', 'source-b', 'source-c'] as const;+export const SHARES: [number, number] = [0.52, 0.43];+export const TWIN_SHARE = 0.1;+export const TYPES: Array<[string, string, number]> = [+ ['person', 'people', 0.15], ['company', 'companies', 0.08], ['meeting', 'meetings', 0.2], ['note', 'notes', 0.25],+ ['concept', 'concepts', 0.1], ['transcript', 'transcripts', 0.12], ['original', 'originals', 0.1],+];+const FIRST = ['alice', 'bob', 'carol', 'dave', 'erin', 'frank', 'grace', 'heidi', 'ivan', 'judy', 'mallory', 'niaj', 'olivia', 'peggy', 'rupert', 'sybil', 'trent', 'victor', 'walter', 'yolanda'];+const SYL = ['ka', 'lo', 'mi', 'ten', 'ar', 'vis', 'no', 're', 'shu', 'pa', 'der', 'qui', 'lan', 'mo', 'zet', 'ri', 'bo', 'ex', 'ul', 'fen'];+const cap = (s: string) => s[0]!.toUpperCase() + s.slice(1);+function word(rng: Rng) { let w = ''; const n = 2 + Math.floor(rng.next() * 2); for (let i = 0; i < n; i++) w += SYL[Math.floor(rng.next() * SYL.length)]; return w; }++export interface PageMeta { id: number; source: string; slug: string; type: string; title: string; date: string }++/** Deterministic page header: type, title, slug and date for page index p. */+export function pageMeta(p: number, source: number): PageMeta {+ const rng = new Rng(hash32(seed, p, 0x7a9e));+ let r = rng.next(), ti = 0;+ while (ti < TYPES.length - 1 && r > TYPES[ti]![2]) { r -= TYPES[ti]![2]; ti++; }+ const [type, dir] = TYPES[ti]!;+ const surname = word(rng), w1 = word(rng), w2 = word(rng);+ const first = FIRST[Math.floor(rng.next() * FIRST.length)]!;+ const date = new Date(Date.UTC(2021, 0, 1) + Math.floor(rng.next() * 1800) * 86_400_000).toISOString().slice(0, 10);+ const title = type === 'person' ? cap(first) + ' ' + cap(surname)+ : type === 'company' ? cap(w1) + cap(w2) + ' Example'+ : type === 'meeting' ? 'Meeting with ' + cap(first) + ' ' + cap(surname) + ' on ' + w1+ : type === 'transcript' ? 'Transcript ' + date + ' ' + w1 + ' ' + w2+ : cap(w1) + ' ' + w2 + ' ' + surname;+ const base = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');+ return { id: p + 1, source: SOURCES[source]!, slug: dir + '/' + base + '-' + p.toString(36), type, title, date };+}++async function main() {+ const admin = postgres(adminUrl!, { max: 1, prepare: false, onnotice: () => {} });+ await admin.unsafe('DROP DATABASE IF EXISTS ' + dbName + ' WITH (FORCE)');+ await admin.unsafe('CREATE DATABASE ' + dbName);+ await admin.end();+ const target = new URL(adminUrl!);+ target.pathname = '/' + dbName;+ const url = target.toString();++ const chunksWanted = Math.round(pagesWanted * 7.13);+ const params: LatentParams = { ...LATENT_DEFAULTS, chunks: chunksWanted, dims: 1536, seed, sourceShares: SHARES };+ const plan = planPages(chunksWanted, seed, SHARES);+ log('plan: ' + plan.count + ' pages, ' + chunksWanted + ' chunks');++ const { createEngine } = await import('../../../src/core/engine-factory.ts');+ const engine = await createEngine({ engine: 'postgres' });+ await engine.connect({ database_url: url });+ await (engine as unknown as { initSchema(o: unknown): Promise<void> }).initSchema({ embedding: { dimensions: 1536, model } });+ await engine.disconnect();+ log('initSchema done');++ const sql = postgres(url, { max: workers + 2, prepare: false, onnotice: () => {} });+ for (const s of SOURCES) await sql.unsafe("INSERT INTO sources (id, name, config) VALUES ($1, $1, '{\"federated\": true}') ON CONFLICT (id) DO NOTHING", [s]);++ // Pages: text COPY in one stream. Twins in source-b reuse the slug of an earlier source-a page.+ const firstA: number[] = [];+ const twinned = new Set<number>();+ const metas: PageMeta[] = new Array(plan.count);+ for (let p = 0; p < plan.count; p++) {+ const m = pageMeta(p, plan.source[p]!);+ if (plan.source[p] === 0 && firstA.length < plan.count) firstA.push(p);+ if (plan.source[p] === 1 && firstA.length > 0 && (hash32(seed, p, 0x7713) % 1000) < TWIN_SHARE * 1000) {+ const twinIndex = firstA[hash32(seed, p, 0x7714) % firstA.length]!;+ if (!twinned.has(twinIndex)) {+ twinned.add(twinIndex);+ const twin = metas[twinIndex]!;+ m.slug = twin.slug; m.type = twin.type; m.title = twin.title;+ }+ }+ metas[p] = m;+ }+ log('metas built');+ const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\r/g, '\\r');+ const pageCopy = await sql.unsafe('COPY pages (id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, effective_date, effective_date_source, created_at, updated_at, trust_tier) FROM STDIN').writable();+ const pagesDone = new Promise<void>((res, rej) => { pageCopy.on('finish', res); pageCopy.on('error', (e: Error) => { log('page COPY failed: ' + e.message); rej(e); }); });+ pagesDone.catch(() => {});+ log('copy stream open');+ let buf = '';+ for (let p = 0; p < plan.count; p++) {+ const m = metas[p]!;+ const body: string[] = [];+ for (let c = 0; c < plan.chunkCount[p]!; c++) body.push(chunkText(seed, p, c, plan.topic[p]!));+ const truth = '# ' + m.title + '\n\n' + body.join('\n\n');+ const timeline = m.type === 'meeting' || m.type === 'person' ? '- **' + m.date + '** | ' + m.title + ' follow-up' : '';+ const fm = JSON.stringify({ type: m.type, title: m.title, date: m.date, tags: [word(new Rng(hash32(seed, p, 0x7a6)))], status: (p % 3 === 0 ? 'active' : 'archived') });+ const at = m.date + 'T12:00:00Z';+ buf += [m.id, m.source, esc(m.slug), m.type, esc(m.title), esc(truth), esc(timeline), esc(fm), hash32(seed, p, 0xc0de).toString(16), at, 'date', at, at, 'operator_curated'].join('\t') + '\n';+ if (buf.length > 4 << 20) { const chunk = buf; buf = ''; await new Promise<void>((res, rej) => pageCopy.write(chunk, (e?: Error | null) => e ? rej(e) : res())); }+ }+ await new Promise<void>((res, rej) => pageCopy.write(buf, (e?: Error | null) => e ? rej(e) : res()));+ pageCopy.end();+ await pagesDone;+ await sql.unsafe("SELECT setval(pg_get_serial_sequence('pages', 'id'), (SELECT max(id) FROM pages))");+ const { titleTierCorpusGeneration } = await import('../../../src/core/contextual-retrieval-service.ts');+ // The importer's sealed state: current text projection, safe-chunk chunker, title-tier contextual retrieval.+ await sql.unsafe("UPDATE pages SET text_projection_revision = knowledge_revision, chunker_version = 4, contextual_retrieval_mode = 'title', corpus_generation = $1, embedding_signature = $2, source_path = slug || '.md'", [titleTierCorpusGeneration(), model + ':1536']);+ log('pages loaded');++ // Chunks: drop chunk-table secondary indexes, load, rebuild with the exact definitions.+ const idx = await sql.unsafe("SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' AND tablename = 'content_chunks' AND indexname NOT IN ('content_chunks_pkey', 'idx_chunks_page_index')") as Array<{ indexname: string; indexdef: string }>;+ for (const i of idx) await sql.unsafe('DROP INDEX ' + i.indexname);+ const basis = buildBasis(params);+ await loadLatentCorpus({ params, plan, basis, queries: [], url, model, workers, log });+ await sql.unsafe("UPDATE content_chunks c SET embedded_at = now(), embedding_pending_since = NULL, projected_byte_start = strpos(p.compiled_truth, c.chunk_text) - 1, projected_byte_end = strpos(p.compiled_truth, c.chunk_text) - 1 + octet_length(c.chunk_text) FROM pages p WHERE p.id = c.page_id");+ log('chunks loaded; rebuilding ' + idx.length + ' indexes');+ await sql.unsafe("SET maintenance_work_mem = '" + (flag('--maintenance-mem', '4GB')) + "'");+ await sql.unsafe('SET max_parallel_maintenance_workers = ' + Math.max(1, workers - 1));+ for (const i of idx) { const s = performance.now(); await sql.unsafe(i.indexdef); log(' ' + i.indexname + ' ' + ((performance.now() - s) / 1000).toFixed(1) + 's'); }++ // Graph and timeline rows.+ await sql.unsafe("INSERT INTO links (from_page_id, to_page_id, link_type, link_source) SELECT g, 1 + ((g::bigint * 7919 + k * 104729) % $1), 'mentions', 'markdown' FROM generate_series(1, $1) g, generate_series(1, 3) k WHERE 1 + ((g::bigint * 7919 + k * 104729) % $1) <> g ON CONFLICT DO NOTHING", [plan.count]);+ await sql.unsafe("INSERT INTO timeline_entries (page_id, date, source, summary) SELECT id, effective_date::date, 'bench', title || ' follow-up' FROM pages WHERE type IN ('meeting', 'person') ON CONFLICT DO NOTHING");+ await sql.unsafe("UPDATE pages SET links_extracted_at = now()");+ await sql.unsafe('VACUUM ANALYZE');+ const [counts] = await sql.unsafe("SELECT (SELECT count(*) FROM pages)::int AS pages, (SELECT count(*) FROM content_chunks)::int AS chunks, (SELECT count(*) FROM links)::int AS links, (SELECT count(*) - count(DISTINCT slug) FROM pages)::int AS twin_slugs, pg_database_size(current_database())::bigint AS bytes") as any;+ await sql.end();+ const manifest = { db: dbName, seed, model, dims: 1536, sources: SOURCES, shares: SHARES, twin_share: TWIN_SHARE, ...counts, bytes: Number(counts.bytes), build_s: Math.round((performance.now() - t0) / 1000) };+ log(JSON.stringify(manifest));+ if (out) writeFileSync(out, JSON.stringify(manifest, null, 2));+}++if (import.meta.main) await main();diff --git a/scripts/bench/retrieval-scale/lexical-probe.ts b/scripts/bench/retrieval-scale/lexical-probe.tsnew file mode 100644index 0000000000..52e2f187b4--- /dev/null+++ b/scripts/bench/retrieval-scale/lexical-probe.ts@@ -0,0 +1,49 @@+#!/usr/bin/env bun+/**+ * Lexical arm probe for the retrieval scale bench (GBRA-156): for N corpus+ * queries, times the keyword and title arms' strict statement and their OR+ * retry separately, and counts the chunks the OR query matches.+ *+ * bun scripts/bench/retrieval-scale/lexical-probe.ts --url <direct postgres url> --pages <n> [--n 20] [--source default] [--compare-tree <checkout>]+ *+ * --compare-tree also runs the OR path through another checkout's engine (for+ * example master) and reports how many of its result pages this tree returns.+ */+import postgres from '#postgres';+import { buildOrFallbackWebsearchQuery } from '../../../src/core/search/sql-ranking.ts';++const argv = process.argv.slice(2);+const flag = (name: string, fallback?: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : fallback; };+const url = flag('--url')!;+const pages = Number(flag('--pages'));+const N = Number(flag('--n', '20'));+const source = flag('--source', 'default')!;+const compareTree = flag('--compare-tree');++const { createEngine } = await import('../../../src/core/engine-factory.ts');+const engine = await createEngine({ engine: 'postgres' });+await engine.connect({ database_url: url });+const other = compareTree ? await (await import(compareTree + '/src/core/engine-factory.ts')).createEngine({ engine: 'postgres' }) : null;+if (other) await other.connect({ database_url: url });+const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {} });+const picks = await sql.unsafe("SELECT p.title, c.chunk_text FROM pages p JOIN content_chunks c ON c.page_id = p.id AND c.chunk_index = 0 WHERE p.id IN (SELECT 1 + ((g::bigint * 2654435761) % $1) FROM generate_series(1, $2) g) ORDER BY p.id", [pages, N]) as Array<{ title: string; chunk_text: string }>;+const time = async <T>(fn: () => Promise<T>) => { const t = performance.now(); try { const v = await fn(); return { ms: Math.round(performance.now() - t), v }; } catch (e) { return { ms: Math.round(performance.now() - t), v: null as T | null, err: (e as Error).message.slice(0, 60) }; } };+for (const [i, p] of picks.entries()) {+ const words = p.chunk_text.replace(/[^a-z\s]/gi, ' ').split(/\s+/).filter(w => w.length > 3);+ const k = 2 + (i % 3), at = (i * 7919) % Math.max(1, words.length - k);+ const titleWord = p.title.split(/\s+/).find(w => w.length > 3);+ const q = [...(i % 2 === 0 && titleWord ? [titleWord.toLowerCase()] : []), ...words.slice(at, at + k)].join(' ');+ const opts = { sourceIds: [source], limit: 50 } as Record<string, unknown>;+ const strictK = await time(() => engine.searchKeyword(q, opts as never));+ const orK = await time(() => engine.searchKeyword(q, { ...opts, orFallback: true } as never));+ const titles = await time(() => engine.searchTitles(q, { ...opts } as never));+ const base = other ? await time(() => other.searchKeyword(q, { ...opts, orFallback: true } as never)) : null;+ const basePages = new Set(((base?.v ?? []) as Array<{ slug: string; source_id: string }>).map(r => r.source_id + ':' + r.slug));+ const overlap = base ? ((orK.v ?? []) as Array<{ slug: string; source_id: string }>).filter(r => basePages.has(r.source_id + ':' + r.slug)).length : null;+ const orq = buildOrFallbackWebsearchQuery(q);+ const matches = orq ? await time(() => sql.unsafe("SELECT count(*)::int AS n FROM content_chunks WHERE search_vector @@ websearch_to_tsquery('english', $1)", [orq])) : null;+ console.log(JSON.stringify({ i, terms: q.split(' ').length, strict_rows: strictK.v?.length ?? null, strict_ms: strictK.ms, or_path_ms: orK.ms, or_rows: orK.v?.length ?? null, or_err: (orK as any).err, title_ms: titles.ms, ...(base ? { base_or_ms: base.ms, base_rows: basePages.size, overlap } : {}), or_matches: (matches?.v as any)?.[0]?.n ?? null, count_ms: matches?.ms }));+}+await sql.end();+await engine.disconnect();+await other?.disconnect();diff --git a/scripts/bench/retrieval-scale/mock-providers.ts b/scripts/bench/retrieval-scale/mock-providers.tsnew file mode 100644index 0000000000..2418f98215--- /dev/null+++ b/scripts/bench/retrieval-scale/mock-providers.ts@@ -0,0 +1,81 @@+#!/usr/bin/env bun+/**+ * Retrieval scale bench: local stand-ins for the embedding and rerank+ * providers (GBRA-156), so a latency run measures gbrain and not a provider.+ *+ * bun scripts/bench/retrieval-scale/mock-providers.ts --manifest manifest.json [--port 0] [--embed-ms 0] [--rerank-ms 0]+ *+ * OpenAI-compatible POST /v1/embeddings returns, for each input, a unit vector+ * near chunk 0 of a page picked by a hash of the text, drawn from the same+ * synthetic-latent geometry the corpus was built with, so the vector arm sees+ * in-distribution queries. Voyage-compatible POST /v1/rerank scores documents+ * by word overlap with the query. Each answer waits --embed-ms / --rerank-ms+ * first (a fixed provider round trip). Counts every call on GET /stats.+ */+import { readFileSync } from 'node:fs';+import { buildBasis, Generator, hash32, LATENT_DEFAULTS, Rng, type LatentParams } from '../hnsw-latent-corpus.ts';++export interface MockOptions { manifest: { seed: number; chunks: number; pages: number; dims: number }; port?: number; embedMs?: number; rerankMs?: number }+export interface MockServer { url: string; stats: { embed_calls: number; embed_inputs: number; rerank_calls: number; rerank_docs: number }; stop(): void }++export function startMockProviders(o: MockOptions): MockServer {+ const params: LatentParams = { ...LATENT_DEFAULTS, chunks: o.manifest.chunks, dims: o.manifest.dims, seed: o.manifest.seed };+ const gen = new Generator(params, buildBasis(params));+ const stats = { embed_calls: 0, embed_inputs: 0, rerank_calls: 0, rerank_docs: 0 };+ const sleep = (ms: number) => ms > 0 ? new Promise(r => setTimeout(r, ms)) : Promise.resolve();+ const vectorFor = (text: string, dims: number): number[] => {+ let h = 0x811c9dc5;+ for (let i = 0; i < text.length; i++) h = hash32(h, text.charCodeAt(i));+ const p = h % o.manifest.pages;+ const out = new Float32Array(params.dims);+ gen.page(p, 1, (_c, vec) => out.set(vec));+ const rng = new Rng(h);+ let norm = 0;+ for (let d = 0; d < out.length; d++) { out[d]! += 0.6 * rng.gauss() / Math.sqrt(out.length); norm += out[d]! * out[d]!; }+ const inv = 1 / Math.sqrt(norm);+ return Array.from(out.subarray(0, dims), v => v * inv);+ };+ const words = (s: string) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter(w => w.length > 2));+ const server = Bun.serve({+ port: o.port ?? 0,+ hostname: '127.0.0.1',+ async fetch(req) {+ const path = new URL(req.url).pathname;+ if (req.method === 'GET' && path.endsWith('/stats')) return Response.json(stats);+ const body = await req.json().catch(() => ({})) as any;+ if (path.endsWith('/embeddings')) {+ const inputs: string[] = Array.isArray(body.input) ? body.input : [String(body.input ?? '')];+ stats.embed_calls++; stats.embed_inputs += inputs.length;+ await sleep(o.embedMs ?? 0);+ const dims = Number(body.dimensions ?? params.dims);+ const data = inputs.map((t, index) => {+ const v = vectorFor(String(t), dims);+ if (body.encoding_format === 'base64') return { object: 'embedding', index, embedding: Buffer.from(new Float32Array(v).buffer).toString('base64') };+ return { object: 'embedding', index, embedding: v };+ });+ const tokens = inputs.reduce((a, t) => a + Math.ceil(String(t).length / 4), 0);+ return Response.json({ object: 'list', data, model: body.model, usage: { prompt_tokens: tokens, total_tokens: tokens } });+ }+ if (path.endsWith('/rerank')) {+ const docs: string[] = body.documents ?? [];+ stats.rerank_calls++; stats.rerank_docs += docs.length;+ await sleep(o.rerankMs ?? 0);+ const q = words(String(body.query ?? ''));+ const scored = docs.map((d, index) => { const w = words(String(d)); let hit = 0; for (const t of q) if (w.has(t)) hit++; return { index, relevance_score: q.size ? hit / q.size : 0 }; });+ scored.sort((a, b) => b.relevance_score - a.relevance_score || a.index - b.index);+ const k = Number(body.top_k ?? scored.length);+ return Response.json({ object: 'list', data: scored.slice(0, k), model: body.model, usage: { total_tokens: docs.reduce((a, d) => a + Math.ceil(String(d).length / 4), 0) } });+ }+ return new Response('not found', { status: 404 });+ },+ });+ return { url: 'http://127.0.0.1:' + server.port, stats, stop: () => server.stop(true) };+}++if (import.meta.main) {+ const argv = process.argv.slice(2);+ const flag = (n: string, f?: string) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : f; };+ const manifest = JSON.parse(readFileSync(flag('--manifest')!, 'utf8'));+ const s = startMockProviders({ manifest, port: Number(flag('--port', '0')), embedMs: Number(flag('--embed-ms', '0')), rerankMs: Number(flag('--rerank-ms', '0')) });+ console.log(s.url);+}diff --git a/scripts/bench/retrieval-scale/run.ts b/scripts/bench/retrieval-scale/run.tsnew file mode 100644index 0000000000..0a7d76efa9--- /dev/null+++ b/scripts/bench/retrieval-scale/run.ts@@ -0,0 +1,225 @@+#!/usr/bin/env bun+/**+ * Retrieval scale bench, step 2: CLI and MCP latency for search, query, get+ * and recall on a corpus.ts brain (GBRA-156). Opt-in, never run in CI.+ *+ * bun scripts/bench/retrieval-scale/run.ts --manifest manifest.json \+ * --url postgresql://postgres:[email protected]:6543/bench_retrieval_300k?prepare=false \+ * [--direct-url postgresql://...:5434/bench_retrieval_300k] [--n 20] [--warmup 3] \+ * [--ops search,query,get,recall] [--modes cold,warm] [--search-mode tokenmax] \+ * [--embed-ms 0] [--rerank-ms 0] [--toxiproxy http://127.0.0.1:8474 --rtt-ms 40] [--trace] [--serve-cpu-prof <dir>] \+ * [--tree <checkout>] [--keep] [--label <name>] [--out results.jsonl]+ *+ * --toxiproxy adds --rtt-ms of round-trip latency to its `pooler` proxy (vm-setup.sh+ * creates it on 127.0.0.1:6544 in front of PgBouncer); point --url at 6544 to use it.+ *+ * --url is what gbrain connects to (point it at a transaction-mode PgBouncer+ * to measure the pooled path); --direct-url (default --url) samples queries.+ * Embedding and rerank go to mock-providers.ts in this process, answering+ * after --embed-ms / --rerank-ms, so the numbers are gbrain's own cost plus a+ * fixed provider round trip.+ *+ * cold one fresh CLI process per sample, the cost a shell-out agent pays.+ * With --trace each sample records GBRAIN_SQL_TRACE and splits wall+ * time into startup (spawn -> first statement), db (first statement+ * -> last reply) and tail (last reply -> exit), plus round trips.+ * warm one long-lived gbrain serve stdio MCP process; per-stage search+ * timings come from _meta.retrieval.timings.+ *+ * Queries are 2-4 generated words from a random page body plus, for half of+ * them, a word of its title: synthetic text only. Rows carry timings and+ * counts. Prints a Markdown table and appends JSONL rows to --out.+ */+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import postgres from '#postgres';+import { startMockProviders } from './mock-providers.ts';++const argv = process.argv.slice(2);+const flag = (name: string, fallback?: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : fallback; };+/** --tree points at another checkout (for example master) to measure its CLI against the same brain. */+const REPO = resolve(flag('--tree', resolve(import.meta.dir, '..', '..', '..'))!);+const CLI = join(REPO, 'src', 'cli.ts');+const has = (name: string) => argv.includes(name);+const manifest = JSON.parse(readFileSync(flag('--manifest')!, 'utf8'));+const url = flag('--url')!;+const directUrl = flag('--direct-url', url.replace(/\?.*$/, ''))!;+const N = Number(flag('--n', '20'));+const WARMUP = Number(flag('--warmup', '3'));+const ops = flag('--ops', 'search,query,get,recall')!.split(',');+const modes = flag('--modes', 'cold,warm')!.split(',');+const searchMode = flag('--search-mode', 'tokenmax')!;+const label = flag('--label', manifest.db + (flag('--rtt-ms') ? '-rtt' + flag('--rtt-ms') : ''))!;+const out = flag('--out');+const trace = has('--trace');+const log = (m: string) => console.error('[retrieval-run] ' + m);++export const pct = (xs: number[], q: number) => { if (!xs.length) return NaN; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.ceil(q * s.length) - 1)]!; };+const r0 = (x: number) => Math.round(x);++interface Sample { ms: number; ok: boolean; stages?: Record<string, number>; startup?: number; db?: number; tail?: number; trips?: number }++async function main() {+ const toxiproxy = flag('--toxiproxy');+ const rttMs = Number(flag('--rtt-ms', '0'));+ if (toxiproxy) {+ for (const name of ['latency_up', 'latency_down']) await fetch(toxiproxy + '/proxies/pooler/toxics/' + name, { method: 'DELETE' }).catch(() => undefined);+ if (rttMs > 0) for (const [name, stream] of [['latency_up', 'upstream'], ['latency_down', 'downstream']] as const) {+ const res = await fetch(toxiproxy + '/proxies/pooler/toxics', { method: 'POST', body: JSON.stringify({ name, type: 'latency', stream, attributes: { latency: rttMs / 2, jitter: 0 } }) });+ if (!res.ok) throw new Error('toxiproxy: ' + res.status + ' ' + await res.text());+ }+ log('toxiproxy pooler RTT ' + rttMs + ' ms');+ }+ const mock = startMockProviders({ manifest, embedMs: Number(flag('--embed-ms', '0')), rerankMs: Number(flag('--rerank-ms', '0')) });+ const home = mkdtempSync(join(tmpdir(), 'gbrain-retrieval-bench-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'postgres', database_url: url, embedding_model: manifest.model, embedding_dimensions: manifest.dims,+ provider_base_urls: { voyage: mock.url + '/v1' },+ }));+ const env: Record<string, string> = {+ ...process.env as Record<string, string>, GBRAIN_HOME: home, OPENAI_BASE_URL: mock.url + '/v1', OPENAI_API_KEY: 'sk-bench', VOYAGE_API_KEY: 'pa-bench',+ GBRAIN_NO_UPDATE_CHECK: '1', GBRAIN_TELEMETRY: '0',+ };+ const runCli = async (args: string[], extra: Record<string, string> = {}) => {+ const t0 = performance.timeOrigin + performance.now();+ const p = Bun.spawn([process.execPath, CLI, ...args], { cwd: REPO, env: { ...env, ...extra }, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);+ const code = await p.exited;+ const t1 = performance.timeOrigin + performance.now();+ return { t0, t1, ms: t1 - t0, code, stdout, stderr };+ };+ const set = await runCli(['config', 'set', 'search.mode', searchMode]);+ if (set.code !== 0) log('config set search.mode failed: ' + set.stderr.slice(0, 300));++ // Query set and get targets, drawn deterministically from the corpus.+ const sql = postgres(directUrl, { max: 1, prepare: false, onnotice: () => {} });+ const picks = await sql.unsafe("SELECT p.slug, p.source_id, p.title, c.chunk_text FROM pages p JOIN content_chunks c ON c.page_id = p.id AND c.chunk_index = 0 WHERE p.id IN (SELECT 1 + ((g::bigint * 2654435761) % $1) FROM generate_series(1, $2) g) ORDER BY p.id", [manifest.pages, Math.max(N + WARMUP, 20) * 2]) as Array<{ slug: string; source_id: string; title: string; chunk_text: string }>;+ await sql.end();+ const queries = picks.map((p, i) => {+ const words = p.chunk_text.replace(/[^a-z\s]/gi, ' ').split(/\s+/).filter(w => w.length > 3);+ const k = 2 + (i % 3), at = (i * 7919) % Math.max(1, words.length - k);+ const titleWord = p.title.split(/\s+/).find(w => w.length > 3);+ return [...(i % 2 === 0 && titleWord ? [titleWord.toLowerCase()] : []), ...words.slice(at, at + k)].join(' ');+ });+ const q = (i: number) => queries[i % queries.length]!;+ // Each op reads its own slice of the query set, so no op reuses another's per-process query embedding.+ const opBase = (op: string) => ops.indexOf(op) * 7 + 1;+ const pk = (i: number) => picks[i % picks.length]!;+ const cli: Record<string, (i: number) => string[]> = {+ search: i => ['search', q(i + opBase('search')), '--json'],+ query: i => ['query', q(i + opBase('query')), '--json'],+ get: i => ['get', pk(i).slug, '--source', pk(i).source_id],+ recall: i => ['recall', q(i + opBase('recall')), '--json'],+ };+ const tool: Record<string, (i: number) => [string, Record<string, unknown>]> = {+ search: i => ['search', { query: q(i + opBase('search')) }],+ query: i => ['query', { query: q(i + opBase('query')) }],+ get: i => ['get_page', { slug: pk(i).slug, source_id: pk(i).source_id }],+ recall: i => ['recall', { query: q(i + opBase('recall')) }],+ };++ const rows: Array<Record<string, unknown>> = [];+ const add = (op: string, mode: string, s: Sample[]) => {+ const ok = s.filter(x => x.ok), ms = ok.map(x => x.ms);+ const row: Record<string, unknown> = { suite: 'retrieval-scale', label, pages: manifest.pages, chunks: manifest.chunks, op, mode, search_mode: searchMode, n: ok.length, errors: s.length - ok.length, p50_ms: r0(pct(ms, 0.5)), p95_ms: r0(pct(ms, 0.95)), embed_ms: Number(flag('--embed-ms', '0')), rerank_ms: Number(flag('--rerank-ms', '0')) };+ const med = (k: keyof Sample) => { const v = ok.map(x => x[k] as number).filter(x => typeof x === 'number'); return v.length ? r0(pct(v, 0.5)) : undefined; };+ if (trace) Object.assign(row, { startup_p50_ms: med('startup'), db_p50_ms: med('db'), tail_p50_ms: med('tail'), round_trips_p50: med('trips') });+ const stageNames = new Set(ok.flatMap(x => Object.keys(x.stages ?? {})));+ if (stageNames.size) row.stages_p50_ms = Object.fromEntries([...stageNames].map(k => [k, r0(pct(ok.map(x => x.stages?.[k] ?? 0), 0.5))]));+ const worst = s.reduce((w, x, i) => (x.ok && x.ms > s[w]!.ms ? i : w), 0);+ if (s[worst]) row.slowest = { i: worst, ms: r0(s[worst]!.ms), ...(s[worst]!.stages ? { stages: s[worst]!.stages } : {}) };+ rows.push(row);+ if (s[worst]?.stages) log(op + ' [' + mode + '] slowest i=' + worst + ' ' + JSON.stringify(row.slowest));+ log(op + ' [' + mode + '] n=' + row.n + ' p50=' + row.p50_ms + ' p95=' + row.p95_ms + ' err=' + row.errors + (row.round_trips_p50 !== undefined ? ' trips=' + row.round_trips_p50 : '') + (row.startup_p50_ms !== undefined ? ' startup=' + row.startup_p50_ms + ' db=' + row.db_p50_ms + ' tail=' + row.tail_p50_ms : '') + (row.stages_p50_ms ? ' ' + JSON.stringify(row.stages_p50_ms) : ''));+ };++ if (modes.includes('cold')) {+ for (const op of ops) {+ for (let i = 0; i < WARMUP; i++) await runCli(cli[op]!(1000 + i));+ const samples: Sample[] = [];+ for (let i = 0; i < N; i++) {+ const traceFile = join(home, 'trace-' + op + '-' + i + '.jsonl');+ const r = await runCli(cli[op]!(i), trace ? { GBRAIN_SQL_TRACE: traceFile } : {});+ const s: Sample = { ms: r.ms, ok: r.code === 0 };+ if (!s.ok && i === 0) log(op + ' cold exit ' + r.code + ': ' + r.stderr.slice(-400));+ if (trace) {+ const recs = readFileSync(traceFile, 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l)).filter((x: any) => typeof x.t === 'number' || typeof x.start === 'number');+ const starts = recs.map((x: any) => x.start ?? x.t), ends = recs.map((x: any) => (x.start ?? x.t) + (x.ms ?? x.duration_ms ?? 0));+ if (starts.length) { s.startup = Math.min(...starts) - r.t0; s.db = Math.max(...ends) - Math.min(...starts); s.tail = r.t1 - Math.max(...ends); s.trips = recs.length; }+ }+ samples.push(s);+ }+ add(op, 'cold', samples);+ }+ }++ if (modes.includes('warm')) {+ const warmTrace = join(home, 'trace-serve.jsonl');+ const profDir = flag('--serve-cpu-prof');+ const proc = Bun.spawn([process.execPath, ...(profDir ? ['--cpu-prof', '--cpu-prof-dir=' + profDir] : []), CLI, 'serve'], { cwd: REPO, env: { ...env, ...(trace ? { GBRAIN_SQL_TRACE: warmTrace } : {}) }, stdin: 'pipe', stdout: 'pipe', stderr: 'ignore' });+ const tripsBetween = async (t0: number, t1: number) => {+ await new Promise(r => setTimeout(r, 1100));+ let n = 0;+ try { for (const l of readFileSync(warmTrace, 'utf8').split('\n')) { if (!l) continue; const x = JSON.parse(l); if (typeof x.t === 'number' && x.t >= t0 && x.t <= t1) n++; } } catch { /* no trace yet */ }+ return n;+ };+ let buf = '';+ const waiters = new Map<number, (v: any) => void>();+ (async () => {+ const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader();+ const dec = new TextDecoder();+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ let k;+ while ((k = buf.indexOf('\n')) >= 0) {+ const line = buf.slice(0, k).trim(); buf = buf.slice(k + 1);+ if (!line.startsWith('{')) continue;+ try { const m = JSON.parse(line); if (typeof m.id === 'number' && waiters.has(m.id)) { waiters.get(m.id)!(m); waiters.delete(m.id); } } catch { /* partial line */ }+ }+ }+ })();+ let nextId = 1;+ const request = (method: string, params: unknown) => new Promise<any>((res, rej) => {+ const id = nextId++;+ const t = setTimeout(() => { waiters.delete(id); rej(new Error('timeout ' + method)); }, 120_000);+ waiters.set(id, v => { clearTimeout(t); res(v); });+ (proc.stdin as any).write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');+ (proc.stdin as any).flush?.();+ });+ await request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'retrieval-scale-bench', version: '1' } });+ (proc.stdin as any).write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized', params: {} }) + '\n');+ for (const op of ops) {+ const call = async (i: number): Promise<Sample> => {+ const [name, args] = tool[op]!(i);+ const t0 = performance.now();+ const r = await request('tools/call', { name, arguments: args });+ const ms = performance.now() - t0;+ const timings = r?.result?._meta?.retrieval?.timings;+ const trips = trace ? await tripsBetween(performance.timeOrigin + t0, performance.timeOrigin + t0 + ms) : undefined;+ if (trace) appendFileSync(join(home, 'warm-calls.jsonl'), JSON.stringify({ op, t0: performance.timeOrigin + t0, t1: performance.timeOrigin + t0 + ms }) + '\n');+ return { ms, ok: !r.error && !r.result?.isError, ...(trips !== undefined ? { trips } : {}), ...(timings ? { stages: { ...timings.stages_ms, other: timings.other_ms, total: timings.total_ms } } : {}) };+ };+ for (let i = 0; i < WARMUP; i++) await call(2000 + i);+ const samples: Sample[] = [];+ for (let i = 0; i < N; i++) samples.push(await call(i));+ add(op, 'warm', samples);+ }+ try { (proc.stdin as any).end(); } catch { /* closed */ }+ const kill = setTimeout(() => proc.kill(), 3000);+ await proc.exited; clearTimeout(kill);+ }++ log('provider calls: ' + JSON.stringify(mock.stats));+ mock.stop();+ if (has('--keep')) log('kept bench home ' + home); else rmSync(home, { recursive: true, force: true });+ if (out) for (const r of rows) appendFileSync(out, JSON.stringify({ ...r, at: new Date().toISOString() }) + '\n');+ console.log('| op | mode | n | p50 ms | p95 ms |' + (trace ? ' startup | db | tail | trips |' : ''));+ console.log('|---|---|---|---|---|' + (trace ? '---|---|---|---|' : ''));+ for (const r of rows) console.log('| ' + [r.op, r.mode, r.n, r.p50_ms, r.p95_ms, ...(trace ? [r.startup_p50_ms ?? '', r.db_p50_ms ?? '', r.tail_p50_ms ?? '', r.round_trips_p50 ?? ''] : [])].join(' | ') + ' |');+}++if (import.meta.main) await main();diff --git a/scripts/bench/retrieval-scale/vm-setup.sh b/scripts/bench/retrieval-scale/vm-setup.shnew file mode 100755index 0000000000..88a8f8ce3d--- /dev/null+++ b/scripts/bench/retrieval-scale/vm-setup.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+# scripts/bench/retrieval-scale/vm-setup.sh — bootstrap one Ubicloud VM for the+# retrieval scale bench (GBRA-156): Docker, bun, frozen dependencies and a+# pgvector/pgvector:pg16 server on 127.0.0.1:5434 sized to the VM (via+# hnsw-scale-vm-setup.sh), then PgBouncer in transaction mode on 127.0.0.1:6543+# in front of it, the pooled topology large hosted brains run behind.+#+# scripts/ubicloud/ubi-runner.sh ssh "$name" 'cd work/gbrain && bash scripts/bench/retrieval-scale/vm-setup.sh'+# bun scripts/bench/retrieval-scale/corpus.ts --url postgresql://postgres:[email protected]:5434/postgres --db bench_retrieval_300k --pages 300000 --workers 16+# bun scripts/bench/retrieval-scale/run.ts --manifest manifest.json --url 'postgresql://postgres:[email protected]:6543/bench_retrieval_300k?prepare=false' --direct-url postgresql://postgres:[email protected]:5434/bench_retrieval_300k --trace+set -euo pipefail+bash "$(dirname "$0")/../hnsw-scale-vm-setup.sh"+sudo docker rm -f retrieval-bench-bouncer >/dev/null 2>&1 || true+sudo docker run -d --name retrieval-bench-bouncer --network host \+ -e DB_HOST=127.0.0.1 -e DB_PORT=5434 -e DB_USER=postgres -e DB_PASSWORD=postgres \+ -e LISTEN_ADDR=127.0.0.1 -e LISTEN_PORT=6543 -e POOL_MODE=transaction -e AUTH_TYPE=plain \+ -e MAX_CLIENT_CONN=500 -e DEFAULT_POOL_SIZE=20 \+ -e IGNORE_STARTUP_PARAMETERS=extra_float_digits,statement_timeout,idle_in_transaction_session_timeout,search_path \+ edoburu/pgbouncer:latest >/dev/null+for _ in $(seq 1 30); do+ PGPASSWORD=postgres psql -h 127.0.0.1 -p 6543 -U postgres -d postgres -tAc 'select 1' >/dev/null 2>&1 && break+ sleep 1+done+PGPASSWORD=postgres psql -h 127.0.0.1 -p 6543 -U postgres -d postgres -tAc "select 'pgbouncer ok'"+# Toxiproxy on 127.0.0.1:6544 -> PgBouncer, so run.ts --rtt-ms can model a pooler across a network.+sudo docker rm -f retrieval-bench-toxiproxy >/dev/null 2>&1 || true+sudo docker run -d --name retrieval-bench-toxiproxy --network host ghcr.io/shopify/toxiproxy:2.9.0 >/dev/null+for _ in $(seq 1 30); do curl -fsS http://127.0.0.1:8474/version >/dev/null 2>&1 && break; sleep 1; done+curl -fsS -XPOST http://127.0.0.1:8474/proxies -d '{"name":"pooler","listen":"127.0.0.1:6544","upstream":"127.0.0.1:6543"}' >/dev/null+echo "toxiproxy ok"diff --git a/skills/RESOLVER.md b/skills/RESOLVER.mdindex a737aa46d1..1262a27fd6 100644--- a/skills/RESOLVER.md+++ b/skills/RESOLVER.md@@ -184,7 +184,7 @@ When multiple skills could match:These apply to ALL brain-writing skills:- `skills/conventions/quality.md` — citations, back-links, notability gate-- `skills/conventions/brain-first.md` — check brain before external APIs+- `skills/conventions/brain-first.md` — search gbrain before external APIs, brain files or SQL; copyable retrieval filters- `skills/conventions/brain-routing.md` — which brain (DB) and which source (repo) to target; cross-brain federation is latent-space only- `skills/conventions/schema-evolution.md` — when to add a type vs alias vs prefix (read before `schema-author`)- `skills/conventions/line-grammar.md` — typed relation lines (`- works_at [[companies/x]]`), fact lines and `@effective[...)` ranges in compiled truthdiff --git a/skills/brain-ops/SKILL.md b/skills/brain-ops/SKILL.mdindex e64e6507f3..3d9f239bcd 100644--- a/skills/brain-ops/SKILL.md+++ b/skills/brain-ops/SKILL.md@@ -35,7 +35,7 @@ provenance; automatic capture is off until the user opts in. Reading this skilldoes not enable capture, delegation, or paid enrichment. A chat-only instructionsuppresses writes for that turn, including when standing capture is enabled.-> **Convention:** See `skills/conventions/brain-first.md` for the 5-step lookup protocol.+> **Convention:** See `skills/conventions/brain-first.md` for the lookup chain and copyable retrieval filters.> **Convention:** See `skills/conventions/quality.md` for citation and back-link rules.> **Memory verbs (MEMORY_VERBS v1, gbrain ≥ 0.43).** Over MCP, prefer the five@@ -131,6 +131,9 @@ Before using ANY external API to research a person, company, or topic:6. Check timeline: recent events involving this entityThe brain almost always has something. External APIs fill gaps, not start from scratch.+Search gbrain before reading, grepping or querying brain files directly; filters+(`--types`, `--match keyword`, `query --since/--until`, `--source`, `--json`) are+in the brain-first convention's "Retrieval: gbrain first" block.**⚠️ NEVER scope/count a corpus with shallow `ls` — query gbrain or `find`.** Federated sources often carry MULTIPLE coexisting directory conventions — a flat legacy layer AND a date-nested `meetings/YYYY/MM/` layer. A non-recursive `ls dir/*.md` sees only one and undercounts massively. Real example: a shallow `ls` of one source's `meetings/` counted 132 files, almost all the user's, and concluded that WAS the corpus — missing thousands of transcripts nested under `meetings/YYYY/MM/`. To count/scope a brain corpus:- **Best:** `gbrain sources list` (shows per-source indexed page counts) + `gbrain query`. gbrain indexes ALL federated sources correctly; trust its index, not the filesystem.diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.mdindex 844840fbad..5cc243e58f 100644--- a/skills/conventions/brain-first.md+++ b/skills/conventions/brain-first.md@@ -5,6 +5,38 @@Sub-agents and fresh sessions inherit gbrain tools but not the knowledge ofwhen and how to use them. This file is that knowledge.+## Retrieval: gbrain first++For anything in the brain, search gbrain, then read the page a hit names. Don't+`grep`, `rg` or `cat` the brain checkout, or run SQL over pages and+frontmatter, before gbrain: gbrain reads the index across sources, ranks results,+filters by type, date and source, and returns the slug to read next. Use the+files only when gbrain is unreachable or for an edit not yet synced.++```bash+gbrain search "Acme Example" # names, codes, exact phrases+gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)+gbrain query "why did the launch move" # questions and concepts+gbrain search "launch" --types '["meeting","person"]' # only these page types+gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)+gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'+gbrain get companies/acme-example # read the page a hit points to+gbrain recall "Alice Example" # facts saved with remember+gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)+gbrain timeline companies/acme-example --since 2026-10-01 # dated events on one page+gbrain list --type meeting --limit 50 # enumerate by type or --tag (instead of SQL)+```++- `--types` takes a JSON array. `--since`/`--until` are `query` flags+ (YYYY-MM-DD or 7d/2w/1y) and match each page's effective date: its+ frontmatter date, else when it was imported.+- Keyword search matches words, not slugs: search `"Acme Example"`, and use+ `backlinks` to find pages linking to `companies/acme-example`.+- Without `--source`, a search reads the resolved source (a notice names it+ when it routes); `--source __all__` searches every source.+- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.+ Read a degraded notice before concluding the brain has nothing.+## Available GBrain ToolsYour tool inventory includes these (prefixed `gbrain__` in OpenClaw):diff --git a/skills/correction-pipeline/SKILL.md b/skills/correction-pipeline/SKILL.mdindex 1cbf0c2d2a..427e29e2b2 100644--- a/skills/correction-pipeline/SKILL.md+++ b/skills/correction-pipeline/SKILL.md@@ -58,10 +58,12 @@ gbrain search "<relevant terms>" --limit 10```For concept-shaped or synonym-phrased claims, escalate to `gbrain query-"<question>"` (LLM expansion recovers phrasings `search` misses). Also grep-the brain repo checkout directly — resolve it once from config:+"<question>"` (LLM expansion recovers phrasings `search` misses). To list+every indexed page carrying the claim, use a keyword search (it pages every+match); grep the checkout only for edits not yet synced:```bash+gbrain search '"<wrong claim terms>"' --match keywordBRAIN_DIR=$(gbrain config get sync.repo_path)grep -ri "<wrong claim terms>" "$BRAIN_DIR/people/" "$BRAIN_DIR/companies/" "$BRAIN_DIR/concepts/" 2>/dev/null```@@ -166,8 +168,8 @@ The wrong fact may have propagated into OTHER brain pages, synthesis output,or memory files.```bash-grep -ri "<wrong claim terms>" "$BRAIN_DIR" 2>/dev/null | grep -v ".git"-gbrain search "<wrong claim terms>" --limit 20+gbrain search '"<wrong claim terms>"' --match keyword+grep -ri "<wrong claim terms>" "$BRAIN_DIR" 2>/dev/null | grep -v ".git" # edits not yet synced```Fix ALL instances, not just the first one found. Re-sync after repo edits.diff --git a/skills/query/SKILL.md b/skills/query/SKILL.mdindex 5aefe9116d..2125a8a3c9 100644--- a/skills/query/SKILL.md+++ b/skills/query/SKILL.md@@ -68,6 +68,9 @@ This skill guarantees:- Cheap-hybrid search gbrain for exact tokens / known names (search)- Full-hybrid search gbrain for concept questions (query; `--expand` adds multi-query expansion)- List pages in gbrain by type or check backlinks for structural queries+ - Narrow with filters instead of grepping the brain checkout: `--types '["meeting"]'`,+ `--match keyword`, `gbrain query "<q>" --since 2026-09-01 --until 2026-09-30`, `--source <id>`.+ Copyable examples: "Retrieval: gbrain first" in `skills/conventions/brain-first.md`.3. **Read top results.** Read the top 3-5 pages from gbrain to get full context.4. **Synthesize answer** with citations. Every claim traces back to a specific page slug.5. **Flag gaps.** If the brain doesn't have info, say "the brain doesn't have information on X" rather than hallucinating. Read the result's notices first (see "When it fails"): a degraded or truncated result is not a gap.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 843b6c5d7b..30b87bf006 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -1,5 +1,5 @@{- "RESOLVER.md": "7387d5d7da701ffae26f13752b3551fbd6c3cf048085ba7064da6159a617a601",+ "RESOLVER.md": "d788b96fae6731a9bad8586074e40d6b22d360f5b5a7f7a85cea0ef3bb46cf2d","_AGENT_README.md": "ab51e36e9a0b53f4d0609294b0556444399147834932d9c1acfdc7aa367c70b8","_brain-filing-rules.json": "4e6ecee2d94867d146583d60bf98dccdd9205bb70793af56fe1397a2b258ae0d","_brain-filing-rules.md": "ff42b331bce542d708f97ff0a73ff0fb5664b46ee9b1862a5478b15dc637487e",@@ -20,7 +20,7 @@"brain-ingest-gate/routing-eval.jsonl": "281e94affbb8631ef7ff44203884cce1c03c468b27f893829da1e6e439401a33","brain-link-discipline/SKILL.md": "db2a77319475dd8eb370e9a3bb0eafe81d3b19d2de126113b30df7454dd9a069","brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",- "brain-ops/SKILL.md": "8e9a6997e94c4474ffff3c4fff95ec90925cb5be1fe65dcbbd1618bcd991b734",+ "brain-ops/SKILL.md": "2f79c8699ca1316d113fe7c20f21791310f1884e1e276051e26c753510877b05","brain-pdf/SKILL.md": "2dfffd2373f00b5f11c1e4b39a75be48e90870201b4c11979d520bd5975dcae4","brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734","brain-taxonomist/SKILL.md": "418fd4cdac3355551c42a70fea4d76e3d9255fe04698358b2c1e89dc666bf11d",@@ -45,7 +45,7 @@"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab","conventions/agent-operator-protocol.md": "d7cfc7e4c84f61392658cbe969058b1e8237b7d44c3ebdeec352569ffddbe001",- "conventions/brain-first.md": "987223ce443b3e8cdcd22975aafabce778016f238deddf544c346238dbde1bd9",+ "conventions/brain-first.md": "a207e18b0a988aee2435c001278484b7bd9a82ee93472d8f6b918e0e952c2dcc","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",@@ -64,7 +64,7 @@"conventions/untrusted-content.md": "259384d490892cd0e1e8e054decf752d7354f516c83aee57b332c1a96aac6a6e","conversation-archive/SKILL.md": "895b63ecc46ab7bd173ba9bb8d0cb740f355fbfaf429584b74842823edf68a42","conversation-archive/routing-eval.jsonl": "ae087a84b1fd5b108b7cdab8d035a09b3ccecd8aad53ba5f71e463059108cfca",- "correction-pipeline/SKILL.md": "c19869aa60ac00e15fc97ca016dd84dd63338fdf3d7b39990b33900eb7dcc703",+ "correction-pipeline/SKILL.md": "04b4aee06d7fcdd75db314da432ed7c08b5fbc20f117f18062c64aaf795bc564","correction-pipeline/routing-eval.jsonl": "7f8d96606a8d7bed3d79fdcee6904764c8abb9fa0b506adb414b5c4805b69d0b","cron-scheduler/SKILL.md": "a89bfeb058034d5033c42d56b35297e5f33e28a6dac01860d5e033a10262b3a5","cross-modal-review/SKILL.md": "fc00a04e2ff9f498bee9b0b636bceba9dcfdc869c35d9a983109f408170f0807",@@ -197,7 +197,7 @@"postgres-adopt/SKILL.md": "8cf801e2e0d29da525a8c4ba275b91e6caffc8aae8e648cbcc8bceaab865c890","postgres-adopt/routing-eval.jsonl": "db91c1fae408a45082979c402c11eff413277ace6cf746297cc86009dcaefe06","publish/SKILL.md": "271bd9ba87279429cd934509071dd032b859d59264038c38829c9af46f15c13b",- "query/SKILL.md": "1a57297d525f3aa30c7b4aa89d840b2dfad8b7e8ec366761f4338c09d51f056a",+ "query/SKILL.md": "afe2a88394bb78bb651ebd5434415dfa1a96cbc3c52848e134be16b3e8d36f08","query/routing-eval.jsonl": "74f5a91e52fabc54e0e9403fa17db87ee26bb7ebb8ae8005148c51142abc62fe","remote-mcp/SKILL.md": "753d4df2c6b8c837d00a9c0593028220bdceb1a83b08b29a1d9b973242b789c5","remote-mcp/routing-eval.jsonl": "7287693135c9fe2d6495d81d22746ddf41b116254db4b6e683dbdee251e08f8e",diff --git a/src/core/engine-sql/titles.ts b/src/core/engine-sql/titles.tsindex a10cbd8adb..85c38add6d 100644--- a/src/core/engine-sql/titles.ts+++ b/src/core/engine-sql/titles.ts@@ -24,21 +24,22 @@* collapse: a regexp measured +37 ms); the tier's JS `normalizeAlias` recheck* stays authoritative, so a mismatch can only miss, never promote.*- * Remote predicate (title FTS; diagnosis credited to PR #5853 by morven-ai):- * safe-chunks callers must match the title alone, which used to mean a- * per-row `to_tsvector(title)` that no index serves (a scan of every page in- * scope). `pages.search_vector` carries the title, and only the title, at- * weight A (schema trigger, `reindex-search-vector`, page-state projection),- * so the remote arm matches `search_vector @@ q_a`, where `q_a` is the- * websearch query with every lexeme labeled `:A`. That is served by- * `idx_pages_search`, and negated or phrase terms are evaluated on title- * lexemes only, so timeline text can never change which titles a remote- * caller sees. Ranking uses the weight-A slice (`ts_filter(..., '{a}')`).- * Remote matching follows the language `search_vector` was built with;- * `gbrain reindex-search-vector` rebuilds it after an FTS language change.- * A page with a NULL `search_vector` is absent from the remote arm (the- * BEFORE INSERT/UPDATE trigger keeps it non-NULL). The local arm keeps- * ranking the whole `search_vector` (title weight A dominates).+ * Title predicate (title FTS; diagnosis credited to PR #5853 by morven-ai):+ * the arm matches the title alone, which used to mean a per-row+ * `to_tsvector(title)` that no index serves (a scan of every page in scope).+ * `pages.search_vector` carries the title, and only the title, at weight A+ * (schema trigger, `reindex-search-vector`, page-state projection), so the+ * arm matches `search_vector @@ q_a`, where `q_a` is the websearch query+ * with every lexeme labeled `:A`. That is served by `idx_pages_search`, and+ * negated or phrase terms are evaluated on title lexemes only, so timeline+ * text (weight C) never changes which titles a caller sees. Ranking uses the+ * weight-A slice (`ts_filter(..., '{a}')`). Matching follows the language+ * `search_vector` was built with; `gbrain reindex-search-vector` rebuilds it+ * after an FTS language change. A page with a NULL `search_vector` is absent+ * from the arm (the BEFORE INSERT/UPDATE trigger keeps it non-NULL). Local+ * callers used to match the whole vector, so a date in a question pulled every+ * dated timeline into `ts_rank_cd` on the OR fallback: 3-5 s on a large brain+ * (#7135, diagnosed by @veltri-23 in #7136).*/import type { SearchOpts, SearchResult } from '../types.ts';import { searchLimitCap } from '../search/eval-pool-depth.ts';diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex af1b260aba..25d04e51e8 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -114,7 +114,8 @@ import { logConnectionEvent } from './connection-audit.ts';import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';-import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';+import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns, orFallbackTokens } from './search/sql-ranking.ts';+import { narrowOrFallbackTokens, orTokenSharesSql } from './search/keyword-or-narrow.ts';import { buildKeywordChunkMatch } from './search/keyword-chunk-match.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';@@ -1096,7 +1097,9 @@ export class PostgresEngine implements BrainEngine {// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();- const rankParam = opts?.rankQuery ? `$${params.push(opts.rankQuery)}` : '$1';+ // An OR retry may match fewer terms than it ranks with (keyword-or-narrow.ts), so a caller that relaxes binds the rank query on its own.+ const rankIdx = opts?.rankQuery ? params.push(opts.rankQuery) - 1 : opts?.orFallback ? params.push(params[0]) - 1 : 0;+ const rankParam = `$${rankIdx + 1}`;const chunk = buildKeywordChunkMatch(ftsLang, opts?.excludePrivate);const rawQuery = `@@ -1148,11 +1151,12 @@ export class PostgresEngine implements BrainEngine {// attempt's enable_seqscan are one settings statement// (postgres-engine/search-settings.ts).const statementTimeout = await this.keywordStatementTimeoutSetting();- const runKeyword = (queryText: string, relaxed = false) => this.keywordTimeouts.run(opts?.keywordTimeoutCache === true, this,- [statementTimeout, relaxed, rawQuery, collapseWebsearchDashRuns(queryText), params.slice(1), opts?.sourceIds ?? null, opts?.sourceId ?? null], () =>+ const runKeyword = (queryText: string, relaxed = false, rankText = queryText) => this.keywordTimeouts.run(opts?.keywordTimeoutCache === true, this,+ [statementTimeout, relaxed, rawQuery, collapseWebsearchDashRuns(queryText), collapseWebsearchDashRuns(rankText), params.slice(1), opts?.sourceIds ?? null, opts?.sourceId ?? null], () =>this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, (tx) => {const boundParams = [...params];boundParams[0] = collapseWebsearchDashRuns(queryText);+ if (rankIdx > 0 && !opts?.rankQuery) boundParams[rankIdx] = collapseWebsearchDashRuns(rankText);return tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);}, { alwaysTransaction: true, jitOff: true, settings: relaxed ? { statement_timeout: statementTimeout, enable_seqscan: 'off' } : { statement_timeout: statementTimeout } }));let rows = await runKeyword(query);@@ -1168,7 +1172,12 @@ export class PostgresEngine implements BrainEngine {if (rows.length === 0 && opts?.orFallback) {const orQuery = buildOrFallbackWebsearchQuery(query);if (orQuery) {- rows = await runKeyword(orQuery, true);+ // Match only the rarest terms within the cap (search/keyword-or-narrow.ts); a failed statistics read keeps them all.+ const shares = await this.executeRaw<{ token: string; lexemes: number; share: number | null; rows: number; analyzed: boolean }>(orTokenSharesSql(ftsLang), [orFallbackTokens(query)]).catch(() => []);+ const narrowed = shares[0]?.analyzed+ ? narrowOrFallbackTokens(shares.map(r => ({ token: r.token, lexemes: Number(r.lexemes), share: r.share === null ? null : Number(r.share) })), Number(shares[0].rows))+ : null;+ rows = await runKeyword(narrowed ? narrowed.join(' OR ') : orQuery, true, orQuery);// 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's// fusion can demote them — an OR-of-common-terms match must not// outvote a healthy vector arm (SearchResult.keyword_relaxed doc).diff --git a/src/core/search/dedup.ts b/src/core/search/dedup.tsindex c9076200ad..6eb2c0fa08 100644--- a/src/core/search/dedup.ts+++ b/src/core/search/dedup.ts@@ -181,15 +181,25 @@ function dedupBySource(results: SearchResult[], keyOf: (r: SearchResult) => stri*/function dedupByTextSimilarity(results: SearchResult[], threshold: number): SearchResult[] {const kept: SearchResult[] = [];- const keptWordsByPage = new Map<string, Set<string>[]>();+ const keptByPage = new Map<string, SearchResult[]>();+ // Word sets are built only for chunks that share a page with a kept chunk:+ // most results are alone on their page, and a widened result row can hold a+ // whole page body (GBRA-156).+ const wordSets = new Map<SearchResult, Set<string>>();+ const wordsOf = (r: SearchResult) => {+ let words = wordSets.get(r);+ if (!words) wordSets.set(r, words = new Set(r.chunk_text.toLowerCase().split(/\s+/)));+ return words;+ };for (const r of results) {- const rWords = new Set(r.chunk_text.toLowerCase().split(/\s+/));const k = pageKey(r);- const samePageKept = keptWordsByPage.get(k) ?? [];+ const samePageKept = keptByPage.get(k) ?? [];let tooSimilar = false;- for (const kWords of samePageKept) {+ for (const keptResult of samePageKept) {+ const rWords = wordsOf(r);+ const kWords = wordsOf(keptResult);// |A ∩ B| by iterating the smaller set; |A ∪ B| = |A| + |B| - |A ∩ B|.// Same value as building intersection/union Sets, without allocating.const [smaller, larger] = rWords.size <= kWords.size ? [rWords, kWords] : [kWords, rWords];@@ -206,8 +216,8 @@ function dedupByTextSimilarity(results: SearchResult[], threshold: number): Searif (!tooSimilar) {kept.push(r);- samePageKept.push(rWords);- keptWordsByPage.set(k, samePageKept);+ samePageKept.push(r);+ keptByPage.set(k, samePageKept);}}diff --git a/src/core/search/keyword-or-narrow.ts b/src/core/search/keyword-or-narrow.tsnew file mode 100644index 0000000000..a29399e874--- /dev/null+++ b/src/core/search/keyword-or-narrow.ts@@ -0,0 +1,68 @@+/**+ * Bounded keyword OR fallback (GBRA-156). When a keyword query's strict AND+ * finds nothing, the arm retries with the OR of its terms. ts_rank then runs+ * on every chunk holding any term: on a 2M-chunk brain a question with one+ * common word matched 100k-850k chunks and took 1-3.8 s, and the worst ran+ * into the 8 s keyword statement timeout, which drops the arm's rows.+ *+ * Postgres keeps per-lexeme row shares for `content_chunks.search_vector`+ * (`pg_stats.most_common_elems`, the statistics the planner prices a+ * tsquery with). The retry keeps every term the statistics do not track+ * (rare, so cheap to match, or absent), then adds the tracked terms rarest+ * first while their estimated matches stay within OR_FALLBACK_MATCH_CAP, and+ * always the rarest tracked one, so a retry never rests on terms that may+ * match nothing. It still ranks with the full OR query, so a retained chunk+ * scores exactly as before; a chunk that holds only the dropped, most common+ * terms is no longer a candidate. Without statistics (never analyzed), or+ * when every term fits, the retry is unchanged.+ */++/** Estimated chunk matches the tracked terms of an OR retry may add: about 0.2 s of ts_rank on the 2M-chunk bench. */+export const OR_FALLBACK_MATCH_CAP = 20_000;++/**+ * A token's statistics: `lexemes` its lexeme count (0 for a stopword),+ * `share` the largest tracked row share among them, null when none is+ * tracked.+ */+export interface OrTokenShare { token: string; lexemes: number; share: number | null }++/**+ * Per-token statistics over `content_chunks.search_vector`, in token order,+ * plus the table's row estimate and whether the column has element+ * statistics at all. `$1` is the token array.+ */+export function orTokenSharesSql(ftsLang: string): string {+ return `WITH s AS (+ SELECT most_common_elems::text::text[] AS elems, most_common_elem_freqs AS freqs+ FROM pg_stats WHERE schemaname = current_schema() AND tablename = 'content_chunks' AND attname = 'search_vector'+ )+ SELECT u.token,+ (SELECT count(*) FROM unnest(to_tsvector('${ftsLang}', u.token)))::int AS lexemes,+ (SELECT max(s.freqs[array_position(s.elems, l.lexeme)]) FROM s, unnest(to_tsvector('${ftsLang}', u.token)) AS l) AS share,+ (SELECT reltuples FROM pg_class WHERE oid = 'content_chunks'::regclass)::float8 AS rows,+ EXISTS (SELECT 1 FROM s WHERE s.freqs IS NOT NULL) AS analyzed+ FROM unnest($1::text[]) WITH ORDINALITY AS u(token, ord)+ ORDER BY u.ord`;+}++/**+ * The tokens an OR retry should match, or null to keep every token: the+ * untracked ones, then tracked ones rarest first within `cap` estimated+ * rows (the rarest tracked one always), stopwords dropped. Null when no word+ * would be dropped.+ */+export function narrowOrFallbackTokens(tokens: OrTokenShare[], rows: number, cap = OR_FALLBACK_MATCH_CAP): string[] | null {+ if (!(rows > 0)) return null;+ const words = tokens.filter(t => t.lexemes > 0);+ const kept = words.filter(t => t.share === null).map(t => t.token);+ const tracked = words.filter(t => t.share !== null).sort((a, b) => a.share! - b.share!);+ let estimate = 0;+ for (const [i, t] of tracked.entries()) {+ estimate += t.share! * rows;+ if (i > 0 && estimate > cap) break;+ kept.push(t.token);+ }+ if (kept.length === 0 || kept.length === words.length) return null;+ return kept;+}diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.tsindex 56e81d1a04..b9cd6f3ffb 100644--- a/src/core/search/sql-ranking.ts+++ b/src/core/search/sql-ranking.ts@@ -364,13 +364,25 @@ export function buildOrFallbackWebsearchQuery(query: string): string | null {// F3 operator guard: any double quote, or a dash LEADING a token// (whitespace/start boundary — interior hyphens like "foo-bar" are fine).if (query.includes('"') || /(^|\s)-\S/.test(query)) return null;- const tokens = query+ const tokens = orFallbackTokens(query);+ return tokens.length < 2 ? null : tokens.join(' OR ');+}++/**+ * The OR fallback's terms: word tokens without the literal OR/AND words, each+ * once (case-insensitive, first spelling kept). A repeated word adds no match+ * and only makes ts_rank evaluate the lexeme again on every matching row:+ * 4.5 s against 0.55 s over a 16,840-page match set, with identical scores+ * (#7135, diagnosed by @veltri-23 in #7136). Callers apply the operator guard.+ */+export function orFallbackTokens(query: string): string[] {+ const seen = new Set<string>();+ return query.normalize('NFKC').split(/[^\p{L}\p{N}]+/u).filter(Boolean)- .filter(t => { const u = t.toUpperCase(); return u !== 'OR' && u !== 'AND'; });- if (tokens.length < 2) return null;- return tokens.join(' OR ');+ .filter(t => { const u = t.toUpperCase(); return u !== 'OR' && u !== 'AND'; })+ .filter(t => { const k = t.toLowerCase(); if (seen.has(k)) return false; seen.add(k); return true; });}// ============================================================diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.tsindex 7e5bae7efa..4bd0388a06 100644--- a/src/core/search/title-statement.ts+++ b/src/core/search/title-statement.ts@@ -60,8 +60,8 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | und// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();const tsq = `websearch_to_tsquery('${ftsLang}', gbrain_fts_input($1))`;- const matchSql = safeChunks ? `p.search_vector @@ ${WEIGHT_A_QUERY(ftsLang)}` : `p.search_vector @@ ${tsq}`;- const rankSql = safeChunks ? `ts_rank_cd(ts_filter(p.search_vector, '{a}'), ${tsq})` : `ts_rank_cd(p.search_vector, ${tsq})`;+ const matchSql = `p.search_vector @@ ${WEIGHT_A_QUERY(ftsLang)}`;+ const rankSql = `ts_rank_cd(ts_filter(p.search_vector, '{a}'), ${tsq})`;const params: unknown[] = [boundWebsearchQuery(query), normalizeAlias(query), limit, offset];let filters = '';diff --git a/src/core/search/vector-pool.ts b/src/core/search/vector-pool.tsindex ed294f22b5..f8fd6b4940 100644--- a/src/core/search/vector-pool.ts+++ b/src/core/search/vector-pool.ts@@ -25,26 +25,35 @@ export interface VectorPoolAttempt {* Runs the statement's index walk, then its scope scan (each when present),* before the pool. Walk rows answer the search when its window is full and* they fill the limit; scope-scan rows when they fill the limit or the scope- * ran out of eligible chunks (a short window). Otherwise, or past an- * attempt's 2 s budget, this returns null and the caller runs the pool. The- * walk may visit its whole over-fetched window, so its tuple budget covers it.+ * ran out of eligible chunks (a short window). A full walk window that holds+ * fewer pages than the limit (pages with many chunks) widens the walk the way+ * the pool escalates (`nextInnerLimit`), so it returns the set the pool's+ * widened attempt would, through the index, instead of handing a large brain+ * to the joined statement, whose plan there is a full scan (GBRA-156).+ * Otherwise, or past an attempt's 2 s budget, this returns null and the+ * caller runs the pool. The walk may visit its whole over-fetched window, so+ * its tuple budget covers it.*/export async function searchIndexWalk(stmt: Pick<VectorSearchStatement, 'indexWalkSql' | 'scopeScanSql' | 'innerLimit' | 'indexWalkOverfetch'>,limit: number,run: (attempt: VectorPoolAttempt) => Promise<VectorPoolBatch>,): Promise<Record<string, unknown>[] | null> {- const attempt = async (kind: { indexWalk: true } | { scopeScan: true }) => {+ const attempt = async (kind: { indexWalk: true } | { scopeScan: true }, innerLimit = stmt.innerLimit) => {try {- return await run({ innerLimit: stmt.innerLimit, maxScanTuples: Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch), remainingMs: 2_000, exact: false, ...kind });+ return await run({ innerLimit, maxScanTuples: Math.max(2_000, innerLimit * stmt.indexWalkOverfetch), remainingMs: 2_000, exact: false, ...kind });} catch (error) {if ((error as { code?: string }).code === '57014') return null;throw error;}};if (stmt.indexWalkSql) {- const batch = await attempt({ indexWalk: true });- if (batch && batch.candidatePool >= stmt.innerLimit && batch.rows.length >= limit) return batch.rows;+ for (let innerLimit = stmt.innerLimit, escalations = 0; ; innerLimit = nextInnerLimit(innerLimit, stmt.innerLimit), escalations++) {+ const batch = await attempt({ indexWalk: true }, innerLimit);+ if (!batch || batch.candidatePool < innerLimit) break;+ if (batch.rows.length >= limit) return batch.rows;+ if (escalations >= MAX_POOL_ESCALATIONS) break;+ }}if (stmt.scopeScanSql) {const batch = await attempt({ scopeScan: true });@@ -68,6 +77,14 @@ export async function searchIndexWalk(*/export const POOL_MAX_SCAN_TUPLES = 20_000;+/** How many times a short pool (and a walk whose full window holds too few pages) widens its window. */+const MAX_POOL_ESCALATIONS = 3;++/** The next, wider candidate window: four times the last, capped at 20,000 chunks (or the first window when that is larger). */+function nextInnerLimit(innerLimit: number, initialLimit: number): number {+ return Math.min(innerLimit * 4, Math.max(initialLimit, 20_000));+}+export function remainingVectorBudget(deadline: number): number {const remaining = Math.floor(deadline - performance.now());if (remaining <= 0) throw Object.assign(new Error('Vector candidate deadline exhausted'), { code: '57014' });@@ -102,8 +119,8 @@ export async function searchVectorPool(if (remaining() === 0) { reason = 'deadline'; break; }if (!(await hasMore(batch.eligiblePool ?? batch.candidatePool, remaining()))) return batch.rows;}- if (escalations >= 3 || (indexed && !iterative)) break;- innerLimit = Math.min(innerLimit * 4, Math.max(initialLimit, 20_000));+ if (escalations >= MAX_POOL_ESCALATIONS || (indexed && !iterative)) break;+ innerLimit = nextInnerLimit(innerLimit, initialLimit);escalations++;}if (engine === 'postgres' && indexed && remaining() > 0) {diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.tsindex d4ca3cf30b..44d3cce68f 100644--- a/src/core/secret-scan.ts+++ b/src/core/secret-scan.ts@@ -700,7 +700,22 @@ function assignmentValueIsSecretShaped(value: string): boolean {return !(value.startsWith('/') && !LEGACY_ASSIGNMENT_VALUE_RE.test(value));}+/**+ * One compiled set per option combination. scanInternal is synchronous and+ * resets each pattern's lastIndex before every line, so the 'g' regexes are+ * safe to share; recompiling them per call cost a search response about a+ * millisecond per scanned field (GBRA-156).+ */+const compiledPatterns = new Map<string, CompiledPattern[]>();+function compilePatterns(opts: ScanOpts): CompiledPattern[] {+ const key = `${opts.highEntropy === true}|${opts.labeledCredentials === true}`;+ let compiled = compiledPatterns.get(key);+ if (!compiled) compiledPatterns.set(key, compiled = buildPatterns(opts));+ return compiled;+}++function buildPatterns(opts: ScanOpts): CompiledPattern[] {const out: CompiledPattern[] = CORE_PATTERNS.map((p) => ({name: p.name,// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- p.source is a compile-time literal from CORE_PATTERNS (never caller input); every pattern uses bounded quantifiers, pinned by test/secret-scan-perf.test.tsdiff --git a/templates/bootstrap/AGENTS.md.template b/templates/bootstrap/AGENTS.md.templateindex 58641923dc..08afb44bf2 100644--- a/templates/bootstrap/AGENTS.md.template+++ b/templates/bootstrap/AGENTS.md.template@@ -84,7 +84,9 @@ commitment named in the message, search the brain before answering: `recall` forfacts, `query` for synthesis, `get_page` for the record. If context was alreadyinjected this turn, use it. Hold what you find silently — never narrate retrieval("based on my memory", "I recall"). Never use generic file-grep where a brain tool-exists.+exists. From a shell: `gbrain search "<name>"` or `gbrain query "<question>"`, then+`gbrain get <slug>`; `gbrain search '"<term>"' --match keyword` lists every matching+page, and `--types '["meeting"]'`, `query --since 30d` and `--source <id>` narrow it.**Gate 4 — Receipts.** Every factual claim about the record — what someone said,did, decided, or committed to — must be backed by a line retrieved THIS turn anddiff --git a/templates/bootstrap/template-repo/AGENTS.md b/templates/bootstrap/template-repo/AGENTS.mdindex 3880532c53..9fa18542b2 100644--- a/templates/bootstrap/template-repo/AGENTS.md+++ b/templates/bootstrap/template-repo/AGENTS.md@@ -88,7 +88,9 @@ commitment named in the message, search the brain before answering: `recall` forfacts, `query` for synthesis, `get_page` for the record. If context was alreadyinjected this turn, use it. Hold what you find silently — never narrate retrieval("based on my memory", "I recall"). Never use generic file-grep where a brain tool-exists.+exists. From a shell: `gbrain search "<name>"` or `gbrain query "<question>"`, then+`gbrain get <slug>`; `gbrain search '"<term>"' --match keyword` lists every matching+page, and `--types '["meeting"]'`, `query --since 30d` and `--source <id>` narrow it.**Gate 4 — Receipts.** Every factual claim about the record — what someone said,did, decided, or committed to — must be backed by a line retrieved THIS turn anddiff --git a/test/e2e/keyword-or-narrow-postgres.test.ts b/test/e2e/keyword-or-narrow-postgres.test.tsnew file mode 100644index 0000000000..c622fca065--- /dev/null+++ b/test/e2e/keyword-or-narrow-postgres.test.ts@@ -0,0 +1,56 @@+/**+ * GBRA-156 bounded keyword OR fallback on real Postgres: the statistics read+ * (orTokenSharesSql over pg_stats.most_common_elems) returns what+ * narrowOrFallbackTokens needs, stopwords included, and the engine's OR retry+ * still returns relaxed rows for the rare and the common terms when every+ * term fits the cap. Postgres only (PGLite has no OR narrowing); skipped+ * without DATABASE_URL.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { seedPage } from '../helpers/keyword-paging-fixture.ts';+import { narrowOrFallbackTokens, orTokenSharesSql } from '../../src/core/search/keyword-or-narrow.ts';++const run = process.env.DATABASE_URL ? describe : describe.skip;+let engine: BrainEngine;+let close: () => Promise<void> = async () => {};++run('keyword OR fallback narrowing on Postgres', () => {+ beforeAll(async () => {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = isolated.engine;+ close = isolated.close;+ for (let i = 0; i < 40; i++) await seedPage(engine, `notes/quasar-log-${i}`, `Quasar log entry ${i}: the quasar survey, night ${i}.`);+ await seedPage(engine, 'notes/nebulith-field', 'Field notes on the nebulith deposit.');+ await engine.executeRaw('ANALYZE content_chunks');+ }, 300_000);++ afterAll(async () => { await close(); });++ test('the statistics read reports lexemes, tracked shares and the row estimate', async () => {+ const rows = await engine.executeRaw<{ token: string; lexemes: number; share: number | null; rows: number; analyzed: boolean }>(+ orTokenSharesSql('english'), [['the', 'quasar', 'nebulith', 'zzqxv']]);+ expect(rows.map(r => r.token)).toEqual(['the', 'quasar', 'nebulith', 'zzqxv']);+ expect(rows[0].analyzed).toBe(true);+ expect(Number(rows[0].rows)).toBeGreaterThan(30);+ expect(rows.map(r => Number(r.lexemes))).toEqual([0, 1, 1, 1]);+ expect(Number(rows[1].share)).toBeGreaterThan(0.9);+ expect(rows[3].share).toBeNull();+ const nebulith = rows[2].share === null ? null : Number(rows[2].share);+ expect(nebulith === null || nebulith < 0.05).toBe(true);++ const tokens = rows.map(r => ({ token: r.token, lexemes: Number(r.lexemes), share: r.share === null ? null : Number(r.share) }));+ expect(narrowOrFallbackTokens(tokens, Number(rows[0].rows), 10)).toEqual(['zzqxv', 'nebulith']);+ expect(narrowOrFallbackTokens(tokens, Number(rows[0].rows))).toBeNull();+ });++ test('an OR retry within the cap still returns relaxed rows for every term', async () => {+ expect(await engine.searchKeyword('quasar nebulith zzqxv', { limit: 10 })).toEqual([]);+ const rows = await engine.searchKeyword('quasar nebulith zzqxv', { limit: 50, orFallback: true });+ const slugs = new Set(rows.map(r => r.slug));+ expect(slugs.has('notes/nebulith-field')).toBe(true);+ expect([...slugs].some(s => s.startsWith('notes/quasar-log-'))).toBe(true);+ expect(rows.every(r => r.keyword_relaxed === true)).toBe(true);+ });+});diff --git a/test/search/keyword-or-narrow.test.ts b/test/search/keyword-or-narrow.test.tsnew file mode 100644index 0000000000..ca731d9ddf--- /dev/null+++ b/test/search/keyword-or-narrow.test.ts@@ -0,0 +1,33 @@+import { describe, expect, test } from 'bun:test';+import { narrowOrFallbackTokens, OR_FALLBACK_MATCH_CAP, type OrTokenShare } from '../../src/core/search/keyword-or-narrow.ts';++const t = (token: string, share: number | null, lexemes = 1): OrTokenShare => ({ token, lexemes, share });++describe('narrowOrFallbackTokens', () => {+ test('keeps the rarest tracked terms while their estimated matches fit the cap, and always the rarest one', () => {+ // 2M rows: kalomi ~2k, pricing ~8k (10k total), meeting ~400k.+ expect(narrowOrFallbackTokens([t('meeting', 0.2), t('kalomi', 0.001), t('pricing', 0.004)], 2_000_000)).toEqual(['kalomi', 'pricing']);+ expect(narrowOrFallbackTokens([t('meeting', 0.2), t('said', 0.3)], 2_000_000)).toEqual(['meeting']);+ });++ test('untracked terms (rare or absent) are always kept, next to the rarest tracked term', () => {+ expect(narrowOrFallbackTokens([t('zqxv', null), t('meeting', 0.2), t('said', 0.3)], 2_000_000)).toEqual(['zqxv', 'meeting']);+ expect(narrowOrFallbackTokens([t('zqxv', null), t('kalomi', 0.001), t('said', 0.3)], 2_000_000)).toEqual(['zqxv', 'kalomi']);+ });++ test('changes nothing when every term fits, when nothing is tracked, or on an empty table', () => {+ expect(narrowOrFallbackTokens([t('alpha', 0.001), t('beta', 0.002)], 2_000_000)).toBeNull();+ expect(narrowOrFallbackTokens([t('alpha', null), t('beta', null)], 2_000_000)).toBeNull();+ expect(narrowOrFallbackTokens([t('alpha', 0.5), t('beta', 0.5)], 0)).toBeNull();+ });++ test('stopwords (no lexeme) are dropped and never count as kept terms', () => {+ expect(narrowOrFallbackTokens([t('the', null, 0), t('meeting', 0.2), t('said', 0.3)], 2_000_000)).toEqual(['meeting']);+ expect(narrowOrFallbackTokens([t('the', null, 0), t('of', null, 0)], 2_000_000)).toBeNull();+ });++ test('the cap is a row count', () => {+ expect(narrowOrFallbackTokens([t('a1', 0.01), t('b2', 0.01)], OR_FALLBACK_MATCH_CAP * 100)).toEqual(['a1']);+ expect(narrowOrFallbackTokens([t('a1', 0.01), t('b2', 0.01)], OR_FALLBACK_MATCH_CAP * 50)).toBeNull();+ });+});diff --git a/test/search/title-arm-exact.test.ts b/test/search/title-arm-exact.test.tsindex 2298dbbc11..3bff3a0296 100644--- a/test/search/title-arm-exact.test.ts+++ b/test/search/title-arm-exact.test.ts@@ -7,10 +7,10 @@* so an identity page titled exactly "Acme" (created last) was buried under* 60+ "Acme weekly sync N" pages for local and remote callers.*- * Remote predicate: safe-chunks callers match weight-A (title) lexemes of+ * Title predicate: every caller matches weight-A (title) lexemes of* pages.search_vector. Parity cases compare against the previous title-only* predicate (`to_tsvector(lang, title) @@ websearch_to_tsquery(lang, q)`),- * so timeline text can never change which titles a remote caller sees.+ * so timeline text can never change which titles a caller sees.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import type { BrainEngine } from '../../src/core/engine.ts';diff --git a/test/search/title-retrieval-arm.test.ts b/test/search/title-retrieval-arm.test.tsindex cc8cc3653e..171122fb0d 100644--- a/test/search/title-retrieval-arm.test.ts+++ b/test/search/title-retrieval-arm.test.ts@@ -154,6 +154,28 @@ describe('searchTitles — D1 title candidate arm', () => {expect(tlHit.chunk_index).toBe(2); // lowest index when no compiled_truth chunk});+ test('local callers match the title only: a timeline word is not a title hit, on the strict query or the OR fallback (#7135)', async () => {+ await engine.putPage('people/dated-entity', {+ type: 'person',+ title: 'Cobalt Meridian Atlas',+ compiled_truth: 'unrelated body',+ timeline: '- 2026-10-07: zircon quarry visit',+ });+ await installFixtureChunks(engine, 'people/dated-entity', [+ { chunk_index: 0, chunk_text: 'unrelated body', chunk_source: 'compiled_truth' },+ ]);+ const inVector = await (engine as any).db.query(+ `SELECT search_vector @@ to_tsquery('english', 'zircon') AS hit FROM pages WHERE slug = 'people/dated-entity'`,+ );+ expect(inVector.rows[0].hit).toBe(true);++ const slugs = async (q: string) => (await engine.searchTitles(q, { limit: 10 })).map(r => r.slug);+ expect(await slugs('zircon quarry')).not.toContain('people/dated-entity');+ expect(await slugs('zircon nebulith')).not.toContain('people/dated-entity');+ expect(await slugs('Cobalt Meridian')).toContain('people/dated-entity');+ expect(await slugs('Cobalt zircon')).toContain('people/dated-entity');+ });+test('respects soft-delete visibility and source scoping', async () => {await seedTitleOnlyPage();@@ -299,6 +321,10 @@ describe('buildOrFallbackWebsearchQuery — pure', () => {test('interior hyphens are not operators — still relaxed', () => {expect(buildOrFallbackWebsearchQuery('alpha-beta gamma')).toBe('alpha OR beta OR gamma');});+ test('drops repeated words: a repeat adds no match and only multiplies ts_rank work (#7135)', () => {+ expect(buildOrFallbackWebsearchQuery('idle tab idle reaper')).toBe('idle OR tab OR reaper');+ expect(buildOrFallbackWebsearchQuery('Idle idle IDLE')).toBeNull();+ });test('drops literal OR/AND words so they cannot re-parse as operators', () => {expect(buildOrFallbackWebsearchQuery('alpha or beta')).toBe('alpha OR beta');expect(buildOrFallbackWebsearchQuery('alpha AND beta')).toBe('alpha OR beta');diff --git a/test/search/vector-pool.test.ts b/test/search/vector-pool.test.tsindex 8e562e5f48..c9a99f949e 100644--- a/test/search/vector-pool.test.ts+++ b/test/search/vector-pool.test.ts@@ -177,6 +177,33 @@ describe('first attempts: index walk, then scope scan', () => {expect(exhausted.attempts[0]).toMatchObject({ scopeScan: true, exact: false });});+ test('a full walk window holding fewer pages than the limit widens the walk the way the pool escalates, before any joined statement', async () => {+ // Many chunks per page: a full 100-chunk window covers 4 pages, 400 chunks cover 16.+ const attempts: VectorPoolAttempt[] = [];+ const result = await searchIndexWalk({ indexWalkSql: 'w', innerLimit: 100, indexWalkOverfetch: 2 }, 10, async attempt => {+ attempts.push(attempt);+ return { rows: rows(Math.floor(attempt.innerLimit / 25)), candidatePool: attempt.innerLimit };+ });+ expect(result).toHaveLength(16);+ expect(attempts.map(a => [a.indexWalk, a.innerLimit, a.maxScanTuples])).toEqual([[true, 100, 2000], [true, 400, 2000]]);+ });++ test('a widened walk stops at the pool escalation cap and leaves the rest to the pool', async () => {+ const attempts: number[] = [];+ const result = await searchIndexWalk({ indexWalkSql: 'w', innerLimit: 100, indexWalkOverfetch: 2 }, 10, async attempt => {+ attempts.push(attempt.innerLimit);+ return { rows: rows(2), candidatePool: attempt.innerLimit };+ });+ expect(result).toBeNull();+ expect(attempts).toEqual([100, 400, 1600, 6400]);+ const dry: number[] = [];+ expect(await searchIndexWalk({ indexWalkSql: 'w', innerLimit: 100, indexWalkOverfetch: 2 }, 10, async attempt => {+ dry.push(attempt.innerLimit);+ return { rows: rows(2), candidatePool: attempt.innerLimit === 100 ? 100 : 150 };+ })).toBeNull();+ expect(dry).toEqual([100, 400]);+ });+test('a full scan window that stale rows left short, or a timed-out attempt, falls back to the pool', async () => {expect((await run({ scopeScanSql: 's' }, { scan: { rows: rows(8), candidatePool: 100, eligiblePool: 90 } })).result).toBeNull();expect((await run({ indexWalkSql: 'w' }, { walk: { rows: rows(4), candidatePool: 40 } })).result).toBeNull();