Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): reindex-search-vector rebuilds page vectors with the seal's expression (#6374)
time-attack01d69bd2f949
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 7e98b6d654..752023dc5e 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -18,6 +18,7 @@ src/commands/migrations/v0_32_2.ts 2 coordinator On a managed brain each entitysrc/commands/pages.ts 2 engine_guard Both engine references are dry-run previews (the --dry-run listing and the D6 consent count before a hard purge, #6114); the purge runs purgeDeletedPagesCoordinated, which is coordinated on managed brains.src/commands/reconcile-links.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/commands/reindex-aliases.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.+src/commands/reindex-search-vector.ts 2 projection reindex-search-vector rewrites only pages.search_vector, through the seal's pageSearchVectorSql over the sanitized timeline and guarded by the knowledge revision it read (its read is an UPDATE-to-self of id); canonical fields are untouched and the managed writer guard passes search_vector-only updates.src/commands/sources-set-path.ts 1 coordinator Managed rebind uses native exclusion, exact manifest verification and a retained source-incarnation receipt; unmanaged pointer repair remains explicit.src/commands/sources.ts 10 coordinator Managed add/archive/restore/remove/purge/reclone route through source lifecycle; remaining legacy canonical SQL stays fenced.src/commands/sync/deletes.ts 1 coordinator Managed Markdown sync routes to immutable page requests and an exhausted-cursor checkpoint; unsupported Git pull, code/image and connector paths refuse early. (Refactor wave 1: moved from src/commands/sync.ts.)diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 2b3e0986f3..b3b7dac0ca 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-vectors.ts` — `gbrain reindex --vectors [--dry-run] [--json]` (dispatched from cli.ts beside `--aliases`). Lists every HNSW index in the current schema from `pg_indexes` and runs `REINDEX INDEX` on each (`REINDEX INDEX CONCURRENTLY` on Postgres), rebuilding the ANN index from stored vectors with no re-embedding; each rebuild runs inside `withHnswBuildMemory` (vector-index.ts), which sizes PGLite's `maintenance_work_mem` to the graph or refuses with `pglite_vector_index_too_large`. The PGLite WAL-repair notice (`buildWalRepairNotice`) and `gbrain pglite-repair` name it, because a WAL reset does not rebuild indexes (#4616). Tests: `test/embedding-zero-norm-4616.serial.test.ts` on both engines.-- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.+- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` and `content_chunks` in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000). Pages: an UPDATE-to-self of `id` reads each batch (`RETURNING id, timeline, knowledge_revision`; row locks only for that statement), the timeline is sanitized with `sanitizeRemoteBody` as the seal does, and one `UPDATE … FROM unnest(…)` writes `search_vector` through `pageSearchVectorSql` (the seal's own expression), guarded by the revision read, so a page edited in between is skipped (its seal reindexes it) and private, withdrawn, takes or malformed fence text never enters the vector. Chunks: direct vector recompute via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`. Both stream phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts` and `test/reindex-search-vector-pages.serial.test.ts`.- `src/commands/init-mode-picker.ts` — install-time mode recommendation, downstream-input cost matrix, and mandatory operator choice. Mode summaries describe payload knobs only. Expansion follows the command (`query` on unless opted out; `search` and memory verbs off), not the chosen mode; provider charges and downstream prompt caching are disclosed separately from GBrain result caching.diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex ffa6d562fc..c9bc604d91 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -53,7 +53,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.-- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).+- `src/core/page-state/projections.ts` — `pageSearchVectorSql` is the one page keyword-vector expression (title weight A, sanitized timeline weight C) used by `sealPageTextProjection`, `sealImportedPage` and `reindex-search-vector`. Captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 223dc235ce..4f031d86f6 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -298,6 +298,7 @@ test/reconcile-owner-journey.serial.test.ts global-state global-state: R3: consttest/reindex-code-max-cost.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gatewaytest/reindex-code-model-source.serial.test.ts R1 R1: mutates process.env (GBRAIN_NO_CODE_MODEL_NUDGE)test/reindex-code-nudge.serial.test.ts R1 R1: mutates process.env (GBRAIN_NO_CODE_MODEL_NUDGE)+test/reindex-search-vector-pages.serial.test.ts R1 R1: mutates process.env (bracket or computed key)test/reindex-search-vector.serial.test.ts R1 R1: mutates process.env (bracket or computed key)test/reindex-trace-transparency.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnecttest/remediation-run-extras.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the processdiff --git a/src/commands/reindex-search-vector.ts b/src/commands/reindex-search-vector.tsindex 73023a02a6..8c8d5539b3 100644--- a/src/commands/reindex-search-vector.ts+++ b/src/commands/reindex-search-vector.ts@@ -51,6 +51,8 @@ import { checkpointKey } from '../core/backfill-base.ts';import { consentGate } from '../core/consent-cli.ts';import type { ConsentEnv } from '../core/consent.ts';import { createProgress } from '../core/progress.ts';+import { pageSearchVectorSql } from '../core/page-state/projections.ts';+import { sanitizeRemoteBody } from '../core/remote-body.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';export interface ReindexSearchVectorOpts {@@ -93,7 +95,7 @@ const CHECKPOINT_NAME = { pages: 'fts_pages', content_chunks: 'fts_content_chunk*/async function batchedBackfill(engine: BrainEngine,- table: 'pages' | 'content_chunks',+ table: 'content_chunks',setClause: string,tick: (n: number) => void): Promise<void> {@@ -119,6 +121,45 @@ async function batchedBackfill(}}+/**+ * #6374: page vectors rebuilt with the seal's own expression. The pages+ * trigger fires only on `UPDATE OF title,timeline` and indexes the RAW+ * timeline, so neither an UPDATE-to-self nor re-firing it is right. Each batch+ * reads its rows through an UPDATE-to-self (row locks held for that statement+ * only, never across the TypeScript sanitize), sanitizes the timeline exactly+ * as the seal does, then writes `search_vector` guarded by the knowledge+ * revision it read: a page edited in between is skipped, and its own seal+ * indexes it under the new trigger language. The cursor is persisted after+ * every batch, as for chunks.+ */+async function backfillPageVectors(engine: BrainEngine, lang: string, tick: (n: number) => void): Promise<void> {+ const key = checkpointKey(CHECKPOINT_NAME.pages);+ const saved = Number(await engine.getConfig(key));+ let cursor = Number.isFinite(saved) && saved > 0 ? saved : 0;+ for (;;) {+ const rows = await engine.executeRaw<{ id: number; timeline: string | null; knowledge_revision: string }>(`+ UPDATE pages SET id = id+ WHERE id IN (+ SELECT id FROM pages+ WHERE search_vector IS NOT NULL AND id > ${cursor}+ ORDER BY id+ LIMIT ${BACKFILL_BATCH_SIZE}+ )+ RETURNING id, timeline, knowledge_revision::text AS knowledge_revision+ `);+ if (rows.length === 0) break;+ await engine.executeRaw(`+ UPDATE pages p SET search_vector = ${pageSearchVectorSql('p.title', 'v.timeline', lang)}+ FROM unnest($1::int[], $2::text[], $3::uuid[]) AS v(id, timeline, revision)+ WHERE p.id = v.id AND p.knowledge_revision = v.revision+ `, [rows.map(r => Number(r.id)), rows.map(r => sanitizeRemoteBody(r.timeline ?? '')), rows.map(r => r.knowledge_revision)]);+ tick(rows.length);+ cursor = rows.reduce((m, r) => Math.max(m, Number(r.id)), cursor);+ await engine.setConfig(key, String(cursor));+ if (rows.length < BACKFILL_BATCH_SIZE) break;+ }+}+/*** Programmatic entrypoint — takes a typed opts object. Used by tests and* future internal callers. The CLI wrapper is `runReindexSearchVectorCli`@@ -255,11 +296,11 @@ export async function runReindexSearchVector(const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));- // Backfill: UPDATE-to-self forces the pages trigger to re-fire- // (Postgres re-fires on UPDATE-to-same-value); content_chunks gets a- // direct vector compute since the column itself is what we want.+ // Backfill: pages through the seal's expression over the sanitized+ // timeline (backfillPageVectors); content_chunks gets a direct vector+ // compute since the column itself is what we want.progress.start('reindex_search_vector.pages', pagesCount);- await batchedBackfill(engine, 'pages', 'id = id', n => progress.tick(n));+ await backfillPageVectors(engine, lang, n => progress.tick(n));progress.finish();progress.start('reindex_search_vector.chunks', chunksCount);diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 2434b84852..143c685134 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -17,6 +17,17 @@ import { belowSafeChunkFence } from '../search/safe-chunks.ts';import { acceptedEmbeddingInputHashes, embeddingInputHash, plainEmbeddingTier, synopsisBodyHash,type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';+/**+ * The page keyword vector every sealed writer stores: the title (weight A) and+ * the SANITIZED timeline (weight C, bound by the caller; never the raw column,+ * which can hold private or withdrawn fence text). `title` and `timeline` are+ * SQL expressions. Shared by the seal, the import seal and+ * `reindex-search-vector`, so the three cannot drift.+ */+export function pageSearchVectorSql(title: string, timeline: string, lang: string = getFtsLanguage()): string {+ return `setweight(to_tsvector('${lang}',COALESCE(${title},'')),'A') || setweight(to_tsvector('${lang}',${timeline}::text),'C')`;+}+/*** Complete the searchable snapshot only after its sanitized chunks are installed.* `guarded` is this transaction's own read of the page under its guard, when@@ -26,8 +37,7 @@ export async function sealPageTextProjection(engine: BrainEngine, slug: string,const current = guarded ?? await engine.readPageSnapshot(slug, { sourceId });if (!current) return;await engine.executeRaw(`UPDATE pages SET text_projection_revision=knowledge_revision,- search_vector=setweight(to_tsvector('${getFtsLanguage()}',COALESCE(title,'')),'A') ||- setweight(to_tsvector('${getFtsLanguage()}',$3::text),'C')+ search_vector=${pageSearchVectorSql('title', '$3')}WHERE source_id=$1 AND slug=$2 AND knowledge_revision=$4::uuid`,[sourceId, slug, sanitizeRemoteBody(current.page.timeline), current.revision]);}@@ -42,8 +52,7 @@ export async function sealImportedPage(engine: BrainEngine, slug: string, sourcechunkerSeal: number, pageId?: number): Promise<void> {const rows = await engine.executeRaw<{ id: number }>(`UPDATE pages SET chunker_version=$5,text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END,- search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('${getFtsLanguage()}',COALESCE(title,'')),'A') ||- setweight(to_tsvector('${getFtsLanguage()}',$3::text),'C') ELSE search_vector END+ search_vector=CASE WHEN knowledge_revision=$4::uuid THEN ${pageSearchVectorSql('title', '$3')} ELSE search_vector ENDWHERE source_id=$1 AND slug=$2 RETURNING id`,[sourceId, slug, live ? sanitizeRemoteBody(live.page.timeline) : '', live?.revision ?? null, chunkerSeal]);if (rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);diff --git a/test/reindex-search-vector-pages.serial.test.ts b/test/reindex-search-vector-pages.serial.test.tsnew file mode 100644index 0000000000..02852d81b1--- /dev/null+++ b/test/reindex-search-vector-pages.serial.test.ts@@ -0,0 +1,124 @@+/**+ * #6374: `gbrain reindex-search-vector` rebuilds PAGE keyword vectors.+ *+ * Protects: after a language change every existing page is retokenized in the+ * new language, through the seal's own expression over the sanitized timeline,+ * so private, withdrawn and takes fence text (and a malformed fence) never+ * enter the page vector. A page edited between the batch read and its write is+ * skipped (its own seal indexes it), and a failed batch keeps the in-progress+ * marker so the run resumes. Fails on the tree before the fix: the backfill+ * was `UPDATE pages SET id = id`, which never fires the+ * `UPDATE OF title,timeline` trigger, so pages kept their old-language stems.+ *+ * SERIAL: mutates GBRAIN_FTS_LANGUAGE.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runReindexSearchVector } from '../src/commands/reindex-search-vector.ts';+import { resetFtsLanguageCache, FTS_REINDEX_MARKER_KEY } from '../src/core/fts-language.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, renderFactsTable } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++const ENV_KEY = 'GBRAIN_FTS_LANGUAGE';+const saved = process.env[ENV_KEY];+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine?.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ delete process.env[ENV_KEY];+ resetFtsLanguageCache();+});+afterEach(() => {+ if (saved === undefined) delete process.env[ENV_KEY]; else process.env[ENV_KEY] = saved;+ resetFtsLanguageCache();+});++async function page(slug: string, title: string, timeline = ''): Promise<void> {+ await engine.putPage(slug, { type: 'note', title, compiled_truth: 'body', timeline, frontmatter: {} });+}+async function vector(slug: string): Promise<string> {+ const [row] = await engine.executeRaw<{ v: string }>(`SELECT search_vector::text AS v FROM pages WHERE slug=$1`, [slug]);+ return row!.v;+}+async function reindex(lang: string) {+ process.env[ENV_KEY] = lang;+ resetFtsLanguageCache();+ return runReindexSearchVector(engine, { yes: true, json: true });+}++describe('reindex-search-vector page vectors (#6374)', () => {+ test('an existing page is retokenized in the new language', async () => {+ await page('notes/runners', 'Running runners');+ expect(await vector('notes/runners')).toContain("'run'");+ await reindex('simple');+ const v = await vector('notes/runners');+ expect(v).toContain("'running'");+ expect(v).toContain("'runners'");+ expect(v).not.toContain("'run':");+ });++ test('private, withdrawn, takes and malformed fence text never enters the page vector', async () => {+ const facts = renderFactsTable([+ { rowNum: 1, claim: 'worldcanary fact', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: 'privatecanary fact', kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+ { rowNum: 3, claim: 'withdrawncanary fact', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: false, forgotten: true, context: 'forgotten: user asked' },+ ]);+ expect(facts).toContain(FACTS_FENCE_BEGIN);+ expect(facts).toContain(FACTS_FENCE_END);+ const takes = `${TAKES_FENCE_BEGIN}\n| # | claim |\n|---|---|\n| 1 | takescanary |\n${TAKES_FENCE_END}`;+ const timeline = `- 2026-10-01 publiccanary meeting\n${facts}\n${takes}\n${FACTS_FENCE_BEGIN}\nmalformedcanary never closed`;+ await page('notes/fenced', 'Fenced page', timeline);+ await reindex('simple');+ const v = await vector('notes/fenced');+ expect(v).toContain("'publiccanary'");+ expect(v).toContain("'worldcanary'");+ for (const hidden of ['privatecanary', 'withdrawncanary', 'takescanary', 'malformedcanary']) expect(v).not.toContain(hidden);+ });++ test('a page edited between the batch read and its write is skipped, not overwritten', async () => {+ await page('notes/a', 'Running alpha');+ await page('notes/b', 'Running beta');+ const real = engine.executeRaw.bind(engine);+ const spy = spyOn(engine, 'executeRaw').mockImplementation((async (sql: string, params?: unknown[]) => {+ const out = await real(sql, params);+ if (/UPDATE pages SET id = id/.test(sql)) {+ // A concurrent edit lands after the batch read: the trigger reindexes it under the new trigger language.+ await real(`UPDATE pages SET timeline='- 2026-10-02 walking' WHERE slug='notes/b'`);+ }+ return out;+ }) as typeof engine.executeRaw);+ try {+ await reindex('simple');+ } finally {+ spy.mockRestore();+ }+ expect(await vector('notes/a')).toContain("'running'");+ // The edit's own timeline survives: the batch's write, built from the timeline it read, skipped this page.+ expect(await vector('notes/b')).toContain("'walking'");+ });++ test('a failed page batch keeps the marker; the rerun resumes and completes', async () => {+ await page('notes/runners', 'Running runners');+ const real = engine.executeRaw.bind(engine);+ const spy = spyOn(engine, 'executeRaw').mockImplementation((async (sql: string, params?: unknown[]) => {+ if (/unnest\(\$1::int\[\]/.test(sql)) throw new Error('injected batch failure');+ return real(sql, params);+ }) as typeof engine.executeRaw);+ try {+ await expect(reindex('simple')).rejects.toThrow('injected batch failure');+ } finally {+ spy.mockRestore();+ }+ expect(await engine.getConfig(FTS_REINDEX_MARKER_KEY)).toBe('simple');+ await reindex('simple');+ expect(await engine.getConfig(FTS_REINDEX_MARKER_KEY)).toBeNull();+ expect(await vector('notes/runners')).toContain("'running'");+ });+});