Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge remote-tracking branch 'origin/master' into capy/v0601310-fixsearch-scoped-vector
garrytanc71ac5ded1b5
diff --cc docs/architecture/key-files/core-search-2.mdindex f05d1c052e,776f667136..e167064fb0--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@@ -22,9 -22,9 +22,9 @@@ Current behavior and load-bearing invar- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.- - `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Every pooled attempt scans with `hnsw.max_scan_tuples` = `POOL_MAX_SCAN_TUPLES` (20,000, pgvector's default), so a filtered attempt fills its candidate window before it is accepted; the index walk keeps 2,000 because it accepts only a full window. Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `withVectorSettings(..., iterativeMode, indexWalk)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit; otherwise (or past its 2 s budget) both engines run the pool unchanged.-- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `withVectorSettings(..., iterativeMode, walkOverfetch)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `walkOverfetch` (the statement's `indexWalkOverfetch`, index walk only) adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk, then its scope scan (each when present), before the pool: walk rows answer 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; otherwise (or past an attempt's 2 s budget) both engines run the pool unchanged. The walk's `hnsw.max_scan_tuples` covers its whole over-fetched window.++- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Every pooled attempt scans with `hnsw.max_scan_tuples` = `POOL_MAX_SCAN_TUPLES` (20,000, pgvector's default), so a filtered attempt fills its candidate window before it is accepted; the index walk and scope scan keep their own window-sized budget (`searchIndexWalk`). Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `withVectorSettings(..., iterativeMode, indexWalk)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` and sizes `ef_search` for the over-fetched window. `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit; otherwise (or past its 2 s budget) both engines run the pool unchanged.- - `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql? }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. `indexWalkSql` (relaxed variant without a type or date filter, same parameters) is the statement both engines run first: `ann` orders `content_chunks` alone with the chunk-level filters over twice the window, then pages and sources are joined by key and every page filter, visibility and the private-page rule apply to those rows, keeping the nearest `innerLimit`. Run with `enable_sort = off` (`INDEX_WALK_SETTINGS`) the HNSW scan is its only ordered path; the joined statement's plan sat on a cost knife edge (TOASTed vectors cost a sequential scan too little, the HNSW estimate grows with `ef_search`, the private-page rule's subplans priced every page lookup high) and flipped to a full scan and sort at a 50-row limit or on any remote read. A full walk window selects the same rows as the joined statement (`test/search/vector-index-walk.test.ts`); a short one falls back to it. A source scope whose share of pages (`pages.source_id` planner statistics, `PAGE_SOURCE_STATS_SQL`, read by each engine's `vectorScopeShareLoader` at most once a minute) is below `INDEX_WALK_MIN_SCOPE_SHARE` (0.1) skips the walk like a type or date filter, because the nearest chunks overall never fill its window; the input `scopeShare` only removes `indexWalkSql`, every other statement stays byte-identical, and missing statistics leave the walk on. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.+ - `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql?, indexWalkOverfetch, scopeScanSql? }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. `indexWalkSql` (relaxed variant without a type or date filter, same parameters) is the statement both engines run first: `ann` orders `content_chunks` alone with the chunk-level filters over twice the window, then pages and sources are joined by key and every page filter, visibility and the private-page rule apply to those rows, keeping the nearest `innerLimit`. Run with `enable_sort = off` (`INDEX_WALK_SETTINGS`) the HNSW scan is its only ordered path; the joined statement's plan sat on a cost knife edge (TOASTed vectors cost a sequential scan too little, the HNSW estimate grows with `ef_search`, the private-page rule's subplans priced every page lookup high) and flipped to a full scan and sort at a 50-row limit or on any remote read. A full walk window selects the same rows as the joined statement (`test/search/vector-index-walk.test.ts`); a short one falls back to it. Source scopes: each engine's `vectorScopeLoader` reads `PAGE_SOURCE_STATS_SQL` (`pages.source_id` planner statistics plus `content_chunks` reltuples) at most once a minute, only for source-scoped searches, and passes `scope` (`share`, and `chunks` = share times chunk reltuples). The walk over-fetches `indexWalkOverfetch(share)` = ceil(2 / share) rows per window slot (2 unscoped or for a whole-brain scope, so that statement is byte-identical), and a share below `INDEX_WALK_MIN_SCOPE_SHARE` (0.04) skips it. `scopeScanSql` (relaxed variant, same parameters) serves a scope under `SCOPE_SCAN_MAX_SHARE` (0.3) of pages with at most `SCOPE_SCAN_MAX_CHUNKS` (60k) estimated chunks: an exact distance scan over the scope's chunks, page filters and visibility applied once per page inside `cc.page_id = ANY(ARRAY(...))` so chunks are always reached through `idx_chunks_page` (an inline join flipped to a sequential scan with the private-page rule), ordering only chunk ids with `(distance) + 0` to keep the index out, then the window joins back for its columns. Up to `SCOPE_SCAN_FIRST_MAX_CHUNKS` (25k) it replaces the walk; above that the walk runs first and the scan answers when the walk comes back short (a scope clustered away from the query). It returns the joined statement's rows (`test/search/vector-index-walk.test.ts`); recall across share buckets on 1024-dim vectors is pinned by `test/e2e/vector-scope-recall-postgres.test.ts`. Missing statistics leave only the unscoped walk and the joined statement. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.diff --cc src/core/behavior-change-notice.tsindex d1c572aee7,acd25034b5..a3f5e35a6c--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -350,9 -350,7 +350,10 @@@ export const BEHAVIOR_CHANGES: Readonly// Budgeted delivery PR 1. `since` equals the branch's VERSION; the integrator sets it to the merge-slot stamp by hand (release:restamp does not rewrite this table).{ since: '0.60.124.0', text: 'A token budget passed under `auto` evidence delivery (`token_budget` on query, search and assemble_evidence, `budget_tokens` on recall with `return_unit: "auto"`) is now a hard cap on the delivered titles and evidence: the best hit comes first, and conversations or notes that do not fit are listed in `delivery.dropped_reasons` instead of being appended as extra chunks. A budget below 32 tokens is refused with `invalid_params`. Calls without a budget, and a bare query `token_budget` (legacy chunk budgeting), are unchanged. `gbrain config set search.auto_packing off` restores the uncapped behavior.' },{ since: '0.60.126.0', text: '`context_pack` cards now list the newest pages that mention each entity and are dated after the entity\'s own page (up to 8 per card, 2,000 characters per card and 6,000 per pack, each with its date, slug, title and preview), so a later mail or note that corrects the page reaches the agent on its first call. A remote caller never sees a private page or another source there, and the section packs last under `budget_tokens`. `gbrain config set mentions.newer_on_cards false` turns it off.' },+ { since: '0.60.131.0', text: 'Vector search scoped to a source that holds a small part of the brain now returns its true nearest chunks: a source with up to about 25,000 chunks is scanned exactly instead of through the HNSW index, and a larger one falls back to that scan when the index comes back short. Unscoped search is unchanged; scoped results can differ from earlier releases where the index had missed closer matches.' },+ // E5.4 HNSW scale wave (GBRA-60); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.130.0', text: 'Vector search under a source or visibility scope now scans up to 20,000 index entries before it settles (it stopped at 2,000), so a scope covering a tenth of a large brain returns its true nearest pages instead of the first few hundred it reached: on 1M chunks with real embeddings and a random 10% scope, recall@50 rose from 0.77 to 0.97, for about 15 to 35 ms more per scoped search on 1M to 2M chunks. Unscoped search returns the same results.' },+ { since: '0.60.130.0', text: 'On Postgres, import, sync, reindex and every embed drain that embedded something now finish with a bounded ANALYZE (30 s statement, 2 s lock timeout) of `content_chunks(model, modality, page_id)` and the page columns search filters read. Without those statistics, vector search on a freshly loaded brain of 1M chunks or more sorted every candidate, hit its 8 s budget and fell back to keyword-only results (`vector_candidates_incomplete`) until autovacuum ran.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/postgres-engine.tsindex e795a20a93,fa1df50ee4..0bb2a299fc--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@@ -64,8 -64,8 +64,8 @@@ import { sanitizeForJsonb, sanitizeTextimport { SCHEMA_SQL } from './schema-embedded.generated.ts';import { verifySchema } from './schema-verify.ts';import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';-import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt } from './search/vector-pool.ts';+import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt, POOL_MAX_SCAN_TUPLES } from './search/vector-pool.ts';- import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeShareLoader, type PageSourceStats, type VectorSearchStatement } from './search/vector-statement.ts';+ import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type VectorSearchStatement } from './search/vector-statement.ts';import { withVectorSettings } from './search/vector-settings.ts';import {vectorCastSuffix,@@@ -1354,9 -1354,9 +1354,9 @@@ export class PostgresEngine implements*/async explainVectorSearch(embedding: Float32Array, opts?: SearchOpts): Promise<Record<string, unknown>> {const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());- const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scopeShare: await this.vectorScopeShare(opts) });+ const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts, scope: await this.vectorScope(opts) });const iterative = await this.vectorIterativeScanSupported();- const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: stmt.indexWalkSql ? 2_000 : POOL_MAX_SCAN_TUPLES, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql };- const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch), remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql, scopeScan: !stmt.indexWalkSql && !!stmt.scopeScanSql };++ const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: stmt.indexWalkSql || stmt.scopeScanSql ? Math.max(2_000, stmt.innerLimit * stmt.indexWalkOverfetch) : POOL_MAX_SCAN_TUPLES, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql, scopeScan: !stmt.indexWalkSql && !!stmt.scopeScanSql };const [row] = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));const plan = row?.['QUERY PLAN'];return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;diff --cc src/core/search/vector-pool.tsindex e7f8375f77,f7e2582b89..ed294f22b5--- a/src/core/search/vector-pool.ts+++ b/src/core/search/vector-pool.ts@@@ -29,31 -34,25 +34,40 @@@ export async function searchIndexWalklimit: number,run: (attempt: VectorPoolAttempt) => Promise<VectorPoolBatch>,): Promise<Record<string, unknown>[] | null> {- if (!stmt.indexWalkSql) return null;- try {- const batch = await run({ innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 2_000, exact: false, indexWalk: true });- return batch.candidatePool >= stmt.innerLimit && batch.rows.length >= limit ? batch.rows : null;- } catch (error) {- if ((error as { code?: string }).code === '57014') return null;- throw error;+ const attempt = async (kind: { indexWalk: true } | { scopeScan: true }) => {+ try {+ return await run({ innerLimit: stmt.innerLimit, maxScanTuples: Math.max(2_000, stmt.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;}+ if (stmt.scopeScanSql) {+ const batch = await attempt({ scopeScan: true });+ if (batch && (batch.rows.length >= limit || batch.candidatePool < stmt.innerLimit)) return batch.rows;+ }+ return null;}+/**+ * `hnsw.max_scan_tuples` for every pooled attempt: pgvector's own default.+ * A filtered pooled attempt asks for `innerLimit` eligible chunks and is+ * accepted once they cover `limit` pages, so its scan budget decides how far+ * it can reach. At 2,000 tuples a 10% source or visibility filter found about+ * 200 eligible chunks: enough pages to be accepted, too shallow to hold the+ * true neighbours. At 20,000 the window fills down to about 1% selectivity+ * at limit 50: 10%-filter recall@50 rose from 0.52-0.63 to 0.96-0.99 on 1M and+ * 2M synthetic chunks and from 0.77 to 0.97 on 1M voyage-4 chunks under a+ * random filter, for 16 to 36 ms more p50 (docs/eval/hnsw-scale-bench.md).+ * An unfiltered scan stops at its LIMIT long before either budget, so only+ * filtered searches pay for the deeper visit.+ */+export const POOL_MAX_SCAN_TUPLES = 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' });diff --cc test/search/vector-pool.test.tsindex 1b47738e4b,c33fb5ec6f..8e562e5f48--- a/test/search/vector-pool.test.ts+++ b/test/search/vector-pool.test.ts@@@ -1,5 -1,5 +1,5 @@@import { describe, expect, test } from 'bun:test';- import { POOL_MAX_SCAN_TUPLES, readVectorPool, searchVectorPool, type VectorPoolAttempt } from '../../src/core/search/vector-pool.ts';-import { readVectorPool, searchIndexWalk, searchVectorPool, type VectorPoolAttempt, type VectorPoolBatch } from '../../src/core/search/vector-pool.ts';++import { POOL_MAX_SCAN_TUPLES, readVectorPool, searchIndexWalk, searchVectorPool, type VectorPoolAttempt, type VectorPoolBatch } from '../../src/core/search/vector-pool.ts';import { supportsHnswIterativeScan } from '../../src/core/vector-index.ts';import type { SearchOpts } from '../../src/core/types.ts';