Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): bounded keyword candidate set (50k) with keyword_candidates_incomplete, one chunk per page in the keyword pool, MCP-first guidance
garrytanadd1483ff2d6
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 7ca67e4726..aa08e90a46 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2183,7 +2183,7 @@ More: [docs/guides/troubleshooting.md#ipc-path-too-long](../../docs/guides/troub| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Hybrid search's CJK keyword arm hit its deadline or candidate cap on a large corpus, so some keyword matches can be missing. | The CJK fallback is an unindexed LIKE scan; the arm is bounded so a large brain cannot stall every hybrid search. An incomplete keyword search is not evidence of absence. | Narrow the search with --source-id (MCP source_id), or ask the user to raise search.cjk_keyword_deadline_ms. Run: gbrain config get search.cjk_keyword_deadline_ms | agent | `gbrain doctor --json` | 1 | no |+| Hybrid search's keyword arm returned a bounded result on a large corpus (the CJK arm's deadline or candidate cap, or a common-word match ranked from a sample), so some keyword matches can be missing. | The CJK fallback is an unindexed LIKE scan, and a query whose words match hundreds of thousands of chunks ranks a bounded sample of them (an OR retry also keeps only its rarer words); each bound keeps a large brain from stalling every hybrid search. An incomplete keyword search is not evidence of absence. | Add a rarer word or an exact "phrase", or narrow the search with --source-id (MCP source_id) or --types; for CJK text, ask the user to raise search.cjk_keyword_deadline_ms. Run: gbrain config get search.cjk_keyword_deadline_ms | agent | `gbrain doctor --json` | 1 | no |More: [docs/guides/multi-language-fts.md#cjk-keyword-budget](../../docs/guides/multi-language-fts.md#cjk-keyword-budget)diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md b/plugin-variants/gbrain-coding/skills/conventions/brain-first.mdindex 5cc243e58f..75d50db52e 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md@@ -13,6 +13,11 @@ frontmatter, before gbrain: gbrain reads the index across sources, ranks resultsfilters by type, date and source, and returns the slug to read next. Use thefiles only when gbrain is unreachable or for an edit not yet synced.+Prefer the gbrain MCP tools (`search`, `query`, `get_page`, `recall`) when your+harness has the server connected: it stays connected, so each call skips the+CLI's startup, which costs seconds per call on a large pooled Postgres brain.+The CLI commands below take the same filters.+```bashgbrain search "Acme Example" # names, codes, exact phrasesgbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md b/plugin-variants/gbrain-daily/skills/conventions/brain-first.mdindex 5cc243e58f..75d50db52e 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md@@ -13,6 +13,11 @@ frontmatter, before gbrain: gbrain reads the index across sources, ranks resultsfilters by type, date and source, and returns the slug to read next. Use thefiles only when gbrain is unreachable or for an edit not yet synced.+Prefer the gbrain MCP tools (`search`, `query`, `get_page`, `recall`) when your+harness has the server connected: it stays connected, so each call skips the+CLI's startup, which costs seconds per call on a large pooled Postgres brain.+The CLI commands below take the same filters.+```bashgbrain search "Acme Example" # names, codes, exact phrasesgbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)diff --git a/plugin/skills/conventions/brain-first.md b/plugin/skills/conventions/brain-first.mdindex 5cc243e58f..75d50db52e 100644--- a/plugin/skills/conventions/brain-first.md+++ b/plugin/skills/conventions/brain-first.md@@ -13,6 +13,11 @@ frontmatter, before gbrain: gbrain reads the index across sources, ranks resultsfilters by type, date and source, and returns the slug to read next. Use thefiles only when gbrain is unreachable or for an edit not yet synced.+Prefer the gbrain MCP tools (`search`, `query`, `get_page`, `recall`) when your+harness has the server connected: it stays connected, so each call skips the+CLI's startup, which costs seconds per call on a large pooled Postgres brain.+The CLI commands below take the same filters.+```bashgbrain search "Acme Example" # names, codes, exact phrasesgbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)diff --git a/scripts/bench/retrieval-scale/lexical-probe.ts b/scripts/bench/retrieval-scale/lexical-probe.tsindex 52e2f187b4..8f574331c5 100644--- a/scripts/bench/retrieval-scale/lexical-probe.ts+++ b/scripts/bench/retrieval-scale/lexical-probe.ts@@ -6,8 +6,11 @@** 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.+ * --compare-tree also runs the same call through another checkout's engine+ * (for example master) and reports how many of its result pages this tree+ * returns (top 50 and top 10) and this tree's top-10 score as a share of the+ * other's, which shows what a bounded candidate sample loses. --query adds a+ * query of your own (repeatable) after the sampled ones.*/import postgres from '#postgres';import { buildOrFallbackWebsearchQuery } from '../../../src/core/search/sql-ranking.ts';@@ -19,6 +22,7 @@ const pages = Number(flag('--pages'));const N = Number(flag('--n', '20'));const source = flag('--source', 'default')!;const compareTree = flag('--compare-tree');+const extra = argv.flatMap((a, i) => (a === '--query' ? [argv[i + 1]!] : []));const { createEngine } = await import('../../../src/core/engine-factory.ts');const engine = await createEngine({ engine: 'postgres' });@@ -28,21 +32,30 @@ 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 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);- const q = [...(i % 2 === 0 && titleWord ? [titleWord.toLowerCase()] : []), ...words.slice(at, at + k)].join(' ');- const opts = { sourceIds: [source], limit: 50 } as Record<string, unknown>;+ return [...(i % 2 === 0 && titleWord ? [titleWord.toLowerCase()] : []), ...words.slice(at, at + k)].join(' ');+}).concat(extra);+type Row = { slug: string; source_id: string; score: number };+for (const [i, q] of queries.entries()) {+ const incomplete: string[] = [];+ const opts = { sourceIds: [source], limit: 50, onKeywordIncomplete: (r: string) => incomplete.push(r) } 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 key = (r: Row) => r.source_id + ':' + r.slug;+ const mine = (orK.v ?? []) as Row[], theirs = (base?.v ?? []) as Row[];+ const basePages = new Set(theirs.map(key)), base10 = new Set(theirs.slice(0, 10).map(key));+ const overlap = base ? mine.filter(r => basePages.has(key(r))).length : null;+ const overlap10 = base ? mine.slice(0, 10).filter(r => base10.has(key(r))).length : null;+ const top10 = (rows: Row[]) => rows.slice(0, 10).reduce((a, r) => a + Number(r.score), 0);+ const score10 = base && top10(theirs) > 0 ? Math.round((100 * top10(mine)) / top10(theirs)) / 100 : 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 }));+ console.log(JSON.stringify({ i, q: i >= picks.length ? q : undefined, 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, incomplete: incomplete.length > 0, ...(base ? { base_or_ms: base.ms, base_rows: basePages.size, base_err: (base as any).err, overlap, overlap10, score10 } : {}), or_matches: (matches?.v as any)?.[0]?.n ?? null, count_ms: matches?.ms }));}await sql.end();await engine.disconnect();diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 196022ad73..8e038e50fb 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -21,9 +21,9 @@ src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is asrc/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 242 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line)src/core/pglite-engine.ts 3085 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)-src/core/postgres-engine.ts 3107 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107)+src/core/postgres-engine.ts 3111 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +4 GBRA-156: searchKeyword ranks a bounded candidate sample, keeps one chunk per page in its pool, and reports a bounded or narrowed result through onKeywordIncomplete (bound in search/keyword-chunk-match.ts, OR narrowing in search/keyword-or-narrow.ts; the statement cannot move)src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts-src/core/types.ts 2325 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts)+src/core/types.ts 2327 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +2 GBRA-156: SearchOpts.onKeywordIncomplete (interface field)src/core/minions/queue.ts 2533 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.mdindex 5cc243e58f..75d50db52e 100644--- a/skills/conventions/brain-first.md+++ b/skills/conventions/brain-first.md@@ -13,6 +13,11 @@ frontmatter, before gbrain: gbrain reads the index across sources, ranks resultsfilters by type, date and source, and returns the slug to read next. Use thefiles only when gbrain is unreachable or for an edit not yet synced.+Prefer the gbrain MCP tools (`search`, `query`, `get_page`, `recall`) when your+harness has the server connected: it stays connected, so each call skips the+CLI's startup, which costs seconds per call on a large pooled Postgres brain.+The CLI commands below take the same filters.+```bashgbrain search "Acme Example" # names, codes, exact phrasesgbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page with any term (instead of grep)diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 30b87bf006..4163dcc66f 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -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": "a207e18b0a988aee2435c001278484b7bd9a82ee93472d8f6b918e0e952c2dcc",+ "conventions/brain-first.md": "b98dc24e086a35f136f74ca4abd856949d8b282e1298a47a250b2d18f69e0927","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 601d3dc65e..3380208577 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1029,6 +1029,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.330.0', text: 'Classic `gbrain sync --full` no longer deletes pages it cannot prove were removed (#7130): when Git cannot list the history that shows their files were committed (a dangling ref fails `git log --all`), it keeps every stale page with a warning, where before it skipped the never-committed check and deleted them all. With readable history it deletes as before.' },{ since: '0.60.330.0', text: 'The autopilot purge phase and the `purge` job no longer hard-delete a page that a managed sync soft-deleted unless another live page of the same source has identical content (#7130). Each sync deletion now leaves a durable record (op_checkpoints `sync-delete-tombstone`; a tombstone from before this release is recognized by its uncompacted `managed_sync_delete` receipt, and one whose receipt was compacted is not). Held pages are reported as `sync_delete_unreviewed` in the phase\'s `purged_pages_blocked` and counted in `held`, and the phase reports warn. `gbrain pages purge-deleted` still purges them after consent: its dry run reports `sync_unreviewed` and its consent text names how many of the set are sync deletions with no live twin and that a purged page can only come back from a backup. The purge phase\'s recovery window (pages and orphan clone temp dirs), and the `purge` job\'s default, now follow `purge.retention_hours` instead of a fixed 72 hours. It can only lengthen the window (default and minimum 72, so a 72-hour restore promise always holds); `gbrain config set` refuses a smaller value.' },{ since: '0.60.330.0', text: 'New doctor check `uncommitted_sync_deletions` and explicit-only repair kind `gbrain repair uncommitted-deletions --source <id>` (#7130): on each managed source\'s owner host, doctor warns about soft-deleted pages a sync removed although Git never held their recorded file (`.gitignore` excludes it, or no commit holds it and it is not on the disk), bounded to 20,000 tombstones per source and 2,000 Git evidence reads per run. The repair previews each page (slug, recorded path, deletion time, evidence, whether a sync deleted it) with a hash; `--apply --expect <hash> --yes` restores exactly that set, each page live and database-only (detached: it forgets its recorded file and no file is written), so the next sync keeps it. Pages another writer deleted join only with `--include-ambiguous`; a sync deletion is recognized by its record or receipt for the page\'s current tombstone. A preview reads one bounded window, newest page id first, and `--after <page-id>` (named in the preview\'s `next_after` and in the doctor message) continues past it. It refuses off the owner host (`not_owner_host`) and a changed plan (`preview_changed`); without `--yes` a non-interactive run exits 3 and changes nothing. Pages already purged cannot be restored by this command; only a backup (pg_dump, or `gbrain backup create`) can bring them back. It never runs on upgrade or automatically.' },+ { since: '0.60.330.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },+ { since: '0.60.330.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },+ { since: '0.60.330.0', text: 'The title arm matches page titles only for local callers too (#7135), as it already did for remote callers: a word that appears only in a page\'s timeline no longer makes it a title hit, and its any-word retry drops repeated words, which cut a 3-5 s title arm to well under a second on a large brain.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d53a36762c..5c5fe4a60e 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -519,7 +519,7 @@ export const CODES = {docs: 'docs/guides/sync-unblock-runbook.md#decision-table',suggestion: 'Rerun the same plain gbrain sync --source <id> --no-pull; it resumes the stopped entry under a fresh request. gbrain sync status --source <id> --json shows what remains.',fix: { argv: ['gbrain', 'sync', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the cursor and the next step; read-only. A plain sync of the source resumes the stopped entry.' } },- keyword_candidates_incomplete: { class: 'unavailable', summary: "Hybrid search's CJK keyword arm hit its deadline or candidate cap on a large corpus, so some keyword matches can be missing.", why: 'The CJK fallback is an unindexed LIKE scan; the arm is bounded so a large brain cannot stall every hybrid search. An incomplete keyword search is not evidence of absence.', docs: 'docs/guides/multi-language-fts.md#cjk-keyword-budget', suggestion: 'Narrow the search with --source-id (MCP source_id), or ask the user to raise search.cjk_keyword_deadline_ms.', fix: { argv: ['gbrain', 'config', 'get', 'search.cjk_keyword_deadline_ms'], consent: [], actor: 'agent', why: 'Shows the deadline in effect (unset means 3000 ms); read-only.', requires_exclusive: false } },+ keyword_candidates_incomplete: { class: 'unavailable', summary: "Hybrid search's keyword arm returned a bounded result on a large corpus (the CJK arm's deadline or candidate cap, or a common-word match ranked from a sample), so some keyword matches can be missing.", why: 'The CJK fallback is an unindexed LIKE scan, and a query whose words match hundreds of thousands of chunks ranks a bounded sample of them (an OR retry also keeps only its rarer words); each bound keeps a large brain from stalling every hybrid search. An incomplete keyword search is not evidence of absence.', docs: 'docs/guides/multi-language-fts.md#cjk-keyword-budget', suggestion: 'Add a rarer word or an exact "phrase", or narrow the search with --source-id (MCP source_id) or --types; for CJK text, ask the user to raise search.cjk_keyword_deadline_ms.', fix: { argv: ['gbrain', 'config', 'get', 'search.cjk_keyword_deadline_ms'], consent: [], actor: 'agent', why: 'Shows the deadline in effect (unset means 3000 ms); read-only.', requires_exclusive: false } },keyword_skipped_after_timeout: { class: 'unavailable', summary: "Hybrid search's Postgres keyword arm skipped a statement that hit the keyword statement timeout within the negative-cache TTL; the search reports keyword_arm_failed with reason skipped_after_timeout and the vector arm still answers.", why: 'Running the same broad keyword statement again would hold a backend for the whole search.keyword_statement_timeout_ms and fail the same way. The skip covers that exact statement and scope only, lasts search.keyword_timeout_negative_cache_seconds (default 600, 0 turns it off) and is per serving process. A skipped keyword arm is not evidence of absence.', docs: 'docs/guides/troubleshooting.md#keyword-search-times-out-on-a-large-postgres-brain', suggestion: 'Narrow the search (source_id, types, since or until) to run keyword search now, or wait for the entry to expire; the user may raise search.keyword_statement_timeout_ms or change the TTL.', fix: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'], consent: [], actor: 'agent', why: 'Read-only: reports the keyword statement bound, the recorded keyword timeouts and skips, and whether broad terms can be ranked inside the bound.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'keyword_plan', '--json'] } } },projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex 1123e1021d..a06f81da30 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -52,7 +52,7 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidancekeyword_relaxed_carried: { why: 'keyword matching was relaxed to find anything at all', fix: null },safe_index_pending: { why: 'some pages in scope are still being safety-indexed for agent readers and are withheld until that finishes', fix: 'doctor' },vector_candidates_incomplete: { why: 'vector search hit its candidate limit or deadline, so some semantic matches can be missing', fix: null },- keyword_candidates_incomplete: { why: 'CJK keyword matching hit its deadline or its candidate cap on a large corpus, so some keyword matches can be missing; narrow the search with source_id (the CLI source-id flag), or ask the user to raise search.cjk_keyword_deadline_ms (milliseconds, default 3000)', fix: null },+ keyword_candidates_incomplete: { why: 'keyword matching returned a bounded result on a large corpus (the CJK deadline or candidate cap, or common words ranked from a sample), so some keyword matches can be missing; add a rarer word or an exact phrase, narrow with source_id (the CLI source-id flag) or types, or for CJK text ask the user to raise search.cjk_keyword_deadline_ms (milliseconds, default 3000)', fix: null },projection_pending: { why: 'recently written pages are not in the search index yet', fix: 'doctor' },projection_by_design: { why: 'some image pages in scope hold protected OCR content and stay out of the search index by design; nothing is pending', fix: null },projection_status_unknown: { why: 'whether recent writes are in the search index could not be checked', fix: 'doctor' },diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 066d197824..86a21b8d93 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1486,7 +1486,7 @@ export class PGLiteEngine implements BrainEngine {const keywordSql =`WITH ranked AS (- SELECT+ SELECT * FROM (SELECT *, row_number() OVER (PARTITION BY page_id ORDER BY score DESC, chunk_id ASC) AS page_rank FROM (SELECTp.slug, p.id as page_id, p.title, p.type, p.source_id,p.effective_date, p.effective_date_source,CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL@@ -1505,7 +1505,7 @@ export class PGLiteEngine implements BrainEngine {-- v0.27.1: hide image rows from default text-keyword search so-- OCR text doesn't drown text-page hits. Image-similarity queries-- run a separate vector path on embedding_image.- AND cc.modality = 'text'+ AND cc.modality = 'text') matched) per_page WHERE page_rank = 1ORDER BY score DESC, page_id ASC, chunk_id ASCLIMIT $2),diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 5fe8a6cb58..5c6be409d6 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -116,7 +116,7 @@ import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowTimport { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';import { narrowedOrFallbackQuery } from './search/keyword-or-narrow.ts';-import { buildKeywordChunkMatch } from './search/keyword-chunk-match.ts';+import { buildKeywordChunkMatch, KEYWORD_RANK_CANDIDATES } 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';import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';@@ -1102,7 +1102,7 @@ export class PostgresEngine implements BrainEngine {const chunk = buildKeywordChunkMatch(ftsLang, opts?.excludePrivate);const rawQuery = `WITH ranked_chunks AS (- SELECT+ SELECT * FROM (SELECT *, count(*) OVER () AS bounded_rows, row_number() OVER (PARTITION BY page_id ORDER BY score DESC, chunk_id ASC) AS page_rank FROM (SELECTp.slug, p.id as page_id, p.title, p.type, p.source_id,p.effective_date, p.effective_date_source,CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL@@ -1127,6 +1127,7 @@ export class PostgresEngine implements BrainEngine {${hardExcludeClause}${visibilityClause}${chunk.modality}+ LIMIT ${KEYWORD_RANK_CANDIDATES}) bounded) per_page WHERE page_rank = 1ORDER BY score DESC, page_id ASC, chunk_id ASCLIMIT ${innerLimitParam}),@@ -1134,7 +1135,7 @@ export class PostgresEngine implements BrainEngine {SELECT slug, page_id, title, type, source_id,effective_date, effective_date_source,message_id, thread_id, source_subject,- chunk_id, chunk_index, chunk_text, chunk_source, score,+ chunk_id, chunk_index, chunk_text, chunk_source, score, bounded_rows,false AS staleFROM best_per_pageORDER BY score DESC, page_id ASC, chunk_id ASC@@ -1168,13 +1169,16 @@ export class PostgresEngine implements BrainEngine {if (rows.length === 0 && opts?.orFallback) {const orQuery = buildOrFallbackWebsearchQuery(query);if (orQuery) {- rows = await runKeyword(await narrowedOrFallbackQuery((sql, p) => this.executeRaw(sql, p), query, ftsLang) ?? orQuery, true, orQuery);+ const narrowed = await narrowedOrFallbackQuery((sql, p) => this.executeRaw(sql, p), query, ftsLang);+ rows = await runKeyword(narrowed ?? orQuery, true, orQuery);+ if (narrowed || Number(rows[0]?.bounded_rows) >= KEYWORD_RANK_CANDIDATES) opts?.onKeywordIncomplete?.('candidate_budget');// 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).return rows.map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));}}+ if (Number(rows[0]?.bounded_rows) >= KEYWORD_RANK_CANDIDATES) opts?.onKeywordIncomplete?.('candidate_budget');return rows.map(rowToSearchResult);}diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.tsindex 2505f3eba3..392174900c 100644--- a/src/core/search/hybrid/request.ts+++ b/src/core/search/hybrid/request.ts@@ -287,6 +287,7 @@ export async function resolveHybridRequest(// Direct searchKeyword consumers (countMentions, link-extraction, eval)// do NOT set this. Knob: search.keywordOrFallback (rationale: ModeBundle).orFallback: resolvedMode.keywordOrFallback,+ onKeywordIncomplete: (reason) => pushDegraded(degraded, 'keyword_candidates_incomplete', reason),// v0.46.15: collect searchVector's bounded-escalation exhaustion signal —// engines have no telemetry sink (R2-10); hybrid owns the meta emit.// ACCUMULATES across vector calls (adversarial F8): expansion runs Ndiff --git a/src/core/search/keyword-chunk-match.ts b/src/core/search/keyword-chunk-match.tsindex 162c0ff7fe..596c3d9851 100644--- a/src/core/search/keyword-chunk-match.ts+++ b/src/core/search/keyword-chunk-match.ts@@ -16,6 +16,19 @@** `ftsLang` must already be validated (getFtsLanguage); `$1` is the websearch text.*/+/**+ * Most matching chunks the Postgres keyword statement ranks (GBRA-156).+ * ts_rank runs on every row it is given, so a query whose terms match+ * hundreds of thousands of chunks (one common word on a 2M-chunk brain)+ * spent 3-8 s ranking and ran into the keyword statement timeout, which+ * returns no rows at all. The statement takes the first matching chunks+ * that pass its filters, up to this bound, and ranks those; a match set under+ * the bound ranks exactly as before. When the bound applies the caller is+ * told (SearchOpts.onKeywordIncomplete), and hybrid reports+ * `keyword_candidates_incomplete`, because the rows come from a sample.+ */+export const KEYWORD_RANK_CANDIDATES = 50_000;+export function buildKeywordChunkMatch(ftsLang: string, excludePrivate: boolean | undefined): { from: string; match: string; modality: string } {const tsq = `websearch_to_tsquery('${ftsLang}', $1)`;if (!excludePrivate) return { from: 'content_chunks cc', match: `cc.search_vector @@ ${tsq}`, modality: `AND cc.modality = 'text'` };diff --git a/src/core/types.ts b/src/core/types.tsindex 7ccf11683d..b166da7d87 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1235,6 +1235,8 @@ export interface SearchOpts extends PageReadPolicy {hnswIterativeScan?: import('./search/hnsw-iterative-scan.ts').HnswIterativeScanMode;/** #5989: bounded CJK keyword arm (deadline + meta sink); set by hybrid only (engine-sql/cjk-search.ts). */cjkKeyword?: import('./engine-sql/cjk-search.ts').CjkKeywordRun;+ /** GBRA-156: the Postgres keyword arm ranked a bounded sample of its matches, or its OR retry dropped common terms (search/keyword-chunk-match.ts, search/keyword-or-narrow.ts). */+ onKeywordIncomplete?: (reason: 'candidate_budget') => void;/*** v0.42 — intent-aware adaptive return-sizing. `true` enables with config/* default caps; an object overrides caps per-call; omitted/`false` = offdiff --git a/test/e2e/keyword-or-narrow-postgres.test.ts b/test/e2e/keyword-or-narrow-postgres.test.tsindex c622fca065..fac1dc9340 100644--- a/test/e2e/keyword-or-narrow-postgres.test.ts+++ b/test/e2e/keyword-or-narrow-postgres.test.ts@@ -11,6 +11,7 @@ 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';+import { KEYWORD_RANK_CANDIDATES } from '../../src/core/search/keyword-chunk-match.ts';const run = process.env.DATABASE_URL ? describe : describe.skip;let engine: BrainEngine;@@ -45,6 +46,35 @@ run('keyword OR fallback narrowing on Postgres', () => {expect(narrowOrFallbackTokens(tokens, Number(rows[0].rows))).toBeNull();});+ test('a page with hundreds of matching chunks does not crowd the only other match out of the pool', async () => {+ await seedPage(engine, 'notes/crowd-log', 'The crowdlex log. Each entry below cites the crowdlex survey.');+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, modality)+ SELECT cc.page_id, cc.chunk_index + g, cc.chunk_text || ' entry ' || g, cc.chunk_source, cc.modality+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id, generate_series(1, 299) g+ WHERE p.slug = 'notes/crowd-log' AND cc.chunk_index = 0`);+ await seedPage(engine, 'notes/solitar-field', 'Field notes on the solitar deposit.');+ const rows = await engine.searchKeyword('crowdlex OR solitar', { limit: 10 });+ expect(rows.map(r => r.slug).sort()).toEqual(['notes/crowd-log', 'notes/solitar-field']);+ });++ test('a match set over KEYWORD_RANK_CANDIDATES ranks a bounded sample and says so', async () => {+ await seedPage(engine, 'notes/plentix-log', 'The plentix log. Each entry below cites the plentix survey.');+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, modality)+ SELECT cc.page_id, cc.chunk_index + g, cc.chunk_text || ' entry ' || g, cc.chunk_source, cc.modality+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id, generate_series(1, $1::int) g+ WHERE p.slug = 'notes/plentix-log' AND cc.chunk_index = 0`, [KEYWORD_RANK_CANDIDATES]);+ const bounded: string[] = [];+ const rows = await engine.searchKeyword('plentix', { limit: 10, onKeywordIncomplete: reason => bounded.push(reason) });+ expect(rows.map(r => r.slug)).toEqual(['notes/plentix-log']);+ expect(bounded).toEqual(['candidate_budget']);++ const exact: string[] = [];+ expect((await engine.searchKeyword('nebulith', { limit: 10, onKeywordIncomplete: reason => exact.push(reason) })).length).toBe(1);+ expect(exact).toEqual([]);+ }, 300_000);+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 });diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex de6eb6e6a5..01a46d28b3 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -1437,6 +1437,7 @@"minTrust?: \"user_confirmed\" | \"operator_curated\" | \"tool_observed\" | \"agent_written\" | \"unknown\" | \"external_untrusted\" | undefined","nearSymbol?: string | undefined","offset?: number | undefined",+ "onKeywordIncomplete?: ((reason: \"candidate_budget\") => void) | undefined","onVectorPoolMeta?: ((m: VectorPoolMeta) => void) | undefined","orFallback?: boolean | undefined","rankQuery?: string | undefined",@@ -7904,6 +7905,7 @@"mode?: string | undefined","nearSymbol?: string | undefined","offset?: number | undefined",+ "onKeywordIncomplete?: ((reason: \"candidate_budget\") => void) | undefined","onMeta?: ((meta: HybridSearchMeta) => void) | undefined","onQueryEmbedding?: ((embedding: Float32Array) => void) | undefined","onRelationalMeta?: ((meta: RelationalArmMeta) => void) | undefined",@@ -9441,6 +9443,7 @@"minTrust?: \"user_confirmed\" | \"operator_curated\" | \"tool_observed\" | \"agent_written\" | \"unknown\" | \"external_untrusted\" | undefined","nearSymbol?: string | undefined","offset?: number | undefined",+ "onKeywordIncomplete?: ((reason: \"candidate_budget\") => void) | undefined","onVectorPoolMeta?: ((m: VectorPoolMeta) => void) | undefined","orFallback?: boolean | undefined","rankQuery?: string | undefined",diff --git a/test/search/keyword-pool-per-page.test.ts b/test/search/keyword-pool-per-page.test.tsnew file mode 100644index 0000000000..51d8dc1945--- /dev/null+++ b/test/search/keyword-pool-per-page.test.ts@@ -0,0 +1,35 @@+/**+ * GBRA-156: the keyword arm's chunk pool (the inner LIMIT before the+ * best-chunk-per-page collapse) keeps one chunk per page, so a page with+ * hundreds of matching chunks cannot push every other matching page out of+ * the arm. Before, a page with 300 matching chunks filled a limit-10 pool and+ * the only other matching page was lost. PGLite here; the Postgres arm runs+ * in test/e2e/keyword-or-narrow-postgres.test.ts.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { seedPage } from '../helpers/keyword-paging-fixture.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await seedPage(engine, 'notes/quasar-log', 'The quasar log. Each entry below cites the quasar survey.');+ await engine.executeRaw(+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, modality)+ SELECT cc.page_id, cc.chunk_index + g, cc.chunk_text || ' entry ' || g, cc.chunk_source, cc.modality+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id, generate_series(1, 299) g+ WHERE p.slug = 'notes/quasar-log' AND cc.chunk_index = 0`);+ await seedPage(engine, 'notes/nebulith-field', 'Field notes on the nebulith deposit.');+}, 120_000);++afterAll(async () => { await engine.disconnect(); });++test('a page with hundreds of matching chunks does not crowd the only other match out of the pool', async () => {+ const relaxed = await engine.searchKeyword('quasar nebulith zzqxv', { limit: 10, orFallback: true });+ expect(relaxed.map(r => r.slug).sort()).toEqual(['notes/nebulith-field', 'notes/quasar-log']);+ const strict = await engine.searchKeyword('quasar OR nebulith', { limit: 10 });+ expect(strict.map(r => r.slug).sort()).toEqual(['notes/nebulith-field', 'notes/quasar-log']);+});