Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.51.7.0 fix(search): restore retrieval and projection reliability (#5252 wave) (#5298)

Garry Tan44f96edf7f49
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 1cddc3fcc0..751372cb46 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 36f18a83a1..5055f9f90b 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.gitattributes b/.gitattributes
index e5b5691048..50bf6b1eb4 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -35,3 +35,4 @@ native/locks/prebuilds/*.node binary
# Preserve the vendored upstream license byte-for-byte, including indentation.
native/locks/vendor/node-v22.15.0/LICENSE -whitespace
scripts/native/** text eol=lf
+src/core/chunkers/symbol-resolver.ts diff
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 683ecb65a0..8fdd6f67a0 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -63,7 +63,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
# This job runs bare `bun test` (not run-e2e.sh), so the snapshot must
# be activated here or the restored tar is never read (the engine gates
@@ -176,7 +176,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- name: Run frozen E2E partition
shell: bash
@@ -230,7 +230,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
# Bare `bun test` job — activate the restored snapshot (see jsonb-parity).
- name: Ensure PGLite snapshot (build-or-validate, non-fatal)
@@ -359,7 +359,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
# Bare `bun test` job — activate the restored snapshot (see jsonb-parity).
- name: Ensure PGLite snapshot (build-or-validate, non-fatal)
@@ -539,7 +539,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- name: Full e2e glob with coverage (all files, incl. engine-parity)
# run-e2e.sh redirects HOME, so COVERAGE_DIR must be absolute; its
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index e36b09749e..89a37ebfb4 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -149,7 +149,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- run: bun run verify
# Guard: no bare `bun test` in workflows/scripts — bun ignores
@@ -199,7 +199,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- run: bun run test:serial
env:
@@ -261,7 +261,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- name: Ensure PGLite snapshot (build-or-validate, non-fatal)
run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-eval && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'
@@ -306,13 +306,13 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
with:
path: |
test/fixtures/pglite-snapshot-default.tar
test/fixtures/pglite-snapshot-default.version
- key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- name: Ensure PGLite snapshot (build-or-validate, non-fatal)
# Absolutized: this file's batch jobs spawn CLI children with varying
@@ -376,7 +376,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot-default.tar
test/fixtures/pglite-snapshot-default.version
- key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- run: bash scripts/ci-brainbench-gate.sh
env:
@@ -413,7 +413,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- name: Ensure PGLite snapshot (build-or-validate, non-fatal)
run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-perf && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'
@@ -496,7 +496,7 @@ jobs:
path: |
test/fixtures/pglite-snapshot.tar
test/fixtures/pglite-snapshot.version
- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'src/core/pglite-engine.ts', 'src/core/fts-language.ts', 'src/core/vector-index.ts', 'src/core/search/projection-statistics.ts', 'src/core/ai/defaults.ts', 'src/core/timeline-dedup-repair.ts', 'src/core/pages-upsert-arbiter.ts', 'src/core/link-extraction.ts', 'src/core/grants/*.ts', 'src/core/scope.ts', 'src/core/sql-query.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/page-state/schema.ts', 'src/core/lease-schema.ts', 'src/core/page-state/projection-schema.ts', 'src/core/persistence/schema.ts', 'src/core/persistence/effect-schema.ts', 'src/core/persistence/writer-guard-schema.ts', 'src/core/persistence/topology-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}
- run: bun install --frozen-lockfile
- name: Run test shard ${{ matrix.shard }}/10
shell: bash
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 93e9ad7d3c..0bf223bb8c 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.51.6.0 -->
+<!-- gbrain-runbook-stamp: 0.51.7.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0ef989c6b0..adacf23de3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,46 @@
All notable changes to GBrain will be documented in this file.
+## [0.51.7.0] - 2026-09-21
+
+**Search can find your pages without quietly mistaking an unfinished index for an empty brain.** Large brains no longer rely on a misleading estimate that made vector search scan every chunk. Filtered searches can look beyond their first batch of candidates, and they tell you when their work limit still leaves the answer incomplete. Keyword results stay stable between repeated requests and adjacent pages.
+
+Code and Markdown recovery now use the same guarded preparation as normal indexing. Code metadata can be repaired while the resident writer owns the database, without changing your original files or paying to embed them again. Existing vectors survive only when their content and model provenance still match. Search and doctor distinguish pending projections from a genuine miss, even when some results are already available.
+
+**Say to your agent:** *"Check whether my search index is ready, and repair code metadata without spending on embeddings."*
+
+### How to use it
+
+Upgrade normally, then run `gbrain doctor`. Keep the upgraded resident `gbrain serve` running to drain queued projection rebuilds. For code metadata repair, use `gbrain reindex-code --force --no-embed`; use `--source <id>` to restrict the work. Authorize `gbrain embed --stale` separately if vectors are still missing.
+
+| Situation | What you can now see |
+|---|---|
+| A filtered vector scan reaches its work limit | `vector_candidates_incomplete`, not a false clean miss. |
+| Some visible pages still need a current text projection | `projection_pending`, including alongside nonempty results. |
+| The readiness probe cannot run | `projection_status_unknown`, rather than an unsupported claim that everything is ready. |
+| A query starts or ends at an exact date boundary | Inclusive public bounds, including the final microseconds of a date-only upper bound. |
+
+### Things to watch
+
+HNSW remains approximate. Postgres can use a server-cancelled exact fallback within its remaining search budget; PGLite reports an unresolved shortfall rather than pretending a timer stopped its database work. A text-ready page may still need embeddings. CLI JSON keeps its result-array format and sends incompleteness notices to stderr; MCP exposes retrieval metadata in its response envelope.
+
+## To take advantage of v0.51.7.0
+
+`gbrain upgrade` should apply the schema changes automatically. If schema maintenance failed, run `gbrain apply-migrations --yes` with an authorized database maintenance role, then run `gbrain doctor`. Statistics hidden by row-security policy are not treated as absent. Your agent can follow `skills/migrations/v0.51.7.0.md`; no global planner settings, vector-index rebuild, provider change or automatic embedding spend is required.
+
+### Itemized changes
+
+- Schema migrations 160 and 161 add verified current-projection expression statistics and the pending-projection lookup index. Bulk import, sync, reindex and drained recovery refresh statistics outside page locks.
+- Both engines separate candidate, iterative-scan and pagination limits; preserve scope and visibility filters; and surface incomplete candidate pools through hybrid search, CLI and MCP.
+- Postgres relaxed keyword retries prefer index access locally. Keyword candidate and result ordering are deterministic; caseless CJK terms use LIKE while case-sensitive alphabets retain ILIKE.
+- Public `since`/`until` comparisons preserve inclusivity and timestamp precision. Independent atoms no longer receive transcript-session demotions.
+- Managed-safe code reindexing and shared Markdown/code preparation preserve fenced metadata, valid vectors and incoming graph edges; rebuilt outgoing edges become eligible for resolution again. Resolver batches and projection replacement share ordered guards, so a concurrent old resolver cannot certify new edges. Code reads enforce current live projections, and recursive operations do not reuse stale traversal caches.
+- Contributed by @time-attack (#5126, keyword ordering), @morven-ai (#5169, CJK operator selection), @Laochaleun (#5245, Markdown projection preparation), and @tarush1989 (#5085, atom diversification). Thanks to the issue reporters for the planner and retrieval reproductions.
+
+### For contributors
+
+- Required PgBouncer execution checks no longer misclassify passing output when the summary reader exits early. Native-lock contention fixtures wait for setup ownership before asserting write exclusion, without changing the contention assertions.
+
## [0.51.6.0] - 2026-09-21
**A temporary brain gets one safe second chance to start.**
diff --git a/README.md b/README.md
index 69c2da3ed8..d01cf13905 100644
--- a/README.md
+++ b/README.md
@@ -250,6 +250,11 @@ gbrain think "who's working on AI agents at portfolio companies?"
**`gbrain search`** returns the top retrieved pages, ranked by hybrid scoring (vector + keyword + RRF + source-tier boost + reranker). Use it when you want raw material to skim: agent context windows, citation lookups, finding a specific quote.
+Search also tells you when its results are incomplete because projections are
+still rebuilding or a bounded vector scan ran short. Ask your agent *"Check
+whether my search index is ready"*; see [search readiness and recovery](docs/architecture/RETRIEVAL.md#chunk-rebuilds-after-upgrading)
+before treating an empty result as proof that a page is missing.
+
**`gbrain think`** runs the same retrieval, then composes a synthesized answer across the results with explicit citations to the source pages AND an honest note on what the brain doesn't know yet. The gap analysis is the differentiator: the answer tells you when a page is stale, when a claim is uncited, when two pages contradict each other, when there's a hole you should fill.
**Say to your agent:** *"What do we know about acme-example?"* — *"Tell me about alice-example before my meeting tomorrow"* — *"Search for who's working on AI agents."* Your agent routes these to the brain automatically; you never type the commands yourself.
diff --git a/TODOS.md b/TODOS.md
index ac9a80a5fe..72696b6800 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -303,7 +303,8 @@
retrieval-gate path were deferred. Triage records (verdict, evidence, fix
sketch, key files per issue) live in the wave workspace
`.context/wave/triage/issue/` + `.context/wave/refute/issue/` (gitignored
- wave working state, not repo content). Deferred: #4381 #4576 #4578 #4603 #4616 #4622 #4649 #4772 #4921 (of the 0.48.5.0 wave's 26 deferrals, 17 shipped in 0.48.6.0: #4558 #4586 #4588 #4600 #4605 #4613 #4653 #4670 #4684 #4741 #4761 #4766 #4795 #4797 #4852 #4879 #4910).
+ wave working state, not repo content). Deferred: #4381 #4576 #4578 #4616 #4622 #4649 #4772 #4921 (of the 0.48.5.0 wave's 26 deferrals, 17 shipped in 0.48.6.0: #4558 #4586 #4588 #4600 #4605 #4613 #4653 #4670 #4684 #4741 #4761 #4766 #4795 #4797 #4852 #4879 #4910).
+ #4603 is completed by the v0.51.7.0 search reliability wave.
Of the 0.48.1.0 wave's 27 deferrals, ten shipped in 0.48.5.0 (#4744 via
#4933, #4729 via #4865, #4728, #4696, #4652, #4620, #4606, #4597, #4589,
#4563), five were re-classified on verification (#4738 and #4732
diff --git a/VERSION b/VERSION
index 24e4a0a339..36d0154631 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.51.6.0
+0.51.7.0
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index c7355f9338..06c0a03a39 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -104,6 +104,17 @@ RRF fusion, multi-query expansion, and 4-layer dedup are engine-agnostic. They o
**Hosting:** Supabase Pro ($25/mo, zero-ops, pgvector built in) is the managed path; self-hosted Postgres + pgvector (Docker or Homebrew — see the "Local Postgres" section below) works the same.
+Current-projection filters use `(text_projection_revision = knowledge_revision)
+IS TRUE` with matching expression statistics, rather than relying on the
+planner's fixed column-equality estimate. Migration 160 creates and collects
+those statistics; bulk import, sync, reindex and completed projection recovery
+refresh them outside page locks. This also matters on PGLite, where an empty
+initial schema sample cannot describe later imports. Maintenance needs an
+authorized database role; an RLS-hidden statistics view is not evidence that
+the object is absent. Highly selective queries may correctly choose an exact
+plan. The [retrieval guide](architecture/RETRIEVAL.md#named-thing-retrieval-per-page-pool--title--alias--evidence)
+describes bounded candidate recovery and incomplete-result metadata.
+
### Opt-in RLS source-scope binding (`GBRAIN_RLS_SCOPE_BINDING`)
Defense-in-depth layer for Postgres deployments that want the database itself
@@ -493,7 +504,7 @@ Every method in `BrainEngine`. The full interface. No optional methods, no featu
|-----------|---------------|-------------|-------|
| CRUD | Full | Full | Same SQL |
| Keyword search | tsvector + ts_rank | tsvector + ts_rank | Identical (real Postgres) |
-| Vector search | pgvector HNSW | pgvector HNSW | Identical (real Postgres) |
+| Vector search | pgvector HNSW | pgvector HNSW | Same operators; bounded fallback/cancellation differs |
| Fuzzy slug | pg_trgm | pg_trgm | Identical (real Postgres) |
| Graph traversal | Recursive CTE | Recursive CTE | Same SQL |
| Transactions | Full ACID | Full ACID | Both support this |
diff --git a/docs/TESTING.md b/docs/TESTING.md
index c74e9eebbb..ae99b3782d 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -3,6 +3,20 @@
On-demand reference (see CLAUDE.md Reference map). Current behavior + invariants
only.
+Search reliability has real-planner and transport regressions in
+`test/e2e/vector-candidate-safety-postgres.test.ts`,
+`test/e2e/search-query-contract-postgres.test.ts`,
+`test/e2e/projection-statistics-postgres.test.ts`, and
+`test/e2e/search-readiness-http.test.ts`. The statistics tests include owner,
+restricted-reader and FORCE-RLS roles; the candidate tests distinguish natural
+plans from forced-HNSW controls and prove server cancellation of exact fallback.
+`test/e2e/projection-recovery-parity.test.ts` runs the shared Markdown/code
+recovery, graph-edge preservation and migration-origin contracts against both
+engines. PGLite work caps never count a Promise race as cancellation evidence.
+The recovery parity entry also runs `symbol-resolver-projection-race.test.ts`:
+paused resolver/rebuild ordering, atomic rollback, candidate revalidation, and
+a real PostgreSQL lock-wait receipt before releasing the competing writer.
+
`test/pglite-in-memory-create-retry.serial.test.ts` injects create failures while
using real PGLite instances and a validated schema snapshot. It pins one cold
retry only before an in-memory database has opened, both failure diagnostics,
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index cd3cce3e0d..4b3fb911f4 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -20,7 +20,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `scripts/persistence/{harness,schedules,worker,validate,failure-diagnostics}.ts` — executable concurrency gate using real journal/coordinator APIs: 1,000 seeded schedules per engine, eight actual process-kill publication boundaries, and 10,000 writes from four producer processes. Each phase owns a temporary disk PGLite datastore or a fresh test Postgres database. Independent accounting queries verify conservation; every soak receipt is compared to its canonical snapshot and file. JSON manifests separate actual counts and latency measurements from the configured Linux/Bun CI matrix. Failed runs preserve private fixtures and collect bounded, allowlisted request/queue/owner diagnostics without changing deadlines or hiding the original error. Cleanup commands read the existing test URL from the environment. The PGLite loopback endpoint is a fixture transport, not production authentication coverage. Contract and commands: `scripts/persistence/README.md`; smoke entries: `test/persistence-chaos.slow.test.ts`, `test/e2e/persistence-chaos.test.ts`; diagnostic/retention contracts: `test/persistence-failure-diagnostics.test.ts`.
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
-- `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` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry).
+- `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` (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. Recovery handles both page kinds, preserves only exact model/hash/metadata-compatible vectors, 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.
- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five paths against the real contextual service on PGLite and isolated Postgres.
- `src/core/contextual-retrieval-service.ts` — captures the complete originating projection before synopsis/embedding providers, then installs vectors with UPDATE-only CAS and stamps mode/generation in the same guarded transaction. Stored corpus generation participates in `page-state/projections.ts` indexing context even when the mode and canonical revision stay unchanged. New vectors receive the captured provider model; text, chunk identity, metadata and retrieval seal remain intact. Source contextual policy is rechecked before publication. Superseded preparation returns the existing retryable database result. Empty/disabled-mode stamps compare identity, seal, context and raw chunk inventory under the guard; unsealed nonempty chunks never reach a provider. `test/embedding-completion-atomic.serial.test.ts` covers real service/edit/rechunk/context interleavings and ordinary retrieval on both engines.
- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.
@@ -62,17 +62,21 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`.
- `src/core/ops/raw-data.ts` — `put_raw_data` / `get_raw_data`. `get_raw_data` follows the page soft-delete (a tombstoned page reads as `[]`, `restore_page` brings the rows back; there is no remote `include_deleted` param — `get_page include_deleted: true` verifies the tombstone) and, per #4352, a `visibility: private` page's raw data reads exactly like a missing page's for untrusted callers. Scope comes from `readPolicyOpts(ctx)`, never from MCP parameters.
- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_versions` filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, partial, wedged, skipped_future}` block stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read).
-- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's result is empty and `hasUnsealedPagesInScope` finds markdown pages in scope below the safe-chunk index version (sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by `pages_chunker_version_idx` as an Index Cond — NOT the COALESCE `safeChunksFilter` form, which the partial btree cannot serve and which walked every markdown page on a sealed brain; pinned by `test/search-safe-index-probe.test.ts`; fail-open; ignores the call's `types`/`excludePrivate`), it appends the `safe_index_pending` degraded stage so the MCP empty-result block names the pending `gbrain reindex --markdown` instead of a clean miss; the withholding itself is unchanged.
+- `src/core/ops/search.ts` — the search-domain op module (`search`, `query`, `search_stats`, `search_modes`, `search_tune`, `cache_stats`). `query` is the hybrid entry (`hybridSearchCached`) plus two non-hybrid legs that share ONE effective-row-contract helper, `resolveEffectiveLimit(ctx, p)`: an explicit `limit` wins, otherwise the mode-derived `searchLimit` resolved through the same trust-gated chain `hybridSearch` uses (`resolvePerCallMode` ignores a remote caller's `mode`, so a remote client cannot select the tokenmax row count); the config reads run lazily on those paths only. The legs: the image-similarity branch (`embedding_image` vector search, `test/query-image-mode-limit.serial.test.ts`) and the CRAG escalation slice — when `search.crag_escalation` is on and `shouldEscalateRetrieval` (`src/core/search/crag.ts`) says the first pass graded `weak`, was not already escalated, AND did not already run with the caller's expansion on (`callerExpanded`), the op re-runs once at `limit: max(effectiveLimit, 50)` with expansion + relational on and autocut off, keeping the better-graded run. `buildRetrievalResponseMeta(ctx, scope, …)` is the ONE producer of the `retrieval` response-meta channel (keyword-only path included): when a remote caller's result is empty and `hasUnsealedPagesInScope` finds markdown pages in scope below the safe-chunk index version (sargable `chunker_version < SAFE_FENCE_CHUNKER_VERSION` LIMIT 1 probe served by `pages_chunker_version_idx` as an Index Cond — NOT the COALESCE `safeChunksFilter` form, which the partial btree cannot serve and which walked every markdown page on a sealed brain; pinned by `test/search-safe-index-probe.test.ts`; fail-open; retains source, private, quarantine and live-page policy), it appends the `safe_index_pending` degraded stage so the MCP empty-result block names the pending `gbrain reindex --markdown` instead of a clean miss; the withholding itself is unchanged. Empty and nonempty replies also carry projection_readiness, with projection_pending/projection_status_unknown degradation when appropriate. Vector candidate incompleteness and scoped pool details survive the public CLI/MCP serialization boundary; public type filters constrain the current-projection probe.
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput`/`TimelineBatchInput` for the bulk-insert API (`addLinksBatch`/`addTimelineEntriesBatch`). `readonly kind: 'postgres' | 'pglite'` discriminator lets `src/core/migrate.ts` and others branch without `instanceof` + dynamic imports. Methods: `batchLoadEmotionalInputs(slugs?)` (CTE-shaped read with per-table aggregates so page × N tags × M takes never produces N×M rows), `setEmotionalWeightBatch(rows)` (`UPDATE FROM unnest($1::text[],$2::text[],$3::real[])` composite-keyed on `(slug, source_id)`), `getRecentSalience(opts)`, `findAnomalies(opts)`. `PageFilters` has `sort?: 'updated_desc'|'updated_asc'|'created_desc'|'slug'` + `PAGE_SORT_SQL` whitelist consumed by both engines. `listAllPageRefs(): Promise<Array<{slug, source_id}>>` ordered by `(source_id, slug)` — cheap cross-source enumeration instead of a `getAllSlugs()→getPage(slug)` N+1 (which would silently default to `source_id='default'`); parity across postgres-engine.ts + pglite-engine.ts; Pinned by `test/e2e/multi-source-bug-class.test.ts`. `SearchOpts`+`PageFilters` add `sourceIds?: string[]` (federated read axis; both engines apply `WHERE source_id = ANY($N::text[])` when set, preserve scalar `sourceId` fast path when unset); `traverseGraph(slug, depth, opts?)` and `traversePaths(slug, opts?)` accept `opts.sourceId`/`opts.sourceIds`. `traversePathsDetailed(slug, opts?)` returns `{ paths: GraphPath[], truncated }` — the final SELECT of the path-enumerating recursive CTE is bounded at `TRAVERSE_PATH_ROW_CAP + 1` rows on both engines (the probe row signals overflow; `ORDER BY depth` means the deepest edges are dropped, so a truncated result is still the complete shallow neighbourhood; the cap counts raw rows before the in-memory edge dedup, so `paths.length` alone cannot reveal truncation) and `traversePaths` is its `.paths` projection. `resolveSlugWithAliasDetailed(slug, sourceOrSources)` returns `{ canonical_slug, source_id } | null` — the winning alias row AND its owning source under the same scope/precedence rules (`ORDER BY array_position(scope, source_id), id`; null when nothing matches or the `slug_aliases` table does not exist yet); `resolveSlugWithAlias` is its canonical-slug projection (falls back to the input slug). A consumer that goes on to read the canonical page must scope that read to `source_id`. The by-slug read methods carry the same federated axis: `getTags`/`getLinks`/`getBacklinks`/`getChunks` opts and `TimelineOpts` (consumed by `getTimeline`) accept `sourceIds?: string[]` taking precedence over the scalar `sourceId` (`source_id = ANY($::text[])` scoping the slug→page-id lookup); `getChunks` falls back to the `'default'` source when neither is set (importCodeFile's incremental-embedding reuse relies on it) and SELECTs an explicit non-vector column list — embedding vectors never ride the payload since rowToChunk discards them (`getChunksWithEmbeddings` stays scalar-only by design: engine-internal, zero remote-reachable callers); the link reads (`getLinks`/`getBacklinks`) scope ALL THREE endpoints (from/to/origin) on the federated branch while the scalar branch scopes only the near endpoint for trusted internal cross-source callers. `traverseGraph` opts has `frontierCap?: number` (per-iteration recursive-CTE cap, approx per-BFS-layer); return type `Promise<GraphNode[]>` for MCP wire stability; export `TraverseGraphOpts`; Postgres uses parenthesized `LIMIT N ORDER BY (slug, id)` inside the recursive term, PGLite mirrors with positional params; Pinned by `test/regressions/v0_36_frontier_cap.test.ts`. Phantom-redirect methods: `refreshPageBody(slug, sourceId, compiled_truth, timeline, content_hash)` narrow-UPDATEs three columns + updated_at, skipping soft-deleted rows (content_hash refresh required so `gbrain sync` sees the canonical as unchanged after fence merge); `migrateFactsToCanonical(phantomSlug, canonicalSlug, sourceId)` UPDATEs `entity_slug`+`source_markdown_slug` on every active fact row keyed on the phantom, preserving embedding/validUntil/kind/status/source_session/confidence and offsetting `row_num` past the canonical page's current MAX(row_num) (all rows incl. expired — the partial `idx_facts_fence_key` only excludes NULL; NULL stays NULL) so overlapping fence rows never collide; parity at `test/phantom-redirect-engine-parity.test.ts`. `getAdjacencyBoosts(pageIds): Promise<Map<number, AdjacencyRow>>` powers the per-query graph-signals stage — one SQL query returning inbound-link counts among top-K plus a cross-source count (links from differing `source_id`); `COALESCE(p.source_id,'default')` null safety, `HAVING >= 1`, cross-source CASE-WHEN excludes the target's own source; parity SQL across both engines; `SearchResult` gains optional `base_score`, `backlink_boost`, `salience_boost`, `recency_boost`, `exact_match_boost`, `graph_adjacency_boost`, `graph_cross_source_boost`, `session_demote_factor`, `reranker_delta` + internal staging fields; Pinned by `test/e2e/graph-signals-engine.test.ts`. Two REQUIRED methods: `deletePages(slugs, {sourceId}): Promise<string[]>` (single-batch primitive returning slugs actually deleted) and `resolveSlugsByPaths(paths, {sourceId}): Promise<Map<path,slug>>` (batch path→slug lookup); `sourceId` REQUIRED on both at the type level (asymmetric with single-row `deletePage` which keeps optional/'default'); both short-circuit on empty input and throw when `> DELETE_BATCH_SIZE`. `softDeletePages(slugs, {sourceId}): Promise<string[]>` is the batch soft-delete twin, mirroring `deletePages`' contract exactly (required `sourceId`, `> DELETE_BATCH_SIZE` throws, empty input short-circuits, caller owns chunking + decompose-to-one-element-batches on failure): one `UPDATE … SET deleted_at = now() … AND deleted_at IS NULL … RETURNING slug` round-trip returning only the slugs that actually flipped active→soft-deleted — the `deleted_at IS NULL` predicate is load-bearing so a re-run never refreshes an already-soft-deleted row's 72h purge clock — and NOTHING cascades (chunks/links/timeline stay behind the read-side `deleted_at` filters; the autopilot purge phase hard-deletes after 72h; a re-import within the window revives via `putPage`'s upsert; `deletePage`/`deletePages` remain the purge/teardown primitives). `getStats(opts?)` / `getHealth(opts?)` take an optional `{sourceId?, sourceIds?}` scope (same shape as `sourceScopeOpts` output): omitted = brain-wide; scoped = EVERY counter/coverage/degree confines to the grant, including derived-table counts via their page joins, and link-derived numbers count only edges with BOTH endpoints in scope — so an excluded source's numbers can't be recovered by subtraction. Consumer is the remote-caller ladder in `src/core/ops/admin.ts`. Embedding-signature stale-detection quartet: `countStaleChunks(opts?)` gains optional `signature?: string` widening the stale predicate from `embedding IS NULL` to ALSO include chunks whose JOINed page `embedding_signature IS NOT NULL AND <> $signature` (NULL signature is GRANDFATHERED, never counted; omit `signature` for the legacy NULL-only count); `sumStaleChunkChars(opts?: {sourceId?, signature?}): Promise<number>` = `SUM(LENGTH(chunk_text))` over stale chunks (same predicate + embed_skip filter + optional sourceId scope), used by `gbrain sync --all` cost preview via `estimateCostFromChars`; `setPageEmbeddingSignature(slug, {sourceId?, signature})` stamps `pages.embedding_signature` after a page's chunks (re)embed, idempotent no-op when page absent; `invalidateStaleSignatureEmbeddings({signature, sourceId?}): Promise<number>` NULLs `embedding`+`embedded_at` on every chunk whose page signature is set AND differs, returning the count, called BEFORE `listStaleChunks` so signature-drift pages flow through the NULL-embedding keyset cursor unchanged (NULL never invalidated). Widens `findOrphanPages(opts?: {sourceId?, sourceIds?})` (candidate-side scoping only; inbound links counted from any source). Pinned by `test/sum-stale-chunk-chars.test.ts`, `test/embedding-signature-stale.test.ts`, `test/e2e/engine-parity.test.ts`. Free-text alias layer: `resolveAliases(aliasNorms, opts?): Promise<Map<string, Array<{slug, source_id}>>>` (READ; maps each normalized alias to declaring `(slug, source_id)` pairs, source-scoped) and `setPageAliases(slug, sourceId, aliasNorms)` (WRITE; replaces the full alias set, delete-then-insert, empty clears, idempotent on the unique triple), called by the `importFromContent` ingest projection and the `reindex --aliases` backfill; parity across both engines, Pinned by `test/search/page-aliases-engine.test.ts`. `searchVector` in both engines injects the shared `buildBestPerPagePoolCte` per-page max-pool so a page surfaces on its strongest chunk. `executeRawDirect(sql, params?, opts?)` is the lock-hot-path sibling of `executeRaw`: same single-statement contract, but routes to the direct session-mode pool when dual-pool is active (Postgres/Supabase port 5432) so a long-held lock heartbeat survives the transaction pooler's per-transaction connection recycling; PGLite delegates straight to `executeRaw` (no pooler). Both engines implement it; the Minion lock path (`claim`/`renewLock`) is the consumer. `reconnect(ctx?: {error?})` is a REQUIRED lifecycle method on BOTH engines: it recovers a dropped connection using the config captured at the last `connect()`, so callers (autopilot health probe, `batchRetry`) never `disconnect()` + bare `connect()` (which loses the config and throws `database_url undefined` forever, and opens a null-connection window). PostgresEngine rebuilds its pool with a `_reconnecting` reentrancy guard and emits pool-recovery audit; PGLite is single-writer in-process so it just restores the saved data dir for parity. Plus two interface members: (1) optional `findDuplicatePage?(sourceId, {hash, frontmatterId?}): Promise<{slug, id} | null>` (identity precedence is content_hash OR frontmatter->>'id', both with `deleted_at IS NULL`); (2) `resolveSlugs(partial, opts?)` extended with `{sourceId?, sourceIds?}` so the MCP fuzzy `get_page` path scopes by source (field names match `sourceScopeOpts(ctx)` output so handlers spread directly; no opts gives the unscoped behavior). Plus a stable tiebreaker `ORDER BY score DESC, page_id ASC, chunk_id ASC` in `searchVector` in both engines: on a score tie (basis-vector eval fixtures) older `page_id` wins, so a new index on `pages` cannot flip ranking on tied scores.
- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports `TRAVERSE_PATH_ROW_CAP = 5000`, the raw-row bound on `traversePaths`/`traversePathsDetailed` (both engines `LIMIT CAP + 1`; the extra row is the truncation probe; counted before edge dedup).
- `src/core/background-work.ts` — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the engine goes away," with TWO exit points. `registerBackgroundWorkDrainer({name, order, drain(timeoutMs, mode), abort?})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle); `mode` is `'exit' | 'disconnect'` (`'exit'` = CLI teardown, engine still live, residual buffers may flush; `'disconnect'` = an engine is mid-disconnect, sinks await only IN-FLIGHT work and never start new writes). `drainAllBackgroundWorkForCliExit({timeoutMs})` runs mode `'exit'` with abort allowed; `drainBackgroundWorkBeforeDisconnect({timeoutMs})` is called by BOTH engines' `disconnect()` so an in-flight statement settles before the underlying handle closes — PGLite's `close()` deadlocks PERMANENTLY with a statement in flight — and it NEVER calls `abort()` (permanent process state, wrong for a long-lived `gbrain serve` disconnecting one engine); a partial disconnect-drain warns once per sink to stderr. The module stays a zero-import leaf on purpose (both engines import it statically). Drains in explicit `(order, name)` order — facts FIRST (order 0) so its abort-path DB `logIngest` runs against the freshest live engine — and AWAITS `abort()` only when `drain()` reports `unfinished>0` in `'exit'` mode. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. SIX sinks register at module import: `facts/queue.ts` (order 0; `abort`=`shutdown()` cancels a hung facts:absorb Haiku via internalAbort), `last-retrieved.ts` (order 1), `search/hybrid.ts` (order 2; `awaitPendingSearchCacheWrites` bounded via `Promise.race`), `eval-capture.ts` (order 3; `captureEvalCandidate` self-tracks its promise via `awaitPendingEvalCaptures`), `context/volunteer-events.ts` (order 4 — batched volunteer-event INSERTs, drained like the rest), `search/telemetry.ts` (order 5 — `awaitPendingTelemetryFlush`: awaits the in-flight flush in both modes, flushes residual buckets only in `'exit'` mode so short-lived CLI calls land in `search_telemetry` on clean exit). Every cli.ts teardown site reaches it through `finishCliTeardown` (`src/core/cli-force-exit.ts`), which drains the registry before `engine.disconnect()`, so `db.close()` cannot race an in-flight job and pin the PGLite single-writer lock. Exports `backgroundWorkSinkCount()` so the teardown helper computes its backstop deadline from the registered sink count, plus the shared teardown budgets: `MAX_TIMER_DELAY_MS` (the 2^31−1 setTimeout ceiling; `process-watchdog.ts` aliases it as `MAX_WATCHDOG_TIMER_MS`), `SINK_DRAIN_TIMEOUT_MS` (the per-sink drain bound, used as the `runDrainers` default), and `pgliteCloseTimeoutMs()` (the env-tunable in-loop close bound, defined here so `cli-force-exit`'s computed deadline budgets the SAME bound the engine honors). CLI-EXIT-ONLY: the facts `shutdown()` abort is permanent process state, never call in a long-lived `gbrain serve`. Companion changes: `src/core/ai/gateway.ts` `withDefaultTimeout(caller, ms)` bounds every outbound AI call (chat 300s, embed+multimodal 60s; env `GBRAIN_AI_{CHAT,EMBED,MULTIMODAL}_TIMEOUT_MS`; composed with caller signals via `AbortSignal.any`) and the teardown backstop honors an errored op's exit code so a hung disconnect can't mask failure as success (see `cli-force-exit.ts`); `src/core/postgres-engine.ts` `reconnect()` module-mode branch re-establishes via idempotent `db.connect()` + `connectionManager.setReadPool` refresh instead of `db.disconnect()` (no null window for concurrent ops; fail-loud on real connect failure); `src/core/search/hybrid.ts` `embedQueryBounded` + a shared `QueryEmbedDeadline` (6s, floored 2s per embed via `MIN_QUERY_EMBED_BUDGET_MS`; env `GBRAIN_QUERY_EMBED_TIMEOUT_MS`) bounds the cache-lookup AND inner query embeds so a stalled provider falls back to keyword instead of stalling the whole op. Pinned by `test/core/background-work.test.ts`, `test/search/query-embed-deadline.test.ts`, `test/eval-capture-drain.test.ts`, `test/e2e/postgres-reconnect-singleton.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts`, `test/fix-wave-structural.test.ts`.
- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.
- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks, adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults.
-- `src/core/search/safe-chunks.ts` — internal remote chunk-read policy and current safe-index version. Remote reads require a completed index built from sanitized inputs; existing chunks remain available to trusted local callers while awaiting rebuild. Both engines apply the predicate before chunk ranking and limits, independently of page-visibility opt-outs. Import seals the index only after replacing chunks in its transaction; body/chunk mutations invalidate it. Uses the existing `pages.chunker_version` column, with no schema migration.
+- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild.
+- `src/core/search/projection-statistics.ts` — current-projection expression statistics, strict migration postconditions and owner-authorized batch refresh. Migration 160 verifies object identity and populated samples before advancing the ledger, distinguishing empty tables and row-security-hidden statistics. Import, sync, reindex and drained recovery refresh outside page locks; failures preserve completed writes and give a maintenance hint. Migration 161 adds the scoped pending-projection index.
+- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Settings are restored even inside caller-owned transactions.
+- `src/core/search/date-bounds.ts` — shared public since/until normalization for text and image query paths; hybrid.ts preserves both existing exports. Exact timestamps keep their precision, date-only upper bounds use exclusive next midnight, and invalid calendar dates fail before embedding. Direct legacy afterDate/beforeDate comparisons remain strict by default.
+- `src/core/search/projection-readiness.ts` — one scoped EXISTS probe for NULL/mismatched text revisions. Excludes hidden, archived, deleted and quarantined rows; returns ready, projection_pending or unknown without identifiers or counts. Shared by search metadata, doctor and code readiness.
- `src/core/remote-body.ts` — linear protected-body sanitizer over the existing Facts parser/renderer. Processes every protected fence, retains only world Facts, removes all Takes and drops malformed protected sections. Chunk creation sanitizes full bodies before splitting. Page/history responses apply it whenever trust is not explicitly local, independently of page-visibility opt-outs and holder grants.
- `src/core/search/query-cache.ts` — stored semantic-cache data and maintenance remain, but `semanticResultCacheAvailable()` is false. `hybridSearchCached` bypasses both result lookup and writes regardless of configuration or `useCache`; request-local query embeddings still work. Search metadata, cache_stats and the mode dashboard report effective caching as disabled. Historical hit counts and search_telemetry remain intact. Restoration requires complete response-dependency provenance.
- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.
-- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard).
+- `src/core/search/graph-signals.ts` — per-query graph-signals helper. `applyGraphSignals(results, engine, opts)` runs as the 4th post-fusion stage (after backlink/salience/recency). Three boosts: `ADJACENCY_BOOST=1.05` (page linked from 2+ OTHER top-K results — local hub for THIS query), `CROSS_SOURCE_BOOST=1.10` (page linked from 2+ DIFFERENT sources — corroborated across team brains, dormant in single-source brains), `SESSION_DEMOTE=0.95` (3+ results from same chat session — keep the highest-scoring at full score, demote the rest). All three inherit the floor-ratio gate preventing weak pages from being boosted past strong ones via popularity. `computeScoreDistribution(results)` emits min/p25/p50/p75/p95/max + `reorder_band_width`. `sessionPrefix(slug)` extracts the chat-session anchor (`chat/2026-05-15-...`). Pure `pairedBootstrapPValue(deltas, resamples, rng)` exported for eval gates. Test seam via `adjacencyFn` DI. Fail-open: any error logs via `logGraphSignalsFailure` (JSONL audit via `audit-writer`) and returns the input array unchanged. Pinned by `test/search/graph-signals.test.ts` (incl. the IRON-RULE floor-gate guard). The atoms/ namespace is excluded from session diversification even when a later segment resembles a date or chat marker; daily, meeting and transcript siblings retain their existing demotion.
- `src/core/search/explain-formatter.ts` — renders `SearchResult[]` as a multi-line per-result breakdown for `gbrain search --explain`. Reads every boost-stamping field; also prints the raw query↔chunk cosine (`SearchResult.cosine`, the calibrated signal evidence keys off) next to the blended score when present — absent on keyword-only / no-embedding paths. Handles the "no boosts applied" empty path. 4-decimal precision with trailing-zero strip. `formatResultsExplain(results, meta?)` prepends header lines from the captured retrieval meta when present — `formatAutocutSummary` (the autocut decision) and `formatDegradedSummary(meta.degraded)`, which renders the closed `degraded[]` vocabulary as `degraded: reranker_skipped (no_key)` (null when the run was clean); `cli.ts:formatResult` threads `lastRetrievalMeta` into it, so a silently skipped reranker is visible from the CLI. Pinned by `test/search/explain-formatter.test.ts` + `test/cli-explain-degraded-render.test.ts`.
- `src/core/search/mode.ts` — Named search-mode bundles and retained semantic-cache key machinery; persisted result reuse remains disabled. `MODE_BUNDLES` (conservative/balanced/tokenmax) and the resolution chain (per-call `SearchOpts` → per-key `search.*` config → bundle → balanced fallback) resolve every search knob; `knobsHash` folds registered search knobs into the `query_cache` key, and `KNOBS_HASH_VERSION` (exported from this file — the single source of truth for the current cache-key version) is bumped whenever a new knob shapes results so stale cache rows become unreachable. `graph_signals: boolean` knob in `ModeBundle` (defaults: `conservative=false`, `balanced=true`, `tokenmax=true`). `KNOBS_HASH_VERSION` appends a `gs=` parts entry per the cache-key contamination convention so a graph-on cache write can't be served to a graph-off lookup. `SearchKeyOverrides` + `SearchPerCallOpts` + `loadOverridesFromConfig` + `SEARCH_MODE_CONFIG_KEYS` + `resolveSearchMode` + `attributeKnob` all carry the field. Opt-out: `gbrain config set search.graph_signals false`. `query_cache` rows written under an older hash version hash differently — natural row segregation, cleared within `cache.ttl_seconds` (3600s default). `title_boost: number | undefined` knob in `ModeBundle` (default `1.25` for all three modes; multiplier for the post-fusion title-phrase boost). Override chain: per-call `SearchOpts` → `search.title_boost` config (clamped `[1.0, 5.0]`) → bundle. `KNOBS_HASH_VERSION` appends a `tib=` parts entry so a title-boost-on cache write can't be served to a title-boost-off lookup. `SEARCH_MODE_CONFIG_KEYS` gains `search.title_boost`. Cross-modal knobs in `ModeBundle`: `cross_modal_both_text_weight`/`cross_modal_both_image_weight` (weighted RRF for 'both' modality, defaults 0.6/0.4), `image_query_text_refinement_weight`/`image_query_image_refinement_weight` (hybrid intersect for `searchByImage` query refinement, defaults 0.4/0.6), `unified_multimodal` + `unified_multimodal_only` (unified-column routing flags), `cross_modal_llm_intent` (opt-in LLM escalation). `KNOB_CONFIG_KEY` (a `Record<keyof ModeBundle, string>`, so every knob names the `search.*` key `loadOverridesFromConfig` reads it from) is the single knob→key map: `SEARCH_MODE_CONFIG_KEYS` derives from it, `attributeKnob` prints it as the override `source_detail`, and `KNOWN_CONFIG_KEYS` in `config.ts` hand-mirrors it (config.ts stays import-light; `test/config-search-registry.test.ts` pins the two equal), and the modality knobs participate in `knobsHash` so a cached text-mode result can't be served to an image-mode caller. Retrieval-quality knobs `autocut_min_top` (default 0.35 in all three bundles; config `search.autocut_min_top`; folds into `knobsHash` as an `acm=` part) and `evidence_cosine_floor` (default 0.8 in all three bundles; config `search.evidence_cosine_floor`; labels evidence — result-set-shape-neutral, so not hashed) ride the same bundle → config → per-call chain. `keywordOrFallback: boolean` knob in `ModeBundle` (default true in all three bundles; config `search.keywordOrFallback`): the keyword arm's AND→OR zero-recall retry — corpora the FTS config can't stem (CJK/agglutinative text under `'english'`) can turn it off because the OR retry has no IDF demotion and its common-token hits read as noise in the RRF blend; folds into `knobsHash` as a `kof=` part. `KnobsHashContext` additionally carries the EFFECTIVE per-call salience/recency boost modes (`sal=`/`rec=` — explicit `SearchOpts` ?? the classifier's auto-suggestion, resolved by the same chain bare `hybridSearch` uses) and the per-engine `search.intent_patterns` config fingerprint (`ipat=`, from `query-intent.ts`'s `intentPatternFingerprint`; threaded through ctx, never read process-globally, so a multi-engine process can't key one brain's rows under another brain's patterns) — a reordered or reclassified write can never serve a differently-configured lookup. Cache HITS slice the stored page to the same resolved result count as misses (per-call `limit` → the mode's `searchLimit`) in `hybridSearchCached`, so a mode's result-count knob holds on both paths; nonzero offsets (positive OR negative) skip the cache entirely. `expansion_variant_budget: number | null` knob in `ModeBundle` (`null` in all three bundles; config `search.expansion_variant_budget` accepts `legacy`/`null` or a number in (0, 4] through the ONE range contract `normalizeExpansionVariantBudget` in `fusion-lists.ts` — out-of-range falls through to the bundle; per-call `HybridSearchOpts.expansionVariantBudget`, normalized by the same function in both the inner search and the cache resolver): the total RRF weight the NON-EMPTY expansion variant/clause lists share at fusion (`weight_i = b / n_voting_arms`; the original list always keeps weight 1), `null` = legacy weight 1 on every list (byte-identical fusion), a no-op when `expansion` is off. It folds into `knobsHash` as the last, append-only `evb=` part (`legacy` or the budget to 3 decimals) — `KNOBS_HASH_VERSION` is 29 with that part in — so a budget-weighted write can never serve a legacy lookup. `KNOB_NULL_LABELS` + `formatKnobValue` in `modes-report.ts` render its legitimate null as `legacy (null)` in `gbrain search modes` (plain `(undefined)` stays reserved for genuinely unset knobs). `relational_rerank_pin: number` knob in `ModeBundle` (3 in all three bundles — a no-op under `conservative`, which has no reranker; config `search.relational_rerank_pin` accepts `off`/`0` or an integer in [0, 10] through the ONE range contract `normalizeRelationalRerankPin` in `relational-rerank-pin.ts`, out-of-range falls through to the bundle; per-call `SearchOpts.relationalRerankPin`, normalized by the same function in both the inner search and the cache resolver): how many relational-arm rows `pinRelationalRows` re-pins above the reranked text rows after `applyReranker`. It folds into `knobsHash` as the append-only `rrp=` part, riding `KNOBS_HASH_VERSION` 29 together with `evb=` (one bump per wave — both parts landed before v29 shipped; a partial-knobs literal without the field hashes as the bundle default), so a pin-3 write can never serve a pin-0 lookup. Pinned by `test/search-mode.test.ts` (bundle snapshots + hash pins), `test/search/knobs-hash-reranker.test.ts` (the version comment chain), `test/config-adaptive-return-keys.test.ts`, `test/search/modes-report-coverage.test.ts`.
- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, sunset_passed, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`.
@@ -120,7 +124,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/embedding-pricing.ts` — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`; EMBEDDINGS only — chat/completion pricing lives in `model-pricing.ts` (different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); ZeroEntropy zembed-1 ($0.05/1M), zerank-2 ($0.025/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M). `voyage-4-nano` is deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0. `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.
- `src/core/post-upgrade-reembed.ts` — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est, graceSeconds)` is the stderr-line formatter. `runPostUpgradeReembedPrompt(engine, model, opts)` orchestrates the 10-second Ctrl-C window; TTY-only wait (non-TTY auto-proceeds for CI / cron); `GBRAIN_NO_REEMBED=1` bails with a doctor-warning marker; `GBRAIN_REEMBED_GRACE_SECONDS=0` skips the wait.
- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.
-- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds; `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source), `test/reindex-cost-refusal.test.ts`.
+- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds; `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source), `test/reindex-cost-refusal.test.ts`. Resident-delegated embedding requires explicit --yes; --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.
- `src/core/fts-language.ts` — Single source for the Postgres text-search configuration name used by FTS. `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).
- `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). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). 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/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSyncInner` resolves the source's persisted `config.strategy` (`markdown`/`code`/`auto`) when the caller passes no `strategy` — the autopilot lane, the dream cycle, the MCP `sync` op and the single-source CLI path all omit it, and without this the walk fell back to `markdown`, importing nothing from a code source while still advancing the anchor and soft-deleting its modified code pages; an explicit `--strategy` still wins, so the `--all` fan-out is unchanged. Pinned by `test/sync-index-matches-tree.serial.test.ts` (index == working tree across first/incremental/full sync). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock; `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) rather than an O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff and there is no cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) decides: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and do not block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so recovery syncs never need `--serial`; a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate does not exit 2: a worker-backed engine can auto-defer, while a runtime without a worker surface reports a manual drain instead of claiming a queued job.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). Every sync delete lane (removed-file drain, full-sync reconcile, un-syncable-page cleanup, rename-stale reconcile) SOFT-deletes via `engine.softDeletePages`: `deleted_at` is set for a 72h recovery window, the autopilot purge phase owns the eventual hard delete, the un-syncable-page sweep counts the rows it actually transitioned into `result.deleted` (a sweep-only run reports `synced`, never `up_to_date`; #4786), and a re-import within the window revives the page through `putPage`'s upsert (lanes without a threaded `sourceId` fall back to `DEFAULT_SOURCE_ID`, matching `deletePage`'s `'default'` scope). The removed-file drain is interleaved per-batch resolve+soft-delete using `engine.resolveSlugsByPaths` + `engine.softDeletePages` from `src/core/engine.ts` (a 73K-delete commit takes ~292 SQL round-trips instead of ~146K, so one big-delete commit cannot jam every other source's sync); per-batch try-catch decomposes batch failures to one-element `softDeletePages` batches per slug (same primitive, per-slug isolation), unrecoverable per-slug failures land in `failedFiles` and the run continues; `pagesAffected` filters to slugs that actually transitioned (phantom slugs and already-soft-deleted rows are excluded by the primitive's `deleted_at IS NULL` predicate). The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan. An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever; an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it soft-deletes file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists (same `softDeletePages` + 72h-window semantics as the incremental lanes; already-soft-deleted rows don't inflate the reconcile count), sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it ("absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.serial.test.ts`. `resolveSlugByPathOrSourcePath` (in `src/core/sync-git.ts` — see its dedicated entry below) delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping the legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `resolveWorkerBackedSyncEmbedMode` + posture-aware `shouldBlockSync` from `src/core/embedding.ts`. The DEFERRED path (v2 on, explicitly Postgres/worker-backed, and not `--serial`; source count controls fan-out only) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, `--serial`, or PGLite/unknown engine) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session auto-defers only when a worker-backed queue is actually available. Without that worker surface it exits 0 without wedging import convergence, writes no queue row, reports `manual_drain_required` with reason `no_worker_surface`, and emits one exact `gbrain embed --stale --source <id>` command per source; a worker-backed runtime with `--no-auto-embed` reports the distinct `auto_submit_disabled` policy reason without denying queue capability; intrinsic >100-file incremental deferral reaches the same final manual outcome on no-worker runtimes; `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). The gate's `--json` status object carries `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | manual_drain_required | posture_tokenmax`) + a paste-ready `hint`; on every proceed path it is RETURNED (`CostGateOutcome.notice`), never printed, and nested as `cost_gate` inside the ONE terminal envelope (stop paths — dry-run, cancelled — print their object as the only document); terminal single-source and `--all` envelopes carry per-source `embed_backfill` outcomes so machine readers see queued/manual/skipped state; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (serve-delegated sync + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). On a PGLite host brain with a live `gbrain serve`, the cli.ts pre-connect hook routes `gbrain sync` through `src/commands/sync-delegate.ts` (delegation over the resolve-IPC socket; default-deny flag gate; 1s status polls; Ctrl-C → `sync_abort`; embeds always deferred to the serve's drain) — `SyncOpts.onProgress` is the seam performSync fires at phase boundaries and checkpoint flushes so the serve-side job record carries live progress; `printSyncResult` is exported for the delegated result path. Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources: `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the metafile posture); an all-excluded run warns loudly (NAV-4). The persisted `sync.exclude` config key (comma- or newline-separated patterns; a trailing `/` normalizes to a `<dir>/**` subtree glob) is UNIONED with per-call `--exclude` on EVERY sync path — union, not override, so an ad-hoc flag narrows further but never silently re-opens a scope the operator persisted, and internal callers with no flag surface (autopilot, minion sync jobs, dream cycle) inherit the same indexing scope. The persisted `sync.include_hidden` key is the dot-directory WAIVER's twin, read at the same spot with the same dialect and trailing-`/` normalization and unioned with per-call `--include-hidden` — the only way to express the waiver on `sync --all` (which refuses the flag), autopilot and the dream cycle; unset admits nothing, so the dot-directory default does not move. CAVEAT: both keys are BRAIN-GLOBAL — one exclude (or admit) list scopes EVERY source, including `sync --all` (where the per-call flags are forbidden), so a pattern meant for repo A silently narrows (or widens) repo B; admission is the riskier direction; per-source scoping is a filed follow-up. The union resolves at the top of `performSyncInner`, ABOVE the `performFullSync` early returns — position is load-bearing: the first sync's full walk is exactly where ignoring the persisted scope would permanently import excluded files that no later incremental revisits. Best-effort config read (an unreadable config never breaks a sync). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath` is threaded into all 4 delete/rename call sites — see its dedicated `src/core/sync-git.ts` entry below for the resolution contract. Above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.serial.test.ts`. Unscoped default-write guard: when the resolver lands on tier `seed_default` for a single-source sync (not `--all`) and `GBRAIN_ALLOW_DEFAULT_WRITE` is unset, `assessDefaultWriteGuard` (`src/core/source-resolver.ts`) decides whether the brain's pages overwhelmingly live outside `default`; if so the run prints `formatDefaultWriteRefusal('sync', …)` and exits 1 — except under `--dry-run`, which prints the same text prefixed `[dry-run] a real run would be refused:` and still previews (a dry run writes nothing; refusing it only hides information). Escapes: `--source default` (tier `flag`), `--all`, or `GBRAIN_ALLOW_DEFAULT_WRITE=1`; a failed assessment is fail-open. Pinned by `test/sync-default-write-guard.serial.test.ts` + `test/sync-default-write-guard-dry-run.test.ts`.
@@ -154,9 +158,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/chunkers/def-types.ts` — `DEF_TYPES`: the ONE list of definition-shaped normalized (post-`normalizeSymbolType`) symbol types, shared by `gbrain code-def`'s lookup allowlist (`src/commands/code-def.ts` re-exports it) and the code chunker's small-sibling merge guard so the two can't drift — a symbol type code-def can resolve never has its `symbol_name` erased by merging a small definition into a neighbor. Includes the fallthrough forms `normalizeSymbolType` emits verbatim for tree-sitter node types it doesn't canonicalize (`'method declaration'`, `'struct specifier'`, `'record declaration'`, …) — most of an OO codebase's symbols arrive in those forms. Pinned by `test/chunkers/code-merge-defs.test.ts`.
- `src/core/errors.ts` — `StructuredAgentError` + `buildError` + `serializeError`. Every agent-facing surface (code-def, code-refs, usage errors) uses this envelope; matches the `CycleReport.PhaseResult.error` shape.
- `src/assets/wasm/` — 37 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so `bun --compile` embeds them deterministically via `import path from ... with { type: 'file' }`. The CI guard `scripts/check-wasm-embedded.sh` requires semantic TypeScript and Bash case-statement symbols in the compiled binary. Bash uses the official tree-sitter-bash v0.23.3 ABI-14 release asset, pinned by checksum in `scripts/vendor-bash-wasm.sh`; `src/assets/wasm/README.md` records provenance. Code chunker version 7 invalidates old content hashes; `gbrain sync --source <id> --full` revisits affected history in active repositories. `tree-sitter-sql.wasm` (DerekStride/tree-sitter-sql @ c2e1e08db1ea20dc23bdb8d228a81a8756e9c450, built with [email protected] --abi 14) adds SQL coverage at 11 MB — larger than peers because the grammar covers PostgreSQL + MySQL + SQLite + T-SQL basics (40 MB generated parser.c); the compiled binary grows ~6%.
-- `src/commands/code-def.ts` + `src/commands/code-refs.ts` — symbol definition + references lookup. Query `content_chunks.symbol_name` or chunk_text ILIKE with `page_kind='code'` filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard `searchKeyword` `DISTINCT ON (slug)` collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + the `code_def`/`code_refs` MCP ops) carries `status` + `ready` from `src/core/code-graph-readiness.ts` so a `count:0` result is distinguishable as `not_built` (no code indexed) vs `ready` (genuinely no match); human output prints a one-line hint when not ready. Both commands resolve `--source <id>` (space or inline `=` spelling) and the ambient source scope through the shared `code-scope.ts` resolver, matching `code-callers`/`code-callees`; `--all-sources` restores the brain-wide read. The `AND p.source_id = $N` fragment comes from `code-scope.ts`'s `pushSourcePredicate(params, opts)` (numbered off `params.length` so it composes with `--lang` and any other optional predicate; `''` when spanning every source) — code-def's lookup, its filtered-types probe, and code-refs all use it.
+- `src/commands/code-def.ts` + `src/commands/code-refs.ts` — symbol definition + references lookup. Query `content_chunks.symbol_name` or chunk_text ILIKE with `page_kind='code'` filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard `searchKeyword` `DISTINCT ON (slug)` collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + the `code_def`/`code_refs` MCP ops) carries `status` + `ready` from `src/core/code-graph-readiness.ts` so a `count:0` result is distinguishable as `not_built` (no code indexed) vs `ready` (genuinely no match); human output prints a one-line hint when not ready. Both commands resolve `--source <id>` (space or inline `=` spelling) and the ambient source scope through the shared `code-scope.ts` resolver, matching `code-callers`/`code-callees`; `--all-sources` restores the brain-wide read. `code-intel/read-scope.ts` applies the same source, live-page, visibility and current-projection policy to result queries and filtered-type diagnostics. Result identity includes source_id. Partial as well as empty results carry readiness; trusted-local operation wrappers retain their documented brain-wide behavior.
- `src/commands/code-scope.ts` — shared `--source`/`--all-sources` resolution for the four code-* CLI commands (code-def, code-refs, code-callers, code-callees), extracted so the four can't drift. `positionalArgs` skips value-taking flags AND their values (`--source`, `--limit`, `--lang` — a naive scan looked up the flag's value as the symbol); inline `name=value` spellings are one token and consume nothing. A bad `.gbrain-source`/`GBRAIN_SOURCE` pin is recognized through the shared `isResolverUserError` predicate (exported by `src/core/source-resolver.ts`, next to the messages it matches) and exits 2 with a clean `invalid_source_pin` envelope instead of an uncaught stack. Also exports `pushSourcePredicate(params, opts)`, the source-scope SQL fragment builder code-def/code-refs share.
-- `src/core/code-graph-readiness.ts` — typed readiness signal shared by the code-* surfaces (`code-def`/`code-refs`/`code-callers`/`code-callees`, plus the `code_blast`/`code_flow` walk ops). `resolveCodeReadiness(engine, {kind:'symbol'|'edge', count, sourceId?, allSources?, remote?})` returns `{status:'not_built'|'no_symbols'|'indexing'|'ready'|'out_of_scope'|'unknown', ready, has_code, pending_edges, scoped_source_id?}` (6-state `CodeGraphStatus`; `scoped_source_id` is set only for `out_of_scope`, naming the excluded scope). `count>0` short-circuits to `ready` with no query; on empty it runs `EXISTS` probes against `content_chunks` JOIN `pages` (`page_kind='code'`) — no `page_kind` index needed, and the pending probe rides the partial `idx_content_chunks_edges_backfill`. `kind:'symbol'` (code-def/refs) is 3-state + brain-wide, because symbol metadata is set at chunk time and edge resolution is irrelevant to it: no code chunks → `not_built`; code chunks but none carry `symbol_name` yet → `no_symbols` (chunks indexed before symbol extraction; hints at `reindex-code`); symbol-bearing chunks → `ready` (it never reports `indexing`). `kind:'edge'` (code-callers/callees) is 3-state + source-scoped (`not_built`/`indexing`/`ready`), with the pending predicate mirroring the resolver (`edges_backfilled_at IS NULL OR < EDGE_EXTRACTOR_VERSION_TS` from `src/core/chunkers/symbol-resolver.ts`) so a resolver-version bump never falsely reports `ready`. Both grains additionally share `out_of_scope`: when the scoped probe finds no code but an unscoped rerun finds code exists brain-wide (a chunk-existence check only — it doesn't verify symbol metadata or edge completeness), it's the caller's resolved scope that excludes it, not an unbuilt graph. That unscoped rerun runs ONLY for trusted local callers (`remote === false`); a scoped remote caller sees `not_built` instead, never a brain-wide code-existence disclosure. Probe scope matches each command's result-query `deleted_at` posture (def/refs don't filter `deleted_at`, so neither do the probes). Any DB error returns `status:'unknown'` (fail-open; never breaks the command). `readinessHint(r)` renders the human one-liner. Wired into `code-def.ts`/`code-refs.ts` (brain-wide), `code-callers.ts`/`code-callees.ts` (resolved `sourceId`/`allSources`), and all six `code_*` MCP op handlers in `src/core/ops/code-intel.ts` (`operations.ts` imports `codeIntelOperations` and spreads it into the canonical `operations` array, not a re-export). `code_blast`/`code_flow` stamp `status`/`ready` (+ `scoped_source_id`) onto the walk result through the module-private `attachWalkReadiness` helper: computed AFTER the traversal cache (readiness is never cached), `not_found` probes at symbol grain, `ok`/`ambiguous` at edge grain with count = nodes/candidates, and `unsupported_language` is passed through untouched. Pinned by `test/code-graph-readiness.test.ts` + readiness-envelope cases in `test/e2e/code-intel-mcp-ops-pglite.test.ts`.
+- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt.
+- `src/core/code-graph-readiness.ts` — shared seven-state code readiness: not_built, no_symbols, indexing, ready, out_of_scope, projection_pending, unknown. Checks scoped current-projection readiness before accepting nonempty results as ready; empty probes apply the same live/current policy as code reads. The brain-wide out_of_scope comparison remains trusted-local-only. Edge readiness uses the resolver backfill watermark. Code definitions/references, callers/callees and recursive operations expose the result; code_blast/code_flow bypass traversal caching until cached data can be revalidated. Recursive disambiguation, language probes and concrete edge endpoints also require current live pages. All six agent-facing code tools remain suspended.
- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking at the SQL layer (curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `<fork>/chat/`, `daily/`, `media/x/`). `searchVector` uses a two-stage CTE so source-boost re-ranking doesn't kill the HNSW index. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/` by default) filter at retrieval, not post-rank. Both gates honor `detail !== 'high'` so temporal queries surface chat pages normally.
- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.
- `src/core/search/llm-intent.ts` — opt-in LLM modality tie-break. `classifyModalityWithLLM(query, fallback)` routes through `gateway.chat()` with a fixed single-word-output system prompt; 1s timeout via AbortController. `parseModality(raw, fallback)` is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by `isAmbiguousModalityQuery` in `query-intent.ts` so the LLM call fires on only a small fraction of queries when on.
@@ -216,7 +221,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `docs/eval-bench.md` — contributor guide for using captured data to benchmark retrieval changes before merging. Linked from CONTRIBUTING.md under "Running real-world eval benchmarks (touching retrieval code)".
- `src/core/eval-capture.ts` — op-layer capture wrapper called from `src/core/operations.ts` `query` + `search` handlers (catches MCP + CLI + subagent tool-bridge from one site). Fire-and-forget; failures route to `engine.logEvalCaptureFailure` so `gbrain doctor` sees drops cross-process. Capture is off by default — `isEvalCaptureEnabled` resolution: explicit `config.eval.capture` (true/false) wins, else `process.env.GBRAIN_CONTRIBUTOR_MODE === '1'`, else off. Contributors set `export GBRAIN_CONTRIBUTOR_MODE=1`. PII scrubber gate is independent and defaults to true regardless of CONTRIBUTOR_MODE.
- `src/core/eval-capture-scrub.ts` — zero-deps PII scrubber: emails, phones, SSN, Luhn-verified credit cards, JWT-shaped tokens, bearer tokens.
-- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` is the engines' out-channel for searchVector's bounded pagination escalation (one dense page filling the inner candidate pool escalates the pool ×4 up to 3 times; HNSW-backed columns additionally cap at the `ef_search` ceiling, while exact-scan columns above the index dim ceiling are bounded by the escalation count alone); hybrid passes the collector and owns the emit, fired when the loop ends with the pre-DISTINCT pool still full — at the substrate cap or after the escalation budget. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).
+- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).
- `src/core/search/fusion-lists.ts` — the ONE composition point for `hybridSearch`'s RRF inputs. Every vector recall list is a ROLE-tagged arm (`VectorArm {list, role: 'original'|'variant'|'clause'|'image'}`, appended only via `pushVectorList`) — never a parallel index-aligned array: the `Promise.allSettled` salvage path drops failed arms and the both-mode image branch fails open, so any positional rule ("last list is the image", "index 0 is the original") mis-tags lists under partial failure. `composeFusionLists({arms, keywordFusionList, titleFusionList, relationalList, includeRelational, ks, knobs})` returns the complete weighted list set (`FusionListEntry {list, k, weight?}`) in the fixed order vector arms → keyword (`keywordK`) → title (`keywordK`, only if non-empty) → relational (`baseRrfK`, only if non-empty and not image modality): text arms fuse at `textRrfK` and the image arm at `imageRrfK` only when BOTH kinds are present, otherwise every arm at `vectorK` (text, image-only, unified, and a both-mode whose image branch fell open). `variant`/`clause` arms share `expansionVariantBudget` as total RRF weight — `weight_i = b / n_voting_arms` over the NON-EMPTY expansion arms (an empty list casts no vote), the `original` arm always weight 1; a `null` budget emits no `weight` key, byte-identical to unweighted fusion; when the original is missing (its embed or `searchVector` failed) every surviving text arm is a `variant` sharing the budget. `rrfFusionWeighted` (hybrid.ts) scores `weight / (k + rank)` — the literature weighted-RRF form, a list-level multiplier that holds at every rank (a k-penalty would fade at deep ranks). `textArmsNonEmpty` is the role-based text-arm health gate behind the OR-relaxed keyword demotion (image arms never count, so a fell-open image branch can't veto the lexical rescue). `normalizeExpansionVariantBudget` is the single range contract for the knob: finite `(0, 4]` (or a string parsing to one) → number, `null`/`legacy`/`null`-literal → null, anything else → `undefined` (fall through to config → bundle); shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`, so an invalid per-call value never reaches fusion or the cache key. Pure, no engine/IO. Pinned by `test/search/fusion-lists.test.ts` (knife-edge arithmetic at budget 1.0, legacy deep-equals the pre-role text mapping, role alignment under rejected arms), `test/search/expansion-variant-budget.test.ts` (hermetic directional PGLite test), and the both-mode demotion-gate regression in `test/keyword-relaxed-fusion.serial.test.ts`.
- `src/core/search/relational-rerank-pin.ts` — relational-arm rows bypass reranker DEMOTION (ranker wave, receipt R1 in `scripts/r1-namedthing-rerank-ab.ts`: on NamedThingBench's 39 graph-relationship questions the shipped `balanced` default lost hit@1 21/39 → 3/39 and hit@3 27/39 → 5/39 with the reranker on — 19 and 22 paired losses — because the cross-encoder scores chunk TEXT and an edge-derived answer's text need not mention the query's entity; with the pin at its default 3, measured with `--autocut on`, the shape that shipped before rule R2 turned autocut off, the same paired run shows 0 hit@1 / 0 hit@3 losses, 21/39 and 27/39, and the 11 non-relational core queries show 0 losses — one hard-negative gain, hit@1 10/11 → 11/11). `pinRelationalRows(reranked, relationalList, {max, fusedOrder?, onPin?})` is a pure PERMUTATION of the post-rerank pool: relational rows (page key `(source_id, slug)` in the arm's list; ONE row per page — its first, highest-ranked occurrence) claim `min(fused_rank, reranked_rank)` (fused rank = position among relational rows in `fusedOrder`, the pre-rerank `deduped` pool; arm order for rows absent from it), claims sort ascending with ties resolved to the FUSED order then the reranked position, the first `max` claimants form the top block in that order, every other row follows in reranked order (an unpinned row lands at its reranked position or up to `pinned.length` lower, never higher). Pinned rows are shallow copies stamped `relational_pinned: true`; no row is added or removed (re-injecting rows dropped upstream stays `ensureRelationalEvidenceSlot`'s job). Every no-op path (`max <= 0`, empty pool, empty arm, no relational page in the pool) returns the input array itself. `normalizeRelationalRerankPin` is the ONE range contract for the knob (non-negative integer `<= 10` or a string parsing to one → that integer; the literals `off` / `false` (any case) or boolean `false` → 0; anything else → `undefined` = fall through), shared by `mode.ts:loadOverridesFromConfig` and both per-call seams in `hybrid.ts`; `DEFAULT_RELATIONAL_RERANK_PIN` (3) and `RELATIONAL_RERANK_PIN_MAX` (10) are exported. `RelationalRerankPinDecision` (`{max, relational_in_pool, pinned:[{slug, source_id, from_rank, to_rank, fused_rank}], moved}`) is surfaced as `HybridSearchMeta.relational_rerank_pin` for `--explain`. Wired in `hybridSearch` immediately after `applyReranker` and before the alias hop, gated on the reranker having actually reordered (`reranked !== deduped` — `applyReranker` returns its input on every fail-open / skip / pass-through path, and the fused order already carries the arm) and on non-image modality; autocut's `scoreOf` ignores pinned rows and its preserve predicate keeps them, so text-row autocut is byte-identical to the pre-pin behavior. Known cost: a false-positive arm (relational shape parsed AND a real seed resolved, but wrong/stale edges) now puts up to `max` edge pages at ranks 1..max instead of one at `limit`; mitigations are the arm's `fallback_slugify` confidence gate, the tier-2 resolution-margin TODO, config `search.relational_rerank_pin off`, and per-call `SearchOpts.relationalRerankPin`. Pinned by `test/search/relational-rerank-pin.test.ts` (pure contract + tie policy) and `test/search/relational-rerank-pin-hybrid.serial.test.ts` (hermetic PGLite on the relational corpus through the REAL gateway rerank path behind `__setRerankTransportForTests` with an inverted-relevance stub: pin 0 reproduces the regression, pin 3 restores hit@1/hit@3 on all 8 who-invested questions, non-relational queries and reranker-off runs are byte-identical).
- `src/core/search/metadata-boost-gate.ts` — the ONE parse + decision contract for `search.metadata_boost_gate` (`always` | `lexical`; every bundle is `lexical`, `DEFAULT_METADATA_BOOST_GATE` stays `always` so a knobs literal without the field keeps its pre-wave hash identity). `lexicalArmsVoted` answers "did a strict keyword, title-phrase or relational row fuse?" from the composed fusion lists (relaxed OR-fallback rows do not count — they are already demoted); `decideMetadataBoosts({gate, lexicalVoted})` returns `{gate, lexical_voted, boosts_applied, reason: 'gate_always'|'lexical_voted'|'vector_only_voter'|'image_modality'}`. Image-modality queries are exempt from the gate: `hybridSearch` never runs the keyword / title arms for an image query and excludes the relational arm, so their lexical arms never vote by construction and `lexical` would silently disable the boosts for the whole modality — the caller passes `modality` (from `effectiveModality`) and an image decision applies the boosts as before (reason `image_modality`). Under `lexical`, `hybridSearch` passes `skipMetadataBoosts` into `runPostFusionStages` so the backlink, salience, recency (+chronicle), graph-signal and alias-resolved boosts are skipped when the vector arm was the only voter; supersede downrank, exact-match boost, title-phrase boost, compiled-truth boost, cosine re-score, dedup, reranker and autocut are untouched either way. Receipt (Cat 13 conceptual recall, sibling repo): the E1 localization showed hub pages carrying 1.03–1.12x backlink / graph-adjacency / recency boosts over gold concept pages that carried none whenever both lexical arms were empty; the pre-registered E3 held-out arm moved gbrain from 53.0 to 57.8 nDCG@5 (rule ≥ 57.0) with NamedThingBench, BrainBench, the retrieval canary and the LongMemEval dev slice byte-identical, so the gate flipped to `lexical` in all three bundles. The decision is surfaced as `HybridSearchMeta.metadata_boost_gate` (`--explain`); knobs-hash part `mbg=`; override chain per-call `metadataBoostGate` → config → bundle (`normalizeMetadataBoostGate` is the shared parser, garbage falls through). Pinned by `test/search/metadata-boost-gate.test.ts` (pure contract, hash participation, resolution chain) and `test/search/metadata-boost-gate-hybrid.test.ts` (hermetic PGLite hub-vs-gold corpus: `always` reproduces the hub-first regression, the default yields gold-first, config and per-call planes, unparseable falls through).
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index 67926cc358..0ce9c5f9f7 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -73,11 +73,14 @@ written up in [`RETRIEVAL_MAXPOOL_INCIDENT.md`](../incidents/RETRIEVAL_MAXPOOL_I
in `sql-ranking.ts`. The vector side returns N distinct pages by best chunk,
not N chunks that collapse to fewer pages downstream. When one dense page's
chunks fill the inner candidate pool, the engines escalate the pool in a
- bounded loop (×4 per step, at most 3 escalations; HNSW-backed columns
- additionally cap at the `ef_search` ceiling) until the page count is honest;
- a loop that ends still underfilled surfaces `vector_pool_underfilled` on the
- hybrid layer's `HybridSearchMeta` (the op-layer capture channel) instead of
- silently returning a short page.
+ bounded loop (×4 per step, at most 3 escalations). SQL candidate limits and
+ offsets are independent of `ef_search`; supported pgvector versions use
+ strict iterative scans with bounded visits. A filtered short pool is not
+ proof that the corpus is exhausted. Postgres may make one exact fallback
+ inside the remaining eight-second arm budget; PGLite does not pretend that
+ a JavaScript timeout can cancel its WASM work. Unresolved shortfalls appear
+ as `vector_candidates_incomplete` in `degraded`, with scoped
+ `vector_pool_underfilled` details in the public retrieval metadata.
- **Title-phrase boost** — when the normalized query is a contiguous token-run
inside `page.title` (or an exact full-title match), a floor-ratio-gated,
bounded multiplier fires (`applyTitleBoost`, `search.title_boost` knob). A
@@ -367,6 +370,22 @@ take-holder permissions.
## Chunk rebuilds after upgrading
+**Say to your agent:** *"Check whether my search index is ready, and repair
+code metadata without spending on embeddings."* Search and query now report
+`projection_readiness` for empty and nonempty results. `projection_pending`
+means visible pages lack a current revision seal; `projection_status_unknown`
+means the diagnostic could not establish readiness. Neither is a clean miss.
+The CLI names these states; `--json` retains its result-array format and sends
+incompleteness notices to stderr. MCP carries them in `_meta.retrieval`.
+
+The upgraded resident `gbrain serve` drains queued Markdown and code rebuilds
+without provider calls. Code repair can also run through the current owner:
+`gbrain reindex-code --force --no-embed`. Rebuilds preserve only exact,
+provenance-compatible vectors; remaining NULL vectors still need an explicitly
+authorized `gbrain embed --stale` run. A text-ready index is not a promise that
+every page has a vector. Diagnostics do not disclose private or foreign-source
+pending pages and never start repair themselves.
+
Markdown chunk creation applies the strict protected-body sanitizer before
splitting text. For remote reads, all existing chunks are withheld until a
successful rebuild records the current chunker version. Public pages require
@@ -385,8 +404,15 @@ previous vectors; use `gbrain embed --stale` later to restore semantic retrieval
when provider usage is authorized. The regular reindex path rebuilds and embeds.
Code pages use `gbrain reindex-code --force --no-embed`. Existing image indexes
require reimporting the source files; images whose OCR contains protected
-sections remain unavailable to remote chunk retrieval. No schema migration is
-required.
+sections remain unavailable to remote chunk retrieval. Schema migrations 160
+and 161 install projection statistics and the pending-projection lookup index;
+they do not rebuild vector indexes or call an embedding provider.
+
+`query --since` includes its exact lower boundary. An exact `--until` timestamp
+is inclusive without losing fractional precision; a date-only upper bound
+includes the entire day, implemented as an exclusive next-midnight boundary.
+Legacy direct engine `afterDate` and `beforeDate` bounds remain strict unless
+their explicit inclusivity flags are set.
Optional code-graph expansion is omitted from remote search. The six dedicated
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index cd045d0077..261ab2716f 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -38,6 +38,20 @@ publication is in progress, a reader may see the prior committed snapshot.
Separate calls can observe different committed revisions. Search ranking,
embeddings, and direct filesystem reads are outside this snapshot guarantee.
+Search reports `projection_pending` while visible canonical revisions still
+need a derived-text rebuild, including when other pages already produce hits.
+The resident owner rebuilds queued Markdown and code using revision-checked
+snapshots. `gbrain reindex-code --force --no-embed` repairs code metadata through
+that owner without changing canonical files or revisions. Exact compatible
+vectors survive; missing vectors remain explicitly stale, not silently ready.
+Rebuilt outgoing code edges are marked for resolution again, while incoming
+edges to unchanged target chunks are preserved. These read diagnostics do not
+start repairs or authorize provider spending.
+
+Edge resolution uses a transaction and the same ordered page guards as
+projection publication. Candidate chunks are revalidated after locking, so a
+resolver cannot certify replacement edges from an older read of their IDs.
+
Do not regenerate a request ID because the response was lost or a waiter timed
out. Repeat the same operation, arguments, source, and UUID. A committed replay
returns its original result; a terminal conflict/failure is not executed again.
diff --git a/llms-full.txt b/llms-full.txt
index 82d3ca0c6b..e5226dd4b9 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -3442,6 +3442,11 @@ gbrain think "who's working on AI agents at portfolio companies?"
**`gbrain search`** returns the top retrieved pages, ranked by hybrid scoring (vector + keyword + RRF + source-tier boost + reranker). Use it when you want raw material to skim: agent context windows, citation lookups, finding a specific quote.
+Search also tells you when its results are incomplete because projections are
+still rebuilding or a bounded vector scan ran short. Ask your agent *"Check
+whether my search index is ready"*; see [search readiness and recovery](docs/architecture/RETRIEVAL.md#chunk-rebuilds-after-upgrading)
+before treating an empty result as proof that a page is missing.
+
**`gbrain think`** runs the same retrieval, then composes a synthesized answer across the results with explicit citations to the source pages AND an honest note on what the brain doesn't know yet. The gap analysis is the differentiator: the answer tells you when a page is stale, when a claim is uncited, when two pages contradict each other, when there's a hole you should fill.
**Say to your agent:** *"What do we know about acme-example?"* — *"Tell me about alice-example before my meeting tomorrow"* — *"Search for who's working on AI agents."* Your agent routes these to the brain automatically; you never type the commands yourself.
@@ -4009,6 +4014,17 @@ RRF fusion, multi-query expansion, and 4-layer dedup are engine-agnostic. They o
**Hosting:** Supabase Pro ($25/mo, zero-ops, pgvector built in) is the managed path; self-hosted Postgres + pgvector (Docker or Homebrew — see the "Local Postgres" section below) works the same.
+Current-projection filters use `(text_projection_revision = knowledge_revision)
+IS TRUE` with matching expression statistics, rather than relying on the
+planner's fixed column-equality estimate. Migration 160 creates and collects
+those statistics; bulk import, sync, reindex and completed projection recovery
+refresh them outside page locks. This also matters on PGLite, where an empty
+initial schema sample cannot describe later imports. Maintenance needs an
+authorized database role; an RLS-hidden statistics view is not evidence that
+the object is absent. Highly selective queries may correctly choose an exact
+plan. The [retrieval guide](architecture/RETRIEVAL.md#named-thing-retrieval-per-page-pool--title--alias--evidence)
+describes bounded candidate recovery and incomplete-result metadata.
+
### Opt-in RLS source-scope binding (`GBRAIN_RLS_SCOPE_BINDING`)
Defense-in-depth layer for Postgres deployments that want the database itself
@@ -4398,7 +4414,7 @@ Every method in `BrainEngine`. The full interface. No optional methods, no featu
|-----------|---------------|-------------|-------|
| CRUD | Full | Full | Same SQL |
| Keyword search | tsvector + ts_rank | tsvector + ts_rank | Identical (real Postgres) |
-| Vector search | pgvector HNSW | pgvector HNSW | Identical (real Postgres) |
+| Vector search | pgvector HNSW | pgvector HNSW | Same operators; bounded fallback/cancellation differs |
| Fuzzy slug | pg_trgm | pg_trgm | Identical (real Postgres) |
| Graph traversal | Recursive CTE | Recursive CTE | Same SQL |
| Transactions | Full ACID | Full ACID | Both support this |
diff --git a/llms.txt b/llms.txt
index 00e505fed2..4d22b09f18 100644
--- a/llms.txt
+++ b/llms.txt
@@ -54,7 +54,7 @@ Repo: https://github.com/garrytan/gbrain
## Migrations
- [docs/UPGRADING_DOWNSTREAM_AGENTS.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/UPGRADING_DOWNSTREAM_AGENTS.md): Patches for downstream agent skill forks. One section per release.
-- [skills/migrations/](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/migrations/): Per-version agent-executable migration instructions (latest: v0.49.0.0 — isolated agent setup, hosted grant migration, and verification).
+- [skills/migrations/](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/migrations/): Per-version agent-executable migration instructions and post-upgrade verification.
- [CHANGELOG.md](https://raw.githubusercontent.com/garrytan/gbrain/master/CHANGELOG.md): Release-summary voice + itemized changes + self-repair block per version.
## Contributing
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 79866f1466..adaac1b18b 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index 90b14d8572..0ce05e7537 100644
--- a/package.json
+++ b/package.json
@@ -177,7 +177,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index f371f7bf75..d69c887065 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 2efd9e9884..67bdd631f9 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 42ab97e207..535ac310c0 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.51.6.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.51.7.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 04be0c454f..f8356a4572 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 4d72e8a17d..74cc024ae7 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.51.6.0",
+ "version": "0.51.7.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index d4d9cd491c..ee859017f2 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.51.6.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.51.7.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 38aa31a14a..5c2f8d38dc 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.51.6.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.51.7.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 7fc261c797..d69b2ea2d1 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -49,6 +49,11 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/commands/orphans.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts"],
// Source-aware ranking, hybrid search, intent classification.
"src/core/search/**": [
+ "test/e2e/projection-statistics-postgres.test.ts",
+ "test/e2e/search-query-contract-postgres.test.ts",
+ "test/e2e/vector-candidate-safety-postgres.test.ts",
+ "test/e2e/search-readiness-http.test.ts",
+ "test/e2e/projection-readiness-currency.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts",
"test/e2e/read-enrichment-privacy.test.ts", "test/e2e/legacy-chunk-privacy.test.ts",
@@ -56,6 +61,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/search-exclude.test.ts",
"test/e2e/search-swamp.test.ts",
],
+ "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts"],
+ "src/core/code-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],
+ "src/core/markdown-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],
// Tree-sitter chunkers feed code-indexing E2E.
"src/core/chunkers/**": ["test/e2e/code-indexing.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts"],
// OpenClaw context-engine plugin: engine + entry feed the plugin-shape E2E
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index 7c7eb40b2d..27a6c4d09c 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -248,7 +248,7 @@ export const SECTIONS: DocSection[] = [
{
title: "skills/migrations/",
description:
- "Per-version agent-executable migration instructions (latest: v0.49.0.0 — isolated agent setup, hosted grant migration, and verification).",
+ "Per-version agent-executable migration instructions and post-upgrade verification.",
path: "skills/migrations/",
},
{
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 85cc60b61c..f15f808cf1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,27 +3,27 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 4078 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave
+src/cli.ts 4092 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation
src/commands/autopilot.ts 2671 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop
-src/commands/doctor.ts 4641 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up
+src/commands/doctor.ts 4643 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration
src/commands/embed.ts 2144 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring
src/commands/extract-conversation-facts.ts 2105 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed
src/commands/extract.ts 2643 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges
src/commands/jobs.ts 3204 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained)
src/commands/serve-http.ts 3384 ratchet +20 #4866: RFC 9728 PRM resource=/mcp + root-path alias rewrite; grown v0.46.25.0 D2: /mcp per-request teardown (#2844); grown wave-g (#4474): resolve-IPC socket under --http via shared helper; +15: metrics wiring — tracker mount + admin-gated /metrics route, helpers live in serve-http-metrics.ts (#3893); +7 test-gap wave C6: adminAuthRateLimiter on admin login + magic-link issuance, 429 JSON envelope; +29 ambient-writeback: per-request buildMcpInstructions (writeback bundle + write-scope gate + allowed-ops extract_facts probe); +6 adversarial fix wave: remember-op bound-client fence probe gates the ambient section; +2 #4748: startup resolveMcpInstructions (deployment identity) threaded into the per-request MCP server | merged v0.48.1.0: master #4788 writeback resolve + wave #4748 identity; master: | merged v0.48.1.0 true-up; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; +12: reject snapshot-bound webhook ingestion outside the shared MCP grant contract; merged v0.49: one owner-consent route with shared grant editing; #5105: resident persistence ingress lifecycle wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction
src/core/ai/gateway.ts 4914 ratchet +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback)
-src/commands/sync.ts 5967 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed
+src/commands/sync.ts 5969 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh
src/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false
src/core/cycle/synthesize.ts 3218 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates
src/core/cycle/extract-atoms.ts 1742 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once
src/core/engine.ts 2655 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration
-src/core/import-file.ts 2354 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction
-src/core/migrate.ts 719 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction
+src/core/import-file.ts 2193 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation
+src/core/migrate.ts 720 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: static projection statistics import; DDL remains region-exempt
src/core/operations.ts 323 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring
-src/core/pglite-engine.ts 6098 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics
+src/core/pglite-engine.ts 6103 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency
src/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)
-src/core/search/hybrid.ts 3306 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call
-src/core/types.ts 2137 ratchet +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
+src/core/search/hybrid.ts 3275 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports
+src/core/types.ts 2139 ratchet +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
src/core/minions/queue.ts 2484 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
src/commands/init.ts 2050 ratchet 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 normalized ZE provider check; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 32d23c60a1..24fc68be3b 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -296,7 +296,7 @@ for f in "${files[@]}"; do
if [ "$rc" -eq 0 ]; then
if [ "$f" = "test/e2e/pgbouncer-teardown.test.ts" ] && \
[ "${GBRAIN_CI_REQUIRE_PGBOUNCER:-0}" = "1" ] && \
- ! printf '%s\n' "$output" | grep -qE '^[[:space:]]*[1-9][0-9]* pass$'; then
+ ! grep -qE '^[[:space:]]*[1-9][0-9]* pass$' <<< "$output"; then
fail_files=$((fail_files + 1))
fail_list+=("$name")
echo "$output"
diff --git a/skills/migrations/v0.51.7.0.md b/skills/migrations/v0.51.7.0.md
new file mode 100644
index 0000000000..85e60a12db
--- /dev/null
+++ b/skills/migrations/v0.51.7.0.md
@@ -0,0 +1,26 @@
+# v0.51.7.0: search and projection readiness
+
+Preserve the operator's brain, source grants, provider choices and capture settings.
+This release fixes search and recovery; it does not authorize paid enrichment.
+
+1. Run `gbrain apply-migrations --yes` if upgrade reported a schema failure.
+ Migrations 160 and 161 create current-projection statistics and a pending-work
+ lookup index. Schema maintenance needs an authorized database role. Do not
+ broaden runtime grants or disable row security to make it pass.
+2. Run `gbrain doctor`. A pending projection is not proof that source content is
+ missing. Restart the upgraded resident `gbrain serve` to let its existing
+ worker drain queued Markdown and code rebuilds.
+3. For code metadata that still needs repair, run
+ `gbrain reindex-code --force --no-embed --source <source-id>` on the brain host.
+ The CLI uses the current datastore owner when required. Do not bypass the
+ managed writer or roll the brain back to legacy writers.
+4. Repeat a source-scoped search and inspect readiness. `projection_pending`,
+ `projection_status_unknown` and `vector_candidates_incomplete` all mean the
+ results are not evidence of complete retrieval. They can accompany hits.
+5. If vectors remain missing after text recovery, explain that distinction and
+ obtain any required provider-spend approval before `gbrain embed --stale`.
+ Diagnostics and keyless rebuilds must not opt the operator into embedding.
+
+If statistics refresh fails after a batch, ask the authorized database owner to
+run `ANALYZE pages(text_projection_revision, knowledge_revision)`. Do not force a
+global index plan or increase query timeouts to conceal the failure.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 481a87e12e..01efcca4d1 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -139,6 +139,7 @@
"migrations/v0.50.0.0.md": "f221a6c907437a7500d2ad8ee9fdc5e14821514d4c1e72164b7aafac0bd5d89b",
"migrations/v0.50.2.0.md": "ff1aab621479eeda5f210e026169ba584a1c402536cabddc7c387a617934b6f1",
"migrations/v0.51.0.0.md": "c07ea78c4887791425358cf3eed5681f867e8d30caf4d639773f08d70578d4cf",
+ "migrations/v0.51.7.0.md": "c34621712c4fc8597e193c7fc44b588cab8622584204a2b6f59ffd24b9d3624c",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
diff --git a/src/cli.ts b/src/cli.ts
index 78ebd448c6..90aef04b75 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1751,7 +1751,17 @@ export function formatResult(
case 'search':
case 'query': {
const results = result as any[];
- if (params.json === true) return JSON.stringify(results, null, 2) + '\n';
+ const incompleteStages = Array.isArray(lastRetrievalMeta?.degraded)
+ ? [...new Set((lastRetrievalMeta.degraded as Array<{ stage?: string }>).map(d => d.stage)
+ .filter(stage => stage === 'vector_candidates_incomplete' || stage === 'projection_pending' || stage === 'projection_status_unknown'))]
+ : [];
+ const incompleteNotice = incompleteStages.length > 0
+ ? `Retrieval incomplete: ${incompleteStages.join(', ')}.\n`
+ : '';
+ if (params.json === true) {
+ if (incompleteNotice) process.stderr.write(incompleteNotice);
+ return JSON.stringify(results, null, 2) + '\n';
+ }
// T15/FOV-1: an empty result names its cause when the pipeline told us
// (degradation stages from _meta.retrieval / the local meta capture) —
// a bare "No results." was indistinguishable from a degraded pipeline.
@@ -1767,7 +1777,7 @@ export function formatResult(
// (autocut decision, `degraded: reranker_skipped (no_key)`) render.
return formatResultsExplain(results, lastRetrievalMeta ?? undefined);
}
- return results.map(r =>
+ return incompleteNotice + results.map(r =>
`[${r.score?.toFixed(4) || '?'}] ${r.slug} -- ${r.chunk_text?.slice(0, 100) || ''}${r.stale ? ' (stale)' : ''}`,
).join('\n') + '\n';
}
@@ -2900,6 +2910,10 @@ async function handleCliOnly(command: string, args: string[]) {
}
}
+ if (command === 'reindex-code') {
+ if (await (await import('./commands/reindex-code-delegate.ts')).maybeDelegateReindexCode(loadConfig(), args)) return;
+ }
+
// Serve-delegated sweep preflight (#677) — same shape as sync above: a live
// `gbrain serve` owns the PGLite single-writer lock, so `sweep --once` used
// to exit 1 with LiveServeLockError. The lock owner runs the sweep over its
diff --git a/src/commands/code-callees.ts b/src/commands/code-callees.ts
index 857844fed3..48ffbfbce3 100644
--- a/src/commands/code-callees.ts
+++ b/src/commands/code-callees.ts
@@ -65,6 +65,7 @@ export async function runCodeCallees(engine: BrainEngine, args: string[]): Promi
const readiness = await resolveCodeReadiness(engine, {
kind: 'edge', count: edges.length, sourceId: sourceId ?? undefined, allSources, remote: false,
});
+ const hint = readinessHint(readiness);
if (shouldEmitJson(args)) {
const out: Record<string, unknown> = {
@@ -73,19 +74,18 @@ export async function runCodeCallees(engine: BrainEngine, args: string[]): Promi
};
// #3707: see code-callers.ts — scope problem vs never-built.
if (readiness.scoped_source_id) out.scoped_source_id = readiness.scoped_source_id;
- if (edges.length === 0 && !allSources && sourceId) {
- out.hint = readiness.status === 'out_of_scope'
- ? (readinessHint(readiness) ?? `No callees in source '${sourceId}'.`)
- : `No callees in source '${sourceId}'. Try --all-sources to search every source.`;
+ if (hint) out.hint = hint;
+ if (edges.length === 0 && !allSources && sourceId
+ && !['projection_pending', 'unknown', 'out_of_scope'].includes(readiness.status)) {
+ out.hint = `No callees in source '${sourceId}'. Try --all-sources to search every source.`;
}
console.log(JSON.stringify(out, null, 2));
} else if (edges.length === 0) {
if (!allSources && sourceId) {
- console.log(`No callees found for "${sym}" in source '${sourceId}'. Try --all-sources to search every source.`);
+ console.log(`No callees found for "${sym}" in source '${sourceId}'.${!['projection_pending', 'unknown'].includes(readiness.status) ? ' Try --all-sources to search every source.' : ''}`);
} else {
console.log(`No callees found for "${sym}".`);
}
- const hint = readinessHint(readiness);
if (hint) console.log(hint);
} else {
console.log(`${edges.length} callee(s) for "${sym}":`);
@@ -93,6 +93,7 @@ export async function runCodeCallees(engine: BrainEngine, args: string[]): Promi
const res = e.resolved ? 'resolved' : 'unresolved';
console.log(` ${e.from_symbol_qualified} → ${e.to_symbol_qualified} [${res}]`);
}
+ if (hint) console.log(hint);
}
} catch (e: unknown) {
const env = serializeError(e);
diff --git a/src/commands/code-callers.ts b/src/commands/code-callers.ts
index a2fbe0b446..5e8dd727bd 100644
--- a/src/commands/code-callers.ts
+++ b/src/commands/code-callers.ts
@@ -76,6 +76,7 @@ export async function runCodeCallers(engine: BrainEngine, args: string[]): Promi
const readiness = await resolveCodeReadiness(engine, {
kind: 'edge', count: edges.length, sourceId: sourceId ?? undefined, allSources, remote: false,
});
+ const hint = readinessHint(readiness);
if (shouldEmitJson(args)) {
const out: Record<string, unknown> = {
@@ -85,19 +86,18 @@ export async function runCodeCallers(engine: BrainEngine, args: string[]): Promi
// #3707: out_of_scope names the empty scope so "grant/scope problem" is
// distinguishable from "graph never built" in machine output.
if (readiness.scoped_source_id) out.scoped_source_id = readiness.scoped_source_id;
- if (edges.length === 0 && !allSources && sourceId) {
- out.hint = readiness.status === 'out_of_scope'
- ? (readinessHint(readiness) ?? `No callers in source '${sourceId}'.`)
- : `No callers in source '${sourceId}'. Try --all-sources to search every source.`;
+ if (hint) out.hint = hint;
+ if (edges.length === 0 && !allSources && sourceId
+ && !['projection_pending', 'unknown', 'out_of_scope'].includes(readiness.status)) {
+ out.hint = `No callers in source '${sourceId}'. Try --all-sources to search every source.`;
}
console.log(JSON.stringify(out, null, 2));
} else if (edges.length === 0) {
if (!allSources && sourceId) {
- console.log(`No callers found for "${sym}" in source '${sourceId}'. Try --all-sources to search every source.`);
+ console.log(`No callers found for "${sym}" in source '${sourceId}'.${!['projection_pending', 'unknown'].includes(readiness.status) ? ' Try --all-sources to search every source.' : ''}`);
} else {
console.log(`No callers found for "${sym}".`);
}
- const hint = readinessHint(readiness);
if (hint) console.log(hint);
} else {
console.log(`${edges.length} caller(s) for "${sym}":`);
@@ -105,6 +105,7 @@ export async function runCodeCallers(engine: BrainEngine, args: string[]): Promi
const res = e.resolved ? 'resolved' : 'unresolved';
console.log(` ${e.from_symbol_qualified} → ${e.to_symbol_qualified} [${res}]`);
}
+ if (hint) console.log(hint);
}
} catch (e: unknown) {
const env = serializeError(e);
diff --git a/src/commands/code-def.ts b/src/commands/code-def.ts
index 99ac44fe30..ec2900dad0 100644
--- a/src/commands/code-def.ts
+++ b/src/commands/code-def.ts
@@ -20,10 +20,12 @@
import type { BrainEngine } from '../core/engine.ts';
import { errorFor, serializeError } from '../core/errors.ts';
import { resolveCodeReadiness, readinessHint } from '../core/code-graph-readiness.ts';
-import { resolveCliCodeScope, positionalArgs, parseFlag, pushSourcePredicate } from './code-scope.ts';
+import { resolveCliCodeScope, positionalArgs, parseFlag } from './code-scope.ts';
+import { codeReadFilter, type CodeReadScope } from '../core/code-intel/read-scope.ts';
export interface CodeDefResult {
slug: string;
+ source_id: string;
file: string | null;
language: string | null;
symbol_type: string | null;
@@ -44,7 +46,7 @@ export { DEF_TYPES };
export async function findCodeDef(
engine: BrainEngine,
symbol: string,
- opts: { limit?: number; language?: string; sourceId?: string; allSources?: boolean } = {},
+ opts: { limit?: number; language?: string } & CodeReadScope = {},
): Promise<CodeDefResult[]> {
const limit = opts.limit ?? 20;
// Placeholders are numbered as params are appended: a fixed $2 broke the
@@ -55,16 +57,16 @@ export async function findCodeDef(
params.push(opts.language);
whereLang = `AND cc.language = $${params.length}`;
}
- const whereSource = pushSourcePredicate(params, opts);
+ const whereSource = `AND ${codeReadFilter(params, opts)}`;
params.push(limit);
// Deterministic ordering: exact type matches first (functions before
// export_statement wrappers), then page slug, then line number.
const rows = await engine.executeRaw<{
- slug: string; file: string | null; language: string | null;
+ slug: string; source_id: string; file: string | null; language: string | null;
symbol_type: string | null; start_line: number | null; end_line: number | null;
chunk_text: string;
}>(
- `SELECT p.slug, (p.frontmatter->>'file') AS file, cc.language, cc.symbol_type,
+ `SELECT p.slug, p.source_id, (p.frontmatter->>'file') AS file, cc.language, cc.symbol_type,
cc.start_line, cc.end_line, cc.chunk_text
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
@@ -79,12 +81,13 @@ export async function findCodeDef(
WHEN 'type' THEN 4 WHEN 'enum' THEN 5 WHEN 'struct' THEN 6
ELSE 7
END,
- p.slug, cc.start_line
+ p.slug, cc.start_line, p.source_id
LIMIT $${params.length}`,
params,
);
return rows.map((r) => ({
slug: r.slug,
+ source_id: r.source_id,
file: r.file,
language: r.language,
symbol_type: r.symbol_type,
@@ -106,7 +109,7 @@ export async function findCodeDef(
export async function probeFilteredSymbolTypes(
engine: BrainEngine,
symbol: string,
- opts: { language?: string; sourceId?: string; allSources?: boolean } = {},
+ opts: { language?: string } & CodeReadScope = {},
): Promise<string[]> {
const params: unknown[] = [symbol];
let whereLang = '';
@@ -116,7 +119,7 @@ export async function probeFilteredSymbolTypes(
}
// Scoped with the main lookup: an unscoped probe would claim "the symbol IS
// indexed, just filtered" on the strength of a different repo's chunks.
- const whereSource = pushSourcePredicate(params, opts);
+ const whereSource = `AND ${codeReadFilter(params, opts)}`;
const rows = await engine.executeRaw<{ symbol_type: string | null }>(
`SELECT DISTINCT cc.symbol_type
FROM content_chunks cc
@@ -178,6 +181,7 @@ export async function runCodeDef(engine: BrainEngine, args: string[]): Promise<v
const readiness = await resolveCodeReadiness(engine, {
kind: 'symbol', count: results.length, sourceId, allSources, remote: false,
});
+ const readinessMessage = readinessHint(readiness);
// #3789: a count:0 that was filtered by the DEF_TYPES allowlist must not
// read as a bare ready:true / "symbol does not exist". Probe the distinct
// symbol types the name DOES have and surface the filtered ones.
@@ -202,20 +206,19 @@ export async function runCodeDef(engine: BrainEngine, args: string[]): Promise<v
count: results.length,
status: readiness.status,
ready: readiness.ready,
+ ...(readinessMessage || filteredHint ? { hint: [readinessMessage, filteredHint].filter(Boolean).join(' ') } : {}),
...(readiness.scoped_source_id ? { scoped_source_id: readiness.scoped_source_id } : {}),
...(filteredTypes.length > 0
- ? { filtered_symbol_types: filteredTypes, hint: filteredHint }
+ ? { filtered_symbol_types: filteredTypes }
: {}),
results,
}, null, 2));
} else {
if (results.length === 0) {
console.log(!allSources && sourceId
- ? `No definitions found for "${sym}" in source '${sourceId}'. Try --all-sources to search every source.`
+ ? `No definitions found for "${sym}" in source '${sourceId}'.${!['projection_pending', 'unknown'].includes(readiness.status) ? ' Try --all-sources to search every source.' : ''}`
: `No definitions found for "${sym}"`);
if (filteredHint) console.log(filteredHint);
- const hint = readinessHint(readiness);
- if (hint) console.log(hint);
} else {
console.log(`Found ${results.length} definition(s) for "${sym}":`);
for (const r of results) {
@@ -223,6 +226,7 @@ export async function runCodeDef(engine: BrainEngine, args: string[]): Promise<v
console.log(` ${r.file || r.slug}${loc} (${r.symbol_type})`);
}
}
+ if (readinessMessage) console.log(readinessMessage);
}
} catch (e: unknown) {
const env = serializeError(e);
diff --git a/src/commands/code-refs.ts b/src/commands/code-refs.ts
index 1733d6768e..79ba632511 100644
--- a/src/commands/code-refs.ts
+++ b/src/commands/code-refs.ts
@@ -21,10 +21,12 @@
import type { BrainEngine } from '../core/engine.ts';
import { errorFor, serializeError } from '../core/errors.ts';
import { resolveCodeReadiness, readinessHint } from '../core/code-graph-readiness.ts';
-import { resolveCliCodeScope, positionalArgs, parseFlag, pushSourcePredicate } from './code-scope.ts';
+import { resolveCliCodeScope, positionalArgs, parseFlag } from './code-scope.ts';
+import { codeReadFilter, type CodeReadScope } from '../core/code-intel/read-scope.ts';
export interface CodeRefResult {
slug: string;
+ source_id: string;
file: string | null;
language: string | null;
symbol_name: string | null;
@@ -37,7 +39,7 @@ export interface CodeRefResult {
export async function findCodeRefs(
engine: BrainEngine,
symbol: string,
- opts: { limit?: number; language?: string; sourceId?: string; allSources?: boolean } = {},
+ opts: { limit?: number; language?: string } & CodeReadScope = {},
): Promise<CodeRefResult[]> {
const limit = opts.limit ?? 50;
const params: unknown[] = [`%${symbol}%`];
@@ -46,15 +48,15 @@ export async function findCodeRefs(
params.push(opts.language);
whereLang = `AND cc.language = $${params.length}`;
}
- const whereSource = pushSourcePredicate(params, opts);
+ const whereSource = `AND ${codeReadFilter(params, opts)}`;
params.push(limit);
const rows = await engine.executeRaw<{
- slug: string; file: string | null; language: string | null;
+ slug: string; source_id: string; file: string | null; language: string | null;
symbol_name: string | null; symbol_type: string | null;
start_line: number | null; end_line: number | null;
chunk_text: string;
}>(
- `SELECT p.slug, (p.frontmatter->>'file') AS file, cc.language,
+ `SELECT p.slug, p.source_id, (p.frontmatter->>'file') AS file, cc.language,
cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line,
cc.chunk_text
FROM content_chunks cc
@@ -63,12 +65,13 @@ export async function findCodeRefs(
AND cc.chunk_text ILIKE $1
${whereLang}
${whereSource}
- ORDER BY p.slug, cc.start_line NULLS LAST
+ ORDER BY p.slug, cc.start_line NULLS LAST, p.source_id
LIMIT $${params.length}`,
params,
);
return rows.map((r) => ({
slug: r.slug,
+ source_id: r.source_id,
file: r.file,
language: r.language,
symbol_name: r.symbol_name,
@@ -120,6 +123,7 @@ export async function runCodeRefs(engine: BrainEngine, args: string[]): Promise<
const readiness = await resolveCodeReadiness(engine, {
kind: 'symbol', count: results.length, sourceId, allSources, remote: false,
});
+ const hint = readinessHint(readiness);
if (shouldEmitJson(args)) {
console.log(JSON.stringify({
symbol: sym,
@@ -128,16 +132,15 @@ export async function runCodeRefs(engine: BrainEngine, args: string[]): Promise<
count: results.length,
status: readiness.status,
ready: readiness.ready,
+ ...(hint ? { hint } : {}),
...(readiness.scoped_source_id ? { scoped_source_id: readiness.scoped_source_id } : {}),
results,
}, null, 2));
} else {
if (results.length === 0) {
console.log(!allSources && sourceId
- ? `No references found for "${sym}" in source '${sourceId}'. Try --all-sources to search every source.`
+ ? `No references found for "${sym}" in source '${sourceId}'.${!['projection_pending', 'unknown'].includes(readiness.status) ? ' Try --all-sources to search every source.' : ''}`
: `No references found for "${sym}"`);
- const hint = readinessHint(readiness);
- if (hint) console.log(hint);
} else {
console.log(`Found ${results.length} reference(s) to "${sym}":`);
for (const r of results) {
@@ -146,6 +149,7 @@ export async function runCodeRefs(engine: BrainEngine, args: string[]): Promise<
console.log(` ${r.file || r.slug}${loc}${sig}`);
}
}
+ if (hint) console.log(hint);
}
} catch (e: unknown) {
const env = serializeError(e);
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 5f5e4556ed..a7d5da0eb7 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -24,6 +24,8 @@ import { hnswIndexExpected, hnswMaxDimsForType } from '../core/vector-index.ts';
import { VERSION as GBRAIN_BINARY_VERSION } from '../version.ts';
import { schemaVersionHealth } from '../core/schema-version-health.ts';
import { zeroTotalContradictionsCheck } from '../core/eval-contradictions/run-health.ts';
+import { checkProjectionReadiness } from './doctor/checks/projection-readiness.ts';
+export { checkProjectionReadiness } from './doctor/checks/projection-readiness.ts';
// Peeled doctor modules (containment sprint): each is a verbatim move out of
// this file. doctor.ts re-exports every moved public symbol under its
// original name so existing importers (tests, scripts/live-brain-first-check.ts,
@@ -1934,6 +1936,7 @@ export async function buildChecks(
// page write fails brain-wide and the version counter can't see the drift.
progress.heartbeat('pages_upsert_arbiter');
checks.push(await pagesUpsertArbiterCheck(engine));
+ checks.push(await checkProjectionReadiness(engine));
// 4a-ter. #4613: links_link_source_check shape — a ledger-current brain
// whose CHECK reverted to the pre-v114 allowlist rejects every kebab
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index eafe6f1c18..54a3d3f195 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -317,9 +317,9 @@ export async function checkCodeChunkMetadata(engine: BrainEngine): Promise<Check
message:
`${chunks} chunk(s) on ${pages} code page(s) have no symbol metadata ` +
`(symbol_name and language both NULL) — code-def/code-refs and ` +
- `--lang/--symbol-kind filters miss them. A plain sync/reindex skips ` +
- `unchanged pages via the content_hash short-circuit. ` +
- `Fix: gbrain reindex-code --force`,
+ `--lang/--symbol-kind filters miss them. A plain sync/reindex may skip ` +
+ `already-current text projections. ` +
+ `Fix: gbrain reindex-code --force --no-embed`,
details: { chunks_missing_metadata: chunks, pages_affected: pages },
};
} catch (e) {
diff --git a/src/commands/doctor/checks/projection-readiness.ts b/src/commands/doctor/checks/projection-readiness.ts
new file mode 100644
index 0000000000..4f24ea02ec
--- /dev/null
+++ b/src/commands/doctor/checks/projection-readiness.ts
@@ -0,0 +1,18 @@
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { PageReadScope } from '../../../core/types.ts';
+import { probeProjectionReadiness } from '../../../core/search/projection-readiness.ts';
+import type { Check } from '../../doctor.ts';
+
+export async function checkProjectionReadiness(engine: BrainEngine, scope: PageReadScope = {}): Promise<Check> {
+ const readiness = await probeProjectionReadiness(engine, scope);
+ return {
+ name: 'text_projection_readiness',
+ status: readiness.ready ? 'ok' : 'warn',
+ message: readiness.status === 'ready'
+ ? 'Visible text projections match their canonical revisions.'
+ : readiness.status === 'projection_pending'
+ ? 'Visible pages have missing or stale text projections; search and code results may be incomplete. Restart the upgraded resident `gbrain serve` to drain queued Markdown and code rebuilds. For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path. No repair or embedding was started by this check.'
+ : 'Text projection readiness is unknown because its read-only probe failed; index completeness could not be verified.',
+ details: { readiness: readiness.status, ready: readiness.ready },
+ };
+}
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index b792bb5844..6ec109e67d 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -16,6 +16,8 @@ import { loadCompletedMigrations } from '../../core/preferences.ts';
import { compareVersions } from '../migrations/index.ts';
import { resolveHoursEnv } from '../../core/env-number.ts';
import { schemaVersionHealth } from '../../core/schema-version-health.ts';
+import { checkProjectionReadiness } from './checks/projection-readiness.ts';
+import { resolveExcludePrivatePages } from '../../core/search/private-visibility.ts';
import {
type Check,
type DoctorReport,
@@ -66,7 +68,7 @@ const _resolveSyncFreshnessHours = resolveHoursEnv;
export async function doctorReportRemote(
engine: BrainEngine,
- opts: { sourceIds?: string[] } = {},
+ opts: { sourceIds?: string[]; remote?: boolean } = {},
): Promise<DoctorReport> {
const checks: Check[] = [];
@@ -453,6 +455,10 @@ export async function doctorReportRemote(
// - contextual_retrieval_mode IS NULL (mode never evaluated)
// - synopsis-failures audit JSONL entries from the last 7 days
checks.push(await checkContextualRetrievalCoverage(engine, { sourceIds: opts.sourceIds }));
+ checks.push(await checkProjectionReadiness(engine, {
+ sourceIds: opts.sourceIds,
+ excludePrivate: await resolveExcludePrivatePages(engine, opts.remote),
+ }));
// issue #1777 — hidden_by_search_policy: chunked pages withheld from default
// search by the hard-exclude prefix policy. Pure SQL COUNT, safe on the
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 0a03ff8292..d2ac006976 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -30,6 +30,7 @@ import {
} from '../core/import-checkpoint.ts';
import { realpathOrResolve } from '../core/path-confine.ts';
import { slog } from '../core/console-prefix.ts';
+import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';
/** Return a refusal when an import target lies outside every admitted root. */
export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {
@@ -1078,6 +1079,7 @@ export async function runImport(
slog(` ${chunksCreated} chunks created`);
}
+ if (imported > 0 && !opts.managedBookmark) await refreshProjectionStatistics(engine);
return {
imported, skipped, errors, chunksCreated, failures,
...(totalMalformed > 0 ? { malformedSkipped: totalMalformed } : {}),
diff --git a/src/commands/reindex-code-delegate.ts b/src/commands/reindex-code-delegate.ts
new file mode 100644
index 0000000000..65a5d22640
--- /dev/null
+++ b/src/commands/reindex-code-delegate.ts
@@ -0,0 +1,52 @@
+import type { GBrainConfig } from '../core/config.ts';
+import { loadMounts } from '../core/brain-registry.ts';
+import { resolveBrainId } from '../core/brain-resolver.ts';
+import { getCliOptions } from '../core/cli-options.ts';
+import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
+import { inspectLockHolder } from '../core/pglite-lock.ts';
+import { OperationError } from '../core/ops/contract.ts';
+import { reportPersistenceCliError } from './persistence-delegate.ts';
+import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
+import type { ReindexCodeOpts, ReindexCodeResult } from './reindex-code.ts';
+
+export function parseReindexCodeDelegateArgs(args: string[]): ReindexCodeOpts {
+ const options: ReindexCodeOpts = {};
+ const booleans = { '--force': 'force', '--no-embed': 'noEmbed', '--dry-run': 'dryRun', '--yes': 'yes', '-y': 'yes', '--json': 'json' } as const;
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ const key = booleans[arg as keyof typeof booleans];
+ if (key) { options[key] = true; continue; }
+ if (!['--source', '--workers', '--concurrency', '--max-cost', '--max-cost-usd'].includes(arg)) throw new OperationError('invalid_params', 'Unsupported owner-delegated reindex-code option. Run gbrain reindex-code --help.');
+ const value = args[++i];
+ if (!value || value.startsWith('-')) throw new OperationError('invalid_params', `${arg} requires a value.`);
+ if (arg === '--source') options.sourceId = value;
+ else if (arg === '--workers' || arg === '--concurrency') {
+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 64) throw new OperationError('invalid_params', 'workers must be an integer from 1 to 64.');
+ options.workers = Number(value);
+ } else {
+ if (!Number.isFinite(Number(value)) || Number(value) <= 0) throw new OperationError('invalid_params', 'Owner-delegated reindex requires a positive numeric cost cap.');
+ options.maxCostUsd = Number(value);
+ }
+ }
+ return options;
+}
+
+export async function maybeDelegateReindexCode(hostConfig: GBrainConfig | null, args: string[]): Promise<boolean> {
+ const brainId = resolveBrainId(getCliOptions().brain, process.cwd());
+ const config = persistenceConfigForBrain(hostConfig, brainId, brainId === 'host' ? [] : loadMounts());
+ if (config?.engine !== 'pglite' || !config.database_path || config.database_url || !inspectLockHolder(config.database_path).held) return false;
+ try {
+ const options = parseReindexCodeDelegateArgs(args);
+ if (!options.noEmbed && !options.dryRun && !options.yes) throw new OperationError('confirmation_required', 'Pass --no-embed for keyless text recovery, --dry-run for a preview, or --yes to authorize embedding costs.');
+ const delegated = await maybeDelegateLocalAdministration('writer_reindex_code', { options }, config, { timeoutMs: 86_400_000 });
+ if (!delegated.handled) throw new OperationError('owner_unavailable', 'The registered owner stopped before reindex admission. Retry the same command.');
+ const result = delegated.result as ReindexCodeResult;
+ await writeStdoutFinal(options.json ? JSON.stringify(result) + '\n' :
+ `reindex-code: ${result.reindexed} reindexed, ${result.skipped} skipped, ${result.failed} failed (${result.codePages} code pages).\n`);
+ if (result.failed) setCliExitVerdict(1);
+ return true;
+ } catch (error) {
+ if (await reportPersistenceCliError(error, args.includes('--json'))) return true;
+ throw error;
+ }
+}
diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.ts
index 74a1d5673e..648535cb32 100644
--- a/src/commands/reindex-code.ts
+++ b/src/commands/reindex-code.ts
@@ -5,18 +5,16 @@
* `sources.chunker_version` gate forces a re-walk next sync on any source
* whose working tree hasn't drifted, but users who want the benefits NOW
* (before the next sync) get this: walk every page where type='code', read
- * compiled_truth + frontmatter.file, re-import via importCodeFile. Pages
- * flow through the same code path as normal sync (chunker + embeddings +
- * content_hash folding), so a reindex is bit-identical to a fresh sync.
+ * compiled_truth + frontmatter.file, and rebuild guarded derived projections.
+ * Managed brains publish through their resident coordinator; canonical bytes,
+ * revisions, identities, and files remain unchanged.
*
* Flags:
* --source <id> Scope to one sources row. Omit = all code pages.
* --dry-run Preview cost + page count, exit 0.
* --yes Skip interactive [y/N]. Required for non-TTY + non-JSON.
* --json Machine-readable ConfirmationRequired / result envelope.
- * --force Bypass importCodeFile's content_hash early-return. Use
- * this for paranoid full reindex when content_hash equals
- * but you still want a re-chunk + re-embed pass.
+ * --force Rebuild even when the canonical text projection is current.
*
* Batched in chunks of 100 pages to avoid OOM on 47K-page brains (codex
* review Finding 4.4). Idempotent: re-running on already-reindexed pages
@@ -24,7 +22,8 @@
*/
import type { BrainEngine } from '../core/engine.ts';
-import { importCodeFile } from '../core/import-file.ts';
+import { reindexCodeProjection } from '../core/persistence/projection-reindex.ts';
+import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';
import { estimateTokens } from '../core/chunkers/code.ts';
import { getEmbeddingModelName, estimateEmbeddingCostUsd } from '../core/embedding.ts';
import { errorFor, serializeError } from '../core/errors.ts';
@@ -141,9 +140,9 @@ async function fetchCodePages(
// non-default-source code page into 'default' and re-embed it.
const rows = await engine.executeRaw<CodePageRow>(
`SELECT p.slug, p.source_id, p.compiled_truth, p.frontmatter
- FROM pages p
- WHERE p.type = 'code' ${sourceClause}
- ORDER BY p.slug
+ FROM pages p JOIN sources s ON s.id=p.source_id
+ WHERE p.page_kind = 'code' AND p.deleted_at IS NULL AND NOT s.archived ${sourceClause}
+ ORDER BY p.source_id,p.slug
LIMIT ${batchSize} OFFSET ${offset}`,
);
return rows;
@@ -152,7 +151,7 @@ async function fetchCodePages(
async function countCodePages(engine: BrainEngine, sourceId: string | undefined): Promise<number> {
const sourceClause = sourceId ? `AND p.source_id = '${sourceId.replace(/'/g, "''")}'` : '';
const rows = await engine.executeRaw<{ n: string | number }>(
- `SELECT COUNT(*)::text AS n FROM pages p WHERE p.type = 'code' ${sourceClause}`,
+ `SELECT COUNT(*)::text AS n FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.page_kind = 'code' AND p.deleted_at IS NULL AND NOT s.archived ${sourceClause}`,
);
if (rows.length === 0) return 0;
const raw = rows[0]!.n;
@@ -191,6 +190,9 @@ export async function runReindexCode(
opts: ReindexCodeOpts = {},
): Promise<ReindexCodeResult> {
const batchSize = opts.batchSize ?? 100;
+ let model: string;
+ try { model = getEmbeddingModelName(); }
+ catch (error) { if (!opts.noEmbed) throw error; model = 'unconfigured'; }
const { totalTokens, totalPages } = await estimateReindexCost(engine, opts.sourceId, batchSize);
const costUsd = estimateEmbeddingCostUsd(totalTokens);
@@ -205,7 +207,7 @@ export async function runReindexCode(
!opts.noEmbed &&
process.env.GBRAIN_NO_CODE_MODEL_NUDGE !== '1'
) {
- const decision = shouldNudgeCodeModel(getEmbeddingModelName());
+ const decision = shouldNudgeCodeModel(model);
if (decision.shouldNudge) printCodeModelNudge(decision);
}
@@ -218,7 +220,7 @@ export async function runReindexCode(
failed: 0,
totalTokens,
costUsd,
- model: getEmbeddingModelName(),
+ model,
};
}
@@ -231,13 +233,11 @@ export async function runReindexCode(
failed: 0,
totalTokens: 0,
costUsd: 0,
- model: getEmbeddingModelName(),
+ model,
};
}
- // Walk every code page, re-run importCodeFile with compiled_truth as
- // the content source. relativePath comes from frontmatter.file (set by
- // the original importCodeFile call). Progress via stderr reporter.
+ // Walk stored code projections without replacing canonical page state.
const reporter = createProgress(cliOptsToProgressOptions(getCliOptions()));
reporter.start('reindex_code.pages', totalPages);
@@ -249,7 +249,7 @@ export async function runReindexCode(
let budgetExhausted: BudgetExhausted | null = null;
// F3: when --max-cost is set, run the body inside withBudgetTracker so
- // every gateway.embed() call inside importCodeFile composes with the cap.
+ // every explicit embedding call composes with the cap.
// On BudgetExhausted, we catch + persist what's been imported so far,
// then surface the throw as a partial-progress result the caller can
// re-run. importCodeFile is idempotent (content_hash short-circuit), so
@@ -293,19 +293,18 @@ export async function runReindexCode(
return;
}
try {
- const result = await importCodeFile(engine, relPath, row.compiled_truth, {
+ const result = await reindexCodeProjection(engine, row.slug, row.source_id, {
noEmbed: opts.noEmbed,
force: opts.force,
// Each page re-imports into its OWN source (row-level), not
// the CLI-level default — reindex must be an in-place
// rebuild, never a cross-source copy.
- sourceId: row.source_id,
});
if (result.status === 'imported') reindexed++;
else if (result.status === 'skipped') skipped++;
else {
failed++;
- failures.push({ slug: row.slug, error: result.error ?? result.status });
+ failures.push({ slug: row.slug, error: result.status });
}
} catch (e: unknown) {
// BudgetExhausted bypasses the helper's onError and hard-
@@ -342,6 +341,7 @@ export async function runReindexCode(
}
}
+ if (reindexed > 0) await refreshProjectionStatistics(engine);
if (budgetExhausted) {
// Partial-progress result: surfaces what got reindexed before the cap
// fired. The CLI wrapper translates this into a clear user-facing
@@ -355,7 +355,7 @@ export async function runReindexCode(
failed,
totalTokens,
costUsd: budgetExhausted.spent,
- model: getEmbeddingModelName(),
+ model,
failures: [
{ slug: '(budget)', error: budgetExhausted.message },
...(failures.length > 0 ? failures : []),
@@ -371,7 +371,7 @@ export async function runReindexCode(
failed,
totalTokens,
costUsd,
- model: getEmbeddingModelName(),
+ model,
failures: failures.length > 0 ? failures : undefined,
};
}
@@ -429,9 +429,9 @@ export function reindexForceHint(
): string | null {
if (force || result.reindexed > 0 || result.skipped === 0) return null;
return (
- `All ${result.skipped} page(s) were skipped by the content_hash short-circuit ` +
- `(content unchanged since last index). To force a full re-chunk + re-embed pass ` +
- `(e.g. to backfill symbol metadata), re-run with --force.`
+ `All ${result.skipped} page(s) already have current text projections ` +
+ `(no content_hash-changing canonical rewrite is needed). To rebuild symbol metadata ` +
+ `without provider costs, re-run with --force --no-embed.`
);
}
diff --git a/src/commands/reindex.ts b/src/commands/reindex.ts
index 13a0f23b82..fcd1a00d69 100644
--- a/src/commands/reindex.ts
+++ b/src/commands/reindex.ts
@@ -33,6 +33,7 @@ import { resolve } from 'path';
// v0.41.15.0 (T10, D9): per-batch parallel workers.
import { runSlidingPool } from '../core/worker-pool.ts';
import { resolveWorkersWithClamp } from '../core/sync-concurrency.ts';
+import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';
interface ReindexOpts {
/** Cap total pages reindexed. Useful for triage runs on huge brains. */
@@ -456,6 +457,7 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<R
reporter.finish();
+ if (reindexed > 0) await refreshProjectionStatistics(engine);
const pendingAfter = await countPending(engine, type, !!opts.noEmbed);
if (failed > 0) setCliExitVerdict(1);
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index c8af5dc2a3..6295adc027 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -5,6 +5,7 @@ import { existsSync, readFileSync, writeFileSync, statSync, lstatSync, realpathS
import { join, relative, resolve as pathResolve } from 'path';
import type { BrainEngine } from '../core/engine.ts';
import { DELETE_BATCH_SIZE } from '../core/engine-constants.ts';
+import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';
import { importFile, importImageFile, isImageFilePath as isImageImportPath, MAX_FILE_SIZE } from '../core/import-file.ts';
import { parseMarkdown } from '../core/markdown.ts';
import { validateSlug } from '../core/utils.ts';
@@ -620,9 +621,12 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
assertSourceFilesystemActive(true);
const jobSignal = currentJobSignal();
if (jobSignal?.aborted) throw jobSignal.reason ?? new Error('Sync job cancelled');
- const finish = (result: SyncResult): SyncResult => {
+ const finish = async (result: SyncResult, refresh = false): Promise<SyncResult> => {
assertSourceFilesystemActive(true);
if (jobSignal?.aborted) throw jobSignal.reason ?? new Error('Sync job cancelled');
+ if (refresh && (result.pagesAffected.length > 0 || result.deleted > 0)) {
+ await refreshProjectionStatistics(engine);
+ }
return result;
};
const inheritedSignal = currentSourceFilesystemSignal();
@@ -662,7 +666,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
// Per-source leases protect the commit/bookmark window. A caller may
// skip this lease only when its broader scope already serializes the work.
if (opts.skipLock) {
- return finish(await performSyncInner(engine, opts));
+ return finish(await performSyncInner(engine, opts), true);
}
const lockKey = opts.lockId ?? syncLockId(opts.sourceId ?? 'default');
@@ -672,7 +676,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
try {
return finish(await withRefreshingLock(engine, lockKey, signal => performSyncInner(engine, {
...opts, signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal,
- })));
+ })), true);
} catch (err) {
if (err instanceof LockUnavailableError) {
throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);
diff --git a/src/core/chunkers/symbol-resolver.ts b/src/core/chunkers/symbol-resolver.ts
index 9d1100c857..3a0e79d6b0 100644
Binary files a/src/core/chunkers/symbol-resolver.ts and b/src/core/chunkers/symbol-resolver.ts differ
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 0b918f4b2c..f27a89b9c1 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -25,7 +25,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
'book-mirror': ['--access', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],
'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-verify', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
- 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-embed', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
+ 'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
'calibration': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
@@ -34,10 +34,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--brain', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
'claw-test': ['--agent', '--brain', '--dir', '--force-retry', '--format', '--help', '--json', '--keep-tempdir', '--list-agents', '--live', '--local', '--locks', '--message', '--no-embed', '--no-embedding', '--output-format', '--pglite', '--progress-json', '--run-id', '--scenario', '--skip-verify', '--source', '--version', '--yes'],
- 'code-callees': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
- 'code-callers': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
- 'code-def': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
- 'code-refs': ['--all-sources', '--brain', '--help', '--json', '--lang', '--limit', '--no-json', '--source'],
+ 'code-callees': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
+ 'code-callers': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
+ 'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
+ 'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],
'config': ['--background', '--brain', '--coverage-override', '--db-url', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--markdown', '--path', '--pattern', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--raw', '--session', '--source', '--timeout', '--to', '--url', '--yes'],
'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
@@ -45,13 +45,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'conversation-parser': ['--brain', '--help', '--json', '--source'],
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
- 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-migrate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
+ 'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-hooks', '--no-migrate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--include-null-signature', '--json', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
- 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--markdown', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],
+ 'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],
'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],
'extract': ['--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],
'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],
@@ -64,7 +64,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],
- 'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--fresh', '--help', '--include-gitignored', '--json', '--log-noop', '--markdown', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],
+ 'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--fresh', '--help', '--include-gitignored', '--json', '--log-noop', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],
'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],
'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--force', '--funnel', '--harness', '--help', '--if-version', '--install', '--json', '--limit', '--no-install', '--no-service', '--no-tailscale', '--port', '--profile', '--queue', '--remove', '--resume', '--root', '--scopes', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-ttl', '--url', '--yes'],
'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-retry', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--to'],
@@ -86,11 +86,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--to', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
- 'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--markdown', '--no-embed', '--source', '--source-id', '--stale'],
+ 'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],
'recall': ['--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],
- 'reindex-code': ['--background', '--brain', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--markdown', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--timeout', '--to', '--workers', '--yes'],
+ 'reindex-code': ['--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--to', '--workers', '--yes'],
'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
'reindex-search-vector': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/code-chunks.ts b/src/core/code-chunks.ts
new file mode 100644
index 0000000000..fdc044083b
--- /dev/null
+++ b/src/core/code-chunks.ts
@@ -0,0 +1,42 @@
+import type { BrainEngine } from './engine.ts';
+import type { ChunkInput, CodeEdgeInput } from './types.ts';
+import { chunkCodeTextFull } from './chunkers/code.ts';
+import { findChunkForOffset } from './chunkers/edge-extractor.ts';
+import { sanitizeRemoteBody } from './remote-body.ts';
+import { isEmbedSkipped } from './embed-skip.ts';
+import { isQuarantined } from './quarantine.ts';
+
+export async function prepareCodeChunks(page: { compiled_truth: string; frontmatter?: Record<string, unknown> | null }, path: string) {
+ const content = sanitizeRemoteBody(page.compiled_truth);
+ const prepared = isEmbedSkipped(page.frontmatter) || isQuarantined(page.frontmatter)
+ ? { chunks: [], edges: [] } : await chunkCodeTextFull(content, path);
+ const chunks: ChunkInput[] = prepared.chunks.map((c, i) => ({
+ chunk_index: i, chunk_text: c.text, chunk_source: 'compiled_truth',
+ language: c.metadata.language, symbol_name: c.metadata.symbolName || undefined,
+ symbol_type: c.metadata.symbolType, start_line: c.metadata.startLine, end_line: c.metadata.endLine,
+ parent_symbol_path: c.metadata.parentSymbolPath?.length ? c.metadata.parentSymbolPath : undefined,
+ symbol_name_qualified: c.metadata.symbolNameQualified || undefined,
+ }));
+ return { chunks, edges: prepared.edges, content };
+}
+
+export async function installCodeChunkEdges(engine: BrainEngine, slug: string, sourceId: string,
+ prepared: Awaited<ReturnType<typeof prepareCodeChunks>>): Promise<void> {
+ const stored = await engine.getChunks(slug, { sourceId, includeUnsealed: true });
+ if (!stored.length) return;
+ const ids = stored.map(c => c.id);
+ await engine.executeRaw('DELETE FROM code_edges_chunk WHERE from_chunk_id = ANY($1::int[])', [ids]);
+ await engine.executeRaw('DELETE FROM code_edges_symbol WHERE from_chunk_id = ANY($1::int[])', [ids]);
+ await engine.executeRaw('UPDATE content_chunks SET edges_backfilled_at=NULL WHERE id = ANY($1::int[])', [ids]);
+ const ranges = stored.map(c => ({ id: c.id, startLine: c.start_line ?? 1,
+ endLine: c.end_line ?? 1, symbol_name_qualified: c.symbol_name_qualified }));
+ const edges: CodeEdgeInput[] = [];
+ for (const edge of prepared.edges) {
+ const index = findChunkForOffset(edge.callSiteByteOffset, prepared.content, ranges);
+ const from = index === null ? undefined : ranges[index];
+ if (!from?.symbol_name_qualified) continue;
+ edges.push({ from_chunk_id: from.id, to_chunk_id: null, from_symbol_qualified: from.symbol_name_qualified,
+ to_symbol_qualified: edge.toSymbol, edge_type: edge.edgeType, source_id: sourceId });
+ }
+ if (edges.length) await engine.addCodeEdges(edges);
+}
diff --git a/src/core/code-graph-readiness.ts b/src/core/code-graph-readiness.ts
index d9108fedf8..7e98ead52e 100644
--- a/src/core/code-graph-readiness.ts
+++ b/src/core/code-graph-readiness.ts
@@ -1,204 +1,84 @@
-/**
- * Code-graph readiness signal (issue #1780 Gap 1).
- *
- * `code-def` / `code-refs` / `code-callers` / `code-callees` historically
- * returned `count: 0` in three indistinguishable situations:
- * 1. the symbol graph isn't built yet for the scope (code never synced /
- * chunked, or edges not yet resolved),
- * 2. the source was never synced,
- * 3. the graph IS built and the symbol genuinely has no match.
- *
- * An agent that gets `count: 0` can't tell "wait and retry" from "trust this
- * empty result." This module adds a typed readiness signal so the envelope
- * carries `status` + `ready`, letting the caller distinguish those cases.
- *
- * Two grains, because the four commands read different data:
- * - `code-def` / `code-refs` read `content_chunks.symbol_name` /
- * `chunk_text`, which are populated at CHUNK time (during sync/import),
- * independent of edge resolution. Their readiness is 3-state: no code
- * chunks → `not_built`; code chunks but none carry `symbol_name` →
- * `no_symbols` (#3640 — chunks predate symbol extraction; hint at
- * `reindex-code`); symbol-bearing chunks exist → `ready`. They never
- * report `indexing` (edge resolution is irrelevant to them).
- * - `code-callers` / `code-callees` read the call graph (`code_edges_*`).
- * Their readiness is 3-state: no code chunks → `not_built`; code chunks
- * but edges not yet resolved → `indexing`; all resolved → `ready`.
- *
- * The "pending edges" predicate MUST mirror the resolver
- * (`symbol-resolver.ts:resolveSymbolEdgesIncremental`): a chunk is pending
- * when `edges_backfilled_at IS NULL OR edges_backfilled_at <
- * EDGE_EXTRACTOR_VERSION_TS`. Counting only `IS NULL` would falsely report
- * `ready` after a resolver-version bump (the graph is stale, not done).
- *
- * Both grains share one more state (#3707): when the SCOPED probe finds no
- * code but an unscoped rerun finds code brain-wide, the status is
- * `out_of_scope` — the graph is built, the caller's resolved scope (per-call
- * source_id / source pin / remote federated_read grant) just excludes it.
- * The hint names the scope instead of misdirecting to `gbrain sync`.
- * #4352 remediation: that unscoped rerun probes code existence OUTSIDE the
- * caller's resolved scope, so it runs ONLY for trusted local callers
- * (`remote === false`, the repo trust convention — anything else is
- * untrusted, fail-closed). A scoped remote caller sees `not_built`, never
- * a brain-wide code-existence disclosure.
- *
- * Cost: callers run this ONLY when `count === 0` (see `resolveCodeReadiness`);
- * a non-empty result short-circuits to `ready: true` with no query. Probes use
- * `EXISTS` (short-circuits on first row) rather than `COUNT(*)` because the
- * bootstrap schema has no `page_kind` index; the pending probe rides the
- * partial `idx_content_chunks_edges_backfill` index. Fail-open: any DB error
- * yields `status: 'unknown'` so a supplementary signal never breaks the command.
- *
- * Scope must match the result query exactly: `code-def` / `code-refs` do NOT
- * filter `deleted_at`, so neither do these probes (else readiness could say
- * `not_built` while results came from soft-deleted code pages).
- */
-
import type { BrainEngine } from './engine.ts';
+import type { PageReadScope } from './types.ts';
import { EDGE_EXTRACTOR_VERSION_TS } from './chunkers/symbol-resolver.ts';
+import { codeReadFilter } from './code-intel/read-scope.ts';
+import { pageReadFilter } from './search/read-policy-sql.ts';
+import { resolveExcludePrivatePages } from './search/private-visibility.ts';
+import { probeProjectionReadiness } from './search/projection-readiness.ts';
-export type CodeGraphStatus = 'not_built' | 'no_symbols' | 'indexing' | 'ready' | 'out_of_scope' | 'unknown';
+export type CodeGraphStatus = 'not_built' | 'no_symbols' | 'indexing' | 'ready' | 'out_of_scope' | 'projection_pending' | 'unknown';
export interface CodeGraphReadiness {
- /** Coarse machine-readable state. */
status: CodeGraphStatus;
- /** Convenience: `status === 'ready'`. */
ready: boolean;
- /** Whether any code chunk exists in scope. */
has_code: boolean;
- /** Whether unresolved/stale edge chunks remain in scope (edge kind only). */
pending_edges: boolean;
- /**
- * #3707: set ONLY for `out_of_scope` — the resolved source scope that was
- * probed and found to hold no code (while code exists brain-wide), so
- * hints/envelopes can name the scope instead of misdirecting to `gbrain sync`.
- */
scoped_source_id?: string;
}
-/** Scope for a readiness probe. Omit `sourceId` (or set `allSources`) for brain-wide. */
-export interface ReadinessScope {
- sourceId?: string;
+export interface ReadinessScope extends PageReadScope {
allSources?: boolean;
}
-function effectiveSourceId(scope: ReadinessScope): string | undefined {
- return scope.allSources ? undefined : scope.sourceId;
-}
-
-/**
- * EXISTS probe: does any code chunk exist in scope? Matches the def/refs result
- * query. Exported for the graph-four federated re-route (#4011,
- * ops/context.ts `routeCodeIntelScope`) so routing and readiness share ONE
- * "has code" predicate and can never disagree.
- */
-export async function codeChunksExist(engine: BrainEngine, sourceId: string | undefined): Promise<boolean> {
- const params: unknown[] = [];
- let scopeClause = '';
- if (sourceId) {
- params.push(sourceId);
- scopeClause = `AND p.source_id = $${params.length}`;
- }
- const rows = await engine.executeRaw<{ e: boolean }>(
- `SELECT EXISTS(
- SELECT 1 FROM content_chunks cc
- JOIN pages p ON p.id = cc.page_id
- WHERE p.page_kind = 'code' ${scopeClause}
- ) AS e`,
- params,
- );
- return Boolean(rows[0]?.e);
-}
-
-/**
- * EXISTS probe: does any SYMBOL-BEARING code chunk exist in scope (#3640)?
- * Code chunks can exist without symbol metadata (chunks written before
- * symbol-aware chunking, or a chunker fallback that skipped extraction);
- * `code-def` / `code-refs` match on `symbol_name`, so bare code-chunk
- * existence would falsely report `ready` while every lookup returns 0.
- * Rides the partial `idx_chunks_symbol_name` index.
- */
-async function symbolChunksExist(engine: BrainEngine, sourceId: string | undefined): Promise<boolean> {
+export async function codeChunksExist(
+ engine: BrainEngine,
+ sourceId: string | undefined,
+ policy: PageReadScope = {},
+): Promise<boolean> {
const params: unknown[] = [];
- let scopeClause = '';
- if (sourceId) {
- params.push(sourceId);
- scopeClause = `AND p.source_id = $${params.length}`;
- }
+ const filter = pageReadFilter('p', { ...policy, sourceId }, params, true);
const rows = await engine.executeRaw<{ e: boolean }>(
`SELECT EXISTS(
- SELECT 1 FROM content_chunks cc
- JOIN pages p ON p.id = cc.page_id
- WHERE p.page_kind = 'code'
- AND cc.symbol_name IS NOT NULL
- ${scopeClause}
+ SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE p.page_kind = 'code' AND ${filter}
+ ${policy.sourceIds?.length === 0 ? 'AND FALSE' : ''}
) AS e`,
params,
);
- return Boolean(rows[0]?.e);
+ if (typeof rows[0]?.e !== 'boolean') throw new Error('Invalid code readiness result');
+ return rows[0].e;
}
-/** EXISTS probe: does any code chunk have unresolved/stale edges (resolver predicate)? */
-async function pendingEdgeChunksExist(engine: BrainEngine, sourceId: string | undefined): Promise<boolean> {
- const params: unknown[] = [EDGE_EXTRACTOR_VERSION_TS];
- let scopeClause = '';
- if (sourceId) {
- params.push(sourceId);
- scopeClause = `AND p.source_id = $${params.length}`;
- }
+async function currentChunksExist(
+ engine: BrainEngine,
+ scope: ReadinessScope,
+ predicate: string,
+ params: unknown[] = [],
+): Promise<boolean> {
+ const filter = codeReadFilter(params, scope);
const rows = await engine.executeRaw<{ e: boolean }>(
`SELECT EXISTS(
- SELECT 1 FROM content_chunks cc
- JOIN pages p ON p.id = cc.page_id
- WHERE p.page_kind = 'code'
- AND (cc.edges_backfilled_at IS NULL
- OR cc.edges_backfilled_at < $1::timestamptz)
- ${scopeClause}
+ SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE p.page_kind = 'code' AND ${filter} AND ${predicate}
) AS e`,
params,
);
- return Boolean(rows[0]?.e);
+ if (typeof rows[0]?.e !== 'boolean') throw new Error('Invalid code readiness result');
+ return rows[0].e;
}
-/**
- * Resolve the readiness signal for a code-* command.
- *
- * `kind: 'symbol'` for code-def/code-refs (2-state); `kind: 'edge'` for
- * code-callers/code-callees (3-state). When `count > 0` the result is
- * trivially `ready` and no query runs. Fail-open: any DB error → `unknown`.
- */
export async function resolveCodeReadiness(
engine: BrainEngine,
- opts: {
- kind: 'symbol' | 'edge';
- count: number;
- /**
- * #4352 remediation: trust gate for the #3707 out_of_scope brain-wide
- * rerun. Pass `ctx.remote` (ops) or `false` (local CLI commands).
- * Omitted/unset is treated as untrusted — the rerun is skipped and a
- * scoped miss stays `not_built` (fail-closed, per the repo trust
- * convention: only strict `false` is trusted).
- */
- remote?: boolean;
- } & ReadinessScope,
+ opts: { kind: 'symbol' | 'edge'; count: number; remote?: boolean } & ReadinessScope,
): Promise<CodeGraphReadiness> {
- if (opts.count > 0) {
- return { status: 'ready', ready: true, has_code: true, pending_edges: false };
- }
- const sourceId = effectiveSourceId(opts);
+ const sourceId = opts.allSources && opts.sourceIds === undefined ? undefined : opts.sourceId;
try {
- const hasCode = await codeChunksExist(engine, sourceId);
+ const scope = {
+ ...opts, sourceId,
+ excludePrivate: opts.excludePrivate ?? await resolveExcludePrivatePages(engine, opts.remote),
+ requireSafeChunks: opts.requireSafeChunks ?? opts.remote !== false,
+ };
+ const projection = await probeProjectionReadiness(engine, { ...scope, pageKind: 'code' });
+ if (!projection.ready) {
+ return { status: projection.status, ready: false, has_code: opts.count > 0, pending_edges: false };
+ }
+ if (opts.count > 0) {
+ return { status: 'ready', ready: true, has_code: true, pending_edges: false };
+ }
+ const hasCode = await currentChunksExist(engine, scope, 'TRUE');
if (!hasCode) {
- // #3707: "no code in scope" conflated two very different situations —
- // the graph was never built, vs. the graph IS built but the caller's
- // resolved scope (per-call source_id, .gbrain-source pin, or a remote
- // client's federated_read grant) excludes every code-bearing source.
- // The old `not_built` hint then misdirected operators to `gbrain sync`
- // on a fully-indexed brain. When a scope was applied, rerun the probe
- // brain-wide: code elsewhere → out_of_scope, a scope/grant problem,
- // not an indexing one. #4352: trusted local callers only — the rerun
- // reads outside the resolved scope, so a remote caller never learns
- // whether code exists beyond its grant.
- if (sourceId !== undefined && opts.remote === false && (await codeChunksExist(engine, undefined))) {
+ if (sourceId !== undefined && opts.remote === false && opts.sourceIds === undefined
+ && await currentChunksExist(engine, { ...scope, sourceId: undefined }, 'TRUE')) {
return {
status: 'out_of_scope', ready: false, has_code: false,
pending_edges: false, scoped_source_id: sourceId,
@@ -207,41 +87,34 @@ export async function resolveCodeReadiness(
return { status: 'not_built', ready: false, has_code: false, pending_edges: false };
}
if (opts.kind === 'symbol') {
- // Symbol metadata is set at chunk time — but only when the chunker
- // actually extracted symbols. Probe for symbol-bearing chunks (#3640):
- // code chunks without any symbol_name mean every def/refs lookup will
- // return 0 no matter the symbol, which is "not built", not "no match".
- const hasSymbols = await symbolChunksExist(engine, sourceId);
- return hasSymbols
- ? { status: 'ready', ready: true, has_code: true, pending_edges: false }
- : { status: 'no_symbols', ready: false, has_code: true, pending_edges: false };
+ const hasSymbols = await currentChunksExist(engine, scope, 'cc.symbol_name IS NOT NULL');
+ return { status: hasSymbols ? 'ready' : 'no_symbols', ready: hasSymbols, has_code: true, pending_edges: false };
}
- const pending = await pendingEdgeChunksExist(engine, sourceId);
- return pending
- ? { status: 'indexing', ready: false, has_code: true, pending_edges: true }
- : { status: 'ready', ready: true, has_code: true, pending_edges: false };
+ const pending = await currentChunksExist(engine, scope,
+ '(cc.edges_backfilled_at IS NULL OR cc.edges_backfilled_at < $1::timestamptz)', [EDGE_EXTRACTOR_VERSION_TS]);
+ return { status: pending ? 'indexing' : 'ready', ready: !pending, has_code: true, pending_edges: pending };
} catch {
- // Supplementary signal: never fail the command on a readiness DB error.
- return { status: 'unknown', ready: false, has_code: false, pending_edges: false };
+ return { status: 'unknown', ready: false, has_code: opts.count > 0, pending_edges: false };
}
}
-/** Human-facing one-liner for non-TTY-less output, or null when ready. */
export function readinessHint(r: CodeGraphReadiness): string | null {
switch (r.status) {
case 'not_built':
- return 'Symbol graph not built (no code indexed in scope). Run `gbrain sync` to index code.';
+ return 'Symbol graph not built (no current code indexed in scope). Run `gbrain doctor` locally to inspect indexing and recovery.';
case 'out_of_scope':
return `Code IS indexed in this brain, but none of it is inside your resolved source scope${
r.scoped_source_id ? ` (source '${r.scoped_source_id}')` : ''
}. This is a scope/grant problem, not an indexing one — do NOT re-run \`gbrain sync\`. ` +
`Pass a source_id that holds code (or --all-sources locally); remote clients: check the client's federated_read grant.`;
case 'no_symbols':
- return 'Code is indexed but carries no symbol metadata (chunks predate symbol-aware chunking). Run `gbrain reindex-code` to rebuild the symbol graph.';
+ return 'Code is indexed but carries no symbol metadata. Run `gbrain reindex-code --force --no-embed` to rebuild it without provider costs.';
case 'indexing':
return 'Symbol graph still building (edges pending resolution). Re-run after the next `gbrain dream` cycle / autopilot tick.';
+ case 'projection_pending':
+ return 'Current code text projections are pending in the visible scope; results may be incomplete. Run `gbrain reindex-code --force --no-embed` locally to rebuild through the datastore owner, then check `gbrain doctor`. This read does not repair or embed content.';
case 'unknown':
- return 'Readiness check unavailable (DB error). Treat the empty result as best-effort.';
+ return 'Readiness check unavailable (DB error). Treat the results as best-effort, not proof of a complete index.';
case 'ready':
return null;
}
diff --git a/src/core/code-intel/read-scope.ts b/src/core/code-intel/read-scope.ts
new file mode 100644
index 0000000000..2efc1cad7e
--- /dev/null
+++ b/src/core/code-intel/read-scope.ts
@@ -0,0 +1,25 @@
+import type { PageReadScope } from '../types.ts';
+import { pageReadFilter } from '../search/read-policy-sql.ts';
+import { currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from '../search/safe-chunks.ts';
+
+export interface CodeReadScope extends PageReadScope {
+ allSources?: boolean;
+}
+
+export function codeReadFilter(params: unknown[], scope: CodeReadScope): string {
+ const policy = scope.allSources && scope.sourceIds === undefined ? { ...scope, sourceId: undefined } : scope;
+ return [
+ pageReadFilter('p', policy, params, true),
+ scope.sourceIds?.length === 0 ? 'FALSE' : 'TRUE',
+ currentTextProjectionFilter('p'),
+ ...(requiresSafeChunks(scope) ? [safeChunksFilter('p')] : []),
+ ].join(' AND ');
+}
+
+export function currentCodeEdgeFilter(edgeAlias: string, resolved: boolean): string {
+ const endpoint = (column: string) => `EXISTS (
+ SELECT 1 FROM content_chunks cc JOIN pages p ON p.id=cc.page_id
+ WHERE cc.id=${edgeAlias}.${column} AND ${codeReadFilter([], {})}
+ )`;
+ return `${endpoint('from_chunk_id')}${resolved ? ` AND ${endpoint('to_chunk_id')}` : ''}`;
+}
diff --git a/src/core/code-intel/recursive-walk.ts b/src/core/code-intel/recursive-walk.ts
index 4449852f6a..e13fb901a8 100644
--- a/src/core/code-intel/recursive-walk.ts
+++ b/src/core/code-intel/recursive-walk.ts
@@ -17,6 +17,7 @@
import type { BrainEngine } from '../engine.ts';
import type { CodeEdgeResult } from '../types.ts';
import { classifySink, type SinkKind } from './sinks/index.ts';
+import { codeReadFilter } from './read-scope.ts';
export type WalkDirection = 'callers' | 'callees';
@@ -84,8 +85,8 @@ async function disambiguateSymbol(
const exact = await engine.executeRaw<{ symbol_name_qualified: string }>(
`SELECT DISTINCT symbol_name_qualified
FROM content_chunks
- JOIN pages ON pages.id = content_chunks.page_id
- WHERE pages.source_id = $1
+ JOIN pages p ON p.id = content_chunks.page_id
+ WHERE p.source_id = $1 AND ${codeReadFilter([], {})}
AND symbol_name_qualified IS NOT NULL
AND (symbol_name = $2 OR symbol_name_qualified = $2)
LIMIT 25`,
@@ -99,8 +100,8 @@ async function disambiguateSymbol(
const fuzzy = await engine.executeRaw<{ symbol_name_qualified: string }>(
`SELECT DISTINCT symbol_name_qualified
FROM content_chunks
- JOIN pages ON pages.id = content_chunks.page_id
- WHERE pages.source_id = $1
+ JOIN pages p ON p.id = content_chunks.page_id
+ WHERE p.source_id = $1 AND ${codeReadFilter([], {})}
AND symbol_name_qualified IS NOT NULL
AND symbol_name_qualified ILIKE $2
LIMIT 5`,
@@ -131,8 +132,8 @@ async function detectSymbolLanguage(
const rows = await engine.executeRaw<{ language: string | null }>(
`SELECT content_chunks.language
FROM content_chunks
- JOIN pages ON pages.id = content_chunks.page_id
- WHERE pages.source_id = $1
+ JOIN pages p ON p.id = content_chunks.page_id
+ WHERE p.source_id = $1 AND ${codeReadFilter([], {})}
AND content_chunks.symbol_name_qualified = $2
LIMIT 1`,
[sourceId, qualified],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 01edbad3ca..a80e01a328 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -125,6 +125,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'sync_freshness',
'takes_count',
'takes_weight_grid',
+ 'text_projection_readiness',
'timeline_coverage',
'undeclared_db_only_pages',
'unified_multimodal_coverage',
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index cdcce6f729..a17e6508f5 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -7,11 +7,11 @@ import { createHash } from 'crypto';
import type { BrainEngine, FileSpec } from './engine.ts';
import { parseMarkdown } from './markdown.ts';
import { classifyStoredType } from './schema-pack/type-usage.ts';
-import { chunkText } from './chunkers/recursive.ts';
-import { resolveMaxChunkTokens } from './embedding-input-limit.ts';
-import { chunkCodeText, chunkCodeTextFull, detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';
+import { prepareMarkdownChunks } from './markdown-chunks.ts';
+import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';
+import { detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';
import { sanitizeRemoteBody } from './remote-body.ts';
-import { installPageEmbeddings, readProjectionSnapshot, sealPageTextProjection, type ProjectionSnapshot } from './page-state/projections.ts';
+import { installPageEmbeddings, installPageProjection, preparePageProjection, readProjectionSnapshot, sealPageTextProjection, type ProjectionSnapshot } from './page-state/projections.ts';
import { sanitizeText } from './batch-rows.ts';
import { hasProtectedBody, safeChunksFilter } from './search/safe-chunks.ts';
import { findChunkForOffset } from './chunkers/edge-extractor.ts';
@@ -32,13 +32,12 @@ import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.
import { assessContentSanity, ContentSanityBlockError } from './content-sanity.ts';
import { loadOperatorLiterals } from './content-sanity-literals.ts';
import { logContentSanityAssessment } from './audit/content-sanity-audit.ts';
-import { isEmbedSkipped, buildEmbedSkipMarker, EMBED_SKIP_KEY } from './embed-skip.ts';
+import { buildEmbedSkipMarker, EMBED_SKIP_KEY } from './embed-skip.ts';
import {
QUARANTINE_KEY,
CONTENT_FLAG_KEY,
buildQuarantineMarker,
buildContentFlagMarker,
- isQuarantined,
} from './quarantine.ts';
import { loadConfig, loadConfigWithEngine } from './config.ts';
import {
@@ -56,66 +55,6 @@ import { computeCorpusGeneration, loadSourceRow } from './contextual-retrieval-s
import { DEFAULT_SYNOPSIS_MODEL } from './page-summary.ts';
import { runGuardrails } from './guardrails.ts';
import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';
-import { scanFencedBlocks, MAX_FENCES_PER_PAGE } from './fence-scan.ts';
-
-/**
- * v0.20.0 Cathedral II Layer 8 D2 — markdown fence extraction helper.
- *
- * Roughly 40% of gbrain's brain is docs/guides/architecture notes with
- * substantial inline code. In v0.19.0 those fenced code blocks chunk as
- * prose, so querying "how do we import from engine" ranks paragraphs
- * ABOUT the import above the actual import example. D2 scans the body for
- * fenced code blocks (linear line scanner as of #2862 — formerly a
- * marked.lexer walk, which was quadratic on autolink-dense text), extracts
- * each fence with a known language tag, chunks the content via the code
- * chunker (so a TS fence gets TS-aware chunking), and persists those as
- * extra chunks on the parent markdown page with `chunk_source='fenced_code'`.
- *
- * Fence tag → pseudo-extension map. We don't need a full file extension
- * because chunkCodeText only calls detectCodeLanguage to pick a grammar;
- * a recognized extension gets the right grammar loaded, that's all.
- * Unknown tags return null → fence is skipped (no synthetic chunk).
- */
-const FENCE_TAG_TO_PSEUDO_PATH: Record<string, string> = {
- ts: 'fence.ts', typescript: 'fence.ts',
- tsx: 'fence.tsx',
- js: 'fence.js', javascript: 'fence.js',
- jsx: 'fence.jsx',
- py: 'fence.py', python: 'fence.py',
- rb: 'fence.rb', ruby: 'fence.rb',
- go: 'fence.go', golang: 'fence.go',
- rs: 'fence.rs', rust: 'fence.rs',
- java: 'fence.java',
- 'c#': 'fence.cs', cs: 'fence.cs', csharp: 'fence.cs',
- cpp: 'fence.cpp', 'c++': 'fence.cpp',
- c: 'fence.c',
- php: 'fence.php',
- swift: 'fence.swift',
- kt: 'fence.kt', kotlin: 'fence.kt',
- scala: 'fence.scala',
- lua: 'fence.lua',
- ex: 'fence.ex', elixir: 'fence.ex',
- elm: 'fence.elm',
- ml: 'fence.ml', ocaml: 'fence.ml',
- dart: 'fence.dart',
- zig: 'fence.zig',
- sol: 'fence.sol', solidity: 'fence.sol',
- sh: 'fence.sh', bash: 'fence.sh', shell: 'fence.sh', zsh: 'fence.sh',
- css: 'fence.css',
- html: 'fence.html',
- vue: 'fence.vue',
- json: 'fence.json',
- yaml: 'fence.yaml', yml: 'fence.yaml',
- toml: 'fence.toml',
-};
-
-function fenceTagToPseudoPath(lang: string | undefined): string | null {
- if (!lang) return null;
- return FENCE_TAG_TO_PSEUDO_PATH[lang.toLowerCase().trim()] ?? null;
-}
-
-// MAX_FENCES_PER_PAGE (fence-bomb DOS cap, GBRAIN_MAX_FENCES_PER_PAGE env
-// override) moved to fence-scan.ts with the #2862 linear scanner.
/**
* #2044 / #4548: row-level, visibility-aware fence merge for one page
@@ -159,67 +98,6 @@ function mergeHiddenFactRowsIntoBody(
return incomingBody;
}
-/**
- * Extract recognizable code fences via the linear scanner in fence-scan.ts
- * (#2862 — formerly a `marked.lexer` walk, which was quadratic on
- * autolink-dense text under bun). Returns one ChunkInput per fence whose
- * language tag maps to a grammar the chunker understands. Unknown tags +
- * empty fences are skipped. Per-fence try/catch: one malformed fence doesn't
- * abort the page import.
- */
-async function extractFencedChunks(
- markdown: string,
- startChunkIndex: number,
-): Promise<ChunkInput[]> {
- markdown = sanitizeRemoteBody(markdown);
- const out: ChunkInput[] = [];
- // Fast path: most pages (prose, tables, converted docs) contain no code
- // fence at all, so there is nothing for this function to extract — skip
- // even the line split when no fence marker (``` or ~~~) is present.
- // The `\r` in the line-start class mirrors the scanner's `\r\n|\r → \n`
- // line splitting, so CR/CRLF-only documents don't lose a real fence.
- if (!/(^|[\r\n])[ \t]{0,3}(```|~~~)/.test(markdown)) return out;
-
- const { fences, capped } = scanFencedBlocks(markdown);
- if (capped) {
- console.warn(
- `[gbrain] markdown fence cap hit (${MAX_FENCES_PER_PAGE} fences/page); skipping additional fences. ` +
- `Override via GBRAIN_MAX_FENCES_PER_PAGE env var.`,
- );
- }
-
- let indexOffset = 0;
- for (const fence of fences) {
- const text = fence.text.trim();
- if (!text) continue;
- const pseudoPath = fenceTagToPseudoPath(fence.lang);
- if (!pseudoPath) continue; // unknown or missing lang tag → prose fallback
- const lang = detectCodeLanguage(pseudoPath);
- if (!lang) continue;
- try {
- const chunks = await chunkCodeText(text, pseudoPath);
- for (const c of chunks) {
- out.push({
- chunk_index: startChunkIndex + indexOffset++,
- chunk_text: c.text,
- chunk_source: 'fenced_code',
- language: c.metadata.language,
- symbol_name: c.metadata.symbolName || undefined,
- symbol_type: c.metadata.symbolType,
- start_line: c.metadata.startLine,
- end_line: c.metadata.endLine,
- });
- }
- } catch (e: unknown) {
- // One fence failing shouldn't sink the page. Log + continue.
- console.warn(
- `[gbrain] fence extraction failed for lang=${fence.lang}: ${e instanceof Error ? e.message : String(e)}`,
- );
- }
- }
- return out;
-}
-
/**
* The parsed page metadata returned by importFromContent. Callers (specifically
* the put_page operation handler running auto-link post-hook) can reuse this to
@@ -880,43 +758,9 @@ export async function importFromContent(
}
}
- // Chunk compiled_truth and timeline.
- // v0.41 content-sanity soft-block: if the gate marked this page as
- // embed-skipped (oversize without junk-pattern), skip chunking
- // entirely. The empty-chunks branch in the transaction below
- // triggers tx.deleteChunks(slug) which purges any pre-existing
- // chunks (D9 transition invariant: embed_skip means no live chunks).
- const chunks: ChunkInput[] = [];
- // Skip chunking for embed-skip (oversize) OR quarantine (junk hidden).
- // Both → zero chunks → the empty-chunks branch in the transaction fires
- // tx.deleteChunks(slug) to purge any pre-existing chunks. (Flag/markup_heavy
- // is NOT here — flagged pages chunk + embed normally, they just carry a
- // warning marker.)
- const embedSkipped = isEmbedSkipped(parsed.frontmatter) || isQuarantined(parsed.frontmatter);
- if (!embedSkipped) {
- // #4530: cap chunk tokens at the ACTIVE embedding model's per-input
- // limit (recipe max_input_tokens x safety; default unchanged) so strict
- // encoders like nvidia/nv-embedqa-e5-v5 (512) never see an unembeddable
- // chunk. Split, not truncated.
- const chunkOpts = { maxTokens: resolveMaxChunkTokens() };
- if (parsed.compiled_truth.trim()) {
- for (const c of chunkText(parsed.compiled_truth, chunkOpts)) {
- chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'compiled_truth' });
- }
- }
- if (parsed.timeline?.trim()) {
- for (const c of chunkText(parsed.timeline, chunkOpts)) {
- chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'timeline' });
- }
- }
-
- // v0.20.0 Cathedral II Layer 8 D2 — extract fenced code blocks from
- // compiled_truth as first-class code chunks.
- if (parsed.compiled_truth.trim()) {
- const fenceChunks = await extractFencedChunks(parsed.compiled_truth, chunks.length);
- chunks.push(...fenceChunks);
- }
- }
+ // Preserve the importer projection (including fenced code and zero-chunk
+ // dispositions) in the provider-free path used by background rebuilds too.
+ const chunks = await prepareMarkdownChunks(parsed);
// Embedding failures propagate unless onPostCommitEmbedding lets the caller
// report enrichment separately from the already-persisted content.
@@ -1512,9 +1356,11 @@ export async function importCodeFile(
engine: BrainEngine,
relativePath: string,
content: string,
- opts: { noEmbed?: boolean; force?: boolean; sourceId?: string } = {},
+ opts: { noEmbed?: boolean; force?: boolean; sourceId?: string;
+ prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult> } = {},
): Promise<ImportResult> {
- await assertUnmanagedCanonicalWriter(engine, 'direct file import');
+ if (!opts.prepare) await assertUnmanagedCanonicalWriter(engine, 'direct file import');
+ if (opts.prepare && !opts.noEmbed) throw new Error('Coordinated code import requires provider-free preparation.');
const slug = slugifyCodePath(relativePath);
const lang = detectCodeLanguage(relativePath) || 'unknown';
const title = `${relativePath} (${lang})`;
@@ -1557,10 +1403,27 @@ export async function importCodeFile(
// mirrors that default instead of matching the slug in ANY source (the
// unscoped-check/scoped-write bug class).
const existing = await engine.getPage(slug, { sourceId: sourceId ?? 'default', includeDeleted: true });
+ const parsedPage: ParsedPage = { type: 'code', title, compiled_truth: storageContent, timeline: '',
+ frontmatter: { ...existing?.frontmatter, language: lang, file: relativePath }, tags: ['code', lang] };
if (!opts.force && existing?.content_hash === hash && !existing.deleted_at && existing.text_projection_revision === existing.knowledge_revision) {
+ if (opts.prepare) {
+ const result: ImportResult = { slug, status: 'skipped', chunks: 0 };
+ return opts.prepare({ slug, parsedPage, observedRevision: existing.knowledge_revision ?? null, noop: true, result, apply: async () => {} });
+ }
await engine.transaction(tx => assertImportBase(tx, slug, sourceId ?? 'default', existing));
return { slug, status: 'skipped', chunks: 0 };
}
+ if (existing?.content_hash === hash && !existing.deleted_at && opts.noEmbed) {
+ const snapshot = await readProjectionSnapshot(engine, slug, txOpts.sourceId, { allowUnsealed: true });
+ if (!snapshot || snapshot.snapshot.revision !== existing.knowledge_revision) throw new Error('Code changed during import preparation. Retry the import.');
+ const projection = await preparePageProjection(snapshot);
+ const result: ImportResult = { slug, status: 'imported', chunks: projection.chunks.length };
+ const apply = (tx: BrainEngine) => installPageProjection(tx, snapshot, projection.chunks,
+ { seal: true, preserveEmbeddings: true, code: projection.code });
+ if (opts.prepare) return opts.prepare({ slug, parsedPage, observedRevision: snapshot.snapshot.revision, noop: false, result, apply });
+ await engine.transaction(apply);
+ return result;
+ }
// Chunk via tree-sitter code chunker. The chunker returns per-chunk
// metadata (symbol_name, symbol_type, language, start_line, end_line)
@@ -1570,22 +1433,8 @@ export async function importCodeFile(
// from the chunker (nested methods carry ['ClassName'] etc.) so the
// chunk-grain FTS trigger picks up scope for ranking and downstream
// Layer 5 edge resolution can use scope-qualified identity.
- const { chunks: codeChunks, edges: extractedEdges } = await chunkCodeTextFull(sanitizeRemoteBody(storageContent), relativePath);
- const chunks: ChunkInput[] = codeChunks.map((c, i) => ({
- chunk_index: i,
- chunk_text: c.text,
- chunk_source: 'compiled_truth' as const,
- language: c.metadata.language,
- symbol_name: c.metadata.symbolName || undefined,
- symbol_type: c.metadata.symbolType,
- start_line: c.metadata.startLine,
- end_line: c.metadata.endLine,
- parent_symbol_path:
- c.metadata.parentSymbolPath && c.metadata.parentSymbolPath.length > 0
- ? c.metadata.parentSymbolPath
- : undefined,
- symbol_name_qualified: c.metadata.symbolNameQualified || undefined,
- }));
+ const code = await prepareCodeChunks(parsedPage, relativePath);
+ const { chunks, edges: extractedEdges } = code;
// v0.19.0 E2 — incremental chunking. Embedding calls dominate the cost
// of a sync; re-embedding unchanged chunks wastes money without
@@ -1627,7 +1476,7 @@ export async function importCodeFile(
// Store. Every per-page tx call carries `txOpts.sourceId` so multi-source
// brains write to the correct (source_id, slug) row instead of duplicating
// under the schema DEFAULT.
- await engine.transaction(async (tx) => {
+ const apply = async (tx: BrainEngine) => {
await assertImportBase(tx, slug, sourceId ?? 'default', existing);
if (existing) await tx.createVersion(slug, txOpts);
@@ -1637,7 +1486,7 @@ export async function importCodeFile(
title,
compiled_truth: storageContent,
timeline: '',
- frontmatter: { language: lang, file: relativePath },
+ frontmatter: parsedPage.frontmatter,
content_hash: hash,
// A code page MUST carry its path. The full-sync reconcile finds a
// deleted file's page by matching `source_path` against the git tree;
@@ -1675,7 +1524,13 @@ export async function importCodeFile(
await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',
[MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);
await sealPageTextProjection(tx, slug, txOpts.sourceId);
- });
+ if (opts.prepare) await installCodeChunkEdges(tx, slug, txOpts.sourceId, code);
+ };
+ if (opts.prepare) {
+ const result: ImportResult = { slug, status: 'imported', chunks: chunks.length };
+ return opts.prepare({ slug, parsedPage, observedRevision: existing?.knowledge_revision ?? null, noop: false, result, apply });
+ }
+ await engine.transaction(apply);
// Post-write read-back verification.
// Same guard as the markdown path: a code page write is not "done" until
diff --git a/src/core/markdown-chunks.ts b/src/core/markdown-chunks.ts
new file mode 100644
index 0000000000..735d9023d5
--- /dev/null
+++ b/src/core/markdown-chunks.ts
@@ -0,0 +1,133 @@
+import type { ChunkInput } from './types.ts';
+import { chunkText } from './chunkers/recursive.ts';
+import { chunkCodeText, detectCodeLanguage } from './chunkers/code.ts';
+import { sanitizeRemoteBody } from './remote-body.ts';
+import { scanFencedBlocks, MAX_FENCES_PER_PAGE } from './fence-scan.ts';
+import { isEmbedSkipped } from './embed-skip.ts';
+import { isQuarantined } from './quarantine.ts';
+import { resolveMaxChunkTokens } from './embedding-input-limit.ts';
+
+/** Recognized fence tags select the existing code grammar; unknown tags stay prose. */
+const FENCE_TAG_TO_PSEUDO_PATH: Record<string, string> = {
+ ts: 'fence.ts', typescript: 'fence.ts',
+ tsx: 'fence.tsx',
+ js: 'fence.js', javascript: 'fence.js',
+ jsx: 'fence.jsx',
+ py: 'fence.py', python: 'fence.py',
+ rb: 'fence.rb', ruby: 'fence.rb',
+ go: 'fence.go', golang: 'fence.go',
+ rs: 'fence.rs', rust: 'fence.rs',
+ java: 'fence.java',
+ 'c#': 'fence.cs', cs: 'fence.cs', csharp: 'fence.cs',
+ cpp: 'fence.cpp', 'c++': 'fence.cpp',
+ c: 'fence.c',
+ php: 'fence.php',
+ swift: 'fence.swift',
+ kt: 'fence.kt', kotlin: 'fence.kt',
+ scala: 'fence.scala',
+ lua: 'fence.lua',
+ ex: 'fence.ex', elixir: 'fence.ex',
+ elm: 'fence.elm',
+ ml: 'fence.ml', ocaml: 'fence.ml',
+ dart: 'fence.dart',
+ zig: 'fence.zig',
+ sol: 'fence.sol', solidity: 'fence.sol',
+ sh: 'fence.sh', bash: 'fence.sh', shell: 'fence.sh', zsh: 'fence.sh',
+ css: 'fence.css',
+ html: 'fence.html',
+ vue: 'fence.vue',
+ json: 'fence.json',
+ yaml: 'fence.yaml', yml: 'fence.yaml',
+ toml: 'fence.toml',
+};
+
+function fenceTagToPseudoPath(lang: string | undefined): string | null {
+ if (!lang) return null;
+ return FENCE_TAG_TO_PSEUDO_PATH[lang.toLowerCase().trim()] ?? null;
+}
+
+/** Sanitize the complete body before scanning any fenced code. */
+async function extractFencedChunks(
+ markdown: string,
+ startChunkIndex: number,
+): Promise<ChunkInput[]> {
+ markdown = sanitizeRemoteBody(markdown);
+ const out: ChunkInput[] = [];
+ // Fast path: most pages (prose, tables, converted docs) contain no code
+ // fence at all, so there is nothing for this function to extract — skip
+ // even the line split when no fence marker (``` or ~~~) is present.
+ // The `\r` in the line-start class mirrors the scanner's `\r\n|\r → \n`
+ // line splitting, so CR/CRLF-only documents don't lose a real fence.
+ if (!/(^|[\r\n])[ \t]{0,3}(```|~~~)/.test(markdown)) return out;
+
+ const { fences, capped } = scanFencedBlocks(markdown);
+ if (capped) {
+ console.warn(
+ `[gbrain] markdown fence cap hit (${MAX_FENCES_PER_PAGE} fences/page); skipping additional fences. ` +
+ `Override via GBRAIN_MAX_FENCES_PER_PAGE env var.`,
+ );
+ }
+
+ let indexOffset = 0;
+ for (const fence of fences) {
+ const text = fence.text.trim();
+ if (!text) continue;
+ const pseudoPath = fenceTagToPseudoPath(fence.lang);
+ if (!pseudoPath) continue; // unknown or missing lang tag → prose fallback
+ const lang = detectCodeLanguage(pseudoPath);
+ if (!lang) continue;
+ try {
+ const chunks = await chunkCodeText(text, pseudoPath);
+ for (const c of chunks) {
+ out.push({
+ chunk_index: startChunkIndex + indexOffset++,
+ chunk_text: c.text,
+ chunk_source: 'fenced_code',
+ language: c.metadata.language,
+ symbol_name: c.metadata.symbolName || undefined,
+ symbol_type: c.metadata.symbolType,
+ start_line: c.metadata.startLine,
+ end_line: c.metadata.endLine,
+ });
+ }
+ } catch (e: unknown) {
+ // One fence failing shouldn't sink the page. Log + continue.
+ console.warn(
+ `[gbrain] fence extraction failed for lang=${fence.lang}: ${e instanceof Error ? e.message : String(e)}`,
+ );
+ }
+ }
+ return out;
+}
+
+
+/**
+ * Provider-free Markdown projection shared by canonical imports and DB-only
+ * rebuilds. The caller owns content/disposition policy and the token limit;
+ * chunkers enforce the full-body privacy boundary before splitting. Order and
+ * metadata match the importer: truth, timeline, then recognized truth fences.
+ */
+export async function prepareMarkdownChunks(page: {
+ compiled_truth: string;
+ timeline?: string;
+ frontmatter?: Record<string, unknown> | null;
+}, maxChunkTokens?: number): Promise<ChunkInput[]> {
+ // Both dispositions intentionally have no live chunks, including code.
+ if (isEmbedSkipped(page.frontmatter) || isQuarantined(page.frontmatter)) return [];
+ const chunks: ChunkInput[] = [];
+ const chunkOpts = { maxTokens: maxChunkTokens ?? resolveMaxChunkTokens() };
+ if (page.compiled_truth.trim()) {
+ for (const c of chunkText(page.compiled_truth, chunkOpts)) {
+ chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'compiled_truth' });
+ }
+ }
+ if (page.timeline?.trim()) {
+ for (const c of chunkText(page.timeline, chunkOpts)) {
+ chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'timeline' });
+ }
+ }
+ if (page.compiled_truth.trim()) {
+ chunks.push(...await extractFencedChunks(page.compiled_truth, chunks.length));
+ }
+ return chunks;
+}
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 93775cb3c9..0b597d7e5c 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -21,6 +21,7 @@ import { repairLinkSourceCheck, LINK_SOURCE_GATE_MIGRATION_VERSION } from './lin
import { GRANT_COLUMNS_SQL, GRANT_AUDIT_SCHEMA_SQL, GRANT_SPEND_COLUMNS_SQL } from './grants/schema.ts';
import { FACT_WITHDRAWAL_SCHEMA_SQL, FACT_WITHDRAWAL_BACKFILL_SQL } from './facts/withdrawal-schema.ts';
import { repairLegacyClientGrants } from './grants/migration.ts';
+import { PROJECTION_STATISTICS_SQL, verifyProjectionStatistics } from './search/projection-statistics.ts';
/**
* When true, per-migration explanatory notices (e.g. the v123/v124 "here is
@@ -6569,6 +6570,28 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs
{ version: 157, name: 'recoverable_source_topology', idempotent: true, sql: PERSISTENCE_TOPOLOGY_SCHEMA_SQL },
{ version: 158, name: 'canonical_version_deletion_state', idempotent: true, sql: PAGE_VERSION_DELETION_SCHEMA_SQL },
{ version: 159, name: 'index_retained_publication_recovery', idempotent: true, sql: PERSISTENCE_REQUEST_RECOVERY_INDEX_SQL + ';' },
+ {
+ version: 160,
+ name: 'current_text_projection_planner_statistics',
+ idempotent: true,
+ sql: PROJECTION_STATISTICS_SQL,
+ sqlFor: { postgres: "SET LOCAL statement_timeout = '30s'; SET LOCAL lock_timeout = '2s';" + PROJECTION_STATISTICS_SQL },
+ handler: verifyProjectionStatistics,
+ },
+ {
+ version: 161,
+ name: 'index_pending_text_projections',
+ idempotent: true,
+ sql: `CREATE INDEX IF NOT EXISTS idx_pages_projection_pending
+ ON pages(source_id, page_kind, slug)
+ WHERE deleted_at IS NULL AND text_projection_revision IS DISTINCT FROM knowledge_revision;`,
+ sqlFor: {
+ postgres: `SET LOCAL statement_timeout = '30s'; SET LOCAL lock_timeout = '2s';
+ CREATE INDEX IF NOT EXISTS idx_pages_projection_pending
+ ON pages(source_id, page_kind, slug)
+ WHERE deleted_at IS NULL AND text_projection_revision IS DISTINCT FROM knowledge_revision;`,
+ },
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index f4f2459c14..5436d3bb3f 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -153,7 +153,7 @@ const run_doctor: Operation = {
// unscoped ctx = brain-wide.
const scope = sourceScopeOpts(ctx);
const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined);
- return doctorReportRemote(ctx.engine, { sourceIds });
+ return doctorReportRemote(ctx.engine, { sourceIds, remote: ctx.remote });
},
scope: 'admin',
localOnly: false,
diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.ts
index 2143aecf4c..0b8ea88b3f 100644
--- a/src/core/ops/code-intel.ts
+++ b/src/core/ops/code-intel.ts
@@ -10,7 +10,7 @@
import type { Operation, OperationContext } from './contract.ts';
import { OperationError } from './contract.ts';
-import { routeCodeIntelScope } from './context.ts';
+import { routeCodeIntelScope, readPolicyOpts } from './context.ts';
import type { WalkResult } from '../code-intel/recursive-walk.ts';
import {
CODE_CALLERS_DESCRIPTION,
@@ -120,14 +120,15 @@ const code_def: Operation = {
scope: 'read',
handler: async (ctx, p) => {
const { findCodeDef } = await import('../../commands/code-def.ts');
+ const policy = await readPolicyOpts(ctx, ctx.remote === false ? {} : undefined);
const defs = await findCodeDef(ctx.engine, p.symbol as string, {
+ ...policy,
limit: (p.limit as number) ?? 20,
language: (p.lang as string) || undefined,
});
- // code_def is brain-wide (not source-scoped); readiness is 'symbol' grain.
- const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
- const readiness = await resolveCodeReadiness(ctx.engine, { kind: 'symbol', count: defs.length });
- return { symbol: p.symbol as string, count: defs.length, status: readiness.status, ready: readiness.ready, defs };
+ const { resolveCodeReadiness, readinessHint } = await import('../code-graph-readiness.ts');
+ const readiness = await resolveCodeReadiness(ctx.engine, { ...policy, remote: ctx.remote, kind: 'symbol', count: defs.length });
+ return { symbol: p.symbol as string, count: defs.length, status: readiness.status, ready: readiness.ready, hint: readinessHint(readiness), defs };
},
cliHints: { name: 'code_def', hidden: true },
};
@@ -143,14 +144,15 @@ const code_refs: Operation = {
scope: 'read',
handler: async (ctx, p) => {
const { findCodeRefs } = await import('../../commands/code-refs.ts');
+ const policy = await readPolicyOpts(ctx, ctx.remote === false ? {} : undefined);
const refs = await findCodeRefs(ctx.engine, p.symbol as string, {
+ ...policy,
limit: (p.limit as number) ?? 50,
language: (p.lang as string) || undefined,
});
- // code_refs is brain-wide (not source-scoped); readiness is 'symbol' grain.
- const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
- const readiness = await resolveCodeReadiness(ctx.engine, { kind: 'symbol', count: refs.length });
- return { symbol: p.symbol as string, count: refs.length, status: readiness.status, ready: readiness.ready, refs };
+ const { resolveCodeReadiness, readinessHint } = await import('../code-graph-readiness.ts');
+ const readiness = await resolveCodeReadiness(ctx.engine, { ...policy, remote: ctx.remote, kind: 'symbol', count: refs.length });
+ return { symbol: p.symbol as string, count: refs.length, status: readiness.status, ready: readiness.ready, hint: readinessHint(readiness), refs };
},
cliHints: { name: 'code_refs', hidden: true },
};
@@ -198,7 +200,6 @@ const code_blast: Operation = {
scope: 'read',
handler: async (ctx, p) => {
const { runRecursiveWalk } = await import('../code-intel/recursive-walk.ts');
- const { getCachedOrCompute } = await import('../code-intel/traversal-cache.ts');
const symbol = p.symbol as string;
const depth = Math.min((p.depth as number) ?? 5, 8);
const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200);
@@ -209,17 +210,13 @@ const code_blast: Operation = {
// exactly preserving pre-fix local behavior.
const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
const sourceId = scopedSourceId ?? ctx.sourceId;
- const walk = await getCachedOrCompute(
- ctx.engine,
- { symbol_qualified: symbol, depth, source_id: sourceId },
- () => runRecursiveWalk(ctx.engine, symbol, {
+ const walk = await runRecursiveWalk(ctx.engine, symbol, {
direction: 'callers',
depth,
maxNodes: max_nodes,
sourceId,
exact,
- }),
- );
+ });
return attachWalkReadiness(ctx, walk, sourceId);
},
cliHints: { name: 'code_blast', hidden: true },
@@ -238,7 +235,6 @@ const code_flow: Operation = {
scope: 'read',
handler: async (ctx, p) => {
const { runRecursiveWalk } = await import('../code-intel/recursive-walk.ts');
- const { getCachedOrCompute } = await import('../code-intel/traversal-cache.ts');
const symbol = p.entry_point as string;
const depth = Math.min((p.depth as number) ?? 8, 12);
const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200);
@@ -246,17 +242,13 @@ const code_flow: Operation = {
// Single trust+grant resolver (see code_blast).
const { sourceId: scopedSourceId } = await routeCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
const sourceId = scopedSourceId ?? ctx.sourceId;
- const walk = await getCachedOrCompute(
- ctx.engine,
- { symbol_qualified: symbol + ':flow', depth, source_id: sourceId },
- () => runRecursiveWalk(ctx.engine, symbol, {
+ const walk = await runRecursiveWalk(ctx.engine, symbol, {
direction: 'callees',
depth,
maxNodes: max_nodes,
sourceId,
exact,
- }),
- );
+ });
return attachWalkReadiness(ctx, walk, sourceId);
},
cliHints: { name: 'code_flow', hidden: true },
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index b2b2918bc0..7bca072c55 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -8,6 +8,7 @@ import { readHolders } from './context.ts';
*/
import { hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from '../search/hybrid.ts';
+import { resolveSearchDateBounds } from '../search/date-bounds.ts';
import { loadSearchModeConfig, resolveSearchMode } from '../search/mode.ts';
import { looksConceptShaped, classifyQueryShape } from '../search/query-intent.ts';
import {
@@ -25,6 +26,9 @@ import { bumpLastRetrievedAt } from '../last-retrieved.ts';
import { applySnippetCap, DEFAULT_AGENT_SNIPPET_CHARS } from '../search/snippet-cap.ts';
import { resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
+import { probeProjectionReadiness } from '../search/projection-readiness.ts';
+import { resolveHardExcludes } from '../search/source-boost.ts';
+import { pageReadFilter } from '../search/read-policy-sql.ts';
import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';
import { OperationError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
@@ -72,21 +76,17 @@ type SourceScope = { sourceId?: string; sourceIds?: string[] };
* SMALLINT NOT NULL, so it is the same set as `NOT safeChunksFilter`), NOT
* the COALESCE form the read legs use: only the range is sargable, and this
* runs on every empty remote result — on a fully sealed brain the COALESCE
- * form walked every markdown page. The probe deliberately ignores the call's
- * `types` / `excludePrivate` filters: it answers "is the fence withholding
- * anything in scope", not "would this exact query have matched".
+ * form walked every markdown page.
*/
-async function hasUnsealedPagesInScope(ctx: OperationContext, scope: SourceScope): Promise<boolean> {
- const [sourceClause, params] = scope.sourceIds?.length
- ? ['AND p.source_id = ANY($1::text[])', [scope.sourceIds]]
- : scope.sourceId
- ? ['AND p.source_id = $1', [scope.sourceId]]
- : ['', []];
+async function hasUnsealedPagesInScope(ctx: OperationContext, scope: SourceScope, excludePrivate: boolean): Promise<boolean> {
+ if (scope.sourceIds?.length === 0) return false;
+ const params: unknown[] = [];
+ const policy = pageReadFilter('p', { ...scope, excludePrivate }, params, true);
try {
const rows = await ctx.engine.executeRaw(
- `SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id
- WHERE p.page_kind = 'markdown' AND p.deleted_at IS NULL AND NOT s.archived
- AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} ${sourceClause} LIMIT 1`,
+ `SELECT 1 FROM pages p
+ WHERE p.page_kind = 'markdown' AND ${policy}
+ AND p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} LIMIT 1`,
params,
);
return rows.length > 0;
@@ -114,18 +114,27 @@ async function buildRetrievalResponseMeta(
queryText: string,
results: unknown[],
meta: HybridSearchMeta | null,
- opts: { conceptHint?: boolean } = {},
+ opts: { conceptHint?: boolean; types?: string[] } = {},
): Promise<Record<string, unknown>> {
const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;
const hint = opts.conceptHint && looksConceptShaped(queryText)
? "concept-shaped question — the 'query' tool adds multi-query expansion and recovers " +
'synonym-phrased matches this keyword-leaning search can miss.'
: undefined;
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
const safeIndexPending = results.length === 0 && ctx.remote !== false
- && await hasUnsealedPagesInScope(ctx, scope);
- const degraded = safeIndexPending
- ? [...(m?.degraded ?? []), { stage: 'safe_index_pending' }]
- : m?.degraded;
+ && await hasUnsealedPagesInScope(ctx, scope, excludePrivate);
+ const readiness = await probeProjectionReadiness(ctx.engine, {
+ ...scope,
+ excludePrivate,
+ types: opts.types,
+ excludeSlugPrefixes: resolveHardExcludes(),
+ });
+ const degraded = [...(m?.degraded ?? [])];
+ if (safeIndexPending) degraded.push({ stage: 'safe_index_pending' });
+ if (readiness.status !== 'ready') {
+ degraded.push({ stage: readiness.status === 'projection_pending' ? 'projection_pending' : 'projection_status_unknown' });
+ }
return {
returned_count: results.length,
retrieved_count: m?.retrieved_count ?? results.length,
@@ -134,9 +143,11 @@ async function buildRetrievalResponseMeta(
expansion_applied: m.expansion_applied,
...(m.cache ? { cache: m.cache.status } : {}),
...(m.token_budget ? { token_budget: m.token_budget } : {}),
+ ...(m.vector_pool_underfilled ? { vector_pool_underfilled: m.vector_pool_underfilled } : {}),
} : {}),
- ...(degraded !== undefined ? { degraded } : {}),
- ...(hint ? { hint } : {}),
+ ...((m?.degraded !== undefined || degraded.length > 0) ? { degraded } : {}),
+ projection_readiness: readiness,
+ ...(hint || readiness.hint ? { hint: [hint, readiness.hint].filter(Boolean).join(' ') } : {}),
};
}
@@ -292,7 +303,7 @@ const search: Operation = {
await stampUnverifiedExtractions(ctx.engine, results, { ...scope, excludePrivate });
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);
- ctx.emitResponseMeta?.('retrieval', await buildRetrievalResponseMeta(ctx, scope, queryText, results, null, { conceptHint: true }));
+ ctx.emitResponseMeta?.('retrieval', await buildRetrievalResponseMeta(ctx, scope, queryText, results, null, { conceptHint: true, types }));
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return applySnippetCap(results, snippetCap);
}
@@ -319,7 +330,7 @@ const search: Operation = {
const latency_ms = Date.now() - startedAt;
bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
- ctx.emitResponseMeta?.('retrieval', await buildRetrievalResponseMeta(ctx, scope, queryText, results, capturedMeta, { conceptHint: true }));
+ ctx.emitResponseMeta?.('retrieval', await buildRetrievalResponseMeta(ctx, scope, queryText, results, capturedMeta, { conceptHint: true, types }));
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return applySnippetCap(results, snippetCap);
},
@@ -482,6 +493,13 @@ const query: Operation = {
// text-only); embeds the image via embedMultimodal and runs a direct
// vector search against the embedding_image column.
if (imageData) {
+ const dates = resolveSearchDateBounds({
+ since: typeof p.since === 'string' ? p.since : undefined,
+ until: typeof p.until === 'string' ? p.until : undefined,
+ });
+ const imageMeta: HybridSearchMeta = {
+ vector_enabled: true, expansion_applied: false, detail_resolved: null, degraded: [],
+ };
const { embedMultimodal } = await import('../ai/gateway.ts');
const [vec] = await embedMultimodal([
{ kind: 'image_base64', data: imageData, mime: imageMime },
@@ -503,7 +521,17 @@ const query: Operation = {
takesHoldersAllowList: readHolders(ctx),
...(types ? { types } : {}),
...querySourceScope,
+ ...dates,
+ onVectorPoolMeta: info => {
+ if (!info.underfilled) return;
+ const { underfilled, ...detail } = info;
+ imageMeta.vector_pool_underfilled = { ...detail, incomplete: true };
+ imageMeta.degraded = [{ stage: 'vector_candidates_incomplete',
+ reason: info.reason === 'deadline' ? 'timeout' : info.reason ?? 'candidate_budget' }];
+ },
});
+ imageMeta.retrieved_count = results.length;
+ ctx.emitResponseMeta?.('retrieval', await buildRetrievalResponseMeta(ctx, querySourceScope, queryText ?? '', results, imageMeta, { types }));
return applySnippetCap(results, snippetCap);
}
@@ -745,7 +773,7 @@ const query: Operation = {
// WP2/D3: query never nudges toward itself — no concept hint here.
// #1663: the CRAG grade rides the same retrieval meta channel.
ctx.emitResponseMeta?.('retrieval', {
- ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, results, capturedMeta)),
+ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, results, capturedMeta, { types })),
crag,
});
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 5256eb91d3..59be1c1d02 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -1,6 +1,9 @@
import type { BrainEngine } from '../engine.ts';
-import type { Chunk, ChunkInput, ResolvedColumn } from '../types.ts';
-import { chunkText, MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';
+import type { Chunk, ChunkInput, ResolvedColumn, PageKind } from '../types.ts';
+import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';
+import { CHUNKER_VERSION } from '../chunkers/code.ts';
+import { prepareMarkdownChunks } from '../markdown-chunks.ts';
+import { prepareCodeChunks, installCodeChunkEdges } from '../code-chunks.ts';
import { resolveMaxChunkTokens } from '../embedding-input-limit.ts';
import { assertPageRevision, PageRevisionConflictError, type PageSnapshot } from './types.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
@@ -8,6 +11,7 @@ import { digest } from '../persistence/digest.ts';
import { quoteIdentifier, resolveWriteColumnFromConfigRows, vectorCastSuffix } from '../search/embedding-column.ts';
import { getFtsLanguage } from '../fts-language.ts';
import { getEmbeddingModel } from '../ai/gateway.ts';
+import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
/** Complete the searchable snapshot only after its sanitized chunks are installed. */
export async function sealPageTextProjection(engine: BrainEngine, slug: string, sourceId: string): Promise<void> {
@@ -25,8 +29,10 @@ export interface ProjectionSnapshot {
chunks: Chunk[];
indexingContext: string;
embeddingModel: string | null;
+ embeddingColumn: ResolvedColumn;
maxChunkTokens: number;
maxChunkTokensOverride?: number;
+ pageKind: PageKind;
}
/** Canonical state can stay unchanged while another worker replaces its projection. */
@@ -38,7 +44,7 @@ export class PageProjectionConflictError extends PageRevisionConflictError {
}
}
-async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxChunkTokensOverride?: number): Promise<{ key: string; model: string | null; maxChunkTokens: number; column: ResolvedColumn }> {
+async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxChunkTokensOverride?: number): Promise<{ key: string; model: string | null; maxChunkTokens: number; column: ResolvedColumn; pageKind: PageKind }> {
const config = await engine.executeRaw<{ key: string; value: string }>(
"SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns','embedding_model','embedding_dimensions','contextual_retrieval.mode') ORDER BY key");
let model = config.find(row => row.key === 'embedding_model')?.value ?? null;
@@ -50,9 +56,12 @@ async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxC
});
const [projection] = await engine.executeRaw<{ chunker_version: number | null; corpus_generation: string | null }>(
'SELECT chunker_version,corpus_generation FROM pages WHERE id=$1', [snapshot.page.id]);
+ const [kind] = await engine.executeRaw<{ page_kind: PageKind }>('SELECT page_kind FROM pages WHERE id=$1', [snapshot.page.id]);
+ if (!kind) throw new PageRevisionConflictError(snapshot.revision, null);
return { key: digest({ config, mode: snapshot.page.contextual_retrieval_mode, model, column,
maxChunkTokens, storedChunkerVersion: projection?.chunker_version ?? null, corpusGeneration: projection?.corpus_generation ?? null,
- chunkerVersion: MARKDOWN_CHUNKER_VERSION, ftsLanguage: getFtsLanguage() }), model, maxChunkTokens, column };
+ chunkerVersion: MARKDOWN_CHUNKER_VERSION, codeChunkerVersion: CHUNKER_VERSION, pageKind: kind.page_kind,
+ ftsLanguage: getFtsLanguage() }), model, maxChunkTokens, column, pageKind: kind.page_kind };
}
/** A short guarded read binds the exact chunk set and title/body revision. */
@@ -64,12 +73,12 @@ export async function readProjectionSnapshot(engine: BrainEngine, slug: string,
if (!snapshot || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;
const context = await indexingContext(tx, snapshot, opts.maxChunkTokens);
return { snapshot, chunks: await tx.getChunks(slug, { sourceId, includeUnsealed: true }), indexingContext: context.key,
- embeddingModel: context.model, maxChunkTokens: context.maxChunkTokens, maxChunkTokensOverride: opts.maxChunkTokens };
+ embeddingModel: context.model, embeddingColumn: context.column, maxChunkTokens: context.maxChunkTokens, maxChunkTokensOverride: opts.maxChunkTokens, pageKind: context.pageKind };
});
}
/** No provider work under the guard. Delayed derived results lose to newer content. */
-export async function installPageProjection(engine: BrainEngine, prepared: ProjectionSnapshot, chunks: ChunkInput[], opts: { seal?: boolean; signature?: string; preserveEmbeddings?: boolean } = {}): Promise<void> {
+export async function installPageProjection(engine: BrainEngine, prepared: ProjectionSnapshot, chunks: ChunkInput[], opts: { seal?: boolean; signature?: string; preserveEmbeddings?: boolean; code?: Awaited<ReturnType<typeof prepareCodeChunks>> } = {}): Promise<void> {
const { snapshot } = prepared;
const sourceId = snapshot.page.source_id;
const slug = snapshot.page.slug;
@@ -77,6 +86,8 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
await tx.lockPageKeys([{ sourceId, slug }]);
const current = await tx.readPageSnapshot(slug, { sourceId });
assertPageRevision(current, { expectedRevision: snapshot.revision });
+ const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);
+ if (!source || source.archived || current!.page.deleted_at) throw new PageRevisionConflictError(snapshot.revision, current!.revision);
if (current!.sourceIncarnation !== snapshot.sourceIncarnation || current!.page.id !== snapshot.page.id) {
throw new PageRevisionConflictError(snapshot.revision, current!.revision);
}
@@ -90,8 +101,25 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
|| context.key !== prepared.indexingContext) {
throw new PageProjectionConflictError(snapshot.revision, current!.revision);
}
- if (opts.seal && !opts.preserveEmbeddings) await tx.deleteChunks(slug, { sourceId });
+ if (opts.seal && opts.preserveEmbeddings) {
+ const byIndex = new Map(chunks.map(chunk => [chunk.chunk_index, chunk]));
+ const identity = (chunk: ChunkInput | Chunk) => [chunk.chunk_text, chunk.chunk_source,
+ chunk.language ?? null, chunk.symbol_name ?? null, chunk.symbol_type ?? null,
+ chunk.start_line ?? null, chunk.end_line ?? null, chunk.parent_symbol_path ?? null,
+ chunk.doc_comment ?? null, chunk.symbol_name_qualified ?? null, chunk.modality ?? 'text'];
+ const matching = stored.filter(chunk => {
+ const next = byIndex.get(chunk.chunk_index);
+ return next && digest(identity(chunk)) === digest(identity(next));
+ }).map(chunk => chunk.id);
+ await tx.executeRaw(`DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))`, [snapshot.page.id, matching]);
+ await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(context.column.name)}=NULL,
+ embedded_at=NULL,embedded_text_hash=NULL WHERE page_id=$1 AND
+ (model IS DISTINCT FROM $2 OR embedded_text_hash IS DISTINCT FROM md5(chunk_text) OR $3::boolean)`,
+ [snapshot.page.id, context.column.name === 'embedding' ? context.model : context.column.embeddingModel,
+ ![null, undefined, 'none'].includes(snapshot.page.contextual_retrieval_mode)]);
+ } else if (opts.seal) await tx.deleteChunks(slug, { sourceId });
await tx.upsertChunks(slug, chunks, { sourceId, expectedRevision: snapshot.revision, embeddingColumn: context.column });
+ if (opts.code) await installCodeChunkEdges(tx, slug, sourceId, opts.code);
if (opts.seal) {
await tx.executeRaw(`UPDATE pages SET chunker_version=$3
WHERE source_id=$1 AND slug=$2`, [sourceId, slug, MARKDOWN_CHUNKER_VERSION]);
@@ -152,12 +180,24 @@ export async function queuePageProjection(engine: Pick<BrainEngine, 'executeRaw'
ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision,reason=EXCLUDED.reason,updated_at=now()`, [sourceId, slug, reason]);
}
-/** Bounded and keyless. Code/image pages retain queued work for their source importer. */
+export async function preparePageProjection(prepared: ProjectionSnapshot) {
+ const page = prepared.snapshot.page;
+ if (prepared.pageKind === 'code') {
+ const path = typeof page.frontmatter.file === 'string' ? page.frontmatter.file : page.source_path;
+ if (!path) throw new Error('Code projection requires a recorded source path. Restore frontmatter.file or source_path before retrying.');
+ const code = await prepareCodeChunks(page, path);
+ return { chunks: code.chunks, code };
+ }
+ if (prepared.pageKind !== 'markdown') throw new Error('This page kind requires its source importer.');
+ return { chunks: await prepareMarkdownChunks(page, prepared.maxChunkTokens), code: undefined };
+}
+
+/** Bounded and keyless. Unsupported media remains queued for its source importer. */
export async function rebuildPendingPageProjections(engine: BrainEngine, limit = 20): Promise<{ rebuilt: number; superseded: number }> {
const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string }>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kind
FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation
JOIN pages p ON p.source_id=s.id AND p.slug=j.slug
- WHERE p.deleted_at IS NULL AND p.page_kind='markdown'
+ WHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')
ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, [Math.max(1, Math.min(limit, 100))]);
let rebuilt = 0;
let superseded = 0;
@@ -169,20 +209,27 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
if (!pending.length) return null;
return readProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });
});
- if (!prepared) { superseded++; continue; }
- const chunks: ChunkInput[] = [];
- for (const field of ['compiled_truth', 'timeline'] as const) {
- for (const chunk of chunkText(sanitizeRemoteBody(prepared.snapshot.page[field]), { maxTokens: prepared.maxChunkTokens })) {
- chunks.push({ chunk_index: chunks.length, chunk_text: chunk.text, chunk_source: field });
- }
- }
+ if (!prepared || prepared.snapshot.sourceIncarnation !== job.source_incarnation || prepared.snapshot.revision !== job.revision) { superseded++; continue; }
try {
- await installPageProjection(engine, prepared, chunks, { seal: true });
+ const projection = await preparePageProjection(prepared);
+ await installPageProjection(engine, prepared, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });
rebuilt++;
} catch (error) {
- if (!(error instanceof PageRevisionConflictError)) throw error;
+ if (!(error instanceof PageRevisionConflictError)) {
+ await engine.executeRaw(`UPDATE page_projection_jobs SET reason='rebuild_failed',updated_at=now()
+ WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);
+ process.stderr.write('[gbrain] Projection rebuild failed; work remains queued. Inspect projection readiness and the recorded source path.\n');
+ continue;
+ }
superseded++;
}
}
+ if (rebuilt > 0) {
+ const remaining = await engine.executeRaw(`SELECT 1 FROM page_projection_jobs j
+ JOIN sources s ON s.incarnation=j.source_incarnation JOIN pages p ON p.source_id=s.id AND p.slug=j.slug
+ WHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')
+ AND j.reason<>'rebuild_failed' LIMIT 1`);
+ if (!remaining.length) await refreshProjectionStatistics(engine);
+ }
return { rebuilt, superseded };
}
diff --git a/src/core/persistence/admin-contract.ts b/src/core/persistence/admin-contract.ts
index a15a876b8a..d1cad37e45 100644
--- a/src/core/persistence/admin-contract.ts
+++ b/src/core/persistence/admin-contract.ts
@@ -1,6 +1,6 @@
/** Local administration is deliberately absent from the public operation registry. */
export const PERSISTENCE_ADMIN_OPERATIONS = [
- 'writer_status', 'writer_sync', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept',
+ 'writer_status', 'writer_sync', 'writer_reindex_code', 'writer_claim', 'writer_activate', 'writer_transfer_prepare', 'writer_transfer_accept',
'local_writer_list', 'local_writer_register', 'local_writer_revoke',
'source_lifecycle', 'source_add',
] as const;
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index 618dee676d..c14cfeb5d7 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -57,6 +57,7 @@ async function registrationGrant(engine: BrainEngine, params: Record<string, unk
export async function runPersistenceAdministration(engine: BrainEngine, operation: PersistenceAdminOperation,
params: Record<string, unknown>): Promise<Record<string, unknown>> {
if (operation === 'writer_sync') return (await import('./sync-administration.ts')).runAuthenticatedSyncSlice(engine, params);
+ if (operation === 'writer_reindex_code') return (await import('./reindex-administration.ts')).runAuthenticatedCodeReindex(engine, params);
if (operation === 'source_add' || operation === 'source_lifecycle') {
const { managedPersistenceEnabled } = await import('./ownership.ts');
if (!await managedPersistenceEnabled(engine)) throw new OperationError('writer_coordinator_required',
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 6426c3990d..1ea800d6e1 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -26,6 +26,7 @@ export interface PreparedMutation {
additionalPageKeys?: readonly {sourceId:string;slug:string}[];
file?: { path: string; root: string; content: string | Uint8Array | null; expectedBeforeHash?: string | null };
noop?: boolean;
+ deferEmbedding?: boolean;
/** Must perform only transaction-composable database work. */
apply(tx: BrainEngine): Promise<Record<string, unknown>>;
validate?(tx: BrainEngine): Promise<void>;
diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.ts
index 44c6333501..7dc45b870e 100644
--- a/src/core/persistence/effect-journal.ts
+++ b/src/core/persistence/effect-journal.ts
@@ -27,8 +27,8 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques
if (outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });
}
if (snapshot && !snapshot.page.deleted_at) {
- await queue('embedding');
- outcome.embedding_state = 'queued';
+ if (!prepared?.deferEmbedding) await queue('embedding');
+ outcome.embedding_state = prepared?.deferEmbedding ? 'deferred' : 'queued';
if ((outcome.facts_backstop as { queued?: boolean } | undefined)?.queued) {
// Recheck activation/kill switch at publication, before promising work.
const [brain] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
diff --git a/src/core/persistence/projection-reindex.ts b/src/core/persistence/projection-reindex.ts
new file mode 100644
index 0000000000..51cf775341
--- /dev/null
+++ b/src/core/persistence/projection-reindex.ts
@@ -0,0 +1,75 @@
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import type { OperationContext } from '../ops/contract.ts';
+import { OperationError } from '../ops/contract.ts';
+import { loadConfig } from '../config.ts';
+import { readProjectionSnapshot, preparePageProjection, installPageProjection, installPageEmbeddings } from '../page-state/projections.ts';
+import { embedBatchWithBackoff } from '../embed-retry.ts';
+import { submissionAuthority } from './authority.ts';
+import { currentVerifiedLocalWriter, registerLocalWriter } from './identity.ts';
+import { getWorktreeBinding, managedPersistenceEnabled } from './ownership.ts';
+import { admitWrite } from './journal.ts';
+import { waitForWrite, writeResponse } from './service.ts';
+import type { PreparedMutation } from './coordinator.ts';
+import type { WriteRequest } from './model.ts';
+
+export async function prepareCodeReindex(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ if (row.authority.remote || row.intent?.kind !== 'code_projection_reindex') throw new OperationError('permission_denied', 'Code reindex requires trusted local authority.');
+ const prepared = await readProjectionSnapshot(engine, row.slug, row.source_id, { allowUnsealed: true });
+ if (!prepared || prepared.pageKind !== 'code' || prepared.snapshot.revision !== row.intent.expected_revision
+ || prepared.snapshot.sourceIncarnation !== row.source_incarnation || prepared.snapshot.page.id !== row.page_id) {
+ throw new OperationError('revision_conflict', 'The code projection changed after reindex admission.');
+ }
+ const noop = row.intent.force !== true && prepared.snapshot.page.text_projection_revision === prepared.snapshot.revision;
+ const projection = noop ? undefined : await preparePageProjection(prepared);
+ return { observedRevision: prepared.snapshot.revision, noop, deferEmbedding: true, apply: async tx => {
+ if (projection) await installPageProjection(tx, prepared, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });
+ return { status: noop ? 'skipped' : 'imported', chunks: projection?.chunks.length ?? 0, noop };
+ } };
+}
+
+export async function reindexCodeProjection(engine: BrainEngine, slug: string, sourceId: string,
+ opts: { force?: boolean; noEmbed?: boolean } = {}): Promise<{ status: 'imported' | 'skipped'; chunks: number }> {
+ const snapshot = await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true });
+ if (!snapshot || snapshot.pageKind !== 'code') throw new OperationError('source_changed', 'The selected code page is unavailable.');
+ let result: { status: 'imported' | 'skipped'; chunks: number };
+ if (await managedPersistenceEnabled(engine)) {
+ const verified = currentVerifiedLocalWriter();
+ if (verified?.remote) throw new OperationError('permission_denied', 'Code reindex requires a local CLI writer.');
+ if (!verified) await registerLocalWriter(engine, 'cli');
+ const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext,
+ 'submit_job', sourceId, snapshot.snapshot.sourceIncarnation, slug);
+ const binding = await getWorktreeBinding(engine, sourceId);
+ if (!binding) authority.databaseOnlyReason = 'no_repo_configured';
+ const intent = { kind: 'code_projection_reindex', expected_revision: snapshot.snapshot.revision, force: opts.force === true };
+ const row = await admitWrite(engine, { requestId: randomUUID(), operation: 'submit_job', sourceId,
+ sourceIncarnation: snapshot.snapshot.sourceIncarnation, slug, pageId: snapshot.snapshot.page.id,
+ principal: authority.principal, authority, callerIntent: intent, intent,
+ worktreeId: binding?.worktree_id, topologyGeneration: binding?.topology_generation });
+ const done = await waitForWrite(engine, row, loadConfig() ?? { engine: engine.kind }, 5000);
+ writeResponse(done);
+ result = done.outcome as typeof result;
+ } else if (!opts.force && snapshot.snapshot.page.text_projection_revision === snapshot.snapshot.revision) {
+ result = { status: 'skipped', chunks: 0 };
+ } else {
+ const projection = await preparePageProjection(snapshot);
+ await installPageProjection(engine, snapshot, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });
+ result = { status: 'imported', chunks: projection.chunks.length };
+ }
+ if (!opts.noEmbed && result.status === 'imported') {
+ const prepared = await readProjectionSnapshot(engine, slug, sourceId);
+ if (!prepared) throw new OperationError('revision_conflict', 'Code changed before embedding preparation.');
+ const chunks = prepared.chunks.filter(c => c.embedding_is_null);
+ if (chunks.length) {
+ if (prepared.embeddingColumn.embeddingModel && prepared.embeddingColumn.embeddingModel !== prepared.embeddingModel) {
+ throw new OperationError('embedding_model_mismatch', 'The configured provider does not match the active embedding column. Text recovery is complete; configure the matching model before embedding.');
+ }
+ const vectors = await embedBatchWithBackoff(chunks.map(c => c.chunk_text));
+ const installed = await installPageEmbeddings(engine, prepared, chunks.map((c, i) => ({
+ chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source,
+ model: prepared.embeddingModel ?? undefined, embedding: vectors[i] })));
+ if (!installed) throw new OperationError('revision_conflict', 'Code changed while embedding; text remains queued or searchable without new vectors.');
+ }
+ }
+ return result;
+}
diff --git a/src/core/persistence/reindex-administration.ts b/src/core/persistence/reindex-administration.ts
new file mode 100644
index 0000000000..fbc559ad39
--- /dev/null
+++ b/src/core/persistence/reindex-administration.ts
@@ -0,0 +1,26 @@
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { currentVerifiedLocalWriter } from './identity.ts';
+import { runReindexCode, type ReindexCodeOpts } from '../../commands/reindex-code.ts';
+
+export async function runAuthenticatedCodeReindex(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {
+ const verified = currentVerifiedLocalWriter();
+ if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Code reindex requires a trusted CLI registration.');
+ if (Object.keys(params).some(k => k !== 'options') || !params.options || typeof params.options !== 'object' || Array.isArray(params.options)) throw new OperationError('invalid_params', 'Code reindex requires typed options.');
+ const options = params.options as Record<string, unknown>;
+ const allowed = ['sourceId', 'dryRun', 'yes', 'json', 'force', 'noEmbed', 'workers', 'maxCostUsd'];
+ if (Object.keys(options).some(k => !allowed.includes(k)) ||
+ ['dryRun', 'yes', 'json', 'force', 'noEmbed'].some(k => options[k] !== undefined && typeof options[k] !== 'boolean') ||
+ options.sourceId !== undefined && (typeof options.sourceId !== 'string' || !options.sourceId) ||
+ options.workers !== undefined && (!Number.isInteger(options.workers) || Number(options.workers) < 1 || Number(options.workers) > 64) ||
+ options.maxCostUsd !== undefined && (typeof options.maxCostUsd !== 'number' || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)) throw new OperationError('invalid_params', 'Invalid code reindex options.');
+ if (!options.noEmbed && !options.dryRun && !options.yes) throw new OperationError('confirmation_required', 'Explicit embedding consent is required; use --no-embed for keyless recovery.');
+ if (!verified.grant.scopes.includes('write') || verified.grant.operations !== null && !verified.grant.operations.includes('submit_job') ||
+ verified.grant.slugPrefixes !== null || !verified.grant.sourceIds.includes('*') &&
+ (typeof options.sourceId !== 'string' || !verified.grant.sourceIds.includes(options.sourceId))) {
+ throw new OperationError('permission_denied', 'Code reindex exceeds the CLI source-wide write grant.');
+ }
+ const work = runReindexCode(engine, options as ReindexCodeOpts);
+ const unregister = engine.registerBeforeDisconnect(async () => { await work.catch(() => {}); });
+ try { return { ...await work }; } finally { unregister(); }
+}
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index 5090ecfeec..43ac75fe54 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -22,6 +22,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConf
const consumer = new PersistenceConsumer(engine, config, async (e, row, cfg) => {
const registered = preparers.get(row.operation);
if (registered) return registered(e, row, cfg);
+ if (row.operation === 'submit_job' && row.intent?.kind === 'code_projection_reindex') return (await import('./projection-reindex.ts')).prepareCodeReindex(e, row);
if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_sync_')) return (await import('./sync-prepare.ts')).prepareManagedSyncMutation(e, row, cfg);
if (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg);
if (['takes_add','takes_update','takes_supersede','takes_resolve'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 81d8968825..5ac8c35961 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -6,7 +6,7 @@ import type { SyncOpts } from '../../commands/sync.ts';
import { parseMarkdown } from '../markdown.ts';
import { OperationError } from '../ops/contract.ts';
import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';
-import { isSyncable, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';
+import { isSyncable, isCodeFilePath, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';
import { resolveSlugRootMode } from '../sync-anchor.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
@@ -101,7 +101,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
for (const rename of dirty.renamed) { put(rename.from, 'delete', true); put(rename.to, 'import', true); }
}
const selected = [...entries.values()].sort((a, b) => a.action.localeCompare(b.action) || a.path.localeCompare(b.path));
- if (selected.some(e => !/\.mdx?$/i.test(e.path))) throw new OperationError('writer_coordinator_required', 'Managed code/image sync requires a prepared importer; this sync was refused before any page write.');
+ if (selected.some(e => !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path))) throw new OperationError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.');
if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw new OperationError('request_too_large', 'Sync discovery exceeds the bounded cursor size.');
const discovered: SyncDiscovery = { binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode };
// Freeze all logical identities in one database statement, before yielding
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 4efefdd647..4771435939 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -3,9 +3,9 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page } from '../types.ts';
import { OperationError } from '../ops/contract.ts';
-import { importFromContent } from '../import-file.ts';
+import { importFromContent, importCodeFile } from '../import-file.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
-import { resolveSlugForPath, slugifyPath } from '../sync.ts';
+import { resolveSlugForPath, slugifyPath, isCodeFilePath } from '../sync.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
import { sameCanonicalImport } from '../page-state/import-guard.ts';
import { assertPageRevision } from '../page-state/types.ts';
@@ -72,6 +72,22 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };
} };
if (typeof p.content !== 'string' || typeof p.sourcePath !== 'string' || typeof p.path !== 'string') throw new OperationError('storage_error', 'The frozen import content is missing.');
+ if (isCodeFilePath(p.sourcePath)) {
+ if (snapshot && p.rawHash !== sha256(p.content) && snapshot.page.compiled_truth !== p.content) {
+ throw new OperationError('source_changed', 'Newer code file bytes disagree with the pinned import.');
+ }
+ let prepared: PreparedContentImport | undefined;
+ const result = await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true,
+ prepare: async value => { prepared = value; return value.result; } });
+ if (!prepared || prepared.slug !== row.slug) throw new OperationError('invalid_params', result.error ?? 'The code file identity could not be prepared.');
+ const ready = prepared;
+ if (ready.observedRevision !== (snapshot?.revision ?? null)) throw new OperationError('revision_conflict', 'The code page changed during preparation.');
+ return { observedRevision: ready.observedRevision, validate, noop: ready.noop, deferEmbedding: true, apply: async tx => {
+ await ready.apply(tx);
+ return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
+ chunks: result.chunks, noop: ready.noop, imported_file: true };
+ } };
+ }
const parsedInput = parseMarkdown(p.content, row.slug);
const expectedSlug = resolveSlugForPath(p.sourcePath);
if (expectedSlug && parsedInput.slug !== expectedSlug && slugifyPath(parsedInput.slug) !== expectedSlug) {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index bf24adecd4..c9c406a850 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -10,6 +10,7 @@ import { assertPersistenceAccepting, foregroundWriteCompletions, startPersistenc
import { discoverManagedSync, resolveManagedSyncContext, readSyncContent, syncRawHash, type SyncDiscovery } from './sync-discovery.ts';
import { managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, type SyncAuthority } from './sync-authority.ts';
import type { SyncIntent } from './sync-prepare.ts';
+import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
interface Pending { requestId: string; slug: string; pageId: number | null; intent: SyncIntent; }
interface Cursor extends SyncDiscovery { runId: string; index: number; authority: SyncAuthority; pending?: Pending; done?: boolean;
@@ -154,6 +155,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
if (pending.intent.kind === 'managed_sync_checkpoint') {
cursor = (await readCursor(engine, key))!;
if (!cursor?.done) throw new OperationError('storage_error', 'Committed sync checkpoint lost its cursor.');
+ if (cursor.counts.added + cursor.counts.modified + cursor.counts.deleted > 0) await refreshProjectionStatistics(engine);
return result(cursor, cursor.from === null ? 'first_sync' : 'synced');
}
// The frozen manifest is shared; only the cursor header changes per page.
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 41592f2036..392b812220 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -67,7 +67,9 @@ import {
} from './chronicle/ontology.ts';
import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';
import { runMigrations } from './migrate.ts';
-import { hnswEfSearchFor, hnswIndexExpected, HNSW_EF_SEARCH_MAX } from './vector-index.ts';
+import { hnswIndexExpected, supportsHnswIterativeScan } from './vector-index.ts';
+import { searchVectorPool, readVectorPool } from './search/vector-pool.ts';
+import { withVectorSettings } from './search/vector-settings.ts';
import { PGLITE_SCHEMA_SQL, getPGLiteSchema } from './pglite-schema.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';
@@ -354,6 +356,7 @@ export function computeSnapshotSchemaHash(
hash.update('files:v3\n');
for (const file of [
'migrate.ts', 'pglite-schema.ts', 'fts-language.ts', 'vector-index.ts', 'ai/defaults.ts',
+ 'search/projection-statistics.ts',
'timeline-dedup-repair.ts', 'pages-upsert-arbiter.ts', 'link-extraction.ts',
'grants/schema.ts', 'grants/migration.ts', 'grants/model.ts', 'grants/service.ts', 'grants/profiles.ts',
'page-state/schema.ts', 'lease-schema.ts', 'page-state/projection-schema.ts', 'persistence/schema.ts', 'persistence/effect-schema.ts', 'persistence/writer-guard-schema.ts', 'persistence/topology-schema.ts', 'scope.ts', 'sql-query.ts', 'minions/tools/brain-allowlist.ts', 'facts/withdrawal-schema.ts',
@@ -702,6 +705,7 @@ export async function probePgliteScratchStore(
}
export class PGLiteEngine implements BrainEngine {
+ private vectorIterativeScan?: Promise<boolean>;
/** Transaction clones keep chunk invalidation and replacement atomic. */
private _chunkWritesInTransaction = false;
readonly kind = 'pglite' as const;
@@ -753,6 +757,7 @@ export class PGLiteEngine implements BrainEngine {
}
return this._connectPromise ?? undefined;
}
+ this.vectorIterativeScan = undefined;
const opening = this._connectInternal(config).then(async () => {
try { await registerManagedFilesystemEngine(this, config.database_path); }
catch (error) {
@@ -929,6 +934,7 @@ export class PGLiteEngine implements BrainEngine {
}
async disconnect(): Promise<void> {
+ this.vectorIterativeScan = undefined;
if (this._disconnectCall) return this._disconnectCall;
if (this._closePoison) throw this._closePoison;
this._disconnectRequested = true;
@@ -2473,11 +2479,11 @@ export class PGLiteEngine implements BrainEngine {
// got reimported). Same param shape as Postgres engine.
if (opts?.afterDate) {
params.push(opts.afterDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
// v0.34.1 (#861 — P0 leak seal): source-isolation. Array wins over scalar.
if (opts?.sourceIds && opts.sourceIds.length > 0) {
@@ -2514,7 +2520,7 @@ export class PGLiteEngine implements BrainEngine {
-- OCR text doesn't drown text-page hits. Image-similarity queries
-- run a separate vector path on embedding_image.
AND cc.modality = 'text'
- ORDER BY score DESC
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT $2
),
${buildBestPerPagePoolCte('ranked')}
@@ -2599,11 +2605,11 @@ export class PGLiteEngine implements BrainEngine {
}
if (opts?.afterDate) {
params.push(opts.afterDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
if (opts?.sourceIds && opts.sourceIds.length > 0) {
params.push(opts.sourceIds);
@@ -2763,11 +2769,11 @@ export class PGLiteEngine implements BrainEngine {
// v0.29.1 since/until parity (codex pass-1 #10).
if (opts?.afterDate) {
params.push(opts.afterDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
// v0.34.1 (#861 — P0 leak seal): source-isolation for the chunk-grain
// anchor primitive. Layer 7 two-pass walks from these anchors so a
@@ -2802,7 +2808,7 @@ export class PGLiteEngine implements BrainEngine {
JOIN pages p ON p.id = cc.page_id
JOIN sources s ON s.id = p.source_id
WHERE cc.search_vector @@ websearch_to_tsquery('${ftsLang}', $1) ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
- ORDER BY score DESC
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT $2 OFFSET $3`,
params
);
@@ -2840,23 +2846,29 @@ export class PGLiteEngine implements BrainEngine {
const sourceFactorCaseOnSlug = buildSourceFactorCase('slug', boostMap, opts?.detail, 'unverified_stub');
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
- // v0.46.15 (retrieval-cathedral P1): bounded escalation — see
- // postgres-engine.ts searchVector for the full rationale; the logic here
- // is IDENTICAL (engine-parity pinned). Cap policy (R2-10 + codex ship
- // review): the ef_search ceiling applies only to HNSW-backed columns;
- // above-ceiling columns fall back to exact scans where capping the SQL
- // LIMIT would make offset >= 1000 permanently empty — those stay bounded
- // by the escalation count instead. (Hoisted resolvedColEarly: same
- // descriptor the cast fragment uses below.)
const resolvedColEarly = normalizeEngineColumn(opts?.embeddingColumn);
- const innerCap = hnswIndexExpected(resolvedColEarly.type, resolvedColEarly.dimensions)
- ? HNSW_EF_SEARCH_MAX
- : Number.MAX_SAFE_INTEGER;
- const innerLimit = Math.min(offset + Math.max(limit * 5, 100), innerCap);
-
- const params: unknown[] = [vecStr, innerLimit, limit, offset];
- const innerLimitIdx = 1; // mutated by the escalation loop
+ const indexed = hnswIndexExpected(resolvedColEarly.type, resolvedColEarly.dimensions);
+ const innerLimit = offset + Math.max(limit * 5, 100);
+ this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(
+ `SELECT extversion FROM pg_extension WHERE extname = 'vector'`,
+ ).then(rows => supportsHnswIterativeScan(rows[0]?.extversion));
+ const probe = this.vectorIterativeScan;
+ let iterative: boolean;
+ try { iterative = await probe; }
+ catch (error) {
+ if (this.vectorIterativeScan === probe) this.vectorIterativeScan = undefined;
+ throw error;
+ }
+ const params: unknown[] = [vecStr];
let extraFilter = '';
+ if (opts?.type) {
+ params.push(opts.type);
+ extraFilter += ` AND p.type = $${params.length}`;
+ }
+ if (opts?.exclude_slugs?.length) {
+ params.push(opts.exclude_slugs);
+ extraFilter += ` AND p.slug != ALL($${params.length}::text[])`;
+ }
if (opts?.language) {
params.push(opts.language);
extraFilter += ` AND cc.language = $${params.length}`;
@@ -2877,11 +2889,11 @@ export class PGLiteEngine implements BrainEngine {
// pages — preserves pagination contract.
if (opts?.afterDate) {
params.push(opts.afterDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
// v0.34.1 (#861, F2 — P0 leak seal): source-isolation in the INNER CTE
// so HNSW candidate pool narrows before re-rank. Mirrors postgres-engine
@@ -2894,6 +2906,12 @@ export class PGLiteEngine implements BrainEngine {
extraFilter += ` AND p.source_id = $${params.length}`;
}
+ const innerLimitIdx = params.length;
+ params.push(innerLimit, limit, offset);
+ const innerLimitParam = `$${innerLimitIdx + 1}`;
+ const limitParam = `$${innerLimitIdx + 2}`;
+ const offsetParam = `$${innerLimitIdx + 3}`;
+
// v0.26.5: visibility filter applied in the inner CTE so HNSW sees the
// same candidate count it always did. See postgres-engine.ts for rationale.
const visibilityClause = buildVisibilityClause('p', 's', opts);
@@ -2916,14 +2934,11 @@ export class PGLiteEngine implements BrainEngine {
modalityFilter = `AND cc.modality = 'text'`;
}
- // hnsw.ef_search: an HNSW scan returns at most ef_search rows (default
- // 40), so LIMIT $2 past 40 was silently unreachable — see hnswEfSearchFor.
- // SET LOCAL semantics need a transaction (PGLite autocommits bare
- // queries); scoping it locally keeps the engine's single session clean.
- const runOnce = async (il: number) => (await this.db.transaction(async (tx) => {
- await tx.query(`SELECT set_config('hnsw.ef_search', $1, true)`, [String(hnswEfSearchFor(il))]);
- return tx.query(
- `WITH hnsw_candidates AS (
+ const candidateFrom = `FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ JOIN sources s ON s.id = p.source_id
+ WHERE cc.${col} IS NOT NULL ${modalityFilter} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}`;
+ const rawQuery = `WITH hnsw_candidates AS (
SELECT
p.slug, p.id as page_id, p.title, p.type, p.source_id, p.updated_at,
p.effective_date, p.effective_date_source,
@@ -2934,12 +2949,9 @@ export class PGLiteEngine implements BrainEngine {
cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
(${unverifiedExtractionFragment('p')}) AS unverified_stub,
1 - (cc.${col} <=> ${castSql}) AS raw_score
- FROM content_chunks cc
- JOIN pages p ON p.id = cc.page_id
- JOIN sources s ON s.id = p.source_id
- WHERE cc.${col} IS NOT NULL ${modalityFilter} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
+ ${candidateFrom}
ORDER BY cc.${col} <=> ${castSql}
- LIMIT $2
+ LIMIT ${innerLimitParam}
),
-- score as a select-list expr; inner ORDER BY stays pure-distance so
-- the HNSW index is usable.
@@ -2950,7 +2962,8 @@ export class PGLiteEngine implements BrainEngine {
-- T1 (retrieval-maxpool incident): collapse to the best chunk PER PAGE
-- over the full candidate set before the user LIMIT. Shared builder with
-- postgres-engine + the keyword path so they cannot drift.
- ${buildBestPerPagePoolCte('scored')}
+ ${buildBestPerPagePoolCte('scored')},
+ page_results AS (
SELECT
bpp.slug, bpp.page_id, bpp.title, bpp.type, bpp.source_id,
bpp.effective_date, bpp.effective_date_source,
@@ -2959,8 +2972,7 @@ export class PGLiteEngine implements BrainEngine {
bpp.score,
CASE WHEN bpp.updated_at < (
SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = bpp.page_id
- ) THEN true ELSE false END AS stale,
- (SELECT count(*) FROM hnsw_candidates)::int AS candidate_pool
+ ) THEN true ELSE false END AS stale
FROM best_per_page bpp
-- v0.41.13: stable tiebreaker. When two chunks share a score (same
-- source-prefix boost + same cosine distance, the basis-vector + same-
@@ -2969,39 +2981,32 @@ export class PGLiteEngine implements BrainEngine {
-- master and feature branches that add unrelated indexes — see the
-- pages_dedup_idx (v95) regression that motivated this.
ORDER BY bpp.score DESC, bpp.page_id ASC, bpp.chunk_id ASC
- LIMIT $3
- OFFSET $4`,
- params
- );
- })).rows;
-
- // v0.46.15 bounded escalation loop — IDENTICAL logic to postgres-engine
- // (parity-pinned): retry ×4 up to 3 times while the PAGE set is short
- // but the pre-collapse candidate pool was full; a short page with a
- // non-full pool is a genuine final page. Zero rows with offset>0
- // escalates (deep pagination) but never emits — pool unknowable there.
- let escalations = 0;
- let rows = await runOnce(innerLimit);
- for (;;) {
- const il = params[innerLimitIdx] as number;
- if (rows.length >= limit) break;
- const pool = rows.length > 0
- ? Number((rows[0] as { candidate_pool?: number }).candidate_pool ?? 0)
- : null;
- const shouldEscalate = pool !== null ? pool >= il : offset > 0;
- if (!shouldEscalate) break;
- if (il >= innerCap || escalations >= 3) {
- if (pool !== null && pool >= il) {
- opts?.onVectorPoolMeta?.({ underfilled: true, escalations, innerLimit: il });
- }
- break;
- }
- params[innerLimitIdx] = Math.min(il * 4, innerCap);
- escalations++;
- rows = await runOnce(params[innerLimitIdx] as number);
- }
-
- return (rows as Record<string, unknown>[]).map(rowToSearchResult);
+ LIMIT ${limitParam}
+ OFFSET ${offsetParam}
+ )
+ SELECT page_results.*, pool.candidate_pool
+ FROM (SELECT count(*)::int AS candidate_pool FROM hnsw_candidates) pool
+ LEFT JOIN page_results ON true
+ ORDER BY score DESC NULLS LAST, page_id ASC, chunk_id ASC`;
+
+ const rows = await searchVectorPool(limit, innerLimit, iterative, indexed, 'pglite',
+ async ({ innerLimit: requested, maxScanTuples }) => this.db.transaction(async tx => {
+ return withVectorSettings(async (sql, values) => (await tx.query<Record<string, unknown>>(sql, values)).rows, iterative, requested, maxScanTuples, async () => {
+ const bound = [...params];
+ bound[innerLimitIdx] = requested;
+ return readVectorPool((await tx.query<Record<string, unknown>>(rawQuery, bound)).rows);
+ });
+ }),
+ async pool => {
+ const bound = [...params.slice(0, innerLimitIdx), pool + 1];
+ const { rows } = await this.db.query<{ eligible: number }>(`SELECT count(*)::int AS eligible FROM (
+ SELECT 1 ${candidateFrom} AND $1::text IS NOT NULL LIMIT $${bound.length}
+ ) eligible`, bound);
+ return Number(rows[0].eligible) > pool;
+ },
+ opts?.onVectorPoolMeta,
+ );
+ return rows.map(rowToSearchResult);
}
async getEmbeddingsByChunkIds(
diff --git a/src/core/pglite-engine/code-edges.ts b/src/core/pglite-engine/code-edges.ts
index 9aa43c5ada..de53dcd2c7 100644
--- a/src/core/pglite-engine/code-edges.ts
+++ b/src/core/pglite-engine/code-edges.ts
@@ -4,6 +4,7 @@
* never the whole engine class.
*/
import type { PGlite } from '@electric-sql/pglite';
+import { currentCodeEdgeFilter } from '../code-intel/read-scope.ts';
// PGLite's parameter bridge corrupts the current engine session when a single
// statement crosses the signed-int16 bind ceiling (32,767 parameters). Keep
@@ -104,11 +105,13 @@ export async function getCallersOf(
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
WHERE to_symbol_qualified = $1 ${sourceClause}
+ AND ${currentCodeEdgeFilter('code_edges_chunk', true)}
UNION ALL
SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, false as resolved
FROM code_edges_symbol
WHERE to_symbol_qualified = $1 ${sourceClause}
+ AND ${currentCodeEdgeFilter('code_edges_symbol', false)}
LIMIT $2`,
[qualifiedName, limit],
);
@@ -129,11 +132,13 @@ export async function getCalleesOf(
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
WHERE ${fromPredicate} ${sourceClause}
+ AND ${currentCodeEdgeFilter('code_edges_chunk', true)}
UNION ALL
SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, false as resolved
FROM code_edges_symbol
WHERE ${fromPredicate} ${sourceClause}
+ AND ${currentCodeEdgeFilter('code_edges_symbol', false)}
LIMIT $2`,
[qualifiedName, limit],
);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index b15bd8a682..fdafdbccf1 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -54,7 +54,9 @@ import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from
import { runMigrations } from './migrate.ts';
import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { verifySchema } from './schema-verify.ts';
-import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, hnswEfSearchFor, hnswIndexExpected, HNSW_EF_SEARCH_MAX } from './vector-index.ts';
+import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, hnswIndexExpected, supportsHnswIterativeScan } from './vector-index.ts';
+import { searchVectorPool, readVectorPool, remainingVectorBudget } from './search/vector-pool.ts';
+import { withVectorSettings } from './search/vector-settings.ts';
import {
normalizeEngineColumn,
buildVectorCastFragment,
@@ -151,6 +153,7 @@ export function getPostgresSchema(
// follow-up that will reintroduce a typed retry mechanism.
export class PostgresEngine implements BrainEngine {
+ private vectorIterativeScan?: Promise<boolean>;
/** Transaction clones keep chunk invalidation and replacement atomic. */
private _chunkWritesInTransaction = false;
readonly kind = 'postgres' as const;
@@ -306,6 +309,7 @@ export class PostgresEngine implements BrainEngine {
// Lifecycle
async connect(config: EngineConfig & { poolSize?: number; parentConnectionManager?: ConnectionManager }): Promise<void> {
+ this.vectorIterativeScan = undefined;
this._savedConfig = config;
const url = config.database_url;
if (config.poolSize) {
@@ -380,6 +384,7 @@ export class PostgresEngine implements BrainEngine {
}
async disconnect(): Promise<void> {
+ this.vectorIterativeScan = undefined;
if (this._disconnectPromise) return this._disconnectPromise;
const work = this.disconnectInternal();
this._disconnectPromise = work;
@@ -1441,7 +1446,7 @@ export class PostgresEngine implements BrainEngine {
if (hasCJK(query)) {
return this._searchKeywordCJK(query, {
limit, offset, innerLimit, sourceFactorCase, hardExcludeClause,
- visibilityClause: buildVisibilityClause('p', 's'),
+ visibilityClause: buildVisibilityClause('p', 's', opts),
detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',
opts, dedup: true,
});
@@ -1479,12 +1484,12 @@ export class PostgresEngine implements BrainEngine {
let afterDateClause = '';
if (opts?.afterDate) {
params.push(opts.afterDate);
- afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
let beforeDateClause = '';
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
// v0.34.1 (#861 — P0 leak seal): source-isolation filter. When the
// caller's auth scope is set, narrow the inner CTE candidate set so
@@ -1548,7 +1553,7 @@ export class PostgresEngine implements BrainEngine {
-- doesn't drown text-page hits. Image search runs a separate
-- vector path on embedding_image.
AND cc.modality = 'text'
- ORDER BY score DESC
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT ${innerLimitParam}
),
${buildBestPerPagePoolCte('ranked_chunks')}
@@ -1558,7 +1563,7 @@ export class PostgresEngine implements BrainEngine {
chunk_id, chunk_index, chunk_text, chunk_source, score,
false AS stale
FROM best_per_page
- ORDER BY score DESC
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT ${limitParam}
OFFSET ${offsetParam}
`;
@@ -1569,12 +1574,16 @@ export class PostgresEngine implements BrainEngine {
// the GUC can never leak onto a pooled connection). Flag off → the
// wrap is identical to master's; flag on → set_config('app.scopes')
// shares the same transaction as the timeout.
- const runKeyword = (queryText: string) =>
+ const runKeyword = (queryText: string, relaxed = false) =>
this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {
await tx`SET LOCAL statement_timeout = '8s'`;
+ const previous = relaxed ? await tx`SHOW enable_seqscan` : [];
+ if (relaxed) await tx`SET LOCAL enable_seqscan = off`;
const boundParams = [...params];
boundParams[0] = queryText;
- return await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);
+ const rows = await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);
+ if (relaxed) await tx`SELECT set_config('enable_seqscan', ${previous[0].enable_seqscan}, true)`;
+ return rows;
}, { alwaysTransaction: true });
let rows = await runKeyword(query);
// D2 fix (fix/title-retrieval-arm): websearch AND semantics at chunk
@@ -1589,7 +1598,7 @@ export class PostgresEngine implements BrainEngine {
if (rows.length === 0 && opts?.orFallback) {
const orQuery = buildOrFallbackWebsearchQuery(query);
if (orQuery) {
- rows = await runKeyword(orQuery);
+ rows = await runKeyword(orQuery, true);
// 2026-09 (#3617 follow-up): relaxed rows are TAGGED so hybrid's
// fusion can demote them — an OR-of-common-terms match must not
// outvote a healthy vector arm (SearchResult.keyword_relaxed doc).
@@ -1654,12 +1663,12 @@ export class PostgresEngine implements BrainEngine {
let afterDateClause = '';
if (opts?.afterDate) {
params.push(opts.afterDate);
- afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
let beforeDateClause = '';
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
let sourceClause = '';
if (opts?.sourceIds && opts.sourceIds.length > 0) {
@@ -1723,18 +1732,23 @@ export class PostgresEngine implements BrainEngine {
// the SET LOCAL statement_timeout needs a transaction regardless of the
// GBRAIN_RLS_SCOPE_BINDING flag). The OR retry re-executes through the
// same scoped wrapper.
- const runTitles = (queryText: string) =>
+ const runTitles = (queryText: string, relaxed = false) =>
this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {
await tx`SET LOCAL statement_timeout = '8s'`;
+ const preferIndex = relaxed && !requiresSafeChunks(opts);
+ const previous = preferIndex ? await tx`SHOW enable_seqscan` : [];
+ if (preferIndex) await tx`SET LOCAL enable_seqscan = off`;
const boundParams = [...params];
boundParams[0] = queryText;
- return await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);
+ const rows = await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);
+ if (preferIndex) await tx`SELECT set_config('enable_seqscan', ${previous[0].enable_seqscan}, true)`;
+ return rows;
}, { alwaysTransaction: true });
let rows = await runTitles(params[0] as string);
if (rows.length === 0) {
const orQuery = buildOrFallbackWebsearchQuery(params[0] as string);
if (orQuery) {
- rows = await runTitles(boundWebsearchQuery(orQuery));
+ rows = await runTitles(boundWebsearchQuery(orQuery), true);
// 2026-09 (#3617 follow-up): same relaxed-row tagging as the keyword
// arm — see SearchResult.keyword_relaxed.
return rows.map((r) => ({ ...rowToSearchResult(r), keyword_relaxed: true as const }));
@@ -1781,7 +1795,7 @@ export class PostgresEngine implements BrainEngine {
limit, offset,
innerLimit: 0, // unused on chunk-grain (no inner CTE)
sourceFactorCase, hardExcludeClause,
- visibilityClause: buildVisibilityClause('p', 's'),
+ visibilityClause: buildVisibilityClause('p', 's', opts),
detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',
opts, dedup: false,
});
@@ -1819,12 +1833,12 @@ export class PostgresEngine implements BrainEngine {
let afterDateClause = '';
if (opts?.afterDate) {
params.push(opts.afterDate);
- afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
let beforeDateClause = '';
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
// v0.34.1 (#861 — P0 leak seal): source-isolation. Anchor primitive
// for two-pass retrieval, so cross-source anchors would let the walk
@@ -1874,7 +1888,7 @@ export class PostgresEngine implements BrainEngine {
${sourceClause}
${hardExcludeClause}
${visibilityClause}
- ORDER BY score DESC
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT ${limitParam}
OFFSET ${offsetParam}
`;
@@ -1944,22 +1958,18 @@ export class PostgresEngine implements BrainEngine {
// (Hoisted above innerLimit so the escalation cap can key off the
// column's index eligibility.)
const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);
- // v0.46.15 (retrieval-cathedral P1): innerLimit counts CHUNKS before the
- // best-per-page DISTINCT collapse — one dense page (150+ chunks near the
- // query) could consume the whole pool and underfill the PAGE result. The
- // execution below runs a bounded escalation loop (×4, ≤3 times) when the
- // page set comes back short while the candidate pool was FULL (more
- // candidates existed). Cap policy (outside-voice R2-10 + codex ship
- // review): for HNSW-backed columns the scan returns at most ef_search
- // rows and the GUC ceilings at 1000, so inner limits beyond that are
- // fictitious. Columns ABOVE the index dim ceiling (e.g. vector >2000d)
- // fall back to exact scans where ef_search is irrelevant — capping their
- // SQL LIMIT would make offset >= 1000 permanently empty; they stay
- // bounded by the escalation count instead.
- const innerCap = hnswIndexExpected(resolvedCol.type, resolvedCol.dimensions)
- ? HNSW_EF_SEARCH_MAX
- : Number.MAX_SAFE_INTEGER;
- const innerLimit = Math.min(offset + Math.max(limit * 5, 100), innerCap);
+ const indexed = hnswIndexExpected(resolvedCol.type, resolvedCol.dimensions);
+ const innerLimit = offset + Math.max(limit * 5, 100);
+ this.vectorIterativeScan ??= this.executeRaw<{ extversion: string }>(
+ `SELECT extversion FROM pg_extension WHERE extname = 'vector'`,
+ ).then(rows => supportsHnswIterativeScan(rows[0]?.extversion));
+ const probe = this.vectorIterativeScan;
+ let iterative: boolean;
+ try { iterative = await probe; }
+ catch (error) {
+ if (this.vectorIterativeScan === probe) this.vectorIterativeScan = undefined;
+ throw error;
+ }
const params: unknown[] = [vecStr];
let typeClause = '';
@@ -1993,12 +2003,12 @@ export class PostgresEngine implements BrainEngine {
let afterDateClause = '';
if (opts?.afterDate) {
params.push(opts.afterDate);
- afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ afterDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
let beforeDateClause = '';
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ beforeDateClause = `AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
// v0.34.1 (#861, F2 — P0 leak seal): source-isolation in the INNER CTE
// specifically. Pushing the filter inside narrows the HNSW candidate set
@@ -2041,19 +2051,7 @@ export class PostgresEngine implements BrainEngine {
modalityFilter = `AND cc.modality = 'text'`;
}
- const rawQuery = `
- WITH hnsw_candidates AS (
- SELECT
- p.slug, p.id as page_id, p.title, p.type, p.source_id,
- p.effective_date, p.effective_date_source,
- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
- THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,
- CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
- THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
- cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
- (${unverifiedExtractionFragment('p')}) AS unverified_stub,
- 1 - (cc.${col} <=> ${castSql}) AS raw_score
- FROM content_chunks cc
+ const candidateFrom = `FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
JOIN sources s ON s.id = p.source_id
WHERE cc.${col} IS NOT NULL ${modalityFilter}
@@ -2067,8 +2065,21 @@ export class PostgresEngine implements BrainEngine {
${beforeDateClause}
${sourceClause}
${hardExcludeClause}
- ${visibilityClause}
- ORDER BY cc.${col} <=> ${castSql}
+ ${visibilityClause}`;
+ const rawQuery = (exact: boolean) => `
+ WITH hnsw_candidates AS (
+ SELECT
+ p.slug, p.id as page_id, p.title, p.type, p.source_id,
+ p.effective_date, p.effective_date_source,
+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
+ THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,
+ CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL
+ THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,
+ cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,
+ (${unverifiedExtractionFragment('p')}) AS unverified_stub,
+ 1 - (cc.${col} <=> ${castSql}) AS raw_score
+ ${candidateFrom}
+ ORDER BY ${exact ? '(' : ''}cc.${col} <=> ${castSql}${exact ? ') + 0' : ''}
LIMIT ${innerLimitParam}
),
-- score computed as a select-list expr (NOT in the inner ORDER BY, which
@@ -2081,62 +2092,55 @@ export class PostgresEngine implements BrainEngine {
-- over the full candidate set before the user LIMIT, so a page's strong
-- chunk can't be crowded out of the result by weaker chunks of other
-- pages. Shared builder keeps keyword + vector × postgres + pglite in lockstep.
- ${buildBestPerPagePoolCte('scored')}
+ ${buildBestPerPagePoolCte('scored')},
+ page_results AS (
SELECT
slug, page_id, title, type, source_id,
effective_date, effective_date_source,
message_id, thread_id, source_subject,
chunk_id, chunk_index, chunk_text, chunk_source,
score,
- false AS stale,
- (SELECT count(*) FROM hnsw_candidates)::int AS candidate_pool
+ false AS stale
FROM best_per_page
-- v0.41.13: stable tiebreaker for tied scores. See pglite-engine for
-- rationale (basis-vector test fixtures, planner-dependent ordering).
ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT ${limitParam}
OFFSET ${offsetParam}
+ )
+ SELECT page_results.*, pool.candidate_pool
+ FROM (SELECT count(*)::int AS candidate_pool FROM hnsw_candidates) pool
+ LEFT JOIN page_results ON true
+ ORDER BY score DESC NULLS LAST, page_id ASC, chunk_id ASC
`;
- // RLS scope binding + search-only timeout. alwaysTransaction: master
- // already wrapped this in sql.begin() for the SET LOCAL; flag off is
- // identical to that wrap, flag on adds set_config in the same tx.
- //
- // hnsw.ef_search: an HNSW scan returns at most ef_search rows (default
- // 40), so the inner CTE's LIMIT past 40 was silently unreachable — see
- // hnswEfSearchFor. Transaction-local (is_local=true); non-HNSW plans
- // (seq scan, or corpora without the index) ignore the GUC.
- //
- // v0.46.15 bounded escalation (identical logic in pglite-engine —
- // engine-parity pinned): retry ×4 up to 3 times while the PAGE set is
- // short but the pre-collapse candidate pool was FULL. A short page with
- // a non-full pool is a genuine final page (corpus/filter exhausted) —
- // no retry, no event. Zero rows with offset>0 escalates (deep
- // pagination) but never emits: pool state is unknowable there.
- const runOnce = async (il: number) =>
- await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {
- await tx`SET LOCAL statement_timeout = '8s'`;
- await tx`SELECT set_config('hnsw.ef_search', ${String(hnswEfSearchFor(il))}, true)`;
- return await tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]);
- }, { alwaysTransaction: true });
- let escalations = 0;
- let rows = await runOnce(innerLimit);
- for (;;) {
- const il = params[innerLimitIdx] as number;
- if (rows.length >= limit) break;
- const pool = rows.length > 0 ? Number((rows[0] as { candidate_pool?: number }).candidate_pool ?? 0) : null;
- const shouldEscalate = pool !== null ? pool >= il : offset > 0;
- if (!shouldEscalate) break;
- if (il >= innerCap || escalations >= 3) {
- if (pool !== null && pool >= il) {
- opts?.onVectorPoolMeta?.({ underfilled: true, escalations, innerLimit: il });
- }
- break;
- }
- params[innerLimitIdx] = Math.min(il * 4, innerCap);
- escalations++;
- rows = await runOnce(params[innerLimitIdx] as number);
- }
+ const rows = await searchVectorPool(limit, innerLimit, iterative, indexed, 'postgres',
+ async ({ innerLimit: requested, maxScanTuples, remainingMs, exact }) => {
+ const deadline = performance.now() + remainingMs;
+ return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {
+ return withVectorSettings((sql, values) => tx.unsafe(sql, values as Parameters<typeof tx.unsafe>[1]), iterative, requested, maxScanTuples, async () => {
+ const bound = [...params];
+ bound[innerLimitIdx] = exact ? null : requested;
+ await tx`SELECT set_config('statement_timeout', ${String(remainingVectorBudget(deadline))}, true)`;
+ return { ...readVectorPool(await tx.unsafe(rawQuery(exact), bound as Parameters<typeof tx.unsafe>[1])), exhausted: exact };
+ }, deadline);
+ }, { alwaysTransaction: true });
+ },
+ async (pool, remainingMs) => {
+ const deadline = performance.now() + remainingMs;
+ return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {
+ const previous = await tx`SHOW statement_timeout`;
+ await tx`SELECT set_config('statement_timeout', ${String(remainingVectorBudget(deadline))}, true)`;
+ const bound = [...params.slice(0, innerLimitIdx), pool + 1];
+ const rows = await tx.unsafe(`SELECT count(*)::int AS eligible FROM (
+ SELECT 1 ${candidateFrom} AND $1::text IS NOT NULL LIMIT $${bound.length}
+ ) eligible`, bound as Parameters<typeof tx.unsafe>[1]);
+ await tx`SELECT set_config('statement_timeout', ${previous[0].statement_timeout}, true)`;
+ return Number(rows[0].eligible) > pool;
+ }, { alwaysTransaction: true });
+ },
+ opts?.onVectorPoolMeta,
+ );
return rows.map(rowToSearchResult);
}
diff --git a/src/core/postgres-engine/code-edges.ts b/src/core/postgres-engine/code-edges.ts
index fd8ad53f09..4798fd41bd 100644
--- a/src/core/postgres-engine/code-edges.ts
+++ b/src/core/postgres-engine/code-edges.ts
@@ -4,6 +4,7 @@
* never the whole engine class.
*/
import type postgres from 'postgres';
+import { currentCodeEdgeFilter } from '../code-intel/read-scope.ts';
type PgSql = ReturnType<typeof postgres>;
@@ -95,12 +96,14 @@ export async function getCallersOf(
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
WHERE to_symbol_qualified = ${qualifiedName}
+ AND ${sql.unsafe(currentCodeEdgeFilter('code_edges_chunk', true))}
${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
UNION ALL
SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, false as resolved
FROM code_edges_symbol
WHERE to_symbol_qualified = ${qualifiedName}
+ AND ${sql.unsafe(currentCodeEdgeFilter('code_edges_symbol', false))}
${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
LIMIT ${limit}
`;
@@ -121,12 +124,14 @@ export async function getCalleesOf(
edge_type, edge_metadata, source_id, true as resolved
FROM code_edges_chunk
WHERE ${fromPredicate}
+ AND ${sql.unsafe(currentCodeEdgeFilter('code_edges_chunk', true))}
${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
UNION ALL
SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
edge_type, edge_metadata, source_id, false as resolved
FROM code_edges_symbol
WHERE ${fromPredicate}
+ AND ${sql.unsafe(currentCodeEdgeFilter('code_edges_symbol', false))}
${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
LIMIT ${limit}
`;
diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.ts
index c057b3d8b2..8156b7bfd4 100644
--- a/src/core/search/cjk-keyword-sql.ts
+++ b/src/core/search/cjk-keyword-sql.ts
@@ -3,7 +3,7 @@
*
* `websearch_to_tsquery` with an ASCII-stemming FTS config ('english', …)
* can't tokenize CJK, so FTS keyword recall is zero for Chinese / Japanese /
- * Korean queries. Both engines fall back to a term-by-term ILIKE match with
+ * Korean queries. Both engines fall back to a term-by-term LIKE/ILIKE match with
* term-frequency ranking (v0.32.7 on PGLite; ported to Postgres by #3986).
* The SQL is built ONCE here with $N positional params so the two engines
* cannot drift; each engine supplies only its own executor.
@@ -17,7 +17,7 @@
* - LIKE parameters are individually escaped with escapeLikePattern and
* wrapped with %.
* - Raw terms and raw query are bound unescaped for ranking arithmetic.
- * - Explicit `ESCAPE '\'` on ILIKE clauses.
+ * - Explicit `ESCAPE '\'` on LIKE/ILIKE clauses; caseless terms use LIKE.
* - Empty-query guard returns null without binding SQL.
*/
import type { SearchOpts } from '../types.ts';
@@ -118,11 +118,11 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
}
if (opts?.afterDate) {
params.push(opts.afterDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) > $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.afterDateInclusive ? '>=' : '>'} $${params.length}::text::timestamptz`;
}
if (opts?.beforeDate) {
params.push(opts.beforeDate);
- extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) < $${params.length}::timestamptz`;
+ extraFilter += ` AND COALESCE(p.effective_date, p.updated_at, p.created_at) ${opts?.beforeDateInclusive ? '<=' : '<'} $${params.length}::text::timestamptz`;
}
// v0.34.1 (#861 — P0 leak seal): source-isolation on the CJK fallback path.
if (opts?.sourceIds && opts.sourceIds.length > 0) {
@@ -134,7 +134,11 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
}
const whereLikeClause = likeParamIndices
- .map(idx => `cc.chunk_text ILIKE $${idx} ESCAPE '\\'`)
+ .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
@@ -177,7 +181,7 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
JOIN sources s ON s.id = p.source_id
WHERE ${whereLikeClause} ${detailFilter}${extraFilter} ${hardExcludeClause} ${visibilityClause}
AND cc.modality = 'text'
- ORDER BY score DESC
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT $${innerLimitIndex}
),
${buildBestPerPagePoolCte('ranked')}
@@ -204,7 +208,7 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx): CjkKeywor
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
+ ORDER BY score DESC, page_id ASC, chunk_id ASC
LIMIT $${limitIndex} OFFSET $${offsetIndex}`,
params,
};
diff --git a/src/core/search/date-bounds.ts b/src/core/search/date-bounds.ts
new file mode 100644
index 0000000000..0b7c5a4518
--- /dev/null
+++ b/src/core/search/date-bounds.ts
@@ -0,0 +1,42 @@
+import type { SearchOpts } from '../types.ts';
+
+export function resolveDateBoundary(raw: string | undefined, boundary: 'since' | 'until'): string | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ const s = String(raw).trim();
+ if (!s) return undefined;
+ const rel = /^(\d+)\s*([dwmy])$/i.exec(s);
+ if (rel) {
+ const n = parseInt(rel[1], 10);
+ const unit = rel[2].toLowerCase();
+ const days = unit === 'd' ? n : unit === 'w' ? n * 7 : unit === 'm' ? n * 30 : n * 365;
+ return new Date(Date.now() - days * 86400000).toISOString();
+ }
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) {
+ const day = new Date(`${s}T00:00:00Z`);
+ if (!Number.isFinite(day.getTime()) || day.toISOString().slice(0, 10) !== s || s.startsWith('0000-')) {
+ throw new Error(`Invalid ${boundary} date: expected a real calendar date.`);
+ }
+ return boundary === 'until' ? `${s}T23:59:59.999Z` : s;
+ }
+ if (Number.isFinite(Date.parse(s))) return s;
+ throw new Error(`Invalid ${boundary} value "${s}" — expected ISO-8601 (YYYY-MM-DD or timestamp) or a relative duration like '7d', '2w', '1y'.`);
+}
+
+export function resolveSearchDateBounds(opts?: SearchOpts): Pick<SearchOpts, 'afterDate' | 'beforeDate' | 'afterDateInclusive' | 'beforeDateInclusive'> {
+ const afterDate = resolveDateBoundary(opts?.since ?? opts?.afterDate, 'since');
+ let beforeDate = resolveDateBoundary(opts?.until ?? opts?.beforeDate, 'until');
+ let beforeDateInclusive = opts?.until !== undefined ? true : opts?.beforeDateInclusive;
+ const untilDay = opts?.until?.trim();
+ if (untilDay && /^\d{4}-\d{2}-\d{2}$/.test(untilDay)) {
+ const nextDay = new Date(`${untilDay}T00:00:00Z`);
+ nextDay.setUTCDate(nextDay.getUTCDate() + 1);
+ beforeDate = nextDay.toISOString();
+ beforeDateInclusive = false;
+ }
+ return {
+ afterDate,
+ beforeDate,
+ afterDateInclusive: opts?.since !== undefined ? true : opts?.afterDateInclusive,
+ beforeDateInclusive,
+ };
+}
diff --git a/src/core/search/graph-signals.ts b/src/core/search/graph-signals.ts
index 4a5d6ecf22..ecde80683e 100644
--- a/src/core/search/graph-signals.ts
+++ b/src/core/search/graph-signals.ts
@@ -199,6 +199,7 @@ const SESSION_MARKERS = new Set(['chat', 'session', 'sessions']);
export function sessionPrefix(slug: string): string | null {
if (!slug.includes('/')) return null;
+ if (slug.startsWith('atoms/')) return null;
const segments = slug.split('/');
// Strategy: walk segments left-to-right. Find the first segment that's
// either a session marker (chat/session/sessions) OR a date prefix.
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index dcf8121063..831a96b2a1 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -25,6 +25,8 @@ import type {
DegradedReason,
} from '../types.ts';
import { affectsRecall } from '../types.ts';
+import { resolveSearchDateBounds } from './date-bounds.ts';
+export { resolveDateBoundary, resolveSearchDateBounds } from './date-bounds.ts';
import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';
import { requiresSafeChunks } from './safe-chunks.ts';
import { embed, embedQuery } from '../embedding.ts';
@@ -1186,41 +1188,6 @@ export async function embedQueryBounded(
}
}
-/**
- * #3442 — resolve the public `since`/`until` contract (SearchOpts v0.29.1):
- * ISO-8601 passes through, relative durations ('7d', '2w', '1y') resolve to a
- * concrete timestamp, and a plain YYYY-MM-DD `until` lands at end-of-day.
- * The relative form was documented since v0.29.1 but never implemented — the
- * raw string ('60d') flowed into the engines' `::timestamptz` casts, every
- * arm failed fail-open, and the date filter was SILENTLY ignored.
- * Unparseable input now throws loudly instead of degrading.
- */
-export function resolveDateBoundary(
- raw: string | undefined,
- boundary: 'since' | 'until',
-): string | undefined {
- if (raw === undefined || raw === null) return undefined;
- const s = String(raw).trim();
- if (!s) return undefined;
- const rel = /^(\d+)\s*([dwmy])$/i.exec(s);
- if (rel) {
- const n = parseInt(rel[1], 10);
- const unit = rel[2].toLowerCase();
- // m = months (30d). Minutes make no sense for an effective_date filter.
- const days = unit === 'd' ? n : unit === 'w' ? n * 7 : unit === 'm' ? n * 30 : n * 365;
- return new Date(Date.now() - days * 86400000).toISOString();
- }
- if (/^\d{4}-\d{2}-\d{2}$/.test(s)) {
- // Plain date: `until` lands at end-of-day (documented SearchOpts
- // semantics); `since` keeps UTC start-of-day.
- return boundary === 'until' ? `${s}T23:59:59.999Z` : s;
- }
- if (Number.isFinite(Date.parse(s))) return s;
- throw new Error(
- `Invalid ${boundary} value "${s}" — expected ISO-8601 (YYYY-MM-DD or timestamp) or a relative duration like '7d', '2w', '1y'.`,
- );
-}
-
/**
* WP2/T3 — classify an embed/vector failure as a timeout vs a provider
* error for the enumerated degraded[] reason codes (D6). Matches both the
@@ -1372,8 +1339,7 @@ export async function hybridSearch(
// PR #618 callers compiling while the new names are the public surface.
// #3442: resolveDateBoundary implements the documented contract (relative
// durations + end-of-day for plain-date `until`) at this single seam.
- afterDate: resolveDateBoundary(opts?.since ?? opts?.afterDate, 'since'),
- beforeDate: resolveDateBoundary(opts?.until ?? opts?.beforeDate, 'until'),
+ ...resolveSearchDateBounds(opts),
// v0.34.1 (#861, D9 — P0 leak seal): thread source-scoping through so the
// inner engine.searchKeyword / engine.searchVector calls apply the
// WHERE source_id filter at SQL level. Pre-fix, this explicit pick
@@ -1405,12 +1371,15 @@ export async function hybridSearch(
// sub-queries through this one opts object — last-write-wins would
// under-report multi-query exhaustion. Keep the max-escalations event.
onVectorPoolMeta: (m) => {
+ if (!m.underfilled) return;
+ pushDegraded(degraded, 'vector_candidates_incomplete', m.reason === 'deadline' ? 'timeout' : m.reason ?? 'candidate_budget');
if (!vectorPoolUnderfill || m.escalations >= vectorPoolUnderfill.escalations) {
- vectorPoolUnderfill = { escalations: m.escalations, innerLimit: m.innerLimit };
+ const { underfilled, ...detail } = m;
+ vectorPoolUnderfill = { ...detail, incomplete: true };
}
},
};
- let vectorPoolUnderfill: { escalations: number; innerLimit: number } | undefined;
+ let vectorPoolUnderfill: HybridSearchMeta['vector_pool_underfilled'];
// Track what actually ran for the optional onMeta callback (v0.25.0).
// Caller leaves onMeta undefined → these flags are computed but never
// surfaced. Capture wrapper passes a closure to receive the meta and
diff --git a/src/core/search/projection-readiness.ts b/src/core/search/projection-readiness.ts
new file mode 100644
index 0000000000..d025b5a252
--- /dev/null
+++ b/src/core/search/projection-readiness.ts
@@ -0,0 +1,59 @@
+import type { BrainEngine } from '../engine.ts';
+import type { PageReadScope } from '../types.ts';
+import { pageReadFilter } from './read-policy-sql.ts';
+
+export interface ProjectionReadinessScope extends PageReadScope {
+ pageKind?: string;
+ types?: string[];
+ excludeSlugPrefixes?: string[];
+}
+
+export interface ProjectionReadiness {
+ status: 'ready' | 'projection_pending' | 'unknown';
+ ready: boolean;
+ hint?: string;
+}
+
+export async function probeProjectionReadiness(
+ engine: Pick<BrainEngine, 'executeRaw'>,
+ scope: ProjectionReadinessScope = {},
+): Promise<ProjectionReadiness> {
+ const params: unknown[] = [];
+ const filters = [pageReadFilter('p', scope, params, true)];
+ if (scope.sourceIds?.length === 0) filters.push('FALSE');
+ if (scope.pageKind) {
+ params.push(scope.pageKind);
+ filters.push(`p.page_kind = $${params.length}`);
+ }
+ if (scope.types) {
+ params.push(scope.types);
+ filters.push(`p.type = ANY($${params.length}::text[])`);
+ }
+ for (const prefix of scope.excludeSlugPrefixes ?? []) {
+ params.push(prefix);
+ filters.push(`LEFT(p.slug, LENGTH($${params.length}::text)) <> $${params.length}`);
+ }
+ try {
+ const rows = await engine.executeRaw<{ pending: boolean }>(
+ `SELECT EXISTS (
+ SELECT 1 FROM pages p
+ WHERE p.deleted_at IS NULL
+ AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision
+ AND ${filters.join(' AND ')}
+ ) AS pending`,
+ params,
+ );
+ if (typeof rows[0]?.pending !== 'boolean') throw new Error('Invalid readiness result');
+ return rows[0].pending
+ ? {
+ status: 'projection_pending', ready: false,
+ hint: 'Current text projections are pending in the visible scope; results may be incomplete. Run `gbrain doctor` locally to inspect recovery. This read does not repair or embed content.',
+ }
+ : { status: 'ready', ready: true };
+ } catch {
+ return {
+ status: 'unknown', ready: false,
+ hint: 'Projection readiness could not be checked; do not treat these results as proof of a complete index. Run `gbrain doctor` locally to diagnose.',
+ };
+ }
+}
diff --git a/src/core/search/projection-statistics.ts b/src/core/search/projection-statistics.ts
new file mode 100644
index 0000000000..7d3bbd39f9
--- /dev/null
+++ b/src/core/search/projection-statistics.ts
@@ -0,0 +1,65 @@
+import type { BrainEngine } from '../engine.ts';
+
+export const PROJECTION_STATISTICS_NAME = 'pages_text_projection_current_stats';
+
+export const PROJECTION_STATISTICS_SQL = `
+CREATE STATISTICS IF NOT EXISTS ${PROJECTION_STATISTICS_NAME}
+ ON ((text_projection_revision = knowledge_revision)) FROM pages;
+ANALYZE pages(text_projection_revision, knowledge_revision);
+`;
+
+export async function verifyProjectionStatistics(engine: Pick<BrainEngine, 'executeRaw'>): Promise<void> {
+ const rows = await engine.executeRaw<{
+ expression: string;
+ correct_table: boolean;
+ sampled_rows: number;
+ can_inspect: boolean;
+ collected: boolean;
+ }>(`SELECT pg_get_expr(e.stxexprs, e.stxrelid) AS expression,
+ e.stxrelid = 'pages'::regclass AS correct_table,
+ p.reltuples AS sampled_rows,
+ has_table_privilege(p.oid, 'SELECT') AND NOT row_security_active(p.oid) AS can_inspect,
+ x.null_frac IS NOT NULL AS collected
+ FROM pg_class p JOIN pg_statistic_ext e ON e.stxnamespace = p.relnamespace
+ LEFT JOIN pg_stats_ext_exprs x
+ ON x.statistics_schemaname = (SELECT nspname FROM pg_namespace WHERE oid = e.stxnamespace)
+ AND x.statistics_name = e.stxname
+ AND x.expr = pg_get_expr(e.stxexprs, e.stxrelid)
+ WHERE p.oid = 'pages'::regclass AND e.stxname = $1`, [PROJECTION_STATISTICS_NAME]);
+ const state = rows[0];
+ if (!state || !state.correct_table || state.expression !== '(text_projection_revision = knowledge_revision)') {
+ throw new Error('Projection planner statistics are missing or have the wrong definition; the schema migration was not verified.');
+ }
+ if (!state.can_inspect) {
+ throw new Error('Projection planner statistics cannot be inspected by this database role or its row-security policy; run schema maintenance with an authorized maintenance role.');
+ }
+ if (Number(state.sampled_rows) < 0 || (Number(state.sampled_rows) > 0 && !state.collected)) {
+ throw new Error('Projection planner statistics have not been collected; run ANALYZE pages(text_projection_revision, knowledge_revision) as the table owner.');
+ }
+}
+
+export async function refreshProjectionStatistics(engine: BrainEngine): Promise<boolean> {
+ try {
+ const [role] = await engine.executeRaw<{ can_analyze: boolean }>(
+ `SELECT pg_has_role(current_user, p.relowner, 'USAGE') OR r.rolsuper AS can_analyze
+ FROM pg_class p CROSS JOIN pg_roles r
+ WHERE p.oid = 'pages'::regclass AND r.rolname = current_user`,
+ );
+ if (!role?.can_analyze) {
+ console.warn('[search] Projection planner statistics were not refreshed: database-owner maintenance is required. Run ANALYZE pages(text_projection_revision, knowledge_revision) as the table owner.');
+ return false;
+ }
+ await engine.transaction(async tx => {
+ if (engine.kind === 'postgres') {
+ await tx.executeRaw("SET LOCAL statement_timeout = '30s'");
+ await tx.executeRaw("SET LOCAL lock_timeout = '2s'");
+ }
+ await tx.executeRaw('ANALYZE pages(text_projection_revision, knowledge_revision)');
+ await verifyProjectionStatistics(tx);
+ });
+ return true;
+ } catch {
+ console.warn('[search] Projection planner statistics could not be refreshed. Run ANALYZE pages(text_projection_revision, knowledge_revision) as the table owner; completed page writes were retained.');
+ return false;
+ }
+}
diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.ts
index 611e1bf246..0ab6dc8c28 100644
--- a/src/core/search/safe-chunks.ts
+++ b/src/core/search/safe-chunks.ts
@@ -34,7 +34,7 @@ export function requiresSafeChunks(scope?: PageReadScope): boolean {
/** Every user sees projections only from the current canonical revision. */
export function currentTextProjectionFilter(alias: string): string {
- return `${alias}.text_projection_revision = ${alias}.knowledge_revision`;
+ return `(${alias}.text_projection_revision = ${alias}.knowledge_revision) IS TRUE`;
}
/** Older fragments lack trustworthy provenance, even if markers were removed later. */
diff --git a/src/core/search/vector-pool.ts b/src/core/search/vector-pool.ts
new file mode 100644
index 0000000000..6200d0e899
--- /dev/null
+++ b/src/core/search/vector-pool.ts
@@ -0,0 +1,73 @@
+import type { SearchOpts } from '../types.ts';
+
+export interface VectorPoolBatch {
+ rows: Record<string, unknown>[];
+ candidatePool: number;
+ exhausted?: boolean;
+}
+
+export interface VectorPoolAttempt {
+ innerLimit: number;
+ maxScanTuples: number;
+ remainingMs: number;
+ exact: boolean;
+}
+
+export function remainingVectorBudget(deadline: number): number {
+ const remaining = Math.floor(deadline - performance.now());
+ if (remaining <= 0) throw Object.assign(new Error('Vector candidate deadline exhausted'), { code: '57014' });
+ return remaining;
+}
+
+export async function searchVectorPool(
+ limit: number,
+ initialLimit: number,
+ iterative: boolean,
+ indexed: boolean,
+ engine: 'postgres' | 'pglite',
+ run: (attempt: VectorPoolAttempt) => Promise<VectorPoolBatch>,
+ hasMore: (pool: number, remainingMs: number) => Promise<boolean>,
+ onMeta: SearchOpts['onVectorPoolMeta'],
+): Promise<Record<string, unknown>[]> {
+ const deadline = performance.now() + 8_000;
+ const remaining = () => Math.max(0, Math.floor(deadline - performance.now()));
+ let batch: VectorPoolBatch = { rows: [], candidatePool: 0 };
+ let innerLimit = initialLimit;
+ let escalations = 0;
+ let exactFallback = false;
+ let reason: 'candidate_budget' | 'iterative_scan_unavailable' | 'deadline' =
+ indexed && !iterative ? 'iterative_scan_unavailable' : 'candidate_budget';
+ try {
+ for (;;) {
+ if (remaining() === 0) { reason = 'deadline'; break; }
+ batch = await run({ innerLimit, maxScanTuples: Math.min(2_000 * 4 ** escalations, 20_000), remainingMs: remaining(), exact: false });
+ if (batch.rows.length >= limit) return batch.rows;
+ if (batch.candidatePool < innerLimit) {
+ if (!indexed) return batch.rows;
+ if (remaining() === 0) { reason = 'deadline'; break; }
+ if (!(await hasMore(batch.candidatePool, remaining()))) return batch.rows;
+ }
+ if (escalations >= 3 || (indexed && !iterative)) break;
+ innerLimit = Math.min(innerLimit * 4, Math.max(initialLimit, 20_000));
+ escalations++;
+ }
+ if (engine === 'postgres' && indexed && remaining() > 0) {
+ exactFallback = true;
+ batch = await run({ innerLimit, maxScanTuples: 20_000, remainingMs: remaining(), exact: true });
+ if (batch.rows.length >= limit || batch.exhausted) return batch.rows;
+ reason = remaining() === 0 ? 'deadline' : 'candidate_budget';
+ }
+ } catch (error) {
+ if (engine !== 'postgres' || (error as { code?: string }).code !== '57014') throw error;
+ reason = 'deadline';
+ }
+ onMeta?.({ underfilled: true, incomplete: true, reason, escalations, innerLimit, candidatePool: batch.candidatePool, exactFallback });
+ return batch.rows;
+}
+
+export function readVectorPool(rows: Record<string, unknown>[]): VectorPoolBatch {
+ return {
+ rows: rows.filter(row => row.page_id != null),
+ candidatePool: Number(rows[0]?.candidate_pool ?? 0),
+ };
+}
diff --git a/src/core/search/vector-settings.ts b/src/core/search/vector-settings.ts
new file mode 100644
index 0000000000..7f149f8dd5
--- /dev/null
+++ b/src/core/search/vector-settings.ts
@@ -0,0 +1,27 @@
+import { hnswEfSearchFor, HNSW_EF_SEARCH_DEFAULT } from '../vector-index.ts';
+import { remainingVectorBudget } from './vector-pool.ts';
+
+export async function withVectorSettings<T>(
+ query: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>,
+ iterative: boolean,
+ candidateLimit: number,
+ maxScanTuples: number,
+ run: () => Promise<T>,
+ deadline?: number,
+): Promise<T> {
+ const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(candidateLimit)) };
+ const defaults: Record<string, string> = { 'hnsw.ef_search': String(HNSW_EF_SEARCH_DEFAULT), 'hnsw.iterative_scan': 'off', 'hnsw.max_scan_tuples': '20000' };
+ if (iterative) {
+ settings['hnsw.iterative_scan'] = 'strict_order';
+ settings['hnsw.max_scan_tuples'] = String(maxScanTuples);
+ }
+ if (deadline !== undefined) settings.statement_timeout = String(remainingVectorBudget(deadline));
+ const names = Object.keys(settings);
+ const previous = await query(`SELECT name, current_setting(name, true) AS value FROM unnest($1::text[]) AS settings(name)`, [names]);
+ const setSql = `SELECT set_config(name, value, true) FROM unnest($1::text[], $2::text[]) AS settings(name, value)`;
+ if (deadline !== undefined) settings.statement_timeout = String(remainingVectorBudget(deadline));
+ await query(setSql, [names, names.map(name => settings[name])]);
+ const result = await run();
+ await query(setSql, [previous.map(row => row.name), previous.map(row => row.value ?? defaults[String(row.name)])]);
+ return result;
+}
diff --git a/src/core/types.ts b/src/core/types.ts
index fb3dfb51f7..3e441fd965 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1100,6 +1100,16 @@ export interface ResolvedColumn {
embeddingModel: string;
}
+export interface VectorPoolMeta {
+ underfilled: boolean;
+ escalations: number;
+ innerLimit: number;
+ incomplete?: boolean;
+ reason?: 'candidate_budget' | 'iterative_scan_unavailable' | 'deadline';
+ candidatePool?: number;
+ exactFallback?: boolean;
+}
+
export interface SearchOpts extends PageReadPolicy {
limit?: number;
offset?: number;
@@ -1109,10 +1119,9 @@ export interface SearchOpts extends PageReadPolicy {
* candidate pool before the per-page DISTINCT collapse, underfilling the
* result). Engines have no telemetry sink; the HYBRID layer passes a
* collector here and owns the emit. Called at most once per searchVector
- * call, only when the escalation loop ended with the page set still
- * underfilled at the HNSW substrate cap (ef_search hard ceiling).
+ * call, only when bounded work ended before exhaustion could be proved.
*/
- onVectorPoolMeta?: (m: { underfilled: boolean; escalations: number; innerLimit: number }) => void;
+ onVectorPoolMeta?: (m: VectorPoolMeta) => void;
/**
* v0.42 — intent-aware adaptive return-sizing. `true` enables with config/
* default caps; an object overrides caps per-call; omitted/`false` = off
@@ -1238,11 +1247,13 @@ export interface SearchOpts extends PageReadPolicy {
* v0.27.0: filter results to pages updated/created after this date. ISO-8601 string.
*/
afterDate?: string;
+ afterDateInclusive?: boolean;
/**
* @deprecated v0.29.1: use `until` instead. Removed in v0.30.
* v0.27.0: filter results to pages updated/created before this date. ISO-8601 string.
*/
beforeDate?: string;
+ beforeDateInclusive?: boolean;
/**
* @deprecated v0.29.1: use `recency` ('off' | 'on' | 'strong') instead. Removed in v0.30.
* v0.27.0: recency boost strength. 0 = off, 1 = moderate, 2 = aggressive.
@@ -1899,6 +1910,9 @@ export const DEGRADED_STAGES = [
'rerank_passthrough',
'keyword_relaxed_carried',
'safe_index_pending',
+ 'vector_candidates_incomplete',
+ 'projection_pending',
+ 'projection_status_unknown',
] as const;
export type DegradedStage = (typeof DEGRADED_STAGES)[number];
@@ -1920,6 +1934,8 @@ export const DEGRADED_REASONS = [
// #4648 — rerank_passthrough reasons (mirror RerankPassThroughReason).
'empty_result_set',
'malformed_shape',
+ 'candidate_budget',
+ 'iterative_scan_unavailable',
] as const;
export type DegradedReason = (typeof DEGRADED_REASONS)[number];
@@ -1983,7 +1999,7 @@ export interface HybridSearchMeta {
* the caller asked for more distinct pages than the candidate pool could
* yield). Omitted on clean runs. Exhaustion is VISIBLE, not silent.
*/
- vector_pool_underfilled?: { escalations: number; innerLimit: number };
+ vector_pool_underfilled?: Omit<VectorPoolMeta, 'underfilled'>;
/**
* 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/src/core/vector-index.ts b/src/core/vector-index.ts
index f584fafb50..f604296c19 100644
--- a/src/core/vector-index.ts
+++ b/src/core/vector-index.ts
@@ -51,20 +51,21 @@ export const HNSW_EF_SEARCH_MAX = 1000;
* `hnsw.ef_search` value for a vector search that wants `candidateLimit`
* candidates back.
*
- * An HNSW index scan returns at most `hnsw.ef_search` rows (default 40)
- * no matter what the query's LIMIT asks for — the GUC sizes the scan's
- * candidate list, so it caps the row count before LIMIT is even applied.
- * Both engines' searchVector ask the inner CTE for
- * `offset + max(limit*5, 100)` candidates; without raising the GUC the
- * pool silently truncates at ~40 and everything downstream (per-page
- * collapse, RRF fusion, rerankers) operates on a fraction of the pool it
- * was designed for. Shared helper keeps postgres + pglite in lockstep.
+ * This sizes the initial candidate list. Supported iterative scans can
+ * continue beyond it, so the GUC ceiling is not a SQL output/offset limit.
+ * Both engines use the same initial-list policy independently of their
+ * bounded iterative work and per-page pooling.
*/
export function hnswEfSearchFor(candidateLimit: number): number {
const wanted = Math.ceil(candidateLimit);
return Math.min(Math.max(wanted, HNSW_EF_SEARCH_DEFAULT), HNSW_EF_SEARCH_MAX);
}
+export function supportsHnswIterativeScan(extensionVersion: string | undefined): boolean {
+ const match = extensionVersion?.match(/^(\d+)\.(\d+)(?:\.|$)/);
+ return !!match && (Number(match[1]) > 0 || Number(match[2]) >= 8);
+}
+
// ---------------------------------------------------------------------------
// v0.30.1 Lifecycle Manager (Fix 5)
// ---------------------------------------------------------------------------
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index d60dd6cf9c..9516b5feaf 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.51.6.0 -->
+<!-- gbrain-template-stamp: 0.51.7.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/cjk-keyword-sql.test.ts b/test/cjk-keyword-sql.test.ts
index a54a5efd0c..cd5738e894 100644
--- a/test/cjk-keyword-sql.test.ts
+++ b/test/cjk-keyword-sql.test.ts
@@ -28,17 +28,29 @@ describe('buildCJKKeywordSql (#3986)', () => {
expect(buildCJKKeywordSql(' ', ctx())).toBeNull();
});
- test('one ILIKE clause per term, AND-joined, with explicit ESCAPE', () => {
+ test('one case-safe LIKE clause per term, AND-joined, with explicit ESCAPE', () => {
const built = buildCJKKeywordSql('東京 会議', ctx());
expect(built).not.toBeNull();
- const ilikeCount = (built!.sql.match(/ILIKE \$\d+ ESCAPE '\\'/g) || []).length;
- expect(ilikeCount).toBe(2);
+ const likeCount = (built!.sql.match(/(?<!I)LIKE \$\d+ ESCAPE '\\'/g) || []).length;
+ expect(likeCount).toBe(2);
// Escaped + wrapped LIKE params come first, raw terms after, raw query next.
expect(built!.params.slice(0, 2)).toEqual(['%東京%', '%会議%']);
expect(built!.params.slice(2, 4)).toEqual(['東京', '会議']);
expect(built!.params[4]).toBe('東京 会議');
});
+ test('mixed Hangul and Latin terms select matching operators independently', () => {
+ const built = buildCJKKeywordSql('앨범 Example 기획', ctx());
+ expect(built!.sql).toContain("cc.chunk_text LIKE $1 ESCAPE '\\'");
+ expect(built!.sql).toContain("cc.chunk_text ILIKE $2 ESCAPE '\\'");
+ expect(built!.sql).toContain("cc.chunk_text LIKE $3 ESCAPE '\\'");
+ });
+
+ test('case-bearing letters remain case-insensitive within a mixed-script term', () => {
+ const built = buildCJKKeywordSql('東京Example', ctx());
+ expect(built!.sql).toContain("cc.chunk_text ILIKE $1 ESCAPE '\\'");
+ });
+
test('LIKE metacharacters in terms are escaped', () => {
const built = buildCJKKeywordSql('東京_50%', ctx());
expect(built!.params[0]).toBe('%東京\\_50\\%%');
@@ -128,7 +140,7 @@ describe('postgres-engine searchKeywordCJK executor (#3986)', () => {
ctx(),
);
expect(calls.length).toBe(1);
- expect(calls[0].sql).toContain('ILIKE');
+ expect(calls[0].sql).toContain("cc.chunk_text LIKE $1 ESCAPE '\\'");
expect(calls[0].params[0]).toBe('%東京%');
expect(results.length).toBe(1);
expect(results[0].slug).toBe('notes/tokyo');
diff --git a/test/cli-incomplete-retrieval-render.test.ts b/test/cli-incomplete-retrieval-render.test.ts
new file mode 100644
index 0000000000..3b1fab2d87
--- /dev/null
+++ b/test/cli-incomplete-retrieval-render.test.ts
@@ -0,0 +1,26 @@
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+import { captureRetrievalMeta, formatResult, resetRetrievalMetaForTests } from '../src/cli.ts';
+
+afterEach(() => resetRetrievalMetaForTests());
+
+describe('CLI incomplete retrieval is visible without changing JSON result shape', () => {
+ test.each(['vector_candidates_incomplete', 'projection_pending', 'projection_status_unknown'])(
+ '%s is visible for empty and partial results', stage => {
+ captureRetrievalMeta('retrieval', { degraded: [{ stage }] });
+ expect(formatResult('search', [], {})).toContain(`degraded: ${stage}`);
+ expect(formatResult('search', [], {})).not.toContain('clean miss');
+ const partial = formatResult('query', [{ slug: 'notes/synthetic', score: 1, chunk_text: 'Synthetic note' }], {});
+ expect(partial).toContain(`Retrieval incomplete: ${stage}.`);
+ expect(partial).toContain('notes/synthetic');
+ },
+ );
+
+ test('JSON remains a bare result array while stderr reports incompleteness', () => {
+ captureRetrievalMeta('retrieval', { degraded: [{ stage: 'vector_candidates_incomplete' }] });
+ const write = spyOn(process.stderr, 'write').mockReturnValue(true);
+ try {
+ expect(JSON.parse(formatResult('search', [], { json: true }))).toEqual([]);
+ expect(write).toHaveBeenCalledWith('Retrieval incomplete: vector_candidates_incomplete.\n');
+ } finally { write.mockRestore(); }
+ });
+});
diff --git a/test/code-def-refs.test.ts b/test/code-def-refs.test.ts
index 914c3ab564..d1b05cc9c6 100644
--- a/test/code-def-refs.test.ts
+++ b/test/code-def-refs.test.ts
@@ -349,6 +349,7 @@ describe('probeFilteredSymbolTypes (#3789)', () => {
VALUES ($1, 0, 'exotic fixture chunk body', 'ExoticFixtureSymbol', 'exotic gizmo kind', 'typescript')`,
[rows[0]!.id],
);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [rows[0]!.id]);
}, 30000);
test('returns the allowlist-filtered symbol types for a name', async () => {
diff --git a/test/code-intel-source-scope.test.ts b/test/code-intel-source-scope.test.ts
index bd293aadd5..0911a8b8d0 100644
--- a/test/code-intel-source-scope.test.ts
+++ b/test/code-intel-source-scope.test.ts
@@ -107,6 +107,7 @@ async function seedTwoSourceCodeGraph(): Promise<void> {
await insertUnresolvedEdge(betaCallerChunk, 'betaCallerFn', 'betaSecretFn', 'srcbeta');
await insertUnresolvedEdge(betaSharedChunk, 'sharedCallerFn', 'betaSecretFn', 'srcbeta');
await insertUnresolvedEdge(betaCallerChunk, 'betaCallerFn', 'alphaTargetFn', 'srcbeta');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
}
// Trusted local reads retain their historical source behavior.
diff --git a/test/code-intel/recursive-walk.test.ts b/test/code-intel/recursive-walk.test.ts
index db930420a4..f28b793659 100644
--- a/test/code-intel/recursive-walk.test.ts
+++ b/test/code-intel/recursive-walk.test.ts
@@ -73,6 +73,7 @@ async function seedGraph(): Promise<void> {
FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = 'code/baz'`,
[],
);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
}
describe('W3: sinks classifier', () => {
diff --git a/test/code-projection-edge-recovery.test.ts b/test/code-projection-edge-recovery.test.ts
new file mode 100644
index 0000000000..621b4bb5df
--- /dev/null
+++ b/test/code-projection-edge-recovery.test.ts
@@ -0,0 +1,97 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importCodeFile } from '../src/core/import-file.ts';
+import { installPageProjection, preparePageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';
+import { resolveSymbolEdgesIncremental } from '../src/core/chunkers/symbol-resolver.ts';
+import { resolveCodeReadiness } from '../src/core/code-graph-readiness.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+describe('code projection recovery preserves graph correctness', () => {
+ const engines: BrainEngine[] = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+
+ beforeAll(async () => {
+ const lite = new PGLiteEngine();
+ await lite.connect({});
+ await lite.initSchema();
+ engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine);
+ closePostgres = pg.close;
+ }
+ }, 120_000);
+
+ afterAll(async () => {
+ await engines.find(engine => engine.kind === 'pglite')?.disconnect();
+ await closePostgres?.();
+ }, 30_000);
+
+ async function seed(engine: BrainEngine, sourceId: string) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const { slug } = await importCodeFile(engine, 'example.ts',
+ 'export function betaExample() { return 3; }\nexport function alphaExample() { return betaExample(); }\n',
+ { sourceId, noEmbed: true });
+ return slug;
+ }
+
+ async function rebuild(engine: BrainEngine, slug: string, sourceId: string) {
+ const snapshot = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ const projection = await preparePageProjection(snapshot);
+ await installPageProjection(engine, snapshot, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });
+ }
+
+ test('unchanged target chunks retain incoming edges owned by other pages', async () => {
+ for (const engine of engines) {
+ const sourceId = 'incoming-edge-example';
+ const targetSlug = await seed(engine, sourceId);
+ const caller = await importCodeFile(engine, 'caller.ts', 'export function callerExample() { return 1; }', { sourceId, noEmbed: true });
+ const [from] = await engine.getChunks(caller.slug, { sourceId });
+ const target = (await engine.getChunks(targetSlug, { sourceId })).find(chunk => chunk.symbol_name === 'betaExample')!;
+ await engine.addCodeEdges([{ from_chunk_id: from.id, to_chunk_id: target.id,
+ from_symbol_qualified: 'callerExample', to_symbol_qualified: 'betaExample', edge_type: 'calls', source_id: sourceId }]);
+ await rebuild(engine, targetSlug, sourceId);
+ const edges = await engine.getCallersOf('betaExample', { sourceId });
+ expect(edges.some(edge => edge.from_chunk_id === from.id && edge.to_chunk_id === target.id)).toBe(true);
+ expect((await engine.getChunks(targetSlug, { sourceId })).some(chunk => chunk.id === target.id)).toBe(true);
+ }
+ });
+
+ test('replaced outgoing edges invalidate the backfill watermark and resolve again', async () => {
+ for (const engine of engines) {
+ const sourceId = 'edge-watermark-example';
+ const slug = await seed(engine, sourceId);
+ expect((await resolveSymbolEdgesIncremental(engine, { sourceId })).edges_resolved).toBe(1);
+ await rebuild(engine, slug, sourceId);
+ expect(await resolveCodeReadiness(engine, { sourceId, kind: 'edge', count: 0, remote: false })).toMatchObject({ status: 'indexing', ready: false });
+ const next = await resolveSymbolEdgesIncremental(engine, { sourceId });
+ expect(next.chunks_walked).toBeGreaterThan(0);
+ expect(next.edges_resolved).toBe(1);
+ expect(await resolveCodeReadiness(engine, { sourceId, kind: 'edge', count: 0, remote: false })).toMatchObject({ status: 'ready', ready: true });
+ }
+ });
+
+ test('recursive operations do not reuse a traversal after its source is archived', async () => {
+ for (const engine of engines) {
+ const sourceId = 'walk-currency-example';
+ await seed(engine, sourceId);
+ const ctx = { engine, sourceId, remote: false } as OperationContext;
+ for (const [name, params] of [
+ ['code_flow', { entry_point: 'alphaExample' }],
+ ['code_blast', { symbol: 'betaExample' }],
+ ] as const) {
+ await engine.executeRaw('UPDATE sources SET archived=false WHERE id=$1', [sourceId]);
+ const first = await operationsByName[name].handler(ctx, { ...params, source_id: sourceId }) as any;
+ expect(first.result).toBe('ok');
+ expect(first.depth_groups[0].nodes.length).toBeGreaterThan(0);
+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ const second = await operationsByName[name].handler(ctx, { ...params, source_id: sourceId }) as any;
+ expect(second.result).toBe('not_found');
+ expect(second.ready).toBe(false);
+ expect(second.did_you_mean).toEqual([]);
+ }
+ }
+ });
+});
diff --git a/test/code-read-currency.test.ts b/test/code-read-currency.test.ts
new file mode 100644
index 0000000000..72b08ec66f
--- /dev/null
+++ b/test/code-read-currency.test.ts
@@ -0,0 +1,215 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { findCodeDef, probeFilteredSymbolTypes, runCodeDef } from '../src/commands/code-def.ts';
+import { findCodeRefs, runCodeRefs } from '../src/commands/code-refs.ts';
+import { runCodeCallers } from '../src/commands/code-callers.ts';
+import { runCodeCallees } from '../src/commands/code-callees.ts';
+import { resolveCodeReadiness } from '../src/core/code-graph-readiness.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { resetPgliteState } from './helpers/reset-pglite.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);
+ for (const source of ['source-a', 'source-b']) {
+ await engine.executeRaw('INSERT INTO sources (id,name) VALUES ($1,$1)', [source]);
+ }
+});
+
+async function seed(source = 'source-a', slug = 'src/shared.ts', symbolType = 'function', frontmatter = {}) {
+ const [page] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO pages (source_id,slug,title,type,page_kind,compiled_truth,frontmatter,chunker_version)
+ VALUES ($1,$2,'Example','code','code','function sampleSymbol() {}',$3::text::jsonb,999) RETURNING id`,
+ [source, slug, JSON.stringify(frontmatter)],
+ );
+ await engine.executeRaw(
+ `INSERT INTO content_chunks(page_id,chunk_index,chunk_text,chunk_source,language,symbol_name,symbol_type)
+ VALUES ($1,0,'function sampleSymbol() {}','compiled_truth','typescript','sampleSymbol',$2)`,
+ [page.id, symbolType],
+ );
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [page.id]);
+ return page.id;
+}
+
+describe('code definition and reference currency', () => {
+ for (const [name, find] of [['definitions', findCodeDef], ['references', findCodeRefs]] as const) {
+ for (const invalid of ['null', 'mismatched', 'deleted', 'archived']) {
+ test(`${name} exclude ${invalid} rows even when their chunks remain`, async () => {
+ const id = await seed();
+ expect(await find(engine, 'sampleSymbol', { sourceId: 'source-a' })).toHaveLength(1);
+ if (invalid === 'null') await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [id]);
+ if (invalid === 'mismatched') await engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid() WHERE id=$1', [id]);
+ if (invalid === 'deleted') await engine.executeRaw('UPDATE pages SET deleted_at=NOW() WHERE id=$1', [id]);
+ if (invalid === 'archived') await engine.executeRaw("UPDATE sources SET archived=true WHERE id='source-a'");
+ expect(await find(engine, 'sampleSymbol', { sourceId: 'source-a' })).toHaveLength(0);
+ });
+ }
+
+ test(`${name} distinguish duplicate slugs, compose bound filters and honor array grants`, async () => {
+ await seed();
+ await seed('source-b');
+ const rows = await find(engine, 'sampleSymbol', { sourceId: 'source-b', sourceIds: ['source-a'], language: 'typescript', limit: 1 });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].source_id).toBe('source-a');
+ expect(await find(engine, 'sampleSymbol', { sourceIds: [] })).toHaveLength(0);
+ expect(await find(engine, 'sampleSymbol', { sourceId: "source-a' OR TRUE--" })).toHaveLength(0);
+ expect(await find(engine, 'sampleSymbol', { sourceIds: ['source-a', 'source-b'] })).toHaveLength(2);
+ });
+
+ test(`${name} apply private visibility without taking it from caller parameters`, async () => {
+ await seed('source-a', 'src/shared.ts', 'function', { visibility: 'private' });
+ expect(await find(engine, 'sampleSymbol', { excludePrivate: true })).toHaveLength(0);
+ expect(await find(engine, 'sampleSymbol', { excludePrivate: false })).toHaveLength(1);
+ });
+ }
+
+ test('filtered symbol diagnostics use the same currency and visibility guards', async () => {
+ const id = await seed('source-a', 'src/shared.ts', 'unsupported_wrapper');
+ expect(await probeFilteredSymbolTypes(engine, 'sampleSymbol', { sourceId: 'source-a' })).toEqual(['unsupported_wrapper']);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [id]);
+ expect(await probeFilteredSymbolTypes(engine, 'sampleSymbol', { sourceId: 'source-a' })).toEqual([]);
+ });
+
+ for (const endpoint of ['caller', 'target']) {
+ for (const invalid of ['null', 'mismatched', 'deleted', 'archived']) {
+ test(`caller and callee queries reject a ${invalid} ${endpoint} projection`, async () => {
+ const from = await seed('source-a', 'src/caller.ts');
+ const target = await seed('source-b', 'src/target.ts');
+ const chunks = await engine.executeRaw<{ id: number; page_id: number }>('SELECT id,page_id FROM content_chunks');
+ await engine.addCodeEdges([{
+ from_chunk_id: chunks.find(c => c.page_id === from)!.id,
+ to_chunk_id: chunks.find(c => c.page_id === target)!.id,
+ from_symbol_qualified: 'callerExample', to_symbol_qualified: 'sampleSymbol',
+ edge_type: 'calls', source_id: 'source-a',
+ }]);
+ expect(await engine.getCallersOf('sampleSymbol', { sourceId: 'source-a' })).toHaveLength(1);
+ expect(await engine.getCalleesOf('callerExample', { sourceId: 'source-a' })).toHaveLength(1);
+ const id = endpoint === 'caller' ? from : target;
+ if (invalid === 'null') await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [id]);
+ if (invalid === 'mismatched') await engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid() WHERE id=$1', [id]);
+ if (invalid === 'deleted') await engine.executeRaw('UPDATE pages SET deleted_at=NOW() WHERE id=$1', [id]);
+ if (invalid === 'archived') await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [endpoint === 'caller' ? 'source-a' : 'source-b']);
+ expect(await engine.getCallersOf('sampleSymbol', { sourceId: 'source-a' })).toHaveLength(0);
+ expect(await engine.getCalleesOf('callerExample', { sourceId: 'source-a' })).toHaveLength(0);
+ });
+ }
+ }
+
+ test('unresolved caller edges are withheld when their concrete origin is stale', async () => {
+ const id = await seed();
+ const [chunk] = await engine.executeRaw<{ id: number }>('SELECT id FROM content_chunks WHERE page_id=$1', [id]);
+ await engine.addCodeEdges([{
+ from_chunk_id: chunk.id, from_symbol_qualified: 'callerExample', to_symbol_qualified: 'sampleSymbol',
+ edge_type: 'calls', source_id: 'source-a',
+ }]);
+ expect(await engine.getCallersOf('sampleSymbol', { sourceId: 'source-a' })).toHaveLength(1);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [id]);
+ expect(await engine.getCallersOf('sampleSymbol', { sourceId: 'source-a' })).toHaveLength(0);
+ expect(await engine.getCalleesOf('callerExample', { sourceId: 'source-a' })).toHaveLength(0);
+ });
+
+ test('trusted-local operation wrappers preserve brain-wide reads while excluding stale definitions', async () => {
+ const id = await seed('source-b');
+ const ctx = { engine, remote: false, sourceId: 'source-a' } as unknown as OperationContext;
+ for (const name of ['code_def', 'code_refs']) {
+ const current = await operationsByName[name].handler(ctx, { symbol: 'sampleSymbol' }) as any;
+ expect(current.count).toBe(1);
+ expect(current.status).toBe('ready');
+ }
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [id]);
+ for (const name of ['code_def', 'code_refs']) {
+ const stale = await operationsByName[name].handler(ctx, { symbol: 'sampleSymbol' }) as any;
+ expect(stale.count).toBe(0);
+ expect(stale.status).toBe('projection_pending');
+ }
+ });
+
+ for (const run of [runCodeDef, runCodeRefs]) {
+ test(`${run.name} reports pending with partial nonempty results, then ready after recovery`, async () => {
+ await seed();
+ const pending = await seed('source-a', 'src/pending.ts');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [pending]);
+ const output: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((text) => { output.push(String(text)); });
+ try {
+ await run(engine, ['sampleSymbol', '--source', 'source-a', '--json']);
+ const first = JSON.parse(output.pop()!);
+ expect(first.count).toBe(1);
+ expect(first.status).toBe('projection_pending');
+ expect(first.ready).toBe(false);
+ expect(first.hint).toContain('incomplete');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [pending]);
+ await run(engine, ['sampleSymbol', '--source', 'source-a', '--json']);
+ const recovered = JSON.parse(output.pop()!);
+ expect(recovered.count).toBe(2);
+ expect(recovered.status).toBe('ready');
+ } finally {
+ log.mockRestore();
+ }
+ });
+ }
+
+ for (const run of [runCodeCallers, runCodeCallees]) {
+ test(`${run.name} gives recovery advice for partial and empty results, not scope widening`, async () => {
+ const current = await seed();
+ const pending = await seed('source-a', 'src/pending.ts');
+ const [chunk] = await engine.executeRaw<{ id: number }>('SELECT id FROM content_chunks WHERE page_id=$1', [current]);
+ await engine.addCodeEdges([{
+ from_chunk_id: chunk.id, to_chunk_id: chunk.id, from_symbol_qualified: 'sampleSymbol', to_symbol_qualified: 'sampleSymbol',
+ edge_type: 'calls', source_id: 'source-a',
+ }]);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [pending]);
+ const output: string[] = [];
+ const log = spyOn(console, 'log').mockImplementation((text) => { output.push(String(text)); });
+ try {
+ for (const count of [1, 0]) {
+ await run(engine, ['sampleSymbol', '--source', 'source-a', '--json']);
+ const result = JSON.parse(output.pop()!);
+ expect(result.count).toBe(count);
+ expect(result.status).toBe('projection_pending');
+ expect(result.hint).toContain('incomplete');
+ expect(result.hint).not.toContain('--all-sources');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [current]);
+ }
+ } finally {
+ log.mockRestore();
+ }
+ });
+ }
+
+ test('hidden-only pending code never changes remote readiness, and probe failure is unknown even with hits', async () => {
+ const id = await seed('source-b', 'src/hidden.ts', 'function', { visibility: 'private' });
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [id]);
+ const result = await resolveCodeReadiness(engine, { kind: 'symbol', count: 0, sourceIds: ['source-a', 'source-b'], remote: true, excludePrivate: true });
+ expect(result.status).toBe('not_built');
+ expect(JSON.stringify(result)).not.toContain('hidden');
+ const unknown = await resolveCodeReadiness({ executeRaw: async () => { throw new Error('unavailable'); } } as any,
+ { kind: 'symbol', count: 1, remote: false, excludePrivate: false });
+ expect(unknown.status).toBe('unknown');
+ expect(unknown.ready).toBe(false);
+ });
+
+ for (const name of ['code_def', 'code_refs', 'code_callers', 'code_callees']) {
+ test(`${name} remains suspended for remote and omitted trust before touching storage`, async () => {
+ let reads = 0;
+ const inaccessible = new Proxy({}, { get() { reads++; throw new Error('storage access'); } });
+ for (const remote of [true, undefined]) {
+ await expect(operationsByName[name].handler({ engine: inaccessible, remote,
+ sourceId: 'source-a', auth: { allowedSources: ['source-a'] } } as unknown as OperationContext,
+ { symbol: 'sampleSymbol' })).rejects.toThrow('temporarily unavailable');
+ }
+ expect(reads).toBe(0);
+ });
+ }
+});
diff --git a/test/dispatch-response-meta.serial.test.ts b/test/dispatch-response-meta.serial.test.ts
index 184224ce5a..07b90879d9 100644
--- a/test/dispatch-response-meta.serial.test.ts
+++ b/test/dispatch-response-meta.serial.test.ts
@@ -37,7 +37,7 @@ const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');
const engineStub = {
getConfig: async () => null,
- executeRaw: async () => [],
+ executeRaw: async (sql: string) => sql.includes('AS pending') ? [{ pending: false }] : [],
} as unknown as BrainEngine;
const DEGRADED_META = {
diff --git a/test/dispatch-vector-incomplete.serial.test.ts b/test/dispatch-vector-incomplete.serial.test.ts
new file mode 100644
index 0000000000..0dba0fb456
--- /dev/null
+++ b/test/dispatch-vector-incomplete.serial.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, mock, test } from 'bun:test';
+import * as realHybrid from '../src/core/search/hybrid.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+let results: unknown[] = [];
+mock.module('../src/core/search/hybrid.ts', () => ({
+ ...realHybrid,
+ hybridSearchCached: async (_engine: unknown, _query: string, opts: { onMeta?: (meta: unknown) => void }) => {
+ opts.onMeta?.({
+ vector_enabled: true, expansion_applied: false, detail_resolved: null,
+ retrieved_count: results.length,
+ degraded: [{ stage: 'vector_candidates_incomplete', reason: 'candidate_budget' }],
+ vector_pool_underfilled: { escalations: 3, innerLimit: 1600, candidatePool: 0, incomplete: true },
+ });
+ return results;
+ },
+}));
+
+const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');
+const engine = {
+ getConfig: async () => null,
+ executeRaw: async (sql: string) => sql.includes('AS pending') ? [{ pending: false }] : [],
+} as unknown as BrainEngine;
+
+describe('HTTP MCP dispatch preserves bounded-vector incompleteness', () => {
+ test.each([false, true])('real operation response carries metadata when nonempty=%s', async nonempty => {
+ results = nonempty ? [{ page_id: 1, source_id: 'default', slug: 'notes/synthetic', chunk_text: 'Synthetic note' }] : [];
+ const response = await dispatchToolCall(engine, 'search', { query: 'synthetic' }, {
+ remote: true, transport: 'http', sourceId: 'default',
+ });
+ expect(response.isError).toBeUndefined();
+ const retrieval = (response._meta as { retrieval: Record<string, unknown> }).retrieval;
+ expect(retrieval.degraded).toContainEqual({ stage: 'vector_candidates_incomplete', reason: 'candidate_budget' });
+ expect(retrieval.vector_pool_underfilled).toEqual({ escalations: 3, innerLimit: 1600, candidatePool: 0, incomplete: true });
+ if (!nonempty) {
+ expect(response.content[1].text).toContain('vector_candidates_incomplete');
+ expect(response.content[1].text).not.toContain('clean miss');
+ }
+ });
+});
diff --git a/test/doctor-report-remote.serial.test.ts b/test/doctor-report-remote.serial.test.ts
index c157b37e57..704ca4251f 100644
--- a/test/doctor-report-remote.serial.test.ts
+++ b/test/doctor-report-remote.serial.test.ts
@@ -218,3 +218,31 @@ describe('doctorReportRemote — source scope (#4592)', () => {
expect(JSON.stringify(scoped)).not.toContain(SRCB);
});
});
+
+describe('run_doctor canonical projection readiness', () => {
+ test('the real handler excludes private and ungranted pending pages while local callers can diagnose them', async () => {
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('readiness-visible','readiness-visible'),('readiness-hidden','readiness-hidden') ON CONFLICT DO NOTHING");
+ await engine.putPage('notes/current-example', { title: 'Example', type: 'note', compiled_truth: 'current' }, { sourceId: 'readiness-visible' });
+ await engine.putPage('notes/private-example', { title: 'Private example', type: 'note', compiled_truth: 'private', frontmatter: { visibility: 'private' } }, { sourceId: 'readiness-hidden' });
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=knowledge_revision WHERE source_id='readiness-visible'");
+ const ctx = {
+ engine, remote: true, sourceId: 'readiness-hidden',
+ auth: { allowedSources: ['readiness-visible', 'readiness-hidden'] },
+ } as unknown as OperationContext;
+ const check = (report: DoctorReport) => report.checks.find(c => c.name === 'text_projection_readiness')!;
+ const remote = check(await operationsByName.run_doctor.handler(ctx, {}) as DoctorReport);
+ expect(remote.status).toBe('ok');
+ expect(remote.details).toEqual({ readiness: 'ready', ready: true });
+ const local = check(await operationsByName.run_doctor.handler({ ...ctx, remote: false }, {}) as DoctorReport);
+ expect(local.status).toBe('warn');
+ expect(local.details).toEqual({ readiness: 'projection_pending', ready: false });
+ const restricted = check(await operationsByName.run_doctor.handler({ ...ctx, auth: { ...ctx.auth!, allowedSources: ['readiness-visible'] } }, {}) as DoctorReport);
+ expect(restricted.status).toBe('ok');
+ expect(JSON.stringify(restricted)).not.toContain('readiness-hidden');
+ expect(JSON.stringify(local)).not.toContain('notes/private-example');
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='readiness-visible'");
+ const pending = check(await operationsByName.run_doctor.handler(ctx, {}) as DoctorReport);
+ expect(pending.status).toBe('warn');
+ expect(pending.details).toEqual({ readiness: 'projection_pending', ready: false });
+ });
+});
diff --git a/test/dream-postgres.serial.test.ts b/test/dream-postgres.serial.test.ts
index 51c48073ed..cc48a9c4c4 100644
--- a/test/dream-postgres.serial.test.ts
+++ b/test/dream-postgres.serial.test.ts
@@ -196,6 +196,7 @@ describe('runCycle — A7 deriveStatus counts resolved edges as work', () => {
[caller[0]!.id],
);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [pageId]);
const report = await runCycle(engine, { brainDir: null, phases: ['resolve_symbol_edges'] });
expect(report.totals.edges_resolved).toBe(1);
expect(report.status).toBe('ok'); // pre-A7 this was 'clean'
diff --git a/test/e2e/code-edges-read-parity.test.ts b/test/e2e/code-edges-read-parity.test.ts
index f2d9d66fd2..53794a6314 100644
--- a/test/e2e/code-edges-read-parity.test.ts
+++ b/test/e2e/code-edges-read-parity.test.ts
@@ -109,6 +109,7 @@ async function seedCodeEdges(eng: BrainEngine): Promise<CeFixture> {
const first = await eng.addCodeEdges(edges);
// Idempotency parity: full replay conflicts away on both engines.
const replay = await eng.addCodeEdges(edges);
+ await eng.executeRaw("UPDATE pages SET text_projection_revision=knowledge_revision WHERE slug IN ('code/ce-main','code/ce-lib','code/ce-alt')");
const rev = new Map<number, string>([[main, 'main'], [helper, 'helper'], [lib, 'lib'], [alt, 'alt']]);
return { main, helper, lib, alt, rev, insertCounts: [first, replay] };
diff --git a/test/e2e/code-intel-mcp-ops-pglite.test.ts b/test/e2e/code-intel-mcp-ops-pglite.test.ts
index 1679a08b22..d3efc3182f 100644
--- a/test/e2e/code-intel-mcp-ops-pglite.test.ts
+++ b/test/e2e/code-intel-mcp-ops-pglite.test.ts
@@ -296,6 +296,7 @@ async function seedQualifiedMethodGraph(engine: PGLiteEngine): Promise<void> {
[page],
);
await insertUnresolvedEdge(engine, rows[0]!.id, 'MyApp.Services.OrderService.SubmitAsync', 'ValidateRequest', 'source-a');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [page]);
}
async function seedCrossSourceGraph(engine: PGLiteEngine): Promise<void> {
@@ -325,6 +326,7 @@ async function seedDefSite(engine: PGLiteEngine): Promise<void> {
VALUES ($1, 0, 'export function parseMarkdown(s: string) { return s; }', 'compiled_truth', 'typescript', 'parseMarkdown', 'parseMarkdown', 'function', 1, 3)`,
[pageA],
);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [pageA]);
}
async function registerSource(engine: PGLiteEngine, id: string): Promise<void> {
@@ -359,6 +361,7 @@ async function insertChunk(
RETURNING id`,
[pageId, chunkIndex, `// ${symbolName} body`, symbolName, symbolType],
);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [pageId]);
return rows[0]!.id;
}
diff --git a/test/e2e/projection-readiness-currency.test.ts b/test/e2e/projection-readiness-currency.test.ts
new file mode 100644
index 0000000000..e3ebcca6dd
--- /dev/null
+++ b/test/e2e/projection-readiness-currency.test.ts
@@ -0,0 +1,81 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { findCodeDef } from '../../src/commands/code-def.ts';
+import { findCodeRefs } from '../../src/commands/code-refs.ts';
+import { probeProjectionReadiness } from '../../src/core/search/projection-readiness.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { hasDatabase } from './helpers.ts';
+
+const describePostgres = hasDatabase() ? describe : describe.skip;
+
+describePostgres('Postgres code-read currency and scoped projection readiness', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ }, 120_000);
+
+ afterAll(async () => { await close?.(); });
+
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('readiness-a','readiness-a'),('readiness-b','readiness-b') ON CONFLICT DO NOTHING");
+ await engine.executeRaw('UPDATE sources SET archived=false');
+ });
+
+ async function seed(source: string, slug: string, kind = 'code', privatePage = false) {
+ const [page] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO pages(source_id,slug,title,type,page_kind,compiled_truth,chunker_version,frontmatter)
+ VALUES ($1,$2,'Example','code',$3,'function readExample() {}',999,$4::text::jsonb) RETURNING id`,
+ [source, slug, kind, JSON.stringify(privatePage ? { visibility: 'private' } : {})],
+ );
+ const [chunk] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO content_chunks(page_id,chunk_index,chunk_text,symbol_name,symbol_type,language)
+ VALUES ($1,0,'function readExample() {}','readExample','function','typescript') RETURNING id`, [page.id],
+ );
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [page.id]);
+ return { page: page.id, chunk: chunk.id };
+ }
+
+ test('partial code and Markdown corpora stay pending independent of chunker version', async () => {
+ await seed('readiness-a', 'src/current.ts');
+ for (const kind of ['code', 'markdown']) {
+ const stale = await seed('readiness-a', `pending-${kind}`, kind);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid() WHERE id=$1', [stale.page]);
+ expect((await probeProjectionReadiness(engine, { sourceId: 'readiness-a', pageKind: kind })).status).toBe('projection_pending');
+ expect(await findCodeDef(engine, 'readExample', { sourceId: 'readiness-a' })).toHaveLength(kind === 'code' ? 1 : 2);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [stale.page]);
+ }
+ expect((await probeProjectionReadiness(engine, { sourceId: 'readiness-a' })).status).toBe('ready');
+ });
+
+ test('private-only and out-of-grant pending rows do not disclose their existence', async () => {
+ await seed('readiness-a', 'src/shared.ts');
+ const hidden = await seed('readiness-b', 'src/shared.ts', 'code', true);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [hidden.page]);
+ expect(await probeProjectionReadiness(engine, { sourceIds: ['readiness-a', 'readiness-b'], excludePrivate: true })).toEqual({ status: 'ready', ready: true });
+ expect(await probeProjectionReadiness(engine, { sourceIds: ['readiness-a'] })).toEqual({ status: 'ready', ready: true });
+ const defs = await findCodeDef(engine, 'readExample', { sourceId: 'readiness-b', sourceIds: ['readiness-a'], language: 'typescript' });
+ const refs = await findCodeRefs(engine, 'readExample', { sourceIds: ['readiness-a', 'readiness-b'], excludePrivate: true });
+ expect(defs.map(r => r.source_id)).toEqual(['readiness-a']);
+ expect(refs.map(r => r.source_id)).toEqual(['readiness-a']);
+ });
+
+ test('resolved and unresolved caller queries require current live endpoints', async () => {
+ const caller = await seed('readiness-a', 'src/caller.ts');
+ const target = await seed('readiness-a', 'src/target.ts');
+ await engine.addCodeEdges([
+ { from_chunk_id: caller.chunk, to_chunk_id: target.chunk, from_symbol_qualified: 'callerExample', to_symbol_qualified: 'targetExample', edge_type: 'calls', source_id: 'readiness-a' },
+ { from_chunk_id: caller.chunk, from_symbol_qualified: 'callerExample', to_symbol_qualified: 'externalExample', edge_type: 'calls', source_id: 'readiness-a' },
+ ]);
+ expect(await engine.getCallersOf('targetExample', { sourceId: 'readiness-a' })).toHaveLength(1);
+ expect(await engine.getCalleesOf('callerExample', { sourceId: 'readiness-a' })).toHaveLength(2);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [target.page]);
+ expect(await engine.getCallersOf('targetExample', { sourceId: 'readiness-a' })).toHaveLength(0);
+ expect(await engine.getCalleesOf('callerExample', { sourceId: 'readiness-a' })).toHaveLength(1);
+ await engine.executeRaw('UPDATE pages SET deleted_at=NOW() WHERE id=$1', [caller.page]);
+ expect(await engine.getCalleesOf('callerExample', { sourceId: 'readiness-a' })).toHaveLength(0);
+ expect(await findCodeDef(engine, 'readExample', { sourceId: 'readiness-a' })).toHaveLength(0);
+ });
+});
diff --git a/test/e2e/projection-recovery-parity.test.ts b/test/e2e/projection-recovery-parity.test.ts
new file mode 100644
index 0000000000..876a381599
--- /dev/null
+++ b/test/e2e/projection-recovery-parity.test.ts
@@ -0,0 +1,11 @@
+import { test } from 'bun:test';
+import { hasDatabase } from './helpers.ts';
+
+if (hasDatabase()) {
+ await import('../page-projection-origin.test.ts');
+ await import('../page-projection-code-recovery.test.ts');
+ await import('../code-projection-edge-recovery.test.ts');
+ await import('../symbol-resolver-projection-race.test.ts');
+} else {
+ test.skip('projection recovery parity requires PostgreSQL', () => {});
+}
diff --git a/test/e2e/projection-statistics-postgres.test.ts b/test/e2e/projection-statistics-postgres.test.ts
new file mode 100644
index 0000000000..89d7b53a4e
--- /dev/null
+++ b/test/e2e/projection-statistics-postgres.test.ts
@@ -0,0 +1,79 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import postgres from 'postgres';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { currentTextProjectionFilter } from '../../src/core/search/safe-chunks.ts';
+import { PROJECTION_STATISTICS_SQL, verifyProjectionStatistics } from '../../src/core/search/projection-statistics.ts';
+import { assertSafeE2eDatabaseUrl, hasDatabase } from './helpers.ts';
+
+const describeDb = hasDatabase() ? describe : describe.skip;
+
+describeDb('projection planner statistics with PostgreSQL runtime roles', () => {
+ const suffix = randomUUID().replaceAll('-', '');
+ const schema = `projection_stats_${suffix}`;
+ const owner = `projection_owner_${suffix}`;
+ const reader = `projection_reader_${suffix}`;
+ let sql: ReturnType<typeof postgres>;
+ const engine = {
+ executeRaw: async (query: string, params: unknown[] = []) => sql.unsafe(query, params as never[]),
+ } as unknown as Pick<BrainEngine, 'executeRaw'>;
+
+ beforeAll(async () => {
+ const url = process.env.DATABASE_URL!;
+ assertSafeE2eDatabaseUrl(url);
+ sql = postgres(url, { max: 1 });
+ await sql.unsafe(`CREATE ROLE ${owner}; CREATE ROLE ${reader}; CREATE SCHEMA ${schema} AUTHORIZATION ${owner};
+ SET search_path TO ${schema}, public;
+ CREATE TABLE pages(id integer PRIMARY KEY, source_id text, text_projection_revision uuid, knowledge_revision uuid);
+ ALTER TABLE pages OWNER TO ${owner};
+ INSERT INTO pages SELECT i, CASE WHEN i <= 1000 THEN 'visible' ELSE 'other' END,
+ '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001'
+ FROM generate_series(1, 10000) i;
+ SET ROLE ${owner};
+ ${PROJECTION_STATISTICS_SQL}
+ RESET ROLE;
+ GRANT USAGE ON SCHEMA ${schema} TO ${reader};
+ GRANT SELECT ON pages TO ${reader};`);
+ }, 30_000);
+
+ afterAll(async () => {
+ if (!sql) return;
+ try {
+ await sql.unsafe(`RESET ROLE; RESET search_path; DROP SCHEMA IF EXISTS ${schema} CASCADE;
+ DROP ROLE IF EXISTS ${reader}; DROP ROLE IF EXISTS ${owner}`);
+ } finally { await sql.end(); }
+ }, 30_000);
+
+ test('table-owner maintenance verifies sampled expression statistics', async () => {
+ await sql.unsafe(`SET ROLE ${owner}`);
+ try { await verifyProjectionStatistics(engine); }
+ finally { await sql.unsafe('RESET ROLE'); }
+ });
+
+ test('the normal planner uses the measured estimate for a non-owner reader', async () => {
+ await sql.unsafe(`SET ROLE ${reader}`);
+ try {
+ const result = await sql.unsafe(`EXPLAIN (FORMAT JSON) SELECT * FROM pages p WHERE ${currentTextProjectionFilter('p')}`);
+ expect(result[0]['QUERY PLAN'][0].Plan['Plan Rows']).toBe(10000);
+ } finally { await sql.unsafe('RESET ROLE'); }
+ });
+
+ test('forced row security keeps scoped reads correct without claiming hidden statistics are absent', async () => {
+ await sql.unsafe(`ALTER TABLE pages ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE pages FORCE ROW LEVEL SECURITY;
+ CREATE POLICY visible_pages ON pages USING (source_id = 'visible')`);
+ try {
+ for (const role of [reader, owner]) {
+ await sql.unsafe(`SET ROLE ${role}`);
+ try {
+ const rows = await sql.unsafe(`SELECT count(*)::int AS count FROM pages p WHERE ${currentTextProjectionFilter('p')}`);
+ expect(rows[0].count).toBe(1000);
+ await expect(verifyProjectionStatistics(engine)).rejects.toThrow('row-security policy');
+ } finally { await sql.unsafe('RESET ROLE'); }
+ }
+ await verifyProjectionStatistics(engine);
+ } finally {
+ await sql.unsafe('ALTER TABLE pages DISABLE ROW LEVEL SECURITY');
+ }
+ });
+});
diff --git a/test/e2e/put-page-persistence-postgres.test.ts b/test/e2e/put-page-persistence-postgres.test.ts
index 6883791f64..62b3655f0d 100644
--- a/test/e2e/put-page-persistence-postgres.test.ts
+++ b/test/e2e/put-page-persistence-postgres.test.ts
@@ -93,7 +93,7 @@ d('Postgres put_page persistence', () => {
const disk = readFileSync(join(root, `${slug}.md`), 'utf8');
const binding = await getWorktreeBinding(engine, 'default');
expect(binding).not.toBeNull();
- const holder = await acquireWorktree(binding!);
+ const holder = await acquireWorktree(binding!, 5000);
expect(holder).not.toBeNull();
let accepted: Awaited<ReturnType<typeof put>>;
try {
diff --git a/test/e2e/search-query-contract-postgres.test.ts b/test/e2e/search-query-contract-postgres.test.ts
new file mode 100644
index 0000000000..04e2f3b9b2
--- /dev/null
+++ b/test/e2e/search-query-contract-postgres.test.ts
@@ -0,0 +1,64 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupLegacyEmbeddingDB, teardownDB } from './helpers.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { seedSearchQueryContract, verifyKeywordTieOrder, verifyMixedCjkCase, verifySearchDateBounds } from '../helpers/search-query-contract.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+(hasDatabase() ? describe : describe.skip)('search query contract on Postgres', () => {
+ let engine: PostgresEngine;
+ beforeAll(async () => {
+ engine = await setupLegacyEmbeddingDB();
+ await seedSearchQueryContract(engine);
+ }, 120_000);
+ afterAll(async () => { await teardownDB(); });
+ test('all arms preserve inclusive bounds and strict legacy microsecond precision', async () => { await verifySearchDateBounds(engine); });
+ test('keyword page pools and chunk pagination have deterministic tie ordering', async () => { await verifyKeywordTieOrder(engine); });
+ test('mixed CJK and Latin terms remain case-insensitive', async () => { await verifyMixedCjkCase(engine); });
+ test('relaxed retries retain scope and restore the planner setting', async () => {
+ const before = await engine.executeRaw(`SHOW enable_seqscan`);
+ for (const requireSafeChunks of [false, true]) {
+ const hits = await engine.searchKeyword('ordertoken impossibleterm', { sourceId: 'query-order', orFallback: true, requireSafeChunks });
+ expect(hits.length).toBeGreaterThan(0);
+ expect(hits.every(hit => hit.keyword_relaxed && hit.source_id === 'query-order')).toBe(true);
+ expect((await engine.searchTitles('ordertoken impossibleterm', { sourceId: 'query-order', requireSafeChunks })).length).toBeGreaterThan(0);
+ }
+ expect(await engine.searchKeyword('ordertoken impossibleterm', { sourceId: 'query-dates', orFallback: true })).toEqual([]);
+ expect(await engine.executeRaw(`SHOW enable_seqscan`)).toEqual(before);
+ });
+
+ test('restricted runtime roles retain RLS and local settings through relaxed retries', async () => {
+ await engine.executeRaw('CREATE ROLE query_contract_reader NOLOGIN');
+ const tables = ['pages', 'content_chunks', 'sources'];
+ const original = await engine.executeRaw<{ relname: string; relrowsecurity: boolean }>(`SELECT relname, relrowsecurity FROM pg_class WHERE relname = ANY($1::text[])`, [tables]);
+ try {
+ await engine.executeRaw('GRANT USAGE ON SCHEMA public TO query_contract_reader');
+ await engine.executeRaw('GRANT SELECT ON pages, content_chunks, sources TO query_contract_reader');
+ for (const table of tables) {
+ await engine.executeRaw(`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY`);
+ await engine.executeRaw(`CREATE POLICY query_contract_allow ON ${table} FOR SELECT TO query_contract_reader USING (true)`);
+ }
+ await engine.executeRaw(`CREATE POLICY query_contract_source ON pages AS RESTRICTIVE FOR SELECT TO query_contract_reader USING (source_id = 'query-order')`);
+ await withEnv({ GBRAIN_RLS_SCOPE_BINDING: '1' }, async () => {
+ await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL ROLE query_contract_reader');
+ await tx.executeRaw(`SELECT set_config('app.scopes', 'original-scope', true)`);
+ const before = await tx.executeRaw(`SHOW enable_seqscan`);
+ const hits = await tx.searchKeyword('ordertoken impossibleterm', { sourceId: 'query-order', orFallback: true });
+ expect(hits.length).toBeGreaterThan(0);
+ expect(hits.every(hit => hit.source_id === 'query-order' && hit.keyword_relaxed)).toBe(true);
+ expect(await tx.searchKeyword('precisiontoken impossibleterm', { sourceId: 'query-dates', orFallback: true })).toEqual([]);
+ expect(await tx.executeRaw(`SELECT current_setting('app.scopes') AS scopes`)).toEqual([{ scopes: 'original-scope' }]);
+ expect(await tx.executeRaw(`SHOW enable_seqscan`)).toEqual(before);
+ });
+ });
+ } finally {
+ await engine.executeRaw('DROP POLICY IF EXISTS query_contract_source ON pages');
+ for (const table of tables) {
+ await engine.executeRaw(`DROP POLICY IF EXISTS query_contract_allow ON ${table}`);
+ if (!original.find(row => row.relname === table)?.relrowsecurity) await engine.executeRaw(`ALTER TABLE ${table} DISABLE ROW LEVEL SECURITY`);
+ }
+ await engine.executeRaw('DROP OWNED BY query_contract_reader');
+ await engine.executeRaw('DROP ROLE query_contract_reader');
+ }
+ });
+});
diff --git a/test/e2e/search-readiness-http.test.ts b/test/e2e/search-readiness-http.test.ts
new file mode 100644
index 0000000000..8e983c639a
--- /dev/null
+++ b/test/e2e/search-readiness-http.test.ts
@@ -0,0 +1,190 @@
+/**
+ * Real legacy-bearer HTTP MCP regression for projection-readiness response
+ * metadata. The fixture is disk-backed because the CLI HTTP server owns the
+ * PGLite lock; all pages are seeded before it starts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { createServer } from 'node:net';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { keylessBrainEnv } from '../helpers/provider-env.ts';
+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';
+
+const MATCH = 'http-readiness-public-match';
+const PRIVATE_PENDING = 'http-readiness-private-pending-canary';
+const FOREIGN_PENDING = 'http-readiness-foreign-pending-canary';
+
+function brainEnv(home: string): Record<string, string> {
+ return keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined,
+ GBRAIN_DATABASE_URL: undefined,
+ GBRAIN_ENGINE: undefined,
+ GBRAIN_SOURCE: undefined,
+ GBRAIN_REMOTE_CLIENT_SECRET: undefined,
+ GBRAIN_MCP_FORCE_SURFACE: undefined,
+ GBRAIN_SKIP_STARTUP_HOOKS: '1',
+ });
+}
+
+function cli(env: Record<string, string>, args: string[]): string {
+ const result = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', ...args], {
+ cwd: process.cwd(), env, encoding: 'utf8', timeout: 60_000,
+ });
+ if (result.status !== 0) {
+ throw new Error(cliDiagnostic(args[0], {
+ exitCode: result.status ?? -1,
+ stdout: result.stdout ?? '',
+ stderr: result.stderr ?? '',
+ }));
+ }
+ return result.stdout;
+}
+
+async function unusedPort(): Promise<number> {
+ const probe = createServer();
+ await new Promise<void>((resolve, reject) => {
+ probe.once('error', reject);
+ probe.listen(0, '127.0.0.1', resolve);
+ });
+ const port = (probe.address() as { port: number }).port;
+ await new Promise<void>((resolve, reject) => probe.close(error => error ? reject(error) : resolve()));
+ return port;
+}
+
+describe('search projection readiness over legacy bearer HTTP MCP', () => {
+ let home = '';
+ let token = '';
+ let base = '';
+ let server: ChildProcess | undefined;
+ let client: Client | undefined;
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-search-readiness-http-'));
+ const env = brainEnv(home);
+ cli(env, ['init', '--pglite', '--no-embedding', '--non-interactive']);
+ const auth = cli(env, ['auth', 'create', 'e2e-search-readiness']);
+ token = auth.match(/gbrain_[a-f0-9]{64}/)?.[0] ?? '';
+ if (!token) throw new Error('auth create did not yield a legacy bearer token');
+
+ const config = JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')) as { database_path: string };
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: config.database_path });
+ try {
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ await engine.executeRaw('INSERT INTO sources(id, name) VALUES ($1, $1)', ['foreign-readiness-source']);
+
+ await importFromContent(engine, 'notes/current', [
+ '---', 'title: Current public fixture', 'type: note', '---', MATCH,
+ ].join('\n'), { sourceId: 'default', noEmbed: true });
+
+ await engine.putPage('notes/pending-visible', {
+ type: 'code', page_kind: 'code', title: 'Pending visible fixture', compiled_truth: 'unprojected visible fixture',
+ }, { sourceId: 'default' });
+ await engine.putPage('notes/pending-private', {
+ type: 'code', page_kind: 'code', title: PRIVATE_PENDING, compiled_truth: PRIVATE_PENDING,
+ frontmatter: { visibility: 'private' },
+ }, { sourceId: 'default' });
+ await engine.putPage('notes/pending-foreign', {
+ type: 'code', page_kind: 'code', title: FOREIGN_PENDING, compiled_truth: FOREIGN_PENDING,
+ }, { sourceId: 'foreign-readiness-source' });
+ await engine.executeRaw(
+ 'UPDATE pages SET text_projection_revision = NULL WHERE slug = ANY($1::text[])',
+ [['notes/pending-visible', 'notes/pending-private', 'notes/pending-foreign']],
+ );
+ const pending = await engine.executeRaw<{ slug: string; pending: boolean }>(
+ `SELECT slug, text_projection_revision IS DISTINCT FROM knowledge_revision AS pending
+ FROM pages WHERE slug LIKE 'notes/pending-%' ORDER BY slug`,
+ );
+ expect(pending).toEqual([
+ { slug: 'notes/pending-foreign', pending: true },
+ { slug: 'notes/pending-private', pending: true },
+ { slug: 'notes/pending-visible', pending: true },
+ ]);
+ } finally {
+ await engine.disconnect();
+ }
+
+ const port = await unusedPort();
+ base = `http://127.0.0.1:${port}`;
+ let stderr = '';
+ server = spawn('bun', [
+ '--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--surface', 'full',
+ '--bind', '127.0.0.1', '--port', String(port), '--public-url', base,
+ '--suppress-bootstrap-token',
+ ], { cwd: process.cwd(), env, stdio: ['ignore', 'ignore', 'pipe'] });
+ server.stderr?.on('data', (chunk: Buffer) => { stderr = (stderr + chunk.toString()).slice(-4000); });
+
+ let ready = false;
+ for (let attempt = 0; attempt < 120; attempt++) {
+ try {
+ ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(1_000) })).ok;
+ } catch {}
+ if (ready) break;
+ if (server.exitCode !== null) break;
+ await Bun.sleep(250);
+ }
+ if (!ready) throw new Error(fixtureDiagnostic('HTTP server readiness', stderr, [token]));
+
+ client = new Client({ name: 'search-readiness-http-e2e', version: '1' }, { capabilities: {} });
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${base}/mcp`), {
+ requestInit: { headers: { Authorization: `Bearer ${token}` } },
+ }), { signal: AbortSignal.timeout(30_000) });
+ }, 120_000);
+
+ afterAll(async () => {
+ try {
+ await client?.close();
+ } catch {}
+ if (server && server.exitCode === null && server.signalCode === null) {
+ const child = server;
+ await new Promise<void>(resolve => {
+ const deadline = setTimeout(() => child.kill('SIGKILL'), 5_000);
+ child.once('exit', () => { clearTimeout(deadline); resolve(); });
+ child.kill('SIGTERM');
+ });
+ }
+ if (home) rmSync(home, { recursive: true, force: true });
+ }, 30_000);
+
+ async function search(query: string) {
+ const result = await client!.callTool({ name: 'search', arguments: { query, source_id: 'default' } }, undefined, { timeout: 30_000 });
+ expect(result.isError, toolDiagnostic('search', result, [token])).not.toBe(true);
+ const content = result.content as Array<{ type: string; text: string }>;
+ const retrieval = (result as typeof result & { _meta?: { retrieval?: Record<string, unknown> } })._meta?.retrieval;
+ expect(retrieval).toBeDefined();
+ return { result, content, body: JSON.parse(content[0]!.text), retrieval: retrieval! };
+ }
+
+ function expectPendingMetadata(retrieval: Record<string, unknown>) {
+ expect(retrieval.degraded).toContainEqual({ stage: 'projection_pending' });
+ expect(retrieval.projection_readiness).toMatchObject({ status: 'projection_pending', ready: false });
+ const publicMetadata = JSON.stringify(retrieval);
+ expect(publicMetadata).not.toContain(PRIVATE_PENDING);
+ expect(publicMetadata).not.toContain(FOREIGN_PENDING);
+ }
+
+ test('empty search keeps its bare-array body and exposes visible pending projection work only through retrieval metadata', async () => {
+ const response = await search('http-readiness-no-match');
+ expect(response.content).toHaveLength(2);
+ expect(response.body).toEqual([]);
+ expectPendingMetadata(response.retrieval);
+ expect(JSON.stringify(response.result)).not.toContain(PRIVATE_PENDING);
+ expect(JSON.stringify(response.result)).not.toContain(FOREIGN_PENDING);
+ }, 30_000);
+
+ test('partial nonempty search exposes the same readiness metadata without changing the public result body', async () => {
+ const response = await search(MATCH);
+ expect(response.content).toHaveLength(1);
+ expect(response.body).toHaveLength(1);
+ expect(JSON.stringify(response.body)).toContain(MATCH);
+ expectPendingMetadata(response.retrieval);
+ expect(JSON.stringify(response.result)).not.toContain(PRIVATE_PENDING);
+ expect(JSON.stringify(response.result)).not.toContain(FOREIGN_PENDING);
+ }, 30_000);
+});
diff --git a/test/e2e/symbol-resolver-pglite.test.ts b/test/e2e/symbol-resolver-pglite.test.ts
index 45716615e3..a94a95a03b 100644
--- a/test/e2e/symbol-resolver-pglite.test.ts
+++ b/test/e2e/symbol-resolver-pglite.test.ts
@@ -201,6 +201,7 @@ async function insertChunk(
RETURNING id`,
[pageId, chunkIndex, `// ${symbolName} body`, symbolName, symbolType],
);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [pageId]);
return rows[0]!.id;
}
diff --git a/test/e2e/vector-candidate-safety-postgres.test.ts b/test/e2e/vector-candidate-safety-postgres.test.ts
new file mode 100644
index 0000000000..655e5dc04b
--- /dev/null
+++ b/test/e2e/vector-candidate-safety-postgres.test.ts
@@ -0,0 +1,188 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { candidateColumn, candidateVector, seedVectorCandidateCorpus, verifyVectorCapabilityRetry } from '../helpers/vector-candidate-corpus.ts';
+import type { SearchOpts } from '../../src/core/types.ts';
+
+(hasDatabase() ? describe : describe.skip)('Postgres filtered ANN candidate safety', () => {
+ let engine: PostgresEngine;
+ let delayExact = false;
+ const statements: Array<{ sql: string; params: unknown[] }> = [];
+ const opts: SearchOpts = { limit: 75, sourceId: 'ann-allowed', excludePrivate: true, embeddingColumn: candidateColumn };
+
+ beforeAll(async () => {
+ const seedEngine = await setupDB();
+ await seedVectorCandidateCorpus(seedEngine);
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: process.env.DATABASE_URL!, poolSize: 1 });
+ const scoped = engine as unknown as { withScopedReadTransaction: (...args: any[]) => Promise<any> };
+ const original = scoped.withScopedReadTransaction;
+ scoped.withScopedReadTransaction = function (sourceIds, sourceId, fn, options) { return original.call(this, sourceIds, sourceId, (tx: any) => fn(new Proxy(tx, {
+ get(target, key) {
+ if (key !== 'unsafe') return Reflect.get(target, key);
+ return (sql: string, params: unknown[]) => {
+ if (sql.includes('WITH hnsw_candidates')) statements.push({ sql, params: [...params] });
+ if (delayExact && sql.includes(') + 0')) return target.unsafe('SELECT pg_sleep(30)');
+ return target.unsafe(sql, params);
+ };
+ },
+ })), options); };
+ }, 240_000);
+
+ afterAll(async () => {
+ await engine?.executeRaw('DROP INDEX IF EXISTS idx_chunks_candidate_fixture');
+ await engine?.executeRaw('ALTER TABLE content_chunks DROP COLUMN IF EXISTS embedding_candidate_fixture');
+ await engine?.disconnect();
+ await teardownDB();
+ }, 60_000);
+
+ test('a transient capability probe is retried and successful capability is cached', async () => { await verifyVectorCapabilityRetry(engine); });
+
+ test('natural HNSW serves a mostly-current corpus and selective plans preserve authorization', async () => {
+ const firstStatement = statements.length;
+ await engine.searchVector(candidateVector, { limit: 75, embeddingColumn: candidateColumn });
+ const events: unknown[] = [];
+ const hits = await engine.searchVector(candidateVector, { ...opts, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits).toHaveLength(75);
+ expect(new Set(hits.map(hit => hit.page_id)).size).toBe(75);
+ expect(hits.every(hit => hit.source_id === 'ann-allowed' && Number(hit.slug.split('-').at(-1)) % 100 !== 1)).toBe(true);
+ expect(events).toEqual([]);
+ const captured = statements[firstStatement];
+ const plan = await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL hnsw.ef_search = 375`);
+ await tx.executeRaw(`SET LOCAL hnsw.iterative_scan = 'strict_order'`);
+ return tx.executeRaw(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${captured.sql}`, captured.params);
+ });
+ expect(JSON.stringify(plan)).toContain('idx_chunks_candidate_fixture');
+ const stale = await engine.executeRaw(`SELECT id FROM pages WHERE text_projection_revision IS DISTINCT FROM knowledge_revision`);
+ expect(stale.length).toBeGreaterThan(0);
+ const staleIds = new Set(stale.map(row => Number(row.id)));
+ expect(hits.some(hit => staleIds.has(hit.page_id))).toBe(false);
+ }, 60_000);
+
+ test('filtered HNSW underfill is recovered without confusing a short pool with exhaustion', async () => {
+ const captured = statements.find(statement => statement.params.includes('ann-allowed'))!;
+ await engine.executeRaw('SET enable_seqscan = off');
+ await engine.executeRaw('SET enable_sort = off');
+ try {
+ const oldRows = await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL hnsw.ef_search = 75`);
+ await tx.executeRaw(`SET LOCAL hnsw.iterative_scan = 'off'`);
+ return tx.executeRaw(captured.sql, captured.params.map(value => value === 375 ? 75 : value));
+ });
+ expect(oldRows.filter(row => row.page_id != null).length).toBeLessThan(75);
+ const events: unknown[] = [];
+ const hits = await engine.searchVector(candidateVector, { ...opts, onVectorPoolMeta: meta => events.push(meta) });
+ console.info(JSON.stringify({ metric: 'filtered-ann-candidates', efSearchOnly: oldRows.filter(row => row.page_id != null).length, boundedRecovery: hits.length }));
+ expect(hits).toHaveLength(75);
+ expect(events).toEqual([]);
+ } finally {
+ await engine.executeRaw('RESET enable_seqscan');
+ await engine.executeRaw('RESET enable_sort');
+ }
+ }, 60_000);
+
+ test('older-extension compatibility uses one explicitly exact and identically scoped fallback', async () => {
+ const capability = engine as unknown as { vectorIterativeScan?: Promise<boolean> };
+ const previous = capability.vectorIterativeScan;
+ const start = statements.length;
+ capability.vectorIterativeScan = Promise.resolve(false);
+ await engine.executeRaw('SET enable_seqscan = off');
+ await engine.executeRaw('SET enable_sort = off');
+ try {
+ const events: unknown[] = [];
+ const hits = await engine.searchVector(candidateVector, { ...opts, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits).toHaveLength(75);
+ expect(hits.every(hit => hit.source_id === 'ann-allowed' && Number(hit.slug.split('-').at(-1)) % 100 !== 1)).toBe(true);
+ expect(events).toEqual([]);
+ const exact = statements.slice(start).filter(statement => statement.sql.includes(') + 0'));
+ expect(exact).toHaveLength(1);
+ const plan = await engine.executeRaw(`EXPLAIN (FORMAT JSON) ${exact[0].sql}`, exact[0].params);
+ expect(JSON.stringify(plan)).not.toContain('idx_chunks_candidate_fixture');
+ } finally {
+ capability.vectorIterativeScan = previous;
+ await engine.executeRaw('RESET enable_seqscan');
+ await engine.executeRaw('RESET enable_sort');
+ }
+ }, 60_000);
+
+ test('deep offsets past ef_search 1000 remain reachable', async () => {
+ const events: unknown[] = [];
+ const hits = await engine.searchVector(candidateVector, { limit: 10, offset: 1040, embeddingColumn: candidateColumn, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits).toHaveLength(10);
+ expect(events).toEqual([]);
+ }, 60_000);
+
+ test('natural ANN recall remains measurable against an identically scoped exact baseline', async () => {
+ for (const angle of [0, 0.5, 1.5]) {
+ const query = new Float32Array([Math.cos(angle), Math.sin(angle), 0.1, 0, 0, 0, 0, 0]);
+ const firstStatement = statements.length;
+ const annStart = performance.now();
+ const hits = await engine.searchVector(query, { limit: 75, embeddingColumn: candidateColumn });
+ const annMs = performance.now() - annStart;
+ const captured = statements[firstStatement];
+ const exactSql = captured.sql.replace('ORDER BY cc."embedding_candidate_fixture" <=> $1::vector', 'ORDER BY (cc."embedding_candidate_fixture" <=> $1::vector) + 0');
+ expect(exactSql).not.toBe(captured.sql);
+ const params = [...captured.params];
+ params[1] = null;
+ const exactStart = performance.now();
+ const exact = await engine.executeRaw(exactSql, params);
+ const exactIds = new Set(exact.map(row => Number(row.page_id)));
+ const recall = hits.filter(hit => exactIds.has(hit.page_id)).length / 75;
+ console.info(JSON.stringify({ metric: 'candidate-recall@75', angle, recall, annMs, exactMs: performance.now() - exactStart }));
+ expect(hits).toHaveLength(75);
+ expect(recall).toBeGreaterThanOrEqual(0.9);
+ }
+ }, 60_000);
+
+ test('all shape filters remain in the candidate pool and empty scopes are genuinely exhausted', async () => {
+ const events: unknown[] = [];
+ expect(await engine.searchVector(candidateVector, { ...opts, type: 'company', onVectorPoolMeta: meta => events.push(meta) })).toEqual([]);
+ expect(await engine.searchVector(candidateVector, { ...opts, sourceId: 'missing-source', onVectorPoolMeta: meta => events.push(meta) })).toEqual([]);
+ expect(await engine.searchVector(candidateVector, { ...opts, language: 'python', onVectorPoolMeta: meta => events.push(meta) })).toEqual([]);
+ expect(events).toEqual([]);
+ const hits = await engine.searchVector(candidateVector, opts);
+ const excluded = hits.slice(0, 10).map(hit => hit.slug);
+ const filtered = await engine.searchVector(candidateVector, { ...opts, exclude_slugs: excluded, types: ['note'], symbolKind: 'function', language: 'typescript' });
+ expect(filtered).toHaveLength(75);
+ expect(filtered.some(hit => excluded.includes(hit.slug))).toBe(false);
+ }, 60_000);
+
+ test('search-local ANN settings never leak onto the pooled connection', async () => {
+ const before = await engine.executeRaw(`SELECT current_setting('hnsw.ef_search') AS ef, current_setting('hnsw.iterative_scan') AS iterative, current_setting('hnsw.max_scan_tuples') AS tuples`);
+ await engine.searchVector(candidateVector, opts);
+ expect(await engine.executeRaw(`SELECT current_setting('hnsw.ef_search') AS ef, current_setting('hnsw.iterative_scan') AS iterative, current_setting('hnsw.max_scan_tuples') AS tuples`)).toEqual(before);
+ await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL statement_timeout = '20s'`);
+ const before = await tx.executeRaw(`SELECT current_setting('statement_timeout') AS timeout, current_setting('hnsw.ef_search') AS ef, current_setting('hnsw.iterative_scan') AS iterative, current_setting('hnsw.max_scan_tuples') AS tuples`);
+ await tx.searchVector(candidateVector, opts);
+ await tx.searchVector(candidateVector, { ...opts, sourceId: 'missing-source' });
+ expect(await tx.executeRaw(`SELECT current_setting('statement_timeout') AS timeout, current_setting('hnsw.ef_search') AS ef, current_setting('hnsw.iterative_scan') AS iterative, current_setting('hnsw.max_scan_tuples') AS tuples`)).toEqual(before);
+ });
+ });
+
+ test('the exact fallback is server-cancelled at the remaining deadline and preserves ANN survivors', async () => {
+ const capability = engine as unknown as { vectorIterativeScan?: Promise<boolean> };
+ const previous = capability.vectorIterativeScan;
+ capability.vectorIterativeScan = Promise.resolve(false);
+ await engine.executeRaw('SET enable_seqscan = off');
+ await engine.executeRaw('SET enable_sort = off');
+ delayExact = true;
+ try {
+ const events: Array<{ reason?: string; exactFallback?: boolean }> = [];
+ const start = performance.now();
+ const hits = await engine.searchVector(candidateVector, { ...opts, onVectorPoolMeta: meta => events.push(meta) });
+ expect(performance.now() - start).toBeLessThan(15_000);
+ expect(hits.length).toBeGreaterThan(0);
+ expect(hits.length).toBeLessThan(75);
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ reason: 'deadline', exactFallback: true });
+ expect(await engine.executeRaw('SELECT 1 AS healthy')).toEqual([{ healthy: 1 }]);
+ } finally {
+ delayExact = false;
+ capability.vectorIterativeScan = previous;
+ await engine.executeRaw('RESET enable_seqscan');
+ await engine.executeRaw('RESET enable_sort');
+ }
+ }, 30_000);
+});
diff --git a/test/fence-extraction.test.ts b/test/fence-extraction.test.ts
index 2f1dc0abf5..dccd319531 100644
--- a/test/fence-extraction.test.ts
+++ b/test/fence-extraction.test.ts
@@ -40,8 +40,13 @@ More prose.`;
await importFromContent(engine, 'guides/fence-ts', md, { noEmbed: true });
const chunks = await engine.getChunks('guides/fence-ts');
const fenceChunks = chunks.filter(c => c.chunk_source === 'fenced_code');
- expect(fenceChunks.length).toBeGreaterThan(0);
- expect(fenceChunks[0]!.language).toBe('typescript');
+ expect(fenceChunks).toHaveLength(1);
+ expect(fenceChunks[0]).toMatchObject({ language: 'typescript', symbol_name: 'hello', start_line: 1, end_line: 3, modality: 'text' });
+ expect(fenceChunks[0].symbol_type).toMatch(/function|export/);
+ expect(fenceChunks[0].chunk_text).toContain('fence.ts:1-3');
+ expect(fenceChunks[0].chunk_text).toContain('return `Hello, ${name}`;');
+ expect(chunks.map(c => c.chunk_index)).toEqual(chunks.map((_, i) => i));
+ expect(chunks.at(-1)?.chunk_source).toBe('fenced_code');
});
test('Python fence → language=python, chunk_text contains the def', async () => {
@@ -195,8 +200,10 @@ echo hi
// Structural pin: the quadratic-lexer class of bug can only come back if
// someone re-imports marked into the import hot path.
const { readFileSync } = await import('fs');
- const src = readFileSync(new URL('../src/core/import-file.ts', import.meta.url), 'utf8');
- expect(src).not.toMatch(/from ['"]marked['"]/);
+ for (const path of ['import-file.ts', 'markdown-chunks.ts']) {
+ const src = readFileSync(new URL(`../src/core/${path}`, import.meta.url), 'utf8');
+ expect(src).not.toMatch(/from ['"]marked['"]/);
+ }
});
// #2862 — linear-scanner parity edges the marked walk used to handle.
diff --git a/test/helpers/embed-projection-mock.ts b/test/helpers/embed-projection-mock.ts
index 79d8bf7932..fc01d9fff7 100644
--- a/test/helpers/embed-projection-mock.ts
+++ b/test/helpers/embed-projection-mock.ts
@@ -7,6 +7,7 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
// throw on indexing and count the page as a failed embed.
const revision = '00000000-0000-4000-8000-000000000001';
const pages = new Map<string, number>();
+ const pageKinds = new Map<number, string>();
overrides = {
executeRaw: async () => [],
getConfigKeys: async () => [],
@@ -15,6 +16,7 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
const page = overrides.getPage ? await overrides.getPage(slug, opts) : { slug, compiled_truth: 'Fixture body', timeline: '' };
if (!page) return null;
if (!pages.has(slug)) pages.set(slug, pages.size + 1);
+ pageKinds.set(pages.get(slug)!, page.page_kind ?? (page.type === 'code' ? 'code' : 'markdown'));
return { revision, sourceIncarnation: revision, tags: [], withdrawals: [], page: {
id: pages.get(slug), slug, source_id: opts?.sourceId ?? 'default', title: slug,
knowledge_revision: revision, text_projection_revision: revision, ...page,
@@ -22,6 +24,10 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
},
...overrides,
};
+ const executeRaw = overrides.executeRaw;
+ overrides.executeRaw = async (sql: string, params?: unknown[]) => sql.startsWith('SELECT page_kind FROM pages WHERE id=')
+ ? [{ page_kind: pageKinds.get(Number(params?.[0])) ?? 'markdown' }]
+ : executeRaw(sql, params);
const calls: { method: string; args: any[] }[] = [];
const track = (method: string) => (...args: any[]) => {
calls.push({ method, args });
diff --git a/test/helpers/search-query-contract.ts b/test/helpers/search-query-contract.ts
new file mode 100644
index 0000000000..265dfcd574
--- /dev/null
+++ b/test/helpers/search-query-contract.ts
@@ -0,0 +1,82 @@
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { SearchOpts } from '../../src/core/types.ts';
+import { installFixtureChunks } from './page-projection.ts';
+
+const vector = new Float32Array(1536);
+vector[0] = 1;
+const dates = [
+ ['start', '2026-03-01T00:00:00Z'],
+ ['before-precise', '2026-03-01T12:00:00.123455Z'],
+ ['precise', '2026-03-01T12:00:00.123456Z'],
+ ['after-precise', '2026-03-01T12:00:00.123457Z'],
+ ['last-millisecond', '2026-03-01T23:59:59.999000Z'],
+ ['last-microsecond', '2026-03-01T23:59:59.999999Z'],
+ ['next-day', '2026-03-02T00:00:00Z'],
+];
+
+export async function seedSearchQueryContract(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('query-dates', 'query-dates'), ('query-order', 'query-order')`);
+ for (const [name, timestamp] of dates) {
+ const slug = `notes/${name}`;
+ await engine.putPage(slug, { type: 'note', title: 'precisiontoken 東京', compiled_truth: 'precisiontoken 東京' }, { sourceId: 'query-dates' });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'precisiontoken 東京', embedding: vector }], { sourceId: 'query-dates' });
+ await engine.executeRaw(`UPDATE pages SET effective_date = $1::text::timestamptz WHERE source_id = 'query-dates' AND slug = $2`, [timestamp, slug]);
+ }
+ for (let i = 0; i < 40; i++) {
+ const slug = `notes/order-${String(i).padStart(2, '0')}`;
+ await engine.putPage(slug, { type: 'note', title: 'ordertoken 東京', compiled_truth: 'ordertoken 東京 앨범 example 기획' }, { sourceId: 'query-order' });
+ await installFixtureChunks(engine, slug, [0, 1].map(chunk_index => ({ chunk_index, chunk_source: 'compiled_truth', chunk_text: 'ordertoken 東京 앨범 example 기획' })), { sourceId: 'query-order' });
+ }
+ await engine.executeRaw(`UPDATE content_chunks SET chunk_text = chunk_text WHERE id % 2 = 0`);
+}
+
+export async function verifySearchDateBounds(engine: BrainEngine): Promise<void> {
+ const arms = [
+ (opts: SearchOpts) => engine.searchKeyword('precisiontoken', opts),
+ (opts: SearchOpts) => engine.searchKeywordChunks('precisiontoken', opts),
+ (opts: SearchOpts) => engine.searchKeyword('東京', opts),
+ (opts: SearchOpts) => engine.searchKeywordChunks('東京', opts),
+ (opts: SearchOpts) => engine.searchTitles('precisiontoken', opts),
+ (opts: SearchOpts) => engine.searchVector(vector, opts),
+ ];
+ for (const arm of arms) {
+ const find = async (bounds: SearchOpts) => (await arm({ limit: 100, sourceId: 'query-dates', ...bounds })).map(r => r.slug).sort();
+ expect(await find({ afterDate: '2026-03-01', afterDateInclusive: true, beforeDate: '2026-03-02' }))
+ .toEqual(dates.slice(0, -1).map(([name]) => `notes/${name}`).sort());
+ expect(await find({ afterDate: '2026-03-01T12:00:00.123456Z', afterDateInclusive: true, beforeDate: '2026-03-01T12:00:00.123456Z', beforeDateInclusive: true }))
+ .toEqual(['notes/precise']);
+ expect(await find({ afterDate: '2026-03-01T04:00:00.123456-08:00', afterDateInclusive: true, beforeDate: '2026-03-01T13:00:00.123456+01:00', beforeDateInclusive: true }))
+ .toEqual(['notes/precise']);
+ expect(await find({ afterDate: '2026-03-01T12:00:00.123456Z', beforeDate: '2026-03-01T12:00:00.123458Z' }))
+ .toEqual(['notes/after-precise']);
+ expect(await find({ afterDate: '2026-03-01T12:00:00.123454Z', beforeDate: '2026-03-01T12:00:00.123456Z' }))
+ .toEqual(['notes/before-precise']);
+ }
+}
+
+export async function verifyKeywordTieOrder(engine: BrainEngine): Promise<void> {
+ for (const query of ['ordertoken', '東京']) {
+ const opts = { limit: 10, sourceId: 'query-order' };
+ const expected = Array.from({ length: 10 }, (_, i) => `notes/order-${String(i).padStart(2, '0')}`);
+ for (let run = 0; run < 3; run++) {
+ const pages = await engine.searchKeyword(query, opts);
+ expect(pages.map(r => r.slug)).toEqual(expected);
+ const first = await engine.searchKeywordChunks(query, opts);
+ const next = await engine.searchKeywordChunks(query, { ...opts, offset: 10 });
+ const chunks = [...first, ...next];
+ expect(chunks.map(r => r.chunk_id)).toEqual([...chunks].sort((a, b) => a.page_id - b.page_id || a.chunk_id - b.chunk_id).map(r => r.chunk_id));
+ expect(new Set(chunks.map(r => r.chunk_id)).size).toBe(20);
+ expect(chunks.map(r => r.slug)).toEqual(expected.flatMap(slug => [slug, slug]));
+ }
+ }
+}
+
+export async function verifyMixedCjkCase(engine: BrainEngine): Promise<void> {
+ for (const search of [engine.searchKeyword.bind(engine), engine.searchKeywordChunks.bind(engine)]) {
+ const hits = await search('앨범 ExAmPlE 기획', { limit: 10, sourceId: 'query-order' });
+ expect(hits).toHaveLength(10);
+ expect(hits.every(hit => hit.chunk_text.includes('example'))).toBe(true);
+ expect(await search('앨범 MissingExample 기획', { sourceId: 'query-order' })).toEqual([]);
+ }
+}
diff --git a/test/helpers/vector-candidate-corpus.ts b/test/helpers/vector-candidate-corpus.ts
new file mode 100644
index 0000000000..1bcc73b4d2
--- /dev/null
+++ b/test/helpers/vector-candidate-corpus.ts
@@ -0,0 +1,53 @@
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { expect } from 'bun:test';
+import { refreshProjectionStatistics } from '../../src/core/search/projection-statistics.ts';
+
+export const candidateColumn = { name: 'embedding_candidate_fixture', type: 'vector' as const, dimensions: 8, embeddingModel: '' };
+export const candidateVector = new Float32Array([1, 0, 0.1, 0, 0, 0, 0, 0]);
+
+export async function seedVectorCandidateCorpus(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('ann-allowed', 'ann-allowed'), ('ann-other', 'ann-other')`);
+ await engine.executeRaw(`ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_candidate_fixture vector(8)`);
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, knowledge_revision, text_projection_revision, chunker_version)
+ SELECT 'notes/ann-' || i, CASE WHEN i % 10 = 1 THEN 'ann-allowed' ELSE 'ann-other' END,
+ 'note', 'Candidate ' || i, 'candidate fixture',
+ CASE WHEN i % 100 = 1 THEN '{"visibility":"private"}'::jsonb ELSE '{}'::jsonb END,
+ '00000000-0000-4000-8000-000000000001'::uuid,
+ CASE WHEN i % 20 = 0 THEN '00000000-0000-4000-8000-000000000002'::uuid ELSE '00000000-0000-4000-8000-000000000001'::uuid END, 4
+ FROM generate_series(1, 6000) i`);
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, language, symbol_type, embedding_candidate_fixture)
+ SELECT p.id, c, 'candidate ' || repeat(md5((p.id * 10 + c)::text), 32), 'compiled_truth', 'typescript', 'function',
+ ARRAY[cos((p.id * 10 + c) * 2.399963229728653)::real, sin((p.id * 10 + c) * 2.399963229728653)::real, 0.1, 0, 0, 0, 0, 0]::vector
+ FROM pages p CROSS JOIN generate_series(0, 9) c WHERE p.slug LIKE 'notes/ann-%'`);
+ await engine.transaction(async tx => {
+ if (engine.kind === 'postgres') await tx.executeRaw('SET LOCAL max_parallel_maintenance_workers = 0');
+ await tx.executeRaw(`CREATE INDEX IF NOT EXISTS idx_chunks_candidate_fixture ON content_chunks USING hnsw (embedding_candidate_fixture vector_cosine_ops)`);
+ });
+ await engine.executeRaw('ANALYZE content_chunks');
+ await engine.executeRaw('ANALYZE pages');
+ await engine.executeRaw('ANALYZE sources');
+ await refreshProjectionStatistics(engine);
+}
+
+export async function verifyVectorCapabilityRetry(engine: BrainEngine): Promise<void> {
+ const original = engine.executeRaw;
+ const capability = engine as unknown as { vectorIterativeScan?: Promise<boolean> };
+ capability.vectorIterativeScan = undefined;
+ let probes = 0;
+ engine.executeRaw = (async (sql, params) => {
+ if (sql.includes("extname = 'vector'")) {
+ probes++;
+ if (probes === 1) throw new Error('synthetic transient capability failure');
+ }
+ return original.call(engine, sql, params);
+ }) as typeof engine.executeRaw;
+ try {
+ await expect(engine.searchVector(candidateVector, { limit: 1, embeddingColumn: candidateColumn })).rejects.toThrow('synthetic transient capability failure');
+ expect(await engine.searchVector(candidateVector, { limit: 1, embeddingColumn: candidateColumn })).toHaveLength(1);
+ if (engine.kind === 'pglite') await engine.connect({});
+ expect(await engine.searchVector(candidateVector, { limit: 1, embeddingColumn: candidateColumn })).toHaveLength(1);
+ expect(probes).toBe(2);
+ } finally {
+ engine.executeRaw = original;
+ }
+}
diff --git a/test/hybrid-vector-incomplete.test.ts b/test/hybrid-vector-incomplete.test.ts
new file mode 100644
index 0000000000..99d0a4bc1d
--- /dev/null
+++ b/test/hybrid-vector-incomplete.test.ts
@@ -0,0 +1,39 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { hybridSearch } from '../src/core/search/hybrid.ts';
+import type { HybridSearchMeta } from '../src/core/types.ts';
+
+describe('hybrid search carries engine underfill into recall degradation', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig('search.reranker.enabled', 'false');
+ }, 60_000);
+
+ afterAll(async () => { await engine?.disconnect(); });
+
+ test('an incomplete zero-row engine result is not a clean miss', async () => {
+ const original = engine.searchVector;
+ engine.searchVector = async (_embedding, opts) => {
+ opts?.onVectorPoolMeta?.({
+ underfilled: true, incomplete: true, reason: 'candidate_budget',
+ escalations: 3, innerLimit: 1600, candidatePool: 0,
+ });
+ return [];
+ };
+ try {
+ let meta: HybridSearchMeta | undefined;
+ const rows = await hybridSearch(engine, 'synthetic missing candidate', {
+ expansion: false,
+ queryEmbedFn: () => Float32Array.from({ length: 1536 }, (_, i) => i === 0 ? 1 : 0),
+ onMeta: value => { meta = value; },
+ });
+ expect(rows).toEqual([]);
+ expect(meta?.degraded).toContainEqual({ stage: 'vector_candidates_incomplete', reason: 'candidate_budget' });
+ expect(meta?.vector_pool_underfilled).toMatchObject({ incomplete: true, candidatePool: 0, innerLimit: 1600 });
+ } finally { engine.searchVector = original; }
+ });
+});
diff --git a/test/mcp-backup-nag.serial.test.ts b/test/mcp-backup-nag.serial.test.ts
index 6b53ebca92..adef622290 100644
--- a/test/mcp-backup-nag.serial.test.ts
+++ b/test/mcp-backup-nag.serial.test.ts
@@ -35,6 +35,9 @@ mock.module('../src/core/search/hybrid.ts', () => ({
...realHybrid,
hybridSearchCached: async () => nextResults,
}));
+mock.module('../src/core/search/projection-readiness.ts', () => ({
+ probeProjectionReadiness: async () => ({ status: 'ready', ready: true }),
+}));
const { dispatchToolCall, __resetBackupNoticeForTests } = await import('../src/mcp/dispatch.ts');
const {
diff --git a/test/page-projection-code-recovery.test.ts b/test/page-projection-code-recovery.test.ts
new file mode 100644
index 0000000000..62e674288a
--- /dev/null
+++ b/test/page-projection-code-recovery.test.ts
@@ -0,0 +1,223 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importCodeFile } from '../src/core/import-file.ts';
+import { runReindexCode } from '../src/commands/reindex-code.ts';
+import { readProjectionSnapshot, preparePageProjection, installPageProjection, rebuildPendingPageProjections, queuePageProjection } from '../src/core/page-state/projections.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-code-recovery-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const sourceId = 'code-recovery-example';
+const body = 'export function beta() { return 3; }\nexport function alpha() { return beta(); }\n';
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false'); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });
+});
+
+async function unseal(engine: BrainEngine, slug: string) {
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ await queuePageProjection(engine, sourceId, slug, 'test_recovery');
+}
+async function seed(engine: BrainEngine, name: string) {
+ return (await importCodeFile(engine, `${name}.ts`, body, { sourceId, noEmbed: true })).slug;
+}
+
+test('code and Markdown jobs both recover keylessly without changing canonical identity or code metadata', async () => {
+ for (const engine of engines) {
+ const slug = await seed(engine, 'queued');
+ const before = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ const original = await engine.getChunks(slug, { sourceId });
+ await unseal(engine, slug);
+ await engine.putPage('queued-note', { type: 'note', title: 'Example note', compiled_truth: 'Example fenced function.\n```ts\nexport function fencedExample() { return 7; }\n```' }, { sourceId });
+ expect(await engine.getChunks(slug, { sourceId })).toEqual([]);
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBe(2);
+ const after = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect(after.revision).toBe(before.revision);
+ expect(after.page.id).toBe(before.page.id);
+ expect(after.page.content_hash).toBe(before.page.content_hash);
+ expect(after.page.compiled_truth).toBe(body);
+ expect(after.page.text_projection_revision).toBe(after.revision);
+ expect((await engine.getChunks(slug, { sourceId })).map(c => [c.id, c.symbol_name, c.parent_symbol_path])).toEqual(original.map(c => [c.id, c.symbol_name, c.parent_symbol_path]));
+ expect((await engine.getChunks('queued-note', { sourceId })).some(c => c.chunk_source === 'fenced_code' && c.symbol_name === 'fencedExample')).toBe(true);
+ expect(await engine.getChunks(slug, { sourceId: 'default' })).toEqual([]);
+ }
+});
+
+test('recovery keeps exact valid vectors and rejects model, hash, metadata and source provenance drift', async () => {
+ for (const engine of engines) {
+ for (const mismatch of ['none', 'model', 'hash', 'metadata', 'source']) {
+ const slug = await seed(engine, `vector-${mismatch}`);
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ const vector = `[${Array.from({ length: 1536 }, (_, i) => i === 0 ? 1 : 0).join(',')}]`;
+ await engine.executeRaw('UPDATE content_chunks SET embedding=$2::vector,model=$3,embedded_at=now(),embedded_text_hash=md5(chunk_text) WHERE page_id=$1',
+ [prepared.snapshot.page.id, vector, prepared.embeddingModel]);
+ if (mismatch === 'model') await engine.executeRaw("UPDATE content_chunks SET model='example:other' WHERE page_id=$1", [prepared.snapshot.page.id]);
+ if (mismatch === 'hash') await engine.executeRaw("UPDATE content_chunks SET embedded_text_hash='bad' WHERE page_id=$1", [prepared.snapshot.page.id]);
+ if (mismatch === 'metadata') await engine.executeRaw("UPDATE content_chunks SET language='python' WHERE page_id=$1", [prepared.snapshot.page.id]);
+ if (mismatch === 'source') await engine.executeRaw("UPDATE content_chunks SET chunk_source='timeline' WHERE page_id=$1", [prepared.snapshot.page.id]);
+ const old = await engine.getChunks(slug, { sourceId, includeEmbedding: true });
+ await unseal(engine, slug);
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBe(1);
+ const chunks = await engine.getChunks(slug, { sourceId, includeEmbedding: true });
+ expect(chunks.every(c => c.embedding_is_null)).toBe(mismatch !== 'none');
+ if (mismatch === 'none') expect(chunks.map(c => [c.id, c.embedding, c.embedded_at])).toEqual(old.map(c => [c.id, c.embedding, c.embedded_at]));
+ else expect((await engine.countStaleChunks({ sourceId }))).toBeGreaterThan(0);
+ }
+ }
+});
+
+test('unchanged code import heals an unsealed page without canonical mutation', async () => {
+ for (const engine of engines) {
+ const slug = await seed(engine, 'unchanged');
+ const before = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ await unseal(engine, slug);
+ expect(await importCodeFile(engine, 'unchanged.ts', body, { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });
+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.revision).toBe(before.revision);
+ }
+});
+
+test('a registry column retains only its own valid vectors and a column switch never copies legacy vectors', async () => {
+ for (const engine of engines) {
+ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN embedding_recovery vector(1536)');
+ const priorColumn = await engine.getConfig('search_embedding_column');
+ const priorRegistry = await engine.getConfig('embedding_columns');
+ try {
+ const slug = await seed(engine, 'column');
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ const vector = `[${Array.from({ length: 1536 }, (_, i) => i === 0 ? 1 : 0).join(',')}]`;
+ await engine.executeRaw('UPDATE content_chunks SET embedding=$2::vector,model=$3,embedded_at=now(),embedded_text_hash=md5(chunk_text) WHERE page_id=$1', [prepared.snapshot.page.id, vector, prepared.embeddingModel]);
+ await engine.setConfig('embedding_columns', JSON.stringify({ embedding_recovery: { provider: prepared.embeddingModel, dimensions: 1536, type: 'vector' } }));
+ await engine.setConfig('search_embedding_column', 'embedding_recovery');
+ await unseal(engine, slug);
+ await rebuildPendingPageProjections(engine, 100);
+ expect((await engine.getChunks(slug, { sourceId })).every(c => c.embedding_is_null)).toBe(true);
+ await engine.executeRaw('UPDATE content_chunks SET embedding_recovery=$2::vector,model=$3,embedded_at=now(),embedded_text_hash=md5(chunk_text) WHERE page_id=$1', [prepared.snapshot.page.id, vector, prepared.embeddingModel]);
+ const before = await engine.getChunks(slug, { sourceId, includeEmbedding: true });
+ await unseal(engine, slug);
+ await rebuildPendingPageProjections(engine, 100);
+ expect((await engine.getChunks(slug, { sourceId, includeEmbedding: true })).map(c => [c.id, c.embedding])).toEqual(before.map(c => [c.id, c.embedding]));
+ } finally {
+ if (priorColumn === null) await engine.unsetConfig('search_embedding_column'); else await engine.setConfig('search_embedding_column', priorColumn);
+ if (priorRegistry === null) await engine.unsetConfig('embedding_columns'); else await engine.setConfig('embedding_columns', priorRegistry);
+ await engine.executeRaw('ALTER TABLE content_chunks DROP COLUMN embedding_recovery');
+ }
+ }
+});
+
+test('a source recreation rejects an old prepared code projection', async () => {
+ for (const engine of engines) {
+ const isolated = 'recreated-code-example';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [isolated]);
+ const slug = (await importCodeFile(engine, 'recreated.ts', body, { sourceId: isolated, noEmbed: true })).slug;
+ const before = (await readProjectionSnapshot(engine, slug, isolated))!;
+ const projection = await preparePageProjection(before);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [isolated]);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [isolated]);
+ await importCodeFile(engine, 'recreated.ts', 'export const replacementExample = 2;', { sourceId: isolated, noEmbed: true });
+ await expect(installPageProjection(engine, before, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code })).rejects.toMatchObject({ code: 'revision_conflict' });
+ expect((await engine.getChunks(slug, { sourceId: isolated })).map(c => c.chunk_text).join('\n')).toContain('replacementExample');
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [isolated]);
+ }
+});
+
+test('a malformed code job stays diagnosable without starving later valid code jobs', async () => {
+ for (const engine of engines) {
+ const isolated = 'failed-code-example';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [isolated]);
+ try {
+ await engine.putPage('broken-ts', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: body }, { sourceId: isolated });
+ const slug = (await importCodeFile(engine, 'healthy.ts', body, { sourceId: isolated, noEmbed: true })).slug;
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1 AND slug=$2', [isolated, slug]);
+ await queuePageProjection(engine, isolated, slug, 'retry');
+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at=now()-interval '1 minute' WHERE slug='broken-ts'");
+ expect((await rebuildPendingPageProjections(engine, 1)).rebuilt).toBe(0);
+ expect((await rebuildPendingPageProjections(engine, 1)).rebuilt).toBe(1);
+ expect(await engine.executeRaw("SELECT reason FROM page_projection_jobs WHERE slug='broken-ts'")).toEqual([{ reason: 'rebuild_failed' }]);
+ expect((await engine.getChunks(slug, { sourceId: isolated })).length).toBeGreaterThan(0);
+ } finally { await engine.executeRaw('DELETE FROM sources WHERE id=$1', [isolated]); }
+ }
+});
+
+test('private code remains invisible remotely after keyless recovery', async () => {
+ for (const engine of engines) {
+ const slug = await seed(engine, 'private');
+ const page = (await engine.getPage(slug, { sourceId }))!;
+ await engine.putPage(slug, { ...page, page_kind: 'code', frontmatter: { ...page.frontmatter, visibility: 'private' } }, { sourceId });
+ await rebuildPendingPageProjections(engine, 100);
+ expect((await engine.getChunks(slug, { sourceId })).length).toBeGreaterThan(0);
+ expect(await engine.getChunks(slug, { sourceId, excludePrivate: true })).toEqual([]);
+ expect((await engine.searchKeyword('alpha', { sourceId, excludePrivate: true })).some(row => row.slug === slug)).toBe(false);
+ }
+});
+
+test('a newer code revision wins a delayed rebuild and interrupted projection work retries atomically', async () => {
+ for (const engine of engines) {
+ const slug = await seed(engine, 'interrupted'); await unseal(engine, slug);
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true }))!;
+ const code = await preparePageProjection(prepared);
+ await engine.putPage(slug, { type: 'code', page_kind: 'code', title: 'Changed', compiled_truth: 'export const newerExample = 9;', frontmatter: { file: 'interrupted.ts' } }, { sourceId });
+ await expect(installPageProjection(engine, prepared, code.chunks, { seal: true, preserveEmbeddings: true, code: code.code })).rejects.toMatchObject({ code: 'revision_conflict' });
+ const transaction = engine.transaction.bind(engine);
+ let interrupted = false;
+ const broken = new Proxy(engine, { get(target, key) {
+ if (key === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>) => transaction(tx => run(new Proxy(tx, { get(inner, prop) {
+ if (prop === 'upsertChunks') return async () => { interrupted = true; throw new Error('simulated interruption'); };
+ const value = Reflect.get(inner, prop, inner); return typeof value === 'function' ? value.bind(inner) : value;
+ } })));
+ const value = Reflect.get(target, key, target); return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ expect((await rebuildPendingPageProjections(broken, 100)).rebuilt).toBe(0);
+ expect(interrupted).toBe(true);
+ expect(await engine.getChunks(slug, { sourceId })).toEqual([]);
+ expect(await engine.executeRaw('SELECT reason FROM page_projection_jobs WHERE slug=$1', [slug])).toEqual([{ reason: 'rebuild_failed' }]);
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBe(1);
+ expect((await engine.getChunks(slug, { sourceId })).map(c => c.chunk_text).join('\n')).toContain('newerExample');
+ }
+});
+
+test('managed reindex uses a durable guarded receipt without canonical writes or paid effects', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const slug = await seed(engine, 'managed');
+ const before = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true');
+ try {
+ await expect(importCodeFile(engine, 'managed.ts', body, { sourceId, noEmbed: true, force: true })).rejects.toMatchObject({ code: 'writer_coordinator_required' });
+ const result = await runReindexCode(engine, { sourceId, noEmbed: true, force: true });
+ expect(result.failed).toBe(0);
+ expect(result.reindexed).toBeGreaterThan(0);
+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.revision).toBe(before.revision);
+ const requests = await engine.executeRaw<{ state: string; revision: string }>('SELECT state,outcome->>\'revision\' AS revision FROM persistence_requests WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ expect(requests).toEqual([{ state: 'committed', revision: before.revision }]);
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE source_id=$1', [sourceId])).toEqual([]);
+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.softDeletePage(slug, { sourceId })));
+ expect((await runReindexCode(engine, { sourceId, noEmbed: true, force: true })).failed).toBe(0);
+ expect(await engine.getPage(slug, { sourceId })).toBeNull();
+ } finally { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false'); }
+ }
+}), 120_000);
+
+test('archived sources stay unsealed and are excluded from reindex', async () => {
+ for (const engine of engines) {
+ const slug = await seed(engine, 'archived'); await unseal(engine, slug);
+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ try {
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBe(0);
+ expect((await runReindexCode(engine, { sourceId, noEmbed: true, force: true })).codePages).toBe(0);
+ expect(await engine.getChunks(slug, { sourceId })).toEqual([]);
+ } finally { await engine.executeRaw('UPDATE sources SET archived=false WHERE id=$1', [sourceId]); }
+ }
+});
diff --git a/test/page-projection-origin.test.ts b/test/page-projection-origin.test.ts
index 6a70f30e47..c9af7758a2 100644
--- a/test/page-projection-origin.test.ts
+++ b/test/page-projection-origin.test.ts
@@ -7,6 +7,7 @@ import { installPageEmbeddings, installPageProjection, PageProjectionConflictErr
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { installFixtureChunks } from './helpers/page-projection.ts';
import { withEnv } from './helpers/with-env.ts';
+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
const engines: BrainEngine[] = [];
let closePostgres: (() => Promise<void>) | undefined;
@@ -251,3 +252,126 @@ test('a listed rebuild that another worker completed does not replace its projec
expect(await engine.getChunks(slug, { sourceId, includeEmbedding: true })).toEqual(current);
}
});
+
+test('queued Markdown rebuild retains ordered fenced code metadata and canonical source state', async () => {
+ const slug = 'guides/complete-projection';
+ const neighbor = `${sourceId}-neighbor`;
+ const clientId = 'projection-origin-reader';
+ const code = 'function increment(value: number): number {\n return value + 1;\n}';
+ for (const engine of engines) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$1)', [neighbor]);
+ try {
+ await engine.putPage(slug, { type: 'note', title: 'Example code guide',
+ compiled_truth: `Public guide.\n\n\`\`\`ts\n${code}\n\`\`\``,
+ timeline: '2026-01-01: Example timeline event.',
+ frontmatter: { custom: 'retained' }, source_path: 'guides/complete-projection.md',
+ }, { sourceId });
+ await engine.addTag(slug, 'enriched-tag', { sourceId });
+ await engine.createVersion(slug, { sourceId });
+ await engine.executeRaw(`UPDATE pages SET contextual_retrieval_mode='title',corpus_generation='fixture-generation'
+ WHERE source_id=$1 AND slug=$2`, [sourceId, slug]);
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,scope,source_id,federated_read)
+ VALUES ($1,'Example reader','read',$2,ARRAY[$2]::text[])`, [clientId, sourceId]);
+ await engine.putPage(slug, { type: 'note', title: 'Other source', compiled_truth: 'neighbor-only-sentinel' }, { sourceId: neighbor });
+ await installFixtureChunks(engine, slug, [chunk('neighbor-only-sentinel')], { sourceId: neighbor });
+ const neighborBefore = await engine.readPageSnapshot(slug, { sourceId: neighbor });
+ const neighborChunks = await engine.getChunks(slug, { sourceId: neighbor });
+ // Compare persisted rows, including source identity, dates, CR policy,
+ // history, tags and grant policy. Only derived projection fields may change.
+ const canonical = () => engine.executeRaw(`SELECT to_jsonb(p)-'text_projection_revision'-'search_vector'-'chunker_version' AS page
+ FROM pages p WHERE source_id=$1 AND slug=$2`, [sourceId, slug]);
+ const history = () => engine.executeRaw(`SELECT v.* FROM page_versions v JOIN pages p ON p.id=v.page_id
+ WHERE p.source_id=$1 AND p.slug=$2 ORDER BY v.id`, [sourceId, slug]);
+ const grants = () => engine.executeRaw('SELECT * FROM oauth_clients WHERE client_id=$1', [clientId]);
+ const before = await canonical(), versions = await history(), grant = await grants();
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBeGreaterThan(0);
+ const chunks = await engine.getChunks(slug, { sourceId, includeEmbedding: true });
+ expect(chunks.map(c => c.chunk_index)).toEqual([0, 1, 2]);
+ expect(chunks.map(c => c.chunk_source)).toEqual(['compiled_truth', 'timeline', 'fenced_code']);
+ expect(chunks[0].chunk_text).toContain(code);
+ expect(chunks[1].chunk_text).toBe('2026-01-01: Example timeline event.');
+ expect(chunks[2]).toMatchObject({ language: 'typescript', symbol_name: 'increment', start_line: 1, end_line: 3, modality: 'text' });
+ expect(chunks[2].symbol_type).toMatch(/function/);
+ expect(chunks[2].chunk_text).toContain(code);
+ expect(chunks[2].chunk_text).toContain('fence.ts:1-3');
+ expect(chunks.every(c => c.embedding === null && c.embedded_at === null)).toBe(true);
+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.page.text_projection_revision).toBe(snapshot.revision);
+ expect(await canonical()).toEqual(before);
+ expect(await history()).toEqual(versions);
+ expect(await grants()).toEqual(grant);
+ expect(await engine.getTags(slug, { sourceId })).toEqual(['enriched-tag']);
+ expect(await engine.readPageSnapshot(slug, { sourceId: neighbor })).toEqual(neighborBefore);
+ expect(await engine.getChunks(slug, { sourceId: neighbor })).toEqual(neighborChunks);
+ expect(await engine.executeRaw(`SELECT j.slug FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation
+ WHERE s.id=$1 AND j.slug=$2`, [sourceId, slug])).toEqual([]);
+ } finally {
+ await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [neighbor]);
+ }
+ }
+});
+
+test('queued Markdown rebuild honors embed-skip and quarantine without retaining stale chunks', async () => {
+ for (const engine of engines) {
+ for (const marker of ['embed_skip', 'quarantine']) {
+ const slug = `disposition-${marker}`;
+ await engine.putPage(slug, { type: 'note', title: 'Example blocked projection',
+ compiled_truth: 'Prose.\n\n```python\ndef visible():\n return 1\n```', timeline: 'Timeline text.',
+ frontmatter: { [marker]: { reason: 'fixture' } },
+ }, { sourceId });
+ await engine.upsertChunks(slug, [chunk('stale-projection-sentinel')], { sourceId });
+ const before = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBeGreaterThan(0);
+ expect(await engine.getChunks(slug, { sourceId, includeUnsealed: true })).toEqual([]);
+ const after = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect(after.revision).toBe(before.revision);
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.timeline).toBe(before.page.timeline);
+ expect(after.page.frontmatter).toEqual(before.page.frontmatter);
+ expect(after.page.text_projection_revision).toBe(before.revision);
+ expect(await engine.executeRaw(`SELECT j.slug FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation
+ WHERE s.id=$1 AND j.slug=$2`, [sourceId, slug])).toEqual([]);
+ }
+ }
+});
+
+test('queued Markdown rebuild sanitizes protected code and applies fact withdrawals before chunking', async () => {
+ const slug = 'protected-projection';
+ const claim = 'withdrawal-projection-sentinel';
+ const facts = `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|---|---|---|---|---|---|---|---|---|
+| 1 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | fixture | |
+| 2 | private-projection-sentinel | fact | 1.0 | private | medium | 2026-01-01 | | fixture | |
+<!--- gbrain:facts:end -->`;
+ for (const engine of engines) {
+ await engine.putPage(slug, { type: 'note', title: 'Example protected guide',
+ compiled_truth: `Safe prose.\n\n\`\`\`python\ndef public_example():\n return 1\n\`\`\`\n\n${facts}\n
+<!--- gbrain:takes:begin -->
+\`\`\`python
+def protected_example():
+ return 'protected-code-sentinel'
+\`\`\`
+<!--- gbrain:takes:end -->`, timeline: facts,
+ }, { sourceId });
+ const fact = await engine.insertFact({ fact: claim, source: 'fixture', visibility: 'world' }, { source_id: sourceId });
+ expect((await recordFactWithdrawal(engine, fact.id, sourceId, true)).withdrawn).toBe(true);
+ const before = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect(before.page.compiled_truth).toContain(`~~${claim}~~`);
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBeGreaterThan(0);
+ const chunks = await engine.getChunks(slug, { sourceId });
+ const text = chunks.map(c => c.chunk_text).join('\n');
+ expect(text).toContain('Safe prose.');
+ expect(text).not.toContain(claim);
+ expect(text).not.toContain('private-projection-sentinel');
+ expect(text).not.toContain('protected-code-sentinel');
+ expect(text).not.toContain('protected_example');
+ expect(chunks.filter(c => c.chunk_source === 'fenced_code').map(c => c.symbol_name)).toEqual(['public_example']);
+ const after = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect(after.revision).toBe(before.revision);
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.timeline).toBe(before.page.timeline);
+ expect(after.withdrawals).toEqual(before.withdrawals);
+ }
+});
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index 9e35ecf0e8..a8f943bae0 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -180,8 +180,10 @@ test('subpath exclusions and unsupported code/pull paths refuse before canonical
expect(await engine.getPage('a',{sourceId:f.id})).not.toBeNull(); expect(await engine.getPage('private/b',{sourceId:f.id})).toBeNull();
await expect(performManagedSync(engine,{sourceId:f.id})).rejects.toMatchObject({code:'writer_coordinator_required'});
const c=await fixture(engine,{'a.md':'Normal page source observation.\n','code.ts':'export const example = 1;\n'});
- await expect(performManagedSync(engine,{sourceId:c.id,noPull:true,strategy:'auto'})).rejects.toMatchObject({code:'writer_coordinator_required'});
- expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1',[c.id])).toHaveLength(0);
+ expect(await performManagedSync(engine,{sourceId:c.id,noPull:true,strategy:'auto',noEmbed:true})).toMatchObject({added:2});
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1',[c.id])).toHaveLength(2);
+ expect(await engine.executeRaw("SELECT page_kind FROM pages WHERE source_id=$1 AND slug='code-ts'",[c.id])).toEqual([{page_kind:'code'}]);
+ expect((await engine.getChunks('code-ts',{sourceId:c.id})).some(chunk=>chunk.symbol_name==='example')).toBe(true);
}
}),120_000);
diff --git a/test/persistence-sync-stdio-owner.serial.test.ts b/test/persistence-sync-stdio-owner.serial.test.ts
index 1f5d461d37..4bb160faeb 100644
--- a/test/persistence-sync-stdio-owner.serial.test.ts
+++ b/test/persistence-sync-stdio-owner.serial.test.ts
@@ -10,6 +10,8 @@ import { inspectLockHolder } from '../src/core/pglite-lock.ts';
import { persistenceSocketPathForConfig, requestPersistenceCapabilities, requestPersistenceAdministration } from '../src/core/persistence/ipc.ts';
import { readPersistenceCliRegistration } from '../src/core/persistence/local-client.ts';
import { parsePersistenceSyncArgs } from '../src/commands/sync-persistence-delegate.ts';
+import { importCodeFile } from '../src/core/import-file.ts';
+import { parseReindexCodeDelegateArgs } from '../src/commands/reindex-code-delegate.ts';
import { withEnv } from './helpers/with-env.ts';
const home=mkdtempSync(join(tmpdir(),'gbrain-stdio-sync-'));
@@ -46,7 +48,11 @@ beforeAll(async()=>{
setup=new PGLiteEngine();
await withEnv(env,async()=>{
await setup.connect(config);await setup.initSchema();
+ await setup.setConfig('search.mcp_keyword_only','true');
await setup.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES('workspace','workspace',$1,'{}')",[root]);
+ const code = 'export function residentExample() { return 4; }\n';
+ writeFileSync(join(root,'example.ts'),code);
+ await importCodeFile(setup,'example.ts',code,{sourceId:'workspace',noEmbed:true});
await claimWorktree(setup,'workspace',root);await registerLocalWriter(setup,'cli');await registerLocalWriter(setup,'stdio');
await setup.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');await setup.disconnect();
});
@@ -83,6 +89,36 @@ test('strict sync parsing retains filtering options and rejects runtime authorit
});
});
+test('actual code recovery CLI delegates to the resident owner without a legacy writer or paid provider',async()=>{
+ const before=await cli(['call','get_page',JSON.stringify({slug:'example-ts',source_id:'workspace'})]);
+ const current=JSON.parse(before.out);
+ for(const args of [['reindex-code','--force'],['reindex-code','--force']]) {
+ const result=await cli([...args,'--source','workspace','--no-embed','--json']);
+ expect({code:result.code,err:result.err}).toMatchObject({code:0});
+ expect(JSON.parse(result.out)).toMatchObject({reindexed:1,failed:0});
+ expect(result.err).not.toContain('writer_coordinator_required');
+ }
+ const after=await cli(['call','get_page',JSON.stringify({slug:'example-ts',source_id:'workspace'})]);
+ expect(JSON.parse(after.out).revision).toBe(current.revision);
+ expect(JSON.parse(after.out).compiled_truth).toBe(current.compiled_truth);
+ (owner!.stdin as {write:(value:string)=>unknown}).write(JSON.stringify({jsonrpc:'2.0',id:2,method:'tools/call',params:{name:'search',arguments:{query:'residentExample',source_id:'workspace'}}})+'\n');
+ await until(()=>stdout.split('\n').some(line=>{try{return JSON.parse(line).id===2;}catch{return false;}}));
+ const search=stdout.split('\n').map(line=>{try{return JSON.parse(line);}catch{return null;}}).find(value=>value?.id===2);
+ expect(search.result.isError).not.toBe(true);
+ expect(JSON.stringify(search.result)).toContain('residentExample');
+ expect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);
+ expect(parseReindexCodeDelegateArgs(['--force','--no-embed','--source','workspace'])).toEqual({force:true,noEmbed:true,sourceId:'workspace'});
+ expect(()=>parseReindexCodeDelegateArgs(['--remote','false'])).toThrow();
+},90000);
+
+test('remote stdio credentials cannot request trusted code reindex',async()=>{
+ const socket=persistenceSocketPathForConfig(config)!,cap=await requestPersistenceCapabilities(socket);
+ const registration=JSON.parse(readFileSync(join(home,'.gbrain','persistence',`${cap.brain_id}.stdio.json`),'utf8'));
+ await expect(requestPersistenceAdministration(socket,{version:1,kind:'administration',brain_id:cap.brain_id,
+ operation:'writer_reindex_code',params:{options:{sourceId:'workspace',force:true,noEmbed:true}},registration:{...registration,lane:'cli'}}))
+ .rejects.toMatchObject({code:'permission_denied'});
+});
+
test('the remote stdio credential cannot enter the trusted CLI sync lane',async()=>{
const socket=persistenceSocketPathForConfig(config)!,cap=await requestPersistenceCapabilities(socket);
const registration=JSON.parse(readFileSync(join(home,'.gbrain','persistence',`${cap.brain_id}.stdio.json`),'utf8'));
@@ -109,3 +145,10 @@ test('a revoked CLI cannot fall through to a competing database open',async()=>{
expect(denied.code).toBe(1);expect(denied.err).toContain('permission_denied');expect(denied.err).not.toContain('LockTimeout');
expect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);
},60000);
+
+test('the recovered code remains searchable from the CLI after resident shutdown',async()=>{
+ owner!.kill('SIGTERM');await owner!.exited;
+ const result=await cli(['search','residentExample','--source','workspace','--json']);
+ expect({code:result.code,err:result.err}).toMatchObject({code:0});
+ expect(result.out).toContain('example-ts');
+},60000);
diff --git a/test/postgres-engine.test.ts b/test/postgres-engine.test.ts
index 60b6a9b6b2..986077b9eb 100644
--- a/test/postgres-engine.test.ts
+++ b/test/postgres-engine.test.ts
@@ -83,7 +83,8 @@ describe('postgres-engine / search path timeout isolation', () => {
const keyword = extractMethod(SRC, 'searchKeyword');
const vector = extractMethod(SRC, 'searchVector');
expect(keyword).toMatch(/SET\s+LOCAL\s+statement_timeout/);
- expect(vector).toMatch(/SET\s+LOCAL\s+statement_timeout/);
+ expect(vector).toMatch(/set_config\('statement_timeout', \$\{String\(remainingVectorBudget\(deadline\)\)\}, true\)/);
+ expect(vector).toContain('withVectorSettings');
});
test('connect() with poolSize honors resolvePrepare (PgBouncer regression guard)', () => {
diff --git a/test/projection-readiness.test.ts b/test/projection-readiness.test.ts
new file mode 100644
index 0000000000..75115beaa9
--- /dev/null
+++ b/test/projection-readiness.test.ts
@@ -0,0 +1,136 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { probeProjectionReadiness } from '../src/core/search/projection-readiness.ts';
+import { checkProjectionReadiness } from '../src/commands/doctor/checks/projection-readiness.ts';
+import { resetPgliteState } from './helpers/reset-pglite.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);
+ for (const source of ['source-a', 'source-b']) {
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [source]);
+ }
+});
+
+async function seed(kind = 'markdown', source = 'source-a', slug = 'example', frontmatter = {}) {
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id,slug,title,type,page_kind,compiled_truth,chunker_version,frontmatter)
+ VALUES ($1,$2,'Example','concept',$3,'canonical body',999,$4::text::jsonb)`,
+ [source, slug, kind, JSON.stringify(frontmatter)],
+ );
+}
+
+describe('canonical projection readiness', () => {
+ test('empty scope is ready and an explicit empty grant never widens', async () => {
+ expect((await probeProjectionReadiness(engine)).status).toBe('ready');
+ await seed();
+ expect((await probeProjectionReadiness(engine, { sourceIds: [] })).status).toBe('ready');
+ });
+
+ for (const kind of ['markdown', 'code']) {
+ for (const revision of ['null', 'mismatched']) {
+ test(`${kind} ${revision} seal is pending even at a newer chunker version`, async () => {
+ await seed(kind);
+ if (revision === 'mismatched') {
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid()');
+ }
+ const result = await probeProjectionReadiness(engine, { sourceId: 'source-a' });
+ expect(result.status).toBe('projection_pending');
+ expect(result.ready).toBe(false);
+ expect(result.hint).toContain('incomplete');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
+ expect((await probeProjectionReadiness(engine, { sourceId: 'source-a' })).status).toBe('ready');
+ });
+ }
+ }
+
+ test('current rows do not mask pending rows and canonical rows do not need old chunks or queue entries', async () => {
+ await seed('markdown', 'source-a', 'current');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
+ await seed('code', 'source-a', 'pending');
+ await engine.executeRaw('DELETE FROM page_projection_jobs');
+ expect((await probeProjectionReadiness(engine, { sourceId: 'source-a' })).status).toBe('projection_pending');
+ expect((await probeProjectionReadiness(engine, { sourceId: 'source-a', pageKind: 'markdown' })).status).toBe('ready');
+ });
+
+ test('federated grants take precedence over scalar scope and duplicated slugs stay isolated', async () => {
+ await seed('code', 'source-a');
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision');
+ await seed('code', 'source-b');
+ expect((await probeProjectionReadiness(engine, { sourceId: 'source-b', sourceIds: ['source-a'] })).status).toBe('ready');
+ expect((await probeProjectionReadiness(engine, { sourceIds: ['source-a', 'source-b'] })).status).toBe('projection_pending');
+ });
+
+ for (const hidden of ['private', 'quarantine', 'deleted', 'archived']) {
+ test(`hidden-only ${hidden} pending rows reveal no readiness signal`, async () => {
+ await seed('markdown', 'source-b', 'hidden-example', hidden === 'private'
+ ? { visibility: 'private' } : hidden === 'quarantine' ? { quarantine: true } : {});
+ if (hidden === 'deleted') await engine.executeRaw('UPDATE pages SET deleted_at=NOW()');
+ if (hidden === 'archived') await engine.executeRaw("UPDATE sources SET archived=true WHERE id='source-b'");
+ const result = await probeProjectionReadiness(engine, { sourceIds: ['source-a', 'source-b'], excludePrivate: true });
+ expect(result).toEqual({ status: 'ready', ready: true });
+ expect(JSON.stringify(result)).not.toContain('hidden-example');
+ expect(JSON.stringify(result)).not.toContain('source-b');
+ if (hidden === 'private') {
+ expect((await probeProjectionReadiness(engine, { excludePrivate: false })).status).toBe('projection_pending');
+ }
+ });
+ }
+
+ test('search type and excluded-prefix filters constrain the probe', async () => {
+ await seed('markdown', 'source-a', 'excluded_%/example');
+ expect((await probeProjectionReadiness(engine, { types: ['person'] })).status).toBe('ready');
+ expect((await probeProjectionReadiness(engine, { excludeSlugPrefixes: ['excluded_%/'] })).status).toBe('ready');
+ expect((await probeProjectionReadiness(engine, { excludeSlugPrefixes: ['excludedZZ/'] })).status).toBe('projection_pending');
+ });
+
+ test('probe errors and malformed results are unknown, without exposing error text', async () => {
+ for (const executeRaw of [async () => { throw new Error('hidden-source database error'); }, async () => []]) {
+ const result = await probeProjectionReadiness({ executeRaw } as any);
+ expect(result.status).toBe('unknown');
+ expect(result.ready).toBe(false);
+ expect(JSON.stringify(result)).not.toContain('hidden-source');
+ }
+ });
+
+ test('diagnostics issue one bound EXISTS and never mutate or repair', async () => {
+ const calls: { sql: string; params: unknown[] }[] = [];
+ const result = await probeProjectionReadiness({
+ executeRaw: async (sql: string, params: unknown[]) => {
+ calls.push({ sql, params });
+ return [{ pending: true }];
+ },
+ } as any, { sourceId: "source-'quote", excludePrivate: true });
+ expect(result.status).toBe('projection_pending');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].sql).toContain('SELECT EXISTS');
+ expect(calls[0].sql).toContain('IS DISTINCT FROM');
+ expect(calls[0].sql).not.toMatch(/COUNT\(|UPDATE |INSERT |DELETE /);
+ expect(calls[0].sql).not.toContain("source-'quote");
+ expect(calls[0].params).toEqual(["source-'quote"]);
+ });
+
+ test('doctor distinguishes ready, pending and unknown without returning identifiers', async () => {
+ expect((await checkProjectionReadiness(engine)).status).toBe('ok');
+ await seed('code');
+ const pending = await checkProjectionReadiness(engine, { sourceId: 'source-a' });
+ expect(pending.status).toBe('warn');
+ expect(pending.details).toEqual({ readiness: 'projection_pending', ready: false });
+ expect(JSON.stringify(pending)).not.toContain('source-a');
+ const unknown = await checkProjectionReadiness({ executeRaw: async () => { throw new Error('private connection'); } } as any);
+ expect(unknown.status).toBe('warn');
+ expect(unknown.details).toEqual({ readiness: 'unknown', ready: false });
+ expect(JSON.stringify(unknown)).not.toContain('private connection');
+ });
+});
diff --git a/test/projection-statistics-import.test.ts b/test/projection-statistics-import.test.ts
new file mode 100644
index 0000000000..4c9389219c
--- /dev/null
+++ b/test/projection-statistics-import.test.ts
@@ -0,0 +1,36 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runImport } from '../src/commands/import.ts';
+import { currentTextProjectionFilter } from '../src/core/search/safe-chunks.ts';
+
+describe('bulk import collects planner statistics after empty initialization', () => {
+ let engine: PGLiteEngine;
+ let directory: string;
+
+ beforeAll(async () => {
+ directory = mkdtempSync(join(tmpdir(), 'gbrain-planner-import-'));
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (let i = 0; i < 12; i++) {
+ writeFileSync(join(directory, `example-${i}.md`), `---\ntitle: Synthetic example ${i}\ntype: note\n---\nSynthetic source observation ${i}.\n`);
+ }
+ }, 60_000);
+
+ afterAll(async () => {
+ await engine?.disconnect();
+ if (directory) rmSync(directory, { recursive: true, force: true });
+ });
+
+ test('the real import completion refreshes expression samples', async () => {
+ const imported = await runImport(engine, [directory, '--no-embed', '--json']);
+ expect(imported.imported).toBe(12);
+ const rows = await engine.executeRaw<{ 'QUERY PLAN': Array<{ Plan: { 'Plan Rows': number } }> }>(
+ `EXPLAIN (FORMAT JSON) SELECT * FROM pages p WHERE ${currentTextProjectionFilter('p')}`,
+ );
+ expect(rows[0]['QUERY PLAN'][0].Plan['Plan Rows']).toBe(12);
+ }, 60_000);
+});
diff --git a/test/projection-statistics.test.ts b/test/projection-statistics.test.ts
new file mode 100644
index 0000000000..0ca7465afd
--- /dev/null
+++ b/test/projection-statistics.test.ts
@@ -0,0 +1,135 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGlite } from '@electric-sql/pglite';
+import { currentTextProjectionFilter } from '../src/core/search/safe-chunks.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PROJECTION_STATISTICS_SQL, refreshProjectionStatistics, verifyProjectionStatistics } from '../src/core/search/projection-statistics.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { LATEST_VERSION, runMigrations } from '../src/core/migrate.ts';
+
+function fixtureEngine(db: Pick<PGlite, 'query'> & Partial<Pick<PGlite, 'transaction'>>): BrainEngine {
+ return {
+ kind: 'pglite',
+ executeRaw: async (sql: string, params?: unknown[]) => (await db.query(sql, params)).rows,
+ transaction: async (fn: (tx: BrainEngine) => Promise<unknown>) => db.transaction
+ ? db.transaction(tx => fn(fixtureEngine(tx)))
+ : fn(fixtureEngine(db)),
+ } as unknown as BrainEngine;
+}
+
+describe('current projection planner estimates', () => {
+ let db: PGlite;
+
+ beforeAll(async () => {
+ db = new PGlite();
+ await db.exec(`CREATE TABLE pages (
+ id integer PRIMARY KEY,
+ text_projection_revision uuid,
+ knowledge_revision uuid
+ );
+ INSERT INTO pages
+ SELECT i, '00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000001'
+ FROM generate_series(1, 10000) i;
+ CREATE STATISTICS pages_text_projection_current_stats
+ ON ((text_projection_revision = knowledge_revision)) FROM pages;
+ ANALYZE pages(text_projection_revision, knowledge_revision);`);
+ }, 30_000);
+
+ afterAll(async () => { await db?.close(); });
+
+ test('the shared read predicate uses the measured current-page population', async () => {
+ const result = await db.query<{ 'QUERY PLAN': Array<{ Plan: { 'Plan Rows': number } }> }>(
+ `EXPLAIN (FORMAT JSON) SELECT * FROM pages p WHERE ${currentTextProjectionFilter('p')}`,
+ );
+ expect(result.rows[0]['QUERY PLAN'][0].Plan['Plan Rows']).toBe(10000);
+ });
+
+ test('NULL and stale revisions remain excluded', async () => {
+ const result = await db.query<{ id: number }>(`SELECT id FROM (VALUES
+ (1, '00000000-0000-0000-0000-000000000001'::uuid, '00000000-0000-0000-0000-000000000001'::uuid),
+ (2, '00000000-0000-0000-0000-000000000001'::uuid, '00000000-0000-0000-0000-000000000002'::uuid),
+ (3, NULL::uuid, '00000000-0000-0000-0000-000000000001'::uuid),
+ (4, '00000000-0000-0000-0000-000000000001'::uuid, NULL::uuid),
+ (5, NULL::uuid, NULL::uuid)
+ ) p(id, text_projection_revision, knowledge_revision)
+ WHERE ${currentTextProjectionFilter('p')}`);
+ expect(result.rows.map(row => row.id)).toEqual([1]);
+ });
+
+ test('statistics follow large readiness changes instead of a fixed selectivity guess', async () => {
+ const engine = fixtureEngine(db);
+ for (const count of [1000, 100, 20, 0, 10000]) {
+ await db.query(`UPDATE pages SET text_projection_revision =
+ CASE WHEN id <= $1 THEN knowledge_revision ELSE NULL END`, [count]);
+ expect(await refreshProjectionStatistics(engine)).toBe(true);
+ const result = await db.query<{ 'QUERY PLAN': Array<{ Plan: { 'Plan Rows': number } }> }>(
+ `EXPLAIN (FORMAT JSON) SELECT * FROM pages p WHERE ${currentTextProjectionFilter('p')}`,
+ );
+ expect(result.rows[0]['QUERY PLAN'][0].Plan['Plan Rows']).toBe(Math.max(count, 1));
+ }
+ });
+});
+
+describe('projection statistics migration postconditions', () => {
+ test('empty initialization and later population both collect valid statistics', async () => {
+ const db = new PGlite();
+ try {
+ const engine = fixtureEngine(db);
+ await db.exec('CREATE TABLE pages(text_projection_revision uuid, knowledge_revision uuid)');
+ await db.exec(PROJECTION_STATISTICS_SQL);
+ await verifyProjectionStatistics(engine);
+ await db.exec(PROJECTION_STATISTICS_SQL);
+ await verifyProjectionStatistics(engine);
+ await db.exec(`INSERT INTO pages SELECT NULL, '00000000-0000-0000-0000-000000000001'::uuid
+ FROM generate_series(1, 1000)`);
+ expect(await refreshProjectionStatistics(engine)).toBe(true);
+ await verifyProjectionStatistics(engine);
+ } finally { await db.close(); }
+ }, 30_000);
+
+ test('an object with the expected name but wrong expression is not certified', async () => {
+ const db = new PGlite();
+ try {
+ await db.exec(`CREATE TABLE pages(text_projection_revision uuid, knowledge_revision uuid);
+ CREATE STATISTICS pages_text_projection_current_stats ON ((knowledge_revision IS NULL)) FROM pages;
+ ANALYZE pages;`);
+ await expect(verifyProjectionStatistics(fixtureEngine(db))).rejects.toThrow('wrong definition');
+ } finally { await db.close(); }
+ }, 30_000);
+
+ test('missing expression samples on a populated table are not certified', async () => {
+ const db = new PGlite();
+ try {
+ await db.exec(`CREATE TABLE pages(text_projection_revision uuid, knowledge_revision uuid);
+ INSERT INTO pages VALUES (NULL, '00000000-0000-0000-0000-000000000001');
+ ANALYZE pages;
+ CREATE STATISTICS pages_text_projection_current_stats
+ ON ((text_projection_revision = knowledge_revision)) FROM pages;`);
+ await expect(verifyProjectionStatistics(fixtureEngine(db))).rejects.toThrow('not been collected');
+ } finally { await db.close(); }
+ }, 30_000);
+
+});
+
+describe('projection migration ledger verification', () => {
+ let engine: PGLiteEngine;
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+
+ afterAll(async () => { await engine?.disconnect(); });
+
+ test('a failed final postcondition never advances the schema version', async () => {
+ await engine.executeRaw('DROP STATISTICS pages_text_projection_current_stats');
+ await engine.executeRaw('CREATE STATISTICS pages_text_projection_current_stats ON ((knowledge_revision IS NULL)) FROM pages');
+ await engine.setConfig('version', '159');
+ await expect(runMigrations(engine)).rejects.toThrow('wrong definition');
+ expect(await engine.getConfig('version')).toBe('159');
+ await engine.executeRaw('DROP STATISTICS pages_text_projection_current_stats');
+ await runMigrations(engine);
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+ await verifyProjectionStatistics(engine);
+ }, 60_000);
+});
diff --git a/test/query-image-date-readiness.serial.test.ts b/test/query-image-date-readiness.serial.test.ts
new file mode 100644
index 0000000000..381c37be04
--- /dev/null
+++ b/test/query-image-date-readiness.serial.test.ts
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import * as gateway from '../src/core/ai/gateway.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import type { SearchOpts } from '../src/core/types.ts';
+
+let embeddings = 0;
+mock.module('../src/core/ai/gateway.ts', () => ({
+ ...gateway,
+ embedMultimodal: async () => { embeddings++; return [new Float32Array(1024)]; },
+}));
+const { operationsByName } = await import('../src/core/operations.ts');
+
+beforeEach(() => { embeddings = 0; });
+
+describe('image query retains date and readiness contracts outside hybrid search', () => {
+ test.each([false, true])('incomplete vector metadata survives with a nonempty image result=%s', async nonempty => {
+ let options: SearchOpts | undefined;
+ let meta: Record<string, unknown> = {};
+ const engine = {
+ getConfig: async () => null,
+ getAllConfig: async () => ({}),
+ executeRaw: async (sql: string) => sql.includes('AS pending') ? [{ pending: false }] : [],
+ searchVector: async (_vector: Float32Array, opts: SearchOpts) => {
+ options = opts;
+ opts.onVectorPoolMeta?.({ underfilled: true, incomplete: true, escalations: 3,
+ innerLimit: 1600, candidatePool: 1, reason: 'deadline' });
+ return nonempty ? [{ slug: 'images/synthetic', page_id: 1, source_id: 'default', chunk_text: 'Synthetic image' }] : [];
+ },
+ } as unknown as BrainEngine;
+ const ctx = { engine, remote: true, sourceId: 'default', config: { engine: 'pglite' },
+ dryRun: false, logger: console,
+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') meta = value as Record<string, unknown>; },
+ } as OperationContext;
+ const results = await operationsByName.query.handler(ctx, {
+ image: 'c3ludGhldGlj', limit: 3, since: '2030-06-15', until: '2030-06-15',
+ });
+ expect(results).toHaveLength(nonempty ? 1 : 0);
+ expect(options).toMatchObject({ afterDate: '2030-06-15', afterDateInclusive: true,
+ beforeDate: '2030-06-16T00:00:00.000Z', beforeDateInclusive: false,
+ sourceId: 'default', excludePrivate: true, requireSafeChunks: true });
+ expect(meta.degraded).toContainEqual({ stage: 'vector_candidates_incomplete', reason: 'timeout' });
+ expect(meta.vector_pool_underfilled).toMatchObject({ incomplete: true, candidatePool: 1 });
+ expect(meta.projection_readiness).toEqual({ status: 'ready', ready: true });
+ });
+
+ test('invalid date input fails before an embedding request', async () => {
+ const engine = { getConfig: async () => null } as unknown as BrainEngine;
+ const ctx = { engine, remote: true, sourceId: 'default', config: { engine: 'pglite' }, dryRun: false, logger: console } as OperationContext;
+ await expect(operationsByName.query.handler(ctx, { image: 'c3ludGhldGlj', since: 'not-a-date' })).rejects.toThrow('Invalid since');
+ expect(embeddings).toBe(0);
+ });
+});
diff --git a/test/reindex-code-delegate.test.ts b/test/reindex-code-delegate.test.ts
new file mode 100644
index 0000000000..70266bfa6e
--- /dev/null
+++ b/test/reindex-code-delegate.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test } from 'bun:test';
+import { parseReindexCodeDelegateArgs } from '../src/commands/reindex-code-delegate.ts';
+
+describe('resident code reindex arguments', () => {
+ test('keyless source-scoped recovery stays explicit', () => {
+ expect(parseReindexCodeDelegateArgs(['--source', 'code-example', '--force', '--no-embed', '--json'])).toEqual({
+ sourceId: 'code-example', force: true, noEmbed: true, json: true,
+ });
+ });
+
+ test('unknown argument values never appear in errors', () => {
+ try {
+ parseReindexCodeDelegateArgs(['--token=synthetic-credential-value']);
+ throw new Error('Expected refusal');
+ } catch (error) {
+ expect(error).toMatchObject({ code: 'invalid_params' });
+ expect((error as Error).message).not.toContain('synthetic-credential-value');
+ }
+ });
+
+ for (const args of [['--workers', '0'], ['--workers', '65'], ['--max-cost', '0'], ['--source']]) {
+ test(`invalid recovery options are refused: ${args.join(' ')}`, () => {
+ expect(() => parseReindexCodeDelegateArgs(args)).toThrow();
+ });
+ }
+});
diff --git a/test/scripts/ci-local-rendering.test.ts b/test/scripts/ci-local-rendering.test.ts
index 0b77fd3faf..511c75e4ea 100644
--- a/test/scripts/ci-local-rendering.test.ts
+++ b/test/scripts/ci-local-rendering.test.ts
@@ -226,14 +226,16 @@ describe('ci-local execution coverage', () => {
});
describe('required PgBouncer execution through run-e2e', () => {
- for (const [required, passes, testExit, expectedExit, parentCoverageExists] of [
+ for (const [required, passes, testExit, expectedExit, parentCoverageExists, outputBytes = 0] of [
[true, 2, 0, 0, false],
[true, 0, 0, 1, false],
[true, 0, 3, 1, false],
[false, 0, 0, 0, false],
[true, 2, 0, 0, true],
+ [true, 2, 0, 0, false, 262144],
+ [true, 0, 0, 1, false, 262144],
] as const) {
- test(`required=${required}, executed=${passes}, Bun exit=${testExit}, parent coverage exists=${parentCoverageExists}`, () => {
+ test(`required=${required}, executed=${passes}, Bun exit=${testExit}, parent coverage exists=${parentCoverageExists}${outputBytes ? `, diagnostic bytes=${outputBytes}` : ''}`, () => {
const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-pooler-'));
try {
const bin = join(home, 'bin');
@@ -246,6 +248,7 @@ describe('required PgBouncer execution through run-e2e', () => {
writeFileSync(join(bin, 'bun'), `#!/bin/sh
printf '%s\\n' "$GBRAIN_PGBOUNCER_URL" "$GBRAIN_PGBOUNCER_DIRECT_URL" "$GBRAIN_CI_REQUIRE_PGBOUNCER" "$GBRAIN_TEST_DB" "\${GBRAIN_SOURCE-unset}" "\${COVERAGE_DIR:-disabled}" > "$ENV_REPORT"
printf ' %s pass\\n 0 fail\\n' "$FAKE_PASSES"
+if [ "$FAKE_OUTPUT_BYTES" -gt 0 ]; then printf '%*s\\n' "$FAKE_OUTPUT_BYTES" ''; fi
exit "$FAKE_EXIT"
`, { mode: 0o755 });
const report = join(home, 'environment');
@@ -272,7 +275,7 @@ exit "$FAKE_EXIT"
DATABASE_URL: direct, GBRAIN_PGBOUNCER_URL: pooled, GBRAIN_PGBOUNCER_DIRECT_URL: direct,
GBRAIN_CI_REQUIRE_PGBOUNCER: required ? '1' : '0', GBRAIN_SOURCE: 'ambient-must-be-removed',
GBRAIN_TEST_DB: '1',
- ENV_REPORT: report, FAKE_PASSES: String(passes), FAKE_EXIT: String(testExit),
+ ENV_REPORT: report, FAKE_PASSES: String(passes), FAKE_EXIT: String(testExit), FAKE_OUTPUT_BYTES: String(outputBytes),
},
});
expect(result.status, result.stdout + result.stderr).toBe(expectedExit);
diff --git a/test/search-date-bounds.test.ts b/test/search-date-bounds.test.ts
new file mode 100644
index 0000000000..06e94d33c0
--- /dev/null
+++ b/test/search-date-bounds.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, test } from 'bun:test';
+import { resolveSearchDateBounds } from '../src/core/search/hybrid.ts';
+
+describe('public search date bounds preserve their comparison contract', () => {
+ test('since includes the exact boundary without rounding microseconds', () => {
+ expect(resolveSearchDateBounds({ since: '2030-06-15T10:00:00.123456+02:00' })).toMatchObject({
+ afterDate: '2030-06-15T10:00:00.123456+02:00', afterDateInclusive: true,
+ });
+ });
+
+ test('exact until includes the timestamp as written', () => {
+ expect(resolveSearchDateBounds({ until: '2030-06-15T23:59:59.999999Z' })).toMatchObject({
+ beforeDate: '2030-06-15T23:59:59.999999Z', beforeDateInclusive: true,
+ });
+ });
+
+ test.each([
+ ['2030-06-15', '2030-06-16T00:00:00.000Z'],
+ ['2032-02-29', '2032-03-01T00:00:00.000Z'],
+ ['2030-12-31', '2031-01-01T00:00:00.000Z'],
+ ])('date-only until %s includes the entire day', (until, boundary) => {
+ expect(resolveSearchDateBounds({ until })).toMatchObject({
+ beforeDate: boundary, beforeDateInclusive: false,
+ });
+ });
+
+ test('legacy after/before remain strict and public fields win', () => {
+ const legacy = resolveSearchDateBounds({ afterDate: '2030-06-01', beforeDate: '2030-06-15' });
+ expect(legacy.afterDateInclusive).not.toBe(true);
+ expect(legacy.beforeDateInclusive).not.toBe(true);
+ expect(legacy.beforeDate).toBe('2030-06-15T23:59:59.999Z');
+ expect(resolveSearchDateBounds({ afterDate: '2030-01-01', since: '2030-06-15' })).toMatchObject({
+ afterDate: '2030-06-15', afterDateInclusive: true,
+ });
+ });
+
+ test('invalid calendar dates are rejected instead of shifting into the next month', () => {
+ expect(() => resolveSearchDateBounds({ until: '2030-02-30' })).toThrow('Invalid until');
+ expect(() => resolveSearchDateBounds({ since: '2030-02-29' })).toThrow('Invalid since');
+ expect(() => resolveSearchDateBounds({ until: '0000-01-01' })).toThrow('Invalid until');
+ });
+});
diff --git a/test/search-projection-readiness.test.ts b/test/search-projection-readiness.test.ts
new file mode 100644
index 0000000000..e230a2438c
--- /dev/null
+++ b/test/search-projection-readiness.test.ts
@@ -0,0 +1,79 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+
+describe('search operations disclose visible projection gaps', () => {
+ let engine: PGLiteEngine;
+ let retrieval: Record<string, unknown>;
+ const sourceId = 'readiness-visible-example';
+ const foreign = 'readiness-foreign-example';
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ for (const id of [sourceId, foreign]) {
+ await engine.executeRaw('INSERT INTO sources(id, name) VALUES ($1, $1)', [id]);
+ }
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ }, 60_000);
+
+ beforeEach(async () => {
+ retrieval = {};
+ await engine.executeRaw('DELETE FROM pages WHERE source_id = ANY($1::text[])', [[sourceId, foreign]]);
+ });
+
+ afterAll(async () => { await engine?.disconnect(); });
+
+ function context(remote: boolean): OperationContext {
+ return {
+ engine, config: { engine: 'pglite' }, dryRun: false, remote, sourceId,
+ logger: { info() {}, warn() {}, error() {} },
+ emitResponseMeta: (key, value) => { if (key === 'retrieval') retrieval = value as Record<string, unknown>; },
+ } as OperationContext;
+ }
+
+ async function sealed(): Promise<void> {
+ await engine.putPage('notes/current', { type: 'note', title: 'Synthetic current', compiled_truth: 'readinessmarker' }, { sourceId });
+ await installFixtureChunks(engine, 'notes/current', [{
+ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'readinessmarker',
+ }], { sourceId });
+ }
+
+ test.each([false, true])('a nonempty result still discloses current-revision pending work, remote=%s', async remote => {
+ await sealed();
+ await engine.putPage('notes/pending', { type: 'note', title: 'Synthetic pending', compiled_truth: 'readinessmarker' }, { sourceId });
+ const rows = await operationsByName.search.handler(context(remote), { query: 'readinessmarker', source_id: sourceId });
+ expect(rows).toHaveLength(1);
+ expect(retrieval.degraded).toContainEqual({ stage: 'projection_pending' });
+ expect(retrieval.projection_readiness).toMatchObject({ status: 'projection_pending', ready: false });
+ });
+
+ test('pending pages outside the requested source do not affect readiness', async () => {
+ await sealed();
+ await engine.putPage('notes/foreign-pending', { type: 'note', title: 'Foreign example', compiled_truth: 'readinessmarker' }, { sourceId: foreign });
+ await operationsByName.search.handler(context(true), { query: 'readinessmarker', source_id: sourceId });
+ expect(retrieval.projection_readiness).toEqual({ status: 'ready', ready: true });
+ expect(retrieval.degraded).toBeUndefined();
+ expect(JSON.stringify(retrieval)).not.toContain(foreign);
+ });
+
+ test('private-only pending pages cannot be disclosed by an empty remote search', async () => {
+ await engine.putPage('notes/private-pending', {
+ type: 'note', title: 'Private synthetic example', compiled_truth: 'readinessmarker', frontmatter: { visibility: 'private' },
+ }, { sourceId });
+ await operationsByName.search.handler(context(true), { query: 'missingtoken', source_id: sourceId });
+ expect(retrieval.projection_readiness).toEqual({ status: 'ready', ready: true });
+ expect(retrieval.degraded).toBeUndefined();
+ });
+
+ test('the current-projection diagnostic honors the public type filter', async () => {
+ await sealed();
+ await engine.putPage('articles/pending', { type: 'article', title: 'Synthetic article', compiled_truth: 'readinessmarker' }, { sourceId });
+ const rows = await operationsByName.search.handler(context(true), { query: 'readinessmarker', source_id: sourceId, types: ['note'] });
+ expect(rows).toHaveLength(1);
+ expect(retrieval.projection_readiness).toEqual({ status: 'ready', ready: true });
+ expect(retrieval.degraded).toBeUndefined();
+ });
+});
diff --git a/test/search-safe-index-probe.test.ts b/test/search-safe-index-probe.test.ts
index 74fd6f4443..11c2efbfae 100644
--- a/test/search-safe-index-probe.test.ts
+++ b/test/search-safe-index-probe.test.ts
@@ -66,7 +66,7 @@ describe('safe_index_pending probe stays sargable (#5004)', () => {
const probe = captured.find(c => c.sql.includes("page_kind = 'markdown'") && /LIMIT 1/.test(c.sql));
expect(probe).toBeDefined();
- expect(probe!.sql).not.toContain('COALESCE');
+ expect(probe!.sql).not.toContain('COALESCE(p.chunker_version');
expect(probe!.sql).toContain(`p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}`);
await engine.executeRaw('SET enable_seqscan = off');
diff --git a/test/search/atom-session-diversification.test.ts b/test/search/atom-session-diversification.test.ts
new file mode 100644
index 0000000000..63acd09321
--- /dev/null
+++ b/test/search/atom-session-diversification.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+import { applyGraphSignals, SESSION_DEMOTE, sessionPrefix } from '../../src/core/search/graph-signals.ts';
+
+describe('atoms retain independent retrieval scores', () => {
+ test.each([
+ 'atoms/2030-04-30/first-lesson',
+ 'atoms/2030-04-30/chat-discussion',
+ 'atoms/2030-04-30/sessions/summary',
+ 'atoms/transcripts/chat/lesson',
+ ])('%s is not a transcript session', slug => {
+ expect(sessionPrefix(slug)).toBeNull();
+ });
+
+ test('same-date atoms keep scores while meeting and daily siblings still diversify', async () => {
+ const slugs = [
+ 'atoms/2030-04-30/first-lesson',
+ 'atoms/2030-04-30/second-lesson',
+ 'atoms/2030-04-30/third-lesson',
+ 'meetings/2030-04-30/notes',
+ 'meetings/2030-04-30/actions',
+ 'daily/2030-04-30/morning',
+ 'daily/2030-04-30/evening',
+ ];
+ const rows: SearchResult[] = slugs.map((slug, index) => ({
+ slug, title: slug, page_id: index + 1, chunk_id: index + 1,
+ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic example',
+ type: 'note', source_id: 'default', score: 20 - index, stale: false,
+ }));
+ let demotions: number | undefined;
+ await applyGraphSignals(rows, {} as BrainEngine, {
+ enabled: true,
+ adjacencyFn: async () => new Map(),
+ onMeta: meta => { demotions = meta.session_demotions; },
+ });
+ for (let index = 0; index < 3; index++) {
+ expect(rows[index].score).toBe(20 - index);
+ expect(rows[index].graph_session_demoted).toBeUndefined();
+ expect(rows[index].graph_session_prefix).toBeUndefined();
+ }
+ expect(rows[3].score).toBe(17);
+ expect(rows[4].score).toBeCloseTo(16 * SESSION_DEMOTE);
+ expect(rows[5].score).toBe(15);
+ expect(rows[6].score).toBeCloseTo(14 * SESSION_DEMOTE);
+ expect(demotions).toBe(2);
+ });
+});
diff --git a/test/search/search-query-contract.test.ts b/test/search/search-query-contract.test.ts
new file mode 100644
index 0000000000..6c961f292a
--- /dev/null
+++ b/test/search/search-query-contract.test.ts
@@ -0,0 +1,17 @@
+import { afterAll, beforeAll, describe, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { seedSearchQueryContract, verifyKeywordTieOrder, verifyMixedCjkCase, verifySearchDateBounds } from '../helpers/search-query-contract.ts';
+
+describe('search query contract on PGLite', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedSearchQueryContract(engine);
+ }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+ test('all arms preserve inclusive bounds and strict legacy microsecond precision', async () => { await verifySearchDateBounds(engine); });
+ test('keyword page pools and chunk pagination have deterministic tie ordering', async () => { await verifyKeywordTieOrder(engine); });
+ test('mixed CJK and Latin terms remain case-insensitive', async () => { await verifyMixedCjkCase(engine); });
+});
diff --git a/test/search/searchvector-escalation.test.ts b/test/search/searchvector-escalation.test.ts
index 2ecc20bb70..bb239c2e62 100644
--- a/test/search/searchvector-escalation.test.ts
+++ b/test/search/searchvector-escalation.test.ts
@@ -7,11 +7,10 @@
* candidate pool, so the PAGE result came back underfilled — sparse pages
* behind the dense one were unreachable at any limit.
*
- * The fix: escalate innerLimit ×4 (≤3 times, hard-capped at the HNSW
- * ef_search substrate ceiling of 1000) while the page set is short but the
- * pre-collapse candidate pool was FULL. A short page with a non-full pool is
- * a genuine final page — no retry. Exhaustion at the cap emits
- * onVectorPoolMeta (visible, not silent).
+ * The fix: escalate the SQL pool independently of the HNSW ef_search
+ * ceiling, with bounded iterative work. A short ANN pool needs scoped
+ * exhaustion evidence before it can be reported as a genuine final page.
+ * Positive incomplete coverage lives in vector-candidate-safety.test.ts.
*
* PGLite side of the engine-parity pair; the postgres side is pinned by
* test/e2e/engine-parity.test.ts.
@@ -134,13 +133,7 @@ describe('searchVector bounded escalation', () => {
// touch its schema.
// ============================================================
-describe('searchVector escalation — fire-at-cap positive (HNSW lane)', () => {
- // hnswIndexExpected('vector', <=2000 dims) → innerCap = HNSW_EF_SEARCH_MAX
- // (1000). Two dense pages carry 1120 embedded chunks between them, so the
- // pre-DISTINCT chunk pull stays FULL at every escalation rung
- // (100 → 400 → 1000) while the PAGE set stays at 2. The loop must stop at
- // the substrate ceiling AND report the exhaustion — the positive twin of
- // the two negative paths pinned above.
+describe('searchVector escalation — dense corpus beyond the old HNSW cap', () => {
let capEngine: PGLiteEngine;
const CAP_DIM = 8; // small dims: 1120-chunk fixture stays fast; cap policy keys on type, not size
@@ -192,18 +185,16 @@ describe('searchVector escalation — fire-at-cap positive (HNSW lane)', () => {
expect(idx.length).toBe(1);
});
- test('exhaustion at the ef_search cap EMITS the underfill event', async () => {
+ test('exhaustion beyond the old ef_search cap is proved without a false underfill event', async () => {
const events: Array<{ underfilled: boolean; escalations: number; innerLimit: number }> = [];
const results = await capEngine.searchVector(capEmb(1), {
limit: 10,
detail: 'high',
onVectorPoolMeta: (m) => events.push(m),
});
- // Page set is genuinely short (2 dense pages < limit 10) but the chunk
- // pool was full at the cap — visible, not silent.
expect(results.length).toBe(2);
expect(new Set(results.map((r) => r.slug))).toEqual(new Set(['notes/dense-a', 'notes/dense-b']));
- expect(events).toEqual([{ underfilled: true, escalations: 2, innerLimit: 1000 }]);
+ expect(events).toEqual([]);
});
});
@@ -288,12 +279,7 @@ describe('searchVector escalation — exact-scan lane (>2000-dim column, cap key
expect(events).toHaveLength(0);
});
- test('contrast: an HNSW-shaped descriptor caps the same deep offset at the substrate ceiling', async () => {
- // The cap keys on the DESCRIPTOR (hnswIndexExpected), not the physical
- // index: the default legacy descriptor claims vector/1536 → cap 1000 →
- // the inner pool can never reach row 1041. Production callers on a
- // >2000-dim brain always get the real descriptor from the registry
- // resolver; this pins the seam the R2-10 policy hangs off.
+ test('an HNSW-shaped descriptor no longer caps SQL output at the ef_search ceiling', async () => {
const events: unknown[] = [];
const results = await exactEngine.searchVector(exactEmb(), {
limit: 10,
@@ -301,9 +287,10 @@ describe('searchVector escalation — exact-scan lane (>2000-dim column, cap key
detail: 'high',
onVectorPoolMeta: (m) => events.push(m),
});
- expect(results.length).toBe(0);
- // Zero rows at offset>0 → pool unknowable → no event (the negative
- // deep-pagination contract pinned above holds here too).
+ expect(results.length).toBe(10);
+ expect(results.map(r => r.slug)).toEqual(
+ Array.from({ length: 10 }, (_, i) => `deep/page-${String(1040 + i).padStart(4, '0')}`),
+ );
expect(events).toHaveLength(0);
});
});
diff --git a/test/search/vector-candidate-safety.test.ts b/test/search/vector-candidate-safety.test.ts
new file mode 100644
index 0000000000..5db0256afa
--- /dev/null
+++ b/test/search/vector-candidate-safety.test.ts
@@ -0,0 +1,76 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { candidateColumn, candidateVector, seedVectorCandidateCorpus, verifyVectorCapabilityRetry } from '../helpers/vector-candidate-corpus.ts';
+
+describe('PGLite filtered ANN candidate safety', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await seedVectorCandidateCorpus(engine);
+ }, 240_000);
+ afterAll(async () => { await engine.disconnect(); }, 60_000);
+ test('a transient capability probe is retried and successful capability is cached', async () => { await verifyVectorCapabilityRetry(engine); });
+
+ test('bounded iterative scanning fills selective source and private-filtered results', async () => {
+ const events: unknown[] = [];
+ const hits = await engine.searchVector(candidateVector, { limit: 75, sourceId: 'ann-allowed', excludePrivate: true, embeddingColumn: candidateColumn, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits).toHaveLength(75);
+ expect(new Set(hits.map(hit => hit.page_id)).size).toBe(75);
+ expect(hits.every(hit => hit.source_id === 'ann-allowed' && Number(hit.slug.split('-').at(-1)) % 100 !== 1)).toBe(true);
+ expect(events).toEqual([]);
+ }, 60_000);
+
+ test('deep offsets and genuinely empty scopes remain distinguishable', async () => {
+ const events: unknown[] = [];
+ expect(await engine.searchVector(candidateVector, { limit: 10, offset: 1040, embeddingColumn: candidateColumn, onVectorPoolMeta: meta => events.push(meta) })).toHaveLength(10);
+ expect(await engine.searchVector(candidateVector, { limit: 10, sourceId: 'missing-source', embeddingColumn: candidateColumn, onVectorPoolMeta: meta => events.push(meta) })).toEqual([]);
+ expect(await engine.searchVector(candidateVector, { limit: 10, sourceId: 'ann-allowed', type: 'company', embeddingColumn: candidateColumn, onVectorPoolMeta: meta => events.push(meta) })).toEqual([]);
+ expect(events).toEqual([]);
+ }, 60_000);
+
+ test('transaction-local scan settings return to their prior values', async () => {
+ const before = await engine.executeRaw(`SELECT current_setting('hnsw.ef_search') AS ef, current_setting('hnsw.iterative_scan') AS iterative, current_setting('hnsw.max_scan_tuples') AS tuples`);
+ await engine.searchVector(candidateVector, { limit: 75, embeddingColumn: candidateColumn });
+ expect(await engine.executeRaw(`SELECT current_setting('hnsw.ef_search') AS ef, current_setting('hnsw.iterative_scan') AS iterative, current_setting('hnsw.max_scan_tuples') AS tuples`)).toEqual(before);
+ });
+
+ test('older-extension underfill is explicit and never triggers a PGLite exact fallback', async () => {
+ const capability = engine as unknown as { vectorIterativeScan?: Promise<boolean> };
+ const previous = capability.vectorIterativeScan;
+ capability.vectorIterativeScan = Promise.resolve(false);
+ await engine.executeRaw('SET enable_seqscan = off');
+ await engine.executeRaw('SET enable_sort = off');
+ try {
+ const events: Array<{ reason?: string; exactFallback?: boolean }> = [];
+ const hits = await engine.searchVector(candidateVector, { limit: 75, sourceId: 'ann-allowed', excludePrivate: true, embeddingColumn: candidateColumn, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits.length).toBeLessThan(75);
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ reason: 'iterative_scan_unavailable', exactFallback: false });
+ } finally {
+ capability.vectorIterativeScan = previous;
+ await engine.executeRaw('RESET enable_seqscan');
+ await engine.executeRaw('RESET enable_sort');
+ }
+ }, 60_000);
+
+ test('the real iterative work ceiling reports incomplete candidates instead of a false clean miss', async () => {
+ await engine.executeRaw(`UPDATE content_chunks cc SET language = 'rare-fixture' FROM pages p
+ WHERE cc.page_id = p.id AND cc.chunk_index = 0 AND p.id % 60 = 1`);
+ await engine.executeRaw('ANALYZE content_chunks');
+ await engine.executeRaw('SET enable_seqscan = off');
+ await engine.executeRaw('SET enable_sort = off');
+ try {
+ const events: Array<{ reason?: string; exactFallback?: boolean }> = [];
+ const hits = await engine.searchVector(candidateVector, { limit: 75, language: 'rare-fixture', embeddingColumn: candidateColumn, onVectorPoolMeta: meta => events.push(meta) });
+ expect(hits.length).toBeLessThan(75);
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ reason: 'candidate_budget', exactFallback: false });
+ expect((await engine.executeRaw(`SELECT count(*)::int AS eligible FROM content_chunks WHERE language = 'rare-fixture'`))[0].eligible).toBe(100);
+ } finally {
+ await engine.executeRaw('RESET enable_seqscan');
+ await engine.executeRaw('RESET enable_sort');
+ }
+ }, 60_000);
+});
diff --git a/test/search/vector-pool.test.ts b/test/search/vector-pool.test.ts
new file mode 100644
index 0000000000..6728c191c5
--- /dev/null
+++ b/test/search/vector-pool.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, test } from 'bun:test';
+import { readVectorPool, searchVectorPool, type VectorPoolAttempt } from '../../src/core/search/vector-pool.ts';
+import { supportsHnswIterativeScan } from '../../src/core/vector-index.ts';
+import type { SearchOpts } from '../../src/core/types.ts';
+
+type PoolMeta = Parameters<NonNullable<SearchOpts['onVectorPoolMeta']>>[0];
+
+describe('bounded vector candidate safety', () => {
+ test('extension capability comes from the installed version, including older releases', () => {
+ for (const version of [undefined, '', 'invalid', '0.7.4', '0.6.2']) expect(supportsHnswIterativeScan(version)).toBe(false);
+ for (const version of ['0.8.0', '0.8.1', '0.10.0', '1.0.0']) expect(supportsHnswIterativeScan(version)).toBe(true);
+ });
+
+ test('empty OFFSET pages preserve the candidate count without exposing a sentinel result', () => {
+ expect(readVectorPool([{ page_id: null, candidate_pool: 375 }])).toEqual({ rows: [], candidatePool: 375 });
+ expect(readVectorPool([{ page_id: 2, candidate_pool: 8 }])).toEqual({ rows: [{ page_id: 2, candidate_pool: 8 }], candidatePool: 8 });
+ });
+
+ test('a filtered short ANN pool is not mistaken for corpus exhaustion', async () => {
+ const attempts: VectorPoolAttempt[] = [];
+ const events: PoolMeta[] = [];
+ const rows = await searchVectorPool(75, 375, true, true, 'pglite', async attempt => {
+ attempts.push(attempt);
+ return { rows: Array.from({ length: attempts.length === 1 ? 8 : 75 }, (_, page_id) => ({ page_id })), candidatePool: attempts.length === 1 ? 8 : 375 };
+ }, async () => true, meta => events.push(meta));
+ expect(rows).toHaveLength(75);
+ expect(attempts.map(a => a.innerLimit)).toEqual([375, 1500]);
+ expect(attempts.every(a => !a.exact)).toBe(true);
+ expect(events).toEqual([]);
+ });
+
+ test('a zero-row ANN pool remains visibly incomplete when eligible rows exist', async () => {
+ const events: PoolMeta[] = [];
+ const attempts: VectorPoolAttempt[] = [];
+ const rows = await searchVectorPool(10, 1100, true, true, 'pglite', async attempt => {
+ attempts.push(attempt);
+ return { rows: [], candidatePool: 0 };
+ }, async () => true, meta => events.push(meta));
+ expect(rows).toEqual([]);
+ expect(attempts).toHaveLength(4);
+ expect(attempts.every(a => a.maxScanTuples <= 20_000 && !a.exact)).toBe(true);
+ expect(events).toEqual([{ underfilled: true, incomplete: true, reason: 'candidate_budget', escalations: 3, innerLimit: 20_000, candidatePool: 0, exactFallback: false }]);
+ });
+
+ test('proved empty and small corpora do not emit degraded metadata', async () => {
+ for (const candidatePool of [0, 2]) {
+ const events: PoolMeta[] = [];
+ let calls = 0;
+ await searchVectorPool(10, 100, true, true, 'pglite', async () => {
+ calls++;
+ return { rows: [], candidatePool };
+ }, async () => false, meta => events.push(meta));
+ expect(calls).toBe(1);
+ expect(events).toEqual([]);
+ }
+ });
+
+ test('older pgvector on PGLite reports capability limits without an exact fallback', async () => {
+ const events: PoolMeta[] = [];
+ const attempts: VectorPoolAttempt[] = [];
+ await searchVectorPool(10, 100, false, true, 'pglite', async attempt => {
+ attempts.push(attempt);
+ return { rows: [], candidatePool: 0 };
+ }, async () => true, meta => events.push(meta));
+ expect(attempts).toHaveLength(1);
+ expect(events[0].reason).toBe('iterative_scan_unavailable');
+ expect(events[0].exactFallback).toBe(false);
+ });
+
+ test('Postgres allows one exact fallback with a remaining server budget', async () => {
+ const events: PoolMeta[] = [];
+ const attempts: VectorPoolAttempt[] = [];
+ const result = await searchVectorPool(10, 100, false, true, 'postgres', async attempt => {
+ attempts.push(attempt);
+ return { rows: attempt.exact ? [{ page_id: 7 }] : [], candidatePool: attempt.exact ? 1 : 0, exhausted: attempt.exact };
+ }, async () => true, meta => events.push(meta));
+ expect(result).toEqual([{ page_id: 7 }]);
+ expect(attempts.map(a => a.exact)).toEqual([false, true]);
+ expect(attempts[1].remainingMs).toBeGreaterThan(0);
+ expect(attempts[1].remainingMs).toBeLessThanOrEqual(attempts[0].remainingMs);
+ expect(events).toEqual([]);
+ });
+
+ test('an exact fallback with a still-capped dense pool cannot claim completeness', async () => {
+ const events: PoolMeta[] = [];
+ const rows = await searchVectorPool(10, 100, false, true, 'postgres', async () => ({ rows: [{ page_id: 1 }], candidatePool: 100 }), async () => true, meta => events.push(meta));
+ expect(rows).toEqual([{ page_id: 1 }]);
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ reason: 'candidate_budget', incomplete: true, exactFallback: true, candidatePool: 100 });
+ });
+
+ test('server cancellation preserves prior rows and reports the deadline', async () => {
+ const events: PoolMeta[] = [];
+ await searchVectorPool(10, 100, false, true, 'postgres', async attempt => {
+ if (attempt.exact) throw Object.assign(new Error('query canceled'), { code: '57014' });
+ return { rows: [{ page_id: 4 }], candidatePool: 1 };
+ }, async () => true, meta => events.push(meta));
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ reason: 'deadline', candidatePool: 1, incomplete: true, exactFallback: true });
+ });
+});
diff --git a/test/select-e2e.test.ts b/test/select-e2e.test.ts
index 0c12dea8ca..97aa990646 100644
--- a/test/select-e2e.test.ts
+++ b/test/select-e2e.test.ts
@@ -119,11 +119,16 @@ describe("selectTests", () => {
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts",
"test/e2e/legacy-chunk-privacy.test.ts",
+ "test/e2e/projection-readiness-currency.test.ts",
+ "test/e2e/projection-statistics-postgres.test.ts",
"test/e2e/read-enrichment-privacy.test.ts",
"test/e2e/remote-privacy-journeys.test.ts",
"test/e2e/search-exclude.test.ts",
"test/e2e/search-quality.test.ts",
+ "test/e2e/search-query-contract-postgres.test.ts",
+ "test/e2e/search-readiness-http.test.ts",
"test/e2e/search-swamp.test.ts",
+ "test/e2e/vector-candidate-safety-postgres.test.ts",
]);
});
@@ -203,11 +208,16 @@ describe("selectTests", () => {
"test/e2e/chunk-canonical-text-privacy.test.ts",
"test/e2e/engine-content-privacy.test.ts",
"test/e2e/legacy-chunk-privacy.test.ts",
+ "test/e2e/projection-readiness-currency.test.ts",
+ "test/e2e/projection-statistics-postgres.test.ts",
"test/e2e/read-enrichment-privacy.test.ts",
"test/e2e/remote-privacy-journeys.test.ts",
"test/e2e/search-exclude.test.ts",
"test/e2e/search-quality.test.ts",
+ "test/e2e/search-query-contract-postgres.test.ts",
+ "test/e2e/search-readiness-http.test.ts",
"test/e2e/search-swamp.test.ts",
+ "test/e2e/vector-candidate-safety-postgres.test.ts",
]);
});
diff --git a/test/snapshot-shape-guard.test.ts b/test/snapshot-shape-guard.test.ts
index c83552131f..33bfea4449 100644
--- a/test/snapshot-shape-guard.test.ts
+++ b/test/snapshot-shape-guard.test.ts
@@ -105,6 +105,7 @@ test('memo: stale hash is terminal — tar never read, repeat calls short-circui
const schemaInputs = [
'migrate.ts', 'pglite-schema.ts', 'fts-language.ts', 'vector-index.ts', 'ai/defaults.ts',
+ 'search/projection-statistics.ts',
'timeline-dedup-repair.ts', 'pages-upsert-arbiter.ts', 'link-extraction.ts',
'grants/schema.ts', 'grants/migration.ts', 'grants/model.ts', 'grants/service.ts', 'grants/profiles.ts',
'page-state/schema.ts', 'lease-schema.ts', 'page-state/projection-schema.ts', 'persistence/schema.ts', 'persistence/effect-schema.ts', 'persistence/writer-guard-schema.ts', 'persistence/topology-schema.ts', 'scope.ts', 'sql-query.ts', 'minions/tools/brain-allowlist.ts', 'facts/withdrawal-schema.ts',
diff --git a/test/sql-ranking.test.ts b/test/sql-ranking.test.ts
index 9cc6bf07fe..f5af849df5 100644
--- a/test/sql-ranking.test.ts
+++ b/test/sql-ranking.test.ts
@@ -311,7 +311,7 @@ describe('buildVisibilityClause (v0.26.5)', () => {
test('uses the supplied aliases verbatim', () => {
expect(buildVisibilityClause('pp', 'src')).toBe(
- "AND pp.deleted_at IS NULL AND pp.text_projection_revision = pp.knowledge_revision AND NOT src.archived AND NOT (COALESCE(pp.frontmatter, '{}'::jsonb) ? 'quarantine')",
+ "AND pp.deleted_at IS NULL AND (pp.text_projection_revision = pp.knowledge_revision) IS TRUE AND NOT src.archived AND NOT (COALESCE(pp.frontmatter, '{}'::jsonb) ? 'quarantine')",
);
});
diff --git a/test/symbol-resolver-projection-race.test.ts b/test/symbol-resolver-projection-race.test.ts
new file mode 100644
index 0000000000..4cb8f1aa87
--- /dev/null
+++ b/test/symbol-resolver-projection-race.test.ts
@@ -0,0 +1,264 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { setTimeout as delay } from 'node:timers/promises';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importCodeFile } from '../src/core/import-file.ts';
+import { installPageProjection, preparePageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';
+import { resolveSymbolEdgesIncremental } from '../src/core/chunkers/symbol-resolver.ts';
+import { resolveCodeReadiness } from '../src/core/code-graph-readiness.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>(done => { resolve = done; });
+ return { promise, resolve };
+}
+
+async function bounded<T>(work: Promise<T>, label: string, ms = 10_000): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([work, new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`Timed out waiting for ${label}`)), ms);
+ })]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function instrumentTransactions(engine: BrainEngine, wrap: (tx: BrainEngine) => BrainEngine): BrainEngine {
+ const wrapped = Object.create(engine) as BrainEngine;
+ wrapped.transaction = <T>(run: (tx: BrainEngine) => Promise<T>) => engine.transaction(tx => run(wrap(tx)));
+ return wrapped;
+}
+
+describe('symbol resolver and projection replacement serialization', () => {
+ let lite: PGLiteEngine;
+ let pg: Awaited<ReturnType<typeof isolatedPersistencePostgres>> | undefined;
+
+ beforeAll(async () => {
+ lite = new PGLiteEngine();
+ await lite.connect({});
+ await lite.initSchema();
+ if (process.env.DATABASE_URL) pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ }, 120_000);
+
+ afterAll(async () => {
+ await lite?.disconnect();
+ await pg?.close();
+ }, 60_000);
+
+ async function seed(engine: BrainEngine, sourceId: string) {
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const { slug } = await importCodeFile(engine, 'example.ts',
+ 'export function betaExample() { return 3; }\nexport function alphaExample() { return betaExample(); }\n',
+ { sourceId, noEmbed: true });
+ const snapshot = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ const projection = await preparePageProjection(snapshot);
+ return { slug, snapshot, projection };
+ }
+
+ async function edges(engine: BrainEngine, sourceId: string) {
+ return engine.executeRaw<{ id: number; from_chunk_id: number; edge_metadata: Record<string, unknown> | null }>(
+ 'SELECT id,from_chunk_id,edge_metadata FROM code_edges_symbol WHERE source_id=$1 ORDER BY id', [sourceId]);
+ }
+
+ async function watermarks(engine: BrainEngine, sourceId: string) {
+ return engine.executeRaw<{ id: number; edges_backfilled_at: Date | string | null }>(
+ `SELECT cc.id,cc.edges_backfilled_at FROM content_chunks cc JOIN pages p ON p.id=cc.page_id
+ WHERE p.source_id=$1 ORDER BY cc.id`, [sourceId]);
+ }
+
+ async function replacementRace(engine: BrainEngine) {
+ const sourceId = `resolver-race-${engine.kind}`;
+ const { slug, snapshot, projection } = await seed(engine, sourceId);
+ const originalEdges = await edges(engine, sourceId);
+ expect(originalEdges).toHaveLength(1);
+ const entered = deferred();
+ const release = deferred();
+ const events: string[] = [];
+ let transactionEntered = false;
+ let guardsAcquired = false;
+ let publisherEntered = false;
+ let publisherCompleted = false;
+ let resolverPid: number | undefined;
+ const resolverEngine = instrumentTransactions(engine, tx => {
+ transactionEntered = true;
+ const wrapped = Object.create(tx) as BrainEngine;
+ wrapped.lockPageKeys = async keys => {
+ expect(keys.every(key => key.sourceId === sourceId && key.slug === slug)).toBe(true);
+ await tx.lockPageKeys(keys);
+ guardsAcquired = true;
+ events.push('resolver-locked');
+ };
+ wrapped.executeRaw = async <T>(sql: string, params?: unknown[]): Promise<T[]> => {
+ const rows = await tx.executeRaw<T>(sql, params);
+ if (sql.includes('SELECT id, from_chunk_id')) {
+ expect(guardsAcquired).toBe(true);
+ expect(rows).toHaveLength(1);
+ if (engine.kind === 'postgres') {
+ resolverPid = (await tx.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid'))[0].pid;
+ }
+ entered.resolve();
+ await bounded(release.promise, 'resolver release', 20_000);
+ }
+ if (sql.includes('SET edges_backfilled_at = NOW()')) events.push('resolver-stamped');
+ return rows;
+ };
+ return wrapped;
+ });
+ const resolver = resolveSymbolEdgesIncremental(resolverEngine, { sourceId, maxChunks: snapshot.chunks.length });
+ void resolver.catch(() => {});
+ let publisher: Promise<void> | undefined;
+ try {
+ await bounded(entered.promise, 'resolver edge read');
+ expect(transactionEntered).toBe(true);
+ const publisherEngine = instrumentTransactions(engine, tx => {
+ publisherEntered = true;
+ const wrapped = Object.create(tx) as BrainEngine;
+ wrapped.lockPageKeys = async keys => {
+ if (engine.kind === 'postgres') {
+ await tx.executeRaw("SELECT set_config('application_name',$1,true),set_config('lock_timeout','15s',true)", [sourceId]);
+ }
+ await tx.lockPageKeys(keys);
+ events.push('publisher-locked');
+ };
+ return wrapped;
+ });
+ publisher = installPageProjection(publisherEngine, snapshot, projection.chunks,
+ { seal: true, preserveEmbeddings: true, code: projection.code }).then(() => {
+ publisherCompleted = true;
+ events.push('publisher-completed');
+ });
+ void publisher.catch(() => {});
+ if (engine.kind === 'postgres') {
+ await bounded((async () => {
+ const deadline = performance.now() + 8_000;
+ while (performance.now() < deadline) {
+ const rows = await engine.executeRaw<{ blocked: boolean }>(
+ `SELECT EXISTS(SELECT 1 FROM pg_stat_activity
+ WHERE datname=current_database() AND application_name=$1 AND wait_event_type='Lock'
+ AND $2::int=ANY(pg_blocking_pids(pid))) AS blocked`, [sourceId, resolverPid]);
+ if (rows[0].blocked) return;
+ await delay(20);
+ }
+ throw new Error('Publisher never reported a database lock wait');
+ })(), 'publisher database lock receipt');
+ expect(publisherEntered).toBe(true);
+ } else {
+ await delay(20);
+ expect(publisherEntered).toBe(false);
+ }
+ expect(publisherCompleted).toBe(false);
+ expect(events).toEqual(['resolver-locked']);
+ release.resolve();
+ expect((await bounded(resolver, 'resolver completion')).edges_resolved).toBe(1);
+ await bounded(publisher, 'projection replacement');
+ expect(events.slice(0, 2)).toEqual(['resolver-locked', 'resolver-stamped']);
+ expect(events.slice(2, -1).length).toBeGreaterThan(0);
+ expect(events.slice(2, -1).every(event => event === 'publisher-locked')).toBe(true);
+ expect(events.at(-1)).toBe('publisher-completed');
+ const replacedEdges = await edges(engine, sourceId);
+ expect(replacedEdges).toHaveLength(1);
+ expect(replacedEdges[0].id).not.toBe(originalEdges[0].id);
+ expect(replacedEdges[0].edge_metadata?.resolved_chunk_id).toBeUndefined();
+ const after = await watermarks(engine, sourceId);
+ expect(after.map(chunk => chunk.id)).toEqual(snapshot.chunks.map(chunk => chunk.id));
+ expect(after.every(chunk => chunk.edges_backfilled_at === null)).toBe(true);
+ expect(await resolveCodeReadiness(engine, { sourceId, kind: 'edge', count: 0, remote: false }))
+ .toMatchObject({ status: 'indexing', ready: false, pending_edges: true });
+ const next = await resolveSymbolEdgesIncremental(engine, { sourceId });
+ expect(next.chunks_walked).toBe(snapshot.chunks.length);
+ expect(next.edges_resolved).toBe(1);
+ expect(typeof (await edges(engine, sourceId))[0].edge_metadata?.resolved_chunk_id).toBe('number');
+ expect(await resolveCodeReadiness(engine, { sourceId, kind: 'edge', count: 0, remote: false }))
+ .toMatchObject({ status: 'ready', ready: true, pending_edges: false });
+ } finally {
+ release.resolve();
+ await bounded(Promise.allSettled([resolver, ...(publisher ? [publisher] : [])]), 'race cleanup', 25_000);
+ }
+ }
+
+ test('PGlite queues actual projection replacement behind the paused resolver transaction', async () => {
+ await replacementRace(lite);
+ }, 60_000);
+
+ test.skipIf(!process.env.DATABASE_URL)('Postgres reports the actual publisher waiting on the resolver page guard', async () => {
+ await replacementRace(pg!.engine);
+ }, 60_000);
+
+ test('a failure after edge updates rolls metadata and watermarks back together', async () => {
+ for (const engine of [lite, ...(pg ? [pg.engine] : [])]) {
+ const sourceId = `resolver-rollback-${engine.kind}`;
+ await seed(engine, sourceId);
+ const beforeEdges = await edges(engine, sourceId);
+ const beforeWatermarks = await watermarks(engine, sourceId);
+ let wroteMetadata = false;
+ const failing = instrumentTransactions(engine, tx => {
+ const wrapped = Object.create(tx) as BrainEngine;
+ wrapped.executeRaw = async <T>(sql: string, params?: unknown[]): Promise<T[]> => {
+ if (sql.includes('SET edges_backfilled_at = NOW()')) {
+ expect(wroteMetadata).toBe(true);
+ expect(typeof (await edges(tx, sourceId))[0].edge_metadata?.resolved_chunk_id).toBe('number');
+ throw new Error('injected resolver watermark failure');
+ }
+ const result = await tx.executeRaw<T>(sql, params);
+ if (sql.includes('UPDATE code_edges_symbol')) wroteMetadata = true;
+ return result;
+ };
+ return wrapped;
+ });
+ await expect(resolveSymbolEdgesIncremental(failing, { sourceId })).rejects.toThrow('injected resolver watermark failure');
+ expect(wroteMetadata).toBe(true);
+ expect(await edges(engine, sourceId)).toEqual(beforeEdges);
+ expect(await watermarks(engine, sourceId)).toEqual(beforeWatermarks);
+ expect((await resolveSymbolEdgesIncremental(engine, { sourceId })).edges_resolved).toBe(1);
+ }
+ }, 60_000);
+
+ test('candidates are revalidated under the page guard before any metadata or watermark update', async () => {
+ for (const engine of [lite, ...(pg ? [pg.engine] : [])]) {
+ for (const change of ['watermark', 'projection', 'archive', 'slug'] as const) {
+ const sourceId = `resolver-stale-${engine.kind}-${change}`;
+ const { snapshot } = await seed(engine, sourceId);
+ const beforeEdges = await edges(engine, sourceId);
+ let invalidated = false;
+ let locked = false;
+ let revalidated = false;
+ let readEdges = false;
+ const stale = instrumentTransactions(engine, tx => {
+ const wrapped = Object.create(tx) as BrainEngine;
+ wrapped.lockPageKeys = async keys => { await tx.lockPageKeys(keys); locked = true; };
+ wrapped.executeRaw = async <T>(sql: string, params?: unknown[]): Promise<T[]> => {
+ const rows = await tx.executeRaw<T>(sql, params);
+ if (!invalidated && sql.includes('SELECT cc.id, cc.page_id, p.slug') && sql.includes('LIMIT $3')) {
+ expect(rows.length).toBeGreaterThan(0);
+ invalidated = true;
+ if (change === 'watermark') await tx.executeRaw("UPDATE content_chunks SET edges_backfilled_at='2099-01-01' WHERE page_id=$1", [snapshot.snapshot.page.id]);
+ if (change === 'projection') await tx.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE id=$1', [snapshot.snapshot.page.id]);
+ if (change === 'archive') await tx.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ if (change === 'slug') await tx.executeRaw("UPDATE pages SET slug='moved-example' WHERE id=$1", [snapshot.snapshot.page.id]);
+ }
+ if (sql.includes('SELECT cc.id, cc.page_id, p.slug') && sql.includes('cc.id=ANY')) {
+ expect(locked).toBe(true);
+ revalidated = true;
+ }
+ if (sql.includes('SELECT id, from_chunk_id')) readEdges = true;
+ return rows;
+ };
+ return wrapped;
+ });
+ expect(await resolveSymbolEdgesIncremental(stale, { sourceId })).toMatchObject({ chunks_walked: 0, edges_examined: 0, batches: 0 });
+ expect(invalidated).toBe(true);
+ expect(locked).toBe(true);
+ expect(revalidated).toBe(true);
+ expect(readEdges).toBe(false);
+ expect(await edges(engine, sourceId)).toEqual(beforeEdges);
+ const after = await watermarks(engine, sourceId);
+ expect(after).toHaveLength(snapshot.chunks.length);
+ expect(after.every(chunk => change === 'watermark'
+ ? new Date(chunk.edges_backfilled_at!).getUTCFullYear() === 2099
+ : chunk.edges_backfilled_at === null)).toBe(true);
+ }
+ }
+ }, 60_000);
+});