Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): CJK keyword OR fallback and a bounded CJK keyword arm (#6043, #5989)

garrytan39a75f2157a8
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 8186250ad0..205c20573f 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -30,6 +30,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/hnsw-iterative-scan.ts` — the pgvector `hnsw.iterative_scan` mode for filtered vector search (#6132 idea): `relaxed_order` by default, `strict_order` or `off` through `GBRAIN_HNSW_ITERATIVE_SCAN` (wins) or `search.hnsw_iterative_scan` (file > DB via loadConfigWithEngine). `resolveHnswIterativeScan(cfg)` latches once per process (hybrid `request.ts` passes it as `SearchOpts.hnswIterativeScan`; engines hand it to `withVectorSettings`), logging once when an override is active. `hnswIterativeScanValueProblem` backs the `config set` refusal through `search/config-values.ts` (`searchConfigValueRefusal`: enum/range rules for `search.*` keys, exit 2 `invalid_params`, nothing written). Pinned by `test/search/hnsw-iterative-scan.test.ts` and the Postgres recall fixture `test/e2e/hnsw-iterative-scan-recall-postgres.test.ts`; bench `scripts/bench/hnsw-iterative-scan.ts`.
+- `src/core/search/cjk-keyword-sql.ts` + `src/core/engine-sql/cjk-search.ts` + `src/core/search/cjk-keyword-deadline.ts` — the CJK keyword fallback shared by both engines. `buildCJKKeywordSql(query, ctx, variant)` keeps today's strict-AND SQL byte-identical by default; `match: 'any'` (the OR fallback, #6043) qualifies a chunk on any term and orders by matched-term count, then the TF score (the count enters the score as 1000 x matched outside the source factor, so a boosted partial match never outranks an all-term chunk); `candidateIds` scores only a candidate set by joining `unnest($n::bigint[])` to `content_chunks` (an `= ANY` filter was a sequential scan). `buildCJKCandidateSql` is the unordered capped LIKE scan for ids (all-term, or any-term excluding ids already taken). `searchKeywordCJK(scoped, query, ctx, engine)` runs strict AND and, with `opts.orFallback` and 2+ terms, the OR pass only when strict AND returns fewer than `limit` rows; with `opts.cjkKeyword` (hybrid only, deadline from `search.cjk_keyword_deadline_ms`, integer ms 500..30000, default 3000) it bounds the arm: Postgres runs full scoring in its own scoped read transaction within 2/3 of the deadline (counted from before the pool wait; every statement of an attempt gets `statement_timeout` = what is left of that attempt, minus a 40 ms rollback margin), and on SQLSTATE 57014 a capped retry (`CJK_CANDIDATE_CAP` = 2000; all-term ids first, partial ids only when the all-term rows fall short) in a fresh scoped transaction with the remaining third (a fresh transaction, not a savepoint, because the driver rethrows any failed statement at the end of its transaction scope); PGLite runs the capped stage whenever `pg_class.reltuples` exceeds `PGLITE_CJK_CAPPED_CHUNKS` = 50,000. `onMeta` gets `{ incomplete, reason, capped, arm_ms }`; hybrid `request.ts` turns `incomplete` into degraded `keyword_candidates_incomplete` and `emitHybridMeta` adds `keyword_candidates` (keyword-arm wall time, separate from total hybrid latency) to every return path's meta. Pinned by `test/cjk-keyword-fallback.test.ts`, `test/e2e/cjk-keyword-deadline-postgres.test.ts` and `test/cjk-keyword-sql.test.ts`; bench `scripts/bench/cjk-keyword-deadline.ts`.
+
- `src/core/search/internal-breadth.ts` — `INTERNAL_BREADTH_SEARCH_OPTS` (`autocut: false, adaptiveReturn: false`), the one option object internal callers spread into `hybridSearch` when they need the full ranked set rather than a reader-trimmed one (#5890): think gather (both legs), brainstorm close-set, grade-takes evidence, whoknows and enrich. Pinned by `test/internal-breadth-callers.serial.test.ts`; `eval-contradictions/runner.ts` still inherits both trims.
- `src/core/temporal-grammar.ts` + `src/core/search/time-range.ts` + `src/core/event-dates.ts` + `src/core/search/hybrid/time-scope.ts` — deterministic time expressions (no LLM). `findTimeMentions(text, refDay, direction)` resolves explicit cues only (ISO and written dates, `in/during <Month>`, capitalized bare months, `Qn YYYY`, `in YYYY`, yesterday/today/tomorrow, last/this/next week|weekend|month|year, rolling "past month", seasons, last/this <weekday>, `N units ago`, `in N units`) to inclusive day ranges; quoted spans, plural weekdays and modal "may" never resolve; overlapping matches keep the longest. `parseQueryTimeRange(query, refDay)` returns one range or abstains with `no_cue`, `duration_question` ("how long", "how many days ago/passed/before…") or `multi_role` (two times not joined by and/or/to/through). `extractEventDates(text, observationDay)` returns the observation day plus mentioned dates, resolving relative phrases only against a known observation day and skipping code fences, inline code and URLs. `applyTimeScope(results, range, datesOf, {mode, k, slackDays=2})` is a permutation: `reserved` keeps the top ⌈k/2⌉ in place and fills the rest of k with in-range results; `partition` moves every in-range result first. These are used by the eval-only `--time-scope` arm; no production search path calls them yet. Tests: `test/time-range-parse.test.ts` (published LongMemEval time-range examples as goldens), `test/time-scope-stage.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index b6d2a9f1f5..b8058b1b33 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1424,6 +1424,16 @@ More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guid
|---|---|---|---|---|---|---|
| Invalid write wait. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+### keyword_candidates_incomplete
+
+<a id="keyword_candidates_incomplete"></a>
+
+| 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 |
+
+More: [docs/guides/multi-language-fts.md#cjk-keyword-budget](../../docs/guides/multi-language-fts.md#cjk-keyword-budget)
+
### legacy_job_selection_invalid
<a id="legacy_job_selection_invalid"></a>
diff --git a/docs/guides/multi-language-fts.md b/docs/guides/multi-language-fts.md
index b0106bbad4..a07defa843 100644
--- a/docs/guides/multi-language-fts.md
+++ b/docs/guides/multi-language-fts.md
@@ -130,3 +130,21 @@ command runs, or Postgres will reject the trigger recreation with
a CJK-aware extension (`pgroonga` / `zhparser`) installed. Wiring a
CJK-capable `GBRAIN_FTS_LANGUAGE` config past the fallback is a filed
follow-up.
+ <a id="cjk-keyword-budget"></a>In hybrid search the fallback keeps every term required first and, when
+ that finds fewer rows than requested, matches any term, ranking chunks by
+ how many terms they contain and then by term frequency (so `席位 升级`
+ finds pages that mention either word). Results are unchanged whenever the
+ all-terms match already fills the request. Direct keyword reads stay
+ all-terms. The hybrid keyword arm also has one time budget,
+ `search.cjk_keyword_deadline_ms` (integer milliseconds, default 3000,
+ range 500 to 30000; `gbrain config set search.cjk_keyword_deadline_ms
+ 5000`). On Postgres the normal scoring gets two thirds of it; if that
+ times out, a capped retry scores at most 2,000 matching chunks (all-terms
+ matches before partial ones) in the remaining third. On PGLite, which
+ cannot interrupt a running query, a brain past 50,000 chunks always uses
+ the capped stage. When the cap or the budget cut the candidates, the search
+ reports the degraded stage `keyword_candidates_incomplete`: an incomplete
+ keyword search is not evidence that the brain has nothing, and the next
+ step is to narrow with `--source-id` (MCP `source_id`) or raise the
+ deadline. The vector arm still runs either way. Ranking quality among the
+ capped candidates has not been measured against relevance judgments.
diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.md
index 847dcdb790..58d3a5d9d8 100644
--- a/docs/guides/search-modes.md
+++ b/docs/guides/search-modes.md
@@ -143,6 +143,13 @@ Seven of the knobs deserve a sentence:
to OR when strict AND matching finds nothing, so a multi-word query still
gets keyword recall instead of leaning on vectors alone. Set the config
key to `false` to keep strict AND matching.
+- **`cjk_keyword_deadline_ms`** (config key `search.cjk_keyword_deadline_ms`,
+ integer milliseconds, default 3000, range 500 to 30000; for example
+ `gbrain config set search.cjk_keyword_deadline_ms 5000`) is the total time
+ budget of hybrid search's CJK keyword arm, split between full scoring and
+ one capped retry (see [multi-language FTS](multi-language-fts.md)). A cut
+ arm reports `keyword_candidates_incomplete`; another value is refused
+ with exit 2.
- **`hnsw_iterative_scan`** (Postgres with pgvector 0.8+; config key
`search.hnsw_iterative_scan`, string, default `relaxed_order`, one of
`relaxed_order | strict_order | off`; env `GBRAIN_HNSW_ITERATIVE_SCAN`
diff --git a/scripts/bench/cjk-keyword-deadline.ts b/scripts/bench/cjk-keyword-deadline.ts
new file mode 100644
index 0000000000..30a057d240
--- /dev/null
+++ b/scripts/bench/cjk-keyword-deadline.ts
@@ -0,0 +1,92 @@
+#!/usr/bin/env bun
+/**
+ * #5989 / #6043 bench: the CJK keyword arm on a large Korean Postgres corpus,
+ * today's path (strict AND under the engine's 8 s statement timeout) against
+ * the hybrid path (OR fallback + one total deadline with a capped retry).
+ * Opt-in, never run in CI, not shipped in the CLI. No network.
+ *
+ * DATABASE_URL=postgresql://postgres:postgres@localhost:5434/gbrain_test \
+ * bun scripts/bench/cjk-keyword-deadline.ts [--pages 50000] [--deadline 3000] [--runs 3] [--keep]
+ *
+ * Creates `gbrain_bench_cjk_<hex>` on the DATABASE_URL server, seeds
+ * `--pages` pages x 8 chunks of ~530-character Korean text drawn from a
+ * fixed vocabulary in which the 2-term query's words are common (about 90%
+ * of chunks match both), so the 2-term query matches most of the table and
+ * the 5- and 7-term particle-bearing queries match nothing, like the
+ * reporter's brain. Reports wall time, rows and the arm outcome per query
+ * and path (median of `--runs`). Ranking quality among capped candidates is
+ * not measured (no relevance judgments). Drops the database unless --keep.
+ */
+import { randomBytes } from 'node:crypto';
+import postgres from '#postgres';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import type { CjkKeywordMeta } from '../../src/core/engine-sql/cjk-search.ts';
+
+function flag(name: string, fallback: number): number {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 ? Number(process.argv[i + 1]) : fallback;
+}
+const PAGES = flag('pages', 50_000);
+const DEADLINE = flag('deadline', 3000);
+const RUNS = flag('runs', 3);
+const KEEP = process.argv.includes('--keep');
+const QUERIES = ['좌석 업그레이드', '팀 좌석을 업그레이드하는 방법은 무엇인가요?', '관리자 계정의 비밀번호를 변경하려면 어떻게 해야 하나요'];
+const adminUrl = process.env.DATABASE_URL;
+if (!adminUrl) throw new Error('Set DATABASE_URL to a Postgres server where this role may CREATE DATABASE.');
+const log = (m: string) => console.error(`[bench ${new Date().toISOString().slice(11, 19)}] ${m}`);
+
+const dbName = `gbrain_bench_cjk_${randomBytes(6).toString('hex')}`;
+const admin = postgres(adminUrl, { max: 1, prepare: false });
+await admin.unsafe(`CREATE DATABASE ${dbName}`);
+const url = new URL(adminUrl);
+url.pathname = `/${dbName}`;
+const engine = new PostgresEngine();
+await engine.connect({ database_url: url.toString(), poolSize: 2 });
+
+const rows: string[] = [];
+try {
+ await engine.initSchema();
+ log(`seeding ${PAGES} pages x 8 chunks into ${dbName}`);
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT 'kr/p-' || i, 'default', 'note', '문서 ' || i, 'x', '00000000-0000-4000-8000-000000000001'::uuid,
+ '00000000-0000-4000-8000-000000000001'::uuid, 4 FROM generate_series(1, ${PAGES}) i`);
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source)
+ SELECT p.id, c, (
+ SELECT string_agg((ARRAY['좌석', '업그레이드', '요금제', '관리자', '설정', '사용자', '계정', '결제', '팀', '기능', '변경', '확인', '지원', '문의', '프로젝트'])[1 + ((p.id * 31 + c * 17 + w * 7) % 15)]
+ || CASE WHEN w % 6 = 0 THEN '. ' ELSE ' ' END, '')
+ FROM generate_series(1, 130) w
+ ), 'compiled_truth'
+ FROM pages p CROSS JOIN generate_series(0, 7) c`);
+ await engine.executeRaw('ANALYZE content_chunks');
+ await engine.executeRaw('ANALYZE pages');
+ const [{ n }] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks`);
+ log(`seeded ${n} chunks`);
+
+ for (const q of QUERIES) {
+ for (const path of ['today', 'bounded'] as const) {
+ const times: number[] = [];
+ let count = 0;
+ let meta: CjkKeywordMeta | undefined;
+ let error = '';
+ for (let r = 0; r < RUNS; r++) {
+ const t = performance.now();
+ try {
+ const res = await engine.searchKeyword(q, path === 'today' ? { limit: 20 } : { limit: 20, orFallback: true, cjkKeyword: { deadlineMs: DEADLINE, onMeta: m => { meta = m; } } });
+ count = res.length;
+ } catch (e) {
+ error = (e as Error).message.slice(0, 60);
+ }
+ times.push(performance.now() - t);
+ }
+ times.sort((a, b) => a - b);
+ const outcome = path === 'today' ? (error || 'complete') : meta ? (meta.incomplete ? `incomplete (${meta.reason})${meta.capped ? ', capped' : ''}` : meta.capped ? 'complete, capped' : 'complete') : error;
+ rows.push(`| ${q} | ${path} | ${times[Math.floor(times.length / 2)]!.toFixed(0)} | ${count} | ${outcome} |`);
+ log(rows.at(-1)!);
+ }
+ }
+} finally {
+ await engine.disconnect();
+ if (!KEEP) await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`);
+ await admin.end();
+}
+console.log(`${PAGES} pages x 8 chunks, deadline ${DEADLINE} ms, median of ${RUNS}\n| query | path | ms | rows | outcome |\n|---|---|---|---|---|\n${rows.join('\n')}`);
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9994a99cfc..23f6bb392a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -23,7 +23,7 @@ src/core/operations.ts 340 ratchet peel target: containment sprint C4-C7; grown
src/core/pglite-engine.ts 2996 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)
src/core/postgres-engine.ts 2941 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)
src/core/search/hybrid.ts 1615 ratchet +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
-src/core/types.ts 2234 ratchet +2 fix wave 11 W6.3 (#6132): SearchOpts.hnswIterativeScan (latched in search/hnsw-iterative-scan.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)
+src/core/types.ts 2239 ratchet +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)
src/core/minions/queue.ts 2528 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)
src/commands/init.ts 1878 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)
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)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1916 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1901 ratchet +5 fix wave 11 W6.3 (#6132): search.hnsw_iterative_scan type field, DB-plane merge and KNOWN_CONFIG_KEYS row (logic in search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS
+src/core/config.ts 1918 ratchet +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 671 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 42b2c65230..006a705aaf 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -257,6 +257,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
+ { since: '0.0.0-wave11', text: 'Hybrid search on CJK text now falls back to matching any query term when matching all terms finds too few rows (all-term matches still rank first), and its CJK keyword arm has one time budget, `search.cjk_keyword_deadline_ms` (default 3000); a cut arm reports degraded `keyword_candidates_incomplete`, so narrow with `--source-id` or raise the key.' },
+ { since: '0.0.0-wave11', text: 'Filtered vector search on Postgres runs pgvector iterative scans in relaxed_order, which keeps closer in-filter matches strict order dropped; `gbrain config set search.hnsw_iterative_scan strict_order` and a restart of serve and autopilot restore the old mode.' },
{ since: '0.0.0-wave11', text: 'With retrieval feedback on, MCP search and query results carry one visible line with the answer id (`Rate after use: rate_answer { answer_id: "ans_…", rating: 1-5 }`), so hosts that hide `_meta` can still rate.' },
{ since: '0.0.0-wave11', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },
];
diff --git a/src/core/config.ts b/src/core/config.ts
index 5316d5a718..d38c0d2e96 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -263,6 +263,8 @@ export interface GBrainConfig {
vector_legacy_guard?: boolean;
/** #6132 pgvector iterative scan mode (search/hnsw-iterative-scan.ts); file > DB, env wins over both. */
hnsw_iterative_scan?: string;
+ /** #5989 CJK keyword arm deadline in ms (search/cjk-keyword-deadline.ts); file > DB. */
+ cjk_keyword_deadline_ms?: number;
};
/**
@@ -821,6 +823,23 @@ export function loadConfig(): GBrainConfig | null {
// #2119 read-side merge list re-exported so callers keep one config surface.
export { DB_MERGED_PROVIDER_KEY_FIELDS } from './config-db-merge.ts';
+/**
+ * DB-plane rows for the vector/keyword scan knobs nested under `search` (file
+ * plane wins): the #5824 legacy guard, the #6132 iterative scan mode and the
+ * #5989 CJK keyword deadline.
+ */
+async function mergeSearchScanKnobs(
+ mergedSearch: NonNullable<GBrainConfig['search']>,
+ dbStr: (key: string) => Promise<string | undefined>,
+ dbBoolStrict: (key: string) => Promise<boolean | undefined>,
+): Promise<void> {
+ const dbVectorLegacyGuard = await dbBoolStrict('search.vector_legacy_guard');
+ if (mergedSearch.vector_legacy_guard === undefined && dbVectorLegacyGuard !== undefined) mergedSearch.vector_legacy_guard = dbVectorLegacyGuard;
+ const dbHnswIterativeScan = await dbStr('search.hnsw_iterative_scan');
+ if (mergedSearch.hnsw_iterative_scan === undefined && dbHnswIterativeScan !== undefined) mergedSearch.hnsw_iterative_scan = dbHnswIterativeScan;
+ const dbCjkDeadline = Number(await dbStr('search.cjk_keyword_deadline_ms'));
+ if (mergedSearch.cjk_keyword_deadline_ms === undefined && Number.isFinite(dbCjkDeadline) && dbCjkDeadline > 0) mergedSearch.cjk_keyword_deadline_ms = dbCjkDeadline;
+}
/**
* v0.27.1 — async config loader that overlays DB-plane config on top of the
* file/env config. Used by `gbrain` CLI's connectEngine() AFTER engine.connect()
@@ -1173,10 +1192,7 @@ export async function loadConfigWithEngine(
const n = Number(await dbStr(`search.${cap}`));
if (Number.isFinite(n)) mergedSearch[cap] = n;
}
- const dbVectorLegacyGuard = await dbBoolStrict('search.vector_legacy_guard');
- if (mergedSearch.vector_legacy_guard === undefined && dbVectorLegacyGuard !== undefined) mergedSearch.vector_legacy_guard = dbVectorLegacyGuard;
- const dbHnswIterativeScan = await dbStr('search.hnsw_iterative_scan');
- if (mergedSearch.hnsw_iterative_scan === undefined && dbHnswIterativeScan !== undefined) mergedSearch.hnsw_iterative_scan = dbHnswIterativeScan;
+ await mergeSearchScanKnobs(mergedSearch, dbStr, dbBoolStrict);
if (Object.keys(mergedSearch).length > 0) {
merged.search = mergedSearch;
}
@@ -1358,6 +1374,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #5824 one-release rollback, latched per process (search/vector-legacy-guard.ts).
'search.vector_legacy_guard',
'search.hnsw_iterative_scan',
+ 'search.cjk_keyword_deadline_ms',
'search.adaptive_return',
'search.adaptive_return_entity_max',
'search.adaptive_return_other_max',
diff --git a/src/core/engine-sql/cjk-search.ts b/src/core/engine-sql/cjk-search.ts
index 26adc18eab..1b56223b75 100644
--- a/src/core/engine-sql/cjk-search.ts
+++ b/src/core/engine-sql/cjk-search.ts
@@ -12,6 +12,26 @@
* `withScopedReadTransaction` with `SET LOCAL statement_timeout`; PGLite (no
* RLS layer) brands its own executor.
*
+ * OR fallback (#6043): with `opts.orFallback` (hybrid's keyword arm) and more
+ * than one term, a strict AND that returns fewer than the requested rows is
+ * re-run matching any term, ranked by matched-term count then term frequency,
+ * the same semantics as the ASCII path. Direct callers keep strict AND.
+ *
+ * Bounded arm (#5989), only when the caller passes `opts.cjkKeyword` (hybrid
+ * does, with `search.cjk_keyword_deadline_ms`): on Postgres one absolute
+ * deadline, started before the pool wait, covers both attempts. Today's full
+ * scoring runs first under 2/3 of it; when its statement times out, that
+ * transaction rolls back and one capped retry runs in the remaining third, in
+ * a fresh scoped read transaction with the same source scope: up to
+ * `CJK_CANDIDATE_CAP` chunk ids by an unordered LIKE scan, all-term matches
+ * first and partial matches only when the all-term rows fall short, scored
+ * over those ids alone. A capped stage that hit the cap reports
+ * `keyword_candidates_incomplete`; a retry that also times out returns no
+ * keyword rows with the same reason, and the vector arm still serves. PGLite
+ * is in-process WASM and cannot be preempted, so it is bounded by work: past
+ * `PGLITE_CJK_CAPPED_CHUNKS` chunks (planner estimate) it always uses the
+ * capped stage.
+ *
* Note: the fallback is an ILIKE scan over content_chunks — correct but not
* index-accelerated. Deployments with heavy CJK corpora should install a
* CJK-aware FTS extension (pgroonga / zhparser); see
@@ -19,19 +39,140 @@
*/
import type { SearchResult } from '../types.ts';
import { rowToSearchResult } from '../utils.ts';
-import { buildCJKKeywordSql, type CjkKeywordCtx } from '../search/cjk-keyword-sql.ts';
-import type { ScopedRead } from './brands.ts';
+import { splitCJKQueryTerms } from '../cjk.ts';
+import { buildCJKCandidateSql, buildCJKKeywordSql, type CjkKeywordCtx, type CjkKeywordVariant } from '../search/cjk-keyword-sql.ts';
+import { scopedRead, type ScopedRead } from './brands.ts';
+import type { SqlExecutor } from './executor.ts';
/** Runs `read` on the engine's scoped read executor. */
export type ScopedReadRunner = <T>(read: (exec: ScopedRead) => Promise<T>) => Promise<T>;
+export const CJK_CANDIDATE_CAP = 2000;
+export const PGLITE_CJK_CAPPED_CHUNKS = 50_000;
+const MIN_ATTEMPT_MS = 50;
+/** Held back from each attempt's statement timeout for the cancel round trip and rollback, so the arm ends inside its deadline. */
+const ROLLBACK_MARGIN_MS = 40;
+
+/** What the bounded arm did; hybrid turns `incomplete` into the degraded stage. */
+export interface CjkKeywordMeta {
+ incomplete: boolean;
+ reason?: 'timeout' | 'candidate_budget';
+ /** The capped candidate stage served the rows. */
+ capped: boolean;
+ /** Keyword-arm wall time for this call, pool wait included. */
+ arm_ms: number;
+}
+
+export interface CjkKeywordRun {
+ deadlineMs: number;
+ onMeta?: (meta: CjkKeywordMeta) => void;
+ /** Test and bench seams; production uses CJK_CANDIDATE_CAP and PGLITE_CJK_CAPPED_CHUNKS. */
+ candidateCap?: number;
+ pgliteCappedChunks?: number;
+}
+
+type Exec = ScopedRead;
+
+async function rows(exec: Exec, query: string, ctx: CjkKeywordCtx, variant?: CjkKeywordVariant): Promise<Record<string, unknown>[]> {
+ const built = buildCJKKeywordSql(query, ctx, variant);
+ return built ? (await exec.unsafe(built.sql, built.params)).rows as Record<string, unknown>[] : [];
+}
+
+/** Strict AND, then the OR fallback when it falls short of the requested rows. */
+async function fullScoring(exec: Exec, query: string, ctx: CjkKeywordCtx, orFallback: boolean): Promise<Record<string, unknown>[]> {
+ const strict = await rows(exec, query, ctx);
+ return orFallback && strict.length < ctx.limit ? rows(exec, query, ctx, { match: 'any' }) : strict;
+}
+
+async function candidates(exec: Exec, query: string, ctx: CjkKeywordCtx, stage: Parameters<typeof buildCJKCandidateSql>[2]): Promise<number[]> {
+ const built = buildCJKCandidateSql(query, ctx, stage);
+ return built ? (await exec.unsafe(built.sql, built.params)).rows.map(r => Number((r as { chunk_id: unknown }).chunk_id)) : [];
+}
+
+/** The capped stage: all-term ids first, partial ids only when the all-term rows fall short. */
+async function cappedScoring(exec: Exec, query: string, ctx: CjkKeywordCtx, orFallback: boolean, cap: number): Promise<{ rows: Record<string, unknown>[]; capHit: boolean }> {
+ const all = await candidates(exec, query, ctx, { match: 'all', cap });
+ const strict = all.length > 0 ? await rows(exec, query, ctx, { candidateIds: all }) : [];
+ if (all.length >= cap || !orFallback || strict.length >= ctx.limit) return { rows: strict, capHit: all.length >= cap };
+ const room = cap - all.length;
+ const partial = await candidates(exec, query, ctx, { match: 'any', cap: room, excludeIds: all });
+ if (partial.length === 0) return { rows: strict, capHit: false };
+ return { rows: await rows(exec, query, ctx, { match: 'any', candidateIds: [...all, ...partial] }), capHit: partial.length >= room };
+}
+
+function isStatementTimeout(e: unknown): boolean {
+ const err = e as { code?: unknown; cause?: { code?: unknown } } | null;
+ return err?.code === '57014' || err?.cause?.code === '57014';
+}
+
+/**
+ * Run `fn` in its own scoped read transaction under a statement timeout. A
+ * fired timeout aborts that transaction (the driver rolls it back), so it
+ * returns null and the next attempt opens a fresh one with the same source
+ * scope.
+ */
+async function bounded<T>(scoped: ScopedReadRunner, ms: number, fn: (exec: Exec) => Promise<T>): Promise<T | null> {
+ ms -= ROLLBACK_MARGIN_MS;
+ if (ms < MIN_ATTEMPT_MS) return null;
+ const end = performance.now() + ms;
+ try {
+ return await scoped(async exec => {
+ // statement_timeout is per statement and an attempt runs several, so
+ // each one gets what is left of the attempt's budget.
+ const timed = scopedRead({
+ ...exec,
+ unsafe: async (sql: string, params: readonly unknown[]) => {
+ const left = Math.floor(end - performance.now());
+ if (left < 1) throw Object.assign(new Error('cjk keyword attempt budget spent'), { code: '57014' });
+ await exec.unsafe(`SELECT set_config('statement_timeout', $1, true)`, [String(left)]);
+ return exec.unsafe(sql, params);
+ },
+ } as SqlExecutor);
+ return fn(timed);
+ });
+ } catch (e) {
+ if (isStatementTimeout(e)) return null;
+ throw e;
+ }
+}
+
+async function chunkEstimate(exec: Exec): Promise<number> {
+ const [row] = (await exec.unsafe(`SELECT reltuples::bigint AS n FROM pg_class WHERE relname = 'content_chunks' AND relkind = 'r'`, [])).rows as Array<{ n: unknown }>;
+ return Number(row?.n ?? -1);
+}
+
export async function searchKeywordCJK(
scoped: ScopedReadRunner,
query: string,
ctx: CjkKeywordCtx,
+ engine: 'postgres' | 'pglite' = 'postgres',
): Promise<SearchResult[]> {
- const built = buildCJKKeywordSql(query, ctx);
- if (!built) return [];
- const rows = await scoped(async (exec) => (await exec.unsafe(built.sql, built.params)).rows);
- return rows.map(rowToSearchResult);
+ if (!buildCJKKeywordSql(query, ctx)) return [];
+ const started = performance.now();
+ const orFallback = ctx.opts?.orFallback === true && splitCJKQueryTerms(query).length > 1;
+ const run = ctx.opts?.cjkKeyword;
+ if (!run) return (await scoped(exec => fullScoring(exec, query, ctx, orFallback))).map(rowToSearchResult);
+ const cap = run.candidateCap ?? CJK_CANDIDATE_CAP;
+ const report = (meta: Omit<CjkKeywordMeta, 'arm_ms'>) => run.onMeta?.({ ...meta, arm_ms: Math.round(performance.now() - started) });
+ if (engine === 'pglite') {
+ const out = await scoped(async exec => {
+ if (await chunkEstimate(exec) <= (run.pgliteCappedChunks ?? PGLITE_CJK_CAPPED_CHUNKS)) {
+ const full = await fullScoring(exec, query, ctx, orFallback);
+ report({ incomplete: false, capped: false });
+ return full;
+ }
+ const capped = await cappedScoring(exec, query, ctx, orFallback, cap);
+ report(capped.capHit ? { incomplete: true, reason: 'candidate_budget', capped: true } : { incomplete: false, capped: true });
+ return capped.rows;
+ });
+ return out.map(rowToSearchResult);
+ }
+ const full = await bounded(scoped, started + (run.deadlineMs * 2) / 3 - performance.now(), exec => fullScoring(exec, query, ctx, orFallback));
+ if (full) {
+ report({ incomplete: false, capped: false });
+ return full.map(rowToSearchResult);
+ }
+ const capped = await bounded(scoped, started + run.deadlineMs - performance.now(), exec => cappedScoring(exec, query, ctx, orFallback, cap));
+ report(capped && !capped.capHit ? { incomplete: false, capped: true } : { incomplete: true, reason: 'timeout', capped: true });
+ return (capped?.rows ?? []).map(rowToSearchResult);
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 082d26af31..a006c6ff7c 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -254,6 +254,7 @@ export const CODES = {
preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },
profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },
projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },
+ 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 } },
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." },
publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },
diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.ts
index 1954a9506d..d3a48a5c76 100644
--- a/src/core/interop-notices.ts
+++ b/src/core/interop-notices.ts
@@ -50,6 +50,7 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidance
keyword_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 (CLI --source-id), or 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_status_unknown: { why: 'whether recent writes are in the search index could not be checked', fix: 'doctor' },
deadline: { why: 'the pack hit its time limit and is partial', fix: null },
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index c02002352c..d073d63031 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1570,7 +1570,7 @@ export class PGLiteEngine implements BrainEngine {
dedup: boolean;
},
): Promise<SearchResult[]> {
- return searchKeywordCJK(async (read) => read(scopedRead(this.engineSql)), query, ctx);
+ return searchKeywordCJK(async (read) => read(scopedRead(this.engineSql)), query, ctx, 'pglite');
}
/**
diff --git a/src/core/search/cjk-keyword-deadline.ts b/src/core/search/cjk-keyword-deadline.ts
new file mode 100644
index 0000000000..575a736c0c
--- /dev/null
+++ b/src/core/search/cjk-keyword-deadline.ts
@@ -0,0 +1,28 @@
+/**
+ * `search.cjk_keyword_deadline_ms` (#5989): the one total deadline, in
+ * milliseconds, for hybrid search's CJK keyword arm (engine-sql/cjk-search.ts
+ * splits it 2/3 full scoring, 1/3 capped retry on Postgres). Integer,
+ * default 3000, range 500..30000; `config set` refuses other values. Read
+ * from the merged config per hybrid request (file > DB).
+ */
+import type { GBrainConfig } from '../config.ts';
+
+export const CJK_KEYWORD_DEADLINE_KEY = 'search.cjk_keyword_deadline_ms';
+export const CJK_KEYWORD_DEADLINE_DEFAULT_MS = 3000;
+export const CJK_KEYWORD_DEADLINE_MIN_MS = 500;
+export const CJK_KEYWORD_DEADLINE_MAX_MS = 30_000;
+
+function valid(n: number): boolean {
+ return Number.isInteger(n) && n >= CJK_KEYWORD_DEADLINE_MIN_MS && n <= CJK_KEYWORD_DEADLINE_MAX_MS;
+}
+
+export function resolveCjkKeywordDeadlineMs(cfg: Pick<GBrainConfig, 'search'> | null | undefined): number {
+ const n = Number(cfg?.search?.cjk_keyword_deadline_ms);
+ return valid(n) ? n : CJK_KEYWORD_DEADLINE_DEFAULT_MS;
+}
+
+export function cjkKeywordDeadlineValueProblem(value: string): string | null {
+ return valid(Number(value.trim()))
+ ? null
+ : `${CJK_KEYWORD_DEADLINE_KEY} must be an integer number of milliseconds from ${CJK_KEYWORD_DEADLINE_MIN_MS} to ${CJK_KEYWORD_DEADLINE_MAX_MS} (got '${value}'). Nothing was written.`;
+}
diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.ts
index 8156b7bfd4..05a4e58e68 100644
--- a/src/core/search/cjk-keyword-sql.ts
+++ b/src/core/search/cjk-keyword-sql.ts
@@ -44,12 +44,28 @@ export interface CjkKeywordSql {
params: unknown[];
}
-export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywordSql | null {
+/**
+ * `match: 'all'` (default) is today's strict AND; `'any'` is the OR fallback
+ * (#6043): a chunk matching any term qualifies and ranks by how many terms it
+ * matches, then by the usual term-frequency score, so all-term chunks always
+ * outrank partial ones. `candidateIds` restricts scoring to a candidate set
+ * from `buildCJKCandidateSql` (the capped retry, #5989).
+ */
+export interface CjkKeywordVariant {
+ match?: 'all' | 'any';
+ candidateIds?: number[];
+}
+
+/** Bound for the matched-term count inside the OR score, above any realistic per-chunk TF sum. */
+const MATCHED_TERM_WEIGHT = 1000;
+
+export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx, variant: CjkKeywordVariant = {}): CjkKeywordSql | null {
const { limit, offset, innerLimit, sourceFactorCase, hardExcludeClause, visibilityClause, detailFilter, opts, dedup } = ctx;
const qRaw = query;
if (qRaw.length === 0) return null;
const terms = splitCJKQueryTerms(qRaw);
if (terms.length === 0) return null;
+ const any = variant.match === 'any' && terms.length > 1;
const params: unknown[] = [];
@@ -90,6 +106,89 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
offsetIndex = params.length;
}
+ const extraFilter = shapeFilters(opts, params);
+ let fromClause = 'content_chunks cc';
+ if (variant.candidateIds) {
+ params.push(variant.candidateIds);
+ fromClause = `unnest($${params.length}::bigint[]) AS cand(id) JOIN content_chunks cc ON cc.id = cand.id`;
+ }
+ const { whereLikeClause, matchedExpr } = likeClauses(terms, likeParamIndices, any);
+
+ const termFreqExpr = rawTermIndices
+ .map(idx => `((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${idx}, ''))) / NULLIF(LENGTH($${idx}), 0)::real)`)
+ .join(' + ');
+
+ const qRawBonusExpr = terms.length > 1
+ ? ` + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${qRawIndex}, ''))) / NULLIF(LENGTH($${qRawIndex}), 0)::real)`
+ : '';
+
+ const positionExpr = `COALESCE(1.0 / NULLIF(POSITION($${qRawIndex} IN cc.chunk_text), 0)::real, 0.0)`;
+ const orderExpr = any ? `(${matchedExpr}) DESC, score DESC` : 'score DESC';
+
+ // Term-frequency count: count occurrences of each term in chunk_text via
+ // (length(chunk) - length(replace(chunk, term, ''))) / length(term),
+ // plus bonus for contiguous raw query occurrences when multi-term, and
+ // position()-tiebreaker so earlier-in-chunk hits outrank later ones.
+ // The OR fallback adds the matched-term count outside the source factor,
+ // so a boosted partial match never outscores an all-term chunk.
+ const tfScoreExpr = `
+ ((${termFreqExpr}${qRawBonusExpr}
+ + ${positionExpr})
+ * ${sourceFactorCase})
+ `;
+ const scoreExpr = any ? `(${MATCHED_TERM_WEIGHT} * (${matchedExpr}) + ${tfScoreExpr})` : tfScoreExpr;
+ return assemble({ dedup, fromClause, scoreExpr, orderExpr, whereLikeClause, detailFilter, extraFilter, hardExcludeClause, visibilityClause, innerLimitIndex, limitIndex, offsetIndex, params });
+}
+
+/**
+ * The capped candidate stage (#5989): up to `cap` chunk ids matching every
+ * term (`match: 'all'`) or any term (`'any'`, excluding `excludeIds`), by an
+ * unordered LIKE scan with the same shape, source and visibility filters as
+ * the scoring query. Ids only, so the scan stops at the cap instead of
+ * scoring every match.
+ */
+export function buildCJKCandidateSql(
+ query: string,
+ ctx: CjkKeywordCtx,
+ stage: { match: 'all' | 'any'; cap: number; excludeIds?: number[] },
+): CjkKeywordSql | null {
+ const terms = splitCJKQueryTerms(query);
+ if (query.length === 0 || terms.length === 0) return null;
+ const params: unknown[] = [];
+ const likeParamIndices = terms.map(term => { params.push(`%${escapeLikePattern(term)}%`); return params.length; });
+ let extraFilter = shapeFilters(ctx.opts, params);
+ if (stage.excludeIds?.length) {
+ params.push(stage.excludeIds);
+ extraFilter += ` AND cc.id != ALL($${params.length}::bigint[])`;
+ }
+ params.push(stage.cap);
+ const capIndex = params.length;
+ const { whereLikeClause } = likeClauses(terms, likeParamIndices, stage.match === 'any' && terms.length > 1);
+ return {
+ sql: `SELECT cc.id AS chunk_id
+ FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${whereLikeClause} ${ctx.detailFilter}${extraFilter} ${ctx.hardExcludeClause} ${ctx.visibilityClause}${ctx.dedup ? `
+ AND cc.modality = 'text'` : ''}
+ LIMIT $${capIndex}`,
+ params,
+ };
+}
+
+function likeClauses(terms: string[], likeParamIndices: number[], any: boolean): { whereLikeClause: string; matchedExpr: string } {
+ const likes = likeParamIndices.map((idx, termIndex) => {
+ const term = terms[termIndex];
+ const operator = term.toLowerCase() === term.toUpperCase() ? 'LIKE' : 'ILIKE';
+ return `cc.chunk_text ${operator} $${idx} ESCAPE '\\'`;
+ });
+ return {
+ whereLikeClause: any ? `(${likes.join(' OR ')})` : likes.join(' AND '),
+ matchedExpr: likes.map(l => `(${l})::int`).join(' + '),
+ };
+}
+
+function shapeFilters(opts: SearchOpts | undefined, params: unknown[]): string {
let extraFilter = '';
// #4480: the CJK arm must honor the SAME shape filters as the main
// keyword arm. type/types/exclude_slugs were silently dropped here, so a
@@ -132,35 +231,14 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
params.push(opts.sourceId);
extraFilter += ` AND p.source_id = $${params.length}`;
}
+ return extraFilter;
+}
- const whereLikeClause = likeParamIndices
- .map((idx, termIndex) => {
- const term = terms[termIndex];
- const operator = term.toLowerCase() === term.toUpperCase() ? 'LIKE' : 'ILIKE';
- return `cc.chunk_text ${operator} $${idx} ESCAPE '\\'`;
- })
- .join(' AND ');
-
- const termFreqExpr = rawTermIndices
- .map(idx => `((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${idx}, ''))) / NULLIF(LENGTH($${idx}), 0)::real)`)
- .join(' + ');
-
- const qRawBonusExpr = terms.length > 1
- ? ` + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $${qRawIndex}, ''))) / NULLIF(LENGTH($${qRawIndex}), 0)::real)`
- : '';
-
- const positionExpr = `COALESCE(1.0 / NULLIF(POSITION($${qRawIndex} IN cc.chunk_text), 0)::real, 0.0)`;
-
- // Term-frequency count: count occurrences of each term in chunk_text via
- // (length(chunk) - length(replace(chunk, term, ''))) / length(term),
- // plus bonus for contiguous raw query occurrences when multi-term, and
- // position()-tiebreaker so earlier-in-chunk hits outrank later ones.
- const scoreExpr = `
- ((${termFreqExpr}${qRawBonusExpr}
- + ${positionExpr})
- * ${sourceFactorCase})
- `;
-
+function assemble(a: {
+ dedup: boolean; fromClause: string; scoreExpr: string; orderExpr: string; whereLikeClause: string; detailFilter: string; extraFilter: string;
+ hardExcludeClause: string; visibilityClause: string; innerLimitIndex: number; limitIndex: number; offsetIndex: number; params: unknown[];
+}): CjkKeywordSql {
+ const { dedup, fromClause, scoreExpr, orderExpr, whereLikeClause, detailFilter, extraFilter, hardExcludeClause, visibilityClause, innerLimitIndex, limitIndex, offsetIndex, params } = a;
if (dedup) {
return {
sql: `WITH ranked AS (
@@ -176,12 +254,12 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
CASE WHEN p.updated_at < (
SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
) THEN true ELSE false END AS stale
- FROM content_chunks cc
+ FROM ${fromClause}
JOIN pages p ON p.id = cc.page_id
JOIN sources s ON s.id = p.source_id
WHERE ${whereLikeClause} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
AND cc.modality = 'text'
- ORDER BY score DESC, page_id ASC, chunk_id ASC
+ ORDER BY ${orderExpr}, page_id ASC, chunk_id ASC
LIMIT $${innerLimitIndex}
),
${buildBestPerPagePoolCte('ranked')}
@@ -204,11 +282,11 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
CASE WHEN p.updated_at < (
SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id
) THEN true ELSE false END AS stale
- FROM content_chunks cc
+ FROM ${fromClause}
JOIN pages p ON p.id = cc.page_id
JOIN sources s ON s.id = p.source_id
WHERE ${whereLikeClause} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
- ORDER BY score DESC, page_id ASC, chunk_id ASC
+ ORDER BY ${orderExpr}, page_id ASC, chunk_id ASC
LIMIT $${limitIndex} OFFSET $${offsetIndex}`,
params,
};
diff --git a/src/core/search/config-values.ts b/src/core/search/config-values.ts
index bbf290b798..cb48c117be 100644
--- a/src/core/search/config-values.ts
+++ b/src/core/search/config-values.ts
@@ -4,6 +4,7 @@
* ignore (exit 2, `invalid_params`, nothing written) instead of storing it.
*/
import { HNSW_ITERATIVE_SCAN_KEY, HNSW_ITERATIVE_SCAN_MODES, hnswIterativeScanValueProblem } from './hnsw-iterative-scan.ts';
+import { CJK_KEYWORD_DEADLINE_DEFAULT_MS, CJK_KEYWORD_DEADLINE_KEY, cjkKeywordDeadlineValueProblem } from './cjk-keyword-deadline.ts';
interface SearchValueRule {
problem: (value: string) => string | null;
@@ -13,6 +14,7 @@ interface SearchValueRule {
export const SEARCH_VALUE_RULES: Readonly<Record<string, SearchValueRule>> = {
[HNSW_ITERATIVE_SCAN_KEY]: { problem: hnswIterativeScanValueProblem, example: HNSW_ITERATIVE_SCAN_MODES[0] },
+ [CJK_KEYWORD_DEADLINE_KEY]: { problem: cjkKeywordDeadlineValueProblem, example: String(CJK_KEYWORD_DEADLINE_DEFAULT_MS) },
};
/** The refusal for an invalid value of a validated `search.*` key, or null. */
diff --git a/src/core/search/hybrid/request.ts b/src/core/search/hybrid/request.ts
index a8fa03dce5..af5ca995d6 100644
--- a/src/core/search/hybrid/request.ts
+++ b/src/core/search/hybrid/request.ts
@@ -24,6 +24,7 @@ import { resolveBoostMap, resolveHardExcludes } from '../source-boost.ts';
import { resolveEmbeddingColumn } from '../embedding-column.ts';
import { resolveVectorLegacyGuard } from '../vector-legacy-guard.ts';
import { resolveHnswIterativeScan } from '../hnsw-iterative-scan.ts';
+import { resolveCjkKeywordDeadlineMs } from '../cjk-keyword-deadline.ts';
import { resolveSearchDateBounds } from '../date-bounds.ts';
import { type DecideSearchContext, decideMetaFor, resolveAndLaunchDecide } from '../decide-stage.ts';
import { applySearchIntent } from '../decide-retrieval.ts';
@@ -56,6 +57,8 @@ export interface HybridRequest {
degraded: DegradedStageEntry[];
/** v0.46.15: max-escalations searchVector exhaustion event, accumulated across vector calls. */
vectorPoolUnderfill: HybridSearchMeta['vector_pool_underfilled'];
+ /** #5989: the last bounded CJK keyword arm outcome. */
+ keywordCandidates?: HybridSearchMeta['keyword_candidates'];
/** v0.25.0: whether query expansion actually produced variants (onMeta). */
expansionApplied: boolean;
/** Telemetry counters set at each return path before emitHybridMeta. */
@@ -237,6 +240,14 @@ export async function resolveHybridRequest(
// #5824 rollback switch, latched once per process from env/config.
vectorLegacyGuard: resolveVectorLegacyGuard(cfgForColumn),
hnswIterativeScan: resolveHnswIterativeScan(cfgForColumn),
+ // #5989: bound the CJK keyword arm by one deadline; its outcome and wall time ride the meta.
+ cjkKeyword: {
+ deadlineMs: resolveCjkKeywordDeadlineMs(cfgForColumn),
+ onMeta: (m) => {
+ if (m.incomplete) pushDegraded(degraded, 'keyword_candidates_incomplete', m.reason);
+ req.keywordCandidates = m;
+ },
+ },
// D2 fix (fix/title-retrieval-arm, Reviewer F1): the hybrid keyword arm
// is a recall arm — opt in to the engine's AND→OR zero-recall fallback.
// Direct searchKeyword consumers (countMentions, link-extraction, eval)
@@ -319,8 +330,9 @@ export async function applyIdentityBoosts(req: HybridRequest, list: SearchResult
// search_telemetry rollup. Telemetry write is sync (bumps a bucket map),
// flush is fire-and-forget on 60s / 100-call thresholds. The hot path
// never waits.
-export function emitHybridMeta(req: HybridRequest, rawMeta: HybridSearchMeta): void {
+export function emitHybridMeta(req: HybridRequest, armMeta: HybridSearchMeta): void {
const { engine, opts } = req;
+ const rawMeta = req.keywordCandidates ? { ...armMeta, keyword_candidates: req.keywordCandidates } : armMeta;
const decide = decideMetaFor(req.decide);
const answerability = req.decide?.answerability;
const meta: HybridSearchMeta = decide || req.rerankMeta || answerability || req.relationalPlan
diff --git a/src/core/types.ts b/src/core/types.ts
index 49255f2f86..ca711b79d1 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1178,6 +1178,8 @@ export interface SearchOpts extends PageReadPolicy {
vectorLegacyGuard?: boolean;
/** #6132: pgvector `hnsw.iterative_scan` mode (default relaxed_order), latched by the caller (search/hnsw-iterative-scan.ts). */
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;
/**
* v0.42 — intent-aware adaptive return-sizing. `true` enables with config/
* default caps; an object overrides caps per-call; omitted/`false` = off
@@ -1997,6 +1999,7 @@ export const DEGRADED_STAGES = [
'keyword_relaxed_carried',
'safe_index_pending',
'vector_candidates_incomplete',
+ 'keyword_candidates_incomplete',
'projection_pending',
'projection_status_unknown',
] as const;
@@ -2093,6 +2096,8 @@ export interface HybridSearchMeta {
* yield). Omitted on clean runs. Exhaustion is VISIBLE, not silent.
*/
vector_pool_underfilled?: Omit<VectorPoolMeta, 'underfilled'>;
+ /** #5989: the bounded CJK keyword arm's outcome and wall time (separate from total hybrid latency). */
+ keyword_candidates?: import('./engine-sql/cjk-search.ts').CjkKeywordMeta;
/**
* v0.42.3.0 — autocut decision (signal, cut point, kept/total, gapRatio).
* Omitted when autocut didn't run (no reranker). Surfaced for
diff --git a/test/cjk-keyword-fallback.test.ts b/test/cjk-keyword-fallback.test.ts
new file mode 100644
index 0000000000..fff21e8eee
--- /dev/null
+++ b/test/cjk-keyword-fallback.test.ts
@@ -0,0 +1,118 @@
+/**
+ * #6043 + #5989: the CJK keyword path honors the hybrid OR fallback with the
+ * ASCII-path semantics (only when strict AND returns fewer than the requested
+ * rows; ranked by matched-term count, then term frequency), and the bounded
+ * arm's capped candidate stage keeps all-term rows ahead of partial ones.
+ * Direct searchKeyword callers keep strict AND.
+ *
+ * R3/R4: engine in beforeAll, disconnect in afterAll; state reset per test.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+async function page(slug: string, body: string): Promise<void> {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body });
+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));
+}
+
+const slugs = (rows: Array<{ slug: string }>) => rows.map((r) => r.slug);
+
+describe('CJK OR fallback (#6043)', () => {
+ test('terms in different documents: strict AND finds nothing, the hybrid fallback finds both', async () => {
+ await page('notes/seats', '团队版的席位数量由管理员配置。');
+ await page('notes/upgrade', '升级到专业版后可以使用更多功能。');
+ expect(await engine.searchKeyword('席位 升级')).toEqual([]);
+ expect(slugs(await engine.searchKeyword('席位 升级', { orFallback: true })).sort()).toEqual(['notes/seats', 'notes/upgrade']);
+ });
+
+ test('when strict AND has at least the requested rows, the result is identical to today', async () => {
+ for (let i = 0; i < 3; i++) await page(`notes/both-${i}`, `席位${'。'.repeat(i)}和升级都在这里`);
+ await page('notes/only-seats', '席位 席位 席位 席位');
+ const strict = await engine.searchKeyword('席位 升级', { limit: 2 });
+ const fallback = await engine.searchKeyword('席位 升级', { limit: 2, orFallback: true });
+ expect(strict).toHaveLength(2);
+ expect(slugs(fallback)).toEqual(slugs(strict));
+ expect(fallback.map((r) => r.score)).toEqual(strict.map((r) => r.score));
+ });
+
+ test('in the fallback an all-term chunk outranks single-term chunks with a higher term frequency', async () => {
+ await page('notes/both', '席位和升级');
+ await page('notes/seats-many', '席位 席位 席位 席位 席位 席位');
+ await page('notes/upgrade-many', '升级 升级 升级 升级 升级 升级');
+ const rows = await engine.searchKeyword('席位 升级', { limit: 5, orFallback: true });
+ expect(rows[0]?.slug).toBe('notes/both');
+ expect(rows).toHaveLength(3);
+ });
+});
+
+describe('bounded CJK keyword arm on PGLite (#5989)', () => {
+ test('past the chunk threshold the capped stage keeps no partial-term row when all-term matches exceed the cap', async () => {
+ for (let i = 0; i < 8; i++) await page(`notes/both-${i}`, `席位和升级 ${i}`);
+ for (let i = 0; i < 4; i++) await page(`notes/partial-${i}`, `只有席位 ${i}`);
+ await engine.executeRaw('ANALYZE content_chunks');
+ const metas: Array<Record<string, unknown>> = [];
+ const rows = await engine.searchKeyword('席位 升级', { limit: 20, orFallback: true,
+ cjkKeyword: { deadlineMs: 3000, candidateCap: 5, pgliteCappedChunks: 0, onMeta: (m) => metas.push(m as never) } });
+ expect(rows).toHaveLength(5);
+ expect(rows.every((r) => r.slug.startsWith('notes/both-'))).toBe(true);
+ expect(metas).toHaveLength(1);
+ expect(metas[0]).toMatchObject({ incomplete: true, reason: 'candidate_budget', capped: true });
+ });
+
+ test('a capped stage under the cap is complete and ranks like the full path', async () => {
+ await page('notes/both', '席位和升级');
+ await page('notes/seats', '席位 席位 席位');
+ await engine.executeRaw('ANALYZE content_chunks');
+ const metas: Array<Record<string, unknown>> = [];
+ const capped = await engine.searchKeyword('席位 升级', { limit: 5, orFallback: true,
+ cjkKeyword: { deadlineMs: 3000, candidateCap: 50, pgliteCappedChunks: 0, onMeta: (m) => metas.push(m as never) } });
+ const full = await engine.searchKeyword('席位 升级', { limit: 5, orFallback: true });
+ expect(slugs(capped)).toEqual(slugs(full));
+ expect(metas[0]).toMatchObject({ incomplete: false, capped: true });
+ });
+
+ test('below the chunk threshold the full path runs and reports complete', async () => {
+ await page('notes/both', '席位和升级');
+ const metas: Array<Record<string, unknown>> = [];
+ await engine.searchKeyword('席位 升级', { orFallback: true, cjkKeyword: { deadlineMs: 3000, onMeta: (m) => metas.push(m as never) } });
+ expect(metas[0]).toMatchObject({ incomplete: false, capped: false });
+ expect(typeof metas[0]?.arm_ms).toBe('number');
+ });
+});
+
+describe('hybrid wiring (#5989)', () => {
+ test('hybrid passes the deadline and turns an incomplete arm into keyword_candidates_incomplete with its arm time', async () => {
+ const { hybridSearch } = await import('../src/core/search/hybrid.ts');
+ await page('notes/both', '席位和升级');
+ await engine.setConfig('embedding_disabled', 'true');
+ const original = engine.searchKeyword.bind(engine);
+ let seenDeadline: number | undefined;
+ engine.searchKeyword = (async (q: string, opts?: Parameters<typeof original>[1]) => {
+ seenDeadline = opts?.cjkKeyword?.deadlineMs;
+ opts?.cjkKeyword?.onMeta?.({ incomplete: true, reason: 'timeout', capped: true, arm_ms: 1234 });
+ return [];
+ }) as typeof engine.searchKeyword;
+ try {
+ let meta: { degraded?: Array<{ stage: string; reason?: string }>; keyword_candidates?: unknown } | undefined;
+ await hybridSearch(engine, '席位 升级', { onMeta: (m) => { meta = m as never; } });
+ expect(seenDeadline).toBe(3000);
+ expect(meta?.degraded).toContainEqual({ stage: 'keyword_candidates_incomplete', reason: 'timeout' });
+ expect(meta?.keyword_candidates).toEqual({ incomplete: true, reason: 'timeout', capped: true, arm_ms: 1234 });
+ } finally {
+ engine.searchKeyword = original;
+ }
+ });
+});
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index 7b2dd03649..ae4ecf8248 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -34,6 +34,7 @@ const DIRECTLY_READ_SINGLETONS = [
'search.adaptive_return_min_keep',
'search.vector_legacy_guard', // search/vector-legacy-guard.ts via loadConfigWithEngine
'search.hnsw_iterative_scan', // search/hnsw-iterative-scan.ts via loadConfigWithEngine
+ 'search.cjk_keyword_deadline_ms', // search/cjk-keyword-deadline.ts via loadConfigWithEngine
'search.crag_escalation', // ops/search.ts
'search.crag_think', // ops/search.ts
'search.return_unit', // search/evidence-delivery.ts
diff --git a/test/e2e/cjk-keyword-deadline-postgres.test.ts b/test/e2e/cjk-keyword-deadline-postgres.test.ts
new file mode 100644
index 0000000000..236b2886df
--- /dev/null
+++ b/test/e2e/cjk-keyword-deadline-postgres.test.ts
@@ -0,0 +1,64 @@
+/**
+ * Postgres parity for the CJK keyword OR fallback (#6043) and the bounded arm
+ * (#5989): a real statement timeout inside the scoped read transaction rolls
+ * back to the savepoint, the capped retry keeps the source scope, and the
+ * engine serves the next query normally.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import type { CjkKeywordMeta } from '../../src/core/engine-sql/cjk-search.ts';
+
+const RUN = hasDatabase();
+let engine: PostgresEngine;
+
+async function seed(source: string, slugPrefix: string, pages: number, chunksPerPage: number, body: string): Promise<void> {
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT '${slugPrefix}' || i, $1, 'note', 'p' || i, 'x', '00000000-0000-4000-8000-000000000001'::uuid,
+ '00000000-0000-4000-8000-000000000001'::uuid, 4 FROM generate_series(1, ${pages}) i`, [source]);
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source)
+ SELECT p.id, c, $1 || ' ' || p.id || '-' || c, 'compiled_truth' FROM pages p CROSS JOIN generate_series(0, ${chunksPerPage - 1}) c
+ WHERE p.slug LIKE '${slugPrefix}%'`, [body]);
+}
+
+describe.skipIf(!RUN)('CJK keyword arm on Postgres', () => {
+ beforeAll(async () => {
+ engine = await setupDB();
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('cjk-a', 'cjk-a'), ('cjk-b', 'cjk-b') ON CONFLICT DO NOTHING`);
+ await seed('cjk-b', 'cjkb/seats-', 1, 1, '团队版的席位数量由管理员配置。');
+ await seed('cjk-b', 'cjkb/upgrade-', 1, 1, '升级到专业版后可以使用更多功能。');
+ await seed('cjk-a', 'cjka/p-', 20_000, 8, `${'팀 좌석을 업그레이드하는 방법과 좌석 수 관리, '.repeat(10)}`);
+ await engine.executeRaw('ANALYZE content_chunks');
+ }, 600_000);
+ afterAll(async () => { await teardownDB(); }, 120_000);
+
+ test('OR fallback: terms in different documents found only with the hybrid flag; direct callers keep strict AND', async () => {
+ expect(await engine.searchKeyword('席位 升级', { sourceId: 'cjk-b' })).toEqual([]);
+ const rows = await engine.searchKeyword('席位 升级', { sourceId: 'cjk-b', orFallback: true });
+ expect(rows.map((r) => r.slug).sort()).toEqual(['cjkb/seats-1', 'cjkb/upgrade-1']);
+ });
+
+ test('a full scoring that times out rolls back; the capped retry, in a fresh transaction, serves in-scope rows and the engine stays usable', async () => {
+ const metas: CjkKeywordMeta[] = [];
+ const started = performance.now();
+ const rows = await engine.searchKeyword('좌석 업그레이드', { sourceId: 'cjk-a', orFallback: true, limit: 20,
+ cjkKeyword: { deadlineMs: 900, onMeta: (m) => metas.push(m) } });
+ const elapsed = performance.now() - started;
+ expect(metas).toHaveLength(1);
+ expect(metas[0]).toMatchObject({ incomplete: true, reason: 'timeout', capped: true });
+ expect(elapsed).toBeLessThan(2_000);
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.every((r) => r.source_id === 'cjk-a')).toBe(true);
+ const after = await engine.searchKeyword('席位', { sourceId: 'cjk-b' });
+ expect(after.map((r) => r.slug)).toEqual(['cjkb/seats-1']);
+ }, 60_000);
+
+ test('a retry that also runs out of time returns no keyword rows with the degraded reason, never an error', async () => {
+ const metas: CjkKeywordMeta[] = [];
+ const rows = await engine.searchKeyword('좌석 업그레이드', { sourceId: 'cjk-a', orFallback: true,
+ cjkKeyword: { deadlineMs: 80, onMeta: (m) => metas.push(m) } });
+ expect(rows).toEqual([]);
+ expect(metas[0]).toMatchObject({ incomplete: true, reason: 'timeout' });
+ expect((await engine.searchKeyword('升级', { sourceId: 'cjk-b' })).map((r) => r.slug)).toEqual(['cjkb/upgrade-1']);
+ }, 60_000);
+});