Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.48.3.0 fix: consistent read policies and reliable verification (#4941)
Garry Tanede85e2e8c51
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 69fbcaebaf..ffc95bc47d 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.48.2.0",+ "version": "0.48.3.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.jsonindex 18e7845d0b..81528055fc 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain",- "version": "0.48.2.0",+ "version": "0.48.3.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/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex d0df76bd11..cd05ca89cd 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -20,44 +20,7 @@ concurrency:cancel-in-progress: truejobs:- # ──────────────────────────────────────────────────────────────────────- # e2e-cache-check: same content-hash skip as test.yml's cache-check, in- # its own key namespace (e2e-pass-<hash>). Doc-only pushes previously- # provisioned 3 pgvector services and spent real OpenAI/Anthropic/- # ZeroEntropy tokens in tier2; now they skip. SCHEDULED runs are exempt- # below — the nightly is a drift check against live providers and must- # run even when the tree is unchanged.- # ──────────────────────────────────────────────────────────────────────- e2e-cache-check:- runs-on: ubuntu-latest- timeout-minutes: 10- outputs:- hit: ${{ steps.lookup.outputs.cache-hit }}- hash: ${{ steps.compute.outputs.hash }}- steps:- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4- - name: Compute content hash- id: compute- run: |- HASH=$(bash scripts/ci-cache-hash.sh --verbose 2>/tmp/cache-diag)- cat /tmp/cache-diag- echo "Computed cache hash: $HASH"- echo "hash=$HASH" >> "$GITHUB_OUTPUT"- - name: Lookup actions/cache for e2e-pass-<hash>- id: lookup- uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3- with:- key: e2e-pass-${{ steps.compute.outputs.hash }}- path: .e2e-cache-marker- lookup-only: true- - name: Cache status- run: |- if [ "${{ steps.lookup.outputs.cache-hit }}" = "true" ]; then- echo "✓ e2e cache HIT for hash ${{ steps.compute.outputs.hash }} — e2e jobs will skip (unless scheduled)"- else- echo "✗ e2e cache MISS for hash ${{ steps.compute.outputs.hash }} — e2e suite will run"- fi-+ # Test results are never cached; selection and live-provider state vary by run.jsonb-parity:# Dedicated required guard for the JSONB double-encode bug-class (#2339).# PGLite parses a double-encoded jsonb string silently, so this assertion can@@ -66,8 +29,6 @@ jobs:# Postgres and HARD-FAILS if DATABASE_URL is missing, so the guard can never# silently skip.name: JSONB parity (#2339 regression guard)- needs: e2e-cache-check- if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'runs-on: ubuntu-latesttimeout-minutes: 15services:@@ -155,12 +116,9 @@ jobs:# PR; this job consumes the default file-selection mode and must not# change the script's exit semantics. On scheduled runs the step# early-exits green: coverage-full-e2e already runs the full glob that- # night, and a skipped-vs-success result here would break the- # e2e-cache-write `success()` gate that nightly writes rely on.+ # night. The aggregate requires that full-corpus execution on schedules.selected-e2e:name: Selected E2E (diff-relevant)- needs: e2e-cache-check- if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'runs-on: ubuntu-latesttimeout-minutes: 60services:@@ -236,8 +194,6 @@ jobs:tier1:name: Tier 1 (Mechanical)- needs: e2e-cache-check- if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'runs-on: ubuntu-latesttimeout-minutes: 30services:@@ -366,8 +322,7 @@ jobs:# stays in front as the broken-build SPEND gate: this job burns real# OpenAI/Anthropic/ZeroEntropy tokens and must not fire when the build# can't even pass the cheapest DB guard.- needs: [e2e-cache-check, jsonb-parity]- if: needs.e2e-cache-check.outputs.hit != 'true' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'+ needs: jsonb-parityruns-on: ubuntu-latesttimeout-minutes: 30services:@@ -486,7 +441,7 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile- name: Coverage shard ${{ matrix.shard }}/10run: scripts/test-shard.sh ${{ matrix.shard }} 10env:@@ -510,7 +465,7 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile- run: bun run test:serialenv:COVERAGE_DIR: ${{ runner.temp }}/coverage@@ -533,11 +488,12 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile# Separate coverage dirs per bun process (a reused dir is overwritten).- run: bun test test/eval-longmemeval-e2e.slow.test.ts --timeout=60000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slow-a- run: bun test test/entity-resolve-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slow-b- run: bun test test/entity-card-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slow-c+ - run: bun test test/eval-brainbench-e2e.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/slow-d- name: Write coverage lane manifestrun: |printf '{"lane":"slow","sha":"%s","lcovCount":%s,"complete":true}\n' \@@ -582,7 +538,7 @@ jobs:test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.versionkey: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/migrate.ts', 'src/core/pglite-schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts') }}- - run: bun install+ - 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# env scrub keeps non-GBRAIN vars, so COVERAGE_DIR and@@ -613,13 +569,13 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 15steps:- - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4with:fetch-depth: 0 # baseline gate reads git show origin/master:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile- name: Download per-lane coverage artifactsuses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0with:@@ -652,61 +608,40 @@ jobs:if-no-files-found: ignoreoverwrite: true- # ──────────────────────────────────────────────────────────────────────- # e2e-cache-write: seals e2e-pass-<hash> only when every gated job- # succeeded (writing earlier would bless states the suite never proved).- # Scheduled runs may also write: a nightly green at an unchanged hash is- # the same proof a push green is.- # ──────────────────────────────────────────────────────────────────────- e2e-cache-write:- needs: [e2e-cache-check, jsonb-parity, tier1, tier2, selected-e2e]- if: success() && needs.e2e-cache-check.outputs.hit != 'true'- runs-on: ubuntu-latest- timeout-minutes: 5- steps:- - name: Create cache marker- run: |- mkdir -p .e2e-cache-marker- echo "${{ needs.e2e-cache-check.outputs.hash }}" > .e2e-cache-marker/hash- echo "$GITHUB_SHA" > .e2e-cache-marker/sha- echo "$GITHUB_REF" > .e2e-cache-marker/ref- - uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3- with:- key: e2e-pass-${{ needs.e2e-cache-check.outputs.hash }}- path: .e2e-cache-marker-- # ──────────────────────────────────────────────────────────────────────- # e2e-status: the single stable "did E2E pass?" name (mirror of- # test.yml's test-status). Succeeds when the cache hit on a non-scheduled- # run, or when every gated job succeeded.- # ──────────────────────────────────────────────────────────────────────+ # The stable aggregate includes nightly execution lanes on schedules.+ # Coverage reporting itself remains advisory; failed tests never do.e2e-status:- needs: [e2e-cache-check, jsonb-parity, tier1, tier2, selected-e2e]+ needs: [jsonb-parity, tier1, tier2, selected-e2e, coverage-full-unit, coverage-full-serial, coverage-full-slow, coverage-full-e2e]if: always()runs-on: ubuntu-latesttimeout-minutes: 5steps:- name: Aggregate resultrun: |- HIT="${{ needs.e2e-cache-check.outputs.hit }}"JSONB="${{ needs.jsonb-parity.result }}"TIER1="${{ needs.tier1.result }}"TIER2="${{ needs.tier2.result }}"SELECTED="${{ needs.selected-e2e.result }}"EVENT="${{ github.event_name }}"- echo "e2e-cache-check.hit=$HIT event=$EVENT"+ echo "event=$EVENT"echo "jsonb-parity=$JSONB tier1=$TIER1 tier2=$TIER2 selected-e2e=$SELECTED"- # schedule AND workflow_dispatch always run the real suite — a- # manual dispatch is an explicit ask for a live run, so a cache- # hit must not report green-without-running for either.- if [ "$HIT" = "true" ] && [ "$EVENT" != "schedule" ] && [ "$EVENT" != "workflow_dispatch" ]; then- echo "✓ e2e cache HIT for hash ${{ needs.e2e-cache-check.outputs.hash }} — E2E green"- exit 0- fifor r in "$JSONB" "$TIER1" "$TIER2" "$SELECTED"; doif [ "$r" != "success" ]; thenecho "✗ gated e2e job did not succeed (got $r) — E2E fail"exit 1fidone- echo "✓ all e2e jobs succeeded — E2E green"+ if [ "$EVENT" = "schedule" ]; then+ FULL_UNIT="${{ needs.coverage-full-unit.result }}"+ FULL_SERIAL="${{ needs.coverage-full-serial.result }}"+ FULL_SLOW="${{ needs.coverage-full-slow.result }}"+ FULL_E2E="${{ needs.coverage-full-e2e.result }}"+ echo "full-unit=$FULL_UNIT full-serial=$FULL_SERIAL full-slow=$FULL_SLOW full-e2e=$FULL_E2E"+ for r in "$FULL_UNIT" "$FULL_SERIAL" "$FULL_SLOW" "$FULL_E2E"; do+ if [ "$r" != "success" ]; then+ echo "✗ scheduled full-corpus job did not succeed (got $r) — E2E fail"+ exit 1+ fi+ done+ fi+ echo "✓ all required e2e jobs succeeded — E2E green"diff --git a/.github/workflows/heavy-tests.yml b/.github/workflows/heavy-tests.ymlindex 139d5db22f..0de8bcf5f4 100644--- a/.github/workflows/heavy-tests.yml+++ b/.github/workflows/heavy-tests.yml@@ -677,7 +677,7 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile- name: Build gbrain (compile once for the doors)run: |@@ -774,7 +774,7 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile- name: Prepare evidence dirrun: |@@ -992,7 +992,7 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile- name: Build gbrainrun: |bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.tsdiff --git a/.github/workflows/osv-scanner.yml b/.github/workflows/osv-scanner.ymlindex 1e242873b8..49d2181fa6 100644--- a/.github/workflows/osv-scanner.yml+++ b/.github/workflows/osv-scanner.yml@@ -12,6 +12,8 @@ on:paths:- 'bun.lock'- 'package.json'+ - 'admin/bun.lock'+ - 'admin/package.json'schedule:- cron: '30 6 * * 1' # weekly, Monday 06:30 UTCworkflow_dispatch:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 0c70f105e7..6c8863121e 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -299,7 +299,7 @@ jobs:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2with:bun-version: 1.3.13- - run: bun install+ - run: bun install --frozen-lockfile- name: Drift gate — committed plugin tree matches the generatorrun: bash scripts/check-plugin-tree.sh- name: Assemble the plugin dist treediff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex f38741450e..b44fb2b229 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -24,63 +24,8 @@ concurrency:cancel-in-progress: truejobs:- # ──────────────────────────────────────────────────────────────────────- # cache-check: runs first, computes the content hash of every tracked- # file EXCEPT the deny-list (CHANGELOG.md, README.md, docs/**/*.md, etc.- # — see scripts/ci-cache-hash.sh for the full list). Looks up- # `ci-pass-<hash>` in actions/cache; if hit, the test matrix + verify- # + serial jobs all skip and test-status reports green immediately.- # If miss, the full suite runs and cache-write seals it on success.- #- # Hit rate covers re-pushes (same SHA twice), branch rebases that- # don't touch tracked code, and any branch update that touches only- # the deny-listed doc files.- # ──────────────────────────────────────────────────────────────────────- cache-check:- runs-on: ubuntu-latest- timeout-minutes: 10- outputs:- hit: ${{ steps.lookup.outputs.cache-hit }}- hash: ${{ steps.compute.outputs.hash }}- steps:- - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4- - name: Compute content hash- id: compute- run: |- # --verbose writes the "X/Y files in hash" diagnostic to stderr;- # stdout carries the 16-char hash. Capture both.- HASH=$(bash scripts/ci-cache-hash.sh --verbose 2>/tmp/cache-diag)- cat /tmp/cache-diag- echo "Computed cache hash: $HASH"- echo "hash=$HASH" >> "$GITHUB_OUTPUT"- - name: Lookup actions/cache for ci-pass-<hash>- id: lookup- uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3- with:- key: ci-pass-${{ steps.compute.outputs.hash }}- path: .ci-cache-marker- # `lookup-only: true` means we only probe whether the cache- # entry exists — we don't download it (the marker contents- # don't matter, only the key match does). `cache-hit` returns- # true only on EXACT key match (per actions/cache docs); a- # restore-keys prefix fallback would set cache-hit=false, so- # it's deliberately omitted here. Cross-branch scoping works- # naturally: PR branches can read default-branch (master)- # cache entries via exact key match when the content hash- # matches, which happens whenever the tree is doc-only- # different from a green master run.- lookup-only: true- - name: Cache status- run: |- if [ "${{ steps.lookup.outputs.cache-hit }}" = "true" ]; then- echo "✓ cache HIT for hash ${{ steps.compute.outputs.hash }} — test jobs will skip"- else- echo "✗ cache MISS for hash ${{ steps.compute.outputs.hash }} — full suite will run"- fi-+ # Re-run checks for every event. Only dependencies and PGLite snapshots are cached.gitleaks:- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latesttimeout-minutes: 10steps:@@ -133,8 +78,6 @@ jobs:# this into `test (1)` via `if: matrix.shard == 1`, which made shard 1# the slowest matrix worker). scripts/run-verify-parallel.sh fans out# the 20 checks via & + wait (~5s vs ~15-25s sequential).- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latesttimeout-minutes: 12steps:@@ -174,8 +117,6 @@ jobs:# sequential: an 8.5-minute job whose serialization the quarantine# contract never required). Lives in its own runner so the matrix shards# aren't carrying the serial tail.- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latest# 25, not 15: on smaller runners the memory clamp in# scripts/run-serial-tests.sh sizes the pool to 1, and the fully@@ -233,8 +174,6 @@ jobs:# atom doesn't dominate a shard's wallclock. Companion file# test/eval-longmemeval.slow.test.ts (the pure-bucket half) stays in# the matrix because it's light (~42s).- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latesttimeout-minutes: 12steps:@@ -279,8 +218,6 @@ jobs:# + deleting the CI-gate-duplicated full-corpus test) cut it to ~72s# local, still far past the ~40s keep-in-matrix bar. Same pattern as# slow-eval-longmemeval above.- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latesttimeout-minutes: 12steps:@@ -338,12 +275,10 @@ jobs:# — a PR cannot rewrite the thing it's compared against. Exit 1 blocks the# merge until the regression is fixed or blessed (justification in the# updated baseline / fixture diff in corpus-bless mode).- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latesttimeout-minutes: 10 # ~15s hermetic run; matches the per-job-timeout hardening (#2254)steps:- - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4- name: Fetch origin/master baseline ref (shallow)# The gate reads ONE file via `git show origin/master:...` — a depth-1# fetch of the master ref replaces the previous full 3700-commit clone.@@ -374,8 +309,6 @@ jobs:# subdivisible without weakening the perf guarantee). Pulled out of the# matrix (see scripts/test-shard.sh) so a single 159s atom doesn't# dominate a shard's wallclock. Runs in parallel with the matrix.- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latesttimeout-minutes: 12steps:@@ -439,7 +372,7 @@ jobs:# slow-entity-resolve-perf (~2.6 min) ≈ 4.8 min.## Concurrency budget: 10 shards + verify + serial + slow-eval +- # slow-entity-resolve-perf + gitleaks + cache-check + cache-write ++ # slow-entity-resolve-perf + slow-brainbench-e2e + brainbench + gitleaks +# test-status = ~18 jobs × 2 concurrent PRs = 36. GitHub free-tier# caps at ~20 concurrent jobs, so multi-PR days will see some queue# pressure. Single-PR runs are unaffected.@@ -448,8 +381,6 @@ jobs:# (replaces FNV-1a path hash). Weights live in scripts/test-weights.json,# mined from real CI logs via scripts/mine-shard-weights.ts. Missing# weights fall back to corpus median — new test files work immediately.- needs: cache-check- if: needs.cache-check.outputs.hit != 'true'runs-on: ubuntu-latest# 22, not 15: under parallel PR load the PGLite WASM cold-starts stretch a# shard past 15 min while every test is still passing — the timeout then@@ -498,19 +429,18 @@ jobs:# lanes) into one honest number, renders it to the step summary, and runs# the diff + baseline gates in report-only mode (COVERAGE_GATE_ENFORCE=0).# ADVISORY during the report-only window: deliberately NOT in test-status's- # required set or cache-write's needs — a coverage infra flake must not- # redden branch protection or block the ci-pass marker until the gate- # graduates (the graduation PR adds it to both and flips ENFORCE).+ # required set — coverage reporting stays advisory until the gate+ # graduates (that PR adds it to the aggregate and flips ENFORCE).# `always()` is load-bearing: without it, a failed shard skips this job at# exactly the moment the (degraded) report matters most.# ──────────────────────────────────────────────────────────────────────coverage-report:- needs: [cache-check, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, test]- if: always() && needs.cache-check.outputs.hit != 'true'+ needs: [serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, test]+ if: always()runs-on: ubuntu-latesttimeout-minutes: 10steps:- - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4with:fetch-depth: 0 # diff gate needs origin/master; baseline gate reads git show origin/master:- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2@@ -560,46 +490,16 @@ jobs:if-no-files-found: ignoreoverwrite: true- # ──────────────────────────────────────────────────────────────────────- # cache-write: ONLY runs when every gated job succeeded. Writes the- # cache entry under `ci-pass-<hash>` so future runs at the same hash- # hit cache. Codex's load-bearing correctness point: writing the- # cache before the matrix completes would permanently bless bad states- # (a future run at the same hash would skip tests because of a cache- # entry written when tests hadn't actually passed).- # ──────────────────────────────────────────────────────────────────────- cache-write:- needs: [cache-check, gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test]- if: success() && needs.cache-check.outputs.hit != 'true'- runs-on: ubuntu-latest- timeout-minutes: 5- steps:- - name: Create cache marker- run: |- mkdir -p .ci-cache-marker- echo "${{ needs.cache-check.outputs.hash }}" > .ci-cache-marker/hash- echo "$GITHUB_SHA" > .ci-cache-marker/sha- echo "$GITHUB_REF" > .ci-cache-marker/ref- - uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3- with:- key: ci-pass-${{ needs.cache-check.outputs.hash }}- path: .ci-cache-marker-- # ──────────────────────────────────────────────────────────────────────- # test-status: the single user-visible "did CI pass?" check.- # Runs always (if: always()), succeeds when EITHER cache-check.hit==true- # OR all gated jobs (gitleaks, verify, serial-tests, test) succeeded.- # Branch protection (when configured) gates on this single job name.- # ──────────────────────────────────────────────────────────────────────+ # The stable aggregate succeeds only when every required lane ran successfully.+ # Coverage percentages remain advisory until their separate graduation.test-status:- needs: [cache-check, gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test]+ needs: [gitleaks, verify, serial-tests, slow-eval-longmemeval, slow-entity-resolve-perf, slow-brainbench-e2e, brainbench, test]if: always()runs-on: ubuntu-latesttimeout-minutes: 5steps:- name: Aggregate resultrun: |- HIT="${{ needs.cache-check.outputs.hit }}"GITLEAKS="${{ needs.gitleaks.result }}"VERIFY="${{ needs.verify.result }}"SERIAL="${{ needs.serial-tests.result }}"@@ -608,13 +508,7 @@ jobs:SLOW_BRAINBENCH="${{ needs.slow-brainbench-e2e.result }}"BRAINBENCH="${{ needs.brainbench.result }}"TEST="${{ needs.test.result }}"- echo "cache-check.hit=$HIT"echo "gitleaks=$GITLEAKS verify=$VERIFY serial-tests=$SERIAL slow-eval-longmemeval=$SLOW_EVAL slow-entity-resolve-perf=$SLOW_PERF slow-brainbench-e2e=$SLOW_BRAINBENCH brainbench=$BRAINBENCH test=$TEST"- if [ "$HIT" = "true" ]; then- echo "✓ cache HIT for hash ${{ needs.cache-check.outputs.hash }} — CI green"- exit 0- fi- # Cache miss: every gated job must have succeeded.for r in "$GITLEAKS" "$VERIFY" "$SERIAL" "$SLOW_EVAL" "$SLOW_PERF" "$SLOW_BRAINBENCH" "$BRAINBENCH" "$TEST"; doif [ "$r" != "success" ]; thenecho "✗ gated job did not succeed (got $r) — CI fail"diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 39d31f7e57..ea2cfcce7e 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.48.2.0 -->+<!-- gbrain-runbook-stamp: 0.48.3.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f398593484..9ee200ad6d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,85 @@All notable changes to GBrain will be documented in this file.+## [0.48.3.0] - 2026-09-06++**Your brain applies consistent access rules, and verification must run before it reports success.**++Agents receive material allowed for their current connection when they read,+search, or follow relationships through your brain. This release also makes+remote calls stop when cancelled and keeps application errors intact so your+agent can explain the actual problem. Existing installations receive the changes+on upgrade, with no database schema migration or new service to configure.++Repeated searches now perform fresh retrieval,+so they can take longer and use more provider tokens. Stored contradiction+reports are available only to trusted local callers searching without a source+filter. Other callers receive an availability note. Your stored cache records+remain available for maintenance, but changing a cache setting cannot turn+semantic result caching back on in this release.++Existing search chunks must be rebuilt with the corrected indexer before+chunk-based remote retrieval resumes. Direct page reads remain available under+the connection's access rules. Remote importance scores reflect permitted active+takes, so they can differ from unrestricted local scores. The upgrade guide+explains these changes and the existing reindex options. Code definition,+reference, caller/callee and flow/blast tools are temporarily available only to+trusted local callers. Remote search also omits optional code-graph expansion.++### What to expect++| Action | Result after upgrading |+|---|---|+| Repeat a search | Fresh retrieval; semantic result caching reports disabled |+| Request a stored contradiction report remotely | A note explaining its temporary availability |+| Cancel a remote request | Discovery, connection and tool work stop with the request |+| Rebuild existing search chunks | Remote chunk retrieval resumes after a successful rebuild |+| Use code-inspection tools remotely | A temporary availability message; trusted local tools still work |+| Run the full local CI command | Required serial, slow, unit and database tests execute |++## To take advantage of v0.48.3.0++**Say to your agent:** *"upgrade gbrain and verify my brain's search configuration"*.++```bash+gbrain upgrade+gbrain doctor+gbrain search modes+gbrain cache stats+```++Agents should read `skills/migrations/v0.48.3.0.md` for the verification steps and+temporary behavior changes and optional chunk-rebuild steps. No provider-key+changes are required. If health checks fail, follow the printed remediation+before retrying.++### Itemized changes++#### Fixed++- Apply consistent access rules to content, history, relationships and search+ metadata across both storage engines.+- Keep protected body sections consistent across agent-facing reads and chunk+ creation, with bounded processing time for repeated sections.+- Refresh remote authentication only for a transport authentication failure,+ and preserve application errors and cancellation throughout the request.++#### Changed++- Temporarily disable semantic result-cache reads and writes while keeping+ ordinary search and cache maintenance available.+- Limit stored contradiction reports to trusted, unscoped local callers.++#### For contributors++- Remove successful-test result caches and require successful execution of the+ applicable CI lanes. Coverage percentages remain advisory.+- Include serial, slow and transaction-mode PgBouncer checks in local CI;+ preserve failures and complete shard logs.+- Isolate routing fixtures from inherited provider configuration and local+ environment files, with bounded diagnostics that redact credentials.+- Keep frozen dependency installation and scan both root and admin manifests.+## [0.48.2.0] - 2026-09-02**Your search reranker now runs on Voyage, and every surface tells you whether it is actually running.**diff --git a/CLAUDE.md b/CLAUDE.mdindex 89867cbc5e..4a5a5186ac 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -232,15 +232,16 @@ Mismatches (tokenmax+Haiku, conservative+Opus) waste capacity differentlyexpensive one.tokenmax adds ~\$1.50 per 1K queries in Haiku expansion calls on top of-the matrix (\$15/mo @ 10K). Cache hits cut all numbers ~50%. **The matrix+the matrix (\$15/mo @ 10K). Semantic result caching is temporarily disabled; budget for fresh retrieval on every query. **The matrixhas three verbatim homes: this section, the `gbrain init` picker copy(`src/commands/init-mode-picker.ts`), and `INSTALL_FOR_AGENTS.md` Step3.5** — update all three when refreshing.**Per-query math vs real-world spend.** The matrix above is what anisolated benchmark would measure. Real agent loops with disciplined-Anthropic prompt caching see 50-80% discount on top (cache hits skip-downstream entirely). The realistic-scale anchor in+Anthropic prompt caching see 50-80% discount on top through lower+cached-input charges. This is separate from GBrain's disabled semantic result+cache. The realistic-scale anchor in`docs/eval/SEARCH_MODE_METHODOLOGY.md` walks the natural pairings atsingle-power-user volume (~860 turns/mo): tokenmax+Opus ~\$700/mo,balanced+Sonnet ~\$430/mo, conservative+Haiku ~\$170/mo. Setups WITHOUT@@ -258,6 +259,8 @@ per `[CDX-5+6]` in `~/.claude/plans/lets-take-a-look-validated-parrot.md` — so`gbrain eval replay` and `gbrain eval longmemeval` test the same mode-affectedbehavior as the production `query` op.+**Effective cache availability:** semantic result lookup and writes are temporarily disabled in the shared wrapper, regardless of mode, config, or `use_cache`. Stored rows and maintenance commands remain. `cache.status`, cache statistics and the mode dashboard report disabled. The following cache-key notes describe retained storage machinery, not active response reuse.+**Cache-key contamination hotfix `[CDX-4]`:** migration v56 added a`knobs_hash` column to `query_cache`. The lookup filter is now`WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $` so adiff --git a/README.md b/README.mdindex 6dbde0b720..6961a83809 100644--- a/README.md+++ b/README.md@@ -171,6 +171,13 @@ Postgres-at-scale, Supabase, and thin-client setup paths live in [`docs/INSTALL.GBrain exposes nearly all of its 100+ operations as MCP tools (stdio and HTTP; a handful of local-only ops stay CLI-side) — or exactly the seven memory verbs with `--surface verbs`. The specific snippet depends on which client you use:+**Upgrading an existing brain:** existing search chunks need rebuilding before+remote chunk retrieval resumes. Semantic result caching is temporarily disabled;+stored contradiction reports and code-inspection tools have local-only limits.+Follow the [upgrade recovery guide](skills/migrations/v0.48.3.0.md) for rebuild+commands, embedding costs, and the restrictions that remain after rebuilding.+**Say to your agent:** *"Upgrade gbrain and check whether my search index needs rebuilding."*+- **[Claude Code](docs/mcp/CLAUDE_CODE.md)** — plugin: `/plugin marketplace add garrytan/gbrain` + `/plugin install gbrain@gbrain` (MCP + skills; persona variants `gbrain-coding` / `gbrain-daily` install curated subsets — pick exactly one gbrain plugin). Marketplace-free skills: `gbrain skillpack scaffold --harness claude-code` copies a persona-curated skill set into your user-scope skills dir with a local-edit-respecting update lens. Or local one-liner: `claude mcp add gbrain -- gbrain serve` (zero server, zero tunnel). Remote with just a bearer token: `gbrain connect https://your-host/mcp --token gbrain_xxx` prints a paste-ready block (or `--install` wires it up and smoke-tests the token).- **[Codex](docs/mcp/CODEX.md)** — plugin (recommended): `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain` installs the MCP server AND the curated skill set. Or connect-only: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`); Codex reads the bearer from `$GBRAIN_REMOTE_TOKEN` at runtime, so the token never lands in Codex config.- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve"]}` to your MCP config.@@ -332,7 +339,7 @@ gbrain schema use my-pack # activate**Say to your agent:** *"My schema isn't matching my notes — propose new types from my corpus"* — *"Add a page type for lab results to my brain's schema."* The schema-author skill runs the detect → suggest → review flow for you.-The active pack threads through every read + write path: `parseMarkdown` infers page type from the pack's path prefixes; `whoknows` scopes expert routing to types declared `expert_routing: true`; `extract_facts` runs only on `extractable: true` types; the search cache folds the pack name + version into its key so cross-pack contamination is structurally impossible. Switch packs and the brain re-interprets itself; switch back and nothing's lost.+The active pack threads through every read + write path: `parseMarkdown` infers page type from the pack's path prefixes; `whoknows` scopes expert routing to types declared `expert_routing: true`; `extract_facts` runs only on `extractable: true` types. The retained search-cache key includes the pack name + version, but semantic result reuse is temporarily disabled. Switch packs and the brain re-interprets itself; switch back and nothing's lost.Seven-tier resolution chain (per-call flag → env var → per-source DB key → brain-wide DB key → `gbrain.yml` → `~/.gbrain/config.json` → `gbrain-base` default). Full reference + authoring guide: [`docs/architecture/schema-packs.md`](docs/architecture/schema-packs.md).diff --git a/TODOS.md b/TODOS.mdindex 096295c73c..75145e595b 100644--- a/TODOS.md+++ b/TODOS.md@@ -1495,11 +1495,10 @@ deferred M-effort issues above are NOT repeated here.- [ ] **P1 — Graduate the diff-coverage gate to blocking (time-boxed 2 weeks from merge).****What:** flip `COVERAGE_GATE_ENFORCE` to `'1'` in test.yml's coverage-report job, add- coverage-report to test-status's required-success set and cache-write's needs, and replace+ coverage-report to test-status's required-success set, and replacethe provisional `scripts/coverage-baseline.json` corpus sections with CI-derived values via`scripts/update-coverage-baseline.ts --promote`. **Criteria:** 10 consecutive green- coverage-report runs on PRs (master runs are structurally cache-skipped — a squash-merged- tree equals its green PR tree, so the ci-pass marker hits; never count master runs) plus 3+ coverage-report runs on PRs (count PR receipts, not master runs) plus 3green nightly fullCorpus merges and zero merge-infrastructure failures. **Why:** the 80%diff gate is built and reporting on every PR; blocking is a one-line flip once themeasurement machinery has receipts. Review `scripts/coverage-gate-exemptions.txt` against@@ -8526,33 +8525,27 @@ covers DEAD logs; go-forward capture beyond Claude Code is deliberately absent.read leaks on its first runs; the write side has had zero equivalentsweep pressure. Effort: M. Depends on: nothing (read-side sweep alreadylanded as the pattern to copy).-- [ ] **P2 — source-scope + row-grain hardening for the salience/anomaly/expert- arms.** Four classes surfaced by the read-side sweep's review and deferred- from the leak PR because each is a family-wide semantics change: (a)- `get_recent_salience`/`find_anomalies` never thread `sourceScopeOpts(ctx)`- into the engine reads (pre-existing v0.34.1 source-isolation class — a- source-bound remote client sees every source's world rows); (b) the whole- `findPrivateOnlySlugs` family is slug-grain, so a slug world-in-source-A /- private-in-source-B serves the PRIVATE row's own title through row-grain- arms (rows carry source_id — a composite-key filter fixes it, but must land- family-wide or semantics diverge across ops); (c) the private post-filters- run AFTER the engine's LIMIT, so remote callers can get fewer than `limit`- rows while world rows exist below the cutoff (push the- `privatePagesFilterFragment` predicate into the engine reads, or over-fetch);- (d) the two unscoped private-visibility probes are slug-only queries- with no slug-leading index (`pages_source_slug_key` leads on source_id) —- add a `pages(slug)` btree index when (a)-(c) land; (e) `find_anomalies`- baselines (`baseline_mean`/`baseline_stddev`) are computed private-inclusive- in both engines, so a mixed cohort's baseline discloses aggregate private- activity volume AND a genuinely-anomalous world spike can be suppressed when- concurrent private activity inflated the baseline — world-only cohort- aggregation belongs in the same engine pass as (a). Effort: M-L. Depends on:- nothing, but coordinate with the P3 chokepoint below rather than duplicating.+- [x] **P2 — source-scope + row-grain hardening for salience/anomaly/experts** — completed v0.48.3.0.+ Corrective-release implementation uses the shared concrete-page SQL policy+ before ranking, limits and baseline aggregation, with final expert admission.+ Slug-only authorization is removed from these data-bearing reads; existing+ source/ID indexes support batched queries, so no migration is needed.+- [ ] **P1 — restore semantic results and remote contradiction reports only with+ complete provenance.** Response dependencies must include metadata, holder+ policy, query context and judgment-cache inputs/keys. Current containment+ bypasses semantic result lookup/write and restricts stored reports to trusted+ unscoped local reads. Pair-only validation is insufficient. Own reviewed plan.+- [ ] **P1 — restore remote code inspection and structural expansion with full+ read-policy enforcement.** Authorize concrete source/page/chunk rows and every+ recursive contributor, including traversal-cache dependencies, before+ restoring remote definition/reference/caller/callee/flow/blast operations and+ optional search expansion. The v0.48.3.0 restriction preserves trusted local+ commands. Own reviewed plan; no source-grant or chunk-rebuild override.- [ ] **P3 — runtime chokepoint for world-only filtering.** Privacy is- enforced per-arm/per-column at N call sites (get_page/fetch strip, delta- page arm, find_orphans/get_recent_salience/find_anomalies post-filters,- context_pack/delta include_private gating); each new remote surface leaks- until someone notices — the class has now recurred five times. Move the+ enforced through shared body sanitizers and SQL read policy, but each read+ path must still thread its caller policy (including analytics and+ context_pack/delta include_private gating). New surfaces can omit that+ policy. Move theworld-only filter to a single dispatch-layer interceptor (or anengine-level read-scope wrapper) so new ops are world-only BY DEFAULT.High blast radius: touches every read op; do NOT attempt until bothdiff --git a/VERSION b/VERSIONindex 75d21dd4bb..8f62e02292 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.48.2.0\ No newline at end of file+0.48.3.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 3eed9403a4..3a902e2e4d 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -7,13 +7,14 @@ only.### Test command tiers-Seven test command tiers, each with a clear scope:+Eight test command tiers, each with a clear scope:| Command | What it runs | Wallclock | When to use ||---|---|---|---|| `bun run test` | Parallel unit-test fast loop. Sharded fan-out via `scripts/run-unit-parallel.sh` (default 4 shards — CPU-detected, clamped to a max of 8; 4 matches CI's fan-out and avoids PGLite WASM-init contention), then a serial pass over `*.serial.test.ts`. Excludes `*.slow.test.ts` and `test/e2e/*`. No pre-checks, no typecheck. Builds/refreshes the PGLite schema snapshot BEFORE the shard fan-out and exports `GBRAIN_PGLITE_SNAPSHOT` so PGLite-booting files restore a baked schema instead of replaying every migration (~3.5x per booting file; see "PGLite schema snapshot" below). Opt out: `GBRAIN_NO_SNAPSHOT=1`. Memory-safe by default: total concurrency (shards × intra-shard width) is capped to available memory at `GBRAIN_TEST_MEM_PER_FILE_MB` (default 1536 — a PGLite WASM instance) per concurrent slot, shedding INTRA-SHARD width first and shards only after it (bun's `--max-concurrency` bounds only `test.concurrent` tests — 1 file in the corpus — so intra width is nearly free to shed, while every dropped shard removes a whole bun process of real fan-out; shedding shards first would collapse a 16GB box to a serial 1×4 run, measured 3.25× slower than 4×1 on the same machine). Two phantom-failure classes are automatically re-run serially (the rescue pass): failures carrying the WASM out-of-memory signature, and shards killed externally (SIGTERM/SIGKILL well before the shard timeout — sibling workspaces' process cleanup, memory jetsam). On machines without coreutils `timeout`, the fallback watchdog drops a `.watchdog` sentinel before TERMing a shard at the cap so the WEDGED/EXIT-HANG classifier stays reachable there (a bare rc=143 would otherwise read as a plain failure). Phantoms pass serially and the run goes green with an `oom_rescued` note; real failures fail again serially and stay red. Knobs: `GBRAIN_TEST_NO_MEM_ADAPT=1`, `GBRAIN_TEST_NO_OOM_FALLBACK=1`, `GBRAIN_TEST_MAX_CONCURRENCY` (intra-shard, default 4), `GBRAIN_TEST_SHARD_TIMEOUT` / `GBRAIN_TEST_SHARD_KILL_AFTER`, plus `--shards N` / `--max-concurrency N` / `--dry-run` script args. | a few minutes on a Mac dev box | Inner edit loop. Default. || `bun run verify` | CI's authoritative pre-test gate set, fanned out by `scripts/run-verify-parallel.sh` through a bounded worker pool (default `detect_cpus`; override `GBRAIN_VERIFY_MAX_PARALLEL`) with the heavy checks ordered first (typecheck, the two compile-embed checks, admin build, fuzz bundles, guard self-tests, the PGLite-booting chronicle eval check, whole-tree greps). The battery includes the deterministic `check:eval-chronicle` eval gate; `check:eval-canary` is deliberately NOT in the battery (its test-file twin `test/eval-canary.test.ts` spawns the identical runner in the unit matrix, and CI's verify job and matrix always run together — the package script stays for on-demand runs, so `verify`-only local callers should know the canary rides the unit lane instead). The `CHECKS` array in that script is the single source of truth — CI literally calls `bun run verify` in a dedicated job. | ~50s (pool-bounded; longest check dominates) | Before pushing; before `/ship`. |-| `bun run test:full` | `verify && bun run test && bun run test:slow && [smart e2e]`. The local equivalent of "everything CI runs." Smart e2e: runs e2e only when `DATABASE_URL` is set; else loud skip notice to stderr. | ~3-5min depending on slow + e2e | Pre-merge sanity, before opening a PR. |+| `bun run test:full` | `verify && bun run test && bun run test:slow && [smart e2e]`. Smart e2e runs only when `DATABASE_URL` is set and propagates its failure; otherwise it prints a skip notice to stderr. Use `ci:local` to provision the databases and require PgBouncer execution. | ~3-5min depending on slow + e2e | Pre-merge sanity, before opening a PR. |+| `bun run ci:local` | Independent host gitleaks scans, then frozen dependencies, guards/typecheck, the complete serial and slow lanes, and four unit/E2E shards inside Docker. Each E2E shard has its own pgvector database; selected PgBouncer tests must execute against the transaction-mode pooler. Unit, serial, and slow lanes have database URL overrides unset. Any failed stage fails the command. Complete shard logs survive container teardown under `.context/ci-local-shards/`. `ci:local:diff` narrows E2E selection; `--no-shard` runs unit/E2E sequentially. Doc-only diffs still require successful gitleaks scans. | Depends on the full corpus | Full local gate before shipping. || `bun run test:slow` | Just the `*.slow.test.ts` set (intentional cold-path correctness checks). | seconds-to-minutes | When touching slow-path code. || `bun run test:serial` | Just the `*.serial.test.ts` set (cross-file-contention quarantine; one bun process per file for true module-registry isolation), run through a POOL of concurrent per-file processes — the isolation is per-process, not per-machine. Dispatch is heaviest-first (LPT) from the advisory `scripts/serial-weights.json` (seconds; mined from the `.context/serial-durations.txt` table each run banks; absent/corrupt weights fall back to discovery order, absent keys to the corpus p75 — scheduling only, never correctness; LPT order + the corrupt-weights fail-soft are pinned by `test/scripts/run-serial-pool.test.ts`). Pool defaults to `min(detect_cpus, 4)` then memory-adapts (same doctrine as the parallel runner); a small growth-guarded set of files (machine-global state or contention-critical timing — see the justified `EXCLUSIVE_FILES` list in `scripts/run-serial-tests.sh`, capped at 3 by `test/scripts/serial-files.test.ts`) runs on a sequential EXCLUSIVE lane after the pool. Per-test timeout 120s (pooled contention headroom); each pooled file is wall-clock-killed at 300s (`timeout -k`, exit-hang containment). Externally-killed files (exit 143/137 or a missing exit sentinel — sibling-workspace cleanup, memory jetsam) get ONE sequential rescue re-run, mirroring the parallel runner's doctrine: phantoms stay green with a rescue note, real failures stay red. Prints per-file PASS lines plus a top-10 slowest-files list. Knobs: `GBRAIN_SERIAL_POOL=N` (explicit pool width — bypasses the memory clamp; `1` restores fully-sequential), `GBRAIN_SERIAL_FILE_TIMEOUT`. | a few minutes for all ~220 files at pool=4 | Debugging quarantined files; CI's serial-tests job. || `bun run test:e2e` | Real Postgres E2E. Requires Docker + `DATABASE_URL`. Sequential within a shard; `SHARD=N/M` fans out against separate databases (ci-local runs 4 containers). Activates the PGLite snapshot like every other runner (per-file cold-path opt-outs where the test asserts the path TO post-initSchema state), exporting it as an ABSOLUTE path so CLI children spawned with varying cwd still find it. | ~5-10min | Pre-ship; nightly. |@@ -149,7 +150,7 @@ there even though they pass on Linux and macOS.### CI vs local: intentionally divergent file sets-- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 10 matrix shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; files with no mined weight fall back to the p75 file weight so a new unweighted file can't silently unbalance a shard) and INCLUDES `*.slow.test.ts` (the three outlier slow files — longmemeval, entity-resolve-perf, brainbench-e2e — run as dedicated jobs alongside the matrix) plus `evals/**/*.test.ts` (keyless-allowlist-gated — `test/scripts/evals-collection.test.ts`). Each shard's bun process is bounded by `--max-concurrency` (`GBRAIN_TEST_MAX_CONCURRENCY`, default 4). Every bun-test job — matrix shards, serial-tests, verify, the slow/eval jobs — activates the PGLite schema snapshot (built in-runner via `scripts/lib/test-env.sh`; the brainbench gate brings its own in-memory PGLite and skips it; the ~42MB tar is also cached across jobs via actions/cache, with the runner's own hash check staying authoritative). CI EXCLUDES `*.serial.test.ts` from the shards and runs them in the pooled `serial-tests` job via `bun run test:serial` — one bun process per file preserves the `mock.module` quarantine; the pool runs those processes concurrently. `bun run verify` gets its own job too, as does the BrainBench memory-conformance gate (`brainbench` job → `scripts/ci-brainbench-gate.sh`, hermetic in-memory PGLite, ~15s), which compares HEAD's fresh run against master's committed baseline (`evals/brainbench/baselines/main.json`) — the `test-status` aggregate checks its result explicitly. E2E (`.github/workflows/e2e.yml`) mirrors the content-hash skip in its own `e2e-pass-<hash>` namespace (scheduled nightly runs are exempt and always run), runs tier1 and tier2 in parallel with the jsonb-parity job in front of tier2 as the token-spend gate, and aggregates through `e2e-status`. CI is the ground truth for "did everything pass."+- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 10 matrix shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; files with no mined weight fall back to the p75 file weight so a new unweighted file can't silently unbalance a shard) and INCLUDES `*.slow.test.ts` (the three outlier slow files — longmemeval, entity-resolve-perf, brainbench-e2e — run as dedicated jobs alongside the matrix) plus `evals/**/*.test.ts` (keyless-allowlist-gated — `test/scripts/evals-collection.test.ts`). Each shard's bun process is bounded by `--max-concurrency` (`GBRAIN_TEST_MAX_CONCURRENCY`, default 4). Every bun-test job — matrix shards, serial-tests, verify, the slow/eval jobs — activates the PGLite schema snapshot (built in-runner via `scripts/lib/test-env.sh`; the brainbench gate brings its own in-memory PGLite and skips it; the ~42MB tar is also cached across jobs via actions/cache, with the runner's own hash check staying authoritative). CI EXCLUDES `*.serial.test.ts` from the shards and runs them in the pooled `serial-tests` job via `bun run test:serial` — one bun process per file preserves the `mock.module` quarantine; the pool runs those processes concurrently. `bun run verify` gets its own job too, as does the BrainBench memory-conformance gate (`brainbench` job → `scripts/ci-brainbench-gate.sh`, hermetic in-memory PGLite, ~15s), which compares HEAD's fresh run against master's committed baseline (`evals/brainbench/baselines/main.json`) — the `test-status` aggregate checks its result explicitly. E2E (`.github/workflows/e2e.yml`) always runs its applicable execution lanes, with the jsonb-parity job in front of tier2 as the token-spend gate, and aggregates through `e2e-status`. Scheduled runs also require the full-corpus lanes, including each slow suite excluded from the coverage shards (longmemeval, entity-resolve-perf, and brainbench-e2e). Both aggregates reject failures, cancellations, and unexpected skips. Dependency caches and validated PGLite snapshots remain; successful test results are never reused. CI is the ground truth for "did everything pass."- **Local fast loop** (`scripts/run-unit-shard.sh` via the parallel wrapper) uses round-robin-by-index sharding and EXCLUDES `*.slow.test.ts` AND `*.serial.test.ts`. Local trades coverage for inner-loop speed; CI catches what local skips.This divergence is intentional. Don't try to make them equal — the two scripts deliberately solve different problems. The regression test at `test/scripts/run-unit-shard.test.ts` pins what the local fast loop should and shouldn't include; `test/scripts/run-unit-parallel.test.ts` pins the wrapper's memory-adaptive concurrency and the OOM/external-kill serial rescue pass.@@ -237,7 +238,12 @@ with both corpus sections unseeded. `scripts/update-coverage-baseline.ts`scripts/render-coverage-summary.ts` to the step summary (including thebehavioral-vs-structural counts from `scripts/structural-suites.tsv`), andruns both gates with `COVERAGE_GATE_ENFORCE: '0'`. It is deliberately NOT in-`test-status` or `cache-write` needs — it cannot block a PR until graduation.+`test-status` needs — it cannot block a PR until graduation. Test results are+never cached: every run executes its required checks, while Bun dependencies+and validated PGLite snapshots remain cached. Gitleaks runs independently for+all changes, including documentation. `e2e-status` also requires the four+`coverage-full-*` execution lanes on scheduled runs; only coverage percentage+reporting remains advisory.**Bun caveats.** Bun/JSC emits line records only, so function coverage isinformational (no reliable function names). There is NO subprocess coverage:@@ -458,8 +464,8 @@ scratch home for debugging.**Provider-key strip preload.** `test/helpers/provider-keys-preload.ts` (bunfig`[test]` preload) strips the ambient provider credentials the canonical fold-recognizes (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Gemini/Google, Voyage,-OpenRouter, ZeroEntropy, DashScope, and the Azure OpenAI endpoint fields) and+recognizes, using the explicit `test/helpers/provider-env.ts` list checked+against every recipe credential/endpoint plus compatibility aliases, anddefaults `GBRAIN_MODEL_DISCOVERY=off` (respecting an explicit operatoroverride), so key-aware model routing (`resolveTierDefault`) resolvesidentically to keyless CI and latest-model discovery never makes a real@@ -470,7 +476,14 @@ Tests that want keys inject them explicitlypreload removes ambient shell state only, before any test file loads. The e2ewrapper (`scripts/run-e2e.sh`) opts back in at its boundary via`GBRAIN_TEST_KEEP_PROVIDER_KEYS=1` — e2e is the lane where real keys are-deliberate (live embed/parity tests skip-gate on them).+deliberate (live embed/parity tests skip-gate on them). The routing-only+`qm-provisioning`, `serve-http-surface-ceiling`, `serve-stdio-roundtrip` and+`thin-client` fixtures still strip provider state in every child, set both+`HOME` and `GBRAIN_HOME` to their temporary brain, and pass Bun+`--no-env-file` (including provisioned shell commands). They exercise routing+without spending provider tokens even inside the keyed nightly lane.+Fixture-specific environment overrides apply last; unrelated credentials are+preserved rather than removed with a broad key-name pattern.**Database-URL run guard.** A `bun test` invocation REFUSES to start while`DATABASE_URL` or `GBRAIN_DATABASE_URL` is ambient in the environment, because some@@ -493,7 +506,11 @@ or carry an inline name floor the coverage gate recognizes(`test/e2e/schema-drift.test.ts` keeps its own `looksLikeTestDb`, deliberatelydifferent because it also accepts `*_e2e`), and `test/db-guard-coverage.test.ts`statically scans the suite and fails when a file connects to `DATABASE_URL` and-runs destructive SQL unguarded. The heavy shell lane gets the same floor outside+runs destructive SQL unguarded. Local CI explicitly sets `GBRAIN_TEST_DB=1`+for its known Docker E2E databases, and `run-e2e.sh` preserves that opt-in so+schema-drift can reset stale fixture schemas on service-name hosts. The hard+test-database name floor still applies; this flag only relaxes the localhost+requirement. The heavy shell lane gets the same floor outsidebun: `tests/heavy/_db_floor.sh` (sourced by `scripts/run-heavy.sh` for the wholelane, and by each database-touching heavy script itself, since scripts aredocumented for direct invocation — the PGLite-based heavy scripts unset the URL@@ -645,7 +662,7 @@ Unit tests and what they cover:- `test/rerank-sunset-short-circuit.serial.test.ts` — the post-sunset gateway short-circuit: effective-model resolution (absent per-call model → configured/legacy default), the before/on/after date matrix via the injected clock, live models and `base_urls` self-host overrides untouched, the ONE-audit-row-per-process-per-model + single stderr line contract, and `applyReranker` failing open with no per-query audit rows.- `test/ai/reranker-readiness.test.ts` — the pure `rerankerReadiness` predicate: the default Voyage model with and without the key (the fix names the key AND the disable command; an empty-string key counts as absent), an explicit ZeroEntropy model across the sunset clock (sunset outranks a missing key in the fix text; a `provider_base_urls` self-host override lifts the block; mixed-case / slash-form ids are still recognized), shape failures that never throw (unknown provider, no reranker touchpoint, unlisted model, keyless local recipe, garbage input), and agreement with `gateway.isAvailable('reranker', model)` on an env × model matrix (the post-sunset divergence is the one intended exception).- `test/rerank-no-key.serial.test.ts` — the gateway `no_key` preflight: `RerankError('no_key')` before any HTTP call, ONE audit row per process per model with no stderr line, the per-model memo and its test seam, sunset precedence over `no_key`, no budget reservation for a skipped rerank (and `BudgetExhausted` before the transport call when the key IS present), HTTP 401 staying `auth`; plus `applyReranker` on `no_key` — results unchanged, no per-query rows, `onSkip` fires, a throwing hook never breaks search, and genuine failures never fire it.-- `test/hybrid-reranker-skipped.serial.test.ts` — balanced search on PGLite without `VOYAGE_API_KEY`: `reranker_skipped (no_key)` stamped on the meta with results kept and nothing printed, the stamp keeps the FULL cache TTL, and with the key present the reranker runs (`rerank_score` stamped, no skip entry).+- `test/hybrid-reranker-skipped.serial.test.ts` — balanced search on PGLite without `VOYAGE_API_KEY`: `reranker_skipped (no_key)` stamped on the meta with results kept and nothing printed, fresh searches retain the stamp while shared result caching stays disabled with no cache writes even when requested, and with the key present the reranker runs (`rerank_score` stamped, no skip entry).- `test/degraded-stages-recall.test.ts` — `affectsRecall` / `RANKING_ONLY_DEGRADED_STAGES`: `reranker_skipped` is ranking-only, every other closed-vocabulary stage affects recall, and a mixed list is degraded iff a recall-affecting stage is present.- `test/cli-explain-degraded-render.test.ts` — `formatResult --explain` threads the captured retrieval meta: a `reranker_skipped` stamp renders as the degraded header, a clean run prints no header, and the plain (non-explain) renderer is unchanged.- `test/doctor-reranker-health.test.ts` — the readiness-aware `reranker_health` check: key absent → warn naming the key and the disable command; key present → ok "ready"; disabled by config row or by the conservative bundle → ok; `no_key` skip rows informational once ready; a DB-plane key the CLI folded into the gateway counts; the no-gateway fallback to env > file > DB plane; unknown model, post-sunset ZE (injected clock), self-host override and `auth` rows; a brain with no embedding provider is never blamed; audit rows for a sunset model never warn on the live default.@@ -681,7 +698,7 @@ E2E tests live in `test/e2e/` and run against real Postgres+pgvector (require `D- `test/e2e/job-isolation.test.ts` — process isolation on real Postgres (DATABASE_URL-gated, wired EXPLICITLY into `.github/workflows/e2e.yml` tier1 — the workflow runs only named files): a concurrency-3 isolated drain through real child processes (the `fake-run-child.mjs` fixture — real spawns, no child DB pools), and the REAL `jobs run-child` CLI entrypoint end-to-end (engine bootstrap incl. the child's own pools, quiet handler registry, token validation, outcome protocol).- `test/e2e/sync-reconcile-postgres.test.ts` — the sync reconcile's real-Postgres array-parameter binding path (`DATABASE_URL`-gated). Wired EXPLICITLY into `.github/workflows/e2e.yml` tier1 beside job-isolation, and listed in the selected-e2e EXCLUDE set so a PR touching sync.ts doesn't run it a second time there.- `test/e2e/pglite-cli-exit.serial.test.ts` — real spawned-CLI exit behavior on PGLite (in-memory, no `DATABASE_URL`): read commands (`search`/`get`/`query`) exit 0 promptly; CLI_ONLY `capture` exits clean and frees the single-writer lock; the teardown describes pin every disconnect site — a failed op exits 1 with the error on stderr, and the dashboard, read-only-timeout, doctor, and `dream --dry-run` paths all exit with no force-exit banner.-- `test/e2e/pgbouncer-teardown.test.ts` — PgBouncer TRANSACTION-mode teardown. Pins the bug CLASS, not timings: a CLI op against a txn-mode pooled URL exits 0 with intact stdout and does NOT ride the 10s hard-deadline backstop (the `engine.disconnect() did not return` banner is the smoking gun). Gated by `GBRAIN_PGBOUNCER_URL` + `GBRAIN_PGBOUNCER_DIRECT_URL` (NOT `DATABASE_URL`) — set automatically by `bun run ci:local`'s `pgbouncer` compose service; skips gracefully elsewhere. Uses a DEDICATED `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures.+- `test/e2e/pgbouncer-teardown.test.ts` — PgBouncer TRANSACTION-mode teardown. Pins the bug CLASS, not timings: a CLI op against a txn-mode pooled URL exits 0 with intact stdout and does NOT ride the 10s hard-deadline backstop (the `engine.disconnect() did not return` banner is the smoking gun). Gated by `GBRAIN_PGBOUNCER_URL` + `GBRAIN_PGBOUNCER_DIRECT_URL` (NOT `DATABASE_URL`) — set automatically by `bun run ci:local`'s `pgbouncer` compose service. Both URLs survive the E2E runner and preload scrub, while CLI children clear ordinary database overrides so the pooled URL in their isolated config wins. Selected CI runs require a nonzero executed-test count (`GBRAIN_CI_REQUIRE_PGBOUNCER=1`); missing targets or an all-skipped file fail the gate. It skips gracefully elsewhere. Uses a DEDICATED `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures.- `test/e2e/volunteer-context-postgres.test.ts` — `volunteer_context` on REAL Postgres (engine parity beyond the hermetic PGLite unit suite): resolution arms through the actual op handler, the fire-and-forget volunteer-event sink landing rows, the stats join, and the RLS pin that `context_volunteer_events` has ROW LEVEL SECURITY enabled (keeps the v35 auto-RLS event trigger honest for migration-created tables). `DATABASE_URL`-gated.- `test/e2e/openclaw-reference-compat.test.ts` — `check-resolvable` + skillpack install-model against a minimal AGENTS.md workspace fixture (`test/fixtures/openclaw-reference-minimal/`), regression guard for the OpenClaw deployment shape.- `test/e2e/workspace-generic-compat.test.ts` — always-on (PGLite, no binary): pins the INSTALL_FOR_AGENTS.md "any repo with a workspace" contract against `test/fixtures/generic-agents-workspace/` (Hermes is the motivating consumer): `cwd_walk_up` detection, the `GBRAIN_SKILLS_DIR` override, `check-resolvable` on a root AGENTS.md, and scaffold additivity + refuse-overwrite. The real Hermes-behavior proof is the door suite below.diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 061501e338..c7ee1f599f 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -79,11 +79,11 @@ Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **S| Tool | Description | Scope | Starter | Gate ||---|---|---|---|---|| `find_anomalies` | Returns statistical anomalies in recent page activity, grouped by cohort (tag or type). | read | yes | |-| `find_contradictions` | v0.32.6 — return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. | read | | |+| `find_contradictions` | Stored contradiction reports are temporarily available only to trusted local callers without a source filter. | read | | || `find_experts` | Answers 'who in my brain knows about <topic>'. | read | | || `find_trajectory` | v0.35.4 — return the chronological claim trajectory for an entity (typed metric values over time, plus auto-detected regressions and narrative drift). | read | | || `get_calibration_profile` | Read the active calibration profile for a holder. | read | | |-| `get_recent_salience` | Returns pages recently touched and ranked by emotional + activity salience (deterministic 0..1 emotional_weight + take density + recency decay). | read | yes | |+| `get_recent_salience` | Returns readable pages recently touched and ranked by activity salience and recency. | read | yes | || `volunteer_context` | Push-based context: volunteer brain pages relevant to a rolling conversation window WITHOUT being asked. | read | | |## jobsdiff --git a/docs/ai-providers/zeroentropy.md b/docs/ai-providers/zeroentropy.mdindex dde02147c8..54eb1036de 100644--- a/docs/ai-providers/zeroentropy.md+++ b/docs/ai-providers/zeroentropy.md@@ -186,17 +186,12 @@ ignore the field — no behavior change.## Cache key versioning-`KNOBS_HASH_VERSION` (`src/core/search/mode.ts`) folds reranker config into-the `query_cache.knobs_hash` column, so a hash-version bump invalidates-every cached row written under the previous version. During a rolling-deploy that carries such a bump:--- Expect a temporary cache hit-rate dip (~1 hour at default- `cache.ttl_seconds = 3600s`)-- Hot queries may briefly double their cache row count (one row per- version)--Both clear naturally; no operator action required.+The retained `KNOBS_HASH_VERSION` machinery (`src/core/search/mode.ts`)+includes reranker config in `query_cache.knobs_hash`, separating rows written+under different settings. Semantic result-cache reads and writes are currently+disabled, so repeated queries perform fresh retrieval and do not repopulate+those rows. Changing the hash version, TTL or cache setting cannot restore+result caching while it is disabled.## Troubleshooting@@ -207,4 +202,4 @@ Both clear naturally; no operator action required.| `reranker_health` says enabled but NOT running (`<KEY> not set`) | The resolved reranker's provider key is absent — search fails open in RRF order, one `no_key` audit row per process, nothing on stderr | `export VOYAGE_API_KEY=…` for the default (or `ZEROENTROPY_API_KEY` for an explicit ZE model), or `gbrain config set search.reranker.enabled false` || `reranker_health` doctor warns about auth failures | Key present but rejected (HTTP 401/403) | Re-export a valid key; `gbrain models doctor` to verify || `reranker_health` doctor warns about transient failures | Upstream flake or rate limit | Reranker fails open to RRF; check the provider's status page if persistent |-| Cache hit rate dipped after upgrade | Expected during rolling deploy | Clears within `cache.ttl_seconds` (default 3600s) |+| Cache reports disabled after upgrade | Semantic result caching is temporarily disabled | Budget for fresh retrieval; waiting for the TTL or changing cache settings does not restore it |diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 24d1acee0a..6abac81a44 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -20,9 +20,15 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `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; 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/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/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 + the search cache key. `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 every result-shaping knob 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). `SEARCH_MODE_CONFIG_KEYS` carries the corresponding config keys, 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.+- `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). `SEARCH_MODE_CONFIG_KEYS` carries the corresponding config keys, 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. The retained cache-hit implementation slices stored pages to the resolved result count (per-call `limit` → the mode's `searchLimit`) and bypasses nonzero offsets. These key and shape checks do not prove every response dependency; the availability gate bypasses all persisted results.- `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`.- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction.- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.@@ -57,8 +63,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/postgres-engine/` + `src/core/pglite-engine/` — narrow-deps engine module directories, mirrored in lockstep (the engine-parity discipline applies to these dirs exactly as to the façades). Each holds `facts.ts`, `takes.ts`, `code-edges.ts`, and `salience.ts`: the corresponding BrainEngine method clusters implemented as free functions over a typed deps interface (e.g. `PgliteFactsDeps`) that the engine class satisfies, so each module depends only on the narrow slice it uses. The façade methods delegate to them via static top-level imports (the engine-live no-runtime-dynamic-import rule applies) and keep the full public surface.- `src/core/postgres-engine/forward-reference-bootstrap.ts` — `applyPostgresForwardReferenceBootstrap(conn)`: the forward-reference bootstrap for the RAW `SCHEMA_SQL` replay path (probe + patch every column/table the embedded schema blob forward-references but older brains don't have yet — single probe round-trip, idempotent, fast no-op when nothing is missing). Peeled out of `PostgresEngine` so BOTH replay entrypoints run it before the blob: `PostgresEngine.initSchema()` AND the standalone module-singleton `db.ts:initSchema()` (replaying with no bootstrap would wedge an upgrade-boundary brain on `CREATE INDEX` over a column the replayed blob forward-references). Callers MUST hold the initSchema advisory lock (key 42) on `conn` so concurrent bootstraps can't race on a transaction pooler. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap` in shape — keep in sync; covered by `test/schema-bootstrap-coverage.test.ts` (PGLite A2 static check + the Postgres-blob CREATE-INDEX class-closure gate, which parses `SCHEMA_SQL` and requires every migration-added blob-indexed column to have a probe here or an explicit exemption) + `test/e2e/postgres-bootstrap.test.ts` (Postgres side, live convergence cases). Probes are column-only (nullable `ADD COLUMN`, plus `SET DEFAULT` where hardening the upgrade window needs it — `dream_verdicts.expires_at`); the owning migration stays the source of truth for backfill/constraints/indexes: on the engine path it runs right after the bootstrap under the same advisory lock, while the standalone `db.ts:initSchema` path replays the blob WITHOUT running migrations — safe because the NULL-tolerant read predicates treat pre-backfill rows as valid until the next full engine init.- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `countCJKAwareWords(s)` (30% density threshold — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS`, `pglite-engine.ts:searchKeyword + searchKeywordChunks`.-- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Lossless invariant: non-overlapping portions reassemble to the original. Also strips the facts fence via `stripFactsFence({keepVisibility:['world']})` so private fact visibility tiers never reach embeddings.-- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries.+- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` before splitting so only world Facts and ordinary prose enter retrieval text; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The markdown chunker version records the current index format.+- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries. Sanitizes the full body before sentence embedding and boundary detection.- `src/core/chunkers/llm.ts` — LLM-guided chunking: pre-splits into 128-word candidates via the recursive chunker, then asks a Haiku-class model "where does the FIRST topic shift occur?" per window.- `src/core/search/dedup.ts` — 4-layer result dedup + compiled-truth guarantee: (1) top 3 chunks per page by score, (2) drop chunks >0.85 Jaccard-similar to already-kept chunks of the SAME page (cross-page near-dups survive — two legitimately similar pages both return), (3) no page type exceeds 60% of results — applied only when the candidate set actually contains multiple page types; a homogeneous set passes through unchanged because dropping (for example) one of three distinct LongMemEval `note` sessions cannot introduce diversity and destroys multi-session recall (pinned by the homogeneous-set case in `test/dedup.test.ts`), (4) max 2 chunks per page (default; the two-pass structural expansion in `hybrid.ts` widens it), (5) ensure at least 1 compiled_truth chunk per page. Page identity is the composite `pageKey()` (source_id, slug) — the one canonical key helper every layer uses, so slug collisions across sources can't collapse recall.- `src/core/audit-slug-fallback.ts` — Weekly ISO-week-rotated audit JSONL at `~/.gbrain/audit/slug-fallback-YYYY-Www.jsonl`. `logSlugFallback(slug, sourcePath)` fires when `importFromFile` falls back to a frontmatter slug because `slugifyPath` returned empty (emoji / Thai / Arabic / non-CJK exotic-script filenames). `readRecentSlugFallbacks(days)` reads the last N days for `gbrain doctor`'s `slug_fallback_audit` check. Honors `GBRAIN_AUDIT_DIR` via the shared `resolveAuditDir()`. Separate surface from `sync-failures.jsonl` — that file carries bookmark-gating semantics that info events shouldn't trigger.@@ -117,7 +123,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/search/title-match.ts` — pure, zero-I/O title-phrase matcher shared by the production title boost AND NamedThingBench (no drift). `isTitlePhraseMatch(query, title)` returns true when the normalized query is a contiguous token run inside the title with `>= MIN_CONTENT_TOKENS=2` non-stopword tokens, OR an exact full-title match (covers deliberate 1-word chosen names like "Helios"). Token-boundary matching (never raw substring, so "art" doesn't match "Bartholomew"); small conservative English stopword set excluded from the content-token floor (guards against promoting generic pages on stopword-y queries); NFKC normalize so CJK / width variants converge. Exports `tokenizeTitle` + `__test__` internals.- `src/core/search/alias-normalize.ts` — ONE normalizer shared by the WRITE path (ingest projects frontmatter `aliases:` into `page_aliases`) and the READ path (search matches query against `page_aliases`), so stored aliases can't silently fail to match queries via divergent normalization (same single-source posture as `cjk.ts`). `normalizeAlias(raw)` does NFKC + lowercase + whitespace-collapse + trim + strip one layer of wrapping quotes/brackets; returns `''` for empty (callers MUST skip empty aliases). `normalizeAliasList(value)` coerces a frontmatter scalar / array / comma-list / garbage into a deduped list of normalized non-empty aliases — used by both the ingest projection and the `reindex --aliases` backfill.- `src/core/search/evidence.ts` — the agent-facing why-it-matched contract (so an agent never reads one blended score, decides "no strong match, safe to create", and writes a duplicate over a fully-developed page). `classifyEvidence(r, opts?)` names the strongest signal (precedence: `alias_hit` > `exact_title_match` > `high_vector_match` (real query↔chunk cosine `SearchResult.cosine` ≥ `DEFAULT_HIGH_COSINE_FLOOR=0.8`, overridable via `EvidenceOpts.cosineFloor` / config `search.evidence_cosine_floor` — never the blended score, so a keyword+boost pile-up can't earn the label; keyless/hermetic runs have no cosine and degrade to keyword-based labels; legacy `HIGH_MATCH_FLOOR=0.85` stays exported for back-compat only) > `keyword_exact` (base ≥ `SOLID_MATCH_FLOOR=0.6`) > `weak_semantic`). `createSafetyFor(evidence)` derives the don't-duplicate hint (`exists`/`probable`/`unknown`) the agent keys off INSTEAD of a raw threshold (a blended RRF/cosine score is not a calibrated probability). `stampEvidence(results, opts?)` stamps `evidence` + `create_safety` in place once at pipeline end (after the alias hop, before slice); idempotent.-- `src/core/search/private-visibility.ts` — page-level `visibility: private` enforcement for untrusted callers; the single trust+config resolver for every remote read surface (search arms, recall's query arm, entity cards, context_pack, get_page/fetch/list_pages, get_chunks/get_versions/get_timeline/get_raw_data, resolve_slugs, get_links/get_backlinks/traverse_graph, and the list-style analytics ops find_orphans/get_recent_salience/find_experts/find_anomalies). Resolution: `ctx.remote === false` → see everything (trusted local CLI); `GBRAIN_REMOTE_PRIVATE_PAGES=1` env or config `search.remote_private_pages` ∈ {visible,true,1} → operator opt-out; otherwise private pages are excluded, FAIL-CLOSED default — a private page reads exactly like a missing one (no existence oracle). `privatePagesFilterFragment(pageAlias)` is the one SQL predicate (`COALESCE(frontmatter->>'visibility','world') <> 'private'`; consumed by `buildVisibilityClause` in sql-ranking.ts behind `SearchOpts.excludePrivate`, both engines' listPages, the relational-arm hydrate, get_page's fuzzy-candidate filter); `isPrivatePage(frontmatter)` is the row-side twin for already-fetched rows; `findPrivateOnlySlugs(engine, slugs, scope)` returns slugs an untrusted caller must not see enumerated (every in-scope page row private; a slug with at least one non-private in-scope page stays visible; dangling endpoints pass through). `findWorldVisibleSlugs(engine, slugs, scope)` is the KEEP-list inverse: of the given slugs, which have at least one world-visible page row — deleted rows considered, so a soft-deleted private page still counts as private-only for callers whose raw queries carry no `deleted_at` predicate; fail-closed by construction, since a slug with NO page row at all (hard-purged between a caller's list read and the probe) is simply absent from the keep-set and gets dropped instead of served. `dropPrivateOnlyRows(engine, remote, rows, slugOf, scope)` is the shared post-filter for list-shaped read ops — one gate read + one batched keep-list probe, keeping only rows whose slug has a world-visible page; consumed by `find_orphans` (which also shrinks `total_orphans`/`total_pages`/`total_linkable` with the hidden rows, leaving `excluded` alone so there's no count oracle), `get_recent_salience`, and `find_experts`. `find_anomalies` composes `resolveExcludePrivatePages` + `findWorldVisibleSlugs` directly: private slugs are filtered out of `page_slugs`, rows whose visible slugs empty out are dropped (an empty-but-present row is a hidden-activity oracle), `count` is adjusted by the slugs actually removed and `sigma_observed` recomputed with the engine's own formula, sub-threshold survivors are dropped, and rows re-sort by the published sigma — accepted residuals for >50-page display-capped cohorts are documented at the call site in `src/core/ops/salience.ts`. Visibility posture folds into the query-cache key (knobs_hash) so remote/local results can't cross-contaminate the cache. Runbook: `docs/operations/mcp-surface-runbook.md`. Orthogonal to this privacy layer, the list-style analytics reads are also source-scoped at the engine (`get_recent_salience`/`find_anomalies` thread `sourceScopeOpts` into both the today and baseline windows), and the `search` op validates its per-call `source_id` through the same shared parser as the page ops (invalid ids throw `invalid_params`; out-of-grant ids throw `permission_denied`).+- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs retain their existing semantics and failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows; link origins and timeline projections use independent ID-based predicates. Legacy slug-set helpers are for name enumeration, never authorization of data from another row/source. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.- `src/commands/search-diagnose.ts` — `gbrain search diagnose "<query>" --target <slug> [--json] [--source <id>]`: Phase-0 retrieval diagnostic. Traces WHERE a target page surfaces (or fails to) across keyword / vector (per-page max-pool) / alias / hybrid layers and names the layer responsible for an incident, so an operator can pin whether the fix is max-pool/innerLimit (vector) vs title/alias. The verdict names the layer that DOES surface the target (or "none"). Pinned by `test/search/search-diagnose.test.ts`.- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.- `src/eval/retrieval-quality/harness.ts` + `src/commands/eval-retrieval-quality.ts` + `test/fixtures/retrieval-quality/namedthing.jsonl` — NamedThingBench, the retrieval-quality eval that pins the named-thing-miss failure class. Seven query families, each a distinct failure class: `title-substring` (the named-thing miss itself), `generic-to-named` (tourist label → named thing), `alias-synonym` (declared alias / romanization → canonical), `multi-chunk-dilution` (one strong chunk among many weak — stresses max-pool), `short-vs-rich`, `graph-relationship` (guardrail), `hard-negative` (precision guard, must NOT return a page). `gbrain eval retrieval-quality <fixture.jsonl>` runs it with hard gates (e.g. title-substring Hit@1 ≥ 0.95, alias Hit@1 ≥ 0.98, multi-chunk-dilution Hit@3 = 1.0). Pure: caller injects a `SearchFn` (CLI uses `hybridSearch`, tests stub) so it's engine-agnostic. Metric glossary entries (`hit@1`/`hit@3`) added to `src/core/eval/metric-glossary.ts`. Pinned by `test/eval-retrieval-quality.test.ts` + `test/retrieval-quality-harness.test.ts`.@@ -359,16 +365,16 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU); refresh rotation also `DELETE...RETURNING` (§10.4 stolen-token detection). `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).- `admin/` — React 19 + Vite + TypeScript admin SPA embedded in the binary via `admin/dist/` served by `serve-http.ts`. 7 screens: Login (bootstrap token → session cookie), Dashboard (metrics + SSE feed + token health), Agents (sortable table + sparklines + Register), Register (modal with scope checkboxes + grant type selector), Credentials reveal (Copy + Download JSON + one-time-only warning), Request Log (filterable paginated), Agent Detail drawer (Details / Activity / Config Export tabs + Revoke). Design tokens: `#0a0a0f` bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. 65KB gzip. Build: `cd admin && bun install && bun run build`; output at `admin/dist/` is committed for self-contained binaries.- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.-- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses JSON error envelopes first, falls back to substring detection for legacy server messages. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.+- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.- `src/commands/connect.ts` + `src/core/connect-probe.ts` — `gbrain connect <mcp-url> [--token <bearer>]` one-command coding-agent onboarding from a bearer token. Turns an MCP URL + token into a paste-ready `claude mcp add ... -H "Authorization: Bearer ..."` block (default) or, with `--install`, runs it directly and smoke-tests the token. Direct HTTP MCP — Claude Code talks straight to a remote `gbrain serve --http`, no local install needed. Token resolution: `--token` > `$GBRAIN_REMOTE_TOKEN` > placeholder (print) / error (install). The generated block tells the agent to call `get_brain_identity` + `list_skills` (the `LEARN_INSTRUCTION` export, which names `capture` — a starter-surface MCP op — alongside `put_page` for full-control writes) with a core-tools fallback for hosts without skill publishing. URL normalization appends `/mcp` to a bare host but REJECTS a scheme-less host; the pure registration helpers (`normalizeMcpUrl`, `isLinkLocalOrMetadata`, `buildClaudeMcpAddArgv` with its optional scope param — claude's default is `local`, so the harness lane passes `user` explicitly — `buildCodexMcpAddArgv`, `validateToken`, `redactToken`, `shellQuote`/`cmdString`, `issuerFromMcpUrl`, the `OAUTH_SECRET_NOTE` secret-hygiene constant, and `openclawThinClientBlock` — the honest openclaw wiring print: a scoped `gbrain init --mcp-only` thin-client block, deliberately NOT a stdio mcpServers config since that grants full local DB access) live in `src/core/mcp-registration.ts` (core must not import from commands; connect.ts re-exports them — `OAUTH_SECRET_NOTE` included — so its surface and tests are unchanged) and are unit-tested. Flags: `--token`, `--name <id>` (default `gbrain`, validated against `NAME_RE`), `--agent claude-code|codex|opencode|perplexity|generic`, `--install`, `--yes` (required for `--install` in non-TTY), `--force`, `--json` (token redacted unless `--show-token`), `--timeout-ms`. `connect` is in `CLI_ONLY` + `CLI_ONLY_SELF_HELP`; dispatched in `cli.ts:handleCliOnly` with no local DB connect. `AGENT_SPECS` drives per-agent rendering + `--install`: `claude-code` → `buildClaudeMcpAddArgv` (literal `-H "Authorization: Bearer <tok>"`); `codex` → `buildCodexMcpAddArgv` = `codex mcp add <name> --url <url> --bearer-token-env-var GBRAIN_REMOTE_TOKEN` (on the CONNECT lane Codex reads the token from the env var at runtime, never written to config — the harness lane in `src/core/bootstrap/harness.ts` is the deliberate exception, writing a managed block with the inline `http_headers = { Authorization = "Bearer <t>" }` credential (codex-cli >=0.149 rejects inline `bearer_token` for streamable_http at config load) because framework-spawned codex inherits no shell profile; `--install` runs it and prints an `export GBRAIN_REMOTE_TOKEN` hint when missing); `opencode` → `buildOpencodeMcpAddArgv` = `opencode mcp add <name> --url <url> --header "Authorization=Bearer {env:GBRAIN_REMOTE_TOKEN}"` (the interpolation is stored LITERALLY and resolved by opencode at read time — token never in argv/config/--json; `--install` writes the entry directly through `ConnectDeps.writeOpencodeRemoteEntry` → `opencode-json.ts` in env token mode, no binary required; `--force` maps to the writer's `allowReplaceOtherSource` so an OURS entry at an old url — a rotated serve — is replaceable, mirroring the exec lanes' `--force` semantics, while foreign same-name entries still refuse with url-appropriate copy: pick `--name`); `perplexity` + `generic` are `installable:false` and reject `--install`. `--oauth` (`supportsOAuth:true` = perplexity/generic only) emits an OAuth 2.1 client-credentials connector block (Issuer URL via `issuerFromMcpUrl` = mcp-url minus `/mcp`, Client ID, Client Secret) — least-privilege scopes + short-lived rotating tokens vs a long-lived full-access secret. Creds from `--client-id`/`--client-secret` (BYO) or `--register` (`deps.registerOAuthClient` shells `gbrain auth register-client <name> --grant-types client_credentials --scopes <DEFAULT_SCOPES="read write"> --token-endpoint-auth-method client_secret_post` and parses `Client ID:`/`Client Secret:`); `--oauth` rejected for claude-code/codex and incompatible with `--install`. `buildJson` is a generic shape (`agent`, `command`/`command_argv` null for perplexity/generic, `header`, `env_var`, oauth fields with redaction); the codex `command` carries only the env-var name, never the token. `cmdString(binary, argv)` POSIX-single-quotes args. `ConnectDeps` = `{isTTY, promptYesNo, hasBinary(bin), runBinary(bin, argv), probe, env(name), registerOAuthClient, writeOpencodeRemoteEntry}` — binary-generic so `claude` and `codex` share the exec path while opencode rides the writer member; `env` injectable for tests. Security: rendered command single-quotes the token so shell metacharacters can't run code when pasted; token validated before it lands in an HTTP header; link-local / cloud-metadata addresses (incl. IPv4-mapped IPv6 `::ffff:169.254.x.x` and AWS IMDSv2-over-IPv6 `fd00:ec2::254`) refused as a token-exfil guard while localhost/RFC1918/LAN stay allowed; token redacted from all error output. `src/core/connect-probe.ts` is the raw-bearer MCP smoke probe backing `--install`: connects the official MCP SDK `Client` over `StreamableHTTPClientTransport` with a STATIC `Authorization` header (no OAuth/discovery — distinct from `mcp-client.ts:callRemoteTool` which is OAuth-only and `remote-mcp-probe.ts:smokeTestMcp` which only sends `initialize`), runs the full `initialize` handshake via `client.connect()`, then calls `get_brain_identity` (read-scope, non-localOnly) to prove a tool call round-trips. Never throws — every failure maps to `{ ok: false, reason: 'auth' | 'unreachable' | 'timeout' | 'tool_error' | 'unknown', message }` so a wrong/expired token fails at setup, not on the agent's first request. `DEFAULT_PROBE_TIMEOUT_MS = 15_000` shared with `connect.ts`. `serve-http.ts` adds exported pure `skillPublishStatus(publishSkills)` for the startup banner `Skills: published / not published` line + a one-line `gbrain config set mcp.publish_skills true` stderr nudge when publishing is OFF. Docs: `docs/mcp/CODEX.md`, `docs/mcp/PERPLEXITY.md`, `docs/mcp/CLAUDE_CODE.md`, `docs/tutorials/connect-coding-agent.md`. Pinned by `test/connect.test.ts` (pure-helper + render, all five agents incl. the opencode writer-install lane) + `test/e2e/connect-bearer.test.ts` (raw-bearer probe + full OAuth chain register→connect→discovery→`/token` mint→`get_brain_identity`, client registered in `beforeAll` before serve takes the PGLite single-writer lock; drives real `claude` + `codex` binaries through `connect --install` with sandboxed `HOME`/`CODEX_HOME`, asserts registration + token never in Codex config, skips when a binary is absent) + `test/e2e/serve-stdio-roundtrip.test.ts` (spawns real `gbrain serve` stdio against a fresh `init --pglite` brain, drives the SDK client through `initialize`→`tools/list`→`tools/call`, asserts the advertised core-tool set including `capture`, a starter-surface MCP op) + `test/serve-skills-publish-nudge.test.ts`.- `src/commands/upgrade.ts` — self-update CLI. `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally.- `src/commands/migrations/` — TS migration registry (compiled into the binary; no runtime walk of `skills/migrations/*.md`). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify); `phaseASchema` has a 600s timeout for duplicate-heavy brains. `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (pending-host-work ping for skills/migrations/v0.14.0.md). All orchestrators are idempotent and resumable from `partial` status. The RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape (orchestrators never call `appendCompletedMigration`). `statusForVersion` prefers `complete` over `partial` (never regresses); 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. Schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) live in the `MIGRATIONS` array in `src/core/migrate.ts`. `in-process.ts` exports `runMigrateOnlyCore({timeoutMs?})` — single source of truth for "bring schema to head" (`configureGateway` → `createEngine` → `connect` → `initSchema` → `disconnect`, idempotent, 600s `MIGRATE_ONLY_TIMEOUT_MS` guard, throws `MigrateOnlyError` on no-config / timeout); the orchestrators' 9 schema phases AND `init.ts:initMigrateOnly` both delegate to it so schema bring-up can't drift (in-process, so no spawn can die with `getaddrinfo ENOTFOUND` on Windows + bun + Supabase pooler). `runGbrainSubprocess` is the diagnostic wrapper for the remaining non-schema spawns (extract/repair/stats): captures child stderr (64MB buffer) into the thrown error. `v0_13_1.ts:phaseCGrandfather` is a CHUNKED bulk SQL pass keyed on `pages.id` (globally unique PK, NOT slug — slug uniqueness is `(source_id, slug)`), filters `deleted_at IS NULL` (no tombstones), chunked in `CHUNK_SIZE` batches (DELETE_BATCH_SIZE convention) for bounded lock-hold; the rollback log carries `{id, slug, source_id, pre_frontmatter}` so rollback is unambiguous across sources; idempotent + resumable (each UPDATE flips its rows out of `GRANDFATHER_WHERE`). Pinned by `test/migration-in-process.serial.test.ts` and `test/migrations-v0_13_1-grandfather.test.ts`.- `src/commands/migrations/v0_46_3.ts` — ZeroEntropy sunset notice migration, detect-and-notify ONLY. Detects the HOST brain's exposure via `src/core/ze-exposure.ts` (read-only); when exposed — or when exposure is UNKNOWN, fail-safe — prints the ACTION REQUIRED banner and appends one idempotent entry to `~/.gbrain/migrations/pending-host-work.jsonl` pointing the host agent at `skills/migrations/v0.46.3.0.md`. Performs NO config writes, NO pinning, and never invokes `migrate embeddings` (the migration costs money and needs a target key — that decision belongs to the user/agent via the playbook). UNKNOWN returns `complete` with an `exposure_unknown` detail rather than `partial` (three consecutive partials would wedge the whole migration chain behind `--force-retry`); the stage-2 upgrade banner and `gbrain doctor` carry the ongoing nag instead. Host-scoped (apply-migrations runs once per host with a global completed.jsonl); mounted/team brains are covered by the per-brain stage-2 banner (`ze_sunset_notice_v2_shown` in each brain's own DB config) + doctor gates.- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.-- `src/commands/orphans.ts` — `gbrain orphans [--json] [--count] [--include-pseudo] [--source <id>] [--mode islanded|inbound]`: surfaces disconnected pages, grouped by domain (auto-generated/raw/pseudo filtered by default). The DEFAULT definition is `islanded` — no live inbound AND no live outbound link — matching `get_health.orphan_pages` so doctor, health, and this command agree by construction; `--mode inbound` gives the no-inbound-only view (pages that link out but are never linked TO). Also exposed as `find_orphans` MCP op (same `mode` param; an unknown mode is rejected loudly, never silently coerced to the default). `findOrphans`/`getOrphansData` (the canonical pure fn shared with doctor's `orphan_ratio`) takes `{ sourceId?, sourceIds?, mode? }`; `BrainEngine.findOrphanPages(opts?)` (both engines) scopes ONLY the candidate side (`p.source_id = $1` scalar, or `= ANY($1::text[])` federated) while still counting inbound links from ANY source — a page in source X linked FROM source Y is reachable, so NOT an orphan of X (deliberate definition; the stricter intra-source-only reading is rejected). `--source` is an explicit raw-flag parse (NOT `resolveSourceWithTier`, which would scope bare invocations to a default). The `total_linkable` denominator enumerates ALL live pages (scoped) and subtracts every excluded-by-slug page (templates/, scratch/, etc.) so excluded NON-orphan pages with inbound links don't inflate it and suppress warnings. The `find_orphans` MCP op threads `sourceScopeOpts(ctx)` so a source-bound OAuth client doesn't see brain-wide orphans, and for remote callers post-filters `visibility: private` pages via `dropPrivateOnlyRows` (`src/core/search/private-visibility.ts`): hidden orphans vanish from every published counter — `total_orphans`, `total_pages`, and `total_linkable` all shrink with them while `excluded` is untouched (folding them into `excluded` would be a one-call private-orphan-count oracle, since with `include_pseudo:true` the unfiltered op guarantees `excluded === 0`), keeping doctor-remote's orphan ratio and the `excluded === total_pages - total_linkable` invariant coherent over the world-visible universe. `gbrain doctor --source <id>` scopes `orphan_ratio` and, under explicit `--source` below 100 entity pages, reports the ratio with a low-scale caveat (thin-client `doctor --source` orphan_ratio remains brain-wide — TODO). Pinned by `test/orphans-source-scope.test.ts` (PGLite) + `test/orphans-mode-islanded.test.ts` (islanded-default + mode contract) + `test/e2e/engine-parity.test.ts` (Postgres↔PGLite scalar + federated parity).+- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter.- `src/commands/salience.ts` — `gbrain salience [--days N] [--limit N] [--kind PREFIX] [--json]`: pages ranked by emotional + activity salience over a recency window. Mirrors orphans.ts shape (pure data fn + JSON formatter + human formatter). Calls `engine.getRecentSalience(opts)`. Score formula: `(emotional_weight × 5) + ln(1 + active_take_count) + 1/(1 + days_since_update)`.- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type.-- `src/commands/whoknows.ts` — `gbrain whoknows <topic> [--explain] [--limit N] [--json]`: expertise + relationship-proximity routing. Mirrors salience/anomalies shape (pure `rankCandidates()` + `findExperts()` orchestrator + `runWhoknows()` CLI dispatch + thin-client routing). MCP op = `find_experts` (scope: read, localOnly: false); for remote callers it post-filters `visibility: private` pages from the rankings via `dropPrivateOnlyRows` (a private page's slug/title/scores never reach untrusted readers; trusted local CLI sees the unfiltered view). Ranking formula: `score = log(1 + raw_match) × max(0.1, exp(-days/180)) × (0.5 + 0.5 × salience)` where `raw_match` is hybridSearch's RRF+source-boost score. Filters at SQL via `SearchOpts.types: ['person', 'company']` (no post-filter waste); hybridSearch's internal salience+recency boosts are intentionally disabled so the locked formula applies on a clean signal. Floors prevent multiplicative-zero edge cases (cold-start people stay visible); ties break alphabetically by slug for determinism. 16 unit tests in `test/whoknows.test.ts` pin the math. with `src/core/operations.ts:find_experts`: pack-aware via `expertTypesFromPack(pack.manifest)` from `best-effort.ts`. Pack-load failure → EMPTY filter (NOT hardcoded `['person', 'company']` defaults). A `researcher` type declared `--expert` surfaces in `whoknows` results.+- `src/commands/whoknows.ts` — `gbrain whoknows <topic>` and MCP `find_experts`: expertise and relationship routing. `findExperts()` threads source, page-privacy and holder policy through hybrid retrieval and enrichment, then requires an authorized effective-date read after optional salience work for every caller, including trusted local callers. Candidates absent from that exact `(source_id, slug)` map are omitted; required admission failures propagate. Optional salience failures retain the existing neutral factor. `rankCandidates()` uses `score = log(1 + raw_match) × max(0.1, exp(-days/180)) × (0.5 + 0.5 × salience)`, with salience normalized before ranking and alphabetical slug tie-breaking. Hybrid salience/recency boosts are disabled here to avoid applying them twice. Expert types are filtered in SQL and resolved from the pack by `ops/insights.ts`; a failed pack load supplies an empty type list. CLI supports `--explain`, `--limit`, `--json` and thin-client routing. Math is pinned by `test/whoknows.test.ts`; exact final admission, mutation races and SQL-failure behavior run on both engines in `test/e2e/read-enrichment-privacy.test.ts`.- `src/commands/eval-whoknows.ts` — `gbrain eval whoknows <fixture.jsonl> [--json] [--skip-replay]`: two-layer eval gate. Layer 1 quality (hand-labeled fixture, top-3 hit rate ≥ 0.8). Layer 2 regression (`eval_candidates` replay set-Jaccard@3 ≥ 0.4). Sparseness fallback: < 20 replay-eligible rows → Layer 2 auto-skips with stderr warning. Stable JSON envelope with `schema_version: 1`; exit 0/1/2 for pass/fail/usage. `WhoknowsFn` callable abstraction makes the gates impl-agnostic; `runEvalWhoknows(engine: BrainEngine | null, args)` picks the impl at entry — thin-client mode (`isThinClient(cfg)`) routes per-query through `callRemoteTool(cfg, 'find_experts', {topic, limit})`, local mode calls `findExperts(engine, ...)` directly. cli.ts adds a thin-client bypass before `connectEngine` (dispatch shape under `src/commands/eval.ts`); the regression gate auto-skips in thin-client mode (no DB access to `eval_candidates`). Public exports `jaccardAtK`, `topKHit`, `readFixture`, `WhoknowsFn`, threshold constants pinned by `test/eval-whoknows.test.ts` (25 cases incl. null-engine signature contract).- `test/fixtures/whoknows-eval.jsonl` — 10-row synthetic placeholder demonstrating the eval-fixture schema (`{query, expected_top_3_slugs, notes?}` JSONL). End users replace with their own real queries; placeholder uses obviously-example slugs (`wiki/people/example-alice`). Drives `test/e2e/whoknows.test.ts` (seeds a matching synthetic brain, asserts the >=80% gate) and the `whoknows_health` doctor check.- `src/core/skillopt/` + `src/commands/skillopt.ts` + `skills/skill-optimizer/` — self-evolving skill optimization grounded in the SkillOpt paper (arXiv 2605.23904). `gbrain skillopt <skill>` treats `SKILL.md` as trainable parameters of a frozen agent: validation-gated (median-of-3 + epsilon=0.05), budget-capped (preflight estimator), per-skill DB-locked (`tryAcquireDbLock('skillopt:<name>', 60min)`), atomic-versioned (history-intent-first 5-step commit), body-only mutations (frontmatter forbidden). Rollouts use `gateway.toolLoop` directly with no-op persistence callbacks (zero `subagent_messages` pollution) + a read-only tool allowlist derived from `BRAIN_TOOL_ALLOWLIST` minus `put_page`/`submit_job`/`file_upload`. Two reflect calls per step; rejected-edit buffer LRU-bounded to 100; bundled-skill gate; bootstrap workflow (sentinel + `--bootstrap-reviewed`); D_sel floor (>=5 with `--split` override); audit JSONL via `audit-writer.ts`. Added to `ALL_PHASES` after `patterns` (default OFF; opt-in via `gbrain config set cycle.skillopt.enabled true`); cycle phase wrapper at `src/core/skillopt/cycle-phase.ts` walks stale skills with per-skill ($0.50) + brain-wide ($2.00) caps. Added to `PROTECTED_JOB_NAMES`. Surface: dream-cycle phase wrapper; `--all` batch mode (`src/core/skillopt/batch.ts:runBatchAll`); `--target-models` fleet (`runFleet` parallel per-model receipts under `skillopt/fleet/<slug>/`); MCP op `run_skillopt` (admin scope + per-skill `skillopt.allowed_skills` allowlist, NOT localOnly, validates `skill_name` kebab-only + confines caller-supplied benchmark/held-out paths to skillsDir for remote callers); Minion `skillopt` handler + `--background` with `allowProtectedSubmit: true`; write-flavored optimization via `src/core/skillopt/write-capture.ts:buildWriteCaptureRegistry` (virtual `put_page`/`submit_job`/`file_upload` captured in-memory; `--write-capture` flag); held-out real-user test set via `src/core/skillopt/held-out.ts` (capture infra at `~/.gbrain/skillopt-captures/<skill>/<run>.jsonl`, `--held-out <path>` flag, `runHeldOutGate` candidate >= baseline). Hermetic via DI seams (`opts.chatFn` for optimizer + judge; `opts.toolLoopFn` for rollouts; no `mock.module`). `--bootstrap-from-skill` → `runBootstrapFromSkill` in `src/core/skillopt/bootstrap-benchmark.ts`: reads `SKILL.md` directly (no `routing-eval.jsonl`), makes ONE LLM call emitting a full starter benchmark (tasks + rule judges) as JSONL, parsed line-by-line with skip-bad-line salvage and a min-2-valid-checks-per-task drop; provider/transport errors PROPAGATE (not collapsed to `bootstrap_empty`). `--bootstrap-tasks N` (default 15, capped 50); `maxTokens` scales `min(8000, max(4000, N*220))`. The stderr REVIEW line prints the literal `gbrain skillopt <name> --bootstrap-reviewed --split 1:1:1` — load-bearing because the default `4:1:5` split makes a 15-task starter's `D_sel = floor(15/10) = 1`, below the `>=5` floor, so a 15-task benchmark needs `--split 1:1:1`. Both bootstrap generators share `assertBenchmarkAbsent` + `readSkillBodyOrThrow`; `--bootstrap-from-skill` is mutually exclusive with `--bootstrap-from-routing`/`--benchmark`/`--all`/`--target-models`/`--resume`. Generated rule judges are explicitly WEAK DRAFTS to be strengthened during the review gate. The held-out gate is wired: `--held-out <path>` is parsed and threaded through every caller (CLI main + `--background` `held_out_path` + batch/fleet `heldOutPath` + the `run_skillopt` `held_out_path` param), running at CHECKPOINT ACCEPTANCE so no-mutate/fleet paths can't promote a held-out-failing candidate. `assertBundledMutationHeldOut` in bundled-skill-gate.ts: bundled + `--allow-mutate-bundled` requires a NON-EMPTY held-out (`MIN_HELD_OUT_SIZE = D_SEL_MIN_SIZE` = 5, derived so they can't desync) or hard-refuses (exit 2), for ALL callers (they funnel through `runSkillOpt`); held-out must be task_id-DISJOINT from the benchmark (overlap rejected — can't catch overfitting). `receipt.baseline_sel_score` populated + a real final-test eval (`test_score` + `baseline_test_score`) scoring best + baseline on `split.test`; shared `scoreSkillOnTasks` primitive (validate-gate.ts) backs baseline/final-test/held-out scoring. `--no-mutate` writes proposed.md via `writeProposed` in version-store.ts. `maxRuntimeMin` ENFORCED (wall-clock deadline between steps → `skillopt_runtime_exceeded` → outcome aborted). Three eval-internal ablation opts on `SkillOptOpts` (NOT on CLI): `reflectMode` (`'both'`/`'failure-only'`), `disableValidationGate` (greedy-accept), `optimizerMode` (`'reflect'`/`'one-shot-rewrite'`), recorded in `RunReceipt` + audit `run_start` for replayability; `ROLLOUT_SUCCESS_THRESHOLD = 0.5` named constant for the partition; one-shot fence-strip is anchored (`^```...```$`) so an embedded code sample isn't truncated. Claude Haiku 4.5's dateless canonical id `claude-haiku-4-5` is in `src/core/anthropic-pricing.ts` (a `BudgetTracker`-capped run on Haiku would otherwise throw `no_pricing` on the FIRST `chat()` of every rollout); `runValidationGate` (validate-gate.ts) scans settled results for `isMustAbortError(error)` (from `worker-pool.ts`; `BUDGET_EXHAUSTED` is in `MUST_ABORT_ERROR_TAGS`) and re-throws so the caller aborts loudly instead of recording a hollow `selScore:0` — ordinary non-abort rollout errors still fail-open to `score:0` (judge-hiccup posture preserved). Pinned by 152 tests across 18 files (foundation + adversarial + v2 surface + E2E PGLite serial), `test/skillopt/bootstrap-from-skill.test.ts` (20 cases), `test/skillopt/rollout.test.ts`, `test/skillopt/validate-gate-abort.test.ts` (3 cases), held-out ENFORCE + one-shot-rewrite unit cases, and e2e (held-out block/allow, bundled no-mutate, runtime deadline, receipt honesty, held-out disjointness, no-DB-pollution). Drives the Track B SkillOpt benchmark suite in the sibling `gbrain-evals` repo.diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex b141510c96..7f32ac2f8a 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -46,7 +46,7 @@ Heuristic link-type inference (`attended`, `works_at`, `invested_in`, `founded`,## Cross-encoder reranker: 60% top-1 reshuffle-The reranker is on for the `balanced` and `tokenmax` mode bundles, off for `conservative`. The mode-bundle default is Voyage `rerank-2.5` (`DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as the embedding default); a brain with no `search.reranker.model` row reranks with it. Without the key, search fails open in RRF order: the gateway skips the HTTP call (`RerankError('no_key')`), writes ONE audit row per process, prints nothing, and stamps `reranker_skipped (no_key)` on the search meta — `gbrain search --explain` shows it, `gbrain search modes` prints a `Reranker:` readiness line, and `gbrain doctor`'s `reranker_health` names the fix (`export VOYAGE_API_KEY=…` or `gbrain config set search.reranker.enabled false`). Keyed installs without a Voyage key get reranking explicitly disabled at init. An explicit ZeroEntropy `zerank-*` config (`LEGACY_DEFAULT_RERANKER_MODEL`; hosted API ends 2026-09-04) short-circuits past that date before any HTTP: one audit row per process per model plus a single stderr line naming the switch command, and `gbrain doctor`'s `provider_sunset` check explains the state; a `base_urls` recipe override (self-hosted wire-compatible endpoint) suppresses the short-circuit. `reranker_model` is folded into the query-cache key unconditionally, so a model change can never serve a result set reranked by a different model. On a real-corpus benchmark across 20 queries, the cross-encoder reshuffled **60% of top-1 results** after the hybrid + RRF + graph stack (measured on zerank-2). The Voyage default's paired LongMemEval numbers live in [`docs/eval-bench.md`](../eval-bench.md#public-benchmarks-longmemeval).+The reranker is on for the `balanced` and `tokenmax` mode bundles, off for `conservative`. The mode-bundle default is Voyage `rerank-2.5` (`DEFAULT_RERANKER_MODEL`, same `VOYAGE_API_KEY` as the embedding default); a brain with no `search.reranker.model` row reranks with it. Without the key, search fails open in RRF order: the gateway skips the HTTP call (`RerankError('no_key')`), writes ONE audit row per process, prints nothing, and stamps `reranker_skipped (no_key)` on the search meta — `gbrain search --explain` shows it, `gbrain search modes` prints a `Reranker:` readiness line, and `gbrain doctor`'s `reranker_health` names the fix (`export VOYAGE_API_KEY=…` or `gbrain config set search.reranker.enabled false`). Keyed installs without a Voyage key get reranking explicitly disabled at init. An explicit ZeroEntropy `zerank-*` config (`LEGACY_DEFAULT_RERANKER_MODEL`; hosted API ends 2026-09-04) short-circuits past that date before any HTTP: one audit row per process per model plus a single stderr line naming the switch command, and `gbrain doctor`'s `provider_sunset` check explains the state; a `base_urls` recipe override (self-hosted wire-compatible endpoint) suppresses the short-circuit. The retained query-cache key includes `reranker_model`; persisted result reuse is disabled until every response dependency can be verified. On a real-corpus benchmark across 20 queries, the cross-encoder reshuffled **60% of top-1 results** after the hybrid + RRF + graph stack (measured on zerank-2). The Voyage default's paired LongMemEval numbers live in [`docs/eval-bench.md`](../eval-bench.md#public-benchmarks-longmemeval).The mechanical reason: hybrid ranking is locally optimal per strategy but globally suboptimal. A cross-encoder reranker reads the query + each candidate document jointly, with full attention. It catches the cases where the vector + keyword + graph signals all agreed on a document that's semantically related but topically wrong.@@ -137,7 +137,9 @@ Expansion is opt-in per mode bundle (`tokenmax` on by default; `balanced` + `con## Putting it together-The full pipeline for a `query` op:+The full pipeline for a trusted local `query` op follows. Remote retrieval+omits the optional code-graph augmentation stage; the policy-filtered typed-edge+relational recall arm remains available.```intent classify (query-intent.ts — deterministic, no LLM)@@ -204,8 +206,12 @@ Two cross-cutting seams sit around the pipeline rather than inside it:recall arm filters `visibility: private` pages via the shared predicate in`src/core/search/private-visibility.ts` (fail-closed default; operatoropt-outs documented in `docs/operations/mcp-surface-runbook.md`). The- posture folds into the query-cache key, so trusted and untrusted runs never- share cache rows.+ same policy also authorizes contributing pages, link origins, dates and+ annotations before enrichment. Semantic result caching is temporarily+ disabled regardless of configuration; each request performs fresh retrieval.+ Query embeddings can still be reused within that request. Repeated searches+ may have higher latency and provider usage until caching can verify every+ response dependency.- **CRAG-style confidence gate.** `src/core/search/crag.ts` grades every`query` op result (`strong`/`moderate`/`weak`) from the already-stampedhonesty signals — zero LLM, zero added latency — and attaches the grade to@@ -259,3 +265,42 @@ gbrain eval --qrels labels.tsv --config balanced.jsonThe current measured LongMemEval result (93.19% session-level `recall_all@5`, cleaned S split, 470 scored questions, k=5, measured 2026-09-02 at gbrain v0.48.2.0), its per-type table, and the reranker-on arms live in [`docs/eval-bench.md`](../eval-bench.md#public-benchmarks-longmemeval).Methodology + metric glossary in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md).++## Restricted salience++Remote reads default to the `world` take holder when no grant is supplied; an+explicit empty grant permits no takes. Counts and average weights use only+permitted active takes. Stored emotional weight contributes zero because it+combines all holders. Recent-salience inclusion uses `updated_at`, while the+existing recency formula is retained; unrestricted local reads keep their+existing formulas. Deleted, quarantined and archived contributors are excluded+before ranking, limits and anomaly-baseline aggregation. Default remote page+privacy also excludes private pages; its documented opt-outs do not widen+take-holder permissions.+++## Chunk rebuilds after upgrading++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+this rebuild too; trusted local chunk reads remain available. Body or chunk changes+invalidate that record until the next successful rebuild. Direct page reads+continue to use current source and visibility policy plus body sanitization.++Run rebuild commands from a local installation on the brain host; thin clients+cannot rebuild the host's indexes.+`gbrain reindex --markdown --dry-run --no-embed` previews the existing rebuild.+`gbrain reindex --markdown --no-embed` rebuilds without embedding calls, replacing+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.+++Optional code-graph expansion is omitted from remote search. The six dedicated+code-inspection operations are also temporarily local-only; see the+[MCP surface runbook](../operations/mcp-surface-runbook.md#temporary-code-inspection-availability).+These restrictions are separate from the chunk rebuild requirement.diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.mdindex 3465c2e774..df298d8c9a 100644--- a/docs/architecture/brains-and-sources.md+++ b/docs/architecture/brains-and-sources.md@@ -285,20 +285,16 @@ fail-closed and tested:slug-bound clients; every other non-read operation is refused (fail-closed:a write op added later is denied until it is fenced and allow-listed).-One known soft edge: the backlink-count ranking boost counts referrers-without source filtering, so the *existence* of out-of-grant referrers can-nudge result ordering (a count-only signal — no slug or content crosses the-boundary; direct edge reads are fully scoped). Scoping that counter is a-filed follow-up.--**Not an enforcement surface: page-level `visibility:` frontmatter.** A-`visibility: local` (or any other value) key in a page's frontmatter is inert-metadata — no schema column stores it, no query filters on it, and a remote-caller with a source grant retrieves the page like any other. If a page must-not be readable by remote callers, put it in a source those callers have no-grant for; that is the supported boundary. (A read-side per-page/per-prefix-ACL is deliberately not offered: it is a new authorization surface that-belongs to the mounts/brains access-policy design, not a bolt-on filter.)+Backlink-count ranking applies the caller's read policy to the result page,+each contributing referrer, and any independent edge-origin page before+counting. Graph enrichment uses the same source and page-visibility policy.++**Page-level `visibility: private` is enforced for remote callers by default.**+The exact frontmatter value `private` hides that concrete page row;+`visibility: local`, absent visibility, and other values do not. Trusted local+CLI callers retain access. Operator settings can opt out of private-page+filtering, so source grants remain an independent boundary: keep content in an+ungranted source when remote callers must have no access to that source.## Further readingdiff --git a/docs/contradictions.md b/docs/contradictions.mdindex 036d1f7712..560d8cfb84 100644--- a/docs/contradictions.md+++ b/docs/contradictions.md@@ -64,9 +64,9 @@ change)" decision is vibes. The probe produces evidence.│┌──────────────────┼──────────────────────┬───────────────┐▼ ▼ ▼ ▼- doctor (M1) MCP (M3) synthesize (M2) trend (M5)+ doctor (M1) local read (M3) synthesize (M2) trend (M5)surfaces find_contradictions informational persistent- findings op for agents block in prompt tracking+ findings unscoped callers block in prompt tracking```## Severity rubric@@ -79,8 +79,8 @@ The judge assigns severity per finding:| `medium` | factual values that may be stale | revenue figure, headcount, valuation || `high` | identity / structural claims | founder/CEO/CFO role, company status |-Doctor sorts findings by severity DESC. The MCP op accepts a severity filter-so agents can fetch just the high-priority items.+Doctor sorts findings by severity DESC. Trusted local callers without a source+filter can use the operation's severity filter to fetch high-priority items.## How to interpret the headline number@@ -144,8 +144,11 @@ pay near-zero on re-runs (until you bump PROMPT_VERSION).- Probe never mutates the brain. Runs only read pages/takes/chunks.Writes go only to `eval_contradictions_runs` and `eval_contradictions_cache`.-- MCP `find_contradictions` is read-scope. NOT in the subagent allowlist —- user-initiated only, not autonomous-action surface.+- `find_contradictions` is read-scope and is not in the subagent allowlist.+ Stored reports are temporarily available only to trusted local callers+ without a source filter. Remote or source-scoped callers receive+ `{ contradictions: [], note }` with an availability note; their requests+ do not load the stored report.- Build-fixture script is local-only. The redactor + `isCleanForCommit`gate makes accidental private-data commits hard, but the operator MUSTinspect every redaction before commit.diff --git a/docs/eval/SEARCH_MODE_METHODOLOGY.md b/docs/eval/SEARCH_MODE_METHODOLOGY.mdindex 97ddb54969..06f01105a7 100644--- a/docs/eval/SEARCH_MODE_METHODOLOGY.md+++ b/docs/eval/SEARCH_MODE_METHODOLOGY.md@@ -28,7 +28,7 @@ No private brain content is used in any reported result. The NDJSON run records- **Random seed:** `42` throughout. Set via `--seed N` on `gbrain eval run-all`; recorded in every per-run record.- **No per-question curation.** Splits are taken whole; no question is filtered for reporting.- **No mode-specific tuning.** The same dataset + same seed feeds every mode. The mode bundle is the only independent variable. A mode Δ therefore measures the joint effect of every knob the bundles differ on — today that's `tokenBudget`, `expansion`, `relationalRetrieval` (the typed-edge fourth recall arm, ON for balanced/tokenmax, OFF for conservative), and `searchLimit`; the canonical diff is `MODE_BUNDLES` in `src/core/search/mode.ts`.-- **Cache comparability across upgrades.** The query cache keys on a versioned knobs hash (`KNOBS_HASH_VERSION` in `mode.ts`) that folds in the active knob set + embedding column/provider, so one mode's cached results can't be served to another mode's queries — and a version bump makes prior rows unreachable (one-time miss spike). Cross-run comparisons that straddle a knobs-hash bump see a cold cache on the first re-run.+- **Cache comparability across upgrades.** Semantic result-cache reads and writes are temporarily disabled in every mode, regardless of configuration. Every query uses fresh retrieval. The retained storage machinery still keys rows on `KNOBS_HASH_VERSION` and the active knobs + embedding column/provider; historical runs with result caching enabled are not directly comparable to current runs for latency or provider spend.- **Stability across re-runs:** with `--seed 42` and the same dataset SHA, two runs of the same (mode, suite) produce identical retrieval orderings (modulo the optional Haiku expansion call, which is non-deterministic). Persisted in `eval_results` so anyone can re-score from a run's `--output` dumps.## 4. Run procedure@@ -65,7 +65,7 @@ Honest list. We name what would let a critic dismiss the numbers.- **char/4 token heuristic.** Token-budget enforcement and cost estimates use a character-count / 4 heuristic. Accurate within ~5-10% for English with the OpenAI tiktoken family; off worse for Voyage (we don't use Voyage in chat retrieval, so it doesn't bias the reported numbers, but if you do, your budget caps will be approximate).- **Expansion's quality lift varies by query distribution.** On LongMemEval-S (cleaned September 2025 revision, 470 scored, k=5, measured 2026-09-02 at gbrain v0.48.2.0 via the gbrain-evals runner) LLM multi-query expansion measures 54.89% `recall_all@5` against 93.19% without it, so expansion is off in `conservative`/`balanced`; the lift on rarer-entity / longer-tail queries is unmeasured here. We report the corpus we measured; YMMV.- **Paired bootstrap assumes question-level independence.** Multi-hop questions within the same conversation thread aren't independent; the bootstrap CI is slightly tighter than reality.-- **Single brain instance per benchmark.** The benchmark spins up an in-memory PGLite per question. Cache hit rate measured here doesn't reflect a long-running production brain's cache state.+- **Single brain instance per benchmark.** The benchmark spins up an in-memory PGLite per question. This does not reproduce a long-running production brain's state; current semantic result-cache hit rates are zero because result reuse is disabled.## 6. Per-question raw outputs@@ -152,10 +152,10 @@ The mode-picker prompt at `gbrain init` and the CLAUDE.md `## Search Mode` table**gbrain's own cost** on top:- Query embedding (text-embedding-3-large @ \$0.13/M tokens): ~\$0.00001 per query. Negligible at every scale.-- Tokenmax Haiku expansion call (\$1/M input, \$5/M output, ~500 input + 200 output per call): ~\$0.0015 per query, or \$150/mo at 100K queries. Cache hits cut this in half.+- Tokenmax Haiku expansion call (\$1/M input, \$5/M output, ~500 input + 200 output per call): ~\$0.0015 per query, or \$150/mo at 100K queries. Repeated queries still run expansion while semantic result caching is disabled.- Per-page indexing (one-time): bounded by your import volume, not query volume. Not modeled here.-**Cache hit adjustment.** A warmed brain typically sees 30-50% cache hits on repeat-query traffic. Cache hits skip the downstream input cost entirely (the cached result was already in the agent's context once). So real-world costs run ~50-70% of the table above on a busy brain.+**Cache hit adjustment.** Apply no semantic result-cache discount to these estimates while result caching is disabled. Downstream prompt caching can independently reduce cached-input charges, but it does not skip GBrain retrieval. The prompt-cache assumptions in the agent-loop example below describe that separate mechanism.**Why these numbers DRIFT from your actual bill:**- Your agent's system prompt + reasoning tokens add input that gbrain doesn't see.diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.mdindex cffee21e2e..35b5f2b819 100644--- a/docs/guides/search-modes.md+++ b/docs/guides/search-modes.md@@ -13,7 +13,12 @@ Two decisions shape every gbrain lookup, and this guide covers both:## The three mode bundlesA search mode is a named preset that sets every search-cost knob at once.-The bundles are frozen in `src/core/search/mode.ts` (`MODE_BUNDLES`):+The bundles are frozen in `src/core/search/mode.ts` (`MODE_BUNDLES`).++Semantic result caching is temporarily disabled in every mode, regardless of+configuration or per-call overrides. The cache settings below are retained+configuration values; each request performs fresh retrieval. Stored cache rows+and maintenance commands remain available.| Knob | `conservative` | `balanced` | `tokenmax` ||-------------------------------|----------------|------------|----------------|@@ -62,11 +67,11 @@ Per-knob resolution (highest first):Mode resolution lives in bare `hybridSearch`, not just the cached wrapper,so eval replays test the same mode-affected behavior as the production-`query` op. The query cache folds the active knobs into its key-(`knobs_hash`), so switching modes never serves you a stale result set-from a different configuration. Cache hits honor the same result-count-resolution as misses (per-call `limit`, else the mode's `searchLimit`) —-a cached page is sliced to what you asked for, never a fixed count.+`query` op. Result counts follow the per-call `limit`, or the mode's+`searchLimit` when no limit is supplied. The wrapper does not read or write+stored semantic results while caching is disabled. `gbrain search modes`+reports effective `cache_enabled: false`, and `cache stats` reports+`enabled: false`, even when retained configuration enables the cache.### Cost intuition@@ -81,9 +86,10 @@ Rough anchors at 10K queries/month, full payload, no cache savings:| balanced (~10K tok) | \$100/mo | \$300/mo | \$500/mo || tokenmax (~20K tok) | \$200/mo | \$600/mo | **\$1,000/mo** |-Scales linearly with volume. Cache hits cut all numbers ~50%; disciplined-prompt caching in the agent loop cuts further. Mismatched pairings waste-capacity in both directions — a tokenmax payload overwhelms a cheap model,+Scales linearly with volume. Budget for fresh retrieval on every query while+semantic result caching is disabled; repeated searches may take longer and use+more provider calls. Downstream prompt caching in the agent loop is independent.+Mismatched pairings waste capacity in both directions — a tokenmax payload overwhelms a cheap model,a conservative payload starves an expensive one. The full methodology andrealistic-scale walkthrough live in[`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md).diff --git a/docs/integrations/qm-harness.md b/docs/integrations/qm-harness.mdindex 40cf6e20e6..cbdcb648de 100644--- a/docs/integrations/qm-harness.md+++ b/docs/integrations/qm-harness.md@@ -84,16 +84,12 @@ boundary, and it does not make every side effect prefix-clean:page content. Unreachable in the layout above (the `agents` source ispath-less and holds no code pages); it applies only if you point employeewrites at a code-synced source.-- **Contradiction findings are matched by slug, not source.** The brain-wide- read ops (`get_recent_salience`, `find_anomalies`, `find_contradictions`,- and `sources_list`/`sources_status`) honor the federated grant (`sources_status` answers `not_found` for an out-of-grant- id, indistinguishable from a nonexistent source). The residual is- `find_contradictions`: findings carry no source attribution, so the scope- check is slug existence within the grant — a finding derived from an- ungranted source stays visible when a granted source holds a page with- the same slug. Per-endpoint source attribution is the filed follow-up- (TODOS.md); withhold `find_contradictions` at the harness layer if that- residual matters for your deployment.+- **Stored contradiction reports are temporarily local-only.**+ `find_contradictions` returns stored findings only to trusted local callers+ without a source filter. Harness clients receive `{ contradictions: [], note }`+ with an availability note. Other brain-wide read ops (`get_recent_salience`,+ `find_anomalies`, and `sources_list`/`sources_status`) honor the federated+ grant; `sources_status` answers `not_found` for an out-of-grant ID.- **Reads touch `last_retrieved_at`** on the pages they return, includingpages in read-only sources. Freshness/usage signals are thereforewritable-by-reading; nothing else about the page is.diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.mdindex 9e1518712d..6b9a97b3a2 100644--- a/docs/mcp/DEPLOY.md+++ b/docs/mcp/DEPLOY.md@@ -224,7 +224,7 @@ Remote agents cannot reach local filesystem surface area.|-------|---------------|| `read` | `search`, `query`, `get_page`, `list_pages`, graph traversal || `write` | `put_page`, `delete_page`, `add_link`, `add_timeline_entry` |-| `admin` | Client management, token revocation, sweep, local-only ops |+| `admin` | Client management, token revocation, sweep; local-only restrictions still apply |Write ops can additionally be fenced per client with `--bound-slug-prefixes`(see [Register OAuth clients](#2-register-oauth-clients) above).@@ -283,11 +283,15 @@ gbrain auth test \## Operations-GBrain's full operation catalog (100+ operations in `src/core/operations.ts`)-is available remotely, with no timeout limits on a self-hosted server. The-only exceptions are the operations flagged `localOnly: true` — `sync_brain`-and the `file_*` ops among them — which are rejected over HTTP regardless of-scope (see [Scopes and localOnly](#4-scopes-and-localonly) above).+GBrain's operation catalog (100+ operations in `src/core/operations.ts`) is+available subject to the selected surface, scope and operation-specific limits.+Operations flagged `localOnly: true` are rejected over HTTP regardless of scope+(see [Scopes and localOnly](#4-scopes-and-localonly) above). Code-inspection+operations and stored contradiction reports also have temporary local-only+restrictions, even when listed in the catalog. The [MCP surface runbook](../operations/mcp-surface-runbook.md)+explains these limits and the separate chunk-rebuild requirement. Rebuild+indexes from a local installation on the brain host; a thin client cannot+rebuild the host's indexes.**Several brains behind one tool catalog?** Give each server an identity so aconnected agent can tell them apart: `gbrain config set mcp.instructionsdiff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.mdindex 415655cea9..a429c26e3d 100644--- a/docs/operations/mcp-surface-runbook.md+++ b/docs/operations/mcp-surface-runbook.md@@ -140,9 +140,8 @@ ops: `get_page` / `fetch` / `list_pages`, `get_chunks` / `get_versions` /`get_timeline` / `get_raw_data`, `resolve_slugs`,`get_links` / `get_backlinks` / `traverse_graph`, and the list-styleanalytics ops `find_orphans` / `get_recent_salience` / `find_anomalies` /-`find_experts` (published counts and derived statistics are adjusted with-the filtered rows, so remote responses stay self-consistent and reveal-nothing about what was filtered). A gated page reads exactly+`find_experts`. Concrete rows and contributing pages are authorized inside+the database before limits and aggregate calculations. A gated page reads exactlylike a missing one (no existence oracle), and link/graph output neverenumerates private slugs.@@ -160,6 +159,20 @@ restores enforcement on the same schedule. Resolver:`src/core/search/private-visibility.ts`; a failed config read counts as"not opted out" (enforce).+Page-visibility opt-outs do not change protected-body filtering: remote page+and history bodies retain only world Facts and omit every Takes fence. History+also checks snapshot visibility while page privacy is enforced. Malformed+protected sections are omitted; unterminated or interleaved sections discard+the remaining tail. Restricted salience counts only permitted active takes and+ignores stored emotional weight; its recent window uses `updated_at` rather+than take-driven salience touches.++Semantic result caching is temporarily disabled even when configuration enables+it. Searches run fresh, so repeated requests may cost more and take longer.+Stored rows and cache maintenance remain available. Stored contradiction reports+are temporarily available only to trusted local callers without a source filter;+other callers receive an empty list and an availability note.+## Incident levers- **`GBRAIN_REMOTE_PRIVATE_PAGES=1`** — operator escape hatch for the@@ -177,14 +190,12 @@ restores enforcement on the same schedule. Resolver:retrieval (no allSettled salvage, strict budget, no minKeep failsafe)if the fail-loud retrieval behavior itself misbehaves.-**Total embed outage, what to expect (ENG-6):** the query cache is-uncacheable by construction during a full embedding outage — `query_cache`-keys on embedding similarity, and both store and lookup no-op on a null-embedding. Expect cache hit rate ~0 (`gbrain search stats`) and-keyword-only degraded results carrying `_meta.retrieval.degraded` stages-plus the model-visible block on empty results. This is the designed-degradation, not a second incident; only PARTIAL degradations (expansion-failed, vector arm failed) get short-TTL cache entries.+**Total embed outage, what to expect (ENG-6):** semantic result caching+remains disabled for both complete and partial degradations; neither reads+nor writes a cached response. New searches report caching as disabled, while+`gbrain search stats` can retain historical hits within its reporting window.+Expect keyword-only degraded results carrying `_meta.retrieval.degraded`+stages plus the model-visible block on empty results.## The honest-catalog metric (trend to zero)@@ -244,3 +255,14 @@ call '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search","a# 3+4 need write/agent scopes — run only when the token has them:# submit_agent → response contains "queue_state"; put_page → "writer_lint".```+++## Temporary code-inspection availability++`code_def`, `code_refs`, `code_callers`, `code_callees`, `code_blast`, and+`code_flow` are temporarily restricted to explicitly trusted local callers.+Remote and unset-trust calls receive an availability error before code storage+or traversal caches are read. Remote search also omits optional code-graph+expansion. Rebuilding search chunks restores ordinary chunk retrieval; it does+not lift this separate code-tool restriction. No remote permission override is+available. Trusted local code commands retain their existing behavior.diff --git a/llms-full.txt b/llms-full.txtindex c4360b2b3e..5fad5a626f 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -409,15 +409,16 @@ Mismatches (tokenmax+Haiku, conservative+Opus) waste capacity differentlyexpensive one.tokenmax adds ~\$1.50 per 1K queries in Haiku expansion calls on top of-the matrix (\$15/mo @ 10K). Cache hits cut all numbers ~50%. **The matrix+the matrix (\$15/mo @ 10K). Semantic result caching is temporarily disabled; budget for fresh retrieval on every query. **The matrixhas three verbatim homes: this section, the `gbrain init` picker copy(`src/commands/init-mode-picker.ts`), and `INSTALL_FOR_AGENTS.md` Step3.5** — update all three when refreshing.**Per-query math vs real-world spend.** The matrix above is what anisolated benchmark would measure. Real agent loops with disciplined-Anthropic prompt caching see 50-80% discount on top (cache hits skip-downstream entirely). The realistic-scale anchor in+Anthropic prompt caching see 50-80% discount on top through lower+cached-input charges. This is separate from GBrain's disabled semantic result+cache. The realistic-scale anchor in`docs/eval/SEARCH_MODE_METHODOLOGY.md` walks the natural pairings atsingle-power-user volume (~860 turns/mo): tokenmax+Opus ~\$700/mo,balanced+Sonnet ~\$430/mo, conservative+Haiku ~\$170/mo. Setups WITHOUT@@ -435,6 +436,8 @@ per `[CDX-5+6]` in `~/.claude/plans/lets-take-a-look-validated-parrot.md` — so`gbrain eval replay` and `gbrain eval longmemeval` test the same mode-affectedbehavior as the production `query` op.+**Effective cache availability:** semantic result lookup and writes are temporarily disabled in the shared wrapper, regardless of mode, config, or `use_cache`. Stored rows and maintenance commands remain. `cache.status`, cache statistics and the mode dashboard report disabled. The following cache-key notes describe retained storage machinery, not active response reuse.+**Cache-key contamination hotfix `[CDX-4]`:** migration v56 added a`knobs_hash` column to `query_cache`. The lookup filter is now`WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $` so a@@ -2011,6 +2014,13 @@ Postgres-at-scale, Supabase, and thin-client setup paths live in [`docs/INSTALL.GBrain exposes nearly all of its 100+ operations as MCP tools (stdio and HTTP; a handful of local-only ops stay CLI-side) — or exactly the seven memory verbs with `--surface verbs`. The specific snippet depends on which client you use:+**Upgrading an existing brain:** existing search chunks need rebuilding before+remote chunk retrieval resumes. Semantic result caching is temporarily disabled;+stored contradiction reports and code-inspection tools have local-only limits.+Follow the [upgrade recovery guide](skills/migrations/v0.48.3.0.md) for rebuild+commands, embedding costs, and the restrictions that remain after rebuilding.+**Say to your agent:** *"Upgrade gbrain and check whether my search index needs rebuilding."*+- **[Claude Code](docs/mcp/CLAUDE_CODE.md)** — plugin: `/plugin marketplace add garrytan/gbrain` + `/plugin install gbrain@gbrain` (MCP + skills; persona variants `gbrain-coding` / `gbrain-daily` install curated subsets — pick exactly one gbrain plugin). Marketplace-free skills: `gbrain skillpack scaffold --harness claude-code` copies a persona-curated skill set into your user-scope skills dir with a local-edit-respecting update lens. Or local one-liner: `claude mcp add gbrain -- gbrain serve` (zero server, zero tunnel). Remote with just a bearer token: `gbrain connect https://your-host/mcp --token gbrain_xxx` prints a paste-ready block (or `--install` wires it up and smoke-tests the token).- **[Codex](docs/mcp/CODEX.md)** — plugin (recommended): `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain` installs the MCP server AND the curated skill set. Or connect-only: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`); Codex reads the bearer from `$GBRAIN_REMOTE_TOKEN` at runtime, so the token never lands in Codex config.- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve"]}` to your MCP config.@@ -2172,7 +2182,7 @@ gbrain schema use my-pack # activate**Say to your agent:** *"My schema isn't matching my notes — propose new types from my corpus"* — *"Add a page type for lab results to my brain's schema."* The schema-author skill runs the detect → suggest → review flow for you.-The active pack threads through every read + write path: `parseMarkdown` infers page type from the pack's path prefixes; `whoknows` scopes expert routing to types declared `expert_routing: true`; `extract_facts` runs only on `extractable: true` types; the search cache folds the pack name + version into its key so cross-pack contamination is structurally impossible. Switch packs and the brain re-interprets itself; switch back and nothing's lost.+The active pack threads through every read + write path: `parseMarkdown` infers page type from the pack's path prefixes; `whoknows` scopes expert routing to types declared `expert_routing: true`; `extract_facts` runs only on `extractable: true` types. The retained search-cache key includes the pack name + version, but semantic result reuse is temporarily disabled. Switch packs and the brain re-interprets itself; switch back and nothing's lost.Seven-tier resolution chain (per-call flag → env var → per-source DB key → brain-wide DB key → `gbrain.yml` → `~/.gbrain/config.json` → `gbrain-base` default). Full reference + authoring guide: [`docs/architecture/schema-packs.md`](docs/architecture/schema-packs.md).@@ -5118,7 +5128,7 @@ Remote agents cannot reach local filesystem surface area.|-------|---------------|| `read` | `search`, `query`, `get_page`, `list_pages`, graph traversal || `write` | `put_page`, `delete_page`, `add_link`, `add_timeline_entry` |-| `admin` | Client management, token revocation, sweep, local-only ops |+| `admin` | Client management, token revocation, sweep; local-only restrictions still apply |Write ops can additionally be fenced per client with `--bound-slug-prefixes`(see [Register OAuth clients](#2-register-oauth-clients) above).@@ -5177,11 +5187,15 @@ gbrain auth test \## Operations-GBrain's full operation catalog (100+ operations in `src/core/operations.ts`)-is available remotely, with no timeout limits on a self-hosted server. The-only exceptions are the operations flagged `localOnly: true` — `sync_brain`-and the `file_*` ops among them — which are rejected over HTTP regardless of-scope (see [Scopes and localOnly](#4-scopes-and-localonly) above).+GBrain's operation catalog (100+ operations in `src/core/operations.ts`) is+available subject to the selected surface, scope and operation-specific limits.+Operations flagged `localOnly: true` are rejected over HTTP regardless of scope+(see [Scopes and localOnly](#4-scopes-and-localonly) above). Code-inspection+operations and stored contradiction reports also have temporary local-only+restrictions, even when listed in the catalog. The [MCP surface runbook](../operations/mcp-surface-runbook.md)+explains these limits and the separate chunk-rebuild requirement. Rebuild+indexes from a local installation on the brain host; a thin client cannot+rebuild the host's indexes.**Several brains behind one tool catalog?** Give each server an identity so aconnected agent can tell them apart: `gbrain config set mcp.instructionsdiff --git a/llms.txt b/llms.txtindex f055f1b71a..a10cd40078 100644--- a/llms.txt+++ b/llms.txt@@ -44,7 +44,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.46.3.0 — the ZeroEntropy-sunset embedding + reranker switch playbook).+- [skills/migrations/](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/migrations/): Per-version agent-executable migration instructions (latest: v0.48.3.0 — index rebuilds and temporary search/report/tool availability).- [CHANGELOG.md](https://raw.githubusercontent.com/garrytan/gbrain/master/CHANGELOG.md): Release-summary voice + itemized changes + self-repair block per version.## Contributingdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 4a2a5fadd0..079b3f2db0 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.48.2.0",+ "version": "0.48.3.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex d30779ea0c..a00139d27e 100644--- a/package.json+++ b/package.json@@ -45,7 +45,7 @@"build:pglite-snapshot": "bun run scripts/build-pglite-snapshot.ts","test": "bash scripts/run-unit-parallel.sh","eval:autocut": "bun test test/search/autocut-eval.test.ts",- "test:full": "bun run verify && bash scripts/run-unit-parallel.sh && bun run test:slow && ([ -n \"$DATABASE_URL\" ] && bash scripts/run-e2e.sh || echo '[test:full] skipped E2E (no DATABASE_URL); run docker-compose -f docker-compose.ci.yml up + bun run test:e2e to include' 1>&2)",+ "test:full": "bun run verify && bash scripts/run-unit-parallel.sh && bun run test:slow && (if [ -n \"$DATABASE_URL\" ]; then bash scripts/run-e2e.sh; else echo '[test:full] skipped E2E (no DATABASE_URL); run docker-compose -f docker-compose.ci.yml up + bun run test:e2e to include' 1>&2; fi)","verify": "bash scripts/run-verify-parallel.sh","check:source-config-leak": "bash scripts/check-source-config-leak.sh","check:no-pii-agent-voice": "bash scripts/check-no-pii-in-agent-voice.sh",@@ -174,7 +174,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.48.2.0",+ "version": "0.48.3.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "3.1.6",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex ecc5f782a5..c0cc345a78 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.48.2.0",+ "version": "0.48.3.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.jsonindex 0fe1e15c50..6f2a71741a 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.48.2.0",+ "version": "0.48.3.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.mdindex 0e0be5d67d..95afbdbc32 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.48.2.0 -->+<!-- gbrain-plugin-tree-stamp: 0.48.3.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-coding/skills/conventions/search-modes.md b/plugin-variants/gbrain-coding/skills/conventions/search-modes.mdindex 5c0b4b8c26..0b663dbc9b 100644--- a/plugin-variants/gbrain-coding/skills/conventions/search-modes.md+++ b/plugin-variants/gbrain-coding/skills/conventions/search-modes.md@@ -7,7 +7,7 @@ type: convention# Convention: Search Modes (v0.32.3)> **Convention:** every brain has one active search mode. The mode bundles the-> search-lite knobs from PR #897 (semantic cache, token budget, intent+> search-lite knobs (semantic result-cache settings, token budget, intent> weighting, LLM expansion, result limit) into a single config key:> `search.mode = conservative | balanced | tokenmax`.@@ -17,7 +17,7 @@ Any agent doing search-adjacent work in a gbrain brain consults this convention:- `brain-ops` / `query` / `signal-detector` skills: respect the active mode atsearch time. Per-call `SearchOpts` overrides win when set; mode is the default.-- Skills that recommend tuning ("the cache hit rate is high — raise threshold?"):+- Skills that recommend tuning ("which search mode fits this brain?"):route operators to `gbrain search tune` rather than rolling their own logic.- New skills that add per-call retrieval overrides: name them explicitly sothe resolved-knob attribution dashboard (`gbrain search modes`) reads cleanly.@@ -40,9 +40,12 @@ The canonical knob table (with cost anchors) lives in| `relationalRetrieval` | false | **true** | **true** || `searchLimit` default | 10 | 25 | 50 |-**Cache, intent weighting, and similarity threshold are constant across modes**-— they're free wins (no API cost). Modes scale the three cost levers:-`tokenBudget`, `expansion`, `searchLimit`.+**Effective semantic result caching is disabled in every mode.** The table+retains the stored bundle values, but result lookup and writes are bypassed+regardless of config or `use_cache`. Cache statistics and the mode dashboard+report disabled; repeated queries perform fresh retrieval. Intent weighting+and the retained cache knobs remain constant across modes. Modes scale+`tokenBudget`, `expansion`, and `searchLimit`.## Resolution chain (matches v0.31.12 model-tier shape)@@ -70,15 +73,15 @@ and prints a paste-ready revert command.## Cache contamination guard-Migration v56 added `query_cache.knobs_hash`. A tokenmax write-(expansion=on, limit=50) is keyed by a different hash than a conservative-read (no expansion, limit=10), so cross-mode contamination is structurally-impossible. The cache lookup filter is:+The retained `query_cache.knobs_hash` machinery separates mode settings:+tokenmax (expansion=on, limit=50) has a different hash from conservative+(no expansion, limit=10). Its stored lookup filter is:WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $-Legacy NULL-knobs_hash rows from pre-v0.32.3 are silently excluded-(treated as misses, re-populated with the right hash on first hit).+Legacy NULL-knobs_hash rows remain excluded. No semantic result rows are read+or repopulated while caching is disabled; changing the stored knobs cannot+restore result reuse.## Trigger phrasesdiff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex 930cb28c4e..541368f4af 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.48.2.0",+ "version": "0.48.3.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.jsonindex 47bb2bea28..81827fe751 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.48.2.0",+ "version": "0.48.3.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.mdindex 34c2b206ab..f720f08c0d 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.48.2.0 -->+<!-- gbrain-plugin-tree-stamp: 0.48.3.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-variants/gbrain-daily/skills/conventions/search-modes.md b/plugin-variants/gbrain-daily/skills/conventions/search-modes.mdindex 5c0b4b8c26..0b663dbc9b 100644--- a/plugin-variants/gbrain-daily/skills/conventions/search-modes.md+++ b/plugin-variants/gbrain-daily/skills/conventions/search-modes.md@@ -7,7 +7,7 @@ type: convention# Convention: Search Modes (v0.32.3)> **Convention:** every brain has one active search mode. The mode bundles the-> search-lite knobs from PR #897 (semantic cache, token budget, intent+> search-lite knobs (semantic result-cache settings, token budget, intent> weighting, LLM expansion, result limit) into a single config key:> `search.mode = conservative | balanced | tokenmax`.@@ -17,7 +17,7 @@ Any agent doing search-adjacent work in a gbrain brain consults this convention:- `brain-ops` / `query` / `signal-detector` skills: respect the active mode atsearch time. Per-call `SearchOpts` overrides win when set; mode is the default.-- Skills that recommend tuning ("the cache hit rate is high — raise threshold?"):+- Skills that recommend tuning ("which search mode fits this brain?"):route operators to `gbrain search tune` rather than rolling their own logic.- New skills that add per-call retrieval overrides: name them explicitly sothe resolved-knob attribution dashboard (`gbrain search modes`) reads cleanly.@@ -40,9 +40,12 @@ The canonical knob table (with cost anchors) lives in| `relationalRetrieval` | false | **true** | **true** || `searchLimit` default | 10 | 25 | 50 |-**Cache, intent weighting, and similarity threshold are constant across modes**-— they're free wins (no API cost). Modes scale the three cost levers:-`tokenBudget`, `expansion`, `searchLimit`.+**Effective semantic result caching is disabled in every mode.** The table+retains the stored bundle values, but result lookup and writes are bypassed+regardless of config or `use_cache`. Cache statistics and the mode dashboard+report disabled; repeated queries perform fresh retrieval. Intent weighting+and the retained cache knobs remain constant across modes. Modes scale+`tokenBudget`, `expansion`, and `searchLimit`.## Resolution chain (matches v0.31.12 model-tier shape)@@ -70,15 +73,15 @@ and prints a paste-ready revert command.## Cache contamination guard-Migration v56 added `query_cache.knobs_hash`. A tokenmax write-(expansion=on, limit=50) is keyed by a different hash than a conservative-read (no expansion, limit=10), so cross-mode contamination is structurally-impossible. The cache lookup filter is:+The retained `query_cache.knobs_hash` machinery separates mode settings:+tokenmax (expansion=on, limit=50) has a different hash from conservative+(no expansion, limit=10). Its stored lookup filter is:WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $-Legacy NULL-knobs_hash rows from pre-v0.32.3 are silently excluded-(treated as misses, re-populated with the right hash on first hit).+Legacy NULL-knobs_hash rows remain excluded. No semantic result rows are read+or repopulated while caching is disabled; changing the stored knobs cannot+restore result reuse.## Trigger phrasesdiff --git a/plugin/README.md b/plugin/README.mdindex 6fc1a6750c..71cfb3a3bc 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.48.2.0 -->+<!-- gbrain-plugin-tree-stamp: 0.48.3.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/plugin/skills/conventions/search-modes.md b/plugin/skills/conventions/search-modes.mdindex 5c0b4b8c26..0b663dbc9b 100644--- a/plugin/skills/conventions/search-modes.md+++ b/plugin/skills/conventions/search-modes.md@@ -7,7 +7,7 @@ type: convention# Convention: Search Modes (v0.32.3)> **Convention:** every brain has one active search mode. The mode bundles the-> search-lite knobs from PR #897 (semantic cache, token budget, intent+> search-lite knobs (semantic result-cache settings, token budget, intent> weighting, LLM expansion, result limit) into a single config key:> `search.mode = conservative | balanced | tokenmax`.@@ -17,7 +17,7 @@ Any agent doing search-adjacent work in a gbrain brain consults this convention:- `brain-ops` / `query` / `signal-detector` skills: respect the active mode atsearch time. Per-call `SearchOpts` overrides win when set; mode is the default.-- Skills that recommend tuning ("the cache hit rate is high — raise threshold?"):+- Skills that recommend tuning ("which search mode fits this brain?"):route operators to `gbrain search tune` rather than rolling their own logic.- New skills that add per-call retrieval overrides: name them explicitly sothe resolved-knob attribution dashboard (`gbrain search modes`) reads cleanly.@@ -40,9 +40,12 @@ The canonical knob table (with cost anchors) lives in| `relationalRetrieval` | false | **true** | **true** || `searchLimit` default | 10 | 25 | 50 |-**Cache, intent weighting, and similarity threshold are constant across modes**-— they're free wins (no API cost). Modes scale the three cost levers:-`tokenBudget`, `expansion`, `searchLimit`.+**Effective semantic result caching is disabled in every mode.** The table+retains the stored bundle values, but result lookup and writes are bypassed+regardless of config or `use_cache`. Cache statistics and the mode dashboard+report disabled; repeated queries perform fresh retrieval. Intent weighting+and the retained cache knobs remain constant across modes. Modes scale+`tokenBudget`, `expansion`, and `searchLimit`.## Resolution chain (matches v0.31.12 model-tier shape)@@ -70,15 +73,15 @@ and prints a paste-ready revert command.## Cache contamination guard-Migration v56 added `query_cache.knobs_hash`. A tokenmax write-(expansion=on, limit=50) is keyed by a different hash than a conservative-read (no expansion, limit=10), so cross-mode contamination is structurally-impossible. The cache lookup filter is:+The retained `query_cache.knobs_hash` machinery separates mode settings:+tokenmax (expansion=on, limit=50) has a different hash from conservative+(no expansion, limit=10). Its stored lookup filter is:WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $-Legacy NULL-knobs_hash rows from pre-v0.32.3 are silently excluded-(treated as misses, re-populated with the right hash on first hit).+Legacy NULL-knobs_hash rows remain excluded. No semantic result rows are read+or repopulated while caching is disabled; changing the stored knobs cannot+restore result reuse.## Trigger phrasesdiff --git a/scripts/ci-cache-hash.sh b/scripts/ci-cache-hash.shdeleted file mode 100755index 9a7f952db4..0000000000--- a/scripts/ci-cache-hash.sh+++ /dev/null@@ -1,188 +0,0 @@-#!/usr/bin/env bash-# scripts/ci-cache-hash.sh — deterministic content hash of all test--# affecting files for the CI auto-cache.-#-# Outputs a 16-character hex prefix of sha256(sorted list of-# `<git-blob-sha> <path>` lines for every tracked file EXCEPT the-# deny-list below). Same tree → same hash. Different code → different-# hash. Doc-only changes → same hash (cache hit).-#-# Used by .github/workflows/test.yml's cache-check job. Cache key is-# `ci-pass-<hash>`. When the hash matches a prior green run, the test-# matrix skips and reports green immediately.-#-# DESIGN: deny-list NOT allowlist. New files default to "include in-# hash" — worst case, cache miss (waste 8min). Allowlist would default-# to "exclude", risking false-pass (broken code shipped under green-# check) when someone adds a new file type that tests read.-#-# WHAT'S DENY-LISTED (genuinely test-irrelevant):-# - CHANGELOG.md, TODOS.md pure documentation-# - README.md, LICENSE marketing / metadata — but README.md is-# re-admitted below [C2]: the bootstrap paste-# block lives in it and check-bootstrap-tag.sh-# asserts its distribution refs-# - docs/**/*.md, *.txt all docs/ subtree is doc-only-#-# WHAT'S DELIBERATELY NOT DENY-LISTED (affects test outcomes):-# - CLAUDE.md 8+ test files reference it (resolver-merge, schema-cli,-# public-exports, eval-cross-modal-batch, etc.)-# - AGENTS.md same — referenced by resolver tests; counterpart to-# CLAUDE.md for OpenClaw hosts-# - skills/** SKILL.md files are read by skill conformance tests-# - everything else under src/, test/, scripts/, .github/, package.json,-# bun.lock, tsconfig*.json, the schema files — obviously test-affecting-#-# POLICY-DOC RE-ADMIT (the docs/ exception): some docs/*.md files carry-# CI / release / test CONTRACTS that the test suite reads (e.g. the-# build-llms content-contract test, the doc-history guard). The broad-# `^docs/.*\.md$` deny above would let a policy edit to those skip CI — a-# false-pass. The ALLOW_PATTERNS list below re-admits them into the hash-# AFTER the deny. ADD a path there whenever you move a policy/contract doc-# under docs/ (current entries: docs/TESTING.md, docs/RELEASING.md,-# README.md, BOOTSTRAP_FOR_AGENTS.md).-#-# The same mechanism re-admits the agent-bootstrap entry documents [C2]:-# README.md (denied above) and BOOTSTRAP_FOR_AGENTS.md (not denied today —-# listed defensively so a future root-doc deny can't silently drop it).-# Both carry the paste-block distribution contract that-# scripts/check-bootstrap-tag.sh asserts (sanctioned `latest-stable` ref +-# runbook version stamp), so a README-only paste-block change must never-# skip CI green.-#-# Locale-stable: LC_ALL=C on the sort step so byte-order is identical-# across runners (different default locales would re-order the line list-# and change the final hash).-#-# Usage:-# bash scripts/ci-cache-hash.sh # print hash-# bash scripts/ci-cache-hash.sh --verbose # print hash + diagnostics to stderr-#-# Exit codes:-# 0 printed a 16-char hex hash-# 1 internal error (git failure, etc.)-# 2 usage error--set -euo pipefail--VERBOSE=0-if [ "${1:-}" = "--verbose" ]; then- VERBOSE=1- shift-fi-if [ "$#" -gt 0 ]; then- echo "usage: bash scripts/ci-cache-hash.sh [--verbose]" >&2- exit 2-fi--cd "$(dirname "$0")/.."--# Deny-list as an extended regex matched against full paths emitted by-# `git ls-files`. -x makes the match anchored (full-line). Each pattern-# is a path predicate, not a glob — `\.` to literal-match dots.-#-# To add a new deny entry: add another `-e '<regex>'` line below. To-# REMOVE a deny entry (= include the path back in hash): delete its line.-# Either change invalidates the cache for everyone on next run (different-# hash output), which is the correct behavior.-DENY_PATTERNS=(- -e '^CHANGELOG\.md$'- -e '^TODOS\.md$'- -e '^README\.md$'- -e '^LICENSE$'- -e '^docs/.*\.md$'- -e '^docs/.*\.txt$'-)--# Use `git ls-files -s` for one-shot enumeration of tracked files + their-# index blob shas. Output shape: `<mode> <sha> <stage>\t<path>` per line.-# Far faster than per-file `git hash-object` (~30ms vs ~9s on 2000 files).-#-# Trade-off: this reflects the INDEX (committed/staged state), not the-# working tree. CI always works against a committed tree so this matches-# what tests actually run. Local dev with uncommitted edits sees the-# committed-side hash (close enough — the hash is for CI's cache lookup,-# not a tree-state diagnostic).-LS_FILES=$(git ls-files -s)-if [ -z "$LS_FILES" ]; then- echo "error: git ls-files -s returned empty (are we in a git repo?)" >&2- exit 1-fi--# Apply deny-list. Each line ends in `\t<path>` so the deny patterns-# anchor on a tab boundary. Compose the alternation regex from-# DENY_PATTERNS — each entry is `^<pat>$`; strip the `^` (since `\t`-# acts as our anchor in `git ls-files -s` output) and the trailing `$`-# stays as-is.-DENY_ALT=""-i=1-while [ $i -lt ${#DENY_PATTERNS[@]} ]; do- p="${DENY_PATTERNS[$i]}"- p="${p#^}"- if [ -z "$DENY_ALT" ]; then- DENY_ALT="$p"- else- DENY_ALT="$DENY_ALT|$p"- fi- i=$((i + 2))-done-DENY_RE=$(printf '\t(%s)' "$DENY_ALT")-# Note: each $p already ends in `$` to anchor end-of-line, so the full-# regex is `\t(^CHANGELOG\.md$|^TODOS\.md$|...)`. Wait — we stripped `^`-# from each but kept `$`, so the composed regex is `\t(CHANGELOG\.md$|-# TODOS\.md$|docs/.*\.md$|...)`. Each alternative anchors its own end.-INCLUDED=$(printf '%s\n' "$LS_FILES" | grep -vE "$DENY_RE" || true)--# Re-admit test-affecting policy docs that live under docs/ but carry CI /-# release / test contracts. The broad `^docs/.*\.md$` deny above removed-# them; without this re-admit a policy edit to docs/TESTING.md or-# docs/RELEASING.md would produce the SAME hash and skip the test shard-# that runs the build-llms + doc-history guards — a false-pass. Patterns-# anchor on the `\t<path>` boundary in `git ls-files -s` output, matching-# the deny-list convention above. Re-admitted lines that don't exist yet-# (pre-relocation) simply match nothing.-# Path predicates only (no leading tab here) — the `\t` boundary is added-# via printf below so it is a REAL tab byte, not the two-char string `\t`.-# GNU grep (CI/Ubuntu) does not interpret `\t` in an ERE as a tab the way-# BSD grep (macOS) does, so an inline `\t` matches nothing on CI and the-# re-admit silently no-ops. Mirror the DENY_RE construction exactly.-ALLOW_PATTERNS=(- 'docs/TESTING\.md$'- 'docs/RELEASING\.md$'- 'README\.md$'- 'BOOTSTRAP_FOR_AGENTS\.md$'-)-ALLOW_ALT=""-for p in "${ALLOW_PATTERNS[@]}"; do- if [ -z "$ALLOW_ALT" ]; then ALLOW_ALT="$p"; else ALLOW_ALT="$ALLOW_ALT|$p"; fi-done-ALLOW_RE=$(printf '\t(%s)' "$ALLOW_ALT")-READMIT=$(printf '%s\n' "$LS_FILES" | grep -E "$ALLOW_RE" || true)-if [ -n "$READMIT" ]; then- INCLUDED=$(printf '%s\n%s\n' "$INCLUDED" "$READMIT" | grep -v '^$' | LC_ALL=C sort -u)-fi--if [ -z "$INCLUDED" ]; then- echo "error: every tracked file is deny-listed — refusing to hash empty set" >&2- exit 1-fi--# Sort by full line (LC_ALL=C for byte-order stability across locales),-# hash the concatenation. Each line carries (mode, sha, path) so any-# change to content (sha), mode (executable bit), or path (rename) flips-# the final hash.-HASH=$(printf '%s\n' "$INCLUDED" \- | LC_ALL=C sort \- | sha256sum \- | cut -c1-16)--if [ "$VERBOSE" = "1" ]; then- included_count=$(printf '%s\n' "$INCLUDED" | wc -l | tr -d ' ')- all_count=$(printf '%s\n' "$LS_FILES" | wc -l | tr -d ' ')- denied_count=$((all_count - included_count))- {- echo "ci-cache-hash: $included_count/$all_count files in hash ($denied_count deny-listed)"- } >&2-fi--echo "$HASH"diff --git a/scripts/ci-local.sh b/scripts/ci-local.shindex 0be11d9457..0b57d652ad 100755--- a/scripts/ci-local.sh+++ b/scripts/ci-local.sh@@ -64,7 +64,8 @@ if [ "$DIFF" = "1" ]; thenecho "[ci-local] --diff: diff is doc-only — skipping postgres + unit + E2E (Tier 2 fast-path)."echo "[ci-local] Running gitleaks on host as the only gate..."if ! command -v gitleaks >/dev/null 2>&1; then- echo "[ci-local] WARN: gitleaks not installed; skipping. brew install gitleaks." >&2+ echo "[ci-local] ERROR: gitleaks not installed; the required secrets scan cannot run. Install gitleaks and retry." >&2+ exit 1elsegitleaks dir . --redact --no-bannergitleaks git . --redact --no-banner --log-opts="origin/master..HEAD"@@ -193,6 +194,10 @@ bash scripts/check-progress-to-stdout.shbash scripts/check-trailing-newline.shbash scripts/check-wasm-embedded.shbun run typecheck+echo "[runner] serial tests (DATABASE_URL unset)"+env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:serial+echo "[runner] slow tests (DATABASE_URL unset)"+env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:slowecho "[runner] unit (unsharded, DATABASE_URL unset)"env -u DATABASE_URL bash scripts/run-unit-shard.shecho "[runner] e2e (unsharded, --diff selected)"@@ -200,10 +205,13 @@ SELECTED=$(bun run scripts/select-e2e.ts)if [ -z "$SELECTED" ]; thenecho "[runner] selector emitted nothing (doc-only diff); skipping E2E."else+ printf "%s\n" "$SELECTED" > /tmp/e2e-selected.txtDATABASE_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test \GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer \GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test \- echo "$SELECTED" | xargs bash scripts/run-e2e.sh+ GBRAIN_CI_REQUIRE_PGBOUNCER=1 \+ GBRAIN_TEST_DB=1 \+ xargs -a /tmp/e2e-selected.txt bash scripts/run-e2e.shfi'elseRUN_PHASES_CMD='echo "[runner] guards + typecheck"@@ -212,12 +220,18 @@ bash scripts/check-progress-to-stdout.shbash scripts/check-trailing-newline.shbash scripts/check-wasm-embedded.shbun run typecheck+echo "[runner] serial tests (DATABASE_URL unset)"+env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:serial+echo "[runner] slow tests (DATABASE_URL unset)"+env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:slowecho "[runner] unit (unsharded, DATABASE_URL unset)"env -u DATABASE_URL bash scripts/run-unit-shard.shecho "[runner] e2e (unsharded)"DATABASE_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test \GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer \GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test \+GBRAIN_CI_REQUIRE_PGBOUNCER=1 \+GBRAIN_TEST_DB=1 \bash scripts/run-e2e.sh'fielse@@ -240,6 +254,10 @@ bash scripts/check-progress-to-stdout.shbash scripts/check-trailing-newline.shbash scripts/check-wasm-embedded.shbun run typecheck+echo \"[runner] serial tests (DATABASE_URL unset)\"+env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:serial+echo \"[runner] slow tests (DATABASE_URL unset)\"+env -u DATABASE_URL -u GBRAIN_DATABASE_URL bun run test:slowecho \"[runner] Tier 3: PGLite snapshot fixture (idempotent; rebuilds on hash drift)\"# W0 fix-wave (Tier-1 #16): unconditional call — the build script self-# short-circuits on a fresh hash and rebuilds STALE snapshots (the old@@ -273,12 +291,16 @@ printf '%s\\n' 1 2 3 4 | xargs -P4 -I{} sh -c 'DATABASE_URL=postgresql://postgres:postgres@postgres-\${shard}:5432/gbrain_test \\GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer \\GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test \\+ GBRAIN_CI_REQUIRE_PGBOUNCER=1 \\+ GBRAIN_TEST_DB=1 \\xargs -a /tmp/e2e-selected.txt bash scripts/run-e2e.sh >> \$log 2>&1elseSHARD=\${shard}/4 \\DATABASE_URL=postgresql://postgres:postgres@postgres-\${shard}:5432/gbrain_test \\GBRAIN_PGBOUNCER_URL=postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer \\GBRAIN_PGBOUNCER_DIRECT_URL=postgresql://postgres:postgres@postgres-1:5432/gbrain_test \\+ GBRAIN_CI_REQUIRE_PGBOUNCER=1 \\+ GBRAIN_TEST_DB=1 \\bash scripts/run-e2e.sh >> \$log 2>&1fie2e_exit=\$?@@ -290,6 +312,9 @@ printf '%s\\n' 1 2 3 4 | xargs -P4 -I{} sh -c '' _ {}shard_xargs_exit=\$?set -e+mkdir -p .context/ci-local-shards+cp /tmp/shard-logs/shard-*.log .context/ci-local-shards/+echo \"[runner] Complete shard logs saved to .context/ci-local-shards/\"echo \"\"echo \"=== SHARD LOGS (last 30 lines each + unit/e2e summaries) ===\"for s in 1 2 3 4; do@@ -317,23 +342,31 @@ fiINNER_CMD=$(cat <<'EOF'set -euo pipefailecho "[runner] bun version: $(bun --version)"-# The oven/bun image omits git; many unit tests use mkdtemp + git init for fixtures.-if ! command -v git >/dev/null 2>&1; then- echo "[runner] Installing git (debian apt)..."+# Test prerequisites may be missing even in a warm runner image: git backs+# fixture repos, python3 backs security scans and argv recorders, and ps backs+# live-process / PID-reuse lock checks. psql cleans up connections between E2E+# files. None are application dependencies.+if ! command -v git >/dev/null 2>&1 || \+ ! command -v python3 >/dev/null 2>&1 || \+ ! command -v ps >/dev/null 2>&1 || \+ ! command -v psql >/dev/null 2>&1; then+ echo "[runner] Installing test prerequisites (debian apt)..."apt-get update -qq >/dev/null- apt-get install -y -qq git ca-certificates >/dev/null+ apt-get install -y -qq git ca-certificates python3 procps postgresql-client >/dev/nullfi# Container runs as root (uid 0) against a host-uid bind-mount; mark repo +# any worktree gitdir as safe so `git status` etc. don't refuse.git config --global --add safe.directory '*' || true-if [ ! -d /app/node_modules ] || [ -z "$(ls -A /app/node_modules 2>/dev/null)" ]; then- echo "[runner] First run (or --clean): bun install --frozen-lockfile"- bun install --frozen-lockfile-fi+# Revalidate even a warm dependency volume against this checkout's lockfile.+echo "[runner] bun install --frozen-lockfile"+bun install --frozen-lockfile__RUN_PHASES__EOF)-INNER_CMD="${INNER_CMD/__RUN_PHASES__/$RUN_PHASES_CMD}"+# Concatenate around the marker instead of using replacement expansion:+# Bash 5.2 expands unquoted '&' in a replacement to the matched marker,+# corrupting shell redirects such as 2>&1. These slices also work on Bash 3.2.+INNER_CMD="${INNER_CMD%%__RUN_PHASES__*}${RUN_PHASES_CMD}${INNER_CMD#*__RUN_PHASES__}"# Conductor / git-worktree support: when `.git` is a file (not a directory),# it points at a host gitdir outside the bind-mount. Without remounting thatdiff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex fe5f9ae643..7c01edbbed 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -36,14 +36,23 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/bootstrap-hook-under-serve.serial.test.ts","test/e2e/bootstrap-real-codex.serial.test.ts",],+ // Concrete content and derived-information read policy parity.+ "src/core/remote-body.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts", "test/e2e/legacy-chunk-privacy.test.ts", "test/e2e/chunk-canonical-text-privacy.test.ts"],+ "src/core/entity-identity.ts": ["test/e2e/engine-content-privacy.test.ts", "test/e2e/remote-privacy-journeys.test.ts"],+ "src/core/ops/**": ["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", "test/e2e/chunk-canonical-text-privacy.test.ts"],+ "src/commands/whoknows.ts": ["test/e2e/read-enrichment-privacy.test.ts"],+ "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/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","test/e2e/search-quality.test.ts","test/e2e/search-exclude.test.ts","test/e2e/search-swamp.test.ts",],// Tree-sitter chunkers feed code-indexing E2E.- "src/core/chunkers/**": ["test/e2e/code-indexing.test.ts"],+ "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// (mocked SDK) AND the real-loader Tier 2 E2E that spawns openclaw and// actually installs the plugin into an isolated --profile.@@ -131,6 +140,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/ops/jobs.ts": ["test/e2e/jobs-agent-scope-postgres.test.ts"],// postgres.js bind paths + JSONB shapes + parity vs PGLite."src/core/postgres-engine.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","test/e2e/postgres-bootstrap.test.ts","test/e2e/postgres-jsonb.test.ts","test/e2e/jsonb-roundtrip.test.ts",@@ -145,6 +157,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {],// PGLite bootstrap path + parity guard."src/core/pglite-engine.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","test/e2e/postgres-bootstrap.test.ts","test/e2e/engine-parity.test.ts","test/e2e/schema-drift.test.ts",@@ -153,6 +168,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {// Engine method modules peeled from the façades carry the same blast// radius as the façades themselves."src/core/postgres-engine/**": [+ "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","test/e2e/postgres-bootstrap.test.ts","test/e2e/postgres-jsonb.test.ts","test/e2e/jsonb-roundtrip.test.ts",@@ -163,6 +181,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"test/e2e/source-boundary-mutation-postgres.test.ts",],"src/core/pglite-engine/**": [+ "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","test/e2e/postgres-bootstrap.test.ts","test/e2e/engine-parity.test.ts","test/e2e/schema-drift.test.ts",diff --git a/scripts/llms-config.ts b/scripts/llms-config.tsindex 56ac26ba30..bb59f8a0f0 100644--- a/scripts/llms-config.ts+++ b/scripts/llms-config.ts@@ -236,7 +236,7 @@ export const SECTIONS: DocSection[] = [{title: "skills/migrations/",description:- "Per-version agent-executable migration instructions (latest: v0.46.3.0 — the ZeroEntropy-sunset embedding + reranker switch playbook).",+ "Per-version agent-executable migration instructions (latest: v0.48.3.0 — index rebuilds and temporary search/report/tool availability).",path: "skills/migrations/",},{diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 6c4a3abaca..5d5953f58f 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -15,14 +15,14 @@ src/core/ai/gateway.ts 4764 ratchet +74: #3657 post-sunset rerank short-circuitsrc/commands/sync.ts 5801 ratchet 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)src/core/cycle.ts 3203 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 contractsrc/core/cycle/synthesize.ts 3151 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-src/core/engine.ts 2634 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-src/core/import-file.ts 2202 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)+src/core/engine.ts 2638 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+src/core/import-file.ts 2250 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)src/core/migrate.ts 687 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)src/core/operations.ts 321 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-src/core/pglite-engine.ts 6284 ratchet 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-src/core/postgres-engine.ts 5782 ratchet 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-src/core/search/hybrid.ts 3114 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)-src/core/types.ts 2031 ratchet 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)+src/core/pglite-engine.ts 6089 ratchet 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+src/core/postgres-engine.ts 5568 ratchet 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+src/core/search/hybrid.ts 3145 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+src/core/types.ts 2047 ratchet 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 PageReadPolicysrc/core/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic leasesrc/commands/init.ts 2048 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 fixessrc/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)@@ -38,5 +38,5 @@ src/core/chunkers/code.ts 1575 ratchet new row: crossed the 1500 unlisted cap insrc/core/config.ts 1764 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-upsrc/core/bootstrap/harness.ts 2300 ratchet +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-upsrc/core/oauth-provider.ts 1552 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard)-src/core/ops/pages.ts 1505 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review)+src/core/ops/pages.ts 1472 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review)src/core/search/mode.ts 1528 ratchet +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness)diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.shindex 8788b4e451..05ad705d0e 100755--- a/scripts/run-e2e.sh+++ b/scripts/run-e2e.sh@@ -118,6 +118,8 @@ for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPENGBRAIN_PGLITE_SNAPSHOT) ;; # snapshot fast-path fixture (exported by ci-local.sh / runners) — keepGBRAIN_TEST_ALLOW_DATABASE_URL) ;; # #3485 preload opt-in (set above) — keepGBRAIN_TEST_KEEP_PROVIDER_KEYS) ;; # provider-keys preload opt-in (set above) — keep+ GBRAIN_TEST_DB) ;; # explicit schema-reset opt-in for service hosts; schema-drift still requires a test-shaped DB name+ GBRAIN_PGBOUNCER_URL|GBRAIN_PGBOUNCER_DIRECT_URL|GBRAIN_CI_REQUIRE_PGBOUNCER) ;; # explicit pooler test target and execution requirementGBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive itGBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error# message tells operators to set it; stripping it@@ -270,6 +272,15 @@ for f in "${files[@]}"; doTIMEOUT_CMD=""fiif output=$($TIMEOUT_CMD bun test --timeout=60000 ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} "$f" 2>&1); 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+ fail_files=$((fail_files + 1))+ fail_list+=("$name")+ echo "$output"+ echo "FAILED: required PgBouncer tests did not execute"+ continue+ fipass_files=$((pass_files + 1))# Extract pass/fail counts from bun's summary (e.g., "123 pass")p=$(echo "$output" | grep -oE '[0-9]+ pass' | tail -1 | grep -oE '[0-9]+' || echo 0)diff --git a/scripts/run-slow-tests.sh b/scripts/run-slow-tests.shindex fd1753d987..bc65b97bfd 100755--- a/scripts/run-slow-tests.sh+++ b/scripts/run-slow-tests.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# scripts/run-slow-tests.sh# Tier 4 sister to run-unit-shard.sh: runs ONLY *.slow.test.ts files.-# CI runs both; bun run ci:local skips slow tests via run-unit-shard.sh.+# CI and bun run ci:local both run this lane alongside the unit shards.set -euo pipefaildiff --git a/scripts/select-e2e.ts b/scripts/select-e2e.tsindex 252424eff7..c8ed99b9ef 100644--- a/scripts/select-e2e.ts+++ b/scripts/select-e2e.ts@@ -3,7 +3,7 @@//// Fail-closed diff-based E2E test selector. Reads the working-tree diff vs// origin/master plus untracked files, classifies the change set as-// EMPTY / DOC_ONLY / SRC, and emits the relevant E2E test files on stdout.+// EMPTY / DOC_ONLY / SRC, and emits one relevant E2E test path per stdout line.//// CONTRACT (fail-closed):// - When in doubt, run all E2E. The map narrows from "all"; it never widens@@ -21,7 +21,7 @@// SRC (at least one path is outside doc allowlist):// a. Any escape-hatch path matched -> emit ALL// b. Else union map matches; include directly-modified test/e2e/*.test.ts-// c. If still empty -> FAIL-CLOSED -> emit ALL+// c. Any non-doc path without coverage -> FAIL-CLOSED -> emit ALL//// On git command failure: print error to stderr and exit 2 so callers see the// failure (xargs -r will run nothing AND the human sees the error).@@ -174,15 +174,19 @@ export function selectTests(inputs: SelectInputs): string[] {result.add(f);continue;}+ let covered = false;for (const [glob, tests] of Object.entries(map)) {if (matchGlob(glob, f)) {+ if (tests.length > 0) covered = true;for (const t of tests) result.add(t);}}+ // A covered sibling must not hide an unknown change's blast radius.+ // Check coverage per changed path, not just whether the union is nonempty.+ if (!covered) return allSorted;}- // 3c. Fail-closed: if no map entry matched any src/ path AND no test files- // were directly modified, run everything.+ // Defensive fallback for an empty map/selection.if (result.size === 0) return allSorted;// Sort for determinism (helps tests + readability).@@ -243,6 +247,6 @@ if (import.meta.main) {map: E2E_TEST_MAP,});- process.stdout.write(tests.join(" "));+ process.stdout.write(tests.join("\n"));if (tests.length > 0) process.stdout.write("\n");}diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex f57d4bb852..9c299ddbd0 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -48,6 +48,7 @@ test/build-llms.test.ts build-llms generator 7 readFileSynctest/canonical-migration-command.test.ts canonical migration command (single home: ai/defaults.ts) 5 doctor-source-helpertest/chat-key-plane.test.ts #3944 both planner surfaces share the helper (source guard) 2 readFileSynctest/check-bootstrap-guards.test.ts check-grok-pin.sh 10 readFileSync+test/check-bootstrap-guards.test.ts check-opencode-pin.sh 6 readFileSynctest/check-bootstrap-guards.test.ts verify + workflow wiring 6 readFileSynctest/check-update.test.ts check-update CLI 3 bun-filetest/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 3 readFileSync@@ -231,10 +232,15 @@ test/retrieval-reflex-recipe-routing.test.ts retrieval-reflex recipe routing istest/schema-cli-contract.test.ts v0.39 T6 — schema CLI contract 7 readFileSynctest/schema-pack-unify-types-handler.test.ts #1575 unify-types worker dry-run default 1 readFileSynctest/schema-pack/suggest.test.ts runSuggest — source-text contract (structural) 1 readFileSync+test/scripts/ci-gates.test.ts CI execution evidence 5 readFileSync+test/scripts/ci-gates.test.ts test:full exit status 0 readFileSync+test/scripts/ci-local-rendering.test.ts ci-local command rendering 1 readFileSync+test/scripts/ci-local-rendering.test.ts ci-local execution coverage 3 readFileSync+test/scripts/ci-local-rendering.test.ts required PgBouncer execution through run-e2e 1 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 18 bun-file,doctor-source-helper,exec-scan,readFileSynctest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSynctest/scripts/e2e-wiring.test.ts e2e file claim ratchet 5 readFileSync-test/scripts/e2e-wiring.test.ts selected-e2e job wiring 5 readFileSync+test/scripts/e2e-wiring.test.ts selected-e2e job wiring 6 readFileSynctest/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSynctest/serve-http-github-webhook.test.ts handler wiring (source pin) 1 readFileSyncdiff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex 857a1f0cae..23d6fc7fc5 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -898,7 +898,6 @@"test/scripts/check-test-isolation.test.ts": 279,"test/scripts/check-worker-lock-renewal-shape.test.ts": 30,"test/scripts/check-worker-pool-atomicity.test.ts": 117,- "test/scripts/ci-cache-hash.test.ts": 1649,"test/scripts/evals-collection.test.ts": 996,"test/scripts/mine-shard-weights.test.ts": 10,"test/scripts/run-serial-pool.test.ts": 3082,diff --git a/skills/conventions/search-modes.md b/skills/conventions/search-modes.mdindex 5c0b4b8c26..0b663dbc9b 100644--- a/skills/conventions/search-modes.md+++ b/skills/conventions/search-modes.md@@ -7,7 +7,7 @@ type: convention# Convention: Search Modes (v0.32.3)> **Convention:** every brain has one active search mode. The mode bundles the-> search-lite knobs from PR #897 (semantic cache, token budget, intent+> search-lite knobs (semantic result-cache settings, token budget, intent> weighting, LLM expansion, result limit) into a single config key:> `search.mode = conservative | balanced | tokenmax`.@@ -17,7 +17,7 @@ Any agent doing search-adjacent work in a gbrain brain consults this convention:- `brain-ops` / `query` / `signal-detector` skills: respect the active mode atsearch time. Per-call `SearchOpts` overrides win when set; mode is the default.-- Skills that recommend tuning ("the cache hit rate is high — raise threshold?"):+- Skills that recommend tuning ("which search mode fits this brain?"):route operators to `gbrain search tune` rather than rolling their own logic.- New skills that add per-call retrieval overrides: name them explicitly sothe resolved-knob attribution dashboard (`gbrain search modes`) reads cleanly.@@ -40,9 +40,12 @@ The canonical knob table (with cost anchors) lives in| `relationalRetrieval` | false | **true** | **true** || `searchLimit` default | 10 | 25 | 50 |-**Cache, intent weighting, and similarity threshold are constant across modes**-— they're free wins (no API cost). Modes scale the three cost levers:-`tokenBudget`, `expansion`, `searchLimit`.+**Effective semantic result caching is disabled in every mode.** The table+retains the stored bundle values, but result lookup and writes are bypassed+regardless of config or `use_cache`. Cache statistics and the mode dashboard+report disabled; repeated queries perform fresh retrieval. Intent weighting+and the retained cache knobs remain constant across modes. Modes scale+`tokenBudget`, `expansion`, and `searchLimit`.## Resolution chain (matches v0.31.12 model-tier shape)@@ -70,15 +73,15 @@ and prints a paste-ready revert command.## Cache contamination guard-Migration v56 added `query_cache.knobs_hash`. A tokenmax write-(expansion=on, limit=50) is keyed by a different hash than a conservative-read (no expansion, limit=10), so cross-mode contamination is structurally-impossible. The cache lookup filter is:+The retained `query_cache.knobs_hash` machinery separates mode settings:+tokenmax (expansion=on, limit=50) has a different hash from conservative+(no expansion, limit=10). Its stored lookup filter is:WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $-Legacy NULL-knobs_hash rows from pre-v0.32.3 are silently excluded-(treated as misses, re-populated with the right hash on first hit).+Legacy NULL-knobs_hash rows remain excluded. No semantic result rows are read+or repopulated while caching is disabled; changing the stored knobs cannot+restore result reuse.## Trigger phrasesdiff --git a/skills/migrations/v0.48.3.0.md b/skills/migrations/v0.48.3.0.mdnew file mode 100644index 0000000000..628332fdb1--- /dev/null+++ b/skills/migrations/v0.48.3.0.md@@ -0,0 +1,69 @@+# v0.48.3.0: verify access rules and temporary search behavior++This release applies access rules consistently and improves remote-call and+verification behavior. It requires no database schema migration or new service.++1. Verify the installed version and brain health:++ ```bash+ gbrain --version+ gbrain doctor+ gbrain search modes+ gbrain cache stats+ ```++2. Explain the temporary semantic result-cache change to the operator. Searches+ use fresh retrieval even when caching is configured. Cache statistics report+ `enabled: false`; stored rows and maintenance commands remain available.+ Repeated searches may take longer and use more provider tokens. Do not change+ provider credentials or promise that a cache setting can restore caching.++3. Stored contradiction reports are temporarily available only to trusted local+ callers without a source filter. Remote and source-scoped requests receive an+ availability note. Do not broaden a caller's source permissions to work around+ that response.++4. Explain any changed remote salience scores using the caller's permitted active+ takes. Restricted scores omit stored emotional weight and use page updates for+ recent inclusion. Existing trusted local callers without holder restrictions+ retain their formulas.++5. Existing chunks are withheld from chunk-based remote retrieval until rebuilt+ with the corrected indexer. This applies to public pages too. Direct page reads remain+ available under the connection's access rules. Preview the existing rebuild:++ ```bash+ gbrain reindex --markdown --dry-run --no-embed+ ```++ For a rebuild without embedding-provider calls:++ ```bash+ gbrain reindex --markdown --no-embed+ ```++ This replaces processed pages' chunks and clears their previous vectors.+ Keyword retrieval becomes available after rebuilding; semantic retrieval+ needs fresh embeddings. Use the normal `gbrain reindex --markdown` path when+ embedding is authorized, or restore vectors later with `gbrain embed --stale`.+ Explain provider usage before running either embedding path. Preserve the+ existing post-upgrade cost confirmation. Do not manually change chunker+ version fields to suppress pending work.++ Code pages use the existing `gbrain reindex-code --force --no-embed` path;+ add `--dry-run` to preview it. Image pages need their original files+ reimported so OCR and visual indexing are rebuilt together. Explain any OCR+ or embedding-provider usage before that import. Images with protected OCR+ sections remain unavailable to remote chunk retrieval; update the source+ image before reimporting it. Direct page access still follows normal policy.++6. Code-inspection operations (`code_def`, `code_refs`, `code_callers`,+ `code_callees`, `code_blast`, `code_flow`) are temporarily available only to+ trusted local callers. Remote callers receive an explicit availability+ error. Rebuilding chunks does not lift this separate restriction. Remote+ search omits optional code-graph expansion; ordinary authorized text search+ remains available after the index rebuild. Use the trusted local CLI when+ local access is available, without widening a remote token's permissions.++No new scheduled job or host configuration is required. Follow the exact+remediation printed by `gbrain doctor` if it finds an independent setup issue.diff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex a042366aca..84ef2b424a 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -56,7 +56,7 @@"conventions/regex-discipline.md": "d96a9baa6f27184e165889a9c655607366a739d851684d9f41cdec294f99edac","conventions/salience-and-recency.md": "0ee7f0216f36a5e321673740d148cb0f1113268df19301bb2473a48a728a500b","conventions/schema-evolution.md": "b5cdd5a17e43b4f2d0546ebf8c421cc0378cbcf74cb2fe97199e115ccb05f9c2",- "conventions/search-modes.md": "2862364874115d75816ba5d0e10f9073043a5fdaa44e9c7f530afc6c492e4a24",+ "conventions/search-modes.md": "550a94923e483e0b61e3d9eb6242f13a08e0a37a1eb1b95d4111bfa6ecc7658d","conventions/subagent-routing.md": "8b8830b815a9a8581a12b489f966c0b0a39eb9b5f66e905a691a03653eef348d","conventions/test-before-bulk.md": "6b2c52cda9e2cd5f04c15152b3d92aeb7187ab193a15082be0f8a3991a6a5725","conventions/untrusted-content.md": "259384d490892cd0e1e8e054decf752d7354f516c83aee57b332c1a96aac6a6e",@@ -133,6 +133,7 @@"migrations/v0.41.11.0.md": "5c6873ab969d14def4a450d792f070f1259d08b3aca43bc7825d0a9114b2b36b","migrations/v0.46.3.0.md": "9885b8ecf42c7388cda459f402f4b057cdf7ae7a0ee8ceb296784e6344575dc0","migrations/v0.46.35.0.md": "145c841d89c4b6b6f7089126354fae272df7db6ceaf9cfcec2797d3301cdab57",+ "migrations/v0.48.3.0.md": "1d9a23b6078164717944c94791b18effc7af630b716e8fde2680d6b6de47ce81","migrations/v0.5.0.md": "5e0dabc451595295c4d971e19bcb33c258a127223d25859d8321cb7e1ce60711","migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a","migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",diff --git a/src/commands/cache.ts b/src/commands/cache.tsindex 419f3d00d4..d3b2d38e99 100644--- a/src/commands/cache.ts+++ b/src/commands/cache.ts@@ -13,7 +13,7 @@import { loadConfig, toEngineConfig } from '../core/config.ts';import { createEngine } from '../core/engine-factory.ts';-import { SemanticQueryCache, loadCacheConfig } from '../core/search/query-cache.ts';+import { SemanticQueryCache, loadCacheConfig, semanticResultCacheAvailable } from '../core/search/query-cache.ts';function printHelp(): void {// eslint-disable-next-line no-console@@ -60,7 +60,7 @@ export async function runCache(args: string[]): Promise<void> {// eslint-disable-next-line no-consoleconsole.log('--------------------------');// eslint-disable-next-line no-console- console.log(`enabled : ${cacheCfg.enabled ?? true}`);+ console.log(`enabled : ${semanticResultCacheAvailable() && (cacheCfg.enabled ?? true)}`);// eslint-disable-next-line no-consoleconsole.log(`similarity_threshold : ${cacheCfg.similarityThreshold ?? 0.92}`);// eslint-disable-next-line no-consolediff --git a/src/commands/orphans.ts b/src/commands/orphans.tsindex 1a6d2f11d9..4758a32fac 100644--- a/src/commands/orphans.ts+++ b/src/commands/orphans.ts@@ -1,3 +1,5 @@+import type { PageReadScope } from '../core/types.ts';+import { pageReadFilter } from '../core/search/read-policy-sql.ts';/*** gbrain orphans — Surface disconnected pages.*@@ -104,7 +106,7 @@ export async function queryOrphanPages(*/export async function findOrphans(engine: BrainEngine,- opts: { includePseudo?: boolean; sourceId?: string; sourceIds?: string[]; mode?: 'inbound' | 'islanded' } = {},+ opts: PageReadScope & { includePseudo?: boolean; mode?: 'inbound' | 'islanded' } = {},): Promise<OrphanResult> {const includePseudo = !!opts.includePseudo;// v0.41.29.0: `sourceId` (scalar, from `--source` + single-source MCP@@ -128,6 +130,7 @@ export async function findOrphans(const overrides = includePseudo ? undefined : await loadOrphanPolicyOverrides(engine);try {allOrphans = await engine.findOrphanPages({+ excludePrivate: opts.excludePrivate,...(sourceIds ? { sourceIds } : sourceId ? { sourceId } : {}),...(opts.mode ? { mode: opts.mode } : {}),});@@ -139,15 +142,8 @@ export async function findOrphans(// total_linkable and suppressing orphan warnings. `getAllSlugs` is NOT// used here because it does not filter soft-deleted rows; `total` must// match `findOrphanPages`'s `deleted_at IS NULL` candidate universe.- let scopeClause = '';const liveParams: unknown[] = [];- if (sourceIds) {- liveParams.push(sourceIds);- scopeClause = ` AND source_id = ANY($${liveParams.length}::text[])`;- } else if (sourceId) {- liveParams.push(sourceId);- scopeClause = ` AND source_id = $${liveParams.length}`;- }+ const scopeClause = ` AND ${pageReadFilter('pages', opts, liveParams)}`;// #4280: carry type + quarantine metadata so the denominator applies the// same served-memory policy as the orphan list itself.const liveRows = await engine.executeRaw<{ slug: string; type: string | null; quarantined: boolean }>(diff --git a/src/commands/whoknows.ts b/src/commands/whoknows.tsindex edc9705069..f60fe758b1 100644--- a/src/commands/whoknows.ts+++ b/src/commands/whoknows.ts@@ -1,3 +1,4 @@+import type { PageReadPolicy } from '../core/types.ts';/*** gbrain whoknows — "Who should I talk to about X?"*@@ -41,7 +42,7 @@ import { hybridSearch } from '../core/search/hybrid.ts';import { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';-export interface WhoknowsOpts {+export interface WhoknowsOpts extends PageReadPolicy {topic: string;limit?: number;explain?: boolean;@@ -197,6 +198,9 @@ export async function findExperts(recency: 'off',sourceId: opts.sourceId,sourceIds: opts.sourceIds,+ excludePrivate: opts.excludePrivate,+ requireSafeChunks: opts.requireSafeChunks,+ takesHoldersAllowList: opts.takesHoldersAllowList,});if (results.length === 0) return [];@@ -212,19 +216,20 @@ export async function findExperts(}const candidates = Array.from(byKey.values());- // 3. Batch-fetch salience + effective_date per (slug, source_id) ref.+ // 3. Enrich by exact page identity, then recheck admission. Salience is an+ // optional ranking signal; dates also prove the current page is readable.const refs = candidates.map((c) => ({slug: c.slug,source_id: c.source_id ?? 'default',}));- const [salienceMap, dateMap] = await Promise.all([- engine.getSalienceScores(refs).catch(() => new Map<string, number>()),- engine.getEffectiveDates(refs).catch(() => new Map<string, Date>()),- ]);+ const salienceMap = await engine.getSalienceScores(refs, opts).catch(() => new Map<string, number>());+ // Admission must happen AFTER optional work: that work can race a source or+ // visibility edit. This read is required for trusted local callers too.+ const dateMap = await engine.getEffectiveDates(refs, opts);// 4. Build the ranking-function input shape.const now = Date.now();- const inputs = candidates.map((c) => {+ const inputs = candidates.filter(c => dateMap.has(`${c.source_id ?? 'default'}::${c.slug}`)).map((c) => {const sourceId = c.source_id ?? 'default';const key = `${sourceId}::${c.slug}`;const salienceRaw = salienceMap.get(key);diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex e8ca556ee6..0a85dc9414 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -23,6 +23,8 @@import { countCJKAwareWords, CJK_SENTENCE_DELIMITERS, CJK_CLAUSE_DELIMITERS } from '../cjk.ts';import { estimateEmbedTokens, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';import { safeSplitIndex } from '../text-safe.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';/*** Markdown chunker version. Folded into the per-page chunker_version column@@ -31,6 +33,9 @@ import { safeSplitIndex } from '../text-safe.ts';* boundaries (delimiters, word counting, maxChars cap) OR the per-chunk* embedding shape (wrapper prefix added at embed time).*+ * v4: strict full-body Facts/Takes sanitation covers repeated, nested and+ * unterminated protected fences before splitting or embedding.+ ** v3 (v0.40.3.0): chunks embed with optional contextual retrieval wrapper* per Anthropic's published methodology. Wrapper is built JUST IN TIME at* embed call; stored `content_chunks.chunk_text` stays canonical. Chunk@@ -39,7 +44,7 @@ import { safeSplitIndex } from '../text-safe.ts';* post-upgrade reembed sweep. See* `src/core/contextual-retrieval-service.ts`.*/-export const MARKDOWN_CHUNKER_VERSION = 3;+export const MARKDOWN_CHUNKER_VERSION = SAFE_FENCE_CHUNKER_VERSION;const DELIMITERS: string[][] = [['\n\n'], // L0: paragraphs@@ -71,10 +76,9 @@ export interface TextChunk {index: number;}-// v0.28: import takes-fence stripper as a pre-processing pass. Takes content+// The strict full-body sanitizer removes all Takes and non-world Facts. Takes content// lives in the takes table only; duplicating it inside content_chunks would// bypass the per-token MCP allow-list (Codex P0 #3 privacy fix).-import { stripTakesFence } from '../takes-fence.ts';// v0.32.2 (Codex R2-#1 P0): same posture for facts — private fact rows must// not reach content_chunks.chunk_text, embeddings, or search. Pass@@ -83,7 +87,6 @@ import { stripTakesFence } from '../takes-fence.ts';// at the row level. The fence shell stays in the chunked body so callers// that re-import the chunk content can still parse it; only the private// rows go.-import { stripFactsFence } from '../facts-fence.ts';export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {const chunkSize = opts?.chunkSize || 300;@@ -106,7 +109,7 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {// v0.32.2: also strip private facts (Codex R2-#1). World facts stay so// search retains its public-knowledge surface; private rows are filtered// out at the fence-row level via stripFactsFence({keepVisibility:['world']}).- const stripped = stripFactsFence(stripTakesFence(text), { keepVisibility: ['world'] });+ const stripped = sanitizeRemoteBody(text);if (!stripped || stripped.trim().length === 0) return [];const wordCount = countWords(stripped);diff --git a/src/core/chunkers/semantic.ts b/src/core/chunkers/semantic.tsindex 84bc74fa98..ec90ed4cb7 100644--- a/src/core/chunkers/semantic.ts+++ b/src/core/chunkers/semantic.ts@@ -14,6 +14,7 @@*/import { chunkText as recursiveChunk, type TextChunk } from './recursive.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';export interface SemanticChunkOptions {chunkSize?: number;@@ -25,6 +26,7 @@ export async function chunkTextSemantic(text: string,opts: SemanticChunkOptions,): Promise<TextChunk[]> {+ text = sanitizeRemoteBody(text);const chunkSize = opts.chunkSize || 300;const chunkOverlap = opts.chunkOverlap || 50;const embedFn = opts.embedFn;diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 15cdf40872..81cd1530cf 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -16,7 +16,7 @@export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'advisor': ['--apply', '--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--skills-dir', '--source', '--surface', '--token-ttl', '--verbose', '--workspace'],'agent': ['--all', '--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated', '--federated-read', '--flag', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-federated', '--no-follow', '--note', '--path', '--port', '--preset', '--reissue', '--repo', '--restore-only', '--scopes', '--show-token', '--since', '--source', '--source-guard', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],- 'anomalies': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--lookback-days', '--mcp-only', '--no-embedding', '--sigma', '--since', '--source', '--surface', '--timeout', '--token-ttl'],+ 'anomalies': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--lookback-days', '--mcp-only', '--no-embedding', '--sigma', '--since', '--source', '--surface', '--token-ttl'],'apply-migrations': ['--ab', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dry-run', '--exclude', '--exclusive', '--fast', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--from-meetings', '--from-pages', '--help', '--history', '--host-dir', '--http', '--json', '--lang', '--list', '--locks', '--markdown', '--max-age', '--migrate-only', '--migration', '--mode', '--multimodal', '--no-autopilot-install', '--no-embedding', '--no-extract', '--non-interactive', '--phase', '--priority', '--refresh-unqualified', '--remediate', '--require-db', '--rollback', '--skip-verify', '--source', '--stale', '--surface', '--token-ttl', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'],'auth': ['--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--id', '--json', '--no-embedding', '--redirect-uri', '--scopes', '--source', '--stale', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],'autopilot': ['--all', '--auto-fix', '--batch', '--brain', '--break-lock', '--by-type', '--check', '--dim', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--exclude', '--explain', '--fast', '--ff-only', '--fix', '--force', '--force-break-lock', '--force-retry', '--from-pages', '--help', '--http', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--json', '--markdown', '--max-age', '--max-rss', '--max-usd', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--no-inject', '--no-mutate', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--phase', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--save', '--source', '--stale', '--status', '--surface', '--swap-only', '--take', '--target', '--target-score', '--timeout', '--to', '--token-ttl', '--uninstall', '--unsafe-bypass-dream-guard', '--user', '--version', '--yes'],@@ -29,7 +29,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'cache': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--source', '--surface', '--token-ttl', '--yes'],'calibration': ['--ab', '--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated', '--file', '--follow', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--lang', '--limit', '--markdown', '--max-usd', '--mode', '--multimodal', '--near-symbol', '--no-federated', '--offset', '--page', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--recency', '--regenerate', '--repo', '--restore-only', '--salience', '--save', '--scrub-gstack', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale', '--stale-ok', '--stats', '--stdin', '--surface', '--symbol-kind', '--thin', '--trusted-extraction', '--types', '--undo-wave', '--url', '--walk-depth', '--with-calibration', '--with-db', '--yes'],'call': ['--brain', '--federated', '--help', '--http', '--json', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--timeout'],- 'capture': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--repo', '--restore-only', '--salience', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale-ok', '--stats', '--stdin', '--surface', '--timeout', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'],+ 'capture': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--depth', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--repo', '--restore-only', '--salience', '--save', '--scopes', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--source-guard', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--type', '--types', '--url', '--walk-depth', '--what', '--where', '--who', '--with-db', '--yes'],'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],@@ -57,14 +57,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'extract-conversation-facts': ['--all', '--all-sources', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--by-mention', '--check', '--clone-dir', '--code', '--concurrency', '--confirm-destructive', '--dim', '--dir', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--federated', '--fix', '--follow', '--force', '--force-break-lock', '--help', '--json', '--judge-model', '--kind', '--limit', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--name', '--no', '--no-embed', '--no-embedding', '--no-federated', '--older-than', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--segment-limit', '--session', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--version', '--workers', '--yes'],'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--progress-json', '--quiet', '--rebuild', '--refresh', '--repo', '--run-id', '--since', '--since-created', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],'files': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--json', '--no-embedding', '--no-federated', '--no-pointer', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--retry-failed', '--save', '--source', '--source-guard', '--stale', '--surface', '--timeout', '--token-ttl', '--type', '--yes'],- 'forget': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],- 'founder': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--since', '--source', '--surface', '--timeout', '--token-ttl', '--until'],+ 'forget': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],+ 'founder': ['--brain', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--mcp-only', '--no-embedding', '--since', '--source', '--surface', '--token-ttl', '--until'],'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--redact', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude', '--exclude-standard', '--fast', '--fix', '--force', '--from-pages', '--full', '--get', '--help', '--http', '--include-catch-all', '--include-hidden', '--json', '--name-only', '--name-status', '--no-embedding', '--no-verify', '--others', '--source', '--strategy', '--surface', '--timeout', '--token-ttl', '--uninstall', '--write-back'],'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', '--exclude', '--expansion-model', '--fast', '--force', '--from-pages', '--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', '--timeout-ms', '--to', '--token-command', '--token-ttl', '--url', '--version', '--via'],- 'graph-query': ['--brain', '--depth', '--direction', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--json', '--mcp-only', '--no-embedding', '--source', '--surface', '--timeout', '--token-ttl', '--type'],+ 'graph-query': ['--brain', '--depth', '--direction', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--include-foreign', '--json', '--mcp-only', '--no-embedding', '--source', '--surface', '--token-ttl', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--delete-brain', '--detach', '--diff-filter', '--end-of-options', '--env', '--exclude', '--exclude-standard', '--fast', '--force', '--from-pages', '--get', '--harness', '--help', '--http', '--jq', '--json', '--name-only', '--no-embedding', '--others', '--path', '--porcelain', '--project', '--pure', '--quiet', '--remove', '--session', '--show-current', '--show-toplevel', '--source', '--stats', '--status', '--surface', '--token', '--token-ttl'],- 'import': ['--all', '--allow-empty', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--cached', '--check', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--include-hidden', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--no-gpg-sign', '--no-verify', '--older-than', '--orphan', '--others', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--short', '--show-toplevel', '--since', '--skip-failed', '--slugs', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--workers'],+ 'import': ['--all', '--allow-empty', '--allow-noncanonical-root', '--asof', '--background', '--brain', '--brain-wide-max-cost-usd', '--cached', '--check', '--code', '--compile', '--concurrency', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--fix', '--follow', '--force', '--force-rechunk', '--fresh', '--from-pages', '--full', '--help', '--http', '--include-gitignored', '--include-hidden', '--json', '--lang', '--log-noop', '--markdown', '--max-age', '--multimodal', '--name-status', '--no-embed', '--no-embedding', '--no-federated', '--no-gpg-sign', '--no-verify', '--older-than', '--orphan', '--others', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--respect-gitignore', '--restore-only', '--short', '--show-toplevel', '--since', '--skip-failed', '--slugs', '--source', '--source-guard', '--source-id', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--url', '--verify', '--workers'],'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--check', '--ctx-size', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--entity', '--exclude', '--expansion-model', '--fast', '--flag', '--force', '--from-pages', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--judge-model', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--reranking', '--reset', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--touchpoint', '--url', '--version', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--embeddings', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--no-embedding', '--overwrite', '--refresh', '--reranking', '--source', '--surface', '--target', '--token-ttl'],'integrity': ['--auto', '--backend', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confidence', '--cost', '--dry-run', '--exclude', '--explain', '--fast', '--follow', '--force', '--fresh', '--from-pages', '--help', '--http', '--json', '--limit', '--no-embedding', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--stale', '--supabase', '--surface', '--timeout', '--token-ttl', '--type', '--url'],@@ -86,7 +86,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--reranking', '--reset', '--source', '--surface', '--to', '--token-ttl', '--touchpoint', '--version', '--yes'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--apply', '--brain', '--code', '--compile', '--exclude', '--fast', '--fix', '--force', '--force-rechunk', '--from-pages', '--help', '--http', '--include-flagged', '--json', '--lang', '--limit', '--markdown', '--no-embed', '--no-embedding', '--source', '--source-id', '--stale', '--surface', '--token-ttl'],- 'recall': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--timeout', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],+ 'recall': ['--access', '--all', '--allow-empty', '--apply', '--as-context', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-tokens', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--entities', '--exclude', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--no-federated', '--offset', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recency', '--repo', '--restore-only', '--rollup', '--salience', '--save', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-guard', '--stale-ok', '--stats', '--stdin', '--supersessions', '--surface', '--today', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--watch', '--with-db', '--yes'],'reconcile-links': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--dry-run', '--explain', '--follow', '--full', '--help', '--include-frontmatter', '--include-hidden', '--json', '--name-status', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--strategy', '--timeout', '--type'],'reindex': ['--aliases', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--from-pages', '--help', '--http', '--json', '--lang', '--limit', '--markdown', '--max-age', '--max-cost-usd', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--older-than', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--token-ttl', '--type', '--version', '--workers', '--yes'],'reindex-code': ['--abi', '--all', '--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--chunker-debug', '--code', '--compile', '--concurrency', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fix', '--follow', '--force', '--force-rechunk', '--help', '--json', '--judge-model', '--lang', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-runtime', '--model', '--multimodal', '--no', '--no-embed', '--older-than', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--serial', '--source', '--stale', '--timeout', '--to', '--version', '--workers', '--yes'],@@ -100,7 +100,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'resolvers': ['--auto', '--backend', '--brain', '--cost', '--help', '--json', '--source'],'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--break-lock', '--catch-up', '--check', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--embeddings', '--exclude', '--explain', '--fast', '--fix', '--follow', '--force', '--force-break-lock', '--force-sunset-target', '--from-pages', '--help', '--http', '--ignore-env-override', '--ignore-missing-key', '--include-null-signature', '--json', '--max-age', '--model', '--multimodal', '--name', '--nice', '--no', '--no-embed', '--no-embedding', '--non-interactive', '--pace', '--pace-max-concurrency', '--parallel', '--prefix', '--priority', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reranking', '--resume', '--retarget', '--slugs', '--source', '--stale', '--status', '--surface', '--timeout', '--to', '--token-ttl', '--version', '--yes'],'routing-eval': ['--brain', '--fix', '--help', '--json', '--llm', '--skills-dir', '--source', '--strict', '--verbose'],- 'salience': ['--brain', '--days', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--kind', '--limit', '--mcp-only', '--no-embedding', '--slug-prefix', '--source', '--surface', '--timeout', '--token-ttl'],+ 'salience': ['--brain', '--days', '--exclude', '--fast', '--force', '--from-pages', '--help', '--http', '--json', '--kind', '--limit', '--mcp-only', '--no-embedding', '--slug-prefix', '--source', '--surface', '--token-ttl'],'schema': ['--alias', '--aliases', '--all', '--apply', '--as-filing-rules', '--asof', '--brain', '--by-mention', '--compile', '--dims', '--exclude', '--expert', '--expert-routing', '--extractable', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--inverse', '--json', '--kind', '--no-embedding', '--no-extract', '--pack', '--page-type', '--pattern', '--pending', '--prefix', '--primitive', '--rebuild', '--reset', '--resolve', '--schema-pack', '--since', '--source', '--source-id', '--stale', '--supersessions', '--surface', '--target-type', '--thin', '--to', '--token-ttl', '--with-db'],'self-upgrade': ['--all', '--brain', '--check', '--check-only', '--dim', '--ff-only', '--force', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],'serve': ['--all', '--bind', '--bound-slug-prefixes', '--brain', '--compile', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--fast', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--log-full-params', '--name', '--no-embedding', '--no-hard-deadline', '--once', '--parallel', '--port', '--prefix', '--print-admin-token', '--public-url', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--timeout', '--token-ttl', '--yes'],@@ -115,11 +115,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'sweep': ['--all', '--background', '--batch-limit', '--brain', '--brain-wide-max-cost-usd', '--budget-ms', '--check', '--delete-brain', '--explain', '--federated', '--follow', '--help', '--home', '--json', '--name', '--no-delegate', '--no-federated', '--once', '--parallel', '--path', '--prefix', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--source', '--source-guard', '--stale', '--stats', '--timeout'],'sync': ['--abbrev-ref', '--abi', '--abort', '--account', '--all', '--all-sources', '--allow-empty', '--apply', '--apply-rewrites', '--asof', '--auto', '--background', '--batch-size', '--brain', '--brain-wide-max-cost-usd', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--clone-dir', '--code', '--column', '--compile', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--federated', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--from-pages', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--lock', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--object-format', '--older-than', '--once', '--orphan', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--prefix', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--rebuild-rollup', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--respect-gitignore', '--restore-only', '--resume', '--retry-failed', '--run-id', '--save', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--since-created', '--skills-dir', '--skip-failed', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token-env', '--token-ttl', '--top-k', '--type', '--url', '--verbose', '--verify', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--all', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--exclude', '--expired', '--fast', '--federated', '--file', '--force', '--from-pages', '--help', '--holder', '--http', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-federated', '--offset', '--outcome', '--path', '--pglite', '--quality', '--reject', '--repo', '--restore-only', '--row', '--semantic', '--serial', '--since', '--slugs', '--sort', '--source', '--source-guard', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--token-ttl', '--unit', '--until', '--value', '--version', '--weight', '--who', '--yes'],- 'think': ['--all', '--anchor', '--asof', '--bind', '--bound-slug-prefixes', '--brain', '--by-mention', '--calibration-holder', '--compile', '--db-url', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--explain', '--fast', '--federated', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--lang', '--log-full-params', '--markdown', '--max-usd', '--mcp-only', '--model', '--multimodal', '--name', '--near-symbol', '--no-embed', '--no-embedding', '--no-federated', '--no-hard-deadline', '--once', '--parallel', '--path', '--port', '--prefix', '--print-admin-token', '--priority', '--public-url', '--remediate', '--repo', '--restore-only', '--rounds', '--save', '--serial', '--since', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--symbol-kind', '--take', '--thin', '--timeout', '--token-ttl', '--until', '--url', '--with-calibration', '--yes'],+ 'think': ['--all', '--anchor', '--asof', '--bind', '--bound-slug-prefixes', '--brain', '--calibration-holder', '--compile', '--db-url', '--enable-dcr', '--enable-dcr-insecure', '--exclude', '--explain', '--fast', '--federated', '--federated-read', '--force', '--from-pages', '--help', '--http', '--json', '--lang', '--log-full-params', '--markdown', '--max-usd', '--mcp-only', '--model', '--multimodal', '--name', '--near-symbol', '--no-embed', '--no-embedding', '--no-federated', '--no-hard-deadline', '--once', '--parallel', '--path', '--port', '--prefix', '--print-admin-token', '--priority', '--public-url', '--remediate', '--repo', '--restore-only', '--rounds', '--save', '--serial', '--since', '--source', '--source-guard', '--stale', '--stdio-idle-timeout', '--suppress', '--suppress-bootstrap-token', '--surface', '--symbol-kind', '--take', '--thin', '--timeout', '--token-ttl', '--until', '--url', '--with-calibration', '--yes'],'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--brain-wide-max-cost-usd', '--by-mention', '--check', '--code', '--compile', '--days', '--dry-run', '--embed', '--exclude', '--explain', '--facts', '--fast', '--federated', '--follow', '--force', '--format', '--from-pages', '--full', '--help', '--http', '--include-self', '--json', '--limit', '--markdown', '--max-bytes', '--max-cost-usd', '--no-embedding', '--no-federated', '--path', '--print', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--repo', '--restore-only', '--since', '--since-last', '--slug', '--source', '--source-guard', '--source-id', '--stale', '--surface', '--timeout', '--token-ttl'],'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--code', '--compile', '--concurrency', '--cost-estimate', '--detail', '--dim', '--embedding-dimensions', '--embedding-model', '--exclude', '--fast', '--ff-only', '--flag', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--from-pages', '--help', '--host-dir', '--http', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--model', '--multimodal', '--name-only', '--no', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pglite', '--quiet', '--recency', '--repo', '--require-db', '--reset', '--since', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--surface', '--swap-only', '--target', '--timeout', '--to', '--token-ttl', '--uninstall', '--user', '--verbose', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--brain', '--federated-read', '--help', '--http', '--json', '--source', '--source-guard', '--stale-ok', '--status', '--timeout', '--top', '--type'],'watch': ['--brain', '--exclude', '--fast', '--federated', '--force', '--from-pages', '--help', '--http', '--json', '--max-pages', '--min-confidence', '--no-embedding', '--no-federated', '--path', '--repo', '--restore-only', '--source', '--source-guard', '--stats', '--surface', '--token-ttl', '--window-turns'],- 'whoknows': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale-ok', '--stats', '--stdin', '--surface', '--timeout', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],+ 'whoknows': ['--access', '--all', '--allow-empty', '--apply', '--asof', '--auto', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--by-mention', '--content', '--date', '--days', '--detail', '--entities', '--exclude', '--explain', '--fast', '--federated', '--file', '--follow', '--force', '--from-pages', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--mode', '--multimodal', '--near-symbol', '--no-embedding', '--offset', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--recency', '--salience', '--save', '--session', '--session-id', '--since', '--slug', '--slugs', '--source', '--stale-ok', '--stats', '--stdin', '--surface', '--token-ttl', '--trusted-extraction', '--types', '--url', '--walk-depth', '--with-db', '--yes'],'ze-switch': ['--background', '--brain', '--brain-wide-max-cost-usd', '--check', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--force-sunset-target', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--reranker', '--reset', '--resume', '--source', '--stale', '--timeout', '--to', '--undo', '--yes'],};diff --git a/src/core/context/chronicle-context.ts b/src/core/context/chronicle-context.tsindex 19a59557be..f9cf3b33d1 100644--- a/src/core/context/chronicle-context.ts+++ b/src/core/context/chronicle-context.ts@@ -5,9 +5,9 @@// orients before acting (the exact thing missing when chronology gets fumbled).// Pure composition of engine.getSince + engine.getOntology — no new SQL.import type { BrainEngine } from '../engine.ts';-import type { ChronicleTimelineRow, OntologyValue } from '../types.ts';+import type { ChronicleTimelineRow, OntologyValue, PageReadScope } from '../types.ts';-export interface ChronicleContextOpts {+export interface ChronicleContextOpts extends PageReadScope {/** Lookback window in days for the recent timeline (default 7). */days?: number;/** Entity slugs to resolve current ontology for (e.g. the people in the session). */@@ -38,7 +38,9 @@ export async function loadChronicleContext(const since = daysAgoIso(days);const scope = { sourceId: opts.sourceId, sourceIds: opts.sourceIds };- const recent_timeline = await engine.getSince(since, { ...scope, limit: opts.limit ?? 50 });+ const recent_timeline = await engine.getSince(since, {+ ...scope, excludePrivate: opts.excludePrivate, limit: opts.limit ?? 50,+ });const ontologies: Record<string, OntologyValue[]> = {};for (const slug of opts.entities ?? []) {diff --git a/src/core/engine.ts b/src/core/engine.tsindex 2cf41e2be5..82e4305a4a 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1,5 +1,5 @@import type {- Page, PageInput, PageFilters, GetPageOpts,+ Page, PageInput, PageFilters, GetPageOpts, PageReadScope, PageReadPolicy,Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,SearchResult, SearchOpts, ResolvedColumn,Link, GraphNode, GraphPath, RelationalFanoutRow, RelationalFanoutOpts,@@ -61,7 +61,7 @@ export interface SourceRow {config: Record<string, unknown>;}-export interface TraverseGraphOpts {+export interface TraverseGraphOpts extends PageReadScope {sourceId?: string;sourceIds?: string[];frontierCap?: number;@@ -295,7 +295,7 @@ export interface Take {updated_at: string;}-export interface TakesListOpts {+export interface TakesListOpts extends PageReadPolicy {page_id?: number;page_slug?: string; // resolved via JOINholder?: string;@@ -399,7 +399,7 @@ export interface TakesScorecard {unresolvable_rate?: number | null;}-export interface TakesScorecardOpts {+export interface TakesScorecardOpts extends PageReadScope {holder?: string;domainPrefix?: string; // e.g. 'companies/' to scope the scorecardsince?: string; // ISO date 'YYYY-MM-DD'@@ -423,7 +423,7 @@ export interface CalibrationBucket {predicted: number | null;}-export interface CalibrationCurveOpts {+export interface CalibrationCurveOpts extends PageReadScope {holder?: string;bucketSize?: number; // default 0.1/** Federated/source scope via the take's page.source_id (array wins over scalar). */@@ -966,7 +966,7 @@ export interface BrainEngine {* `gbrain query --resolve` CLI path, etc.). Field names match the* `sourceScopeOpts(ctx)` helper output so callers can spread directly.*/- resolveSlugs(partial: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<string[]>;+ resolveSlugs(partial: string, opts?: PageReadScope): Promise<string[]>;/*** Returns the slug of every page in the brain. Used by batch commands as a* mutation-immune iteration source (alternative to listPages OFFSET pagination,@@ -1139,7 +1139,7 @@ export interface BrainEngine {* them away). `includeEmbedding` opts back in, and beats* `getChunksWithEmbeddings`, which honors neither scope precedence nor RLS.*/- getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean }): Promise<Chunk[]>;+ getChunks(slug: string, opts?: PageReadScope & { includeEmbedding?: boolean }): Promise<Chunk[]>;/*** Count chunks whose registry-ACTIVE embedding column IS NULL (S2).* Pre-flight short-circuit for `embed --stale` so a 100%-embedded brain@@ -1428,13 +1428,13 @@ export interface BrainEngine {* grant); the scalar branch is internal/CLI and keeps cross-source visibility* (reconcileLinks + back-link validators depend on it).*/- getLinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<Link[]>;+ getLinks(slug: string, opts?: PageReadScope): Promise<Link[]>;/*** v0.31.8 (D12 + D16): same `opts.sourceId` semantics as `getLinks`,* applied to the to-page side of the join. #2200: `opts.sourceIds` federated* grant constrains both endpoints (see `getLinks`).*/- getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<Link[]>;+ getBacklinks(slug: string, opts?: PageReadScope): Promise<Link[]>;/*** v114 (#1941): distinct link_source provenances with edge counts, for* `gbrain link-sources`. Source-scoped via `{sourceId?, sourceIds?}` (both@@ -1497,7 +1497,7 @@ export interface BrainEngine {*/traversePaths(slug: string,- opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[] },+ opts?: PageReadScope & { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both' },): Promise<GraphPath[]>;/*** `traversePaths` plus its truncation signal. The final SELECT is bounded@@ -1511,7 +1511,7 @@ export interface BrainEngine {*/traversePathsDetailed(slug: string,- opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[] },+ opts?: PageReadScope & { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both' },): Promise<{ paths: GraphPath[]; truncated: boolean }>;/*** Typed-edge relational fan-out for the relational recall arm (v0.43).@@ -1543,7 +1543,7 @@ export interface BrainEngine {* Keyed by page id — NOT slug — so namesake slugs across sources never* share or sum counts (#4380). Ids with zero links map to 0.*/- getBacklinkCounts(pageIds: number[]): Promise<Map<number, number>>;+ getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>>;/*** v0.40.4 — for a list of page_ids, return adjacency aggregates* restricted to the subgraph induced by them. Returns ALL pages with@@ -1556,7 +1556,7 @@ export interface BrainEngine {* target's own source), in-set** SOURCE-SCOPE CONTRACT: pageIds MUST already be source-scoped by the- * caller. This method does NOT filter by source_id. Adjacency is+ * caller. An optional read scope authorizes endpoints and origins. Adjacency is* page-id keyed and the in-set restriction makes cross-source leakage* impossible BY CONSTRUCTION (a leaked-in page_id from another source* would have to also appear in the caller's input set, which the@@ -1569,7 +1569,7 @@ export interface BrainEngine {* source" (codex outside-voice #15). T-todo-4 captures the v0.41+* sync-topology-aware refinement.*/- getAdjacencyBoosts(pageIds: number[]): Promise<Map<number, AdjacencyRow>>;+ getAdjacencyBoosts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, AdjacencyRow>>;/*** v0.42 (issue #1699): for a list of page_ids, return their* `frontmatter.content_flag` markers (reason + detail). Used by hybrid@@ -1580,6 +1580,7 @@ export interface BrainEngine {*/getContentFlagsByPageIds(pageIds: number[],+ opts?: PageReadScope,): Promise<Map<number, { reason: string; detail: string }>>;/*** Extraction quarantine lane (issue #160), widened for #4220: for a list@@ -1595,6 +1596,7 @@ export interface BrainEngine {*/getUnverifiedExtractionPageIds(pageIds: number[],+ opts?: PageReadScope,): Promise<Map<number, { unverified: boolean; status: string }>>;/*** v0.27.0: for a list of slugs, return their updated_at timestamps (or created_at fallback).@@ -1614,7 +1616,7 @@ export interface BrainEngine {* Drives the new applyRecencyBoost post-fusion stage. Returns NULL for refs* with no row; map omits them.*/- getEffectiveDates(refs: Array<{slug: string; source_id: string}>): Promise<Map<string, Date>>;+ getEffectiveDates(refs: Array<{slug: string; source_id: string}>, opts?: PageReadScope): Promise<Map<string, Date>>;/*** v0.29.1: for a list of (slug, source_id) refs, return the salience score* (emotional_weight × 5 + ln(1 + take_count)) per ref. Single SQL query.@@ -1624,7 +1626,7 @@ export interface BrainEngine {* (or zero emotional_weight + zero takes) get score = 0; the boost stage* skips them.*/- getSalienceScores(refs: Array<{slug: string; source_id: string}>): Promise<Map<string, number>>;+ getSalienceScores(refs: Array<{slug: string; source_id: string}>, opts?: PageReadPolicy): Promise<Map<string, number>>;/*** Return every page with no inbound links.* Domain comes from the frontmatter `domain` field (null if unset).@@ -1650,10 +1652,10 @@ export interface BrainEngine {/*** #4280: rows carry `type` + `quarantined` so the shared orphan-reporting* policy can exclude machine leaf types and quarantined shells that slug- * conventions cannot infer. The SQL stays raw (no filtering here) — policy- * lives in ONE place (`shouldExcludeFromOrphanReporting`).+ * conventions cannot infer. SQL applies read authorization; reporting exclusions remain in+ * ONE place (`shouldExcludeFromOrphanReporting`).*/- findOrphanPages(opts?: {+ findOrphanPages(opts?: PageReadScope & {sourceId?: string;sourceIds?: string[];mode?: 'inbound' | 'islanded';@@ -1729,9 +1731,9 @@ export interface BrainEngine {/** Events/timeline rows on or after `date`, optionally filtered by event.kind. */getSince(date: string, opts?: ChronicleTimelineOpts): Promise<ChronicleTimelineRow[]>;/** "On this day" — events from the same month-day in PRIOR years (default: today). */- getOnThisDay(opts?: { date?: string; limit?: number; sourceId?: string; sourceIds?: string[] }): Promise<ChronicleTimelineRow[]>;+ getOnThisDay(opts?: PageReadScope & { date?: string; limit?: number }): Promise<ChronicleTimelineRow[]>;/** Most recent date an entity appears (its own page or an event's `who`). */- getLastSeen(entitySlug: string, opts?: { asof?: string; sourceId?: string; sourceIds?: string[] }): Promise<LastSeenResult>;+ getLastSeen(entitySlug: string, opts?: PageReadScope & { asof?: string }): Promise<LastSeenResult>;/*** Upsert the date-index projection row for an event page: page_id = depth* page, event_page_id = event page, keyed (event_page_id, date). Re-extraction@@ -1770,7 +1772,7 @@ export interface BrainEngine {* it, multi-source brains return raw_data rows from every same-slug page* (preserved via two-branch query for back-compat).*/- getRawData(slug: string, source?: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<RawData[]>;+ getRawData(slug: string, source?: string, opts?: PageReadScope): Promise<RawData[]>;// Files (v0.27.1: binary asset metadata + storage_path. Image bytes never// enter the DB; storage_path references a path inside the brain repo or an@@ -2237,7 +2239,7 @@ export interface BrainEngine {* When omitted, returns versions for every same-slug page across sources* (pre-v0.31.8 behavior; preserved via two-branch query).*/- getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<PageVersion[]>;+ getVersions(slug: string, opts?: PageReadScope): Promise<PageVersion[]>;/*** v0.31.8 (D12): `opts.sourceId` source-scopes both the version lookup* and the page revert. Without it, multi-source brains can revert the@@ -2304,6 +2306,7 @@ export interface BrainEngine {resolveSlugWithAlias(slug: string,sourceOrSources: string | readonly string[],+ opts?: Pick<PageReadScope, 'excludePrivate'>,): Promise<string>;/*** `resolveSlugWithAlias` plus the OWNING source of the winning alias row@@ -2316,6 +2319,7 @@ export interface BrainEngine {resolveSlugWithAliasDetailed(slug: string,sourceOrSources: string | readonly string[],+ opts?: Pick<PageReadScope, 'excludePrivate'>,): Promise<{ canonical_slug: string; source_id: string } | null>;/**@@ -2333,7 +2337,7 @@ export interface BrainEngine {*/resolveAliases(aliasNorms: string[],- opts?: { sourceId?: string; sourceIds?: string[] },+ opts?: PageReadScope,): Promise<Map<string, Array<{ slug: string; source_id: string }>>>;/**diff --git a/src/core/entity-identity.ts b/src/core/entity-identity.tsindex 96197bbcf8..a9cddcf2fc 100644--- a/src/core/entity-identity.ts+++ b/src/core/entity-identity.ts@@ -29,6 +29,7 @@import type { BrainEngine } from './engine.ts';import type { Link } from './types.ts';import { isUndefinedTableError } from './utils.ts';+import { privatePagesFilterFragment } from './search/private-visibility.ts';/** Config key for the flag-gated retrieval union. Default OFF. */export const ENTITY_IDENTITY_UNION_CONFIG_KEY = 'entity_identity.union';@@ -146,9 +147,11 @@ export async function unlinkEntityIdentity(}/**- * List identity members. Filters compose (AND). `allowedSources` restricts+ * List identity members. Filters compose (AND). Non-empty `allowedSources` restricts* MEMBER VISIBILITY (federated read grant) — a caller who can't read source- * X never learns X's member pages, even when another member matched.+ * X never learns X's member pages, even when another member matched. Without+ * that grant, `sourceId` is the scalar floor; private seeds and members are+ * excluded together when `excludePrivate` is set.** The identity key is (source_id, slug), so the `slug` filter alone is* ambiguous: pass `slugSourceId` to seed group resolution from exactly the@@ -159,10 +162,13 @@ export async function unlinkEntityIdentity(*/export async function listEntityIdentities(engine: BrainEngine,- opts: { entityId?: string; slug?: string; slugSourceId?: string; allowedSources?: string[] } = {},+ opts: { entityId?: string; slug?: string; slugSourceId?: string; sourceId?: string; allowedSources?: string[]; excludePrivate?: boolean } = {},): Promise<EntityIdentityMember[]> {const where: string[] = [];const params: unknown[] = [];+ const allowedSources = opts.allowedSources?.length ? opts.allowedSources+ : opts.sourceId ? [opts.sourceId] : undefined;+ if (opts.excludePrivate) where.push(privatePagesFilterFragment('p'));if (opts.entityId) {params.push(validateEntityId(opts.entityId));where.push(`ei.entity_id = $${params.length}`);@@ -178,21 +184,23 @@ export async function listEntityIdentities(if (opts.slugSourceId) {params.push(opts.slugSourceId);seedScope = ` AND ei2.source_id = $${params.length}`;- } else if (opts.allowedSources && opts.allowedSources.length > 0) {- const ph = opts.allowedSources.map((s) => {+ }+ if (allowedSources) {+ const ph = allowedSources.map((s) => {params.push(s);return `$${params.length}`;});- seedScope = ` AND ei2.source_id IN (${ph.join(', ')})`;+ seedScope += ` AND ei2.source_id IN (${ph.join(', ')})`;}+ if (opts.excludePrivate) seedScope += ` AND ${privatePagesFilterFragment('p2')}`;where.push(`ei.entity_id IN (SELECT ei2.entity_id FROM entity_identities ei2- JOIN pages p2 ON p2.id = ei2.page_id+ JOIN pages p2 ON p2.id = ei2.page_id AND p2.source_id = ei2.source_idWHERE p2.slug = $${slugParam} AND p2.deleted_at IS NULL${seedScope})`);}- if (opts.allowedSources && opts.allowedSources.length > 0) {- const placeholders = opts.allowedSources.map((s) => {+ if (allowedSources) {+ const placeholders = allowedSources.map((s) => {params.push(s);return `$${params.length}`;});@@ -212,7 +220,7 @@ export async function listEntityIdentities(`SELECT ei.entity_id, ei.source_id, p.slug, p.title, ei.confidence,ei.established_by, ei.established_at, ei.canonicalFROM entity_identities ei- JOIN pages p ON p.id = ei.page_id AND p.deleted_at IS NULL+ JOIN pages p ON p.id = ei.page_id AND p.source_id = ei.source_id AND p.deleted_at IS NULL${where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''}ORDER BY ei.entity_id, ei.canonical DESC, ei.source_id, p.slug`,params,@@ -266,7 +274,7 @@ export async function unionLinksAcrossIdentity(slug: string,links: Link[],direction: 'out' | 'in',- opts: { sourceId?: string; allowedSources?: string[] } = {},+ opts: { sourceId?: string; allowedSources?: string[]; excludePrivate?: boolean } = {},): Promise<Link[]> {if (!(await isIdentityUnionEnabled(engine))) return links;let members: EntityIdentityMember[];@@ -276,7 +284,9 @@ export async function unionLinksAcrossIdentity(// #4224 review fix: seed group resolution from the BASE page's// (slug, source) — never from a foreign same-slug page.slugSourceId: opts.sourceId,+ sourceId: opts.sourceId,allowedSources: opts.allowedSources,+ excludePrivate: opts.excludePrivate,});} catch {return links; // never let the union break the base read@@ -298,10 +308,19 @@ export async function unionLinksAcrossIdentity(const seen = new Set(merged.map(keyOf));for (const m of coMembers) {try {+ const memberScope = {+ sourceId: m.source_id,+ ...(opts.allowedSources?.length ? { sourceIds: opts.allowedSources } : {}),+ excludePrivate: opts.excludePrivate,+ };const memberLinks = direction === 'out'- ? await engine.getLinks(m.slug, { sourceId: m.source_id })- : await engine.getBacklinks(m.slug, { sourceId: m.source_id });+ ? await engine.getLinks(m.slug, memberScope)+ : await engine.getBacklinks(m.slug, memberScope);for (const l of memberLinks) {+ // Federated engine reads span same-slug pages across the grant. Keep+ // this identity member's concrete pair, not a same-slug non-member.+ const memberSource = direction === 'out' ? l.from_source_id : l.to_source_id;+ if (memberSource !== m.source_id) continue;const k = keyOf(l);if (seen.has(k)) continue;seen.add(k);diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 9a51fb2a17..0c14d44582 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -7,6 +7,9 @@ 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 { sanitizeRemoteBody } from './remote-body.ts';+import { sanitizeText } from './batch-rows.ts';+import { hasProtectedBody, safeChunksFilter } from './search/safe-chunks.ts';import { findChunkForOffset } from './chunkers/edge-extractor.ts';import { planEmbeddingReuse } from './embed-reuse.ts';import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';@@ -175,6 +178,7 @@ 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@@ -405,6 +409,12 @@ export async function importFromContent(return { slug, status: 'error', chunks: 0, error: frontmatterError };}+ // Canonicalize only free-prose fields before protected-fence parsing, hidden+ // row merging, hashing and indexing. Frontmatter identities stay untouched.+ parsed.title = sanitizeText(parsed.title);+ parsed.compiled_truth = sanitizeText(parsed.compiled_truth);+ parsed.timeline = sanitizeText(parsed.timeline);+// v0.42 (#1699 trust boundary): strip gate-owned markers from UNTRUSTED// input. parseMarkdown preserves every frontmatter key except type/title/// tags/slug, so a remote MCP put_page (ctx.remote !== false, threaded as@@ -981,11 +991,7 @@ export async function importFromContent(effective_date: effectiveDate,effective_date_source: effectiveDateSource,import_filename: filenameForChain,- // v0.32.7 CJK wave: stamp the chunker version so the post-upgrade- // reindex sweep can find pre-bump pages via `chunker_version < 2`.- // Also capture the repo-relative source path so sync's delete/rename- // code can resolve frontmatter-fallback slugs back to their files.- chunker_version: MARKDOWN_CHUNKER_VERSION,+ // Preserve the repo-relative path for sync's delete/rename handling.source_path: opts.sourcePath ?? null,// v0.39.3.0 provenance write-through (WARN-8). Engine layer applies// COALESCE-preserve UPDATE so omitting these on a later put_page@@ -1036,6 +1042,10 @@ export async function importFromContent(await tx.addTag(slug, tag, txOpts);}+ // A new seal cannot inherit vectors or metadata from an older index, even+ // when a public fragment is unchanged: its old contextual vector may have+ // included a private sibling fragment. Replace every derived row atomically.+ await tx.deleteChunks(slug, txOpts);if (chunks.length > 0) {await tx.upsertChunks(slug, chunks, txOpts);// v0.41.31: stamp embedding provenance when this import actually@@ -1054,6 +1064,10 @@ export async function importFromContent(// Content is empty — delete stale chunks so they don't ghost in search resultsawait tx.deleteChunks(slug, txOpts);}+ // Seal only the completed, full-body sanitized replacement. A body-only+ // write or a failed transaction must never certify old stored fragments.+ await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',+ [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);// v0.19.0 E1 — doc↔impl linking: if this markdown page cites code paths// (e.g. 'src/core/sync.ts:42'), create bidirectional edges to the code@@ -1061,7 +1075,7 @@ export async function importFromContent(// this in v0.18.x), so we wrap each pair in try/catch — guides imported// before their code repo syncs are common, and the missing edges land// later via `gbrain reconcile-links` (Layer 8 D3, v0.21.0).- const codeRefs = extractCodeRefs(parsed.compiled_truth + '\n' + (parsed.timeline || ''));+ const codeRefs = extractCodeRefs(sanitizeRemoteBody(parsed.compiled_truth) + '\n' + sanitizeRemoteBody(parsed.timeline || ''));// For doc↔impl edges, both endpoints are within the same source as the// markdown page being imported. Cross-source edges (markdown in one// source, code in another) currently fail with "page not found" — a@@ -1442,7 +1456,7 @@ export async function importCodeFile(// PostgreSQL text columns reject U+0000 even though source files may// legitimately contain it inside string/regex fixtures. Preserve a visible,// searchable representation instead of dropping the entire code page.- const storageContent = content.replaceAll('\0', '\\0');+ const storageContent = sanitizeText(content.replaceAll('\0', '\\0'));const byteLength = Buffer.byteLength(content, 'utf-8');if (byteLength > MAX_FILE_SIZE) {@@ -1488,7 +1502,7 @@ 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(storageContent, relativePath);+ const { chunks: codeChunks, edges: extractedEdges } = await chunkCodeTextFull(sanitizeRemoteBody(storageContent), relativePath);const chunks: ChunkInput[] = codeChunks.map((c, i) => ({chunk_index: i,chunk_text: c.text,@@ -1515,8 +1529,8 @@ export async function importCodeFile(// byte-identical bodies.// `includeEmbedding` is load-bearing: #2544 dropped the vector from the// default column list, which silently made this whole cache a no-op.- const existingChunks = existing- ? await engine.getChunks(slug, { sourceId: sourceId ?? 'default', includeEmbedding: true })+ const existingChunks = existing && !opts.noEmbed+ ? await engine.getChunks(slug, { sourceId: sourceId ?? 'default', includeEmbedding: true, requireSafeChunks: true }): [];const { reuse, needsEmbedIndexes } = planEmbeddingReuse(existingChunks, chunks);for (const [i, matched] of reuse) {@@ -1563,6 +1577,7 @@ export async function importCodeFile(await tx.addTag(slug, 'code', txOpts);await tx.addTag(slug, lang, txOpts);+ await tx.deleteChunks(slug, txOpts);if (chunks.length > 0) {await tx.upsertChunks(slug, chunks, txOpts);// v0.41.31: stamp embedding provenance ONLY when every chunk was@@ -1580,6 +1595,8 @@ export async function importCodeFile(} else {await tx.deleteChunks(slug, txOpts);}+ await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',+ [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);});// Post-write read-back verification.@@ -1710,6 +1727,8 @@ export interface ImportTransactionSpec {page: PageInput;/** When undefined, no chunk write happens. When [], deletes any prior chunks. */chunks?: ChunkInput[];+ /** Internal import assertion: all indexing inputs were checked as a full body. */+ safeChunks?: boolean;/** Optional file-row insert (image ingest). Page link injected automatically. */file?: FileSpec;/**@@ -1743,12 +1762,17 @@ export async function withImportTransaction(});}if (spec.chunks !== undefined) {+ await tx.deleteChunks(spec.slug, txOpts);if (spec.chunks.length > 0) {await tx.upsertChunks(spec.slug, spec.chunks, txOpts);} else {await tx.deleteChunks(spec.slug, txOpts);}}+ if (spec.safeChunks && spec.chunks !== undefined) {+ await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3',+ [MARKDOWN_CHUNKER_VERSION, sourceId, spec.slug]);+ }if (spec.after) await spec.after(tx);});}@@ -1946,10 +1970,12 @@ async function maybeOcr(engine: BrainEngine,imgBuf: Buffer,mime: string,-): Promise<string> {+): Promise<{ text: string; successful: boolean }> {const opt = process.env.GBRAIN_EMBEDDING_IMAGE_OCR;- if (opt !== 'true') return '';- return maybeOcrGated(engine, imgBuf, mime);+ if (opt !== 'true') return { text: '', successful: false };+ let successful = false;+ const text = await maybeOcrGated(engine, imgBuf, mime, () => { successful = true; });+ return { text, successful };}/** #3973: body of maybeOcr past the opt-in check; exported for budget tests. */@@ -1965,6 +1991,7 @@ async function maybeOcrGated(engine: BrainEngine,imgBuf: Buffer,mime: string,+ onSuccess?: () => void,): Promise<string> {// Counter helpers — quiet failure if config table is unavailable.@@ -2006,6 +2033,7 @@ async function maybeOcrGated(}const text = await generateOcrText(imgBuf, mime);await bump('ocr_succeeded');+ onSuccess?.();return text;} catch (err) {if (!_ocrWarnedThisSession) {@@ -2078,8 +2106,18 @@ export async function importImageFile(const hash = createHash('sha256').update(buf).digest('hex');const existing = await engine.getPage(imageSlug, sourceOpts);+ const hadProtectedOcr = !!existing && hasProtectedBody(existing.compiled_truth + '\n' + (existing.timeline || ''));if (existing?.content_hash === hash) {- return { slug: imageSlug, status: 'skipped', chunks: 0 };+ if (hadProtectedOcr) {+ // OCR being disabled or failing on a later run cannot make the same+ // protected pixels safe for visual ranking.+ return { slug: imageSlug, status: 'skipped', chunks: 0,+ error: 'Image OCR contains protected sections. Remove that content from the source image and reimport the changed image.' };+ }+ // An unchanged legacy image still needs its full OCR/visual index rebuilt.+ const sealed = await engine.executeRaw(`SELECT id FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND ${safeChunksFilter('p')}`,+ [sourceOpts.sourceId, imageSlug]);+ if (sealed.length) return { slug: imageSlug, status: 'skipped', chunks: 0 };}// Decode HEIC/AVIF; pass-through for universal codecs.@@ -2100,9 +2138,16 @@ export async function importImageFile(// OCR opt-in (cherry-1). Runs through the per-process limiter so 100// images first-import doesn't serialize into 200s of OCR latency.- const ocrText: string = opts.noEmbed- ? ''+ const ocr = opts.noEmbed+ ? { text: '', successful: false }: await _ocrLimiter(() => maybeOcr(engine, decoded.buf, decoded.mime));+ if (hadProtectedOcr && !ocr.successful) {+ return { slug: imageSlug, status: 'skipped', chunks: 0,+ error: 'Replacing an image with protected OCR requires successful fresh OCR. Enable OCR and reimport the changed image.' };+ }+ // Protection checks, chunks and stored OCR must agree on canonical text,+ // including markers made recognizable by NUL removal.+ const ocrText = sanitizeText(ocr.text);// Multimodal embed.let embedding: Float32Array | null = null;@@ -2136,7 +2181,7 @@ export async function importImageFile(// chunk_source='image_asset' joins the v0.20 chunk_source allowlist.const chunk: ChunkInput & { modality?: string; embedding_image?: Float32Array } = {chunk_index: 0,- chunk_text: ocrText || filename,+ chunk_text: sanitizeRemoteBody(ocrText || filename),chunk_source: 'image_asset',modality: 'image',...(embedding ? { embedding_image: embedding } : {}),@@ -2167,6 +2212,9 @@ export async function importImageFile(// a changed image whose OCR yields nothing legitimately blanks the body.allowEmptyOverwrite: true,chunks: [chunk],+ // The visual embedding still represents every pixel. An OCR fence means+ // the image cannot be sealed merely by sanitizing its textual fragment.+ safeChunks: !hasProtectedBody(ocrText || ''),file: fileSpec,after: async (tx) => {// Cherry-3: path-proximity auto-link to a sibling text page. The firstdiff --git a/src/core/mcp-client.ts b/src/core/mcp-client.tsindex 6fc91ed444..964109673e 100644--- a/src/core/mcp-client.ts+++ b/src/core/mcp-client.ts@@ -12,14 +12,14 @@* + N × get_job). Persisting to disk would create a credential-on-disk* surface for marginal benefit — re-mint is a single sub-100ms /token call.*- * 401 handling: on a tool-call rejection, drop the cached token, mint fresh- * once, retry the call. If the second attempt also 401s, surface a structured- * error with the mcp_url + suggested remedy. Auth-failure-after-refresh is the- * canonical "client credentials revoked or scope insufficient" signal.+ * HTTP 401 handling: drop the cached token, mint fresh once, retry the call.+ * Application errors and other HTTP statuses are terminal. If the refreshed+ * attempt is also rejected with HTTP 401, surface auth_after_refresh.*/import { Client } from '@modelcontextprotocol/sdk/client/index.js';-import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { StreamableHTTPClientTransport, StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { anySignal } from './abort-check.ts';import type { GBrainConfig } from './config.ts';import { discoverOAuth, mintClientCredentialsToken } from './remote-mcp-probe.ts';@@ -91,25 +91,35 @@ export class RemoteMcpError extends Error {* Not part of the public API — production code should consume this only via* the callRemoteTool funnel.*/-export function toRemoteMcpError(e: unknown, mcpUrl: string): RemoteMcpError {+export function toRemoteMcpError(e: unknown, mcpUrl: string, signal?: AbortSignal): RemoteMcpError {+ if (signal?.aborted) {+ const kind = signal.reason instanceof Error && signal.reason.name === 'TimeoutError'+ ? 'timeout' : 'aborted';+ return new RemoteMcpError(+ 'network',+ `Request to ${mcpUrl} ${kind === 'timeout' ? 'timed out' : 'was aborted'}`,+ { mcp_url: mcpUrl, kind },+ );+ }if (e instanceof RemoteMcpError) return e;if (e instanceof Error) {- // AbortError fires for both --timeout and SIGINT; the caller distinguishes- // via the AbortSignal.reason it set, but the SDK swallows that. Fall back- // to message inspection for the timeout sub-kind.- const isAbort = e.name === 'AbortError' || /abort/i.test(e.message);- if (isAbort) {+ if (e.name === 'AbortError' || e.name === 'TimeoutError') {return new RemoteMcpError('network',- `Request to ${mcpUrl} aborted: ${e.message}`,- { mcp_url: mcpUrl, kind: 'aborted' },+ `Request to ${mcpUrl} ${e.name === 'TimeoutError' ? 'timed out' : 'was aborted'}`,+ { mcp_url: mcpUrl, kind: e.name === 'TimeoutError' ? 'timeout' : 'aborted' },);}// undici/fetch network errors (DNS, connection refused, TLS) end up here.return new RemoteMcpError('network',`Network error talking to ${mcpUrl}: ${e.message}`,- { mcp_url: mcpUrl, kind: 'unreachable' },+ {+ mcp_url: mcpUrl,+ kind: 'unreachable',+ ...(e instanceof StreamableHTTPError && e.code !== undefined && e.code > 0+ ? { status: e.code } : {}),+ },);}return new RemoteMcpError(@@ -132,7 +142,8 @@ export function extractToolErrorCode(message: string): string | undefined {try {const parsed = JSON.parse(message);if (parsed && typeof parsed === 'object') {- const code = (parsed as any).error?.code ?? (parsed as any).code;+ const code = typeof parsed.error === 'string'+ ? parsed.error : parsed.error?.code ?? parsed.code;if (typeof code === 'string') return code;}} catch { /* not json; fall through */ }@@ -167,7 +178,8 @@ function resolveSecret(remote: NonNullable<GBrainConfig['remote_mcp']>): string* Mint or reuse a cached access_token for the given config. Throws* RemoteMcpError on discovery failure or auth rejection.*/-async function getAccessToken(config: GBrainConfig, force = false): Promise<string> {+async function getAccessToken(config: GBrainConfig, force = false, signal?: AbortSignal): Promise<string> {+ signal?.throwIfAborted();const remote = requireRemoteMcp(config);const cached = tokenCache.get(remote.mcp_url);if (!force && cached && cached.expires_at_ms > Date.now()) {@@ -176,21 +188,23 @@ async function getAccessToken(config: GBrainConfig, force = false): Promise<striconst secret = resolveSecret(remote);- const disco = await discoverOAuth(remote.issuer_url);+ const disco = await discoverOAuth(remote.issuer_url, { signal });+ signal?.throwIfAborted();if (!disco.ok) {throw new RemoteMcpError(disco.reason === 'http' || disco.reason === 'parse' ? 'discovery' : 'network',`OAuth discovery failed: ${disco.message}`,- { ...(disco.status ? { status: disco.status } : {}), mcp_url: remote.mcp_url },+ { ...(disco.status ? { status: disco.status } : {}), ...(disco.kind ? { kind: disco.kind } : {}), mcp_url: remote.mcp_url },);}- const tokenRes = await mintClientCredentialsToken(disco.metadata.token_endpoint, remote.oauth_client_id, secret);+ const tokenRes = await mintClientCredentialsToken(disco.metadata.token_endpoint, remote.oauth_client_id, secret, { signal });+ signal?.throwIfAborted();if (!tokenRes.ok) {throw new RemoteMcpError(tokenRes.reason === 'auth' ? 'auth' : tokenRes.reason === 'network' ? 'network' : 'discovery',`OAuth /token failed: ${tokenRes.message}`,- { ...(tokenRes.status ? { status: tokenRes.status } : {}), mcp_url: remote.mcp_url },+ { ...(tokenRes.status ? { status: tokenRes.status } : {}), ...(tokenRes.kind ? { kind: tokenRes.kind } : {}), mcp_url: remote.mcp_url },);}@@ -208,8 +222,8 @@ async function getAccessToken(config: GBrainConfig, force = false): Promise<stri* swap headers on an existing connection — re-mint + reconnect on 401 is* cheaper than reusing.*- * v0.31.1: optional AbortSignal threaded into `requestInit` so callers can- * cancel in-flight HTTP requests on timeout or SIGINT.+ * The SDK replaces requestInit.signal with its own transport signal. Compose+ * them in fetch so cancellation covers HTTP bodies as well as SDK requests.*/async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSignal): Promise<Client> {const transport = new StreamableHTTPClientTransport(new URL(mcpUrl), {@@ -217,20 +231,31 @@ async function buildClient(mcpUrl: string, accessToken: string, signal?: AbortSiheaders: {'Authorization': `Bearer ${accessToken}`,},- ...(signal ? { signal } : {}),},+ fetch: (input, init) => fetch(input, {+ ...init,+ signal: signal ? anySignal(signal, init?.signal) : init?.signal,+ }),});const client = new Client({ name: 'gbrain-remote-cli', version: '1' },{ capabilities: {} },);- await client.connect(transport);- return client;+ try {+ signal?.throwIfAborted();+ await client.connect(transport, { signal });+ return client;+ } catch (error) {+ try { await client.close(); } catch { /* best-effort */ }+ // Also close when connect failed before attaching the transport.+ try { await transport.close(); } catch { /* best-effort */ }+ throw error;+ }}/**- * v0.31.1: options for `callRemoteTool`. Both fields optional; when absent the- * call inherits SDK defaults (no client-side timeout, no abort).+ * Options for `callRemoteTool`. When absent, discovery/token requests retain+ * their own caps and MCP requests inherit the SDK's timeout.*/export interface CallRemoteToolOptions {/** Hard wall-clock cap for the whole call (token mint + tool call). Aborts on expiry. */@@ -251,7 +276,7 @@ export function buildAbortController(opts: CallRemoteToolOptions): { signal: Aboif (opts.timeoutMs !== undefined && opts.timeoutMs > 0) {const timer = setTimeout(() => {- controller.abort(new Error(`timeout after ${opts.timeoutMs}ms`));+ controller.abort(new DOMException(`timeout after ${opts.timeoutMs}ms`, 'TimeoutError'));}, opts.timeoutMs);cleanups.push(() => clearTimeout(timer));}@@ -296,15 +321,16 @@ export async function callRemoteTool(// Step 1: mint (or reuse cached) token. If THIS fails — bad credentials,// unreachable issuer, etc. — surface immediately. Retry-on-401 is for// the mid-session token-rotation case, NOT for initial-credentials-wrong.- const initialToken = await getAccessToken(config, false);+ const initialToken = await getAccessToken(config, false, signal);- // Step 2: try the tool call. On a 401-shaped failure here, drop the cache+ // Step 2: try the tool call. On an HTTP 401 here, drop the cache// and retry ONCE with a freshly-minted token (handles host-side rotation// mid-session). If the retry also fails auth, surface auth_after_refresh.const tryCall = async (token: string): Promise<unknown> => {const client = await buildClient(remote.mcp_url, token, signal);try {- const res = await client.callTool({ name: toolName, arguments: args });+ signal.throwIfAborted();+ const res = await client.callTool({ name: toolName, arguments: args }, undefined, { signal });if (res.isError) {const message = Array.isArray(res.content)? res.content.map((c: unknown) => (c as { text?: string }).text ?? '').join('\n')@@ -328,23 +354,21 @@ export async function callRemoteTool(try {return await tryCall(initialToken);} catch (e) {- // RemoteMcpError already-typed: bubble unless it's a tool_error that- // happens to look 401-shaped (e.g. SDK wrapping HTTP 401 in a tool- // error). For plain Error, do the 401 sniff.- const message = e instanceof Error ? e.message : String(e);- const looksLike401 = /401|unauthor|invalid.token/i.test(message);- if (!looksLike401) throw e;+ // Application errors can contain arbitrary text (including client IDs+ // with "401"). Only a rejected HTTP request authorizes a replay.+ signal.throwIfAborted();+ if (!(e instanceof StreamableHTTPError) || e.code !== 401) throw e;// Drop cached token and retry once with a fresh mint.tokenCache.delete(remote.mcp_url);let freshToken: string;try {- freshToken = await getAccessToken(config, true);+ freshToken = await getAccessToken(config, true, signal);} catch (mintErr) {if (mintErr instanceof RemoteMcpError && mintErr.reason === 'auth') {throw new RemoteMcpError('auth_after_refresh',`Auth failed after token refresh. Verify oauth_client_id and secret are still valid; the host operator may need to re-run \`gbrain auth register-client\`.`,- { mcp_url: remote.mcp_url },+ { mcp_url: remote.mcp_url, ...(mintErr.detail?.status ? { status: mintErr.detail.status } : {}) },);}throw mintErr;@@ -352,12 +376,13 @@ export async function callRemoteTool(try {return await tryCall(freshToken);} catch (e2) {- const m2 = e2 instanceof Error ? e2.message : String(e2);- if (/401|unauthor|invalid.token/i.test(m2)) {+ signal.throwIfAborted();+ if (e2 instanceof StreamableHTTPError && e2.code === 401) {+ tokenCache.delete(remote.mcp_url);throw new RemoteMcpError('auth_after_refresh',`Auth failed after token refresh. Verify oauth_client_id and secret are still valid; the host operator may need to re-run \`gbrain auth register-client\`.`,- { mcp_url: remote.mcp_url },+ { mcp_url: remote.mcp_url, status: 401 },);}throw e2;@@ -367,7 +392,7 @@ export async function callRemoteTool(// CDX-4: this is the funnel. ANYTHING that escapes the inner block becomes// a typed RemoteMcpError. The dispatcher's exhaustive switch can rely on// this contract.- throw toRemoteMcpError(e, remote.mcp_url);+ throw toRemoteMcpError(e, remote.mcp_url, signal);} finally {cleanup();}diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.tsindex c476e1754a..b4f4a9553c 100644--- a/src/core/operations-descriptions.ts+++ b/src/core/operations-descriptions.ts@@ -19,8 +19,10 @@// ──────────────────────────────────────────────────────────────────────────────export const GET_RECENT_SALIENCE_DESCRIPTION =- "Returns pages recently touched and ranked by emotional + activity salience " +- "(deterministic 0..1 emotional_weight + take density + recency decay). " ++ "Returns readable pages recently touched and ranked by activity salience and recency. " ++ "Unrestricted local reads include deterministic 0..1 emotional_weight, take density, and recency decay. " ++ "Holder-restricted reads count only permitted active takes, use zero emotional_weight, " ++ "and select recent pages by updated_at; unrestricted local reads retain take-driven touches. " +"Use this when the user asks what's been going on, what's notable, what's hot, " +"anything crazy happening, or for any open-ended 'current state' question " +"about themselves or their work. Do NOT run a semantic search for these — " +@@ -100,13 +102,15 @@ export const SEARCH_DESCRIPTION =// ──────────────────────────────────────────────────────────────────────────────export const FIND_CONTRADICTIONS_DESCRIPTION =- "v0.32.6 — return suspected-contradiction findings from the most recent " ++ "Stored contradiction reports are temporarily available only to trusted local callers without a source filter. " ++ "Remote or source-scoped callers receive {contradictions: [], note} with an availability note. " ++ "For eligible local callers, return suspected-contradiction findings from the most recent " +"`gbrain eval suspected-contradictions` probe run, optionally filtered by slug " +"and/or severity. Use this when the user asks 'what's inconsistent in my " +"brain', 'show me contradictions about Acme', 'high-severity issues only', or " +"wants to act on the probe's findings without re-running it. Returns " +"{contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. " +- "Reads the cached run row — does NOT trigger a new probe; users run " ++ "An eligible read loads the stored run without triggering a new probe; users run " +"`gbrain eval suspected-contradictions` for that.";export const FIND_TRAJECTORY_DESCRIPTION =diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex 8a3e841b63..ca553f0df2 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -1,3 +1,5 @@+import { readPolicyOpts } from './context.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';/*** Admin operation cluster — pure move from operations.ts (v0.46.x tranche 2).* Op consts stay module-private; `adminOperations` below lists them in@@ -10,8 +12,6 @@import type { Operation, OperationContext } from './contract.ts';import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';-import { stripTakesFence } from '../takes-fence.ts';-import { slugHiddenFromCaller } from '../search/private-visibility.ts';import { VERSION } from '../../version.ts';// --- Admin ---@@ -161,19 +161,9 @@ const get_versions: Operation = {slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },},handler: async (ctx, p) => {- const scope = sourceScopeOpts(ctx);- // #4352 remediation: a `visibility: private` page's version history reads- // exactly like a missing page's ([]) for untrusted callers — snapshots- // persist historical compiled_truth verbatim, so /history was a full- // bypass of get_page's gate. No existence oracle.- if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];- const versions = await ctx.engine.getVersions(p.slug as string, scope);- // Same takes-allow-list privacy boundary as get_page. Snapshots persist- // historical compiled_truth verbatim, including the takes fence, so- // a remote token bypassing get_page via /history would re-introduce- // the same leak across every prior version.- if (!ctx.takesHoldersAllowList) return versions;- return versions.map(v => ({ ...v, compiled_truth: stripTakesFence(v.compiled_truth) }));+ const versions = await ctx.engine.getVersions(p.slug as string, await readPolicyOpts(ctx));+ if (ctx.remote === false) return versions;+ return versions.map(v => ({ ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth) }));},scope: 'read',cliHints: { name: 'history', positional: ['slug'] },diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.tsindex 8b1f21a2d8..f3e31b3747 100644--- a/src/core/ops/chronicle.ts+++ b/src/core/ops/chronicle.ts@@ -8,7 +8,7 @@*/import type { Operation, OperationContext } from './contract.ts';-import { sourceScopeOpts } from './context.ts';+import { readPolicyOpts, sourceScopeOpts } from './context.ts';// ── Remote diary redaction (fail-closed) ─────────────────────────────────// The exact mechanism the ontology siblings use (`ctx.remote !== false` →@@ -48,7 +48,7 @@ const chronicle_day: Operation = {const rows = redactDiaryTimeline(ctx, await ctx.engine.getTimelineForDate(String(p.date), {week: p.week === true,limit: typeof p.limit === 'number' ? p.limit : undefined,- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),}));if (p.narrative === true) {const { renderTimelineNarrative } = await import('../chronicle/narrative.ts');@@ -72,7 +72,7 @@ const chronicle_on_this_day: Operation = {handler: async (ctx, p) => redactDiaryTimeline(ctx, await ctx.engine.getOnThisDay({date: typeof p.date === 'string' ? p.date : undefined,limit: typeof p.limit === 'number' ? p.limit : undefined,- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),})),cliHints: { name: 'on-this-day' },};@@ -92,7 +92,7 @@ const chronicle_since: Operation = {return redactDiaryTimeline(ctx, await ctx.engine.getSince(String(p.date), {kind: typeof p.kind === 'string' ? p.kind : undefined,limit: typeof p.limit === 'number' ? p.limit : undefined,- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),}));},cliHints: { name: 'since', positional: ['date'] },@@ -111,7 +111,7 @@ const chronicle_last_seen: Operation = {handler: async (ctx, p) => {const res = await ctx.engine.getLastSeen(String(p.entity), {asof: typeof p.asof === 'string' ? p.asof : undefined,- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),});// Fail-closed diary redaction: when the evidence is a life/diary event// (or a life/diary page is queried AS the entity), remote callers get@@ -245,7 +245,7 @@ const volunteer_chronicle: Operation = {entities,limit: typeof p.limit === 'number' ? p.limit : undefined,remote: ctx.remote !== false,- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),});// Same fail-closed diary redaction as the timeline reads: the loader// redacts diary-sourced ONTOLOGY; the recent timeline is redacted here.diff --git a/src/core/ops/chunks.ts b/src/core/ops/chunks.tsindex a9f457deef..a9e96d0d07 100644--- a/src/core/ops/chunks.ts+++ b/src/core/ops/chunks.ts@@ -7,12 +7,8 @@*/import type { Operation } from './contract.ts';-import { federatedSearchScope, parseSourceIdParam, sourceScopeOpts } from './context.ts';-import {- findPrivateOnlySlugs,- resolveExcludePrivatePages,- slugHiddenFromCaller,-} from '../search/private-visibility.ts';+import { readPolicyOpts } from './context.ts';+import { federatedSearchScope, parseSourceIdParam } from './context.ts';// --- Resolution & Chunks ---@@ -35,15 +31,7 @@ const resolve_slugs: Operation = {// per-call source_id narrows through resolveRequestedScope.const sourceIdParam = parseSourceIdParam(p.source_id, 'resolve_slugs', { allowAll: true });const scope = federatedSearchScope(ctx, sourceIdParam);- const candidates = await ctx.engine.resolveSlugs(p.partial as string, scope);- // #4352 remediation: fuzzy resolution must not enumerate private slugs to- // an untrusted caller — same gate as get_page's candidate filter (trusted- // local + the operator opt-outs resolve to false and skip the probe).- if (candidates.length === 0 || !(await resolveExcludePrivatePages(ctx.engine, ctx.remote))) {- return candidates;- }- const hidden = await findPrivateOnlySlugs(ctx.engine, candidates, scope);- return candidates.filter(c => !hidden.has(c));+ return ctx.engine.resolveSlugs(p.partial as string, await readPolicyOpts(ctx, scope));},scope: 'read',};@@ -58,10 +46,9 @@ const get_chunks: Operation = {// #2555: route through the canonical scope ladder (federated array >// scalar floor > nothing) instead of the pre-#2200 scalar-only pattern —// a federated grant could read the page via get_page but got [] here.- const scope = sourceScopeOpts(ctx);+ const scope = await readPolicyOpts(ctx);// #4352 remediation: a `visibility: private` page's chunks read exactly// like a missing page's ([]) for untrusted callers — no existence oracle.- if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];return ctx.engine.getChunks(p.slug as string, scope);},scope: 'read',diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.tsindex 29f2c03486..2310f5aebd 100644--- a/src/core/ops/code-intel.ts+++ b/src/core/ops/code-intel.ts@@ -9,6 +9,7 @@*/import type { Operation } from './contract.ts';+import { OperationError } from './contract.ts';import { routeCodeIntelScope } from './context.ts';import {CODE_CALLERS_DESCRIPTION,@@ -260,8 +261,24 @@ const code_traversal_cache_clear: Operation = {cliHints: { name: 'code_traversal_cache_clear', hidden: true },};-export const codeIntelOperations: Operation[] = [+const codeReadOperations: Operation[] = [code_callers, code_callees, code_def, code_refs,code_blast, code_flow,+];++// Raw code fragments and cached traversals do not yet support the complete+// remote read policy. Suspend this optional surface before touching storage.+export const codeIntelOperations: Operation[] = [+ ...codeReadOperations.map((op): Operation => ({+ ...op,+ description: `${op.description} Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.`,+ handler: async (ctx, params) => {+ if (ctx.remote !== false) {+ throw new OperationError('permission_denied',+ `${op.name} is temporarily unavailable to agent callers. Use the trusted local CLI for code reads.`);+ }+ return op.handler(ctx, params);+ },+ })),code_traversal_cache_clear,];diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 9a6e96ce88..aa29712690 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -19,7 +19,8 @@ import { ALL_SOURCES, isValidSourceId } from '../source-id.ts';import { isSearchMode } from '../search/mode.ts';import { stampEvidence } from '../search/evidence.ts';import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from '../eval-capture.ts';-import type { SearchResult, HybridSearchMeta } from '../types.ts';+import type { SearchResult, HybridSearchMeta, PageReadScope, PageReadPolicy } from '../types.ts';+import { resolveExcludePrivatePages } from '../search/private-visibility.ts';// --- Upload validators (Fix 1 / B5 / H5 / M4) ---@@ -460,6 +461,24 @@ export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; soureturn {};}+/** Holder permissions are independent of the operator's page-visibility opt-out. */+export function readHolders(ctx: OperationContext): string[] | undefined {+ return ctx.remote === false ? ctx.takesHoldersAllowList : ctx.takesHoldersAllowList ?? ['world'];+}++/** Resolve policy once at the operation boundary; callers may supply a canonical per-call scope. */+export async function readPolicyOpts(+ ctx: OperationContext,+ scope: PageReadScope = sourceScopeOpts(ctx),+): Promise<PageReadPolicy> {+ return {+ ...scope,+ excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote),+ requireSafeChunks: ctx.remote !== false,+ takesHoldersAllowList: readHolders(ctx),+ };+}+/** Map the operation-layer scope names onto runThink's public options. */export function thinkSourceScopeOpts(ctx: OperationContext): {sourceId?: string;diff --git a/src/core/ops/entity-identity.ts b/src/core/ops/entity-identity.tsindex 048b79b75b..8dcf752f95 100644--- a/src/core/ops/entity-identity.ts+++ b/src/core/ops/entity-identity.ts@@ -20,7 +20,7 @@*/import type { Operation } from './contract.ts';-import { sourceScopeOpts } from './context.ts';+import { sourceScopeOpts, readPolicyOpts } from './context.ts';import {linkEntityIdentity,unlinkEntityIdentity,@@ -120,6 +120,7 @@ const entity_identity_list: Operation = {entityId: p.entity_id as string | undefined,slug: p.slug as string | undefined,allowedSources: identityReadScope(ctx),+ excludePrivate: (await readPolicyOpts(ctx)).excludePrivate,});// Group for readability: one object per entity_id.const groups = new Map<string, typeof members>();diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex bac8a9cc91..4c019bcb5b 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -1,3 +1,4 @@+import { readHolders } from './context.ts';/*** Hot-memory (facts) operation cluster — pure move from operations.ts* (v0.46.x tranche 3): extract_facts, the extended `recall` verb, the@@ -381,18 +382,20 @@ const recall: Operation = {const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);if (!isAvailable('embedding')) {- const raw = await ctx.engine.searchKeyword(queryText, { limit, excludePrivate, ...searchScope });+ const raw = await ctx.engine.searchKeyword(queryText, { limit, excludePrivate, requireSafeChunks: ctx.remote !== false, ...searchScope });searchResults = dedupResults(raw);// #3783 — direct FTS path: every row is a keyword hit by construction.markKeywordHits(searchResults);stampEvidenceSafe(searchResults);- await stampContentFlags(ctx.engine, searchResults);+ await stampContentFlags(ctx.engine, searchResults, { ...searchScope, excludePrivate });searchDegraded = 'keyword_only_no_embedding_provider';} else {searchResults = await hybridSearchCached(ctx.engine, queryText, {limit,expansion: false,excludePrivate,+ requireSafeChunks: ctx.remote !== false,+ takesHoldersAllowList: readHolders(ctx),...searchScope,});}diff --git a/src/core/ops/image.ts b/src/core/ops/image.tsindex e0417e57f8..c183837350 100644--- a/src/core/ops/image.ts+++ b/src/core/ops/image.ts@@ -1,3 +1,4 @@+import { readPolicyOpts } from './context.ts';/*** Image-as-query operation cluster — pure move from operations.ts (v0.46.x* tranche 3): the v0.36 Phase 2 search_by_image op plus its cluster-local@@ -115,7 +116,7 @@ const search_by_image: Operation = {limit: (p.limit as number) || 20,offset: (p.offset as number) || 0,query: queryRefinement,- ...imageSourceScope,+ ...await readPolicyOpts(ctx, imageSourceScope),},);} catch (providerError) {diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex 968ad08ac5..d901b07164 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -11,17 +11,12 @@import type { Operation } from './contract.ts';import { OperationError } from './contract.ts';-import { sourceScopeOpts } from './context.ts';+import { sourceScopeOpts, readPolicyOpts } from './context.ts';import {FIND_EXPERTS_DESCRIPTION,FIND_CONTRADICTIONS_DESCRIPTION,FIND_TRAJECTORY_DESCRIPTION,} from '../operations-descriptions.ts';-import {- dropPrivateOnlyRows,- findWorldVisibleSlugs,- resolveExcludePrivatePages,-} from '../search/private-visibility.ts';// --- v0.43 (#2095): push-based context — the brain volunteers pages ---@@ -157,7 +152,7 @@ const find_experts: Operation = {const { loadActivePackBestEffort, expertTypesFromPack } = await import('../schema-pack/index.ts');const pack = await loadActivePackBestEffort(ctx);const types = pack ? expertTypesFromPack(pack.manifest) : [];- const scope = sourceScopeOpts(ctx);+ const scope = await readPolicyOpts(ctx);const experts = await findExperts(ctx.engine, {topic,limit: typeof p.limit === 'number' ? p.limit : undefined,@@ -165,10 +160,7 @@ const find_experts: Operation = {types: types as never,...scope,});- // A `visibility: private` page's slug/title/scores must not reach remote- // readers through the expertise rankings (same read-leak class as the- // delta page arm / find_orphans / get_recent_salience).- return dropPrivateOnlyRows(ctx.engine, ctx.remote, experts, e => e.slug, scope);+ return experts;},// hidden: 'whoknows' is in CLI_ONLY (src/cli.ts) — runWhoknows owns the CLI// surface (ranked table + per-factor explain + thin-client routing) and was@@ -202,6 +194,11 @@ const find_contradictions: Operation = {},},handler: async (ctx, p) => {+ const scope = sourceScopeOpts(ctx);+ if (ctx.remote !== false || scope.sourceId !== undefined || scope.sourceIds !== undefined) {+ return { contradictions: [], note: 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.' };+ }+const limit = typeof p.limit === 'number' && p.limit > 0 ? Math.min(p.limit, 100) : 20;const slugFilter = typeof p.slug === 'string' ? p.slug.toLowerCase() : null;const sevFilter = (p.severity === 'low' || p.severity === 'medium' || p.severity === 'high')@@ -226,11 +223,8 @@ const find_contradictions: Operation = {}>;}> | undefined) ?? [];const allFindings = perQuery.flatMap((q) => q.contradictions);- // Cheap in-memory filters (severity/slug) run FIRST, so the scoped- // existence probes below only pay for findings that could actually be- // returned. Pre-fix, every finding in the report paid a sequential- // scoped getPage probe BEFORE the filters/slice — the deprecated- // getPage-per-row N+1 class.+ // This branch is trusted and unscoped. Apply the requested display+ // filters before the limit; source-scoped reports are unavailable above.const matching = allFindings.filter((f) => {if (sevFilter && f.severity !== sevFilter) return false;if (slugFilter) {@@ -240,74 +234,13 @@ const find_contradictions: Operation = {}return true;});- // Source isolation (fail-closed): the probe report is brain-wide, so a- // scoped caller sees a finding only when BOTH endpoints resolve inside- // their source scope. Existence is checked with a SCOPED getPage- // (per-call slug cache), early-exiting once `limit` findings are kept.- // An unscoped trusted local caller ({} scope) keeps the brain-wide view.- // KNOWN CAVEAT (slug collision): the scope check is slug-EXISTENCE within- // scope — findings carry no source attribution, so a finding about- // source B's page stays visible to a source-A caller whenever source A- // holds a page with the SAME slug. Recording source_id on the probe side- // is the follow-up that closes this.- const scope = sourceScopeOpts(ctx);- const scoped = scope.sourceId !== undefined || scope.sourceIds !== undefined;- // #4352 posture, same keep-list idiom as get_recent_salience- // (ops/salience.ts): a `visibility: private` endpoint must not leak to a- // remote caller through the contradictions surface. Fail-closed: a- // finding survives only when BOTH endpoint slugs have a world-visible- // page row inside the caller's scope. Trusted local + the operator- // opt-outs resolve to "expose" inside resolveExcludePrivatePages.- const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);- let kept: typeof allFindings;- if (!scoped && !excludePrivate) {- kept = matching.slice(0, limit);- } else {- // Both fences run BEFORE a finding counts toward `limit` — filtering- // after the cutoff would silently under-fill the response (findings- // past the break point were never examined) while total_in_run claims- // completeness. Batched so the world-visibility keep-list probe stays- // one query per batch rather than per finding.- const cache = new Map<string, boolean>();- const inScope = async (slug: string): Promise<boolean> => {- const hit = cache.get(slug);- if (hit !== undefined) return hit;- const ok = (await ctx.engine.getPage(slug, scope)) !== null;- cache.set(slug, ok);- return ok;- };- kept = [];- const BATCH = 25;- for (let i = 0; i < matching.length && kept.length < limit; i += BATCH) {- const batch = matching.slice(i, i + BATCH);- const scopeOk: typeof allFindings = [];- for (const f of batch) {- if (kept.length + scopeOk.length >= limit + BATCH) break;- if (!scoped || ((await inScope(f.a.slug)) && (await inScope(f.b.slug)))) scopeOk.push(f);- }- let visibleOk = scopeOk;- if (excludePrivate && scopeOk.length > 0) {- const endpointSlugs = [...new Set(scopeOk.flatMap((f) => [f.a.slug, f.b.slug]))];- const worldVisible = await findWorldVisibleSlugs(ctx.engine, endpointSlugs, scope);- visibleOk = scopeOk.filter((f) => worldVisible.has(f.a.slug) && worldVisible.has(f.b.slug));- }- for (const f of visibleOk) {- if (kept.length >= limit) break;- kept.push(f);- }- }- }+ const kept = matching.slice(0, limit);return {run_id: latest.run_id,ran_at: latest.ran_at,contradictions: kept,- // Trusted local unscoped callers keep the exact pre-fix semantics- // (every finding in the run). Scoped/remote callers get the count of- // findings actually verified visible to them — the full scoped count- // would require paying the per-slug probe for every finding (the N+1- // this handler no longer does), and a larger-than-returned count is a- // hidden-finding oracle for privacy-filtered callers.- total_in_run: scoped || ctx.remote !== false ? kept.length : allFindings.length,+ // Trusted unscoped callers retain the complete local run count.+ total_in_run: allFindings.length,};},cliHints: { name: 'find-contradictions' },diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 699dde4ffa..2fddb6eeb5 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -11,6 +11,7 @@ import { OperationError, type Operation } from './contract.ts';import {enforceClientSlugFence,linkReadScopeOpts,+ readPolicyOpts,reclassifyMutationTimePageMiss,requireWritablePage,sourceScopeOpts,@@ -19,9 +20,6 @@ import { PageMissingError } from '../engine-errors.ts';import { TRAVERSE_PATH_ROW_CAP } from '../engine-constants.ts';// #4224: flag-gated cross-source identity union for the link read ops.import { unionLinksAcrossIdentity } from '../entity-identity.ts';-import { findPrivateOnlySlugs, resolveExcludePrivatePages } from '../search/private-visibility.ts';-import type { BrainEngine } from '../engine.ts';-import type { Link } from '../types.ts';// #4655: write-time pack vocabulary enforcement for explicit link verbs.import {loadActivePackForWriteVocabulary,@@ -30,34 +28,6 @@ import {undeclaredLinkTypeSuggestion,} from '../schema-pack/write-vocabulary.ts';-/**- * #4352 remediation shared by get_links / get_backlinks: when the caller is- * untrusted, a `visibility: private` queried page reads exactly like a- * missing one ([]), and edges touching a private endpoint (from / to /- * frontmatter origin) are dropped so the link surface can't enumerate- * private slugs. One probe covers the queried slug + every endpoint; the- * probe considers deleted rows too (fail-closed). Trusted local + the- * operator opt-outs short-circuit before any query.- */-async function dropPrivateLinkEndpoints(- engine: BrainEngine,- remote: boolean | undefined,- slug: string,- links: Link[],- scope: { sourceId?: string; sourceIds?: string[] },-): Promise<Link[]> {- if (!(await resolveExcludePrivatePages(engine, remote))) return links;- const endpointSlugs = [...new Set([- slug,- ...links.flatMap(l => [l.from_slug, l.to_slug, ...(l.origin_slug ? [l.origin_slug] : [])]),- ])];- const hidden = await findPrivateOnlySlugs(engine, endpointSlugs, scope, { includeDeleted: true });- if (hidden.has(slug)) return [];- return links.filter(- l => !hidden.has(l.from_slug) && !hidden.has(l.to_slug) && !(l.origin_slug && hidden.has(l.origin_slug)),- );-}-// --- Links ---/**@@ -185,7 +155,7 @@ const get_links: Operation = {// #2200: linkReadScopeOpts so a federated grant — and an untrusted remote// scalar scope (promoted to sourceIds[]) — reaches the engine's all-endpoint// branch. Trusted local/internal callers keep the scalar cross-source view.- const sourceOpts = linkReadScopeOpts(ctx);+ const sourceOpts = await readPolicyOpts(ctx, linkReadScopeOpts(ctx));const links = await ctx.engine.getLinks(p.slug as string, sourceOpts);// #4224: flag-gated identity union — merge edges from the page's identity// co-members (entity_identity.union config, default off; pure no-op then).@@ -194,10 +164,11 @@ const get_links: Operation = {const unioned = await unionLinksAcrossIdentity(ctx.engine, p.slug as string, links, 'out', {sourceId: sourceOpts.sourceId,allowedSources: sourceOpts.sourceIds,+ excludePrivate: sourceOpts.excludePrivate,});- // #4352: private filtering runs AFTER the identity union so co-member- // edges the union adds are subject to the same visibility gate.- return dropPrivateLinkEndpoints(ctx.engine, ctx.remote, p.slug as string, unioned, sourceOpts);+ // The engine authorizes the base and every member read before merging;+ // each union contributor must preserve this policy because no final filter runs.+ return unioned;},scope: 'read',};@@ -211,15 +182,16 @@ const get_backlinks: Operation = {handler: async (ctx, p) => {// #2200: linkReadScopeOpts — federated grant + untrusted remote scalar// (promoted to sourceIds[]) reach the engine's all-endpoint branch.- const sourceOpts = linkReadScopeOpts(ctx);+ const sourceOpts = await readPolicyOpts(ctx, linkReadScopeOpts(ctx));const links = await ctx.engine.getBacklinks(p.slug as string, sourceOpts);// #4224: flag-gated identity union (see get_links).const unioned = await unionLinksAcrossIdentity(ctx.engine, p.slug as string, links, 'in', {sourceId: sourceOpts.sourceId,allowedSources: sourceOpts.sourceIds,+ excludePrivate: sourceOpts.excludePrivate,});- // #4352: private filtering after the union (see get_links).- return dropPrivateLinkEndpoints(ctx.engine, ctx.remote, p.slug as string, unioned, sourceOpts);+ // Base and member reads enforce the policy before merging (see get_links).+ return unioned;},scope: 'read',cliHints: { name: 'backlinks', positional: ['slug'] },@@ -297,34 +269,13 @@ const traverse_graph: Operation = {// walks stay within the auth'd client's accessible sources. Pre-fix,// traverseGraph / traversePaths happily followed edges into pages from// foreign sources, leaking topology + page metadata via the graph op.- const scope = sourceScopeOpts(ctx);- // #4352 remediation: graph output must not enumerate private slugs to an- // untrusted caller. A private START page reads exactly like a missing one- // ([]); private nodes/edges elsewhere in the walk are stripped post-hoc- // (op-level gate, same as get_page — the engine CTE stays shared).- const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);- if (excludePrivate) {- const startHidden = await findPrivateOnlySlugs(ctx.engine, [slug], scope, { includeDeleted: true });- if (startHidden.has(slug)) return [];- }+ const scope = await readPolicyOpts(ctx);// Backward compat: trusted local no-filter callers keep the legacy// GraphNode[] shape used by `gbrain graph`. Remote MCP callers need the// natural no-filter invocation to surface inbound-only typed edges too,// so they default to direction=both and get explicit GraphPath[] edges.if (linkType === undefined && requestedDirection === undefined && ctx.remote === false) {- const nodes = await ctx.engine.traverseGraph(slug, depth, scope);- if (!excludePrivate) return nodes;- const hidden = await findPrivateOnlySlugs(- ctx.engine,- [...new Set(nodes.flatMap(n => [n.slug, ...n.links.map(l => l.to_slug)]))],- scope,- { includeDeleted: true },- );- return nodes- .filter(n => !hidden.has(n.slug))- .map(n => (n.links.some(l => hidden.has(l.to_slug))- ? { ...n, links: n.links.filter(l => !hidden.has(l.to_slug)) }- : n));+ return ctx.engine.traverseGraph(slug, depth, scope);}const { paths, truncated } = await ctx.engine.traversePathsDetailed(slug, { depth, linkType, direction, ...scope });// Row cap hit: the walk's deepest edges were dropped. stderr-only so the@@ -335,14 +286,7 @@ const traverse_graph: Operation = {`Lower depth or narrow with link_type/direction for a complete walk.`,);}- if (!excludePrivate) return paths;- const hidden = await findPrivateOnlySlugs(- ctx.engine,- [...new Set(paths.flatMap(e => [e.from_slug, e.to_slug]))],- scope,- { includeDeleted: true },- );- return paths.filter(e => !hidden.has(e.from_slug) && !hidden.has(e.to_slug));+ return paths;},scope: 'read',cliHints: { name: 'graph', positional: ['slug'] },diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.tsindex 2efc7d74d1..e6a40924f2 100644--- a/src/core/ops/orphans.ts+++ b/src/core/ops/orphans.ts@@ -6,8 +6,7 @@*/import type { Operation } from './contract.ts';-import { sourceScopeOpts } from './context.ts';-import { dropPrivateOnlyRows } from '../search/private-visibility.ts';+import { readPolicyOpts } from './context.ts';// --- Orphans ---@@ -39,32 +38,13 @@ const find_orphans: Operation = {// source-bound OAuth client's scope — a read leak in the v0.34.1// source-isolation class. Local CLI callers route through `gbrain// orphans --source` instead (ctx.remote === false → empty scope here).- const scope = sourceScopeOpts(ctx);+ const scope = await readPolicyOpts(ctx);const result = await findOrphans(ctx.engine, {includePseudo: (p.include_pseudo as boolean) || false,...(mode ? { mode } : {}),...scope,});- // An orphaned `visibility: private` page's slug + title must not reach- // remote readers (same read-leak class as the delta page arm; same- // helper family as the get_page/resolve_slugs gates). Hidden orphans- // VANISH from every published counter — total_pages and total_linkable- // shrink with them and `excluded` is left alone. Folding them into- // `excluded` instead would relocate the count, not hide it: with- // include_pseudo:true the unfiltered op guarantees excluded === 0, so a- // non-zero value would be an exact one-call private-orphan-count oracle.- // Subtracting from both denominators keeps doctor-remote's- // total_orphans/total_linkable ratio and the excluded ===- // total_pages - total_linkable invariant coherent over the- // world-visible universe.- const kept = await dropPrivateOnlyRows(ctx.engine, ctx.remote, result.orphans, o => o.slug, scope);- const hiddenCount = result.orphans.length - kept.length;- if (hiddenCount > 0) {- result.orphans = kept;- result.total_orphans = kept.length;- result.total_pages -= hiddenCount;- result.total_linkable -= hiddenCount;- }+return result;},cliHints: { name: 'orphans', hidden: true },diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 37867d8d1a..f5d2a5288e 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -17,9 +17,8 @@ import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBas// #3190: pack-aware link typing on the put_page auto-link path.import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';import { isFactsBackstopEligible } from '../facts/eligibility.ts';-import { stripTakesFence } from '../takes-fence.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';import type { WriterLintPayload } from '../output/post-write.ts';-import { stripFactsFence } from '../facts-fence.ts';import { getContentFlag } from '../quarantine.ts';import { bumpLastRetrievedAt } from '../last-retrieved.ts';import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';@@ -96,17 +95,7 @@ async function dropPrivateSlugs(* entirely, facts fence keeps only `world`-visibility rows.*/function stripPrivacyFencesForRemoteReader(page: Page): Page {- return {- ...page,- compiled_truth: stripFactsFence(- stripTakesFence(page.compiled_truth),- { keepVisibility: ['world'] },- ),- timeline: stripFactsFence(- stripTakesFence(page.timeline ?? ''),- { keepVisibility: ['world'] },- ),- };+ return { ...page, compiled_truth: sanitizeRemoteBody(page.compiled_truth), timeline: sanitizeRemoteBody(page.timeline ?? '') };}const get_page: Operation = {@@ -146,7 +135,7 @@ const get_page: Operation = {// oracle), composing with — not replacing — the source-grant scope above.const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);- let page = await ctx.engine.getPage(slug, { includeDeleted, ...sourceOpts });+ let page = await ctx.engine.getPage(slug, { includeDeleted, excludePrivate, ...sourceOpts });if (page && excludePrivate && isPrivatePage(page.frontmatter)) page = null;let resolved_slug: string | undefined;@@ -176,9 +165,9 @@ const get_page: Operation = {: sourceOpts.sourceId !== undefined? sourceOpts.sourceId: (await ctx.engine.listAllSources({ includeArchived: includeDeleted })).map(s => s.id);- const hit = await ctx.engine.resolveSlugWithAliasDetailed(slug, aliasScope);+ const hit = await ctx.engine.resolveSlugWithAliasDetailed(slug, aliasScope, { excludePrivate });if (hit) {- const aliasPage = await ctx.engine.getPage(hit.canonical_slug, { includeDeleted, sourceId: hit.source_id });+ const aliasPage = await ctx.engine.getPage(hit.canonical_slug, { includeDeleted, excludePrivate, sourceId: hit.source_id });if (aliasPage && !(excludePrivate && isPrivatePage(aliasPage.frontmatter))) {page = aliasPage;resolved_slug = hit.canonical_slug;@@ -187,13 +176,13 @@ const get_page: Operation = {}if (!page && fuzzy) {- let candidates = await ctx.engine.resolveSlugs(slug, fuzzyScope);+ let candidates = await ctx.engine.resolveSlugs(slug, { ...fuzzyScope, excludePrivate });// #4352: the ambiguous_slug candidate list must not enumerate private slugs.if (excludePrivate && candidates.length > 0) {candidates = await dropPrivateSlugs(ctx.engine, candidates, fuzzyScope, includeDeleted);}if (candidates.length === 1) {- const fuzzyPage = await ctx.engine.getPage(candidates[0], { includeDeleted, ...sourceOpts });+ const fuzzyPage = await ctx.engine.getPage(candidates[0], { includeDeleted, excludePrivate, ...sourceOpts });// Multi-source backstop: the slug may still resolve to a private// variant (same slug private in one source, world in another —// getPage returns the first in-scope match).@@ -241,30 +230,9 @@ const get_page: Operation = {// non-default page. We already hold the resolved page, so its source is// unambiguous.const tags = await ctx.engine.getTags(page.slug, { sourceId: page.source_id });- // Privacy boundary for the per-token allow-list (v0.28.6 for takes,- // v0.32.2 for facts).- //- // takes_list / takes_search / think.gather filter rows by holder at- // the SQL layer, but takes AND facts are also rendered as markdown- // tables inside the page body between fence markers. A read-only- // remote MCP caller could otherwise call `get_page <slug>` and- // recover every fence row verbatim.- //- // v0.32.2 (Codex R2-#5): the strip trigger is now `ctx.remote === true`- // rather than the takes-holders-allow-list flag (which subagent paths- // didn't set, leaving a pre-existing privacy hole). Subagent + remote- // MCP + scope-restricted-token callers all get the strip; local CLI- // (`ctx.remote === false`) sees the full fence. Closes the- // pre-existing takes hole as a bonus.- //- // Both fences are stripped:- // - stripTakesFence: drops the entire takes table for untrusted- // readers (per-token holder allow-list is the row-level surface- // for trusted callers).- // - stripFactsFence({keepVisibility: ['world']}): keeps world rows,- // drops private. World facts are public knowledge by definition;- // untrusted readers see them. Private facts never cross the boundary.- const isUntrustedReader = ctx.remote === true;+ // Only explicitly trusted local reads retain protected body sections.+ // Holder grants and page-visibility opt-outs do not bypass this boundary.+ const isUntrustedReader = ctx.remote !== false;const visibleBody = isUntrustedReader? stripPrivacyFencesForRemoteReader(page): page;diff --git a/src/core/ops/raw-data.ts b/src/core/ops/raw-data.tsindex ec3c1520b1..ac32f0e19e 100644--- a/src/core/ops/raw-data.ts+++ b/src/core/ops/raw-data.ts@@ -6,8 +6,8 @@*/import type { Operation } from './contract.ts';-import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';-import { slugHiddenFromCaller } from '../search/private-visibility.ts';+import { readPolicyOpts } from './context.ts';+import { enforceClientSlugFence } from './context.ts';// --- Raw Data ---@@ -39,11 +39,10 @@ const get_raw_data: Operation = {source: { type: 'string', description: 'Filter by source' },},handler: async (ctx, p) => {- const scope = sourceScopeOpts(ctx);+ const scope = await readPolicyOpts(ctx);// #4352 remediation: a `visibility: private` page's raw data reads// exactly like a missing page's ([]) for untrusted callers — no// existence oracle.- if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];return ctx.engine.getRawData(p.slug as string, p.source as string | undefined, scope);},scope: 'read',diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.tsindex e8fc2206fb..cf6cd35e51 100644--- a/src/core/ops/salience.ts+++ b/src/core/ops/salience.ts@@ -9,16 +9,11 @@*/import type { Operation } from './contract.ts';-import { sourceScopeOpts } from './context.ts';+import { readPolicyOpts } from './context.ts';import {GET_RECENT_SALIENCE_DESCRIPTION,FIND_ANOMALIES_DESCRIPTION,} from '../operations-descriptions.ts';-import {- dropPrivateOnlyRows,- findWorldVisibleSlugs,- resolveExcludePrivatePages,-} from '../search/private-visibility.ts';// --- v0.29: Salience + Anomaly Detection ---@@ -61,14 +56,9 @@ const get_recent_salience: Operation = {limit: typeof p.limit === 'number' ? p.limit : undefined,slugPrefix: typeof p.slugPrefix === 'string' ? p.slugPrefix : undefined,recency_bias: recencyBias,- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),});- // A `visibility: private` page's slug/title/metadata must not reach- // remote readers through the salience list (same read-leak class as the- // delta page arm). The salience read is source-scoped above; the private- // probe deliberately keeps the EMPTY scope — a broader privacy check can- // only remove more rows (fail-closed), never leak, so don't narrow it.- return dropPrivateOnlyRows(ctx.engine, ctx.remote, rows, r => r.slug, {});+ return rows;},// hidden: 'salience' is in CLI_ONLY (src/cli.ts) — runSalience owns the CLI// surface; the non-hidden hint was dead (CLI_ONLY wins at dispatch).@@ -103,64 +93,9 @@ const find_anomalies: Operation = {since: typeof p.since === 'string' ? p.since : undefined,lookback_days: typeof p.lookback_days === 'number' ? p.lookback_days : undefined,sigma: typeof p.sigma === 'number' ? p.sigma : undefined,- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),});- // AnomalyResult.page_slugs can name `visibility: private` pages — a- // private slug is still page metadata a remote reader must not see.- // Leak shapes closed together for remote callers: the slug list is- // filtered; rows whose visible slugs empty out are dropped (an- // empty-but-present row is a hidden-activity oracle, and its- // cohort_value can be a tag name sourced only from private pages);- // `count` is adjusted by the slugs actually removed — NEVER recomputed- // from the list, which is display-capped at 50 (cycle/anomaly.ts) and- // would clamp big cohorts; `sigma_observed` is recomputed from the- // adjusted count with the engine's own formula so the stats stay- // mutually consistent and the pre-filter count is not reconstructible- // from mean + sigma*stddev; and a row that no longer clears the- // caller's threshold on its VISIBLE pages is dropped (a sub-threshold- // survivor is itself a hidden-activity tell). Residuals, accepted and- // documented: for >50-page cohorts, private slugs beyond the display- // cap are invisible to the adjustment (bounded imprecision, not an- // exact oracle), and the flip side — a >50 cohort whose visible sample- // is ALL private is dropped wholly even if uncapped world pages drove- // it (fails closed toward confidentiality); baseline_mean/stddev remain- // private-inclusive (world-only cohort aggregation is the deferred- // row-grain TODO — the source-scope half is now discharged: both the- // baseline and today windows are source-scoped in the engine via- // sourceScopeOpts above).- // includeDeleted: the anomaly queries have no deleted_at predicate, so- // a soft-deleted private page must still count as private-only.- if (await resolveExcludePrivatePages(ctx.engine, ctx.remote)) {- const all = [...new Set(anomalies.flatMap(a => a.page_slugs))];- // Keep-list probe (fail-closed): a slug hard-purged between the- // engine read and this probe has no page row and simply isn't kept,- // instead of being served because "no row" looked like "not private".- const keep = await findWorldVisibleSlugs(ctx.engine, all, {});- if (keep.size < all.length) {- const sigmaThreshold = typeof p.sigma === 'number' ? p.sigma : 3.0;- const filtered = anomalies.flatMap(a => {- const kept = a.page_slugs.filter(s => keep.has(s));- const removed = a.page_slugs.length - kept.length;- if (removed === 0) return [a]; // untouched rows pass through verbatim- if (kept.length === 0) return [];- const count = a.count - removed;- const sigma_observed =- a.baseline_stddev > 0- ? (count - a.baseline_mean) / a.baseline_stddev- : count - a.baseline_mean;- const stillAnomalous =- a.baseline_stddev > 0- ? count > a.baseline_mean + sigmaThreshold * a.baseline_stddev- : count > a.baseline_mean + 1;- if (!stillAnomalous) return [];- return [{ ...a, page_slugs: kept, count, sigma_observed }];- });- // Re-sort by the PUBLISHED sigma (engine sorts by pre-filter sigma,- // cycle/anomaly.ts) — otherwise an out-of-order pair is an- // ordering-channel tell that a row was privately adjusted.- return filtered.sort((x, y) => y.sigma_observed - x.sigma_observed);- }- }+return anomalies;},// hidden: 'anomalies' is in CLI_ONLY (src/cli.ts) — runAnomalies owns thediff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex a8ebe41ca3..4107f6caba 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -1,3 +1,4 @@+import { readHolders } from './context.ts';/*** Search operation cluster (search + query) — pure move from operations.ts* (v0.46.x tranche 1). search_by_image stays in operations.ts (v0.36 Phase 2@@ -220,7 +221,7 @@ const search: Operation = {const keywordOnly = (await ctx.engine.getConfig('search.mcp_keyword_only')) === 'true';if (keywordOnly) {- const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, ...(types ? { types } : {}), ...scope });+ const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, excludePrivate, requireSafeChunks: ctx.remote !== false, ...(types ? { types } : {}), ...scope });const results = dedupResults(raw);// #3783 — every row here IS a keyword hit (direct FTS path); mark// before stamping so evidence still reads keyword_exact.@@ -230,11 +231,11 @@ const search: Operation = {// #1699: the keyword-only opt-out must STILL surface the content_flag// agent-warning channel (hybridSearch stamps it; this branch bypasses// hybridSearch, so stamp explicitly). Fail-open inside the helper.- await stampContentFlags(ctx.engine, results);+ await stampContentFlags(ctx.engine, results, { ...scope, excludePrivate });// #160: same for the unverified auto-extracted stub marker (no boost// to cancel on this path — keyword-only never applies the compiled-// truth boost — but the provenance marker must still surface).- await stampUnverifiedExtractions(ctx.engine, results);+ 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', buildRetrievalResponseMeta(queryText, results, null, { conceptHint: true }));@@ -250,6 +251,8 @@ const search: Operation = {offset,expansion: false,excludePrivate,+ requireSafeChunks: ctx.remote !== false,+ takesHoldersAllowList: readHolders(ctx),...(types ? { types } : {}),...scope,...(perCallMode ? { mode: perCallMode } : {}),@@ -440,6 +443,8 @@ const query: Operation = {offset: (p.offset as number) || 0,embeddingColumn: 'embedding_image',excludePrivate,+ requireSafeChunks: ctx.remote !== false,+ takesHoldersAllowList: readHolders(ctx),...(types ? { types } : {}),...querySourceScope,});@@ -467,8 +472,8 @@ const query: Operation = {// cross-source mode (matches SearchOpts.sourceId contract).let capturedMeta: HybridSearchMeta | null = null;// v0.32.x search-lite: route the query op through hybridSearchCached so- // semantic cache + token budget + intent weighting fire automatically.- // Plain hybridSearch remains the bare API for callers that opt out.+ // token budget and intent weighting apply at the operation boundary.+ // Semantic cache reuse is suspended in the wrapper.// (#1663: `let` — the CRAG gate below may swap in an escalated run.)let results = await hybridSearchCached(ctx.engine, queryText, {// #4356 — was a hard `|| 20`, independent of the mode-resolution@@ -482,6 +487,8 @@ const query: Operation = {limit: (p.limit as number) || undefined,offset: (p.offset as number) || 0,excludePrivate,+ requireSafeChunks: ctx.remote !== false,+ takesHoldersAllowList: readHolders(ctx),expansion: expand,expandFn: expand ? expandQuery : undefined,// T4/D5 — per-call mode (local/trusted only; remote ignored).@@ -513,9 +520,8 @@ const query: Operation = {// (master's #1182 cleanup of the duplicate sourceScopeOpts spread).embeddingColumn: embeddingColumnParam,// v0.41.33 — agent-explicit adaptive return-sizing. Omitted = off- // (config default applies). 2026-08 wave (E5b): adaptive-on calls now- // CACHE — the gate params + resolved intent class key the semantic- // cache via the KNOBS_HASH v=27 fold (the old skip-when-on is gone).+ // (config default applies). The wrapper still applies adaptive sizing+ // while semantic cache reuse is suspended.adaptiveReturn: typeof p.adaptive_return === 'boolean' ? (p.adaptive_return as boolean) : undefined,// v0.42.3.0 — autocut ceiling override. Omitted = smart default (ON in// reranked modes). `false` forces the full top-K.@@ -564,6 +570,9 @@ const query: Operation = {const effectiveLimit = await resolveEffectiveLimit(ctx, p);let escalatedMeta: HybridSearchMeta | null = null;const escalated = await hybridSearchCached(ctx.engine, queryText, {+ excludePrivate,+ requireSafeChunks: ctx.remote !== false,+ takesHoldersAllowList: readHolders(ctx),limit: Math.max(effectiveLimit, 50),offset: (p.offset as number) || 0,expansion: true,@@ -794,13 +803,13 @@ const cache_stats: Operation = {handler: async (ctx) => {const { withRelationGuard } = await import('./contract.ts');return withRelationGuard(async () => {- const { SemanticQueryCache, loadCacheConfig } = await import('../search/query-cache.ts');+ const { SemanticQueryCache, loadCacheConfig, semanticResultCacheAvailable } = await import('../search/query-cache.ts');const config = await loadCacheConfig(ctx.engine);const cache = new SemanticQueryCache(ctx.engine, config);const stats = await cache.stats();return {schema_version: 1,- enabled: config.enabled ?? true,+ enabled: semanticResultCacheAvailable() && (config.enabled ?? true),similarity_threshold: config.similarityThreshold,ttl_seconds: config.ttlSeconds,...stats,diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex 054b9645d5..744c3f5727 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -7,7 +7,8 @@import { OperationError, type Operation, type OperationContext } from './contract.ts';import {- sourceScopeOpts,+ readPolicyOpts,+ readHolders,thinkSourceScopeOpts,enforceClientSlugFence,validatePageSlug,@@ -21,6 +22,7 @@ import {TakesWriteError,} from '../takes-write.ts';import { embedQuery } from '../embedding.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';// --- v0.28: Takes ---@@ -41,7 +43,7 @@ const takes_list: Operation = {handler: async (ctx, p) => {return ctx.engine.listTakes({// #2200-class: honor federated/source scope (via the take's page.source_id).- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),page_slug: p.page_slug as string | undefined,holder: p.holder as string | undefined,kind: p.kind as never,@@ -52,7 +54,7 @@ const takes_list: Operation = {offset: p.offset as number | undefined,// Per-token allow-list — server-side filter for MCP-bound calls.// Local CLI callers leave takesHoldersAllowList unset and see all holders.- takesHoldersAllowList: ctx.takesHoldersAllowList,+ takesHoldersAllowList: readHolders(ctx),});},cliHints: { name: 'takes-list' },@@ -68,9 +70,9 @@ const takes_search: Operation = {},handler: async (ctx, p) => {return ctx.engine.searchTakes(p.query as string, {- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),limit: p.limit as number | undefined,- takesHoldersAllowList: ctx.takesHoldersAllowList,+ takesHoldersAllowList: readHolders(ctx),});},cliHints: { name: 'takes-search', positional: ['query'] },@@ -97,13 +99,13 @@ const takes_scorecard: Operation = {handler: async (ctx, p) => {const card = await ctx.engine.getScorecard({- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),holder: p.holder as string | undefined,domainPrefix: p.domain_prefix as string | undefined,since: p.since as string | undefined,until: p.until as string | undefined,},- ctx.takesHoldersAllowList,+ readHolders(ctx),);// [OV8/EV5] Resolver-provenance visibility: remote resolutions are// server-stamped resolved_by='mcp:<client>' (takes_resolve below), and@@ -134,11 +136,11 @@ const takes_calibration: Operation = {// a breaking change; the scorecard is the segregation surface.)return ctx.engine.getCalibrationCurve({- ...sourceScopeOpts(ctx),+ ...await readPolicyOpts(ctx),holder: p.holder as string | undefined,bucketSize: p.bucket_size as number | undefined,},- ctx.takesHoldersAllowList,+ readHolders(ctx),);},cliHints: { name: 'takes-calibration' },@@ -151,8 +153,9 @@ const takes_calibration: Operation = {* signal, not a scorecard dimension).*/async function countMcpResolved(ctx: OperationContext): Promise<number> {- const scope = sourceScopeOpts(ctx);+ const scope = await readPolicyOpts(ctx);const where: string[] = [`t.resolved_at IS NOT NULL`, `t.resolved_by LIKE 'mcp:%'`];+ if (scope.excludePrivate) where.push(privatePagesFilterFragment('p'));const params: unknown[] = [];if (scope.sourceIds && scope.sourceIds.length > 0) {params.push(scope.sourceIds);@@ -161,8 +164,9 @@ async function countMcpResolved(ctx: OperationContext): Promise<number> {params.push(scope.sourceId);where.push(`p.source_id = $${params.length}`);}- if (ctx.takesHoldersAllowList) {- params.push(ctx.takesHoldersAllowList);+ const holders = readHolders(ctx);+ if (holders !== undefined) {+ params.push(holders);where.push(`t.holder = ANY($${params.length}::text[])`);}try {@@ -222,8 +226,9 @@ const think: Operation = {modelExplicit: !!p.model,since: p.since ? String(p.since) : undefined,until: p.until ? String(p.until) : undefined,- takesHoldersAllowList: ctx.takesHoldersAllowList,+ takesHoldersAllowList: readHolders(ctx),...thinkScope,+ excludePrivate: (await readPolicyOpts(ctx)).excludePrivate,remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)});diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.tsindex 2284bb132d..0ac4f73374 100644--- a/src/core/ops/timeline.ts+++ b/src/core/ops/timeline.ts@@ -7,15 +7,14 @@*/import type { Operation } from './contract.ts';+import { readPolicyOpts } from './context.ts';import {enforceSubagentSlugFence,enforceClientSlugFence,reclassifyMutationTimePageMiss,requireWritablePage,- sourceScopeOpts,} from './context.ts';import { PageMissingError } from '../engine-errors.ts';-import { slugHiddenFromCaller } from '../search/private-visibility.ts';import { writeTimelineEntryThrough } from '../timeline-write-through.ts';// --- Timeline ---@@ -155,11 +154,10 @@ const get_timeline: Operation = {handler: async (ctx, p) => {// #2200: route through sourceScopeOpts so a federated grant reaches the// engine via TimelineOpts.sourceIds; scalar/unset unchanged.- const scope = sourceScopeOpts(ctx);+ const scope = await readPolicyOpts(ctx);// #4352 remediation: a `visibility: private` page's timeline reads// exactly like a missing page's ([]) for untrusted callers — no// existence oracle.- if (await slugHiddenFromCaller(ctx.engine, ctx.remote, p.slug as string, scope)) return [];const after = typeof p.after === 'string' ? p.after : typeof p.since === 'string' ? p.since : undefined;const before = typeof p.before === 'string' ? p.before : typeof p.until === 'string' ? p.until : undefined;const limit = typeof p.limit === 'number' ? p.limit : undefined;diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 90bb45c276..494e587080 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1,3 +1,6 @@+import type { PageReadScope } from './types.ts';+import type { PageReadPolicy } from './types.ts';+import { readRelationalFanout, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';import { PGlite } from '@electric-sql/pglite';import type { Transaction } from '@electric-sql/pglite';// Engine-live path: static top-level imports (scratch probe, #2674) — the@@ -60,7 +63,7 @@ import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaimport { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';import { PageMissingError } from './engine-errors.ts';import { SOURCE_CONFIG_OBJECT_SQL } from './source-config-sql.ts';-import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';+import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';import { acquireLock, releaseLock, type LockHandle } from './pglite-lock.ts';// Engine-live path (#3596): static import, never a lazy `import()` in the// connect() catch. No cycle: pglite-repair.ts imports nothing from this file.@@ -94,7 +97,7 @@ import { PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';import { finalizeLastSeen } from './chronicle/last-seen.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';-import { privatePagesFilterFragment } from './search/private-visibility.ts';+import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment } from './search/private-visibility.ts';import { unverifiedExtractionFragment } from './extraction-review.ts';import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';@@ -693,6 +696,8 @@ export async function probePgliteScratchStore(}export class PGLiteEngine implements BrainEngine {+ /** Transaction clones keep chunk invalidation and replacement atomic. */+ private _chunkWritesInTransaction = false;readonly kind = 'pglite' as const;private _db: PGLiteDB | null = null;private _lock: LockHandle | null = null;@@ -1653,18 +1658,20 @@ export class PGLiteEngine implements BrainEngine {async transaction<T>(fn: (engine: BrainEngine) => Promise<T>): Promise<T> {return this.db.transaction(async (tx) => {const txEngine = Object.create(this) as PGLiteEngine;+ Object.defineProperty(txEngine, '_chunkWritesInTransaction', { value: true });Object.defineProperty(txEngine, 'db', { get: () => tx });return fn(txEngine);});}// Pages CRUD- async getPage(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeDeleted?: boolean }): Promise<Page | null> {+ async getPage(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeDeleted?: boolean; excludePrivate?: boolean }): Promise<Page | null> {// v0.26.5: hide soft-deleted by default; opt-in via opts.includeDeleted.const includeDeleted = opts?.includeDeleted === true;const sourceId = opts?.sourceId;const sourceIds = opts?.sourceIds;const where: string[] = ['slug = $1'];+ if (opts?.excludePrivate) where.push(privatePagesFilterFragment('pages'));const params: unknown[] = [slug];// #1393: federated grant (sourceIds[]) wins over scalar sourceId so the// exact-match read honors allowedSources, not just one source.@@ -1764,7 +1771,8 @@ export class PGLiteEngine implements BrainEngine {const effectiveDateSource = page.effective_date_source ?? null;const importFilename = page.import_filename ?? null;// v0.32.7 CJK wave: chunker_version + source_path columns.- const chunkerVersion = page.chunker_version ?? null;+ // Only an import transaction may seal a fully sanitized chunk replacement.+ const chunkerVersion = Math.min(page.chunker_version ?? 0, SAFE_FENCE_CHUNKER_VERSION - 1);const sourcePath = page.source_path ?? null;// v0.39.3.0 provenance write-through (WARN-8 + CV12). Mirrors postgres-engine.ts.// Server stamps `ingested_at = now()` ONLY when any provenance field is being@@ -1776,7 +1784,7 @@ export class PGLiteEngine implements BrainEngine {const ingestedAt = (sourceKind || sourceUri || ingestedVia) ? new Date().toISOString() : null;const { rows } = await this.db.query(`INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, now(), $10::timestamptz, $11, $12, COALESCE($13, ${MARKDOWN_CHUNKER_VERSION}), $14, $15, $16, $17, $18::timestamptz)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, now(), $10::timestamptz, $11, $12, $13, $14, $15, $16, $17, $18::timestamptz)ON CONFLICT (source_id, slug) DO UPDATE SETtype = EXCLUDED.type,page_kind = EXCLUDED.page_kind,@@ -1790,7 +1798,7 @@ export class PGLiteEngine implements BrainEngine {effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date),effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source),import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename),- chunker_version = COALESCE(EXCLUDED.chunker_version, pages.chunker_version),+ chunker_version = ${bodyWriteChunkVersion('EXCLUDED.compiled_truth', 'EXCLUDED.timeline')},source_path = COALESCE(EXCLUDED.source_path, pages.source_path),source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind),source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri),@@ -1969,6 +1977,7 @@ export class PGLiteEngine implements BrainEngine {SET compiled_truth = $1,timeline = $2,content_hash = $3,+ chunker_version = ${bodyWriteChunkVersion('$1', '$2')},updated_at = now()WHERE source_id = $4AND slug = $5@@ -2326,15 +2335,16 @@ export class PGLiteEngine implements BrainEngine {}));}- async resolveSlugs(partial: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<string[]> {+ async resolveSlugs(partial: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<string[]> {// v0.41.13 #1436: source scope. When opts.sourceIds is set// (federated_read OAuth tier), filter via `source_id = ANY($N::text[])`.// When opts.sourceId is set (scalar single-source tier), filter via// `source_id = $N`. When neither is set, preserve the pre-fix unscoped// behavior so internal CLI callers (`gbrain query --resolve` etc.)// continue to walk every source.- const sources = opts?.sourceIds ?? null;+ const sources = opts?.sourceIds?.length ? opts.sourceIds : null;const scalar = opts?.sourceId ?? null;+ const privacy = opts?.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '';const scopeSql = sources? ` AND source_id = ANY($${'__N__'}::text[])`: scalar@@ -2342,7 +2352,7 @@ export class PGLiteEngine implements BrainEngine {: '';// Try exact match first- const exactSql = `SELECT slug FROM pages WHERE slug = $1 AND deleted_at IS NULL${scopeSql.replace('__N__', '2')}`;+ const exactSql = `SELECT slug FROM pages WHERE slug = $1 AND deleted_at IS NULL${scopeSql.replace('__N__', '2')}${privacy}`;const exactParams: unknown[] = sources ? [partial, sources] : scalar ? [partial, scalar] : [partial];const exact = await this.db.query(exactSql, exactParams);if (exact.rows.length > 0) return [(exact.rows[0] as { slug: string }).slug];@@ -2350,7 +2360,7 @@ export class PGLiteEngine implements BrainEngine {// Fuzzy match via pg_trgmconst fuzzySql = `SELECT slug, similarity(title, $1) AS simFROM pages- WHERE deleted_at IS NULL AND (title % $1 OR slug ILIKE $2)${scopeSql.replace('__N__', '3')}+ WHERE deleted_at IS NULL AND (title % $1 OR slug ILIKE $2)${scopeSql.replace('__N__', '3')}${privacy}ORDER BY sim DESCLIMIT 5`;const fuzzyParams: unknown[] = sources@@ -2395,7 +2405,7 @@ export class PGLiteEngine implements BrainEngine {const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);// v0.26.5: visibility filter (soft-deleted + archived-source).- const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// v0.32.7: CJK query branch. PGLite uses websearch_to_tsquery('english')// which can't tokenize CJK; queries return empty. Switch to ILIKE on@@ -2535,10 +2545,11 @@ export class PGLiteEngine implements BrainEngine {const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();+ const titleVector = requiresSafeChunks(opts) ? `to_tsvector('${ftsLang}', COALESCE(p.title, ''))` : 'p.search_vector';const params: unknown[] = [boundWebsearchQuery(query), limit, offset];let extraFilter = '';@@ -2588,7 +2599,7 @@ export class PGLiteEngine implements BrainEngine {COALESCE(rep.chunk_index, 0) as chunk_index,COALESCE(rep.chunk_text, '') as chunk_text,COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source,- ts_rank_cd(p.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,+ ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,CASE WHEN p.updated_at < (SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id) THEN true ELSE false END AS stale@@ -2603,7 +2614,7 @@ export class PGLiteEngine implements BrainEngine {ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASCLIMIT 1) rep ON true- WHERE p.search_vector @@ websearch_to_tsquery('${ftsLang}', $1)+ WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)${extraFilter} ${hardExcludeClause} ${visibilityClause}ORDER BY score DESC, p.id ASCLIMIT $2 OFFSET $3`;@@ -2694,7 +2705,7 @@ export class PGLiteEngine implements BrainEngine {const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// v0.32.7: CJK branch (same as searchKeyword but without page-dedup).if (hasCJK(query)) {@@ -2853,7 +2864,7 @@ export class PGLiteEngine implements BrainEngine {// 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', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// v0.36 (D11): column routing via resolved descriptor. Engine doesn't// read config — caller resolved at hybrid/op boundary. The cast SQL@@ -3035,24 +3046,35 @@ export class PGLiteEngine implements BrainEngine {// Chunksasync upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void> {- return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal, () => this._upsertChunksOnce(slug, chunks, opts), chunks.length);+ if (this._chunkWritesInTransaction) return this._upsertChunksOnce(slug, chunks, opts);+ return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal,+ () => this.transaction(tx => (tx as PGLiteEngine)._upsertChunksOnce(slug, chunks, opts)), chunks.length);}private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn }): Promise<void> {// Normalize the same way putPage does — pages.slug is stored lowercased,// so a raw mixed-case slug here would miss the row it just wrote (#430).slug = validateSlug(slug);+ // Compare and persist the same canonical body bytes. JSONB rejects raw+ // NUL/lone surrogates before the INSERT can sanitize them; identity fields+ // remain untouched so malformed identifiers still reject the transaction.+ chunks = chunks.map(chunk => ({ ...chunk, chunk_text: sanitizeText(chunk.chunk_text) }));const sourceId = opts?.sourceId ?? 'default';// Source-scope the page-id lookup so duplicate slugs in different sources// do not return multiple rows or target the wrong page.const pageResult = await this.db.query(- 'SELECT id FROM pages WHERE slug = $1 AND source_id = $2',+ 'SELECT id FROM pages WHERE slug = $1 AND source_id = $2 FOR UPDATE',[slug, sourceId]);if (pageResult.rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);const pageId = (pageResult.rows[0] as { id: number }).id;+ // A fragment write cannot certify the full-body fence boundary. Import seals+ // only after its complete replacement succeeds in the same transaction.+ const invalidation = chunkWriteInvalidation(pageId, chunks);+ await this.db.query(invalidation.sql, invalidation.params);+// Remove chunks that no longer existconst newIndices = chunks.map(c => c.chunk_index);if (newIndices.length > 0) {@@ -3172,11 +3194,9 @@ export class PGLiteEngine implements BrainEngine {`$${paramIdx++}, ${embeddingImagePh})`,);- // NUL/lone-surrogate cleanup ONCE into a local shared by BOTH binds:- // the md5() embedded_text_hash input and the stored chunk_text must see- // the same bytes, or the hash diverges from the sanitized stored text- // (and the raw NUL would still abort the INSERT via the md5 param).- const sanitizedChunkText = sanitizeText(chunk.chunk_text);+ // Already normalized before the seal snapshot. Both storage and the+ // embedded_text_hash input must use those same canonical bytes.+ const sanitizedChunkText = chunk.chunk_text;// Param push order MUST match placeholder allocation order. Both// embedding placeholders (when present) are allocated BEFORE the// bulk row placeholders, so their values must be pushed first.@@ -3259,7 +3279,7 @@ export class PGLiteEngine implements BrainEngine {);}- async getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean }): Promise<Chunk[]> {+ async getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean }): Promise<Chunk[]> {const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;const source = sourceIds ?? opts?.sourceId ?? 'default';// S2: embedding_is_null reports the registry-ACTIVE column's truth —@@ -3284,6 +3304,8 @@ export class PGLiteEngine implements BrainEngine {FROM content_chunks ccJOIN pages p ON p.id = cc.page_idWHERE p.slug = $1 AND ${sourceIds ? 'p.source_id = ANY($2::text[])' : 'p.source_id = $2'}+ ${opts?.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : ''}+ ${requiresSafeChunks(opts) ? `AND ${safeChunksFilter('p')}` : ''}ORDER BY cc.chunk_index`,[slug, source]);@@ -3894,7 +3916,8 @@ export class PGLiteEngine implements BrainEngine {}}- async getLinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<Link[]> {+ async getLinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {+ const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';// #2200: federated grant scopes ALL THREE page endpoints — from, to, AND the// origin (the authoring page, surfaced as origin_slug). The origin LEFT JOIN// carries the same ANY($) filter so an out-of-grant origin's slug nulls out.@@ -3911,7 +3934,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY($2::text[])WHERE f.slug = $1 AND f.source_id = ANY($2::text[]) AND t.source_id = ANY($2::text[])- AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${privacy}`,[slug, opts.sourceIds]);return rows as unknown as Link[];@@ -3935,7 +3958,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE f.slug = $1 AND f.source_id = $2- AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${privacy}`,[slug, opts.sourceId]);return rows as unknown as Link[];@@ -3951,13 +3974,14 @@ export class PGLiteEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE f.slug = $1- AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${privacy}`,[slug]);return rows as unknown as Link[];}- async getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<Link[]> {+ async getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {+ const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';// #2200: federated grant scopes all three endpoints (mirrors getLinks) — the// referrer (from), the queried page (to), AND the origin — so neither a// foreign referrer nor a foreign origin slug is disclosed to the caller.@@ -3973,7 +3997,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY($2::text[])WHERE t.slug = $1 AND t.source_id = ANY($2::text[]) AND f.source_id = ANY($2::text[])- AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${privacy}`,[slug, opts.sourceIds]);return rows as unknown as Link[];@@ -3992,7 +4016,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE t.slug = $1 AND t.source_id = $2- AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${privacy}`,[slug, opts.sourceId]);return rows as unknown as Link[];@@ -4008,7 +4032,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE t.slug = $1- AND f.deleted_at IS NULL AND t.deleted_at IS NULL`,+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${privacy}`,[slug]);return rows as unknown as Link[];@@ -4089,6 +4113,8 @@ export class PGLiteEngine implements BrainEngine {depth: number = 5,opts?: import('./engine.ts').TraverseGraphOpts,): Promise<GraphNode[]> {+ const privacy = (page: string, link?: string) => opts?.excludePrivate+ ? `AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}` : '';// v0.34.1 (#861 — P0 leak seal): source-scope filters at seed, step, and// aggregation subquery. Mirrors postgres-engine.traverseGraph placement.const params: unknown[] = [slug, depth];@@ -4126,7 +4152,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < $2AND NOT (p2.id = ANY(g.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${stepScope}ORDER BY p2.slug ASC, p2.id ASCLIMIT $${capIdx})`;@@ -4137,7 +4163,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < $2AND NOT (p2.id = ANY(g.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${stepScope}`;}@@ -4146,7 +4172,7 @@ export class PGLiteEngine implements BrainEngine {const { rows } = await this.db.query(`WITH RECURSIVE graph AS (SELECT p.id, p.slug, p.title, p.type, 0 as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALL@@ -4162,7 +4188,7 @@ export class PGLiteEngine implements BrainEngine {(SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type))FROM links l2JOIN pages p3 ON p3.id = l2.to_page_id- WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${aggScope}),+ WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${privacy('p3', 'l2')} ${aggScope}),'[]'::jsonb) as linksFROM graph g@@ -4184,15 +4210,17 @@ export class PGLiteEngine implements BrainEngine {async traversePaths(slug: string,- opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[] },+ opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },): Promise<GraphPath[]> {return (await this.traversePathsDetailed(slug, opts)).paths;}async traversePathsDetailed(slug: string,- opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[] },+ opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },): Promise<{ paths: GraphPath[]; truncated: boolean }> {+ const privacy = (page: string, link?: string) => opts?.excludePrivate+ ? `AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}` : '';const depth = opts?.depth ?? 5;const direction = opts?.direction ?? 'out';const linkType = opts?.linkType ?? null;@@ -4232,7 +4260,7 @@ export class PGLiteEngine implements BrainEngine {sql = `WITH RECURSIVE walk AS (SELECT p.id, p.slug, 0::int AS depth, ARRAY[p.id] AS visited- FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALLSELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.idFROM walk w@@ -4240,7 +4268,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE w.depth < $2AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope})@@ -4250,7 +4278,7 @@ export class PGLiteEngine implements BrainEngine {JOIN links l ON l.from_page_id = w.idJOIN pages p2 ON p2.id = l.to_page_idWHERE w.depth < $2- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope}ORDER BY depth, from_slug, to_slug@@ -4260,7 +4288,7 @@ export class PGLiteEngine implements BrainEngine {sql = `WITH RECURSIVE walk AS (SELECT p.id, p.slug, 0::int AS depth, ARRAY[p.id] AS visited- FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALLSELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.idFROM walk w@@ -4268,7 +4296,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.from_page_idWHERE w.depth < $2AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope})@@ -4278,7 +4306,7 @@ export class PGLiteEngine implements BrainEngine {JOIN links l ON l.to_page_id = w.idJOIN pages p2 ON p2.id = l.from_page_idWHERE w.depth < $2- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope}ORDER BY depth, from_slug, to_slug@@ -4290,7 +4318,7 @@ export class PGLiteEngine implements BrainEngine {sql = `WITH RECURSIVE walk AS (SELECT p.id, 0::int AS depth, ARRAY[p.id] AS visited- FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALLSELECT p2.id, w.depth + 1, w.visited || p2.idFROM walk w@@ -4298,7 +4326,7 @@ export class PGLiteEngine implements BrainEngine {JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id ENDWHERE w.depth < $2AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${linkTypeWhere}${stepScope})@@ -4309,8 +4337,8 @@ export class PGLiteEngine implements BrainEngine {JOIN pages pf ON pf.id = l.from_page_idJOIN pages pt ON pt.id = l.to_page_idWHERE w.depth < $2- AND pf.deleted_at IS NULL- AND pt.deleted_at IS NULL+ AND pf.deleted_at IS NULL ${privacy('pf', 'l')}+ AND pt.deleted_at IS NULL ${privacy('pt')}${linkTypeWhere}${pfScope}${ptScope}@@ -4346,208 +4374,23 @@ export class PGLiteEngine implements BrainEngine {seeds: string[],opts?: import('./types.ts').RelationalFanoutOpts,): Promise<import('./types.ts').RelationalFanoutRow[]> {- if (!seeds || seeds.length === 0) return [];- const depth = Math.min(Math.max(1, opts?.depth ?? 2), 3);- const direction = opts?.direction ?? 'both';- const limit = Math.min(Math.max(1, opts?.limit ?? 50), 200);- const types = opts?.linkTypes && opts.linkTypes.length > 0 ? opts.linkTypes : null;-- // $1=seeds, $2=depth, $3=limit; optional scope/type params appended.- const params: unknown[] = [seeds, depth, limit];- const useSourceIds = opts?.sourceIds && opts.sourceIds.length > 0;- let seedScope = '';- if (useSourceIds) {- params.push(opts!.sourceIds);- seedScope = `AND p.source_id = ANY($${params.length}::text[])`;- } else if (opts?.sourceId) {- params.push(opts.sourceId);- seedScope = `AND p.source_id = $${params.length}`;- }- let typeFilter = '';- if (types) {- params.push(types);- typeFilter = `AND l.link_type = ANY($${params.length}::text[])`;- }- const mentionsFilter = opts?.includeMentions ? '' : `AND l.link_source IS DISTINCT FROM 'mentions'`;-- const recurStep =- direction === 'out'- ? `JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id`- : direction === 'in'- ? `JOIN links l ON l.to_page_id = w.id JOIN pages p2 ON p2.id = l.from_page_id`- : `JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id)- JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END`;-- const sql = `- WITH RECURSIVE walk AS (- SELECT p.id, p.slug, p.source_id, 0::int AS depth,- ARRAY[p.id] AS visited, ARRAY[p.slug] AS path,- p.source_id AS seed_source, NULL::text AS last_link_type- FROM pages p- WHERE p.slug = ANY($1::text[]) ${seedScope} AND p.deleted_at IS NULL- UNION ALL- SELECT p2.id, p2.slug, p2.source_id, w.depth + 1,- w.visited || p2.id, w.path || p2.slug,- w.seed_source, l.link_type- FROM walk w- ${recurStep}- WHERE w.depth < $2- AND NOT (p2.id = ANY(w.visited))- AND p2.source_id = w.seed_source- AND p2.deleted_at IS NULL- ${mentionsFilter}- ${typeFilter}- )- SELECT n.source_id, n.slug,- MIN(n.depth) AS hop,- COUNT(DISTINCT n.last_link_type) AS edge_count,- array_agg(DISTINCT n.last_link_type)- FILTER (WHERE n.last_link_type IS NOT NULL) AS via_link_types,- -- Final path tie-break (lexicographic) makes the pick deterministic- -- when a node is reachable at the same depth from multiple seeds;- -- without it the winner is plan/heap-order dependent and the two- -- engines (or two runs) can disagree. Relational retrieval is- -- documented deterministic; keep in lockstep with postgres-engine.ts.- (array_agg(array_to_string(n.path, chr(9))- ORDER BY n.depth ASC, array_length(n.path, 1) ASC,- array_to_string(n.path, chr(9)) ASC))[1] AS path_str,- (SELECT cc.id FROM content_chunks cc- WHERE cc.page_id = n.id ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_id- FROM walk n- WHERE n.depth > 0- GROUP BY n.source_id, n.slug, n.id- ORDER BY hop ASC, edge_count DESC, n.source_id ASC, n.slug ASC- LIMIT $3- `;-- const { rows } = await this.db.query(sql, params);- return (rows as Record<string, unknown>[]).map(r => ({- source_id: r.source_id as string,- slug: r.slug as string,- hop: Number(r.hop),- edge_count: Number(r.edge_count),- via_link_types: Array.isArray(r.via_link_types) ? (r.via_link_types as string[]) : [],- path: r.path_str ? String(r.path_str).split('\t') : [],- canonical_chunk_id: r.canonical_chunk_id == null ? null : Number(r.canonical_chunk_id),- }));+ return readRelationalFanout(this.executeRaw.bind(this), seeds, opts);}- async getBacklinkCounts(pageIds: number[]): Promise<Map<number, number>> {- const result = new Map<number, number>();- if (pageIds.length === 0) return result;- // Initialize all ids to 0 so callers get a consistent map.- for (const id of pageIds) result.set(id, 0);-- // v0.41.18.0 D12: filter mentions OUT of backlink-count for search- // ranking — parity with postgres-engine.ts. See that file's comment- // for the full rationale. `IS DISTINCT FROM` is NULL-safe so legacy- // rows with NULL link_source still count toward backlinks.- // #4380: keyed by p.id, not slug — parity with postgres-engine.ts.- // PGLite needs explicit cast for array binding (does not auto-serialize JS arrays).- const { rows } = await this.db.query(- `SELECT p.id AS page_id, COUNT(l.id)::int AS cnt- FROM pages p- LEFT JOIN links l ON l.to_page_id = p.id- AND l.link_source IS DISTINCT FROM 'mentions'- WHERE p.id = ANY($1::int[])- GROUP BY p.id`,- [pageIds]- );- for (const r of rows as { page_id: number; cnt: number }[]) {- result.set(Number(r.page_id), Number(r.cnt));- }- return result;+ async getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>> {+ return readBacklinkCounts(this.executeRaw.bind(this), pageIds, opts);}- async getAdjacencyBoosts(pageIds: number[]): Promise<Map<number, import('./types.ts').AdjacencyRow>> {- const result = new Map<number, import('./types.ts').AdjacencyRow>();- if (pageIds.length === 0) return result;-- // PGLite parity with PostgresEngine.getAdjacencyBoosts. SQL contract- // and source-scope rationale: see BrainEngine.getAdjacencyBoosts JSDoc.- // Same CTE shape, same COALESCE on source_id for NULL safety, same- // CASE-WHEN exclusion of target's own source for cross_source_hits.- //- // Defense-in-depth (codex outside-voice review): deleted_at IS NULL- // on both join sides. Matches Postgres-engine parity.- const { rows } = await this.db.query(- `WITH targets AS (- SELECT id, COALESCE(source_id, 'default') AS source_id- FROM pages- WHERE id = ANY($1::int[])- AND deleted_at IS NULL- )- SELECT- l.to_page_id AS to_page_id,- COUNT(DISTINCT l.from_page_id)::int AS hits,- COUNT(DISTINCT- CASE WHEN COALESCE(p.source_id, 'default') <> t.source_id- THEN COALESCE(p.source_id, 'default') END- )::int AS cross_source_hits- FROM links l- JOIN pages p ON p.id = l.from_page_id AND p.deleted_at IS NULL- JOIN targets t ON t.id = l.to_page_id- WHERE l.from_page_id = ANY($1::int[])- AND l.to_page_id = ANY($1::int[])- GROUP BY l.to_page_id- HAVING COUNT(DISTINCT l.from_page_id) >= 1`,- [pageIds]- );- for (const r of rows as { to_page_id: number; hits: number; cross_source_hits: number }[]) {- result.set(Number(r.to_page_id), {- hits: Number(r.hits),- cross_source_hits: Number(r.cross_source_hits),- });- }- return result;+ async getAdjacencyBoosts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, import('./types.ts').AdjacencyRow>> {+ return readAdjacencyBoosts(this.executeRaw.bind(this), pageIds, opts);}- async getContentFlagsByPageIds(- pageIds: number[],- ): Promise<Map<number, { reason: string; detail: string }>> {- const result = new Map<number, { reason: string; detail: string }>();- if (pageIds.length === 0) return result;- // Parity with PostgresEngine.getContentFlagsByPageIds (issue #1699).- const { rows } = await this.db.query(- `SELECT id,- frontmatter -> 'content_flag' ->> 'reason' AS reason,- frontmatter -> 'content_flag' ->> 'detail' AS detail- FROM pages- WHERE id = ANY($1::int[])- AND frontmatter ? 'content_flag'`,- [pageIds]- );- for (const r of rows as { id: number; reason: string | null; detail: string | null }[]) {- if (!r.reason) continue;- result.set(Number(r.id), { reason: r.reason, detail: r.detail ?? '' });- }- return result;+ async getContentFlagsByPageIds(pageIds: number[], opts?: PageReadScope): Promise<Map<number, { reason: string; detail: string }>> {+ return readContentFlags(this.executeRaw.bind(this), pageIds, opts);}- async getUnverifiedExtractionPageIds(- pageIds: number[],- ): Promise<Map<number, { unverified: boolean; status: string }>> {- const result = new Map<number, { unverified: boolean; status: string }>();- if (pageIds.length === 0) return result;- // Parity with PostgresEngine.getUnverifiedExtractionPageIds (issue #160,- // widened for #4220). Quarantine predicate is the shared- // unverifiedExtractionFragment so this query and the SQL-side- // source-boost guard can never drift; any page with a frontmatter- // `status` value is returned so draft/superseded/restricted surface on- // SearchResult.status.- const { rows } = await this.db.query(- `SELECT id,- (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') AS status,- (${unverifiedExtractionFragment('pages')}) AS unverified- FROM pages- WHERE id = ANY($1::int[])- AND (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') IS NOT NULL`,- [pageIds]- );- for (const r of rows as { id: number; status: string; unverified: boolean }[]) {- result.set(Number(r.id), { unverified: r.unverified === true, status: r.status });- }- return result;+ async getUnverifiedExtractionPageIds(pageIds: number[], opts?: PageReadScope): Promise<Map<number, { unverified: boolean; status: string }>> {+ return readExtractionStates(this.executeRaw.bind(this), pageIds, opts);}async getPageTimestamps(slugs: string[]): Promise<Map<string, Date>> {@@ -4560,51 +4403,18 @@ export class PGLiteEngine implements BrainEngine {return new Map(rows.map((r: any) => [r.slug as string, new Date(r.ts as string)]));}- async getEffectiveDates(refs: Array<{slug: string; source_id: string}>): Promise<Map<string, Date>> {- if (refs.length === 0) return new Map();- const slugs = refs.map(r => r.slug);- const sourceIds = refs.map(r => r.source_id);- const { rows } = await this.db.query(- `SELECT p.slug, p.source_id, COALESCE(p.effective_date, p.updated_at, p.created_at) AS ts- FROM pages p- JOIN unnest($1::text[], $2::text[]) AS u(slug, source_id)- ON p.slug = u.slug AND p.source_id = u.source_id`,- [slugs, sourceIds],- );- const out = new Map<string, Date>();- for (const r of rows as Array<{slug: string; source_id: string; ts: string | Date}>) {- const key = `${r.source_id}::${r.slug}`;- out.set(key, r.ts instanceof Date ? r.ts : new Date(r.ts));- }- return out;+ async getEffectiveDates(refs: Array<{slug: string; source_id: string}>, opts?: PageReadScope): Promise<Map<string, Date>> {+ return readEffectiveDates(this.executeRaw.bind(this), refs, opts);}- async getSalienceScores(refs: Array<{slug: string; source_id: string}>): Promise<Map<string, number>> {- if (refs.length === 0) return new Map();- const slugs = refs.map(r => r.slug);- const sourceIds = refs.map(r => r.source_id);- const { rows } = await this.db.query(- `SELECT p.slug, p.source_id,- (COALESCE(p.emotional_weight, 0) * 5- + ln(1 + COUNT(DISTINCT t.id))) AS score- FROM pages p- JOIN unnest($1::text[], $2::text[]) AS u(slug, source_id)- ON p.slug = u.slug AND p.source_id = u.source_id- LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE- GROUP BY p.id`,- [slugs, sourceIds],- );- const out = new Map<string, number>();- for (const r of rows as Array<{slug: string; source_id: string; score: number | string}>) {- const key = `${r.source_id}::${r.slug}`;- out.set(key, Number(r.score));- }- return out;+ async getSalienceScores(refs: Array<{slug: string; source_id: string}>, opts?: PageReadPolicy): Promise<Map<string, number>> {+ return readSalienceScores(this.executeRaw.bind(this), refs, opts);}async findOrphanPages(opts?: {sourceId?: string;sourceIds?: string[];+ excludePrivate?: boolean;mode?: 'inbound' | 'islanded';}): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }>> {// Soft-delete filter on BOTH sides:@@ -4638,7 +4448,7 @@ export class PGLiteEngine implements BrainEngine {FROM links lJOIN pages tgt ON tgt.id = l.to_page_idWHERE l.from_page_id = p.id- AND tgt.deleted_at IS NULL+ AND tgt.deleted_at IS NULL ${opts?.excludePrivate ? `AND ${privatePagesFilterFragment('tgt')} AND ${privateLinkOriginFilterFragment('l')}` : ''})`: '';const { rows } = await this.db.query(@@ -4649,14 +4459,14 @@ export class PGLiteEngine implements BrainEngine {p.type,(NOT ${QUARANTINE_FILTER_FRAGMENT}) AS quarantinedFROM pages p- WHERE p.deleted_at IS NULL+ WHERE p.deleted_at IS NULL ${opts?.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : ''}${sourceFilter}AND NOT EXISTS (SELECT 1FROM links lJOIN pages src ON src.id = l.from_page_idWHERE l.to_page_id = p.id- AND src.deleted_at IS NULL+ AND src.deleted_at IS NULL ${opts?.excludePrivate ? `AND ${privatePagesFilterFragment('src')} AND ${privateLinkOriginFilterFragment('l')}` : ''})${outboundFilter}ORDER BY p.slug`,@@ -4786,6 +4596,10 @@ export class PGLiteEngine implements BrainEngine {// idiom, same result; the engines stay lockstep on behavior, not on builder.)const limit = opts?.limit || 100;const where: string[] = ['p.slug = $1'];+ if (opts?.excludePrivate) {+ where.push(privatePagesFilterFragment('p'));+ where.push(privateTimelineEventFilterFragment('te'));+ }const params: unknown[] = [slug];if (opts?.after) {params.push(opts.after);@@ -4822,7 +4636,10 @@ export class PGLiteEngine implements BrainEngine {// date). Source scope: federated sourceIds[] > scalar sourceId > unscoped.// Returns the ep-side fragment (same param slot): the event-page LEFT JOIN carries// the caller's scope so out-of-scope event fields null out (#2200 origin-join shape).- private pushChronicleSource(where: string[], params: unknown[], opts?: { sourceId?: string; sourceIds?: string[] }): string {+ private pushChronicleSource(where: string[], params: unknown[], opts?: PageReadScope): string {+ if (opts?.excludePrivate) {+ where.push(privatePagesFilterFragment('p'), privateTimelineEventFilterFragment('te'));+ }if (opts?.sourceIds && opts.sourceIds.length > 0) {params.push(opts.sourceIds);where.push(`p.source_id = ANY($${params.length}::text[])`);@@ -4892,7 +4709,7 @@ export class PGLiteEngine implements BrainEngine {return result.rows as unknown as ChronicleTimelineRow[];}- async getOnThisDay(opts?: { date?: string; limit?: number; sourceId?: string; sourceIds?: string[] }): Promise<ChronicleTimelineRow[]> {+ async getOnThisDay(opts?: PageReadScope & { date?: string; limit?: number }): Promise<ChronicleTimelineRow[]> {const limit = opts?.limit ?? 50;const params: unknown[] = [];let target: string;@@ -4916,7 +4733,7 @@ export class PGLiteEngine implements BrainEngine {return result.rows as unknown as ChronicleTimelineRow[];}- async getLastSeen(entitySlug: string, opts?: { asof?: string; sourceId?: string; sourceIds?: string[] }): Promise<LastSeenResult> {+ async getLastSeen(entitySlug: string, opts?: PageReadScope & { asof?: string }): Promise<LastSeenResult> {const params: unknown[] = [entitySlug, `%${entitySlug}%`];const where: string[] = [`(te.event_page_id IS NULL OR ep.deleted_at IS NULL)`,@@ -5140,11 +4957,12 @@ export class PGLiteEngine implements BrainEngine {async getRawData(slug: string,source?: string,- opts?: { sourceId?: string; sourceIds?: string[] },+ opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },): Promise<RawData[]> {// v0.31.8 (D21): build WHERE clause dynamically. Without opts.sourceId,// no source filter (preserves pre-v0.31.8 cross-source read).const where: string[] = ['p.slug = $1'];+ if (opts?.excludePrivate) where.push(privatePagesFilterFragment('p'));const params: unknown[] = [slug];if (source) {params.push(source);@@ -5559,12 +5377,15 @@ export class PGLiteEngine implements BrainEngine {return rows[0] as unknown as PageVersion;}- async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<PageVersion[]> {+ async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {+ const privacy = opts?.excludePrivate+ ? `AND ${privatePagesFilterFragment('p')} AND ${privatePagesFilterFragment('pv')}` : '';if (opts?.sourceIds && opts.sourceIds.length > 0) {const { rows } = await this.db.query(`SELECT pv.* FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = $1 AND p.source_id = ANY($2::text[])+ ${privacy}ORDER BY pv.snapshot_at DESC`,[slug, opts.sourceIds]);@@ -5575,6 +5396,7 @@ export class PGLiteEngine implements BrainEngine {`SELECT pv.* FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = $1 AND p.source_id = $2+ ${privacy}ORDER BY pv.snapshot_at DESC`,[slug, opts.sourceId]);@@ -5584,6 +5406,7 @@ export class PGLiteEngine implements BrainEngine {`SELECT pv.* FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = $1+ ${privacy}ORDER BY pv.snapshot_at DESC`,[slug]);@@ -5603,6 +5426,7 @@ export class PGLiteEngine implements BrainEngine {`UPDATE pages SETcompiled_truth = pv.compiled_truth,frontmatter = pv.frontmatter,+ chunker_version = ${bodyWriteChunkVersion('pv.compiled_truth', 'pages.timeline')},updated_at = now()FROM page_versions pvWHERE pages.slug = $1 AND pages.source_id = $3@@ -5615,6 +5439,7 @@ export class PGLiteEngine implements BrainEngine {`UPDATE pages SETcompiled_truth = pv.compiled_truth,frontmatter = pv.frontmatter,+ chunker_version = ${bodyWriteChunkVersion('pv.compiled_truth', 'pages.timeline')},updated_at = now()FROM page_versions pvWHERE pages.slug = $1 AND pv.id = $2 AND pv.page_id = pages.id`,@@ -5938,18 +5763,21 @@ export class PGLiteEngine implements BrainEngine {async resolveSlugWithAlias(slug: string,sourceOrSources: string | readonly string[],+ opts?: { excludePrivate?: boolean },): Promise<string> {- return (await this.resolveSlugWithAliasDetailed(slug, sourceOrSources))?.canonical_slug ?? slug;+ return (await this.resolveSlugWithAliasDetailed(slug, sourceOrSources, opts))?.canonical_slug ?? slug;}async resolveSlugWithAliasDetailed(slug: string,sourceOrSources: string | readonly string[],+ opts?: { excludePrivate?: boolean },): Promise<{ canonical_slug: string; source_id: string } | null> {const sources = Array.isArray(sourceOrSources)? [...sourceOrSources]: [sourceOrSources as string];if (sources.length === 0) return null;+ const privacy = opts?.excludePrivate ? `AND EXISTS (SELECT 1 FROM pages p WHERE p.slug = slug_aliases.canonical_slug AND p.source_id = slug_aliases.source_id AND p.deleted_at IS NULL AND ${privatePagesFilterFragment('p')})` : '';try {// PGLite supports `= ANY($N::text[])` per pgvector / postgres semantics.// ORDER BY array_position pins the federated-read precedence so the@@ -5959,7 +5787,7 @@ export class PGLiteEngine implements BrainEngine {`SELECT canonical_slug, source_idFROM slug_aliasesWHERE alias_slug = $1- AND source_id IN (${placeholders})+ AND source_id IN (${placeholders}) ${privacy}ORDER BY id`,[slug, ...sources],);@@ -5985,32 +5813,9 @@ export class PGLiteEngine implements BrainEngine {async resolveAliases(aliasNorms: string[],- opts?: { sourceId?: string; sourceIds?: string[] },+ opts?: PageReadScope,): Promise<Map<string, Array<{ slug: string; source_id: string }>>> {- const out = new Map<string, Array<{ slug: string; source_id: string }>>();- if (!aliasNorms || aliasNorms.length === 0) return out;- const sources =- opts?.sourceIds && opts.sourceIds.length > 0- ? opts.sourceIds- : opts?.sourceId- ? [opts.sourceId]- : null;- let q = `SELECT alias_norm, slug, source_id FROM page_aliases WHERE alias_norm = ANY($1::text[])`;- const params: unknown[] = [aliasNorms];- if (sources) {- params.push(sources);- q += ` AND source_id = ANY($2::text[])`;- }- q += ` ORDER BY alias_norm, source_id, slug`;- const { rows } = await this.db.query(q, params);- for (const r of rows as Array<{ alias_norm: string; slug: string; source_id: string }>) {- const list = out.get(r.alias_norm) ?? [];- if (!list.some(x => x.slug === r.slug && x.source_id === r.source_id)) {- list.push({ slug: r.slug, source_id: r.source_id });- }- out.set(r.alias_norm, list);- }- return out;+ return readAliases(this.executeRaw.bind(this), aliasNorms, opts);}async setPageAliases(slug: string, sourceId: string, aliasNorms: string[]): Promise<void> {diff --git a/src/core/pglite-engine/salience.ts b/src/core/pglite-engine/salience.tsindex db51f4699a..648b40e356 100644--- a/src/core/pglite-engine/salience.ts+++ b/src/core/pglite-engine/salience.ts@@ -1,3 +1,4 @@+import { pageReadFilter } from '../search/read-policy-sql.ts';/*** v0.29 — Salience + Anomaly Detection, peeled out of PGLiteEngine* (containment sprint C15). Free functions over a NARROW deps surface —@@ -108,6 +109,17 @@ export async function getRecentSalience(deps: PgliteSalienceDeps, opts: Salienceparams.push(opts.sourceId);sourceCondition = `AND p.source_id = $${params.length}`;}+ const restricted = opts.takesHoldersAllowList !== undefined;+ const emotionalSql = restricted ? '0' : 'p.emotional_weight';+ const touchedSql = restricted ? 'p.updated_at' : 'GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at))';+ let holderCondition = '';+ if (restricted) {+ params.push(opts.takesHoldersAllowList);+ holderCondition = `AND t.holder = ANY($${params.length}::text[])`;+ }+ // Scope is already bound above; the shared live predicate excludes deleted,+ // quarantined and archived-source rows before ranking and LIMIT.+ sourceCondition += ` AND ${pageReadFilter('p', { excludePrivate: opts.excludePrivate }, [], true)}`;params.push(limit);const limitParam = `$${params.length}`;@@ -131,16 +143,16 @@ export async function getRecentSalience(deps: PgliteSalienceDeps, opts: Salience});}const { rows } = await deps.db.query(- `SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, p.emotional_weight,+ `SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, ${emotionalSql} AS emotional_weight,COUNT(DISTINCT t.id) AS take_count,COALESCE(AVG(t.weight), 0) AS take_avg_weight,- (p.emotional_weight * 5)+ (${emotionalSql} * 5)+ ln(1 + COUNT(DISTINCT t.id))+ ${recencySql}AS scoreFROM pages p- LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE- WHERE GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at)) >= $1::timestamptz+ LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE ${holderCondition}+ WHERE ${touchedSql} >= $1::timestamptz${prefixCondition}${excludeBriefings}${sourceCondition}@@ -262,6 +274,10 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOpt? [opts.sourceId]: [];+ // Apply the identical live/privacy predicate to baseline keys, baseline+ // counts and current counts, before deriving any statistical signal.+ const readClause = `AND ${pageReadFilter('p', { excludePrivate: opts.excludePrivate }, [], true)}`;+const tagBaselineRes = await deps.db.query(`WITH days AS (SELECT day::date FROM generate_series(@@ -270,14 +286,14 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOpt),cohort_keys AS (SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_id- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause} ${readClause}),touched AS (SELECT t.tag,date_trunc('day', p.updated_at)::date AS day,COUNT(DISTINCT p.id) AS cntFROM tags t JOIN pages p ON p.id = t.page_id- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause} ${readClause}GROUP BY 1, 2)SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count@@ -294,14 +310,14 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOpt),cohort_keys AS (SELECT DISTINCT p.type FROM pages p- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause} ${readClause}),touched AS (SELECT p.type,date_trunc('day', p.updated_at)::date AS day,COUNT(DISTINCT p.id) AS cntFROM pages p- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause} ${readClause}GROUP BY 1, 2)SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count@@ -315,7 +331,7 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOptCOUNT(DISTINCT p.id)::int AS count,array_agg(DISTINCT p.slug) AS slugsFROM tags t JOIN pages p ON p.id = t.page_id- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause} ${readClause}GROUP BY 1`,[sinceIso, sinceEnd.toISOString(), ...sourceParam]);@@ -325,7 +341,7 @@ export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOptCOUNT(DISTINCT p.id)::int AS count,array_agg(DISTINCT p.slug) AS slugsFROM pages p- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause}+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz ${sourceClause} ${readClause}GROUP BY 1`,[sinceIso, sinceEnd.toISOString(), ...sourceParam]);diff --git a/src/core/pglite-engine/takes.ts b/src/core/pglite-engine/takes.tsindex f0fd9d0c5a..1511ed7255 100644--- a/src/core/pglite-engine/takes.ts+++ b/src/core/pglite-engine/takes.ts@@ -20,6 +20,7 @@ import { deriveResolutionTuple, finalizeScorecard } from '../takes-resolution.tsimport { normalizeWeightForStorage } from '../takes-fence.ts';import { buildTakeRows } from '../batch-rows.ts';import { staleTakeRowToRow, takeRowToTake, takeHitRowToHit } from '../utils.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';/** Narrow slice of PGLiteEngine the takes operations use. */export interface PgliteTakesDeps {@@ -282,6 +283,7 @@ export async function listTakes(deps: PgliteTakesDeps, opts: TakesListOpts = {})AND ($7::text[] IS NULL OR t.holder = ANY($7::text[]))AND ($11::text[] IS NULL OR p.source_id = ANY($11::text[]))AND ($12::text IS NULL OR p.source_id = $12::text)+ ${opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : ''}ORDER BYCASE WHEN $8 = 'weight' THEN t.weight END DESC NULLS LAST,CASE WHEN $8 = 'since_date' THEN t.since_date END DESC NULLS LAST,@@ -320,6 +322,7 @@ export async function searchTakes(JOIN pages p ON p.id = t.page_idWHERE t.activeAND $1 <% t.claim+ ${opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : ''}AND ($2::text[] IS NULL OR t.holder = ANY($2::text[]))AND ($4::text[] IS NULL OR p.source_id = ANY($4::text[]))AND ($5::text IS NULL OR p.source_id = $5::text)@@ -353,6 +356,7 @@ export async function searchTakesVector(JOIN pages p ON p.id = t.page_idWHERE t.activeAND t.embedding IS NOT NULL+ ${opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : ''}AND ($2::text[] IS NULL OR t.holder = ANY($2::text[]))AND ($4::text[] IS NULL OR p.source_id = ANY($4::text[]))AND ($5::text IS NULL OR p.source_id = $5::text)@@ -577,6 +581,7 @@ export async function getScorecard(deps: PgliteTakesDeps, opts: TakesScorecardOp// shares the SQL dialect with real Postgres so the math expressions match.const params: unknown[] = [];const clauses: string[] = [];+ if (opts.excludePrivate) clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterFragment('p')})`);if (opts.holder !== undefined) { params.push(opts.holder); clauses.push(`AND holder = $${params.length}`); }if (opts.domainPrefix !== undefined) {params.push(opts.domainPrefix + '%');@@ -623,6 +628,7 @@ export async function getCalibrationCurve(deps: PgliteTakesDeps, opts: Calibraticonst maxIdx = Math.floor(1 / bucketSize) - 1;const params: unknown[] = [bucketSize, maxIdx];const clauses: string[] = [];+ if (opts.excludePrivate) clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterFragment('p')})`);if (opts.holder !== undefined) { params.push(opts.holder); clauses.push(`AND holder = $${params.length}`); }if (allowList !== undefined) { params.push(allowList); clauses.push(`AND holder = ANY($${params.length}::text[])`); }// #2200-class: source scope via the take's page (EXISTS — no pages JOIN here).diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 6daa9eeb59..5d9f2568a8 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -1,3 +1,6 @@+import type { PageReadScope } from './types.ts';+import type { PageReadPolicy } from './types.ts';+import { readRelationalFanout, readAliases, readBacklinkCounts, readAdjacencyBoosts, readContentFlags, readExtractionStates, readEffectiveDates, readSalienceScores } from './search/read-enrichment.ts';import postgres from 'postgres';import type {BrainEngine,@@ -55,7 +58,7 @@ import {EmbeddingColumnNotRegisteredError,} from './search/embedding-column.ts';import { getFtsLanguage, applyFtsLanguagePolicy } from './fts-language.ts';-import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';+import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';import type {Page, PageInput, PageFilters, PageType,Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,@@ -85,7 +88,7 @@ import { drainBackgroundWorkBeforeDisconnect } from './background-work.ts';import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';-import { privatePagesFilterFragment } from './search/private-visibility.ts';+import { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment } from './search/private-visibility.ts';import { unverifiedExtractionFragment } from './extraction-review.ts';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP } from './engine-constants.ts';@@ -139,6 +142,8 @@ export function getPostgresSchema(// follow-up that will reintroduce a typed retry mechanism.export class PostgresEngine implements BrainEngine {+ /** Transaction clones keep chunk invalidation and replacement atomic. */+ private _chunkWritesInTransaction = false;readonly kind = 'postgres' as const;private _sql: ReturnType<typeof postgres> | null = null;/** Saved config for reconnection. */@@ -541,6 +546,7 @@ export class PostgresEngine implements BrainEngine {return await (conn.begin(async (tx) => {// Create a scoped engine with tx as its connection, no shared state mutationconst txEngine = Object.create(this) as PostgresEngine;+ Object.defineProperty(txEngine, '_chunkWritesInTransaction', { value: true });Object.defineProperty(txEngine, 'sql', { get: () => tx });Object.defineProperty(txEngine, '_sql', { value: tx as unknown as ReturnType<typeof postgres>, writable: false });return fn(txEngine);@@ -662,7 +668,7 @@ export class PostgresEngine implements BrainEngine {}// Pages CRUD- async getPage(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeDeleted?: boolean }): Promise<Page | null> {+ async getPage(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeDeleted?: boolean; excludePrivate?: boolean }): Promise<Page | null> {const includeDeleted = opts?.includeDeleted === true;const sourceId = opts?.sourceId;const sourceIds = opts?.sourceIds;@@ -683,6 +689,7 @@ export class PostgresEngine implements BrainEngine {? tx`AND source_id = ${sourceId}`: tx``;const deletedCondition = includeDeleted ? tx`` : tx`AND deleted_at IS NULL`;+ const privacy = opts?.excludePrivate ? tx.unsafe(`AND ${privatePagesFilterFragment('pages')}`) : tx``;// #3931: anchor on sourceIds[0] (caller's own resolved source, see// localFederatedSourceIds) instead of a hardcoded 'default'.const anchorSourceId = sourceIds && sourceIds.length > 0 ? sourceIds[0] : 'default';@@ -692,7 +699,7 @@ export class PostgresEngine implements BrainEngine {source_kind, source_uri, ingested_via, ingested_at,contextual_retrieval_modeFROM pages- WHERE slug = ${slug} ${sourceCondition} ${deletedCondition}+ WHERE slug = ${slug} ${sourceCondition} ${deletedCondition} ${privacy}ORDER BY (source_id = ${anchorSourceId}) DESC, source_id ASCLIMIT 1`;@@ -773,7 +780,8 @@ export class PostgresEngine implements BrainEngine {const effectiveDateSource = page.effective_date_source ?? null;const importFilename = page.import_filename ?? null;// v0.32.7 CJK wave: chunker_version + source_path columns.- const chunkerVersion = page.chunker_version ?? null;+ // Only an import transaction may seal a fully sanitized chunk replacement.+ const chunkerVersion = Math.min(page.chunker_version ?? 0, SAFE_FENCE_CHUNKER_VERSION - 1);const sourcePath = page.source_path ?? null;// v0.39.3.0 provenance write-through (WARN-8 + CV12). Server stamps// `ingested_at = now()` ONLY when any provenance is being written —@@ -786,7 +794,7 @@ export class PostgresEngine implements BrainEngine {const ingestedAt = (sourceKind || sourceUri || ingestedVia) ? new Date() : null;const rows = await sql`INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, content_hash, updated_at, effective_date, effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at)- VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${sanitizeText(page.title)}, ${sanitizeText(page.compiled_truth)}, ${sanitizeText(page.timeline || '')}, ${sql.json(frontmatter as Parameters<typeof sql.json>[0])}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, COALESCE(${chunkerVersion}::smallint, ${MARKDOWN_CHUNKER_VERSION}), ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt})+ VALUES (${sourceId}, ${slug}, ${page.type}, ${pageKind}, ${sanitizeText(page.title)}, ${sanitizeText(page.compiled_truth)}, ${sanitizeText(page.timeline || '')}, ${sql.json(frontmatter as Parameters<typeof sql.json>[0])}, ${hash}, now(), ${effectiveDate}, ${effectiveDateSource}, ${importFilename}, ${chunkerVersion}::smallint, ${sourcePath}, ${sourceKind}, ${sourceUri}, ${ingestedVia}, ${ingestedAt})ON CONFLICT (source_id, slug) DO UPDATE SETtype = EXCLUDED.type,page_kind = EXCLUDED.page_kind,@@ -800,7 +808,7 @@ export class PostgresEngine implements BrainEngine {effective_date = COALESCE(EXCLUDED.effective_date, pages.effective_date),effective_date_source = COALESCE(EXCLUDED.effective_date_source, pages.effective_date_source),import_filename = COALESCE(EXCLUDED.import_filename, pages.import_filename),- chunker_version = COALESCE(EXCLUDED.chunker_version, pages.chunker_version),+ chunker_version = ${sql.unsafe(bodyWriteChunkVersion('EXCLUDED.compiled_truth', 'EXCLUDED.timeline'))},source_path = COALESCE(EXCLUDED.source_path, pages.source_path),source_kind = COALESCE(EXCLUDED.source_kind, pages.source_kind),source_uri = COALESCE(EXCLUDED.source_uri, pages.source_uri),@@ -964,6 +972,7 @@ export class PostgresEngine implements BrainEngine {SET compiled_truth = ${compiledTruth},timeline = ${timeline},content_hash = ${contentHash},+ chunker_version = ${sql.unsafe(bodyWriteChunkVersion('$1', '$2'), [compiledTruth, timeline])},updated_at = now()WHERE source_id = ${sourceId}AND slug = ${slug}@@ -1361,7 +1370,7 @@ export class PostgresEngine implements BrainEngine {}, { alwaysTransaction: typeof opts.seed === 'number' });}- async resolveSlugs(partial: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<string[]> {+ async resolveSlugs(partial: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<string[]> {const sql = this.sql;// v0.41.13 #1436: source scope via postgres.js tagged-template@@ -1369,8 +1378,9 @@ export class PostgresEngine implements BrainEngine {// for back-compat with internal callers. The `deleted_at IS NULL`// filter excludes soft-deleted rows (v0.26.5) from fuzzy candidates// — they're not legitimate match targets for a remote `get_page`.- const sources = opts?.sourceIds ?? null;+ const sources = opts?.sourceIds?.length ? opts.sourceIds : null;const scalar = opts?.sourceId ?? null;+ const privacy = opts?.excludePrivate ? sql.unsafe(` AND ${privatePagesFilterFragment('pages')}`) : sql``;const scopeFragment = sources? sql` AND source_id = ANY(${sources}::text[])`: scalar@@ -1378,14 +1388,14 @@ export class PostgresEngine implements BrainEngine {: sql``;// Try exact match first- const exact = await sql`SELECT slug FROM pages WHERE slug = ${partial} AND deleted_at IS NULL${scopeFragment}`;+ const exact = await sql`SELECT slug FROM pages WHERE slug = ${partial} AND deleted_at IS NULL${scopeFragment}${privacy}`;if (exact.length > 0) return [exact[0].slug];// Fuzzy match via pg_trgmconst fuzzy = await sql`SELECT slug, similarity(title, ${partial}) AS simFROM pages- WHERE deleted_at IS NULL AND (title % ${partial} OR slug ILIKE ${'%' + partial + '%'})${scopeFragment}+ WHERE deleted_at IS NULL AND (title % ${partial} OR slug ILIKE ${'%' + partial + '%'})${scopeFragment}${privacy}ORDER BY sim DESCLIMIT 5`;@@ -1508,7 +1518,7 @@ export class PostgresEngine implements BrainEngine {// archived sources. Joined `sources s` lets the predicate compile to a// column lookup. NOT bypassed by detail=high — soft-delete is a contract,// not a temporal preference.- const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();@@ -1621,10 +1631,11 @@ export class PostgresEngine implements BrainEngine {const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();+ const titleVector = requiresSafeChunks(opts) ? `to_tsvector('${ftsLang}', COALESCE(p.title, ''))` : 'p.search_vector';const params: unknown[] = [boundWebsearchQuery(query)];let typeClause = '';@@ -1686,7 +1697,7 @@ export class PostgresEngine implements BrainEngine {COALESCE(rep.chunk_index, 0) as chunk_index,COALESCE(rep.chunk_text, '') as chunk_text,COALESCE(rep.chunk_source, 'compiled_truth') as chunk_source,- ts_rank_cd(p.search_vector, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,+ ts_rank_cd(${titleVector}, websearch_to_tsquery('${ftsLang}', $1)) * ${sourceFactorCase} AS score,false AS staleFROM pages pJOIN sources s ON s.id = p.source_id@@ -1699,7 +1710,7 @@ export class PostgresEngine implements BrainEngine {ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASCLIMIT 1) rep ON true- WHERE p.search_vector @@ websearch_to_tsquery('${ftsLang}', $1)+ WHERE ${titleVector} @@ websearch_to_tsquery('${ftsLang}', $1)${typeClause}${typesClause}${excludeSlugsClause}@@ -1837,7 +1848,7 @@ export class PostgresEngine implements BrainEngine {const offsetParam = `$${params.length}`;// v0.26.5: visibility filter for searchKeywordChunks (anchor primitive).- const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();@@ -2019,7 +2030,7 @@ export class PostgresEngine implements BrainEngine {// sees the same row count it always did. Pulling the predicate to the// outer SELECT would force the HNSW scan to over-fetch and post-filter,// wasting candidate slots on hidden rows.- const visibilityClause = buildVisibilityClause('p', 's', { excludePrivate: opts?.excludePrivate === true });+ const visibilityClause = buildVisibilityClause('p', 's', opts);// v0.36 Phase 3: 'embedding_multimodal' is the unified column populated// by `gbrain reindex --multimodal`. Carries BOTH text and image content@@ -2243,23 +2254,34 @@ export class PostgresEngine implements BrainEngine {// Chunksasync upsertChunks(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn } & BatchOpts): Promise<void> {- return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal, () => this._upsertChunksOnce(slug, chunks, opts), chunks.length);+ if (this._chunkWritesInTransaction) return this._upsertChunksOnce(slug, chunks, opts);+ return this.batchRetry(opts?.auditSite ?? 'upsertChunks', opts?.signal,+ () => this.transaction(tx => (tx as PostgresEngine)._upsertChunksOnce(slug, chunks, opts)), chunks.length);}private async _upsertChunksOnce(slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn }): Promise<void> {// Normalize the same way putPage does — pages.slug is stored lowercased,// so a raw mixed-case slug here would miss the row it just wrote (#430).slug = validateSlug(slug);+ // Compare and persist the same canonical body bytes. JSONB rejects raw+ // NUL/lone surrogates before the INSERT can sanitize them; identity fields+ // remain untouched so malformed identifiers still reject the transaction.+ chunks = chunks.map(chunk => ({ ...chunk, chunk_text: sanitizeText(chunk.chunk_text) }));const sql = this.sql;const sourceId = opts?.sourceId ?? 'default';// Source-scope the page-id lookup. Without this filter, multi-source// brains where the slug exists in 2+ sources return >1 row and the// chunk replacement targets the wrong page (or fans out across pages).- const pages = await sql`SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId}`;+ const pages = await sql`SELECT id FROM pages WHERE slug = ${slug} AND source_id = ${sourceId} FOR UPDATE`;if (pages.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);const pageId = pages[0].id;+ // A fragment write cannot certify the full-body fence boundary. Import seals+ // only after its complete replacement succeeds in the same transaction.+ const invalidation = chunkWriteInvalidation(pageId, chunks);+ await sql.unsafe(invalidation.sql, invalidation.params as never[]);+// Remove chunks that no longer exist (chunk_index beyond new count)const newIndices = chunks.map(c => c.chunk_index);if (newIndices.length > 0) {@@ -2380,11 +2402,9 @@ export class PostgresEngine implements BrainEngine {`$${paramIdx++}, ${embeddingImagePh})`,);- // NUL/lone-surrogate cleanup ONCE into a local shared by BOTH binds:- // the md5() embedded_text_hash input and the stored chunk_text must see- // the same bytes, or the hash diverges from the sanitized stored text- // (and the raw NUL would still abort the INSERT via the md5 param).- const sanitizedChunkText = sanitizeText(chunk.chunk_text);+ // Already normalized before the seal snapshot. Both storage and the+ // embedded_text_hash input must use those same canonical bytes.+ const sanitizedChunkText = chunk.chunk_text;// Param push order MUST match placeholder allocation order.if (embeddingStr) params.push(embeddingStr);if (embeddingImageStr) params.push(embeddingImageStr);@@ -2481,7 +2501,7 @@ export class PostgresEngine implements BrainEngine {);}- async getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean }): Promise<Chunk[]> {+ async getChunks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean }): Promise<Chunk[]> {const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;const scalarSourceId = opts?.sourceId ?? 'default';// S2: embedding_is_null reports the registry-ACTIVE column's truth —@@ -2513,6 +2533,8 @@ export class PostgresEngine implements BrainEngine {FROM content_chunks ccJOIN pages p ON p.id = cc.page_idWHERE p.slug = ${slug} AND ${scope}+ ${opts?.excludePrivate ? tx.unsafe(`AND ${privatePagesFilterFragment('p')}`) : tx``}+ ${requiresSafeChunks(opts) ? tx.unsafe(`AND ${safeChunksFilter('p')}`) : tx``}ORDER BY cc.chunk_index`;return rows.map((r: Record<string, unknown>) => rowToChunk(r, includeEmbedding));@@ -3138,7 +3160,8 @@ export class PostgresEngine implements BrainEngine {}}- async getLinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<Link[]> {+ async getLinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {+ const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';// Two layers of defense (see getPage for the full pattern):// 1. RLS scope binding (opt-in via GBRAIN_RLS_SCOPE_BINDING)// 2. App-layer source filter (#2200 federated)@@ -3161,7 +3184,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[])WHERE f.slug = ${slug} AND f.source_id = ANY(${ids}::text[]) AND t.source_id = ANY(${ids}::text[])- AND f.deleted_at IS NULL AND t.deleted_at IS NULL+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${tx.unsafe(privacy)}`;return rows as unknown as Link[];}@@ -3184,7 +3207,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE f.slug = ${slug} AND f.source_id = ${opts.sourceId}- AND f.deleted_at IS NULL AND t.deleted_at IS NULL+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${tx.unsafe(privacy)}`;return rows as unknown as Link[];}@@ -3199,13 +3222,14 @@ export class PostgresEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE f.slug = ${slug}- AND f.deleted_at IS NULL AND t.deleted_at IS NULL+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${tx.unsafe(privacy)}`;return rows as unknown as Link[];});}- async getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<Link[]> {+ async getBacklinks(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<Link[]> {+ const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';// Two layers of defense (see getPage for the full pattern):// 1. RLS scope binding (opt-in via GBRAIN_RLS_SCOPE_BINDING)// 2. App-layer source filter (#2200 federated)@@ -3226,7 +3250,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_id AND o.source_id = ANY(${ids}::text[])WHERE t.slug = ${slug} AND t.source_id = ANY(${ids}::text[]) AND f.source_id = ANY(${ids}::text[])- AND f.deleted_at IS NULL AND t.deleted_at IS NULL+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${tx.unsafe(privacy)}`;return rows as unknown as Link[];}@@ -3244,7 +3268,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE t.slug = ${slug} AND t.source_id = ${opts.sourceId}- AND f.deleted_at IS NULL AND t.deleted_at IS NULL+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${tx.unsafe(privacy)}`;return rows as unknown as Link[];}@@ -3259,7 +3283,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages t ON t.id = l.to_page_idLEFT JOIN pages o ON o.id = l.origin_page_idWHERE t.slug = ${slug}- AND f.deleted_at IS NULL AND t.deleted_at IS NULL+ AND f.deleted_at IS NULL AND t.deleted_at IS NULL ${tx.unsafe(privacy)}`;return rows as unknown as Link[];});@@ -3348,6 +3372,8 @@ export class PostgresEngine implements BrainEngine {opts?: import('./engine.ts').TraverseGraphOpts,): Promise<GraphNode[]> {const sql = this.sql;+ const privacy = (page: string, link?: string) => opts?.excludePrivate+ ? sql.unsafe(`AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}`) : sql``;// v0.34.1 (#861 — P0 leak seal): scope visited nodes to the caller's// source(s). Without this, the walk follows edges into pages from// foreign sources, leaking topology + page metadata. The filter@@ -3386,7 +3412,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < ${depth}AND NOT (p2.id = ANY(g.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${stepScope}ORDER BY p2.slug ASC, p2.id ASCLIMIT ${cap})`@@ -3396,13 +3422,13 @@ export class PostgresEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE g.depth < ${depth}AND NOT (p2.id = ANY(g.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}${stepScope}`;// Cycle prevention: visited array tracks page IDs already in the path.const rows = await sql`WITH RECURSIVE graph AS (SELECT p.id, p.slug, p.title, p.type, 0 as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALL@@ -3420,7 +3446,7 @@ export class PostgresEngine implements BrainEngine {(SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type))FROM links l2JOIN pages p3 ON p3.id = l2.to_page_id- WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${aggScope}),+ WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL ${privacy('p3', 'l2')} ${aggScope}),'[]'::jsonb) as linksFROM graph g@@ -3444,16 +3470,18 @@ export class PostgresEngine implements BrainEngine {async traversePaths(slug: string,- opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[] },+ opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },): Promise<GraphPath[]> {return (await this.traversePathsDetailed(slug, opts)).paths;}async traversePathsDetailed(slug: string,- opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[] },+ opts?: { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both'; sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },): Promise<{ paths: GraphPath[]; truncated: boolean }> {const sql = this.sql;+ const privacy = (page: string, link?: string) => opts?.excludePrivate+ ? sql.unsafe(`AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}`) : sql``;const depth = opts?.depth ?? 5;const direction = opts?.direction ?? 'out';const linkType = opts?.linkType ?? null;@@ -3494,7 +3522,7 @@ export class PostgresEngine implements BrainEngine {rows = await sql`WITH RECURSIVE walk AS (SELECT p.id, p.slug, 0::int as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALLSELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.idFROM walk w@@ -3502,7 +3530,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.to_page_idWHERE w.depth < ${depth}AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope})@@ -3512,7 +3540,7 @@ export class PostgresEngine implements BrainEngine {JOIN links l ON l.from_page_id = w.idJOIN pages p2 ON p2.id = l.to_page_idWHERE w.depth < ${depth}- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope}ORDER BY depth, from_slug, to_slug@@ -3522,7 +3550,7 @@ export class PostgresEngine implements BrainEngine {rows = await sql`WITH RECURSIVE walk AS (SELECT p.id, p.slug, 0::int as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALLSELECT p2.id, p2.slug, w.depth + 1, w.visited || p2.idFROM walk w@@ -3530,7 +3558,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages p2 ON p2.id = l.from_page_idWHERE w.depth < ${depth}AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope})@@ -3540,7 +3568,7 @@ export class PostgresEngine implements BrainEngine {JOIN links l ON l.to_page_id = w.idJOIN pages p2 ON p2.id = l.from_page_idWHERE w.depth < ${depth}- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope}ORDER BY depth, from_slug, to_slug@@ -3550,7 +3578,7 @@ export class PostgresEngine implements BrainEngine {rows = await sql`WITH RECURSIVE walk AS (SELECT p.id, 0::int as depth, ARRAY[p.id] as visited- FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${seedScope}+ FROM pages p WHERE p.slug = ${slug} AND p.deleted_at IS NULL ${privacy('p')} ${seedScope}UNION ALLSELECT p2.id, w.depth + 1, w.visited || p2.idFROM walk w@@ -3558,7 +3586,7 @@ export class PostgresEngine implements BrainEngine {JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id ENDWHERE w.depth < ${depth}AND NOT (p2.id = ANY(w.visited))- AND p2.deleted_at IS NULL+ AND p2.deleted_at IS NULL ${privacy('p2', 'l')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${stepScope})@@ -3569,8 +3597,8 @@ export class PostgresEngine implements BrainEngine {JOIN pages pf ON pf.id = l.from_page_idJOIN pages pt ON pt.id = l.to_page_idWHERE w.depth < ${depth}- AND pf.deleted_at IS NULL- AND pt.deleted_at IS NULL+ AND pf.deleted_at IS NULL ${privacy('pf', 'l')}+ AND pt.deleted_at IS NULL ${privacy('pt')}AND (${!linkTypeMatches} OR l.link_type = ${linkType ?? ''})${pfScope}${ptScope}@@ -3605,212 +3633,23 @@ export class PostgresEngine implements BrainEngine {seeds: string[],opts?: import('./types.ts').RelationalFanoutOpts,): Promise<import('./types.ts').RelationalFanoutRow[]> {- if (!seeds || seeds.length === 0) return [];- const sql = this.sql;- const depth = Math.min(Math.max(1, opts?.depth ?? 2), 3);- const direction = opts?.direction ?? 'both';- const limit = Math.min(Math.max(1, opts?.limit ?? 50), 200);- const types = opts?.linkTypes && opts.linkTypes.length > 0 ? opts.linkTypes : null;-- // Scope is applied to SEED selection only. Within-source traversal is- // enforced separately by `p2.source_id = w.seed_source` in the recursive- // step, so a walk can never cross a source boundary even when several- // sources are in scope.- const useSourceIds = opts?.sourceIds && opts.sourceIds.length > 0;- const seedScope = useSourceIds- ? sql`AND p.source_id = ANY(${opts!.sourceIds!}::text[])`- : opts?.sourceId- ? sql`AND p.source_id = ${opts.sourceId}`- : sql``;- const typeFilter = types ? sql`AND l.link_type = ANY(${types}::text[])` : sql``;- const mentionsFilter = opts?.includeMentions- ? sql``- : sql`AND l.link_source IS DISTINCT FROM 'mentions'`;-- // Recursive step join differs by direction; everything else is shared.- const recurStep =- direction === 'out'- ? sql`JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id`- : direction === 'in'- ? sql`JOIN links l ON l.to_page_id = w.id JOIN pages p2 ON p2.id = l.from_page_id`- : sql`JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id)- JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END`;-- const rows = await sql`- WITH RECURSIVE walk AS (- SELECT p.id, p.slug, p.source_id, 0::int AS depth,- ARRAY[p.id] AS visited, ARRAY[p.slug] AS path,- p.source_id AS seed_source, NULL::text AS last_link_type- FROM pages p- WHERE p.slug = ANY(${seeds}::text[]) ${seedScope} AND p.deleted_at IS NULL- UNION ALL- SELECT p2.id, p2.slug, p2.source_id, w.depth + 1,- w.visited || p2.id, w.path || p2.slug,- w.seed_source, l.link_type- FROM walk w- ${recurStep}- WHERE w.depth < ${depth}- AND NOT (p2.id = ANY(w.visited))- AND p2.source_id = w.seed_source- AND p2.deleted_at IS NULL- ${mentionsFilter}- ${typeFilter}- )- SELECT n.source_id, n.slug,- MIN(n.depth) AS hop,- COUNT(DISTINCT n.last_link_type) AS edge_count,- array_agg(DISTINCT n.last_link_type)- FILTER (WHERE n.last_link_type IS NOT NULL) AS via_link_types,- -- Final path tie-break (lexicographic) makes the pick deterministic- -- when a node is reachable at the same depth from multiple seeds;- -- without it the winner is plan/heap-order dependent and the two- -- engines (or two runs) can disagree. Relational retrieval is- -- documented deterministic; keep in lockstep with pglite-engine.ts.- (array_agg(array_to_string(n.path, chr(9))- ORDER BY n.depth ASC, array_length(n.path, 1) ASC,- array_to_string(n.path, chr(9)) ASC))[1] AS path_str,- (SELECT cc.id FROM content_chunks cc- WHERE cc.page_id = n.id ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_id- FROM walk n- WHERE n.depth > 0- GROUP BY n.source_id, n.slug, n.id- ORDER BY hop ASC, edge_count DESC, n.source_id ASC, n.slug ASC- LIMIT ${limit}- `;-- return (rows as Record<string, unknown>[]).map(r => ({- source_id: r.source_id as string,- slug: r.slug as string,- hop: Number(r.hop),- edge_count: Number(r.edge_count),- via_link_types: Array.isArray(r.via_link_types) ? (r.via_link_types as string[]) : [],- path: r.path_str ? String(r.path_str).split('\t') : [],- canonical_chunk_id: r.canonical_chunk_id == null ? null : Number(r.canonical_chunk_id),- }));+ return readRelationalFanout(this.executeRaw.bind(this), seeds, opts);}- async getBacklinkCounts(pageIds: number[]): Promise<Map<number, number>> {- const result = new Map<number, number>();- if (pageIds.length === 0) return result;- for (const id of pageIds) result.set(id, 0);-- // v0.41.18.0 D12: filter mentions OUT of backlink-count for search- // ranking. `link_source='mentions'` rows are auto-linked body-text- // mentions from `gbrain extract links --by-mention`; they're- // graph-completeness signal, NOT human-intent signal. Counting them- // toward backlinks would shift search ranking globally on first- // --by-mention run, boosting popular-mention pages over intentional-- // backlink pages. `IS DISTINCT FROM` is NULL-safe so legacy rows with- // NULL link_source still count (NULL != 'mentions' → row included).- // #4380: keyed by p.id, not slug — grouping by bare slug summed every- // namesake's backlinks across sources, boosting zero-backlink pages.- const sql = this.sql;- const rows = await sql`- SELECT p.id as page_id, COUNT(l.id)::int as cnt- FROM pages p- LEFT JOIN links l ON l.to_page_id = p.id- AND l.link_source IS DISTINCT FROM 'mentions'- WHERE p.id = ANY(${pageIds}::int[])- GROUP BY p.id- `;- for (const r of rows as unknown as { page_id: number; cnt: number }[]) {- result.set(Number(r.page_id), Number(r.cnt));- }- return result;+ async getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>> {+ return readBacklinkCounts(this.executeRaw.bind(this), pageIds, opts);}- async getAdjacencyBoosts(pageIds: number[]): Promise<Map<number, import('./types.ts').AdjacencyRow>> {- const result = new Map<number, import('./types.ts').AdjacencyRow>();- if (pageIds.length === 0) return result;-- const sql = this.sql;- // SQL contract: see BrainEngine.getAdjacencyBoosts JSDoc. Both ANY- // filters restrict the scan to the input set's induced subgraph,- // which keeps cross-source leakage impossible by construction.- // cross_source_hits uses COALESCE so NULL source_id rows behave as- // 'default' and don't silently disappear from the count.- //- // Defense-in-depth (codex outside-voice review): deleted_at IS NULL- // on both join sides so a soft-deleted page in the input set- // (theoretically possible if a future caller bypasses hybridSearch's- // visibility filter) can't contribute to hits or cross_source_hits.- // Matches the v0.35.5.0 findOrphanPages fix pattern.- const rows = await sql`- WITH targets AS (- SELECT id, COALESCE(source_id, 'default') AS source_id- FROM pages- WHERE id = ANY(${pageIds}::int[])- AND deleted_at IS NULL- )- SELECT- l.to_page_id AS to_page_id,- COUNT(DISTINCT l.from_page_id)::int AS hits,- COUNT(DISTINCT- CASE WHEN COALESCE(p.source_id, 'default') <> t.source_id- THEN COALESCE(p.source_id, 'default') END- )::int AS cross_source_hits- FROM links l- JOIN pages p ON p.id = l.from_page_id AND p.deleted_at IS NULL- JOIN targets t ON t.id = l.to_page_id- WHERE l.from_page_id = ANY(${pageIds}::int[])- AND l.to_page_id = ANY(${pageIds}::int[])- GROUP BY l.to_page_id- HAVING COUNT(DISTINCT l.from_page_id) >= 1- `;- for (const r of rows as unknown as { to_page_id: number; hits: number; cross_source_hits: number }[]) {- result.set(Number(r.to_page_id), {- hits: Number(r.hits),- cross_source_hits: Number(r.cross_source_hits),- });- }- return result;+ async getAdjacencyBoosts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, import('./types.ts').AdjacencyRow>> {+ return readAdjacencyBoosts(this.executeRaw.bind(this), pageIds, opts);}- async getContentFlagsByPageIds(- pageIds: number[],- ): Promise<Map<number, { reason: string; detail: string }>> {- const result = new Map<number, { reason: string; detail: string }>();- if (pageIds.length === 0) return result;- const sql = this.sql;- const rows = await sql`- SELECT id,- frontmatter -> 'content_flag' ->> 'reason' AS reason,- frontmatter -> 'content_flag' ->> 'detail' AS detail- FROM pages- WHERE id = ANY(${pageIds}::int[])- AND frontmatter ? 'content_flag'- `;- for (const r of rows as unknown as { id: number; reason: string | null; detail: string | null }[]) {- if (!r.reason) continue;- result.set(Number(r.id), { reason: r.reason, detail: r.detail ?? '' });- }- return result;+ async getContentFlagsByPageIds(pageIds: number[], opts?: PageReadScope): Promise<Map<number, { reason: string; detail: string }>> {+ return readContentFlags(this.executeRaw.bind(this), pageIds, opts);}- async getUnverifiedExtractionPageIds(- pageIds: number[],- ): Promise<Map<number, { unverified: boolean; status: string }>> {- const result = new Map<number, { unverified: boolean; status: string }>();- if (pageIds.length === 0) return result;- const sql = this.sql;- // Quarantine predicate is the shared unverifiedExtractionFragment (issue- // #160) so this query and the SQL-side source-boost guard can never- // drift. #4220 widened the projection: any page with a frontmatter- // `status` value is returned (draft/superseded/restricted/... surface on- // SearchResult.status); the fragment match stays the quarantine flag.- const rows = await sql.unsafe(- `SELECT id,- (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') AS status,- (${unverifiedExtractionFragment('pages')}) AS unverified- FROM pages- WHERE id = ANY($1::int[])- AND (COALESCE(frontmatter, '{}'::jsonb) ->> 'status') IS NOT NULL`,- [pageIds] as never,- );- for (const r of rows as unknown as { id: number; status: string; unverified: boolean }[]) {- result.set(Number(r.id), { unverified: r.unverified === true, status: r.status });- }- return result;+ async getUnverifiedExtractionPageIds(pageIds: number[], opts?: PageReadScope): Promise<Map<number, { unverified: boolean; status: string }>> {+ return readExtractionStates(this.executeRaw.bind(this), pageIds, opts);}async getPageTimestamps(slugs: string[]): Promise<Map<string, Date>> {@@ -3823,59 +3662,18 @@ export class PostgresEngine implements BrainEngine {return new Map(rows.map(r => [r.slug as string, new Date(r.ts as string)]));}- async getEffectiveDates(refs: Array<{slug: string; source_id: string}>): Promise<Map<string, Date>> {- if (refs.length === 0) return new Map();- const sql = this.sql;- const slugs = refs.map(r => r.slug);- const sourceIds = refs.map(r => r.source_id);- // Composite-keyed: a page is unique by (source_id, slug). unnest the- // two arrays in lockstep so multi-source brains don't fan out across- // sources (codex pass-1 finding #3).- const rows = await sql`- SELECT p.slug, p.source_id, COALESCE(p.effective_date, p.updated_at, p.created_at) AS ts- FROM pages p- JOIN unnest(${slugs}::text[], ${sourceIds}::text[]) AS u(slug, source_id)- ON p.slug = u.slug AND p.source_id = u.source_id- `;- const out = new Map<string, Date>();- for (const raw of rows as unknown as Array<Record<string, unknown>>) {- const r = raw as { slug: string; source_id: string; ts: string | Date };- const key = `${r.source_id}::${r.slug}`;- out.set(key, r.ts instanceof Date ? r.ts : new Date(r.ts));- }- return out;+ async getEffectiveDates(refs: Array<{slug: string; source_id: string}>, opts?: PageReadScope): Promise<Map<string, Date>> {+ return readEffectiveDates(this.executeRaw.bind(this), refs, opts);}- async getSalienceScores(refs: Array<{slug: string; source_id: string}>): Promise<Map<string, number>> {- if (refs.length === 0) return new Map();- const sql = this.sql;- const slugs = refs.map(r => r.slug);- const sourceIds = refs.map(r => r.source_id);- // Salience = emotional_weight × 5 + ln(1 + take_count). Pure mattering- // signal — NO time component (per D9: salience and recency are- // orthogonal axes). Composite-keyed for multi-source isolation.- const rows = await sql`- SELECT p.slug, p.source_id,- (COALESCE(p.emotional_weight, 0) * 5- + ln(1 + COUNT(DISTINCT t.id))) AS score- FROM pages p- JOIN unnest(${slugs}::text[], ${sourceIds}::text[]) AS u(slug, source_id)- ON p.slug = u.slug AND p.source_id = u.source_id- LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE- GROUP BY p.id- `;- const out = new Map<string, number>();- for (const raw of rows as unknown as Array<Record<string, unknown>>) {- const r = raw as { slug: string; source_id: string; score: number | string };- const key = `${r.source_id}::${r.slug}`;- out.set(key, Number(r.score));- }- return out;+ async getSalienceScores(refs: Array<{slug: string; source_id: string}>, opts?: PageReadPolicy): Promise<Map<string, number>> {+ return readSalienceScores(this.executeRaw.bind(this), refs, opts);}async findOrphanPages(opts?: {sourceId?: string;sourceIds?: string[];+ excludePrivate?: boolean;mode?: 'inbound' | 'islanded';}): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }>> {const sql = this.sql;@@ -3907,7 +3705,7 @@ export class PostgresEngine implements BrainEngine {FROM links lJOIN pages tgt ON tgt.id = l.to_page_idWHERE l.from_page_id = p.id- AND tgt.deleted_at IS NULL+ AND tgt.deleted_at IS NULL ${opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('tgt')} AND ${privateLinkOriginFilterFragment('l')}`) : sql``})`: sql``;const rows = await sql`@@ -3918,14 +3716,14 @@ export class PostgresEngine implements BrainEngine {p.type,(NOT ${sql.unsafe(QUARANTINE_FILTER_FRAGMENT)}) AS quarantinedFROM pages p- WHERE p.deleted_at IS NULL+ WHERE p.deleted_at IS NULL ${opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``}${sourceFilter}AND NOT EXISTS (SELECT 1FROM links lJOIN pages src ON src.id = l.from_page_idWHERE l.to_page_id = p.id- AND src.deleted_at IS NULL+ AND src.deleted_at IS NULL ${opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('src')} AND ${privateLinkOriginFilterFragment('l')}`) : sql``})${outboundFilter}ORDER BY p.slug@@ -4069,6 +3867,8 @@ export class PostgresEngine implements BrainEngine {const rows = await sql`SELECT te.* FROM timeline_entries te JOIN pages p ON p.id = te.page_idWHERE p.slug = ${slug} ${sourceCond} ${afterCond} ${beforeCond}+ ${opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}+ AND ${privateTimelineEventFilterFragment('te')}`) : sql``}ORDER BY te.date DESC LIMIT ${limit}`;return rows as unknown as TimelineEntry[];}@@ -4079,12 +3879,15 @@ export class PostgresEngine implements BrainEngine {// doctor); order by COALESCE(event effective_date, date) for intra-day// sequence. Source scope: federated sourceIds[] > scalar sourceId > unscoped.// ep=true: the ep LEFT JOIN carries the same scope so out-of-scope event fields null out (#2200 origin-join shape).- private chronicleSourceCond(opts?: { sourceId?: string; sourceIds?: string[] }, ep = false) {+ private chronicleSourceCond(opts?: PageReadScope, ep = false) {const sql = this.sql;+ const privacy = opts?.excludePrivate && !ep+ ? sql.unsafe(`AND ${privatePagesFilterFragment('p')} AND ${privateTimelineEventFilterFragment('te')}`)+ : sql``;if (opts?.sourceIds && opts.sourceIds.length > 0)- return ep ? sql`AND ep.source_id = ANY(${opts.sourceIds}::text[])` : sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`;- if (opts?.sourceId) return ep ? sql`AND ep.source_id = ${opts.sourceId}` : sql`AND p.source_id = ${opts.sourceId}`;- return sql``;+ return ep ? sql`AND ep.source_id = ANY(${opts.sourceIds}::text[])` : sql`AND p.source_id = ANY(${opts.sourceIds}::text[]) ${privacy}`;+ if (opts?.sourceId) return ep ? sql`AND ep.source_id = ${opts.sourceId}` : sql`AND p.source_id = ${opts.sourceId} ${privacy}`;+ return privacy;}async getTimelineForDate(date: string, opts?: ChronicleTimelineOpts): Promise<ChronicleTimelineRow[]> {@@ -4132,7 +3935,7 @@ export class PostgresEngine implements BrainEngine {return rows as unknown as ChronicleTimelineRow[];}- async getOnThisDay(opts?: { date?: string; limit?: number; sourceId?: string; sourceIds?: string[] }): Promise<ChronicleTimelineRow[]> {+ async getOnThisDay(opts?: PageReadScope & { date?: string; limit?: number }): Promise<ChronicleTimelineRow[]> {const sql = this.sql;const limit = opts?.limit ?? 50;const target = opts?.date ? sql`${opts.date}::date` : sql`current_date`;@@ -4155,7 +3958,7 @@ export class PostgresEngine implements BrainEngine {return rows as unknown as ChronicleTimelineRow[];}- async getLastSeen(entitySlug: string, opts?: { asof?: string; sourceId?: string; sourceIds?: string[] }): Promise<LastSeenResult> {+ async getLastSeen(entitySlug: string, opts?: PageReadScope & { asof?: string }): Promise<LastSeenResult> {const sql = this.sql;// "Seen" = the entity's own page has a timeline row, OR an event's `who`// array references the entity (exact slug or wikilink-substring match).@@ -4369,35 +4172,36 @@ export class PostgresEngine implements BrainEngine {async getRawData(slug: string,source?: string,- opts?: { sourceId?: string; sourceIds?: string[] },+ opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },): Promise<RawData[]> {const sql = this.sql;+ const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``;const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;const sourceId = sourceIds ? undefined : opts?.sourceId;let rows;if (source && sourceIds) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id+ JOIN pages p ON p.id = rd.page_id ${privacy}WHERE p.slug = ${slug} AND rd.source = ${source} AND p.source_id = ANY(${sourceIds}::text[])`;} else if (sourceIds) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id+ JOIN pages p ON p.id = rd.page_id ${privacy}WHERE p.slug = ${slug} AND p.source_id = ANY(${sourceIds}::text[])`;} else if (source && sourceId) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id+ JOIN pages p ON p.id = rd.page_id ${privacy}WHERE p.slug = ${slug} AND rd.source = ${source} AND p.source_id = ${sourceId}`;} else if (source) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id+ JOIN pages p ON p.id = rd.page_id ${privacy}WHERE p.slug = ${slug} AND rd.source = ${source}`;} else if (sourceId) {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id+ JOIN pages p ON p.id = rd.page_id ${privacy}WHERE p.slug = ${slug} AND p.source_id = ${sourceId}`;} else {rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd- JOIN pages p ON p.id = rd.page_id+ JOIN pages p ON p.id = rd.page_id ${privacy}WHERE p.slug = ${slug}`;}return rows as unknown as RawData[];@@ -4837,13 +4641,16 @@ export class PostgresEngine implements BrainEngine {return rows[0] as unknown as PageVersion;}- async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[] }): Promise<PageVersion[]> {+ async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {const sql = this.sql;+ const privacy = opts?.excludePrivate+ ? sql.unsafe(`AND ${privatePagesFilterFragment('p')} AND ${privatePagesFilterFragment('pv')}`) : sql``;if (opts?.sourceIds && opts.sourceIds.length > 0) {const rows = await sql`SELECT pv.* FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = ${slug} AND p.source_id = ANY(${opts.sourceIds}::text[])+ ${privacy}ORDER BY pv.snapshot_at DESC`;return rows as unknown as PageVersion[];@@ -4853,6 +4660,7 @@ export class PostgresEngine implements BrainEngine {SELECT pv.* FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = ${slug} AND p.source_id = ${opts.sourceId}+ ${privacy}ORDER BY pv.snapshot_at DESC`;return rows as unknown as PageVersion[];@@ -4861,6 +4669,7 @@ export class PostgresEngine implements BrainEngine {SELECT pv.* FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = ${slug}+ ${privacy}ORDER BY pv.snapshot_at DESC`;return rows as unknown as PageVersion[];@@ -4880,6 +4689,7 @@ export class PostgresEngine implements BrainEngine {UPDATE pages SETcompiled_truth = pv.compiled_truth,frontmatter = pv.frontmatter,+ chunker_version = ${sql.unsafe(bodyWriteChunkVersion('pv.compiled_truth', 'pages.timeline'))},updated_at = now()FROM page_versions pvWHERE pages.slug = ${slug} AND pages.source_id = ${opts.sourceId}@@ -4891,6 +4701,7 @@ export class PostgresEngine implements BrainEngine {UPDATE pages SETcompiled_truth = pv.compiled_truth,frontmatter = pv.frontmatter,+ chunker_version = ${sql.unsafe(bodyWriteChunkVersion('pv.compiled_truth', 'pages.timeline'))},updated_at = now()FROM page_versions pvWHERE pages.slug = ${slug} AND pv.id = ${versionId} AND pv.page_id = pages.id@@ -5235,23 +5046,26 @@ export class PostgresEngine implements BrainEngine {async resolveSlugWithAlias(slug: string,sourceOrSources: string | readonly string[],+ opts?: { excludePrivate?: boolean },): Promise<string> {- return (await this.resolveSlugWithAliasDetailed(slug, sourceOrSources))?.canonical_slug ?? slug;+ return (await this.resolveSlugWithAliasDetailed(slug, sourceOrSources, opts))?.canonical_slug ?? slug;}async resolveSlugWithAliasDetailed(slug: string,sourceOrSources: string | readonly string[],+ opts?: { excludePrivate?: boolean },): Promise<{ canonical_slug: string; source_id: string } | null> {const sql = this.sql;const sources = Array.isArray(sourceOrSources) ? sourceOrSources : [sourceOrSources];if (sources.length === 0) return null;+ const privacy = opts?.excludePrivate ? sql.unsafe(`AND EXISTS (SELECT 1 FROM pages p WHERE p.slug = slug_aliases.canonical_slug AND p.source_id = slug_aliases.source_id AND p.deleted_at IS NULL AND ${privatePagesFilterFragment('p')})`) : sql``;try {const rows = await sql`SELECT canonical_slug, source_idFROM slug_aliasesWHERE alias_slug = ${slug}- AND source_id = ANY(${sources}::text[])+ AND source_id = ANY(${sources}::text[]) ${privacy}ORDER BY array_position(${sources}::text[], source_id), id`;if (rows.length === 0) return null;@@ -5272,37 +5086,9 @@ export class PostgresEngine implements BrainEngine {async resolveAliases(aliasNorms: string[],- opts?: { sourceId?: string; sourceIds?: string[] },+ opts?: PageReadScope,): Promise<Map<string, Array<{ slug: string; source_id: string }>>> {- const out = new Map<string, Array<{ slug: string; source_id: string }>>();- if (!aliasNorms || aliasNorms.length === 0) return out;- const sql = this.sql;- const sources =- opts?.sourceIds && opts.sourceIds.length > 0- ? opts.sourceIds- : opts?.sourceId- ? [opts.sourceId]- : null;- const rows = sources- ? await sql`- SELECT alias_norm, slug, source_id- FROM page_aliases- WHERE alias_norm = ANY(${aliasNorms}::text[])- AND source_id = ANY(${sources}::text[])- ORDER BY alias_norm, source_id, slug`- : await sql`- SELECT alias_norm, slug, source_id- FROM page_aliases- WHERE alias_norm = ANY(${aliasNorms}::text[])- ORDER BY alias_norm, source_id, slug`;- for (const r of rows) {- const a = r.alias_norm as string;- const list = out.get(a) ?? [];- const ref = { slug: r.slug as string, source_id: r.source_id as string };- if (!list.some(x => x.slug === ref.slug && x.source_id === ref.source_id)) list.push(ref);- out.set(a, list);- }- return out;+ return readAliases(this.executeRaw.bind(this), aliasNorms, opts);}async setPageAliases(slug: string, sourceId: string, aliasNorms: string[]): Promise<void> {diff --git a/src/core/postgres-engine/salience.ts b/src/core/postgres-engine/salience.tsindex b73b13084b..c1253b8e6f 100644--- a/src/core/postgres-engine/salience.ts+++ b/src/core/postgres-engine/salience.ts@@ -1,3 +1,4 @@+import { pageReadFilter } from '../search/read-policy-sql.ts';/*** v0.29 — Salience + Anomaly Detection, peeled out of PostgresEngine* (containment sprint C15). Free functions over a NARROW deps surface —@@ -153,20 +154,27 @@ export async function getRecentSalience(deps: PgSalienceDeps, opts: SalienceOptsfallback: { halflifeDays: 1, coefficient: 1.0 },});}+ const restricted = opts.takesHoldersAllowList !== undefined;+ const emotionalSql = restricted ? '0' : 'p.emotional_weight';+ const touchedSql = restricted ? 'p.updated_at' : 'GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at))';+ const holderCondition = restricted ? sql`AND t.holder = ANY(${opts.takesHoldersAllowList!}::text[])` : sql``;+ // Scope is already bound above; use the shared live/privacy predicate+ // before ranking and LIMIT, including for holder-unrestricted callers.+ const readCondition = sql.unsafe(`AND ${pageReadFilter('p', { excludePrivate: opts.excludePrivate }, [], true)}`);const rows = await sql`- SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, p.emotional_weight,+ SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, ${sql.unsafe(emotionalSql)} AS emotional_weight,COUNT(DISTINCT t.id) AS take_count,COALESCE(AVG(t.weight), 0) AS take_avg_weight,- (p.emotional_weight * 5)+ (${sql.unsafe(emotionalSql)} * 5)+ ln(1 + COUNT(DISTINCT t.id))+ ${sql.unsafe(recencySql)}AS scoreFROM pages p- LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE- WHERE GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at)) >= ${boundaryIso}::timestamptz+ LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE ${holderCondition}+ WHERE ${sql.unsafe(touchedSql)} >= ${boundaryIso}::timestamptz${prefixCondition}${excludeBriefings}- ${sourceCondition}+ ${sourceCondition} ${readCondition}GROUP BY p.idORDER BY score DESCLIMIT ${limit}@@ -271,6 +279,9 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):? sql`AND p.source_id = ${opts.sourceId}`: sql``;+ // Baseline keys, baseline counts and current counts must share visibility.+ const readCondition = sql.unsafe(`AND ${pageReadFilter('p', { excludePrivate: opts.excludePrivate }, [], true)}`);+// Tag cohort baseline with day densification + zero-fill (codex C4#6).const tagBaseline = await sql`WITH days AS (@@ -284,7 +295,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_idWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz- ${sourceCondition}+ ${sourceCondition} ${readCondition}),touched AS (SELECT t.tag,@@ -293,7 +304,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM tags t JOIN pages p ON p.id = t.page_idWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz- ${sourceCondition}+ ${sourceCondition} ${readCondition}GROUP BY 1, 2)SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count@@ -313,7 +324,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):SELECT DISTINCT p.type FROM pages pWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz- ${sourceCondition}+ ${sourceCondition} ${readCondition}),touched AS (SELECT p.type,@@ -322,7 +333,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM pages pWHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptzAND p.updated_at < ${sinceDate.toISOString()}::timestamptz- ${sourceCondition}+ ${sourceCondition} ${readCondition}GROUP BY 1, 2)SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count@@ -338,7 +349,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM tags t JOIN pages p ON p.id = t.page_idWHERE p.updated_at >= ${sinceIso}::timestamptzAND p.updated_at < ${sinceEnd.toISOString()}::timestamptz- ${sourceCondition}+ ${sourceCondition} ${readCondition}GROUP BY 1`;const typeToday = await sql`@@ -348,7 +359,7 @@ export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts):FROM pages pWHERE p.updated_at >= ${sinceIso}::timestamptzAND p.updated_at < ${sinceEnd.toISOString()}::timestamptz- ${sourceCondition}+ ${sourceCondition} ${readCondition}GROUP BY 1`;diff --git a/src/core/postgres-engine/takes.ts b/src/core/postgres-engine/takes.tsindex b29ce86109..9b3b39238e 100644--- a/src/core/postgres-engine/takes.ts+++ b/src/core/postgres-engine/takes.ts@@ -23,6 +23,7 @@ import { deriveResolutionTuple, finalizeScorecard } from '../takes-resolution.tsimport { normalizeWeightForStorage } from '../takes-fence.ts';import { buildTakeRows } from '../batch-rows.ts';import { staleTakeRowToRow, takeRowToTake, takeHitRowToHit, tryParseEmbedding } from '../utils.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';/** Narrow slice of PostgresEngine the takes operations use. */export interface PgTakesDeps {@@ -299,6 +300,7 @@ export async function listTakes(deps: PgTakesDeps, opts: TakesListOpts = {}): PrFROM takes tJOIN pages p ON p.id = t.page_idWHERE 1=1+ ${opts.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``}AND (${opts.page_id ?? null}::int IS NULL OR t.page_id = ${opts.page_id ?? null}::int)AND (${opts.page_slug ?? null}::text IS NULL OR p.slug = ${opts.page_slug ?? null}::text)AND (${opts.holder ?? null}::text IS NULL OR t.holder = ${opts.holder ?? null}::text)@@ -339,6 +341,7 @@ export async function searchTakes(deps: PgTakesDeps, query: string, opts: SearchJOIN pages p ON p.id = t.page_idWHERE t.activeAND ${query} <% t.claim+ ${opts.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``}AND (${opts.takesHoldersAllowList ?? null}::text[] IS NULLOR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])@@ -374,6 +377,7 @@ export async function searchTakesVector(JOIN pages p ON p.id = t.page_idWHERE t.activeAND t.embedding IS NOT NULL+ ${opts.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``}AND (${opts.takesHoldersAllowList ?? null}::text[] IS NULLOR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])@@ -595,6 +599,7 @@ export async function getScorecard(deps: PgTakesDeps, opts: TakesScorecardOpts,)::float AS brierFROM takesWHERE 1=1 ${holderClause} ${domainClause} ${sinceClause} ${untilClause} ${allowed} ${sourceFilter}+ ${opts.excludePrivate ? sql.unsafe(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterFragment('p')})`) : sql``}`;const r = rows[0] as { total_bets: number; resolved: number; correct: number; incorrect: number; partial: number; unresolvable_count: number; brier: number | null };return finalizeScorecard(r);@@ -636,6 +641,7 @@ export async function getCalibrationCurve(deps: PgTakesDeps, opts: CalibrationCuFROM takesWHERE resolved_quality IN ('correct','incorrect')${holderClause} ${allowed} ${sourceFilter}+ ${opts.excludePrivate ? sql.unsafe(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterFragment('p')})`) : sql``})SELECT(bucket_idx::numeric * ${bucketSize}::numeric)::float AS bucket_lo,diff --git a/src/core/remote-body.ts b/src/core/remote-body.tsnew file mode 100644index 0000000000..97c7f8a783--- /dev/null+++ b/src/core/remote-body.ts@@ -0,0 +1,46 @@+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable } from './facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from './takes-fence.ts';+import { sanitizeText } from './batch-rows.ts';++const protectedMarkerPattern = new RegExp(+ [FACTS_FENCE_BEGIN, FACTS_FENCE_END, TAKES_FENCE_BEGIN, TAKES_FENCE_END]+ .map(marker => marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'),+ 'g',+);++/** Strict protected-body boundary shared by remote reads and chunk creation. */+export function sanitizeRemoteBody(body: string): string {+ if (typeof body !== 'string') return '';+ // Parse the same free-text bytes storage accepts. Removing NUL after fence+ // detection could turn an unrecognized marker into a protected stored fence.+ body = sanitizeText(body);+ let cursor = 0;+ const output: string[] = [];+ let open: { start: number; endMarker: string; facts: boolean } | undefined;+ // Each token is visited once. Looking for every marker from each block's+ // cursor would repeatedly scan the remaining body when a marker is absent.+ for (const token of body.matchAll(protectedMarkerPattern)) {+ const marker = token[0];+ if (!open) {+ const facts = marker === FACTS_FENCE_BEGIN;+ if (!facts && marker !== TAKES_FENCE_BEGIN) continue;+ output.push(body.slice(cursor, token.index));+ open = { start: token.index, endMarker: facts ? FACTS_FENCE_END : TAKES_FENCE_END, facts };+ continue;+ }+ // Another begin or the wrong end makes the protected tail ambiguous.+ if (marker !== open.endMarker) return output.join('');+ cursor = token.index + marker.length;+ if (open.facts) {+ try {+ const parsed = parseFactsFence(body.slice(open.start, cursor));+ if (parsed.warnings.length === 0) output.push(renderFactsTable(parsed.facts.filter(row => row.visibility === 'world')));+ } catch {+ // A protected block that cannot be parsed is omitted, never echoed.+ }+ }+ open = undefined;+ }+ if (!open) output.push(body.slice(cursor));+ return output.join('');+}diff --git a/src/core/remote-mcp-probe.ts b/src/core/remote-mcp-probe.tsindex 26d5a2c844..8cb48306aa 100644--- a/src/core/remote-mcp-probe.ts+++ b/src/core/remote-mcp-probe.ts@@ -14,6 +14,25 @@* errors get their own `auth` reason for clean rendering.*/+import { anySignal } from './abort-check.ts';++type ProbeFailure<Reason extends string> = {+ ok: false;+ reason: Reason;+ status?: number;+ kind?: 'timeout' | 'aborted';+ message: string;+};++function networkFailure(label: string, error: unknown, signal: AbortSignal): ProbeFailure<'network'> {+ if (signal.aborted) {+ const kind = signal.reason instanceof Error && signal.reason.name === 'TimeoutError'+ ? 'timeout' : 'aborted';+ return { ok: false, reason: 'network', kind, message: `${label} ${kind === 'timeout' ? 'timed out' : 'was aborted'}` };+ }+ return { ok: false, reason: 'network', message: `${label} network error: ${error instanceof Error ? error.message : String(error)}` };+}+export type ProbeResult<T = void> =| { ok: true } & ({} extends T ? unknown : T extends void ? unknown : { value: T })| { ok: false; reason: 'network' | 'http' | 'auth' | 'parse' | 'config'; status?: number; message: string };@@ -35,24 +54,27 @@ export interface OAuthMetadata {export async function discoverOAuth(issuerUrl: string,- opts: { timeoutMs?: number } = {},-): Promise<{ ok: true; metadata: OAuthMetadata } | { ok: false; reason: 'network' | 'http' | 'parse' | 'config'; status?: number; message: string }> {+ opts: { timeoutMs?: number; signal?: AbortSignal } = {},+): Promise<{ ok: true; metadata: OAuthMetadata } | ProbeFailure<'network' | 'http' | 'parse' | 'config'>> {const trimmed = issuerUrl.replace(/\/+$/, '');if (!/^https?:\/\//i.test(trimmed)) {return { ok: false, reason: 'config', message: `issuer_url must start with http:// or https:// — got: ${issuerUrl}` };}const url = `${trimmed}/.well-known/oauth-authorization-server`;const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 10_000);+ const timer = setTimeout(() => controller.abort(new DOMException('OAuth request timed out', 'TimeoutError')), opts.timeoutMs ?? 10_000);+ const signal = anySignal(controller.signal, opts.signal);try {- const res = await fetch(url, { signal: controller.signal });+ const res = await fetch(url, { signal });if (!res.ok) {+ await res.body?.cancel().catch(() => {});return { ok: false, reason: 'http', status: res.status, message: `OAuth discovery returned ${res.status} for ${url}` };}let body: unknown;try {body = await res.json();} catch (e) {+ if (signal.aborted) return networkFailure('OAuth discovery', e, signal);return { ok: false, reason: 'parse', message: `OAuth discovery returned non-JSON body: ${(e as Error).message}` };}if (!body || typeof body !== 'object' || typeof (body as OAuthMetadata).token_endpoint !== 'string') {@@ -60,7 +82,7 @@ export async function discoverOAuth(}return { ok: true, metadata: body as OAuthMetadata };} catch (e) {- return { ok: false, reason: 'network', message: `OAuth discovery network error: ${(e as Error).message}` };+ return networkFailure('OAuth discovery', e, signal);} finally {clearTimeout(timer);}@@ -82,8 +104,8 @@ export async function mintClientCredentialsToken(tokenEndpoint: string,clientId: string,clientSecret: string,- opts: { scope?: string; timeoutMs?: number } = {},-): Promise<{ ok: true; token: TokenResponse } | { ok: false; reason: 'network' | 'http' | 'auth' | 'parse' | 'config'; status?: number; message: string }> {+ opts: { scope?: string; timeoutMs?: number; signal?: AbortSignal } = {},+): Promise<{ ok: true; token: TokenResponse } | ProbeFailure<'network' | 'http' | 'auth' | 'parse' | 'config'>> {if (!clientId) return { ok: false, reason: 'config', message: 'client_id is required' };if (!clientSecret) return { ok: false, reason: 'config', message: 'client_secret is required' };@@ -94,24 +116,28 @@ export async function mintClientCredentialsToken(if (opts.scope) body.set('scope', opts.scope);const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 10_000);+ const timer = setTimeout(() => controller.abort(new DOMException('OAuth request timed out', 'TimeoutError')), opts.timeoutMs ?? 10_000);+ const signal = anySignal(controller.signal, opts.signal);try {const res = await fetch(tokenEndpoint, {method: 'POST',headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: body.toString(),- signal: controller.signal,+ signal,});if (res.status === 401 || res.status === 403) {+ await res.body?.cancel().catch(() => {});return { ok: false, reason: 'auth', status: res.status, message: `OAuth /token returned ${res.status} — check client_id and client_secret` };}if (!res.ok) {+ await res.body?.cancel().catch(() => {});return { ok: false, reason: 'http', status: res.status, message: `OAuth /token returned ${res.status}` };}let json: unknown;try {json = await res.json();} catch (e) {+ if (signal.aborted) return networkFailure('OAuth /token', e, signal);return { ok: false, reason: 'parse', message: `OAuth /token returned non-JSON: ${(e as Error).message}` };}if (!json || typeof json !== 'object' || typeof (json as TokenResponse).access_token !== 'string') {@@ -119,7 +145,7 @@ export async function mintClientCredentialsToken(}return { ok: true, token: json as TokenResponse };} catch (e) {- return { ok: false, reason: 'network', message: `OAuth /token network error: ${(e as Error).message}` };+ return networkFailure('OAuth /token', e, signal);} finally {clearTimeout(timer);}diff --git a/src/core/search/by-image.ts b/src/core/search/by-image.tsindex 36f5ca5900..4b896ea48e 100644--- a/src/core/search/by-image.ts+++ b/src/core/search/by-image.ts@@ -73,6 +73,9 @@ export async function searchByImage(offset: 0,sourceId: opts.sourceId,sourceIds: opts.sourceIds,+ excludePrivate: opts.excludePrivate,+ requireSafeChunks: opts.requireSafeChunks,+ takesHoldersAllowList: opts.takesHoldersAllowList,// Both branches use the same source-scope threading.};diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.tsindex a31e02afbd..0a68f7712c 100644--- a/src/core/search/exact-lookup.ts+++ b/src/core/search/exact-lookup.ts@@ -31,8 +31,10 @@* Fail-open everywhere: a probe error returns the organic results unchanged.*/+import { sanitizeRemoteBody } from '../remote-body.ts';+import { hasReadPolicy } from './read-policy-sql.ts';import type { BrainEngine } from '../engine.ts';-import type { SearchResult } from '../types.ts';+import type { SearchResult, PageReadPolicy } from '../types.ts';import { normalizeAlias } from './alias-normalize.ts';import { isLookupShapedQuery } from './query-intent.ts';import { applySupersedeDownrank } from './hybrid.ts';@@ -48,7 +50,7 @@ export function isSlugShapedQuery(query: string): boolean {return q.length > 0 && !/\s/.test(q) && q.includes('/') && !q.startsWith('/') && !q.endsWith('/');}-export interface ExactLookupOpts {+export interface ExactLookupOpts extends PageReadPolicy {sourceId?: string;sourceIds?: string[];/**@@ -116,8 +118,8 @@ export async function structuralExactLookup(for (const scope of scopes) {try {const page = scope != null- ? await engine.getPage(q, { sourceId: scope })- : await engine.getPage(q); // gbrain-allow-unscoped-getpage — read-only first-match; no paired write+ ? await engine.getPage(q, { sourceId: scope, excludePrivate: opts.excludePrivate })+ : await engine.getPage(q, { excludePrivate: opts.excludePrivate }); // gbrain-allow-unscoped-getpage — read-only first-match; no paired writeif (!page) continue;push({page_id: page.id,@@ -125,7 +127,7 @@ export async function structuralExactLookup(title: page.title,type: page.type,source_id: page.source_id ?? scope ?? 'default',- chunk_text: (page.compiled_truth ?? '').slice(0, 200),+ chunk_text: sanitizeRemoteBody(page.compiled_truth ?? '').slice(0, 200),chunk_index: 0,chunk_id: 0,score: 0, // caller assigns the injection score@@ -159,7 +161,7 @@ export async function structuralExactLookup(// `superseded`); tier scores are assigned by the caller afterwards, so the// stage's score mutation on dropped rows is irrelevant.try {- await applySupersedeDownrank(hits, engine);+ await applySupersedeDownrank(hits, engine, hasReadPolicy(opts) ? opts : undefined);} catch {// fail-open: filter unavailable (pre-links schema) → keep hits}diff --git a/src/core/search/graph-signals.ts b/src/core/search/graph-signals.tsindex 695a15a943..4a5d6ecf22 100644--- a/src/core/search/graph-signals.ts+++ b/src/core/search/graph-signals.ts@@ -38,9 +38,10 @@* rates cross-process.*/-import type { SearchResult } from '../types.ts';+import type { SearchResult, PageReadPolicy } from '../types.ts';import type { AdjacencyRow } from '../types.ts';import type { BrainEngine } from '../engine.ts';+import { hasReadPolicy } from './read-policy-sql.ts';import { createAuditWriter } from '../audit/audit-writer.ts';// ===========================================================================@@ -98,7 +99,7 @@ export interface GraphSignalsMeta {duration_ms: number;}-export interface GraphSignalsOpts {+export interface GraphSignalsOpts extends PageReadPolicy {/** Master gate. False short-circuits to no-op with zero-meta emitted. */enabled: boolean;/** Top-K size (default DEFAULT_TOP_K). */@@ -333,7 +334,7 @@ export async function applyGraphSignals(try {adjacency = opts.adjacencyFn? await opts.adjacencyFn(uniquePageIds)- : await engine.getAdjacencyBoosts(uniquePageIds);+ : await engine.getAdjacencyBoosts(uniquePageIds, hasReadPolicy(opts) ? opts : undefined);} catch (err) {const msg = err instanceof Error ? err.message : String(err);failureWriter.log({diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex b56ded2899..ae3cbf2a26 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -9,10 +9,12 @@* Cosine re-score: blend 0.7*rrf + 0.3*cosine for query-specific ranking*/+import { sanitizeRemoteBody } from '../remote-body.ts';import type { BrainEngine } from '../engine.ts';import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';import type {SearchResult,+ PageReadPolicy,SearchOpts,HybridSearchMeta,DegradedStage,@@ -20,6 +22,8 @@ import type {DegradedReason,} from '../types.ts';import { affectsRecall } from '../types.ts';+import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';+import { requiresSafeChunks } from './safe-chunks.ts';import { embed, embedQuery } from '../embedding.ts';import { registerBackgroundWorkDrainer } from '../background-work.ts';import { isDbAccessFailure } from '../pg-access-classify.ts';@@ -63,6 +67,7 @@ import {import {SemanticQueryCache,loadCacheConfig,+ semanticResultCacheAvailable,} from './query-cache.ts';export const RRF_K = 60;@@ -131,14 +136,14 @@ const pendingCacheWrites = new Set<Promise<unknown>>();* candidate pool. Fail-open: the warning is best-effort and never breaks search.* Mirrors the stampEvidence post-fusion precedent (T4).*/-export async function stampContentFlags(engine: BrainEngine, results: SearchResult[]): Promise<void> {+export async function stampContentFlags(engine: BrainEngine, results: SearchResult[], policy?: PageReadPolicy): Promise<void> {if (results.length === 0) return;try {const ids = [...new Set(results.map((r) => r.page_id).filter((n): n is number => typeof n === 'number' && Number.isFinite(n)),)];if (ids.length === 0) return;- const flags = await engine.getContentFlagsByPageIds(ids);+ const flags = await engine.getContentFlagsByPageIds(ids, policy);if (flags.size === 0) return;for (const r of results) {const f = flags.get(r.page_id);@@ -168,6 +173,7 @@ export async function stampContentFlags(engine: BrainEngine, results: SearchResuexport async function stampUnverifiedExtractions(engine: BrainEngine,results: SearchResult[],+ policy?: PageReadPolicy,): Promise<void> {if (results.length === 0) return;try {@@ -175,7 +181,7 @@ export async function stampUnverifiedExtractions(results.map((r) => r.page_id).filter((n): n is number => typeof n === 'number' && Number.isFinite(n)),)];if (ids.length === 0) return;- const marks = await engine.getUnverifiedExtractionPageIds(ids);+ const marks = await engine.getUnverifiedExtractionPageIds(ids, policy);if (marks.size === 0) return;for (const r of results) {const m = marks.get(r.page_id);@@ -485,7 +491,7 @@ export function applyChronicleTypeBoost(** Mutates `results` in place; caller re-sorts.*/-export interface PostFusionOpts {+export interface PostFusionOpts extends PageReadPolicy {applyBacklinks: boolean;salience: 'off' | 'on' | 'strong';recency: 'off' | 'on' | 'strong';@@ -551,6 +557,7 @@ export async function runPostFusionStages(opts: PostFusionOpts,): Promise<void> {if (results.length === 0) return;+ const policy = hasReadPolicy(opts) ? opts : undefined;// v0.40.4 attribution stamp (D12=A) — capture base_score ONCE at entry,// BEFORE any boost mutates r.score. Without this, --explain can't@@ -573,7 +580,7 @@ export async function runPostFusionStages(if (opts.applyBacklinks) {try {const pageIds = Array.from(new Set(results.map(r => r.page_id)));- const counts = await engine.getBacklinkCounts(pageIds);+ const counts = await engine.getBacklinkCounts(pageIds, policy);applyBacklinkBoost(results, counts, floorThreshold);} catch {// Non-fatal; preserves the existing pre-v0.29.1 contract.@@ -590,7 +597,7 @@ export async function runPostFusionStages(// Salience stage (mattering, no time).if (opts.salience !== 'off') {try {- const scores = await engine.getSalienceScores(refs);+ const scores = await engine.getSalienceScores(refs, policy);applySalienceBoost(results, scores, opts.salience, floorThreshold);} catch {// Non-fatal.@@ -600,7 +607,7 @@ export async function runPostFusionStages(// Recency stage (per-prefix decay, no mattering).if (opts.recency !== 'off') {try {- const dates = await engine.getEffectiveDates(refs);+ const dates = await engine.getEffectiveDates(refs, policy);// Resolve the effective decay map (defaults + gbrain.yml `recency:` +// GBRAIN_RECENCY_DECAY env) instead of the baked-in defaults. The// get_recent_salience SQL path already goes through resolveRecencyDecayMap()@@ -649,6 +656,7 @@ export async function runPostFusionStages(try {const { applyGraphSignals } = await import('./graph-signals.ts');await applyGraphSignals(results, engine, {+ ...policy,enabled: true,floorThreshold,onMeta: opts.onGraphMeta,@@ -667,7 +675,7 @@ export async function runPostFusionStages(// in-depth: pre-v105 brains don't have slug_aliases table; the lookup// throws isUndefinedTableError and the stage no-ops.try {- await applyAliasResolvedBoost(results, engine);+ await applyAliasResolvedBoost(results, engine, policy);} catch {// Non-fatal; preserves the per-stage contract.}@@ -680,7 +688,7 @@ export async function runPostFusionStages(// facts. Fail-open per the per-stage contract: a brain with no `supersedes`// edges (or a pre-links schema) finds 0 rows / throws and no-ops.try {- await applySupersedeDownrank(results, engine);+ await applySupersedeDownrank(results, engine, policy);} catch {// Non-fatal; preserves the per-stage contract.}@@ -752,6 +760,7 @@ export const SUPERSEDE_PENALTY = 0.5;export async function applySupersedeDownrank(results: SearchResult[],engine: import('../engine.ts').BrainEngine,+ policy?: PageReadPolicy,): Promise<void> {if (results.length === 0) return;const pageIds = Array.from(@@ -759,6 +768,10 @@ export async function applySupersedeDownrank();if (pageIds.length === 0) return;if (!(await hasAnySupersedeEdges(engine))) return;+ const params: unknown[] = [pageIds];+ const fromFilter = pageReadFilter('pf', policy, params, !!policy);+ const toFilter = pageReadFilter('pt', policy, params, !!policy);+ const originFilter = policy ? `(l.origin_page_id IS NULL OR EXISTS (SELECT 1 FROM pages origin WHERE origin.id = l.origin_page_id AND ${pageReadFilter('origin', policy, params, true)}))` : 'TRUE';let rows: Array<{ to_page_id: number; by_slug: string }> = [];try {rows = await engine.executeRaw<{ to_page_id: number; by_slug: string }>(@@ -769,8 +782,9 @@ export async function applySupersedeDownrank(WHERE l.link_type = 'supersedes'AND pf.deleted_at IS NULLAND pf.source_id = pt.source_id- AND l.to_page_id = ANY($1::bigint[])`,- [pageIds],+ AND l.to_page_id = ANY($1::bigint[])+ AND ${fromFilter} AND ${toFilter} AND ${originFilter}`,+ params,);} catch {// Pre-links schema or SQL miss; no-op.@@ -809,6 +823,7 @@ const ALIAS_RESOLVED_BOOST = 1.05;async function applyAliasResolvedBoost(results: SearchResult[],engine: import('../engine.ts').BrainEngine,+ policy?: PageReadPolicy,): Promise<void> {if (results.length === 0) return;// Build the (source_id, slug) composite list for the lookup.@@ -825,15 +840,17 @@ async function applyAliasResolvedBoost(// Two-array unnest for source-scoped composite lookup.const sourceIds = refs.map(r => r.source_id);const slugs = refs.map(r => r.slug);+ const params: unknown[] = [sourceIds, slugs];+ const filter = pageReadFilter('p', policy, params, !!policy);let rows: Array<{ source_id: string; canonical_slug: string }> = [];try {rows = await engine.executeRaw<{ source_id: string; canonical_slug: string }>(- `SELECT DISTINCT source_id, canonical_slug- FROM slug_aliases- WHERE (source_id, canonical_slug) IN (+ `SELECT DISTINCT a.source_id, a.canonical_slug+ FROM slug_aliases a JOIN pages p ON p.source_id = a.source_id AND p.slug = a.canonical_slug+ WHERE (a.source_id, a.canonical_slug) IN (SELECT * FROM unnest($1::text[], $2::text[])- )`,- [sourceIds, slugs],+ ) AND ${filter}`,+ params,);} catch {// Pre-v104 brain or other SQL miss; no-op.@@ -879,7 +896,7 @@ export async function applyAliasHop(engine: import('../engine.ts').BrainEngine,results: SearchResult[],query: string,- opts: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },+ opts: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; requireSafeChunks?: boolean },): Promise<SearchResult[]> {if (!query) return results;const qNorm = normalizeAlias(query);@@ -887,7 +904,7 @@ export async function applyAliasHop(let aliasMap: Map<string, Array<{ slug: string; source_id: string }>>;try {- aliasMap = await engine.resolveAliases([qNorm], { sourceId: opts.sourceId, sourceIds: opts.sourceIds });+ aliasMap = await engine.resolveAliases([qNorm], opts);} catch {return results; // pre-v110 table-missing OR transient error -> fail-open}@@ -914,7 +931,7 @@ export async function applyAliasHop(// Absent canonical: fetch (in its OWN source) + inject at top-of-organic + epsilon.let page;try {- page = await engine.getPage(ref.slug, { sourceId: ref.source_id });+ page = await engine.getPage(ref.slug, { sourceId: ref.source_id, excludePrivate: opts.excludePrivate });} catch {continue;}@@ -937,7 +954,7 @@ export async function applyAliasHop(title: page.title,type: page.type,source_id: page.source_id ?? ref.source_id,- chunk_text: (page.compiled_truth ?? '').slice(0, 200),+ chunk_text: sanitizeRemoteBody(page.compiled_truth ?? '').slice(0, 200),chunk_index: 0,chunk_id: 0,score: injectScore,@@ -1275,6 +1292,7 @@ export async function hybridSearch(// let an untrusted caller read `visibility: private` pages through the// hybrid hot path.excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,// v0.36 (D11): pass the pre-validated descriptor into the engine so// it never has to read config. Engines normalize string-or-descriptor// via normalizeEngineColumn; the descriptor path is the strict one.@@ -1421,6 +1439,11 @@ export async function hybridSearch(const recencyMode: 'off' | 'on' | 'strong' =resolveEffectiveRecency(opts, suggestions, intentWeightingOn);const postFusionOpts: PostFusionOpts = {+ sourceId: opts?.sourceId,+ sourceIds: opts?.sourceIds,+ excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,+ takesHoldersAllowList: opts?.takesHoldersAllowList,applyBacklinks: true,salience: salienceMode,recency: recencyMode,@@ -1457,6 +1480,8 @@ export async function hybridSearch(// straight from pages — thread the caller's private-page gate or a// remote relational query bypasses the keyword/vector visibility clause.excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,+ takesHoldersAllowList: opts?.takesHoldersAllowList,onMeta: opts?.onRelationalMeta,});}@@ -1501,7 +1526,7 @@ export async function hybridSearch(// chunk-grain keyword FTS alone fails (D1).// issue #160: stamp unverified stubs BEFORE fusion so the compiled-truth// boost skips them (flag survives fusion's result spread).- await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList]);+ await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);let noEmbedResults = keywordResults;if (relationalList.length > 0 || titleResults.length > 0) {const fk = opts?.rrfK ?? RRF_K;@@ -1520,12 +1545,16 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,});// #1663 — structural exact-lookup tier (slug / exact-title identity).const noEmbedHopped = await applyExactLookupTier(engine, noEmbedPreExact, query, {sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,titleCandidates: titleResults,+ excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,+ takesHoldersAllowList: opts?.takesHoldersAllowList,// #4480: gate tier injections on the caller's shape filters.type: opts?.type,types: opts?.types,@@ -1548,7 +1577,7 @@ export async function hybridSearch(const noEmbedSliced = noEmbedPool.slice(offset, offset + limit);// v0.32.3 search-lite: budget enforcement on the no-embedding-provider path.const { results: noEmbedBudgeted, meta: noEmbedBudgetMeta } = enforceTokenBudget(noEmbedSliced, resolvedMode.tokenBudget);- await stampContentFlags(engine, noEmbedBudgeted);+ await stampContentFlags(engine, noEmbedBudgeted, opts);lastResultsCount = noEmbedBudgeted.length;lastRank1Score = noEmbedBudgeted[0] ? (noEmbedBudgeted[0].base_score ?? noEmbedBudgeted[0].score) : undefined;// WP2/T3 — no silent bypass: the keyword-only-config branch names why@@ -1894,7 +1923,7 @@ export async function hybridSearch(// here too (same rationale as the no-embedding-provider path — D1).// issue #160: stamp unverified stubs BEFORE fusion (see the// no-embedding-provider path for rationale).- await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList]);+ await stampUnverifiedExtractions(engine, [...keywordResults, ...titleResults, ...relationalList], opts);let fallbackResults = keywordResults;if (relationalList.length > 0 || titleResults.length > 0) {const fk = opts?.rrfK ?? RRF_K;@@ -1911,12 +1940,16 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,});// #1663 — structural exact-lookup tier (slug / exact-title identity).const kwHopped = await applyExactLookupTier(engine, kwPreExact, query, {sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,titleCandidates: titleResults,+ excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,+ takesHoldersAllowList: opts?.takesHoldersAllowList,// #4480: gate tier injections on the caller's shape filters.type: opts?.type,types: opts?.types,@@ -1926,7 +1959,7 @@ export async function hybridSearch(const kwSliced = kwHopped.slice(offset, offset + limit);// v0.32.3 search-lite: budget enforcement on the keyword-fallback path too.const { results: kwBudgeted, meta: kwBudgetMeta } = enforceTokenBudget(kwSliced, resolvedMode.tokenBudget);- await stampContentFlags(engine, kwBudgeted);+ await stampContentFlags(engine, kwBudgeted, opts);lastResultsCount = kwBudgeted.length;lastRank1Score = kwBudgeted[0] ? (kwBudgeted[0].base_score ?? kwBudgeted[0].score) : undefined;// WP2/T3 — the embed/vector failure that emptied vectorLists already@@ -2049,7 +2082,7 @@ export async function hybridSearch(// issue #160: stamp unverified auto-extracted stubs across ALL candidate// arms BEFORE fusion so the compiled-truth authority boost skips them.- await stampUnverifiedExtractions(engine, allLists.flatMap((l) => l.list));+ await stampUnverifiedExtractions(engine, allLists.flatMap((l) => l.list), opts);let fused = rrfFusionWeighted(allLists, shouldBoostCompiledTruth(detail));@@ -2085,7 +2118,9 @@ export async function hybridSearch(// structural neighbors from the same file/class are the whole point// of two-pass; clipping them at 2/page defeats A2 (codex F5).const walkDepth = Math.min(opts?.walkDepth ?? 0, 2);- const needsExpansion = walkDepth > 0 || Boolean(opts?.nearSymbol);+ // The optional code walk's raw graph hydration has no row-level read policy.+ // Keep it suspended for untrusted retrieval until that boundary is supported.+ const needsExpansion = !requiresSafeChunks(opts) && (walkDepth > 0 || Boolean(opts?.nearSymbol));let dedupOpts = opts?.dedupOpts;if (needsExpansion) {@@ -2182,6 +2217,7 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,});// #1663 — structural exact-lookup tier: a query that IS a page identity@@ -2194,6 +2230,9 @@ export async function hybridSearch(sourceId: opts?.sourceId,sourceIds: opts?.sourceIds,titleCandidates: titleResults,+ excludePrivate: opts?.excludePrivate,+ requireSafeChunks: opts?.requireSafeChunks,+ takesHoldersAllowList: opts?.takesHoldersAllowList,// #4480: gate tier injections on the caller's shape filters.type: opts?.type,types: opts?.types,@@ -2289,7 +2328,7 @@ export async function hybridSearch(// hybridSearch enforces it too so eval-replay + eval-longmemeval see// the same budget behavior as the production query op.const { results: budgeted, meta: budgetMeta } = enforceTokenBudget(sliced, resolvedMode.tokenBudget);- await stampContentFlags(engine, budgeted);+ await stampContentFlags(engine, budgeted, opts);lastResultsCount = budgeted.length;lastRank1Score = budgeted[0] ? (budgeted[0].base_score ?? budgeted[0].score) : undefined;stampBudgetStage(degraded, budgetMeta);@@ -2493,12 +2532,7 @@ export async function hybridSearchCached(// (and thus results), so it must change the key immediately instead of// serving old-classification rows for the rest of the cache TTL.intentPatterns: intentStateForCache.fingerprint,- // #4352 follow-up — fold the private-visibility posture into the key- // (xp=, v=23) for BOTH the lookup and the write below (they share this- // one hash), instead of the original wholesale skipCache bypass. A- // remote-default (excludePrivate=true) caller now caches normally, on- // rows that can never be served to (or written by) a trusted- // private-included call.+ // Retained storage-key shape; semantic response reuse is disabled below.excludePrivate: opts?.excludePrivate === true,// v=27 (E5b) — the resolved gate + this query's intent class, classified// by the SAME pattern-aware banks bare hybridSearch resolves (above).@@ -2565,13 +2599,10 @@ export async function hybridSearchCached(// array's start and returns nothing — so `> 0` let those requests// read/write the cache anyway.const pagedRequest = (opts?.offset ?? 0) !== 0;- // #4352 follow-up — excludePrivate no longer skips the cache: the posture- // is folded into knobsHash (xp=), so a private-included (trusted)- // write can never serve a private-excluding lookup and vice versa. The- // original wholesale skip disabled the semantic cache for every remote MCP- // caller (excludePrivate=true is their default) — exactly the- // highest-volume beneficiaries of the ~50% cache savings.+ // Hard availability gate: no persisted result is read or written until+ // every response dependency can be authorized at reuse time.const skipCache =+ !semanticResultCacheAvailable() ||!cache.isEnabled() ||(opts?.walkDepth ?? 0) > 0 ||Boolean(opts?.nearSymbol) ||diff --git a/src/core/search/modes-report.ts b/src/core/search/modes-report.tsindex b71298f4bb..8aadd9e1fb 100644--- a/src/core/search/modes-report.ts+++ b/src/core/search/modes-report.ts@@ -6,6 +6,7 @@*/import type { BrainEngine } from '../engine.ts';+import { semanticResultCacheAvailable } from './query-cache.ts';import {MODE_BUNDLES,SEARCH_MODE_CONFIG_KEYS,@@ -144,6 +145,15 @@ export async function buildModesReport(engine: BrainEngine): Promise<SearchModes};}+ if (!semanticResultCacheAvailable()) {+ attributions.cache_enabled = {+ ...attributions.cache_enabled,+ value: false,+ source: 'availability',+ source_detail: 'Semantic result caching is temporarily disabled; configured settings are retained.',+ };+ }+let reranker_readiness: SearchModesReport['reranker_readiness'];try {// Same plane the CLI hands the gateway (env > file > DB-plane providerdiff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 071ba8f13b..8591c8ed7a 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -35,6 +35,24 @@ export function privatePagesFilterFragment(pageAlias: string): string {return `COALESCE(${pageAlias}.frontmatter->>'visibility', 'world') <> 'private'`;}+/** Check the actual origin, independently of joins that redact its source. */+export function privateLinkOriginFilterFragment(linkAlias: string): string {+ return `(${linkAlias}.origin_page_id IS NULL OR EXISTS (+ SELECT 1 FROM pages origin_private+ WHERE origin_private.id = ${linkAlias}.origin_page_id+ AND ${privatePagesFilterFragment('origin_private')}+ ))`;+}++/** A projection's private event must stay hidden even when its join is source-redacted. */+export function privateTimelineEventFilterFragment(timelineAlias: string): string {+ return `(${timelineAlias}.event_page_id IS NULL OR EXISTS (+ SELECT 1 FROM pages event_private+ WHERE event_private.id = ${timelineAlias}.event_page_id+ AND ${privatePagesFilterFragment('event_private')}+ ))`;+}+/*** Row-side twin of privatePagesFilterFragment for pages already fetched* (get_page / fetch read one row by slug; re-querying just to filter would@@ -54,9 +72,9 @@ export function isPrivatePage(frontmatter: unknown): boolean {* for the slug is `visibility: private`. A slug with at least one non-private* in-scope page stays visible (multi-source: private in one source, world in* another). Slugs with no page row at all (dangling link endpoints) are not- * returned — they reveal nothing private. Shared by the #4352 read-op gates- * (get_page fuzzy candidates, resolve_slugs, link/graph endpoint filtering,- * and the content-op probes via slugHiddenFromCaller). `scope` follows the+ * returned — they reveal nothing private. Used only for get_page's fuzzy+ * candidate enumeration; data-bearing reads authorize concrete rows in the+ * engine instead of treating a visible namesake as authorization. `scope` follows the* canonical precedence (federated array > scalar > nothing); with* `includeDeleted` unset, only live rows are considered.*/@@ -88,26 +106,6 @@ export async function findPrivateOnlySlugs(return new Set(rows.map(r => r.slug));}-/**- * One-slug trust + probe combo for the sibling content ops (#4352- * remediation: get_chunks / get_versions / get_timeline / get_raw_data).- * True ⇒ the caller's read of `slug` must behave exactly like a missing- * page (no existence oracle). Trusted local + the operator opt-outs resolve- * to false via resolveExcludePrivatePages before any query runs. The probe- * considers DELETED rows too (fail-closed: a soft-deleted private page's- * history/timeline/raw data stays hidden).- */-export async function slugHiddenFromCaller(- engine: BrainEngine,- remote: boolean | undefined,- slug: string,- scope: { sourceId?: string; sourceIds?: string[] } = {},-): Promise<boolean> {- if (!(await resolveExcludePrivatePages(engine, remote))) return false;- const hidden = await findPrivateOnlySlugs(engine, [slug], scope, { includeDeleted: true });- return hidden.has(slug);-}-const CACHE_TTL_MS = 30_000;let cache = new WeakMap<BrainEngine, { at: number; expose: boolean }>();@@ -143,65 +141,3 @@ export async function resolveExcludePrivatePages(}return !expose;}--/**- * KEEP-list inverse of findPrivateOnlySlugs: of the given slugs, which have- * at least one world-visible page row (deleted rows considered — see- * findWorldVisibleSlugs' consumers for why)? Fail-closed by construction: a- * slug with NO page row at all (e.g. hard-purged between a caller's list- * read and this probe) is simply absent from the keep-set, so a- * keep-list consumer drops it instead of serving it — the drop-list shape- * fails OPEN on exactly that TOCTOU window.- */-export async function findWorldVisibleSlugs(- engine: BrainEngine,- slugs: string[],- scope: { sourceId?: string; sourceIds?: string[] } = {},-): Promise<Set<string>> {- if (slugs.length === 0) return new Set();- const params: unknown[] = [slugs];- let scopeClause = '';- if (scope.sourceIds && scope.sourceIds.length > 0) {- params.push(scope.sourceIds);- scopeClause = `AND p.source_id = ANY($${params.length}::text[])`;- } else if (scope.sourceId) {- params.push(scope.sourceId);- scopeClause = `AND p.source_id = $${params.length}`;- }- const rows = await engine.executeRaw<{ slug: string }>(- `SELECT p.slug FROM pages p- WHERE p.slug = ANY($1::text[])- ${scopeClause}- GROUP BY p.slug- HAVING bool_or(${privatePagesFilterFragment('p')})`,- params,- );- return new Set(rows.map(r => r.slug));-}--/**- * Shared post-filter for list-shaped read ops (find_orphans,- * get_recent_salience, find_experts): one gate read + one batched KEEP-list- * probe, keeping only rows whose slug has a world-visible page row.- *- * Deleted rows are considered by the probe on purpose: some callers' raw- * list queries carry no `deleted_at` predicate, so a soft-deleted private- * page can still be IN the rows — a live-rows-only probe would never see- * it and the filter would fail open (same fail-closed reasoning as- * slugHiddenFromCaller above). And the keep-list shape means a slug whose- * page row vanished entirely (concurrent purge) drops out too, instead of- * being served because "no row" looked like "not private".- */-export async function dropPrivateOnlyRows<T>(- engine: BrainEngine,- remote: boolean | undefined,- rows: T[],- slugOf: (row: T) => string,- scope: { sourceId?: string; sourceIds?: string[] } = {},-): Promise<T[]> {- if (rows.length === 0) return rows;- if (!(await resolveExcludePrivatePages(engine, remote))) return rows;- const keep = await findWorldVisibleSlugs(engine, rows.map(slugOf), scope);- if (keep.size === rows.length) return rows;- return rows.filter(r => keep.has(slugOf(r)));-}diff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.tsindex b570006fc1..4c7c3bd9ed 100644--- a/src/core/search/query-cache.ts+++ b/src/core/search/query-cache.ts@@ -30,6 +30,10 @@*/import { createHash } from 'node:crypto';++/** Stored semantic responses are unavailable until all response dependencies can be revalidated. */+export function semanticResultCacheAvailable(): boolean { return false; }+import type { BrainEngine } from '../engine.ts';import type { SearchResult, HybridSearchMeta } from '../types.ts';import { buildPageGenerationsSnapshot, CACHE_GATE_WHERE_CLAUSE } from './query-cache-gate.ts';diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.tsnew file mode 100644index 0000000000..098ae02b52--- /dev/null+++ b/src/core/search/read-enrichment.ts@@ -0,0 +1,180 @@+import type { PageReadScope, PageReadPolicy, AdjacencyRow, RelationalFanoutOpts, RelationalFanoutRow } from '../types.ts';+import { unverifiedExtractionFragment } from '../extraction-review.ts';+import { requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';+import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';++/** Narrow query dependency shared by both engines. */+export type ReadQuery = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;+type PageRef = { slug: string; source_id: string };++function originFilter(scope: PageReadScope | undefined, params: unknown[]): string {+ if (!scope) return 'TRUE';+ const filter = pageReadFilter('origin', scope, params, true);+ return `(l.origin_page_id IS NULL OR EXISTS (SELECT 1 FROM pages origin WHERE origin.id = l.origin_page_id AND ${filter}))`;+}++/** Authorize graph seeds, hops and edge origins before ranking or emitting paths. */+export async function readRelationalFanout(query: ReadQuery, seeds: string[], opts?: RelationalFanoutOpts): Promise<RelationalFanoutRow[]> {+ if (!seeds?.length) return [];+ const depth = Math.min(Math.max(1, opts?.depth ?? 2), 3);+ const direction = opts?.direction ?? 'both';+ const limit = Math.min(Math.max(1, opts?.limit ?? 50), 200);+ const params: unknown[] = [seeds, depth, limit];+ const policy = hasReadPolicy(opts) ? opts : undefined;+ const seed = pageReadFilter('p', policy, params, !!policy);+ const step = pageReadFilter('p2', policy, params, !!policy);+ const origin = originFilter(policy, params);+ let seedIdentities = '';+ if (opts?.seedRefs !== undefined) {+ params.push(opts.seedRefs.map(ref => ref.source_id), opts.seedRefs.map(ref => ref.slug));+ seedIdentities = `AND (p.source_id, p.slug) IN (SELECT * FROM unnest($${params.length - 1}::text[], $${params.length}::text[]))`;+ }+ let typeFilter = '';+ if (opts?.linkTypes?.length) {+ params.push(opts.linkTypes);+ typeFilter = `AND l.link_type = ANY($${params.length}::text[])`;+ }+ const mentionsFilter = opts?.includeMentions ? '' : `AND l.link_source IS DISTINCT FROM 'mentions'`;+ const recurStep = direction === 'out'+ ? 'JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id'+ : direction === 'in'+ ? 'JOIN links l ON l.to_page_id = w.id JOIN pages p2 ON p2.id = l.from_page_id'+ : `JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id)+ JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END`;+ const rows = await query<Record<string, unknown>>(`+ WITH RECURSIVE walk AS (+ SELECT p.id, p.slug, p.source_id, 0::int AS depth,+ ARRAY[p.id] AS visited, ARRAY[p.slug] AS path,+ p.source_id AS seed_source, NULL::text AS last_link_type+ FROM pages p WHERE p.slug = ANY($1::text[]) AND p.deleted_at IS NULL AND ${seed} ${seedIdentities}+ UNION ALL+ SELECT p2.id, p2.slug, p2.source_id, w.depth + 1,+ w.visited || p2.id, w.path || p2.slug, w.seed_source, l.link_type+ FROM walk w ${recurStep}+ WHERE w.depth < $2 AND NOT (p2.id = ANY(w.visited))+ AND p2.source_id = w.seed_source AND p2.deleted_at IS NULL+ AND ${step} AND ${origin} ${mentionsFilter} ${typeFilter}+ )+ SELECT n.source_id, n.slug, MIN(n.depth) AS hop,+ COUNT(DISTINCT n.last_link_type) AS edge_count,+ array_agg(DISTINCT n.last_link_type) FILTER (WHERE n.last_link_type IS NOT NULL) AS via_link_types,+ (array_agg(array_to_string(n.path, chr(9)) ORDER BY n.depth ASC,+ array_length(n.path, 1) ASC, array_to_string(n.path, chr(9)) ASC))[1] AS path_str,+ (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = n.id+ ${requiresSafeChunks(opts) ? `AND EXISTS (SELECT 1 FROM pages cp WHERE cp.id = n.id AND ${safeChunksFilter('cp')})` : ''}+ ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_id+ FROM walk n WHERE n.depth > 0 GROUP BY n.source_id, n.slug, n.id+ ORDER BY hop ASC, edge_count DESC, n.source_id ASC, n.slug ASC LIMIT $3`, params);+ return rows.map(row => ({+ source_id: row.source_id as string, slug: row.slug as string,+ hop: Number(row.hop), edge_count: Number(row.edge_count),+ via_link_types: Array.isArray(row.via_link_types) ? row.via_link_types as string[] : [],+ path: row.path_str ? String(row.path_str).split('\t') : [],+ canonical_chunk_id: row.canonical_chunk_id == null ? null : Number(row.canonical_chunk_id),+ }));+}++export async function readBacklinkCounts(query: ReadQuery, ids: number[], scope?: PageReadScope): Promise<Map<number, number>> {+ const result = new Map(ids.map(id => [id, 0]));+ if (!ids.length) return result;+ const params: unknown[] = [ids];+ const target = pageReadFilter('p', scope, params, !!scope);+ const contributor = pageReadFilter('contributor', scope, params, true);+ const origin = originFilter(scope, params);+ const rows = await query<{ page_id: number; cnt: number }>(`+ SELECT p.id AS page_id, COUNT(l.id)::int AS cnt+ FROM pages p LEFT JOIN links l ON l.to_page_id = p.id+ AND l.link_source IS DISTINCT FROM 'mentions'+ ${scope ? `AND EXISTS (SELECT 1 FROM pages contributor WHERE contributor.id = l.from_page_id AND ${contributor}) AND ${origin}` : ''}+ WHERE p.id = ANY($1::int[]) AND ${target} GROUP BY p.id`, params);+ for (const row of rows) result.set(Number(row.page_id), Number(row.cnt));+ return result;+}++export async function readAdjacencyBoosts(query: ReadQuery, ids: number[], scope?: PageReadScope): Promise<Map<number, AdjacencyRow>> {+ if (!ids.length) return new Map();+ const params: unknown[] = [ids];+ const from = pageReadFilter('p', scope, params, !!scope);+ const to = pageReadFilter('t', scope, params, !!scope);+ const origin = originFilter(scope, params);+ const rows = await query<{ to_page_id: number; hits: number; cross_source_hits: number }>(`+ SELECT l.to_page_id, COUNT(DISTINCT l.from_page_id)::int AS hits,+ COUNT(DISTINCT CASE WHEN p.source_id <> t.source_id THEN p.source_id END)::int AS cross_source_hits+ FROM links l JOIN pages p ON p.id = l.from_page_id AND p.deleted_at IS NULL+ JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL+ WHERE l.from_page_id = ANY($1::int[]) AND l.to_page_id = ANY($1::int[])+ AND ${from} AND ${to} AND ${origin}+ GROUP BY l.to_page_id HAVING COUNT(DISTINCT l.from_page_id) >= 1`, params);+ return new Map(rows.map(row => [Number(row.to_page_id), { hits: Number(row.hits), cross_source_hits: Number(row.cross_source_hits) }]));+}++export async function readContentFlags(query: ReadQuery, ids: number[], scope?: PageReadScope): Promise<Map<number, { reason: string; detail: string }>> {+ if (!ids.length) return new Map();+ const params: unknown[] = [ids];+ const filter = pageReadFilter('p', scope, params, !!scope);+ const rows = await query<{ id: number; reason: string | null; detail: string | null }>(`+ SELECT p.id, p.frontmatter->'content_flag'->>'reason' AS reason,+ p.frontmatter->'content_flag'->>'detail' AS detail FROM pages p+ WHERE p.id = ANY($1::int[]) AND p.frontmatter ? 'content_flag' AND ${filter}`, params);+ return new Map(rows.filter(row => row.reason).map(row => [Number(row.id), { reason: row.reason!, detail: row.detail ?? '' }]));+}++export async function readExtractionStates(query: ReadQuery, ids: number[], scope?: PageReadScope): Promise<Map<number, { unverified: boolean; status: string }>> {+ if (!ids.length) return new Map();+ const params: unknown[] = [ids];+ const filter = pageReadFilter('p', scope, params, !!scope);+ const rows = await query<{ id: number; status: string; unverified: boolean }>(`+ SELECT p.id, p.frontmatter->>'status' AS status, (${unverifiedExtractionFragment('p')}) AS unverified+ FROM pages p WHERE p.id = ANY($1::int[]) AND p.frontmatter->>'status' IS NOT NULL AND ${filter}`, params);+ return new Map(rows.map(row => [Number(row.id), { unverified: row.unverified === true, status: row.status }]));+}++export async function readEffectiveDates(query: ReadQuery, refs: PageRef[], scope?: PageReadScope): Promise<Map<string, Date>> {+ if (!refs.length) return new Map();+ const params: unknown[] = [refs.map(r => r.slug), refs.map(r => r.source_id)];+ const filter = pageReadFilter('p', scope, params, !!scope);+ const rows = await query<{ slug: string; source_id: string; ts: string | Date }>(`+ SELECT p.slug, p.source_id, COALESCE(p.effective_date, p.updated_at, p.created_at) AS ts+ FROM pages p JOIN unnest($1::text[], $2::text[]) AS u(slug, source_id)+ ON p.slug = u.slug AND p.source_id = u.source_id WHERE ${filter}`, params);+ return new Map(rows.map(row => [`${row.source_id}::${row.slug}`, row.ts instanceof Date ? row.ts : new Date(row.ts)]));+}++export async function readSalienceScores(query: ReadQuery, refs: PageRef[], scope?: PageReadPolicy): Promise<Map<string, number>> {+ if (!refs.length) return new Map();+ const params: unknown[] = [refs.map(r => r.slug), refs.map(r => r.source_id)];+ const filter = pageReadFilter('p', scope, params, !!scope);+ const restricted = scope?.takesHoldersAllowList !== undefined;+ let holder = '';+ if (restricted) {+ params.push(scope.takesHoldersAllowList);+ holder = `AND t.holder = ANY($${params.length}::text[])`;+ }+ const rows = await query<{ slug: string; source_id: string; score: number }>(`+ SELECT p.slug, p.source_id,+ (${restricted ? '0' : 'COALESCE(p.emotional_weight, 0) * 5'} + ln(1 + COUNT(DISTINCT t.id))) AS score+ FROM pages p JOIN unnest($1::text[], $2::text[]) AS u(slug, source_id)+ ON p.slug = u.slug AND p.source_id = u.source_id+ LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE ${holder}+ WHERE ${filter} GROUP BY p.id`, params);+ return new Map(rows.map(row => [`${row.source_id}::${row.slug}`, Number(row.score)]));+}++/** Resolve alias contributors before callers rank or cap canonical pages. */+export async function readAliases(query: ReadQuery, aliases: string[], scope?: PageReadScope): Promise<Map<string, PageRef[]>> {+ const out = new Map<string, PageRef[]>();+ if (!aliases.length) return out;+ const params: unknown[] = [aliases];+ const filter = pageReadFilter('p', scope, params, true);+ const rows = await query<PageRef & { alias_norm: string }>(`+ SELECT a.alias_norm, a.slug, a.source_id FROM page_aliases a+ JOIN pages p ON p.source_id = a.source_id AND p.slug = a.slug+ WHERE a.alias_norm = ANY($1::text[]) AND ${filter}+ ORDER BY a.alias_norm, a.source_id, a.slug`, params);+ for (const row of rows) {+ const refs = out.get(row.alias_norm) ?? [];+ if (!refs.some(ref => ref.slug === row.slug && ref.source_id === row.source_id)) refs.push({ slug: row.slug, source_id: row.source_id });+ out.set(row.alias_norm, refs);+ }+ return out;+}diff --git a/src/core/search/read-policy-sql.ts b/src/core/search/read-policy-sql.tsnew file mode 100644index 0000000000..20d306676b--- /dev/null+++ b/src/core/search/read-policy-sql.ts@@ -0,0 +1,32 @@+import type { PageReadScope, PageReadPolicy } from '../types.ts';+import { privatePagesFilterFragment } from './private-visibility.ts';+import { quarantineFilterFragment } from '../quarantine.ts';++/** Preserve unrestricted local reads while retaining source-only restrictions. */+export function hasReadPolicy(scope?: PageReadPolicy): boolean {+ return !!(scope?.sourceIds?.length || scope?.sourceId || scope?.excludePrivate || scope?.requireSafeChunks || scope?.takesHoldersAllowList !== undefined);+}++/** Callers supply fixed SQL aliases; all policy values are bound parameters. */+export function pageReadFilter(+ alias: string,+ scope: PageReadScope | undefined,+ params: unknown[],+ live = false,+): string {+ const clauses: string[] = [];+ if (scope?.sourceIds?.length) {+ params.push(scope.sourceIds);+ clauses.push(`${alias}.source_id = ANY($${params.length}::text[])`);+ } else if (scope?.sourceId) {+ params.push(scope.sourceId);+ clauses.push(`${alias}.source_id = $${params.length}`);+ }+ if (scope?.excludePrivate) clauses.push(privatePagesFilterFragment(alias));+ if (live) clauses.push(+ `${alias}.deleted_at IS NULL`,+ quarantineFilterFragment(alias),+ `EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = ${alias}.source_id AND NOT read_source.archived)`,+ );+ return clauses.length ? clauses.join(' AND ') : 'TRUE';+}diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.tsindex fe030f2385..1a1ecee926 100644--- a/src/core/search/relational-recall.ts+++ b/src/core/search/relational-recall.ts@@ -25,14 +25,16 @@*/import type { BrainEngine } from '../engine.ts';-import type { SearchResult, PageType, RelationalFanoutRow } from '../types.ts';+import type { SearchResult, PageType, RelationalFanoutRow, PageReadPolicy } from '../types.ts';import { createAuditWriter } from '../audit/audit-writer.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { buildVisibilityClause } from './sql-ranking.ts';+import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';import { parseRelationalQuery, type RelationalQuery, type RelationVocab } from './relational-intent.ts';import { stampEvidence, type EvidenceOpts } from './evidence.ts';-export interface RelationalArmOpts {+export interface RelationalArmOpts extends PageReadPolicy {sourceId?: string;sourceIds?: string[];depth?: number;@@ -93,6 +95,7 @@ async function resolveSeedScoped(engine: BrainEngine,sources: string[],phrase: string,+ policy: PageReadPolicy,): Promise<Array<{ source_id: string; slug: string }>> {const out: Array<{ source_id: string; slug: string }> = [];const seen = new Set<string>();@@ -104,7 +107,16 @@ async function resolveSeedScoped(seen.add(key);out.push({ source_id: sid, slug: r.slug });}- return out;+ if (!out.length || !hasReadPolicy(policy)) return out;+ const params: unknown[] = [out.map(ref => ref.source_id), out.map(ref => ref.slug)];+ const filter = pageReadFilter('p', policy, params, true);+ const admitted = await engine.executeRaw<{ source_id: string; slug: string }>(+ `SELECT p.source_id, p.slug FROM pages p+ JOIN unnest($1::text[], $2::text[]) AS refs(source_id, slug)+ ON p.source_id = refs.source_id AND p.slug = refs.slug WHERE ${filter}`, params,+ );+ const allowed = new Set(admitted.map(ref => `${ref.source_id}:${ref.slug}`));+ return out.filter(ref => allowed.has(`${ref.source_id}:${ref.slug}`));}/** Batch-hydrate fanout rows into SearchResult rows in fanout (ranked) order.@@ -116,19 +128,22 @@ async function hydrate(engine: BrainEngine,rows: RelationalFanoutRow[],seedSlug: string,- excludePrivate: boolean,+ policy: PageReadPolicy,): Promise<SearchResult[]> {if (rows.length === 0) return [];- const slugs = Array.from(new Set(rows.map(r => r.slug)));+ const params: unknown[] = [rows.map(r => r.source_id), rows.map(r => r.slug)];+ const filter = pageReadFilter('p', policy, params);const pageRows = await engine.executeRaw<{page_id: number; slug: string; source_id: string; title: string; type: string; synopsis: string | null;}>(`SELECT p.id AS page_id, p.slug, p.source_id, p.title, p.type,- LEFT(p.compiled_truth, 240) AS synopsis+ p.compiled_truth AS synopsisFROM pages pJOIN sources s ON s.id = p.source_id- WHERE p.slug = ANY($1::text[]) ${buildVisibilityClause('p', 's', { excludePrivate })}`,- [slugs],+ JOIN unnest($1::text[], $2::text[]) AS refs(source_id, slug)+ ON p.source_id = refs.source_id AND p.slug = refs.slug+ WHERE ${filter} ${buildVisibilityClause('p', 's', { excludePrivate: policy.excludePrivate, requireSafeChunks: false })}`,+ params,);const byKey = new Map<string, typeof pageRows[number]>();for (const pr of pageRows) byKey.set(`${pr.source_id}:${pr.slug}`, pr);@@ -142,7 +157,7 @@ async function hydrate(page_id: pr.page_id,title: pr.title,type: pr.type as PageType,- chunk_text: pr.synopsis ?? r.slug,+ chunk_text: sanitizeRemoteBody(pr.synopsis ?? r.slug).slice(0, 240),chunk_source: 'compiled_truth',// E1: reinforce the page's REAL canonical chunk; F3: chunkless entity// pages key page-level (chunk_id 0 → rrfKey `source:slug:0`, stable and@@ -273,6 +288,11 @@ export async function buildRelationalArm(try {const sources = scopeSources(opts);const fanoutOpts = {+ sourceId: opts.sourceId,+ sourceIds: opts.sourceIds,+ excludePrivate: opts.excludePrivate,+ requireSafeChunks: opts.requireSafeChunks,+ takesHoldersAllowList: opts.takesHoldersAllowList,linkTypes: parsed.linkTypes,direction: parsed.direction,depth: opts.depth,@@ -281,20 +301,15 @@ export async function buildRelationalArm(if (parsed.kind === 'connects' && parsed.seeds.length === 2) {// Resolve both endpoints; both must resolve or the arm no-ops.- const resA = await resolveSeedScoped(engine, sources, parsed.seeds[0]);- const resB = await resolveSeedScoped(engine, sources, parsed.seeds[1]);+ const resA = await resolveSeedScoped(engine, sources, parsed.seeds[0], opts);+ const resB = await resolveSeedScoped(engine, sources, parsed.seeds[1], opts);if (resA.length === 0 || resB.length === 0) return finish([]);meta.seeds_resolved = resA.length + resB.length;- const perSource = (rs: typeof resA) => ({- sourceId: rs.length === 1 ? rs[0].source_id : undefined,- sourceIds: rs.length > 1 ? Array.from(new Set(rs.map(x => x.source_id))) : undefined,- slugs: Array.from(new Set(rs.map(x => x.slug))),- });- const a = perSource(resA);- const b = perSource(resB);- const fanA = await engine.relationalFanout(a.slugs, { ...fanoutOpts, sourceId: a.sourceId, sourceIds: a.sourceIds });- const fanB = await engine.relationalFanout(b.slugs, { ...fanoutOpts, sourceId: b.sourceId, sourceIds: b.sourceIds });+ const a = { slugs: [...new Set(resA.map(ref => ref.slug))], seedRefs: resA };+ const b = { slugs: [...new Set(resB.map(ref => ref.slug))], seedRefs: resB };+ const fanA = await engine.relationalFanout(a.slugs, { ...fanoutOpts, seedRefs: a.seedRefs });+ const fanB = await engine.relationalFanout(b.slugs, { ...fanoutOpts, seedRefs: b.seedRefs });// Shared midpoints: nodes reachable from BOTH endpoints (exclude the// endpoints themselves). Ordered by combined hop.const bByKey = new Map(fanB.map(r => [`${r.source_id}:${r.slug}`, r] as const));@@ -304,23 +319,21 @@ export async function buildRelationalArm(.map(r => ({ row: r, combined: r.hop + bByKey.get(`${r.source_id}:${r.slug}`)!.hop })).sort((x, y) => x.combined - y.combined || x.row.slug.localeCompare(y.row.slug)).map(x => x.row);- const list = await hydrate(engine, shared, parsed.seeds.join(' ↔ '), opts.excludePrivate === true);+ const list = await hydrate(engine, shared, parsed.seeds.join(' ↔ '), opts);meta.fired = list.length > 0;return finish(list);}// who_rel / who_at / intro: single logical seed (may resolve in N sources).- const resolved = await resolveSeedScoped(engine, sources, parsed.seeds[0]);+ const resolved = await resolveSeedScoped(engine, sources, parsed.seeds[0], opts);if (resolved.length === 0) return finish([]);meta.seeds_resolved = resolved.length;const slugs = Array.from(new Set(resolved.map(r => r.slug)));- const srcIds = Array.from(new Set(resolved.map(r => r.source_id)));const rows = await engine.relationalFanout(slugs, {...fanoutOpts,- sourceId: srcIds.length === 1 ? srcIds[0] : undefined,- sourceIds: srcIds.length > 1 ? srcIds : undefined,+ seedRefs: resolved,});- const list = await hydrate(engine, rows, resolved[0].slug, opts.excludePrivate === true);+ const list = await hydrate(engine, rows, resolved[0].slug, opts);meta.fired = list.length > 0;return finish(list);} catch (err) {diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.tsnew file mode 100644index 0000000000..a342ba252f--- /dev/null+++ b/src/core/search/safe-chunks.ts@@ -0,0 +1,69 @@+import type { ChunkInput, PageReadScope } from '../types.ts';++/** First markdown index built from the strict full-body fence sanitizer. */+export const SAFE_FENCE_CHUNKER_VERSION = 4;++const PROTECTED_MARKER = '<!--- gbrain:(facts|takes):(begin|end) -->';++export function hasProtectedBody(text: string): boolean {+ return new RegExp(PROTECTED_MARKER).test(text);+}++/** Expression and aliases are internal SQL, never caller-supplied values. */+export function protectedTextFilter(expression: string): string {+ return `COALESCE(${expression}, '') ~ '${PROTECTED_MARKER}'`;+}++/** Fixed SQL aliases only. Check full bodies because fragments can lose markers. */+export function protectedBodyFilter(alias: string): string {+ return `(${protectedTextFilter(`${alias}.compiled_truth`)} OR ${protectedTextFilter(`${alias}.timeline`)})`;+}++/** A body-only write cannot certify old fragments, even after fence removal. */+export function bodyWriteChunkVersion(compiledTruth: string, timeline: string): string {+ return `CASE WHEN pages.compiled_truth IS NOT DISTINCT FROM ${compiledTruth}+ AND pages.timeline IS NOT DISTINCT FROM ${timeline} THEN pages.chunker_version+ WHEN pages.chunker_version < 0 OR ${protectedBodyFilter('pages')}+ OR ${protectedTextFilter(compiledTruth)} OR ${protectedTextFilter(timeline)} THEN -1+ ELSE LEAST(COALESCE(pages.chunker_version, 0), ${SAFE_FENCE_CHUNKER_VERSION - 1}) END`;+}++export function requiresSafeChunks(scope?: PageReadScope): boolean {+ return scope?.requireSafeChunks ?? scope?.excludePrivate ?? false;+}++/** Older fragments lack trustworthy provenance, even if markers were removed later. */+export function safeChunksFilter(alias: string): string {+ return `COALESCE(${alias}.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}`;+}++/**+ * Preserve an existing seal for an embedding-only refresh of the exact chunk+ * snapshot. Additions, removals and textual metadata changes invalidate before+ * the first mutation, including partial failures outside an import transaction.+ * Both engines canonicalize chunk_text before calling, and persist/hash those+ * same bytes. Identity and enum fields retain their existing rejection policy.+ */+export function chunkWriteInvalidation(pageId: number, chunks: ChunkInput[]): { sql: string; params: unknown[] } {+ const metadata = ['language', 'symbol_name', 'symbol_type', 'start_line', 'end_line', 'parent_symbol_path', 'doc_comment', 'symbol_name_qualified'] as const;+ const incoming = chunks.map(chunk => Object.fromEntries(+ ['chunk_index', 'chunk_text', 'chunk_source', 'modality', ...metadata].map(key => [key, chunk[key as keyof ChunkInput] ?? null]),+ ));+ return {+ sql: `UPDATE pages SET chunker_version = -1 WHERE id = $1 AND (+ NOT (${safeChunksFilter('pages')}) OR EXISTS (+ SELECT 1 FROM (SELECT * FROM content_chunks WHERE page_id = $1) cc+ FULL JOIN jsonb_to_recordset($2::text::jsonb) AS incoming(+ chunk_index int, chunk_text text, chunk_source text, modality text,+ language text, symbol_name text, symbol_type text, start_line int,+ end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text)+ ON incoming.chunk_index = cc.chunk_index+ WHERE cc.id IS NULL OR incoming.chunk_index IS NULL+ OR cc.chunk_text IS DISTINCT FROM incoming.chunk_text+ OR cc.chunk_source IS DISTINCT FROM incoming.chunk_source+ OR cc.modality IS DISTINCT FROM COALESCE(incoming.modality, 'text')+ ${metadata.map(key => `OR cc.${key} IS DISTINCT FROM COALESCE(incoming.${key}, cc.${key})`).join('\n ')}+ ))`,+ params: [pageId, JSON.stringify(incoming)],+ };+}diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.tsindex 078bea7350..c36bbb56f8 100644--- a/src/core/search/sql-ranking.ts+++ b/src/core/search/sql-ranking.ts@@ -20,6 +20,7 @@import { quarantineFilterFragment } from '../quarantine.ts';import { unverifiedExtractionFragment } from '../extraction-review.ts';import { privatePagesFilterFragment } from './private-visibility.ts';+import { requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';/*** Escape `%`, `_`, and `\` so a string can be used as a LIKE prefix literal.@@ -183,6 +184,7 @@ export function buildVisibilityClause(* are unchanged.*/excludePrivate?: boolean;+ requireSafeChunks?: boolean;},): string {// Single source of truth for the quarantine SQL lives in quarantine.ts so@@ -193,7 +195,8 @@ export function buildVisibilityClause(const privateClause = opts?.excludePrivate? ` AND ${privatePagesFilterFragment(pageAlias)}`: '';- return `AND ${pageAlias}.deleted_at IS NULL AND NOT ${sourceAlias}.archived AND ${quarantine}${privateClause}`;+ const chunksClause = requiresSafeChunks(opts) ? ` AND ${safeChunksFilter(pageAlias)}` : '';+ return `AND ${pageAlias}.deleted_at IS NULL AND NOT ${sourceAlias}.archived AND ${quarantine}${privateClause}${chunksClause}`;}// ============================================================diff --git a/src/core/think/gather.ts b/src/core/think/gather.tsindex 9bd72e7afe..4855f5ab66 100644--- a/src/core/think/gather.ts+++ b/src/core/think/gather.ts@@ -17,6 +17,7 @@import type { BrainEngine, TakeHit, Take } from '../engine.ts';import { hybridSearch } from '../search/hybrid.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';import type { Page, SearchResult } from '../types.ts';import { filterPagesToWindow, type TemporalWindow } from './temporal-window.ts';import { sanitizeQueryForPrompt } from '../search/expansion.ts';@@ -38,6 +39,8 @@ export interface ThinkGatherOpts {window?: TemporalWindow;/** When set, MCP-bound calls forward this allow-list to takes_search. Local CLI leaves unset. */takesHoldersAllowList?: string[];+ excludePrivate?: boolean;+ remote?: boolean;/** Source scope inherited from the caller. Federated array wins over scalar. */sourceId?: string;sourceIds?: string[];@@ -121,6 +124,8 @@ export async function runGather(: opts.sourceId? { sourceId: opts.sourceId }: {};+ const pageScope = { ...sourceScope, excludePrivate: opts.excludePrivate, requireSafeChunks: opts.remote !== false, takesHoldersAllowList: opts.takesHoldersAllowList };+ const visibleBody = (body: string) => opts.remote === false ? body : sanitizeRemoteBody(body);// Sanitize the question for any path that includes it in an LLM prompt.// (Direct DB search is fine — those are parameterized queries.)@@ -131,7 +136,7 @@ export async function runGather(const toSearchResult = (page: Page, rank: number): SearchResult => ({slug: page.slug, page_id: page.id, title: page.title, type: page.type,- chunk_text: page.compiled_truth ?? '', chunk_source: 'compiled_truth',+ chunk_text: visibleBody(page.compiled_truth ?? ''), chunk_source: 'compiled_truth',chunk_id: 0, chunk_index: 0, score: 1 / (51 + rank), stale: false,source_id: page.source_id ?? 'default',effective_date: page.effective_date instanceof Date ? page.effective_date.toISOString() : null,@@ -151,12 +156,12 @@ export async function runGather(limit: Math.min(gatherLimit * 4, 200),expansion: false,autocut: false,- ...sourceScope,+ ...pageScope,}),engine.listPages({...(window.startMs !== null ? { effective_after: new Date(window.startMs).toISOString() } : {}),...(window.endMs !== null ? { effective_before: new Date(window.endMs).toISOString() } : {}),- limit: 50, ...sourceScope,+ limit: 50, ...pageScope,}).then(pages => pages.map(toSearchResult)).catch((e) => {warnings.push('GATHER_WINDOW_FLOOR_FAILED');process.stderr.write(`[think.gather] window floor failed: ${(e as Error).message}\n`);@@ -172,7 +177,7 @@ export async function runGather(limit: gatherLimit,expansion: false,autocut: false,- ...sourceScope,+ ...pageScope,})).catch((e) => {warnings.push('GATHER_HYBRID_FAILED');process.stderr.write(`[think.gather] hybrid stream failed: ${(e as Error).message}\n`);@@ -182,8 +187,7 @@ export async function runGather(// Stream 2: keyword search across takes.const takesKwPromise = engine.searchTakes(opts.question, {limit: takesLimit,- takesHoldersAllowList: opts.takesHoldersAllowList,- ...sourceScope,+ ...pageScope,}).catch((e) => {warnings.push('GATHER_TAKES_KEYWORD_FAILED');process.stderr.write(`[think.gather] takes-keyword stream failed: ${(e as Error).message}\n`);@@ -194,8 +198,7 @@ export async function runGather(const takesVecPromise: Promise<TakeHit[]> = opts.questionEmbedding? engine.searchTakesVector(opts.questionEmbedding, {limit: takesLimit,- takesHoldersAllowList: opts.takesHoldersAllowList,- ...sourceScope,+ ...pageScope,}).catch((e) => {warnings.push('GATHER_TAKES_VECTOR_FAILED');process.stderr.write(`[think.gather] takes-vector stream failed: ${(e as Error).message}\n`);@@ -205,7 +208,7 @@ export async function runGather(// Stream 4: graph walk (anchor only).const graphPromise: Promise<string[]> = opts.anchor- ? engine.traversePaths(opts.anchor, { depth: graphDepth, direction: 'both', ...sourceScope })+ ? engine.traversePaths(opts.anchor, { depth: graphDepth, direction: 'both', ...pageScope }).then(paths => {const slugs = new Set<string>([opts.anchor!]);for (const p of paths) {@@ -228,7 +231,7 @@ export async function runGather(// compiled_truth always reaches the <pages> block.let anchorHydrateFailed = false;const anchorPagePromise: Promise<Page | null> = opts.anchor- ? engine.getPage(opts.anchor, sourceScope).catch((e) => {+ ? engine.getPage(opts.anchor, pageScope).catch((e) => {anchorHydrateFailed = true;warnings.push('GATHER_ANCHOR_HYDRATE_FAILED');process.stderr.write(`[think.gather] anchor hydrate failed: ${(e as Error).message}\n`);@@ -254,9 +257,10 @@ export async function runGather(pages.unshift({slug: anchorPage.slug,page_id: anchorPage.id,+ source_id: anchorPage.source_id ?? 'default',title: anchorPage.title,type: anchorPage.type,- chunk_text: anchorPage.compiled_truth,+ chunk_text: visibleBody(anchorPage.compiled_truth),chunk_source: 'compiled_truth',chunk_id: 0,chunk_index: 0,diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 113a31ceda..7f426ad65b 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -32,6 +32,7 @@ import { AIConfigError } from '../ai/errors.ts';import { normalizeModelId } from '../model-id.ts';import { hasAnthropicKey } from '../ai/anthropic-key.ts';import { parseTemporalWindow } from './temporal-window.ts';+import { resolveExcludePrivatePages } from '../search/private-visibility.ts';/** Anthropic Messages client interface — same shape used by subagent.ts so test stubs can be shared. */export interface ThinkLLMClient {@@ -80,6 +81,8 @@ export interface RunThinkOpts {until?: string;/** When set, MCP-bound calls forward this to the gather phase (server-side filter). */takesHoldersAllowList?: string[];+ /** Resolved operation-layer page visibility policy. */+ excludePrivate?: boolean;/** Inject an LLM client (for tests). Defaults to a fresh Anthropic SDK client. */client?: ThinkLLMClient;/** Inject a question-embedding function. When omitted, vector takes search is skipped. */@@ -531,7 +534,9 @@ export async function runThink(anchor: opts.anchor,questionEmbedding,...(window ? { window } : {}),- takesHoldersAllowList: opts.takesHoldersAllowList,+ takesHoldersAllowList: opts.remote === false ? opts.takesHoldersAllowList : opts.takesHoldersAllowList ?? ['world'],+ excludePrivate: opts.excludePrivate ?? await resolveExcludePrivatePages(engine, opts.remote),+ remote: opts.remote,...(opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),...(opts.allowedSources !== undefined ? { sourceIds: opts.allowedSources } : {}),});diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex f0b8d477f9..f24e64e70e 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -1,3 +1,4 @@+import { bodyWriteChunkVersion } from './search/safe-chunks.ts';/*** #1856 — write-through for manual timeline entries.*@@ -406,7 +407,7 @@ export async function writeTimelineEntryThrough(spliceTimelineBlock(page.timeline ?? '', entry.date, rendered.block),);await engine.executeRaw(- `UPDATE pages SET timeline = $1, updated_at = now()+ `UPDATE pages SET timeline = $1, chunker_version = ${bodyWriteChunkVersion('pages.compiled_truth', '$1')}, updated_at = now()WHERE slug = $2 AND source_id = $3 AND deleted_at IS NULL`,[newTimeline, slug, sourceId],);diff --git a/src/core/types.ts b/src/core/types.tsindex 8b5da7c724..88a7260fb5 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -361,7 +361,21 @@ export interface PageFilters {}/** v0.26.5 — opts for getPage / softDeletePage / restorePage. */-export interface GetPageOpts {+export interface PageReadScope {+ sourceId?: string;+ sourceIds?: string[];+ /** Resolved by the trusted operation layer, never from MCP parameters. */+ excludePrivate?: boolean;+ /** Untrusted chunk reads require a verified protected-body index, even with visibility opt-outs. */+ requireSafeChunks?: boolean;+}++export interface PageReadPolicy extends PageReadScope {+ /** Undefined is unrestricted; an empty list permits no holders. */+ takesHoldersAllowList?: string[];+}++export interface GetPageOpts extends PageReadScope {/** Filter to a specific source. When omitted, getPage returns the first slug match across sources (pre-existing semantics). */sourceId?: string;/**@@ -446,7 +460,7 @@ export interface DomainBankRow {representative_chunk_id: number | null;}-export interface SalienceOpts {+export interface SalienceOpts extends PageReadPolicy {/** Scalar source scope. Ignored when `sourceIds` is set (array wins). */sourceId?: string;/** Federated source scope — the op layer passes `ctx.auth.allowedSources`. */@@ -550,7 +564,7 @@ export const ENRICH_ORDER_SQL: Record<EnrichCandidatesOpts['order'], string> = {* the number of distinct pages touched on `since`. A cohort is anomalous when its* current count exceeds `mean + sigma * stddev`. Year cohort deferred to v0.30.*/-export interface AnomaliesOpts {+export interface AnomaliesOpts extends PageReadScope {/** Scalar source scope. Ignored when `sourceIds` is set (array wins). */sourceId?: string;/** Federated source scope — the op layer passes `ctx.auth.allowedSources`. */@@ -1055,7 +1069,7 @@ export interface ResolvedColumn {embeddingModel: string;}-export interface SearchOpts {+export interface SearchOpts extends PageReadPolicy {limit?: number;offset?: number;/**@@ -1440,7 +1454,9 @@ export interface RelationalFanoutRow {}/** Options for BrainEngine.relationalFanout. */-export interface RelationalFanoutOpts {+export interface RelationalFanoutOpts extends PageReadPolicy {+ /** Resolved seed identities; separate from the read grant for edge origins. */+ seedRefs?: Array<{ source_id: string; slug: string }>;/** Edge types to traverse; null/empty = type-agnostic. */linkTypes?: string[] | null;/** Direction from each seed. Default 'both'. */@@ -1475,7 +1491,7 @@ export interface TimelineInput {detail?: string;}-export interface TimelineOpts {+export interface TimelineOpts extends PageReadScope {limit?: number;after?: string;before?: string;@@ -1511,7 +1527,7 @@ export interface ChronicleTimelineRow {kind: string | null; // event.kind from the event page frontmatter}-export interface ChronicleTimelineOpts {+export interface ChronicleTimelineOpts extends PageReadScope {/** getTimelineForDate: expand to the ISO week (Mon–Sun) containing `date`. */week?: boolean;/** getSince: filter event projections by `event.kind`. */diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 81b641232c..b04e0dedf8 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.48.2.0 -->+<!-- gbrain-template-stamp: 0.48.3.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/bootstrap-doctor-checks.test.ts b/test/bootstrap-doctor-checks.test.tsindex 74178efe0c..b4cd6cc3cb 100644--- a/test/bootstrap-doctor-checks.test.ts+++ b/test/bootstrap-doctor-checks.test.ts@@ -13,7 +13,7 @@* mutation, no PGLite engine (checks accept `engine: null`; the one* engine-shaped check gets a stub with just `getConfig`).*/-import { describe, test, expect, afterAll } from 'bun:test';+import { describe, test, expect, afterAll, spyOn } from 'bun:test';import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -712,14 +712,21 @@ describe('bootstrap_durability_job [B7/D7]', () => {// the verdict). Fresh empty HOME → durabilityJobStatus kind 'none'.const fakeHome = mkdtempSync(join(tmpdir(), 'gb-bdc-fakehome-'));tmpDirs.push(fakeHome);- const checks = await withEnv(- { ...NEUTRAL_ENV, GBRAIN_HOME: parent, HOME: fakeHome },- () => bootstrapDoctorChecks(null),- );- const c = byName(checks, 'bootstrap_durability_job');- expect(c?.status).toBe('warn');- expect(c?.message).toContain('PERSIST_CRON=yes');- expect(c?.message).toContain('gbrain sources harden workspace');+ // Clearing env cannot erase Docker's /.dockerenv. Pin the branch this+ // fixture exercises; execution-env.test.ts independently covers detection.+ const environment = spyOn(await import('../src/core/execution-env.ts'), 'detectExecutionEnvironment').mockReturnValue('local');+ try {+ const checks = await withEnv(+ { ...NEUTRAL_ENV, GBRAIN_HOME: parent, HOME: fakeHome },+ () => bootstrapDoctorChecks(null),+ );+ const c = byName(checks, 'bootstrap_durability_job');+ expect(c?.status).toBe('warn');+ expect(c?.message).toContain('PERSIST_CRON=yes');+ expect(c?.message).toContain('gbrain sources harden workspace');+ } finally {+ environment.mockRestore();+ }}, T);});diff --git a/test/check-bootstrap-guards.test.ts b/test/check-bootstrap-guards.test.tsindex a89e78ae84..317acb00f6 100644--- a/test/check-bootstrap-guards.test.ts+++ b/test/check-bootstrap-guards.test.ts@@ -465,10 +465,11 @@ describe('verify + workflow wiring', () => {expect(pkg.scripts['check:bootstrap-templates']).toContain('check-bootstrap-templates.sh');});- test('ci-cache-hash re-admits the bootstrap entry docs [C2]', () => {- const script = require('node:fs').readFileSync(join(ROOT, 'scripts/ci-cache-hash.sh'), 'utf8');- expect(script).toContain("'README\\.md$'");- expect(script).toContain("'BOOTSTRAP_FOR_AGENTS\\.md$'");+ test('bootstrap guards run for documentation changes without a result-cache bypass [C2]', () => {+ const workflow = require('node:fs').readFileSync(join(ROOT, '.github/workflows/test.yml'), 'utf8');+ expect(workflow).toContain('bun run verify');+ expect(workflow).not.toContain('paths-ignore:');+ expect(workflow).not.toContain('cache-check');});test('release.yml advances latest-stable only as the final release step [C1]', () => {diff --git a/test/chunker-version-insert-default.test.ts b/test/chunker-version-insert-default.test.tsindex 86980ee452..c786503225 100644--- a/test/chunker-version-insert-default.test.ts+++ b/test/chunker-version-insert-default.test.ts@@ -1,80 +1,83 @@-/**- * #2807 — putPage INSERT default for chunker_version.- *- * postgres-engine / pglite-engine used `COALESCE(<chunkerVersion>, 1)` in the- * pages INSERT. Callers that don't supply chunker_version (no MCP/subagent- * caller does — it's internal metadata) landed new pages at version 1, so- * doctor's contextual_retrieval_coverage check flagged dream-written pages as- * "older chunker_version" forever, even though they were chunked/embedded with- * the current chunker.- *- * Fix: default the INSERT to MARKDOWN_CHUNKER_VERSION. The ON CONFLICT UPDATE- * still COALESCE-preserves an explicitly supplied version.- */-+/** Chunk safety versions are minted by full imports, never body-only writes. */import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';+import { importFromContent } from '../src/core/import-file.ts';+import type { ChunkInput } from '../src/core/types.ts';-describe('#2807 — putPage chunker_version INSERT default', () => {- let engine: PGLiteEngine;+const protectedBody = 'Public version fixture.\n<!--- gbrain:takes:begin -->\nPRIVATE_VERSION_CANARY\n<!--- gbrain:takes:end -->';+describe('verified chunk safety versions', () => {+ let engine: PGLiteEngine;beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();});+ afterAll(async () => { await engine.disconnect(); }, 30_000);- afterAll(async () => {- await engine.disconnect();- }, 30_000);-- async function readChunkerVersion(slug: string): Promise<number> {- const { rows } = await (engine as any).db.query(- `SELECT chunker_version FROM pages WHERE slug = $1`,- [slug],- );- return Number((rows[0] as { chunker_version: number }).chunker_version);+ async function version(slug: string): Promise<number> {+ const rows = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE slug = $1', [slug]);+ return Number(rows[0].chunker_version);}+ async function imported(slug: string, body = protectedBody) {+ await importFromContent(engine, slug, `---\ntype: note\ntitle: Version fixture\n---\n${body}`, { noEmbed: true, forceRechunk: true });+ expect(await version(slug)).toBe(MARKDOWN_CHUNKER_VERSION);+ return (await engine.getPage(slug, { sourceId: 'default' }))!;+ }++ test('body-only insert is unsealed, and explicit current versions cannot certify chunks', async () => {+ for (const supplied of [undefined, MARKDOWN_CHUNKER_VERSION, 2]) {+ const slug = `notes/unsealed-${supplied ?? 'unset'}`;+ await engine.putPage(slug, { type: 'note', title: 'Version fixture', compiled_truth: protectedBody, chunker_version: supplied });+ expect(await version(slug)).toBeLessThan(MARKDOWN_CHUNKER_VERSION);+ if (supplied === 2) expect(await version(slug)).toBe(2);+ }+ });- test('page written without chunker_version defaults to MARKDOWN_CHUNKER_VERSION, not 1', async () => {- await engine.putPage('dream/no-chunker-version', {- type: 'concept',- title: 'Dream synthesized page',- compiled_truth: 'Written directly through putPage, like a dream subagent.',- timeline: '',- });- expect(await readChunkerVersion('dream/no-chunker-version')).toBe(MARKDOWN_CHUNKER_VERSION);- expect(MARKDOWN_CHUNKER_VERSION).toBeGreaterThan(1);+ test('metadata-only put preserves a seal, body changes invalidate it even after marker removal', async () => {+ const slug = 'notes/body-write-version';+ const page = await imported(slug);+ await engine.putPage(slug, { ...page, title: 'Changed public title' });+ expect(await version(slug)).toBe(MARKDOWN_CHUNKER_VERSION);+ await engine.putPage(slug, { ...page, compiled_truth: 'All markers removed.', chunker_version: MARKDOWN_CHUNKER_VERSION });+ expect(await version(slug)).toBeLessThan(0);+ expect(await engine.getChunks(slug, { requireSafeChunks: true })).toEqual([]);+ expect((await engine.getChunks(slug)).length).toBeGreaterThan(0);});- test('explicit chunker_version is honored on INSERT', async () => {- await engine.putPage('dream/explicit-chunker-version', {- type: 'concept',- title: 'Explicit version',- compiled_truth: 'Caller supplied a version.',- timeline: '',- chunker_version: 2,- });- expect(await readChunkerVersion('dream/explicit-chunker-version')).toBe(2);+ test('embedding-only refresh preserves a seal; text, metadata, and chunk-set changes invalidate', async () => {+ const slug = 'notes/chunk-write-version';+ await imported(slug);+ let chunks = await engine.getChunks(slug);+ const vector = new Float32Array(1536); vector[0] = 1;+ await engine.upsertChunks(slug, chunks.map(chunk => ({ ...chunk, embedding: vector })) as ChunkInput[]);+ expect(await version(slug)).toBe(MARKDOWN_CHUNKER_VERSION);+ expect((await engine.getChunks(slug, { requireSafeChunks: true }))[0].embedding_is_null).toBe(false);+ for (const mutation of ['text', 'metadata', 'addition', 'removal']) {+ await imported(slug);+ chunks = await engine.getChunks(slug);+ const next = chunks.map(chunk => ({ ...chunk })) as ChunkInput[];+ if (mutation === 'text') next[0].chunk_text = 'PRIVATE_REPLACEMENT_CANARY';+ if (mutation === 'metadata') next[0].doc_comment = 'PRIVATE_METADATA_CANARY';+ if (mutation === 'addition') next.push({ chunk_index: next.length, chunk_source: 'compiled_truth', chunk_text: 'PRIVATE_ADDED_CANARY' });+ if (mutation === 'removal') next.length = 0;+ await engine.upsertChunks(slug, next);+ expect(await version(slug), mutation).toBeLessThan(0);+ expect(await engine.getChunks(slug, { requireSafeChunks: true })).toEqual([]);+ }});- test('re-put without chunker_version does not lower an already-current version', async () => {- await engine.putPage('dream/preserve-version', {- type: 'concept',- title: 'Preserve me',- compiled_truth: 'first write',- timeline: '',- chunker_version: MARKDOWN_CHUNKER_VERSION,- });- // Second write omits chunker_version; the UPDATE branch must not drop it- // below the current chunker version.- await engine.putPage('dream/preserve-version', {- type: 'concept',- title: 'Preserve me',- compiled_truth: 'second write',- timeline: '',- });- expect(await readChunkerVersion('dream/preserve-version')).toBe(MARKDOWN_CHUNKER_VERSION);+ test('refresh and version revert invalidate existing chunks before exposing a changed body', async () => {+ const slug = 'notes/refresh-version';+ await imported(slug);+ await engine.createVersion(slug, { sourceId: 'default' });+ const [snapshot] = await engine.getVersions(slug, { sourceId: 'default' });+ await engine.refreshPageBody(slug, 'default', 'Public replacement body.', '', 'changed');+ expect(await version(slug)).toBeLessThan(0);+ await imported(slug, 'Public replacement body.');+ await engine.revertToVersion(slug, snapshot.id, { sourceId: 'default' });+ expect(await version(slug)).toBeLessThan(0);+ expect(await engine.getChunks(slug, { requireSafeChunks: true })).toEqual([]);});});diff --git a/test/chunkers/recursive.test.ts b/test/chunkers/recursive.test.tsindex b872e082e8..cb5e91daae 100644--- a/test/chunkers/recursive.test.ts+++ b/test/chunkers/recursive.test.ts@@ -135,13 +135,11 @@ describe('Recursive Text Chunker', () => {});describe('CJK chunking (v0.32.7)', () => {- test('MARKDOWN_CHUNKER_VERSION is 3', async () => {- // v0.40.3.0: bumped 2→3 to signal the post-upgrade reembed sweep that- // contextual retrieval wrapping is now applied at embed time. Chunk- // boundaries themselves are unchanged; the bump forces re-embed for- // pages where chunker_version < 3.+ test('MARKDOWN_CHUNKER_VERSION is 4', async () => {+ // v4 verifies strict full-body protected-fence sanitation before every+ // chunk split. Older indexes are unavailable to remote chunk readers.const mod = await import('../../src/core/chunkers/recursive.ts');- expect(mod.MARKDOWN_CHUNKER_VERSION).toBe(3);+ expect(mod.MARKDOWN_CHUNKER_VERSION).toBe(4);});test('long pure-Chinese paragraph splits into multiple chunks', () => {diff --git a/test/cite-render-closure.test.ts b/test/cite-render-closure.test.tsindex 807e72e251..ae9f289295 100644--- a/test/cite-render-closure.test.ts+++ b/test/cite-render-closure.test.ts@@ -125,6 +125,7 @@ describe('runThink — resolved citations close against the gather set', () => {test('a structured citation outside the gathered evidence warns CITATION_NOT_IN_GATHER', async () => {const result = await runThink(engine, {question: 'technical founder',+ remote: false, // trusted-local citation closure includes every holderwithTrajectory: false,client: stubClientFromResponse({answer: 'The answer cites [records/example-a] visibly.',@@ -142,6 +143,7 @@ describe('runThink — resolved citations close against the gather set', () => {test('citations covered by the gathered evidence emit no closure warnings', async () => {const result = await runThink(engine, {question: 'technical founder',+ remote: false, // trusted-local citation closure includes every holderwithTrajectory: false,client: stubClientFromResponse({answer: 'Strong founder [people/alice-example#2].',diff --git a/test/code-intel-source-scope.test.ts b/test/code-intel-source-scope.test.tsindex 9277fddab1..c1092d24eb 100644--- a/test/code-intel-source-scope.test.ts+++ b/test/code-intel-source-scope.test.ts@@ -1,44 +1,4 @@-/**- * A13 — code-intel op scoping (test-plan item A13).- *- * Pins the per-op source-scope CONTRACT of the code-intel cluster- * (src/core/ops/code-intel.ts) so none of it stays ambiguous:- *- * - code_def / code_refs — BRAIN-WIDE BY DESIGN (documented decision:- * the brain-wide comments in code_def's and code_refs' handlers in- * src/core/ops/code-intel.ts say "brain-wide (not source-scoped)", and- * the underlying SQL in src/commands/code-def.ts:findCodeDef /- * src/commands/code-refs.ts:findCodeRefs carries NO source filter). A- * remote caller scoped to srcalpha (scalar or federated grant) CAN see- * srcbeta definitions and references. Rows do NOT project source_id- * (slug is the only source signal) — pinned below so a future scoping- * change trips this suite deliberately rather than drifting silently.- *- * - code_blast / code_flow — fenced through resolveCodeIntelScope- * (src/core/ops/context.ts): remote + no source in scope → the- * resolver's permission_denied throw; remote + multi-source federated- * grant → its invalid_params "single source" throw; scoped →- * single-source traversal (disambiguation AND edge walk both filter by- * that source).- *- * - code_callees — mirrors code_callers' contract (already pinned for- * LOCAL ctx by the code_callers assertions in- * test/e2e/code-intel-mcp-ops-pglite.test.ts; those- * assertions are NOT duplicated here). This suite adds the REMOTE side:- * scalar/federated alpha scope isolates beta edges, and all_sources=true- * from a remote caller collapses to the caller's grant instead of- * widening brain-wide.- *- * Fixture: two sources (srcalpha / srcbeta) with code chunks + symbol edges;- * every beta-side identifier carries the lowercase marker 'beta' and no- * alpha-side identifier does, so a whole-JSON scan for 'beta' is a complete- * leak probe. Anti-vacuity: every isolation assertion is paired with a- * control call that CAN see the beta marker, so an inadequate fixture fails- * loudly instead of passing vacuously.- *- * Registered as the owner of code_def/code_refs/code_blast/code_flow in- * test/operations-source-isolation-matrix.test.ts (mode: 'skip' rows).- */+/** Temporary remote code-read suspension: no raw/cached storage access; trusted local controls remain available. */import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operationsByName, type OperationContext } from '../src/core/operations.ts';@@ -74,29 +34,8 @@ function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {...overrides,} as OperationContext;}-const remoteAlpha = () => ctxOf({ sourceId: 'srcalpha' });-const remoteBeta = () => ctxOf({ sourceId: 'srcbeta' });-const remoteFederatedAlpha = () => ctxOf({ auth: { allowedSources: ['srcalpha'] } as any });-const remoteNoScope = () => ctxOf({});const localAlpha = () => ctxOf({ remote: false, sourceId: 'srcalpha' });-/** Whole-payload leak probe: every beta-side identifier contains 'beta'. */-function containsBeta(payload: unknown): boolean {- return (JSON.stringify(payload) ?? '').includes('beta');-}--async function expectOpError(promise: Promise<unknown>, code: string, msgFragment: string): Promise<void> {- let caught: unknown;- try {- await promise;- } catch (e) {- caught = e;- }- expect(caught).toBeInstanceOf(OperationError);- expect((caught as OperationError).code).toBe(code as OperationError['code']);- expect((caught as OperationError).message).toContain(msgFragment);-}-// ─── Fixture seeding (approach reused from test/e2e/code-intel-mcp-ops-pglite.test.ts) ───async function registerSource(id: string): Promise<void> {@@ -170,205 +109,40 @@ async function seedTwoSourceCodeGraph(): Promise<void> {await insertUnresolvedEdge(betaCallerChunk, 'betaCallerFn', 'alphaTargetFn', 'srcbeta');}-// ─── (1) code_def / code_refs: brain-wide by design — pinned explicitly ────--describe('A13 — code_def / code_refs are brain-wide by design (documented decision)', () => {- test('code_def: alpha-scoped remote caller sees a beta-only definition (brain-wide handler)', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_def!;- // DOCUMENTED DECISION: code_def does not route through ctx scope — the- // findCodeDef SQL (src/commands/code-def.ts) has no source filter and the- // brain-wide comment in code_def's handler (src/core/ops/code-intel.ts)- // names it brain-wide.- const result = (await op.handler(remoteAlpha(), { symbol: 'betaSecretFn' })) as {- count: number;- defs: Array<Record<string, unknown>>;- };- expect(result.count).toBe(1);- expect(result.defs[0]!.slug).toBe('src/beta-lib.ts');- // Rows do not project source_id; the slug is the only source signal.- // Pinned so a future projection/scoping change fails here consciously.- expect('source_id' in result.defs[0]!).toBe(false);- // Sanity: the same brain-wide read also sees the caller's own source.- const own = (await op.handler(remoteAlpha(), { symbol: 'alphaTargetFn' })) as { count: number };- expect(own.count).toBe(1);- });-- test('code_def: a federated grant does not scope it either (brain-wide for federated remote callers)', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_def!;- const result = (await op.handler(remoteFederatedAlpha(), { symbol: 'betaSecretFn' })) as {- count: number;- defs: Array<{ slug: string }>;- };- expect(result.count).toBe(1);- expect(result.defs[0]!.slug).toBe('src/beta-lib.ts');- });-- test('code_refs: alpha-scoped remote caller sees beta chunk text (brain-wide handler)', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_refs!;- // DOCUMENTED DECISION: findCodeRefs (src/commands/code-refs.ts) is an- // unscoped ILIKE scan over content_chunks; the brain-wide comment in- // code_refs' handler (src/core/ops/code-intel.ts) names it brain-wide.- const result = (await op.handler(remoteAlpha(), { symbol: 'betaSecretFn' })) as {- count: number;- refs: Array<Record<string, unknown>>;- };- expect(result.count).toBe(1);- expect(result.refs[0]!.slug).toBe('src/beta-lib.ts');- expect(String(result.refs[0]!.snippet)).toContain('betaSecretFn');- // No source_id projection on ref rows either — pinned (see code_def above).- expect('source_id' in result.refs[0]!).toBe(false);- });-});--// ─── (2) code_blast / code_flow: the resolveCodeIntelScope fence ──────────--describe('A13 — code_blast / code_flow resolveCodeIntelScope fence', () => {- test('code_blast: remote ctx with NO scope is refused with permission_denied (resolveCodeIntelScope no-scope throw)', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_blast!;- await expectOpError(- op.handler(remoteNoScope(), { symbol: 'alphaTargetFn' }),- 'permission_denied',- 'No source in scope',- );- });-- test('code_flow: remote ctx with NO scope is refused with permission_denied (resolveCodeIntelScope no-scope throw)', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_flow!;- await expectOpError(- op.handler(remoteNoScope(), { entry_point: 'sharedCallerFn' }),- 'permission_denied',- 'No source in scope',- );- });-- test("code_blast: remote multi-source federated grant is refused with invalid_params (resolveCodeIntelScope's multi-source throw)", async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_blast!;- // Traversal is single-source by design; a two-source grant must name one.- // (Shared fence — code_flow routes through the identical resolver branch.)- await expectOpError(- op.handler(ctxOf({ auth: { allowedSources: ['srcalpha', 'srcbeta'] } as any }), { symbol: 'alphaTargetFn' }),- 'invalid_params',- 'single source',- );- });-- test('code_blast: alpha scope walks alpha edges only — the beta-owned edge into the same target stays invisible', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_blast!;- const result = (await op.handler(remoteAlpha(), { symbol: 'alphaTargetFn' })) as {- result: string;- depth_groups: Array<{ depth: number; nodes: Array<{ symbol: string }> }>;- };- expect(result.result).toBe('ok');- const symbols = result.depth_groups.flatMap((g) => g.nodes.map((n) => n.symbol));- expect(symbols).toContain('alphaCallerFn');- expect(symbols).toContain('sharedCallerFn');- // srcbeta's betaCallerFn → alphaTargetFn edge must not surface anywhere.- expect(containsBeta(result)).toBe(false);- // Anti-vacuity control: a beta-scoped caller CAN see that beta edge- // (exact=true skips bare-name disambiguation, which is source-scoped and- // would otherwise not_found a symbol whose defining chunk lives in alpha).- const control = (await op.handler(remoteBeta(), { symbol: 'alphaTargetFn', exact: true })) as {- result: string;- depth_groups: Array<{ nodes: Array<{ symbol: string }> }>;- };- expect(control.result).toBe('ok');- expect(control.depth_groups.flatMap((g) => g.nodes.map((n) => n.symbol))).toContain('betaCallerFn');- });-- test('code_blast: a beta-only symbol is not_found under alpha scope (source-scoped disambiguation)', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_blast!;- const scoped = (await op.handler(remoteAlpha(), { symbol: 'betaSecretFn' })) as {- result: string;- did_you_mean: unknown[];- };- expect(scoped.result).toBe('not_found');- // The did_you_mean suggestions are source-scoped too — no beta leak.- expect(containsBeta(scoped.did_you_mean)).toBe(false);- // Anti-vacuity control: beta scope resolves and walks the same symbol.- const control = (await op.handler(remoteBeta(), { symbol: 'betaSecretFn' })) as {- result: string;- depth_groups: Array<{ nodes: Array<{ symbol: string }> }>;- };- expect(control.result).toBe('ok');- expect(control.depth_groups.flatMap((g) => g.nodes.map((n) => n.symbol))).toContain('betaCallerFn');- });-- test('code_flow: alpha scope traces alpha callees only; beta scope sees the beta branch (anti-vacuity)', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_flow!;- // sharedCallerFn exists in BOTH sources with different callees — the- // sharpest probe: same entry point, scope decides what is disclosed.- const alpha = (await op.handler(remoteAlpha(), { entry_point: 'sharedCallerFn' })) as {- result: string;- depth_groups: Array<{ nodes: Array<{ symbol: string }> }>;- };- expect(alpha.result).toBe('ok');- const alphaSymbols = alpha.depth_groups.flatMap((g) => g.nodes.map((n) => n.symbol));- expect(alphaSymbols).toContain('alphaTargetFn');- expect(containsBeta(alpha)).toBe(false);- const beta = (await op.handler(remoteBeta(), { entry_point: 'sharedCallerFn' })) as {- result: string;- depth_groups: Array<{ nodes: Array<{ symbol: string }> }>;- };- expect(beta.result).toBe('ok');- expect(beta.depth_groups.flatMap((g) => g.nodes.map((n) => n.symbol))).toContain('betaSecretFn');- });-});--// ─── (3) code_callees: isolation mirror of code_callers' pinned contract ──--describe('A13 — code_callees remote isolation (mirrors code_callers, pinned in code-intel-mcp-ops e2e)', () => {- test('remote scalar alpha scope: beta callee edges invisible; local all_sources control sees them', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_callees!;- const scoped = (await op.handler(remoteAlpha(), { symbol: 'sharedCallerFn' })) as {- count: number;- callees: Array<{ to_symbol_qualified: string; source_id: string | null }>;- };- expect(scoped.count).toBe(1);- expect(scoped.callees[0]!.to_symbol_qualified).toBe('alphaTargetFn');- expect(containsBeta(scoped)).toBe(false);- // Anti-vacuity control: trusted local caller spanning all sources sees- // srcbeta's sharedCallerFn → betaSecretFn edge.- const control = (await op.handler(localAlpha(), { symbol: 'sharedCallerFn', all_sources: true })) as {- callees: Array<{ to_symbol_qualified: string }>;- };- expect(control.callees.map((c) => c.to_symbol_qualified)).toContain('betaSecretFn');- });-- test('remote federated grant [srcalpha]: same isolation as the scalar scope', async () => {- await seedTwoSourceCodeGraph();- const op = operationsByName.code_callees!;- const scoped = (await op.handler(remoteFederatedAlpha(), { symbol: 'sharedCallerFn' })) as {- count: number;- callees: Array<{ to_symbol_qualified: string }>;- };- expect(scoped.count).toBe(1);- expect(scoped.callees[0]!.to_symbol_qualified).toBe('alphaTargetFn');- expect(containsBeta(scoped)).toBe(false);- });+// Trusted local reads retain their historical source behavior.+++const readOps = ['code_callers', 'code_callees', 'code_def', 'code_refs', 'code_blast', 'code_flow'] as const;+const parameters = { symbol: 'betaOnlyFunction', entry_point: 'betaOnlyFunction', exact: true };++describe('code reads require trusted local context while remote authorization is suspended', () => {+ for (const name of readOps) {+ test(`${name}: remote and omitted trust fail before accessing storage for every source grant`, async () => {+ let accesses = 0;+ const inaccessibleEngine = new Proxy({}, { get() { accesses++; throw new Error('storage must not be accessed'); } });+ for (const remote of [true, undefined]) {+ for (const scope of [{ sourceId: 'srcalpha' }, { auth: { allowedSources: ['srcalpha', 'srcbeta'] } }, { auth: { allowedSources: [] } }, {}]) {+ const ctx = ctxOf({ ...scope, remote, engine: inaccessibleEngine } as any);+ let caught: unknown;+ try { await operationsByName[name].handler(ctx, parameters); } catch (error) { caught = error; }+ expect(caught).toBeInstanceOf(OperationError);+ expect((caught as OperationError).code).toBe('permission_denied');+ expect((caught as Error).message).toContain('temporarily unavailable');+ }+ }+ expect(accesses).toBe(0);+ expect(operationsByName[name].description).toContain('agent-facing code reads are suspended');+ });+ }- test('remote all_sources=true collapses to the grant — never widens brain-wide', async () => {+ test('trusted local definitions and references retain the brain-wide public contract', async () => {await seedTwoSourceCodeGraph();- const op = operationsByName.code_callees!;- const remote = (await op.handler(remoteAlpha(), { symbol: 'sharedCallerFn', all_sources: true })) as {- callees: Array<{ to_symbol_qualified: string }>;- };- expect(remote.callees.map((c) => c.to_symbol_qualified)).toContain('alphaTargetFn');- expect(containsBeta(remote)).toBe(false);- // Anti-vacuity control: the SAME args from a trusted local caller DO span- // sources — proving the collapse above is the trust fence, not the fixture.- const control = (await op.handler(localAlpha(), { symbol: 'sharedCallerFn', all_sources: true })) as {- callees: Array<{ to_symbol_qualified: string }>;- };- expect(control.callees.map((c) => c.to_symbol_qualified)).toContain('betaSecretFn');+ const ctx = localAlpha();+ const defs = await operationsByName.code_def.handler(ctx, { symbol: 'betaSecretFn' }) as { count: number; defs: unknown[] };+ const refs = await operationsByName.code_refs.handler(ctx, { symbol: 'betaSecretFn' }) as { count: number; refs: unknown[] };+ expect(defs.count).toBeGreaterThan(0);+ expect(refs.count).toBeGreaterThan(0);+ expect(JSON.stringify(defs.defs)).toContain('beta');+ expect(JSON.stringify(refs.refs)).toContain('beta');});});diff --git a/test/commands-search.test.ts b/test/commands-search.test.tsindex 81784a3b9f..a5270e0c52 100644--- a/test/commands-search.test.ts+++ b/test/commands-search.test.ts@@ -76,15 +76,24 @@ describe('gbrain search modes (read-only dashboard)', () => {test('per-key override shows up with source=override', async () => {await engine.setConfig('search.mode', 'conservative');- await engine.setConfig('search.cache.enabled', 'false');+ await engine.setConfig('search.title_boost', '2');const out = await captureRun(() => runSearch(engine, ['modes', '--json']));const report = JSON.parse(out);- expect(report.resolved.cache_enabled.value).toBe(false);- expect(report.resolved.cache_enabled.source).toBe('override');+ expect(report.resolved.title_boost.value).toBe(2);+ expect(report.resolved.title_boost.source).toBe('override');// Other knobs still come from the mode bundle.expect(report.resolved.searchLimit.source).toBe('mode');});+ test.each(['false', 'true'])('cache availability overrides configured %s without erasing it', async (configured) => {+ await engine.setConfig('search.cache.enabled', configured);+ const report = JSON.parse(await captureRun(() => runSearch(engine, ['modes', '--json'])));+ expect(report.resolved.cache_enabled.value).toBe(false);+ expect(report.resolved.cache_enabled.source).toBe('availability');+ expect(report.resolved.cache_enabled.source_detail).toContain('temporarily disabled');+ expect(await engine.getConfig('search.cache.enabled')).toBe(configured);+ });+test('default text output names the active mode', async () => {await engine.setConfig('search.mode', 'tokenmax');const out = await captureRun(() => runSearch(engine, ['modes']));diff --git a/test/corrective-containment.test.ts b/test/corrective-containment.test.tsnew file mode 100644index 0000000000..f47bd9e2c8--- /dev/null+++ b/test/corrective-containment.test.ts@@ -0,0 +1,82 @@+import { describe, expect, mock, test } from 'bun:test';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';++function context(engine: Partial<BrainEngine>, opts: Partial<OperationContext> = {}): OperationContext {+ return {+ engine: engine as BrainEngine,+ config: { engine: 'pglite' },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: '__all__',+ ...opts,+ };+}++const REPORT_NOTE = 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.';+const auth = (allowedSources: string[]): NonNullable<OperationContext['auth']> => ({ token: 'fixture', clientId: 'example-client', scopes: ['read'], allowedSources });++describe('stored contradiction report containment', () => {+ const deniedContexts: Array<[string, Partial<OperationContext>]> = [+ ['remote', { remote: true }],+ ['unset trust', { remote: undefined as unknown as boolean }],+ ['remote all-sources sentinel', { remote: true, sourceId: '__all__' }],+ ['trusted scalar source', { sourceId: 'default' }],+ ['trusted federated scope', { auth: auth(['default']) }],+ ['empty federated grant falls back to scalar', { sourceId: 'default', auth: auth([]) }],+ ['federated grant wins over trusted all-sources sentinel', { sourceId: '__all__', auth: auth(['default']) }],+ ];+ for (const [label, opts] of deniedContexts) {+ test(`${label} returns the availability note before reading any reports`, async () => {+ const load = mock(async () => { throw new Error('protected report must not be loaded'); });+ const result = await operationsByName.find_contradictions.handler(context({ loadContradictionsTrend: load }, opts), {});+ expect(result).toEqual({ contradictions: [], note: REPORT_NOTE });+ expect(load).not.toHaveBeenCalled();+ });+ }++ for (const sourceId of [undefined, '__all__']) {+ test(`trusted unscoped source ${sourceId ?? '(absent)'} retains local reports`, async () => {+ const finding = { a: { slug: 'page-a' }, b: { slug: 'page-b' }, severity: 'high', axis: 'LOCAL_QUERY_DERIVED_SECRET' };+ const load = mock(async () => [{+ run_id: 'local-run', ran_at: '2026-09-01T00:00:00Z', report_json: { per_query: [{ contradictions: [finding] }] },+ }]);+ const result = await operationsByName.find_contradictions.handler(context({ loadContradictionsTrend: load as never }, { sourceId }), {});+ expect(load).toHaveBeenCalledTimes(1);+ expect(result).toMatchObject({ run_id: 'local-run', contradictions: [finding], total_in_run: 1 });+ });+ }+});++describe('remote history uses strict body sanitization', () => {+ const body = renderFactsTable([+ { rowNum: 1, claim: 'WORLD_HISTORY', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: 'PRIVATE_HISTORY', kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+ ]) + `\n${TAKES_FENCE_BEGIN}\nPRIVATE_TAKE_HISTORY\n${TAKES_FENCE_END}`;+ for (const remote of [true, undefined, false]) {+ for (const takesHoldersAllowList of [undefined, [], ['world'], ['world', 'owner-example']]) {+ test(`history sanitizes when remote=${String(remote)}, holders=${JSON.stringify(takesHoldersAllowList)}, independently of page opt-out`, async () => {+ const version = { id: 1, page_id: 1, version: 1, compiled_truth: body, frontmatter: {}, snapshot_at: new Date() };+ const getVersions = mock(async () => [version]);+ const result = await operationsByName.get_versions.handler(context({+ getVersions: getVersions as never,+ // Even an operator opt-out cannot disable the Facts/Takes boundary.+ getConfig: async () => 'visible',+ }, { remote: remote as boolean, sourceId: 'default', takesHoldersAllowList }), { slug: 'example-page' }) as Array<{ compiled_truth: string }>;+ expect(result).toHaveLength(1);+ expect(result[0].compiled_truth).toContain('WORLD_HISTORY');+ if (remote === false) {+ expect(result[0].compiled_truth).toBe(body);+ } else {+ expect(result[0].compiled_truth).not.toContain('PRIVATE_HISTORY');+ expect(result[0].compiled_truth).not.toContain('PRIVATE_TAKE_HISTORY');+ }+ expect(version.compiled_truth).toBe(body);+ expect(getVersions).toHaveBeenCalledTimes(1);+ });+ }+ }+});diff --git a/test/doctor.test.ts b/test/doctor.test.tsindex d2f75988e8..6afa480b07 100644--- a/test/doctor.test.ts+++ b/test/doctor.test.ts@@ -1,4 +1,5 @@-import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';+import { resetGateway } from '../src/core/ai/gateway.ts';import { mkdirSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';@@ -9,6 +10,10 @@ import { withEnv } from './helpers/with-env.ts';import { logRerankFailure } from '../src/core/rerank-audit.ts';import { doctorSource, doctorFileSource } from './helpers/doctor-source.ts';+// Health fixtures configure fake provider keys. Clear the gateway snapshot as+// well as each fixture's process env so later tests cannot send real requests.+afterEach(() => resetGateway());+describe('doctor command', () => {test('doctor module exports runDoctor', async () => {const { runDoctor } = await import('../src/commands/doctor.ts');diff --git a/test/e2e/chunk-canonical-text-privacy.test.ts b/test/e2e/chunk-canonical-text-privacy.test.tsnew file mode 100644index 0000000000..4bcf2403eb--- /dev/null+++ b/test/e2e/chunk-canonical-text-privacy.test.ts@@ -0,0 +1,195 @@+/** Canonical storage bytes must agree with index privacy and seal comparisons. */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { ChunkInput } from '../../src/core/types.ts';+import { importFromContent, importImageFile, _resetOcrRunBudgetForTests } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';+import { FACTS_FENCE_BEGIN, renderFactsTable } from '../../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { sanitizeRemoteBody } from '../../src/core/remote-body.ts';+import * as gateway from '../../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { withEnv } from '../helpers/with-env.ts';++const SOURCE = 'canonical-chunk-privacy-fixture';+const NUL = String.fromCharCode(0);+const LONE_HI = String.fromCharCode(0xd83c);+const PRIVATE = 'PRIVATE_CANONICAL_BODY_CANARY';+const WORLD = 'WORLD_CANONICAL_BODY_CONTROL';+const obscure = (marker: string) => marker.replace('gbrain:', `gbrain:${NUL}`);++for (const kind of ['pglite', 'postgres'] as const) {+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;+ suite(`${kind}: canonical chunk text privacy`, () => {+ let engine: BrainEngine;+ let fixtureDir: string;++ beforeAll(async () => {+ gateway.configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+ if (kind === 'postgres') assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ await engine.connect(kind === 'postgres' ? { database_url: process.env.DATABASE_URL! } : {});+ await engine.initSchema();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SOURCE]);+ fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-canonical-chunks-'));+ }, 120_000);++ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages WHERE source_id = $1', [SOURCE]);+ });++ afterAll(async () => {+ try {+ if (engine) {+ await engine.executeRaw('DELETE FROM sources WHERE id = $1', [SOURCE]);+ await engine.disconnect();+ }+ } finally {+ if (fixtureDir) rmSync(fixtureDir, { recursive: true, force: true });+ gateway.resetGateway();+ _resetOcrRunBudgetForTests();+ }+ }, 60_000);++ async function version(slug: string): Promise<number> {+ const [row] = await engine.executeRaw<{ version: number }>(+ 'SELECT chunker_version AS version FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, slug]);+ return Number(row.version);+ }++ async function imported(slug: string, body: string, timeline = '') {+ const result = await importFromContent(engine, slug,+ serializeMarkdown({}, body, timeline, { type: 'note', title: 'Canonical text fixture', tags: [] }),+ { sourceId: SOURCE, noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');+ expect(await version(slug)).toBe(MARKDOWN_CHUNKER_VERSION);+ return result;+ }++ test('canonical embedding refresh preserves a seal and matching hash; changed text invalidates', async () => {+ const slug = 'notes/canonical-refresh';+ await imported(slug, 'Public canonical replacement � control.');+ const before = await engine.getChunks(slug, { sourceId: SOURCE, requireSafeChunks: true });+ expect(before).toHaveLength(1);+ const vector = new Float32Array(1536); vector[0] = 1;+ const poison = before[0].chunk_text.replace('�', LONE_HI) + NUL;+ // Embedding refresh supplies body fields only; omitted code metadata+ // retains its stored value under the upsert contract.+ const input: ChunkInput[] = [{+ chunk_index: before[0].chunk_index,+ chunk_source: before[0].chunk_source,+ chunk_text: poison,+ embedding: vector,+ }];+ await engine.upsertChunks(slug, input, { sourceId: SOURCE });+ expect(input[0].chunk_text).toBe(poison); // normalization must not mutate the caller's input+ expect(await version(slug)).toBe(MARKDOWN_CHUNKER_VERSION);+ const refreshed = await engine.getChunks(slug, { sourceId: SOURCE, requireSafeChunks: true });+ expect(refreshed).toHaveLength(1);+ expect(refreshed[0].chunk_text).toBe(before[0].chunk_text);+ expect(refreshed[0].embedding_is_null).toBe(false);+ const hashes = () => engine.executeRaw<{ stored: string; recomputed: string }>(+ `SELECT c.embedded_text_hash AS stored, md5(c.chunk_text) AS recomputed+ FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.source_id = $1 AND p.slug = $2`, [SOURCE, slug]);+ let [hash] = await hashes();+ expect(hash.stored).toBe(hash.recomputed);++ await engine.upsertChunks(slug, [{ ...input[0], chunk_text: `${poison} changed` }], { sourceId: SOURCE });+ expect(await version(slug)).toBeLessThan(0);+ expect(await engine.getChunks(slug, { sourceId: SOURCE, requireSafeChunks: true })).toEqual([]);+ const [changed] = await engine.getChunks(slug, { sourceId: SOURCE });+ expect(changed.chunk_text).toBe(`${before[0].chunk_text} changed`);+ [hash] = await hashes();+ expect(hash.stored).toBe(hash.recomputed);+ });++ test('identity fields still reject poisoned input without changing sealed chunks', async () => {+ const slug = 'notes/canonical-identity';+ await imported(slug, 'Public identity control.');+ const chunks = await engine.getChunks(slug, { sourceId: SOURCE });+ await expect(engine.upsertChunks(slug, [{+ chunk_index: chunks[0].chunk_index,+ chunk_text: chunks[0].chunk_text,+ chunk_source: `compiled_${NUL}truth` as ChunkInput['chunk_source'],+ }], { sourceId: SOURCE })).rejects.toThrow();+ expect(await version(slug)).toBe(MARKDOWN_CHUNKER_VERSION);+ expect(await engine.getChunks(slug, { sourceId: SOURCE, requireSafeChunks: true })).toEqual(chunks);+ });++ test('actual imports normalize protected prose, facts, timeline and code fences before indexing', async () => {+ const slug = 'notes/canonical-protected';+ const facts = renderFactsTable([+ { rowNum: 1, claim: WORLD, kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: PRIVATE, kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+ ]).replace(FACTS_FENCE_BEGIN, obscure(FACTS_FENCE_BEGIN));+ const takes = `${obscure(TAKES_FENCE_BEGIN)}\n\`\`\`typescript\nexport const hidden = '${PRIVATE}';\n\`\`\`\n${TAKES_FENCE_END}`;+ const body = `Public canonical prefix ${LONE_HI}.\n${takes}\n${facts}\nPublic canonical suffix.`;+ const timeline = `Public timeline prefix.\n${takes}\n${facts}\nPublic timeline suffix.`;+ // Direct chunker/compile callers also use this boundary on raw text.+ const sanitized = sanitizeRemoteBody(body);+ expect(sanitized).toContain(WORLD);+ expect(sanitized).toContain('Public canonical prefix �.');+ expect(sanitized).not.toContain(PRIVATE);+ expect(sanitized).not.toContain(NUL);+ const result = await imported(slug, body, timeline);+ const page = (await engine.getPage(slug, { sourceId: SOURCE }))!;+ expect(page.compiled_truth).toContain(TAKES_FENCE_BEGIN);+ expect(page.compiled_truth).toContain(PRIVATE); // owner body is preserved+ expect(page.compiled_truth).not.toContain(NUL);+ expect(page.compiled_truth).toContain('�');+ const chunks = await engine.getChunks(slug, { sourceId: SOURCE, requireSafeChunks: true });+ expect(chunks.length).toBeGreaterThan(0);+ const text = chunks.map(chunk => chunk.chunk_text).join('\n');+ expect(text).toContain(WORLD);+ expect(text).toContain('Public canonical prefix �.');+ expect(text).toContain('Public timeline suffix.');+ expect(text).not.toContain(PRIVATE);+ expect(text).not.toContain(NUL);+ expect(result.parsedPage?.compiled_truth).toBe(page.compiled_truth);+ expect(result.parsedPage?.timeline).toBe(page.timeline);+ expect(chunks.some(chunk => chunk.chunk_source === 'fenced_code')).toBe(false);+ expect(sanitizeRemoteBody(page.compiled_truth)).not.toContain(PRIVATE);+ expect(sanitizeRemoteBody(page.timeline)).not.toContain(PRIVATE);+ expect(await engine.searchKeyword(PRIVATE, { sourceId: SOURCE, requireSafeChunks: true })).toEqual([]);+ expect((await engine.searchKeyword(WORLD, { sourceId: SOURCE, requireSafeChunks: true })).length).toBeGreaterThan(0);+ });++ test('successful OCR normalizes protected markers before image sealing', async () => {+ const path = join(fixtureDir, 'canonical.png');+ writeFileSync(path, Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aV9kAAAAASUVORK5CYII=', 'base64'));+ gateway.configureGateway({ ...LEGACY_EMBEDDING_CONFIG, embedding_image_ocr_model: 'openai:gpt-4o-mini', env: { OPENAI_API_KEY: 'synthetic-ocr-key' } });+ _resetOcrRunBudgetForTests();+ const ocr = spyOn(gateway, 'generateOcrText').mockResolvedValue(`Public OCR.\n${obscure(TAKES_FENCE_BEGIN)}\n${PRIVATE}\n${obscure(TAKES_FENCE_END)}`);+ const vector = new Float32Array(1024); vector[0] = 1;+ const embed = spyOn(gateway, 'embedMultimodal').mockResolvedValue([vector]);+ try {+ const slug = 'images/canonical.png';+ const result = await withEnv({ GBRAIN_EMBEDDING_IMAGE_OCR: 'true' },+ () => importImageFile(engine, path, slug, { sourceId: SOURCE }));+ expect(result.status).toBe('imported');+ expect(ocr).toHaveBeenCalledTimes(1);+ expect(embed).toHaveBeenCalledTimes(1);+ expect(await version(slug)).toBeLessThan(MARKDOWN_CHUNKER_VERSION);+ expect(await engine.getChunks(slug, { sourceId: SOURCE, requireSafeChunks: true })).toEqual([]);+ const page = (await engine.getPage(slug, { sourceId: SOURCE }))!;+ expect(page.compiled_truth).toContain(TAKES_FENCE_BEGIN);+ expect(page.compiled_truth).not.toContain(NUL);+ const [chunk] = await engine.getChunks(slug, { sourceId: SOURCE });+ expect(chunk.chunk_text).toContain('Public OCR.');+ expect(chunk.chunk_text).not.toContain(PRIVATE);+ } finally {+ ocr.mockRestore();+ embed.mockRestore();+ gateway.configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ }+ });+ });+}diff --git a/test/e2e/code-intel-mcp-ops-pglite.test.ts b/test/e2e/code-intel-mcp-ops-pglite.test.tsindex a6825efa8a..1f2fceef81 100644--- a/test/e2e/code-intel-mcp-ops-pglite.test.ts+++ b/test/e2e/code-intel-mcp-ops-pglite.test.ts@@ -50,25 +50,25 @@ describe('v0.34 W3 — code-intel MCP ops registered', () => {test('code_callers exists with scope:read and v0.34 description', () => {expect(operationsByName.code_callers).toBeDefined();expect(operationsByName.code_callers!.scope).toBe('read');- expect(operationsByName.code_callers!.description).toBe(CODE_CALLERS_DESCRIPTION);+ expect(operationsByName.code_callers!.description).toStartWith(CODE_CALLERS_DESCRIPTION);});test('code_callees exists with scope:read and v0.34 description', () => {expect(operationsByName.code_callees).toBeDefined();expect(operationsByName.code_callees!.scope).toBe('read');- expect(operationsByName.code_callees!.description).toBe(CODE_CALLEES_DESCRIPTION);+ expect(operationsByName.code_callees!.description).toStartWith(CODE_CALLEES_DESCRIPTION);});test('code_def exists with scope:read and v0.34 description', () => {expect(operationsByName.code_def).toBeDefined();expect(operationsByName.code_def!.scope).toBe('read');- expect(operationsByName.code_def!.description).toBe(CODE_DEF_DESCRIPTION);+ expect(operationsByName.code_def!.description).toStartWith(CODE_DEF_DESCRIPTION);});test('code_refs exists with scope:read and v0.34 description', () => {expect(operationsByName.code_refs).toBeDefined();expect(operationsByName.code_refs!.scope).toBe('read');- expect(operationsByName.code_refs!.description).toBe(CODE_REFS_DESCRIPTION);+ expect(operationsByName.code_refs!.description).toStartWith(CODE_REFS_DESCRIPTION);});test('all four code_* ops have a symbol param marked required', () => {@@ -154,7 +154,7 @@ describe('v0.34 W3 — code_callers source scoping', () => {});describe('#4011 — graph ops re-route to the code-bearing federated source', () => {- test('unqualified code_callers on a code-less seed source finds callers in the sole code-bearing federated source', async () => {+ test('remote code_callers is temporarily suspended before federated rerouting', async () => {// Vault+code brain: the caller's scalar scope ('default') holds no code;// the graph lives entirely in 'code-src'. Pre-#4011 the traversal stayed// on 'default' and readiness honestly reported not_built — masking a@@ -171,12 +171,9 @@ describe('#4011 — graph ops re-route to the code-bearing federated source', ()remote: true,localFederatedSourceIds: ['default', 'code-src'],};- const result = (await operationsByName.code_callers!.handler(ctx, { symbol: 'parseMarkdown' })) as {- count: number; status: string; callers: Array<{ from_symbol_qualified: string }>;- };- expect(result.status).not.toBe('not_built');- expect(result.count).toBe(1);- expect(result.callers[0]!.from_symbol_qualified).toBe('callerInCode');+ await expect(operationsByName.code_callers!.handler(ctx, { symbol: 'parseMarkdown' })).rejects.toMatchObject({+ code: 'permission_denied', message: expect.stringContaining('temporarily unavailable'),+ });});});diff --git a/test/e2e/contextual-retrieval-pglite.test.ts b/test/e2e/contextual-retrieval-pglite.test.tsindex ac3f2028dc..52af39798c 100644--- a/test/e2e/contextual-retrieval-pglite.test.ts+++ b/test/e2e/contextual-retrieval-pglite.test.ts@@ -138,7 +138,7 @@ but should NOT mutate what we store as canonical chunk_text.`;[slug],);expect(rows[0].cv).toBe(MARKDOWN_CHUNKER_VERSION);- expect(rows[0].cv).toBe(3); // v0.40.3.0 bump+ expect(rows[0].cv).toBe(4); // v0.48.3.0 safe index requires strict full-body sanitation.});});diff --git a/test/e2e/engine-content-privacy.test.ts b/test/e2e/engine-content-privacy.test.tsnew file mode 100644index 0000000000..2d1b3d86b8--- /dev/null+++ b/test/e2e/engine-content-privacy.test.ts@@ -0,0 +1,412 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { listEntityIdentities, linkEntityIdentity, unionLinksAcrossIdentity } from '../../src/core/entity-identity.ts';+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';+import { runGather } from '../../src/core/think/gather.ts';+import { runThink } from '../../src/core/think/index.ts';+import { __resetPrivateVisibilityCacheForTests } from '../../src/core/search/private-visibility.ts';+import { renderFactsTable } from '../../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';++const SOURCES = ['privacy-engine-a', 'privacy-engine-b', 'privacy-engine-c'];+const [A, B, C] = SOURCES;+const PRIVATE = 'PRIVATE_CONTENT_CANARY';++for (const kind of ['pglite', 'postgres'] as const) {+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;+ suite(`${kind}: concrete content and graph privacy`, () => {+ let engine: BrainEngine;++ beforeAll(async () => {+ if (kind === 'postgres') {+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ engine = new PostgresEngine();+ await engine.connect({ database_url: process.env.DATABASE_URL! });+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ }+ await engine.initSchema();+ for (const source of SOURCES) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);+ }+ }, 120_000);++ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages WHERE source_id = ANY($1::text[])', [SOURCES]);+ await engine.executeRaw('DELETE FROM slug_aliases WHERE source_id = ANY($1::text[])', [SOURCES]);+ await engine.unsetConfig('entity_identity.union');+ });++ afterAll(async () => {+ if (engine) {+ await engine.executeRaw('DELETE FROM sources WHERE id = ANY($1::text[])', [SOURCES]);+ await engine.unsetConfig('entity_identity.union');+ await engine.disconnect();+ }+ }, 60_000);++ async function page(slug: string, source = A, hidden = false): Promise<number> {+ const body = hidden ? PRIVATE : `public ${slug} ${source}`;+ const imported = await importFromContent(engine, slug, serializeMarkdown(+ { visibility: hidden ? 'private' : 'world' }, body, '',+ { type: 'person', title: hidden ? `${PRIVATE} ${slug}` : slug, tags: [] },+ ), { sourceId: source, noEmbed: true, forceRechunk: true });+ expect(imported.status, imported.error).toBe('imported');+ const rows = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2', [slug, source]);+ const id = Number(rows[0].id);+ await engine.executeRaw("INSERT INTO raw_data (page_id, source, data) VALUES ($1, 'fixture', $2::text::jsonb)", [id, JSON.stringify({ body })]);+ await engine.executeRaw("INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-08-01', $2)", [id, body]);+ return id;+ }++ async function edge(from: number, to: number, context = 'public edge', origin: number | null = null) {+ await engine.executeRaw("INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id) VALUES ($1, $2, 'knows', $3, 'manual', $4)", [from, to, context, origin]);+ }++ async function chronicleFixture() {+ const depth = await page('people/chronicle-subject');+ const privateDepth = await page('people/chronicle-subject', B, true);+ const publicEvent = await page('events/chronicle-public');+ const depthEvent = await page('events/chronicle-private-depth');+ const privateEvent = await page('events/chronicle-collision', B, true);+ await page('events/chronicle-collision', A);+ const foreignPrivateEvent = await page('events/chronicle-foreign-private', C, true);+ await engine.executeRaw('DELETE FROM timeline_entries WHERE page_id IN (SELECT id FROM pages WHERE source_id = ANY($1::text[]))', [SOURCES]);+ for (const [id, when, who] of [+ [publicEvent, '2026-08-10T12:00:00Z', ['people/chronicle-subject', 'people/public-event-only']],+ [depthEvent, '2026-08-11T20:00:00Z', ['people/chronicle-subject', 'people/private-depth-only']],+ [privateEvent, '2026-08-11T21:00:00Z', ['people/chronicle-subject', 'people/private-event-only']],+ [foreignPrivateEvent, '2026-08-11T22:00:00Z', ['people/chronicle-subject']],+ ] as const) {+ await engine.executeRaw("UPDATE pages SET type = 'event', effective_date = $2::timestamptz, frontmatter = frontmatter || $3::text::jsonb WHERE id = $1", [id, when, JSON.stringify({ event: { who, kind: 'meeting' } })]);+ }+ for (const [pageId, eventId, date, summary] of [+ [privateDepth, null, '2026-08-10', PRIVATE],+ [depth, privateEvent, '2026-08-10', PRIVATE],+ [depth, foreignPrivateEvent, '2026-08-10', PRIVATE],+ [depth, publicEvent, '2026-08-10', 'visible chronicle event'],+ [privateDepth, depthEvent, '2026-08-11', PRIVATE],+ [depth, privateEvent, '2026-08-11', PRIVATE],+ [depth, foreignPrivateEvent, '2026-08-11', PRIVATE],+ ] as const) {+ await engine.executeRaw('INSERT INTO timeline_entries (page_id, event_page_id, date, summary, source) VALUES ($1, $2, $3::date, $4, $5)', [pageId, eventId, date, summary, `fixture:event:${eventId}`]);+ }+ }++ test('same-slug private rows cannot win exact resolution or leak through content readers', async () => {+ const publicId = await page('people/shared');+ const privateId = await page('people/shared', B, true);+ const scope = { sourceIds: [B, A], excludePrivate: true };+ expect((await engine.getPage('people/shared', scope))?.id).toBe(publicId);+ expect((await engine.getPage('people/shared', { sourceIds: [B, A] }))?.id).toBe(privateId);+ expect(await engine.getPage('people/shared', { sourceId: B, excludePrivate: true })).toBeNull();+ expect((await engine.getPage('people/shared', { sourceId: A, sourceIds: [], excludePrivate: true }))?.id).toBe(publicId);+ for (const rows of [+ await engine.getChunks('people/shared', scope),+ await engine.getRawData('people/shared', undefined, scope),+ await engine.getRawData('people/shared', 'fixture', scope),+ await engine.getTimeline('people/shared', { ...scope, limit: 1 }),+ ]) {+ expect(rows).toHaveLength(1);+ expect(JSON.stringify(rows)).not.toContain(PRIVATE);+ }+ expect(JSON.stringify(await engine.getRawData('people/shared'))).toContain(PRIVATE);+ expect(await engine.getChunks('people/shared', { sourceId: B, excludePrivate: true })).toEqual([]);+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [privateId]);+ expect(await engine.getPage('people/shared', { sourceId: B, includeDeleted: true, excludePrivate: true })).toBeNull();+ });++ test('fuzzy and alias resolution filter private candidates before choosing a winner', async () => {+ for (let i = 0; i < 8; i++) await page(`people/needle-secret-${i}`, A, true);+ await page('people/needle-public', A);+ expect(await engine.resolveSlugs('needle', { sourceId: A, excludePrivate: true })).toEqual(['people/needle-public']);+ expect((await engine.resolveSlugs('needle', { sourceId: A })).length).toBe(5);+ await page('people/canonical-secret', B, true);+ await page('people/canonical-public', A);+ for (const [source, canonical] of [[B, 'people/canonical-secret'], [A, 'people/canonical-public']]) {+ await engine.executeRaw('INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ($1, $2, $3)', [source, 'people/alias', canonical]);+ }+ expect(await engine.resolveSlugWithAliasDetailed('people/alias', [B, A], { excludePrivate: true })).toEqual({ canonical_slug: 'people/canonical-public', source_id: A });+ expect(await engine.resolveSlugWithAlias('people/alias', [B, A])).toBe('people/canonical-secret');+ });++ test('history requires both a visible current page and a visible historical snapshot', async () => {+ const visible = await page('people/history');+ const hidden = await page('people/history', B, true);+ for (const [id, visibility, body] of [[visible, 'world', 'public history'], [visible, 'private', PRIVATE], [hidden, 'world', PRIVATE], [hidden, 'private', PRIVATE]] as const) {+ await engine.executeRaw('INSERT INTO page_versions (page_id, compiled_truth, frontmatter) VALUES ($1, $2, $3::text::jsonb)', [id, body, JSON.stringify({ visibility })]);+ }+ const history = await engine.getVersions('people/history', { sourceIds: [A, B], excludePrivate: true });+ expect(history).toHaveLength(1);+ expect(history[0].compiled_truth).toBe('public history');+ expect(await engine.getVersions('people/history', { sourceId: B, excludePrivate: true })).toEqual([]);+ expect(await engine.getVersions('people/history', { sourceIds: [A, B], excludePrivate: false })).toHaveLength(4);+ expect(JSON.stringify(await engine.getVersions('people/history'))).toContain(PRIVATE);+ });++ test('get_page protects every body field when trust is unset, independently of holder grants and page opt-outs', async () => {+ const body = `${renderFactsTable([+ { rowNum: 1, claim: 'PUBLIC_BODY_FACT', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: PRIVATE, kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+ ])}\n${TAKES_FENCE_BEGIN}\nPRIVATE_BODY_TAKE\n${TAKES_FENCE_END}`;+ await engine.putPage('people/body-default', {+ type: 'person', title: 'Public body fixture', compiled_truth: body, timeline: body,+ frontmatter: { visibility: 'world' },+ }, { sourceId: A });+ try {+ for (const allowPrivatePages of [false, true]) {+ if (allowPrivatePages) await engine.setConfig('search.remote_private_pages', 'visible');+ else await engine.unsetConfig('search.remote_private_pages');+ __resetPrivateVisibilityCacheForTests();+ for (const remote of [undefined, true, false]) {+ const ctx = { engine, sourceId: A, remote, takesHoldersAllowList: ['world', 'owner-example'] } as OperationContext;+ const result = await operationsByName.get_page.handler(ctx, { slug: 'people/body-default', include_content: true }) as Record<string, string>;+ for (const field of ['compiled_truth', 'timeline', 'content']) {+ expect(result[field]).toContain('PUBLIC_BODY_FACT');+ if (remote === false) {+ expect(result[field]).toContain(PRIVATE);+ expect(result[field]).toContain('PRIVATE_BODY_TAKE');+ } else {+ expect(result[field]).not.toContain(PRIVATE);+ expect(result[field]).not.toContain('PRIVATE_BODY_TAKE');+ }+ }+ }+ }+ } finally {+ await engine.unsetConfig('search.remote_private_pages');+ __resetPrivateVisibilityCacheForTests();+ }+ });++ test('private event projections are excluded before the timeline limit', async () => {+ const depth = await page('people/timeline');+ for (let i = 0; i < 5; i++) {+ const event = await page(`events/private-${i}`, B, true);+ await engine.executeRaw(+ 'INSERT INTO timeline_entries (page_id, date, summary, event_page_id) VALUES ($1, $2::date, $3, $4)',+ [depth, `2026-08-${String(20 + i).padStart(2, '0')}`, PRIVATE, event],+ );+ }+ const rows = await engine.getTimeline('people/timeline', { sourceId: A, excludePrivate: true, limit: 1 });+ expect(rows).toHaveLength(1);+ expect(rows[0].summary).toBe('public people/timeline privacy-engine-a');+ expect(JSON.stringify(await engine.getTimeline('people/timeline', { sourceId: A, limit: 1 }))).toContain(PRIVATE);+ });++ test('Chronicle filters private depth and event pages before limits and last-seen selection', async () => {+ await chronicleFixture();+ const scope = { sourceId: C, sourceIds: [A, B], excludePrivate: true, limit: 1 };+ for (const rows of [+ await engine.getTimelineForDate('2026-08-10', scope),+ await engine.getTimelineForDate('2026-08-10', { ...scope, week: true }),+ await engine.getSince('2026-08-10', scope),+ await engine.getSince('2026-08-10', { ...scope, kind: 'meeting' }),+ await engine.getOnThisDay({ ...scope, date: '2027-08-10' }),+ await engine.getSince('2026-08-10', { sourceId: A, sourceIds: [], excludePrivate: true, limit: 1 }),+ ]) {+ expect(rows.map(r => r.summary)).toEqual(['visible chronicle event']);+ expect(JSON.stringify(rows)).not.toContain(PRIVATE);+ }+ expect(await engine.getLastSeen('people/chronicle-subject', { ...scope, asof: '2026-08-12' })).toEqual({+ entity_slug: 'people/chronicle-subject', last_date: '2026-08-10', last_event_slug: 'events/chronicle-public', days_ago: 2,+ });+ expect((await engine.getLastSeen('people/public-event-only', { ...scope, asof: '2026-08-12' })).last_date).toBe('2026-08-10');+ for (const entity of ['people/private-depth-only', 'people/private-event-only']) {+ expect((await engine.getLastSeen(entity, { ...scope, asof: '2026-08-12' })).last_date).toBeNull();+ }+ expect(JSON.stringify(await engine.getSince('2026-08-10', { sourceIds: [A, B] }))).toContain(PRIVATE);+ expect((await engine.getLastSeen('people/chronicle-subject', { sourceIds: [A, B], asof: '2026-08-12' })).last_date).toBe('2026-08-11');+ });++ test('Chronicle operations propagate remote privacy through timeline and volunteer reads', async () => {+ await chronicleFixture();+ for (const remote of [true, undefined]) {+ const ctx = { engine, remote, sourceId: A, auth: { allowedSources: [A, B] } } as OperationContext;+ for (const [op, args] of [+ ['chronicle_day', { date: '2026-08-10', limit: 1, narrative: true }],+ ['chronicle_since', { date: '2026-08-10', limit: 1 }],+ ['chronicle_on_this_day', { date: '2027-08-10', limit: 1 }],+ ['volunteer_chronicle', { days: 36500, limit: 1 }],+ ] as const) {+ const result = await operationsByName[op].handler(ctx, args);+ expect(JSON.stringify(result)).toContain('visible chronicle event');+ expect(JSON.stringify(result)).not.toContain(PRIVATE);+ }+ const seen = await operationsByName.chronicle_last_seen.handler(ctx, { entity: 'people/chronicle-subject', asof: '2026-08-12' });+ expect(seen).toMatchObject({ last_date: '2026-08-10', last_event_slug: 'events/chronicle-public' });+ }+ const local = { engine, remote: false, sourceId: A } as OperationContext;+ expect(JSON.stringify(await operationsByName.chronicle_since.handler(local, { date: '2026-08-10' }))).toContain(PRIVATE);+ });++ test('takes require both a visible concrete page and an allowed holder in every read arm', async () => {+ const visible = await page('people/takes-shared');+ const hidden = await page('people/takes-shared', B, true);+ await engine.addTakesBatch([+ { page_id: visible, row_num: 1, claim: 'privacy retrieval public', kind: 'bet', holder: 'world', weight: 0.4 },+ { page_id: hidden, row_num: 1, claim: `privacy retrieval ${PRIVATE}`, kind: 'bet', holder: 'world', weight: 1 },+ { page_id: visible, row_num: 2, claim: 'privacy retrieval PRIVATE_HOLDER_CANARY', kind: 'bet', holder: 'owner-example', weight: 0.9 },+ ]);+ for (const [pageId, rowNum, quality] of [[visible, 1, 'correct'], [hidden, 1, 'incorrect'], [visible, 2, 'incorrect']] as const) {+ await engine.resolveTake(pageId, rowNum, { quality, resolvedBy: 'mcp:privacy-fixture' });+ }+ const [column] = await engine.executeRaw<{ dims: number }>("SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'takes'::regclass AND attname = 'embedding'");+ const vector = new Float32Array(Number(column.dims));+ vector[0] = 1;+ await engine.executeRaw('UPDATE takes SET embedding = $1::vector WHERE page_id = ANY($2::int[])', [`[${Array.from(vector).join(',')}]`, [visible, hidden]]);+ const scope = { sourceId: C, sourceIds: [A, B], excludePrivate: true, takesHoldersAllowList: ['world'], limit: 1 };+ for (const rows of [+ await engine.listTakes({ ...scope, sortBy: 'weight' }),+ await engine.searchTakes('privacy retrieval', scope),+ await engine.searchTakesVector(vector, scope),+ ]) {+ expect(rows.map(r => r.claim)).toEqual(['privacy retrieval public']);+ }+ expect(await engine.searchTakes('privacy retrieval', { ...scope, takesHoldersAllowList: [] })).toEqual([]);+ expect(await engine.searchTakesVector(vector, { ...scope, takesHoldersAllowList: [] })).toEqual([]);+ const gathered = await runGather(engine, { question: 'privacy retrieval', remote: true, ...scope, questionEmbedding: vector });+ expect(gathered.takes.map(r => r.claim)).toEqual(['privacy retrieval public']);+ const remote = { engine, remote: true, sourceId: A, auth: { allowedSources: [A, B] } } as OperationContext;+ for (const [op, args] of [['takes_list', {}], ['takes_search', { query: 'privacy retrieval' }]] as const) {+ expect((await operationsByName[op].handler(remote, args) as Array<{ claim: string }>).map(r => r.claim)).toEqual(['privacy retrieval public']);+ }+ expect(await engine.listTakes({ sourceIds: [A, B] })).toHaveLength(3);+ expect(await engine.getScorecard(scope, ['world'])).toMatchObject({ total_bets: 1, resolved: 1, correct: 1, incorrect: 0 });+ expect((await engine.getCalibrationCurve(scope, ['world'])).map(r => [r.n, r.observed])).toEqual([[1, 1]]);+ expect((await engine.getScorecard(scope, [])).total_bets).toBe(0);+ expect(await engine.getCalibrationCurve(scope, [])).toEqual([]);+ for (const remoteFlag of [true, undefined]) {+ // Exercise the runtime fail-closed default for legacy contexts that omit remote.+ const context = { ...remote, remote: remoteFlag } as OperationContext;+ expect(await operationsByName.takes_scorecard.handler(context, {})).toMatchObject({ total_bets: 1, mcp_resolved: 1 });+ expect((await operationsByName.takes_calibration.handler(context, {}) as Array<{ n: number }>).map(r => r.n)).toEqual([1]);+ }+ expect(await operationsByName.takes_scorecard.handler({ ...remote, takesHoldersAllowList: [] }, {})).toMatchObject({ total_bets: 0, mcp_resolved: 0 });+ expect((await engine.getScorecard({ sourceIds: [A, B] }, undefined)).total_bets).toBe(3);+ try {+ await engine.setConfig('search.remote_private_pages', 'visible');+ __resetPrivateVisibilityCacheForTests();+ const optedOut = await operationsByName.takes_search.handler(remote, { query: 'privacy retrieval' }) as Array<{ claim: string }>;+ expect(optedOut).toHaveLength(2);+ expect(JSON.stringify(optedOut)).toContain(PRIVATE);+ expect(JSON.stringify(optedOut)).not.toContain('PRIVATE_HOLDER_CANARY');+ expect(await operationsByName.takes_scorecard.handler(remote, {})).toMatchObject({ total_bets: 2, mcp_resolved: 2 });+ } finally {+ await engine.unsetConfig('search.remote_private_pages');+ __resetPrivateVisibilityCacheForTests();+ }+ });++ test('runThink resolves omitted page privacy centrally while trusted callers retain private reads', async () => {+ const hidden = await page('people/private-think', B, true);+ await engine.addTakesBatch([{ page_id: hidden, row_num: 1, claim: `privacy retrieval ${PRIVATE}`, kind: 'fact', holder: 'world', weight: 1 }]);+ const opts = {+ question: 'privacy retrieval', anchor: 'people/private-think', sourceId: B,+ stubResponse: { answer: 'Synthetic fixture answer.', citations: [], gaps: [] },+ };+ const remote = await runThink(engine, { ...opts, remote: true });+ expect(remote.pagesGathered).toBe(0);+ expect(remote.takesGathered).toBe(0);+ const local = await runThink(engine, { ...opts, remote: false });+ expect(local.pagesGathered).toBeGreaterThan(0);+ expect(local.takesGathered).toBe(1);+ });++ test('link endpoints and an independently resolved private origin are excluded', async () => {+ const root = await page('people/root');+ const visible = await page('people/visible');+ const hidden = await page('people/secret', A, true);+ const foreign = await page('people/foreign', B);+ const privateOrigin = await page('people/origin', C, true);+ const originTarget = await page('people/origin-target');+ await edge(root, visible);+ await edge(root, hidden, PRIVATE);+ await edge(root, foreign, 'cross-source public');+ await edge(root, originTarget, PRIVATE, privateOrigin);+ const scoped = await engine.getLinks('people/root', { sourceIds: [A], excludePrivate: true });+ expect(scoped.map(r => r.to_slug)).toEqual(['people/visible']);+ expect(await engine.getBacklinks('people/origin-target', { sourceIds: [A], excludePrivate: true })).toEqual([]);+ expect(await engine.getBacklinks('people/secret', { sourceId: A, excludePrivate: true })).toEqual([]);+ expect(await engine.getLinks('people/root', { sourceId: A })).toHaveLength(4);+ expect(await engine.getLinks('people/root', { sourceId: A, excludePrivate: true })).toHaveLength(2);+ expect(await engine.getBacklinks('people/visible', { sourceIds: [A], excludePrivate: true })).toHaveLength(1);+ });++ test('private graph hops and origins cannot relay paths or consume the frontier budget', async () => {+ const root = await page('people/root');+ const hidden = await page('people/a-private', A, true);+ const tail = await page('people/tail');+ const visible = await page('people/z-visible');+ const origin = await page('people/private-origin', B, true);+ const originTarget = await page('people/origin-target');+ await edge(root, hidden, PRIVATE);+ await edge(hidden, tail, PRIVATE);+ await edge(root, visible);+ await edge(root, originTarget, PRIVATE, origin);+ const scope = { sourceIds: [A], excludePrivate: true };+ const graph = await engine.traverseGraph('people/root', 3, { ...scope, frontierCap: 1 });+ expect(graph.map(r => r.slug).sort()).toEqual(['people/root', 'people/z-visible']);+ expect(graph.find(r => r.slug === 'people/root')?.links).toEqual([{ to_slug: 'people/z-visible', link_type: 'knows' }]);+ for (const direction of ['out', 'in', 'both'] as const) {+ const paths = await engine.traversePathsDetailed('people/root', { ...scope, direction, depth: 3 });+ expect(JSON.stringify(paths)).not.toContain(PRIVATE);+ expect(paths.paths.some(r => r.to_slug === 'people/tail' || r.to_slug === 'people/origin-target')).toBe(false);+ expect(paths.paths).toHaveLength(direction === 'in' ? 0 : direction === 'both' ? 2 : 1);+ expect(paths.paths.every(r => [r.from_slug, r.to_slug].every(slug => ['people/root', 'people/z-visible'].includes(slug)))).toBe(true);+ }+ expect(await engine.traverseGraph('people/a-private', 3, scope)).toEqual([]);+ expect((await engine.traversePaths('people/root', { sourceId: A, depth: 3 })).length).toBeGreaterThan(1);+ });++ test('orphans exclude private candidates and edges while preserving public cross-source reachability', async () => {+ const isolated = await page('people/private-only-link');+ const hidden = await page('people/hidden', A, true);+ const reachable = await page('people/reachable');+ const foreign = await page('people/public-referrer', B);+ await edge(isolated, hidden, PRIVATE);+ await edge(foreign, reachable);+ const rows = await engine.findOrphanPages({ sourceId: A, excludePrivate: true });+ expect(rows.map(r => r.slug)).toEqual(['people/private-only-link']);+ expect(await engine.findOrphanPages({ sourceId: A })).toEqual([]);+ });++ test('identity seed, members and member link unions share source and private boundaries', async () => {+ const seed = await page('people/seed');+ const member = await page('people/member', B);+ await page('people/private-member', B, true);+ await page('people/foreign-member', C);+ const target = await page('people/target');+ const foreignTarget = await page('people/foreign-target', C);+ const nonmember = await page('people/member', A);+ const nonmemberTarget = await page('people/nonmember-target');+ await edge(member, target);+ await edge(member, foreignTarget, 'foreign edge');+ await edge(nonmember, nonmemberTarget, 'same-slug nonmember edge');+ for (const [slug, source] of [['people/seed', A], ['people/member', B], ['people/private-member', B], ['people/foreign-member', C]]) {+ await linkEntityIdentity(engine, { entityId: 'privacy-fixture', slug, sourceId: source });+ }+ const opts = { sourceId: A, allowedSources: [A, B], excludePrivate: true };+ const members = await listEntityIdentities(engine, { slug: 'people/seed', ...opts });+ expect(members.map(r => r.slug).sort()).toEqual(['people/member', 'people/seed']);+ expect(await listEntityIdentities(engine, { slug: 'people/private-member', ...opts })).toEqual([]);+ expect(await listEntityIdentities(engine, { entityId: 'privacy-fixture', sourceId: A, allowedSources: [], excludePrivate: true })).toHaveLength(1);+ expect(await listEntityIdentities(engine, { entityId: 'privacy-fixture' })).toHaveLength(4);+ await engine.setConfig('entity_identity.union', 'true');+ const union = await unionLinksAcrossIdentity(engine, 'people/seed', [], 'out', opts);+ expect(union).toHaveLength(1);+ expect(union[0].to_slug).toBe('people/target');+ expect(await unionLinksAcrossIdentity(engine, 'people/seed', [], 'out', { sourceId: A, allowedSources: [], excludePrivate: true })).toEqual([]);+ await engine.executeRaw('UPDATE entity_identities SET source_id = $1 WHERE source_id = $2', [A, C]);+ expect((await listEntityIdentities(engine, { entityId: 'privacy-fixture', allowedSources: [A], excludePrivate: true })).map(r => r.slug)).toEqual(['people/seed']);+ expect(await listEntityIdentities(engine, { slug: 'people/foreign-member', allowedSources: [A], excludePrivate: true })).toEqual([]);+ expect(seed).toBeGreaterThan(0);+ });+ });+}diff --git a/test/e2e/legacy-chunk-privacy.test.ts b/test/e2e/legacy-chunk-privacy.test.tsnew file mode 100644index 0000000000..27975f2e06--- /dev/null+++ b/test/e2e/legacy-chunk-privacy.test.ts@@ -0,0 +1,363 @@+/** Real imports and materialized legacy chunks, not pre-cleaned chunk fixtures.+ * PostgreSQL uses only these synthetic sources and this unique reindex type.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { SearchResult } from '../../src/core/types.ts';+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';+import { readPolicyOpts } from '../../src/core/ops/context.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { runReindex } from '../../src/commands/reindex.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, renderFactsTable } from '../../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { __resetPrivateVisibilityCacheForTests } from '../../src/core/search/private-visibility.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';++const [A, B, FOREIGN] = ['chunk-privacy-a', 'chunk-privacy-b', 'chunk-privacy-foreign'];+const SOURCES = [A, B, FOREIGN];+const TYPE = 'legacy-chunk-privacy-fixture';+const PRIVATE = 'PRIVATE_PERSISTED_CHUNK_CANARY';+const QUERY = 'orbitchunkmarker';+const takes = (body: string) => `${TAKES_FENCE_BEGIN}\n${body}\n${TAKES_FENCE_END}`;+const facts = (world: string) => renderFactsTable([+ { rowNum: 1, claim: world, kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: PRIVATE, kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+]);+const variants = [+ { name: 'repeated-takes', body: `${takes(PRIVATE)}\n${takes(`${PRIVATE}_SECOND`)}`, world: undefined },+ { name: 'repeated-facts', body: `${facts('WORLD_FIRST_CHUNK_FACT')}\n${facts('WORLD_SECOND_CHUNK_FACT')}`, world: 'WORLD_SECOND_CHUNK_FACT' },+ { name: 'unterminated-takes', body: `${TAKES_FENCE_BEGIN}\n${PRIVATE}`, world: undefined },+ { name: 'unterminated-facts', body: `${FACTS_FENCE_BEGIN}\n${PRIVATE}`, world: undefined },+ { name: 'malformed-facts', body: `${FACTS_FENCE_BEGIN}\n${PRIVATE} is not a parseable Facts table.\n${FACTS_FENCE_END}`, world: undefined },+ { name: 'protected-code', body: takes(`\`\`\`typescript\nexport const forbidden = '${PRIVATE}';\n\`\`\``), world: undefined },+] as const;++for (const kind of ['pglite', 'postgres'] as const) {+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;+ suite(`${kind}: imported and legacy chunk privacy`, () => {+ let engine: BrainEngine;++ beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+ if (kind === 'postgres') assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ await engine.connect(kind === 'postgres' ? { database_url: process.env.DATABASE_URL! } : {});+ await engine.initSchema();+ for (const source of SOURCES) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);+ }+ }, 120_000);++ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages WHERE source_id = ANY($1::text[])', [SOURCES]);+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await engine.setConfig('search.crag_escalation', 'false');+ await engine.unsetConfig('search.remote_private_pages');+ __resetPrivateVisibilityCacheForTests();+ });++ afterAll(async () => {+ if (engine) {+ try {+ await engine.executeRaw('DELETE FROM sources WHERE id = ANY($1::text[])', [SOURCES]);+ for (const key of ['search.mcp_keyword_only', 'search.crag_escalation', 'search.remote_private_pages']) await engine.unsetConfig(key);+ } finally { await engine.disconnect(); }+ }+ __resetPrivateVisibilityCacheForTests();+ resetGateway();+ }, 60_000);++ function context(remote: boolean | undefined, sourceId = A, allowedSources?: string[]): OperationContext {+ return {+ engine, config: { engine: 'pglite' }, dryRun: false, remote: remote as boolean, sourceId,+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ ...(allowedSources !== undefined ? { auth: {+ token: 'fixture', clientId: 'chunk-reader-example', scopes: ['read'], allowedSources,+ } } : {}),+ };+ }++ const call = (ctx: OperationContext, name: string, args: Record<string, unknown>) => operationsByName[name].handler(ctx, args);++ async function legacy(slug: string, sourceId: string, body: string, text: string, timeline = ''): Promise<number> {+ const page = await engine.putPage(slug, {+ type: TYPE, title: 'Synthetic old document', compiled_truth: body, timeline,+ frontmatter: { visibility: 'world' }, chunker_version: 3,+ }, { sourceId });+ // An old overlapping chunk can contain only the private fragment: output+ // fence stripping alone cannot recognize or repair this payload.+ await engine.executeRaw("INSERT INTO content_chunks (page_id, chunk_index, chunk_source, chunk_text) VALUES ($1, 0, 'compiled_truth', $2)", [page.id, text]);+ return page.id;+ }++ async function safe(slug: string, sourceId: string, body: string): Promise<number> {+ const result = await importFromContent(engine, slug,+ serializeMarkdown({ visibility: 'world' }, body, '', { type: TYPE, title: 'Synthetic safely imported document', tags: [] }),+ { sourceId, noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');+ return (await engine.getPage(slug, { sourceId }))!.id;+ }++ test('actual imports strip every protected section from prose, timeline, and fenced-code chunks', async () => {+ expect(MARKDOWN_CHUNKER_VERSION).toBeGreaterThanOrEqual(4);+ for (const variant of variants) {+ const slug = `notes/import-${variant.name}`;+ const publicToken = `publicchunk${variant.name.replaceAll('-', '')}`;+ const content = serializeMarkdown({ visibility: 'world' },+ `Ordinary public context ${publicToken}.\n\n${variant.body}\n\n\`\`\`typescript\nexport const publicExample = '${publicToken}';\n\`\`\``,+ `Public timeline ${publicToken}.\n${variant.body}`,+ { type: TYPE, title: `Imported ${variant.name}`, tags: [] });+ const imported = await importFromContent(engine, slug, content, { sourceId: A, noEmbed: true, forceRechunk: true });+ expect(imported.status, `${variant.name}: ${imported.error ?? ''}`).toBe('imported');+ expect((await engine.getPage(slug, { sourceId: A }))?.compiled_truth).toContain(PRIVATE);+ const [version] = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE source_id = $1 AND slug = $2', [A, slug]);+ expect(Number(version.chunker_version)).toBe(MARKDOWN_CHUNKER_VERSION);+ const stored = await engine.getChunks(slug, { sourceId: A });+ expect(stored.length).toBeGreaterThan(0);+ expect(JSON.stringify(stored)).toContain(publicToken);+ expect(JSON.stringify(stored)).not.toContain(PRIVATE);+ if (variant.world) expect(JSON.stringify(stored)).toContain(variant.world);+ for (const remote of [true, undefined]) {+ const ctx = context(remote);+ const chunks = await call(ctx, 'get_chunks', { slug });+ expect(JSON.stringify(chunks)).toContain(publicToken);+ expect(JSON.stringify(chunks)).not.toContain(PRIVATE);+ const results = await call(ctx, 'search', { query: publicToken, limit: 5 });+ expect(JSON.stringify(results)).toContain(publicToken);+ expect(JSON.stringify(results)).not.toContain(PRIVATE);+ }+ }+ }, 60_000);++ test('unsafe legacy fragments are excluded before keyword/vector limits for remote and unset-trust scopes', async () => {+ const slug = 'notes/legacy-shared';+ const unsafe = await legacy(slug, A, `Public current body.\n${takes(PRIVATE)}`, `${QUERY} ${PRIVATE}`);+ // Current bodies cannot prove what an older materialized chunk contains.+ // Both unsafe and entirely public old chunks require a rebuild remotely.+ const markerFree = await legacy('notes/legacy-marker-free', A, 'Current body has no fence markers.', `${QUERY} ${PRIVATE}_NO_MARKERS`);+ await legacy('notes/legacy-public', A, `${QUERY} OLD_PUBLIC_CHUNK`, `${QUERY} OLD_PUBLIC_CHUNK`);+ const cleanA = await safe('notes/current-clean', A, `${QUERY} PUBLIC_CLEAN_A`);+ const cleanB = await safe(slug, B, `${QUERY} PUBLIC_CLEAN_B`);+ await safe('notes/current-foreign', FOREIGN, `${QUERY} PUBLIC_FOREIGN`);+ const [column] = await engine.executeRaw<{ dims: number }>("SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'");+ const vector = new Float32Array(Number(column.dims));+ vector[0] = 1;+ const cleanVector = vector.slice();+ cleanVector[0] = 0.8; cleanVector[1] = 0.6;+ const markerFreeVector = vector.slice();+ markerFreeVector[0] = 0.96; markerFreeVector[1] = 0.28;+ await engine.executeRaw('UPDATE content_chunks SET embedding = $1::vector WHERE page_id = ANY($2::int[])', [`[${Array.from(cleanVector)}]`, [cleanA, cleanB]]);+ await engine.executeRaw('UPDATE content_chunks SET embedding = $1::vector WHERE page_id = $2', [`[${Array.from(vector)}]`, unsafe]);+ await engine.executeRaw('UPDATE content_chunks SET embedding = $1::vector WHERE page_id = $2', [`[${Array.from(markerFreeVector)}]`, markerFree]);+ expect(JSON.stringify(await call(context(false), 'get_chunks', { slug }))).toContain(PRIVATE);+ expect(JSON.stringify(await call(context(false), 'get_chunks', { slug: 'notes/legacy-marker-free' }))).toContain(`${PRIVATE}_NO_MARKERS`);+ expect(JSON.stringify(await call(context(false), 'get_chunks', { slug: 'notes/legacy-public' }))).toContain('OLD_PUBLIC_CHUNK');++ for (const exposePrivatePages of [false, true]) {+ if (exposePrivatePages) await engine.setConfig('search.remote_private_pages', 'visible');+ else await engine.unsetConfig('search.remote_private_pages');+ __resetPrivateVisibilityCacheForTests();+ for (const remote of [true, undefined]) {+ for (const scope of [+ { ctx: context(remote), allowedIds: [cleanA], sharedChunk: undefined },+ { ctx: context(remote, A, []), allowedIds: [cleanA], sharedChunk: undefined },+ { ctx: context(remote, FOREIGN, [A, B]), allowedIds: [cleanA, cleanB], sharedChunk: 'PUBLIC_CLEAN_B' },+ ]) {+ const chunks = await call(scope.ctx, 'get_chunks', { slug });+ if (scope.sharedChunk) expect(JSON.stringify(chunks)).toContain(scope.sharedChunk);+ else expect(chunks).toEqual([]);+ expect(JSON.stringify(chunks)).not.toContain(PRIVATE);+ expect(await call(scope.ctx, 'get_chunks', { slug: 'notes/legacy-marker-free' })).toEqual([]);+ expect(await call(scope.ctx, 'get_chunks', { slug: 'notes/legacy-public' })).toEqual([]);+ const policy = await readPolicyOpts(scope.ctx);+ for (const rows of [+ await engine.searchKeyword(QUERY, { ...policy, limit: 1 }),+ await engine.searchKeywordChunks(QUERY, { ...policy, limit: 1 }),+ await engine.searchVector(vector, { ...policy, limit: 1 }),+ ]) {+ expect(rows).toHaveLength(1);+ expect(scope.allowedIds).toContain(rows[0].page_id);+ expect(JSON.stringify(rows)).not.toContain(PRIVATE);+ }+ for (const keywordOnly of ['true', 'false']) {+ await engine.setConfig('search.mcp_keyword_only', keywordOnly);+ for (const name of ['search', 'query']) {+ const rows = await call(scope.ctx, name, { query: QUERY, expand: false, limit: 1 }) as SearchResult[];+ expect(rows).toHaveLength(1);+ expect(scope.allowedIds).toContain(rows[0].page_id);+ expect(JSON.stringify(rows)).not.toContain(PRIVATE);+ }+ }+ }+ }+ }+ const policy = await readPolicyOpts(context(true));+ const before = await engine.searchVector(vector, { ...policy, limit: 1 });+ await engine.executeRaw('UPDATE content_chunks SET chunk_text = $1 WHERE page_id = $2', [`${QUERY} `.repeat(100) + PRIVATE, unsafe]);+ const after = await engine.searchVector(vector, { ...policy, limit: 1 });+ expect(after.map(row => [row.page_id, row.score])).toEqual(before.map(row => [row.page_id, row.score]));+ expect((await engine.searchVector(vector, { sourceId: A, limit: 1 }))[0].page_id).toBe(unsafe);+ }, 60_000);++ test('direct page rewrites cannot bless unsafe chunks even after protected markers are removed', async () => {+ const slug = 'notes/rewrite-cannot-bless';+ const id = await legacy(slug, A, `Original public context.\n${takes(PRIVATE)}`, `${QUERY} ${PRIVATE}`);+ for (const body of [`Edited public context.\n${takes(PRIVATE)}`, 'Edited public context without any fence markers.']) {+ await engine.putPage(slug, {+ type: TYPE, title: 'Synthetic rewritten document', compiled_truth: body, timeline: '',+ frontmatter: { visibility: 'world' }, chunker_version: MARKDOWN_CHUNKER_VERSION,+ }, { sourceId: A });+ expect((await engine.getPage(slug, { sourceId: A }))?.compiled_truth).toBe(body);+ expect(JSON.stringify(await engine.getChunks(slug, { sourceId: A }))).toContain(PRIVATE);+ for (const remote of [true, undefined]) {+ expect(await call(context(remote), 'get_chunks', { slug })).toEqual([]);+ expect(await call(context(remote), 'search', { query: QUERY, limit: 1 })).toEqual([]);+ }+ }+ const [invalidated] = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE id = $1', [id]);+ expect(Number(invalidated.chunker_version)).toBeLessThan(0);+ const repaired = await importFromContent(engine, slug,+ serializeMarkdown({ visibility: 'world' }, `${QUERY} public replacement after successful import.`, '', { type: TYPE, title: 'Repaired synthetic document', tags: [] }),+ { sourceId: A, noEmbed: true, forceRechunk: true });+ expect(repaired.status).toBe('imported');+ const chunks = await call(context(true), 'get_chunks', { slug });+ expect(JSON.stringify(chunks)).toContain('public replacement');+ expect(JSON.stringify(chunks)).not.toContain(PRIVATE);+ expect((await call(context(true), 'search', { query: QUERY, limit: 1 }) as SearchResult[])[0].page_id).toBe(id);+ }, 60_000);++ test('failed import rolls back partial chunk replacement and cannot mark legacy material safe', async () => {+ const slug = 'notes/partial-chunk-failure';+ const id = await legacy(slug, A, `Original public context.\n${takes(PRIVATE)}`, `${QUERY} ${PRIVATE}`);+ const originalChunks = await engine.getChunks(slug, { sourceId: A });+ const [originalVersion] = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE id = $1', [id]);+ let wrotePartialChunks = false;+ // Inject one failure at the storage boundary after a real chunk write.+ // The real engine transaction must roll back both page/version and chunks.+ const failingEngine = new Proxy(engine, {+ get(target, key) {+ if (key === 'transaction') return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => fn(new Proxy(tx, {+ get(transaction, method) {+ if (method === 'upsertChunks') return async (...args: Parameters<BrainEngine['upsertChunks']>) => {+ await transaction.upsertChunks(args[0], args[1].slice(0, 1), args[2]);+ wrotePartialChunks = true;+ throw new Error('synthetic chunk storage failure');+ };+ const value = Reflect.get(transaction, method);+ return typeof value === 'function' ? value.bind(transaction) : value;+ },+ })));+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ const content = serializeMarkdown({ visibility: 'world' }, `${QUERY} new safe replacement.\n${takes(PRIVATE)}\n${facts('WORLD_REPAIRED_FACT')}`,+ 'Public replacement timeline.', { type: TYPE, title: 'Repaired synthetic document', tags: [] });+ await expect(importFromContent(failingEngine, slug, content, { sourceId: A, noEmbed: true, forceRechunk: true })).rejects.toThrow('synthetic chunk storage failure');+ expect(wrotePartialChunks).toBe(true);+ expect(await engine.getChunks(slug, { sourceId: A })).toEqual(originalChunks);+ expect((await engine.executeRaw('SELECT chunker_version FROM pages WHERE id = $1', [id]))[0]).toEqual(originalVersion);+ for (const remote of [true, undefined]) {+ expect(await call(context(remote), 'get_chunks', { slug })).toEqual([]);+ expect(await call(context(remote), 'search', { query: QUERY, limit: 1 })).toEqual([]);+ }+ expect((await importFromContent(engine, slug, content, { sourceId: A, noEmbed: true, forceRechunk: true })).status).toBe('imported');+ const chunks = await call(context(true), 'get_chunks', { slug });+ expect(JSON.stringify(chunks)).toContain('new safe replacement');+ expect(JSON.stringify(chunks)).toContain('WORLD_REPAIRED_FACT');+ expect(JSON.stringify(chunks)).not.toContain(PRIVATE);+ }, 60_000);++ test('keyless rebuild discards every old vector and derived field even when public chunk text is unchanged', async () => {+ const slug = 'notes/same-text-derived-state';+ const id = await safe(slug, A, `${QUERY} public text stays unchanged.\n${takes(PRIVATE)}`);+ const [canonical] = await engine.getChunks(slug, { sourceId: A });+ expect(canonical.chunk_text).not.toContain(PRIVATE);+ // Model a pre-fix contextual embedding built from the whole document,+ // including a private sibling: unchanged public text is not provenance.+ await engine.executeRaw('UPDATE pages SET chunker_version = 3 WHERE id = $1', [id]);+ await engine.executeRaw("INSERT INTO content_chunks (page_id, chunk_index, chunk_source, chunk_text) VALUES ($1, 999, 'compiled_truth', $2)", [id, PRIVATE]);+ await engine.executeRaw(`UPDATE content_chunks SET doc_comment = $2, symbol_name = $2,+ symbol_name_qualified = $2, parent_symbol_path = ARRAY[$2::text], model = $2,+ language = $2, symbol_type = $2, modality = 'image', token_count = 999999,+ embedded_text_hash = $2, embedded_at = now(), start_line = 123, end_line = 124+ WHERE page_id = $1`, [id, PRIVATE]);+ const columns = await engine.executeRaw<{ name: string; dims: number; type: string }>(`+ SELECT a.attname AS name, a.atttypmod AS dims, t.typname AS type+ FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid+ WHERE a.attrelid = 'content_chunks'::regclass AND NOT a.attisdropped+ AND t.typname IN ('vector', 'halfvec')`);+ expect(columns.length).toBeGreaterThan(0);+ for (const column of columns) {+ expect(column.name).toMatch(/^[a-z_][a-z0-9_]*$/);+ const vector = new Array(Number(column.dims) > 0 ? Number(column.dims) : 1536).fill(0);+ vector[0] = 1;+ await engine.executeRaw(`UPDATE content_chunks SET "${column.name}" = $1::${column.type} WHERE page_id = $2`, [`[${vector}]`, id]);+ }+ expect(JSON.stringify(await engine.getChunks(slug, { sourceId: A }))).toContain(PRIVATE);+ expect(await call(context(true), 'get_chunks', { slug })).toEqual([]);++ expect(await runReindex(engine, ['--markdown', '--no-embed', '--type', TYPE])).toMatchObject({ reindexed: 1, failed: 0, pendingAfter: 0 });+ const chunks = await call(context(true), 'get_chunks', { slug }) as Array<{ chunk_text: string }>;+ expect(chunks.some(chunk => chunk.chunk_text === canonical.chunk_text)).toBe(true);+ expect(JSON.stringify(chunks)).not.toContain(PRIVATE);+ const derived = await engine.executeRaw<Record<string, unknown>>(`SELECT ${columns.map(column => `"${column.name}" IS NULL AS "${column.name}"`).join(', ')},+ doc_comment, symbol_name, symbol_name_qualified, parent_symbol_path, embedded_text_hash, embedded_at,+ language, symbol_type, start_line, end_line, modality, token_count+ FROM content_chunks WHERE page_id = $1`, [id]);+ expect(derived.length).toBeGreaterThan(0);+ for (const row of derived) {+ for (const column of columns) expect(row[column.name], column.name).toBe(true);+ for (const field of ['doc_comment', 'symbol_name', 'symbol_name_qualified', 'parent_symbol_path', 'embedded_text_hash', 'embedded_at', 'language', 'symbol_type', 'start_line', 'end_line']) expect(row[field], field).toBeNull();+ expect(row.modality).toBe('text');+ expect(row.token_count).not.toBe(999999);+ }+ const rows = await call(context(true), 'search', { query: QUERY, limit: 1 }) as SearchResult[];+ expect(rows[0].page_id).toBe(id);+ expect(JSON.stringify(rows)).not.toContain(PRIVATE);+ }, 60_000);++ test('markdown reindex upgrades legacy protected bodies and restores only safe public chunks', async () => {+ const slugs: string[] = [];+ for (const variant of variants) {+ const slug = `notes/reindex-${variant.name}`;+ slugs.push(slug);+ await legacy(slug, A, `reindexpublic ${variant.name}.\n${variant.body}`, PRIVATE,+ `reindexpublic timeline ${variant.name}.\n${variant.body}`);+ expect(await call(context(true), 'get_chunks', { slug })).toEqual([]);+ }+ // Also cover a protected section that exists only in the timeline column.+ const timelineSlug = 'notes/reindex-timeline-only';+ slugs.push(timelineSlug);+ await legacy(timelineSlug, A, 'reindexpublic body without fences.', PRIVATE,+ `reindexpublic timeline.\n${takes(PRIVATE)}\n${takes(`${PRIVATE}_SECOND`)}`);+ expect(await call(context(true), 'get_chunks', { slug: timelineSlug })).toEqual([]);+ const markerFreeSlug = 'notes/reindex-marker-free';+ slugs.push(markerFreeSlug);+ await legacy(markerFreeSlug, A, 'reindexpublic current body without any private content or markers.', PRIVATE);+ expect(await call(context(true), 'get_chunks', { slug: markerFreeSlug })).toEqual([]);++ const reindexed = await runReindex(engine, ['--markdown', '--no-embed', '--type', TYPE]);+ expect(reindexed).toMatchObject({ reindexed: slugs.length, failed: 0, pendingAfter: 0, chunkerVersion: MARKDOWN_CHUNKER_VERSION });+ const versions = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE source_id = $1', [A]);+ expect(versions).toHaveLength(slugs.length);+ expect(versions.every(row => Number(row.chunker_version) >= 4)).toBe(true);+ for (const slug of slugs) {+ const chunks = await call(context(true), 'get_chunks', { slug });+ expect(JSON.stringify(chunks)).toContain('reindexpublic');+ expect(JSON.stringify(chunks)).not.toContain(PRIVATE);+ if (slug !== markerFreeSlug) expect(JSON.stringify(await engine.getPage(slug, { sourceId: A }))).toContain(PRIVATE);+ }+ const rows = await call(context(true), 'search', { query: 'reindexpublic', limit: 20 }) as SearchResult[];+ expect(new Set(rows.map(row => row.slug))).toEqual(new Set(slugs));+ expect(JSON.stringify(rows)).not.toContain(PRIVATE);+ expect(await runReindex(engine, ['--markdown', '--no-embed', '--type', TYPE])).toMatchObject({ reindexed: 0, pending: 0, failed: 0 });+ }, 60_000);+ });+}diff --git a/test/e2e/pgbouncer-teardown.test.ts b/test/e2e/pgbouncer-teardown.test.tsindex 29b3feb9ed..aaa72ee73a 100644--- a/test/e2e/pgbouncer-teardown.test.ts+++ b/test/e2e/pgbouncer-teardown.test.ts@@ -30,10 +30,16 @@ import { join, resolve } from 'path';import { tmpdir } from 'os';import postgres from 'postgres';import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';const POOLED_URL = process.env.GBRAIN_PGBOUNCER_URL;const DIRECT_ADMIN_URL = process.env.GBRAIN_PGBOUNCER_DIRECT_URL;const SKIP = !POOLED_URL || !DIRECT_ADMIN_URL;+if (process.env.GBRAIN_CI_REQUIRE_PGBOUNCER === '1' && SKIP) {+ throw new Error('Required PgBouncer fixture is missing GBRAIN_PGBOUNCER_URL or GBRAIN_PGBOUNCER_DIRECT_URL');+}const describePooled = SKIP ? describe.skip : describe;const REPO = resolve(import.meta.dir, '..', '..');@@ -54,9 +60,14 @@ async function runCli(timeoutMs: number,): Promise<{ exitCode: number; stdout: string; stderr: string; wallMs: number }> {const t0 = Date.now();- const proc = Bun.spawn(['bun', 'run', join(REPO, 'src', 'cli.ts'), ...args], {+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', join(REPO, 'src', 'cli.ts'), ...args], {cwd: REPO,- env: { ...process.env, ...env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },+ // The suite's DATABASE_URL addresses the normal shard DB. The CLI must+ // use this fixture's pooled config, with no environment URL override.+ env: keylessBrainEnv(process.env, env.GBRAIN_HOME, {+ ...env, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_SKIP_STARTUP_HOOKS: '1',+ }),stdout: 'pipe',stderr: 'pipe',});@@ -79,6 +90,7 @@ describePooled('pgbouncer txn-mode teardown (#2084 / TD1)', () => {let home: string;beforeAll(async () => {+ assertSafeE2eDatabaseUrl(DIRECT_ADMIN_URL!);// Dedicated database on the same server, created via the DIRECT url// (CREATE DATABASE cannot run through a transaction-mode pooler).const admin = postgres(DIRECT_ADMIN_URL!, { max: 1 });@@ -122,8 +134,7 @@ describePooled('pgbouncer txn-mode teardown (#2084 / TD1)', () => {const res = await runCli(['get', SLUG], env, 90_000);if (res.exitCode !== 0 || /force-exiting/.test(res.stderr)) {- console.error('--- stdout ---\n' + res.stdout);- console.error('--- stderr ---\n' + res.stderr);+ console.error(fixtureDiagnostic('PgBouncer CLI read', res.stderr || res.stdout));}expect(res.exitCode).toBe(0);// Output is complete — the #1959 truncation class.diff --git a/test/e2e/qm-provisioning.test.ts b/test/e2e/qm-provisioning.test.tsindex 31d7e2922a..78331bf57c 100644--- a/test/e2e/qm-provisioning.test.ts+++ b/test/e2e/qm-provisioning.test.ts@@ -21,6 +21,8 @@ import { describe, test as testRaw, expect, beforeAll, afterAll } from 'bun:testimport { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';function test(name: string, fn: () => void | Promise<unknown>): void {testRaw(name, fn, 120000);@@ -32,16 +34,12 @@ const SCRIPT = join(__dirname, '..', '..', 'docs', 'integrations', 'qm-harness-sinterface RunResult { exitCode: number; stdout: string; stderr: string; }async function spawn(cmd: string[], env: Record<string, string | undefined>, cwd?: string): Promise<RunResult> {- const fullEnv: Record<string, string> = {};- for (const [k, v] of Object.entries(process.env)) {- if (v !== undefined) fullEnv[k] = v;- }- delete fullEnv.GBRAIN_REMOTE_CLIENT_SECRET;- delete fullEnv.DATABASE_URL;- for (const [k, v] of Object.entries(env)) {- if (v === undefined) delete fullEnv[k];- else fullEnv[k] = v;- }+ const fullEnv = keylessBrainEnv(process.env, env.GBRAIN_HOME!, {+ GBRAIN_REMOTE_CLIENT_SECRET: undefined,+ DATABASE_URL: undefined,+ GBRAIN_DATABASE_URL: undefined,+ ...env,+ });const proc = Bun.spawn({ cmd, env: fullEnv, cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(),@@ -52,7 +50,7 @@ async function spawn(cmd: string[], env: Record<string, string | undefined>, cwd}const gbrain = (args: string[], home: string, extraEnv: Record<string, string | undefined> = {}) =>- spawn(['bun', 'run', CLI, ...args], { GBRAIN_HOME: home, ...extraEnv });+ spawn(['bun', '--no-env-file', 'run', CLI, ...args], { GBRAIN_HOME: home, ...extraEnv });describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {let hostHome: string;@@ -70,7 +68,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {async function provision(): Promise<RunResult> {return spawn(- ['bash', SCRIPT, rosterPath(), '--gbrain', `bun run ${CLI}`, '--budget-usd-per-day', '5'],+ ['bash', SCRIPT, rosterPath(), '--gbrain', `bun --no-env-file run ${CLI}`, '--budget-usd-per-day', '5'],{ GBRAIN_HOME: hostHome },workDir,);@@ -84,7 +82,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {// 1. Host brain on PGLite, embedding deferred (FTS is enough here).const init = await gbrain(['init', '--pglite', '--no-embedding'], hostHome);- if (init.exitCode !== 0) throw new Error(`host init failed: ${init.stderr || init.stdout}`);+ if (init.exitCode !== 0) throw new Error(cliDiagnostic(`host init failed`, init));// 2. Roster v1: alice in eng, bob in product.writeFileSync(rosterPath(), [@@ -95,7 +93,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {'',].join('\n'));const p1 = await provision();- if (p1.exitCode !== 0) throw new Error(`provision v1 failed: ${p1.stderr || p1.stdout}`);+ if (p1.exitCode !== 0) throw new Error(cliDiagnostic(`provision v1 failed`, p1));for (const line of readFileSync(secretsPath(), 'utf8').trim().split('\n')) {const [slug, clientId, secret] = line.split('\t');@@ -105,7 +103,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {// 3. Idempotency: re-run with the same roster mints no new secrets.const before = readFileSync(secretsPath(), 'utf8');const p2 = await provision();- if (p2.exitCode !== 0) throw new Error(`provision re-run failed: ${p2.stderr || p2.stdout}`);+ if (p2.exitCode !== 0) throw new Error(cliDiagnostic(`provision re-run failed`, p2));rerunCredsGrew = readFileSync(secretsPath(), 'utf8') !== before;// 4. Roster churn: alice joins product → rescope in place.@@ -117,7 +115,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {'',].join('\n'));const p3 = await provision();- if (p3.exitCode !== 0) throw new Error(`provision rescope failed: ${p3.stderr || p3.stdout}`);+ if (p3.exitCode !== 0) throw new Error(cliDiagnostic(`provision rescope failed`, p3));// 4b. An UNBOUND client, standing in for a webhook integration. Registered// here because PGLite is single-process: once serve --http holds the@@ -126,7 +124,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {'auth', 'register-client', 'webhook-integration','--grant-types', 'client_credentials', '--scopes', 'read write',], hostHome);- if (wh.exitCode !== 0) throw new Error(`webhook client registration failed: ${wh.stderr || wh.stdout}`);+ if (wh.exitCode !== 0) throw new Error(cliDiagnostic(`webhook client registration failed`, wh));creds['webhook-integration'] = {clientId: wh.stdout.match(/Client ID:\s+(gbrain_cl_\S+)/)?.[1] ?? '',secret: wh.stdout.match(/Client Secret:\s+(gbrain_cs_\S+)/)?.[1] ?? '',@@ -134,14 +132,11 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {// 5. Serve over HTTP MCP (holds the PGLite lock from here on).serverPort = 30000 + Math.floor(Math.random() * 30000);- const env: Record<string, string> = {};- for (const [k, v] of Object.entries(process.env)) {- if (v !== undefined) env[k] = v;- }- env.GBRAIN_HOME = hostHome;- delete env.DATABASE_URL;+ const env = keylessBrainEnv(process.env, hostHome, {+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,+ });serverProc = Bun.spawn({- cmd: ['bun', 'run', CLI, 'serve', '--http', '--port', String(serverPort)],+ cmd: ['bun', '--no-env-file', 'run', CLI, 'serve', '--http', '--port', String(serverPort)],env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',});const deadline = Date.now() + 30_000;@@ -171,7 +166,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {'--oauth-client-id', creds[slug].clientId,'--oauth-client-secret', creds[slug].secret,], home);- if (tc.exitCode !== 0) throw new Error(`thin-client init (${slug}) failed: ${tc.stderr || tc.stdout}`);+ if (tc.exitCode !== 0) throw new Error(cliDiagnostic(`thin-client init (${slug}) failed`, tc));}}, 300_000);@@ -197,7 +192,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {body: `grant_type=client_credentials&client_id=${encodeURIComponent(clientId)}`+ `&client_secret=${encodeURIComponent(secret)}&scope=${encodeURIComponent('read write')}`,});- if (!res.ok) throw new Error(`token mint failed: ${res.status} ${await res.text()}`);+ if (!res.ok) throw new Error(fixtureDiagnostic("token mint", `status=${res.status} ${await res.text()}`));return ((await res.json()) as { access_token: string }).access_token;}@@ -230,43 +225,43 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {test('alice writes inside her prefixes (personal + channel)', async () => {const own = await asAlice(['put', 'emp-alice-example/notes/hello', '--content', '# hello\nmine']);- expect(own.exitCode).toBe(0);+ expect(own.exitCode, cliDiagnostic("qm CLI", own)).toBe(0);const chan = await asAlice(['put', 'chan-eng/notes/standup', '--content', '# standup\nshared']);- expect(chan.exitCode).toBe(0);+ expect(chan.exitCode, cliDiagnostic("qm CLI", chan)).toBe(0);});test('roster churn took effect: alice can write chan-product/ after rescope', async () => {const joined = await asAlice(['put', 'chan-product/notes/joined', '--content', '# joined']);- expect(joined.exitCode).toBe(0);+ expect(joined.exitCode, cliDiagnostic("qm CLI", joined)).toBe(0);});test("alice cannot write bob's namespace or an unbound prefix", async () => {const bobNs = await asAlice(['put', 'emp-bob-example/notes/nope', '--content', 'x']);- expect(bobNs.exitCode).not.toBe(0);+ expect(bobNs.exitCode, cliDiagnostic("qm CLI", bobNs)).not.toBe(0);expect(bobNs.stdout + bobNs.stderr).toMatch(/bound_slug_prefixes/);const stray = await asAlice(['put', 'org-notes/anything', '--content', 'x']);- expect(stray.exitCode).not.toBe(0);+ expect(stray.exitCode, cliDiagnostic("qm CLI", stray)).not.toBe(0);expect(stray.stdout + stray.stderr).toMatch(/bound_slug_prefixes/);});test('bob is fenced to HIS prefixes (not in eng)', async () => {const own = await asBob(['put', 'emp-bob-example/notes/hello', '--content', '# hi']);- expect(own.exitCode).toBe(0);+ expect(own.exitCode, cliDiagnostic("qm CLI", own)).toBe(0);const eng = await asBob(['put', 'chan-eng/notes/nope', '--content', 'x']);- expect(eng.exitCode).not.toBe(0);+ expect(eng.exitCode, cliDiagnostic("qm CLI", eng)).not.toBe(0);expect(eng.stdout + eng.stderr).toMatch(/bound_slug_prefixes/);});test('reads stay source-granular: bob CAN read chan-eng pages (documented tradeoff)', async () => {const read = await asBob(['get', 'chan-eng/notes/standup']);- expect(read.exitCode).toBe(0);+ expect(read.exitCode, cliDiagnostic("qm CLI", read)).toBe(0);expect(read.stdout).toContain('standup');});test('the documented health check works on a read+write client (no admin scope)', async () => {const who = await asAlice(['whoami']);- expect(who.exitCode).toBe(0);+ expect(who.exitCode, cliDiagnostic("qm CLI", who)).toBe(0);expect(who.stdout).toContain(creds['alice-example'].clientId);});diff --git a/test/e2e/read-enrichment-privacy.test.ts b/test/e2e/read-enrichment-privacy.test.tsnew file mode 100644index 0000000000..467e601a25--- /dev/null+++ b/test/e2e/read-enrichment-privacy.test.ts@@ -0,0 +1,427 @@+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { PageReadPolicy, SearchResult } from '../../src/core/types.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { findExperts } from '../../src/commands/whoknows.ts';+import { applySupersedeDownrank, runPostFusionStages, _resetSupersedeProbeForTests } from '../../src/core/search/hybrid.ts';+import { applyGraphSignals } from '../../src/core/search/graph-signals.ts';+import { buildRelationalArm } from '../../src/core/search/relational-recall.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { readBacklinkCounts, type ReadQuery } from '../../src/core/search/read-enrichment.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';++// Whole-engine initialization, synthetic source-scoped fixtures, no shared DB+// truncation. Every assertion below runs against PGLite and real Postgres.+const [A, B, FOREIGN, ARCHIVED] = ['enrichment-a', 'enrichment-b', 'enrichment-foreign', 'enrichment-archived'];+const SOURCES = [A, B, FOREIGN, ARCHIVED];+const policy: PageReadPolicy = { sourceIds: [A, B, ARCHIVED], excludePrivate: true, takesHoldersAllowList: ['reader'] };+const key = (slug: string, source = A) => `${source}::${slug}`;+const ref = (slug: string, source = A) => ({ slug, source_id: source });++for (const kind of ['pglite', 'postgres'] as const) {+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;+ suite(`${kind}: read enrichment privacy`, () => {+ let engine: BrainEngine;++ beforeAll(async () => {+ // Explicitly keyless: findExperts exercises the real keyword pipeline.+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();+ if (kind === 'postgres') assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);+ await engine.connect(kind === 'postgres' ? { database_url: process.env.DATABASE_URL! } : {});+ await engine.initSchema();+ for (const source of SOURCES) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [source]);+ }+ }, 120_000);++ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages WHERE source_id = ANY($1::text[])', [SOURCES]);+ await engine.executeRaw('UPDATE sources SET archived = FALSE WHERE id = ANY($1::text[])', [SOURCES]);+ _resetSupersedeProbeForTests();+ });++ afterAll(async () => {+ if (engine) {+ try { await engine.executeRaw('DELETE FROM sources WHERE id = ANY($1::text[])', [SOURCES]); }+ finally { await engine.disconnect(); }+ }+ resetGateway();+ }, 60_000);++ async function page(slug: string, source = A, frontmatter: Record<string, unknown> = {}, type = 'note'): Promise<number> {+ await engine.putPage(slug, { type, title: slug, compiled_truth: `Public fixture ${slug}`, frontmatter }, { sourceId: source });+ const rows = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2', [slug, source]);+ return Number(rows[0].id);+ }++ async function edge(from: number, to: number, origin: number | null = null, linkType = 'related', linkSource = 'manual') {+ await engine.executeRaw('INSERT INTO links (from_page_id, to_page_id, origin_page_id, link_type, link_source) VALUES ($1, $2, $3, $4, $5)', [from, to, origin, linkType, linkSource]);+ }++ async function take(id: number, row: number, holder: string, weight: number, active = true) {+ await engine.addTakesBatch([{ page_id: id, row_num: row, claim: 'Synthetic holder opinion', kind: 'take', holder, weight, active }]);+ }++ function result(slug: string, id: number, source = A): SearchResult {+ return { slug, page_id: id, source_id: source, title: slug, type: 'note', chunk_id: id, chunk_index: 0, chunk_text: 'public', chunk_source: 'compiled_truth', score: 1, stale: false } as SearchResult;+ }++ test('source-only policies reach post-fusion and graph-origin authorization', async () => {+ const target = await page('notes/scope-target');+ const first = await page('notes/scope-first');+ const second = await page('notes/scope-second');+ const foreign = await page('notes/scope-origin', FOREIGN);+ await edge(first, target, foreign);+ await edge(second, target, foreign);+ const opts = { applyBacklinks: true, salience: 'off', recency: 'off' } as const;+ const unscoped = [result('notes/scope-target', target)];+ await runPostFusionStages(engine, unscoped, opts);+ expect(unscoped[0].score).toBeGreaterThan(1);+ for (const scope of [{ sourceId: A }, { sourceIds: [A, B] }, { sourceId: A, sourceIds: [] }]) {+ const scoped = [result('notes/scope-target', target)];+ await runPostFusionStages(engine, scoped, { ...opts, ...scope });+ expect(scoped[0].score).toBe(1);+ const graph = [result('notes/scope-target', target), result('notes/scope-first', first), result('notes/scope-second', second)];+ await applyGraphSignals(graph, engine, { enabled: true, ...scope });+ expect(graph[0].score).toBe(1);+ expect(graph[0].graph_adjacency_hits).toBeUndefined();+ }+ const granted = [result('notes/scope-target', target), result('notes/scope-first', first), result('notes/scope-second', second)];+ await applyGraphSignals(granted, engine, { enabled: true, sourceIds: [A, FOREIGN] });+ expect(granted[0].graph_adjacency_hits).toBe(2);+ expect(granted[0].score).toBeGreaterThan(1);+ });++ test('relational retrieval authorizes private seeds, intermediate pages and actual origins before limits', async () => {+ const start = await page('people/relational-start');+ const bridge = await page('people/relational-a-private', A, { visibility: 'private' });+ await page('people/relational-a-private', B); // A public namesake cannot authorize the bridge.+ const beyond = await page('people/relational-beyond');+ const visible = await page('people/relational-visible');+ const hiddenOrigin = await page('people/relational-hidden-origin', B, { visibility: 'private' });+ const foreignOrigin = await page('people/relational-foreign-origin', FOREIGN);+ const grantedOrigin = await page('people/relational-granted-origin', B);+ const hiddenTarget = await page('people/relational-hidden-target');+ const foreignTarget = await page('people/relational-foreign-target');+ await edge(start, bridge);+ await edge(bridge, beyond);+ await edge(start, visible, grantedOrigin);+ await edge(start, hiddenTarget, hiddenOrigin);+ await edge(start, foreignTarget, foreignOrigin);+ const scope = { sourceIds: [A, B], excludePrivate: true, takesHoldersAllowList: ['world'] };+ const list = await buildRelationalArm(engine, 'who introduced me to people/relational-start', { ...scope, depth: 2, limit: 1 });+ expect(list.map(row => row.slug)).toEqual(['people/relational-visible']);+ expect(list[0].relational_path).toEqual(['people/relational-start', 'people/relational-visible']);+ expect(await buildRelationalArm(engine, 'who introduced me to people/relational-hidden-origin', scope)).toEqual([]);+ const unrestricted = await engine.relationalFanout(['people/relational-start']);+ expect(unrestricted.map(row => row.slug)).toContain('people/relational-a-private');+ expect(unrestricted.map(row => row.slug)).toContain('people/relational-beyond');+ expect(unrestricted.map(row => row.slug)).toContain('people/relational-hidden-target');+ expect(unrestricted.map(row => row.slug)).toContain('people/relational-foreign-target');+ expect((await engine.relationalFanout(['people/relational-start'], { sourceIds: [A, B, FOREIGN], excludePrivate: true })).map(row => row.slug)).toContain('people/relational-foreign-target');+ });++ test('relational snippets sanitize every protected fence before truncation, including page-visibility opt-outs', async () => {+ const start = await page('people/snippet-start');+ const target = await page('people/snippet-target');+ await edge(start, target);+ const take = `${TAKES_FENCE_BEGIN}\n${'PRIVATE_RELATIONAL_TAKE '.repeat(30)}\n${TAKES_FENCE_END}`;+ await engine.executeRaw('UPDATE pages SET compiled_truth = $2 WHERE id = $1', [target, `${take}\n${take}\nPUBLIC_RELATIONAL_SNIPPET`]);+ for (const excludePrivate of [true, false]) {+ const rows = await buildRelationalArm(engine, 'who introduced me to people/snippet-start', { sourceId: A, excludePrivate, takesHoldersAllowList: [] });+ expect(rows).toHaveLength(1);+ expect(rows[0].chunk_text).toContain('PUBLIC_RELATIONAL_SNIPPET');+ expect(rows[0].chunk_text).not.toContain('PRIVATE_RELATIONAL_TAKE');+ expect(rows[0].chunk_text.length).toBeLessThanOrEqual(240);+ }+ });++ test('remote title admission cannot depend on protected timeline terms in the page vector', async () => {+ const slug = 'notes/title-privacy-example';+ await importFromContent(engine, slug, serializeMarkdown({}, 'Public title-search body.',+ `${TAKES_FENCE_BEGIN}\nnegationcanary\n${TAKES_FENCE_END}`,+ { type: 'note', title: 'titleprobe example', tags: [] }), { sourceId: A, noEmbed: true, forceRechunk: true });+ const query = 'titleprobe -negationcanary';+ const [raw] = await engine.executeRaw<{ matched: boolean }>(+ "SELECT search_vector @@ websearch_to_tsquery('english', $1) AS matched FROM pages WHERE source_id = $2 AND slug = $3", [query, A, slug]);+ expect(raw.matched).toBe(false); // The old full-page prefilter would reject it.+ for (const excludePrivate of [true, false]) {+ const rows = await engine.searchTitles(query, { sourceId: A, requireSafeChunks: true, excludePrivate });+ expect(rows.map(row => row.slug)).toEqual([slug]);+ expect(JSON.stringify(rows)).not.toContain('negationcanary');+ }+ });++ test('backlinks and adjacency authorize contributors, targets and independent origins', async () => {+ const target = await page('notes/target');+ const allowed = await page('notes/allowed');+ const crossSource = await page('notes/cross-source', B);+ const hidden = await page('notes/hidden', A, { visibility: 'private' });+ const foreign = await page('notes/foreign', FOREIGN);+ const archived = await page('notes/archived', ARCHIVED);+ const deleted = await page('notes/deleted');+ const quarantined = await page('notes/quarantined', A, { quarantine: { reason: 'fixture' } });+ const originCarrier = await page('notes/origin-carrier');+ for (const id of [allowed, crossSource, hidden, foreign, archived, deleted, quarantined]) await edge(id, target);+ await edge(originCarrier, target, hidden);+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [deleted]);+ await engine.executeRaw('UPDATE sources SET archived = TRUE WHERE id = $1', [ARCHIVED]);+ const ids = [target, allowed, crossSource, hidden, foreign, archived, deleted, quarantined, originCarrier];++ expect((await engine.getBacklinkCounts(ids, policy)).get(target)).toBe(2);+ expect((await engine.getAdjacencyBoosts(ids, policy)).get(target)).toEqual({ hits: 2, cross_source_hits: 1 });+ expect((await engine.getBacklinkCounts([target])).get(target)).toBe(8); // Trusted local control.+ // An empty source array preserves the scalar floor; a nonempty grant wins.+ expect((await engine.getBacklinkCounts([target], { ...policy, sourceIds: [], sourceId: A })).get(target)).toBe(1);+ expect((await engine.getBacklinkCounts([target], { ...policy, sourceId: FOREIGN })).get(target)).toBe(2);++ await engine.executeRaw("UPDATE pages SET frontmatter = '{\"visibility\":\"private\"}'::jsonb WHERE id = $1", [target]);+ expect((await engine.getBacklinkCounts([target], policy)).get(target)).toBe(0);+ expect(await engine.getAdjacencyBoosts(ids, policy)).toEqual(new Map());+ });++ test('superseders cannot disclose private endpoints or private/foreign origins', async () => {+ const hiddenOrigin = await page('notes/hidden-origin', B, { visibility: 'private' });+ const foreignOrigin = await page('notes/foreign-origin', FOREIGN);+ const ids: number[] = [];+ for (const variant of ['allowed', 'hidden', 'foreign', 'deleted', 'quarantined', 'hidden-origin', 'foreign-origin']) {+ const target = await page(`notes/old-${variant}`);+ const from = await page(`notes/new-${variant}`, variant === 'foreign' ? FOREIGN : A,+ variant === 'hidden' ? { visibility: 'private' } : variant === 'quarantined' ? { quarantine: {} } : {});+ if (variant === 'deleted') await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [from]);+ await edge(from, target, variant === 'hidden-origin' ? hiddenOrigin : variant === 'foreign-origin' ? foreignOrigin : null, 'supersedes');+ ids.push(target);+ }+ const rows = ids.map((id, i) => result(`notes/old-${i}`, id));+ await applySupersedeDownrank(rows, engine, policy);+ expect(rows.filter(r => r.superseded).map(r => r.superseded_by)).toEqual(['notes/new-allowed']);+ expect(rows.slice(1).every(r => r.score === 1 && r.superseded_by === undefined)).toBe(true);+ const local = [result('notes/local-control', ids[5])];+ await applySupersedeDownrank(local, engine);+ expect(local[0].superseded_by).toBe('notes/new-hidden-origin');+ });++ test('stale candidate IDs and same-slug refs cannot read flags, extraction state or dates after revocation', async () => {+ const fm = { content_flag: { reason: 'fixture', detail: 'VISIBLE_FLAG' }, provenance: 'auto-extracted', status: 'unverified' };+ const visible = await page('notes/shared', A, fm);+ const hidden = await page('notes/shared', B, { ...fm, visibility: 'private' });+ const foreign = await page('notes/shared', FOREIGN, fm);+ const archived = await page('notes/shared', ARCHIVED, fm);+ await engine.executeRaw('UPDATE sources SET archived = TRUE WHERE id = $1', [ARCHIVED]);+ const ids = [visible, hidden, foreign, archived];+ const refs = SOURCES.map(source => ref('notes/shared', source));+ expect([...(await engine.getContentFlagsByPageIds(ids, policy)).keys()]).toEqual([visible]);+ expect([...(await engine.getUnverifiedExtractionPageIds(ids, policy)).keys()]).toEqual([visible]);+ expect([...(await engine.getEffectiveDates(refs, policy)).keys()]).toEqual([key('notes/shared')]);+ expect((await engine.getEffectiveDates(refs)).size).toBe(4);+ expect((await engine.getEffectiveDates(refs, { sourceId: A, sourceIds: [], excludePrivate: true })).size).toBe(1);+ await engine.executeRaw("UPDATE pages SET frontmatter = frontmatter || '{\"visibility\":\"private\"}'::jsonb WHERE id = $1", [visible]);+ expect(await engine.getContentFlagsByPageIds(ids, policy)).toEqual(new Map());+ expect(await engine.getUnverifiedExtractionPageIds(ids, policy)).toEqual(new Map());+ expect(await engine.getEffectiveDates(refs, policy)).toEqual(new Map());+ });++ test('forbidden-holder writes cannot affect restricted scores, counters or the recent window', async () => {+ const current = await page('notes/salient');+ const old = await page('notes/old-salient');+ const currentRef = ref('notes/salient');+ await take(current, 0, 'reader', 0.25);+ await take(current, 1, 'owner', 0.75);+ await take(current, 2, 'reader', 1, false);+ await take(old, 0, 'owner', 0.75);+ await engine.executeRaw("UPDATE pages SET updated_at = now() - interval '40 days', salience_touched_at = now() - interval '40 days' WHERE id = $1", [old]);+ await engine.setEmotionalWeightBatch([{ ...currentRef, weight: 0.5 }]);+ const before = (await engine.getRecentSalience({ ...policy, days: 7, limit: 100 })).find(r => r.slug === currentRef.slug)!;+ expect(before.take_count).toBe(1);+ expect(before.take_avg_weight).toBe(0.25);+ expect(before.emotional_weight).toBe(0);+ expect((await engine.getSalienceScores([currentRef], policy)).get(key(currentRef.slug))).toBeCloseTo(Math.log(2), 12);++ await take(current, 3, 'owner', 1);+ await engine.setEmotionalWeightBatch([{ ...currentRef, weight: 0.875 }, { ...ref('notes/old-salient'), weight: 0.875 }]);+ const restricted = await engine.getRecentSalience({ ...policy, days: 7, limit: 100 });+ const after = restricted.find(r => r.slug === currentRef.slug)!;+ expect(after.take_count).toBe(before.take_count);+ expect(after.take_avg_weight).toBe(before.take_avg_weight);+ expect(after.emotional_weight).toBe(0);+ expect(new Date(after.updated_at).getTime()).toBe(new Date(before.updated_at).getTime());+ expect(after.score).toBeCloseTo(before.score, 4); // Only wall-clock recency can advance.+ expect(restricted.some(r => r.slug === 'notes/old-salient')).toBe(false);+ expect((await engine.getSalienceScores([currentRef], policy)).get(key(currentRef.slug))).toBeCloseTo(Math.log(2), 12);++ const local = await engine.getRecentSalience({ sourceId: A, days: 7, limit: 100 });+ expect(local.some(r => r.slug === 'notes/old-salient')).toBe(true);+ expect(local.find(r => r.slug === currentRef.slug)!.take_count).toBe(3);+ expect((await engine.getSalienceScores([currentRef])).get(key(currentRef.slug))).toBeCloseTo(0.875 * 5 + Math.log(4), 12);+ await take(current, 4, 'reader', 0.75);+ expect((await engine.getSalienceScores([currentRef], policy)).get(key(currentRef.slug))).toBeCloseTo(Math.log(3), 12);+ const empty = { ...policy, takesHoldersAllowList: [] };+ expect((await engine.getSalienceScores([currentRef], empty)).get(key(currentRef.slug))).toBe(0);+ const emptyRecent = (await engine.getRecentSalience({ ...empty, days: 7 })).find(r => r.slug === currentRef.slug)!;+ expect([emptyRecent.take_count, emptyRecent.take_avg_weight, emptyRecent.emotional_weight]).toEqual([0, 0, 0]);+ });++ test('recent salience excludes invisible rows before limit and keeps exact source identity', async () => {+ const visible = await page('notes/shared');+ await page('notes/shared', B, { visibility: 'private' });+ await page('notes/foreign', FOREIGN);+ await page('notes/archived', ARCHIVED);+ const deleted = await page('notes/deleted');+ await page('notes/quarantined', A, { quarantine: {} });+ await engine.executeRaw('UPDATE pages SET emotional_weight = 1 WHERE source_id = ANY($1::text[]) AND id <> $2', [SOURCES, visible]);+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [deleted]);+ await engine.executeRaw('UPDATE sources SET archived = TRUE WHERE id = $1', [ARCHIVED]);+ const rows = await engine.getRecentSalience({ ...policy, takesHoldersAllowList: undefined, days: 7, limit: 1 });+ expect(rows.map(r => key(r.slug, r.source_id))).toEqual([key('notes/shared')]);+ expect((await engine.getSalienceScores(SOURCES.map(source => ref('notes/shared', source)), policy)).size).toBe(1);+ const localPrivate = await engine.getRecentSalience({ sourceId: B, days: 7 });+ expect(localPrivate.map(r => key(r.slug, r.source_id))).toEqual([key('notes/shared', B)]);+ expect((await engine.getRecentSalience({ ...policy, sourceIds: [], sourceId: A, days: 7 })).map(r => r.slug)).toEqual(['notes/shared']);+ });++ test('anomaly baselines and totals count authorized page rows before the 50-slug display cap', async () => {+ const since = '2026-08-20';+ async function activity(slug: string, source: string, day: string, fm: Record<string, unknown> = {}, tag = 'public-cohort') {+ const id = await page(slug, source, fm);+ await engine.executeRaw('UPDATE pages SET updated_at = $1::timestamptz WHERE id = $2', [`${day}T12:00:00Z`, id]);+ await engine.executeRaw('INSERT INTO tags (page_id, tag) VALUES ($1, $2)', [id, tag]);+ return id;+ }+ for (let i = 0; i < 55; i++) await activity(`notes/current-${i}`, A, since);+ await activity('notes/current-0', B, since); // Same slug, distinct authorized page: total 56, display 50.+ for (let i = 0; i < 4; i++) await activity(`notes/baseline-${i}`, A, `2026-08-${16 + i}`);+ const opts = { ...policy, since, lookback_days: 4, sigma: 3 };+ const before = await engine.findAnomalies(opts);+ const cohort = before.find(r => r.cohort_kind === 'tag' && r.cohort_value === 'public-cohort')!;+ expect(cohort.count).toBe(56);+ expect(cohort.page_slugs).toHaveLength(50);+ expect([cohort.baseline_mean, cohort.baseline_stddev]).toEqual([1, 0]);++ for (const day of ['2026-08-16', since]) {+ await activity(`notes/private-${day}`, B, day, { visibility: 'private' });+ await activity(`notes/foreign-${day}`, FOREIGN, day);+ await activity(`notes/archived-${day}`, ARCHIVED, day);+ const deleted = await activity(`notes/deleted-${day}`, A, day);+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [deleted]);+ await activity(`notes/quarantined-${day}`, A, day, { quarantine: {} });+ }+ await activity('notes/secret-only-1', B, since, { visibility: 'private' }, 'PRIVATE_COHORT_CANARY');+ await activity('notes/secret-only-2', B, since, { visibility: 'private' }, 'PRIVATE_COHORT_CANARY');+ await engine.executeRaw('UPDATE sources SET archived = TRUE WHERE id = $1', [ARCHIVED]);+ const after = await engine.findAnomalies(opts);+ expect(after).toEqual(before);+ expect(JSON.stringify(after)).not.toContain('PRIVATE_COHORT_CANARY');+ expect((await engine.findAnomalies({ ...opts, excludePrivate: false })).some(r => r.cohort_value === 'PRIVATE_COHORT_CANARY')).toBe(true);+ const scalar = await engine.findAnomalies({ ...opts, sourceIds: [], sourceId: A });+ expect(scalar.find(r => r.cohort_kind === 'tag')!.count).toBe(55);+ });++ for (const caller of ['remote', 'local scalar'] as const) {+ const expertSlug = 'people/expert-example';+ const opts = { ...(caller === 'remote' ? policy : { sourceId: A }), topic: 'nebularrouting', limit: 5 };++ async function seedExpert() {+ await importFromContent(engine, expertSlug, serializeMarkdown({}, 'Synthetic nebularrouting expertise specialist', '',+ { type: 'person', title: expertSlug, tags: [] }), { sourceId: A, noEmbed: true, forceRechunk: true });+ return (await engine.getPage(expertSlug, { sourceId: A }))!.id;+ }++ test(`${caller} experts recheck admission after salience completes a visibility/source edit`, async () => {+ const id = await seedExpert();+ expect((await findExperts(engine, opts)).map(r => r.slug)).toEqual([expertSlug]);+ const readScores = engine.getSalienceScores.bind(engine);+ const readDates = engine.getEffectiveDates.bind(engine);+ let editCompleted = false;+ try {+ engine.getSalienceScores = async (refs, scope) => {+ const scores = await readScores(refs, scope);+ if (caller === 'remote') {+ await engine.executeRaw("UPDATE pages SET frontmatter = '{\"visibility\":\"private\"}'::jsonb WHERE id = $1", [id]);+ } else {+ await engine.executeRaw('UPDATE pages SET source_id = $1 WHERE id = $2', [B, id]);+ }+ editCompleted = true;+ return scores;+ };+ engine.getEffectiveDates = async (refs, scope) => {+ // Pins the ordering independently of each engine's query scheduler:+ // an admission read started before this edit cannot authorize it.+ expect(editCompleted).toBe(true);+ return readDates(refs, scope);+ };+ expect(await findExperts(engine, opts)).toEqual([]);+ } finally {+ engine.getSalienceScores = readScores;+ engine.getEffectiveDates = readDates;+ }+ });++ test(`${caller} experts preserve salience factors and use the neutral factor when optional SQL fails`, async () => {+ const id = await seedExpert();+ await take(id, 0, 'reader', 0.25);+ await take(id, 1, 'owner', 0.75);+ await engine.setEmotionalWeightBatch([{ ...ref(expertSlug), weight: 0.5 }]);+ const baseline = await findExperts(engine, opts);+ expect(baseline.map(r => r.slug)).toEqual([expertSlug]);+ const rawSalience = caller === 'remote' ? Math.log(2) : 2.5 + Math.log(3);+ const normalized = rawSalience / (1 + rawSalience);+ expect(baseline[0].factors.salience).toBeCloseTo(normalized, 12);+ expect(baseline[0].factors.salience_factor).toBeCloseTo(0.5 + 0.5 * normalized, 12);+ const readScores = engine.getSalienceScores.bind(engine);+ try {+ engine.getSalienceScores = async () => {+ await engine.executeRaw('SELECT enrichment_missing_column FROM pages LIMIT 1');+ return new Map();+ };+ const fallback = await findExperts(engine, opts);+ expect(fallback.map(r => r.slug)).toEqual([expertSlug]);+ expect(fallback[0].factors.salience).toBe(0.5);+ expect(fallback[0].factors.salience_factor).toBe(0.75);+ expect(fallback[0].score).toBeCloseTo(fallback[0].factors.expertise * fallback[0].factors.recency_factor * 0.75, 12);+ } finally { engine.getSalienceScores = readScores; }+ });++ test(`${caller} experts propagate required admission SQL failures`, async () => {+ await seedExpert();+ expect((await findExperts(engine, opts)).map(r => r.slug)).toEqual([expertSlug]);+ const readDates = engine.getEffectiveDates.bind(engine);+ try {+ engine.getEffectiveDates = async () => {+ await engine.executeRaw('SELECT admission_missing_column FROM pages LIMIT 1');+ return new Map();+ };+ await expect(findExperts(engine, opts)).rejects.toThrow('admission_missing_column');+ } finally { engine.getEffectiveDates = readDates; }+ });+ }++ test('fixed 40-page enrichment batch uses one query and has an executable real-engine plan', async () => {+ const ids: number[] = [];+ for (let i = 0; i < 40; i++) ids.push(await page(`notes/batch-${i}`));+ for (let i = 1; i < ids.length; i++) await edge(ids[i], ids[0]);+ const statements: Array<{ sql: string; params?: unknown[] }> = [];+ const query: ReadQuery = async <T>(sql: string, params?: unknown[]): Promise<T[]> => {+ statements.push({ sql, params });+ return engine.executeRaw<T>(sql, params);+ };+ const start = performance.now();+ const counts = await readBacklinkCounts(query, ids, policy);+ const elapsedMs = performance.now() - start;+ expect(statements).toHaveLength(1);+ expect(counts.get(ids[0])).toBe(39);+ expect(counts.size).toBe(40);+ const plan = await engine.executeRaw<Record<string, unknown>>(`EXPLAIN (ANALYZE, FORMAT JSON) ${statements[0].sql}`, statements[0].params);+ expect(plan).toHaveLength(1);+ expect(JSON.stringify(plan)).toContain('Actual Rows');+ // Diagnostic evidence, not a host-speed assertion. The query-count guard+ // is stable under CI load; an arbitrary latency threshold would not be.+ console.info(`[read-enrichment] ${kind} pages=40 links=39 queries=1 elapsed_ms=${elapsedMs.toFixed(2)} explain_analyze=ok`);+ });+ });+}diff --git a/test/e2e/remote-privacy-journeys.test.ts b/test/e2e/remote-privacy-journeys.test.tsnew file mode 100644index 0000000000..462e42dbc1--- /dev/null+++ b/test/e2e/remote-privacy-journeys.test.ts@@ -0,0 +1,264 @@+/** Real MCP transport journeys over isolated, persistent PGLite brains.+ * Data seeding uses the engine before serve starts (PGLite is single-writer).+ * No provider keys, model calls, ambient brain, or external database is used.+ */+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 { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.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 { serializeMarkdown } from '../../src/core/markdown.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { renderFactsTable } from '../../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { operationsByName, type OperationContext } from '../../src/core/operations.ts';+import { unpackToolResult } from '../../src/core/mcp-client.ts';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';++const PUBLIC = 'privacyjourneypublic';+const PRIVATE = 'PRIVATE_PAGE_JOURNEY_CANARY';+const PRIVATE_FACT = 'PRIVATE_FACT_JOURNEY_CANARY';+const PRIVATE_TAKE = 'PRIVATE_TAKE_JOURNEY_CANARY';+const PRIVATE_REPORT = 'PRIVATE_QUERY_REPORT_JOURNEY_CANARY';+const SHARED = 'notes/shared-privacy';+const REPORT_NOTE = 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.';++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 server = createServer();+ await new Promise<void>((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', resolve);+ });+ const port = (server.address() as { port: number }).port;+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));+ return port;+}++const historyBody = `Ordinary public history prose.\n${renderFactsTable([+ { rowNum: 1, claim: PUBLIC, kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: PRIVATE_FACT, kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+])}\n${TAKES_FENCE_BEGIN}\n${PRIVATE_TAKE}\n${TAKES_FENCE_END}\n${renderFactsTable([+ { rowNum: 3, claim: `${PUBLIC} repeated`, kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 4, claim: `${PRIVATE_FACT} repeated`, kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+])}`;++async function seed(home: string): Promise<void> {+ const config = JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8'));+ const engine = new PGLiteEngine();+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ await engine.connect({ database_path: config.database_path });+ try {+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('private-source', 'private-source', '{\"federated\":true}'::jsonb)");+ await engine.setConfig('search.cache.enabled', 'true');+ for (const [slug, source, hidden] of [+ [SHARED, 'default', false],+ [SHARED, 'private-source', true],+ ['notes/private-only', 'default', true],+ ] as const) {+ const body = hidden ? PRIVATE : historyBody;+ const imported = await importFromContent(engine, slug, serializeMarkdown(+ { visibility: hidden ? 'private' : 'world' }, body, '',+ { type: 'note', title: hidden ? PRIVATE : PUBLIC, tags: [] },+ ), { sourceId: source, noEmbed: true, forceRechunk: true });+ expect(imported.status).toBe('imported');+ const rows = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2', [slug, source]);+ const id = Number(rows[0].id);+ // The real import path must build safe chunks from repeated protected+ // fences before the MCP transport starts reading this persistent brain.+ const chunks = JSON.stringify(await engine.getChunks(slug, { sourceId: source }));+ expect(chunks).toContain(hidden ? PRIVATE : PUBLIC);+ expect(chunks).not.toContain(PRIVATE_FACT);+ expect(chunks).not.toContain(PRIVATE_TAKE);+ await engine.executeRaw("INSERT INTO raw_data (page_id, source, data) VALUES ($1, 'fixture', $2::text::jsonb)", [id, JSON.stringify({ body: hidden ? PRIVATE : PUBLIC })]);+ await engine.executeRaw("INSERT INTO timeline_entries (page_id, date, summary) VALUES ($1, '2026-08-01', $2)", [id, hidden ? PRIVATE : PUBLIC]);+ await engine.executeRaw("INSERT INTO page_versions (page_id, compiled_truth, frontmatter) VALUES ($1, $2, '{\"visibility\":\"world\"}'::jsonb)", [id, body]);+ // A public current page must not make its formerly-private snapshot public.+ if (!hidden) await engine.executeRaw("INSERT INTO page_versions (page_id, compiled_truth, frontmatter) VALUES ($1, $2, '{\"visibility\":\"private\"}'::jsonb)", [id, PRIVATE]);+ }+ const finding = { severity: 'high', axis: PRIVATE_REPORT, a: { slug: SHARED }, b: { slug: SHARED } };+ await engine.writeContradictionsRun({+ run_id: 'privacy-journey-run', judge_model: 'fixture', prompt_version: '1',+ queries_evaluated: 1, queries_with_contradiction: 1, total_contradictions_flagged: 1,+ wilson_ci_lower: 0, wilson_ci_upper: 1, judge_errors_total: 0, cost_usd_total: 0,+ duration_ms: 1, source_tier_breakdown: {}, report_json: { per_query: [{ contradictions: [finding] }] },+ });+ // Positive controls: persisted private evidence and trusted local reports+ // exist, so empty remote responses cannot pass on an empty fixture.+ expect(JSON.stringify(await engine.getChunks(SHARED, { sourceId: 'private-source' }))).toContain(PRIVATE);+ expect(JSON.stringify(await engine.getVersions(SHARED))).toContain(PRIVATE_FACT);+ const local: OperationContext = {+ engine,+ config: { engine: 'pglite' },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: '__all__',+ };+ expect(JSON.stringify(await operationsByName.find_contradictions.handler(local, {}))).toContain(PRIVATE_REPORT);+ } finally {+ await engine.disconnect();+ resetGateway();+ }+}++for (const kind of ['stdio', 'http'] as const) {+ describe(`${kind}: remote privacy through a real MCP session`, () => {+ let home: string;+ let env: Record<string, string>;+ let client: Client | undefined;+ let transport: StdioClientTransport | StreamableHTTPClientTransport | undefined;+ let server: ChildProcess | undefined;+ let credentials: { clientId: string; clientSecret: string } | undefined;++ async function closeSession(): Promise<void> {+ try { await client?.close(); } finally {+ client = undefined;+ try { await transport?.close(); } finally {+ transport = undefined;+ if (server && server.exitCode === null && server.signalCode === null) {+ const child = server;+ await new Promise<void>(resolve => {+ const timer = setTimeout(() => child.kill('SIGKILL'), 5_000);+ child.once('exit', () => { clearTimeout(timer); resolve(); });+ child.kill('SIGTERM');+ });+ }+ server = undefined;+ }+ }+ }++ async function openSession(exposePrivatePages = false): Promise<void> {+ const sessionEnv = { ...env, ...(exposePrivatePages ? { GBRAIN_REMOTE_PRIVATE_PAGES: '1' } : {}) };+ client = new Client({ name: `privacy-journey-${kind}`, version: '1.0.0' }, { capabilities: {} });+ if (kind === 'stdio') {+ transport = new StdioClientTransport({+ command: 'bun', args: ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--surface', 'full'],+ cwd: process.cwd(), env: sessionEnv, stderr: 'pipe',+ });+ } else {+ const port = await unusedPort();+ const 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,+ ], { cwd: process.cwd(), env: sessionEnv, stdio: ['ignore', 'ignore', 'pipe'] });+ server.stderr?.on('data', (data: Buffer) => { stderr = (stderr + data.toString()).slice(-4000); });+ let ready = false;+ for (let attempt = 0; attempt < 120; attempt++) {+ try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(1000) })).ok; } catch { /* starting */ }+ if (ready || server.exitCode !== null) break;+ await Bun.sleep(250);+ }+ if (!ready) throw new Error(fixtureDiagnostic('privacy journey HTTP startup', stderr));+ const response = await fetch(`${base}/token`, {+ method: 'POST', signal: AbortSignal.timeout(10_000),+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: credentials!.clientId, client_secret: credentials!.clientSecret }),+ });+ expect(response.status).toBe(200);+ const token = await response.json() as { access_token: string };+ expect(typeof token.access_token).toBe('string');+ transport = new StreamableHTTPClientTransport(new URL(`${base}/mcp`), {+ requestInit: { headers: { Authorization: `Bearer ${token.access_token}` } },+ });+ }+ await client.connect(transport, { signal: AbortSignal.timeout(30_000) });+ }++ async function call(name: string, args: Record<string, unknown> = {}) {+ const result = await client!.callTool({ name, arguments: args }, undefined, { timeout: 30_000 });+ expect(result.isError, toolDiagnostic(name, result)).not.toBe(true);+ // The structured body is block zero; MCP may append advisory text.+ return { result, body: unpackToolResult<any>(result) };+ }++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), `gbrain-privacy-${kind}-`));+ env = keylessBrainEnv(process.env, home, {+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,+ GBRAIN_REMOTE_PRIVATE_PAGES: undefined, GBRAIN_MCP_FORCE_SURFACE: undefined,+ GBRAIN_SOURCE: undefined, GBRAIN_SWEEP: '0',+ });+ cli(env, ['init', '--pglite', '--no-embedding', '--non-interactive']);+ await seed(home);+ if (kind === 'http') {+ const registered = cli(env, ['auth', 'register-client', 'privacy-journey',+ '--grant-types', 'client_credentials', '--scopes', 'read admin',+ '--source', 'private-source', '--federated-read', 'private-source,default',+ '--token-endpoint-auth-method', 'client_secret_post']);+ const clientId = registered.match(/Client ID:\s+(\S+)/)?.[1];+ const clientSecret = registered.match(/Client Secret:\s+(\S+)/)?.[1];+ if (!clientId || !clientSecret) throw new Error('Privacy fixture client registration omitted credentials');+ credentials = { clientId, clientSecret };+ cli(env, ['auth', 'rescope-client', clientId, '--surface', 'full']);+ }+ await openSession();+ }, 120_000);++ afterAll(async () => {+ try { await closeSession(); } finally {+ if (home) rmSync(home, { recursive: true, force: true });+ }+ }, 30_000);++ test('same-slug content readers and history retain public data and exclude private rows', async () => {+ for (const name of ['get_page', 'get_chunks', 'get_raw_data', 'get_timeline', 'get_versions']) {+ const { result, body } = await call(name, { slug: SHARED });+ expect(JSON.stringify(body)).toContain(PUBLIC);+ for (const hidden of [PRIVATE, PRIVATE_FACT, PRIVATE_TAKE]) expect(JSON.stringify(result)).not.toContain(hidden);+ if (name === 'get_versions') {+ expect(body).toHaveLength(1);+ expect(body[0].compiled_truth).toContain(`${PUBLIC} repeated`);+ }+ }+ for (const name of ['get_chunks', 'get_raw_data', 'get_timeline', 'get_versions']) {+ const { body } = await call(name, { slug: 'notes/private-only' });+ expect(body).toEqual([]);+ }+ }, 45_000);++ test('fresh query metadata and stored-report containment survive the transport', async () => {+ for (let i = 0; i < 2; i++) {+ const { result, body } = await call('query', { query: PUBLIC, expand: false, use_cache: true, limit: 5 });+ expect(JSON.stringify(body)).toContain(PUBLIC);+ expect(JSON.stringify(result)).not.toContain(PRIVATE);+ expect((result._meta?.retrieval as { cache?: string })?.cache).toBe('disabled');+ }+ expect((await call('cache_stats')).body.enabled).toBe(false);+ const { body } = await call('find_contradictions');+ expect(body).toEqual({ contradictions: [], note: REPORT_NOTE });+ expect(JSON.stringify(body)).not.toContain(PRIVATE_REPORT);+ }, 45_000);++ test('page-visibility opt-out leaves historical Facts/Takes and report boundaries active', async () => {+ await closeSession();+ await openSession(true);+ const { body: privateChunks } = await call('get_chunks', { slug: 'notes/private-only' });+ expect(JSON.stringify(privateChunks)).toContain(PRIVATE);+ const { result, body } = await call('get_versions', { slug: SHARED });+ expect(JSON.stringify(body)).toContain(PUBLIC);+ expect(JSON.stringify(result)).not.toContain(PRIVATE_FACT);+ expect(JSON.stringify(result)).not.toContain(PRIVATE_TAKE);+ expect((await call('find_contradictions')).body).toEqual({ contradictions: [], note: REPORT_NOTE });+ }, 60_000);+ });+}diff --git a/test/e2e/serve-http-surface-ceiling.test.ts b/test/e2e/serve-http-surface-ceiling.test.tsindex a334c6bb0b..e85fb23751 100644--- a/test/e2e/serve-http-surface-ceiling.test.ts+++ b/test/e2e/serve-http-surface-ceiling.test.ts@@ -28,9 +28,11 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import { spawn, execFileSync, type ChildProcess } from 'child_process';+import { spawn, spawnSync, type ChildProcess } from 'child_process';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';import { join } from 'path';import { VERB_NAMES } from '../../src/core/verbs.ts';import { operations } from '../../src/core/operations.ts';@@ -59,17 +61,20 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {// DATABASE_URL would put the spawned serve on Postgres) and any ambient// kill-switch value (server B sets its own explicitly).function brainEnv(home: string): Record<string, string | undefined> {- const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home };- delete env.DATABASE_URL;- delete env.GBRAIN_DATABASE_URL;- delete env.GBRAIN_MCP_FORCE_SURFACE;- return env;+ return keylessBrainEnv(process.env, home, {+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ GBRAIN_MCP_FORCE_SURFACE: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,+ });}function cli(env: Record<string, string | undefined>, args: string[]): string {- return execFileSync('bun', ['run', 'src/cli.ts', ...args], {+ const result = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', ...args], {cwd: process.cwd(), env, encoding: 'utf8',});+ 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 waitReady(base: string, stderrRef: { text: string }): Promise<boolean> {@@ -80,7 +85,7 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {} catch { /* not up yet */ }await new Promise((r) => setTimeout(r, 500));}- throw new Error(`serve --http did not become ready at ${base}:\n${stderrRef.text.slice(-800)}`);+ throw new Error(fixtureDiagnostic("serve --http readiness", stderrRef.text));}beforeAll(async () => {@@ -94,7 +99,7 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {cli(envA, ['init', '--pglite', '--no-embedding', '--non-interactive']);const authA = cli(envA, ['auth', 'create', 'e2e-surface-bare']);bareTokenA = (authA.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];- if (!bareTokenA) throw new Error(`auth create did not yield a token:\n${authA}`);+ if (!bareTokenA) throw new Error("auth create did not yield a token");const reg = cli(envA, ['auth', 'register-client', 'e2e-surface-full-preset',@@ -103,37 +108,37 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {]);fullClientId = (reg.match(/Client ID:\s+(\S+)/) ?? ['', ''])[1];fullClientSecret = (reg.match(/Client Secret:\s+(\S+)/) ?? ['', ''])[1];- if (!fullClientId || !fullClientSecret) throw new Error(`register-client did not yield creds:\n${reg}`);+ if (!fullClientId || !fullClientSecret) throw new Error("register-client did not yield credentials");// The "full preset": pin the client's row surface to 'full' — the widest// possible per-client request. The verbs ceiling must still win.const rescope = cli(envA, ['auth', 'rescope-client', fullClientId, '--surface', 'full']);- if (!/full/.test(rescope)) throw new Error(`rescope-client --surface full did not confirm:\n${rescope}`);+ if (!/full/.test(rescope)) throw new Error(fixtureDiagnostic("rescope-client --surface full", rescope));// ── Brain B: bare legacy token only (kill-switch server).cli(envB, ['init', '--pglite', '--no-embedding', '--non-interactive']);const authB = cli(envB, ['auth', 'create', 'e2e-surface-force']);bareTokenB = (authB.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];- if (!bareTokenB) throw new Error(`auth create did not yield a token:\n${authB}`);+ if (!bareTokenB) throw new Error("auth create did not yield a token");// ── Spawn both servers. B carries the kill switch set to FULL — the// widening attempt this suite proves impossible.const errA = { text: '' };const errB = { text: '' };serverA = spawn('bun', [- 'run', 'src/cli.ts', 'serve', '--http', '--surface', 'verbs',+ '--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--surface', 'verbs','--bind', '127.0.0.1', '--port', String(PORT_A), '--public-url', BASE_A,], { cwd: process.cwd(), env: envA, stdio: ['ignore', 'pipe', 'pipe'] });- serverA.stderr?.on('data', (d: Buffer) => { errA.text += d.toString(); });+ serverA.stderr?.on('data', (d: Buffer) => { errA.text = (errA.text + d.toString()).slice(-4000); });serverB = spawn('bun', [- 'run', 'src/cli.ts', 'serve', '--http', '--surface', 'verbs',+ '--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--surface', 'verbs','--bind', '127.0.0.1', '--port', String(PORT_B), '--public-url', BASE_B,], {cwd: process.cwd(),env: { ...envB, GBRAIN_MCP_FORCE_SURFACE: 'full' },stdio: ['ignore', 'pipe', 'pipe'],});- serverB.stderr?.on('data', (d: Buffer) => { errB.text += d.toString(); });+ serverB.stderr?.on('data', (d: Buffer) => { errB.text = (errB.text + d.toString()).slice(-4000); });readyA = await waitReady(BASE_A, errA);readyB = await waitReady(BASE_B, errB);@@ -144,7 +149,7 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {headers: { 'Content-Type': 'application/x-www-form-urlencoded' },body: `grant_type=client_credentials&client_id=${fullClientId}&client_secret=${fullClientSecret}&scope=${encodeURIComponent('read write')}`,});- if (!tokenRes.ok) throw new Error(`token mint failed: ${tokenRes.status} ${await tokenRes.text()}`);+ if (!tokenRes.ok) throw new Error(fixtureDiagnostic("token mint", `status=${tokenRes.status} ${await tokenRes.text()}`, [fullClientSecret]));fullPresetToken = ((await tokenRes.json()) as { access_token: string }).access_token;}, 120_000);@@ -163,7 +168,7 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {const trimmed = text.trim();if (trimmed.startsWith('{')) return JSON.parse(trimmed);const dataLines = trimmed.split('\n').filter((l) => l.startsWith('data:'));- if (dataLines.length === 0) throw new Error('No JSON-RPC payload in /mcp response: ' + trimmed.slice(0, 300));+ if (dataLines.length === 0) throw new Error(fixtureDiagnostic('No JSON-RPC payload', trimmed));return JSON.parse(dataLines[dataLines.length - 1].slice('data:'.length).trim());}@@ -252,7 +257,7 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {name: 'remember',arguments: { fact: factText, provenance: 'e2e: serve-http-surface-ceiling' },});- expect(rememberResult.isError).toBeFalsy();+ expect(rememberResult.isError, toolDiagnostic("verbs roundtrip", rememberResult)).toBeFalsy();const remembered = JSON.parse(rememberResult.content[0].text);expect(remembered.protocol_version).toBe(1);expect(remembered.status).toBe('inserted');@@ -262,7 +267,7 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {name: 'recall',arguments: {},});- expect(recallResult.isError).toBeFalsy();+ expect(recallResult.isError, toolDiagnostic("verbs roundtrip", recallResult)).toBeFalsy();const recalled = JSON.parse(recallResult.content[0].text);expect(recalled.protocol_version).toBe(1);expect(Array.isArray(recalled.facts)).toBe(true);diff --git a/test/e2e/serve-stdio-roundtrip.test.ts b/test/e2e/serve-stdio-roundtrip.test.tsindex 76d3bce9d7..52d2d81009 100644--- a/test/e2e/serve-stdio-roundtrip.test.ts+++ b/test/e2e/serve-stdio-roundtrip.test.ts@@ -26,7 +26,10 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import { execFileSync } from 'child_process';+import { spawnSync } from 'child_process';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { cliDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -35,6 +38,13 @@ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'import { VERB_NAMES } from '../../src/core/verbs.ts';import { GBRAIN_MCP_INSTRUCTIONS } from '../../src/mcp/instructions.ts';+function execFixture(args: string[], env: Record<string, string>): void {+ const result = spawnSync('bun', ['--no-env-file', ...args], { cwd: process.cwd(), env, encoding: 'utf8' });+ if (result.status !== 0) throw new Error(cliDiagnostic(args[2] ?? 'stdio fixture', {+ exitCode: result.status ?? -1, stdout: result.stdout ?? '', stderr: result.stderr ?? '',+ }));+}+// Distinctive token so keyword search can't accidentally match anything else.const MARKER = 'qantani-marker-9f3z';const FEDERATED_MARKER = 'umbriel-federated-marker-71c4';@@ -64,17 +74,13 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()// assertion fails).// Build a concrete Record<string,string> (StdioClientTransport.env rejects// undefined values), dropping the ambient DB URLs so the subprocess is PGLite.- const env: Record<string, string> = {};- for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;- env.GBRAIN_HOME = home;- delete env.DATABASE_URL;- delete env.GBRAIN_DATABASE_URL;+ const env = keylessBrainEnv(process.env, home, {+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,+ });delete env.GBRAIN_SOURCE;// 1. Init a local PGLite brain (the "from nothing" step).- execFileSync('bun', ['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], {- cwd: process.cwd(), env, stdio: 'ignore',- });+ execFixture(['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], env);// 2. Seed one page so page_count > 0 and search has something to find.// --no-embed keeps it hermetic (no embedding provider configured); the@@ -85,9 +91,7 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()join(notes, 'marker.md'),`---\ntitle: ${MARKER} note\n---\n\n# ${MARKER}\n\nThis page exists to prove ${MARKER} is retrievable over stdio MCP.\n`,);- execFileSync('bun', ['run', 'src/cli.ts', 'import', notes, '--no-embed'], {- cwd: process.cwd(), env, stdio: 'ignore',- });+ execFixture(['run', 'src/cli.ts', 'import', notes, '--no-embed'], env);// Seed a second source that participates in unqualified federated reads.// Import through the CLI so this uses the ordinary source registration@@ -98,22 +102,14 @@ describe('serve stdio round-trip E2E (local PGLite → real MCP tool calls)', ()join(federatedNotes, 'marker.md'),`---\ntitle: ${FEDERATED_MARKER} note\n---\n\n# ${FEDERATED_MARKER}\n\nThis page exists only in the federated source.\n`,);- execFileSync(- 'bun',- ['run', 'src/cli.ts', 'sources', 'add', 'federated-source', '--path', federatedNotes, '--federated', '--force'],- { cwd: process.cwd(), env, stdio: 'ignore' },- );- execFileSync(- 'bun',- ['run', 'src/cli.ts', 'import', federatedNotes, '--no-embed', '--source-id', 'federated-source'],- { cwd: process.cwd(), env, stdio: 'ignore' },- );+ execFixture(['run', 'src/cli.ts', 'sources', 'add', 'federated-source', '--path', federatedNotes, '--federated', '--force'], env);+ execFixture(['run', 'src/cli.ts', 'import', federatedNotes, '--no-embed', '--source-id', 'federated-source'], env);// 3. Let the MCP SDK spawn `gbrain serve` (stdio) and run the initialize// handshake — exactly what `claude mcp add gbrain -- gbrain serve` does.transport = new StdioClientTransport({command: 'bun',- args: ['run', 'src/cli.ts', 'serve'],+ args: ['--no-env-file', 'run', 'src/cli.ts', 'serve'],cwd: process.cwd(),env, // includes PATH (to find `bun`) + GBRAIN_HOME});@@ -196,11 +192,9 @@ describe('serve --surface verbs stdio E2E (the 7 frozen memory verbs over a realbeforeAll(async () => {home = mkdtempSync(join(tmpdir(), 'gbrain-stdio-verbs-e2e-'));// Same hermetic-PGLite env dance as the full-surface session above.- const env: Record<string, string> = {};- for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;- env.GBRAIN_HOME = home;- delete env.DATABASE_URL;- delete env.GBRAIN_DATABASE_URL;+ const env = keylessBrainEnv(process.env, home, {+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,+ });// Quiescent brain: the startup sweep could touch pages BETWEEN the two// delta wakes and legitimately re-surface them (a changed page is SUPPOSED// to re-appear), turning the cursor-advance assertion flaky. Kill switch@@ -208,9 +202,7 @@ describe('serve --surface verbs stdio E2E (the 7 frozen memory verbs over a realenv.GBRAIN_SWEEP = '0';// 1. Init a local PGLite brain.- execFileSync('bun', ['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], {- cwd: process.cwd(), env, stdio: 'ignore',- });+ execFixture(['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], env);// 2. Seed two pages BEFORE serve spawns so the first delta wake has pages// to deliver (the cursor-advance assertion needs a non-empty delivery).@@ -224,14 +216,12 @@ describe('serve --surface verbs stdio E2E (the 7 frozen memory verbs over a realjoin(notes, 'pack-b.md'),`---\ntitle: ${VERBS_MARKER} beta\n---\n\n# ${VERBS_MARKER} beta\n\nSeed page B for the verbs-surface delta cursor.\n`,);- execFileSync('bun', ['run', 'src/cli.ts', 'import', notes, '--no-embed'], {- cwd: process.cwd(), env, stdio: 'ignore',- });+ execFixture(['run', 'src/cli.ts', 'import', notes, '--no-embed'], env);// 3. Spawn the QUICKSTART surface — exactly the 7 protocol verbs.transport = new StdioClientTransport({command: 'bun',- args: ['run', 'src/cli.ts', 'serve', '--surface', 'verbs'],+ args: ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--surface', 'verbs'],cwd: process.cwd(),env,});@@ -256,7 +246,7 @@ describe('serve --surface verbs stdio E2E (the 7 frozen memory verbs over a realtest('tools/call context_pack on an unknown entity → schema-valid empty pack, protocol_version 1', async () => {expect(connected).toBe(true);const res = await client!.callTool({ name: 'context_pack', arguments: { entities: 'nonexistent-entity' } });- expect((res as { isError?: boolean }).isError).not.toBe(true);+ expect((res as { isError?: boolean }).isError, toolDiagnostic("verbs roundtrip", res)).not.toBe(true);const pack = JSON.parse(textOf(res)) as {protocol_version: number;entities: string[];@@ -278,7 +268,7 @@ describe('serve --surface verbs stdio E2E (the 7 frozen memory verbs over a realtest('tools/call delta with an explicit epoch cursor → protocol_version 1 + has_more + next_cursor', async () => {expect(connected).toBe(true);const res = await client!.callTool({ name: 'delta', arguments: { since: '1970-01-01T00:00:00Z' } });- expect((res as { isError?: boolean }).isError).not.toBe(true);+ expect((res as { isError?: boolean }).isError, toolDiagnostic("verbs roundtrip", res)).not.toBe(true);const d = JSON.parse(textOf(res)) as {protocol_version: number;since: string;@@ -325,7 +315,7 @@ describe('serve --surface verbs stdio E2E (the 7 frozen memory verbs over a realprovenance: 'e2e: serve-stdio-roundtrip',},});- expect((remembered as { isError?: boolean }).isError).not.toBe(true);+ expect((remembered as { isError?: boolean }).isError, toolDiagnostic("remember roundtrip", remembered)).not.toBe(true);const rem = JSON.parse(textOf(remembered)) as { id: string; status: string; protocol_version: number };expect(rem.protocol_version).toBe(1);expect(['inserted', 'duplicate', 'superseded']).toContain(rem.status);diff --git a/test/e2e/source-isolation-pglite.test.ts b/test/e2e/source-isolation-pglite.test.tsindex 5eb4650fb1..ae4c60d2fd 100644--- a/test/e2e/source-isolation-pglite.test.ts+++ b/test/e2e/source-isolation-pglite.test.ts@@ -18,6 +18,8 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';let engine: PGLiteEngine;let chunkEmbedDim = 0;@@ -37,6 +39,21 @@ afterAll(async () => {await engine.disconnect();});+async function importFixture(slug: string, sourceId: string, title: string, body: string, frontmatter: Record<string, unknown>, embeddingIndex?: number) {+ const result = await importFromContent(engine, slug,+ serializeMarkdown(frontmatter, body, '', { type: 'person', title, tags: [] }),+ { sourceId, noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');+ if (embeddingIndex !== undefined) {+ // The index is built by the real importer. Only its test vector is+ // synthetic, preserving the existing deterministic source-ranking probe.+ const embedding = Array.from({ length: chunkEmbedDim }, (_, i) => i === embeddingIndex ? 1 : 0);+ await engine.executeRaw(`UPDATE content_chunks SET embedding = $1::vector+ WHERE page_id IN (SELECT id FROM pages WHERE source_id = $2 AND slug = $3)`,+ [`[${embedding}]`, sourceId, slug]);+ }+}+beforeEach(async () => {await resetPgliteState(engine);// Two sources so we can prove the filter excludes cross-source rows.@@ -46,60 +63,23 @@ beforeEach(async () => {);// Seed one person page in each source. Same slug intentionally —// proves the composite (source_id, slug) key is honored, not just slug.- // upsertChunks is needed because searchKeyword scans content_chunks, not- // pages.compiled_truth directly. Each page gets one chunk that mirrors- // its compiled_truth so search-by-keyword has something to find.- await engine.putPage('people/alice', {- type: 'person',- title: 'Alice Source-A',- compiled_truth: 'Alice works on widgets in source A. Important context here.',- timeline: '',- frontmatter: {+ // Real imports build current safe chunks for the remote operation controls.+ await importFixture('people/alice', 'default', 'Alice Source-A',+ 'Alice works on widgets in source A. Important context here.', {message_id: '<[email protected]>',thread_id: 'thread-source-a',subject: 'Source A exact subject',- },- }, { sourceId: 'default' });- await engine.upsertChunks('people/alice', [{- chunk_index: 0,- chunk_text: 'Alice works on widgets in source A. Important context here.',- chunk_source: 'compiled_truth',- token_count: 12,- embedding: Float32Array.from({ length: chunkEmbedDim }, (_, i) => i === 0 ? 1 : 0),- }], { sourceId: 'default' });+ }, 0);- await engine.putPage('people/alice', {- type: 'person',- title: 'Alice Source-B',- compiled_truth: 'Alice works on gadgets in source B. Important context here.',- timeline: '',- frontmatter: {+ await importFixture('people/alice', 'src-b', 'Alice Source-B',+ 'Alice works on gadgets in source B. Important context here.', {message_id: '<[email protected]>',thread_id: 'thread-source-b',subject: 'Source B exact subject',- },- }, { sourceId: 'src-b' });- await engine.upsertChunks('people/alice', [{- chunk_index: 0,- chunk_text: 'Alice works on gadgets in source B. Important context here.',- chunk_source: 'compiled_truth',- token_count: 12,- embedding: Float32Array.from({ length: chunkEmbedDim }, (_, i) => i === 1 ? 1 : 0),- }], { sourceId: 'src-b' });+ }, 1);- await engine.putPage('people/bob', {- type: 'person',- title: 'Bob Source-B Only',- compiled_truth: 'Bob lives only in source B. Important context here.',- timeline: '',- frontmatter: {},- }, { sourceId: 'src-b' });- await engine.upsertChunks('people/bob', [{- chunk_index: 0,- chunk_text: 'Bob lives only in source B. Important context here.',- chunk_source: 'compiled_truth',- token_count: 11,- }], { sourceId: 'src-b' });+ await importFixture('people/bob', 'src-b', 'Bob Source-B Only',+ 'Bob lives only in source B. Important context here.', {});});describe('v0.34.1 source-isolation regression (#861)', () => {diff --git a/test/e2e/thin-client.test.ts b/test/e2e/thin-client.test.tsindex 79182015ae..2ce276e591 100644--- a/test/e2e/thin-client.test.ts+++ b/test/e2e/thin-client.test.ts@@ -27,6 +27,8 @@ import { describe, test as testRaw, expect, beforeAll, afterAll } from 'bun:testimport { mkdtempSync, rmSync, readFileSync, existsSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';function test(name: string, fn: () => void | Promise<unknown>): void {testRaw(name, fn, 120000);@@ -38,18 +40,11 @@ const DATABASE_URL = process.env.DATABASE_URL;interface RunResult { exitCode: number; stdout: string; stderr: string; }async function spawn(args: string[], home: string, extraEnv: Record<string, string | undefined> = {}): Promise<RunResult> {- const env: Record<string, string> = {};- for (const [k, v] of Object.entries(process.env)) {- if (v !== undefined) env[k] = v;- }- env.GBRAIN_HOME = home;- delete env.GBRAIN_REMOTE_CLIENT_SECRET;- for (const [k, v] of Object.entries(extraEnv)) {- if (v === undefined) delete env[k];- else env[k] = v;- }+ const env = keylessBrainEnv(process.env, home, {+ GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_DATABASE_URL: undefined, ...extraEnv,+ });const proc = Bun.spawn({- cmd: ['bun', 'run', CLI, ...args],+ cmd: ['bun', '--no-env-file', 'run', CLI, ...args],env,stdin: 'ignore',stdout: 'pipe',@@ -84,19 +79,17 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {// deferral flag); thin-client tests exercise the routing surface, not// embedding, so no provider is needed.const init = await spawn(['init', '--non-interactive', '--no-embedding', '--url', DATABASE_URL!], hostHome);- if (init.exitCode !== 0) throw new Error(`host init failed: ${init.stderr || init.stdout}`);+ if (init.exitCode !== 0) throw new Error(cliDiagnostic(`host init failed`, init));// 2. Pick a random free port for serve --http.serverPort = 30000 + Math.floor(Math.random() * 30000);// 3. Spawn serve --http (background, async).- const env: Record<string, string> = {};- for (const [k, v] of Object.entries(process.env)) {- if (v !== undefined) env[k] = v;- }- env.GBRAIN_HOME = hostHome;+ const env = keylessBrainEnv(process.env, hostHome, {+ GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_DATABASE_URL: undefined,+ });serverProc = Bun.spawn({- cmd: ['bun', 'run', CLI, 'serve', '--http', '--port', String(serverPort)],+ cmd: ['bun', '--no-env-file', 'run', CLI, 'serve', '--http', '--port', String(serverPort)],env,stdin: 'ignore',stdout: 'pipe',@@ -121,12 +114,12 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {'--grant-types', 'client_credentials','--scopes', 'read write admin',], hostHome);- if (reg.exitCode !== 0) throw new Error(`register-client failed: ${reg.stderr || reg.stdout}`);+ if (reg.exitCode !== 0) throw new Error(cliDiagnostic(`register-client failed`, reg));const parsed = parseRegisterClientOutput(reg.stdout);clientId = parsed.clientId;clientSecret = parsed.clientSecret;if (!clientId || !clientSecret) {- throw new Error(`register-client returned unexpected output: ${reg.stdout}`);+ throw new Error(fixtureDiagnostic("register-client", "missing client ID or secret"));}});@@ -159,7 +152,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {'--oauth-client-id', clientId,'--oauth-client-secret', clientSecret,], clientHome);- expect(r.exitCode).toBe(0);+ expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(0);const cfgPath = join(clientHome, '.gbrain', 'config.json');expect(existsSync(cfgPath)).toBe(true);const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'));@@ -170,7 +163,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {test('doctor reports mode: thin-client with all checks green', async () => {const r = await spawn(['doctor', '--json'], clientHome);- expect(r.exitCode).toBe(0);+ expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(0);const report = JSON.parse(r.stdout.trim());expect(report.mode).toBe('thin-client');expect(report.status).toBe('ok');@@ -184,7 +177,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {test('sync is refused with canonical thin-client error', async () => {const r = await spawn(['sync'], clientHome);- expect(r.exitCode).toBe(1);+ expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(1);// refuseThinClient() emits "(thin-client of <mcp_url>)" with the hyphenated// form. Allow either spelling so a future format tweak doesn't false-fail.expect(r.stderr).toMatch(/thin[- ]client/);@@ -193,7 +186,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {test('re-running init refuses without --force', async () => {const r = await spawn(['init', '--non-interactive', '--pglite', '--json'], clientHome);- expect(r.exitCode).toBe(1);+ expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(1);const parsed = JSON.parse(r.stdout.trim().split('\n').pop()!);expect(parsed.reason).toBe('thin_client_config_present');});@@ -267,7 +260,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {'--grant-types', 'client_credentials','--scopes', 'read write',], hostHome);- if (reg.exitCode !== 0) throw new Error(`register-client failed: ${reg.stderr || reg.stdout}`);+ if (reg.exitCode !== 0) throw new Error(cliDiagnostic(`register-client failed`, reg));const parsed = parseRegisterClientOutput(reg.stdout);const lowScopeId = parsed.clientId;const lowScopeSecret = parsed.clientSecret;@@ -283,12 +276,12 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {'--oauth-client-secret', lowScopeSecret,], lowScopeHome);if (init.exitCode !== 0) {- throw new Error(`low-scope init exit=${init.exitCode}\nstdout:${init.stdout}\nstderr:${init.stderr}`);+ throw new Error(cliDiagnostic("low-scope init", init));}- expect(init.exitCode).toBe(0);+ expect(init.exitCode, cliDiagnostic("thin-client CLI", init)).toBe(0);const r = await spawn(['remote', 'doctor', '--json'], lowScopeHome);- expect(r.exitCode).toBe(1);+ expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(1);const err = JSON.parse(r.stdout.trim());expect(err.status).toBe('error');// Either the SDK 401 path or our auth_after_refresh wrap is fine —@@ -332,12 +325,12 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {// Clear it — suites that need it set it themselves.await spawn(['config', 'unset', 'sync.repo_path'], hostHome);const put = await spawn(['put', G3_SLUG, '--content', content], hostHome);- if (put.exitCode !== 0) throw new Error(`seed put failed: ${put.stderr || put.stdout}`);+ if (put.exitCode !== 0) throw new Error(cliDiagnostic(`seed put failed`, put));const rem = await spawn(['remember', `The rendezvous codeword is ${G3_MARKER}`, '--provenance', 'thin-client e2e seed'],hostHome,);- if (rem.exitCode !== 0) throw new Error(`seed remember failed: ${rem.stderr || rem.stdout}`);+ if (rem.exitCode !== 0) throw new Error(cliDiagnostic(`seed remember failed`, rem));}interface VerbRuns {@@ -431,7 +424,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {const r = await spawn(['search', G3_MARKER, '--json'], clientHome, {GBRAIN_REMOTE_CLIENT_SECRET: 'gbrain_cs_definitely_not_the_real_secret',});- expect(r.exitCode).toBe(1);+ expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(1);// No fabricated results — stdout stays empty on the error path.expect(r.stdout.trim()).toBe('');// Canonical RemoteMcpError surface. mcp-client maps the non-401 /token@@ -459,10 +452,10 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {// routed default timeout is 30s. Anything near the 120s test timeout is// the hang this test exists to forbid.expect(Date.now() - t0).toBeLessThan(60_000);- expect(search.exitCode).toBe(1);+ expect(search.exitCode, cliDiagnostic("thin-client CLI", search)).toBe(1);expect(search.stdout.trim()).toBe('');expect(search.stderr).toContain(`Cannot reach http://127.0.0.1:${serverPort}/mcp`);- expect(recall.exitCode).toBe(1);+ expect(recall.exitCode, cliDiagnostic("thin-client CLI", recall)).toBe(1);expect(recall.stdout.trim()).toBe('');expect(recall.stderr).toMatch(/OAuth discovery failed/);});diff --git a/test/e2e/think-source-isolation-pglite.test.ts b/test/e2e/think-source-isolation-pglite.test.tsindex 8d64ff4ac3..61455f5fb4 100644--- a/test/e2e/think-source-isolation-pglite.test.ts+++ b/test/e2e/think-source-isolation-pglite.test.ts@@ -1,10 +1,15 @@import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';import { runGather } from '../../src/core/think/gather.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';let engine: PGLiteEngine;beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();@@ -23,12 +28,11 @@ beforeAll(async () => {] as const;const takeVector = new Float32Array(1536).fill(0.01);for (const [sourceId, slug, body] of fixtures) {- const page = await engine.putPage(slug, {- type: 'person', title: slug, compiled_truth: body, timeline: '', frontmatter: {},- }, { sourceId });- await engine.upsertChunks(slug, [{- chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth', token_count: 4,- }], { sourceId });+ const imported = await importFromContent(engine, slug,+ serializeMarkdown({}, body, '', { type: 'person', title: slug, tags: [] }),+ { sourceId, noEmbed: true });+ expect(imported.status).toBe('imported');+ const page = (await engine.getPage(slug, { sourceId }))!;await engine.addTakesBatch([{page_id: page.id, row_num: 1, claim: 'thinkscope evidence',kind: 'fact', holder: 'world', weight: 1,@@ -50,7 +54,7 @@ beforeAll(async () => {});afterAll(async () => {- await engine.disconnect();+ try { await engine.disconnect(); } finally { resetGateway(); }});describe('think gather source isolation (#2200)', () => {@@ -89,4 +93,49 @@ describe('think gather source isolation (#2200)', () => {expect(result.graphSlugs).not.toContain('people/think-allowed');expect(result.graphSlugs).not.toContain('people/think-denied');}, 20_000);++ test('unindexed anchor keeps its source identity and sanitizes remote body reads', async () => {+ const slug = 'people/unindexed-anchor';+ const question = 'zzunindexedidentityprobezz';+ const publicBody = 'Public unindexed anchor control.';+ const privateBody = 'PRIVATE_UNINDEXED_ANCHOR_CANARY';+ const deniedBody = 'DENIED_UNINDEXED_ANCHOR_CANARY';+ const anchor = await engine.putPage(slug, {+ type: 'person', title: 'Unindexed anchor', timeline: '',+ compiled_truth: `${publicBody}\n<!--- gbrain:takes:begin -->\n${privateBody}\n<!--- gbrain:takes:end -->`,+ }, { sourceId: 'think-a' });+ await engine.putPage(slug, {+ type: 'person', title: 'Denied namesake', compiled_truth: deniedBody, timeline: '',+ }, { sourceId: 'think-denied' });+ expect(await engine.getChunks(slug, { sourceId: 'think-a' })).toEqual([]);++ for (const remote of [undefined, true]) {+ const result = await runGather(engine, {+ question, anchor: slug, sourceId: 'think-a', remote,+ });+ expect(result.diagnostics.pagesFromHybrid).toBe(0);+ expect(result.pages).toHaveLength(1);+ const row = result.pages[0];+ expect(row.page_id).toBe(anchor.id);+ expect(row.source_id).toBe('think-a');+ expect(row.chunk_id).toBe(0);+ expect(row.score).toBe(1);+ expect(row.chunk_text).toContain(publicBody);+ expect(row.chunk_text).not.toContain(privateBody);+ expect(row.chunk_text).not.toContain(deniedBody);+ expect(result.warnings).not.toContain('ANCHOR_PAGE_NOT_FOUND');+ }++ const local = await runGather(engine, {+ question, anchor: slug, sourceId: 'think-a', remote: false,+ });+ expect(local.pages[0].source_id).toBe('think-a');+ expect(local.pages[0].chunk_text).toContain(privateBody);++ const denied = await runGather(engine, {+ question, anchor: slug, sourceId: 'think-b', remote: true,+ });+ expect(denied.pages).toEqual([]);+ expect(denied.warnings).toContain('ANCHOR_PAGE_NOT_FOUND');+ }, 20_000);});diff --git a/test/entity-identity.test.ts b/test/entity-identity.test.tsindex 5d5e12f398..3664a654c7 100644--- a/test/entity-identity.test.ts+++ b/test/entity-identity.test.ts@@ -297,15 +297,21 @@ describe('#4224 review — the identity key is (source_id, slug) in the union to// shares the slug but is a REAL co-member — pre-fix `m.slug !== slug`// dropped it and its edges never merged.const base = await engine.getLinks('people/alice', { sourceId: 'default' });- const out = await unionLinksAcrossIdentity(engine, 'people/alice', base, 'out', { sourceId: 'default' });+ const out = await unionLinksAcrossIdentity(engine, 'people/alice', base, 'out', {+ sourceId: 'default', allowedSources: ['default', 'team-brain'],+ });expect(out.some(l => l.to_slug === 'companies/acme')).toBe(true);expect(out.some(l => l.to_slug === 'companies/widget-co')).toBe(true);+ const scalar = await unionLinksAcrossIdentity(engine, 'people/alice', base, 'out', {+ sourceId: 'default', allowedSources: [],+ });+ expect(scalar).toEqual(base);- // Op-level: the scalar ctx scope threads through as the base source.+ // Op-level: a scalar ctx scope is also the member visibility floor.const links = await operationsByName.get_links!.handler(localCtx({ sourceId: 'default' }), { slug: 'people/alice' },) as Array<{ to_slug: string }>;- expect(links.some(l => l.to_slug === 'companies/widget-co')).toBe(true);+ expect(links.some(l => l.to_slug === 'companies/widget-co')).toBe(false);});test('NON-member base page with a same-slug member elsewhere is NOT unioned', async () => {diff --git a/test/extract-atoms-page-discovery.test.ts b/test/extract-atoms-page-discovery.test.tsindex d421c18fbd..0a144c65c9 100644--- a/test/extract-atoms-page-discovery.test.ts+++ b/test/extract-atoms-page-discovery.test.ts@@ -236,7 +236,7 @@ describe('v0.41.2.1: discoverExtractablePages SQL contract', () => {test('executeRaw failure returns [] (fail-soft, transcript path proceeds)', async () => {// Inject a SQL error by passing a sourceId that breaks the query —// actually easier: temporarily replace executeRaw to throw.- const realExecute = engine.executeRaw.bind(engine);+ const realExecute = engine.executeRaw;(engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =async () => { throw new Error('synthetic discovery failure'); };try {@@ -636,16 +636,17 @@ describe('local extract-atoms config knobs — invalid-value fallbacks', () => {* resolvePageDiscoveryLimit's parse/clamp behavior without exporting it.*/async function effectiveDiscoveryLimit(): Promise<number> {- const realExecute = engine.executeRaw.bind(engine);+ const realExecute = engine.executeRaw;let limitParam: number | undefined;- (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = (async (+ (engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw = (async function (+ this: PGLiteEngine,sql: string,params?: unknown[],- ) => {+ ) {if (sql.includes('atoms_scan_hash') && sql.includes('LIMIT $4')) {limitParam = Number((params ?? [])[3]);}- return realExecute(sql as never, params as never);+ return realExecute.call(this, sql as never, params as never);}) as typeof engine.executeRaw;try {await runPhaseExtractAtoms(engine, { _transcripts: [], _chat: stubChat('[]') });diff --git a/test/extraction-review.test.ts b/test/extraction-review.test.tsindex 75ffe202e9..924ed653d2 100644--- a/test/extraction-review.test.ts+++ b/test/extraction-review.test.ts@@ -625,13 +625,15 @@ describe('e2e: hostile transcript', () => {const real = await engine.getPage('people/zorbulon-realperson');// 3. Chunk both with equal lexical relevance (distinct texts — identical- // ones would be Jaccard-deduped). Enrichment stubs are chunked by the- // normal reindex/import pipeline later; seed what it would write.+ // ones would be Jaccard-deduped). Replace the imported stub's chunk+ // and seed the control's chunk with comparable lexical evidence.await engine.upsertChunks(stub!.slug, [{ chunk_index: 0, chunk_text: 'zorbulon pivot details from the injected meeting', chunk_source: 'compiled_truth', token_count: 7 }]);await engine.upsertChunks(real!.slug, [{ chunk_index: 0, chunk_text: 'zorbulon launch update in my own written notes', chunk_source: 'compiled_truth', token_count: 7 }]);- // 4. Search. No embedding provider configured → keyword(+title) fusion path.- const results = await hybridSearch(engine, 'zorbulon', { limit: 10 });+ // 4. Select the low-detail authority lane explicitly. The default detail+ // gives all chunks equal footing; only low enables compiled-truth boost.+ // No embedding provider configured → keyword(+title) fusion path.+ const results = await hybridSearch(engine, 'zorbulon', { limit: 10, detail: 'low' });const fake = results.find((r) => r.slug === stub!.slug);const legit = results.find((r) => r.slug === real!.slug);expect(fake).toBeDefined();@@ -641,7 +643,7 @@ describe('e2e: hostile transcript', () => {expect(fake!.unverified).toBe(true);expect(legit!.unverified).toBeUndefined();// …and stripped of entity authority: the verified page outranks the- // injected stub despite identical chunk text (2x compiled-truth boost ++ // injected stub despite equal lexical relevance (2x compiled-truth boost +// people/ source-boost apply only to the verified page).expect(legit!.score).toBeGreaterThan(fake!.score);});diff --git a/test/fts-language-cache-isolation.serial.test.ts b/test/fts-language-cache-isolation.serial.test.tsindex f6a4ae464e..bc9785b9aa 100644--- a/test/fts-language-cache-isolation.serial.test.ts+++ b/test/fts-language-cache-isolation.serial.test.ts@@ -1,25 +1,8 @@/**- * GBRAIN_FTS_LANGUAGE must isolate query_cache rows.- *- * getFtsLanguage() reaches both sides of the lexical arms — the- * `update_page_search_vector` / `update_chunk_search_vector` triggers that- * build the tsvector, and the `websearch_to_tsquery(<lang>, …)` inside- * searchKeyword / searchTitles / searchKeywordChunks on BOTH engines — but it- * only applied at DB-query build time, i.e. on a cache MISS. So the- * documented language-switch procedure- * (`GBRAIN_FTS_LANGUAGE=… gbrain reindex-search-vector --yes`) left every- * pre-switch cache row reachable: the freshly retokenized index was silently- * bypassed for up to cache.ttl_seconds.- *- * This drives the real production path (`hybridSearchCached` over a PGLite- * brain) rather than the hash in isolation: a run under `english` populates a- * row from an english-stemmed index, then the same query under a different- * configuration must NOT be served that row. The fixture makes the difference- * observable — "builders" stems to "builder" under english and matches the- * seeded pages; under `simple` it stays "builders" and matches nothing, so a- * stale hit is a visibly wrong answer, not just a wrong key.- *- * Serial: mock.module + process.env mutation (isolation guards R1 + R2).+ * Production-wrapper regression coverage with semantic response caching disabled.+ * Fresh reads must retain filtering, metadata and telemetry guarantees; legacy+ * cache implementation behavior is covered by the direct cache-class suites.+ * Serial because embedding and gateway configuration are process-global.*/import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';@@ -85,14 +68,9 @@ async function search(query: string): Promise<{}beforeAll(async () => {- // Hermetic config home so a developer's real ~/.gbrain/config.json can't- // leak an embedding_model that flips the consult to 'disabled' via- // isCacheSafe (same rationale as hybrid-cached-hit-budget-meta).tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-fts-cache-key-'));process.env.GBRAIN_HOME = tmpHome;- // The brain is built and indexed under the default language, exactly like- // an install that has not run a language switch yet.setFtsLanguage(undefined);resetGateway();@@ -106,9 +84,6 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();- // Keyword-findable pages. putPage never chunks and searchKeyword joins- // content_chunks, so the chunks are explicit. The chunk trigger stamps- // search_vector with the language in force at initSchema time (english).const fixtures: Array<[string, string, string]> = [['alice-foo', 'Alice Foo', 'person'],['bob-bar', 'Bob Bar', 'company'],@@ -134,40 +109,26 @@ afterAll(async () => {try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }});-describe('query_cache isolation across an FTS language switch', () => {- test('an english-tokenized row is not served to a differently configured process', async () => {- // 1. Default (english) install: 'builders' stems to 'builder' and finds- // the seeded pages. The row lands in query_cache.+describe('fresh retrieval across an FTS language switch', () => {+ test('switching language immediately changes fresh results and switching back restores recall', async () => {setFtsLanguage(undefined);const englishRun = await search('builders');- expect(englishRun.status).toBe('miss');+ expect(englishRun.status).toBe('disabled');expect(englishRun.results.length).toBeGreaterThan(0);- // Same process, same language → the row is reachable (the cache still- // works; this pins that the fix isolates rather than disables).const englishRepeat = await search('builders');- expect(englishRepeat.status).toBe('hit');+ expect(englishRepeat.status).toBe('disabled');expect(englishRepeat.results.length).toBe(englishRun.results.length);- // 2. Operator switches the language. Only the query side moves here (the- // seeded search_vector stays english-stemmed), which is what makes the- // divergence observable in-process: 'builders' no longer reaches- // 'builder', so this process cannot reproduce the english answer from- // the index it is now querying. A real switch also retokenizes the- // write side via `reindex-search-vector`; either way the cached rows- // describe a corpus view the new configuration does not have.setFtsLanguage('simple');const switched = await search('builders');- // Pre-fix this was a HIT serving englishRun.results (3 pages).- expect(switched.status).toBe('miss');+ expect(switched.status).toBe('disabled');expect(switched.results.length).toBeLessThan(englishRun.results.length);- // 3. Switching back reaches the original row, not a rebuilt one — the- // two languages occupy distinct rows rather than overwriting.setFtsLanguage(undefined);const back = await search('builders');- expect(back.status).toBe('hit');+ expect(back.status).toBe('disabled');expect(back.results.map((r) => r.slug)).toEqual(englishRun.results.map((r) => r.slug));});});diff --git a/test/get-page-federated-scope.test.ts b/test/get-page-federated-scope.test.tsindex 5c0c7efeeb..842275f79f 100644--- a/test/get-page-federated-scope.test.ts+++ b/test/get-page-federated-scope.test.ts@@ -25,6 +25,8 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:tesimport { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';let engine: PGLiteEngine;const get_page = operations.find(o => o.name === 'get_page')!;@@ -48,6 +50,13 @@ function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {};}+async function importPage(slug: string, sourceId: string, title: string, body: string, timeline = '') {+ const result = await importFromContent(engine, slug,+ serializeMarkdown({}, body, timeline, { type: 'note', title, tags: [] }),+ { sourceId, noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');+}+beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});@@ -63,9 +72,7 @@ beforeEach(async () => {await engine.executeRaw(`INSERT INTO sources (id, name, local_path) VALUES ('alpha', 'alpha', '/tmp/alpha') ON CONFLICT (id) DO NOTHING`);await engine.executeRaw(`INSERT INTO sources (id, name, local_path) VALUES ('beta', 'beta', '/tmp/beta') ON CONFLICT (id) DO NOTHING`);// Distinct slugs per source so an exact lookup can leak across the boundary.- await engine.putPage('secret/beta-doc', {- type: 'note', title: 'Beta secret', compiled_truth: 'beta-only content', frontmatter: {},- }, { sourceId: 'beta' });+ await importPage('secret/beta-doc', 'beta', 'Beta secret', 'beta-only content');await engine.putPage('shared/alpha-doc', {type: 'note', title: 'Alpha doc', compiled_truth: 'alpha content', frontmatter: {},}, { sourceId: 'alpha' });@@ -87,16 +94,8 @@ beforeEach(async () => {await engine.addTag('secret/beta-doc', 'beta-tag', { sourceId: 'beta' });// A same-slug page in 'default' with DIFFERENT tags — the cross-source bleed// guard. A federated read scoped to [alpha,beta] must NEVER surface these.- await engine.putPage('secret/beta-doc', {- type: 'note', title: 'Default decoy', compiled_truth: 'default content', frontmatter: {},- }, { sourceId: 'default' });+ await importPage('secret/beta-doc', 'default', 'Default decoy', 'default content');await engine.addTag('secret/beta-doc', 'default-secret-tag', { sourceId: 'default' });- await engine.upsertChunks('secret/beta-doc', [{- chunk_index: 0, chunk_text: 'beta chunk', chunk_source: 'compiled_truth', token_count: 2,- }], { sourceId: 'beta' });- await engine.upsertChunks('secret/beta-doc', [{- chunk_index: 0, chunk_text: 'default chunk', chunk_source: 'compiled_truth', token_count: 2,- }], { sourceId: 'default' });await engine.putRawData('secret/beta-doc', 'crm', { owner: 'beta' }, { sourceId: 'beta' });await engine.putRawData('secret/beta-doc', 'crm', { owner: 'default' }, { sourceId: 'default' });await engine.createVersion('secret/beta-doc', { sourceId: 'beta' });@@ -435,7 +434,7 @@ describe('#2200 get_timeline honors the federated grant', () => {describe('#2200 residual by-slug reads honor the federated grant', () => {test('get_chunks returns only in-grant chunks', async () => {const hit = await get_chunks.handler(remoteCtx(['alpha', 'beta']), { slug: 'secret/beta-doc' }) as any[];- expect(hit.map(c => c.chunk_text)).toEqual(['beta chunk']);+ expect(hit.map(c => c.chunk_text)).toEqual(['beta-only content']);expect(await get_chunks.handler(remoteCtx(['alpha']), { slug: 'secret/beta-doc' })).toEqual([]);});@@ -526,14 +525,10 @@ describe('#2555 get_chunks federated scope', () => {const get_chunks = operations.find(o => o.name === 'get_chunks')!;beforeEach(async () => {- await engine.upsertChunks('secret/beta-doc', [- { chunk_index: 0, chunk_text: 'beta chunk zero', chunk_source: 'compiled_truth' },- { chunk_index: 1, chunk_text: 'beta chunk one', chunk_source: 'compiled_truth' },- ], { sourceId: 'beta' });+ // Separate body/timeline sections produce two real, safely indexed chunks.+ await importPage('secret/beta-doc', 'beta', 'Beta secret', 'beta chunk zero', 'beta chunk one');// Same-slug decoy chunks in 'default' — the cross-source bleed guard.- await engine.upsertChunks('secret/beta-doc', [- { chunk_index: 0, chunk_text: 'default decoy chunk', chunk_source: 'compiled_truth' },- ], { sourceId: 'default' });+ await importPage('secret/beta-doc', 'default', 'Default decoy', 'default decoy chunk');});test('op: federated grant including the page source returns its chunks (the #2555 repro)', async () => {diff --git a/test/get-timeline-op.test.ts b/test/get-timeline-op.test.tsindex 06554eeb55..44affadf09 100644--- a/test/get-timeline-op.test.ts+++ b/test/get-timeline-op.test.ts@@ -1,18 +1,17 @@import { describe, expect, test } from 'bun:test';import { operationsByName, type OperationContext } from '../src/core/operations.ts';-import type { TimelineOpts } from '../src/core/types.ts';+import type { TimelineOpts, PageReadPolicy } from '../src/core/types.ts';const getTimeline = operationsByName['get_timeline'];function makeCtx(): OperationContext {- const calls: Array<{ slug: string; opts?: TimelineOpts }> = [];+ const calls: Array<{ slug: string; opts?: TimelineOpts & PageReadPolicy }> = [];const engine = {- getTimeline: async (slug: string, opts?: TimelineOpts) => {+ getTimeline: async (slug: string, opts?: TimelineOpts & PageReadPolicy) => {calls.push({ slug, opts });return [];},- // #4352 gate surface: remote callers resolve the private-pages config- // (no opt-out here) and probe for private-only slugs (none here).+ // Remote callers resolve the private-pages config (no opt-out here).getConfig: async () => null,executeRaw: async () => [],};@@ -32,7 +31,7 @@ function makeCtx(): OperationContext {allowedSources: ['alpha', 'beta'],},__calls: calls,- } as unknown as OperationContext & { __calls: Array<{ slug: string; opts?: TimelineOpts }> };+ } as unknown as OperationContext & { __calls: Array<{ slug: string; opts?: TimelineOpts & PageReadPolicy }> };}describe('get_timeline op', () => {@@ -53,10 +52,13 @@ describe('get_timeline op', () => {limit: 7,});- expect((ctx as typeof ctx & { __calls: Array<{ slug: string; opts?: TimelineOpts }> }).__calls).toEqual([{+ expect((ctx as typeof ctx & { __calls: Array<{ slug: string; opts?: TimelineOpts & PageReadPolicy }> }).__calls).toEqual([{slug: 'people/alice-example',opts: {sourceIds: ['alpha', 'beta'],+ excludePrivate: true,+ requireSafeChunks: true,+ takesHoldersAllowList: ['world'],after: '2026-01-01',before: '2026-03-31',limit: 7,@@ -72,8 +74,11 @@ describe('get_timeline op', () => {until: '2026-04-30',});- expect((ctx as typeof ctx & { __calls: Array<{ slug: string; opts?: TimelineOpts }> }).__calls[0]?.opts).toMatchObject({+ expect((ctx as typeof ctx & { __calls: Array<{ slug: string; opts?: TimelineOpts & PageReadPolicy }> }).__calls[0]?.opts).toMatchObject({sourceIds: ['alpha', 'beta'],+ excludePrivate: true,+ requireSafeChunks: true,+ takesHoldersAllowList: ['world'],after: '2026-04-01',before: '2026-04-30',});diff --git a/test/git-remote.test.ts b/test/git-remote.test.tsindex 99d8c1bfc2..b96b39b551 100644--- a/test/git-remote.test.ts+++ b/test/git-remote.test.ts@@ -20,7 +20,7 @@ import { withEnv } from './helpers/with-env.ts';import { gitStderrLeads } from './helpers/git-stderr-probe.ts';// ----------------------------------------------------------------------------// Fake-git harness: write a shell script that records its argv to a log file,+// Fake-git harness: write a Bun script that records its argv to a log file,// then prepend its dir to PATH for the test. Lets us assert exact argv shape// without invoking real git.// ---------------------------------------------------------------------------@@ -35,17 +35,20 @@ function writeFakeGit(): void {writeFileSync(FAKE_GIT_MODE, 'ok');// Per-invocation argv goes into argv.log (one JSON array per line).writeFileSync(FAKE_GIT_LOG, '');- const script = `#!/usr/bin/env bash-# Fake git for git-remote.test.ts-{ printf '['; for arg in "$@"; do printf '%s,' "$(printf '%s' "$arg" | jq -Rs .)"; done; printf 'null]\\n'; } >> "${FAKE_GIT_LOG}"-mode=$(cat "${FAKE_GIT_MODE}" 2>/dev/null || echo ok)-case "$mode" in- fail) exit 1 ;;- url-drift) echo "https://github.com/different/url" ;;- url-match) echo "https://github.com/expected/url" ;;- *) ;;-esac-exit 0+ const recorder = join(FAKE_GIT_DIR, 'record-argv.ts');+ writeFileSync(recorder, `+import { appendFileSync, readFileSync } from 'node:fs';+appendFileSync(${JSON.stringify(FAKE_GIT_LOG)}, JSON.stringify(process.argv.slice(2)) + '\\n');+const mode = readFileSync(${JSON.stringify(FAKE_GIT_MODE)}, 'utf8');+if (mode === 'fail') process.exit(1);+if (mode === 'url-drift') console.log('https://github.com/different/url');+if (mode === 'url-match') console.log('https://github.com/expected/url');+`);+ // Use the already-required Bun executable: optional host tools such as jq+ // must not decide whether argv security assertions can run in CI.+ const shellQuote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;+ const script = `#!/bin/sh+exec ${shellQuote(process.execPath)} --no-env-file ${shellQuote(recorder)} "$@"`;const path = join(FAKE_GIT_DIR, 'git');writeFileSync(path, script);@@ -57,10 +60,7 @@ function readArgvLog(): string[][] {return raw.split('\n').filter(Boolean)- .map(line => {- const arr = JSON.parse(line) as (string | null)[];- return arr.filter((x): x is string => x !== null);- });+ .map(line => JSON.parse(line) as string[]);}function clearArgvLog(): void {@@ -80,6 +80,12 @@ beforeEach(() => {const fakePath = (): string => `${FAKE_GIT_DIR}:${process.env.PATH ?? ''}`;+test('fake git records exact argument boundaries without external JSON tools', () => {+ const args = ['', 'with spaces', 'quote"and\'slash\\', 'first\nsecond', '$(literal-command); &'];+ execFileSync(join(FAKE_GIT_DIR, 'git'), args);+ expect(readArgvLog()).toEqual([args]);+});+// ---------------------------------------------------------------------------// GIT_SSRF_FLAGS — pinned shape (snapshot test). If a future flag is added,// update the expected list here AND verify both cloneRepo + pullRepo pick itdiff --git a/test/helpers/fixture-diagnostics.ts b/test/helpers/fixture-diagnostics.tsnew file mode 100644index 0000000000..9df3044237--- /dev/null+++ b/test/helpers/fixture-diagnostics.ts@@ -0,0 +1,80 @@+import { redactConnectionInfo } from '../../src/core/audit/redact-connection-info.ts';++function redactFixtureText(text: string, secrets: readonly string[]): string {+ let safe = text;+ for (const secret of [...secrets].filter(Boolean).sort((a, b) => b.length - a.length)) {+ safe = safe.split(secret).join('[REDACTED]');+ }+ safe = safe+ .replace(/\bgbrain_(?:cs_|cl_)?[A-Za-z0-9_-]+/g, '[REDACTED:credential]')+ .replace(/\bBearer\s+[^\s"'<>]+/gi, 'Bearer [REDACTED]')+ .replace(/((?:["']?(?:access_token|refresh_token|client_secret|api_key|authorization)["']?)\s*[:=]\s*["']?)[^\s,"'&}]+/gi, '$1[REDACTED]')+ .replace(/\b(?:sk|sk-ant)-[A-Za-z0-9_-]+/g, '[REDACTED:provider-key]');+ return redactConnectionInfo(safe);+}++function bounded(text: string, limit = 2000): string {+ const suffix = '\n[truncated]';+ return text.length > limit ? `${text.slice(0, limit - suffix.length)}${suffix}` : text;+}++/** Structured codes only; free-form error messages stay in the redacted detail. */+function operationErrorCode(value: unknown): string | undefined {+ if (!value || typeof value !== 'object') return undefined;+ const payload = value as { error?: unknown; code?: unknown; message?: unknown };+ const nested = payload.error && typeof payload.error === 'object'+ ? (payload.error as { code?: unknown }).code : undefined;+ for (const candidate of [nested, payload.code, typeof payload.message === 'string' ? payload.error : undefined]) {+ if (typeof candidate === 'string' && /^[a-z][a-z0-9_.:-]{0,127}$/i.test(candidate)) return candidate;+ if (typeof candidate === 'number' && Number.isSafeInteger(candidate)) return String(candidate);+ }+ return undefined;+}++function textErrorCode(text: string): string | undefined {+ // CLI stdout may be one pretty-printed object or JSON lines after notices.+ try {+ const code = operationErrorCode(JSON.parse(text));+ if (code) return code;+ } catch { /* Try independently parseable lines below. */ }+ for (const line of text.split('\n')) {+ try {+ const code = operationErrorCode(JSON.parse(line));+ if (code) return code;+ } catch { /* Warning/progress text is not a structured error code. */ }+ }+ return undefined;+}++/** Bounded failure context. Never pass env maps or successful credential output.+ * Known fixture secrets supplement token/credential-field redaction.+ */+export function fixtureDiagnostic(operation: string, detail: string, secrets: readonly string[] = []): string {+ return bounded(redactFixtureText(`${operation}: ${detail}`, secrets));+}++export function cliDiagnostic(operation: string, result: { exitCode: number; stderr: string; stdout: string }, secrets: readonly string[] = []): string {+ // stdout can contain freshly minted credentials even on partial failure;+ // redact it using the same policy before it can become assertion output.+ const code = textErrorCode(result.stdout) ?? textErrorCode(result.stderr);+ const header = fixtureDiagnostic(operation, `exit=${result.exitCode}${code ? ` code=${code}` : ''}`, secrets);+ // Separate budgets preserve evidence from both streams. Redact BEFORE+ // truncation, so cutting through a credential cannot expose its prefix.+ const detail = [['stderr', result.stderr], ['stdout', result.stdout]]+ .filter(([, text]) => text)+ .map(([label, text]) => `${label}:\n${bounded(redactFixtureText(text, secrets), 850)}`)+ .join('\n');+ return bounded(`${header}\n${detail}`);+}++/** On success avoid serializing the tool result (which may carry user data). */+export function toolDiagnostic(operation: string, result: unknown, secrets: readonly string[] = []): string {+ const tool = result as { isError?: boolean; error?: unknown; content?: Array<{ type?: string; text?: string }> };+ if (!tool?.isError && !tool?.error) return operation;+ const texts = Array.isArray(tool.content)+ ? tool.content.filter(item => item.type === 'text').map(item => item.text ?? '') : [];+ const code = texts.map(textErrorCode).find(Boolean) ?? operationErrorCode(tool);+ const detail = texts.join('\n')+ || (typeof tool.error === 'string' ? tool.error : JSON.stringify(tool.error)) || 'tool error';+ return fixtureDiagnostic(operation, `${code ? `code=${code}\n` : ''}${detail}`, secrets);+}diff --git a/test/helpers/operator-env-preload.ts b/test/helpers/operator-env-preload.tsindex f3ad2f5949..5228e69fa1 100644--- a/test/helpers/operator-env-preload.ts+++ b/test/helpers/operator-env-preload.ts@@ -43,6 +43,8 @@ const KEEP_EXACT = new Set(['GBRAIN_DATABASE_URL', // e2e DB target; database-url-guard-preload (registered first) already vetoed un-opted runs'GBRAIN_MODEL_DISCOVERY', // operator override provider-keys-preload deliberately respects'GBRAIN_PGLITE_SNAPSHOT', // schema-snapshot fast path exported by every unit runner (scripts/lib/test-env.sh)+ 'GBRAIN_PGBOUNCER_URL', // explicit pooled test target supplied by ci-local+ 'GBRAIN_PGBOUNCER_DIRECT_URL', // admin connection used to create the isolated pooler test DB'GBRAIN_COMPILED_BIN', // heavy-lane compile-once binary (agent-harness.ts ensureCompiledGbrain)'GBRAIN_AUDIT_DIR', // audit-dir-preload honors a wrapper pre-set (inspect audit output after a run)'GBRAIN_SYNC_FAILURES_DIR', // same wrapper pre-set contract in sync-failures-preloaddiff --git a/test/helpers/provider-env.ts b/test/helpers/provider-env.tsnew file mode 100644index 0000000000..f9f170531c--- /dev/null+++ b/test/helpers/provider-env.ts@@ -0,0 +1,42 @@+/** Explicit provider state shared by the unit preload and keyless E2E children.+ * Keep this module pure: importing it must not change the calling test's env.+ * test/provider-fixture-env.test.ts checks the list against the recipe registry.+ */+export const PROVIDER_ENV_KEYS = [+ 'ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL',+ 'AZURE_OPENAI_API_KEY', 'AZURE_OPENAI_API_VERSION', 'AZURE_OPENAI_DEPLOYMENT',+ 'AZURE_OPENAI_ENDPOINT', 'AZURE_OPENAI_USE_ENTRA',+ 'DASHSCOPE_API_KEY', 'DEEPSEEK_API_KEY', 'GEMINI_API_KEY',+ 'GOOGLE_GENERATIVE_AI_API_KEY', 'GROQ_API_KEY',+ 'LITELLM_API_KEY', 'LITELLM_BASE_URL',+ 'LLAMA_SERVER_API_KEY', 'LLAMA_SERVER_BASE_URL',+ 'LLAMA_SERVER_RERANKER_API_KEY', 'LLAMA_SERVER_RERANKER_BASE_URL',+ 'LMSTUDIO_API_KEY', 'LMSTUDIO_BASE_URL', 'MINIMAX_API_KEY', 'MINIMAX_GROUP_ID',+ 'MISTRAL_API_KEY', 'MOONSHOT_API_KEY', 'NAN_API_KEY', 'NVIDIA_API_KEY',+ 'OLLAMA_API_KEY', 'OLLAMA_BASE_URL',+ 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_ORG_ID', 'OPENAI_PROJECT',+ 'OPENROUTER_API_KEY', 'OPENROUTER_BASE_URL', 'OPENROUTER_REFERER', 'OPENROUTER_TITLE',+ 'PERPLEXITY_API_KEY', 'TOGETHER_API_KEY', 'VOYAGE_API_KEY',+ 'ZEROENTROPY_API_KEY', 'ZHIPUAI_API_KEY',+] as const;++type Env = Readonly<Record<string, string | undefined>>;++/** Clones ambient env, removes provider state, then applies explicit overrides.+ * Database policy belongs to the fixture: PGLite removes URLs; Postgres keeps+ * its test URL. Overrides can deliberately inject a provider for a specific test.+ */+export function keylessBrainEnv(parent: Env, home: string, overrides: Env = {}): Record<string, string> {+ const env: Record<string, string> = {};+ for (const [key, value] of Object.entries(parent)) {+ if (value !== undefined) env[key] = value;+ }+ for (const key of PROVIDER_ENV_KEYS) delete env[key];+ env.HOME = home;+ env.GBRAIN_HOME = home;+ for (const [key, value] of Object.entries(overrides)) {+ if (value === undefined) delete env[key];+ else env[key] = value;+ }+ return env;+}diff --git a/test/helpers/provider-keys-preload.ts b/test/helpers/provider-keys-preload.tsindex 88145f0697..00d5fcbb14 100644--- a/test/helpers/provider-keys-preload.ts+++ b/test/helpers/provider-keys-preload.ts@@ -23,27 +23,10 @@* today's behavior — same pattern as GBRAIN_TEST_ALLOW_DATABASE_URL.*/-// Every provider credential/endpoint the canonical fold recognizes-// (src/core/ai/provider-env.ts mergedProviderEnv) — an ambient GEMINI,-// VOYAGE, ZEROENTROPY, or Azure endpoint flips capability/embedding-// assertions the same way a chat key flips model routing. Keep this list in-// sync with mergedProviderEnv's output names.-const STRIPPED_KEYS = [- 'ANTHROPIC_API_KEY',- 'OPENAI_API_KEY',- 'GEMINI_API_KEY',- 'GOOGLE_GENERATIVE_AI_API_KEY',- 'VOYAGE_API_KEY',- 'OPENROUTER_API_KEY',- 'ZEROENTROPY_API_KEY',- 'DASHSCOPE_API_KEY',- 'AZURE_OPENAI_ENDPOINT',- 'AZURE_OPENAI_DEPLOYMENT',- 'AZURE_OPENAI_USE_ENTRA',-] as const;+import { PROVIDER_ENV_KEYS } from './provider-env.ts';if (process.env.GBRAIN_TEST_KEEP_PROVIDER_KEYS !== '1') {- for (const key of STRIPPED_KEYS) {+ for (const key of PROVIDER_ENV_KEYS) {if (process.env[key] !== undefined) {delete process.env[key];}diff --git a/test/hybrid-adaptive-dedup-cache-plane.serial.test.ts b/test/hybrid-adaptive-dedup-cache-plane.serial.test.tsindex c620bef820..0345709a20 100644--- a/test/hybrid-adaptive-dedup-cache-plane.serial.test.ts+++ b/test/hybrid-adaptive-dedup-cache-plane.serial.test.ts@@ -1,20 +1,10 @@/**- * 2026-08 fix wave (E5b) — cache-plane behavior flips in hybridSearchCached.- *- * Two changes moved in opposite directions and neither had an integration pin- * (only the knobs-hash key-divergence was unit-pinned in search-mode.test.ts):- * 1. adaptive-on calls now CACHE — the gate params + resolved intent class- * fold into knobsHash v=27, so the old blanket skip is gone. A regression- * that quietly re-adds the skip erases the wave's cost win; a regression- * that drops the hash fold is cross-config contamination.- * 2. per-call dedupOpts now SKIPS the cache — it is result-affecting- * (maxPerPage/cosine overrides) but not part of the hash, so a- * maxPerPage:1 caller must never be served a stored default-cap row- * (same contamination class as #3985 types and #3442 dates).- *- * Serial: mock.module + gateway/global-env mutation (harness shape copied- * from test/hybrid-types-cache-skip.serial.test.ts).+ * Production-wrapper regression coverage with semantic response caching disabled.+ * Fresh reads must retain filtering, metadata and telemetry guarantees; legacy+ * cache implementation behavior is covered by the direct cache-class suites.+ * Serial because embedding and gateway configuration are process-global.*/+import { afterAll, beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, test } from 'bun:test';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -90,58 +80,51 @@ beforeEach(async () => {await engine.executeRaw('DELETE FROM query_cache');});-describe('E5b — adaptive-on calls now cache (skip removed, hash-folded instead)', () => {- test('adaptive-on miss STORES a row; the identical adaptive-on lookup HITS it', async () => {- let missMeta: HybridSearchMeta | undefined;+describe('adaptive return remains fresh during cache containment', () => {+ test('adaptive-on calls return stable results without writing cache rows', async () => {+ let firstMeta: HybridSearchMeta | undefined;const first = await hybridSearchCached(engine, 'builder', {limit: 10,adaptiveReturn: true,- onMeta: (m) => { missMeta = m; },+ onMeta: (m) => { firstMeta = m; },});- // Pre-wave this was 'disabled' (blanket adaptive skip). Now it runs the- // cache plane: miss + store.- expect(missMeta?.cache?.status).toBe('miss');+ expect(firstMeta?.cache?.status).toBe('disabled');expect(first.length).toBeGreaterThan(0);await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);- let hitMeta: HybridSearchMeta | undefined;+ let repeatMeta: HybridSearchMeta | undefined;const second = await hybridSearchCached(engine, 'builder', {limit: 10,adaptiveReturn: true,- onMeta: (m) => { hitMeta = m; },+ onMeta: (m) => { repeatMeta = m; },});- expect(hitMeta?.cache?.status).toBe('hit');+ expect(repeatMeta?.cache?.status).toBe('disabled');expect(second.map((r) => r.slug).sort()).toEqual(first.map((r) => r.slug).sort());});- test('an adaptive-on row is NEVER served to an adaptive-off lookup (v=27 key divergence, end to end)', async () => {+ test('switching adaptive return off leaves the cache empty', async () => {await hybridSearchCached(engine, 'builder', { limit: 10, adaptiveReturn: true });await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);let offMeta: HybridSearchMeta | undefined;await hybridSearchCached(engine, 'builder', {limit: 10,onMeta: (m) => { offMeta = m; },});- // Same query, same embedding (cosine 1.0) — only knobsHash separates- // them. A 'hit' here means the ar=/ari= fold regressed out of the key.- expect(offMeta?.cache?.status).toBe('miss');+ expect(offMeta?.cache?.status).toBe('disabled');await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(2);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);});});-describe('E5b adjunct — per-call dedupOpts skips the cache (not hash-folded)', () => {- test('a stored default-cap row is never served to a dedupOpts read (and the dedupOpts run stores nothing)', async () => {- // 1. Plain miss-run stores a row.+describe('per-call dedup remains fresh during cache containment', () => {+ test('default and dedupOpts reads both leave the cache empty', async () => {await hybridSearchCached(engine, 'builder', { limit: 10 });await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);- // 2. Same query WITH per-call dedupOpts: identical embedding + knobs- // would have HIT the stored row — must bypass instead.let dedupMeta: HybridSearchMeta | undefined;await hybridSearchCached(engine, 'builder', {limit: 10,@@ -150,10 +133,7 @@ describe('E5b adjunct — per-call dedupOpts skips the cache (not hash-folded)',});expect(dedupMeta?.cache?.status).toBe('disabled');- // 3. The dedupOpts run must not have stored anything either — a- // maxPerPage:1 result set served to a default-cap lookup is the- // reverse contamination.await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);});});diff --git a/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts b/test/hybrid-cache-hit-limit-honors-mode.serial.test.tsindex 1742382724..17e62cad96 100644--- a/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts+++ b/test/hybrid-cache-hit-limit-honors-mode.serial.test.ts@@ -1,45 +1,7 @@/**- * #4356 Site 2 — the semantic-cache-hit slice used a hard- * `opts?.limit || 20`, independent of the mode-resolution logic the cache-- * MISS path uses (`opts?.limit || resolvedMode.searchLimit`, bare- * hybridSearch). In `balanced` mode (searchLimit: 25) a miss with `limit`- * omitted could return and cache up to 25 results, but the next identical-- * shape call served from cache silently sliced that cached row down to 20 —- * inconsistent between the miss and hit paths for the same call shape.- * (Scope note: this fix closes that gap for `offset: 0` — the common case,- * and the shape the first three tests below drive. A SEPARATE bug — offset- * used to be applied twice on a hit, once already baked into what the miss- * path stored and once again by the hit branch — used to break hit/miss- * parity for a nonzero `offset` (filed as #4358); the positive-offset half- * of that bug is now closed by upstream's #4368 wave (this branch is- * rebased onto it) by skipping the cache entirely for any positive offset,- * so there's no cached row left to double-slice for the case the last test- * near the end of this file drives. A separate PR, #4414 (this account's- * own, still open as of this commit), widens the same skip condition to- * also cover negative offsets — not exercised by this file. Both fixes are- * orthogonal to the `|| 20` vs `|| resolvedMode.searchLimit` substitution- * this PR makes and neither is part of this PR's diff.)- *- * Companion to #4356 Site 1 (see- * test/query-op-limit-mode-4356.serial.test.ts, the `query` op's own- * text-path `limit` translation). Fixing both sites in the same PR is the- * point: shipping only the miss-path fix would make this miss/hit- * inconsistency newly OBSERVABLE (previously both were wrong at a flat 20,- * so they agreed) without resolving it — a maintainer-lens review rejected- * exactly that partial shape when it shipped split across two closed PRs- * (#4355, #4357).- *- * Drives a real store→hit roundtrip (mocked `embed`/`embedQuery` for a- * deterministic vector, real PGLite SemanticQueryCache — same pattern as- * test/hybrid-cached-hit-budget-meta.serial.test.ts) with 60 keyword-- * findable pages spread across 6 page types (dedup's type-diversity layer- * caps any one type at 60% of the result set, so a single type would- * silently shrink the pool below 50 regardless of this fix). `autocut` and- * `relationalRetrieval` are forced off per-call so the result count is- * driven only by the limit slice under test, not by an unrelated cliff cut- * or graph arm.- *- * Serial: mock.module (isolation guard R2).+ * Repeated fresh-search behavior while semantic response caching is disabled.+ * Keeps the mode-limit, pagination and budget guarantees independent of cache+ * availability. Serial because embedding/gateway mocks are process-global.*/import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';@@ -82,9 +44,6 @@ const PAGE_COUNT = 60; // > tokenmax searchLimit (50), so every mode's cap — nconst KEYWORD = 'gbrain4356widget';beforeAll(async () => {- // Hermetic config home so the developer's real ~/.gbrain/config.json- // can't leak an embedding_model that flips the cache consult to- // 'disabled' via isCacheSafe.tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-cache-hit-limit-'));process.env.GBRAIN_HOME = tmpHome;@@ -118,181 +77,118 @@ afterAll(async () => {try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }});-describe('cache HIT — limit honors the resolved mode (#4356)', () => {- test('balanced mode, limit omitted: hit returns the same count as the miss (searchLimit=25), not clipped to 20', async () => {- let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const missResults = await hybridSearchCached(engine, KEYWORD, {+describe('fresh repeated reads honor the resolved mode', () => {+ test('balanced mode, limit omitted: repeated reads return the same count (searchLimit=25), not clipped to 20', async () => {+ let firstMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const firstResults = await hybridSearchCached(engine, KEYWORD, {autocut: false,relationalRetrieval: false,- onMeta: (m) => { missMeta = m; },+ onMeta: (m) => { firstMeta = m; },});- expect(missMeta?.cache?.status).toBe('miss');- // Sanity: the pool is deep enough that the mode's searchLimit (25),- // not the pool size, is what caps the miss — otherwise this test- // can't distinguish `|| 20` from `|| resolvedMode.searchLimit`.- expect(missResults.length).toBe(25);+ expect(firstMeta?.cache?.status).toBe('disabled');+ expect(firstResults.length).toBe(25);await awaitPendingSearchCacheWrites();- let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, KEYWORD, {+ let repeatMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const repeatResults = await hybridSearchCached(engine, KEYWORD, {autocut: false,relationalRetrieval: false,- onMeta: (m) => { hitMeta = m; },+ onMeta: (m) => { repeatMeta = m; },});- expect(hitMeta?.cache?.status).toBe('hit');- // Pre-fix: this was clipped to 20 regardless of the miss's count.- expect(hitResults.length).toBe(missResults.length);- expect(hitResults.length).toBe(25);+ expect(repeatMeta?.cache?.status).toBe('disabled');+ expect(repeatResults.length).toBe(firstResults.length);+ expect(repeatResults.length).toBe(25);});- test('conservative mode, limit omitted: hit still matches the miss (searchLimit=10, both below the old flat 20)', async () => {- let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const missResults = await hybridSearchCached(engine, KEYWORD, {+ test('conservative mode, limit omitted: repeated reads match (searchLimit=10, both below the old flat 20)', async () => {+ let firstMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const firstResults = await hybridSearchCached(engine, KEYWORD, {mode: 'conservative',autocut: false,relationalRetrieval: false,- onMeta: (m) => { missMeta = m; },+ onMeta: (m) => { firstMeta = m; },});- expect(missMeta?.cache?.status).toBe('miss');- expect(missResults.length).toBe(10);+ expect(firstMeta?.cache?.status).toBe('disabled');+ expect(firstResults.length).toBe(10);await awaitPendingSearchCacheWrites();- let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, KEYWORD, {+ let repeatMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const repeatResults = await hybridSearchCached(engine, KEYWORD, {mode: 'conservative',autocut: false,relationalRetrieval: false,- onMeta: (m) => { hitMeta = m; },+ onMeta: (m) => { repeatMeta = m; },});- expect(hitMeta?.cache?.status).toBe('hit');- expect(hitResults.length).toBe(missResults.length);+ expect(repeatMeta?.cache?.status).toBe('disabled');+ expect(repeatResults.length).toBe(firstResults.length);});- test('tokenmax mode, limit omitted: miss and hit both return searchLimit=50 (above the old flat 20)', async () => {- let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const missResults = await hybridSearchCached(engine, KEYWORD, {+ test('tokenmax mode, limit omitted: repeated reads return searchLimit=50 (above the old flat 20)', async () => {+ let firstMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const firstResults = await hybridSearchCached(engine, KEYWORD, {mode: 'tokenmax',autocut: false,relationalRetrieval: false,- onMeta: (m) => { missMeta = m; },+ onMeta: (m) => { firstMeta = m; },});- expect(missMeta?.cache?.status).toBe('miss');- // Sanity: the 60-page pool keeps the mode's searchLimit (50), not the- // pool size, as the cap — same reasoning as the balanced test above.- expect(missResults.length).toBe(50);+ expect(firstMeta?.cache?.status).toBe('disabled');+ expect(firstResults.length).toBe(50);await awaitPendingSearchCacheWrites();- let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, KEYWORD, {+ let repeatMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const repeatResults = await hybridSearchCached(engine, KEYWORD, {mode: 'tokenmax',autocut: false,relationalRetrieval: false,- onMeta: (m) => { hitMeta = m; },+ onMeta: (m) => { repeatMeta = m; },});- expect(hitMeta?.cache?.status).toBe('hit');- expect(hitResults.length).toBe(missResults.length);- expect(hitResults.length).toBe(50);+ expect(repeatMeta?.cache?.status).toBe('disabled');+ expect(repeatResults.length).toBe(firstResults.length);+ expect(repeatResults.length).toBe(50);});- test('explicit numeric limit round-trips through a hit (limit is folded into knobsHash, so a hit only ever serves a lookup with the SAME resolved limit as the write — this pins that path still behaves, not just the mode-default path above)', async () => {+ test('explicit numeric limits survive repeated fresh reads', async () => {await hybridSearchCached(engine, KEYWORD, { limit: 3, autocut: false, relationalRetrieval: false });await awaitPendingSearchCacheWrites();- let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, KEYWORD, {+ let repeatMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const repeatResults = await hybridSearchCached(engine, KEYWORD, {limit: 3,autocut: false,relationalRetrieval: false,- onMeta: (m) => { hitMeta = m; },+ onMeta: (m) => { repeatMeta = m; },});- expect(hitMeta?.cache?.status).toBe('hit');- expect(hitResults.length).toBe(3);+ expect(repeatMeta?.cache?.status).toBe('disabled');+ expect(repeatResults.length).toBe(3);});- // FIXED for POSITIVE offset (was "KNOWN LIMITATION" — the positive-offset- // half of #4358 landed via upstream's #4368 wave, which this branch is- // rebased onto; the SEPARATE negative-offset half is #4414, this- // account's own PR, still open/unmerged as of this commit — see below):- // a nonzero offset used to break hit/miss count parity, because the miss- // path stores the ALREADY offset-sliced array (`hybridSearch`'s own- // `returnPool.slice(offset, offset + limit)`) and the cache-hit branch- // re-applied `offset` a SECOND time on top of that already-sliced array.- // For offset=0 this was a no-op (slicing from 0 twice is idempotent),- // which is why every test above — and the miss/hit consistency this PR- // actually fixes — held even pre-#4358. For a nonzero offset it was NOT- // idempotent: e.g. a miss with `limit: 9, offset: 2` stored 9 rows- // representing pool positions [2, 11); a hit then re-sliced THAT 9-row- // array at [2, 11) again, yielding rows [2, 9) of a 9-element array — 7- // rows, not 9.- //- // The fix in THIS branch's `hybrid.ts` is `pagedRequest = (opts?.offset- // ?? 0) > 0` — positive-offset only. It skips the cache entirely (lookup- // AND store) for any positive offset, so the double-slice path is- // unreachable for this test's `offset: 2` case: a paginated request- // returns freshly-computed, correctly-sliced results with- // `cache.status: 'disabled'`, never a re-sliced cached page. (#4414 later- // widens this same condition to `!== 0` so negative offsets get the same- // protection — Array.prototype.slice's negative-index semantics mean a- // negative offset re-slices a stored page just as badly as a positive- // one, an independent gap `> 0` alone doesn't cover. That's out of scope- // for THIS test, which only ever calls with a positive offset.)- //- // (`limit: 9` here — rather than the mode default this file's other tests- // rely on — is deliberate, not incidental: `offset` still isn't part of- // `knobsHash` (mode.ts's `knobsHash()` has no `offset=` component), so a- // lookup with a NEW offset but the SAME resolved limit as an earlier test- // in this file could otherwise collide with an already-written row if the- // cache were consulted. A limit value unique to this test sidesteps that- // collision — though it's moot for THIS assertion, since paginated- // requests bypass the cache outright now; kept for robustness against- // future changes to the skip condition.)- test('positive offset never hits the cache — hit/miss count parity holds (was #4358, fixed here by #4368)', async () => {- let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const missResults = await hybridSearchCached(engine, KEYWORD, {+ test('positive offsets preserve result counts across repeated fresh reads', async () => {+ let firstMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const firstResults = await hybridSearchCached(engine, KEYWORD, {limit: 9,offset: 2,autocut: false,relationalRetrieval: false,- onMeta: (m) => { missMeta = m; },+ onMeta: (m) => { firstMeta = m; },});- expect(missMeta?.cache?.status).toBe('disabled');- expect(missResults.length).toBe(9);+ expect(firstMeta?.cache?.status).toBe('disabled');+ expect(firstResults.length).toBe(9);await awaitPendingSearchCacheWrites();- let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, KEYWORD, {+ let repeatMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const repeatResults = await hybridSearchCached(engine, KEYWORD, {limit: 9,offset: 2,autocut: false,relationalRetrieval: false,- onMeta: (m) => { hitMeta = m; },+ onMeta: (m) => { repeatMeta = m; },});- // Still 'disabled', not 'hit' — a paginated request skips the cache on- // EVERY call (lookup AND store), so there's never a stored row for a- // nonzero offset to serve back. If this assertion ever changes to- // 'hit', the skip-cache design changed — re-verify the double-slice- // fix still holds under whatever replaced it, rather than just- // updating the expected string.- expect(hitMeta?.cache?.status).toBe('disabled');- expect(hitResults.length).toBe(9);+ expect(repeatMeta?.cache?.status).toBe('disabled');+ expect(repeatResults.length).toBe(9);});- // NOTE on `limit: 0` (not a test — documenting why one isn't here): a- // `limit: 0` call always returns zero rows (resolveSearchMode's- // perCall.searchLimit pick treats a forwarded 0 as a set value, so- // `0 || resolvedMode.searchLimit` resolves to 0 — verified directly- // against mode.ts), and the miss-path writeback above explicitly skips- // caching empty result sets ("skip when search returned empty so we- // don't cache zero-result queries forever"). A `limit: 0` query can- // therefore never reach a cache HIT via the public API: nothing is ever- // written for it to hit against, and even if a prior non-zero-limit- // write existed, `lim=<n>` is folded into `knobsHash` (mode.ts), so a- // `limit: 0` lookup's hash never matches a `limit: 25` write's row. The- // line this PR changes (`resolvedForCache.searchLimit` instead of a flat- // `20`) is exercised by the non-zero cases above; a 0-specific hit- // scenario is structurally unreachable, not merely untested.});diff --git a/test/hybrid-cache-scope-poison.serial.test.ts b/test/hybrid-cache-scope-poison.serial.test.tsindex 98ce266220..87b7d9e883 100644--- a/test/hybrid-cache-scope-poison.serial.test.ts+++ b/test/hybrid-cache-scope-poison.serial.test.ts@@ -1,26 +1,12 @@/**- * #3871 — query-cache scope isolation (poisoned-row regression).- *- * Pre-fix, an UNSCOPED search (neither sourceId nor sourceIds) keyed its- * cache row to 'default' — the same key a scalar `sourceId: 'default'`- * read uses. An unscoped search reads ALL sources, so its stored result- * set can carry rows from every source; serving that row to a scoped read- * is a cross-source leak. Two layers close it:- *- * 1. Key split: unscoped now keys to '__unscoped__', so unscoped writes- * and default-source-scoped reads can never share a row again.- * 2. Hit-path re-filter: the hit path re-filters stored rows by the- * CALLER's scope before offset/limit paging, so even a legacy row- * poisoned under the pre-fix key scheme yields no foreign rows.- *- * This file drives real store→hit roundtrips through hybridSearchCached- * (mocked embedQuery for a deterministic vector, real PGLite- * SemanticQueryCache) and pins both layers.- *- * Serial: mock.module + gateway/global-env mutation (isolation guard R2).+ * Corrective-release containment: stored semantic responses are never consulted+ * or written by the production wrapper, even with a provider, enabled config,+ * caller opt-in and an existing cache row containing private data.+ * Direct SemanticQueryCache storage/lookup tests remain independently active.+ * Serial because embedding and gateway configuration are process-global.*/-import { afterAll, beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, test } from 'bun:test';+import { afterAll, beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, spyOn, test } from 'bun:test';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -51,6 +37,8 @@ const { hybridSearchCached, awaitPendingSearchCacheWrites } =await import('../src/core/search/hybrid.ts');const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+const { importFromContent } = await import('../src/core/import-file.ts');+const { SemanticQueryCache, semanticResultCacheAvailable } = await import('../src/core/search/query-cache.ts');// Cold-start PGLite schema setup (beforeAll) can exceed bun's 5s default// hook budget on a fresh checkout; same bump pattern as@@ -81,19 +69,21 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();+ await engine.setConfig('search.cache.enabled', 'true');- // Keyword-findable pages in the DEFAULT source. putPage never chunks —- // searchKeyword joins content_chunks, so chunks are explicit.+ // Real imports create keyword-findable pages with completed indexes for+ // every source/privacy scope exercised below.const fixtures: Array<[string, string, string]> = [['alice-foo', 'Alice Foo', 'person'],['bob-bar', 'Bob Bar', 'company'],];for (const [slug, title, type] of fixtures) {const truth = `${title} is a builder.`;- await engine.putPage(slug, { type, title, compiled_truth: truth });- await engine.upsertChunks(slug, [- { chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },- ]);+ const imported = await importFromContent(+ engine, slug, `---\ntitle: ${title}\ntype: ${type}\n---\n\n${truth}`,+ { noEmbed: true, sourceId: 'default' },+ );+ expect(imported.status).toBe('imported');}});@@ -110,207 +100,94 @@ beforeEach(async () => {await engine.executeRaw('DELETE FROM query_cache');});-describe('cache scope-key split (#3871 layer 1)', () => {- test('an unscoped write is keyed __unscoped__ and never serves a scoped read', async () => {- // Unscoped search (reads all sources) → miss → cache write.- let unscopedMeta: HybridSearchMeta | undefined;- const unscopedResults = await hybridSearchCached(engine, 'builder', {- limit: 10,- onMeta: (m) => { unscopedMeta = m; },- });- expect(unscopedResults.length).toBeGreaterThan(0);- expect(unscopedMeta?.cache?.status).toBe('miss');- await awaitPendingSearchCacheWrites();-- // The stored row keys to the sentinel, NOT to 'default'.- const rows = await engine.executeRaw<{ source_id: string }>(- 'SELECT source_id FROM query_cache',- );- expect(rows.length).toBe(1);- expect(rows[0].source_id).toBe('__unscoped__');-- // A scoped `sourceId: 'default'` read with the identical embedding +- // knobs must MISS — pre-fix both keyed 'default' and this was a HIT- // serving the all-sources row.- let scopedMeta: HybridSearchMeta | undefined;- await hybridSearchCached(engine, 'builder', {- limit: 10,- sourceId: 'default',- onMeta: (m) => { scopedMeta = m; },- });- expect(scopedMeta?.cache?.status).toBe('miss');+describe('semantic response containment', () => {+ test('the effective availability gate is disabled', () => {+ expect(semanticResultCacheAvailable()).toBe(false);});- test('a later unscoped read still hits its own row', async () => {- await hybridSearchCached(engine, 'builder', { limit: 10 });- await awaitPendingSearchCacheWrites();-- let hitMeta: HybridSearchMeta | undefined;- const results = await hybridSearchCached(engine, 'builder', {- limit: 10,- onMeta: (m) => { hitMeta = m; },- });- expect(hitMeta?.cache?.status).toBe('hit');- expect(results.length).toBeGreaterThan(0);+ test('neither configuration nor per-call cache preferences can override containment', async () => {+ const lookup = spyOn(SemanticQueryCache.prototype, 'lookup');+ const store = spyOn(SemanticQueryCache.prototype, 'store');+ try {+ for (const enabled of ['false', 'true']) {+ await engine.setConfig('search.cache.enabled', enabled);+ for (const useCache of [undefined, false, true]) {+ let meta: HybridSearchMeta | undefined;+ const results = await hybridSearchCached(engine, 'builder', { useCache, onMeta: value => { meta = value; } });+ expect(results.length).toBeGreaterThan(0);+ expect(meta?.cache?.status).toBe('disabled');+ }+ }+ await awaitPendingSearchCacheWrites();+ expect(lookup).not.toHaveBeenCalled();+ expect(store).not.toHaveBeenCalled();+ expect(await engine.executeRaw('SELECT id FROM query_cache')).toEqual([]);+ } finally {+ lookup.mockRestore();+ store.mockRestore();+ }});-});-describe('poisoned default-key row (#3871 layer 2 — hit-path re-filter)', () => {- test('a poisoned row under the default key yields no foreign rows to a scoped read', async () => {- // 1. Scoped miss-run writes a legitimate row under scope key 'default'.- let missMeta: HybridSearchMeta | undefined;- const missResults = await hybridSearchCached(engine, 'builder', {- limit: 10,- sourceId: 'default',- onMeta: (m) => { missMeta = m; },+ const scopes = [+ { label: 'unscoped', opts: {} },+ { label: 'scalar source', opts: { sourceId: 'default' } },+ { label: 'federated sources', opts: { sourceIds: ['default'] } },+ { label: 'private-excluding source', opts: { sourceId: 'default', excludePrivate: true } },+ ];+ for (const { label, opts } of scopes) {+ test(`${label}: enabled config and caller opt-in cannot read or rewrite legacy cache data`, async () => {+ const fresh = await hybridSearchCached(engine, 'builder', { ...opts, useCache: true, limit: 10 });+ expect(fresh.length).toBeGreaterThan(0);+ const privateRow: SearchResult = { ...fresh[0], title: 'CACHED_PRIVATE_TITLE', chunk_text: 'CACHED_PRIVATE_TEXT' };+ const cache = new SemanticQueryCache(engine, { enabled: true });+ await cache.store('builder', fixedEmbedding(), [privateRow], {+ vector_enabled: true, detail_resolved: null, expansion_applied: false, retrieved_count: 1,+ legacy_private_detail: 'CACHED_PRIVATE_METADATA',+ } as HybridSearchMeta, { sourceId: 'default', knobsHash: 'legacy-policy' });+ // Positive control: this is a readable cache row, not a vacuous empty cache.+ const legacy = await cache.lookup(fixedEmbedding(), { sourceId: 'default', knobsHash: 'legacy-policy', queryText: 'builder' });+ expect(legacy.hit).toBe(true);+ expect(legacy.results?.[0].chunk_text).toBe('CACHED_PRIVATE_TEXT');+ const before = await engine.executeRaw('SELECT id, results, meta, hit_count, created_at FROM query_cache');+ expect(before).toHaveLength(1);++ const lookup = spyOn(SemanticQueryCache.prototype, 'lookup');+ const store = spyOn(SemanticQueryCache.prototype, 'store');+ try {+ let meta: HybridSearchMeta | undefined;+ const results = await hybridSearchCached(engine, 'builder', {+ ...opts, useCache: true, limit: 10, onMeta: value => { meta = value; },+ });+ await awaitPendingSearchCacheWrites();+ expect(results.length).toBeGreaterThan(0);+ expect(results.map(row => row.slug).sort()).toEqual(fresh.map(row => row.slug).sort());+ expect(JSON.stringify({ results, meta })).not.toContain('CACHED_PRIVATE');+ expect(meta?.cache?.status).toBe('disabled');+ expect(lookup).not.toHaveBeenCalled();+ expect(store).not.toHaveBeenCalled();+ expect(await engine.executeRaw('SELECT id, results, meta, hit_count, created_at FROM query_cache')).toEqual(before);+ } finally {+ lookup.mockRestore();+ store.mockRestore();+ }});- expect(missMeta?.cache?.status).toBe('miss');- expect(missResults.length).toBeGreaterThan(0);- await awaitPendingSearchCacheWrites();+ }- // 2. Poison the stored row the way a pre-fix unscoped write would have:- // splice foreign-source rows into its results payload. (Pre-fix,- // unscoped all-sources writes landed on this exact key.)- const stored = await engine.executeRaw<{ id: string; results: unknown }>(- `SELECT id, results FROM query_cache WHERE source_id = 'default'`,- );- expect(stored.length).toBe(1);- const storedResults: SearchResult[] =- typeof stored[0].results === 'string'- ? JSON.parse(stored[0].results)- : (stored[0].results as SearchResult[]);- const foreignRow: SearchResult = {- slug: 'secret/leak',- page_id: 9999,- title: 'Team Secret Leak',- type: 'note',- chunk_text: 'a secret builder note from another source',- chunk_source: 'compiled_truth',- chunk_id: 9999,- chunk_index: 0,- score: 99, // ranks first — pre-fix it would lead the served page- stale: false,- source_id: 'team-secret',+ test('repeated paginated reads stay fresh and never write a sliced cache entry', async () => {+ const search = async (offset: number) => {+ let meta: HybridSearchMeta | undefined;+ const rows = await hybridSearchCached(engine, 'builder', {+ sourceId: 'default', offset, limit: 1, useCache: true, onMeta: value => { meta = value; },+ });+ expect(meta?.cache?.status).toBe('disabled');+ expect(rows).toHaveLength(1);+ return rows;};- const poisoned = [foreignRow, ...storedResults];- // $N::text::jsonb — binds as text, the cast parses it (jsonb rule).- await engine.executeRaw(- `UPDATE query_cache SET results = $1::text::jsonb WHERE id = $2`,- [JSON.stringify(poisoned), stored[0].id],- );-- // 3. Scoped read again: identical embedding + knobs + scope key → HIT- // (this exercises the hit path, not a fresh search) — but the- // re-filter must drop every foreign row before paging.- let hitMeta: HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, 'builder', {- limit: 10,- sourceId: 'default',- onMeta: (m) => { hitMeta = m; },- });- expect(hitMeta?.cache?.status).toBe('hit');- expect(hitResults.length).toBeGreaterThan(0);- expect(hitResults.some((r) => r.source_id === 'team-secret')).toBe(false);- expect(hitResults.some((r) => r.slug === 'secret/leak')).toBe(false);- // The legitimate default-source rows still come through.- const slugs = hitResults.map((r) => r.slug).sort();- expect(slugs).toEqual(missResults.map((r) => r.slug).sort());- });-- test('the re-filter runs BEFORE offset/limit paging (foreign rows cannot displace page 1)', async () => {- // Seed a legitimate scoped row, then poison it with MANY leading- // foreign rows. If the filter ran after the slice, limit=1 would page- // a foreign row (or an empty page); filtering first must return the- // top legitimate row.- await hybridSearchCached(engine, 'builder', { limit: 1, sourceId: 'default' });+ const first = await search(0);+ const second = await search(1);+ expect(first[0].slug).not.toBe(second[0].slug);+ expect((await search(0))[0].slug).toBe(first[0].slug);await awaitPendingSearchCacheWrites();-- const stored = await engine.executeRaw<{ id: string; results: unknown }>(- `SELECT id, results FROM query_cache WHERE source_id = 'default'`,- );- expect(stored.length).toBe(1);- const storedResults: SearchResult[] =- typeof stored[0].results === 'string'- ? JSON.parse(stored[0].results)- : (stored[0].results as SearchResult[]);- const foreign: SearchResult[] = Array.from({ length: 5 }, (_, i) => ({- slug: `secret/leak-${i}`,- page_id: 9000 + i,- title: `Leak ${i}`,- type: 'note',- chunk_text: `secret ${i}`,- chunk_source: 'compiled_truth',- chunk_id: 9000 + i,- chunk_index: 0,- score: 99 - i,- stale: false,- source_id: 'team-secret',- }));- await engine.executeRaw(- `UPDATE query_cache SET results = $1::text::jsonb WHERE id = $2`,- [JSON.stringify([...foreign, ...storedResults]), stored[0].id],- );-- let hitMeta: HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, 'builder', {- limit: 1,- sourceId: 'default',- onMeta: (m) => { hitMeta = m; },- });- expect(hitMeta?.cache?.status).toBe('hit');- expect(hitResults.length).toBe(1);- expect(hitResults[0].source_id ?? 'default').toBe('default');- expect(hitResults[0].slug.startsWith('secret/')).toBe(false);- });-});--describe('offset pages bypass the cache (wave-D review)', () => {- test('a page-2 read after a page-1 write reaches the engine — no poisoned empty page', async () => {- // Page 1 (offset 0, limit 1): miss → the SLICED page is what gets stored.- let p1Meta: HybridSearchMeta | undefined;- const page1 = await hybridSearchCached(engine, 'builder', {- limit: 1,- onMeta: (m) => { p1Meta = m; },- });- expect(p1Meta?.cache?.status).toBe('miss');- expect(page1.length).toBe(1);- await awaitPendingSearchCacheWrites();- const afterP1 = await engine.executeRaw<{ n: number }>(- `SELECT COUNT(*)::int AS n FROM query_cache`,- );- expect(afterP1[0].n).toBe(1);-- // Page 2 (offset 1, limit 1): identical embedding + knobs (offset is NOT- // in the knobs hash). Pre-fix this HIT the page-1 row and re-sliced the- // already-sliced 1-row page → an empty page-2 forever. Post-fix the- // cache is bypassed entirely and the engine serves the real second row.- let p2Meta: HybridSearchMeta | undefined;- const page2 = await hybridSearchCached(engine, 'builder', {- limit: 1,- offset: 1,- onMeta: (m) => { p2Meta = m; },- });- expect(p2Meta?.cache?.status).toBe('disabled');- expect(page2.length).toBe(1);- expect(page2[0].slug).not.toBe(page1[0].slug);-- // The bypass covers the STORE too: the page-2 read banks no row (a- // stored page-2 slice under the shared knobs hash would poison offset-0- // reads the same way).- await awaitPendingSearchCacheWrites();- const afterP2 = await engine.executeRaw<{ n: number }>(- `SELECT COUNT(*)::int AS n FROM query_cache`,- );- expect(afterP2[0].n).toBe(1);-- // Page-1 semantics unchanged: a repeat offset-0 read still hits and- // serves the same page.- let p1AgainMeta: HybridSearchMeta | undefined;- const page1Again = await hybridSearchCached(engine, 'builder', {- limit: 1,- onMeta: (m) => { p1AgainMeta = m; },- });- expect(p1AgainMeta?.cache?.status).toBe('hit');- expect(page1Again.map((r) => r.slug)).toEqual(page1.map((r) => r.slug));+ expect(await engine.executeRaw('SELECT id FROM query_cache')).toEqual([]);});});diff --git a/test/hybrid-cached-hit-budget-meta.serial.test.ts b/test/hybrid-cached-hit-budget-meta.serial.test.tsindex b1b86424ab..0dda0c7c4b 100644--- a/test/hybrid-cached-hit-budget-meta.serial.test.ts+++ b/test/hybrid-cached-hit-budget-meta.serial.test.ts@@ -1,17 +1,7 @@/**- * Cache-HIT budget-meta provenance — companion to the miss-path fix.- *- * With a per-call tokenBudget, the miss path stores an already-budgeted- * result set; a subsequent HIT re-applies the same budget to that trimmed- * payload (a structural no-op: tokenBudget is folded into knobsHash, so a- * hit only ever serves a lookup with the identical resolved budget as the- * write) — and pre-fix published that no-op pass's meta, reporting- * dropped=0 while the miss that produced the very same result set reported- * the real cut. This file drives a real store→hit roundtrip (mocked- * `embedQuery` for a deterministic vector, real PGLite SemanticQueryCache)- * and pins that the hit's token_budget matches the miss's.- *- * Serial: mock.module + gateway/global-env mutation (isolation guard R2).+ * Repeated fresh-search behavior while semantic response caching is disabled.+ * Keeps the mode-limit, pagination and budget guarantees independent of cache+ * availability. Serial because embedding/gateway mocks are process-global.*/import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';@@ -50,15 +40,9 @@ let tmpHome: string;const savedGbrainHome = process.env.GBRAIN_HOME;beforeAll(async () => {- // Hermetic config home so the developer's real ~/.gbrain/config.json- // can't leak an embedding_model that flips the cache consult to- // 'disabled' via isCacheSafe.tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-hit-budget-meta-'));process.env.GBRAIN_HOME = tmpHome;- // Pin the gateway to a 1536d provider BEFORE initSchema so the- // query_cache.embedding column is sized for the mock vectors. The fake- // key is never used — embedQuery is mocked above.resetGateway();configureGateway({embedding_model: 'openai:text-embedding-3-large',@@ -70,9 +54,6 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();- // Three keyword-findable pages, ~200 tokens each, mixed types so dedup's- // type-diversity layer keeps all of them. putPage never chunks —- // searchKeyword joins content_chunks, so chunks are explicit.const longText = 'x'.repeat(800);const fixtures: Array<[string, string, string]> = [['alice-foo', 'Alice Foo', 'person'],@@ -96,38 +77,32 @@ afterAll(async () => {try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }});-describe('cache HIT — token_budget provenance', () => {- test('hit reports the same cut the miss reported, not the no-op re-application', async () => {- // Miss: budget 250 keeps ~1 of 3 rows (~209 tokens each); the meta- // carries the real cut from the inner enforcement.- let missMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const missResults = await hybridSearchCached(engine, 'builder', {+describe('fresh repeated reads preserve token-budget provenance', () => {+ test('repeated reads report the original inner budget cut', async () => {+ let firstMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const firstResults = await hybridSearchCached(engine, 'builder', {limit: 10,tokenBudget: 250,- onMeta: (m) => { missMeta = m; },+ onMeta: (m) => { firstMeta = m; },});- expect(missResults.length).toBeGreaterThan(0);- expect(missMeta?.cache?.status).toBe('miss');- expect(missMeta?.token_budget?.budget).toBe(250);- const missDropped = missMeta?.token_budget?.dropped;- expect(missDropped).toBeGreaterThan(0);+ expect(firstResults.length).toBeGreaterThan(0);+ expect(firstMeta?.cache?.status).toBe('disabled');+ expect(firstMeta?.token_budget?.budget).toBe(250);+ const firstDropped = firstMeta?.token_budget?.dropped;+ expect(firstDropped).toBeGreaterThan(0);await awaitPendingSearchCacheWrites();- // Hit: identical query + knobs (tokenBudget is part of knobsHash, so- // this is the ONLY kind of lookup the stored row can serve). The- // published budget record must match the miss's — pre-fix it was the- // outer no-op pass's meta with dropped=0.- let hitMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;- const hitResults = await hybridSearchCached(engine, 'builder', {+ let repeatMeta: import('../src/core/types.ts').HybridSearchMeta | undefined;+ const repeatResults = await hybridSearchCached(engine, 'builder', {limit: 10,tokenBudget: 250,- onMeta: (m) => { hitMeta = m; },+ onMeta: (m) => { repeatMeta = m; },});- expect(hitMeta?.cache?.status).toBe('hit');- expect(hitResults.length).toBe(missResults.length);- expect(hitMeta?.token_budget?.budget).toBe(250);- expect(hitMeta?.token_budget?.dropped).toBe(missDropped);- expect(hitMeta?.token_budget?.kept).toBe(missMeta?.token_budget?.kept);+ expect(repeatMeta?.cache?.status).toBe('disabled');+ expect(repeatResults.length).toBe(firstResults.length);+ expect(repeatMeta?.token_budget?.budget).toBe(250);+ expect(repeatMeta?.token_budget?.dropped).toBe(firstDropped);+ expect(repeatMeta?.token_budget?.kept).toBe(firstMeta?.token_budget?.kept);});});diff --git a/test/hybrid-degraded-cache-meta.serial.test.ts b/test/hybrid-degraded-cache-meta.serial.test.tsindex b5ace44190..85687003da 100644--- a/test/hybrid-degraded-cache-meta.serial.test.ts+++ b/test/hybrid-degraded-cache-meta.serial.test.ts@@ -1,22 +1,8 @@/**- * WP2/T3 — cached-wrapper meta correctness (ENG-5 + D14.2 + cache_prestamp).- *- * Drives real store→hit roundtrips (mocked `embedQuery` for a deterministic- * vector, real PGLite SemanticQueryCache) and pins:- *- * - meta-key-parity: bare hybridSearch's meta keys ⊆ cached wrapper's,- * on BOTH the miss and the hit path (the spread-carry rebuild can- * never silently drop a key again — the adaptive_return drop class)- * - cache-hit stamping: `cache.status === 'hit'`, degraded carried from- * the stored row; hit-with-offset stays labeled 'hit'- * - cache_prestamp: a row whose stored meta lacks the degradation stamp- * surfaces degraded:[{stage:'cache_prestamp'}], never a clean claim- * - D14.2 short TTL: a degraded (but embeddable) result set is written- * with ttl_seconds=60; a clean set keeps the resolved TTL (3600)- * - null-embedding store is a silent no-op (ENG-6 — total embed outage- * is uncacheable by construction)- *- * Serial: mock.module + gateway/global-env mutation (isolation guard R2).+ * Production-wrapper regression coverage with semantic response caching disabled.+ * Fresh reads must retain filtering, metadata and telemetry guarantees; legacy+ * cache implementation behavior is covered by the direct cache-class suites.+ * Serial because embedding and gateway configuration are process-global.*/import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';@@ -55,7 +41,6 @@ const {hybridSearch,hybridSearchCached,awaitPendingSearchCacheWrites,- DEGRADED_CACHE_TTL_SECONDS,} = await import('../src/core/search/hybrid.ts');const { SemanticQueryCache } = await import('../src/core/search/query-cache.ts');const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');@@ -79,9 +64,6 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- // v0.48.2: the balanced bundle now reranks with a keyed default; without the- // key the search stamps `reranker_skipped` (by design). This suite is about- // EMBED degradation, so hold the reranker off to keep `degraded` clean.await engine.setConfig('search.reranker.enabled', 'false');const fixtures: Array<[string, string, string]> = [@@ -107,8 +89,6 @@ afterAll(async () => {});beforeEach(async () => {- // Every query shares the same mocked vector, so rows from one test would- // HIT for another test's different query text. Isolate per test.await engine.executeRaw('DELETE FROM query_cache');});@@ -125,46 +105,43 @@ async function cachedRun(return { results, meta };}-describe('meta-key-parity (ENG-5) — bare keys ⊆ cached keys, hit and miss', () => {- test('miss and hit both carry every key bare hybridSearch emits', async () => {+describe('meta-key parity between bare and repeated wrapper reads', () => {+ test('repeated wrapper reads carry every key bare hybridSearch emits', async () => {let bareMeta: HybridSearchMeta | undefined;await hybridSearch(engine, 'builder', { limit: 5, onMeta: (m) => { bareMeta = m; } });const bareKeys = Object.keys(bareMeta!);expect(bareKeys).toContain('degraded');expect(bareKeys).toContain('retrieved_count');- const { meta: missMeta } = await cachedRun('builder', { limit: 5 });- expect(missMeta.cache?.status).toBe('miss');+ const { meta: firstMeta } = await cachedRun('builder', { limit: 5 });+ expect(firstMeta.cache?.status).toBe('disabled');for (const k of bareKeys) {- expect(Object.keys(missMeta)).toContain(k);+ expect(Object.keys(firstMeta)).toContain(k);}await awaitPendingSearchCacheWrites();- const { meta: hitMeta } = await cachedRun('builder', { limit: 5 });- expect(hitMeta.cache?.status).toBe('hit');+ const { meta: repeatMeta } = await cachedRun('builder', { limit: 5 });+ expect(repeatMeta.cache?.status).toBe('disabled');for (const k of bareKeys) {- expect(Object.keys(hitMeta)).toContain(k);+ expect(Object.keys(repeatMeta)).toContain(k);}});});-describe('cache-hit stamping', () => {- test('hit carries cache.status=hit + the stored (clean) degradation stamp', async () => {- const { meta: missMeta } = await cachedRun('builder', { limit: 5 });- expect(missMeta.degraded).toEqual([]);+describe('fresh wrapper metadata', () => {+ test('repeated fresh reads report disabled caching and clean degradation metadata', async () => {+ const { meta: firstMeta } = await cachedRun('builder', { limit: 5 });+ expect(firstMeta.degraded).toEqual([]);await awaitPendingSearchCacheWrites();- const { meta: hitMeta } = await cachedRun('builder', { limit: 5 });- expect(hitMeta.cache?.status).toBe('hit');- expect(hitMeta.degraded).toEqual([]); // stored stamp, not cache_prestamp- expect(typeof hitMeta.retrieved_count).toBe('number');+ const { meta: repeatMeta } = await cachedRun('builder', { limit: 5 });+ expect(repeatMeta.cache?.status).toBe('disabled');+ expect(repeatMeta.degraded).toEqual([]); // stored stamp, not cache_prestamp+ expect(typeof repeatMeta.retrieved_count).toBe('number');});- test('offset>0 bypasses the cache entirely (pages are cache-hostile until the pre-slice pool is stored)', async () => {- // Post-#3002/#3871 hardening: the cache stores the already-sliced page,- // so serving ANY offset against it returns wrong/empty rows. Paged- // requests skip both lookup and store — status 'disabled', engine-served.+ test('positive offsets remain uncached with retrieval metadata', async () => {const { results: missResults } = await cachedRun('builder', { limit: 5 });expect(missResults.length).toBeGreaterThan(0);await awaitPendingSearchCacheWrites();@@ -174,7 +151,7 @@ describe('cache-hit stamping', () => {expect(typeof meta.retrieved_count).toBe('number');});- test('offset<0 also bypasses the cache entirely (#4358 residual — negative offsets re-slice a stored page just as badly as positive ones)', async () => {+ test('negative offsets remain uncached with retrieval metadata', async () => {const { results: missResults } = await cachedRun('builder', { limit: 5 });expect(missResults.length).toBeGreaterThan(0);await awaitPendingSearchCacheWrites();@@ -185,47 +162,45 @@ describe('cache-hit stamping', () => {});});-describe('cache_prestamp — pre-upgrade rows cannot claim clean', () => {- test('stored meta lacking the degraded key surfaces cache_prestamp on hit', async () => {- await cachedRun('builder', { limit: 5 });- await awaitPendingSearchCacheWrites();- // Simulate a pre-stamp row: strip the degraded key from the stored meta.- await engine.executeRaw(`UPDATE query_cache SET meta = meta - 'degraded'`);+describe('legacy metadata is never restored into a fresh response', () => {+ test('legacy metadata lacking the degradation stamp cannot affect a fresh response', async () => {+ const first = await cachedRun('builder', { limit: 5 });+ expect(first.results.length).toBeGreaterThan(0);+ const { degraded: _degraded, ...legacyMeta } = first.meta;+ await new SemanticQueryCache(engine).store('builder', fixedEmbedding(), first.results, legacyMeta);+ expect(await engine.executeRaw('SELECT id FROM query_cache')).toHaveLength(1);const { meta } = await cachedRun('builder', { limit: 5 });- expect(meta.cache?.status).toBe('hit');- expect(meta.degraded).toEqual([{ stage: 'cache_prestamp' }]);+ expect(meta.cache?.status).toBe('disabled');+ expect(meta.degraded).toEqual([]);+ expect(meta.retrieved_count).toBe(first.meta.retrieved_count);});});-describe('D14.2 — degraded result sets get a short-TTL cache entry', () => {- test('embeddable degradation (expansion_partial) writes ttl_seconds=60, stamped', async () => {+describe('clean and degraded result sets both bypass cache writes', () => {+ test('expansion degradation is reported without writing a cache row', async () => {const { meta } = await cachedRun('builder', {limit: 5,expansion: true,expandFn: async () => ['builder', 'EMBEDFAIL variant'],});- expect(meta.cache?.status).toBe('miss');+ expect(meta.cache?.status).toBe('disabled');expect((meta.degraded ?? []).map((d) => d.stage)).toContain('expansion_partial');await awaitPendingSearchCacheWrites();const rows = await engine.executeRaw<{ ttl_seconds: number; meta: unknown }>('SELECT ttl_seconds, meta FROM query_cache',);- expect(rows).toHaveLength(1);- expect(rows[0].ttl_seconds).toBe(DEGRADED_CACHE_TTL_SECONDS);- const storedMeta = rows[0].meta as HybridSearchMeta;- expect((storedMeta.degraded ?? []).map((d) => d.stage)).toContain('expansion_partial');+ expect(rows).toHaveLength(0);});- test('clean run keeps the resolved TTL (3600 default)', async () => {+ test('clean runs also leave the cache empty', async () => {await cachedRun('builder', { limit: 5 });await awaitPendingSearchCacheWrites();const rows = await engine.executeRaw<{ ttl_seconds: number }>('SELECT ttl_seconds FROM query_cache',);- expect(rows).toHaveLength(1);- expect(rows[0].ttl_seconds).toBe(3600);+ expect(rows).toHaveLength(0);});});diff --git a/test/hybrid-exclude-private-cache-fold.serial.test.ts b/test/hybrid-exclude-private-cache-fold.serial.test.tsindex 5efee55dba..87336d435b 100644--- a/test/hybrid-exclude-private-cache-fold.serial.test.ts+++ b/test/hybrid-exclude-private-cache-fold.serial.test.ts@@ -1,21 +1,10 @@/**- * #4352 follow-up — excludePrivate searches CACHE (posture folded into- * knobsHash), they no longer skip the semantic query cache.- *- * #4352 originally shipped a wholesale `privateFiltered || ` skipCache term —- * but excludePrivate=true is the DEFAULT for every remote MCP caller, so the- * skip disabled the cache for exactly the highest-volume beneficiaries- * (~50% cost savings lost). The v=23 fold (xp=) restores caching while- * keeping the postures contamination-proof. Pins:- * 1. a remote-default (excludePrivate=true) run reports 'miss' then 'hit'- * on repeat — never 'disabled' — and never surfaces a private page,- * 2. a trusted (private-included) write is never served to a- * private-excluding read (distinct knobs_hash rows),- * 3. a private-excluding write is never served to a trusted read.- *- * Serial: mock.module + gateway/global-env mutation (same harness shape as- * test/hybrid-types-cache-skip.serial.test.ts).+ * Production-wrapper regression coverage with semantic response caching disabled.+ * Fresh reads must retain filtering, metadata and telemetry guarantees; legacy+ * cache implementation behavior is covered by the direct cache-class suites.+ * Serial because embedding and gateway configuration are process-global.*/+import { afterAll, beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, test } from 'bun:test';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -44,6 +33,8 @@ const { hybridSearchCached, awaitPendingSearchCacheWrites } =await import('../src/core/search/hybrid.ts');const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+const { importFromContent } = await import('../src/core/import-file.ts');+const { serializeMarkdown } = await import('../src/core/markdown.ts');setDefaultTimeout(30_000);@@ -72,10 +63,10 @@ beforeAll(async () => {];for (const [slug, title, frontmatter] of fixtures) {const truth = `${title} is a builder.`;- await engine.putPage(slug, { type: 'concept', title, frontmatter, compiled_truth: truth });- await engine.upsertChunks(slug, [- { chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },- ]);+ const result = await importFromContent(engine, slug,+ serializeMarkdown(frontmatter, truth, '', { type: 'concept', title, tags: [] }),+ { noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');}});@@ -91,80 +82,70 @@ beforeEach(async () => {await engine.executeRaw('DELETE FROM query_cache');});-describe('#4352 follow-up — excludePrivate folds into the cache key instead of skipping', () => {- test('a remote-default run gets miss then hit (never disabled) and never a private page', async () => {- // 1. First excludePrivate run: cache MISS (not 'disabled' — the pre-fix- // wholesale skip is the regression this pins), filtered results.+describe('private visibility applies on every fresh wrapper read', () => {+ test('repeated remote-default reads stay uncached and never expose private pages', async () => {let firstMeta: HybridSearchMeta | undefined;const first = await hybridSearchCached(engine, 'builder', {limit: 10,excludePrivate: true,onMeta: (m) => { firstMeta = m; },});- expect(firstMeta?.cache?.status).toBe('miss');+ expect(firstMeta?.cache?.status).toBe('disabled');expect(first.map((r) => r.slug)).toEqual(['notes/world-widget']);await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);- // 2. Repeat run under the SAME posture: HIT, still filtered.let repeatMeta: HybridSearchMeta | undefined;const repeat = await hybridSearchCached(engine, 'builder', {limit: 10,excludePrivate: true,onMeta: (m) => { repeatMeta = m; },});- expect(repeatMeta?.cache?.status).toBe('hit');+ expect(repeatMeta?.cache?.status).toBe('disabled');expect(repeat.map((r) => r.slug)).toEqual(['notes/world-widget']);});- test('a trusted (private-included) write is never served to an excludePrivate read', async () => {- // 1. Trusted miss-run stores a row containing BOTH pages.+ test('a private-excluding read stays filtered after a trusted read', async () => {let trustedMeta: HybridSearchMeta | undefined;const trusted = await hybridSearchCached(engine, 'builder', {limit: 10,onMeta: (m) => { trustedMeta = m; },});- expect(trustedMeta?.cache?.status).toBe('miss');+ expect(trustedMeta?.cache?.status).toBe('disabled');expect(trusted.map((r) => r.slug).sort()).toEqual(['notes/private-widget', 'notes/world-widget']);await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);- // 2. Same query, remote posture: identical embedding — pre-fold this- // would have HIT the trusted row and leaked the private page. Must- // MISS onto its own key instead (fresh, filtered query).let remoteMeta: HybridSearchMeta | undefined;const remote = await hybridSearchCached(engine, 'builder', {limit: 10,excludePrivate: true,onMeta: (m) => { remoteMeta = m; },});- expect(remoteMeta?.cache?.status).toBe('miss');+ expect(remoteMeta?.cache?.status).toBe('disabled');expect(remote.map((r) => r.slug)).toEqual(['notes/world-widget']);- // 3. The remote run stores its OWN row — two distinct knobs_hash rows.await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(2);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);});- test('an excludePrivate write is never served to a trusted read (no hidden pages)', async () => {+ test('a trusted read still includes private pages after a filtered read', async () => {let remoteMeta: HybridSearchMeta | undefined;await hybridSearchCached(engine, 'builder', {limit: 10,excludePrivate: true,onMeta: (m) => { remoteMeta = m; },});- expect(remoteMeta?.cache?.status).toBe('miss');+ expect(remoteMeta?.cache?.status).toBe('disabled');await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);- // A trusted read of the same query must NOT be served the filtered row —- // it is entitled to the private page.let trustedMeta: HybridSearchMeta | undefined;const trusted = await hybridSearchCached(engine, 'builder', {limit: 10,onMeta: (m) => { trustedMeta = m; },});- expect(trustedMeta?.cache?.status).toBe('miss');+ expect(trustedMeta?.cache?.status).toBe('disabled');expect(trusted.map((r) => r.slug).sort()).toEqual(['notes/private-widget', 'notes/world-widget']);});});diff --git a/test/hybrid-reranker-skipped.serial.test.ts b/test/hybrid-reranker-skipped.serial.test.tsindex 99d610b17b..06fc6d4791 100644--- a/test/hybrid-reranker-skipped.serial.test.ts+++ b/test/hybrid-reranker-skipped.serial.test.ts@@ -126,19 +126,24 @@ describe('balanced search without VOYAGE_API_KEY (v0.48.2)', () => {expect(second.meta.degraded ?? []).toContainEqual({ stage: 'reranker_skipped', reason: 'no_key' });});- test('a reranker_skipped stamp keeps the FULL cache TTL (config state, not a transient limp)', async () => {+ test('fresh cached-wrapper searches retain reranker_skipped metadata with effective cache disabled', async () => {configure(false);_resetSunsetWarningsForTest();__setRerankTransportForTests(async () => new Response(JSON.stringify({ results: [] }), { status: 200 }));await engine.executeRaw('DELETE FROM query_cache');- let meta: HybridSearchMeta | undefined;- const results = await hybridSearchCached(engine, 'builder plumbing', { limit: 5, onMeta: (m) => { meta = m; } });- expect(results.length).toBeGreaterThan(0);- expect(meta?.degraded ?? []).toContainEqual({ stage: 'reranker_skipped', reason: 'no_key' });+ await engine.setConfig('search.cache.enabled', 'true');+ for (let attempt = 0; attempt < 2; attempt++) {+ let meta: HybridSearchMeta | undefined;+ const results = await hybridSearchCached(engine, 'builder plumbing', {+ limit: 5, useCache: true, onMeta: (m) => { meta = m; },+ });+ expect(results.length).toBeGreaterThan(0);+ expect(results.every((r) => r.rerank_score === undefined)).toBe(true);+ expect(meta?.degraded ?? []).toContainEqual({ stage: 'reranker_skipped', reason: 'no_key' });+ expect(meta?.cache?.status).toBe('disabled');+ }await awaitPendingSearchCacheWrites();- const rows = await engine.executeRaw<{ ttl_seconds: number }>('SELECT ttl_seconds FROM query_cache');- expect(rows).toHaveLength(1);- expect(rows[0]!.ttl_seconds).toBe(3600);+ expect(await engine.executeRaw('SELECT id FROM query_cache')).toHaveLength(0);});test('with the key present the reranker runs: rerank_score stamped, no skip entry', async () => {diff --git a/test/hybrid-types-cache-skip.serial.test.ts b/test/hybrid-types-cache-skip.serial.test.tsindex 04ef026ef5..8a62eaac63 100644--- a/test/hybrid-types-cache-skip.serial.test.ts+++ b/test/hybrid-types-cache-skip.serial.test.ts@@ -1,16 +1,10 @@/**- * #3985 — `types`-filtered searches must bypass the semantic query cache.- *- * `types` is not part of knobsHash, so a type-filtered result set stored in- * the cache could be served to an unfiltered lookup (and vice versa) — the- * same contamination class as #3442's date filters. Pins:- * 1. a types run reports cache 'disabled' (skip on lookup AND store),- * 2. an unfiltered write is never served to a types read,- * 3. a types run never stores a row for later unfiltered hits.- *- * Serial: mock.module + gateway/global-env mutation (same harness shape as- * test/hybrid-cache-scope-poison.serial.test.ts).+ * Production-wrapper regression coverage with semantic response caching disabled.+ * Fresh reads must retain filtering, metadata and telemetry guarantees; legacy+ * cache implementation behavior is covered by the direct cache-class suites.+ * Serial because embedding and gateway configuration are process-global.*/+import { afterAll, beforeAll, beforeEach, describe, expect, mock, setDefaultTimeout, test } from 'bun:test';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';@@ -87,20 +81,17 @@ beforeEach(async () => {});describe('#3985 — types-filtered requests skip the semantic cache', () => {- test('an unfiltered write is never served to a types read (and the types run stores nothing)', async () => {- // 1. Unfiltered miss-run stores a row containing BOTH pages.- let missMeta: HybridSearchMeta | undefined;+ test('a types filter applies after an unfiltered read and both leave the cache empty', async () => {+ let firstMeta: HybridSearchMeta | undefined;const unfiltered = await hybridSearchCached(engine, 'builder', {limit: 10,- onMeta: (m) => { missMeta = m; },+ onMeta: (m) => { firstMeta = m; },});- expect(missMeta?.cache?.status).toBe('miss');+ expect(firstMeta?.cache?.status).toBe('disabled');expect(unfiltered.map((r) => r.slug).sort()).toEqual(['alice-foo', 'bob-bar']);await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);- // 2. Same query WITH a types filter: identical embedding + knobs would- // have HIT the stored all-types row pre-fix. Must bypass instead.let typesMeta: HybridSearchMeta | undefined;const personsOnly = await hybridSearchCached(engine, 'builder', {limit: 10,@@ -110,9 +101,8 @@ describe('#3985 — types-filtered requests skip the semantic cache', () => {expect(typesMeta?.cache?.status).toBe('disabled');expect(personsOnly.map((r) => r.slug)).toEqual(['alice-foo']);- // 3. The types run must not have stored anything either.await awaitPendingSearchCacheWrites();- expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(1);+ expect((await engine.executeRaw('SELECT id FROM query_cache')).length).toBe(0);});test('a types-first run leaves the cache empty, so a later unfiltered read gets full recall', async () => {diff --git a/test/import-default-write-guard-once.test.ts b/test/import-default-write-guard-once.test.tsindex 8fca5a0ed0..1a7fa9fa24 100644--- a/test/import-default-write-guard-once.test.ts+++ b/test/import-default-write-guard-once.test.ts@@ -36,10 +36,12 @@ beforeAll(async () => {await engine.initSchema();// Count the guard's aggregate (the only query in the codebase that projects// `non_default_sources`) without changing its behavior.- const realExecuteRaw = engine.executeRaw.bind(engine);- (engine as unknown as { executeRaw: typeof realExecuteRaw }).executeRaw = (async (sql: string, params?: unknown[]) => {+ // Import transaction clones inherit this wrapper, so keep their receiver+ // instead of sending transaction queries through the base engine.+ const realExecuteRaw = engine.executeRaw;+ (engine as unknown as { executeRaw: typeof realExecuteRaw }).executeRaw = (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {if (sql.includes('non_default_sources')) aggregateRuns++;- return realExecuteRaw(sql, params);+ return realExecuteRaw.call(this, sql, params);}) as typeof realExecuteRaw;home = mkdtempSync(join(tmpdir(), 'gbrain-import-guard-once-home-'));// Second engine for the per-engine memo test; created here so the isolation@@ -47,10 +49,10 @@ beforeAll(async () => {other = new PGLiteEngine();await other.connect({});await other.initSchema();- const realOtherExecuteRaw = other.executeRaw.bind(other);- (other as unknown as { executeRaw: typeof realOtherExecuteRaw }).executeRaw = (async (sql: string, params?: unknown[]) => {+ const realOtherExecuteRaw = other.executeRaw;+ (other as unknown as { executeRaw: typeof realOtherExecuteRaw }).executeRaw = (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {if (sql.includes('non_default_sources')) otherRuns++;- return realOtherExecuteRaw(sql, params);+ return realOtherExecuteRaw.call(this, sql, params);}) as typeof realOtherExecuteRaw;});@@ -192,9 +194,9 @@ describe('assessDefaultWriteGuardOnce does not memoize a failed assessment', ()writeFileSync(join(dir, 'r.md'), '---\ntype: note\ntitle: r\n---\n# r\n\nbody r\n');const wrapped = engine.executeRaw;let guardCalls = 0;- (engine as unknown as { executeRaw: typeof wrapped }).executeRaw = (async (sql: string, params?: unknown[]) => {+ (engine as unknown as { executeRaw: typeof wrapped }).executeRaw = (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {if (sql.includes('non_default_sources') && ++guardCalls === 1) throw new Error('connection reset by peer');- return wrapped(sql, params);+ return wrapped.call(this, sql, params);}) as typeof wrapped;const stderrLines: string[] = [];try {diff --git a/test/import-file.test.ts b/test/import-file.test.tsindex a725ed7c17..e23c2f33da 100644--- a/test/import-file.test.ts+++ b/test/import-file.test.ts@@ -485,6 +485,37 @@ ${longText}});describe('importFile — CJK wave (v0.32.7)', () => {+ const isVersionStamp = (sql: string) => /^\s*UPDATE\s+pages\s+SET\s+chunker_version\s*=/i.test(sql);++ function mockCompletedIndexEngine(): BrainEngine {+ let deletionCompleted = false;+ let replacementCompleted = false;+ return mockEngine({+ deleteChunks: async () => {+ await Promise.resolve();+ deletionCompleted = true;+ },+ upsertChunks: async () => {+ expect(deletionCompleted).toBe(true);+ await Promise.resolve();+ replacementCompleted = true;+ },+ executeRaw: async (sql: string) => {+ if (isVersionStamp(sql)) expect(replacementCompleted).toBe(true);+ return [];+ },+ });+ }++ function expectCompletedIndexVersion(engine: BrainEngine, slug: string): void {+ const calls = (engine as any)._calls;+ const putCall = calls.find((c: any) => c.method === 'putPage');+ expect(putCall.args[1].chunker_version).toBeUndefined();+ const stamps = calls.filter((c: any) => c.method === 'executeRaw' && isVersionStamp(c.args[0]));+ expect(stamps).toHaveLength(1);+ expect(stamps[0].args[1]).toEqual([MARKDOWN_CHUNKER_VERSION, 'default', slug]);+ }+test('REGRESSION: pure-CJK filename with NO frontmatter slug imports cleanly as CJK slug', async () => {// After #115, slugifyPath('小米.md') = '小米' (CJK preserved). The// anti-spoof rule is content with no frontmatter slug present.@@ -496,12 +527,12 @@ title: XiaomiBody text.`);- const engine = mockEngine();+ const engine = mockCompletedIndexEngine();const result = await importFile(engine, filePath, '小米.md', { noEmbed: true });expect(result.status).toBe('imported');expect(result.slug).toBe('小米');const putCall = (engine as any)._calls.find((c: any) => c.method === 'putPage');- expect(putCall.args[1].chunker_version).toBe(MARKDOWN_CHUNKER_VERSION);+ expectCompletedIndexVersion(engine, '小米');expect(putCall.args[1].source_path).toBe('小米.md');});@@ -562,7 +593,7 @@ Hijack.expect((engine as any)._calls.length).toBe(0);});- test('chunker_version + source_path populated on every import', async () => {+ test('completed index receives chunker_version and preserves source_path', async () => {const filePath = join(TMP, 'cjk-source-path.md');writeFileSync(filePath, `---type: concept@@ -571,11 +602,12 @@ title: Has source pathContent.`);- const engine = mockEngine();- await importFile(engine, filePath, 'concepts/cjk-source-path.md', { noEmbed: true });+ const engine = mockCompletedIndexEngine();+ const result = await importFile(engine, filePath, 'concepts/cjk-source-path.md', { noEmbed: true });+ expect(result.status).toBe('imported');const putCall = (engine as any)._calls.find((c: any) => c.method === 'putPage');expect(putCall).toBeTruthy();- expect(putCall.args[1].chunker_version).toBe(MARKDOWN_CHUNKER_VERSION);+ expectCompletedIndexVersion(engine, 'concepts/cjk-source-path');expect(putCall.args[1].source_path).toBe('concepts/cjk-source-path.md');});});diff --git a/test/import-image-file.test.ts b/test/import-image-file.test.tsindex 1fef8228be..d860462bf5 100644--- a/test/import-image-file.test.ts+++ b/test/import-image-file.test.ts@@ -12,6 +12,7 @@ import { tmpdir } from 'node:os';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { importImageFile, isImageFilePath, pLimit, SUPPORTED_IMAGE_EXTS } from '../src/core/import-file.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';let engine: PGLiteEngine;let tmpDir: string;@@ -108,6 +109,7 @@ describe('importImageFile happy path (noEmbed)', () => {expect((chunks[0] as { chunk_source: string }).chunk_source).toBe('image_asset');// chunk_text falls back to filename when OCR is off (default).expect(chunks[0].chunk_text).toBe('photo.png');+ expect(await engine.getChunks('originals/photos/photo.png', { requireSafeChunks: true })).toHaveLength(1);});test('idempotent on content_hash: re-import same bytes returns skipped', async () => {@@ -120,6 +122,40 @@ describe('importImageFile happy path (noEmbed)', () => {expect(r2.status).toBe('skipped');});+ test('unchanged clean legacy images rebuild and seal instead of skipping on content hash', async () => {+ const target = join(tmpDir, 'legacy.png');+ writeFileSync(target, Buffer.from('synthetic-stable-image-bytes'));+ const slug = 'photos/legacy.png';+ await importImageFile(engine, target, slug, { noEmbed: true });+ const page = (await engine.getPage(slug))!;+ await engine.executeRaw('UPDATE pages SET chunker_version = 3 WHERE id = $1', [page.id]);+ await engine.executeRaw('UPDATE content_chunks SET chunk_text = $1 WHERE page_id = $2', ['PRIVATE_OLD_IMAGE_FRAGMENT', page.id]);+ expect(await engine.getChunks(slug, { requireSafeChunks: true })).toEqual([]);+ expect(await importImageFile(engine, target, slug, { noEmbed: true })).toMatchObject({ status: 'imported' });+ const [version] = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE id = $1', [page.id]);+ expect(Number(version.chunker_version)).toBe(MARKDOWN_CHUNKER_VERSION);+ const chunks = await engine.getChunks(slug, { requireSafeChunks: true });+ expect(chunks).toHaveLength(1);+ expect(chunks[0].chunk_text).toBe('legacy.png');+ expect(JSON.stringify(chunks)).not.toContain('PRIVATE_OLD_IMAGE_FRAGMENT');+ });++ test('turning OCR off cannot certify unchanged pixels with known protected OCR content', async () => {+ const target = join(tmpDir, 'protected.png');+ writeFileSync(target, Buffer.from('synthetic-protected-image-bytes'));+ const slug = 'photos/protected.png';+ await importImageFile(engine, target, slug, { noEmbed: true });+ const page = (await engine.getPage(slug))!;+ await engine.putPage(slug, { ...page, compiled_truth: '<!--- gbrain:takes:begin -->\nPRIVATE_IMAGE_CANARY\n<!--- gbrain:takes:end -->' });+ expect(await importImageFile(engine, target, slug, { noEmbed: true })).toMatchObject({ status: 'skipped', error: expect.stringContaining('Remove that content') });+ expect(await engine.getChunks(slug, { requireSafeChunks: true })).toEqual([]);+ expect((await engine.getPage(slug))!.compiled_truth).toContain('PRIVATE_IMAGE_CANARY');+ writeFileSync(target, Buffer.from('changed-synthetic-image-bytes'));+ expect(await importImageFile(engine, target, slug, { noEmbed: true })).toMatchObject({ status: 'skipped', error: expect.stringContaining('successful fresh OCR') });+ expect(await engine.getChunks(slug, { requireSafeChunks: true })).toEqual([]);+ expect((await engine.getPage(slug))!.compiled_truth).toContain('PRIVATE_IMAGE_CANARY');+ });+test('routes page, chunks, and file metadata to the requested source (#2706)', async () => {await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING`,diff --git a/test/local-federated-search-scope.test.ts b/test/local-federated-search-scope.test.tsindex ed34ec8110..40b7e9a03c 100644--- a/test/local-federated-search-scope.test.ts+++ b/test/local-federated-search-scope.test.ts@@ -26,6 +26,8 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { localFederatedSourceIds } from '../src/core/source-resolver.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';import {federatedSearchScope,operations,@@ -71,12 +73,10 @@ beforeAll(async () => {['old/topic', 'oldnews', 'oldnews'],];for (const [slug, sourceId, where] of pages) {- await engine.putPage(slug, {- type: 'note', title: `Topic in ${where}`, compiled_truth: `the zebra telescope in ${where}`, frontmatter: {},- }, { sourceId });- await engine.upsertChunks(slug, [- { chunk_index: 0, chunk_text: `the zebra telescope in ${where}`, chunk_source: 'compiled_truth' },- ], { sourceId });+ const result = await importFromContent(engine, slug,+ serializeMarkdown({}, `the zebra telescope in ${where}`, '', { type: 'note', title: `Topic in ${where}`, tags: [] }),+ { sourceId, noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');}// Keyword-only search path: no embedding provider needed in tests.await engine.setConfig('search.mcp_keyword_only', 'true');diff --git a/test/mcp-client-hardening.test.ts b/test/mcp-client-hardening.test.tsindex befcf78b35..561a0eac0b 100644--- a/test/mcp-client-hardening.test.ts+++ b/test/mcp-client-hardening.test.ts@@ -50,15 +50,27 @@ describe('toRemoteMcpError', () => {expect(out.detail?.kind).toBe('aborted');});- test('Error with /abort/i in message becomes network/aborted (SDK swallows .name)', () => {- // The MCP SDK sometimes wraps AbortError in a generic Error with the- // word "abort" in the message. The funnel catches both shapes.+ test('abort text alone does not classify cancellation', () => {const err = new Error('request was aborted by the user');const out = toRemoteMcpError(err, MCP_URL);expect(out.reason).toBe('network');+ expect(out.detail?.kind).toBe('unreachable');+ });++ test('the call signal identifies cancellation even when the SDK wraps its error', () => {+ const controller = new AbortController();+ controller.abort(new Error('caller stopped'));+ const out = toRemoteMcpError(new Error('SDK request failed'), MCP_URL, controller.signal);expect(out.detail?.kind).toBe('aborted');});+ test('a timeout signal overrides an already-normalized probe failure', () => {+ const controller = new AbortController();+ controller.abort(new DOMException('deadline', 'TimeoutError'));+ const out = toRemoteMcpError(new RemoteMcpError('network', 'probe failed'), MCP_URL, controller.signal);+ expect(out.detail?.kind).toBe('timeout');+ });+test('non-Error throwable (string) becomes network/unreachable', () => {const out = toRemoteMcpError('something blew up', MCP_URL);expect(out).toBeInstanceOf(RemoteMcpError);@@ -104,6 +116,11 @@ describe('toRemoteMcpError', () => {});describe('extractToolErrorCode', () => {+ test('parses the operation error string without replacing it with a guessed code', () => {+ const msg = JSON.stringify({ error: 'permission_denied', message: 'access denied to client abc401def' });+ expect(extractToolErrorCode(msg)).toBe('permission_denied');+ });+test('parses JSON envelope with error.code', () => {const msg = JSON.stringify({ error: { code: 'missing_scope', message: 'admin required' } });expect(extractToolErrorCode(msg)).toBe('missing_scope');@@ -199,11 +216,7 @@ describe('buildAbortController', () => {const { signal, cleanup } = buildAbortController({ timeoutMs: 30 });cleanup();await new Promise(r => setTimeout(r, 80));- // signal can fire from the timer if cleanup didn't clear it.- // We accept either outcome but clear cleanup is the contract.- // The hard assertion is that calling cleanup doesn't throw and the- // pending timer doesn't crash the process.- void signal;+ expect(signal.aborted).toBe(false);});test('cleanup is idempotent (safe to call multiple times)', () => {diff --git a/test/mcp-client.test.ts b/test/mcp-client.test.tsindex 36d25f2294..c1b46e27c0 100644--- a/test/mcp-client.test.ts+++ b/test/mcp-client.test.ts@@ -16,7 +16,6 @@*/import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';-import { createServer, Server, IncomingMessage, ServerResponse } from 'http';import {callRemoteTool,unpackToolResult,@@ -24,93 +23,112 @@ import {_clearMcpClientTokenCache,} from '../src/core/mcp-client.ts';import type { GBrainConfig } from '../src/core/config.ts';+import { discoverOAuth, mintClientCredentialsToken } from '../src/core/remote-mcp-probe.ts';import { withEnv } from './helpers/with-env.ts';-let server: Server;+let server: ReturnType<typeof Bun.serve>;let port: number;// Per-test response controllet tokenStatus = 200;let mcpResponseFor: (req: { method: string; params?: unknown }) => unknown = () => ({});-let mcpStatusOverride: number | null = null;let tokenMintCount = 0;+type Stage = 'discovery' | 'token' | 'initialize' | 'notifications/initialized' | 'tools/call';+let requests: Partial<Record<Stage, number>> = {};+let statusFor: (stage: Stage, attempt: number) => number | undefined = () => undefined;+let hangingStage: Stage | undefined;+let hangFromAttempt = 1;+let hangAfterHeaders = false;+let onHang: (() => void) | undefined;+let onHangClosed: (() => void) | undefined;+let toolExecutions = 0;+let initializeTokens: string[] = [];-beforeAll(async () => {- server = createServer(async (req: IncomingMessage, res: ServerResponse) => {- if (req.url === '/.well-known/oauth-authorization-server') {- res.statusCode = 200;- res.setHeader('Content-Type', 'application/json');- res.end(JSON.stringify({ token_endpoint: `http://127.0.0.1:${port}/token`, issuer: `http://127.0.0.1:${port}` }));- return;+function intercept(stage: Stage, req: Request): Response | Promise<Response> | undefined {+ requests[stage] = (requests[stage] ?? 0) + 1;+ if (stage === hangingStage && requests[stage]! >= hangFromAttempt) {+ const closed = onHangClosed;+ onHang?.();+ if (hangAfterHeaders) {+ return new Response(new ReadableStream({+ start(controller) { controller.enqueue(new TextEncoder().encode('{')); },+ cancel() { closed?.(); },+ }), { headers: { 'Content-Type': 'application/json' } });}- if (req.url === '/token') {- tokenMintCount++;- res.statusCode = tokenStatus;- res.setHeader('Content-Type', 'application/json');- if (tokenStatus === 200) {- res.end(JSON.stringify({- access_token: `token-${Date.now()}-${tokenMintCount}`,- token_type: 'bearer',- expires_in: 3600,- scope: 'read write admin',- }));- } else {- res.end(JSON.stringify({ error: 'invalid_client' }));- }- return;- }- if (req.url === '/mcp' && req.method === 'POST') {- // Test-controlled status override (used to simulate 401 from MCP).- if (mcpStatusOverride !== null) {- res.statusCode = mcpStatusOverride;- res.end();- return;+ return new Promise<Response>(resolve => {+ req.signal.addEventListener('abort', () => {+ closed?.();+ resolve(new Response(null, { status: 499 }));+ }, { once: true });+ });+ }+ const status = statusFor(stage, requests[stage]!);+ if (status !== undefined) return new Response('fixture rejection', { status });+}++beforeAll(() => {+ server = Bun.serve({+ hostname: '127.0.0.1',+ port: 0,+ async fetch(req) {+ const path = new URL(req.url).pathname;+ if (path === '/.well-known/oauth-authorization-server') {+ const intercepted = intercept('discovery', req);+ if (intercepted) return intercepted;+ return Response.json({ token_endpoint: `http://127.0.0.1:${port}/token`, issuer: `http://127.0.0.1:${port}` });}- // Read JSON-RPC body- const chunks: Buffer[] = [];- for await (const chunk of req) chunks.push(chunk as Buffer);- const body = JSON.parse(Buffer.concat(chunks).toString('utf-8'));- const isNotification = body.id === undefined;- // Notifications get 202 No Content- if (isNotification) {- res.statusCode = 202;- res.end();- return;+ if (path === '/token') {+ tokenMintCount++;+ const intercepted = intercept('token', req);+ if (intercepted) return intercepted;+ return Response.json(tokenStatus === 200 ? {+ access_token: `token-${Date.now()}-${tokenMintCount}`,+ token_type: 'bearer', expires_in: 3600, scope: 'read write admin',+ } : { error: 'invalid_client' }, { status: tokenStatus });}- let result: unknown;- if (body.method === 'initialize') {- result = {- protocolVersion: body.params?.protocolVersion ?? '2024-11-05',- capabilities: { tools: {} },- serverInfo: { name: 'mcp-client-test-fixture', version: '1' },- };- } else if (body.method === 'tools/call') {- result = mcpResponseFor({ method: body.method, params: body.params });- } else {- result = {};+ if (path === '/mcp' && req.method === 'POST') {+ const body = await req.json() as { id?: number; method: string; params?: { protocolVersion?: string } };+ if (body.method === 'initialize') initializeTokens.push(req.headers.get('authorization') ?? '');+ const intercepted = intercept(body.method as Stage, req);+ if (intercepted) return intercepted;+ if (body.id === undefined) return new Response(null, { status: 202 });+ let result: unknown;+ if (body.method === 'initialize') {+ result = {+ protocolVersion: body.params?.protocolVersion ?? '2024-11-05',+ capabilities: { tools: {} },+ serverInfo: { name: 'mcp-client-test-fixture', version: '1' },+ };+ } else if (body.method === 'tools/call') {+ toolExecutions++;+ result = mcpResponseFor({ method: body.method, params: body.params });+ } else {+ result = {};+ }+ return Response.json({ jsonrpc: '2.0', id: body.id, result });}- res.statusCode = 200;- res.setHeader('Content-Type', 'application/json');- res.end(JSON.stringify({ jsonrpc: '2.0', id: body.id, result }));- return;- }- res.statusCode = 404;- res.end();+ return new Response(null, { status: path === '/mcp' ? 405 : 404 });+ },});- await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()));- const addr = server.address();- if (!addr || typeof addr === 'string') throw new Error('failed to bind fixture');- port = addr.port;+ port = server.port!;});afterAll(async () => {- await new Promise<void>(resolve => server.close(() => resolve()));+ await server.stop(true);});beforeEach(() => {tokenStatus = 200;tokenMintCount = 0;- mcpStatusOverride = null;+ requests = {};+ statusFor = () => undefined;+ hangingStage = undefined;+ hangFromAttempt = 1;+ hangAfterHeaders = false;+ onHang = undefined;+ onHangClosed = undefined;+ toolExecutions = 0;+ initializeTokens = [];mcpResponseFor = () => ({ content: [{ type: 'text', text: JSON.stringify({ ok: true }) }] });_clearMcpClientTokenCache();});@@ -155,51 +173,184 @@ describe('callRemoteTool — happy path', () => {});});-describe('callRemoteTool — 401 refresh-on-once', () => {- test('401 from /mcp → re-mint token + retry succeeds', async () => {- // Pre-seed cache with a fresh-but-server-rejected token by first- // succeeding once, then flipping the server to 401 just once.- await callRemoteTool(makeConfig(), 'first_success', {});- expect(tokenMintCount).toBe(1);+describe('callRemoteTool — HTTP authentication boundaries', () => {+ for (const stage of ['initialize', 'tools/call'] as const) {+ test(`${stage}: one HTTP 401 refreshes once and executes the tool once`, async () => {+ statusFor = (current, attempt) => current === stage && attempt === 1 ? 401 : undefined;+ const result = await callRemoteTool(makeConfig(), 'write_example', { value: 1 });+ expect(unpackToolResult<{ ok: boolean }>(result)).toEqual({ ok: true });+ expect(tokenMintCount).toBe(2);+ expect(requests[stage]).toBe(2);+ expect(initializeTokens).toHaveLength(2);+ expect(initializeTokens[0]).not.toBe(initializeTokens[1]);+ expect(toolExecutions).toBe(1);+ });- // Next call: the /mcp endpoint will return 401 on the first attempt;- // the client should re-mint and retry. We simulate "rejected once,- // accepted on retry" by counting requests.- let mcpCallCount = 0;- mcpStatusOverride = null;- const origResponse = mcpResponseFor;- mcpResponseFor = ({ method, params }) => {- if (method === 'tools/call') mcpCallCount++;- // First call: instruct fixture to return 401 by setting override THEN restore- // Actually simpler: throw on first attempt by setting mcpStatusOverride pre-emptively- return origResponse({ method, params });- };+ test(`${stage}: repeated HTTP 401 stops after one refresh`, async () => {+ statusFor = current => current === stage ? 401 : undefined;+ await expect(callRemoteTool(makeConfig(), 'write_example')).rejects.toMatchObject({+ reason: 'auth_after_refresh', detail: { status: 401 },+ });+ expect(tokenMintCount).toBe(2);+ expect(requests[stage]).toBe(2);+ expect(toolExecutions).toBe(0);+ });++ for (const status of [403, 500, 503]) {+ test(`${stage}: HTTP ${status} is terminal and preserves status`, async () => {+ statusFor = current => current === stage ? status : undefined;+ await expect(callRemoteTool(makeConfig(), 'write_example')).rejects.toMatchObject({+ reason: 'network', detail: { status },+ });+ expect(tokenMintCount).toBe(1);+ expect(requests[stage]).toBe(1);+ expect(toolExecutions).toBe(0);+ });+ }+ }++ for (const text of ['client abc401def may not write', 'unauthorized operation', 'invalid_token is a field name']) {+ test(`application error is never retried: ${text}`, async () => {+ mcpResponseFor = () => ({+ isError: true,+ content: [{ type: 'text', text: JSON.stringify({ error: 'permission_denied', message: text }) }],+ });+ await expect(callRemoteTool(makeConfig(), 'write_example')).rejects.toMatchObject({+ reason: 'tool_error', detail: { code: 'permission_denied' },+ });+ expect(tokenMintCount).toBe(1);+ expect(toolExecutions).toBe(1);+ });+ }++ test('application error after a genuine refresh remains a tool error', async () => {+ statusFor = (stage, attempt) => stage === 'tools/call' && attempt === 1 ? 401 : undefined;+ mcpResponseFor = () => ({ isError: true, content: [{ type: 'text', text: 'unauthorized 401 operation' }] });+ await expect(callRemoteTool(makeConfig(), 'write_example')).rejects.toMatchObject({ reason: 'tool_error' });+ expect(tokenMintCount).toBe(2);+ expect(toolExecutions).toBe(1);+ });++ test('rejected token refresh stops before a second tool request', async () => {+ statusFor = (stage, attempt) => stage === 'tools/call' ? 401 : stage === 'token' && attempt === 2 ? 401 : undefined;+ await expect(callRemoteTool(makeConfig(), 'write_example')).rejects.toMatchObject({ reason: 'auth_after_refresh', detail: { status: 401 } });+ expect(tokenMintCount).toBe(2);+ expect(requests['tools/call']).toBe(1);+ expect(toolExecutions).toBe(0);+ });+});- // Easier path: install a once-only 401 on /mcp by setting mcpStatusOverride- // for one request; we need a counter. Use a flag.- let overrideUsed = false;- const realServer = server;- void realServer;- mcpStatusOverride = null;- // Wrap mcpResponseFor with a one-shot rejector — but the override is a- // status-line mechanism, not a body mechanism. Use a small hack: make- // the next /mcp request return a tool-error envelope that the client- // interprets as 401-equivalent. Actually the SDK throws on 401 status,- // so we need a real 401. Use mcpStatusOverride for one request.- // For test simplicity: expect that calling with stale-cached-token-then-- // 401 flow will re-mint. Achieve by setting tokenStatus to a failing- // value AFTER first success, then restoring. Skipped for this case;- // covered indirectly by the cache-reuse test above.-- // Instead, assert that the cache invalidation API works: clear cache,- // call again, expect new token.- _clearMcpClientTokenCache();- await callRemoteTool(makeConfig(), 'after_clear', {});+function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>(done => { resolve = done; });+ return { promise, resolve };+}++async function bounded<T>(promise: Promise<T>): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ promise,+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('fixture did not settle')), 2_000); }),+ ]);+ } finally {+ clearTimeout(timer);+ }+}++describe('callRemoteTool — cancellation across every network stage', () => {+ test('the original call deadline also bounds token refresh', async () => {+ statusFor = stage => stage === 'tools/call' ? 401 : undefined;+ hangingStage = 'token';+ hangFromAttempt = 2;+ const closed = deferred();+ onHangClosed = closed.resolve;+ await expect(callRemoteTool(makeConfig(), 'write_example', {}, { timeoutMs: 200 })).rejects.toMatchObject({+ reason: 'network', detail: { kind: 'timeout' },+ });+ await bounded(closed.promise);expect(tokenMintCount).toBe(2);+ expect(requests['tools/call']).toBe(1);+ expect(toolExecutions).toBe(0);});++ for (const stage of ['discovery', 'token', 'initialize', 'notifications/initialized', 'tools/call'] as const) {+ for (const cancel of ['timeout', 'external'] as const) {+ test(`${cancel} closes a hanging ${stage} request`, async () => {+ hangingStage = stage;+ const started = deferred();+ const closed = deferred();+ onHang = started.resolve;+ onHangClosed = closed.resolve;+ const controller = new AbortController();+ const pending = callRemoteTool(makeConfig(), 'write_example', {}, {+ ...(cancel === 'timeout' ? { timeoutMs: 200 } : { signal: controller.signal }),+ });+ const outcome = pending.then(value => ({ value }), error => ({ error }));+ await bounded(started.promise);+ if (cancel === 'external') controller.abort(new Error('caller stopped'));+ expect(await bounded(outcome)).toMatchObject({+ error: { reason: 'network', detail: { kind: cancel === 'timeout' ? 'timeout' : 'aborted' } },+ });+ await bounded(closed.promise);+ expect(requests[stage]).toBe(1);+ expect(tokenMintCount).toBe(stage === 'discovery' ? 0 : 1);+ expect(toolExecutions).toBe(0);+ });+ }+ }++ for (const stage of ['discovery', 'token', 'initialize', 'tools/call'] as const) {+ test(`timeout closes a partial JSON response at ${stage}`, async () => {+ hangingStage = stage;+ hangAfterHeaders = true;+ const closed = deferred();+ onHangClosed = closed.resolve;+ await expect(callRemoteTool(makeConfig(), 'write_example', {}, { timeoutMs: 200 })).rejects.toMatchObject({+ reason: 'network', detail: { kind: 'timeout' },+ });+ await bounded(closed.promise);+ expect(requests[stage]).toBe(1);+ expect(toolExecutions).toBe(0);+ });+ }++ test('already-aborted calls never contact discovery or MCP', async () => {+ const controller = new AbortController();+ controller.abort();+ await expect(callRemoteTool(makeConfig(), 'write_example', {}, { signal: controller.signal })).rejects.toMatchObject({+ reason: 'network', detail: { kind: 'aborted' },+ });+ expect(requests).toEqual({});+ expect(tokenMintCount).toBe(0);+ });++ for (const stage of ['discovery', 'token'] as const) {+ test(`${stage} keeps its own timeout cap when no call-wide timeout is set`, async () => {+ hangingStage = stage;+ const closed = deferred();+ onHangClosed = closed.resolve;+ const base = `http://127.0.0.1:${port}`;+ const result = stage === 'discovery'+ ? await discoverOAuth(base, { timeoutMs: 30 })+ : await mintClientCredentialsToken(`${base}/token`, 'cid', 'csecret', { timeoutMs: 30 });+ expect(result).toMatchObject({ ok: false, reason: 'network', kind: 'timeout' });+ await bounded(closed.promise);+ });+ }});describe('callRemoteTool — error surfaces', () => {+ test('an unreachable MCP transport is terminal after one token mint', async () => {+ const config = makeConfig();+ config.remote_mcp!.mcp_url = 'http://127.0.0.1:1/mcp';+ await expect(callRemoteTool(config, 'write_example')).rejects.toMatchObject({+ reason: 'network', detail: { kind: 'unreachable' },+ });+ expect(tokenMintCount).toBe(1);+ expect(toolExecutions).toBe(0);+ });+test('config has no remote_mcp → throws RemoteMcpError(config)', async () => {await expect(callRemoteTool({ engine: 'postgres' }, 'foo', {})).rejects.toThrow(RemoteMcpError);});diff --git a/test/mcp-eval-capture.test.ts b/test/mcp-eval-capture.test.tsindex f5a96174af..34387ca16c 100644--- a/test/mcp-eval-capture.test.ts+++ b/test/mcp-eval-capture.test.ts@@ -20,7 +20,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operations } from '../src/core/operations.ts';import type { OperationContext } from '../src/core/operations.ts';import type { GBrainConfig } from '../src/core/config.ts';-import type { PageInput } from '../src/core/types.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';let engine: PGLiteEngine;const savedKey = process.env.OPENAI_API_KEY;@@ -30,39 +31,19 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- const page: PageInput = {- type: 'person',- title: 'Alice Example',- compiled_truth: 'Alice Example for op-layer capture tests.',- };- await engine.putPage('people/alice-example', page);await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('testsrc', 'Test Source') ON CONFLICT DO NOTHING`,);- await engine.putPage('notes/source-override-default', {- type: 'note',- title: 'Default Source Override',- compiled_truth: 'sourceoverrideunique belongs to the default source.',- });- await engine.upsertChunks('notes/source-override-default', [- {- chunk_index: 0,- chunk_text: 'sourceoverrideunique belongs to the default source.',- chunk_source: 'compiled_truth',- },- ]);- await engine.putPage('notes/source-override-testsrc', {- type: 'note',- title: 'Test Source Override',- compiled_truth: 'sourceoverrideunique belongs to the explicit source.',- }, { sourceId: 'testsrc' });- await engine.upsertChunks('notes/source-override-testsrc', [- {- chunk_index: 0,- chunk_text: 'sourceoverrideunique belongs to the explicit source.',- chunk_source: 'compiled_truth',- },- ], { sourceId: 'testsrc' });+ for (const [slug, sourceId, type, title, body] of [+ ['people/alice-example', 'default', 'person', 'Alice Example', 'Alice Example for op-layer capture tests.'],+ ['notes/source-override-default', 'default', 'note', 'Default Source Override', 'sourceoverrideunique belongs to the default source.'],+ ['notes/source-override-testsrc', 'testsrc', 'note', 'Test Source Override', 'sourceoverrideunique belongs to the explicit source.'],+ ] as const) {+ const result = await importFromContent(engine, slug,+ serializeMarkdown({}, body, '', { type, title, tags: [] }),+ { sourceId, noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');+ }});afterAll(async () => {diff --git a/test/memory-verbs-conformance.test.ts b/test/memory-verbs-conformance.test.tsindex 90cfc8881a..3fda689fca 100644--- a/test/memory-verbs-conformance.test.ts+++ b/test/memory-verbs-conformance.test.ts@@ -52,11 +52,13 @@ import {} from '../src/core/ai/gateway.ts';import { __setUsageLogPathForTests } from '../src/core/verbs/usage-log.ts';import { emptyHome, withEnv } from './helpers/with-env.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';let engine: PGLiteEngine;let home: string;beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });// Sidecar writes go to a temp file via the test seam — no global env mutation.home = mkdtempSync(join(tmpdir(), 'gbrain-verbs-test-'));__setUsageLogPathForTests(join(home, 'usage.jsonl'));@@ -82,6 +84,10 @@ afterAll(async () => {beforeEach(async () => {await resetPgliteState(engine);+ // This suite's default contract is keyless. A previous file (or one of the+ // deterministic-embedder cases below) must not leave fake credentials active+ // after the transport seam is cleared. Individual cases opt in explicitly.+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });__setChatTransportForTests(null);__setEmbedTransportForTests(null);});diff --git a/test/operator-env-preload.test.ts b/test/operator-env-preload.test.tsindex 4dd1fcb2b3..c11cdbb1ae 100644--- a/test/operator-env-preload.test.ts+++ b/test/operator-env-preload.test.ts@@ -109,6 +109,9 @@ describe('operator-env-preload (#4023)', () => {const probed = ['GBRAIN_MODEL_DISCOVERY','GBRAIN_PGLITE_SNAPSHOT',+ 'GBRAIN_PGBOUNCER_URL',+ 'GBRAIN_PGBOUNCER_DIRECT_URL',+ 'GBRAIN_CI_REQUIRE_PGBOUNCER','GBRAIN_COMPILED_BIN','GBRAIN_TEST_SENTINEL','GBRAIN_CI_PG_PORT',@@ -120,6 +123,9 @@ describe('operator-env-preload (#4023)', () => {// preload's own default of 'off' when the var is absent.GBRAIN_MODEL_DISCOVERY: '1',GBRAIN_PGLITE_SNAPSHOT: 'probe-snapshot.tar',+ GBRAIN_PGBOUNCER_URL: 'postgresql://pooler.example/gbrain_test',+ GBRAIN_PGBOUNCER_DIRECT_URL: 'postgresql://direct.example/gbrain_test',+ GBRAIN_CI_REQUIRE_PGBOUNCER: '1',GBRAIN_COMPILED_BIN: '/probe/bin/gbrain',GBRAIN_TEST_SENTINEL: 'kept',GBRAIN_CI_PG_PORT: '5434',diff --git a/test/orphans-private-aggregate.test.ts b/test/orphans-private-aggregate.test.tsnew file mode 100644index 0000000000..d73083eb31--- /dev/null+++ b/test/orphans-private-aggregate.test.ts@@ -0,0 +1,106 @@+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 type { OrphanResult } from '../src/commands/orphans.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++const [A, B, FOREIGN] = ['orphan-public-a', 'orphan-public-b', 'orphan-foreign'];+const PRIVATE = 'PRIVATE_ORPHAN_AGGREGATE_CANARY';+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++async function page(slug: string, sourceId: string, hidden = false) {+ return engine.putPage(slug, {+ type: 'note', title: hidden ? PRIVATE : slug,+ compiled_truth: hidden ? PRIVATE : 'Public orphan fixture.',+ frontmatter: { visibility: hidden ? 'private' : 'world' },+ }, { sourceId });+}++beforeEach(async () => {+ await resetPgliteState(engine);+ for (const source of [A, B, FOREIGN]) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [source]);+ }+ await page('notes/shared-example', A);+ await page('templates/public-example', A); // Excluded from linkable pages by default.+ await page('notes/second-example', B);+ await page('notes/foreign-example', FOREIGN);+});++function context(remote: boolean | undefined, sourceId: string, allowedSources?: string[]): OperationContext {+ return {+ engine, config: { engine: 'pglite' },+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false, remote: remote as boolean, sourceId,+ ...(allowedSources !== undefined ? {+ auth: { token: 'fixture', clientId: 'orphan-reader-example', scopes: ['read'], allowedSources },+ } : {}),+ };+}++async function read(ctx: OperationContext, includePseudo = false): Promise<OrphanResult> {+ return operationsByName.find_orphans.handler(ctx, { include_pseudo: includePseudo }) as Promise<OrphanResult>;+}++describe('orphan aggregate privacy through the operation boundary', () => {+ for (const remote of [true, undefined]) {+ for (const scope of [+ { name: 'scalar', sourceId: A, allowedSources: undefined, publicPages: 2, localPages: 4 },+ { name: 'federated grant overrides scalar', sourceId: FOREIGN, allowedSources: [A, B], publicPages: 3, localPages: 7 },+ { name: 'empty grant falls back to scalar', sourceId: A, allowedSources: [], publicPages: 2, localPages: 4 },+ ]) {+ test(`remote=${String(remote)}, ${scope.name}: private mutations cannot change totals or denominators`, async () => {+ const ctx = context(remote, scope.sourceId, scope.allowedSources);+ const before = await read(ctx);+ const beforeWithPseudo = await read(ctx, true);+ expect(before).toMatchObject({+ total_pages: scope.publicPages, total_linkable: scope.publicPages - 1,+ total_orphans: scope.publicPages - 1, excluded: 1,+ });+ expect(before.orphans.map(row => row.slug)).toContain('notes/shared-example');+ expect(beforeWithPseudo).toMatchObject({+ total_pages: scope.publicPages, total_linkable: scope.publicPages,+ total_orphans: scope.publicPages, excluded: 0,+ });++ const hidden = await page('notes/private-example', A, true);+ await page('templates/private-example', A, true);+ // A public namesake cannot authorize the private row in the other source.+ await page('notes/shared-example', B, true);+ await page('notes/private-second-example', B, true);+ await page('notes/private-foreign-example', FOREIGN, true);+ expect(await read(ctx)).toEqual(before);+ expect(await read(ctx, true)).toEqual(beforeWithPseudo);+ expect(JSON.stringify(await read(ctx))).not.toContain(PRIVATE);++ // Both a hidden body edit and removal must remain unobservable in the+ // separately computed totals, even though local readers see the rows.+ await engine.executeRaw('UPDATE pages SET title = $1 WHERE id = $2', [`${PRIVATE}_EDITED`, hidden.id]);+ expect(await read(ctx)).toEqual(before);+ const localCtx = context(false, scope.sourceId, scope.allowedSources);+ const local = await read(localCtx);+ expect(local).toMatchObject({+ total_pages: scope.localPages, total_linkable: scope.localPages - 2,+ total_orphans: scope.localPages - 2, excluded: 2,+ });+ expect(JSON.stringify(local.orphans)).toContain(PRIVATE);+ expect((await read(localCtx, true)).total_linkable).toBe(scope.localPages);++ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [hidden.id]);+ expect(await read(ctx)).toEqual(before);+ expect(await read(ctx, true)).toEqual(beforeWithPseudo);+ expect((await read(localCtx)).total_pages).toBe(scope.localPages - 1);+ });+ }+ }+});diff --git a/test/private-visibility.test.ts b/test/private-visibility.test.tsindex 6c1d4c8288..fe8f784875 100644--- a/test/private-visibility.test.ts+++ b/test/private-visibility.test.ts@@ -26,6 +26,8 @@ import {import { buildEntityCard } from '../src/core/verbs/entity-card.ts';import { operationsByName } from '../src/core/operations.ts';import { withEnv } from './helpers/with-env.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';let engine: PGLiteEngine;@@ -33,37 +35,18 @@ beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- await engine.putPage('notes/world-page', {- title: 'Zebra Widget World',- type: 'concept',- frontmatter: { visibility: 'world' },- compiled_truth: 'zebra widget public knowledge body',- timeline: '',- });- await engine.putPage('notes/private-page', {- title: 'Zebra Widget Private',- type: 'concept',- frontmatter: { visibility: 'private' },- compiled_truth: 'zebra widget secret private knowledge body',- timeline: '',- });- // No visibility key at all → defaults to world (visible everywhere).- await engine.putPage('notes/unmarked-page', {- title: 'Zebra Widget Unmarked',- type: 'concept',- frontmatter: {},- compiled_truth: 'zebra widget unmarked knowledge body',- timeline: '',- });- // putPage doesn't chunk; the keyword/chunk arms search content_chunks.- for (const [slug, body] of [- ['notes/world-page', 'zebra widget public knowledge body'],- ['notes/private-page', 'zebra widget secret private knowledge body'],- ['notes/unmarked-page', 'zebra widget unmarked knowledge body'],+ // Real imports certify current chunks; these tests exercise page visibility,+ // independently of the separate block on old, unrebuilt chunk indexes.+ for (const [slug, title, body, frontmatter] of [+ ['notes/world-page', 'Zebra Widget World', 'zebra widget public knowledge body', { visibility: 'world' }],+ ['notes/private-page', 'Zebra Widget Private', 'zebra widget secret private knowledge body', { visibility: 'private' }],+ // No visibility key at all → defaults to world (visible everywhere).+ ['notes/unmarked-page', 'Zebra Widget Unmarked', 'zebra widget unmarked knowledge body', {}],] as const) {- await engine.upsertChunks(slug, [- { chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' },- ]);+ const result = await importFromContent(engine, slug,+ serializeMarkdown(frontmatter, body, '', { type: 'concept', title, tags: [] }),+ { noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');}});diff --git a/test/provider-fixture-env.test.ts b/test/provider-fixture-env.test.tsnew file mode 100644index 0000000000..3a4ed74a00--- /dev/null+++ b/test/provider-fixture-env.test.ts@@ -0,0 +1,135 @@+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import { listRecipes } from '../src/core/ai/recipes/index.ts';+import { keylessBrainEnv, PROVIDER_ENV_KEYS } from './helpers/provider-env.ts';+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from './helpers/fixture-diagnostics.ts';++describe('keyless fixture environment', () => {+ test('covers every recipe credential and compatibility endpoint', () => {+ const registered = listRecipes().flatMap(recipe => [+ ...(recipe.auth_env?.required ?? []), ...(recipe.auth_env?.optional ?? []),+ ]);+ const required = new Set([...registered, 'GEMINI_API_KEY', 'OPENAI_BASE_URL', 'ANTHROPIC_BASE_URL']);+ expect([...required].filter(key => !PROVIDER_ENV_KEYS.includes(key as typeof PROVIDER_ENV_KEYS[number]))).toEqual([]);+ });++ test.each([...PROVIDER_ENV_KEYS])('removes inherited %s without touching its parent', key => {+ const parent = { [key]: 'fixture-value', UNRELATED_API_KEY: 'preserve', PATH: '/fixture/bin' };+ const env = keylessBrainEnv(parent, '/fixture/home');+ expect(env[key]).toBeUndefined();+ expect(parent[key]).toBe('fixture-value');+ expect(env.UNRELATED_API_KEY).toBe('preserve');+ expect(env.PATH).toBe('/fixture/bin');+ expect(env.HOME).toBe('/fixture/home');+ expect(env.GBRAIN_HOME).toBe('/fixture/home');+ });++ test('explicit overrides are last and database policy belongs to the fixture', () => {+ const parent = { OPENAI_API_KEY: 'ambient', DATABASE_URL: 'test-url', GBRAIN_DATABASE_URL: 'other-url' };+ const env = keylessBrainEnv(parent, '/fixture/home', { OPENAI_API_KEY: 'explicit-test-key', GBRAIN_DATABASE_URL: undefined });+ expect(env.OPENAI_API_KEY).toBe('explicit-test-key');+ expect(env.DATABASE_URL).toBe('test-url');+ expect(env.GBRAIN_DATABASE_URL).toBeUndefined();+ expect(parent.GBRAIN_DATABASE_URL).toBe('other-url');+ });++ test('no-env-file prevents cwd .env from restoring stripped provider state in children', () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-provider-env-'));+ try {+ writeFileSync(join(home, '.env'), 'OPENAI_API_KEY=synthetic-cwd-key\n');+ const env = keylessBrainEnv(process.env, home, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined });+ const probe = 'process.stdout.write(String(Boolean(process.env.OPENAI_API_KEY)))';+ const ordinary = spawnSync(process.execPath, ['--eval', probe], { cwd: home, env, encoding: 'utf8' });+ const isolated = spawnSync(process.execPath, ['--no-env-file', '--eval', probe], { cwd: home, env, encoding: 'utf8' });+ expect(ordinary.status).toBe(0);+ expect(ordinary.stdout).toBe('true');+ expect(isolated.status).toBe(0);+ expect(isolated.stdout).toBe('false');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('preload strips all provider state by default and honors the explicit live-lane opt-in', () => {+ const preload = join(import.meta.dir, 'helpers/provider-keys-preload.ts');+ const probe = `await import(${JSON.stringify(preload)}); process.stdout.write(JSON.stringify(${JSON.stringify(PROVIDER_ENV_KEYS)}.map(key => Boolean(process.env[key]))))`;+ const synthetic = Object.fromEntries(PROVIDER_ENV_KEYS.map(key => [key, 'synthetic-fixture-value']));+ for (const keep of ['0', '1']) {+ const result = spawnSync(process.execPath, ['--no-env-file', '--eval', probe], {+ cwd: tmpdir(), encoding: 'utf8',+ env: { ...process.env, ...synthetic, GBRAIN_TEST_KEEP_PROVIDER_KEYS: keep },+ });+ expect(result.status).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual(PROVIDER_ENV_KEYS.map(() => keep === '1'));+ }+ });+});++describe('fixture failure diagnostics', () => {+ test('keeps operation, exit and error code while redacting credentials before truncation', () => {+ const detail = 'code=permission_denied gbrain_cs_syntheticsecret Bearer synthetic-bearer ' ++ 'client_secret=synthetic-secret {"access_token":"synthetic-token"} explicit-fixture-secret sk-synthetic-provider';+ const diagnostic = cliDiagnostic('put', { exitCode: 1, stdout: detail, stderr: '' }, ['explicit-fixture-secret']);+ expect(diagnostic).toContain('put: exit=1');+ expect(diagnostic).toContain('code=permission_denied');+ for (const secret of ['syntheticsecret', 'synthetic-bearer', 'synthetic-secret', 'synthetic-token', 'explicit-fixture-secret', 'sk-synthetic-provider']) {+ expect(diagnostic).not.toContain(secret);+ }+ const bounded = fixtureDiagnostic('remember', 'x'.repeat(5000));+ expect(bounded.length).toBeLessThanOrEqual(2000);+ expect(bounded).toContain('[truncated]');+ });++ test('reports tool error text without serializing successful result data', () => {+ expect(toolDiagnostic('remember', { isError: true, content: [{ type: 'text', text: '{"code":"invalid_dimension","error":"expected 1536"}' }] })).toContain('invalid_dimension');+ expect(toolDiagnostic('remember', { content: [{ type: 'text', text: 'private-success-data' }] })).toBe('remember');+ });++ test('warning stderr cannot hide the structured stdout error or crowd out either stream', () => {+ const secret = 'fixture-secret-canary';+ const diagnostic = cliDiagnostic('capture', {+ exitCode: 1,+ stderr: `WARNING_STDERR Bearer warning-token ${secret} ${'w'.repeat(5000)}`,+ stdout: JSON.stringify({ error: 'permission_denied', message: `OPERATION_STDOUT ${secret}`, access_token: 'stdout-token' }),+ }, [secret]);+ expect(diagnostic.startsWith('capture: exit=1 code=permission_denied\n')).toBe(true);+ expect(diagnostic).toContain('stderr:\nWARNING_STDERR');+ expect(diagnostic).toContain('stdout:\n');+ expect(diagnostic).toContain('OPERATION_STDOUT');+ expect(diagnostic).toContain('[truncated]');+ expect(diagnostic.length).toBeLessThanOrEqual(2000);+ for (const canary of [secret, 'warning-token', 'stdout-token']) expect(diagnostic).not.toContain(canary);+ });++ test('structured codes survive long stdout details and JSON-line notices', () => {+ const diagnostic = cliDiagnostic('remember', {+ exitCode: 2,+ stderr: 'stderr warning',+ stdout: `stdout notice\n${JSON.stringify({ error: { message: 'x'.repeat(5000), code: 'invalid_dimension' } })}`,+ });+ expect(diagnostic.startsWith('remember: exit=2 code=invalid_dimension\n')).toBe(true);+ expect(diagnostic).toContain('stderr warning');+ expect(diagnostic).toContain('stdout notice');+ expect(diagnostic).toContain('[truncated]');+ expect(diagnostic.length).toBeLessThanOrEqual(2000);+ });++ test('tool error codes precede long warning content and redact structured secrets', () => {+ const diagnostic = toolDiagnostic('recall', {+ isError: true,+ content: [+ { type: 'text', text: `warning tool-secret-canary ${'x'.repeat(5000)}` },+ { type: 'text', text: JSON.stringify({ error: 'missing_scope', message: 'Requires read', client_secret: 'tool-client-secret' }) },+ ],+ }, ['tool-secret-canary']);+ expect(diagnostic.startsWith('recall: code=missing_scope\n')).toBe(true);+ expect(diagnostic).toContain('[truncated]');+ expect(diagnostic.length).toBeLessThanOrEqual(2000);+ expect(diagnostic).not.toContain('tool-secret-canary');+ expect(diagnostic).not.toContain('tool-client-secret');+ expect(toolDiagnostic('recall', { error: { code: -32603, message: 'Internal error' } })).toStartWith('recall: code=-32603\n');+ });+});diff --git a/test/query-image-mode-limit.serial.test.ts b/test/query-image-mode-limit.serial.test.tsindex 725c04ffe9..7b7e52bd48 100644--- a/test/query-image-mode-limit.serial.test.ts+++ b/test/query-image-mode-limit.serial.test.ts@@ -8,20 +8,37 @@// caller's `mode` param must never escalate cost/result-count).import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, 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 { importImageFile } from '../src/core/import-file.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { operations as OPERATIONS } from '../src/core/operations.ts';let engine: PGLiteEngine;+let fixtureDir: string;+let imagePath: string;beforeAll(async () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();+ fixtureDir = mkdtempSync(join(tmpdir(), 'gbrain-image-mode-limit-'));+ imagePath = join(fixtureDir, 'clean.png');+ // A clean 1x1 PNG exercises the real image import without external assets.+ writeFileSync(imagePath, Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aV9kAAAAASUVORK5CYII=',+ 'base64',+ ));});afterAll(async () => {- await engine.disconnect();+ try {+ await engine.disconnect();+ } finally {+ if (fixtureDir) rmSync(fixtureDir, { recursive: true, force: true });+ }});beforeEach(async () => {@@ -39,23 +56,17 @@ function fakeImage1024(seed: number): Float32Array {}async function seedImagePages(count: number): Promise<void> {+ let imageIndex = 0;+ mock.module('../src/core/ai/gateway.ts', () => ({+ // Small seed spread so every page is a plausible near-neighbor —+ // the point of these tests is counting how many come back, not+ // ranking correctness (covered by query-image-flag.serial.test.ts).+ embedMultimodal: async () => [fakeImage1024(imageIndex++ * 0.01)],+ }));for (let i = 0; i < count; i++) {- const slug = `photos/img-${i}`;- await engine.putPage(slug, {- type: 'image', page_kind: 'image', title: slug, compiled_truth: '', timeline: '',- });- await engine.upsertChunks(slug, [- {- chunk_index: 0,- chunk_text: slug,- chunk_source: 'image_asset',- // Small seed spread so every page is a plausible near-neighbor —- // the point of these tests is counting how many come back, not- // ranking correctness (covered by query-image-flag.serial.test.ts).- embedding_image: fakeImage1024(i * 0.01),- modality: 'image',- },- ]);+ // Remote queries require the completed index produced by image import.+ const result = await importImageFile(engine, imagePath, `photos/img-${i}.png`);+ expect(result.status).toBe('imported');}}diff --git a/test/recall-federated-search-scope.test.ts b/test/recall-federated-search-scope.test.tsindex a28feca0f8..aac7312f5a 100644--- a/test/recall-federated-search-scope.test.ts+++ b/test/recall-federated-search-scope.test.ts@@ -22,6 +22,8 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';import {federatedSearchScope,sourceScopeOpts,@@ -72,16 +74,10 @@ beforeAll(async () => {['privsrc/topic', 'privsrc', 'privsrc'],];for (const [slug, sourceId, where] of pages) {- await engine.putPage(- slug,- { type: 'note', title: `Topic in ${where}`, compiled_truth: `the zebra telescope in ${where}`, frontmatter: {} },- { sourceId },- );- await engine.upsertChunks(- slug,- [{ chunk_index: 0, chunk_text: `the zebra telescope in ${where}`, chunk_source: 'compiled_truth' }],- { sourceId },- );+ const result = await importFromContent(engine, slug,+ serializeMarkdown({}, `the zebra telescope in ${where}`, '', { type: 'note', title: `Topic in ${where}`, tags: [] }),+ { sourceId, noEmbed: true, forceRechunk: true });+ expect(result.status).toBe('imported');}// Keyword-only search path: no embedding provider needed in tests.await engine.setConfig('search.mcp_keyword_only', 'true');diff --git a/test/reindex-code.test.ts b/test/reindex-code.test.tsindex c585eb6bfc..e4961d9033 100644--- a/test/reindex-code.test.ts+++ b/test/reindex-code.test.ts@@ -15,6 +15,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runReindexCode } from '../src/commands/reindex-code.ts';import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';describe('Layer 13 E2 — runReindexCode', () => {let engine: PGLiteEngine;@@ -128,4 +129,28 @@ describe('Layer 13 E2 — runReindexCode', () => {});expect(result.codePages).toBe(3);});++ test('forced CPU-only code rebuild removes legacy private fragments and restores sealed public chunks', async () => {+ const sourceId = 'code-seal-example';+ const slug = 'src-protected-example-ts';+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [sourceId]);+ try {+ const body = "export const publicExample = 'publiccodeseal';\n<!--- gbrain:takes:begin -->\nexport const hiddenExample = 'PRIVATE_CODE_CANARY';\n<!--- gbrain:takes:end -->";+ const page = await engine.putPage(slug, {+ type: 'code', page_kind: 'code', title: 'src/protected-example.ts', compiled_truth: body,+ frontmatter: { language: 'typescript', file: 'src/protected-example.ts' },+ }, { sourceId });+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'PRIVATE_CODE_CANARY' }], { sourceId });+ expect(await engine.getChunks(slug, { sourceId, requireSafeChunks: true })).toEqual([]);+ const result = await runReindexCode(engine, { sourceId, force: true, noEmbed: true });+ expect(result).toMatchObject({ reindexed: 1, failed: 0 });+ const [version] = await engine.executeRaw<{ chunker_version: number }>('SELECT chunker_version FROM pages WHERE id = $1', [page.id]);+ expect(Number(version.chunker_version)).toBe(MARKDOWN_CHUNKER_VERSION);+ const chunks = await engine.getChunks(slug, { sourceId, requireSafeChunks: true });+ expect(chunks.length).toBeGreaterThan(0);+ expect(JSON.stringify(chunks)).toContain('publiccodeseal');+ expect(JSON.stringify(chunks)).not.toContain('PRIVATE_CODE_CANARY');+ expect(chunks.every(chunk => chunk.embedding_is_null)).toBe(true);+ } finally { await engine.executeRaw('DELETE FROM sources WHERE id = $1', [sourceId]); }+ });});diff --git a/test/remote-body.test.ts b/test/remote-body.test.tsnew file mode 100644index 0000000000..7cf89362e3--- /dev/null+++ b/test/remote-body.test.ts@@ -0,0 +1,82 @@+import { describe, expect, test } from 'bun:test';+import { sanitizeRemoteBody } from '../src/core/remote-body.ts';+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, renderFactsTable } from '../src/core/facts-fence.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../src/core/takes-fence.ts';++function facts(world: string, privateClaim: string): string {+ return renderFactsTable([+ { rowNum: 1, claim: world, kind: 'fact', confidence: 1, visibility: 'world', notability: 'high', active: true },+ { rowNum: 2, claim: privateClaim, kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', active: true },+ ]);+}++describe('strict remote body sanitizer', () => {+ test('ordinary Markdown is unchanged', () => {+ const body = '# Public page\n\nOrdinary prose with `code` and a [link](https://example.com).\n';+ expect(sanitizeRemoteBody(body)).toBe(body);+ expect(sanitizeRemoteBody('')).toBe('');+ });++ test('closing markers outside protected blocks remain ordinary text', () => {+ const body = `before\n${FACTS_FENCE_END}\n${TAKES_FENCE_END}\nafter`;+ expect(sanitizeRemoteBody(body)).toBe(body);+ });++ test('many protected blocks do not repeatedly scan the remaining body', () => {+ // Under 1 MB (the import cap is 5 MB). Repeated searches for the absent+ // Facts markers took seconds here; a forward scan has ample headroom.+ const blockCount = 16_000;+ const body = `${TAKES_FENCE_BEGIN}\nx\n${TAKES_FENCE_END}\n`.repeat(blockCount);+ const start = performance.now();+ const result = sanitizeRemoteBody(body);+ const elapsedMs = performance.now() - start;+ expect(result).toBe('\n'.repeat(blockCount));+ expect(elapsedMs).toBeLessThan(1_000);+ });++ test('every facts fence keeps world rows and removes private rows', () => {+ const body = `before\n${facts('WORLD_ONE', 'PRIVATE_ONE')}\nbetween\n${facts('WORLD_TWO', 'PRIVATE_TWO')}\nafter`;+ const result = sanitizeRemoteBody(body);+ for (const visible of ['before', 'between', 'after', 'WORLD_ONE', 'WORLD_TWO']) expect(result).toContain(visible);+ for (const hidden of ['PRIVATE_ONE', 'PRIVATE_TWO']) expect(result).not.toContain(hidden);+ expect(sanitizeRemoteBody(result)).toBe(result);+ });++ test('all takes fences disappear, including world-holder takes, alongside facts', () => {+ const take = `${TAKES_FENCE_BEGIN}\n| 1 | PRIVATE_TAKE | take | owner-example | 1 | | |\n${TAKES_FENCE_END}`;+ const worldTake = `${TAKES_FENCE_BEGIN}\n| 1 | WORLD_TAKE | fact | world | 1 | | |\n${TAKES_FENCE_END}`;+ const result = sanitizeRemoteBody(`before\n${take}\n${facts('WORLD_FACT', 'PRIVATE_FACT')}\n${worldTake}\nafter`);+ expect(result).toContain('WORLD_FACT');+ expect(result).toContain('before');+ expect(result).toContain('after');+ for (const hidden of ['PRIVATE_TAKE', 'WORLD_TAKE', 'PRIVATE_FACT', 'gbrain:takes']) expect(result).not.toContain(hidden);+ });++ for (const marker of [FACTS_FENCE_BEGIN, TAKES_FENCE_BEGIN]) {+ test(`unterminated ${marker} drops the protected tail`, () => {+ expect(sanitizeRemoteBody(`safe prefix\n${marker}\nPRIVATE_TAIL\notherwise ordinary suffix`)).toBe('safe prefix\n');+ });+ }++ for (const [outerStart, outerEnd] of [[FACTS_FENCE_BEGIN, FACTS_FENCE_END], [TAKES_FENCE_BEGIN, TAKES_FENCE_END]]) {+ for (const innerStart of [FACTS_FENCE_BEGIN, TAKES_FENCE_BEGIN]) {+ test(`nested ${innerStart} inside ${outerStart} drops the ambiguous tail`, () => {+ const body = `safe prefix\n${outerStart}\nPRIVATE_ONE\n${innerStart}\nPRIVATE_TWO\n${outerEnd}\nsuffix`;+ expect(sanitizeRemoteBody(body)).toBe('safe prefix\n');+ });+ }+ }++ test('an interleaved closing marker drops the ambiguous tail', () => {+ const body = `safe prefix\n${FACTS_FENCE_BEGIN}\nPRIVATE\n${TAKES_FENCE_END}\n${FACTS_FENCE_END}\nsuffix`;+ expect(sanitizeRemoteBody(body)).toBe('safe prefix\n');+ });++ test('a malformed facts block is omitted without echoing parser warnings', () => {+ const body = facts('WORLD_FACT', 'PRIVATE_FACT').replace('| private |', '| invalid-visibility |');+ const result = sanitizeRemoteBody(`before\n${body}\nafter`);+ expect(result).toBe('before\n\nafter');+ expect(result).not.toContain('PRIVATE_FACT');+ expect(result).not.toContain('invalid-visibility');+ });+});diff --git a/test/salience-source-scope.test.ts b/test/salience-source-scope.test.tsindex ec02b9906b..e0a0bebb3c 100644--- a/test/salience-source-scope.test.ts+++ b/test/salience-source-scope.test.ts@@ -128,10 +128,8 @@ describe('find_anomalies source scoping', () => {describe('find_contradictions source scoping', () => {beforeEach(async () => {- // Page-level privacy fixture: an IN-SCOPE (alpha) endpoint that is- // `visibility: private`. The scope check alone would keep a finding- // touching it (the page exists in alpha); the #4352 world-visibility- // keep-list must drop it for remote callers.+ // Private in-scope content remains in the stored report. Only the+ // trusted, unscoped local control may inspect this historical payload.await engine.putPage('alpha/private-note', {type: 'note', title: 'Alpha Private', compiled_truth: 'alpha private content',frontmatter: { visibility: 'private' },@@ -170,70 +168,52 @@ describe('find_contradictions source scoping', () => {expect(touchesPrivate(res)).toBe(true);});- test('remote scalar scope alpha: only the alpha-alpha finding survives', async () => {- const res = await find_contradictions.handler(ctxOf({ sourceId: 'alpha' }), {}) as { contradictions: Array<{ a: { slug: string }; b: { slug: string } }> };- expect(res.contradictions.length).toBe(1);- expect(res.contradictions[0].a.slug).toBe('alpha/one');- expect(res.contradictions[0].b.slug).toBe('alpha/two');- assertNoBeta(res);- });-- test('federated grant [alpha]: identical isolation', async () => {- const ctx = ctxOf({ auth: { allowedSources: ['alpha'] } as any });- const res = await find_contradictions.handler(ctx, {}) as { contradictions: Array<{ a: { slug: string }; b: { slug: string } }> };- expect(res.contradictions.length).toBe(1);- assertNoBeta(res);- expect(touchesPrivate(res)).toBe(false);- });-- test('limit under-fill: fences run BEFORE the limit cutoff — droppable findings ahead of a visible one cannot starve it', async () => {- // A later run whose report orders a private-endpoint finding and a- // cross-boundary finding BEFORE the only visible finding. With limit=1,- // filtering AFTER the cutoff would keep the private finding (it IS in- // scope), hit the limit, then drop it in the visibility pass — returning- // 0 while total_in_run claims completeness. The fences must instead- // verify before counting, so the visible finding still surfaces.- const finding = (aSlug: string, bSlug: string) => ({- kind: 'direct', severity: 'high', axis: 'fact', confidence: 0.9,- a: { slug: aSlug, chunk_id: null, take_id: null },- b: { slug: bSlug, chunk_id: null, take_id: null },- resolution_kind: 'manual', resolution_command: '',+ // Stored text has no trustworthy snapshot provenance. Current endpoint+ // visibility cannot authorize old private content, so restricted readers+ // must receive an explicit unavailable result BEFORE loading any report.+ for (const [label, overrides] of [+ ['remote scalar', { sourceId: 'alpha' }],+ ['remote federated', { auth: { allowedSources: ['alpha'] } }],+ ['remote unscoped', {}],+ ['unset trust', { remote: undefined }],+ ['local scalar', { remote: false, sourceId: 'alpha' }],+ ['local federated', { remote: false, auth: { allowedSources: ['alpha'] } }],+ ['remote empty grant with scalar floor', { sourceId: 'alpha', auth: { allowedSources: [] } }],+ ['local empty grant with scalar floor', { remote: false, sourceId: 'alpha', auth: { allowedSources: [] } }],+ ] as const) {+ test(`${label}: reports unavailable before any database load`, async () => {+ const original = engine.loadContradictionsTrend;+ let loads = 0;+ engine.loadContradictionsTrend = async () => {+ loads++;+ throw new Error('Restricted callers must not load stored reports');+ };+ try {+ const res = await find_contradictions.handler(ctxOf(overrides as Partial<OperationContext>), { limit: 1, severity: 'high', slug: 'alpha/one' });+ expect(res).toEqual({+ contradictions: [],+ note: 'Stored contradiction reports are temporarily available only to trusted local callers without a source filter.',+ });+ expect(loads).toBe(0);+ } finally {+ engine.loadContradictionsTrend = original;+ }});- await engine.writeContradictionsRun({- run_id: 'fixture-run-underfill', judge_model: 'test', prompt_version: 'v1',- queries_evaluated: 3, queries_with_contradiction: 3, total_contradictions_flagged: 3,- wilson_ci_lower: 0, wilson_ci_upper: 1, judge_errors_total: 0,- cost_usd_total: 0, duration_ms: 1,- source_tier_breakdown: {},- report_json: {- per_query: [{- contradictions: [- finding('alpha/one', 'alpha/private-note'), // in scope, private — dropped by visibility- finding('alpha/one', 'beta/secret-one'), // cross-boundary — dropped by scope- finding('alpha/one', 'alpha/two'), // the visible finding, ordered LAST- ],- }],- },- });- const res = await find_contradictions.handler(ctxOf({ sourceId: 'alpha' }), { limit: 1 }) as {+ }++ test('trusted unscoped local retains filters, limits and full-run totals', async () => {+ const res = await find_contradictions.handler(localUnscoped(), { limit: 1, slug: 'alpha/one', severity: 'high' }) as {contradictions: Array<{ a: { slug: string }; b: { slug: string } }>; total_in_run: number;};- expect(res.contradictions.length).toBe(1);+ expect(res.contradictions).toHaveLength(1);expect(res.contradictions[0].a.slug).toBe('alpha/one');- expect(res.contradictions[0].b.slug).toBe('alpha/two');- expect(touchesPrivate(res)).toBe(false);+ expect(res.total_in_run).toBe(4);});- test('#4352: a visibility:private endpoint hides the finding from remote scoped callers; trusted local keeps it', async () => {- // Remote scalar caller scoped to alpha: the private-endpoint finding is- // IN scope (both pages exist in alpha) — the world-visibility keep-list- // is what drops it.- const remote = await find_contradictions.handler(ctxOf({ sourceId: 'alpha' }), {}) as { contradictions: Array<{ a: { slug: string }; b: { slug: string } }> };- expect(touchesPrivate(remote)).toBe(false);- // Trusted local caller, even SCOPED to alpha, still sees it (privacy- // enforcement is a remote-only posture; resolveExcludePrivatePages- // returns false for ctx.remote === false).- const localScoped = await find_contradictions.handler(ctxOf({ remote: false, sourceId: 'alpha' }), {}) as { contradictions: Array<{ a: { slug: string }; b: { slug: string } }> };- expect(touchesPrivate(localScoped)).toBe(true);+ test('an empty grant without a scalar remains a legitimate unscoped local context', async () => {+ const res = await find_contradictions.handler(ctxOf({ remote: false, auth: { allowedSources: [] } as any }), {}) as {+ contradictions: unknown[];+ };+ expect(res.contradictions).toHaveLength(4);});});diff --git a/test/scripts/ci-cache-hash.test.ts b/test/scripts/ci-cache-hash.test.tsdeleted file mode 100644index fbc876dab6..0000000000--- a/test/scripts/ci-cache-hash.test.ts+++ /dev/null@@ -1,480 +0,0 @@-/**- * ci-cache-hash.test.ts — adversarial coverage of the auto-cache hash.- *- * The cache key controls false-pass risk. If a test-affecting file is- * accidentally deny-listed (or a file change fails to invalidate the- * hash), broken code ships under a green CI check. This suite is the- * primary safety net.- *- * Strategy: each test spins up a synthetic git repo, copies the- * ci-cache-hash.sh script in, populates a small file set covering the- * deny-list edges, runs the script, modifies one file, runs again,- * asserts hash behavior.- *- * Critical invariants (the false-pass guards):- * - CLAUDE.md edit → DIFFERENT hash- * - AGENTS.md edit → DIFFERENT hash- * - skills/foo/SKILL.md edit → DIFFERENT hash- * - src/core/db.ts edit → DIFFERENT hash- * - test/foo.test.ts edit → DIFFERENT hash- *- * Safe deny-list invariants:- * - CHANGELOG.md edit → same hash- * - docs/guide.md edit → same hash- * - TODOS.md edit → same hash- * - LICENSE edit → same hash- *- * Policy-doc re-admissions (ALLOW_PATTERNS — must invalidate):- * - README.md edit → DIFFERENT hash (carries the bootstrap paste block; a- * paste-block edit must never ship under a cached green [C2])- * - BOOTSTRAP_FOR_AGENTS.md edit → DIFFERENT hash (same reason)- */--import { afterAll, beforeAll, describe, expect, it } from "bun:test";-import { execFileSync, spawnSync } from "node:child_process";-import {- cpSync,- mkdirSync,- mkdtempSync,- rmSync,- symlinkSync,- writeFileSync,-} from "node:fs";-import { tmpdir } from "node:os";-import { join, resolve } from "node:path";--const REPO_ROOT = resolve(import.meta.dir, "..", "..");-const SCRIPT_SRC = resolve(REPO_ROOT, "scripts/ci-cache-hash.sh");--interface Sandbox {- dir: string;- scriptPath: string;-}--function makeSandbox(files: Record<string, string>): Sandbox {- const dir = mkdtempSync(join(tmpdir(), "ci-cache-hash-"));- // Init git repo- execFileSync("git", ["init", "--quiet"], { cwd: dir });- execFileSync("git", ["config", "user.email", "[email protected]"], { cwd: dir });- execFileSync("git", ["config", "user.name", "Test"], { cwd: dir });-- // Copy script under scripts/ so cd "$(dirname "$0")/.." lands at sandbox root- mkdirSync(join(dir, "scripts"), { recursive: true });- cpSync(SCRIPT_SRC, join(dir, "scripts/ci-cache-hash.sh"));-- // Write each fixture file under its declared path- for (const [path, content] of Object.entries(files)) {- const abs = join(dir, path);- mkdirSync(resolve(abs, ".."), { recursive: true });- writeFileSync(abs, content);- }-- // Stage + commit so git ls-files returns them- execFileSync("git", ["add", "-A"], { cwd: dir });- execFileSync("git", ["commit", "--quiet", "-m", "fixture"], { cwd: dir });-- return { dir, scriptPath: join(dir, "scripts/ci-cache-hash.sh") };-}--function hash(s: Sandbox): string {- const r = spawnSync("bash", [s.scriptPath], {- cwd: s.dir,- encoding: "utf8",- });- if (r.status !== 0) {- throw new Error(`ci-cache-hash exit ${r.status}: ${r.stderr}`);- }- return r.stdout.trim();-}--function modify(s: Sandbox, path: string, content: string) {- writeFileSync(join(s.dir, path), content);- // The script reads `git ls-files -s` which reflects the INDEX, not- // the working tree. Stage + commit so the change is visible to the- // hash. This matches what CI sees on a checked-out PR (committed- // tree, not working tree).- execFileSync("git", ["add", path], { cwd: s.dir });- execFileSync("git", ["commit", "--quiet", "-m", `modify ${path}`], {- cwd: s.dir,- });-}--// ──────────────────────────────────────────────────────────────────────-// Baseline fixtures used across most cases.-// ──────────────────────────────────────────────────────────────────────-const BASELINE_FILES: Record<string, string> = {- "CHANGELOG.md": "# Changelog\n\n## [1.0.0]\n",- "TODOS.md": "- [ ] thing\n",- "README.md": "# Project\n",- "LICENSE": "MIT\n",- "CLAUDE.md": "# CLAUDE.md\n\nproject instructions\n",- "AGENTS.md": "# AGENTS.md\n\nopenclaw entry\n",- "package.json": '{"name":"test","version":"0.0.0"}\n',- "bun.lock": "lockfile-v1\n",- "tsconfig.json": '{"compilerOptions":{"strict":true}}\n',- "src/core/db.ts": "export const db = 1;\n",- "src/cli.ts": "console.log('hi');\n",- "test/foo.test.ts": "import {test} from 'bun:test';\ntest('x', () => {});\n",- "scripts/check-x.sh": "#!/bin/bash\necho ok\n",- ".github/workflows/test.yml": "name: Test\n",- "skills/foo/SKILL.md": "---\nname: foo\n---\nFoo skill\n",- "docs/guide.md": "# Guide\n",- "docs/sub/notes.md": "Notes\n",- "docs/raw.txt": "raw text\n",-};--describe("ci-cache-hash.sh — determinism", () => {- let sb: Sandbox;- beforeAll(() => {- sb = makeSandbox(BASELINE_FILES);- });- afterAll(() => {- if (sb) rmSync(sb.dir, { recursive: true, force: true });- });-- it("same tree → same hash (run twice)", () => {- const h1 = hash(sb);- const h2 = hash(sb);- expect(h1).toBe(h2);- expect(h1).toMatch(/^[0-9a-f]{16}$/);- });-- it("hash is 16-char lowercase hex", () => {- const h = hash(sb);- expect(h).toMatch(/^[0-9a-f]{16}$/);- });-});--describe("ci-cache-hash.sh — CRITICAL false-pass guards (must invalidate)", () => {- // Each test gets its own sandbox so modifications don't leak across cases.-- function withSandbox(test: (sb: Sandbox) => void) {- const sb = makeSandbox(BASELINE_FILES);- try {- test(sb);- } finally {- rmSync(sb.dir, { recursive: true, force: true });- }- }-- it("CLAUDE.md edit MUST change hash (8+ test files reference it)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "CLAUDE.md", "# CLAUDE.md\n\nNEW INSTRUCTIONS\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("AGENTS.md edit MUST change hash (resolver tests read it)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "AGENTS.md", "# AGENTS.md\n\nNEW DISPATCH\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("skills/foo/SKILL.md edit MUST change hash (skill conformance tests)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "skills/foo/SKILL.md", "---\nname: foo\n---\nNEW SKILL BODY\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("src/core/db.ts edit MUST change hash", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "src/core/db.ts", "export const db = 2;\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("test/foo.test.ts edit MUST change hash", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(- sb,- "test/foo.test.ts",- "import {test} from 'bun:test';\ntest('y', () => {});\n",- );- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("package.json edit MUST change hash", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "package.json", '{"name":"test","version":"0.0.1"}\n');- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("bun.lock edit MUST change hash (dependency drift catches false-pass)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "bun.lock", "lockfile-v2\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it(".github/workflows/test.yml edit MUST change hash (CI shape change is test-affecting)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, ".github/workflows/test.yml", "name: Test\n# changed\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-});--describe("ci-cache-hash.sh — SAFE deny-list invariants (must NOT invalidate)", () => {- function withSandbox(test: (sb: Sandbox) => void) {- const sb = makeSandbox(BASELINE_FILES);- try {- test(sb);- } finally {- rmSync(sb.dir, { recursive: true, force: true });- }- }-- it("CHANGELOG.md edit produces SAME hash (deny-listed)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "CHANGELOG.md", "# Changelog\n\n## [1.1.0]\nnew release\n");- const after = hash(sb);- expect(after).toBe(before);- });- });-- it("README.md edit produces DIFFERENT hash (re-admitted: carries the paste block [C2])", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "README.md", "# Project\n\nupdated tagline\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("BOOTSTRAP_FOR_AGENTS.md edit produces DIFFERENT hash (re-admitted [C2])", () => {- withSandbox((sb) => {- modify(sb, "BOOTSTRAP_FOR_AGENTS.md", "<!-- gbrain-runbook-stamp: 0.0.0.0 -->\n# runbook\n");- const before = hash(sb);- modify(sb, "BOOTSTRAP_FOR_AGENTS.md", "<!-- gbrain-runbook-stamp: 0.0.0.0 -->\n# runbook v2\n");- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("TODOS.md edit produces SAME hash (deny-listed)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "TODOS.md", "- [x] thing\n");- const after = hash(sb);- expect(after).toBe(before);- });- });-- it("LICENSE edit produces SAME hash (deny-listed)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "LICENSE", "Apache-2.0\n");- const after = hash(sb);- expect(after).toBe(before);- });- });-- it("docs/guide.md edit produces SAME hash (deny-listed via docs/**/*.md)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "docs/guide.md", "# Guide v2\n");- const after = hash(sb);- expect(after).toBe(before);- });- });-- it("docs/sub/notes.md edit produces SAME hash (nested docs match)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "docs/sub/notes.md", "Updated notes\n");- const after = hash(sb);- expect(after).toBe(before);- });- });-- it("docs/raw.txt edit produces SAME hash (deny-listed via docs/**/*.txt)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "docs/raw.txt", "new raw text\n");- const after = hash(sb);- expect(after).toBe(before);- });- });-});--describe("ci-cache-hash.sh — edge cases", () => {- function withSandbox(- files: Record<string, string>,- test: (sb: Sandbox) => void,- ) {- const sb = makeSandbox(files);- try {- test(sb);- } finally {- rmSync(sb.dir, { recursive: true, force: true });- }- }-- it("untracked file does NOT affect hash (git ls-files only)", () => {- withSandbox(BASELINE_FILES, (sb) => {- const before = hash(sb);- // Write a new file but don't `git add` it.- writeFileSync(join(sb.dir, "src/untracked.ts"), "const x = 1;\n");- const after = hash(sb);- expect(after).toBe(before);- });- });-- it("rename detection: same content, new path → DIFFERENT hash", () => {- withSandbox(BASELINE_FILES, (sb) => {- const before = hash(sb);- execFileSync("git", ["mv", "src/cli.ts", "src/main.ts"], { cwd: sb.dir });- const after = hash(sb);- // Same content, new path. Our hash includes the path, so it changes.- // This is correct: a rename can absolutely affect test outcomes- // (imports change, file resolution changes, etc.).- expect(after).not.toBe(before);- });- });-- it("new file under unknown path (e.g. prompts/x.md) DOES affect hash (deny-list default)", () => {- withSandbox(BASELINE_FILES, (sb) => {- const before = hash(sb);- // Add a NEW file in a path that isn't deny-listed and didn't exist- // before. Default behavior: include in hash. Closes the "missed file- // type" false-pass class (e.g. someone adds `prompts/*.md` that- // tests read).- mkdirSync(join(sb.dir, "prompts"), { recursive: true });- writeFileSync(join(sb.dir, "prompts/extract-takes.md"), "system prompt\n");- execFileSync("git", ["add", "prompts/extract-takes.md"], { cwd: sb.dir });- execFileSync("git", ["commit", "--quiet", "-m", "add prompts"], {- cwd: sb.dir,- });- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("symlink target change affects hash (git hash-object follows symlink contents)", () => {- // Note: git stores symlinks as the link target string, so changing- // the LINK TARGET changes the git blob sha. Our hash will catch- // that. We can't easily test "change of target's content" without- // creating an out-of-tree file, so this case pins the link-target- // path change.- withSandbox(BASELINE_FILES, (sb) => {- // Create a symlink and commit.- symlinkSync("./db.ts", join(sb.dir, "src/core/db-link.ts"));- execFileSync("git", ["add", "src/core/db-link.ts"], { cwd: sb.dir });- execFileSync("git", ["commit", "--quiet", "-m", "add link"], {- cwd: sb.dir,- });- const before = hash(sb);- // Point the symlink elsewhere — and commit so it lands in the- // index that `git ls-files -s` reads.- rmSync(join(sb.dir, "src/core/db-link.ts"));- symlinkSync("./cli.ts", join(sb.dir, "src/core/db-link.ts"));- execFileSync("git", ["add", "src/core/db-link.ts"], { cwd: sb.dir });- execFileSync("git", ["commit", "--quiet", "-m", "repoint link"], {- cwd: sb.dir,- });- const after = hash(sb);- expect(after).not.toBe(before);- });- });-- it("locale-stable: LC_ALL=de_DE.UTF-8 produces the same hash as default", () => {- withSandbox(BASELINE_FILES, (sb) => {- const defaultHash = spawnSync("bash", [sb.scriptPath], {- cwd: sb.dir,- encoding: "utf8",- }).stdout.trim();- const altLocale = spawnSync("bash", [sb.scriptPath], {- cwd: sb.dir,- encoding: "utf8",- env: { ...process.env, LC_ALL: "de_DE.UTF-8", LANG: "de_DE.UTF-8" },- }).stdout.trim();- expect(altLocale).toBe(defaultHash);- });- });-});--describe("ci-cache-hash.sh — policy-doc re-admit (test-affecting docs under docs/)", () => {- // These docs live under docs/ (normally deny-listed) but carry CI/release/- // test contracts the suite reads. The re-admit must make edits to them- // invalidate the hash, WITHOUT un-denying ordinary docs.- const POLICY_FILES: Record<string, string> = {- ...BASELINE_FILES,- "docs/TESTING.md": "# Testing\n\ntest tiers + isolation lint\n",- "docs/RELEASING.md": "# Releasing\n\nversion locations + ship process\n",- };-- function withSandbox(test: (sb: Sandbox) => void) {- const sb = makeSandbox(POLICY_FILES);- try {- test(sb);- } finally {- rmSync(sb.dir, { recursive: true, force: true });- }- }-- it("docs/TESTING.md edit MUST change hash (re-admitted policy doc)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "docs/TESTING.md", "# Testing\n\nNEW POLICY\n");- expect(hash(sb)).not.toBe(before);- });- });-- it("docs/RELEASING.md edit MUST change hash (re-admitted policy doc)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "docs/RELEASING.md", "# Releasing\n\nNEW SHIP RULE\n");- expect(hash(sb)).not.toBe(before);- });- });-- it("docs/guide.md edit STILL produces same hash (re-admit is scoped, not a blanket docs un-deny)", () => {- withSandbox((sb) => {- const before = hash(sb);- modify(sb, "docs/guide.md", "# Guide v3\n");- expect(hash(sb)).toBe(before);- });- });-});--describe("ci-cache-hash.sh — usage errors", () => {- it("--bogus arg exits 2", () => {- const r = spawnSync("bash", [SCRIPT_SRC, "--bogus"], {- cwd: REPO_ROOT,- encoding: "utf8",- });- expect(r.status).toBe(2);- expect(r.stderr).toContain("usage:");- });-- it("--verbose flag works (writes diagnostics to stderr, hash to stdout)", () => {- const r = spawnSync("bash", [SCRIPT_SRC, "--verbose"], {- cwd: REPO_ROOT,- encoding: "utf8",- });- expect(r.status).toBe(0);- expect(r.stdout.trim()).toMatch(/^[0-9a-f]{16}$/);- expect(r.stderr).toContain("files in hash");- });-});diff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.tsnew file mode 100644index 0000000000..ec7f8857a7--- /dev/null+++ b/test/scripts/ci-gates.test.ts@@ -0,0 +1,114 @@+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import { safeLoad } from 'js-yaml';++const root = join(import.meta.dir, '..', '..');+type Job = { needs?: string | string[]; if?: string; steps: Array<{ name?: string; run?: string; uses?: string }> };+type Workflow = { on: Record<string, { paths?: string[] }>; jobs: Record<string, Job> };+const loadWorkflow = (name: string) => safeLoad(readFileSync(join(root, '.github/workflows', name), 'utf8')) as Workflow;+const unit = loadWorkflow('test.yml');+const e2e = loadWorkflow('e2e.yml');++function aggregate(workflow: Workflow, name: string, event: string, results: Record<string, string>) {+ const script = workflow.jobs[name].steps.find(step => step.name === 'Aggregate result')!.run!+ .replace(/\$\{\{ needs\.([\w-]+)\.result \}\}/g, (_, job) => results[job] ?? 'success')+ .replace(/\$\{\{ github.event_name \}\}/g, event);+ expect(script).not.toContain('${{');+ return spawnSync('bash', ['-e', '-c', script], { encoding: 'utf8' }).status;+}++describe('CI execution evidence', () => {+ test('gitleaks and verify run independently for every change, with no pass-marker cache', () => {+ for (const [name, workflow] of [['test.yml', unit], ['e2e.yml', e2e]] as const) {+ const source = readFileSync(join(root, '.github/workflows', name), 'utf8');+ expect(source).not.toMatch(/(?:ci|e2e)-pass-|cache-check|cache-write/);+ expect(source).toContain('bun-cache-');+ expect(source).toContain('pglite-snapshot-');+ expect(workflow.on.pull_request.paths).toBeUndefined();+ }+ for (const name of ['gitleaks', 'verify']) {+ expect(unit.jobs[name].needs).toBeUndefined();+ expect(unit.jobs[name].if).toBeUndefined();+ }+ expect(e2e.jobs.tier2.needs).toBe('jsonb-parity');+ expect(e2e.jobs.tier2.if).toBeUndefined();+ });++ test('unit aggregate rejects failed, cancelled or skipped required jobs', () => {+ expect(unit.jobs['test-status'].if).toBe('always()');+ expect(unit.jobs['test-status'].needs).toEqual([+ 'gitleaks', 'verify', 'serial-tests', 'slow-eval-longmemeval',+ 'slow-entity-resolve-perf', 'slow-brainbench-e2e', 'brainbench', 'test',+ ]);+ expect(aggregate(unit, 'test-status', 'pull_request', {})).toBe(0);+ for (const job of unit.jobs['test-status'].needs as string[]) {+ for (const result of ['failure', 'cancelled', 'skipped']) {+ expect(aggregate(unit, 'test-status', 'pull_request', { [job]: result }), `${job}: ${result}`).toBe(1);+ }+ }+ });++ test('E2E aggregate gates nightly full-corpus execution and allows its skip on other events', () => {+ expect(e2e.jobs['e2e-status'].if).toBe('always()');+ const needs = e2e.jobs['e2e-status'].needs as string[];+ const nightly = ['coverage-full-unit', 'coverage-full-serial', 'coverage-full-slow', 'coverage-full-e2e'];+ expect(needs).toEqual(['jsonb-parity', 'tier1', 'tier2', 'selected-e2e', ...nightly]);+ for (const event of ['pull_request', 'push', 'workflow_dispatch']) {+ expect(aggregate(e2e, 'e2e-status', event, Object.fromEntries(nightly.map(job => [job, 'skipped'])))).toBe(0);+ }+ expect(aggregate(e2e, 'e2e-status', 'schedule', {})).toBe(0);+ for (const job of needs) {+ for (const result of ['failure', 'cancelled', 'skipped']) {+ expect(aggregate(e2e, 'e2e-status', 'schedule', { [job]: result }), `${job}: ${result}`).toBe(1);+ }+ }+ });++ test('admin manifest changes trigger the security scan and CI installs are frozen', () => {+ expect(loadWorkflow('osv-scanner.yml').on.pull_request.paths).toEqual(expect.arrayContaining(['bun.lock', 'package.json', 'admin/bun.lock', 'admin/package.json']));+ for (const name of ['test.yml', 'e2e.yml', 'heavy-tests.yml', 'release.yml']) {+ const source = readFileSync(join(root, '.github/workflows', name), 'utf8');+ const installs = source.split('\n').filter(line => /^\s*-?\s*run: bun install/.test(line));+ for (const line of installs) expect(line, name).toContain('--frozen-lockfile');+ }+ });++ test('scheduled slow lane includes every slow file excluded from the coverage shards', () => {+ const shard = readFileSync(join(root, 'scripts/test-shard.sh'), 'utf8');+ const excluded = [...shard.matchAll(/-not -name '([^']+\.slow\.test\.ts)'/g)].map(match => match[1]);+ expect(excluded.length).toBeGreaterThan(0);+ const slow = e2e.jobs['coverage-full-slow'].steps.map(step => step.run ?? '').join('\n');+ for (const file of excluded) expect(slow).toContain(`bun test test/${file}`);+ });+});++describe('test:full exit status', () => {+ test.each([+ { database: '', e2eExit: 0, expected: 0, called: false },+ { database: 'fixture-test-db', e2eExit: 0, expected: 0, called: true },+ { database: 'fixture-test-db', e2eExit: 7, expected: 7, called: true },+ ])('DATABASE_URL=$database E2E exit=$e2eExit', ({ database, e2eExit, expected, called }) => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-test-full-'));+ try {+ mkdirSync(join(home, 'scripts'));+ mkdirSync(join(home, 'bin'));+ writeFileSync(join(home, 'bin/bun'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ writeFileSync(join(home, 'scripts/run-unit-parallel.sh'), 'exit 0\n');+ writeFileSync(join(home, 'scripts/run-e2e.sh'), `echo E2E_CALLED\nexit ${e2eExit}\n`);+ const script = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).scripts['test:full'];+ writeFileSync(join(home, 'package.json'), JSON.stringify({ scripts: { 'test:full': script } }));+ const result = spawnSync(process.execPath, ['--no-env-file', 'run', 'test:full'], {+ cwd: home, encoding: 'utf8',+ env: { ...process.env, DATABASE_URL: database, PATH: `${join(home, 'bin')}:${process.env.PATH}` },+ });+ expect(result.status).toBe(expected);+ expect(result.stdout.includes('E2E_CALLED')).toBe(called);+ expect(result.stderr.split('\n').some(line => line.startsWith('[test:full] skipped E2E'))).toBe(!called);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/test/scripts/ci-local-rendering.test.ts b/test/scripts/ci-local-rendering.test.tsnew file mode 100644index 0000000000..702d9b041d--- /dev/null+++ b/test/scripts/ci-local-rendering.test.ts@@ -0,0 +1,266 @@+import { describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const source = readFileSync(join(import.meta.dir, '../../scripts/ci-local.sh'), 'utf8');+const templateStart = source.indexOf("INNER_CMD=$(cat <<'EOF'");+const templateEnd = source.indexOf('\n# Conductor / git-worktree support:', templateStart);++describe('ci-local command rendering', () => {+ const cases = [+ { phaseExit: 0, missingTool: '' },+ { phaseExit: 7, missingTool: '' },+ ...['git', 'python3', 'ps', 'psql'].map(missingTool => ({ phaseExit: 0, missingTool })),+ ];+ for (const { phaseExit, missingTool } of cases) {+ test(`preserves stderr and exit ${phaseExit}; missing prerequisite ${missingTool || 'none'}`, () => {+ expect(templateStart).toBeGreaterThanOrEqual(0);+ expect(templateEnd).toBeGreaterThan(templateStart);+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-render-'));+ try {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ // Execute the actual runner template, with installation/configuration+ // commands stubbed so this regression needs neither Docker nor root.+ for (const name of ['bun', 'git', 'python3', 'ps', 'psql']) {+ writeFileSync(join(bin, name), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ }+ writeFileSync(join(bin, 'apt-get'), '#!/bin/sh\nprintf "%s\\n" "$*" >> "$INSTALL_LOG"\n', { mode: 0o755 });+ const phaseLog = join(home, 'phase.log');+ const installLog = join(home, 'install.log');+ const phases = [+ 'printf "%s\\n" "literal & marker"',+ 'sh -c \'printf "%s\\n" "phase stdout"; printf "%s\\n" "phase stderr" >&2; exit "$1"\' _ "$PHASE_EXIT" >> "$PHASE_LOG" 2>&1',+ 'printf "%s\\n" "phase completed"',+ ].join('\n');+ const script = [+ // Exercise Bash 5.2's replacement semantics when available; older+ // macOS Bash still runs the same rendering and redirection checks.+ 'shopt -s patsub_replacement 2>/dev/null || true',+ // Hide exactly one prerequisite, even on a fully provisioned host.+ 'command() { if [ "$1" = "-v" ] && [ "${2:-}" = "$FIXTURE_MISSING_TOOL" ]; then return 1; fi; builtin command "$@"; }',+ 'export -f command',+ source.slice(templateStart, templateEnd),+ 'bash -c "$INNER_CMD"',+ ].join('\n');+ const result = spawnSync('bash', ['-c', script], {+ cwd: home, encoding: 'utf8', timeout: 5_000,+ env: {+ ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`,+ RUN_PHASES_CMD: phases, PHASE_LOG: phaseLog, PHASE_EXIT: String(phaseExit),+ FIXTURE_MISSING_TOOL: missingTool, INSTALL_LOG: installLog,+ },+ });+ expect(result.status, result.stderr).toBe(phaseExit);+ expect(readFileSync(phaseLog, 'utf8')).toBe('phase stdout\nphase stderr\n');+ expect(result.stdout).toContain('literal & marker');+ expect(result.stdout.includes('phase completed')).toBe(phaseExit === 0);+ expect(existsSync(join(home, '__RUN_PHASES__1'))).toBe(false);+ if (missingTool) {+ expect(readFileSync(installLog, 'utf8')).toBe('update -qq\ninstall -y -qq git ca-certificates python3 procps postgresql-client\n');+ } else {+ expect(existsSync(installLog)).toBe(false);+ }+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+ }+});++function runPhases(noShard: boolean, diff: boolean, failStage = '') {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-phases-'));+ try {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ mkdirSync(join(home, 'scripts'));+ const trace = join(home, 'trace');+ const put = (path: string, body: string) => writeFileSync(join(home, path), `#!/bin/bash\n${body}\n`, { mode: 0o755 });+ for (const name of ['git', 'python3', 'ps', 'psql', 'apt-get']) put(`bin/${name}`, 'exit 0');+ put('bin/bun', `+case "$*" in+ "run scripts/select-e2e.ts") printf '%s\\n' test/e2e/one.test.ts test/e2e/two.test.ts; exit 0 ;;+ "run typecheck") stage=verify ;;+ "run test:serial") stage=serial ;;+ "run test:slow") stage=slow ;;+ *) exit 0 ;;+esac+printf '%s:%s\\n' "$stage" "\${DATABASE_URL-unset}" >> "$TRACE"+[ "$FAIL_STAGE" != "$stage" ] || exit 7+`);+ for (const script of ['check-jsonb-pattern.sh', 'check-progress-to-stdout.sh', 'check-trailing-newline.sh', 'check-wasm-embedded.sh']) {+ put(`scripts/${script}`, 'exit 0');+ }+ put('scripts/run-unit-shard.sh', `+printf 'unit:%s:%s\\n' "\${SHARD-all}" "\${DATABASE_URL-unset}" >> "$TRACE"+printf '%s\\n' 'early diagnostic retained beyond summary tail' >&2+for line in {1..35}; do printf 'fixture progress %s\\n' "$line"; done+[ -z "\${DATABASE_URL:-}" ] || exit 41+[ "$FAIL_STAGE" != unit ] || exit 7+`);+ put('scripts/run-e2e.sh', `+set -eu+case "$DATABASE_URL" in postgresql://postgres:postgres@postgres-*:5432/gbrain_test) ;; *) exit 42 ;; esac+[ "$GBRAIN_PGBOUNCER_URL" = postgresql://postgres:postgres@pgbouncer:5432/gbrain_pgbouncer ] || exit 43+[ "$GBRAIN_PGBOUNCER_DIRECT_URL" = postgresql://postgres:postgres@postgres-1:5432/gbrain_test ] || exit 44+[ "$GBRAIN_CI_REQUIRE_PGBOUNCER" = 1 ] || exit 45+[ "$GBRAIN_TEST_DB" = 1 ] || exit 46+printf 'e2e:%s:%s\\n' "\${SHARD-all}" "$*" >> "$TRACE"+[ "$FAIL_STAGE" != e2e ] || exit 7+`);+ const start = source.indexOf('# Step 4: build the runner-side command.');+ expect(start).toBeGreaterThanOrEqual(0);+ const script = source.slice(start, templateEnd)+ .replaceAll('/tmp/shard-logs', join(home, 'shard-logs'))+ .replaceAll('/tmp/e2e-selected.txt', join(home, 'selected.txt'));+ const result = spawnSync('bash', ['-c', `${script}\nbash -c "$INNER_CMD"`], {+ cwd: home, encoding: 'utf8', timeout: 5_000,+ env: {+ ...process.env, HOME: home, PATH: `${bin}:${process.env.PATH}`, TRACE: trace,+ NO_SHARD: noShard ? '1' : '0', DIFF: diff ? '1' : '0', FAIL_STAGE: failStage,+ DATABASE_URL: 'ambient-fixture', GBRAIN_DATABASE_URL: 'ambient-fixture',+ GBRAIN_TEST_DB: 'ambient-must-be-overridden',+ },+ });+ const archivedLogs = [1, 2, 3, 4].map(shard => {+ const path = join(home, '.context/ci-local-shards', `shard-${shard}.log`);+ return existsSync(path) ? readFileSync(path, 'utf8') : '';+ });+ return { ...result, archivedLogs, trace: existsSync(trace) ? readFileSync(trace, 'utf8').trim().split('\n') : [] };+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+}++describe('ci-local execution coverage', () => {+ for (const noShard of [false, true]) {+ for (const diff of [false, true]) {+ test(`serial and slow precede unit/E2E with live target forwarding (no-shard=${noShard}, diff=${diff})`, () => {+ const result = runPhases(noShard, diff);+ expect(result.status, result.stdout + result.stderr).toBe(0);+ expect(result.trace.slice(0, 3)).toEqual(['verify:ambient-fixture', 'serial:unset', 'slow:unset']);+ const units = result.trace.filter(line => line.startsWith('unit:'));+ const e2e = result.trace.filter(line => line.startsWith('e2e:'));+ expect(units).toHaveLength(noShard ? 1 : 4);+ expect(units.every(line => line.endsWith(':unset'))).toBe(true);+ expect(e2e).toHaveLength(noShard ? 1 : 4);+ if (diff) expect(e2e.every(line => line.endsWith('test/e2e/one.test.ts test/e2e/two.test.ts'))).toBe(true);+ if (!noShard) {+ expect(result.stdout).toContain('Complete shard logs saved to .context/ci-local-shards/');+ for (const log of result.archivedLogs) {+ expect(log).toContain('early diagnostic retained beyond summary tail');+ expect(log).toContain('DONE');+ }+ }+ });+ }+ }++ for (const failStage of ['verify', 'serial', 'slow', 'unit', 'e2e']) {+ test(`a failed ${failStage} stage cannot produce a green local CI result`, () => {+ const result = runPhases(false, false, failStage);+ expect(result.status).not.toBe(0);+ expect(result.stdout).not.toContain('All 4 shards passed');+ if (failStage !== 'e2e') expect(result.trace.some(line => line.startsWith('e2e:'))).toBe(false);+ if (['verify', 'serial', 'slow'].includes(failStage)) {+ expect(result.status).toBe(7);+ expect(result.trace.some(line => line.startsWith('unit:'))).toBe(false);+ } else {+ for (const log of result.archivedLogs) {+ expect(log).toContain('early diagnostic retained beyond summary tail');+ expect(log).toContain(`${failStage.toUpperCase()} FAILED`);+ }+ }+ });+ }++ for (const gitleaks of ['missing', 'success', 'failure']) {+ test(`doc-only diff requires a successful gitleaks scan (${gitleaks})`, () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-docs-'));+ try {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ mkdirSync(join(home, 'scripts'));+ writeFileSync(join(bin, 'bun'), '#!/bin/sh\necho DOC_ONLY\n', { mode: 0o755 });+ writeFileSync(join(bin, 'docker'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ writeFileSync(join(bin, 'gitleaks'), '#!/bin/sh\nprintf "%s\\n" "$1" >> "$SCAN_LOG"\n[ "$SCAN_MODE" != failure ]\n', { mode: 0o755 });+ const end = source.indexOf('# Pre-flight: postgres host ports');+ const script = `command() { if [ "$1" = -v ] && [ "\${2:-}" = gitleaks ] && [ "$SCAN_MODE" = missing ]; then return 1; fi; builtin command "$@"; }\n${source.slice(0, end)}`;+ const log = join(home, 'scans');+ const result = spawnSync('bash', ['-c', script, join(home, 'scripts/ci-local.sh'), '--diff'], {+ encoding: 'utf8', timeout: 5_000,+ env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, SCAN_MODE: gitleaks, SCAN_LOG: log },+ });+ expect(result.status, result.stderr).toBe(gitleaks === 'success' ? 0 : 1);+ const scans = existsSync(log) ? readFileSync(log, 'utf8') : '';+ expect(scans).toBe(gitleaks === 'success' ? 'dir\ngit\n' : gitleaks === 'failure' ? 'dir\n' : '');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+ }+});++describe('required PgBouncer execution through run-e2e', () => {+ for (const [required, passes, testExit, expectedExit, parentCoverageExists] 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],+ ] as const) {+ test(`required=${required}, executed=${passes}, Bun exit=${testExit}, parent coverage exists=${parentCoverageExists}`, () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ci-pooler-'));+ try {+ const bin = join(home, 'bin');+ mkdirSync(bin);+ mkdirSync(join(home, 'scripts/lib'), { recursive: true });+ const script = readFileSync(join(import.meta.dir, '../../scripts/run-e2e.sh'), 'utf8');+ writeFileSync(join(home, 'scripts/run-e2e.sh'), script);+ writeFileSync(join(home, 'scripts/lib/test-env.sh'), 'ensure_pglite_snapshot() { :; }\n');+ writeFileSync(join(bin, 'psql'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });+ 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"+exit "$FAKE_EXIT"+`, { mode: 0o755 });+ const report = join(home, 'environment');+ const pooled = 'postgresql://localhost:6543/gbrain_pgbouncer';+ const direct = 'postgresql://localhost:5434/gbrain_test';+ const parentCoverage = join(home, 'parent-coverage');+ const parentManifest = join(parentCoverage, 'lane-manifest.json');+ const manifestBefore = '{"lane":"shard-1","complete":true}\n';+ if (parentCoverageExists) {+ mkdirSync(parentCoverage);+ writeFileSync(parentManifest, manifestBefore);+ }+ // Model hosted CI even when this test runs locally: nested fake Bun+ // must neither collect into nor overwrite the outer unit lane.+ const inheritedEnv = { ...process.env, COVERAGE_DIR: parentCoverage };+ const result = spawnSync('bash', [join(home, 'scripts/run-e2e.sh'), 'test/e2e/pgbouncer-teardown.test.ts'], {+ cwd: home, encoding: 'utf8', timeout: 5_000,+ env: {+ ...inheritedEnv, HOME: home, PATH: `${bin}:${process.env.PATH}`,+ // This child intentionally exercises one selected file. The outer+ // unit shard must not repartition it into an empty E2E selection.+ SHARD: '',+ COVERAGE_DIR: '',+ 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),+ },+ });+ expect(result.status, result.stdout + result.stderr).toBe(expectedExit);+ expect(readFileSync(report, 'utf8')).toBe(`${pooled}\n${direct}\n${required ? '1' : '0'}\n1\nunset\ndisabled\n`);+ if (parentCoverageExists) expect(readFileSync(parentManifest, 'utf8')).toBe(manifestBefore);+ else expect(existsSync(parentCoverage)).toBe(false);+ if (required && passes === 0 && testExit === 0) expect(result.stdout).toContain('required PgBouncer tests did not execute');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+ }+});diff --git a/test/scripts/e2e-wiring.test.ts b/test/scripts/e2e-wiring.test.tsindex 1e75db28ce..1260941edd 100644--- a/test/scripts/e2e-wiring.test.ts+++ b/test/scripts/e2e-wiring.test.ts@@ -5,9 +5,8 @@* 1. The selected-e2e job exists, consumes scripts/select-e2e.ts in its* default file-selection mode, and NOTHING masks the selector's exit* code (exit 2 = git failure must fail the job — fail-loud).- * 2. Both aggregation consumers (e2e-cache-write, e2e-status) carry the- * job in `needs` — a red selected lane can neither seal the content-- * hash cache marker nor report E2E green.+ * 2. The e2e-status aggregate carries the job in `needs` and requires+ * success — a red selected lane cannot report E2E green.* 3. The job passes NO live provider keys, so it is fork-runnable by* construction (service Postgres only) and can never spend tokens.* 4. The job's checkout fetches real history (select-e2e diffs@@ -24,8 +23,10 @@* never grow past the seeded literal.*/import { describe, test, expect } from 'bun:test';-import { existsSync, readdirSync, readFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { spawnSync } from 'node:child_process';import { E2E_TEST_MAP } from '../../scripts/e2e-test-map.ts';const repoRoot = join(import.meta.dir, '..', '..');@@ -58,10 +59,8 @@ describe('selected-e2e job wiring', () => {expect(job).not.toContain('continue-on-error');});- test('cache-write and status both gate on the job', () => {- const cacheWrite = jobBlock('e2e-cache-write');+ test('status gates on the job', () => {const status = jobBlock('e2e-status');- expect(cacheWrite).toContain('selected-e2e');expect(status).toContain('selected-e2e');expect(status).toContain('needs.selected-e2e.result');// The aggregate loop must actually check the result, not just need it.@@ -78,6 +77,38 @@ describe('selected-e2e job wiring', () => {expect(job).toContain('fetch-depth: 0');});+ test('selector emits separate lines so workflow exclusions retain other selected files', () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-selector-wiring-'));+ try {+ const git = (args: string[]) => {+ const result = spawnSync('git', args, { cwd: dir, encoding: 'utf8' });+ expect(result.status, result.stderr).toBe(0);+ };+ git(['init', '-q']);+ git(['-c', 'user.name=fixture', '-c', '[email protected]', 'commit', '-qm', 'fixture', '--allow-empty']);+ git(['update-ref', 'refs/remotes/origin/master', 'HEAD']);+ mkdirSync(join(dir, 'test/e2e'), { recursive: true });+ const files = ['test/e2e/mechanical.test.ts', 'test/e2e/route-a.test.ts', 'test/e2e/route-b.test.ts'];+ for (const file of files) writeFileSync(join(dir, file), '// fixture\n');+ const selected = spawnSync(process.execPath, ['--no-env-file', join(repoRoot, 'scripts/select-e2e.ts')], { cwd: dir, encoding: 'utf8' });+ expect(selected.status, selected.stderr).toBe(0);+ expect(selected.stdout).toBe(files.join('\n') + '\n');+ writeFileSync(join(dir, 'selected.txt'), selected.stdout);+ // Execute the workflow's actual exclusion loop, with only its temporary+ // paths relocated so concurrent tests never share /tmp/run.txt.+ const start = job.indexOf("EXCLUDE='");+ const end = job.indexOf('done < /tmp/selected.txt', start) + 'done < /tmp/selected.txt'.length;+ const filter = job.slice(start, end)+ .replaceAll('/tmp/selected.txt', `'${join(dir, 'selected.txt')}'`)+ .replaceAll('/tmp/run.txt', `'${join(dir, 'run.txt')}'`);+ const filtered = spawnSync('bash', ['-e', '-c', filter], { encoding: 'utf8' });+ expect(filtered.status, filtered.stderr).toBe(0);+ expect(readFileSync(join(dir, 'run.txt'), 'utf8')).toBe(files.slice(1).join('\n') + '\n');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+test('every EXCLUDE entry is named by another job here or is a live-key spender', () => {const m = job.match(/EXCLUDE='([^']+)'/);expect(m).not.toBeNull();diff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.tsindex 3d9247bd37..02a4c342b3 100644--- a/test/search-alias-resolved-boost.test.ts+++ b/test/search-alias-resolved-boost.test.ts@@ -34,24 +34,23 @@ const noopPostFusionOpts: PostFusionOpts = {graphSignalsEnabled: false,};+async function candidate(slug: string, sourceId = 'default'): Promise<SearchResult> {+ const page = await engine.putPage(slug, {+ title: slug, type: 'concept', compiled_truth: 'Synthetic alias fixture',+ }, { sourceId });+ return {+ slug, source_id: sourceId, score: 1, chunk_id: page.id, page_id: page.id,+ chunk_text: '', chunk_index: 0, title: slug, type: 'concept', slug_lower: slug,+ } as unknown as SearchResult;+}+describe('alias_resolved boost stage', () => {it('applies 1.05x multiplier to pages that are canonicals of aliases', async () => {- // Insert an alias pointing at canonical-page+ // A canonical alias must point at an actual page in the same source.+ const results = [await candidate('canonical-page'), await candidate('plain-page')];await engine.executeRaw(`INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ('default', 'old-name', 'canonical-page')`,);- const results: SearchResult[] = [- {- slug: 'canonical-page', source_id: 'default', score: 1.0,- chunk_id: 1, page_id: 1, chunk_text: '', chunk_index: 0,- title: 'Canonical', type: 'concept' as never, slug_lower: 'canonical-page',- } as unknown as SearchResult,- {- slug: 'plain-page', source_id: 'default', score: 1.0,- chunk_id: 2, page_id: 2, chunk_text: '', chunk_index: 0,- title: 'Plain', type: 'concept' as never, slug_lower: 'plain-page',- } as unknown as SearchResult,- ];await runPostFusionStages(engine, results, noopPostFusionOpts);// canonical-page gets 1.05x boostexpect(results[0].score).toBeCloseTo(1.05, 5);@@ -62,11 +61,7 @@ describe('alias_resolved boost stage', () => {});it('does not boost when no aliases exist', async () => {- const results: SearchResult[] = [{- slug: 'plain', source_id: 'default', score: 1.0,- chunk_id: 1, page_id: 1, chunk_text: '', chunk_index: 0,- title: 'p', type: 'concept' as never, slug_lower: 'plain',- } as unknown as SearchResult];+ const results = [await candidate('plain')];await runPostFusionStages(engine, results, noopPostFusionOpts);expect(results[0].score).toBeCloseTo(1.0, 5);expect(results[0].alias_resolved_boost).toBeUndefined();@@ -74,17 +69,14 @@ describe('alias_resolved boost stage', () => {it('is source-scoped (F9): alias in source A does not boost in source B', async () => {await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('alt', 'alt') ON CONFLICT DO NOTHING`);+ const results = [await candidate('shared'), await candidate('shared', 'alt')];await engine.executeRaw(`INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ('alt', 'old', 'shared')`,);- // Same slug, different source — should NOT be boosted (alias is in 'alt')- const results: SearchResult[] = [{- slug: 'shared', source_id: 'default', score: 1.0,- chunk_id: 1, page_id: 1, chunk_text: '', chunk_index: 0,- title: 's', type: 'concept' as never, slug_lower: 'shared',- } as unknown as SearchResult];+ // Both namesakes exist, but only the alias's exact source gets the boost.await runPostFusionStages(engine, results, noopPostFusionOpts);expect(results[0].alias_resolved_boost).toBeUndefined();+ expect(results[1].alias_resolved_boost).toBe(1.05);});});diff --git a/test/search-telemetry-cache-wiring.serial.test.ts b/test/search-telemetry-cache-wiring.serial.test.tsindex 320e2708d1..ad829384ae 100644--- a/test/search-telemetry-cache-wiring.serial.test.ts+++ b/test/search-telemetry-cache-wiring.serial.test.ts@@ -1,22 +1,8 @@/**- * Regression wiring test for #2952 — cache classification reaches telemetry.- *- * Pre-fix, `recordSearchTelemetry` fired only from bare `hybridSearch`, whose- * meta never carries a `cache` field, and a cache HIT returned from- * `hybridSearchCached` before any record at all. Net effect on a live brain:- * `search stats` reported `0 hit / 0 miss` forever while the `query_cache`- * table grew, and hit searches vanished from count/results/tokens/rank-1.- *- * This file drives the REAL pipeline (PGLite brain, real SemanticQueryCache- * store→lookup roundtrip, mocked `embedQuery` for a deterministic vector) and- * pins the decision matrix:- *- * - consulted + no row → recorded once with cache_miss- * - consulted + row → recorded once with cache_hit (plus results/rank-1)- * - consult skipped → recorded once with neither counter- * - bare hybridSearch → recorded once with neither counter (unchanged)- *- * Serial: mock.module + gateway/global-env mutation (isolation guard R2).+ * Production-wrapper regression coverage with semantic response caching disabled.+ * Fresh reads must retain filtering, metadata and telemetry guarantees; legacy+ * cache implementation behavior is covered by the direct cache-class suites.+ * Serial because embedding and gateway configuration are process-global.*/import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';@@ -86,16 +72,9 @@ async function readCounters(): Promise<Counters> {}beforeAll(async () => {- // Hermetic config home so the developer's real ~/.gbrain/config.json can't- // leak an embedding_model that flips isCacheSafe → 'disabled'.tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-cache-telemetry-'));process.env.GBRAIN_HOME = tmpHome;- // Pin the gateway to a 1536d provider BEFORE initSchema so the- // query_cache.embedding column is sized for the mock vectors, and so- // isAvailable('embedding') lets the cache consult proceed. The fake key is- // never used — embedQuery is mocked above. (Pattern:- // test/query-cache-knobs-hash.serial.test.ts.)resetGateway();configureGateway({embedding_model: 'openai:text-embedding-3-large',@@ -107,10 +86,6 @@ beforeAll(async () => {await engine.connect({});await engine.initSchema();- // Keyword-findable fixtures so the inner search returns rows (a non-empty- // result set is what arms the cache writeback). searchKeyword joins- // content_chunks, so pages need explicit chunks — putPage alone leaves the- // chunk table empty (pattern: test/chunk-grain-fts.test.ts).await engine.putPage('alice-foo', {type: 'person',title: 'Alice Foo',@@ -146,54 +121,42 @@ beforeEach(async () => {});describe('hybridSearchCached — telemetry carries the cache outcome', () => {- test('miss then hit: one record per search, classified, hit keeps results/rank-1 telemetry', async () => {- // Call 1 — cache consulted, empty → miss.+ test('repeated fresh reads each record results and rank-1 without cache hit or miss counts', async () => {const first = await hybridSearchCached(engine, 'alice telemetry fixtures', { limit: 5 });expect(first.length).toBeGreaterThan(0);await awaitPendingSearchCacheWrites();- // Sanity: the writeback actually landed, so call 2 exercises a REAL hit- // (a broken writeback would otherwise fail the hit assertion ambiguously).const cacheRows = await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM query_cache',);- expect(cacheRows[0].n).toBeGreaterThan(0);+ expect(cacheRows[0].n).toBe(0);- const afterMiss = await readCounters();- expect(afterMiss.c).toBe(1);- expect(afterMiss.miss).toBe(1);- expect(afterMiss.hit).toBe(0);- expect(afterMiss.rank1).toBe(1);- expect(afterMiss.results).toBeGreaterThan(0);+ const afterFirst = await readCounters();+ expect(afterFirst.c).toBe(1);+ expect(afterFirst.miss).toBe(0);+ expect(afterFirst.hit).toBe(0);+ expect(afterFirst.rank1).toBe(1);+ expect(afterFirst.results).toBeGreaterThan(0);- // Call 2 — identical query + knobs, deterministic embedding → hit.let meta: import('../src/core/types.ts').HybridSearchMeta | undefined;const second = await hybridSearchCached(engine, 'alice telemetry fixtures', {limit: 5,onMeta: (m) => { meta = m; },});- expect(meta?.cache?.status).toBe('hit');+ expect(meta?.cache?.status).toBe('disabled');expect(second.length).toBeGreaterThan(0);- const afterHit = await readCounters();- // Pre-fix both sides of this were wrong: hit stayed 0 forever AND the hit- // search was missing from count entirely (c would read 1, not 2).- expect(afterHit.c).toBe(2);- expect(afterHit.miss).toBe(1);- expect(afterHit.hit).toBe(1);- // The hit search contributes results/rank-1/tokens telemetry too.- expect(afterHit.rank1).toBe(2);- expect(afterHit.results).toBeGreaterThan(afterMiss.results);- // Token parity (codex): the hit serves the SAME result set the miss- // stored, so its token contribution must EQUAL the miss's — a hit/miss- // accounting asymmetry (e.g. hits counting tokens the miss convention- // skips) would break this exact-delta check.- expect(afterHit.tokens - afterMiss.tokens).toBe(afterMiss.tokens);+ const afterSecond = await readCounters();+ expect(afterSecond.c).toBe(2);+ expect(afterSecond.miss).toBe(0);+ expect(afterSecond.hit).toBe(0);+ expect(afterSecond.rank1).toBe(2);+ expect(afterSecond.results).toBeGreaterThan(afterFirst.results);+ expect(afterSecond.tokens - afterFirst.tokens).toBe(afterFirst.tokens);});- test('lookup-embed failure: consult degrades to disabled — recorded once, neither counter', async () => {+ test('embedding failure keeps keyword fallback and records once without cache counters', async () => {embedBehavior = async () => { throw new Error('embed provider down'); };- // The failed consult must not break the search: keyword fallback serves.const results = await hybridSearchCached(engine, 'bob cache wiring', { limit: 5 });expect(results.length).toBeGreaterThan(0);@@ -212,7 +175,6 @@ describe('hybridSearchCached — telemetry carries the cache outcome', () => {expect(counters.c).toBe(1);expect(counters.hit).toBe(0);expect(counters.miss).toBe(0);- // Telemetry otherwise unchanged: the search still counts fully.expect(counters.rank1).toBe(1);expect(counters.results).toBeGreaterThan(0);});@@ -226,8 +188,6 @@ describe('bare hybridSearch — direct callers unchanged', () => {onMeta: (m) => { meta = m; },});expect(results.length).toBeGreaterThan(0);- // The onMeta contract is untouched: no cache field is injected into the- // caller-visible meta (the fold happens on the recorded copy only).expect(meta?.cache).toBeUndefined();const counters = await readCounters();diff --git a/test/search/alias-hop.test.ts b/test/search/alias-hop.test.tsindex 1b8fbc17c9..fdc146626d 100644--- a/test/search/alias-hop.test.ts+++ b/test/search/alias-hop.test.ts@@ -26,6 +26,26 @@ function res(slug: string, score: number, title = slug): SearchResult {}describe('applyAliasHop', () => {+ test('a page made private after retrieval cannot add alias metadata or boost', async () => {+ const page = await engine.putPage('notes/revoked-example', { type: 'note', title: 'Revoked', compiled_truth: 'PUBLIC_BEFORE' });+ await engine.setPageAliases(page.slug, 'default', ['revoked alias']);+ const organic = { ...res(page.slug, 0.5), page_id: page.id };+ await engine.putPage(page.slug, { type: 'note', title: 'Revoked', compiled_truth: 'SECRET_NOW', frontmatter: { visibility: 'private' } });+ const hits = await applyAliasHop(engine, [organic], 'revoked alias', { sourceId: 'default', excludePrivate: true });+ expect(hits).toEqual([organic]);+ expect(hits[0].alias_hit).toBeUndefined();+ expect((await engine.resolveAliases(['revoked alias'], { sourceId: 'default', excludePrivate: true })).size).toBe(0);+ expect((await engine.resolveAliases(['revoked alias'], { sourceId: 'default' })).get('revoked alias')?.[0].slug).toBe(page.slug);+ });++ test('alias-injected excerpts strip every protected take fence', async () => {+ await engine.putPage('notes/body-example', { type: 'note', title: 'Public', compiled_truth: '<!--- gbrain:takes:begin -->\nSECRET_ALIAS_TAKE\n<!--- gbrain:takes:end -->\nPUBLIC_ALIAS_EXCERPT' });+ await engine.setPageAliases('notes/body-example', 'default', ['public alias']);+ const hits = await applyAliasHop(engine, [], 'public alias', { sourceId: 'default', excludePrivate: true });+ expect(hits[0].chunk_text).toContain('PUBLIC_ALIAS_EXCERPT');+ expect(hits[0].chunk_text).not.toContain('SECRET_ALIAS_TAKE');+ });+test('injects an absent canonical when the query matches its alias', async () => {await engine.putPage('projects/mingtang', { type: 'note', title: 'The Mingtang', compiled_truth: 'Indoor Greek amphitheater.' });await engine.setPageAliases('projects/mingtang', 'default', ['hall of light', '明堂']);@@ -61,10 +81,15 @@ describe('applyAliasHop', () => {test('P0 source-isolation: alias hop boosts only the aliased source, not the same slug in another source', async () => {// The alias belongs to the src-b page only. Two same-slug results, different// sources, both in the organic set. The hop must boost ONLY src-b's row.+ const pages = [];+ for (const sourceId of ['src-a', 'src-b']) {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [sourceId]);+ pages.push(await engine.putPage('shared/page', { type: 'note', title: 'Shared', compiled_truth: 'Synthetic source-scoped alias fixture' }, { sourceId }));+ }await engine.setPageAliases('shared/page', 'src-b', ['only in b']);const organic = [- { slug: 'shared/page', source_id: 'src-a', score: 0.5 } as unknown as SearchResult,- { slug: 'shared/page', source_id: 'src-b', score: 0.5 } as unknown as SearchResult,+ { ...res('shared/page', 0.5), page_id: pages[0].id, source_id: 'src-a' },+ { ...res('shared/page', 0.5), page_id: pages[1].id, source_id: 'src-b' },];const out = await applyAliasHop(engine, organic, 'only in b', { sourceIds: ['src-a', 'src-b'] });const a = out.find(r => r.source_id === 'src-a')!;diff --git a/test/search/crag-escalation-limit.serial.test.ts b/test/search/crag-escalation-limit.serial.test.tsindex 17c805c903..484d91ad6c 100644--- a/test/search/crag-escalation-limit.serial.test.ts+++ b/test/search/crag-escalation-limit.serial.test.ts@@ -15,7 +15,7 @@*/import { describe, test, expect, beforeAll, afterAll, mock } from 'bun:test';-import type { SearchResult } from '../../src/core/types.ts';+import type { SearchResult, SearchOpts } from '../../src/core/types.ts';const HYBRID_PATH = '../../src/core/search/hybrid.ts';const actualHybrid = await import(HYBRID_PATH);@@ -38,16 +38,16 @@ function row(i: number, rerankScore: number): SearchResult {// Call log: one entry per hybridSearchCached invocation with the opts we// need to pin (limit + autocut identify the escalated re-run).-const calls: Array<{ limit: unknown; autocut: unknown }> = [];+const calls: SearchOpts[] = [];mock.module(HYBRID_PATH, () => ({...actualHybrid,hybridSearchCached: async (_engine: unknown,_query: string,- opts: { limit?: number; autocut?: boolean },+ opts: SearchOpts,): Promise<SearchResult[]> => {- calls.push({ limit: opts?.limit, autocut: opts?.autocut });+ calls.push(opts);if (opts?.autocut === false) {// The escalated high-ceiling sweep: 30 rows, strong rank-1.return Array.from({ length: 30 }, (_, i) => row(100 + i, i === 0 ? 0.9 : 0.05));@@ -75,6 +75,23 @@ afterAll(async () => {});describe('#4610 query op — adopted escalation is sliced to the caller limit', () => {+ test('escalation retains default and empty holder grants with the page/source policy', async () => {+ for (const holders of [undefined, []]) {+ calls.length = 0;+ const ctx: OperationContext = {+ engine, remote: true, sourceId: 'default', takesHoldersAllowList: holders,+ config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false,+ };+ await operationsByName.query.handler(ctx, { query: 'sprocket subsystem retries', expand: false });+ expect(calls).toHaveLength(2);+ for (const call of calls) {+ expect(call.sourceId).toBe('default');+ expect(call.excludePrivate).toBe(true);+ expect(call.takesHoldersAllowList).toEqual(holders ?? ['world']);+ }+ }+ });+test('limit:10 caller gets exactly 10 rows from the adopted 30-row sweep', async () => {calls.length = 0;const meta: Record<string, unknown> = {};diff --git a/test/search/crag-query-op.test.ts b/test/search/crag-query-op.test.tsindex 74f4f266a9..7807baeab1 100644--- a/test/search/crag-query-op.test.ts+++ b/test/search/crag-query-op.test.ts@@ -92,6 +92,25 @@ describe('query op — CRAG gate (#1663)', () => {expect(crag.escalate_to_think).toBe(true);}, 30000);+ test('remote and unset-trust escalation cannot adopt a matching private page', async () => {+ await engine.setConfig('search.crag_escalation', 'true');+ await engine.putPage('notes/private-crag', {+ type: 'note', title: 'Synthetic restricted record', compiled_truth: 'PRIVATE_CRAG_CANARY',+ frontmatter: { visibility: 'private' },+ });+ await engine.upsertChunks('notes/private-crag', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic restricted record PRIVATE_CRAG_CANARY' }]);+ for (const remote of [true, undefined]) {+ const { ctx, meta } = ctxWithMeta();+ const rows = await operationsByName.query.handler({ ...ctx, remote } as OperationContext, { query: 'Synthetic restricted record', expand: false });+ expect(rows).toEqual([]);+ expect(cragOf(meta).escalated).toBe(true);+ expect(cragOf(meta).confidence).toBe('weak');+ }+ const { ctx } = ctxWithMeta();+ const local = await operationsByName.query.handler(ctx, { query: 'Synthetic restricted record', expand: false });+ expect(JSON.stringify(local)).toContain('PRIVATE_CRAG_CANARY');+ }, 30000);+test('#4610: default-shape caller (expand on) skips the re-run — the documented callerExpanded guard', async () => {await engine.setConfig('search.crag_escalation', 'true');const { ctx, meta } = ctxWithMeta();diff --git a/test/search/exact-lookup.test.ts b/test/search/exact-lookup.test.tsindex 2c90eff24d..ff6ac19719 100644--- a/test/search/exact-lookup.test.ts+++ b/test/search/exact-lookup.test.ts@@ -47,6 +47,23 @@ describe('isSlugShapedQuery', () => {});describe('structuralExactLookup (#1663)', () => {+ test('private exact slugs cannot bypass retrieval privacy; local and public controls survive', async () => {+ await engine.putPage('notes/private-example', { type: 'note', title: 'Private', compiled_truth: 'SECRET_EXACT', frontmatter: { visibility: 'private' } });+ await engine.putPage('notes/public-example', { type: 'note', title: 'Public', compiled_truth: 'PUBLIC_EXACT' });+ expect(await structuralExactLookup(engine, 'notes/private-example', { sourceId: 'default', excludePrivate: true })).toEqual([]);+ expect(await structuralExactLookup(engine, 'notes/private-example', { excludePrivate: true })).toEqual([]);+ expect(await structuralExactLookup(engine, 'notes/private-example', { sourceId: 'default', sourceIds: [], excludePrivate: true })).toEqual([]);+ expect((await structuralExactLookup(engine, 'notes/private-example', { sourceId: 'default' }))[0].chunk_text).toContain('SECRET_EXACT');+ expect((await structuralExactLookup(engine, 'notes/public-example', { sourceId: 'default', excludePrivate: true }))[0].chunk_text).toContain('PUBLIC_EXACT');+ });++ test('injected excerpts strip protected sections before truncating', async () => {+ await engine.putPage('notes/body-example', { type: 'note', title: 'Public', compiled_truth: '<!--- gbrain:takes:begin -->\nSECRET_EXACT_TAKE\n<!--- gbrain:takes:end -->\nPUBLIC_EXCERPT' });+ const hits = await structuralExactLookup(engine, 'notes/body-example', { sourceId: 'default', excludePrivate: true });+ expect(hits[0].chunk_text).toContain('PUBLIC_EXCERPT');+ expect(hits[0].chunk_text).not.toContain('SECRET_EXACT_TAKE');+ });+test('slug-shaped query resolves the page directly (evidence → exists)', async () => {await engine.putPage('people/alice-example', {type: 'person', title: 'Alice Example', compiled_truth: 'Founder of widget-co.',diff --git a/test/search/hybrid-reranker-integration.serial.test.ts b/test/search/hybrid-reranker-integration.serial.test.tsindex 03e528a583..b54141c5a7 100644--- a/test/search/hybrid-reranker-integration.serial.test.ts+++ b/test/search/hybrid-reranker-integration.serial.test.ts@@ -151,7 +151,7 @@ describe('hybridSearch — reranker disabled (pass-through)', () => {});describe('hybridSearchCached — email metadata through vector-first fusion', () => {- test('fresh cache miss preserves metadata through vector-first RRF duplicate handling', async () => {+ test('fresh uncached retrieval preserves metadata through vector-first RRF duplicate handling', async () => {await engine.executeRaw(`DELETE FROM query_cache`);let cacheStatus: string | undefined;const out = await hybridSearchCached(engine, 'vector first duplicate metadata evidence', {@@ -162,13 +162,14 @@ describe('hybridSearchCached — email metadata through vector-first fusion', ()onMeta: (meta) => { cacheStatus = meta.cache?.status; },});- expect(cacheStatus).toBe('miss');+ expect(cacheStatus).toBe('disabled');const matches = out.filter(r => r.slug === 'mail/vector-first');expect(matches).toHaveLength(1);expect(matches[0].message_id).toBe('<[email protected]>');expect(matches[0].thread_id).toBe('thread-vector-first');expect(matches[0].source_subject).toBe('Vector-first exact subject');await awaitPendingSearchCacheWrites();+ expect(await engine.executeRaw('SELECT id FROM query_cache')).toHaveLength(0);});});diff --git a/test/search/modes-report-coverage.test.ts b/test/search/modes-report-coverage.test.tsindex f17893ab5d..8339bf6c00 100644--- a/test/search/modes-report-coverage.test.ts+++ b/test/search/modes-report-coverage.test.ts@@ -65,6 +65,14 @@ describe('#4604 buildModesReport — full-bundle knob coverage', () => {expect(report.resolved.reranker_enabled.source).toBe('override');});+ test('effective semantic caching stays disabled despite an enabling override', async () => {+ const report = await buildModesReport(stubEngine({ 'search.cache.enabled': 'true' }));+ expect(report.resolved.cache_enabled.value).toBe(false);+ expect(report.resolved.cache_enabled.source).toBe('availability');+ expect(report.resolved.cache_enabled.source_detail).toContain('temporarily disabled');+ expect(report.bundles.balanced.cache_enabled).toBe(true); // retained configuration+ });+test('per_call_note labels the report as brain-level resolution only', async () => {const report = await buildModesReport(stubEngine());expect(report.per_call_note).toBe(MODES_REPORT_PER_CALL_NOTE);diff --git a/test/search/page-aliases-engine.test.ts b/test/search/page-aliases-engine.test.tsindex 5d30510446..634bb59420 100644--- a/test/search/page-aliases-engine.test.ts+++ b/test/search/page-aliases-engine.test.ts@@ -27,8 +27,14 @@ beforeEach(async () => {const slugsOf = (m: Map<string, Array<{ slug: string; source_id: string }>>, k: string) =>(m.get(k) ?? []).map(r => r.slug).sort();+async function canonicalPage(slug: string, sourceId = 'default') {+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [sourceId]);+ return engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Synthetic alias fixture' }, { sourceId });+}+describe('setPageAliases + resolveAliases', () => {test('write then read maps alias_norm → slug', async () => {+ await canonicalPage('projects/mingtang');await engine.setPageAliases('projects/mingtang', 'default', ['hall of light', '明堂']);const m = await engine.resolveAliases(['hall of light'], { sourceId: 'default' });expect(slugsOf(m, 'hall of light')).toEqual(['projects/mingtang']);@@ -36,6 +42,8 @@ describe('setPageAliases + resolveAliases', () => {});test('collision: two pages claim the same alias → both returned', async () => {+ await canonicalPage('projects/mingtang');+ await canonicalPage('projects/other-hall');await engine.setPageAliases('projects/mingtang', 'default', ['the hall']);await engine.setPageAliases('projects/other-hall', 'default', ['the hall']);const m = await engine.resolveAliases(['the hall'], { sourceId: 'default' });@@ -43,6 +51,8 @@ describe('setPageAliases + resolveAliases', () => {});test('source-scoped: alias in source A not returned for source B', async () => {+ await canonicalPage('a/page', 'src-a');+ await canonicalPage('b/page', 'src-b');await engine.setPageAliases('a/page', 'src-a', ['shared name']);await engine.setPageAliases('b/page', 'src-b', ['shared name']);const aOnly = await engine.resolveAliases(['shared name'], { sourceId: 'src-a' });@@ -50,11 +60,12 @@ describe('setPageAliases + resolveAliases', () => {expect(aOnly.get('shared name')![0].source_id).toBe('src-a');const both = await engine.resolveAliases(['shared name'], { sourceIds: ['src-a', 'src-b'] });expect(slugsOf(both, 'shared name')).toEqual(['a/page', 'b/page']);- // same slug across sources stays distinct (the P0 contract)+ // Each resolved canonical retains its concrete source identity.expect((both.get('shared name') ?? []).map(r => r.source_id).sort()).toEqual(['src-a', 'src-b']);});test('rewrite replaces the prior alias set (delete + insert)', async () => {+ await canonicalPage('p/x');await engine.setPageAliases('p/x', 'default', ['old name']);await engine.setPageAliases('p/x', 'default', ['new name']);const oldM = await engine.resolveAliases(['old name'], { sourceId: 'default' });@@ -64,7 +75,9 @@ describe('setPageAliases + resolveAliases', () => {});test('empty alias set clears the page', async () => {+ await canonicalPage('p/x');await engine.setPageAliases('p/x', 'default', ['temp']);+ expect(slugsOf(await engine.resolveAliases(['temp'], { sourceId: 'default' }), 'temp')).toEqual(['p/x']);await engine.setPageAliases('p/x', 'default', []);const m = await engine.resolveAliases(['temp'], { sourceId: 'default' });expect(m.size).toBe(0);@@ -76,8 +89,16 @@ describe('setPageAliases + resolveAliases', () => {});test('idempotent re-write does not duplicate (unique triple)', async () => {+ await canonicalPage('p/x');await engine.setPageAliases('p/x', 'default', ['name', 'name']);const m = await engine.resolveAliases(['name'], { sourceId: 'default' });expect(slugsOf(m, 'name')).toEqual(['p/x']);});++ test('dangling alias storage cannot resolve without an admitted canonical page', async () => {+ await engine.setPageAliases('p/missing', 'default', ['dangling']);+ expect(await engine.resolveAliases(['dangling'], { sourceId: 'default' })).toEqual(new Map());+ await canonicalPage('p/missing');+ expect(slugsOf(await engine.resolveAliases(['dangling'], { sourceId: 'default' }), 'dangling')).toEqual(['p/missing']);+ });});diff --git a/test/select-e2e.test.ts b/test/select-e2e.test.tsindex 0620bac0d6..0c12dea8ca 100644--- a/test/select-e2e.test.ts+++ b/test/select-e2e.test.ts@@ -20,6 +20,11 @@ const ALL_E2E = ["test/e2e/dream.test.ts","test/e2e/code-indexing.test.ts","test/e2e/engine-parity.test.ts",+ "test/e2e/chunk-canonical-text-privacy.test.ts",+ "test/e2e/engine-content-privacy.test.ts",+ "test/e2e/legacy-chunk-privacy.test.ts",+ "test/e2e/read-enrichment-privacy.test.ts",+ "test/e2e/remote-privacy-journeys.test.ts","test/e2e/graph-quality.test.ts","test/e2e/http-transport.test.ts","test/e2e/integrity-batch.test.ts",@@ -111,6 +116,11 @@ describe("selectTests", () => {test("case 3: single mapped src -> only mapped tests", () => {expect(select(["src/core/search/intent.ts"])).toEqual([+ "test/e2e/chunk-canonical-text-privacy.test.ts",+ "test/e2e/engine-content-privacy.test.ts",+ "test/e2e/legacy-chunk-privacy.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-swamp.test.ts",@@ -154,6 +164,24 @@ describe("selectTests", () => {expect(select(["src/cli.ts"])).toEqual(ALL_E2E.slice().sort());});+ test("an unmapped change forces all tests even beside a mapped change or direct test edit", () => {+ for (const changes of [+ ["src/core/search/intent.ts", "src/new-unmapped.ts"],+ ["src/new-unmapped.ts", "src/core/search/intent.ts"],+ ["test/e2e/sync.test.ts", "src/new-unmapped.ts"],+ ]) {+ expect(select(changes)).toEqual(ALL_E2E.slice().sort());+ }+ });++ test("an empty map entry cannot declare an unknown change covered", () => {+ expect(selectTests({+ changedFiles: ["src/covered.ts", "src/empty.ts"],+ allE2ETests: ALL_E2E,+ map: { "src/covered.ts": ["test/e2e/sync.test.ts"], "src/empty.ts": [] },+ })).toEqual(ALL_E2E.slice().sort());+ });+test("case 9: directly-modified test file is included", () => {// Touching a test file directly with no other src changes:// - test/e2e/foo.test.ts is in changedFiles@@ -172,6 +200,11 @@ describe("selectTests", () => {"src/core/search/intent.ts",]);expect(result).toEqual([+ "test/e2e/chunk-canonical-text-privacy.test.ts",+ "test/e2e/engine-content-privacy.test.ts",+ "test/e2e/legacy-chunk-privacy.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-swamp.test.ts",diff --git a/test/sync-rename-reconcile.serial.test.ts b/test/sync-rename-reconcile.serial.test.tsindex 3d75b596fd..c975185d00 100644--- a/test/sync-rename-reconcile.serial.test.ts+++ b/test/sync-rename-reconcile.serial.test.ts@@ -968,11 +968,13 @@ describe('#3583 review: orphan-sentinel self-heal probe/clear race', () => {// after the first orphan probe returned "no active row". The second// probe must see it and keep the sentinel open — a single-probe sweep// cleared it while the duplicate existed.- const origExecuteRaw = engine.executeRaw.bind(engine);+ // Preserve the dynamic receiver: import transaction clones inherit this+ // interceptor and must query their own transaction, including after restore.+ const origExecuteRaw = engine.executeRaw;let probeCalls = 0;(engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =- (async (sql: string, params?: unknown[]) => {- const res = await origExecuteRaw(sql, params);+ (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {+ const res = await origExecuteRaw.call(this, sql, params);if (sql.includes('source_path = ANY')) {probeCalls++;if (probeCalls === 1) {@@ -980,7 +982,7 @@ describe('#3583 review: orphan-sentinel self-heal probe/clear race', () => {type: 'person', title: 'Dana (revenant)',compiled_truth: 'materialized between probe and clear',}, { sourceId: 'default' });- await origExecuteRaw(+ await origExecuteRaw.call(this,`UPDATE pages SET source_path = 'people/dana-old.md'WHERE source_id = 'default' AND slug = 'people/dana-old-revenant'`,);@@ -1298,11 +1300,11 @@ describe('#3583 review: a writer landing AFTER the second probe gets its sentine// the second probe returned, i.e. after the double-probe verdict is// final and the clear is committed. The post-clear verify probe must// detect the row and RESTORE the sentinel.- const origExecuteRaw = engine.executeRaw.bind(engine);+ const origExecuteRaw = engine.executeRaw;let probeCalls = 0;(engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =- (async (sql: string, params?: unknown[]) => {- const res = await origExecuteRaw(sql, params);+ (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {+ const res = await origExecuteRaw.call(this, sql, params);if (sql.includes('source_path = ANY')) {probeCalls++;if (probeCalls === 2) {@@ -1310,7 +1312,7 @@ describe('#3583 review: a writer landing AFTER the second probe gets its sentinetype: 'person', title: 'Dana (late writer)',compiled_truth: 'materialized after the second probe',}, { sourceId: 'default' });- await origExecuteRaw(+ await origExecuteRaw.call(this,`UPDATE pages SET source_path = 'people/dana-old.md'WHERE source_id = 'default' AND slug = 'people/dana-old-late-writer'`,);@@ -1370,11 +1372,11 @@ describe('#3583 review: the failure-gate clear paths also verify-and-restore', (writeFileSync(join(repo, 'people/newfile.md'), personMd('New', 'New person.'));execSync('git add -A && git commit -m "unrelated addition"', { cwd: repo, stdio: 'pipe' });- const origExecuteRaw = engine.executeRaw.bind(engine);+ const origExecuteRaw = engine.executeRaw;let probeCalls = 0;(engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =- (async (sql: string, params?: unknown[]) => {- const res = await origExecuteRaw(sql, params);+ (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {+ const res = await origExecuteRaw.call(this, sql, params);if (sql.includes('source_path = ANY')) {probeCalls++;if (probeCalls === 2) {@@ -1383,7 +1385,7 @@ describe('#3583 review: the failure-gate clear paths also verify-and-restore', (type: 'person', title: 'Dana (gate writer)',compiled_truth: 'materialized between the gate verdict and the clear',}, { sourceId: 'default' });- await origExecuteRaw(+ await origExecuteRaw.call(this,`UPDATE pages SET source_path = 'people/dana-old.md'WHERE source_id = 'default' AND slug = 'people/dana-old-gate-writer'`,);@@ -1425,15 +1427,15 @@ describe('#3583 review: the failure-gate clear paths also verify-and-restore', (// Both orphan probes succeed (empty) → clear commits; the post-clear// VERIFY probe (third matching SELECT) throws. Fail-closed means every// cleared sentinel comes back.- const origExecuteRaw = engine.executeRaw.bind(engine);+ const origExecuteRaw = engine.executeRaw;let probeCalls = 0;(engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =- (async (sql: string, params?: unknown[]) => {+ (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {if (sql.includes('source_path = ANY')) {probeCalls++;if (probeCalls === 3) throw new Error('injected verify-probe outage');}- return origExecuteRaw(sql, params);+ return origExecuteRaw.call(this, sql, params);}) as typeof engine.executeRaw;try {const result = await performSync(engine, { repoPath: repo, ...SYNC_OPTS });@@ -1515,13 +1517,13 @@ describe('#3583 review: a throwing bookmark advance can no longer lose a sentinewriteFileSync(join(repo, 'people/newfile.md'), personMd('New', 'New person.'));execSync('git add -A && git commit -m "unrelated addition"', { cwd: repo, stdio: 'pipe' });- const origExecuteRaw = engine.executeRaw.bind(engine);+ const origExecuteRaw = engine.executeRaw;(engine as unknown as { executeRaw: typeof engine.executeRaw }).executeRaw =- (async (sql: string, params?: unknown[]) => {+ (async function (this: PGLiteEngine, sql: string, params?: unknown[]) {if (sql.includes('UPDATE sources SET last_commit')) {throw new Error('injected advance outage');}- return origExecuteRaw(sql, params);+ return origExecuteRaw.call(this, sql, params);}) as typeof engine.executeRaw;let threw = false;try {diff --git a/test/think-max-output-tokens.test.ts b/test/think-max-output-tokens.test.tsindex 2f61247a7c..789b87bd20 100644--- a/test/think-max-output-tokens.test.ts+++ b/test/think-max-output-tokens.test.ts@@ -12,6 +12,7 @@import { afterAll, beforeAll, describe, test, expect } from 'bun:test';import { maxOutputTokensFor, runThink, type ThinkLLMClient } from '../src/core/think/index.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';describe('maxOutputTokensFor — thinking-default headroom', () => {test('Claude 5 family gets 16000', () => {@@ -115,11 +116,13 @@ describe('runThink — max_tokens truncation labeling (gbrain#4375)', () => {engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();- await engine.putPage('notes/quokka-payments', {- title: 'Quokka Payments',- type: 'note',- compiled_truth: 'The quokka payments migration finished in March with zero downtime.',- });+ const imported = await importFromContent(+ engine,+ 'notes/quokka-payments',+ '---\ntitle: Quokka Payments\ntype: note\n---\n\nThe quokka payments migration finished in March with zero downtime.',+ { noEmbed: true, sourceId: 'default' },+ );+ expect(imported.status).toBe('imported');});afterAll(async () => {diff --git a/test/think-pipeline.serial.test.ts b/test/think-pipeline.serial.test.tsindex 4444aca39f..5efb523e11 100644--- a/test/think-pipeline.serial.test.ts+++ b/test/think-pipeline.serial.test.ts@@ -1,5 +1,6 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';import { operationsByName } from '../src/core/operations.ts';import { runThink, persistSynthesis, type ThinkLLMClient } from '../src/core/think/index.ts';import { sanitizeTakeForPrompt, renderTakesBlock } from '../src/core/think/sanitize.ts';@@ -308,6 +309,7 @@ describe('runThink (with stub client)', () => {const result = await runThink(engine, {question: 'technical founder', // matches pg_trgm against 'Strong technical founder'+ remote: false, // Trusted local synthesis intentionally includes the non-world take.client: stubClient,});@@ -357,16 +359,16 @@ describe('runThink (with stub client)', () => {};try {- const page = await engine.putPage('companies/widget-co', {- title: 'Widget Co', type: 'company', compiled_truth: content,- });- pageId = page.id;- await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [page.id]);- await engine.executeRaw(- `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source)- VALUES ($1, 0, $2, 'compiled_truth')`,- [page.id, content],+ // Build the completed index that the default remote gather requires.+ const imported = await importFromContent(+ engine,+ 'companies/widget-co',+ `---\ntitle: Widget Co\ntype: company\n---\n\n${content}`,+ { noEmbed: true, sourceId: 'default' },);+ expect(imported.status).toBe('imported');+ const page = await engine.getPage('companies/widget-co', { sourceId: 'default' });+ pageId = page!.id;const result = await runThink(engine, {question: 'What is Widget Co enterprise pricing in credits per month?',diff --git a/test/think-temporal-window.serial.test.ts b/test/think-temporal-window.serial.test.tsindex 537dcd0b56..660d9a887a 100644--- a/test/think-temporal-window.serial.test.ts+++ b/test/think-temporal-window.serial.test.ts@@ -1,5 +1,6 @@import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';import { runGather } from '../src/core/think/gather.ts';import {filterPagesToWindow,@@ -8,24 +9,24 @@ import {TemporalWindowError,} from '../src/core/think/temporal-window.ts';import { __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';-import type { ChunkInput, SearchResult } from '../src/core/types.ts';+import type { SearchResult } from '../src/core/types.ts';let engine: PGLiteEngine;async function seed(slug: string, body: string, effective?: string, type = 'note') {- await engine.putPage(slug, {- title: slug,- type,- compiled_truth: body,- ...(effective ? { effective_date: new Date(effective), effective_date_source: 'date' as const } : {}),- });- const chunks: ChunkInput[] = [{- chunk_index: 0,- chunk_text: body,- chunk_source: 'compiled_truth',- token_count: 10,- }];- await engine.upsertChunks(slug, chunks);+ const imported = await importFromContent(+ engine, slug,+ `---\ntitle: ${slug}\ntype: ${type}\n${effective ? `date: "${effective}"\n` : ''}---\n\n${body}`,+ { noEmbed: true, sourceId: 'default' },+ );+ expect(imported.status).toBe('imported');+ if (!effective) {+ // Import normally supplies a fallback date; retain the NULL-date fixture.+ await engine.executeRaw(+ 'UPDATE pages SET effective_date = NULL, effective_date_source = NULL WHERE source_id = $1 AND slug = $2',+ ['default', slug],+ );+ }}beforeAll(async () => {diff --git a/test/two-pass.test.ts b/test/two-pass.test.tsindex 8fc182cbd3..19b1247203 100644--- a/test/two-pass.test.ts+++ b/test/two-pass.test.ts@@ -13,6 +13,10 @@import { describe, test, expect, beforeAll, afterAll } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { expandAnchors, hydrateChunks } from '../src/core/search/two-pass.ts';+import { hybridSearch } from '../src/core/search/hybrid.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';describe('Layer 7 (A2) — expandAnchors', () => {let engine: PGLiteEngine;@@ -21,6 +25,7 @@ describe('Layer 7 (A2) — expandAnchors', () => {let chunkC: number;beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });engine = new PGLiteEngine();await engine.connect({});await engine.initSchema();@@ -89,6 +94,7 @@ describe('Layer 7 (A2) — expandAnchors', () => {});afterAll(async () => {+ resetGateway();await engine.disconnect();}, 30_000);@@ -167,6 +173,22 @@ describe('Layer 7 (A2) — expandAnchors', () => {const rows = await hydrateChunks(engine, []);expect(rows).toEqual([]);});++ test('untrusted hybrid retrieval suspends structural expansion that could inject unsealed chunks', async () => {+ const slug = 'notes/structural-public-anchor';+ await importFromContent(engine, slug, '---\ntitle: publicanchor\ntype: note\n---\npublicanchor content', { noEmbed: true, forceRechunk: true });+ const page = (await engine.getPage(slug))!;+ const vector = new Float32Array(1536); vector[0] = 1;+ await engine.executeRaw('UPDATE content_chunks SET embedding = $1::vector WHERE page_id = $2', [`[${Array.from(vector)}]`, page.id]);+ await engine.executeRaw('UPDATE content_chunks SET chunk_text = $1 WHERE id = $2', ['PRIVATE_TWO_PASS_CANARY', chunkB]);+ const opts = { sourceId: 'default', expansion: false, queryEmbedFn: () => vector, nearSymbol: 'b', walkDepth: 1, limit: 20, excludePrivate: false };+ const local = await hybridSearch(engine, 'publicanchor', { ...opts, requireSafeChunks: false });+ expect(JSON.stringify(local)).toContain('PRIVATE_TWO_PASS_CANARY');+ const remote = await hybridSearch(engine, 'publicanchor', { ...opts, requireSafeChunks: true });+ expect(remote.map(row => row.slug)).toContain(slug);+ expect(JSON.stringify(remote)).not.toContain('PRIVATE_TWO_PASS_CANARY');+ expect(remote.map(row => row.slug)).not.toContain('src-b-ts');+ });});describe('Layer 7 (A2) — query operation schema', () => {