Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.46.9.1 feat(coverage,refactor): containment sprint — merged coverage measurement, module-size ratchet, monolith peels (#4173)

Garry Tanc11c0fe24c7c
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index ce7020d052..dc9ed47876 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -155,6 +155,15 @@ jobs:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
# #3485 preload guard: this job intentionally tests against a DB.
GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
+ - name: Run engine parity suite
+ # The behavioral parity pin for the two engines (containment-sprint
+ # engine peels lean on it). Own invocation line: this suite has only
+ # ever run one-process-per-file via run-e2e.sh — do not fold it into
+ # the shared-process tier1 line above.
+ run: bun test --timeout=60000 test/e2e/engine-parity.test.ts
+ env:
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
tier2:
name: Tier 2 (LLM Skills)
@@ -240,6 +249,187 @@ jobs:
# dim handling + gateway.rerank against the real provider.
ZEROENTROPY_API_KEY: ${{ secrets.ZEROENTROPY_API_KEY }}
+ # ──────────────────────────────────────────────────────────────────────
+ # Nightly coverage-full pipeline (schedule-only). The honest
+ # "unit + serial + E2E merged" number the containment sprint mandates:
+ # every lane runs WITH coverage inside THIS workflow (no cross-workflow
+ # artifact fetch — that channel is racy by construction), then one merge
+ # job compares against the fullCorpus baseline and uploads the trend
+ # artifact. PR runs never pay this cost; the schedule gate on every job
+ # below is load-bearing.
+ # ──────────────────────────────────────────────────────────────────────
+ coverage-full-unit:
+ if: github.event_name == 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - run: bun install
+ - name: Coverage shard ${{ matrix.shard }}/10
+ run: scripts/test-shard.sh ${{ matrix.shard }} 10
+ env:
+ COVERAGE_DIR: ${{ runner.temp }}/coverage
+ - name: Upload coverage
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-full-shard-${{ matrix.shard }}
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
+
+ coverage-full-serial:
+ if: github.event_name == 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - run: bun install
+ - run: bun run test:serial
+ env:
+ COVERAGE_DIR: ${{ runner.temp }}/coverage
+ - name: Upload coverage
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-full-serial
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
+
+ coverage-full-slow:
+ if: github.event_name == 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - run: bun install
+ # 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
+ - name: Write coverage lane manifest
+ run: |
+ printf '{"lane":"slow","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$GITHUB_SHA" "$(find "$RUNNER_TEMP/coverage" -name lcov.info | wc -l | tr -d ' ')" \
+ > "$RUNNER_TEMP/coverage/lane-manifest.json"
+ - name: Upload coverage
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-full-slow
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
+
+ coverage-full-e2e:
+ if: github.event_name == 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ services:
+ postgres:
+ image: pgvector/pgvector:pg16
+ env:
+ POSTGRES_PASSWORD: postgres
+ POSTGRES_DB: gbrain_test
+ ports:
+ - 5432:5432
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - run: bun install
+ - 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
+ # E2E_FILE_TIMEOUT_SECS survive. 300s/file absorbs instrumentation
+ # overhead on the slowest files (the default cap is 180s).
+ run: bash scripts/run-e2e.sh
+ env:
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test
+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
+ COVERAGE_DIR: ${{ runner.temp }}/coverage
+ E2E_FILE_TIMEOUT_SECS: '300'
+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
+ ZEROENTROPY_API_KEY: ${{ secrets.ZEROENTROPY_API_KEY }}
+ - name: Upload coverage
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-full-e2e
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
+
+ coverage-full-report:
+ needs: [coverage-full-unit, coverage-full-serial, coverage-full-slow, coverage-full-e2e]
+ if: always() && github.event_name == 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ with:
+ fetch-depth: 0 # baseline gate reads git show origin/master:
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - run: bun install
+ - name: Download per-lane coverage artifacts
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ pattern: coverage-full-*
+ path: ${{ runner.temp }}/coverage-artifacts
+ - name: Merge full corpus
+ env:
+ COVERAGE_CORPUS: fullCorpus
+ run: |
+ bun scripts/merge-lcov.ts \
+ --out-lcov "$RUNNER_TEMP/coverage-full-merged/lcov.info" \
+ --out-json "$RUNNER_TEMP/coverage-full-merged/summary.json" \
+ --manifest-expect shard-1,shard-2,shard-3,shard-4,shard-5,shard-6,shard-7,shard-8,shard-9,shard-10,serial,slow,e2e \
+ "$RUNNER_TEMP/coverage-artifacts"
+ - name: Coverage summary → step summary
+ run: bun scripts/render-coverage-summary.ts --summary "$RUNNER_TEMP/coverage-full-merged/summary.json" --structural scripts/structural-suites.tsv >> "$GITHUB_STEP_SUMMARY"
+ - name: Baseline gate (fullCorpus, like-for-like)
+ # shell: bash → pipefail, so tee can't mask the gate's exit code.
+ shell: bash
+ env:
+ COVERAGE_GATE_ENFORCE: '0'
+ run: bun scripts/coverage-baseline-gate.ts --summary "$RUNNER_TEMP/coverage-full-merged/summary.json" --corpus fullCorpus | tee -a "$GITHUB_STEP_SUMMARY"
+ - name: Upload merged full-corpus coverage (trend artifact)
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-full-merged
+ path: ${{ runner.temp }}/coverage-full-merged
+ retention-days: 30
+ if-no-files-found: ignore
+ overwrite: true
+
# ──────────────────────────────────────────────────────────────────────
# e2e-cache-write: seals e2e-pass-<hash> only when every gated job
# succeeded (writing earlier would bless states the suite never proved).
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index ad11c4a9f9..2d5a3682cc 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -205,6 +205,17 @@ jobs:
key: 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 --frozen-lockfile
- run: bun run test:serial
+ env:
+ COVERAGE_DIR: ${{ runner.temp }}/coverage
+ - name: Upload coverage (serial lane)
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-serial
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
slow-eval-longmemeval:
# Dedicated runner for the LongMemEval end-to-end test file. The file
@@ -238,7 +249,21 @@ jobs:
- run: bun install --frozen-lockfile
- name: Ensure PGLite snapshot (build-or-validate, non-fatal)
run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-eval && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'
- - run: bun test test/eval-longmemeval-e2e.slow.test.ts --timeout=60000
+ - run: bun test test/eval-longmemeval-e2e.slow.test.ts --timeout=60000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/sloweval
+ - name: Write coverage lane manifest
+ run: |
+ printf '{"lane":"sloweval","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$GITHUB_SHA" "$(find "$RUNNER_TEMP/coverage" -name lcov.info | wc -l | tr -d ' ')" \
+ > "$RUNNER_TEMP/coverage/lane-manifest.json"
+ - name: Upload coverage (slow-eval lane)
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-sloweval
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
brainbench:
# BrainBench memory-conformance gate (Cathedral 2). Hermetic: in-memory
@@ -307,11 +332,27 @@ jobs:
- run: bun install --frozen-lockfile
- name: Ensure PGLite snapshot (build-or-validate, non-fatal)
run: bash -c '. scripts/lib/test-env.sh && ensure_pglite_snapshot slow-perf && echo "GBRAIN_PGLITE_SNAPSHOT=${GBRAIN_PGLITE_SNAPSHOT:-}" >> "$GITHUB_ENV"'
- - run: bun test test/entity-resolve-perf.slow.test.ts --timeout=300000
+ # Two bun processes: each needs its own coverage dir (a reused dir is
+ # silently overwritten by the second process).
+ - run: bun test test/entity-resolve-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-a
# MEMORY_VERBS v1 (Cathedral 1): the entity() p99 < 100ms contract gate
# (20K-page corpus + ratio guard) shares this runner — same perf-job
# shape, runs in parallel with the matrix.
- - run: bun test test/entity-card-perf.slow.test.ts --timeout=300000
+ - run: bun test test/entity-card-perf.slow.test.ts --timeout=300000 --coverage --coverage-reporter=lcov --coverage-dir=${{ runner.temp }}/coverage/perf-b
+ - name: Write coverage lane manifest
+ run: |
+ printf '{"lane":"slowperf","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$GITHUB_SHA" "$(find "$RUNNER_TEMP/coverage" -name lcov.info | wc -l | tr -d ' ')" \
+ > "$RUNNER_TEMP/coverage/lane-manifest.json"
+ - name: Upload coverage (slow-perf lane)
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-slowperf
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
# Protocol self-certification: init a scratch brain and run the
# conformance kit against gbrain's own stdio server. --synthesize is
# safe here: no LLM key in CI, so it asserts the clean `unavailable`
@@ -375,6 +416,84 @@ jobs:
- run: bun install --frozen-lockfile
- name: Run test shard ${{ matrix.shard }}/10
run: scripts/test-shard.sh ${{ matrix.shard }} 10
+ env:
+ COVERAGE_DIR: ${{ runner.temp }}/coverage
+ - name: Upload coverage (shard lane)
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-shard-${{ matrix.shard }}
+ path: ${{ runner.temp }}/coverage
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
+
+ # ──────────────────────────────────────────────────────────────────────
+ # coverage-report: merges the PR corpus (10 shards + serial + 2 slow
+ # 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).
+ # `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, test]
+ if: always() && needs.cache-check.outputs.hit != 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ with:
+ fetch-depth: 0 # diff gate needs origin/master; baseline gate reads git show origin/master:
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.3.13
+ - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: ~/.bun/install/cache
+ key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
+ - run: bun install --frozen-lockfile
+ - name: Download per-lane coverage artifacts
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ pattern: coverage-*
+ path: ${{ runner.temp }}/coverage-artifacts
+ - name: Merge lanes
+ env:
+ COVERAGE_CORPUS: prCorpus
+ run: |
+ bun scripts/merge-lcov.ts \
+ --out-lcov "$RUNNER_TEMP/coverage-merged/lcov.info" \
+ --out-json "$RUNNER_TEMP/coverage-merged/summary.json" \
+ --manifest-expect shard-1,shard-2,shard-3,shard-4,shard-5,shard-6,shard-7,shard-8,shard-9,shard-10,serial,sloweval,slowperf \
+ "$RUNNER_TEMP/coverage-artifacts"
+ - name: Coverage summary → step summary
+ run: bun scripts/render-coverage-summary.ts --summary "$RUNNER_TEMP/coverage-merged/summary.json" --structural scripts/structural-suites.tsv >> "$GITHUB_STEP_SUMMARY"
+ - name: Diff coverage gate (report-only until graduation)
+ # shell: bash is load-bearing: the default `bash -e {0}` has NO
+ # pipefail, so the tee pipe would mask the gate's exit code — the
+ # graduated gate could never fail the job.
+ shell: bash
+ env:
+ COVERAGE_GATE_ENFORCE: '0'
+ run: bun scripts/coverage-diff-gate.ts --summary "$RUNNER_TEMP/coverage-merged/summary.json" | tee -a "$GITHUB_STEP_SUMMARY"
+ - name: Baseline gate (prCorpus, like-for-like)
+ shell: bash
+ env:
+ COVERAGE_GATE_ENFORCE: '0'
+ run: bun scripts/coverage-baseline-gate.ts --summary "$RUNNER_TEMP/coverage-merged/summary.json" --corpus prCorpus | tee -a "$GITHUB_STEP_SUMMARY"
+ - name: Upload merged coverage
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: coverage-merged
+ path: ${{ runner.temp }}/coverage-merged
+ retention-days: 14
+ if-no-files-found: ignore
+ overwrite: true
# ──────────────────────────────────────────────────────────────────────
# cache-write: ONLY runs when every gated job succeeded. Writes the
diff --git a/.gitignore b/.gitignore
index da4b7dc431..bf475eac44 100644
--- a/.gitignore
+++ b/.gitignore
@@ -49,3 +49,7 @@ test/fixtures/pglite-snapshot.version
# Private brain reports — never check these in (per CLAUDE.md privacy rule)
reports/network-intelligence/
+
+# Coverage lane output (COVERAGE_DIR opt-in in test-shard.sh /
+# run-serial-tests.sh / run-e2e.sh; merged by scripts/merge-lcov.ts)
+.coverage/
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index d15731911f..01ee57d893 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.46.8.0 -->
+<!-- gbrain-runbook-stamp: 0.46.9.1 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 64cbcabdfa..cf7bdadbea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,65 @@
All notable changes to GBrain will be documented in this file.
+## [0.46.9.1] - 2026-08-16
+
+**Coverage is now measured, honestly, on every PR — and the six giant modules stopped growing.**
+
+### Added
+- **Merged code-coverage reporting in CI.** Every PR run now collects per-lane
+ lcov from the 10 unit shards, the serial lane, and the two slow jobs, merges
+ them (`scripts/merge-lcov.ts`), and renders one honest number to the run
+ summary — with lane-completeness manifests, a degraded banner when a lane is
+ missing, a never-loaded-file list instead of fake all-files math, and
+ behavioral-vs-structural test counts side by side. A nightly pipeline runs
+ every lane INCLUDING the full real-Postgres e2e glob inside one workflow for
+ the true unit+serial+E2E merged number.
+- **Diff-coverage gate (report-only, graduating).** New and changed source
+ lines are held to an 80% coverage bar with a per-file uncovered-line table on
+ every PR. It reports without blocking until the measurement machinery has two
+ weeks of receipts, then flips to enforcing via a one-line change. Escape
+ hatch: a `[coverage-exempt: reason]` commit trailer. A corpus-matched
+ baseline gate (brainbench-style governance against origin/master's committed
+ baseline) catches whole-repo regressions.
+- **Module-size ratchet.** `check:module-size` (in `bun run verify`) pins every
+ oversized file to a committed ceiling: growth fails, stale slack after a
+ shrink fails, and any unlisted src file over 1,500 lines fails. Growing a
+ giant now requires a reviewer-visible edit to
+ `scripts/module-size-limits.tsv`. The append-only migrations file is
+ region-aware: the migration array grows freely while the runner logic around
+ it is ratcheted.
+- **Test-intent classification.** `scripts/classify-tests.ts` separates suites
+ that execute product behavior from suites that assert on source/doc text
+ (wiring guards, drift pins), with a freshness-checked committed inventory —
+ so the headline test count stops conflating the two.
+- The 34-test behavioral engine-parity suite now runs in CI on every PR and
+ push to master (it previously only ran locally).
+
+### Changed
+- **The four biggest modules are now façades over focused modules** (~19,500
+ lines peeled, behavior unchanged and pinned by the existing parity/guard
+ suites): the operations contract assembles from `src/core/ops/*` domain
+ modules; doctor's check library lives in `src/commands/doctor/checks/*`
+ bundles plus four tail-cluster modules; sync's cost-gate/git/anchor/lock/
+ reconcile/status-report clusters live in `src/core/sync-*`; and both database
+ engines delegate their facts/takes/code-edges/salience method groups to
+ narrow-interface modules, moved in lockstep and verified against live
+ Postgres. Every façade re-exports its full prior surface, so imports and the
+ published package exports are unchanged.
+- The CLI flag-registry generator understands the new façade layout, so
+ command flag surfaces are byte-identical to before the split.
+
+### Fixed
+- Structural guard tests that pinned source text in the peeled files now read
+ the whole module surface (or the specific post-peel file), so a future move
+ can never silently blind a guard.
+
+To take advantage of v0.46.9.1: upgrade normally — no schema changes, no
+config changes, no action required. Contributors get the new guards
+automatically via `bun run verify`; coverage numbers appear in each CI run's
+summary. If `check:module-size` fails on your branch, the message names the
+exact ceiling to raise (a conscious, reviewer-visible TSV edit) or — better —
+the sibling module dir to put the new code in.
## [0.46.8.0] - 2026-08-15
**The full local test suite is trustworthy again.** `bun run test` and
diff --git a/CLAUDE.md b/CLAUDE.md
index c9194a405b..29609aa55f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -105,6 +105,26 @@ Per-file detail is in `docs/architecture/KEY_FILES.md`.
(fail-closed vs warn-only vs null), not its own numbers. Pinned by `test/model-pricing.test.ts`
(drift guard asserts each view equals canonical). Embeddings price separately in
`embedding-pricing.ts` (different unit).
+- **Module-size ratchet.** `scripts/module-size-limits.tsv` pins per-file line ceilings
+ (`check:module-size` in verify): growth over a ceiling, >50 lines of stale slack after a
+ shrink, a row for a deleted file, and any UNLISTED src file over 1,500 lines all fail.
+ Raise a ceiling only via a reviewer-visible TSV edit in the same commit; lower it in the
+ same commit as any peel. migrate.ts is `region-exempt` (the MIGRATIONS array grows freely;
+ the runner logic around it is ratcheted).
+- **Peeled façades keep their surface.** operations.ts (`src/core/ops/*`), doctor.ts
+ (`src/commands/doctor/*`), sync.ts (`src/core/sync-*`), and both engines
+ (`src/core/{postgres,pglite}-engine/*`) are façades re-exporting everything they always
+ exported — import sites and published package exports never chase the peel. New code goes
+ in the module dirs, not back into the façades. Engine modules take narrow explicit deps
+ (never an engine-shaped bag); doctor source-text guards read `test/helpers/doctor-source.ts`,
+ and the flag-registry generator's `facadeExpansion` keeps peeled flag text in each command's
+ scan surface.
+- **Coverage is measured, honestly.** CI merges per-lane lcov (`scripts/merge-lcov.ts`) into
+ a PR-corpus report on every run (advisory until the diff gate graduates via
+ `COVERAGE_GATE_ENFORCE`) and a nightly fullCorpus number incl. the full e2e glob. bun
+ facts: unique `--coverage-dir` per process (reuse overwrites lcov.info), line records only
+ (JSC omits function names), no subprocess coverage (cli.ts is exempt as a documented
+ undercount), never-loaded files are a count+list, never fake all-files math.
## Reference map (load on demand)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 87aa7441a8..030e6f64db 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -45,14 +45,21 @@ directly. Keep that prefix when you add a new shell-script check.
src/
cli.ts CLI entry point
commands/ CLI-only commands (init, upgrade, import, export, etc.)
+ doctor.ts gbrain doctor façade (buildChecks/runDoctor/output)
+ doctor/ Peeled doctor modules: checks/* bundles + tail clusters
+ sync.ts gbrain sync CLI + performSync/performFullSync
core/
- operations.ts Contract-first operation definitions (the foundation)
+ operations.ts Operation contract assembly (façade over ops/)
+ ops/ Contract types + security fences + the op domain modules
engine.ts BrainEngine interface
engine-factory.ts Engine factory (dynamic import of the configured engine)
- postgres-engine.ts Postgres + pgvector implementation
- pglite-engine.ts PGLite (embedded Postgres via WASM) implementation
+ postgres-engine.ts Postgres + pgvector implementation (façade)
+ postgres-engine/ Narrow-deps engine modules (facts, takes, code-edges, salience)
+ pglite-engine.ts PGLite (embedded Postgres via WASM) implementation (façade)
+ pglite-engine/ Narrow-deps engine modules (facts, takes, code-edges, salience)
db.ts Connection management + schema loader
import-file.ts Import pipeline (chunk + embed + tags)
+ sync-*.ts Peeled sync clusters (cost-gate, git, anchor, lock, reconcile, status-report, ...)
types.ts TypeScript types
markdown.ts Frontmatter parsing
config.ts Config file management
@@ -199,10 +206,16 @@ bun build --compile --outfile bin/gbrain src/cli.ts
## Adding a new operation
-GBrain uses a contract-first architecture. Add your operation to one file and it
-automatically appears in the CLI, MCP server, and tools-json:
+GBrain uses a contract-first architecture. Add your operation to one domain module
+and it automatically appears in the CLI, MCP server, and tools-json:
-1. Add your operation to `src/core/operations.ts` (define params, handler, cliHints)
+1. Add your operation to the matching domain module under `src/core/ops/`
+ (`pages.ts`, `search.ts`, `takes.ts`, `jobs.ts`, ... — define params, handler,
+ cliHints there). `src/core/operations.ts` is the assembly façade that spreads
+ every domain module into the single `operations` array: a new op in an existing
+ domain needs no façade change; a brand-new domain module gets one spread line
+ in `operations.ts`. Shared contract types live in `src/core/ops/contract.ts`,
+ the security/scope fences in `src/core/ops/context.ts`.
2. Add tests
3. That's it. The CLI, MCP server, and tools-json are generated from operations.
@@ -298,9 +311,9 @@ Trigger paths (rerun if your diff touches any of these):
- `src/core/search/hybrid.ts`
- `src/core/search/source-boost.ts`, `sql-ranking.ts`
-- `src/core/search/intent.ts`, `expansion.ts`, `dedup.ts`
+- `src/core/search/query-intent.ts`, `expansion.ts`, `dedup.ts`
- `src/core/embedding.ts`
-- `src/core/operations.ts` (query / search handlers)
+- `src/core/ops/search.ts` (query / search op handlers)
- `src/core/postgres-engine.ts` / `pglite-engine.ts` (searchKeyword /
searchVector SQL)
diff --git a/TODOS.md b/TODOS.md
index 559a64bc6e..c81bf75f87 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,66 @@
# TODOS
+## Containment-sprint follow-ups (coverage truth + module peels; plan: ~/.claude/plans/system-instruction-you-are-working-serialized-forest.md)
+
+- [ ] **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
+ the 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
+ green 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 the
+ measurement machinery has receipts. Review `scripts/coverage-gate-exemptions.txt` against
+ report-only-window data in the same PR (shrink what gained unit coverage, add only what
+ repeatedly false-positives). **Adversarial acceptance items for the same PR:** decide the
+ enforce-mode degraded posture (today degraded -> report-only, which post-graduation is a
+ bypass channel - fail loud, or require explicit re-run); set a baseline re-seed cadence so
+ serial sub-threshold drops (<=0.49pp) cannot compound unboundedly. **Effort:** S. **Priority:** P1.
+- [ ] **P2 — Wave 4a: decompose performSyncInner (own plan).** **What:** the 1,923-line
+ procedure inside src/commands/sync.ts → sync-phase-{deletes,renames,imports} modules.
+ **Why:** the six pure clusters are peeled (sync.ts 5,991→4,121); the remaining bulk is one
+ function. **Blocked by:** re-pointing the two positional source-text guards
+ (test/sync.test.ts #132 prelude scan, test/redos-hardening.test.ts ordering) at the phase
+ modules — needs its own plan. **Effort:** L→M with CC. **Priority:** P2.
+- [ ] **P2 — Wave 4b: hoist buildChecks' ~220 inline checks.push literals into named
+ functions, then finish the doctor split (own plan).** **What:** doctor.ts is 4,177 lines,
+ ~3,240 of them buildChecks. Hoisting the inline literals into named check functions makes
+ them movable into the checks/ bundles. **Why:** completes the assessment's #1 named peel
+ target. **Effort:** L→M with CC. **Priority:** P2.
+- [ ] **P2 — CLI subprocess coverage.** **What:** investigate an in-process CLI-invocation
+ harness for a coverage lane (import cli.ts main instead of spawning) and track bun
+ child-process coverage support upstream. **Why:** E2E-spawned `bun src/cli.ts` children are
+ invisible to bun's coverage (the documented 15.2% cli.ts undercount);
+ src/cli.ts sits in the gate exemption list until this closes. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Migrate-runner extraction (revisit only on evidence).** **What:** the ~668
+ region-guarded runner lines in src/core/migrate.ts could move to migrate-runner.ts.
+ **Why deferred:** 9 slice-window source-text assertions in test/migrate.test.ts pin
+ locality; the region-exempt ratchet already forbids logic growth. Revisit if the region
+ guard starts failing on legitimate runner work. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Shrink coverage-gate-exemptions.txt as engine unit coverage rises.** **What:**
+ the engine files + dirs are exempt because the PR corpus can't see their e2e coverage;
+ nightly fullCorpus data shows their true numbers (postgres-engine 40% merged). As narrow-deps
+ modules gain unit tests, delist them. **Effort:** S per file. **Priority:** P3.
+- [ ] **P3 — Branch coverage when bun ships it.** **What:** bun 1.3.x emits line+function
+ lcov only (and JSC omits function names). When branch records (BRDA) land upstream, extend
+ merge-lcov.ts and report branch coverage. **Effort:** S. **Priority:** P3.
+- [ ] **P2 — Local shard-1 SIGTERM self-kill under load (master-inherited).** **What:** the
+ local fast loop's shard 1/4 dies rc=143 with ZERO test failures ~50–85s in when the machine
+ carries concurrent bun-test load: an `extract.stale` abort observes SIGTERM and the parent
+ bun process dies (`[run-child] job ... not claimed` lines adjacent). Reproduced
+ byte-identically on a clean master worktree (`SHARD=1/4 bash scripts/run-unit-shard.sh
+ --max-concurrency=2`), so it predates the containment sprint — most plausibly a
+ process-group signal escaping a per-job isolation test (#4151 landed the process-isolation
+ lane). **Why:** a self-killing shard reads as CI/local flake and poisons full-suite runs.
+ **Where to start:** the shard-1 file set's isolation/lifecycle tests
+ (test/run-child-entry.test.ts, test/worker-job-isolation.test.ts, test/extract-stale.test.ts)
+ — audit for kill(0)/process-group signals under contention. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Evidence-gated engine-core dedup.** **What:** the narrow-deps engine modules
+ (facts/takes/code-edges/salience × both engines) are the stepping stone toward a shared
+ engine core, NOT the substitute. The prior proposal drew 15 substantive review objections
+ (see the earlier module-singleton TODO) — pull this in only when parity maintenance costs
+ demonstrably recur. **Effort:** XL→L with CC. **Priority:** P3.
## Codex/Claude plugin lane follow-ups (filed from the plugin packaging wave)
- [ ] **Plugin-lane receipt provenance: re-run bootstrap after plugin install can strand a hand-wired registration.** `appendReceiptRegistration` dedups by (host, scope), so wiring via bootstrap (detail:`mcp`) → enabling the plugin → re-running `bootstrap hooks` overwrites the record with `plugin-mcp`; the plugin-owned uninstall guard then skips `mcp remove` forever, stranding the registration bootstrap itself created. Narrow sequence (plugin enabled AFTER a hand-wired bootstrap). Fix: on the plugin-owned skip, don't downgrade an existing `mcp`-detail record for the same (host,scope), or offer to remove the stale hand-wired entry. Priority: P3. Surfaced by the ship-stage red-team review of the codex-plugin wave.
diff --git a/VERSION b/VERSION
index 0a747c2fb5..c97ece44cc 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.46.8.0
\ No newline at end of file
+0.46.9.1
\ No newline at end of file
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 1f0368a0fa..70f29201be 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -72,7 +72,7 @@ handler-source hash sensitivity).
### Guard registry and self-test
`scripts/guards-manifest.tsv` is THE single registry of `scripts/check-*`
-guards (currently 45), each classified `scanner` (greps/parses repo sources —
+guards (currently 48), each classified `scanner` (greps/parses repo sources —
must eventually carry fixtures), `buildfresh`, or `repostate` (build/freshness
guards are exempt-with-reason, not fixture-tested).
`scripts/guard-self-test.sh` (`bun run check:guard-self-test`, wired into
@@ -117,6 +117,114 @@ there even though they pass on Linux and macOS.
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.
+### Coverage lanes and gates
+
+Line coverage is opt-in via `COVERAGE_DIR`: when set, the shell lanes
+(`scripts/test-shard.sh`, `scripts/run-serial-tests.sh`, `scripts/run-e2e.sh`)
+pass `--coverage --coverage-reporter=lcov` to bun; when unset, the exec line is
+byte-identical to a non-coverage run. Every bun process gets its OWN coverage
+dir (`$COVERAGE_DIR/shard`, `serial-$idx`, `e2e-$idx`) because a reused dir
+silently overwrites `lcov.info` — the shard runner also pins xargs to a single
+batch (`-n 100000 -x`) so an argv overflow fails loud instead of spawning a
+second, overwriting bun process. On a green run each lane writes
+`$COVERAGE_DIR/lane-manifest.json` (`{lane, sha, lcovCount, complete}`); a red
+run writes no manifest, which downstream merging treats as an incomplete lane.
+`run-e2e.sh` specifics: `COVERAGE_DIR` is normalized to an absolute path
+against the repo root before `HOME` moves (the script redirects
+`HOME`/`GBRAIN_HOME` and E2E tests spawn CLI subprocesses with varying cwd —
+an un-normalized relative dir would scatter output), and `E2E_FILE_TIMEOUT_SECS`
+caps each file's wallclock (default 180s; the nightly coverage lane uses 300s
+for instrumentation overhead). Both env names are deliberately
+non-`GBRAIN_`-prefixed so the hermetic env scrub keeps them.
+
+**Two corpora.**
+
+- **PR corpus** (`prCorpus`) — the 13 coverage-collecting lanes in
+ `.github/workflows/test.yml`: the 10 matrix shards, `serial-tests`, and the
+ two dedicated slow jobs. Deterministic (runs identically on every PR); this
+ is the corpus the gates run against.
+- **fullCorpus** — nightly, schedule-only in `.github/workflows/e2e.yml`:
+ `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report`. Fully
+ self-contained (every lane re-runs with coverage inside that workflow,
+ including the full `test/e2e/*` glob against real Postgres) — the honest
+ merged unit+serial+slow+e2e number, kept as the `coverage-full-merged` trend
+ artifact.
+
+**Merge** (`scripts/merge-lcov.ts`). Walks the input dirs for `lcov.info` +
+`lane-manifest.json`, sums DA hits per file:line, normalizes paths
+repo-relative, and emits a merged lcov plus a summary JSON: src-only
+totals/per-dir/per-file percentages, a `lineHits` map (the diff gate's input),
+and the never-loaded src file list. `--manifest-expect lane,lane,...` pins the
+expected lane set; a missing or `complete: false` manifest, an unparseable
+lcov, or a `shard` lane with `lcovCount != 1` marks the summary
+`degraded: true`. Degraded is data, not failure: the merge never aborts (exit
+0), and both gates print `WOULD PASS`/`WOULD FAIL` and exit 0 on a degraded
+summary instead of enforcing against partial data.
+
+**Diff gate** (`scripts/coverage-diff-gate.ts`). Gates the added/changed lines
+of `git diff origin/master...HEAD` restricted to gate scope (`src/**.ts` minus
+`*.test.ts`/`*.generated.ts`/`*.d.ts`): covered/(covered+uncovered) must be
+≥ 80%, AND no gate-scoped changed file may be entirely absent from the
+coverage data (a never-loaded file is one violation — add a test that imports
+it). Non-executable lines (no lcov record) don't count against you; empty and
+doc-only diffs short-circuit to PASS via the `select-e2e` classifier. Escape
+hatches: a commit body containing `[coverage-exempt: reason]` passes with a
+loud warning, and `scripts/coverage-gate-exemptions.txt` (exact path or
+trailing-`/` prefix per line; resolved via
+`git show origin/master:scripts/coverage-gate-exemptions.txt`, never the
+working tree, so a PR cannot self-exempt; SHRINK-ONLY — additions need a
+graduation review in the PR description) excludes paths from the gate while
+still reporting them
+(`[e2e-exempt]`, `[subprocess-undercount]`). Report-only unless
+`COVERAGE_GATE_ENFORCE=1`. Exit contract: 0 = pass or report-only, 1 = gate
+fail while enforcing, 2 = infrastructure error (missing summary, git failure —
+never conflated with a coverage verdict).
+
+**Baseline gate** (`scripts/coverage-baseline-gate.ts`). Anti-erosion floor:
+reads the baseline via `git show origin/master:scripts/coverage-baseline.json`
+— the master copy, never the working tree, so a PR cannot weaken its own bar —
+and compares like-for-like by corpus (`--corpus prCorpus` in test.yml,
+`--corpus fullCorpus` nightly). A global drop > 0.5pp, a per-directory drop
+> 1.0pp, or a never-loaded-count increase fails (deleting tests shrinks the
+coverage denominator, which inflates pct for free); a corpus section that is
+`null` on master is an ungated first landing. `provisional: true` in the baseline keeps the gate report-only
+regardless of enforcement — the committed baseline is currently provisional
+with both corpus sections unseeded. `scripts/update-coverage-baseline.ts
+--summary <json> --corpus <c> [--promote]` writes the working-tree baseline
+(per-file detail limited to the baseline's `watchlist`); `--promote` flips
+`provisional: false` at graduation.
+
+**CI wiring.** The 13 PR lanes upload `coverage-*` artifacts; the advisory
+`coverage-report` job downloads + merges (`COVERAGE_CORPUS=prCorpus`), renders
+`scripts/render-coverage-summary.ts` to the step summary (including the
+behavioral-vs-structural counts from `scripts/structural-suites.tsv`), and
+runs 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.
+
+**Bun caveats.** Bun/JSC emits line records only, so function coverage is
+informational (no reliable function names). There is NO subprocess coverage:
+code exercised only through spawned CLI subprocesses undercounts — `src/cli.ts`
+carries a permanent `[subprocess-undercount]` exemption for this. A src file
+never imported by any test produces no lcov record at all; the summary reports
+these as a count + sorted list, deliberately never a percentage (physical
+lines ≠ executable lines), and the diff gate treats a changed-but-never-loaded
+file as a violation.
+
+**One-command local smoke** (one shard of ten, so totals reflect a tenth of
+the corpus — this checks the plumbing, not the number):
+
+```bash
+COVERAGE_DIR=$PWD/.coverage bash scripts/test-shard.sh 1 10 \
+ && bun scripts/merge-lcov.ts --out-lcov .coverage/merged.lcov --out-json .coverage/summary.json .coverage \
+ && bun scripts/render-coverage-summary.ts --summary .coverage/summary.json
+```
+
+Optional flags: `coverage-diff-gate.ts --base <ref>` overrides the diff base
+(default `origin/master`); `render-coverage-summary.ts --structural
+scripts/structural-suites.tsv` adds the behavioral-vs-structural split to the
+rendered summary (both CI lanes pass it); `classify-tests.ts --summary` prints
+counts only.
+
### Failure-first logging
When `bun run test` finds any failure, the wrapper:
@@ -142,6 +250,13 @@ Triage rule: a `warn-pass` EXIT-HANG line in `.context/test-summary.txt` is NOT
- `tests/heavy/*.sh` → ops-shape shell scripts. Cost minutes per run; NOT in default `bun test`. Run via `bun run test:heavy` or scheduled nightly via `.github/workflows/heavy-tests.yml`. Examples: pg_upgrade matrix (boot legacy brain → walk to head), RSS budget gate (measure peak worker RSS vs committed baseline), read-latency-under-sync (p50/p95/p99 under concurrent writer load), sync lock regression (N concurrent syncs assert 1 winner + N-1 lock-busy + zero leaked `gbrain_cycle_locks` rows). See `tests/heavy/README.md` for when to add a script here vs `*.slow.test.ts`. Files prefixed with `_` (e.g. `tests/heavy/_build_legacy_fixtures.sh`) are helpers/libs invoked by sibling tests — the runner skips them.
- `test/fuzz/*.test.ts` → property-based fuzz harness. Pure-validator targets in `pure-validators.test.ts` are guarded by `scripts/check-fuzz-purity.sh` (in `bun run verify`), which `bun build --target=bun` bundles each target and greps the resulting bundle for banned transitive imports (`node:fs`, `node:child_process`, engine modules). Anything that fails the guard moves to `mixed-validators.test.ts` (still property-tested, but no purity guarantee) or `filesystem-validators.test.ts` (fs-backed, uses temp dirs). Fuzz tests run in the default `bun test` loop because they're fast (~3s for ~12 properties × 1000 runs each).
+The taxonomy above is LANE-based (where a test runs). A second, orthogonal axis is INTENT:
+
+- **Behavioral** tests execute product code and assert on behavior — the default.
+- **Structural** (source-shape) suites read repo source/doc TEXT and assert on its shape (wiring guards, drift pins, `doctorSource()` consumers). They are real invariants but execute no product paths, so they inflate the headline test count without adding line coverage. The committed inventory is `scripts/structural-suites.tsv`, generated by `scripts/classify-tests.ts` (suite-level, content-based detectors: repo-anchored `readFileSync`/`Bun.file` readers, grep-style exec scanners, the doctor-source helpers) and freshness-checked in `bun run verify` (`check:structural-manifest` — regenerate with `bun scripts/classify-tests.ts` when suites change shape). The inventory is approximate by design; fix misclassifications in the classifier's detector list, never by hand-editing the TSV. CI's coverage report renders behavioral vs structural counts side by side.
+
+Guards that pin doctor source text read it through `test/helpers/doctor-source.ts` (`doctorSource()` = the façade + every `src/commands/doctor/**` module, for containment assertions; `doctorFileSource(rel)` = one named file, for positional/ordering assertions) so peeling doctor.ts into modules can't silently move a pinned string out of a guard's sight.
+
### TTY and interactive-CLI testing
Four escalating tools; reach for the cheapest one that answers the question:
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 2582bea6fe..63057162fd 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -11,7 +11,8 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `docs/operations/conversation-parser-llm-fallback.md` — operator and maintainer contract for the default-off LLM parse fallback: exact config key, deterministic-first dispatch boundary, sampled data surface, untrusted-content prompt handling, page-date/cache-key coupling, timestamp validation, cache/checkpoint behavior, observability, limitations, and focused test commands.
-- `src/core/operations.ts` — Contract-first operation definitions (the foundation). Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link skipped only when `remote=true && !trustedWorkspace`. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Plain-startsWith semantics matching `submit_agent`'s check for the same column (NOT the glob grammar of the subagent allow-list); empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the v85 `<prefix>/*` glob spelling via `normalizeSlugPrefix` (the column predates this fence as submit_agent's binding, so one stored value must mean one span of slugs on both paths), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` applies the same boundary-aware rule when validating a requested prefix against the binding, normalizes trailing-slash prefixes to the glob form `matchesSlugAllowList` expects before handing them to the child job, and collapses an EXPLICIT empty `allowed_tools`/`allowed_slug_prefixes` to the binding (the worker reads empty as "full registry" / "legacy `wiki/agents/<id>/` namespace", so `??` — which only substitutes null/undefined — left a vacuous-subset bypass). `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` but NO `auth`, so an auth-only test let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (closes the HTTP MCP shell-job RCE where a read+write OAuth token could submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface (#1941): `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
+- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link skipped only when `remote=true && !trustedWorkspace`. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Plain-startsWith semantics matching `submit_agent`'s check for the same column (NOT the glob grammar of the subagent allow-list); empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the v85 `<prefix>/*` glob spelling via `normalizeSlugPrefix` (the column predates this fence as submit_agent's binding, so one stored value must mean one span of slugs on both paths), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` applies the same boundary-aware rule when validating a requested prefix against the binding, normalizes trailing-slash prefixes to the glob form `matchesSlugAllowList` expects before handing them to the child job, and collapses an EXPLICIT empty `allowed_tools`/`allowed_slug_prefixes` to the binding (the worker reads empty as "full registry" / "legacy `wiki/agents/<id>/` namespace", so `??` — which only substitutes null/undefined — left a vacuous-subset bypass). `put_page` additionally fences the RESOLVED slug when importFromContent's dedup pre-check redirects the write to a different page (same content_hash / `frontmatter.id`), since the disk write-through runs against that slug. That re-check applies whichever confinement the CALLER is under — OAuth binding and/or subagent allow-list/legacy namespace — via `slugOutsideCallerFence(ctx, slug)`, which composes `slugUnderBoundPrefixes` with the subagent fence's own match rule: the delegated `submit_agent` → subagent context carries `viaSubagent` + `allowedSlugPrefixes` but NO `auth`, so an auth-only test let a slug-bound client holding `agent` scope reach an out-of-fence page simply by delegating the write. Denials never name the resolved slug (it would be a slug-enumeration oracle). Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/e2e/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (closes the HTTP MCP shell-job RCE where a read+write OAuth token could submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `linkReadScopeOpts(ctx)` is the link-read sibling for `get_links`/`get_backlinks`: a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page`'s inline disk write-through is the shared `writePageThrough` helper (`src/core/write-through.ts`), ATOMIC via temp-sibling + rename so a crash or concurrent `gbrain sync` can't read a half-written `.md`; same helper backs `gbrain brainstorm/lsd --save`. Link provenance surface (#1941): `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).
+- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.
- `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 replacing the `getAllSlugs()→getPage(slug)` N+1 (which silently defaulted 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`. 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`. 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; back-compatible — no opts gives prior 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, closing the planner-non-determinism class where a new index on `pages` could 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.
- `src/core/background-work.ts` (#1762/#1745/#1775) — process background-work registry: the single owner of "drain every fire-and-forget DB-write sink before the CLI disconnects." `registerBackgroundWorkDrainer({name, order, drain(timeoutMs), abort?})` + `drainAllBackgroundWorkForCliExit({timeoutMs})` over a `Map<name, BackgroundWorkDrainer>` (idempotent registration by name; `__registerDrainerForTest` returns an unregister handle). 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`. Best-effort per drainer: one sink's failure never blocks the others or the disconnect. FIVE 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, #2095 — batched volunteer-event INSERTs, drained like the rest). Every cli.ts teardown site reaches it through `finishCliTeardown` (`src/core/cli-force-exit.ts`), which drains the registry before `engine.disconnect()` — closing the PGLite busy-loop where `db.close()` raced an in-flight job and pinned the single-writer lock (#1762). Exports `backgroundWorkSinkCount()` so the teardown helper computes its backstop deadline from the registered sink count. 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 — #1745); `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 (#1775). Incorporates + hardens PR #1763 (@ElliotDrel). 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`.
@@ -27,13 +28,15 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/search.ts:gbrain search stats` — `graph_signals` section (enabled/source/failures_count/failures_by_reason). JSON envelope adds a `graph_signals` sibling property; `_meta.metric_glossary` adds `graph_signals.enabled` + `graph_signals.failures_by_reason`. Human output prints the section after the existing block. Reads `search.graph_signals` config first, falls back to the mode default. Pinned by `test/search/search-stats-graph-signals.test.ts`. Both `gbrain search stats` and `gbrain search tune` also surface a `coverage` disclosure (JSON: `{cli_invocations: 'typically_not_recorded', reason}`; human: a one-line caveat) sourced from `telemetryCoverage()`/`TELEMETRY_COVERAGE_CAVEAT` in `src/core/search/telemetry.ts`, documenting that the underlying `search_telemetry` buffer favors long-lived processes (serve/MCP/jobs work) and typically drops a lone short-lived CLI search call before its flush timer/threshold fires — display-only, no telemetry behavior change. Pinned by the coverage-disclosure tests in `test/commands-search.test.ts`.
- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`).
-- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown — the #223/#1670/#2575 class, historically misdiagnosed as a macOS WASM bug), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, #3596 engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and modern brains (closes the upgrade-wedge bug class #239/#243/#266/#357/#366/#374/#375/#378/#395/#396/#1018/#974/#820). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode` (#2084): PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and keeps the #223 link; `unknown` is platform-gated per #2674). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.
+- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all BrainEngine methods. The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/pglite-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full prior public surface. `listLinkSources({sourceId?, sourceIds?})` returns distinct `link_source` provenances + counts (`ORDER BY count DESC, link_source ASC NULLS LAST`; scalar + federated scoped; parity with postgres-engine.ts) powering `gbrain link-sources`. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the whole batch as one JSONB document via `jsonb_to_recordset(($1::jsonb)->'rows')` (bound through `executeRawJsonb` with a `{ rows }` wrapper; rows built by the shared `src/core/batch-rows.ts` helpers, NUL-stripped), and are `batchRetry`-wrapped. `connect()` wraps `PGlite.create()` in a try/catch that classifies the failure and, for the `wasm-abort` verdict on a persistent data dir (torn WAL/checkpoint state after an unclean shutdown — the #223/#1670/#2575 class, historically misdiagnosed as a macOS WASM bug), runs in-place auto-repair via `attemptWalRepairAndRetry` (static import from `pglite-repair.ts`, #3596 engine-live rule; the retry create is `preservingProcessExitCode`-wrapped; success sets the public `walRepairReceipt` field + prints `buildWalRepairNotice` to stderr and returns with the lock held). The seam never throws, so every non-repaired path funnels through the single lock-release-then-throw site; repair refuses when the lock was acquired by reaping (`LockHandle.reaped` → `'possibly-live-writer'`), when disabled (`GBRAIN_PGLITE_WAL_REPAIR=off`), on layout-validation failure, or inside the post-failure cooldown. `searchKeyword`/`searchKeywordChunks` multiply `ts_rank` by the source-factor CASE at chunk grain; `searchVector` is a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`, inner LIMIT scales with offset to preserve pagination. `searchTakes`/`searchTakesVector` take full `SearchOpts` and apply the standard source-scope predicates (federated `sourceIds[]` wins over scalar `sourceId`, via the joined page's `source_id`) alongside the holder allow-list — parity SQL in postgres-engine.ts; pinned by `test/e2e/think-source-isolation-pglite.test.ts`. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for forward-referenced state the embedded blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target, plus `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`, `sources.archived_at`, `sources.archive_expires_at`, `timeline_entries.event_page_id` — column-only, migration v121 stays the source of truth for its FK + indexes) and adds only what's missing; threads the DDL connection from `initSchema` so probes run inside the advisory-lock scope; no-op on fresh installs and modern brains (closes the upgrade-wedge bug class #239/#243/#266/#357/#366/#374/#375/#378/#395/#396/#1018/#974/#820). `getBrainScore` returns 100/100 with full breakdown (35/25/15/15/10) when `pageCount === 0` (vacuous truth — empty brain has no coverage problem); Pinned by `test/brain-score-breakdown.test.ts` empty-brain assertion + `test/doctor-report-remote.serial.test.ts`. `disconnect()` uses snapshot+early-null (snapshot `_db`/`_lock`, null instance fields BEFORE any `await` so a concurrent `connect()` can't see a partial mid-close state) wrapped in try/finally guaranteeing lock-release even if `db.close()` throws; KEEPS close-then-release order (release-then-close was rejected: it would widen the window where a sibling process connects to a still-closing brain); Pinned by `test/pglite-engine-disconnect.serial.test.ts`. `PGlite.create()` runs inside `preservingProcessExitCode` (#2084): PGLite's Emscripten runtime writes its own status into `process.exitCode` (99 at create; in-memory brains run initdb whose status lands on a later tick; the exit status at close — and assigning `undefined` cannot clear a prior value), which would otherwise silently clobber an errored op's exit 1 back to 0. The wrapper keeps the global tidy for external readers; `db.close()` stays unwrapped (its 0-write is baseline behavior test runners depend on). The CLI's exit verdict is immune either way — it lives in the gbrain-owned channel in `cli-force-exit.ts` and never reads `process.exitCode` back. Exports `classifyPgliteInitError(message): 'bunfs' | 'wasm-abort' | 'corrupt' | 'unknown'` + `buildPgliteInitErrorMessage(verdict, original, platform?, ctx?)` + `stringifyPgliteInitError(err)` + `buildWalRepairNotice(receipt)` + the `PgliteInitRepairContext` type, routing the catch-block hint by failure shape (`bunfs` matches literal `$$bunfs` OR `ENOENT[\s\S]*pglite\.data` co-occurrence, surfaces a paste-ready `bun upgrade` + Node fallback; `corrupt` — 58P01/`internal_load_library`/missing vector type, catalog corruption WAL repair can't fix — stays matched BEFORE the wasm arm and routes to `reinit-pglite`; `wasm-abort` matches the real production shapes `Aborted()`/`RuntimeError`/`unreachable` plus legacy signatures, names the corrupt-WAL root cause + the recovery ladder (`pglite-repair` → rebuild → engine switch) + what auto-repair did per `ctx` incl. the honesty-critical `failed-not-restored` arm, and keeps the #223 link; `unknown` is platform-gated per #2674). `stringifyPgliteInitError` also surfaces message-less Emscripten objects (`ErrnoError (errno N)`) instead of `[object Object]`. Pinned by `test/pglite-init-classifier.test.ts` + `test/pglite-wal-repair.serial.test.ts` + `test/fix-wave-structural.test.ts`. Implements `deletePages(slugs, {sourceId})` + `resolveSlugsByPaths(paths, {sourceId})` via `slug = ANY($1::text[])` array-param binding, caller-chunking primitive throwing when input exceeds `DELETE_BATCH_SIZE`, `deletePages` returns `RETURNING slug` rows so callers filter `pagesAffected` to confirmed deletes. Implements the embedding-signature stale-detection quartet — `sumStaleChunkChars({sourceId?, signature?})`, `setPageEmbeddingSignature(slug, {sourceId?, signature})`, `invalidateStaleSignatureEmbeddings({signature, sourceId?})`, widened `countStaleChunks({sourceId?, signature?})` (the `signature` opt widens via `JOIN pages p ... WHERE cc.embedding IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $signature)`, NULL grandfathered); parity SQL with postgres-engine.ts. PGLite-specific DDL (pgvector, pg_trgm, triggers). Engine-path helper dependencies (`retry`, ontology, recency decay) avoid dynamic `import()`; the only lazy dynamic imports are `ai/gateway.ts` in `initSchema` and `_upsertChunksOnce`, line-marked because their local catches preserve compiled-default and stored-config fallbacks that eager module evaluation would bypass.
- `src/core/pglite-lock.ts` — advisory data-dir lock so two processes never open the same embedded PGLite (single-connection WASM Postgres) at once. Atomic `mkdir` of `.gbrain-lock/` + a `lock` file carrying `{pid, acquired_at, refreshed_at, command, subcommand}`. A held lock HEARTBEATS its `refreshed_at` every 30s (`.unref()`ed timer; informational). A waiting acquirer reaps a holder ONLY when its PID is dead — a LIVE holder is NEVER stolen, regardless of how stale its heartbeat is (#2348). A live `gbrain serve` holder is identified from the parsed `subcommand` and reported immediately with separate CLI-retry and MCP-tool choices; other live holders keep the bounded wait. The heartbeat runs on the JS event loop, which is blocked during long synchronous WASM imports/CHECKPOINTs, so a working `dream`/`embed` holder can look stale while alive; the old steal-on-stale-heartbeat grace let a second OS process open the same data dir and corrupt the catalog + pgvector extension (58P01 / `internal_load_library` / `type "vector" does not exist`), recoverable only by wipe+restore. A wedged-but-alive or PID-reused holder is never stolen: serve-tagged holders report immediately, while other holders time out with a message naming the PID. Each holder carries an ownership token (`<pid>:<acquired_at>`); the heartbeat and `releaseLock` verify the on-disk lock is STILL theirs before touching it. In-memory engines take no lock. There is deliberately NO same-process reentrancy or same-PID special case: a second `acquireLock` from the process that already holds the lock waits out the timeout like any other live holder (#1963 was this shape — a command double-connecting a second engine on the same data dir; the fix is to reuse the connected engine at the dispatch layer, never to soften the lock). `LockHandle.reaped` marks an acquisition that reaped a prior holder's lock (dead-PID reap or corrupt-lock-file removal — the only reaps that exist post-#2348); the WAL auto-repair gate refuses to run surgery on a reaped acquisition since a corrupt lock file cannot prove its holder is dead. A corrupt-lock reap ALSO writes a persisted marker (`<dataDir>.lock-reap.json`, read via exported `msSinceLastReap`) so the NEXT process's clean acquisition is still repair-quarantined for 10 minutes — the in-process flag alone let the reaper's successor run surgery under a possibly-live writer; dead-PID reaps (affirmative ESRCH verdict; EPERM reads as ALIVE) deliberately skip the marker so dead-holder recovery stays one-failed-command-plus-one-re-run. Heartbeat refreshes write via tmp+rename (a torn in-place write could be read mid-flight by a polling acquirer and misclassify a HEALTHY live holder as a corrupt lock). Pinned by `test/pglite-lock.test.ts`. A corrupted store surfaces a `reinit-pglite` recovery hint via `classifyPgliteInitError`'s `corrupt` verdict in `pglite-engine.ts`.
- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (ported from electric-sql/pglite PR #994 by @yestheboxer, Apache-2.0, rejected upstream as "should be a separate tool" — gbrain is that tool). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.
- `src/core/pglite-repair.ts` — WAL-repair orchestrator wrapping the resetWal port with the safety layers that make it runnable automatically from `connect()`: `validateWalRepairTarget` (read-only, fail-closed; refuses symlinked dataDir/pg_wal/`global`/pg_control — lstat follows INTERMEDIATE symlinks, so `global/` itself must be checked or surgery would write pg_control through it into a foreign dir; tolerates the in-dir `.gbrain-lock`), rename-based backup (the ENTIRE `pg_wal/` dir + postmaster.pid renamed into a sibling `<dataDir>.wal-repair-backup-<ts>/`, only the 8KB pg_control copied — zero transient disk cost), `restoreWalBackup` (overwrite order: control first via atomic tmp+rename, then a pg_wal dir swap with the reset dir set ASIDE inside the backup — nothing is ever deleted during restore; mtime guard refuses when a foreign segment is newer than the backup; a missing/empty backup NEVER reports `restored:true`), `WalRepairError` (thrown when resetWal fails AFTER the backup — carries the receipt + the best-effort restore's REAL result so the seam's `restored` flag and the `failed-restored`/`failed-not-restored` message arms never lie), a cooldown sidecar `<dataDir>.wal-repair-attempt.json` (skip `'recently-failed'` inside `GBRAIN_PGLITE_WAL_REPAIR_COOLDOWN_SECONDS`, default 3600 — bounds the autopilot/supervisor reconnect loops) with episode-scoped backups (attempts within one corruption episode REUSE the episode's first backup — the pre-damage forensic state, honored only when the sidecar's path is a real non-symlink `<dataDir>.wal-repair-backup-*` sibling since the sidecar is user-writable JSON; retention keeps the newest 3 episodes, never pruning the open episode's), and `attemptWalRepairAndRetry` — the engine seam that NEVER throws (gates: kill-switch → reaped-lock `'possibly-live-writer'` → 10-minute reap-marker quarantine (`msSinceLastReap`, cross-process) → validation → cooldown; then repair → retry create once → restore-and-record on failure; prints a repair-start stderr line so a timeout-killed attempt is self-explaining). `inspectPgliteDataDir` is the read-only diagnosis for `gbrain doctor` + `pglite-repair --dry-run`. Imports runtime values only from `pglite-lock.ts`/`pglite-resetwal.ts`/node:fs — never from `pglite-engine.ts` (no cycle; the engine statically imports THIS file per the #3596 engine-live rule). Pinned by `test/pglite-repair.test.ts` + `test/pglite-wal-repair.serial.test.ts`.
- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Its confirmation prompt (and `src/commands/reinit-pglite.ts`'s) writes to stderr so `--json` stdout stays clean, refuses non-TTY stdin in-prompt (defense-in-depth behind the caller-side "Non-TTY environment requires --yes" guard), resolves `false` on EOF/close instead of parking forever on a closed or piped stdin, and cleans up its listeners; `--yes`/`-y` stays the non-interactive path. The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the #2348 concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.
-- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit]`: health checks. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. IRON-RULE regression banning stale verb names, the sync_freshness boundary matrix, the D4 regression guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure batch (#2250/#2784/#2788): `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check (#1849), a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource): Promise<Check[]>` exported as a test seam. `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`.
-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (the old `unnest(${arr}::text[])` array-literal path crashed Postgres with "malformed array literal" on calendar/Zoom context, gbrain#1861) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same probe set as PGLite (extended for column-only forward-reference cases: `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`); the entire probe path runs on the DDL connection threaded from `initSchema` (closing a concurrent-bootstrap race for Supabase pooler users); closes #1018/#974/#820. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` no longer hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds stop pinning the worker's shared read pool (the issue #6 starvation class) — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation class reintroduced on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`.
+- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit]`: health checks. The file is a façade carrying `buildChecks`/`runDoctor` and output rendering; the check-function library lives in bundles under `src/commands/doctor/checks/` plus four tail-cluster modules under `src/commands/doctor/` (see that entry), all re-exported here so the full prior surface is unchanged — structural guards pin its source text via `test/helpers/doctor-source.ts`, never by reading this file alone. Checks include `jsonb_integrity` + `markdown_body_completeness` (reliability), `schema_version` (fails loudly when `version=0`, routes to `gbrain apply-migrations --yes`), `queue_health` (Postgres-only: stalled-forever active jobs started_at > 1h, waiting-depth-per-name > threshold default 10 via `GBRAIN_QUEUE_WAITING_THRESHOLD`, and dead-lettered subagent jobs with `last_error` matching the `prompt_too_long` classifier in last 24h), `sync_failures` (`[CODE=N, ...]` breakdown for unacked-warn + acked-ok; severity comes from the shared `decideSyncFailureSeverity` in `src/core/sync-failure-ledger.ts` so the LOCAL and REMOTE/thin-client doctor surfaces can never drift — a stuck bookmark escalates to FAIL once an OPEN failure has blocked past the staleness window or ≥10 files block, while already `auto_skipped` rows stay a visible WARN), `rls_event_trigger` (healthy `evtenabled` set is `('O','A')` only; fix hint `gbrain apply-migrations --force-retry 35`), `graph_coverage` (short-circuits to ok when `SELECT COUNT(*) FROM pages WHERE type IN ('entity','person','company','organization')` returns 0; WARN hint is `gbrain extract all`), `embedding_column_registry` (probes each declared column via Postgres `format_type(atttypid, atttypmod)` to catch dim mismatch with a paste-ready `gbrain config set embedding_columns '{...}'` hint, probes HNSW index presence via `pg_indexes`, computes default-column population via `COUNT(*) FILTER (WHERE <col> IS NOT NULL) / COUNT(*)` warning below 90% except empty brains where chunk_count=0 short-circuits to ok; PGLite parity via `executeRaw`), and `skill_brain_first` (walks SKILL.md via `autoDetectSkillsDirReadOnly`, calls `analyzeSkillBrainFirst()` from `src/core/skill-brain-first.ts` per file with structured `Check.issues[]`; warn states `missing_brain_first`/`brain_first_typo`, ok states `compliant_callout`/`compliant_phase`/`compliant_position`/`exempt_frontmatter`/`no_external`; snapshot+diff audit at `~/.gbrain/audit/skill-brain-first-YYYY-Www.jsonl`). `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](path).` callouts via `src/core/dry-fix.ts` (and MISSING_RULE_PATTERNS for the brain-first callout); `--fix --dry-run` previews. `--index-audit` (Postgres-only, informational, no auto-drop) reports zero-scan indexes from `pg_stat_user_indexes`. Every DB check runs under a progress phase; `markdown_body_completeness` runs under a 1s heartbeat. `runDoctor` uses `autoDetectSkillsDirReadOnly` (from `src/core/repo-root.ts`; install-path fallback so `cd ~ && gbrain doctor` finds bundled skills); `--fix` carries a D6 install-path safety gate that refuses auto-repair when `detected.source === 'install_path'` (would rewrite the bundled tree). The Lane D supervisor check at `doctor.ts:1011-1043` consumes `summarizeCrashes(events)` from `src/core/minions/handlers/supervisor-audit.ts` (warn at `>=1` real crash; ok message has `clean_exits_24h=N`; warn message has `runtime=A oom=B unknown=C legacy=D` per-cause breakdown) so OOM/runtime/unknown crashes are distinguishable from clean code=0 worker drains; cross-surface parity with `gbrain jobs supervisor status` is pinned by source-grep wiring assertions requiring the breakdown substrings in BOTH `doctor.ts` and `jobs.ts`. `checkSyncFreshness` (exported, in `runDoctor` local + `doctorReportRemote` thin-client) is a staleness probe: warns at 24h, fails at 72h or never-synced; future-`last_sync_at` warns ("clock skew") instead of falling through ok; env overrides `GBRAIN_SYNC_FRESHNESS_WARN_HOURS`/`GBRAIN_SYNC_FRESHNESS_FAIL_HOURS` (invalid fall back with once-per-process stderr warn via `_resolveSyncFreshnessHours`); failure messages embed `source.id` so the printed `gbrain sync --source <id>` matches. A source holding a LIVE, non-expired per-source sync lock (`inspectLock(engine, syncLockId(source.id))` from `src/core/db-lock.ts`) is reported as actively syncing (the message names the holder pid + host) and counted in `synced_recently_count`, NOT flagged stale — the live lock is the only honest in-progress signal (checkpoint banking can't distinguish in-progress from wedged: a blocked sync banks its files but writes no anchor). A blocked/failed sync's process has exited (no lock row) and a wedged holder stops refreshing (TTL lapses), so either falls through to the stale path and is never masked; the dynamic `db-lock` import is swallowed to a no-op on a stub engine or pre-lock-table brain, so this can only ADD an in-progress verdict, never suppress a real stale one. The in-progress note is appended to whatever verdict the buckets produce and is empty when nothing is syncing, so steady-state messages stay byte-for-byte unchanged. It has a `localOnly`-gated git short-circuit (`runDoctor` passes `localOnly: true`; `doctorReportRemote` runs in the HTTP MCP server `src/commands/serve-http.ts` and keeps default `false` so that path never walks DB-supplied `local_path` via subprocess — trust boundary). The local predicate mirrors sync's "do work?" gate (HEAD == `last_commit` AND working tree clean via `requireCleanWorkingTree: 'ignore-untracked'` so a quiet repo with only untracked dirs is `unchanged` not SEVERE, AND `chunker_version === CURRENT`); the inline SELECT carries `last_commit + chunker_version + newest_content_at`. The REMOTE path computes lag via `lagFromContentMs(newest_content_at, lastSync, now)` from the stored column, NO git subprocess; LOCAL fall-through and the `< 0` clock-skew check stay on raw wall-clock. Three-bucket count math populates `Check.details = {unchanged_count, synced_recently_count, stale_count}` with the invariant `sum === sources.length`. `checkCycleFreshness` is DELIBERATELY NOT git-short-circuited or content-relativized (`last_commit == HEAD` can't answer "did the full cycle complete?"; a sync can succeed while later cycle phases fail; different axis `last_full_cycle_at`). Pinned by `test/doctor.test.ts` (incl. IRON-RULE regression banning stale verb names, the sync_freshness boundary matrix, the D4 regression guard verifying git probes are NEVER called when `localOnly` is unset/false, the three-bucket invariant, and the untracked-folders / remote-never-shells-out trust-boundary cases). `pglite_data_dir` check: fs-only check that runs when a PGLite brain FAILS to connect (`!fastMode && !engine && config.engine === 'pglite'`, placed after `orphan_clones`, before the DB-checks gate): `computePgliteDataDirCheck(dataDir, diagnosis)` (exported pure fn, `computeWorkerOomLoopCheck` convention) maps the `inspectPgliteDataDir` verdict to a Check — corruption-likely/looks-healthy-but-unopenable/unsupported-layout → `fail` naming `gbrain pglite-repair --dry-run`/`--yes` or the rebuild path, live-lock/missing-dir → `warn`; all `remediation_status: 'human_only'` (Minion remediation needs the DB that is down). Escalates when ≥2 repair attempts failed inside 7 days (unclean-shutdown genesis still active → engine-switch pointer) and reports retained backup-dir inventory (orphan_clones disk-visibility class). Registered in `doctor-categories.ts` OPS_CHECK_NAMES. Pinned by `test/doctor-pglite-datadir.test.ts`. silent-failure batch (#2250/#2784/#2788): `content_hash_duplicates` (single GROUP BY over `(source_id, content_hash)` with FILTER aggregates — never N² — flagging hash groups that hold BOTH a bare and a path-prefixed slug, the wrong-import-root pattern; warn carries sample pairs + the `pages delete` → `purge-deleted --older-than 0` remediation); `undeclared_db_only_pages` (per source with a local repo: markdown pages with no backing file outside every declared + derive-phase-default db_only prefix — the one check deliberately allowed to stat the repo); `db_only_collector_collision` (configured recipe `output_paths` inside a declared db_only dir — auto-gitignore means sync AND import silently skip the collector's files; same warning fires in sync's `manageGitignore` at config-write time). All warn-level, engine-parity pinned by `test/e2e/doctor-silent-death-parity.test.ts`; units in `test/doctor-silent-death-checks.test.ts`. `graph_signals_coverage` check wired into both `runDoctor` (local) and `doctorReportRemote` (HTTP/JSON thin-client path). Reads `search.graph_signals` config first, falls back to mode default; silent `ok` when disabled. Computes inbound link coverage on the page set; warns at <10% with `gbrain extract all` fix hint; `ok` at ≥30% ("fire on most queries") and 10-29% ("fire occasionally"), each with the percentage embedded. Pinned by cases in `test/doctor.test.ts`. `subagent_provider` check (layer 3 of 3). Resolves subagent model config in runtime order (`models.subagent` > `models.default` > `models.tier.subagent` > built-in default) and warns when the selected model lacks native tool-loop capability (message names the bad value + paste-ready fix `gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6`); also warns when `models.default` would sneak `subagent` into a non-Anthropic provider via tier inheritance. OK when subagent tier resolves to Anthropic. Tests in `test/doctor.test.ts`. `computeWorkerOomLoopCheck(engine)` is the single authoritative OOM-loop signal, unioning supervised `summarizeCrashes(readRecentSupervisorEvents(24)).by_cause.rss_watchdog` (cross-week read via `readRecentSupervisorEvents` so a Monday window can't lose Sunday) + bare-worker `minion_jobs error_text='aborted: watchdog'` count (Postgres-only; the same source `queue_health` subcheck 3 reads). Cap comes from the latest `rss_watchdog_loop` breaker alert's `max_rss_mb`, else `resolveDefaultMaxRssMb()` fallback. fail at breaker-tripped or oomKills≥5, warn at ≥1, null otherwise. `computePoolReapHealthCheck(engine)` is the Postgres-only `pool_reap_health` check reading `readRecentPoolRecoveries(1)` — fail when reconnect failures>0 (reconnect throwing is the actionable signal), warn at ≥10 reaps/hr (pooler thrash), null otherwise. Both registered in `buildChecks` after the `supervisor` block. The `supervisor` causeStr carries `rss=N (see worker_oom_loop)` and `queue_health`'s watchdog message cross-references `worker_oom_loop`. `DoctorReport.top_issues` + the cause-ranked render header. `worker_oom_loop` + `pool_reap_health` registered under ops in `doctor-categories.ts`. Pinned by `test/doctor-worker-oom-loop.test.ts`, `test/doctor-pool-reap-health.test.ts`. `supervisor_singleton` check (#1849), a SEPARATE check from `supervisor` (same split precedent as the niceness check) so a singleton-divergence warn can't clobber the crash/liveness precedence. Runs only when a `started` supervisor event was seen in the last 24h and a live engine is available. Reads the queue-scoped DB lock row (`gbrain_cycle_locks WHERE id = supervisorLockId(queue)`) and compares the lock holder (`holder_host:holder_pid`) against the local pidfile holder via the pure `classifySupervisorSingleton`. `mismatch` → warn (a second supervisor may be running with a different `--max-rss`; message names both holders, the effective cap from the `started` event's `max_rss_mb`, and the fix `gbrain jobs supervisor stop`); `single` → ok (names holder + cap); `no_lock` → no check emitted. Best-effort try/catch (silent skip on brains without the lock table). Registered under ops in `doctor-categories.ts` as `supervisor_singleton`. Pinned by `test/supervisor-db-lock.test.ts` + `test/doctor.test.ts`. `checkBatchRetryHealth`: `batch_retry_health` check surfacing Supavisor circuit-breaker incidents. Wired into both `runDoctor` (local) and `doctorReportRemote` (thin-client). Reads last 24h. States: `ok` (zero exhausted in 24h OR <3 from a single site), `warn` (>=3 same-site OR >=5 cross-site), `fail` (>=20 sustained breaker). Surfaces bad `GBRAIN_BULK_*` env at doctor startup. Corrupt-JSONL tolerant. Paste-ready fix hints in every warn/fail message. Also reads `readRecentDbDisconnects(24)` and appends `Disconnect-call audit: N call(s) in 24h (most recent caller: <frame>).` to ALL three message paths so connection-incident signal is greppable from one `gbrain doctor --json` call (module-import wrapped in try/catch so older brains without the audit file degrade silently). Pinned by `test/doctor-batch-retry.test.ts` (10 cases). three checks wired into `runDoctor()` and the JSON envelope, all warn-only with paste-ready fix hints. (1) `checkSourceRoutingHealth(engine)` scans up to 200 pages on federated brains and flags pages whose `source_id` doesn't match what `resolveSourceWithTier()` would have picked for their `source_path`; single-source brains short-circuit to `ok`; the 200-page cap is total across the brain so doctor stays under 5s. (2) `checkOauthConfidentialHealth(engine)` probes registered confidential clients for `/token` reachability. (3) `checkAutopilotLockScope()` (pure, no engine) compares the resolved lock path to `$GBRAIN_HOME`; warns when set but the lock lives elsewhere, with a PID-safe inspection hint (`kill -0 <pid>` before deletion). Pinned by `test/doctor-v0_37_7_checks.test.ts`. `buildChecks(engine, args, dbSource): Promise<Check[]>` exported as a test seam. `runDoctor` is a thin wrapper: `buildChecks → computeDoctorReport → render + process.exit`. All 10 `process.exit` sites stay in the wrapper; the two early-return paths (no engine, connection failure) return partial check lists instead of inline exits (observable output identical). Pinned by `test/doctor-behavioral.test.ts` (13 cases: pure aggregation math over `computeDoctorReport`, orchestrator cases for `--fast` skip set + `--json` flag + no-engine partial path + snapshot of load-bearing check names) and `test/doctor-cli-smoke.serial.test.ts` (1 subprocess case spawning `bun run src/cli.ts doctor --json` against a fresh PGLite tempdir, asserting schema_version=2 envelope, status enum, non-empty checks array — the render-path coverage buildChecks-only tests miss; quarantined `.serial` because PGLite write-locks don't play with parallel runners). three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept). two checks wired into `runDoctor()` + the JSON envelope: `quarantined_pages` (counts pages carrying the `quarantine` marker via `engine.executeRaw` JSONB `?` existence, works on PGLite + Postgres; warn-only with a `gbrain quarantine list` hint) and `flagged_pages` (counts `content_flag` pages — searchable but odd; warn-only). Both skip gracefully (status ok, "Skipped") on engines/brains where the probe errors. Pinned by `test/doctor.test.ts`. `home_dir_in_worktree`: filesystem check walking up from `gbrainPath()` toward `$HOME` looking for a `.git` directory (main repo) or `.git` file (linked worktree pointer; Conductor + git-worktrees topology). Walk terminates at `$HOME` so a `.git` above the user's home doesn't false-positive. Honors `GBRAIN_HOME` (appends `.gbrain` to the override). Warn (not fail) with worktree-root path + paste-ready fix pointing at `GBRAIN_HOME` override or moving the brain. `--remediation-plan [--json] [--target-score N]` prints what would run (stable `id`, `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on`); `--remediate [--yes] [--target-score N] [--max-usd N]` submits each plan step as a Minion job in dependency order, re-checking score between steps. `--target-score N` defaults to 90; refuses to start when target exceeds `maxReachableScore()` and lists what's missing. `--max-usd N` is the cron-safety guard — submission refuses when the plan's `est_total_usd_cost` exceeds the cap. JSON envelope adds a `Check.remediation` field (additive, schema_version unchanged). Pinned by tests in `test/doctor.test.ts`. 4 checks: `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` (mitigation surface; math ships later), `voice_gate_health`.
+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts`, `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface.
+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). The facts/takes/code-edges/salience method clusters are implemented in narrow-deps modules under `src/core/postgres-engine/` (see the engine-module-dirs entry below); the class methods delegate to them and the façade keeps its full prior public surface. `addLinksBatch`/`addTimelineEntriesBatch`/`addTakesBatch` pass the batch as one JSONB document — `INSERT ... SELECT FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(...) JOIN pages ...` bound through `executeRawJsonb({ rows })` — which encodes arbitrary free text safely (the old `unnest(${arr}::text[])` array-literal path crashed Postgres with "malformed array literal" on calendar/Zoom context, gbrain#1861) and sidesteps the 65535-parameter cap; takes declares native recordset column types (`page_id int, weight real, active boolean, …`) so no per-element casts; all three are `batchRetry`-wrapped. `searchKeyword`/`searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection. `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. `searchKeyword`/`searchKeywordChunks`/`searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude from `src/core/search/sql-ranking.ts`; `searchVector` is a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in outer SELECT) carrying `p.source_id` inner→outer. `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures, and by `batchRetry` on a retryable connection error). Concurrent callers share one in-flight `_reconnectPromise` (they await the single reconnect rather than racing a half-rebuilt pool); ownership re-samples through the atomic `db.connect()` token on the connect leg. `reconnect(ctx?)` accepts the triggering error and records a pool-recovery audit event (`reap_detected`/`reconnect_other`/`reconnect_succeeded`/`reconnect_failed`) for the `pool_reap_health` doctor check. `executeRaw` is a single-statement passthrough — no per-call retry (unsound for non-idempotent statements; recovery is supervisor-driven). `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. `countStaleChunks()`+`listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale` (eliminates ~76 MB/call client-side pull); `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding. `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same probe set as PGLite (extended for column-only forward-reference cases: `files.source_id`, `files.page_id`, `oauth_clients.source_id`, `oauth_clients.federated_read`, `sources.archived`/`archived_at`/`archive_expires_at`, `timeline_entries.event_page_id`); the entire probe path runs on the DDL connection threaded from `initSchema` (closing a concurrent-bootstrap race for Supabase pooler users); closes #1018/#974/#820. `disconnect()` is idempotent — `_connectionStyle` tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than clobbering the singleton; and a module-style engine only calls `db.disconnect()` when it owns the singleton (`_ownsModuleSingleton`, set from the `db.connect()` creation token), so a borrower probe engine's teardown leaves the cycle owner's connection intact. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` + `test/postgres-engine-singleton-ownership.test.ts`. `getBrainScore` empty-brain parity with PGLite — 100/100 with breakdown 35/25/15/15/10 when `pageCount === 0` (both engines must agree to keep `doctor-report-remote.serial.test.ts` deterministic). Implements `deletePages(slugs, {sourceId}): Promise<string[]>` via `DELETE FROM pages WHERE slug = ANY($1::text[]) AND source_id = $2 RETURNING slug` (single round-trip; caller chunks); `resolveSlugsByPaths` does `SELECT slug, source_path FROM pages WHERE source_path = ANY($1::text[]) AND source_id = $2`; FK cascades through `content_chunks`/`links`/`tags`/`raw_data`/`timeline_entries`/`page_versions`, `files.page_id`+`links.origin_page_id` go SET NULL; throws when input exceeds `DELETE_BATCH_SIZE` (from `src/core/engine-constants.ts`); both short-circuit on empty input. Implements the embedding-signature stale-detection quartet (`sumStaleChunkChars`, `setPageEmbeddingSignature`, `invalidateStaleSignatureEmbeddings`, widened `countStaleChunks`, all accept optional `signature` extending "stale" to model/dims-swap drift via the `pages.embedding_signature` JOIN, NULL grandfathered; the `embedding IS NULL` server-side filter is preserved as the no-signature fast path); Pinned by `test/e2e/engine-parity.test.ts`. Retry classifiers, ontology/recency helpers, and disconnect/pool-recovery audit writers bind statically; only the two `ai/gateway.ts` fallback lookups stay lazy and line-marked, in parity with PGLite. `insertFact` + `insertFacts` no longer hardcode `tx.unsafe(\`'${embedLit}'::vector\`)` for the embedding column. `resolveFactsEmbeddingCast()` (private) probes `pg_attribute` once per engine instance (cached in `_factsEmbeddingCastSuffix`) and returns `'::halfvec'` when migration v40 created the column as halfvec, else `'::vector'`; both insert paths use the cached suffix so the cast matches the actual column type (works on older pgvector that lacks implicit auto-cast). Test seam `__resetFactsEmbeddingCastCacheForTest()` clears the per-engine cache. `withReservedConnection` routes long-hold reserved work (CREATE INDEX CONCURRENTLY, `transaction: false` migration DDL, backfill write batches) to the DIRECT session lane when dual-pool is active, so multi-minute holds stop pinning the worker's shared read pool (the issue #6 starvation class) — never rerouted inside an open transaction (same guard shape as `executeRawDirect`), semaphore-capped below `direct_pool_size` with deliberately NO minimum-1 floor (at `direct_pool_size=1` a floor would let one long reserve consume the only direct session and starve the claim/renewLock heartbeats — the same starvation class reintroduced on the direct lane), overflowing to the shared read pool when the direct lane has no spare capacity or is unavailable; the permit is released on both fn throw and reserve failure. `getPoolDiagnostics()` (duck-typed, no BrainEngine change) surfaces the `CheckoutGauge` in-flight counters from `src/core/pool-gauge.ts` at the raw/direct/reserved/tx seams — a tracked SUBSET (tagged-template traffic is untracked) that `db-probe.ts` labels honestly in health-probe failure lines. Pinned by `test/postgres-engine-reserved-routing.test.ts`.
+- `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 prior public surface.
- `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.
@@ -46,7 +49,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/reindex-code.ts` — `gbrain reindex --code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks `pages WHERE type = 'code'` in 100-row batches, replays through `importCodeFile` for chunk + embed + content_hash folding. Idempotent unless `--force` bypasses the content_hash early-return. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds (#2139); `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE regression for the cost-preview fix), `test/reindex-cost-refusal.test.ts`.
- `src/core/fts-language.ts` — Single source for the Postgres text-search configuration name used by FTS. `getFtsLanguage()` resolves `GBRAIN_FTS_LANGUAGE` (default `english`), validates against `/^[a-z][a-z0-9_]*$/` (tsvector config names can't be bound as parameters, so the value is interpolated into raw SQL — the allowlist regex is the injection guard; invalid values warn once and fall back to `english`), and caches on first read (`resetFtsLanguageCache()` is test-only). Consumed by both engines' `searchKeyword`/`searchKeywordChunks` (`websearch_to_tsquery` query side), the `configurable_fts_language` migration, and `reindex-search-vector` (write-side trigger functions). Pinned by `test/fts-language.serial.test.ts` + `test/fts-language-migration.serial.test.ts` (includes the `'; DROP TABLE pages; --` injection cases).
- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.
-- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) not the old O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate no longer exits 2 — it auto-defers; #2139.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan (#1970). An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it (#2426 — "absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.serial.test.ts`. `resolveSlugByPathOrSourcePath` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `willEmbedSynchronously` + posture-aware `shouldBlockSync` from `src/core/embedding.ts` (#2139). The DEFERRED path (v2 on, parallel) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, or `--serial`) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session AUTO-DEFERS embeds to capped backfill jobs and exits 0 (NEVER exit 2 — the wedged-cron fix); `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). JSON envelopes carry `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | posture_tokenmax`) + a paste-ready `hint`; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (PGLite single-writer serve↔sync contention + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources (#753/#774): `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the #1433 metafile posture); an all-excluded run warns loudly (NAV-4). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath`: Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path. #2849: above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.serial.test.ts`.
+- `src/commands/sync.ts` — `gbrain sync` CLI + the `performSync` / `performFullSync` library entrypoints (consumed by the autopilot cycle and the Minion sync handler). Six pure-function clusters live in `src/core/sync-{cost-gate,git,anchor,lock,reconcile,status-report}.ts` (see the grouped entry below) and are re-exported through this façade, so the full prior import surface is unchanged. `performSync` runs under a writer lock: per-source `gbrain-sync:<sourceId>` whenever `opts.sourceId` is set, wrapped in `withRefreshingLock` from `src/core/db-lock.ts` so long-running sources (250K+ chunks) don't lose the lock at the 30-min TTL mid-run; the bare no-source path uses the SAME refreshing lock (#1794 — it was previously a non-refreshing `tryAcquireDbLock`, stealable mid-run during an incident); `SyncOpts.lockId?: string` is the explicit override. The lock refresh AND its health probe route through the DIRECT session pool so Supavisor transaction-pool exhaustion (`EMAXCONNSESSION`) can't kill renewal; takeover is heartbeat-aware (it will NOT steal a holder whose `last_refreshed_at` is within `GBRAIN_LOCK_STEAL_GRACE_SECONDS`, defending an alive-but-starved holder); the import loop yields the event loop every `GBRAIN_SYNC_YIELD_EVERY` files (`setTimeout(0)`, not `setImmediate` — Bun starves the timers phase) so the refresh `setInterval` heartbeat fires mid-import. This lock-identity invariant prevents a `sync --all` per-source worker racing `sync --source foo` on the global lock from corrupting the same source. `performSync` throws a typed `SyncLockBusyError` when the writer lock is held; the Minion `sync` handler (`src/commands/jobs.ts`) catches it and marks the job SKIPPED (not failed) so a cron/autopilot tick defers to the holder without polluting crash metrics. `performSyncInner` is RESUMABLE (incremental path): it drains a PINNED target commit (`lastCommit..pin`), banking drained file paths via `appendCompleted` (append-only delta into the `op_checkpoint_paths` child table, migration v115 — one row per path, O(delta) not the old O(N²) full-array rewrite), keyed by `syncFingerprint({sourceId, lastCommit})` from `src/core/op-checkpoint.ts` (paths under `op:'sync'`; the pinned target under `op:'sync-target'`), and advances `last_commit`/`last_sync_at` ONLY at full import completion. Checkpoint writes route through the DIRECT session pool + bounded retry so they survive `EMAXCONNSESSION`; the flush cadence is first-file then every `GBRAIN_SYNC_CHECKPOINT_EVERY` (default 1000) files OR `GBRAIN_SYNC_CHECKPOINT_SECONDS` (default 10s), with a race-safe `pendingCheckpointPaths` delta (single-flight swap, re-merge on failure) under parallel workers; a SIGTERM banks the in-flight delta via a no-retry one-shot (`appendCompletedOnce`, ordered before lock release through `registerCleanup`); and sustained flush failure aborts the run with `reason:'checkpoint_unavailable'` after `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` consecutive fails rather than importing work it can never bank (every partial/blocked exit logs the banked-file count). A sync killed mid-import banks its progress, leaves the anchor unmoved (the source stays correctly stale to the autopilot scheduler — `last_sync_at` is never bumped on a partial), and the next run `resumeFilter`s the same fixed diff to skip done files. The pin is the checkpoint's stored target when still reachable from HEAD, else live HEAD (a history rewrite / reset re-pins); completion advances to the pin, NOT live HEAD, so commits landing past the pin are a clean next-sync diff — this closes the cross-run staleness window. After import a pin-reachability gate (`git merge-base --is-ancestor pin HEAD`) replaces the old strict head-drift gate: forward commits on top of the pin (e.g. a background enrich process committing to the same repo every ~2 min) are SAFE and no longer block the run; only a real rewrite (pin not an ancestor of HEAD) blocks and discards the checkpoint. A file added in `lastCommit..pin` but gone from disk (deleted by a commit after the pin) is SKIPPED and marked completed, not recorded as a failure. Downstream extract/facts/embed are size-gated: inline only for `totalChanges <= 100`; large syncs defer to the resumable `extract --stale` watermark + `embed --stale`/backfill + the facts cycle phases, so a 44K-page facts/embed pass never re-blocks import convergence (sync convergence == import convergence). Worker engines wrap in try/finally so disconnect always fires; both PGLite-detection sites use `engine.kind === 'pglite'`. CLI accepts `--workers N` (alias `--concurrency N`) validated via `parseWorkers` (explicit bypasses the file-count floor; auto path defers to `autoConcurrency()`). The newest-first descending-lex order uses `sortNewestFirst(addsAndMods)` from `src/core/sort-newest-first.ts` (shared with `gbrain import`). `gbrain sync --all` runs a continuous worker pool: `parseWorkers`-validated `--parallel N` (default `min(sourceCount, --workers, DEFAULT_PARALLEL_SOURCES=4)`), long-lived async workers pulling from a shared FIFO queue (no head-of-line blocking), per-source `withSourcePrefix(src.id, ...)` so every `slog`/`serr` line carries `[<source-id>]`; `--skip-failed`/`--retry-failed` are scoped per source (`acknowledgeFailures(sourceId)`; `--all` acks every source, single-source acks only its own) and run UNDER parallel — the #1939 failure ledger is per-`(source_id, path)` and serialized through `withLedgerLock`, so the old "not supported under parallel, re-run with --serial" refusal is lifted (#2139, which also removed the forcing-function that pushed recovery syncs to `--serial` and thus armed the inline cost gate); a connection-budget stderr warning fires when `parallel × workers × 2 > 16` (the `× 2 per-file pool` factor: each per-file worker opens its own `PostgresEngine` with `poolSize=2`). Exports `resolveParallelism`, `syncOneSource`, `buildSyncStatusReport`, `printSyncStatusReport`, `SyncStatusReport` back the `gbrain sources status` dashboard. `--json` envelope `{schema_version: 1, sources, parallel, ok_count, error_count, skipped_count}` on stdout; human banners route to stderr via `humanSink` so `jq` parses cleanly. Exit matrix: 0 all ok (sources skipped by `--missing-path skip` count as ok), 1 any error. `--missing-path <fail|skip>` (default fail) handles sources whose `local_path` does not exist on this machine — machine-specific state in a brain-wide table, so a brain registered from several machines fails every foreign source on every run; `skip` classifies them `skipped_missing_path` (⊘ line, envelope entry with `local_path`, excluded from `error_count` and the rc gate) via the exported pure helpers `parseMissingPathMode` + `partitionMissingPathSources`, pinned by `test/sync-all-missing-path.test.ts`; default `fail` stays loud because on a single-machine brain a missing path usually means an unmounted volume. (The non-TTY cost gate no longer exits 2 — it auto-defers; #2139.) The dashboard SQL is `content_chunks ch JOIN pages pg ON pg.id = ch.page_id WHERE pg.deleted_at IS NULL` with `archived = false` at the caller; embedding column resolved via `resolveEmbeddingColumn(undefined, cfg)` from `src/core/search/embedding-column.ts` so Voyage/multimodal/non-default-column brains count against the column they use; errors propagate (no swallow-catch). The sync delete loop is interleaved per-batch resolve+delete using `engine.resolveSlugsByPaths` + `engine.deletePages` from `src/core/engine.ts` (73K-delete commit: ~146K SQL round-trips → ~292, closing the cascade-staleness class where one big-delete commit jammed every other source's sync); per-batch try-catch decomposes batch DELETE failures to per-slug `deletePage` fallback, unrecoverable per-slug failures land in `failedFiles`; `pagesAffected` filters to confirmed-deleted slugs. The rename loop gets the same batched slug-resolve; a rename whose destination is un-syncable folds the source path into the delete set so the old page can't orphan (#1970). An entry-time bookmark-reachability guard distinguishes a gc'd anchor (`cat-file` fails → `performFullSync`) from a history-rewrite anchor that is merely no-longer-an-ancestor but still on disk: the latter is diffed tree-to-tree directly (`git diff lastCommit..pin` is an endpoint-tree compare, ancestry not required) so a force-push / `master`→`main` consolidation imports only the real delta instead of re-walking the whole tree forever (#1970); an oversized or failed diff degrades to `performFullSync`. `performFullSync` is itself authoritative for deletes — after an advancing full import it purges file-backed pages (`source_path != null` AND strategy-aware `isSyncable`) whose source file no longer exists, sparing `put_page`/manual pages (null `source_path`) and metafiles. The stale-file decision routes through the pure, exported `planReconcileDeletes(rows, currentFiles, isSyncablePath)`: it normalizes path separators on both sides of the membership test (a Windows `path.relative` backslash path vs a git-derived forward-slash `source_path` would otherwise mark every page stale and wipe the source) and computes a mass-delete signal — when the reconcile would delete more than `MASS_RECONCILE_RATIO` (50%) of the file-backed pages the strategy manages, on a source holding more than `MASS_RECONCILE_MIN_PAGES` (20) of them, the delete is REFUSED with a loud stderr warning (that shape is almost always a path-comparison bug or the wrong repo path, not a genuine bulk deletion); `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the unguarded delete for genuinely intended bulk removals. Pinned by `test/sync-reconcile-mass-delete.test.ts`. Below the valve, stale pages are partitioned by git history via exported `listEverCommittedPaths(repoPath)` (one `git log --all --no-renames --diff-filter=A --name-only` pass; null on non-git dirs → unchanged behavior): a stale path that EVER existed in history was genuinely deleted → reconciled; a path with NO history is DB-only write-through (never committed/pushed, e.g. lost to a fresh clone) → the page is KEPT and its markdown re-exported to the working tree via `writePageThrough`, with a stderr hint to commit it (#2426 — "absent from git" is the symptom of the missing write-through commit, not evidence the content is disposable). Pinned by `test/sync-reconcile-db-only.serial.test.ts`. `resolveSlugByPathOrSourcePath` at `sync.ts:267` delegates to `engine.resolveSlugsByPaths` when `sourceId` is set, keeping legacy `executeRaw` fallback for the no-sourceId path. `failedFiles` is hoisted to the top of `performSyncInner` so both delete-decompose and import loops feed the same bookmark gate. The cost gate is the shared `runInlineCostGate` (one implementation on BOTH the `--all` and single-source paths; runs at the command layer, never inside `performSync`), mode-aware via `willEmbedSynchronously` + posture-aware `shouldBlockSync` from `src/core/embedding.ts` (#2139). The DEFERRED path (v2 on, parallel) is INFORMATIONAL (embedding goes to per-source `embed-backfill` jobs with their own `$X/source/24h` cap, default $25 via `SPEND_CAP_CONFIG_KEY` from `embed-backfill-submit.ts`; prints the cap + backlog + queued-job count, NEVER exits 2). The INLINE path (v2 off, or `--serial`) gates on the DELTA estimate vs `sync.cost_gate_min_usd` (default $0.50): below floor proceeds; above floor in a TTY prompts `[y/N]`; above floor in a non-TTY/`--json` session AUTO-DEFERS embeds to capped backfill jobs and exits 0 (NEVER exit 2 — the wedged-cron fix); `spend.posture=tokenmax` makes it informational and proceeds inline. The estimate MIRRORS EXECUTION instead of pricing the whole tree: `estimateInlineNewTokens` routes through the shared `computeSyncDelta` (`src/core/sync-delta.ts`) — fetch-first against `origin/<branch>`, prices only the committed delta (a dirty-but-caught-up tree → $0), with a full-tree CEILING only on the fail-open rungs (chunker drift, first sync, git-unavailable) honestly labeled; `--full` adds the stale backlog (full sync sweeps it inline). Return shape carries `estimateKind: 'delta'|'ceiling'|'mixed'|'unchanged'` + `ceilingReasons`. Helpers `resolveCostGateFloorUsd(engine)` + `resolveBackfillCapUsd(engine)` resolve via `parseUsdLimit` (`off`/`unlimited` → `Infinity`; floor accepts `0` = block-on-any-spend). JSON envelopes carry `mode` + `gate` discriminators (`dry_run | deferred_notice | below_floor | auto_deferred_embeds | posture_tokenmax`) + a paste-ready `hint`; `Infinity` floors/caps render as the string `'unlimited'` (never raw, which JSON-serializes to `null`); `SyncStatusReportSource` gains `backfill_queued`/`backfill_active`/`backfill_last_completed_at`; cost previews read `getEmbeddingModelName()` (no hardcoded OpenAI). Format splits on the explicit `--json` flag only (human text otherwise). `SyncOpts.noSchemaPack` (CLI `--no-schema-pack`, threaded through `performSync` AND `syncOneSource`) skips `loadActivePack` so pages fall back to legacy prefix typing — an escape hatch when a suspect pack regex wedges a sync. A per-file BEGIN heartbeat `if (process.env.GBRAIN_SYNC_TRACE) serr('[sync] begin import: <path>')` fires BEFORE `importFile` (the `progress.tick` fires only AFTER) so a stuck file is a begin-line with no matching completion. Triage doc: `docs/architecture/serve-sync-concurrency.md` (PGLite single-writer serve↔sync contention + the `GBRAIN_SYNC_TRACE` + `--no-schema-pack` recipes). Pinned by `test/e2e/sync-status-pglite.test.ts` (IRON-RULE: PGLite seeds 2 sources × pages × chunks, soft-deletes 1 page, archives 1 source, validates the SQL excludes both AND uses the active embedding column), `test/sync-cost-gate.serial.test.ts`, `test/sync-cost-preview.test.ts`. Runaway-sync protection: `resolveSyncHardDeadline(args, {isTty, env, defaultNonTtySec?})` resolves a wall-clock hard deadline (precedence `--no-hard-deadline` > `--hard-deadline <s>` > `--timeout <s>`(non-`--all`, which auto-arms the backstop) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none; `HARD_DEADLINE_GRACE_SEC=30`). `src/cli.ts` installs the out-of-band watchdog (see `src/core/process-watchdog.ts`) for the sync command BEFORE `connectEngine` and disposes it in the dispatch `finally`, so even an event-loop-starved sync — or a connect-phase hang — is SIGTERM-then-SIGKILLed by the deadline instead of orphaning under cron. `runSync` registers a SIGINT handler that aborts an interrupt `AbortController` composed via `composeAbortSignals(...)` (an `AbortSignal.any` wrapper over the defined signals) with the per-source `--timeout` signal, so Ctrl-C returns a clean `partial` and releases the lock through the normal `finally` (process-cleanup.ts owns SIGTERM lock-release; the watchdog owns the hard kill). `withRefreshingLock` `unref()`s its refresh `setInterval`. The spin's own root cause is not yet pinned (leading lead is catastrophic-backtracking in a pack link-inference regex, bounded by the redos-guard); the watchdog heartbeat plus the existing `[gbrain phase]` breadcrumbs are the diagnosis surface. Pinned by `test/sync-hard-deadline.test.ts` (resolution precedence + `composeAbortSignals`). Monorepo subdir sources (#753/#774): `--src-subpath <dir>` (or a repo path that IS a subdir — auto-discovery via `discoverGitRoot`, i.e. `git rev-parse --show-toplevel`) splits the repo path into `gitContextRoot` (all git ops: pull/diff/rev-parse/cat-file) and `syncScopeRoot` (walk/import/delete/rename scope); scoped syncs use git-root-relative slugs + `source_path` (full sync threads `slugRoot` into `runImport`) so full and incremental agree; NAV-1/NAV-2 realpath containment rejects `../`-traversal and symlinked scopes resolving outside the repo BEFORE any git op, and a per-file realpath guard (`isPathSafe`) refuses symlink-escape files in the incremental drain and rename reimport (fail-closed into `failedFiles`, so the bookmark can't advance past an escape); the full-sync reconcile is scope-restricted so a scoped sync never sweeps out-of-scope pages. `--exclude <glob>` (repeatable) filters scope-relative paths in both full and incremental paths; exclusion never deletes previously-imported pages (conservative, matching the #1433 metafile posture); an all-excluded run warns loudly (NAV-4). A warn-and-continue internal `git pull` failure (non-timeout class — e.g. a local-path origin rejected by `protocol.file.allow=never`) still falls through to sync the local working tree, but a ZERO-import run after a failed pull returns `partial` with `reason: 'pull_failed'` instead of `up_to_date`: `last_commit` AND the `last_sync_at` heartbeat stay frozen (so doctor `sync_freshness` / `sources status` staleness fires), the single-source CLI exits non-zero, `sync --all` exits non-zero if any source hit it (JSON envelope carries the per-source `reason`), and the autopilot cycle's sync phase maps it to `warn`. Timeout-class partials keep their pre-existing exit-0 / phase-`ok` semantics (they converge on retry; a failing pull does not). Pinned by `test/sync-pull-failed-anchor.serial.test.ts`. `resolveSlugByPathOrSourcePath`: Resolves a slug by `pages.source_path` first (returns the stored slug for frontmatter-fallback pages whose path doesn't derive a slug), then falls back to `resolveSlugForPath(path)`. Threaded into all 4 delete/rename call sites (`performSync`'s un-syncable cleanup at ~:531, deletes at ~:603, rename oldSlug at ~:622). Without this, emoji-only / Thai / Arabic filenames whose slug came from frontmatter would orphan on delete/rename (the delete path would compute the wrong path-derived slug). Best-effort query — pre-migration brains fall through to the legacy path. #2849: above the size gate (totalChanges > 100) the deferred link/timeline extraction is DURABLY QUEUED, not just hinted — the defer branch submits an `extract` Minion job `{stale: true, sourceId?, deferred_commit: pin}` keyed `extract-stale:<sourceId|default>:<pin>` (repeat submissions toward the same drained pin coalesce; deliberately NO maxWaiting — an unscoped payload's coalesce filter matches ANY waiting extract job and would silently drop the sweep), `timeout_ms` derived from extract.ts's exported `STALE_TIME_BUDGET_MS` + headroom. The returned row is verified to be a live `{stale:true}` job (waiting/delayed/active) before the log claims "queued"; a finished row occupying the key slot (a prior sweep toward the same pin that completed before this run's pages landed — the checkpoint-resume / blocked-advance re-sync case) triggers a fresh submission under a run-unique key so those pages never strand stale. Submission is best-effort (failure falls back to the hint; pages stay stale + doctor-visible, never mis-stamped). Pinned by `test/sync-deferred-extract-queue.serial.test.ts`.
- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`.
- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; replaces bare `catch {}` blocks in `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column).
- `src/core/db.ts` — Connection management, schema initialization. `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT`/`GBRAIN_IDLE_TX_TIMEOUT`/`GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (`setSessionDefaults` kept as a back-compat no-op shim). `connect()` returns `Promise<boolean>` — `true` iff THIS call created the module singleton, `false` if it joined an existing one; the decision is atomic (no `await` between the `if (sql)` null-check and the synchronous `sql = postgres(...)` assignment), so two concurrent module connects can't both claim creation. `PostgresEngine` stores the return as its `_ownsModuleSingleton` token and only the creating engine may `db.disconnect()` the singleton — a borrower probe engine (lint/doctor config-lift) no-ops its disconnect, so its teardown can't null the connection the long-lived cycle owner is still using (the dream-cycle "connect() has not been called" failure). The module `sql` is only ever nulled by `db.disconnect()` (postgres.js auto-reconnects its own internal pool and never touches our reference). `disconnect()` snapshots + nulls `sql` before awaiting the pool end so a concurrent connect can't join a pool that's already closing. The end routes through `endPoolBounded(pool)` (#1972) — a gbrain-owned `Promise.race` of `pool.end({ timeout: POOL_END_TIMEOUT_SECONDS })` against a hard timer — so a PgBouncer transaction-mode drain that never settles can't hang teardown — the #2084 contract (finishCliTeardown's computed-deadline backstop + flushThenExit's fence-and-grace exit in cli-force-exit.ts) bounds it and delivers pending stdout before exit. `connection-manager.ts` ends its direct + read pools concurrently through the same helper so the per-pool bounds don't stack. `resolveMaxLifetimeSeconds(env?)` — explicit client-pool `max_lifetime` for all four postgres() call sites (matches the postgres.js implicit 30-60min jittered default; `GBRAIN_POOL_MAX_LIFETIME_S` overrides, 0 disables; warn-once on invalid). Pinned by `test/db-pool-max-lifetime.test.ts`.
@@ -55,6 +58,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent`'s tag reconciliation is ADD-ONLY: it only `addTag` (idempotent, ON CONFLICT DO NOTHING). The `tags` table has no provenance column and frontmatter tags are stripped from stored `pages.frontmatter` (markdown.ts:118), so a frontmatter-origin tag can't be distinguished from a DB-enrichment tag (auto-tag / dream synthesize / signal-detector) at re-import — deletion is unsafe (would wipe enrichment under `gbrain reindex --markdown`). Accepted trade-off: removing a tag from frontmatter no longer removes it from the DB on next sync (needs a `tag_source` provenance column). Pinned by `test/reindex-preserve-tags.test.ts` + `test/import-file.test.ts`. identity-based dedup pre-check at `:427-490`. Calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId})` (optional `?` so test doubles compile). Posture: SKIP when `frontmatter.id` matches (true external duplicate from overlapping ingest roots), WARN-ALWAYS on content_hash collision with different/missing `frontmatter.id` (templates and daily logs may legitimately share text), FAIL CLOSED on lookup error, bypass via `--force-rechunk`. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Pinned by `test/import-dedup-frontmatter-id.test.ts` (11 cases). `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (#2576; existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`.
- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion). Exported `pruneDir(name: string): boolean` is the single source of truth for descent-time directory exclusion across walkers — blocks `node_modules` (no leading dot, so naive walkers slipped through and inflated MISSING_OPEN counts via vendor packages), `vendor`/`dist`/`build`/`venv`, dot-prefix dirs, and `*.raw` sidecars — NOT `ops/`, which is ordinary user content (#2404; the bundled daily-task-manager stores `ops/tasks` there); `isSyncable` applies it per path segment, and `walkMarkdownFiles` in `src/commands/extract.ts` + `listTextFiles` in `src/core/cycle/transcript-discovery.ts` consult it BEFORE recursing to save the IO of walking thousands of vendor files (closes #923 + #202). `manageGitignore` worktree discriminator matches the gitdir path segment (`/modules/<name>` = submodule, `/worktrees/<name>` = worktree, per Git's documented layout) so Conductor worktrees (first-class repos) get `.gitignore` management for storage-tiering (closes #889). The sync-failure ledger (failure store, error classifier, the shared bookmark gate, and the doctor severity rule) lives in `src/core/sync-failure-ledger.ts`; `sync.ts` re-exports `classifyErrorCode`, `summarizeFailuresByCode`, `loadSyncFailures`, `unacknowledgedSyncFailures`, `acknowledgeSyncFailures`, `recordSyncFailures`, `decideSyncFailureSeverity`, `applySyncFailureGate`, and the `SyncFailure` type for backward-compatible imports — see its entry below. `isSyncable` factored through private `classifySync(path, opts): SyncableReason | null`; exported companion `unsyncableReason(path, opts)` returns the same tagged reason or null when syncable. `SYNC_SKIP_FILES` is a named export (the four canonical metafile basenames `schema.md`, `index.md`, `log.md`, `README.md`). `SyncableReason` union: `'metafile' | 'strategy' | 'pruned-dir' | 'include-glob-miss' | 'exclude-glob-hit'`. The `commands/sync.ts` cleanup loop guards on `unsyncableReason(path)` being `'metafile'` OR `'pruned-dir'` (#2404) so previously-indexed metafile pages AND deliberately put-created pages under pruned dirs survive every re-sync. Does NOT cover `manifest.deleted` (the upstream filter already strips metafiles). Pinned by `test/sync-isSyncable-shape.test.ts` (15 cases, duality contract) + `test/sync-metafile-skip.serial.test.ts` (3 PGLite cases incl. the renamed `.md → .txt` negative). `pruneDir`: `pruneDir(name, parentDir?)` extended with optional `parentDir`. When provided, additionally rejects directories containing `.git` as a FILE — the git submodule gitfile pattern (regular repos have `.git` as a DIRECTORY; submodules as a file pointing into the parent's `.git/modules/`). Sync + extract walkers thread `parentDir` so the gitfile-as-FILE check fires per descend step. Best-effort: `statSync` failures fall through and treat as a normal dir. Closes the phantom-import bug class where syncing a worktree-with-submodules walked into submodule trees. Pinned by `test/sync-walker-submodule.test.ts`.
- `src/core/sync-failure-ledger.ts` — the bounded auto-skip sync failure ledger (issue #1939; formerly inline "Bug 9" in `sync.ts`). A LEAF module (imports only fs/path/crypto/config) so `sync.ts` can re-export it without a circular dependency. State lives in `~/.gbrain/sync-failures.jsonl`, one JSON object per line, keyed by `(source_id, path)` with a per-key `attempts` count and a 3-state machine: `open` (fresh/blocking) → `auto_skipped` (chronic, still doctor-visible) or `acknowledged` (human resolved via `gbrain sync --skip-failed` from either unresolved state). `classifyErrorCode(errorMsg)` regex classifier with 12 codes (`SLUG_MISMATCH`, `YAML_PARSE`, `YAML_DUPLICATE_KEY`, `MISSING_OPEN`, `MISSING_CLOSE`, `NESTED_QUOTES`, `EMPTY_FRONTMATTER`, `NULL_BYTES`, `INVALID_UTF8`, `STATEMENT_TIMEOUT`, `FILE_TOO_LARGE`, `SYMLINK_NOT_ALLOWED`) plus `UNKNOWN` (also recognizes `PAGE_JUNK_PATTERN` from the content-sanity gate); `summarizeFailuresByCode(failures)` returns sorted `[{code, count}]`; `MISSING_OPEN`/`MISSING_CLOSE`/`EMPTY_FRONTMATTER` regexes match the `markdown.ts` validator strings, `FILE_TOO_LARGE` covers `import-file.ts:199, 352, 401`, `SYMLINK_NOT_ALLOWED` covers `:347`. All mutations run under `withLedgerLock` (cross-process file lock) with an atomic rename write. The auto-skip threshold resolves via `resolveAutoSkipThreshold()` from `GBRAIN_SYNC_AUTOSKIP_AFTER` (default `DEFAULT_AUTOSKIP_AFTER = 3`; `0` disables the valve = pure fail-closed). Two pure decision functions are the unit-test surface: `decideGateAction({fileFailures, sentinels, attemptsByPath, threshold, skipFailed})` returns `hard_block | block | advance | advance_then_autoskip` (sentinels like `<head>` ALWAYS hard-block, even with `--skip-failed`, so a history rewrite can't auto-skip; any FRESH failure with `attempts < threshold` blocks fail-closed; only when ALL failures are chronic does it `advance_then_autoskip`), and `decideSyncFailureSeverity({entries, nowMs, failHours})` returns the `sync_failures` doctor status (`ok` when zero unresolved; `fail` when ≥10 OPEN-blocking or the oldest OPEN failure has blocked the bookmark past `failHours`; otherwise `warn` — `auto_skipped`-only rows stay WARN-visible regardless of count because the bookmark already advanced). `applySyncFailureGate(input)` is the one orchestrator BOTH sync paths (incremental + full/`runImport`) call: it records/clears ledger rows, runs `decideGateAction`, then executes effects in the crash-safe order (advance the bookmark FIRST via the injected `advance()` callback, THEN auto-skip the chronic set) so a crash can never mark a file skipped while leaving sync wedged. `isSkippablePath` rejects `<…>` sentinels. Pinned by `test/sync-failure-ledger.serial.test.ts` + `test/sync-failures.test.ts`.
+- `src/core/sync-cost-gate.ts` + `sync-git.ts` + `sync-anchor.ts` + `sync-lock.ts` + `sync-reconcile.ts` + `sync-status-report.ts` — six pure-function clusters relocated out of `src/commands/sync.ts` as a pure move; the façade re-exports them, and `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps exactly these six (NOT the pre-existing `sync-*` siblings, which are ordinary deps) on the sync command's flag-scan surface. `sync-cost-gate.ts`: the inline-embed cost gate + token estimation for `gbrain sync`. `sync-git.ts`: git plumbing — invocation building, repo discovery, baseline-commit self-heal, path-containment guards. `sync-anchor.ts`: sync anchor + chunker-version state helpers (source-scoped vs legacy global-config storage). `sync-lock.ts`: the lock layer — typed lock-busy error, the rich busy message, `--break-lock` handling, the partial-result envelope (`performSync` itself stays in the façade). `sync-reconcile.ts`: full-sync reconcile planning (the mass-delete valve and ever-committed gate) + sync deadline/stall resolution. `sync-status-report.ts`: the per-source sync status report backing `gbrain sources status` and the `get_status_snapshot` op.
- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).
- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml`, normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them, the #2788 class) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.
- `src/core/disk-walk.ts` — `walkBrainRepo(repoPath)` returns `Map<slug, {size, mtimeMs}>` from one recursive `readdirSync`. Skips dot-dirs, `node_modules`, non-`.md` files. Used by `gbrain storage status` to replace per-page `existsSync + statSync` (~400K syscalls on 200K-page brains → tens).
@@ -350,7 +354,10 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `scripts/check-jsonb-pattern.sh` — CI grep guard. Fails the build if anyone reintroduces (a) the `${JSON.stringify(x)}::jsonb` interpolation pattern (postgres.js v3 double-encodes it), or (b) `max_stalled INTEGER NOT NULL DEFAULT 1` in any schema source file (must be DEFAULT 5 to preserve SIGKILL-rescue). It also invokes `scripts/check-jsonb-params.mjs` and propagates its exit code. Wired into `bun test`.
- `scripts/check-jsonb-params.mjs` — AST-lite CI guard for the POSITIONAL jsonb double-encode form the template grep above misses: an `executeRaw`/`executeRawDirect`/`.unsafe()` call whose balanced arg span binds `JSON.stringify(x)` into a bare `$N::jsonb` cast (the #2339 class). Walks each call's balanced span respecting strings/templates/comments, handles generic-typed calls (`executeRaw<T>(`), and allows the sanctioned forms (`$N::text::jsonb`, `$N::text[]`, `executeRawJsonb`, `sql.json`, an inline `jsonb-guard-ok` comment). PGLite's native `db.query` is deliberately not scanned (it parses text→jsonb, so the bug can't occur there). Heuristic by design (whole-span correlation; can't see a `JSON.stringify` assigned to a variable before the call) — the real backstop is the DATABASE_URL-gated e2e parity tests. Scan roots overridable via argv for its self-test (`test/check-jsonb-params.test.ts`).
- `scripts/check-source-id-projection.sh` — CI grep guard for the multi-source bug class. Greps `src/core/postgres-engine.ts` + `src/core/pglite-engine.ts` for `SELECT.*FROM pages` projections matching the `rowToPage` feeder shape (id + slug + type + title) and fails if `source_id` is missing. `Page.source_id` is required at the type level; a projection dropping the column produces `Page` rows with `source_id: undefined` while TypeScript's `: string` lies about it. Wired into `bun run verify`.
-- `scripts/guards-manifest.tsv` + `scripts/guard-self-test.sh` — THE single registry of `scripts/check-*` CI guards (46 guards) and its self-test harness. Every guard is classified `scanner` (greps/parses repo sources — must eventually carry fixtures), `buildfresh`, or `repostate` (exempt-with-reason, not fixture-tested). `guard-self-test.sh` (`bun run check:guard-self-test`, wired into `bun run verify`) runs each `selftest=yes` scanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees under `test/fixtures/guards/<guard>/{bad,good}/` via the `GBRAIN_GUARD_ROOT` env seam, and fails the build when a new `scripts/check-*` script is missing from the manifest — so a guard whose pattern rots into a permanently-green no-op fails CI instead of masquerading as coverage. The manifest replaces the second hand-synced REGISTRY copy (package.json's `check:all` chain — deleted); it registers and classifies guards but does not itself schedule them — `run-verify-parallel.sh`'s `CHECKS` array remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + a `CHECKS` entry if it should gate pushes.
+- `scripts/guards-manifest.tsv` + `scripts/guard-self-test.sh` — THE single registry of `scripts/check-*` CI guards (48 guards) and its self-test harness. Every guard is classified `scanner` (greps/parses repo sources — must eventually carry fixtures), `buildfresh`, or `repostate` (exempt-with-reason, not fixture-tested). `guard-self-test.sh` (`bun run check:guard-self-test`, wired into `bun run verify`) runs each `selftest=yes` scanner against known-bad (must exit non-zero) and known-good (must pass) fixture trees under `test/fixtures/guards/<guard>/{bad,good}/` via the `GBRAIN_GUARD_ROOT` env seam, and fails the build when a new `scripts/check-*` script is missing from the manifest — so a guard whose pattern rots into a permanently-green no-op fails CI instead of masquerading as coverage. The manifest replaces the second hand-synced REGISTRY copy (package.json's `check:all` chain — deleted); it registers and classifies guards but does not itself schedule them — `run-verify-parallel.sh`'s `CHECKS` array remains the execution list, and a registered guard is not automatically wired into verify. New guard = new manifest row (+ fixtures if scanner) + a `CHECKS` entry if it should gate pushes.
+- `scripts/merge-lcov.ts` + `scripts/coverage-diff-gate.ts` + `scripts/coverage-baseline-gate.ts` + `scripts/update-coverage-baseline.ts` + `scripts/render-coverage-summary.ts` + `scripts/coverage-gate-exemptions.txt` + `scripts/coverage-baseline.json` — the coverage measurement + gating cluster; the operating guide is docs/TESTING.md "Coverage lanes and gates". `merge-lcov.ts` walks artifact dirs for `lcov.info` + `lane-manifest.json`, sums DA hits per file:line, normalizes paths repo-relative, and emits a merged lcov + summary JSON (src-only totals/per-dir/per-file, the `lineHits` extension the diff gate consumes, and never-loaded src files as count + sorted list — deliberately never a percentage, since physical lines ≠ executable lines); `--manifest-expect` pins the lane set, and a missing/incomplete lane or a `shard` lane with `lcovCount != 1` (the xargs-batching tripwire) marks the summary `degraded: true` — still exit 0 (degraded is data, and both gates go report-only on it). `coverage-diff-gate.ts` gates added/changed gate-scoped lines (non-test, non-generated `src/**.ts`) at ≥80% covered plus zero changed-but-never-loaded files; report-only unless `COVERAGE_GATE_ENFORCE=1`; a `[coverage-exempt: reason]` commit trailer passes with a loud warning; `coverage-gate-exemptions.txt` rows (exact path or trailing-`/` prefix; SHRINK-ONLY — additions need a graduation review) are excluded from the gate but still reported (`[e2e-exempt]` / `[subprocess-undercount]`); exit contract: 0 = pass or report-only, 1 = fail while enforcing, 2 = infrastructure error (never conflated with a coverage verdict). `coverage-baseline-gate.ts` reads the baseline via `git show origin/master:scripts/coverage-baseline.json` (never the working tree, so a PR can't weaken its own bar) and compares corpus-matched sections only (`--corpus prCorpus|fullCorpus`), failing on >0.5pp global or >1.0pp per-dir drops; `provisional: true` in the baseline (the current state — both corpus sections unseeded) keeps it report-only regardless of enforcement; `update-coverage-baseline.ts` writes the working-tree baseline (per-file detail limited to the committed `watchlist`) and `--promote` flips `provisional: false`. `render-coverage-summary.ts` renders the summary JSON as markdown on stdout for `$GITHUB_STEP_SUMMARY`, including the behavioral-vs-structural counts from `scripts/structural-suites.tsv`. Wiring: 13 PR-corpus lanes in test.yml (10 matrix shards + serial + the two dedicated slow jobs) upload `coverage-*` artifacts and the advisory `coverage-report` job merges + renders + runs both gates report-only (deliberately absent from `test-status`/`cache-write` until graduation); schedule-only `coverage-full-{unit,serial,slow,e2e}` + `coverage-full-report` in e2e.yml produce the self-contained nightly fullCorpus number (full e2e glob included) and the `coverage-full-merged` trend artifact. Collection is `COVERAGE_DIR`-opt-in in `test-shard.sh`/`run-serial-tests.sh`/`run-e2e.sh` — unique coverage dir per bun process (a reused dir overwrites `lcov.info`), lane manifest written only on a green run, `run-e2e.sh` requires an ABSOLUTE `COVERAGE_DIR` and honors `E2E_FILE_TIMEOUT_SECS` (both deliberately non-`GBRAIN_`-prefixed to survive the hermetic env scrub). Bun/JSC emits line records only (function coverage is informational) and no subprocess coverage, so `src/cli.ts` undercounts. Pinned by `test/scripts/merge-lcov.test.ts`, `test/scripts/coverage-diff-gate.test.ts`, `test/scripts/render-coverage-summary.test.ts`.
+- `scripts/check-module-size.sh` + `scripts/module-size-limits.tsv` — the module-size ratchet (`bun run check:module-size`, wired into `bun run verify`). The TSV commits a per-file `wc -l` ceiling (`path max_lines policy note`); four rules, all violations reported before a single exit 1: a file above its ceiling fails (raise a ceiling only as a conscious TSV edit); a ceiling more than 50 lines above the measured size fails (stale slack after a shrink — lower it so the ratchet holds); a TSV row whose path no longer exists fails (remove the row); an unlisted `src/**/*.ts` (excluding `*.generated.ts`/`*.test.ts`) above the 1500-line new-file cap fails (split it or add a row). Policy `region-exempt` (only `src/core/migrate.ts`) counts lines OUTSIDE the append-only `export const MIGRATIONS = [` … `];` region, so the migrations array grows freely while the surrounding runner logic stays ratcheted. Self-test seams: `GBRAIN_GUARD_ROOT`, `GBRAIN_MODULE_SIZE_SLACK`, `GBRAIN_MODULE_SIZE_NEWFILE_CAP`.
+- `scripts/classify-tests.ts` + `scripts/structural-suites.tsv` — suite-level behavioral-vs-structural test classification (the intent axis described in docs/TESTING.md "File taxonomy"). Content-based detectors — repo-anchored `readFileSync`/`Bun.file` readers, exec-scan grep windows over `src|scripts|docs`, and the `doctorSource()`/`doctorFileSource()` helpers — mark a suite STRUCTURAL when its assertions read repo source/doc text rather than executing product code; tmpdir-anchored reads don't count, and files with detectors but no attributable suite land in an `unknown` bucket emitted as comment rows (surfaced, never silently dropped). Modes: bare = rewrite the TSV; `--check` = byte-for-byte regenerate-and-diff freshness (wired as `bun run check:structural-manifest` in `bun run verify` via `scripts/check-structural-manifest.sh`); `--summary` = counts only. Fix misclassifications in the detector list, never by hand-editing the TSV. `render-coverage-summary.ts` consumes the TSV for the behavioral-vs-structural line in the CI coverage report.
- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot`: bakes a post-`initSchema()` PGLite data dir into `test/fixtures/pglite-snapshot.tar` + a version file (schema hash line, then `dims=`/`model=` lines recording the embedding shape it was baked with). Idempotent (hash short-circuit ~40ms when fresh; rebuilds stale) and concurrency-safe (atomic `mkdir` lock at `test/fixtures/.pglite-snapshot.lock` with staleness-verified takeover — a live lock is never stolen; tar written first, version file last, so a crash can't leave a fresh-looking torn fixture; waiter bounded by `GBRAIN_SNAPSHOT_LOCK_TIMEOUT_MS`, default 120000; an exhausted waiter facing a still-live lock proceeds unlocked as a last resort — the loader's hash/shape gate validates the version file, not the tar bytes). Called through the shared `ensure_pglite_snapshot` helper in `scripts/lib/test-env.sh` (also home of `detect_cpus` + `detect_available_mem_mb`; sourced by `run-unit-parallel.sh`, `test-shard.sh`, `run-slow-tests.sh`, `run-serial-tests.sh`, and `run-verify-parallel.sh` — default-on, opt out `GBRAIN_NO_SNAPSHOT=1`, no-op when a parent already exported the path, non-fatal on build failure with a one-line "active" echo so a silent cold-init fallback stays visible) and directly by `scripts/ci-local.sh`; every caller exports `GBRAIN_PGLITE_SNAPSHOT`. The loader side is `tryLoadSnapshot` + `computeSnapshotSchemaHash` (exported from `src/core/pglite-engine.ts`): the hash folds `PGLITE_SCHEMA_SQL`, every migration's `sql` + `sqlFor.pglite`, AND each migration `handler`'s function source (handler-only migrations are invisible to a sql-only hash); any hash or embedding-shape mismatch warns once and falls through to normal cold init — the snapshot is an optimization, never authoritative. The loader memoizes per process: the schema hash computes once (MIGRATIONS + PGLITE_SCHEMA_SQL are static for the process lifetime) and the version file + ~42MB tar are read once per (path, process) instead of once per engine construction (a full suite constructs 600+ engines); a terminally-unusable path (missing/stale/torn) memoizes as null and is never retried, the tar blob loads lazily only after the FIRST caller passes the shape gate, and the dims/model shape gate itself is deliberately NOT memoized (tests reconfigure the gateway mid-process — a mismatched engine must still fall back to cold init). Accepted limitation: a snapshot rewritten mid-process is not observed; the only writer runs before test fan-out. Test seams `__snapshotMemoStatsForTests`/`__resetSnapshotMemoForTests`. Pinned by `test/snapshot-shape-guard.test.ts`.
- `docker-compose.ci.yml` + `scripts/ci-local.sh` — Local CI gate. `bun run ci:local` spins up four `pgvector/pgvector:pg16` services (postgres-1..4) + `oven/bun:1` with named volumes (`gbrain-ci-pg-data-{1..4}`, `gbrain-ci-node-modules`, `gbrain-ci-bun-cache`), runs gitleaks on host, smoke-tests `scripts/run-e2e.sh` argv handling, runs guards + typecheck, then the Tier 1 default: 4-shard parallel unit + E2E (`xargs -P4`, one Postgres per shard; unit phase keeps `DATABASE_URL` unset). `--no-shard` falls back to the legacy unsharded sequential flow (debug aid); `--diff` runs the diff-aware selector unsharded. Also runs a `pgbouncer` service (`edoburu/pgbouncer`, `POOL_MODE: transaction`, `AUTH_TYPE: plain` — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; `IGNORE_STARTUP_PARAMETERS` whitelists gbrain's `statement_timeout`/`idle_in_transaction_session_timeout` startup params the way the Supabase pooler does) fronting postgres-1 on host port `GBRAIN_CI_PGBOUNCER_PORT` (default 6543); every E2E invocation exports `GBRAIN_PGBOUNCER_URL` (pooled; dedicated `gbrain_pgbouncer` database so it never races the `gbrain_test` TRUNCATE fixtures) + `GBRAIN_PGBOUNCER_DIRECT_URL`, consumed by `test/e2e/pgbouncer-teardown.test.ts` — the transaction-mode teardown bug class (#1972/#2015/#2084) reproduced in the local gate instead of only in production. `--no-pull` skips upstream pulls; `--clean` nukes named volumes. Postgres host port defaults to 5434; override with `GBRAIN_CI_PG_PORT=NNNN`. Stronger gate than PR CI's 2-file Tier 1 set.
- `scripts/select-e2e.ts` + `scripts/e2e-test-map.ts` — Diff-aware E2E test selector. Reads three git sources (committed `origin/master...HEAD`, working-tree `HEAD`, and `git ls-files --others --exclude-standard` for untracked NOT-gitignored files), classifies as EMPTY / DOC_ONLY / SRC. Fail-closed: EMPTY → all files; DOC_ONLY (every path matches the README/CLAUDE/AGENTS/CHANGELOG/TODOS allowlist) → empty stdout; SRC → escape-hatch paths (schema, package.json, skills/) trigger all, else the hand-tuned `E2E_TEST_MAP` glob narrows, and an unmapped src/ change still emits ALL files (never silently nothing). Pure-function exports `selectTests`, `classify`, `matchGlob`. `bun run ci:select-e2e` prints the current selection on stdout. `test/select-e2e.test.ts` covers all 4 branches plus 3 regression guards (skills/, untracked files, unmapped src/) — 24 cases.
diff --git a/docs/eval-bench.md b/docs/eval-bench.md
index 4b42d8a5e5..0f16686114 100644
--- a/docs/eval-bench.md
+++ b/docs/eval-bench.md
@@ -301,11 +301,11 @@ Before merging anything that touches:
- `src/core/search/hybrid.ts` (RRF, fusion, dedup, two-pass retrieval)
- `src/core/search/source-boost.ts` / `sql-ranking.ts` (per-source ranking)
-- `src/core/search/intent.ts` (auto-detail classification)
+- `src/core/search/query-intent.ts` (auto-detail classification)
- `src/core/search/expansion.ts` (Haiku query expansion)
- `src/core/search/dedup.ts` (cross-page result collapse)
- `src/core/embedding.ts` or any embedding model swap
-- `src/core/operations.ts` `query` or `search` op handlers (capture surface)
+- `src/core/ops/search.ts` `query` or `search` op handlers (capture surface)
- `src/core/postgres-engine.ts` / `pglite-engine.ts` `searchKeyword` /
`searchVector` SQL
diff --git a/docs/eval-capture.md b/docs/eval-capture.md
index 2e671d9d26..1339cf5ba2 100644
--- a/docs/eval-capture.md
+++ b/docs/eval-capture.md
@@ -14,7 +14,7 @@ replay captured real-world queries as a BrainBench-Real fixture.
MCP / CLI / subagent tool-bridge caller
│
▼
-src/core/operations.ts — query + search op handlers
+src/core/ops/search.ts — query + search op handlers
│
│ (hybridSearch or searchKeyword)
│
diff --git a/docs/eval/FIX_WAVE_BASELINES.md b/docs/eval/FIX_WAVE_BASELINES.md
index 94738f4c25..5758ae6c0b 100644
--- a/docs/eval/FIX_WAVE_BASELINES.md
+++ b/docs/eval/FIX_WAVE_BASELINES.md
@@ -23,6 +23,49 @@ touch `~/.gbrain` per the eval discipline — results land in
`<repo>/.gbrain-evals/eval-results.jsonl`). Record the gate verdict + headline
metrics here per run.
+## Containment sprint (2026-08-15, v0.46.9.1, branch garrytan/containment-sprint-coverage-modularity)
+
+God-file line counts AFTER the façade peels. Five of the six giants (all but
+migrate.ts) were peeled into focused module dirs; the peeled lines live in the sibling dirs
+listed below the table (count both when comparing against W0 — the façade
+number alone is not the receipt).
+
+| File | Lines |
+|---|---|
+| src/commands/doctor.ts | 4,177 |
+| src/core/operations.ts | 303 |
+| src/core/pglite-engine.ts | 5,546 |
+| src/core/postgres-engine.ts | 5,704 |
+| src/core/migrate.ts | 6,320 |
+| src/commands/sync.ts | 4,120 |
+| src/core/ai/gateway.ts | 4,049 |
+| src/cli.ts | 3,323 |
+| src/core/cycle.ts | 2,933 |
+| src/core/search/hybrid.ts | 2,453 |
+| src/core/engine.ts | 2,343 |
+| src/core/search/mode.ts | 1,232 |
+
+Peeled module dirs (where the moved lines live): `src/core/ops/*` 7,759;
+`src/commands/doctor/checks/*` 4,944 + four tail modules 1,321;
+`src/core/sync-{anchor,cost-gate,git,lock,reconcile,status-report}.ts` 2,030;
+`src/core/{pglite,postgres}-engine/*` 3,505. Every façade re-exports its full
+prior surface.
+
+Guards: 50 scripts/check-* files; 4 self-tested (harness 0s, budget 30s).
+Regrowth is now ratcheted: `check:module-size` (in `bun run verify`) pins
+per-file ceilings in `scripts/module-size-limits.tsv` — growth, stale slack,
+and unlisted >1,500-line src files all fail.
+
+Test infra: merged lcov coverage on every PR run (advisory), diff-coverage
+gate report-only at 80%, corpus-matched baseline gate vs origin/master's
+committed baseline, nightly unit+serial+E2E coverage-full pipeline;
+behavioral-vs-structural suite classification (`scripts/classify-tests.ts`)
+splits the headline test count.
+
+Retrieval canary: NOT RUN in this PR (structural refactor; behavior pinned by
+the engine-parity suite, now in CI on every PR and master push). The W1/W3/W9
+canary mandate is unchanged.
+
## W0 (2026-08-14, branch garrytan/code-smell-fix-wave @ post-hotfix)
God-file line counts (the audit's structural targets, BEFORE the registry waves):
diff --git a/llms-full.txt b/llms-full.txt
index fab4c7203e..4ed29dbe9e 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -260,6 +260,26 @@ Per-file detail is in `docs/architecture/KEY_FILES.md`.
(fail-closed vs warn-only vs null), not its own numbers. Pinned by `test/model-pricing.test.ts`
(drift guard asserts each view equals canonical). Embeddings price separately in
`embedding-pricing.ts` (different unit).
+- **Module-size ratchet.** `scripts/module-size-limits.tsv` pins per-file line ceilings
+ (`check:module-size` in verify): growth over a ceiling, >50 lines of stale slack after a
+ shrink, a row for a deleted file, and any UNLISTED src file over 1,500 lines all fail.
+ Raise a ceiling only via a reviewer-visible TSV edit in the same commit; lower it in the
+ same commit as any peel. migrate.ts is `region-exempt` (the MIGRATIONS array grows freely;
+ the runner logic around it is ratcheted).
+- **Peeled façades keep their surface.** operations.ts (`src/core/ops/*`), doctor.ts
+ (`src/commands/doctor/*`), sync.ts (`src/core/sync-*`), and both engines
+ (`src/core/{postgres,pglite}-engine/*`) are façades re-exporting everything they always
+ exported — import sites and published package exports never chase the peel. New code goes
+ in the module dirs, not back into the façades. Engine modules take narrow explicit deps
+ (never an engine-shaped bag); doctor source-text guards read `test/helpers/doctor-source.ts`,
+ and the flag-registry generator's `facadeExpansion` keeps peeled flag text in each command's
+ scan surface.
+- **Coverage is measured, honestly.** CI merges per-lane lcov (`scripts/merge-lcov.ts`) into
+ a PR-corpus report on every run (advisory until the diff gate graduates via
+ `COVERAGE_GATE_ENFORCE`) and a nightly fullCorpus number incl. the full e2e glob. bun
+ facts: unique `--coverage-dir` per process (reuse overwrites lcov.info), line records only
+ (JSC omits function names), no subprocess coverage (cli.ts is exempt as a documented
+ undercount), never-loaded files are a count+list, never fake all-files math.
## Reference map (load on demand)
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 886a020b25..9dacf4ca56 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.46.8.0",
+ "version": "0.46.9.1",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"configSchema": {
diff --git a/package.json b/package.json
index b8c7ff76e8..127003134c 100644
--- a/package.json
+++ b/package.json
@@ -106,7 +106,9 @@
"check:skill-refs": "bun scripts/check-skill-refs.mjs",
"gate:skills": "bash scripts/skills-commit-gate.sh",
"check:guard-self-test": "bash scripts/guard-self-test.sh",
- "check:no-legacy-getconnection": "bash scripts/check-no-legacy-getconnection.sh"
+ "check:no-legacy-getconnection": "bash scripts/check-no-legacy-getconnection.sh",
+ "check:module-size": "bash scripts/check-module-size.sh",
+ "check:structural-manifest": "bash scripts/check-structural-manifest.sh"
},
"openclaw": {
"compat": {
@@ -165,7 +167,7 @@
"bun": ">=1.3.10"
},
"license": "MIT",
- "version": "0.46.8.0",
+ "version": "0.46.9.1",
"overrides": {
"@hono/node-server": "^2.0.5",
"fast-uri": "^3.1.5",
diff --git a/plugin/README.md b/plugin/README.md
index d1aa9a9b8c..3add284ff5 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.46.8.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.46.9.1 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/conventions/calibration.md b/plugin/skills/conventions/calibration.md
index 6f3e9e39b4..606bd74a50 100644
--- a/plugin/skills/conventions/calibration.md
+++ b/plugin/skills/conventions/calibration.md
@@ -17,7 +17,7 @@ which one applies to their current task.
## When to surface a calibration warning
-The four doctor checks (in `src/commands/doctor.ts`):
+The four doctor checks (in `src/commands/doctor/checks/calibration.ts`):
- `abandoned_threads` — informational. Count of high-conviction takes
(weight >= 0.7) older than 12 months that haven't been superseded or
diff --git a/scripts/check-engine-dynamic-import.sh b/scripts/check-engine-dynamic-import.sh
index 7883c9954a..c605ec721d 100644
--- a/scripts/check-engine-dynamic-import.sh
+++ b/scripts/check-engine-dynamic-import.sh
@@ -26,6 +26,13 @@ else
src/core/postgres-engine.ts
src/core/migrate.ts
)
+ # Engine method modules peeled out of the façade classes are engine-live
+ # paths too — extraction must not shrink this guard's coverage.
+ for d in src/core/pglite-engine src/core/postgres-engine; do
+ if [ -d "$d" ]; then
+ while IFS= read -r f; do FILES+=("$f"); done < <(find "$d" -name '*.ts' | sort)
+ fi
+ done
fi
exec bun "$SCRIPT_DIR/check-engine-dynamic-import.ts" "${FILES[@]}"
diff --git a/scripts/check-fuzz-purity.sh b/scripts/check-fuzz-purity.sh
index ae1ffc4e39..67671d7c41 100755
--- a/scripts/check-fuzz-purity.sh
+++ b/scripts/check-fuzz-purity.sh
@@ -90,6 +90,8 @@ BANNED_PATH_PATTERNS=(
'src/core/engine.ts'
'src/core/postgres-engine.ts'
'src/core/pglite-engine.ts'
+ 'src/core/postgres-engine/'
+ 'src/core/pglite-engine/'
'src/core/db.ts'
'src/core/engine-factory.ts'
)
diff --git a/scripts/check-module-size.sh b/scripts/check-module-size.sh
new file mode 100755
index 0000000000..6d36da653b
--- /dev/null
+++ b/scripts/check-module-size.sh
@@ -0,0 +1,124 @@
+#!/usr/bin/env bash
+# CI guard: module-size ratchet (containment sprint).
+#
+# The six giant modules (doctor.ts 10k, operations.ts 7.5k, ...) got that way
+# one innocent commit at a time. This guard freezes every oversized file at a
+# committed ceiling (scripts/module-size-limits.tsv) and caps every UNLISTED
+# src file at a hard limit, so the only way to grow a giant is a reviewer-
+# visible TSV edit.
+#
+# TSV columns (tab-separated): path max_lines policy note
+# policy=ratchet line count (wc -l) must stay <= max_lines
+# policy=region-exempt lines OUTSIDE the `export const MIGRATIONS = [` ...
+# `];` region must stay <= max_lines (the append-only
+# migrations array grows freely; the runner logic
+# around it must not)
+#
+# Rules (all violations reported, then one exit):
+# 1. measured > max_lines -> FAIL (growth; raise the ceiling
+# consciously via a TSV edit)
+# 2. max_lines - measured > SLACK -> FAIL (stale ceiling after a shrink;
+# lower it so the ratchet holds)
+# 3. TSV path does not exist -> FAIL (remove the row)
+# 4. unlisted src file > NEWFILE_CAP -> FAIL (split it, or add a TSV row
+# consciously)
+#
+# Self-test seams: GBRAIN_GUARD_ROOT (fixture tree root; TSV read from
+# <root>/scripts/module-size-limits.tsv), GBRAIN_MODULE_SIZE_SLACK,
+# GBRAIN_MODULE_SIZE_NEWFILE_CAP.
+
+set -uo pipefail
+
+ROOT="${GBRAIN_GUARD_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
+cd "$ROOT" || exit 1
+
+TSV="scripts/module-size-limits.tsv"
+SLACK="${GBRAIN_MODULE_SIZE_SLACK:-50}"
+NEWFILE_CAP="${GBRAIN_MODULE_SIZE_NEWFILE_CAP:-1500}"
+
+if [ ! -f "$TSV" ]; then
+ echo "FAIL: $TSV not found under $ROOT" >&2
+ exit 1
+fi
+
+fail=0
+
+measure_region_exempt() {
+ # Lines outside the MIGRATIONS array region. The opener must be EXACTLY
+ # `export const MIGRATIONS` followed by ':', ' ', or '=' — a bare prefix
+ # match would let a spoof-named `export const MIGRATIONS_ANYTHING` open a
+ # free-growth region. An unclosed region (EOF while still inside) prints
+ # -1 so the caller fails loudly instead of silently exempting the rest of
+ # the file.
+ awk '
+ /^export const MIGRATIONS[:= ]/ { in_region = 1; next }
+ in_region && /^\];/ { in_region = 0; next }
+ !in_region { n++ }
+ END { print (in_region ? -1 : n + 0) }
+ ' "$1"
+}
+
+listed_paths=""
+
+while IFS=$'\t' read -r path max policy note; do
+ case "$path" in ''|'#'*) continue ;; esac
+ listed_paths="$listed_paths $path"
+
+ if [ ! -f "$path" ]; then
+ echo "FAIL: $TSV lists $path but the file does not exist — remove the row." >&2
+ fail=1
+ continue
+ fi
+
+ case "$policy" in
+ ratchet)
+ measured=$(wc -l < "$path" | tr -d ' ')
+ label="lines"
+ ;;
+ region-exempt)
+ measured=$(measure_region_exempt "$path")
+ if [ "$measured" -eq -1 ]; then
+ echo "FAIL: $path — region-exempt file has an unclosed MIGRATIONS region (opened but never closed with '];')." >&2
+ echo " An unclosed region would exempt the rest of the file from the size" >&2
+ echo " ratchet; close the array or fix the file structure." >&2
+ fail=1
+ continue
+ fi
+ label="lines outside the MIGRATIONS array"
+ ;;
+ *)
+ echo "FAIL: $TSV row for $path has unknown policy '$policy' (ratchet|region-exempt)." >&2
+ fail=1
+ continue
+ ;;
+ esac
+
+ if [ "$measured" -gt "$max" ]; then
+ echo "FAIL: $path is $measured $label, over its $max ceiling." >&2
+ echo " Growing a size-ratcheted module is a conscious decision: either move" >&2
+ echo " the new code into a sibling module (preferred), or raise the ceiling" >&2
+ echo " in $TSV in this same commit so the reviewer sees it." >&2
+ fail=1
+ elif [ $((max - measured)) -gt "$SLACK" ]; then
+ echo "FAIL: $path shrank to $measured $label but its ceiling is still $max." >&2
+ echo " Lower the ceiling in $TSV to $measured so the ratchet holds the win." >&2
+ fail=1
+ fi
+done < "$TSV"
+
+# Rule 4: every unlisted src .ts file (non-test, non-generated) obeys the cap.
+while IFS= read -r f; do
+ case " $listed_paths " in *" $f "*) continue ;; esac
+ lines=$(wc -l < "$f" | tr -d ' ')
+ if [ "$lines" -gt "$NEWFILE_CAP" ]; then
+ echo "FAIL: $f is $lines lines, over the $NEWFILE_CAP cap for files not listed in $TSV." >&2
+ echo " Split it into sibling modules, or add a TSV row consciously." >&2
+ fail=1
+ fi
+done < <(find src -name '*.ts' -not -name '*.generated.ts' -not -name '*.test.ts' 2>/dev/null | sort)
+
+if [ "$fail" -ne 0 ]; then
+ exit 1
+fi
+
+echo "OK: module sizes within committed ceilings ($TSV; new-file cap $NEWFILE_CAP)."
diff --git a/scripts/check-no-legacy-getconnection.sh b/scripts/check-no-legacy-getconnection.sh
index b3060ecb24..df5222d7dd 100755
--- a/scripts/check-no-legacy-getconnection.sh
+++ b/scripts/check-no-legacy-getconnection.sh
@@ -32,6 +32,7 @@ ALLOWED=(
"src/core/postgres-engine.ts" # calls db.connect + fallback in sql getter — PR 1 removes the fallback
"src/commands/init.ts" # first-time setup path, no engine yet
"src/commands/doctor.ts" # PR 1 refactors to accept engine
+ "src/commands/doctor/checks/pglite-worker.ts" # grandfathered doctor.ts call site, peeled verbatim (containment sprint); PR 1 refactors to accept engine
"src/commands/files.ts" # PR 1 refactors to accept engine
"src/commands/repair-jsonb.ts" # PR 1 refactors
"src/commands/serve-http.ts" # PR 1 threads engine through the OAuth dispatch path
diff --git a/scripts/check-operations-filter-bypass.sh b/scripts/check-operations-filter-bypass.sh
index 84ceac1498..a425a496dd 100755
--- a/scripts/check-operations-filter-bypass.sh
+++ b/scripts/check-operations-filter-bypass.sh
@@ -52,6 +52,14 @@ ALLOWED=(
"src/mcp/publish-gates.ts" # reads op.publishGateKey/name only to compute gate-DISABLED sets; never lists/exposes ops
"src/mcp/tool-catalog.ts" # docs/TOOL_CATALOG.md renderer; filters !op.localOnly at the boundary; never a transport surface
"src/commands/serve-http.ts" # MUST APPLY .filter(op => !op.localOnly) — verified by grep below
+ "src/core/ops/request-tools.ts" # visibleOpsForCaller loads the assembled list lazily (verbs.ts house pattern) and applies (isLocal || !op.localOnly) + surface + gate filtering
+ # The four below predate the widened specifier regex (they import via
+ # '../operations.ts', invisible to the old 'core/operations.ts' pattern) —
+ # all internal consumers, none a transport surface:
+ "src/core/advisor/collect-mcp-client-fit.ts" # advisor collector; uses op.localOnly names to SCORE client fit, never serves the list
+ "src/core/bootstrap/verify.ts" # bootstrap wiring verifier; finds ops by name to probe local wiring, remote=false context
+ "src/core/skillopt/rollout.ts" # skillopt internals; iterates op metadata for rollout planning, not exposed
+ "src/core/skillopt/write-capture.ts" # skillopt internals; iterates op params for capture schema, not exposed
)
# Pattern: any import that brings the `operations` VALUE in from core/operations.ts.
@@ -65,7 +73,11 @@ ALLOWED=(
# inside the destructured clause OR a namespace import (`* as X`); type-only
# imports of sibling exports like `sourceScopeOpts` / `OperationContext` are
# left alone (those don't expose the op list to a transport surface).
-PATTERN='import[[:space:]]+(\*[[:space:]]+as[[:space:]]+[a-zA-Z_$][a-zA-Z0-9_$]*|\{[^}]*\boperations\b[^}]*\})[[:space:]]+from[[:space:]]*['\''"][^'\''"]*core/operations\.ts['\''"]'
+# Specifier: `core/operations.ts` from outside src/core, `../operations.ts`
+# from inside (the ops/ module dir sits one level down post-peel), and the
+# dynamic `import('...operations.ts')` house pattern — all three reach the
+# assembled op list.
+PATTERN='(import[[:space:]]+(\*[[:space:]]+as[[:space:]]+[a-zA-Z_$][a-zA-Z0-9_$]*|\{[^}]*\boperations\b[^}]*\})[[:space:]]+from[[:space:]]*['\''"][^'\''"]*(core/operations|\.\./operations)\.ts['\''"]|\{[^}]*\boperations\b[^}]*\}[[:space:]]*=[[:space:]]*await[[:space:]]+import\(['\''"][^'\''"]*operations\.ts['\''"]\))'
# Collect files that import `operations`. Use a while-loop over grep output
# instead of `mapfile` to stay compatible with macOS's default bash 3.2.
diff --git a/scripts/check-skill-refs.mjs b/scripts/check-skill-refs.mjs
index 193c10d94e..5aff6de3f1 100755
--- a/scripts/check-skill-refs.mjs
+++ b/scripts/check-skill-refs.mjs
@@ -212,12 +212,22 @@ if (RUN_CLI_REFS) {
const cliSrc = readFileSync('src/cli.ts', 'utf8');
for (const m of cliSrc.matchAll(/(?:command === |case )'([a-z][a-z0-9-]*)'/g)) known.add(m[1]);
} catch {}
- // ops cliHints that --tools-json does not serialize: read them from source
+ // ops cliHints that --tools-json does not serialize: read them from source.
+ // operations.ts is a façade post-peel — the op declarations (and their
+ // cliHints) live in src/core/ops/*.ts, so scan the whole surface.
try {
- const opsSrc = readFileSync('src/core/operations.ts', 'utf8');
- for (const m of opsSrc.matchAll(/cliHints:\s*\{\s*name:\s*'([a-z][a-z0-9-]*)'/g)) known.add(m[1]);
- for (const m of opsSrc.matchAll(/aliases:\s*\[([^\]]*)\]/g)) {
- for (const a of m[1].matchAll(/'([a-z][a-z0-9-]*)'/g)) known.add(a[1]);
+ const opsFiles = ['src/core/operations.ts'];
+ try {
+ for (const f of readdirSync('src/core/ops')) {
+ if (f.endsWith('.ts')) opsFiles.push(`src/core/ops/${f}`);
+ }
+ } catch {}
+ for (const opsFile of opsFiles) {
+ const opsSrc = readFileSync(opsFile, 'utf8');
+ for (const m of opsSrc.matchAll(/cliHints:\s*\{\s*name:\s*'([a-z][a-z0-9-]*)'/g)) known.add(m[1]);
+ for (const m of opsSrc.matchAll(/aliases:\s*\[([^\]]*)\]/g)) {
+ for (const a of m[1].matchAll(/'([a-z][a-z0-9-]*)'/g)) known.add(a[1]);
+ }
}
} catch {}
for (const file of files) {
diff --git a/scripts/check-source-id-projection.sh b/scripts/check-source-id-projection.sh
index 6aa3cae1c3..11ebf22ed7 100755
--- a/scripts/check-source-id-projection.sh
+++ b/scripts/check-source-id-projection.sh
@@ -58,7 +58,17 @@ check_file() {
}
EXIT=0
-for f in src/core/postgres-engine.ts src/core/pglite-engine.ts; do
+
+# The engine surface = the two façade files plus every method module peeled
+# into their sibling dirs — SQL moved out of the façades must stay scanned.
+ENGINE_FILES=(src/core/postgres-engine.ts src/core/pglite-engine.ts)
+for d in src/core/postgres-engine src/core/pglite-engine; do
+ if [ -d "$d" ]; then
+ while IFS= read -r ef; do ENGINE_FILES+=("$ef"); done < <(find "$d" -name '*.ts' | sort)
+ fi
+done
+
+for f in "${ENGINE_FILES[@]}"; do
if ! check_file "$f"; then
EXIT=1
fi
@@ -66,7 +76,7 @@ done
# Also check RETURNING clauses (putPage uses INSERT ... RETURNING).
# Same shape: returns a row that feeds rowToPage.
-for f in src/core/postgres-engine.ts src/core/pglite-engine.ts; do
+for f in "${ENGINE_FILES[@]}"; do
awk '
/RETURNING/ {
buf = $0
diff --git a/scripts/check-structural-manifest.sh b/scripts/check-structural-manifest.sh
new file mode 100755
index 0000000000..052d25a94a
--- /dev/null
+++ b/scripts/check-structural-manifest.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+# CI guard: scripts/structural-suites.tsv (the behavioral-vs-structural test
+# inventory) must match a fresh regeneration. Suites drift constantly; a stale
+# inventory silently lies in the coverage report, so freshness is enforced the
+# same way as skills.lock / TOOL_CATALOG (generate-then-diff).
+#
+# Regenerate: bun scripts/classify-tests.ts
+set -euo pipefail
+
+ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
+cd "$ROOT"
+
+exec bun scripts/classify-tests.ts --check
diff --git a/scripts/classify-tests.ts b/scripts/classify-tests.ts
new file mode 100644
index 0000000000..d7f793b3ef
--- /dev/null
+++ b/scripts/classify-tests.ts
@@ -0,0 +1,258 @@
+#!/usr/bin/env bun
+/**
+ * Test-intent classifier: separates STRUCTURAL suites (assert on repo source/
+ * doc TEXT — guards against code shape) from BEHAVIORAL suites (execute
+ * product code). Output is a committed TSV (scripts/structural-suites.tsv)
+ * kept fresh by scripts/check-structural-manifest.sh in `bun run verify`, and
+ * rendered next to coverage numbers so the headline test count stops
+ * conflating the two.
+ *
+ * Method (suite-level, content-based — filename heuristics measured 22/23
+ * false-positive on `*audit*`):
+ * 1. Per test file, find repo-anchored source-read DETECTORS:
+ * - readFileSync / Bun.file whose argument window names a repo path
+ * (src/, scripts/, docs/, .github/, llms*, CLAUDE.md and friends) and
+ * not a tmpdir
+ * - execSync/spawnSync windows that grep/scan repo sources or invoke
+ * scripts/check-*.sh
+ * - the doctor-source helpers (test/helpers/doctor-source.ts), which
+ * exist precisely to feed structural guards
+ * 2. Bind each detector to constants it initializes; attribute a describe()
+ * suite as structural when its region contains a detector or references
+ * a bound constant. Hits outside any describe attribute to the suites
+ * that reference the binding, else to a '(file-level)' pseudo-suite.
+ * 3. Anything with detectors but no attributable suite lands in the
+ * `unknown` bucket — surfaced in reporting, never silently dropped.
+ *
+ * This is an APPROXIMATE inventory by design; the TSV freshness check makes
+ * drift loud, and misclassifications are fixed by editing the detector list
+ * here (never by hand-editing the TSV).
+ *
+ * Usage:
+ * bun scripts/classify-tests.ts # rewrite scripts/structural-suites.tsv
+ * bun scripts/classify-tests.ts --check # exit 1 if the committed TSV is stale
+ * bun scripts/classify-tests.ts --summary # print counts only
+ */
+import { readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const REPO_ROOT = join(import.meta.dir, '..');
+const OUT_TSV = join(REPO_ROOT, 'scripts', 'structural-suites.tsv');
+
+const REPO_ANCHORS = [
+ /['"`]\.?\.?\/?src\//,
+ /['"]src['"]/, // join(..., 'src', ...)
+ /['"`]\.?\.?\/?scripts\//,
+ /['"]scripts['"]/,
+ /['"`]\.?\.?\/?docs\//,
+ /['"`]\.?\.?\/?\.github\//,
+ /llms(?:-full)?\.txt/,
+ /CLAUDE\.md|AGENTS\.md|TESTING\.md|CONTRIBUTING\.md|README\.md|CHANGELOG\.md/,
+ /['"`]\.?\.?\/?skills\//,
+ /package\.json['"`]/,
+];
+const TMP_ANCHORS = /tmpdir|mkdtemp|TMPDIR|os\.tmp|TMP_|tmpPath|tempDir|testDir|workDir|FIXTURES?_/i;
+
+export interface SuiteRow {
+ file: string;
+ suite: string;
+ cases: number;
+ detector: string;
+}
+export interface FileResult {
+ rows: SuiteRow[];
+ unknown: boolean; // detectors present but nothing attributable
+}
+
+interface Detector {
+ line: number;
+ kind: string;
+ binding: string | null;
+}
+
+/** Window of a line plus the next few — read args often span lines. */
+function windowAt(lines: string[], i: number, span = 4): string {
+ return lines.slice(i, i + span).join('\n');
+}
+
+function isRepoAnchored(win: string): boolean {
+ if (TMP_ANCHORS.test(win)) return false;
+ return REPO_ANCHORS.some((r) => r.test(win));
+}
+
+export function classifyFile(relPath: string, content: string): FileResult {
+ const lines = content.split('\n');
+ const detectors: Detector[] = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (/^\s*(\/\/|\*|\/\*)/.test(line)) continue; // comments
+ let kind: string | null = null;
+ if (/\b(?:readFileSync|readFile)\s*\(/.test(line)) kind = 'readFileSync';
+ else if (/\bBun\.file\s*\(/.test(line)) kind = 'bun-file';
+ else if (/\b(?:execSync|spawnSync|execFileSync)\s*\(/.test(line)) kind = 'exec-scan';
+ else if (/\bdoctor(?:File)?Source\s*\(/.test(line)) kind = 'doctor-source-helper';
+ if (!kind) continue;
+
+ const win = windowAt(lines, i);
+ if (kind === 'exec-scan') {
+ // Only exec calls that scan repo sources / run repo guards are structural.
+ // Anchor check is looser than the read-path one: shell commands name
+ // repo dirs bare (`grep ... src/`), not as quoted path prefixes.
+ const scansRepo = /(^|[\s'"`=])(src|scripts|docs)\//.test(win) && !TMP_ANCHORS.test(win);
+ if (!(/grep|rg\s|scripts\/check-|--include=.*\.ts/.test(win) && scansRepo)) continue;
+ } else if (kind !== 'doctor-source-helper' && !isRepoAnchored(win)) {
+ continue;
+ }
+
+ const bind = line.match(/(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=/);
+ detectors.push({ line: i, kind, binding: bind ? bind[1] : null });
+ }
+
+ if (detectors.length === 0) return { rows: [], unknown: false };
+
+ // describe regions: [start, nextDescribeStart)
+ const describes: { line: number; title: string }[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const m = lines[i].match(/(?:^|\s)describe(?:\.\w+)?\s*\(\s*(['"`])((?:\\.|(?!\1).)*)\1/);
+ if (m) describes.push({ line: i, title: m[2] });
+ }
+
+ const bindings = detectors.map((d) => d.binding).filter((b): b is string => b !== null);
+ const rows: SuiteRow[] = [];
+ let attributedAny = false;
+
+ const caseCount = (start: number, end: number): number => {
+ let n = 0;
+ for (let i = start; i < end; i++) {
+ if (/(?:^|\s)(?:test|it)(?:\.\w+)?\s*\(\s*['"`]/.test(lines[i])) n++;
+ }
+ return n;
+ };
+
+ for (let d = 0; d < describes.length; d++) {
+ const start = describes[d].line;
+ const end = d + 1 < describes.length ? describes[d + 1].line : lines.length;
+ const kinds = new Set<string>();
+ for (const det of detectors) {
+ if (det.line >= start && det.line < end) kinds.add(det.kind);
+ }
+ if (bindings.length > 0) {
+ const region = lines.slice(start, end).join('\n');
+ for (const b of bindings) {
+ // Binding names may contain regex metachars (e.g. `$SRC`) — escape
+ // them or the interpolated RegExp misparses (a `$` reads as an
+ // end-anchor and the binding can never match). `\b` anchors are also
+ // wrong for `$`-prefixed names ($ is not a word char, so \b$ never
+ // matches after `(`), so bound the name with explicit
+ // non-identifier-char checks instead.
+ const escaped = b.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ if (new RegExp(`(?:^|[^\\w$])${escaped}(?![\\w$])`).test(region)) {
+ const det = detectors.find((x) => x.binding === b);
+ if (det) kinds.add(det.kind);
+ }
+ }
+ }
+ if (kinds.size > 0) {
+ rows.push({
+ file: relPath,
+ suite: describes[d].title,
+ cases: caseCount(start, end),
+ detector: [...kinds].sort().join(','),
+ });
+ attributedAny = true;
+ }
+ }
+
+ if (!attributedAny) {
+ // Detectors exist but no describe claimed them: file-level tests, or
+ // bindings only used outside describes.
+ const total = caseCount(0, lines.length);
+ if (total > 0) {
+ rows.push({
+ file: relPath,
+ suite: '(file-level)',
+ cases: total,
+ detector: [...new Set(detectors.map((d) => d.kind))].sort().join(','),
+ });
+ return { rows, unknown: false };
+ }
+ return { rows: [], unknown: true };
+ }
+
+ return { rows, unknown: false };
+}
+
+function listTestFiles(dir: string): string[] {
+ const out: string[] = [];
+ for (const entry of readdirSync(dir).sort()) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) {
+ if (entry === 'fixtures' || entry === 'node_modules') continue;
+ out.push(...listTestFiles(full));
+ } else if (entry.endsWith('.test.ts')) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+export function generate(): { tsv: string; suites: number; cases: number; files: number; unknown: string[] } {
+ const testDir = join(REPO_ROOT, 'test');
+ const rows: SuiteRow[] = [];
+ const unknown: string[] = [];
+ for (const f of listTestFiles(testDir)) {
+ const rel = relative(REPO_ROOT, f);
+ const res = classifyFile(rel, readFileSync(f, 'utf-8'));
+ rows.push(...res.rows);
+ if (res.unknown) unknown.push(rel);
+ }
+ // Codepoint compare, NOT localeCompare: the committed TSV is byte-diffed
+ // by check-structural-manifest.sh, and localeCompare ordering shifts
+ // across ICU versions/locales — a flake source, not a real change.
+ const codepointCompare = (x: string, y: string): number => (x < y ? -1 : x > y ? 1 : 0);
+ rows.sort((a, b) => (a.file === b.file ? codepointCompare(a.suite, b.suite) : codepointCompare(a.file, b.file)));
+ const header = [
+ '# Structural test suites — suites whose assertions read repo source/doc text.',
+ '# GENERATED by scripts/classify-tests.ts; freshness-checked in verify.',
+ '# Fix misclassifications in the classifier, never by hand-editing rows.',
+ '# Columns: file\tsuite\tcases\tdetector',
+ ].join('\n');
+ const body = rows.map((r) => `${r.file}\t${r.suite}\t${r.cases}\t${r.detector}`).join('\n');
+ const unknownBlock = unknown.length
+ ? `\n# unknown (detectors present, no attributable suite):\n${unknown.map((u) => `# unknown\t${u}`).join('\n')}`
+ : '';
+ return {
+ tsv: `${header}\n${body}${unknownBlock}\n`,
+ suites: rows.length,
+ cases: rows.reduce((s, r) => s + r.cases, 0),
+ files: new Set(rows.map((r) => r.file)).size,
+ unknown,
+ };
+}
+
+if (import.meta.main) {
+ const mode = process.argv[2] ?? '';
+ const res = generate();
+ const summary = `structural suites: ${res.suites} · cases: ${res.cases} · files: ${res.files} · unknown: ${res.unknown.length}`;
+ if (mode === '--check') {
+ let committed = '';
+ try {
+ committed = readFileSync(OUT_TSV, 'utf-8');
+ } catch {
+ console.error(`FAIL: ${relative(REPO_ROOT, OUT_TSV)} missing. Run: bun scripts/classify-tests.ts`);
+ process.exit(1);
+ }
+ if (committed !== res.tsv) {
+ console.error('FAIL: scripts/structural-suites.tsv is stale (test suites changed shape).');
+ console.error(' Regenerate and commit: bun scripts/classify-tests.ts');
+ process.exit(1);
+ }
+ console.log(`OK: structural-suites.tsv fresh (${summary})`);
+ } else if (mode === '--summary') {
+ console.log(summary);
+ } else {
+ writeFileSync(OUT_TSV, res.tsv);
+ console.log(`wrote scripts/structural-suites.tsv (${summary})`);
+ }
+}
diff --git a/scripts/coverage-baseline-gate.ts b/scripts/coverage-baseline-gate.ts
new file mode 100644
index 0000000000..b63329727c
--- /dev/null
+++ b/scripts/coverage-baseline-gate.ts
@@ -0,0 +1,243 @@
+#!/usr/bin/env bun
+/**
+ * scripts/coverage-baseline-gate.ts — whole-corpus coverage regression gate
+ * (containment sprint). Compares the merged summary against the committed
+ * baseline AS IT EXISTS ON origin/master — never the working tree, so a PR
+ * cannot weaken its own bar by editing the baseline file.
+ *
+ * Usage:
+ * bun scripts/coverage-baseline-gate.ts --summary <json> --corpus <prCorpus|fullCorpus>
+ *
+ * Behavior:
+ * - Baseline source: `git show origin/master:scripts/coverage-baseline.json`.
+ * * unresolvable ref → exit 2 (infrastructure)
+ * * path absent on master → 'ungated first landing', exit 0
+ * * present on master but the working-tree file was DELETED → exit 2
+ * (deletion defense: removing the file must not silently un-gate)
+ * - Like-for-like: ONLY the section named by --corpus is compared. A null
+ * corpus section → 'ungated first landing', exit 0 (sections are seeded
+ * by scripts/update-coverage-baseline.ts from real runs).
+ * - Regression: global pct drop > 0.5pp, or > 1.0pp on any dirs entry
+ * present in both baseline and summary → fail.
+ * - Shrinking-denominator defense: when the baseline corpus section has a
+ * numeric neverLoadedCount, a run whose neverLoaded.count EXCEEDS it is
+ * a regression too — deleting tests that load a module removes its files
+ * from the pct denominator and RAISES total %, which the pct checks
+ * alone cannot see. A null/absent baseline field skips the check.
+ * - Baseline "provisional": true OR summary degraded → report-only
+ * (verdict printed, exit 0) regardless of enforcement.
+ * - COVERAGE_GATE_ENFORCE: anything but '1' = report-only (WOULD
+ * PASS/WOULD FAIL, exit 0); '1' = exit 1 on fail.
+ * - Exit codes: 0 pass/report-only; 1 gate fail (enforcing); 2
+ * infrastructure error.
+ *
+ * Test seams (production ignores them when unset):
+ * COVERAGE_BASELINE_JSON_OVERRIDE literal baseline JSON text used instead
+ * of git show; the sentinel value
+ * 'ABSENT_ON_MASTER' simulates a missing
+ * path on master, 'GIT_FAILURE' simulates
+ * an unresolvable ref.
+ * COVERAGE_BASELINE_WORKTREE_PATH working-tree baseline path checked by
+ * the deletion defense (default
+ * scripts/coverage-baseline.json next to
+ * this script).
+ */
+
+import { spawnSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+export interface CorpusSection {
+ global: { lines: number; covered: number; pct: number };
+ dirs: Record<string, { lines: number; covered: number; pct: number }>;
+ files: Record<string, { lines: number; covered: number; pct: number }>;
+ /** neverLoaded.count at seeding time; null/absent skips the check. */
+ neverLoadedCount?: number | null;
+}
+
+export interface RegressionReport {
+ regressions: string[];
+ pass: boolean;
+}
+
+const GLOBAL_THRESHOLD_PP = 0.5;
+const DIR_THRESHOLD_PP = 1.0;
+const EPS = 1e-9;
+
+/**
+ * Pure comparison: baseline corpus section vs summary totals/dirs.
+ * Returns human-readable regression lines; pass when none.
+ */
+export function compareCorpus(
+ baseline: CorpusSection,
+ summaryTotal: { pct: number },
+ summaryDirs: Record<string, { pct: number }>,
+ summaryNeverLoadedCount?: number | null,
+): RegressionReport {
+ const regressions: string[] = [];
+ const globalDrop = baseline.global.pct - summaryTotal.pct;
+ if (globalDrop > GLOBAL_THRESHOLD_PP + EPS) {
+ regressions.push(
+ `global: ${baseline.global.pct}% → ${summaryTotal.pct}% (-${globalDrop.toFixed(2)}pp > ${GLOBAL_THRESHOLD_PP}pp)`,
+ );
+ }
+ for (const dir of Object.keys(baseline.dirs).sort()) {
+ const sum = summaryDirs[dir];
+ if (!sum) continue; // dir absent from this run's corpus — not comparable
+ const drop = baseline.dirs[dir]!.pct - sum.pct;
+ if (drop > DIR_THRESHOLD_PP + EPS) {
+ regressions.push(`${dir}: ${baseline.dirs[dir]!.pct}% → ${sum.pct}% (-${drop.toFixed(2)}pp > ${DIR_THRESHOLD_PP}pp)`);
+ }
+ }
+ // Shrinking-denominator defense: a growing never-loaded count means files
+ // dropped OUT of the coverage denominator (tests deleted), which raises
+ // pct for free — a regression the pct thresholds cannot see. Skipped when
+ // either side lacks a numeric count (older baseline/summary shapes).
+ const baseNL = baseline.neverLoadedCount;
+ if (typeof baseNL === "number" && typeof summaryNeverLoadedCount === "number" && summaryNeverLoadedCount > baseNL) {
+ regressions.push(
+ `neverLoaded: ${baseNL} → ${summaryNeverLoadedCount} src files never loaded by any test ` +
+ `(count may not grow — deleting tests shrinks the coverage denominator)`,
+ );
+ }
+ return { regressions, pass: regressions.length === 0 };
+}
+
+// ---------------------------------------------------------------------------
+// main
+// ---------------------------------------------------------------------------
+
+function infraFail(msg: string): never {
+ process.stderr.write(`coverage-baseline-gate: infrastructure error: ${msg}\n`);
+ process.exit(2);
+}
+
+type BaselineFetch =
+ | { status: "ok"; text: string }
+ | { status: "absent" }
+ | { status: "git-failure"; msg: string };
+
+function fetchBaselineFromMaster(): BaselineFetch {
+ const override = process.env.COVERAGE_BASELINE_JSON_OVERRIDE;
+ if (override !== undefined && override !== "") {
+ if (override === "ABSENT_ON_MASTER") return { status: "absent" };
+ if (override === "GIT_FAILURE") return { status: "git-failure", msg: "simulated by COVERAGE_BASELINE_JSON_OVERRIDE" };
+ return { status: "ok", text: override };
+ }
+ const res = spawnSync("git", ["show", "origin/master:scripts/coverage-baseline.json"], {
+ encoding: "utf8",
+ maxBuffer: 16 * 1024 * 1024,
+ });
+ if (res.error) return { status: "git-failure", msg: String(res.error) };
+ if (res.status === 0) return { status: "ok", text: res.stdout };
+ const stderr = res.stderr || "";
+ // Path errors mean the ref resolved but the file is not on master yet.
+ if (/does not exist in|exists on disk, but not in/.test(stderr)) return { status: "absent" };
+ return { status: "git-failure", msg: stderr.trim() };
+}
+
+interface BaselineJson {
+ provisional?: boolean;
+ prCorpus?: CorpusSection | null;
+ fullCorpus?: CorpusSection | null;
+ watchlist?: string[];
+}
+
+interface SummaryJson {
+ corpus?: string;
+ degraded?: boolean;
+ total?: { lines: number; covered: number; pct: number };
+ dirs?: Record<string, { lines: number; covered: number; pct: number }>;
+ neverLoaded?: { count?: number };
+}
+
+function main(): void {
+ const argv = process.argv.slice(2);
+ let summaryPath = "";
+ let corpus = "";
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ if (a === "--summary") summaryPath = argv[++i] ?? "";
+ else if (a === "--corpus") corpus = argv[++i] ?? "";
+ else infraFail(`unknown argument: ${a}`);
+ }
+ if (!summaryPath) infraFail("--summary <json> is required");
+ if (corpus !== "prCorpus" && corpus !== "fullCorpus") {
+ infraFail("--corpus must be prCorpus or fullCorpus");
+ }
+ if (!existsSync(summaryPath)) infraFail(`summary JSON not found: ${summaryPath}`);
+ let summary: SummaryJson;
+ try {
+ summary = JSON.parse(readFileSync(summaryPath, "utf8")) as SummaryJson;
+ } catch (err) {
+ infraFail(`summary JSON unparseable: ${String(err)}`);
+ }
+ if (!summary.total) infraFail("summary JSON has no total section");
+ if (summary.corpus && summary.corpus !== "unknown" && summary.corpus !== corpus) {
+ process.stderr.write(
+ `coverage-baseline-gate: warning: summary.corpus='${summary.corpus}' but --corpus=${corpus}; comparing the ${corpus} baseline section anyway\n`,
+ );
+ }
+
+ const fetched = fetchBaselineFromMaster();
+ if (fetched.status === "git-failure") infraFail(`cannot read baseline from origin/master: ${fetched.msg}`);
+ if (fetched.status === "absent") {
+ console.log("PASS: ungated first landing — scripts/coverage-baseline.json is not on origin/master yet.");
+ process.exit(0);
+ }
+
+ // Deletion defense: baseline exists on master; the working-tree copy must
+ // still exist too, or a PR could delete the file to dodge the gate.
+ const worktreePath =
+ process.env.COVERAGE_BASELINE_WORKTREE_PATH || join(import.meta.dir, "coverage-baseline.json");
+ if (!existsSync(worktreePath)) {
+ infraFail(
+ `baseline exists on origin/master but the working-tree copy is missing (${worktreePath}) — restore scripts/coverage-baseline.json`,
+ );
+ }
+
+ let baseline: BaselineJson;
+ try {
+ baseline = JSON.parse(fetched.text) as BaselineJson;
+ } catch (err) {
+ infraFail(`baseline JSON on origin/master is unparseable: ${String(err)}`);
+ }
+
+ const section = baseline[corpus as "prCorpus" | "fullCorpus"];
+ if (section === null || section === undefined) {
+ console.log(`PASS: ungated first landing — baseline has no ${corpus} section yet (seeded by update-coverage-baseline.ts).`);
+ process.exit(0);
+ }
+
+ const report = compareCorpus(section, summary.total, summary.dirs ?? {}, summary.neverLoaded?.count);
+ console.log(`Baseline comparison (${corpus}): baseline global ${section.global.pct}% vs run ${summary.total.pct}%`);
+ for (const r of report.regressions) console.log(` REGRESSION: ${r}`);
+ if (report.pass) {
+ console.log(" no regressions beyond thresholds (global 0.5pp, per-dir 1.0pp, never-loaded count non-increasing)");
+ }
+
+ // Provisional baseline / degraded data: report-only regardless of enforcement.
+ if (baseline.provisional === true) {
+ console.log(`REPORT-ONLY (baseline is provisional): ${report.pass ? "WOULD PASS" : "WOULD FAIL"}`);
+ process.exit(0);
+ }
+ if (summary.degraded === true) {
+ console.log("DEGRADED: coverage data is degraded — gate downgraded to report-only for this run.");
+ console.log(`Verdict: ${report.pass ? "WOULD PASS" : "WOULD FAIL"}`);
+ process.exit(0);
+ }
+
+ const enforcing = process.env.COVERAGE_GATE_ENFORCE === "1";
+ if (!enforcing) {
+ console.log(`Report-only (COVERAGE_GATE_ENFORCE != '1'): ${report.pass ? "WOULD PASS" : "WOULD FAIL"}`);
+ process.exit(0);
+ }
+ if (report.pass) {
+ console.log("PASS: no coverage regression vs origin/master baseline.");
+ process.exit(0);
+ }
+ console.log("FAIL: coverage regression vs origin/master baseline.");
+ process.exit(1);
+}
+
+if (import.meta.main) main();
diff --git a/scripts/coverage-baseline.json b/scripts/coverage-baseline.json
new file mode 100644
index 0000000000..8a06456c01
--- /dev/null
+++ b/scripts/coverage-baseline.json
@@ -0,0 +1,16 @@
+{
+ "provisional": true,
+ "prCorpus": null,
+ "fullCorpus": null,
+ "watchlist": [
+ "src/commands/doctor.ts",
+ "src/core/operations.ts",
+ "src/core/postgres-engine.ts",
+ "src/core/pglite-engine.ts",
+ "src/core/migrate.ts",
+ "src/commands/sync.ts",
+ "src/core/ai/gateway.ts",
+ "src/cli.ts"
+ ],
+ "note": "seeded post-peel; corpus sections filled by update-coverage-baseline.ts from real runs"
+}
diff --git a/scripts/coverage-diff-gate.ts b/scripts/coverage-diff-gate.ts
new file mode 100644
index 0000000000..14d9a28657
--- /dev/null
+++ b/scripts/coverage-diff-gate.ts
@@ -0,0 +1,396 @@
+#!/usr/bin/env bun
+/**
+ * scripts/coverage-diff-gate.ts — changed-line coverage gate (containment
+ * sprint). Verifies that lines ADDED/CHANGED by this branch are executed by
+ * the merged PR test corpus.
+ *
+ * Usage:
+ * bun scripts/coverage-diff-gate.ts --summary <merged json> [--base <ref>]
+ * --summary JSON artifact written by scripts/merge-lcov.ts (its
+ * lineHits extension key is the per-line input; this gate
+ * never re-parses lcov text and never stdout-parses tools)
+ * --base diff base ref (default origin/master)
+ *
+ * Behavior:
+ * a. `bun scripts/select-e2e.ts --classify-only`: EMPTY|DOC_ONLY → PASS.
+ * b. Diff scope: `git diff --unified=0 <base>...HEAD -- src`, filtered in
+ * code to *.ts minus *.test.ts / *.generated.ts / *.d.ts. (The in-code
+ * filter, not a 'src/**\/*.ts' pathspec, because git's default fnmatch
+ * for that pattern misses top-level files like src/cli.ts.) Paths in
+ * scripts/coverage-gate-exemptions.txt AS IT EXISTS ON origin/master
+ * (mirroring the baseline-gate's governance — a PR cannot add its own
+ * files to the list and self-exempt; working-tree additions are inert
+ * until merged) are excluded from the gate but still REPORTED with
+ * their tag. If the file is absent on master (first landing) the
+ * working-tree copy is used; if git itself fails, exit 2 infra unless
+ * report-only (which warns and falls back to the working tree).
+ * c. Zero gate-scoped changed lines → PASS.
+ * d. Per changed file with a coverage record: added line present in DA
+ * with hits>0 → covered; present with 0 → uncovered; absent from DA →
+ * non-executable (excluded). A gate-scoped changed file with NO record
+ * is ONE violation ("never loaded by any test in the PR corpus — add a
+ * test that imports it"); its physical line count is deliberately NOT
+ * used.
+ * e. Verdict: covered/(covered+uncovered) >= 0.80 AND zero never-loaded
+ * violations.
+ * f. Escape hatch: any commit body in <base>..HEAD containing
+ * '[coverage-exempt:' → PASS with a loud warning.
+ * g. Degraded summary → report-only for this run (DEGRADED banner,
+ * verdict printed, exit 0).
+ * h. COVERAGE_GATE_ENFORCE: anything but '1' = report-only (WOULD
+ * PASS/WOULD FAIL + per-file table, exit 0); '1' = exit 1 on fail.
+ * i. Exit codes: 0 pass/report-only; 1 gate fail (enforcing); 2
+ * infrastructure error (missing summary, git failure, unresolvable
+ * base).
+ *
+ * Test seams (fixture injection; production ignores them when unset):
+ * COVERAGE_GATE_CLASSIFY literal EMPTY|DOC_ONLY|SRC (skips select-e2e)
+ * COVERAGE_GATE_DIFF_FILE path to unified-diff text (skips git diff)
+ * COVERAGE_GATE_COMMITS_FILE path to commit-message text (skips git log)
+ * COVERAGE_GATE_EXEMPTIONS_OVERRIDE literal exemptions-file CONTENT; wins
+ * over both origin/master and the working tree
+ */
+
+import { spawnSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+// ---------------------------------------------------------------------------
+// Diff parsing
+// ---------------------------------------------------------------------------
+
+/**
+ * Parse `git diff --unified=0` text into new-side added/changed line numbers
+ * per file. Deletions (`+++ /dev/null`) are skipped; a hunk `@@ -a,b +c,d @@`
+ * contributes lines c..c+d-1 (d defaults to 1; d=0 contributes nothing).
+ */
+export function parseUnifiedDiff(text: string): Map<string, number[]> {
+ const out = new Map<string, number[]>();
+ let current: string | null = null;
+ for (const line of text.split("\n")) {
+ if (line.startsWith("+++ ")) {
+ const p = line.slice(4).trim();
+ current = p === "/dev/null" ? null : p.replace(/^b\//, "");
+ continue;
+ }
+ if (!current) continue;
+ const m = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
+ if (!m) continue;
+ const start = parseInt(m[1]!, 10);
+ const count = m[2] === undefined ? 1 : parseInt(m[2]!, 10);
+ if (count <= 0) continue;
+ const arr = out.get(current) ?? [];
+ for (let i = 0; i < count; i++) arr.push(start + i);
+ out.set(current, arr);
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Exemptions
+// ---------------------------------------------------------------------------
+
+export interface Exemptions {
+ exact: Set<string>;
+ prefixes: string[];
+}
+
+export function parseExemptions(text: string): Exemptions {
+ const exact = new Set<string>();
+ const prefixes: string[] = [];
+ for (const raw of text.split("\n")) {
+ const line = raw.trim();
+ if (line === "" || line.startsWith("#")) continue;
+ if (line.endsWith("/")) prefixes.push(line);
+ else exact.add(line);
+ }
+ return { exact, prefixes };
+}
+
+export function isExempt(path: string, ex: Exemptions): boolean {
+ if (ex.exact.has(path)) return true;
+ return ex.prefixes.some((p) => path.startsWith(p));
+}
+
+/** Gate scope: src/ TypeScript, excluding tests/generated/declarations. */
+export function isGateScopedPath(path: string): boolean {
+ return (
+ path.startsWith("src/") &&
+ path.endsWith(".ts") &&
+ !path.endsWith(".test.ts") &&
+ !path.endsWith(".generated.ts") &&
+ !path.endsWith(".d.ts")
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Reporting
+// ---------------------------------------------------------------------------
+
+interface FileRow {
+ file: string;
+ added: number;
+ covered: number | null;
+ uncovered: number | null;
+ uncoveredLines: number[];
+ status: string;
+}
+
+function formatLineList(lines: number[]): string {
+ const shown = lines.slice(0, 20).map((l) => `L${l}`);
+ const extra = lines.length > 20 ? `, +${lines.length - 20} more` : "";
+ return shown.join(", ") + extra;
+}
+
+function printTable(rows: FileRow[]): void {
+ if (rows.length === 0) return;
+ console.log("");
+ console.log("| file | added lines | covered | uncovered | status |");
+ console.log("|---|---|---|---|---|");
+ for (const r of rows) {
+ const cov = r.covered === null ? "-" : String(r.covered);
+ const unc =
+ r.uncovered === null
+ ? "-"
+ : r.uncoveredLines.length > 0
+ ? `${r.uncovered} (${formatLineList(r.uncoveredLines)})`
+ : String(r.uncovered);
+ console.log(`| ${r.file} | ${r.added} | ${cov} | ${unc} | ${r.status} |`);
+ }
+ console.log("");
+}
+
+// ---------------------------------------------------------------------------
+// main
+// ---------------------------------------------------------------------------
+
+function infraFail(msg: string): never {
+ process.stderr.write(`coverage-diff-gate: infrastructure error: ${msg}\n`);
+ process.exit(2);
+}
+
+function runGit(args: string[]): string {
+ const res = spawnSync("git", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
+ if (res.error || res.status !== 0) {
+ infraFail(`git ${args.join(" ")} failed: ${res.error ? String(res.error) : (res.stderr || "").trim()}`);
+ }
+ return res.stdout;
+}
+
+const EXEMPTIONS_REPO_PATH = "scripts/coverage-gate-exemptions.txt";
+
+/**
+ * Resolve the exemption LIST from origin/master, never the working tree —
+ * mirroring coverage-baseline-gate.ts's governance. Otherwise a PR could add
+ * its own files to the list and self-exempt from the 80% gate the moment
+ * enforcement graduates. Working-tree additions are INERT until merged.
+ *
+ * Resolution order:
+ * 1. COVERAGE_GATE_EXEMPTIONS_OVERRIDE (test seam; literal file content).
+ * 2. `git show origin/master:scripts/coverage-gate-exemptions.txt`.
+ * 3. Path absent on master (first landing) → working-tree copy.
+ * 4. git itself failed (unresolvable ref, ...) → exit 2 infra when
+ * enforcing; report-only warns and falls back to the working tree so
+ * the report still prints.
+ */
+function resolveExemptionsText(enforcing: boolean): string {
+ const override = process.env.COVERAGE_GATE_EXEMPTIONS_OVERRIDE;
+ if (override !== undefined) return override;
+
+ const res = spawnSync("git", ["show", `origin/master:${EXEMPTIONS_REPO_PATH}`], {
+ encoding: "utf8",
+ maxBuffer: 16 * 1024 * 1024,
+ });
+ if (!res.error && res.status === 0) return res.stdout;
+
+ const stderr = res.error ? String(res.error) : res.stderr || "";
+ const worktreePath = join(import.meta.dir, "coverage-gate-exemptions.txt");
+ const readWorktree = (): string => {
+ if (!existsSync(worktreePath)) infraFail(`exemptions file missing: ${worktreePath}`);
+ return readFileSync(worktreePath, "utf8");
+ };
+
+ // Path errors mean the ref resolved but the file is not on master yet.
+ if (!res.error && /does not exist in|exists on disk, but not in/.test(stderr)) {
+ return readWorktree();
+ }
+ if (enforcing) {
+ infraFail(`cannot read ${EXEMPTIONS_REPO_PATH} from origin/master: ${stderr.trim()}`);
+ }
+ process.stderr.write(
+ `coverage-diff-gate: warning: cannot read ${EXEMPTIONS_REPO_PATH} from origin/master (${stderr.trim()}) — report-only run falls back to the working-tree copy\n`,
+ );
+ return readWorktree();
+}
+
+interface SummaryJson {
+ degraded?: boolean;
+ files?: Record<string, { lines: number; covered: number; pct: number }>;
+ lineHits?: Record<string, Record<string, number>>;
+}
+
+function main(): void {
+ const argv = process.argv.slice(2);
+ let summaryPath = "";
+ let base = "origin/master";
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ if (a === "--summary") summaryPath = argv[++i] ?? "";
+ else if (a === "--base") base = argv[++i] ?? "origin/master";
+ else infraFail(`unknown argument: ${a}`);
+ }
+ if (!summaryPath) infraFail("--summary <merged json> is required");
+ if (!existsSync(summaryPath)) infraFail(`summary JSON not found: ${summaryPath}`);
+ const enforcing = process.env.COVERAGE_GATE_ENFORCE === "1";
+ let summary: SummaryJson;
+ try {
+ summary = JSON.parse(readFileSync(summaryPath, "utf8")) as SummaryJson;
+ } catch (err) {
+ infraFail(`summary JSON unparseable: ${String(err)}`);
+ }
+
+ // (a) change classification — doc-only/empty diffs are not gated.
+ let classification = process.env.COVERAGE_GATE_CLASSIFY ?? "";
+ if (!classification) {
+ const res = spawnSync("bun", ["scripts/select-e2e.ts", "--classify-only"], { encoding: "utf8" });
+ if (res.error || res.status !== 0) {
+ infraFail(`select-e2e --classify-only failed: ${res.error ? String(res.error) : (res.stderr || "").trim()}`);
+ }
+ classification = res.stdout.trim();
+ } else {
+ classification = classification.trim();
+ }
+ if (classification === "EMPTY" || classification === "DOC_ONLY") {
+ console.log(`PASS: change classified ${classification} — coverage diff gate not applicable.`);
+ process.exit(0);
+ }
+
+ // (b) diff scope.
+ const diffFile = process.env.COVERAGE_GATE_DIFF_FILE;
+ let diffText: string;
+ if (diffFile) {
+ if (!existsSync(diffFile)) infraFail(`COVERAGE_GATE_DIFF_FILE not found: ${diffFile}`);
+ diffText = readFileSync(diffFile, "utf8");
+ } else {
+ diffText = runGit(["diff", "--unified=0", `${base}...HEAD`, "--", "src"]);
+ }
+ const changed = parseUnifiedDiff(diffText);
+
+ const exemptions = parseExemptions(resolveExemptionsText(enforcing));
+
+ const rows: FileRow[] = [];
+ let covered = 0;
+ let uncovered = 0;
+ let neverLoadedViolations = 0;
+ let gatedChangedLines = 0;
+
+ const lineHits = summary.lineHits;
+ const filesWithRecords = new Set([
+ ...Object.keys(summary.files ?? {}),
+ ...Object.keys(lineHits ?? {}),
+ ]);
+
+ const scopedFiles = [...changed.keys()].filter(isGateScopedPath).sort();
+ for (const file of scopedFiles) {
+ const addedLines = changed.get(file)!;
+ if (isExempt(file, exemptions)) {
+ // Exempt: reported, never gated. src/cli.ts gets its own honest tag.
+ const tag = file === "src/cli.ts" ? "[subprocess-undercount]" : "[e2e-exempt]";
+ rows.push({ file, added: addedLines.length, covered: null, uncovered: null, uncoveredLines: [], status: tag });
+ continue;
+ }
+ gatedChangedLines += addedLines.length;
+ if (!filesWithRecords.has(file)) {
+ // (d) no coverage record at all: ONE violation; do NOT count physical lines.
+ neverLoadedViolations++;
+ rows.push({
+ file,
+ added: addedLines.length,
+ covered: null,
+ uncovered: null,
+ uncoveredLines: [],
+ status: "VIOLATION: never loaded by any test in the PR corpus — add a test that imports it",
+ });
+ continue;
+ }
+ if (!lineHits) {
+ infraFail("summary JSON has no lineHits key — regenerate it with the current scripts/merge-lcov.ts");
+ }
+ const da = lineHits[file] ?? {};
+ let fileCovered = 0;
+ const fileUncoveredLines: number[] = [];
+ for (const line of addedLines) {
+ const hits = da[String(line)];
+ if (hits === undefined) continue; // non-executable — excluded
+ if (hits > 0) fileCovered++;
+ else fileUncoveredLines.push(line);
+ }
+ covered += fileCovered;
+ uncovered += fileUncoveredLines.length;
+ rows.push({
+ file,
+ added: addedLines.length,
+ covered: fileCovered,
+ uncovered: fileUncoveredLines.length,
+ uncoveredLines: fileUncoveredLines,
+ status: "gated",
+ });
+ }
+
+ // (c) zero gate-scoped changed lines.
+ if (gatedChangedLines === 0) {
+ printTable(rows); // exempt-only changes still get reported
+ console.log("PASS: no gate-scoped changes.");
+ process.exit(0);
+ }
+
+ // (e) verdict.
+ const denom = covered + uncovered;
+ const ratio = denom === 0 ? 1 : covered / denom;
+ const pass = ratio >= 0.8 - 1e-9 && neverLoadedViolations === 0;
+ const pctStr = (ratio * 100).toFixed(2);
+
+ printTable(rows);
+ console.log(`Changed-line coverage: ${covered}/${denom} = ${pctStr}% (threshold 80%)`);
+ if (neverLoadedViolations > 0) {
+ console.log(`Never-loaded gate-scoped files: ${neverLoadedViolations} (each is a violation)`);
+ }
+
+ // (f) escape hatch trailer.
+ const commitsFile = process.env.COVERAGE_GATE_COMMITS_FILE;
+ let commitsText: string;
+ if (commitsFile) {
+ if (!existsSync(commitsFile)) infraFail(`COVERAGE_GATE_COMMITS_FILE not found: ${commitsFile}`);
+ commitsText = readFileSync(commitsFile, "utf8");
+ } else {
+ commitsText = runGit(["log", `${base}..HEAD`, "--format=%B"]);
+ }
+ if (commitsText.includes("[coverage-exempt:")) {
+ console.log("");
+ console.log("WARNING: '[coverage-exempt:' trailer found in a commit body — coverage diff gate BYPASSED for this branch.");
+ console.log(`PASS (escape hatch): verdict without the trailer would have been ${pass ? "PASS" : "FAIL"}.`);
+ process.exit(0);
+ }
+
+ // (g) degraded coverage data → report-only for this run.
+ if (summary.degraded === true) {
+ console.log("");
+ console.log("DEGRADED: coverage data is degraded (lane incomplete/malformed) — gate downgraded to report-only for this run.");
+ console.log(`Verdict: ${pass ? "WOULD PASS" : "WOULD FAIL"}`);
+ process.exit(0);
+ }
+
+ // (h) enforcement.
+ if (!enforcing) {
+ console.log(`Report-only (COVERAGE_GATE_ENFORCE != '1'): ${pass ? "WOULD PASS" : "WOULD FAIL"}`);
+ process.exit(0);
+ }
+ if (pass) {
+ console.log("PASS: changed-line coverage gate.");
+ process.exit(0);
+ }
+ console.log("FAIL: changed-line coverage below 80% or never-loaded files present.");
+ process.exit(1);
+}
+
+if (import.meta.main) main();
diff --git a/scripts/coverage-gate-exemptions.txt b/scripts/coverage-gate-exemptions.txt
new file mode 100644
index 0000000000..6e60e9697c
--- /dev/null
+++ b/scripts/coverage-gate-exemptions.txt
@@ -0,0 +1,23 @@
+# coverage-gate-exemptions.txt — shrink-only allowlist for the coverage
+# diff gate (scripts/coverage-diff-gate.ts).
+#
+# Paths listed here are EXCLUDED from the >=80% changed-line coverage gate.
+# They are still REPORTED in the gate's table, tagged:
+# [e2e-exempt] coverage for these lives in DATABASE_URL-gated
+# e2e lanes that the PR corpus may not run
+# [subprocess-undercount] src/cli.ts only: the CLI is exercised via child
+# processes and bun coverage does not propagate
+# into subprocesses, so its numbers undercount
+#
+# SHRINK-ONLY: entries may be removed as the coverage corpus learns to see
+# these paths; ADDING an entry requires a graduation review in the PR
+# description explaining why the path cannot be gated yet.
+#
+# Syntax: one path per line; '#' starts a comment. Entries ending in '/'
+# are directory prefix matches; all others are exact file matches.
+src/core/postgres-engine.ts
+src/core/pglite-engine.ts
+src/core/postgres-engine/
+src/core/pglite-engine/
+src/core/migrate.ts
+src/cli.ts
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 55a9e28b13..f4515ad892 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -87,6 +87,21 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/engine-parity.test.ts",
"test/e2e/schema-drift.test.ts",
],
+ // Engine method modules peeled from the façades carry the same blast
+ // radius as the façades themselves.
+ "src/core/postgres-engine/**": [
+ "test/e2e/postgres-bootstrap.test.ts",
+ "test/e2e/postgres-jsonb.test.ts",
+ "test/e2e/jsonb-roundtrip.test.ts",
+ "test/e2e/engine-parity.test.ts",
+ "test/e2e/schema-drift.test.ts",
+ "test/e2e/migrate-embeddings-postgres.test.ts",
+ ],
+ "src/core/pglite-engine/**": [
+ "test/e2e/postgres-bootstrap.test.ts",
+ "test/e2e/engine-parity.test.ts",
+ "test/e2e/schema-drift.test.ts",
+ ],
// Schema source of truth: any change must pass the cross-engine drift gate.
"src/schema.sql": ["test/e2e/schema-drift.test.ts"],
"src/core/pglite-schema.ts": ["test/e2e/schema-drift.test.ts"],
@@ -106,6 +121,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/migration-flow.test.ts",
],
"src/commands/doctor.ts": ["test/e2e/doctor-progress.test.ts"],
+ // Doctor check modules peeled from doctor.ts feed the same e2e surface.
+ "src/commands/doctor/**": ["test/e2e/doctor-progress.test.ts"],
// Knowledge graph layer feeds graph-quality.
"src/core/link-extraction.ts": ["test/e2e/graph-quality.test.ts"],
// v0.38 ingestion substrate. POST /ingest lives inside serve-http.ts
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 6ee4b066b9..32641f6905 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -22,7 +22,7 @@
* Hand-tuning lane: EXTRA_FLAGS below, for flags that live deeper than the
* one-level scan (add with a comment naming the deep module).
*/
-import { readFileSync, writeFileSync, existsSync } from 'fs';
+import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from 'fs';
import { dirname, resolve as resolvePath, join } from 'path';
import { fileURLToPath } from 'url';
@@ -59,7 +59,45 @@ function relativeImports(src: string, fromDir: string): string[] {
for (const m of src.matchAll(/import\('(\.\.?\/[^']+\.ts)'\)/g)) paths.add(m[1]);
return [...paths]
.map(p => resolvePath(fromDir, p))
- .filter(p => existsSync(p));
+ .filter(p => existsSync(p))
+ .flatMap(p => [p, ...facadeExpansion(p)]);
+}
+
+/**
+ * Peeled façade files (containment sprint) whose flag-bearing text moved into
+ * sibling module dirs. Before the peels, that text lived inside the façade
+ * itself and rode the one-level walk; scanning the façade now pulls its
+ * modules back in so a peel can never silently shrink a command's flag set.
+ */
+function facadeExpansion(p: string): string[] {
+ const rel = p.startsWith(ROOT) ? p.slice(ROOT.length + 1) : p;
+ const collect = (dir: string): string[] => {
+ if (!existsSync(dir)) return [];
+ const out: string[] = [];
+ for (const entry of readdirSync(dir).sort()) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) out.push(...collect(full));
+ else if (entry.endsWith('.ts')) out.push(full);
+ }
+ return out;
+ };
+ if (rel === 'src/core/operations.ts') return collect(join(ROOT, 'src/core/ops'));
+ if (rel === 'src/commands/doctor.ts') return collect(join(ROOT, 'src/commands/doctor'));
+ if (rel === 'src/commands/sync.ts') {
+ // Only the modules PEELED OUT of sync.ts (their text used to live inside
+ // it). Pre-existing sync-* siblings were always ordinary deps — sweeping
+ // them in here would widen surfaces that never saw their text.
+ const peeled = [
+ 'sync-cost-gate.ts',
+ 'sync-git.ts',
+ 'sync-anchor.ts',
+ 'sync-lock.ts',
+ 'sync-reconcile.ts',
+ 'sync-status-report.ts',
+ ];
+ return peeled.map(f => join(ROOT, 'src/core', f)).filter(p => existsSync(p));
+ }
+ return [];
}
export function buildFlagRegistry(): Record<string, string[]> {
@@ -130,11 +168,17 @@ export function buildFlagRegistry(): Record<string, string[]> {
.map(mm => resolvePath(join(ROOT, 'src'), mm[1]))
.filter(p => existsSync(p));
for (const modPath of commandModules) {
- const modSrc = readFileSync(modPath, 'utf-8');
- depthZeroText += modSrc;
- for (const f of flagsInText(modSrc)) { flags.add(f); depthZero.add(f); }
- for (const dep of relativeImports(modSrc, dirname(modPath))) {
- for (const f of flagsInText(readFileSync(dep, 'utf-8'))) flags.add(f);
+ // A command module that IS a peeled façade counts its module files as
+ // part of itself: their text scans at module depth and THEIR relative
+ // imports scan at dep depth — exactly the pre-peel walk.
+ const surface = [modPath, ...facadeExpansion(modPath)];
+ for (const sfPath of surface) {
+ const sfSrc = readFileSync(sfPath, 'utf-8');
+ depthZeroText += sfSrc;
+ for (const f of flagsInText(sfSrc)) { flags.add(f); depthZero.add(f); }
+ for (const dep of relativeImports(sfSrc, dirname(sfPath))) {
+ for (const f of flagsInText(readFileSync(dep, 'utf-8'))) flags.add(f);
+ }
}
}
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index 93f9c685db..bda8dc2308 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -62,5 +62,7 @@ check-bootstrap-tag.sh repostate exempt VERSION stamp drift check
check-cli-executable.sh repostate exempt file-mode check
check-no-tracked-symlinks.sh repostate exempt git index state check
check-grok-pin.sh repostate exempt pin-stamp drift check (GROK-CLI-PIN.md stamps vs heavy-tests grok-door env); own bun guard tests in test/check-bootstrap-guards.test.ts
+check-module-size.sh scanner yes committed per-file line ceilings (module-size-limits.tsv); growth + stale-ceiling + missing-row + new-file cap; region-exempt policy for migrate.ts
+check-structural-manifest.sh buildfresh exempt regenerate+diff of structural-suites.tsv (classify-tests.ts); the diff IS the self-test
check-opencode-pin.sh repostate exempt pin-stamp drift check (OPENCODE-CLI-PIN.md stamps vs heavy-tests opencode-door env); own bun guard tests in test/check-bootstrap-guards.test.ts
check-pin-doc-privacy.sh repostate exempt PIN-doc placeholder discipline (no operator paths/key material/emails in docs/mcp/*-CLI-PIN.md); own bun guard tests in test/check-bootstrap-guards.test.ts
diff --git a/scripts/merge-lcov.ts b/scripts/merge-lcov.ts
new file mode 100644
index 0000000000..9af5a18846
--- /dev/null
+++ b/scripts/merge-lcov.ts
@@ -0,0 +1,540 @@
+#!/usr/bin/env bun
+/**
+ * scripts/merge-lcov.ts — merge per-lane bun lcov.info files into one
+ * artifact pair: a regenerated merged lcov + a JSON summary for the
+ * coverage gates (containment sprint).
+ *
+ * Usage:
+ * bun scripts/merge-lcov.ts --out-lcov <path> --out-json <path> \
+ * [--manifest-expect <lane,lane,...>] <dir-or-file>...
+ *
+ * Behavior:
+ * - Recursively finds every lcov.info under the input dirs (a file input
+ * is used directly). Only LOADED files appear in bun's lcov output; a
+ * src file that never appears was never imported by any test. Any
+ * lcov.info under a `coverage-merged` path segment is skipped: report-
+ * job re-runs download the prior run's merged artifact via the
+ * `coverage-*` glob, and re-merging it would double every hit count.
+ * - Parses SF/DA/FN/FNDA/LF/LH/TN/end_of_record. Unknown record types
+ * (e.g. BRDA) warn to stderr and are SKIPPED — never passed through.
+ * - A malformed/truncated lcov.info warns, is skipped WHOLE, and marks
+ * the summary degraded — the merge never aborts on bad lane data.
+ * - SF normalization: absolute paths become repo-relative POSIX paths
+ * (repo root = process.cwd(); any absolute prefix ending in the repo
+ * directory name is also stripped), then deduped/merged.
+ * - Merge math: DA hits summed per file:line; FNDA hits summed per
+ * function name. All output records are REGENERATED from parsed data
+ * (fresh FN/FNDA/FNF/FNH/LF/LH). bun/JSC omits function names, so
+ * function records are informational only — line records are the only
+ * gate input (summary carries functionCoverage: 'informational').
+ * - Lane manifests: each lane dir may contain lane-manifest.json
+ * {lane, sha, lcovCount, complete}. With --manifest-expect, a
+ * missing/incomplete manifest for an expected lane marks degraded.
+ * A manifest whose lane name contains 'shard' with lcovCount != 1
+ * marks degraded: the shard lane runs ONE bun process via xargs -x;
+ * a second bun process reusing the coverage dir would have OVERWRITTEN
+ * lcov.info, so any other count means the xargs-batching tripwire
+ * fired and line data was silently lost.
+ * - JSON metrics count src/ files ONLY (test/, scripts/, node_modules
+ * records are kept in the merged out-lcov but excluded from
+ * totals/dirs/files). neverLoaded lists src/**\/*.ts files (non-test,
+ * non-generated, non-*.d.ts) absent from the merged data — a COUNT +
+ * sorted list, deliberately NEVER a fake all-files percentage
+ * (physical lines != executable lines).
+ * - lineHits (EXTENSION KEY, consumed by scripts/coverage-diff-gate.ts):
+ * per-src-file per-line merged DA hits, so the gates read ONE JSON
+ * artifact and never re-parse lcov text.
+ *
+ * Env:
+ * COVERAGE_CORPUS names the corpus ('prCorpus'|'fullCorpus'; default
+ * 'unknown').
+ * GENERATED_AT overrides the generatedAt timestamp (fixture-locked
+ * tests).
+ *
+ * Exit codes: 0 success (including degraded — degraded is DATA, carried in
+ * the summary for the gates to downgrade on); 2 usage/IO error.
+ */
+
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join } from "node:path";
+
+// ---------------------------------------------------------------------------
+// Parsing
+// ---------------------------------------------------------------------------
+
+export interface LcovFileRecord {
+ sf: string;
+ /** [line, hits] pairs, in file order (may repeat lines across records). */
+ da: Array<[number, number]>;
+ /** [line, name] pairs. */
+ fn: Array<[number, string]>;
+ /** [hits, name] pairs. */
+ fnda: Array<[number, string]>;
+}
+
+export interface ParseResult {
+ records: LcovFileRecord[];
+ warnings: string[];
+ /** True when the file is malformed/truncated; caller must skip it whole. */
+ malformed: boolean;
+}
+
+/** Record types we parse but do not carry through (they are recomputed). */
+const KNOWN_RECOMPUTED = new Set(["TN", "FNF", "FNH", "LF", "LH"]);
+
+/**
+ * Parse one lcov.info text. Never throws. On any malformed/truncated
+ * structure, returns malformed:true — the caller drops the whole file.
+ */
+export function parseLcovText(text: string): ParseResult {
+ const warnings: string[] = [];
+ const warnedTypes = new Set<string>();
+ const records: LcovFileRecord[] = [];
+ let current: LcovFileRecord | null = null;
+
+ const fail = (msg: string): ParseResult => {
+ warnings.push(msg);
+ return { records: [], warnings, malformed: true };
+ };
+
+ const lines = text.split("\n");
+ for (let i = 0; i < lines.length; i++) {
+ const raw = lines[i] ?? "";
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
+ if (line.trim() === "") continue;
+
+ if (line === "end_of_record") {
+ if (!current) return fail(`line ${i + 1}: end_of_record without SF`);
+ records.push(current);
+ current = null;
+ continue;
+ }
+
+ const colon = line.indexOf(":");
+ if (colon < 0) return fail(`line ${i + 1}: unparseable line ${JSON.stringify(line)}`);
+ const type = line.slice(0, colon);
+ const rest = line.slice(colon + 1);
+
+ if (type === "SF") {
+ if (current) return fail(`line ${i + 1}: SF while previous record open (missing end_of_record)`);
+ if (rest.trim() === "") return fail(`line ${i + 1}: SF with empty path`);
+ current = { sf: rest.trim(), da: [], fn: [], fnda: [] };
+ continue;
+ }
+ if (KNOWN_RECOMPUTED.has(type)) continue; // parsed + ignored; regenerated on output
+ if (type === "DA") {
+ if (!current) return fail(`line ${i + 1}: DA outside an SF record`);
+ const parts = rest.split(",");
+ const ln = Number(parts[0]);
+ const hits = Number(parts[1]);
+ if (!Number.isFinite(ln) || !Number.isFinite(hits)) {
+ return fail(`line ${i + 1}: malformed DA record ${JSON.stringify(line)}`);
+ }
+ current.da.push([ln, hits]);
+ continue;
+ }
+ if (type === "FN") {
+ if (!current) return fail(`line ${i + 1}: FN outside an SF record`);
+ const comma = rest.indexOf(",");
+ const ln = Number(comma < 0 ? rest : rest.slice(0, comma));
+ const name = comma < 0 ? "" : rest.slice(comma + 1);
+ if (!Number.isFinite(ln)) return fail(`line ${i + 1}: malformed FN record`);
+ current.fn.push([ln, name]);
+ continue;
+ }
+ if (type === "FNDA") {
+ if (!current) return fail(`line ${i + 1}: FNDA outside an SF record`);
+ const comma = rest.indexOf(",");
+ const hits = Number(comma < 0 ? rest : rest.slice(0, comma));
+ const name = comma < 0 ? "" : rest.slice(comma + 1);
+ if (!Number.isFinite(hits)) return fail(`line ${i + 1}: malformed FNDA record`);
+ current.fnda.push([hits, name]);
+ continue;
+ }
+ // Unknown record type: warn once per type per file, skip (no pass-through).
+ if (!warnedTypes.has(type)) {
+ warnedTypes.add(type);
+ warnings.push(`unknown lcov record type ${JSON.stringify(type)} — skipped`);
+ }
+ }
+ if (current) return fail("truncated file: SF record without end_of_record");
+ return { records, warnings, malformed: false };
+}
+
+// ---------------------------------------------------------------------------
+// SF normalization
+// ---------------------------------------------------------------------------
+
+/**
+ * Normalize an SF path to repo-relative POSIX. Repo root = repoRootAbs
+ * (process.cwd() in production). Also strips any absolute prefix ending in
+ * the repo directory name (CI checkouts live under a different absolute
+ * root than the machine that reads the artifact).
+ */
+export function normalizeSf(sfRaw: string, repoRootAbs: string): string {
+ let p = sfRaw.replace(/\\/g, "/");
+ const root = repoRootAbs.replace(/\\/g, "/").replace(/\/+$/, "");
+ if (p === root) return "";
+ if (p.startsWith(root + "/")) p = p.slice(root.length + 1);
+ else if (p.startsWith("/") || /^[A-Za-z]:\//.test(p)) {
+ const repoDirName = root.slice(root.lastIndexOf("/") + 1);
+ const marker = "/" + repoDirName + "/";
+ const idx = p.lastIndexOf(marker);
+ if (idx >= 0) p = p.slice(idx + marker.length);
+ // else: absolute path outside any recognizable repo prefix — keep as-is;
+ // it will not match src/ and stays out of the JSON metrics.
+ }
+ while (p.startsWith("./")) p = p.slice(2);
+ return p;
+}
+
+// ---------------------------------------------------------------------------
+// Merging
+// ---------------------------------------------------------------------------
+
+export interface MergedFile {
+ /** line -> summed hits */
+ da: Map<number, number>;
+ /** function name -> first (lowest) line seen */
+ fnLine: Map<string, number>;
+ /** function name -> summed hits */
+ fnda: Map<string, number>;
+}
+
+export type Merged = Map<string, MergedFile>;
+
+export function mergeRecord(merged: Merged, sfNormalized: string, rec: LcovFileRecord): void {
+ let f = merged.get(sfNormalized);
+ if (!f) {
+ f = { da: new Map(), fnLine: new Map(), fnda: new Map() };
+ merged.set(sfNormalized, f);
+ }
+ for (const [line, hits] of rec.da) f.da.set(line, (f.da.get(line) ?? 0) + hits);
+ for (const [line, name] of rec.fn) {
+ const prev = f.fnLine.get(name);
+ if (prev === undefined || line < prev) f.fnLine.set(name, line);
+ }
+ for (const [hits, name] of rec.fnda) f.fnda.set(name, (f.fnda.get(name) ?? 0) + hits);
+}
+
+/** Regenerate a merged lcov text from parsed data (fresh counters). */
+export function emitLcov(merged: Merged): string {
+ const out: string[] = [];
+ const files = [...merged.keys()].sort();
+ for (const file of files) {
+ const f = merged.get(file)!;
+ out.push("TN:");
+ out.push(`SF:${file}`);
+ const fnEntries = [...f.fnLine.entries()].sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1));
+ for (const [name, line] of fnEntries) out.push(`FN:${line},${name}`);
+ const fndaEntries = [...f.fnda.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
+ for (const [name, hits] of fndaEntries) out.push(`FNDA:${hits},${name}`);
+ out.push(`FNF:${f.fnLine.size}`);
+ out.push(`FNH:${[...f.fnda.values()].filter((h) => h > 0).length}`);
+ const daLines = [...f.da.keys()].sort((a, b) => a - b);
+ for (const line of daLines) out.push(`DA:${line},${f.da.get(line)!}`);
+ out.push(`LF:${f.da.size}`);
+ out.push(`LH:${[...f.da.values()].filter((h) => h > 0).length}`);
+ out.push("end_of_record");
+ }
+ return out.join("\n") + (out.length > 0 ? "\n" : "");
+}
+
+// ---------------------------------------------------------------------------
+// src/ inventory for neverLoaded
+// ---------------------------------------------------------------------------
+
+/**
+ * All gate-relevant source files on disk: src/**\/*.ts, excluding *.test.ts,
+ * *.generated.ts, *.d.ts. Repo-relative POSIX, sorted.
+ */
+export function listSrcTsFiles(repoRootAbs: string): string[] {
+ const srcAbs = join(repoRootAbs, "src");
+ if (!existsSync(srcAbs)) return [];
+ const out: string[] = [];
+ const walk = (dirAbs: string, relFromSrc: string): void => {
+ for (const ent of readdirSync(dirAbs, { withFileTypes: true })) {
+ const rel = relFromSrc ? `${relFromSrc}/${ent.name}` : ent.name;
+ if (ent.isDirectory()) {
+ if (ent.name === "node_modules") continue;
+ walk(join(dirAbs, ent.name), rel);
+ } else if (
+ ent.name.endsWith(".ts") &&
+ !ent.name.endsWith(".test.ts") &&
+ !ent.name.endsWith(".generated.ts") &&
+ !ent.name.endsWith(".d.ts")
+ ) {
+ out.push(`src/${rel}`);
+ }
+ }
+ };
+ walk(srcAbs, "");
+ return out.sort();
+}
+
+// ---------------------------------------------------------------------------
+// Summary
+// ---------------------------------------------------------------------------
+
+export interface CovTriple {
+ lines: number;
+ covered: number;
+ pct: number;
+}
+
+export function pctOf(covered: number, lines: number): number {
+ if (lines === 0) return 0;
+ return Math.round((covered / lines) * 10000) / 100;
+}
+
+/** Top-level src dir bucket: src/core/x/y.ts -> 'src/core'; src/cli.ts -> 'src'. */
+export function topLevelSrcDir(file: string): string {
+ const parts = file.split("/");
+ return parts.length >= 3 ? `${parts[0]}/${parts[1]}` : parts[0]!;
+}
+
+// ---------------------------------------------------------------------------
+// Lane manifests
+// ---------------------------------------------------------------------------
+
+export interface LaneManifest {
+ lane: string;
+ sha?: string;
+ lcovCount?: number;
+ complete?: boolean;
+}
+
+// ---------------------------------------------------------------------------
+// main
+// ---------------------------------------------------------------------------
+
+function warn(msg: string): void {
+ process.stderr.write(`merge-lcov: warning: ${msg}\n`);
+}
+
+function usage(msg: string): never {
+ process.stderr.write(`merge-lcov: ${msg}\n`);
+ process.stderr.write(
+ "usage: bun scripts/merge-lcov.ts --out-lcov <path> --out-json <path> [--manifest-expect <lane,lane,...>] <dir-or-file>...\n",
+ );
+ process.exit(2);
+}
+
+/**
+ * Self-merge guard: the CI report job downloads coverage artifacts via the
+ * `coverage-*` glob, and on a re-run the PRIOR report job's own
+ * `coverage-merged` artifact matches that glob too. Re-merging our own merged
+ * output into itself would double every hit count, so any lcov.info whose
+ * path contains a `coverage-merged` segment is skipped.
+ */
+export function isMergedArtifactPath(p: string): boolean {
+ return p.split(/[\\/]/).includes("coverage-merged");
+}
+
+function walkForInputs(dirAbs: string, lcovFiles: string[], manifestFiles: string[]): void {
+ for (const ent of readdirSync(dirAbs, { withFileTypes: true })) {
+ const p = join(dirAbs, ent.name);
+ if (ent.isDirectory()) {
+ if (ent.name === "node_modules") continue;
+ walkForInputs(p, lcovFiles, manifestFiles);
+ } else if (ent.name === "lcov.info") {
+ if (isMergedArtifactPath(p)) {
+ // Expected on report-job re-runs — skipped, NOT degraded.
+ warn(`skipping ${p}: under a coverage-merged path segment (self-merge guard)`);
+ continue;
+ }
+ lcovFiles.push(p);
+ } else if (ent.name === "lane-manifest.json") {
+ manifestFiles.push(p);
+ }
+ }
+}
+
+function main(): void {
+ const argv = process.argv.slice(2);
+ let outLcov = "";
+ let outJson = "";
+ let manifestExpect: string[] = [];
+ const inputs: string[] = [];
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ if (a === "--out-lcov") outLcov = argv[++i] ?? "";
+ else if (a === "--out-json") outJson = argv[++i] ?? "";
+ else if (a === "--manifest-expect") {
+ manifestExpect = (argv[++i] ?? "")
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ } else if (a.startsWith("--")) usage(`unknown flag: ${a}`);
+ else inputs.push(a);
+ }
+ if (!outLcov || !outJson) usage("--out-lcov and --out-json are required");
+ if (inputs.length === 0) usage("at least one <dir-or-file> input is required");
+
+ let degraded = false;
+ const lcovFiles: string[] = [];
+ const manifestFiles: string[] = [];
+ for (const input of inputs) {
+ if (!existsSync(input)) {
+ warn(`input path not found: ${input} — marking degraded`);
+ degraded = true;
+ continue;
+ }
+ const st = statSync(input);
+ if (st.isFile()) {
+ if (isMergedArtifactPath(input)) {
+ warn(`skipping ${input}: under a coverage-merged path segment (self-merge guard)`);
+ continue;
+ }
+ lcovFiles.push(input);
+ } else {
+ walkForInputs(input, lcovFiles, manifestFiles);
+ }
+ }
+
+ // --- lane manifests ---
+ const manifests: LaneManifest[] = [];
+ for (const mf of manifestFiles) {
+ try {
+ const parsed = JSON.parse(readFileSync(mf, "utf8")) as Partial<LaneManifest>;
+ if (typeof parsed.lane !== "string" || parsed.lane === "") {
+ warn(`manifest ${mf} has no lane name — marking degraded`);
+ degraded = true;
+ continue;
+ }
+ manifests.push({
+ lane: parsed.lane,
+ sha: typeof parsed.sha === "string" ? parsed.sha : undefined,
+ lcovCount: typeof parsed.lcovCount === "number" ? parsed.lcovCount : undefined,
+ complete: parsed.complete === true,
+ });
+ } catch {
+ warn(`manifest ${mf} is not valid JSON — marking degraded`);
+ degraded = true;
+ }
+ }
+ for (const m of manifests) {
+ // xargs-batching tripwire: a shard lane must have written EXACTLY ONE
+ // lcov.info (one bun process). Anything else means data was overwritten
+ // or never written.
+ if (m.lane.includes("shard") && m.lcovCount !== 1) {
+ warn(`shard lane '${m.lane}' has lcovCount=${m.lcovCount ?? "missing"} (expected 1) — marking degraded`);
+ degraded = true;
+ }
+ }
+ for (const expected of manifestExpect) {
+ const m = manifests.find((x) => x.lane === expected);
+ if (!m) {
+ warn(`expected lane '${expected}' has no lane-manifest.json — marking degraded`);
+ degraded = true;
+ } else if (m.complete !== true) {
+ warn(`expected lane '${expected}' manifest is not complete — marking degraded`);
+ degraded = true;
+ }
+ }
+
+ // --- parse + merge ---
+ const repoRoot = process.cwd();
+ const merged: Merged = new Map();
+ let parsedFiles = 0;
+ for (const lf of lcovFiles) {
+ let text: string;
+ try {
+ text = readFileSync(lf, "utf8");
+ } catch (err) {
+ warn(`cannot read ${lf}: ${String(err)} — skipped, marking degraded`);
+ degraded = true;
+ continue;
+ }
+ const res = parseLcovText(text);
+ for (const w of res.warnings) warn(`${lf}: ${w}`);
+ if (res.malformed) {
+ warn(`${lf}: malformed/truncated — file skipped whole, marking degraded`);
+ degraded = true;
+ continue;
+ }
+ parsedFiles++;
+ for (const rec of res.records) {
+ const sf = normalizeSf(rec.sf, repoRoot);
+ if (sf === "") continue;
+ mergeRecord(merged, sf, rec);
+ }
+ }
+ if (parsedFiles === 0) warn("no lcov.info data merged (zero parseable inputs)");
+
+ // --- JSON metrics: src/ files only ---
+ const srcFiles = [...merged.keys()].filter((f) => f.startsWith("src/")).sort();
+ const files: Record<string, CovTriple> = {};
+ const dirAgg = new Map<string, { lines: number; covered: number }>();
+ const lineHits: Record<string, Record<string, number>> = {};
+ let totalLines = 0;
+ let totalCovered = 0;
+ for (const f of srcFiles) {
+ const m = merged.get(f)!;
+ const lines = m.da.size;
+ const covered = [...m.da.values()].filter((h) => h > 0).length;
+ files[f] = { lines, covered, pct: pctOf(covered, lines) };
+ totalLines += lines;
+ totalCovered += covered;
+ const dir = topLevelSrcDir(f);
+ const agg = dirAgg.get(dir) ?? { lines: 0, covered: 0 };
+ agg.lines += lines;
+ agg.covered += covered;
+ dirAgg.set(dir, agg);
+ const hits: Record<string, number> = {};
+ for (const line of [...m.da.keys()].sort((a, b) => a - b)) hits[String(line)] = m.da.get(line)!;
+ lineHits[f] = hits;
+ }
+ const dirs: Record<string, CovTriple> = {};
+ for (const dir of [...dirAgg.keys()].sort()) {
+ const agg = dirAgg.get(dir)!;
+ dirs[dir] = { lines: agg.lines, covered: agg.covered, pct: pctOf(agg.covered, agg.lines) };
+ }
+
+ const loaded = new Set(srcFiles);
+ const neverLoadedFiles = listSrcTsFiles(repoRoot).filter((f) => !loaded.has(f));
+
+ const summary = {
+ generatedAt: process.env.GENERATED_AT || new Date().toISOString(),
+ corpus: process.env.COVERAGE_CORPUS || "unknown",
+ lanes: {
+ expected: manifestExpect,
+ complete: manifests
+ .filter((m) => m.complete === true)
+ .map((m) => m.lane)
+ .sort(),
+ },
+ degraded,
+ total: { lines: totalLines, covered: totalCovered, pct: pctOf(totalCovered, totalLines) },
+ dirs,
+ files,
+ functionCoverage: "informational" as const,
+ neverLoaded: { count: neverLoadedFiles.length, files: neverLoadedFiles },
+ lineHits,
+ };
+
+ try {
+ mkdirSync(dirname(outLcov), { recursive: true });
+ mkdirSync(dirname(outJson), { recursive: true });
+ writeFileSync(outLcov, emitLcov(merged), "utf8");
+ writeFileSync(outJson, JSON.stringify(summary, null, 2) + "\n", "utf8");
+ } catch (err) {
+ process.stderr.write(`merge-lcov: cannot write outputs: ${String(err)}\n`);
+ process.exit(2);
+ }
+
+ process.stderr.write(
+ `merge-lcov: merged ${lcovFiles.length} lcov file(s) (${parsedFiles} parseable) → ` +
+ `${srcFiles.length} src file(s), total ${summary.total.pct}% ` +
+ `(${totalCovered}/${totalLines} lines), degraded=${degraded}\n`,
+ );
+}
+
+if (import.meta.main) main();
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
new file mode 100644
index 0000000000..8591af5740
--- /dev/null
+++ b/scripts/module-size-limits.tsv
@@ -0,0 +1,35 @@
+# Module-size ratchet ceilings (containment sprint). Enforced by
+# scripts/check-module-size.sh via `bun run check:module-size` (in verify).
+# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
+# the same commit as any peel (the guard fails on >50 lines of stale slack).
+# Columns: path max_lines policy note
+src/commands/doctor.ts 4183 ratchet peel target: containment sprint C8-C13
+src/core/operations.ts 303 ratchet peel target: containment sprint C4-C7
+src/core/postgres-engine.ts 5716 ratchet peel target: containment sprint C15
+src/core/pglite-engine.ts 5609 ratchet peel target: containment sprint C15
+src/core/migrate.ts 668 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted
+src/commands/sync.ts 4121 ratchet peel target: containment sprint C13-C14
+src/core/ai/gateway.ts 4105 ratchet watchlist
+src/cli.ts 3337 ratchet watchlist
+src/core/cycle.ts 2933 ratchet
+src/commands/serve-http.ts 2836 ratchet
+src/commands/jobs.ts 2826 ratchet
+src/core/search/hybrid.ts 2479 ratchet
+src/core/engine.ts 2343 ratchet
+src/commands/autopilot.ts 2301 ratchet
+src/commands/extract.ts 2161 ratchet
+src/commands/extract-conversation-facts.ts 1968 ratchet
+src/core/import-file.ts 1895 ratchet
+src/core/cycle/synthesize.ts 2616 ratchet
+src/commands/embed.ts 1859 ratchet
+src/core/types.ts 1822 ratchet
+src/commands/skillpack.ts 1763 ratchet
+src/core/minions/queue.ts 1824 ratchet
+src/commands/init.ts 1923 ratchet
+src/commands/integrations.ts 1675 ratchet
+src/core/minions/handlers/subagent.ts 1643 ratchet
+src/commands/bootstrap.ts 1923 ratchet grandfathered at merge (grew past the 1500 cap on master)
+src/core/minions/worker.ts 1508 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170)
+src/commands/sources.ts 1586 ratchet
+src/core/bootstrap/harness.ts 1947 ratchet
+src/commands/hook.ts 1525 ratchet
diff --git a/scripts/render-coverage-summary.ts b/scripts/render-coverage-summary.ts
new file mode 100644
index 0000000000..872c68c2ae
--- /dev/null
+++ b/scripts/render-coverage-summary.ts
@@ -0,0 +1,176 @@
+#!/usr/bin/env bun
+/**
+ * scripts/render-coverage-summary.ts — render the merged coverage summary
+ * JSON as a GitHub-step-summary markdown block (containment sprint).
+ *
+ * Usage:
+ * bun scripts/render-coverage-summary.ts --summary <json> \
+ * [--structural scripts/structural-suites.tsv]
+ *
+ * Prints: corpus, lane completeness, DEGRADED banner (when set), total %,
+ * per-dir table, top-10 worst-covered files (watchlist prioritized; the
+ * watchlist is read from the working-tree scripts/coverage-baseline.json),
+ * neverLoaded count + first 10, the src/cli.ts subprocess-undercount note,
+ * and the behavioral-vs-structural test-intent line parsed from the TSV.
+ *
+ * This renderer consumes ONLY the JSON artifact (+ the structural TSV);
+ * it never stdout-parses other tools.
+ *
+ * Exit codes: 0 success; 2 usage/IO error.
+ */
+
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+export interface StructuralCounts {
+ suites: number;
+ cases: number;
+}
+
+/**
+ * Parse scripts/structural-suites.tsv (columns: file, suite, cases,
+ * detector; '#' comments). Returns suite-row count + summed cases.
+ */
+export function parseStructuralTsv(text: string): StructuralCounts {
+ let suites = 0;
+ let cases = 0;
+ for (const raw of text.split("\n")) {
+ const line = raw.trimEnd();
+ if (line === "" || line.startsWith("#")) continue;
+ const cols = line.split("\t");
+ if (cols.length < 3) continue;
+ suites++;
+ const n = Number(cols[2]);
+ if (Number.isFinite(n)) cases += n;
+ }
+ return { suites, cases };
+}
+
+interface CovTriple {
+ lines: number;
+ covered: number;
+ pct: number;
+}
+
+interface SummaryJson {
+ generatedAt?: string;
+ corpus?: string;
+ lanes?: { expected?: string[]; complete?: string[] };
+ degraded?: boolean;
+ total?: CovTriple;
+ dirs?: Record<string, CovTriple>;
+ files?: Record<string, CovTriple>;
+ neverLoaded?: { count: number; files: string[] };
+}
+
+function fail(msg: string): never {
+ process.stderr.write(`render-coverage-summary: ${msg}\n`);
+ process.exit(2);
+}
+
+function main(): void {
+ const argv = process.argv.slice(2);
+ let summaryPath = "";
+ let structuralPath = "";
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ if (a === "--summary") summaryPath = argv[++i] ?? "";
+ else if (a === "--structural") structuralPath = argv[++i] ?? "";
+ else fail(`unknown argument: ${a}`);
+ }
+ if (!summaryPath) fail("--summary <json> is required");
+ if (!existsSync(summaryPath)) fail(`summary JSON not found: ${summaryPath}`);
+ let summary: SummaryJson;
+ try {
+ summary = JSON.parse(readFileSync(summaryPath, "utf8")) as SummaryJson;
+ } catch (err) {
+ fail(`summary JSON unparseable: ${String(err)}`);
+ }
+
+ const out: string[] = [];
+ out.push("## Coverage summary");
+ out.push("");
+ out.push(`- Corpus: \`${summary.corpus ?? "unknown"}\` (generated ${summary.generatedAt ?? "?"})`);
+ const expected = summary.lanes?.expected ?? [];
+ const complete = summary.lanes?.complete ?? [];
+ const completeOfExpected = expected.filter((l) => complete.includes(l));
+ if (expected.length > 0) {
+ out.push(`- Lanes: ${completeOfExpected.length}/${expected.length} complete (expected: ${expected.join(", ")}; complete: ${complete.join(", ") || "none"})`);
+ } else {
+ out.push(`- Lanes: no expected-lane manifest check (complete: ${complete.join(", ") || "none"})`);
+ }
+ if (summary.degraded === true) {
+ out.push("");
+ out.push("> **DEGRADED COVERAGE DATA** — a lane was incomplete or an lcov file was malformed; gates run report-only for this run.");
+ }
+ out.push("");
+ const total = summary.total ?? { lines: 0, covered: 0, pct: 0 };
+ out.push(`- Total line coverage: **${total.pct}%** (${total.covered}/${total.lines} executable lines)`);
+ out.push("- Function coverage: informational only (bun/JSC omits function names; line records are the gate input)");
+ out.push("");
+
+ // Per-directory table.
+ const dirs = summary.dirs ?? {};
+ out.push("### Per-directory line coverage");
+ out.push("");
+ out.push("| dir | lines | covered | pct |");
+ out.push("|---|---|---|---|");
+ for (const dir of Object.keys(dirs).sort()) {
+ const d = dirs[dir]!;
+ out.push(`| ${dir} | ${d.lines} | ${d.covered} | ${d.pct}% |`);
+ }
+ out.push("");
+
+ // Worst-covered files, watchlist prioritized.
+ const files = summary.files ?? {};
+ let watchlist: string[] = [];
+ const baselinePath = join(import.meta.dir, "coverage-baseline.json");
+ if (existsSync(baselinePath)) {
+ try {
+ const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { watchlist?: string[] };
+ if (Array.isArray(baseline.watchlist)) watchlist = baseline.watchlist;
+ } catch {
+ // display-only nicety; a broken baseline never blocks rendering
+ }
+ }
+ const watchSet = new Set(watchlist);
+ const byPctAsc = (a: string, b: string) => files[a]!.pct - files[b]!.pct || (a < b ? -1 : 1);
+ const watchRows = Object.keys(files).filter((f) => watchSet.has(f)).sort(byPctAsc);
+ const otherRows = Object.keys(files).filter((f) => !watchSet.has(f)).sort(byPctAsc);
+ const worst = [...watchRows, ...otherRows].slice(0, 10);
+ out.push("### Worst-covered files (top 10, watchlist prioritized)");
+ out.push("");
+ out.push("| file | pct | lines | watchlist |");
+ out.push("|---|---|---|---|");
+ for (const f of worst) {
+ const e = files[f]!;
+ out.push(`| ${f} | ${e.pct}% | ${e.lines} | ${watchSet.has(f) ? "yes" : ""} |`);
+ }
+ out.push("");
+
+ // Never-loaded inventory (count + head, never a fake percentage).
+ const never = summary.neverLoaded ?? { count: 0, files: [] };
+ out.push(`### Never-loaded src files: ${never.count}`);
+ out.push("");
+ for (const f of never.files.slice(0, 10)) out.push(`- ${f}`);
+ if (never.count > 10) out.push(`- … +${never.count - 10} more`);
+ out.push("");
+
+ out.push(
+ "Note: src/cli.ts is exercised mostly via CLI subprocesses; bun coverage does not propagate into child processes, so its numbers undercount ([subprocess-undercount]).",
+ );
+ out.push("");
+
+ if (structuralPath) {
+ if (!existsSync(structuralPath)) fail(`structural TSV not found: ${structuralPath}`);
+ const counts = parseStructuralTsv(readFileSync(structuralPath, "utf8"));
+ out.push(
+ `Behavioral vs structural: structural suites ${counts.suites} / cases ${counts.cases} (see scripts/structural-suites.tsv)`,
+ );
+ out.push("");
+ }
+
+ process.stdout.write(out.join("\n"));
+}
+
+if (import.meta.main) main();
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 30adc536d8..c7754199a8 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -36,6 +36,19 @@ set -euo pipefail
cd "$(dirname "$0")/.."
+# COVERAGE_DIR (opt-in lcov coverage) must be an ABSOLUTE path: this script
+# redirects HOME (and E2E tests spawn CLI subprocesses with varying cwd), so
+# a relative --coverage-dir would scatter lcov output across working dirs.
+# Normalize it once against the repo root, before HOME moves. COVERAGE_DIR is
+# deliberately NOT GBRAIN-prefixed: the hermetic env scrub below drops
+# GBRAIN_*/operator prefixes, and this variable must survive that scrub.
+if [ -n "${COVERAGE_DIR:-}" ]; then
+ case "$COVERAGE_DIR" in
+ /*) ;;
+ *) COVERAGE_DIR="$PWD/$COVERAGE_DIR" ;;
+ esac
+fi
+
# #3485: this wrapper IS the e2e boundary — opt in to running with a database
# URL present. The bunfig test preload (database-url-guard-preload.ts) refuses
# bare `bun test` runs while DATABASE_URL/GBRAIN_DATABASE_URL is ambient; the
@@ -98,6 +111,7 @@ for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPEN
GBRAIN_HOME) ;; # required for HOME isolation (set above) — keep
GBRAIN_PGLITE_SNAPSHOT) ;; # snapshot fast-path fixture (exported by ci-local.sh / runners) — keep
GBRAIN_TEST_ALLOW_DATABASE_URL) ;; # #3485 preload opt-in (set above) — keep
+ GBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive it
GBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error
# message tells operators to set it; stripping it
# here would make that escape hatch a dead end
@@ -171,9 +185,19 @@ fail_files=0
fail_list=()
total_pass=0
total_fail=0
+file_idx=0
for f in "${files[@]}"; do
name=$(basename "$f")
+ file_idx=$((file_idx + 1))
+ # COVERAGE_DIR (opt-in): each E2E file runs in its OWN bun process, so each
+ # needs its OWN coverage dir — a second bun process reusing a coverage dir
+ # OVERWRITES lcov.info. Empty/unset COVERAGE_DIR leaves the exec line
+ # byte-identical to the pre-coverage behavior.
+ COVERAGE_ARGS=()
+ if [ -n "${COVERAGE_DIR:-}" ]; then
+ COVERAGE_ARGS=(--coverage --coverage-reporter=lcov --coverage-dir="$COVERAGE_DIR/e2e-$file_idx")
+ fi
echo ""
echo "=== $name ==="
# Cross-file isolation: terminate any stale connections from the prior
@@ -186,10 +210,13 @@ for f in "${files[@]}"; do
if [ -n "${DATABASE_URL:-}" ]; then
psql "$DATABASE_URL" -At -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid != pg_backend_pid() AND datname = current_database()" >/dev/null 2>&1 || true
fi
- # Hard outer timeout (default 180s per file; GBRAIN_E2E_FILE_TIMEOUT
- # overrides). bun's --timeout covers tests AND hooks (measured on 1.3.14),
- # but it's timer-based: a PGLite WASM call that blocks the event loop
- # synchronously never lets the timer fire and the file wedges indefinitely.
+ # Hard outer timeout (default 180s per file; GBRAIN_E2E_FILE_TIMEOUT or
+ # E2E_FILE_TIMEOUT_SECS overrides — the GBRAIN_ name is kept in the scrub
+ # keep-list below, the non-GBRAIN name survives the scrub by construction;
+ # nightly coverage runs use it to absorb instrumentation overhead). bun's
+ # --timeout covers tests AND hooks (measured on 1.3.14), but it's
+ # timer-based: a PGLite WASM call that blocks the event loop synchronously
+ # never lets the timer fire and the file wedges indefinitely.
# gtimeout/timeout SIGKILLs the file so the suite advances. gtimeout (macOS
# via coreutils) preferred; timeout (Linux) fallback; bare bun (no outer
# cap) if neither is installed.
@@ -200,7 +227,7 @@ for f in "${files[@]}"; do
# assertion output, which reads like a mystery failure. CI runs those
# files in their own job WITHOUT this wrapper (see .github/workflows/
# e2e.yml tier2), so the cap only ever bit local runs: give them 4x.
- file_timeout="${GBRAIN_E2E_FILE_TIMEOUT:-180}"
+ file_timeout="${GBRAIN_E2E_FILE_TIMEOUT:-${E2E_FILE_TIMEOUT_SECS:-180}}"
# Digits-only validation (same strict positive-int posture as the TS env
# knobs): a malformed value falls back to the default instead of
# word-splitting into extra gtimeout arguments or breaking the 4x math.
@@ -215,7 +242,7 @@ for f in "${files[@]}"; do
else
TIMEOUT_CMD=""
fi
- if output=$($TIMEOUT_CMD bun test --timeout=60000 "$f" 2>&1); then
+ if output=$($TIMEOUT_CMD bun test --timeout=60000 ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} "$f" 2>&1); then
pass_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)
@@ -282,3 +309,12 @@ if [ ${#fail_list[@]} -gt 0 ]; then
done
exit 1
fi
+
+# Lane manifest: written ONLY on a fully green run (isolation breach exits 2
+# and failing files exit 1 above, both before reaching here), so
+# complete:true means the lcov data represents the whole E2E lane.
+if [ -n "${COVERAGE_DIR:-}" ]; then
+ LCOV_COUNT=$(find "$COVERAGE_DIR" -name 'lcov.info' 2>/dev/null | grep -c '^' || true)
+ printf '{"lane":"e2e","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$(git rev-parse HEAD)" "${LCOV_COUNT:-0}" > "$COVERAGE_DIR/lane-manifest.json"
+fi
diff --git a/scripts/run-serial-tests.sh b/scripts/run-serial-tests.sh
index 03562d5ebf..2012b16727 100755
--- a/scripts/run-serial-tests.sh
+++ b/scripts/run-serial-tests.sh
@@ -161,11 +161,21 @@ echo "[serial-tests] ${#files[@]} file(s): pool=$POOL (${#exclusive_present[@]}
run_one_file() {
# $1 file, $2 log path, $3 exit-sentinel path, $4 wrap ("wrap"|"nowrap")
local f="$1" log="$2" exitf="$3" wrap="$4" rc=0
+ # COVERAGE_DIR (opt-in): every bun process needs its OWN coverage dir — a
+ # second process reusing a dir OVERWRITES lcov.info. The log basename is
+ # unique per file (pool idx / exclusive i), so it keys the dir. Empty/unset
+ # COVERAGE_DIR leaves the exec line byte-identical to pre-coverage behavior.
+ local cov_args=()
+ if [ -n "${COVERAGE_DIR:-}" ]; then
+ local key
+ key=$(basename "$log" .log)
+ cov_args=(--coverage --coverage-reporter=lcov --coverage-dir="$COVERAGE_DIR/serial-$key")
+ fi
if [ "$wrap" = "wrap" ] && [ -n "$TIMEOUT_BIN" ]; then
"$TIMEOUT_BIN" -k 15 "$PER_FILE_TIMEOUT" \
- bun test --max-concurrency=1 --timeout=120000 "$f" > "$log" 2>&1 || rc=$?
+ bun test --max-concurrency=1 --timeout=120000 ${cov_args[@]+"${cov_args[@]}"} "$f" > "$log" 2>&1 || rc=$?
else
- bun test --max-concurrency=1 --timeout=120000 "$f" > "$log" 2>&1 || rc=$?
+ bun test --max-concurrency=1 --timeout=120000 ${cov_args[@]+"${cov_args[@]}"} "$f" > "$log" 2>&1 || rc=$?
fi
echo "$rc" > "$exitf"
}
@@ -308,6 +318,14 @@ if [ "$fail_count" -gt 0 ]; then
done
exit 1
fi
+# Lane manifest: written ONLY on a fully green run (complete:true means the
+# lcov data represents every serial file). merge-lcov.ts's --manifest-expect
+# treats a missing manifest as a degraded lane.
+if [ -n "${COVERAGE_DIR:-}" ]; then
+ LCOV_COUNT=$(find "$COVERAGE_DIR" -name 'lcov.info' 2>/dev/null | grep -c '^' || true)
+ printf '{"lane":"serial","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$(git rev-parse HEAD)" "${LCOV_COUNT:-0}" > "$COVERAGE_DIR/lane-manifest.json"
+fi
# bun-summary-format aggregate: run-unit-parallel.sh's headline counter
# (bun_summary_count awk: $1 numeric, $2 == "pass") reads this line — without
# it the serial suite's tests vanish from `bun run test`'s pass=N banner.
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index d1fe317799..d4b4d0555e 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -111,6 +111,9 @@ CHECKS=(
# Revived registered-but-never-executed guards (this pass):
"check:pagetype-exhaustive"
"check:pg-url-redaction"
+ # Containment sprint: module-size ratchet + structural-suite freshness.
+ "check:module-size"
+ "check:structural-manifest"
)
if [ "${#CHECKS[@]}" -eq 0 ]; then
diff --git a/scripts/select-e2e.ts b/scripts/select-e2e.ts
index f57122f8bd..252424eff7 100644
--- a/scripts/select-e2e.ts
+++ b/scripts/select-e2e.ts
@@ -78,6 +78,9 @@ const ESCAPE_HATCH_FILES = new Set([
const ESCAPE_HATCH_PREFIXES = [
"src/commands/migrations/",
+ // Operation domain modules peeled out of operations.ts (an escape-hatch
+ // file) carry the same blast radius as the contract itself.
+ "src/core/ops/",
"test/e2e/fixtures/",
"skills/",
".github/workflows/",
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
new file mode 100644
index 0000000000..9e4016f219
--- /dev/null
+++ b/scripts/structural-suites.tsv
@@ -0,0 +1,215 @@
+# Structural test suites — suites whose assertions read repo source/doc text.
+# GENERATED by scripts/classify-tests.ts; freshness-checked in verify.
+# Fix misclassifications in the classifier, never by hand-editing rows.
+# Columns: file suite cases detector
+test/apply-migrations.test.ts failed migration prints phase detail (#921) 1 readFileSync
+test/apply-migrations.test.ts resolveSchemaBehind (#1530) 5 readFileSync
+test/apply-migrations.test.ts runApplyMigrations exit codes (v0.36.1.x #1062) 1 readFileSync
+test/asymmetric-encoding-contract.test.ts Source-text contract (cheap belt + suspenders) 3 readFileSync
+test/autopilot-auto-drain-wiring.test.ts autopilot auto-drain wiring 8 readFileSync
+test/autopilot-cycle-failure-classification.test.ts autopilot cycle-failure classification — only 'failed' trips the circuit breaker 2 readFileSync
+test/autopilot-cycle-failure-classification.test.ts runPhaseOrphans ratio threshold — no more absolute count > 20 3 readFileSync
+test/autopilot-fanout-wiring.test.ts autopilot.ts ↔ dispatchPerSource wiring 13 readFileSync
+test/autopilot-install.test.ts autopilot showStatus — wrapper-path detection 1 readFileSync
+test/autopilot-install.test.ts autopilot wrapper script — bun PATH export (v0.42.x regression) 1 readFileSync
+test/autopilot-install.test.ts autopilot wrapper script — env source order (v0.36.1.x #966) 1 readFileSync
+test/autopilot-pause-marker.test.ts pause marker fences minion job pickup 1 readFileSync
+test/autopilot-self-upgrade.test.ts autopilot self-upgrade static-shape regressions 4 readFileSync
+test/autopilot-shutdown-engine-close.test.ts autopilot.ts graceful engine shutdown (#1872) 4 readFileSync
+test/autopilot-supervisor-wiring.test.ts autopilot.ts ↔ ChildWorkerSupervisor wiring 6 readFileSync
+test/backlinks-job-default.test.ts backlinks Minion handler — empty payload defaults to check, not fix 3 readFileSync
+test/book-mirror.test.ts gbrain book-mirror — source file invariants 7 readFileSync
+test/bootstrap-codex-door.test.ts Codex door — rendered AGENTS.md pull protocol (Gate 3) 2 readFileSync
+test/bootstrap-opencode-door.serial.test.ts opencode door — rendered AGENTS.md pull protocol 1 readFileSync
+test/brain-repo-durability.serial.test.ts hardenBrainRepo 15 readFileSync
+test/brain-score-breakdown.test.ts Bug 11 — BrainHealth type shape 1 bun-file
+test/brain-score-breakdown.test.ts Bug 11 — doctor renders brain_score breakdown 1 doctor-source-helper
+test/brain-score-breakdown.test.ts Bug 11 — orphan_pages is "no inbound links" 3 doctor-source-helper
+test/brain-score-breakdown.test.ts linkable scope — archive pages do not drag the score 3 doctor-source-helper
+test/brainstorm-timeout.test.ts orchestrator entry-point wrap (CV11 single-point classification) 2 bun-file
+test/build-llms.test.ts CLAUDE.md restructure content contracts 5 readFileSync
+test/build-llms.test.ts build-llms generator 7 readFileSync
+test/check-bootstrap-guards.test.ts check-grok-pin.sh 10 readFileSync
+test/check-bootstrap-guards.test.ts verify + workflow wiring 6 readFileSync
+test/check-update.test.ts check-update CLI 3 bun-file
+test/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 3 readFileSync
+test/cli-force-exit-teardown-arming.test.ts cli.ts — disconnect hard-deadline armed at teardown entry, not before the op body 1 readFileSync
+test/cli.test.ts BigInt-safe output normalization (#2450) 5 readFileSync
+test/cli.test.ts CLI structure 6 readFileSync
+test/cli.test.ts CLI version 2 readFileSync
+test/cli.test.ts ask alias 2 readFileSync
+test/codex-plugin-manifest.test.ts codex mcp.json 3 readFileSync
+test/codex-plugin-manifest.test.ts curated tree membership + scanner guard 5 readFileSync
+test/config.test.ts config source correctness 2 readFileSync
+test/connection-resilience.test.ts Eng-review D3 — executeRaw has no per-call retry wrapper 3 readFileSync
+test/contextual-retrieval-service-pure.test.ts inline import contextual synopsis containment 1 readFileSync
+test/cycle-abort.test.ts #1972 — complete cooperative-abort coverage 3 readFileSync
+test/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 4 readFileSync
+test/cycle-abort.test.ts autopilot-cycle handler contract (v0.20.5) 3 readFileSync
+test/cycle-drain-renewal.test.ts db-lock heartbeat wiring (structural — issue #6 cancellation) 1 readFileSync
+test/cycle-drain-renewal.test.ts drain-loop wiring (structural — the shape guard only covers worker.ts) 1 readFileSync
+test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: NEEDS_LOCK_PHASES contract (source-shape) 2 readFileSync
+test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: dispatch result envelope 2 readFileSync
+test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: orchestrator dispatch wires the pack-gate 5 readFileSync
+test/cycle-pack-gating.test.ts v0.41 T9 R-GATE: pre-existing 17 core phases always run 3 readFileSync
+test/cycle-patterns-deadline-budget.test.ts deadline plumbing wiring (structural) 7 readFileSync
+test/cycle-patterns.test.ts patterns phase wiring 9 readFileSync
+test/cycle-patterns.test.ts patterns scope filter 6 readFileSync
+test/cycle/cycle-lock-ttl.test.ts cycle lock TTL (T2 regression pin) 1 readFileSync
+test/doctor-embedding-env-override.test.ts cross-surface parity (source-grep regression guard) 1 doctor-source-helper
+test/doctor-fix.test.ts gbrain doctor --fix CLI integration 3 readFileSync
+test/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — load-bearing render strings 5 doctor-source-helper
+test/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — structural rendering (source-grep) 6 doctor-source-helper
+test/doctor-orphan-ratio.test.ts cross-surface parity contract 3 doctor-source-helper,readFileSync
+test/doctor-orphan-ratio.test.ts runOrphanRatioCheck — thin-client surface (D11) 1 readFileSync
+test/doctor-supervisor-singleton-pidfile.test.ts doctor supervisor_singleton — honors the recorded pid_file (custom --pid-file) 2 doctor-source-helper
+test/doctor-supervisor-singleton-pidfile.test.ts doctor supervisor_singleton — pid_file fallback (source-grep) 1 doctor-source-helper
+test/doctor-volunteer-channels.test.ts checkVolunteerChannels 9 doctor-source-helper,readFileSync
+test/doctor-wedged-queue.test.ts issue #1801 fix #3 — remote queue_health state→status regression 1 doctor-source-helper
+test/doctor.test.ts BUG 4 — in-progress sync via live lock, not stale freshness 8 doctor-source-helper
+test/doctor.test.ts doctor command 32 doctor-source-helper
+test/doctor.test.ts issue #972 — link_resolution_opportunity check 8 doctor-source-helper
+test/doctor.test.ts stub_guard_24h check (v0.34.5) 5 doctor-source-helper
+test/doctor.test.ts supervisor crash classifier wiring (v0.35.x) 4 bun-file,doctor-source-helper
+test/doctor.test.ts sync_freshness — clone-unavailable content-lag fallback 6 doctor-source-helper
+test/doctor.test.ts v0.31.8 — wedge migration force-retry hint (D19) 4 doctor-source-helper
+test/doctor.test.ts v0.32.4 — sync_freshness check 12 doctor-source-helper
+test/doctor.test.ts v0.40.4 — graph_signals_coverage check 7 doctor-source-helper
+test/doctor.test.ts v0.41.27.0 — sync_freshness git short-circuit 9 doctor-source-helper
+test/doctor.test.ts v0.41.32.0 — commit-relative staleness 5 doctor-source-helper
+test/doctor.test.ts v0.42 (#1699) — quarantined_pages + flagged_pages checks 1 doctor-source-helper
+test/dream-cli-flags.test.ts --drain wiring 4 readFileSync
+test/dream-cli-flags.test.ts --once wiring (issue #2860) 5 readFileSync
+test/dream-cli-flags.test.ts --source / --source-id wiring (v0.41.13) 9 readFileSync
+test/dream-cli-flags.test.ts dream CLI flag wiring 9 readFileSync
+test/dry-fix.test.ts autoFixDryViolations 12 readFileSync
+test/e2e/bootstrap-real-codex.serial.test.ts bootstrap rendered protocol — ambient boundaries (always runs) 4 readFileSync
+test/e2e/codex-plugin-install-real.serial.test.ts (file-level) 2 readFileSync
+test/e2e/migration-flow.test.ts (file-level) 4 readFileSync
+test/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (W1 + W2 + W3) 8 readFileSync
+test/e2e/skillpack-flow.test.ts skillpack flow (E2E) 17 readFileSync
+test/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync
+test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper
+test/eval-brainbench-e2e.test.ts --llm availability gate 1 exec-scan
+test/eval-brainbench-e2e.test.ts privacy guard violation branches (negative path) 1 exec-scan
+test/eval-brainbench-e2e.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan
+test/eval-brainbench-e2e.test.ts run-all once-per-sweep semantics (decision 16) 1 exec-scan
+test/exit-classification.test.ts consumer wire-up — helper used by all 3 sites (no inline filters left) 5 doctor-source-helper,readFileSync
+test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on provider_failure (issue #3218) 2 readFileSync
+test/extract-atoms-drain.test.ts shared wiring helper holds the cycle lock (5A) 2 readFileSync
+test/extract-workers.test.ts extract.ts → workers wiring (T7) 10 readFileSync
+test/features.test.ts CLI routing 2 bun-file
+test/filing-rules-resolution.serial.test.ts per-source filing-rules resolution 3 readFileSync
+test/fix-wave-structural.test.ts #2084 — cli.ts owns process-exit teardown via finishCliTeardown 4 readFileSync
+test/fix-wave-structural.test.ts WAL-repair wave structural pins (#223/#2575) 4 readFileSync
+test/fix-wave-structural.test.ts v0.36.1.x #1077 — admin register-client supports PKCE public clients 1 readFileSync
+test/fix-wave-structural.test.ts v0.36.1.x #1090 — admin embed two-tier resolution 3 readFileSync
+test/fix-wave-structural.test.ts v0.36.1.x #1124 — query --no-expand actually negates expand 1 readFileSync
+test/fix-wave-structural.test.ts v0.41.37.0 #1605 — v0.11.0 phaseASchema routes in-process for ALL engines 2 readFileSync
+test/fix-wave-structural.test.ts v0.41.8.0 #1340 — PGLite WASM init classifier 2 readFileSync
+test/fix-wave-structural.test.ts v0.42.20.0 — background-work registry drains every sink before disconnect 6 readFileSync
+test/fix-wave-structural.test.ts v0.42.20.0 — search-cache drained via the background-work registry 1 readFileSync
+test/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (structural pins) 2 readFileSync
+test/hook-command.serial.test.ts user-prompt 14 readFileSync
+test/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSync
+test/integrations.test.ts CLI integration 3 readFileSync
+test/jobs-thin-client-date-rehydration.test.ts thin-client unpack sites route through rehydrateJobDates (source audit) 2 readFileSync
+test/migrate-stdout-clean.test.ts migration output stays off stdout 2 readFileSync
+test/migrate.test.ts PR #356 + #363 — session timeouts applied via startup parameters 1 readFileSync
+test/migrate.test.ts PR #356 — LATEST_VERSION is max(versions), not array[-1] 2 readFileSync
+test/migrate.test.ts PR #356 — apply-migrations pre-flight schema-version warning 1 readFileSync
+test/migrate.test.ts PR #356 — non-transactional DDL runs via reserved connection 1 readFileSync
+test/migrate.test.ts migrate runner v67 — typed-claim columns materialized on PGLite 3 readFileSync
+test/migrate.test.ts migrate v14 — pages_updated_at_index (handler-based, engine-aware) 2 readFileSync
+test/migrate.test.ts migrate v20 — sources_table_additive 6 readFileSync
+test/migrate.test.ts migrate v23 — files_source_id_page_id_ledger 6 readFileSync
+test/migrate.test.ts migrate v36 — subagent_provider_neutral_persistence_v0_27 7 readFileSync
+test/migrate.test.ts migrate v66 — embed_stale_partial_index (D6) 4 readFileSync
+test/migrate.test.ts migrate v89 — round-trip on PGLite 4 readFileSync
+test/migrate.test.ts migrate — DROP INDEX CONCURRENTLY invalid-remnant cleanup (#1178, file-wide) 3 readFileSync
+test/migrate.test.ts migrate — runner behavioral (v14 handler + v15 backfill) 2 readFileSync
+test/migrate.test.ts migrate: v9 (timeline_dedup_index) regression — must be fast on 200 duplicate rows 1 readFileSync
+test/migrate.test.ts migration v49 — eval_takes_quality_runs (v0.32) 6 readFileSync
+test/migrate.test.ts resolvePoolSize — env var + explicit override 4 readFileSync
+test/migrate.test.ts resolveSessionTimeouts — env var overrides 5 readFileSync
+test/migrate.test.ts v117 — context_volunteer_events_table 5 readFileSync
+test/migration-orchestrator-v0_46_3.serial.test.ts v0.46.3 orchestrator behavior 4 readFileSync
+test/migration-resume.test.ts Bug 3 — orchestrator no longer writes the ledger directly 6 bun-file
+test/migrations-v0_11_0.test.ts AGENTS.md marker injection 6 readFileSync
+test/migrations-v0_11_0.test.ts cron manifest rewrite — gbrain builtins only 8 readFileSync
+test/migrations-v0_14_0.test.ts Bug 5 + Bug 8 — v0_14_0 module shape 3 bun-file
+test/migrations-v0_14_0.test.ts Bug 5 — Phase B host-work entry dedup 2 readFileSync
+test/migrations-v0_14_0.test.ts Bug 8 — max_stalled default bumped in schema files 3 bun-file
+test/migrations-v0_22_4.test.ts v0.22.4 migration (B11) 9 readFileSync
+test/model-pricing.test.ts no heavy import (cycle guard) 1 readFileSync
+test/models-doctor-embed.test.ts models doctor — embedding reachability probe (v0.40.x) 3 readFileSync
+test/openclaw-plugin-manifest.test.ts bundled-skill reference closure (nothing bundled points at a non-bundled skill) 1 readFileSync
+test/openclaw-plugin-manifest.test.ts plugin membership curation (skills = plugin ∪ exclusions, disjoint) 9 readFileSync
+test/openclaw-plugin-manifest.test.ts root OpenClaw plugin manifest 2 readFileSync
+test/pglite-engine.test.ts PGLiteEngine: v0.13.1 error-wrap on connect() (#223) 1 readFileSync
+test/pglite-wal-repair.serial.test.ts WAL auto-repair — real-brain regression (#223/#1670/#2575) 6 readFileSync
+test/phantom-redirect-per-source-lock.test.ts phantom-redirect lock contract 3 readFileSync
+test/postgres-engine-singleton-ownership.test.ts postgres-engine / module-singleton ownership (#1471) 7 readFileSync
+test/postgres-engine.test.ts postgres-engine / search date filtering 1 readFileSync
+test/postgres-engine.test.ts postgres-engine / search path timeout isolation 7 readFileSync
+test/readme-hero-anchors.test.ts README hero anchors (D9 regression guard) 5 readFileSync
+test/redos-hardening.test.ts #1569 --no-schema-pack + heartbeat wiring (structural) 2 readFileSync
+test/register-client-source-normalize.test.ts register-client route wiring (structural) 1 readFileSync
+test/regression-strict-source-id.test.ts cycle reverse-write call sites use the consolidated path 4 readFileSync
+test/regression-strict-source-id.test.ts utils.ts no longer carries an inline permissive regex 2 readFileSync
+test/release-workflow.test.ts release.yml ↔ binary-self-update asset contract 7 readFileSync
+test/resolver.test.ts RESOLVER.md trigger round-trip (D5/C) 2 readFileSync
+test/resolver.test.ts Skill example-name validator (D13) 4 readFileSync
+test/schema-cli-contract.test.ts v0.39 T6 — schema CLI contract 7 readFileSync
+test/schema-pack-unify-types-handler.test.ts #1575 unify-types worker dry-run default 1 readFileSync
+test/scripts/classify-tests.test.ts classify-tests detectors 18 bun-file,doctor-source-helper,exec-scan,readFileSync
+test/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSync
+test/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSync
+test/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSync
+test/skillify-scaffold.test.ts 11-item scaffold contract (T9 + Phase 3 cross-modal eval) 1 readFileSync
+test/skillify-scaffold.test.ts applyScaffold 3 readFileSync
+test/skillify-scaffold.test.ts planScaffold 13 readFileSync
+test/skillpack-harvest.test.ts addToBundleManifest 1 readFileSync
+test/skillpack-harvest.test.ts runHarvest — happy path 2 readFileSync
+test/skillpack-harvest.test.ts runHarvest — privacy linter integration (T7) 2 readFileSync
+test/skillpack-init-brain-pack.test.ts runInitBrainPack 5 readFileSync
+test/skillpack-init-pack.test.ts runInitScaffold — cathedral default 6 readFileSync
+test/skillpack-install.test.ts managed-block receipt + cumulative semantics (v0.19) 4 readFileSync
+test/skillpack-install.test.ts planInstall + applyInstall 11 readFileSync
+test/skillpack-migrate-fence.test.ts runMigrateFence 8 readFileSync
+test/skillpack-scaffold.test.ts runScaffold — IRON-RULE regressions (R1, R2) 3 readFileSync
+test/skillpack-scaffold.test.ts runScaffold — happy path 3 readFileSync
+test/skillpack-scrub-legacy.test.ts runScrubLegacy 8 readFileSync
+test/sources-webhook.test.ts Webhook sync job extraction contract 1 readFileSync
+test/spend-off-switch.test.ts reindex / onboard off-switch dispatch (regression guards) 3 bun-file
+test/sync-failures.test.ts Bug 9 — doctor surfaces sync failures 2 doctor-source-helper
+test/sync-failures.test.ts Bug 9 — sync.ts CLI flag wiring 6 bun-file,doctor-source-helper
+test/sync.test.ts buildSyncManifest 9 bun-file
+test/sync.test.ts isSyncable 8 bun-file
+test/sync.test.ts resolveSlugByPathOrSourcePath (CJK wave v0.32.7, codex F4) 3 bun-file
+test/sync.test.ts sync auto-embed arguments 2 bun-file
+test/sync.test.ts sync regression — #132 nested transaction deadlock 1 bun-file
+test/template-repo-generator.test.ts generateTemplateTree 0 readFileSync
+test/template-repo-generator.test.ts renderTemplateReadme 5 readFileSync
+test/thin-client-routing-audit.test.ts thin-client routing audit — scratch-DB additions (jobs partial dispatch + config refusal) 5 readFileSync
+test/thin-client-routing-audit.test.ts thin-client routing audit — v0.32 REFUSE additions stay in the table 4 readFileSync
+test/thin-client-routing-audit.test.ts thin-client routing audit — v0.32 ROUTE additions wire callRemoteTool 4 readFileSync
+test/timing-safe.test.ts extraction contract 1 readFileSync
+test/tool-catalog.test.ts freshness guard 2 readFileSync
+test/transcription-injection.test.ts transcription — command injection (#245) 2 readFileSync
+test/upgrade.serial.test.ts detectInstallMethod heuristic (source analysis) 13 readFileSync
+test/v0_37_fix_wave.serial.test.ts v0.37 Lane A — defaults sweep 8 readFileSync
+test/v0_37_fix_wave.serial.test.ts v0.37 Lane B — init paths 3 readFileSync
+test/v0_37_fix_wave.serial.test.ts v0.37 Lane C.3 — ZE key reaches buildGatewayConfig 3 readFileSync
+test/v0_37_fix_wave.serial.test.ts v0.37 Lane D.2 — embed pre-flight dim mismatch 1 readFileSync
+test/v0_37_fix_wave.serial.test.ts v0.37 Lane D.4 — sync --help dispatch 1 readFileSync
+test/v0_37_fix_wave.serial.test.ts v0.37 deferred TODO shipped — gbrain reinit-pglite 3 readFileSync
+test/v0_37_gap_fill.serial.test.ts Lane A.7 — chunk-row INSERT default tracks the gateway-resolved model 1 readFileSync
+test/v0_37_gap_fill.serial.test.ts Lane B — init precedence chain (CLI > env > existing file > default) 1 readFileSync
+test/v0_37_gap_fill.serial.test.ts Lane C.3 — env ZEROENTROPY_API_KEY merges into loadConfig 2 readFileSync
+test/v0_37_gap_fill.serial.test.ts Lane D.2 — embed pre-flight catches dim mismatch before worker pool 2 readFileSync
+test/v0_37_gap_fill.serial.test.ts Lane D.3 — sync surfaces dim-mismatch recipe at incremental AND first-sync catches 2 readFileSync
+test/v0_37_gap_fill.serial.test.ts Lane E.4 — loadRecommendationContext is provider-aware 1 readFileSync
+test/v0_37_gap_fill.serial.test.ts reinit-pglite — backup + reinit 7 readFileSync
+test/voyage-response-cap.test.ts v0.31.8 — voyage Content-Length pre-check + per-item cap 6 bun-file
+test/worker-supervised-db-probe.test.ts issue #1801 fix #2 — supervised DB self-defense 5 readFileSync
diff --git a/scripts/test-shard.sh b/scripts/test-shard.sh
index 5e3cbde757..fb06d0d433 100755
--- a/scripts/test-shard.sh
+++ b/scripts/test-shard.sh
@@ -122,7 +122,37 @@ fi
# Convert newline-separated file list to argv. xargs handles the
# whitespace correctly without word-splitting on spaces in paths.
+#
+# COVERAGE_DIR (opt-in): when set, run under bun's lcov coverage into
+# $COVERAGE_DIR/shard and write a lane manifest on success. xargs -x makes
+# an argv overflow FAIL LOUD instead of silently batching into a second bun
+# process — a second process reusing the same coverage dir OVERWRITES
+# lcov.info, silently losing the first batch's line data. BSD xargs only
+# accepts -x together with -n (GNU accepts both spellings), so we pass
+# -n 100000: far beyond any real shard's file count, it keeps everything in
+# ONE invocation while -x turns "args do not fit" into a hard error.
+# merge-lcov.ts's lcovCount!=1 manifest tripwire is the second line of
+# defense. When COVERAGE_DIR is empty/unset both arrays stay empty and the
+# exec line is byte-identical to the pre-coverage behavior.
+COVERAGE_ARGS=()
+XARGS_FLAGS=()
+if [ -n "${COVERAGE_DIR:-}" ]; then
+ COVERAGE_ARGS=(--coverage --coverage-reporter=lcov --coverage-dir="$COVERAGE_DIR/shard")
+ XARGS_FLAGS=(-n 100000 -x)
+fi
# --max-concurrency mirrors the local runner: unbounded intra-process
# concurrency under parallel PGLite boots produced real shard deaths (the
# 22-minute matrix timeout in test.yml records 13 of them).
-printf '%s\n' "$SHARD_FILES" | xargs bun test --timeout=60000 --max-concurrency="${GBRAIN_TEST_MAX_CONCURRENCY:-4}"
+rc=0
+printf '%s\n' "$SHARD_FILES" | xargs ${XARGS_FLAGS[@]+"${XARGS_FLAGS[@]}"} bun test --timeout=60000 --max-concurrency="${GBRAIN_TEST_MAX_CONCURRENCY:-4}" ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} || rc=$?
+
+# Lane manifest: written ONLY on a fully green run (complete:true means the
+# lcov data represents the whole shard). The real exit code is preserved
+# either way. lcovCount != 1 downstream (merge-lcov.ts) means the xargs -x
+# tripwire logic above was defeated somehow — merge marks the run degraded.
+if [ -n "${COVERAGE_DIR:-}" ] && [ "$rc" -eq 0 ]; then
+ LCOV_COUNT=$(find "$COVERAGE_DIR" -name 'lcov.info' 2>/dev/null | grep -c '^' || true)
+ printf '{"lane":"shard-%s","sha":"%s","lcovCount":%s,"complete":true}\n' \
+ "$SHARD_INDEX" "$(git rev-parse HEAD)" "${LCOV_COUNT:-0}" > "$COVERAGE_DIR/lane-manifest.json"
+fi
+exit "$rc"
diff --git a/scripts/update-coverage-baseline.ts b/scripts/update-coverage-baseline.ts
new file mode 100644
index 0000000000..0fe7b5d5f2
--- /dev/null
+++ b/scripts/update-coverage-baseline.ts
@@ -0,0 +1,121 @@
+#!/usr/bin/env bun
+/**
+ * scripts/update-coverage-baseline.ts — rewrite one corpus section of
+ * scripts/coverage-baseline.json from a real merged-summary run
+ * (containment sprint).
+ *
+ * Usage:
+ * bun scripts/update-coverage-baseline.ts --summary <json> \
+ * --corpus <prCorpus|fullCorpus> [--promote]
+ *
+ * Behavior:
+ * - Reads the working-tree scripts/coverage-baseline.json (this is the
+ * WRITE side; the gate reads origin/master's copy, so an update only
+ * takes effect when it lands on master).
+ * - Replaces baseline[<corpus>] with {global, dirs, files, neverLoadedCount}
+ * derived from the summary; `files` is limited to the watchlist paths
+ * listed in the baseline file itself (the 8 containment-sprint watchlist
+ * modules), never the full file map. `neverLoadedCount` records the
+ * summary's neverLoaded.count so the baseline gate can catch the
+ * shrinking-denominator regression (deleting tests that load a module
+ * removes its files from the pct denominator and RAISES total %).
+ * - --promote clears "provisional" (sets it to false), turning both
+ * gates from report-only into real gates once COVERAGE_GATE_ENFORCE=1.
+ *
+ * Exit codes: 0 success; 2 usage/IO error.
+ */
+
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+export interface CovTriple {
+ lines: number;
+ covered: number;
+ pct: number;
+}
+
+export interface SummaryForBaseline {
+ total: CovTriple;
+ dirs: Record<string, CovTriple>;
+ files: Record<string, CovTriple>;
+ neverLoaded?: { count?: number };
+}
+
+export interface BaselineCorpusSection {
+ global: CovTriple;
+ dirs: Record<string, CovTriple>;
+ files: Record<string, CovTriple>;
+ /** neverLoaded.count from the seeding run; null when the summary lacks it. */
+ neverLoadedCount: number | null;
+}
+
+/**
+ * Pure section builder: global + dirs from the summary, files limited to
+ * the watchlist entries that actually appear in the summary.
+ * neverLoadedCount carries merge-lcov's neverLoaded.count into the baseline
+ * so a later run that INCREASES it (tests deleted → files drop out of the
+ * denominator → pct rises for free) is gateable as a regression.
+ */
+export function buildCorpusSection(summary: SummaryForBaseline, watchlist: string[]): BaselineCorpusSection {
+ const files: Record<string, CovTriple> = {};
+ for (const path of watchlist) {
+ const entry = summary.files[path];
+ if (entry) files[path] = entry;
+ }
+ const neverLoadedCount = typeof summary.neverLoaded?.count === "number" ? summary.neverLoaded.count : null;
+ return { global: summary.total, dirs: summary.dirs, files, neverLoadedCount };
+}
+
+function fail(msg: string): never {
+ process.stderr.write(`update-coverage-baseline: ${msg}\n`);
+ process.exit(2);
+}
+
+function main(): void {
+ const argv = process.argv.slice(2);
+ let summaryPath = "";
+ let corpus = "";
+ let promote = false;
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i]!;
+ if (a === "--summary") summaryPath = argv[++i] ?? "";
+ else if (a === "--corpus") corpus = argv[++i] ?? "";
+ else if (a === "--promote") promote = true;
+ else fail(`unknown argument: ${a}`);
+ }
+ if (!summaryPath) fail("--summary <json> is required");
+ if (corpus !== "prCorpus" && corpus !== "fullCorpus") fail("--corpus must be prCorpus or fullCorpus");
+ if (!existsSync(summaryPath)) fail(`summary JSON not found: ${summaryPath}`);
+
+ let summary: SummaryForBaseline;
+ try {
+ summary = JSON.parse(readFileSync(summaryPath, "utf8")) as SummaryForBaseline;
+ } catch (err) {
+ fail(`summary JSON unparseable: ${String(err)}`);
+ }
+ if (!summary.total || !summary.dirs || !summary.files) fail("summary JSON missing total/dirs/files sections");
+
+ const baselinePath = process.env.COVERAGE_BASELINE_WORKTREE_PATH || join(import.meta.dir, "coverage-baseline.json");
+ if (!existsSync(baselinePath)) fail(`baseline file not found: ${baselinePath}`);
+ let baseline: Record<string, unknown>;
+ try {
+ baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as Record<string, unknown>;
+ } catch (err) {
+ fail(`baseline JSON unparseable: ${String(err)}`);
+ }
+
+ const watchlist = Array.isArray(baseline.watchlist) ? (baseline.watchlist as string[]) : [];
+ const section = buildCorpusSection(summary, watchlist);
+ baseline[corpus] = section;
+ if (promote) baseline.provisional = false;
+
+ writeFileSync(baselinePath, JSON.stringify(baseline, null, 2) + "\n", "utf8");
+ process.stderr.write(
+ `update-coverage-baseline: wrote ${corpus} section (global ${summary.total.pct}%, ` +
+ `${Object.keys(summary.dirs).length} dirs, ${Object.keys(section.files).length} watchlist files, ` +
+ `neverLoaded ${section.neverLoadedCount ?? "n/a"})` +
+ `${promote ? ", provisional cleared" : ""}\n`,
+ );
+}
+
+if (import.meta.main) main();
diff --git a/skills/conventions/calibration.md b/skills/conventions/calibration.md
index 6f3e9e39b4..606bd74a50 100644
--- a/skills/conventions/calibration.md
+++ b/skills/conventions/calibration.md
@@ -17,7 +17,7 @@ which one applies to their current task.
## When to surface a calibration warning
-The four doctor checks (in `src/commands/doctor.ts`):
+The four doctor checks (in `src/commands/doctor/checks/calibration.ts`):
- `abandoned_threads` — informational. Count of high-conviction takes
(weight >= 0.7) older than 12 months that haven't been superseded or
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 3b050b67ba..456ca660bc 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -44,7 +44,7 @@
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
"conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1",
"conventions/brain-routing.md": "a8035f7dbadff0ea68b8babb8314b3d044cafbed8242dce5b931fa08b028fc45",
- "conventions/calibration.md": "eda7ca76f80c8a17ae546110484389f805c5b21fc0a57f951bbe8b6abba26e03",
+ "conventions/calibration.md": "dc357891a86987fbc39e06a21a190119b9900e03a2460af64b278307af1b4289",
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
"conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",
"conventions/exec-output.md": "2bf371ac3ec4987eff7cc13cd3ea8cc97c46bd43f588eec024ff27f3171bc58f",
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 503db6e381..9472da5101 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -1,84 +1,206 @@
import type { BrainEngine } from '../core/engine.ts';
-import { REPAIR_SOURCE_CONFIG_SQL } from '../core/source-config-sql.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import * as db from '../core/db.ts';
import { LATEST_VERSION, getIdleBlockers } from '../core/migrate.ts';
import { checkResolvable } from '../core/check-resolvable.ts';
-import { autoFixDryViolations, type AutoFixReport, type FixOutcome } from '../core/dry-fix.ts';
+import { autoFixDryViolations, type AutoFixReport } from '../core/dry-fix.ts';
import { autoDetectSkillsDirReadOnly } from '../core/repo-root.ts';
-import {
- SKILLS_MANIFEST_FILENAME,
- verifySkillsManifest,
- type SkillsManifest,
-} from '../core/skills-integrity.ts';
-import { loadOrDeriveManifest } from '../core/skill-manifest.ts';
-import { computeSkillCurrency } from '../core/skillpack/skill-currency.ts';
-import { findGbrainRoot } from '../core/skillpack/bundle.ts';
-import { checkPreconditions, type PreconditionContext } from '../core/skillpack/preconditions.ts';
-import { parseSkillFrontmatter } from '../core/skill-frontmatter.ts';
-import {
- analyzeSkillBrainFirst,
- buildBrainFirstSummaryLine,
- type BrainFirstAnalysis,
-} from '../core/skill-brain-first.ts';
-import {
- loadSnapshot,
- writeSnapshotAtomically,
- diffAgainstSnapshot,
- appendAuditEventsForTransitions,
-} from '../core/audit-skill-brain-first.ts';
import { loadCompletedMigrations } from '../core/preferences.ts';
import { compareVersions } from './migrations/index.ts';
-import { createProgress, startHeartbeat, type ProgressReporter } from '../core/progress.ts';
+import { createProgress, startHeartbeat } from '../core/progress.ts';
import { categorizeCheck, type CheckCategory } from '../core/doctor-categories.ts';
import { rankIssues, type RankedIssue } from '../core/doctor-cause-rank.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import type { DbUrlSource } from '../core/config.ts';
import { gbrainPath, loadConfig } from '../core/config.ts';
-import { reflexEnabled } from '../core/context/reflex.ts';
-import { resolveSocketPath } from '../core/context/resolve-ipc.ts';
-import { resolveOwnerHolder } from '../core/owner-holder.ts';
-import { homedir } from 'os';
-import { dirname, isAbsolute, join, resolve as resolvePath } from 'path';
-import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
-import {
- extractEntityRefs,
- isGlobalBasenameEnabled,
- buildBasenameIndex,
- queryBasenameIndex,
-} from '../core/link-extraction.ts';
-import { probeSourceGitState } from '../core/git-head.ts';
-// v0.41.32.0: remote staleness reads the stored newest_content_at column via
-// this pure comparator (no git subprocess on the HTTP MCP doctor path).
-import { lagFromContentMs, resolveStalenessCeilingSeconds } from '../core/source-health.ts';
-import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../core/env-number.ts';
-import { CHUNKER_VERSION } from '../core/chunkers/code.ts';
-import { LINK_EXTRACTOR_VERSION_TS } from '../core/link-extraction.ts';
-import { isUndefinedColumnError } from '../core/utils.ts';
-import {
- loadStorageConfig,
- effectiveDbOnlyDirs,
- DERIVE_PHASE_DB_ONLY_DEFAULTS,
- findDbOnlyCollisions,
-} from '../core/storage-config.ts';
-import { slugifyPath } from '../core/sync.ts';
-// issue #1777: hidden_by_search_policy — count chunked pages withheld from
-// default search by the hard-exclude prefix policy. Reuses the canonical
-// exclude resolver + LIKE escaper + visibility clause so the doctor count can't
-// drift from what search actually filters.
-import { resolveHardExcludes, DEFAULT_HARD_EXCLUDES } from '../core/search/source-boost.ts';
-import { escapeLikePattern, buildVisibilityClause } from '../core/search/sql-ranking.ts';
-import { unverifiedExtractionFragment } from '../core/extraction-review.ts';
+import { resolveEnvNumber, resolveHoursEnv } from '../core/env-number.ts';
import { hnswIndexExpected, hnswMaxDimsForType } from '../core/vector-index.ts';
-// Agent-bootstrap doctor group (plan B2/B4/ENG-4 + one-live-serve note).
-import { readHarnessReceiptState, readReceipt } from '../core/bootstrap/format.ts';
-import { probeLivePgliteHolder, resolveBrainDataDir } from '../core/bootstrap/uninstall.ts';
-import { readRunbookStamp, hooksInstalled, listVerifyRuns } from '../core/bootstrap/status.ts';
-import { resolveGbrainHome } from '../core/gbrain-home.ts';
import { VERSION as GBRAIN_BINARY_VERSION } from '../version.ts';
-import { execFileSync } from 'child_process';
-
+// Peeled doctor modules (containment sprint): each is a verbatim move out of
+// this file. doctor.ts re-exports every moved public symbol under its
+// original name so existing importers (tests, scripts/live-brain-first-check.ts,
+// the run_doctor op's dynamic import of doctorReportRemote) keep working
+// unchanged.
+import { multiSourceDriftAdvice } from './doctor/schema-pack-checks.ts';
+import { bootstrapDoctorChecks } from './doctor/bootstrap-checks.ts';
+import {
+ skillConformanceCheck,
+ skillsManifestIntegrityCheck,
+ skillCurrencyCheck,
+ skillPreconditionsCheck,
+ skillBrainFirstCheck,
+} from './doctor/skill-checks.ts';
+export {
+ multiSourceDriftAdvice,
+ bootstrapDoctorChecks,
+ skillConformanceCheck,
+ skillsManifestIntegrityCheck,
+ skillCurrencyCheck,
+ skillPreconditionsCheck,
+ skillBrainFirstCheck,
+};
+export { doctorReportRemote } from './doctor/report-remote.ts';
+
+// Peeled check bundles (containment sprint): verbatim moves of the standalone
+// check-function library into src/commands/doctor/checks/*. Every exported
+// symbol keeps its original name and import path via these re-exports
+// (dozens of tests + scripts import checks directly from doctor.ts, and
+// report-remote.ts consumes them through this façade).
+export {
+ resolveWhoknowsFixturePath,
+ whoknowsHealthCheck,
+ pgvectorCheck,
+ jsonbIntegrityCheck,
+ checkVolunteerChannels,
+ takesWeightGridCheck,
+ childTableOrphansCheck,
+ rawProvenanceCheck,
+ checkSourceConfigShape,
+ checkPgliteScratchProbe,
+} from './doctor/checks/core-health.ts';
+export {
+ checkContextualRetrievalCoverage,
+ checkHiddenBySearchPolicy,
+ checkLinkResolutionOpportunity,
+ checkAbandonedThreads,
+ checkCalibrationFreshness,
+ checkGradeConfidenceDrift,
+ checkSubagentHealth,
+ checkVoiceGateHealth,
+ checkRerankerHealth,
+} from './doctor/checks/calibration.ts';
+export {
+ computeQueueHealthCheck,
+ computeWedgedQueueCheck,
+ computeAutopilotFanoutConcurrencyCheck,
+ checkBatchRetryHealth,
+} from './doctor/checks/queue-jobs.ts';
+export {
+ checkGraphSignalsCoverage,
+ checkBrainstormHealth,
+ checkZeEmbeddingHealth,
+ checkProviderSunset,
+ checkEmbeddingWidthConsistency,
+ checkFactsEmbeddingWidthConsistency,
+} from './doctor/checks/graph-embedding.ts';
+export {
+ checkSourceRoutingHealth,
+ checkFederationHealth,
+ checkOauthConfidentialHealth,
+ checkAutopilotLockScope,
+ checkStaleLocks,
+ checkCyclePhaseScope,
+} from './doctor/checks/routing-federation.ts';
+export {
+ checkSearchMode,
+ checkEvalDrift,
+ checkEmbeddingEnvOverride,
+ checkSubagentCapability,
+ computeConversationParserProbeHealthCheck,
+ computeNightlyQualityProbeHealthCheck,
+ computeConversationFactsBacklogCheck,
+} from './doctor/checks/search-eval.ts';
+export {
+ EXTRACTION_LAG_WARN_PCT_DEFAULT,
+ EXTRACTION_LAG_MIN_PAGES,
+ checkLinksExtractionLag,
+ checkUnverifiedExtractions,
+ checkContentHashDuplicates,
+ checkUndeclaredDbOnlyPages,
+ checkDbOnlyCollectorCollision,
+ computeExtractAtomsBacklogCheck,
+ computeExtractHealthCheck,
+ checkSyncFreshness,
+} from './doctor/checks/extraction-sync.ts';
+export {
+ checkSyncConsolidation,
+ computePoolBudgetCheck,
+ checkPoolBudget,
+ checkCycleFreshness,
+} from './doctor/checks/consolidation-cycle.ts';
+export {
+ computePgliteDataDirCheck,
+ computeWorkerOomLoopCheck,
+ computePoolReapHealthCheck,
+} from './doctor/checks/pglite-worker.ts';
+export {
+ buildMemoryVerbsCheck,
+ buildRetrievalReflexCheck,
+} from './doctor/checks/verbs-reflex.ts';
+// Import-back seam: buildChecks/runDoctor below call these moved checks.
+// (`export ... from` above creates no local binding, so the plain imports
+// here are required and non-conflicting.)
+import {
+ whoknowsHealthCheck,
+ pgvectorCheck,
+ jsonbIntegrityCheck,
+ checkVolunteerChannels,
+ takesWeightGridCheck,
+ childTableOrphansCheck,
+ rawProvenanceCheck,
+ checkSourceConfigShape,
+ checkPgliteScratchProbe,
+} from './doctor/checks/core-health.ts';
+import {
+ checkHiddenBySearchPolicy,
+ checkLinkResolutionOpportunity,
+ checkRerankerHealth,
+} from './doctor/checks/calibration.ts';
+import {
+ computeQueueHealthCheck,
+ computeWedgedQueueCheck,
+ computeAutopilotFanoutConcurrencyCheck,
+ checkBatchRetryHealth,
+} from './doctor/checks/queue-jobs.ts';
+import {
+ checkGraphSignalsCoverage,
+ checkBrainstormHealth,
+ checkZeEmbeddingHealth,
+ checkProviderSunset,
+ checkEmbeddingWidthConsistency,
+ checkFactsEmbeddingWidthConsistency,
+} from './doctor/checks/graph-embedding.ts';
+import {
+ checkSourceRoutingHealth,
+ checkOauthConfidentialHealth,
+ checkAutopilotLockScope,
+ checkStaleLocks,
+ checkCyclePhaseScope,
+} from './doctor/checks/routing-federation.ts';
+import {
+ checkSearchMode,
+ checkEvalDrift,
+ checkEmbeddingEnvOverride,
+ checkSubagentCapability,
+ computeConversationParserProbeHealthCheck,
+ computeNightlyQualityProbeHealthCheck,
+ computeConversationFactsBacklogCheck,
+} from './doctor/checks/search-eval.ts';
+import {
+ checkLinksExtractionLag,
+ checkUnverifiedExtractions,
+ checkContentHashDuplicates,
+ checkUndeclaredDbOnlyPages,
+ checkDbOnlyCollectorCollision,
+ computeExtractAtomsBacklogCheck,
+ computeExtractHealthCheck,
+ checkSyncFreshness,
+} from './doctor/checks/extraction-sync.ts';
+import {
+ checkSyncConsolidation,
+ checkCycleFreshness,
+} from './doctor/checks/consolidation-cycle.ts';
+import {
+ computePgliteDataDirCheck,
+ computeWorkerOomLoopCheck,
+ computePoolReapHealthCheck,
+} from './doctor/checks/pglite-worker.ts';
+import {
+ buildMemoryVerbsCheck,
+ buildRetrievalReflexCheck,
+} from './doctor/checks/verbs-reflex.ts';
export interface Check {
name: string;
status: 'ok' | 'warn' | 'fail';
@@ -237,5314 +359,115 @@ export function computeDoctorReport(checks: Check[]): DoctorReport {
* pending demand. Local doctor is unchanged — operators on the host machine
* still get the full check set.
*/
-/**
- * Doctor check: takes.weight grid integrity (v0.32 — EXP-2).
- *
- * Pure helper — no `process.exit`, no side effects beyond the SQL probe.
- * `runDoctor` calls this and pushes the result onto its check list.
- * Tests can target this directly with a stubbed engine (codex review #7).
- *
- * Branches:
- * - takes table doesn't exist (fresh brain pre-v37) → warn, "skipped"
- * - 0 takes total → ok, "no takes yet" (avoids divide-by-zero)
- * - off_grid / total > 10% → fail
- * - off_grid / total > 1% → warn
- * - else → ok
- *
- * Tolerance matches migration v48: any value with abs(weight - on_grid) > 1e-3
- * is genuinely off-grid (the 0.05 grid is 5e-2; float32 noise is ~1e-7).
- */
-const WHOKNOWS_FIXTURE_RELATIVE_PATH = 'test/fixtures/whoknows-eval.jsonl';
-
-function isGbrainSourceRoot(dir: string): boolean {
- return (
- existsSync(join(dir, 'src', 'cli.ts')) &&
- existsSync(join(dir, 'skills', 'RESOLVER.md'))
- );
-}
-
-export function resolveWhoknowsFixturePath(
- env: NodeJS.ProcessEnv = process.env,
- moduleUrl: string = import.meta.url,
-): string | null {
- if (env.GBRAIN_WHOKNOWS_FIXTURE_PATH) {
- return isAbsolute(env.GBRAIN_WHOKNOWS_FIXTURE_PATH)
- ? env.GBRAIN_WHOKNOWS_FIXTURE_PATH
- : resolvePath(process.cwd(), env.GBRAIN_WHOKNOWS_FIXTURE_PATH);
- }
-
- try {
- let dir = dirname(fileURLToPath(moduleUrl));
- for (let i = 0; i < 10; i++) {
- if (isGbrainSourceRoot(dir)) return join(dir, WHOKNOWS_FIXTURE_RELATIVE_PATH);
- const parent = dirname(dir);
- if (parent === dir) break;
- dir = parent;
- }
- } catch {
- // Some bundlers/runtimes may not expose a normal file: import URL.
- // Doctor should surface an override hint instead of fabricating a path.
- }
-
- return null;
-}
-
-/**
- * v0.33: whoknows_health — verify the eval fixture is present at the
- * documented path. Lightweight; just checks file existence and row count,
- * not the eval gate outcome (that runs via `gbrain eval whoknows`).
- *
- * Surface is intentionally narrow: a missing fixture means the eval
- * cannot run at all, which is the highest-leverage signal. Hit-rate
- * regression detection lives in `gbrain eval whoknows --json` and is
- * the job of the eval command, not the doctor sweep.
- */
-export async function whoknowsHealthCheck(_engine: BrainEngine): Promise<Check> {
- try {
- const fixturePath = resolveWhoknowsFixturePath();
- if (!fixturePath) {
- return {
- name: 'whoknows_health',
- status: 'warn',
- message: 'whoknows eval fixture path could not be resolved. Set GBRAIN_WHOKNOWS_FIXTURE_PATH to the absolute path for test/fixtures/whoknows-eval.jsonl.',
- };
- }
- if (!existsSync(fixturePath)) {
- return {
- name: 'whoknows_health',
- status: 'warn',
- message: `whoknows eval fixture missing at ${fixturePath}. Fix: hand-label 10 queries you'd actually run, format {query, expected_top_3_slugs, notes}.`,
- };
- }
- const stat = statSync(fixturePath);
- if (stat.size === 0) {
- return {
- name: 'whoknows_health',
- status: 'warn',
- message: 'whoknows eval fixture exists but is empty. The eval cannot pass without queries.',
- };
- }
- const raw = readFileSync(fixturePath, 'utf-8');
- const rows = raw
- .split('\n')
- .filter((l) => {
- const t = l.trim();
- return t && !t.startsWith('#') && !t.startsWith('//');
- });
- if (rows.length < 5) {
- return {
- name: 'whoknows_health',
- status: 'warn',
- message: `whoknows eval fixture has only ${rows.length} row(s); ENG-D2 recommends 10. Fix: add more hand-labeled queries.`,
- };
- }
- return {
- name: 'whoknows_health',
- status: 'ok',
- message: `whoknows eval fixture present (${rows.length} queries). Run \`gbrain eval whoknows test/fixtures/whoknows-eval.jsonl\` to grade.`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'whoknows_health',
- status: 'warn',
- message: `Could not check whoknows fixture: ${msg}`,
- };
- }
-}
-
-/**
- * Doctor check: pgvector availability.
- *
- * Use the active engine instead of the module-level Postgres singleton.
- * PGLite exposes pg_extension through its engine connection, but does not
- * connect db.ts's Postgres singleton; using db.getConnection() here turns a
- * healthy PGLite brain into a false warning.
- */
-export async function pgvectorCheck(engine: BrainEngine): Promise<Check> {
- try {
- const ext = await engine.executeRaw<{ extname: string }>(
- `SELECT extname FROM pg_extension WHERE extname = 'vector'`,
- );
- if (ext.length > 0) {
- return { name: 'pgvector', status: 'ok', message: 'Extension installed' };
- }
- return { name: 'pgvector', status: 'fail', message: 'Extension not found. Run: CREATE EXTENSION vector;' };
- } catch {
- return { name: 'pgvector', status: 'warn', message: 'Could not check pgvector extension' };
- }
-}
-
-/**
- * Doctor check: JSONB columns are not double-encoded as strings.
- *
- * This check is valid on both Postgres and PGLite. Route through
- * engine.executeRaw() so embedded PGLite brains are checked through their
- * actual connection instead of the unrelated Postgres singleton.
- */
-export async function jsonbIntegrityCheck(
- engine: BrainEngine,
- progress?: Pick<ProgressReporter, 'heartbeat'>,
-): Promise<Check> {
- try {
- const targets: Array<{ table: string; col: string; expected: 'object' | 'array'; jsonPayloadOnly?: boolean }> = [
- { table: 'pages', col: 'frontmatter', expected: 'object' },
- { table: 'raw_data', col: 'data', expected: 'object' },
- { table: 'ingest_log', col: 'pages_updated', expected: 'array' },
- { table: 'files', col: 'metadata', expected: 'object' },
- { table: 'page_versions', col: 'frontmatter', expected: 'object' },
- // Subagent persistence — second double-encode site (historical damage
- // rows from the pre-v0.42.53.0 positional bind; write paths fixed in
- // #2375). Mirrors repair-jsonb's targets incl. jsonPayloadOnly: these
- // columns can legitimately hold jsonb STRING scalars (persistToolExec
- // binds pre-serialized string payloads as-is), so only JSON-container
- // content counts as damage.
- { table: 'subagent_messages', col: 'content_blocks', expected: 'array', jsonPayloadOnly: true },
- { table: 'subagent_tool_executions', col: 'input', expected: 'object', jsonPayloadOnly: true },
- { table: 'subagent_tool_executions', col: 'output', expected: 'object', jsonPayloadOnly: true },
- ];
- let totalBad = 0;
- const breakdown: string[] = [];
- for (const { table, col, jsonPayloadOnly } of targets) {
- progress?.heartbeat(`jsonb_integrity.${table}.${col}`);
- // Skip targets whose table doesn't exist on this brain (subagent_*
- // tables are v0.15+; pre-v0.15 brains naturally lack them).
- const existsRows = await engine.executeRaw<{ exists: boolean }>(
- `SELECT to_regclass($1) IS NOT NULL AS exists`,
- [table],
- );
- if (!existsRows[0]?.exists) continue;
- const damage = jsonPayloadOnly
- ? `jsonb_typeof(${col}) = 'string' AND (${col} #>> '{}') ~ '^[[:space:]]*[\\[{]' AND pg_input_is_valid(${col} #>> '{}', 'jsonb')`
- : `jsonb_typeof(${col}) = 'string'`;
- const rows = await engine.executeRaw<{ n: number }>(
- `SELECT count(*)::int AS n FROM ${table} WHERE ${damage}`,
- );
- const n = Number(rows[0]?.n ?? 0);
- if (n > 0) { totalBad += n; breakdown.push(`${table}.${col}=${n}`); }
- }
- if (totalBad === 0) {
- return { name: 'jsonb_integrity', status: 'ok', message: 'All JSONB columns store objects/arrays' };
- }
- return {
- name: 'jsonb_integrity',
- status: 'warn',
- message: `${totalBad} row(s) double-encoded (${breakdown.join(', ')}). Fix: gbrain repair-jsonb`,
- };
- } catch {
- return { name: 'jsonb_integrity', status: 'warn', message: 'Could not check JSONB integrity' };
- }
-}
-
-/**
- * Per-channel push-context visibility (harness hook adapters). Groups
- * context_volunteer_events by channel over the last 7 days so the operator
- * can see which adapters (ambient reflex / op / watch / claude-code / codex)
- * are actually firing. Engine-aware SIBLING of buildRetrievalReflexCheck
- * (which is engine-free and heartbeat-file based) — deliberately a separate
- * check so the existing builder keeps its signature.
- *
- * Info-only (never warn/fail on quiet channels — most installs use a subset).
- * The message distinguishes the two "installed but nothing happens" classes:
- * a hook script that never registered (restart the harness session) vs a
- * registered adapter whose channel went quiet. Pre-v117 brains (no events
- * table) return ok with a note instead of throwing. A serve started before
- * this build logs hook traffic as 'reflex' — restart serve after upgrade.
- */
-export async function checkVolunteerChannels(
- engine: BrainEngine,
- opts: { sourceIds?: string[] } = {},
-): Promise<Check> {
- const name = 'volunteer_channels';
- try {
- // Source scoping (cross-model P1): remote source-bound callers pass their
- // authorized ids — an unqualified aggregate would leak other sources'
- // activity counts/timestamps. Local trusted doctor passes none (brain-wide).
- // Unscoped shape: no source_id predicate → the composite
- // (source_id, volunteered_at DESC) index can't range-scan and this
- // seq-scans the table. Accepted DELIBERATELY for the local info check
- // (table is TTL-pruned at 90 days) — do NOT reuse on a hot path.
- const scoped = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;
- const rows = await engine.executeRaw<{ channel: string; n: string | number; last_fired: string | Date | null }>(
- scoped
- ? `SELECT channel, count(*)::int AS n, max(volunteered_at) AS last_fired
- FROM context_volunteer_events
- WHERE source_id = ANY($1::text[])
- AND volunteered_at > now() - interval '7 days'
- GROUP BY channel
- ORDER BY channel`
- : `SELECT channel, count(*)::int AS n, max(volunteered_at) AS last_fired
- FROM context_volunteer_events
- WHERE volunteered_at > now() - interval '7 days'
- GROUP BY channel
- ORDER BY channel`,
- scoped ? [opts.sourceIds] : [],
- );
- const channels: Record<string, { count: number; last_fired: string | null }> = {};
- for (const r of rows) {
- channels[r.channel] = {
- count: Number(r.n),
- last_fired: r.last_fired ? new Date(r.last_fired).toISOString() : null,
- };
- }
- const active = Object.keys(channels);
-
- // RT reconciliation: server-side delivery counts fire at the response
- // write — a hook client that timed out / hit its deadline / trimmed to
- // nothing still gets counted. The hook's own heartbeat records those
- // degradations, so surface the degraded rate next to the counts: a
- // "healthy" channel with a mostly-degraded heartbeat is delivery failure.
- let heartbeatNote = '';
- let heartbeat: { user_prompt_ok: number; user_prompt_degraded: number } | undefined;
- try {
- const { readHeartbeatTail } = await import('./hook.ts');
- const tail = await readHeartbeatTail(200);
- // Same 7-day window as the event counts (a month-old degraded streak
- // must not indict a healthy current week), and a minimum sample floor
- // so one bad entry can't trigger the caution.
- const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
- const up = tail.filter(
- (e) => e.event === 'user-prompt' && Date.parse(e.ts ?? '') >= cutoff,
- );
- if (up.length >= 5) {
- const degraded = up.filter((e) => e.outcome !== 'ok').length;
- heartbeat = { user_prompt_ok: up.length - degraded, user_prompt_degraded: degraded };
- if (degraded > up.length / 2) {
- heartbeatNote = ` — CAUTION: the hook heartbeat shows ${degraded}/${up.length} user-prompt events degraded this week, so server-side counts may overstate what was actually injected`;
- }
- }
- } catch { /* heartbeat surface is best-effort */ }
-
- // Engine-aware quiet-channel guidance: the harness-hook lane rides the
- // PGLite serve socket — on a Postgres brain, "check your registration and
- // restart" can never make the channel fire (pull-mode covers Postgres).
- const cfg = (() => { try { return loadConfig(); } catch { return null; } })();
- const quietGuidance =
- cfg?.engine === 'pglite'
- ? 'if a hook adapter is installed, confirm its registration landed and the harness session was RESTARTED (hooks snapshot at session start); a serve older than this build logs NOTHING for the hook lane — restart serve on the new build to activate the feedback loop'
- : 'note: the harness-hook channels require a PGLite serve socket — on this engine the hook lane stays quiet by design (pull-mode retrieval covers it)';
- const message = active.length
- ? `push-context channels active (7d): ${active.map((c) => `${c}=${channels[c].count}`).join(', ')}${heartbeatNote}`
- : `no push-context activity in 7 days — ${quietGuidance}`;
- return {
- name,
- status: 'ok',
- message,
- details: { window_days: 7, channels, ...(heartbeat ? { hook_heartbeat: heartbeat } : {}) },
- };
- } catch (e) {
- // Discriminate table-absent (pre-v117 brain) from transient failures —
- // a connection blip on a fully-migrated brain must not be misreported
- // as an old schema. Info-only either way; never block doctor.
- const msg = e instanceof Error ? e.message : String(e);
- const tableAbsent = /does not exist|undefined table|no such table|42P01/i.test(msg);
- return {
- name,
- status: 'ok',
- message: tableAbsent
- ? 'volunteer-events table not available (pre-v117 brain) — per-channel push visibility inactive'
- : `volunteer_channels query failed (info-only check; may or may not be transient): ${msg}`,
- details: { window_days: 7, channels: {} },
- };
- }
-}
-
-export async function takesWeightGridCheck(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ off_grid: string | number; total: string | number }>(
- `SELECT
- count(*) FILTER (WHERE weight IS NOT NULL
- AND abs(weight::numeric - ROUND(weight::numeric * 20) / 20) > 0.001)::int AS off_grid,
- count(*)::int AS total
- FROM takes`,
- );
- const total = Number(rows[0]?.total ?? 0);
- const offGrid = Number(rows[0]?.off_grid ?? 0);
- if (total === 0) {
- return { name: 'takes_weight_grid', status: 'ok', message: 'No takes yet' };
- }
- const ratio = offGrid / total;
- if (ratio > 0.10) {
- return {
- name: 'takes_weight_grid',
- status: 'fail',
- message: `${offGrid}/${total} takes off the 0.05 grid (${(ratio * 100).toFixed(1)}%). Fix: gbrain apply-migrations --yes`,
- };
- }
- if (ratio > 0.01) {
- return {
- name: 'takes_weight_grid',
- status: 'warn',
- message: `${offGrid}/${total} takes off the 0.05 grid (${(ratio * 100).toFixed(1)}%). Fix: gbrain apply-migrations --yes`,
- };
- }
- return {
- name: 'takes_weight_grid',
- status: 'ok',
- message: offGrid === 0
- ? `${total} take(s) on grid`
- : `${total} take(s) on grid (${offGrid} within tolerance)`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- // takes table missing on a fresh pre-v37 brain — warn, don't fail.
- return {
- name: 'takes_weight_grid',
- status: 'warn',
- message: `Could not check takes weight grid: ${msg}`,
- };
- }
-}
-
-/**
- * Child-table orphan detection (closes #1063).
- *
- * The autopilot `orphans` phase (src/core/cycle.ts:runPhaseOrphans) detects
- * orphan PAGES (pages with no inbound links via the page-graph). It does NOT
- * scan FK-child tables for orphan rows. When a bulk page delete leaves
- * orphans in `content_chunks` / `page_versions` / `tags` / `takes` / etc.
- * — whether from pre-FK migrations, race conditions, or a code path that
- * bypassed cascade — they persist indefinitely until manual SQL cleanup.
- *
- * All ten FK-to-pages tables declare `ON DELETE CASCADE` in the live schema
- * (verified via `pg_constraint` snapshot in the issue body), so finding any
- * orphan row is by definition unexpected. The check ships paste-ready
- * cleanup SQL when orphans surface.
- *
- * Excluded: `files.page_id` and `links.origin_page_id` — both declared as
- * `ON DELETE SET NULL`, so a NULL value is a valid state (file/link survives
- * after page deletion); only NOT-NULL-but-page-missing is an orphan there.
- * The check encodes that distinction for the two SET NULL columns.
- *
- * Pure helper for parity with `takesWeightGridCheck` so tests can target it
- * directly without driving the full `runDoctor` pipeline.
- */
-export async function childTableOrphansCheck(engine: BrainEngine): Promise<Check> {
- // (table, fk_column, allow_null). When allow_null=true, NULL is a valid
- // state (FK was declared ON DELETE SET NULL); the orphan predicate filters
- // out NULL values. When false, NULL is impossible by NOT NULL constraint;
- // any value not in pages.id is an orphan.
- const targets: Array<{ table: string; col: string; allowNull: boolean }> = [
- { table: 'content_chunks', col: 'page_id', allowNull: false },
- { table: 'page_versions', col: 'page_id', allowNull: false },
- { table: 'tags', col: 'page_id', allowNull: false },
- { table: 'takes', col: 'page_id', allowNull: false },
- { table: 'raw_data', col: 'page_id', allowNull: false },
- { table: 'timeline_entries', col: 'page_id', allowNull: false },
- { table: 'links', col: 'from_page_id', allowNull: false },
- { table: 'links', col: 'to_page_id', allowNull: false },
- { table: 'links', col: 'origin_page_id', allowNull: true },
- { table: 'files', col: 'page_id', allowNull: true },
- ];
- let totalOrphans = 0;
- const breakdown: string[] = [];
- const cleanupSql: string[] = [];
- const errors: string[] = [];
- for (const { table, col, allowNull } of targets) {
- try {
- // NOT IN subquery is portable across postgres + PGLite. The `pages.id`
- // subquery covers every existing parent row.
- const nullFilter = allowNull ? `${col} IS NOT NULL AND ` : '';
- const rows = await engine.executeRaw<{ n: string | number }>(
- `SELECT COUNT(*)::int AS n FROM ${table} WHERE ${nullFilter}${col} NOT IN (SELECT id FROM pages)`,
- );
- const n = Number(rows[0]?.n ?? 0);
- if (n > 0) {
- totalOrphans += n;
- breakdown.push(`${table}.${col}=${n}`);
- cleanupSql.push(
- `DELETE FROM ${table} WHERE ${nullFilter}${col} NOT IN (SELECT id FROM pages);`,
- );
- }
- } catch (e) {
- // Table or column may not exist on older schemas — skip and continue.
- // Aggregate the errors so doctor surfaces "could not check N tables"
- // when a real failure shape appears (network, lock, syntax).
- const msg = e instanceof Error ? e.message : String(e);
- errors.push(`${table}.${col}: ${msg.slice(0, 80)}`);
- }
- }
- if (totalOrphans === 0 && errors.length === 0) {
- return {
- name: 'child_table_orphans',
- status: 'ok',
- message: 'All FK-child tables clean (10 tables checked)',
- };
- }
- if (totalOrphans === 0 && errors.length > 0) {
- return {
- name: 'child_table_orphans',
- status: 'warn',
- message: `Could not check ${errors.length}/10 FK-child tables (older schema or transient error): ${errors.slice(0, 3).join('; ')}`,
- };
- }
- return {
- name: 'child_table_orphans',
- status: 'warn',
- message:
- `${totalOrphans} orphan row(s) in FK-child tables (${breakdown.join(', ')}). ` +
- `Cleanup: ${cleanupSql.join(' ')}`,
- };
-}
/**
- * Raw-source persistence guarantee (#1978, warn-only v1).
- *
- * Invariant: every synthesized/derived page (dream_generated:true frontmatter
- * or type:synthesis) must either carry a raw trace or declare an explicit
- * exemption. Accepted traces:
- * - frontmatter key `raw_trace` / `raw_source` / `source_uri`
- * - an attached `raw_data` row
- * - `synthesis_evidence` rows (think-op citations)
- * - explicit `raw_trace_exempt: true` (reason in `raw_trace_exempt_reason`)
- *
- * v1 is deliberately warn-only — no write path is blocked. Escalation to
- * fail-closed enforcement in the synthesis/import write paths is the v2
- * follow-up once real brains run clean.
- *
- * Pure helper (engine.executeRaw only) for parity with
- * childTableOrphansCheck so tests can target it directly.
+ * v0.42 self_upgrade_health. Surfaces the self-upgrade mode, whether an update
+ * is pending (from the cache), and any recent failed auto-upgrade attempts.
+ * File-plane only (no DB) so it runs on thin clients. Three-state: warn on
+ * recent failures, otherwise ok.
*/
-export async function rawProvenanceCheck(engine: BrainEngine): Promise<Check> {
- const where = `
- p.deleted_at IS NULL
- AND (COALESCE(p.frontmatter->>'dream_generated', '') = 'true' OR p.type = 'synthesis')
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ?| ARRAY['raw_trace', 'raw_source', 'source_uri', 'raw_trace_exempt'])
- AND NOT EXISTS (SELECT 1 FROM raw_data rd WHERE rd.page_id = p.id)
- AND NOT EXISTS (SELECT 1 FROM synthesis_evidence se WHERE se.synthesis_page_id = p.id)`;
+export function checkSelfUpgradeHealth(): Check {
try {
- const rows = await engine.executeRaw<{ n: string | number }>(
- `SELECT COUNT(*)::int AS n FROM pages p WHERE ${where}`,
- );
- const n = Number(rows[0]?.n ?? 0);
- if (n === 0) {
- return {
- name: 'raw_provenance',
- status: 'ok',
- message: 'All synthesized pages carry a raw trace or explicit exemption',
- };
- }
- const sample = await engine.executeRaw<{ slug: string }>(
- `SELECT p.slug FROM pages p WHERE ${where} ORDER BY p.slug LIMIT 5`,
- );
- const slugs = sample.map(r => r.slug).join(', ');
- return {
- name: 'raw_provenance',
- status: 'warn',
- message:
- `${n} synthesized page(s) lack a raw trace (no raw_trace/raw_source/source_uri frontmatter, ` +
- `raw_data row, or synthesis evidence) and carry no raw_trace_exempt marker. e.g. ${slugs}. ` +
- `Fix: stamp raw_source (path/URI of the source material) or raw_trace_exempt: true + ` +
- `raw_trace_exempt_reason in frontmatter. Warn-only (#1978).`,
- };
- } catch {
- return { name: 'raw_provenance', status: 'warn', message: 'Could not check raw provenance (older schema?)' };
- }
-}
+ const { loadConfig } = require('../core/config.ts');
+ const {
+ resolveSelfUpgradeMode,
+ pendingUpgradeVersion,
+ } = require('../core/self-upgrade.ts');
+ const { readRecentSelfUpgrades } = require('../core/audit/self-upgrade-audit.ts');
-/**
- * #2829: source `config` is a jsonb OBJECT column (`DEFAULT '{}'::jsonb`), but a
- * re-wrapping bug could store it as a JSON string scalar ("{}", "\"{}\"", ...)
- * that grows a layer on every read→write cycle. Any row where
- * `jsonb_typeof(config) <> 'object'` is corrupted — federation and ACL settings
- * on that source are read off a string instead of the settings object. Surface
- * the affected sources with the repair path. The `gbrain sources` config writers
- * now normalize before write, so any config-writing command self-heals the row
- * (the app unwraps up to 10 nested layers); the SQL below repairs one layer
- * directly for the common case.
- */
-export async function checkSourceConfigShape(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ id: string; typ: string | null }>(
- `SELECT id, jsonb_typeof(config) AS typ FROM sources WHERE jsonb_typeof(config) <> 'object'`,
- );
- if (rows.length === 0) {
+ const cfg = loadConfig();
+ const mode = resolveSelfUpgradeMode(cfg);
+ if (mode === 'off') {
return {
- name: 'source_config_shape',
+ name: 'self_upgrade_health',
status: 'ok',
- message: 'All source config values are JSON objects',
+ message: 'Self-upgrade disabled (mode=off). Enable: gbrain config set self_upgrade.mode notify',
};
}
- const affected = rows.map((r) => `${r.id} (${r.typ ?? 'null'})`).join(', ');
- return {
- name: 'source_config_shape',
- status: 'warn',
- message:
- `${rows.length} source(s) have a non-object config — a JSON string/scalar ` +
- `instead of an object (the #2829 re-wrapping bug): ${affected}. ` +
- `Federation and ACL settings on these sources won't be read correctly. ` +
- `Repair by running any 'gbrain sources' config write (self-heals nested ` +
- `strings and recoverable arrays), or in SQL: ${REPAIR_SOURCE_CONFIG_SQL}`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return { name: 'source_config_shape', status: 'warn', message: `Check failed: ${msg}` };
- }
-}
-/**
- * #2674 — pglite_scratch_probe: distinguish a damaged PGLite store from a
- * broken WASM runtime.
- *
- * PGLite reports only `Aborted()` to JS (the PANIC goes to its own stderr),
- * so when init fails, the error string cannot say WHICH of the two it is.
- * The probe initializes a throwaway store in a temp dir, round-trips a row,
- * and reads the outcome:
- *
- * - scratch works, real init failed → the runtime is fine; the failure is
- * specific to YOUR store. The store-damage verdict is only ASSERTED when
- * the caller supplies positive evidence (`storeDamageEvidence`: a
- * damage-class disk diagnosis from `inspectPgliteDataDir`, or a
- * wasm-abort/corrupt classification of the real init error). engine=null
- * alone also covers locks and config refusals — blaming the store for
- * those was the original false-positive defect; without evidence the
- * message hedges and points at the `pglite_data_dir` diagnosis instead.
- * - scratch fails too → the runtime cannot start on this machine; report
- * OS + Bun versions on #223.
- *
- * COST GATE: a PGLite cold start is 5–20s on loaded machines, so this never
- * runs on a routine `gbrain doctor`. It runs only when (a) the real PGLite
- * engine actually failed to open (engine=null, not --fast, configured engine
- * is pglite) AND the disk diagnosis didn't already fully explain the failure
- * (a live lock / missing dir needs no runtime probe), or (b) the operator
- * asks with `--probe-pglite`.
- *
- * `probeFn` is a test seam so message routing can be pinned without paying
- * real cold starts.
- */
-export async function checkPgliteScratchProbe(opts: {
- realInitFailed: boolean;
- /**
- * Positive evidence the REAL store is damaged: `inspectPgliteDataDir`
- * verdict wal-corruption-likely/unsupported-layout (buildChecks path) or a
- * wasm-abort/corrupt classification of the actual connect error (remote
- * path). Without it the scratch-ok arm hedges instead of asserting damage.
- */
- storeDamageEvidence?: boolean;
- realStorePath?: string;
- probeFn?: () => Promise<import('../core/pglite-engine.ts').PgliteScratchProbeResult>;
-}): Promise<Check> {
- const name = 'pglite_scratch_probe';
- try {
- const probe =
- opts.probeFn ??
- (async () => {
- const { probePgliteScratchStore } = await import('../core/pglite-engine.ts');
- return probePgliteScratchStore(opts.realStorePath);
- });
- const r = await probe();
- const secs = (r.duration_ms / 1000).toFixed(1);
- if (r.ok) {
- if (opts.realInitFailed && opts.storeDamageEvidence) {
- return {
- name,
- status: 'fail',
- message:
- `A scratch PGLite store initialized, wrote and read back fine on this machine (${secs}s), ` +
- `so the runtime is healthy and YOUR STORE is damaged — not the WASM runtime. ` +
- `Your markdown is unaffected: the DB holds derived data (chunks, embeddings, links, facts) that a re-sync rebuilds. ` +
- `Recover: \`gbrain pglite-repair --dry-run\` to diagnose, \`gbrain pglite-repair --yes\` for in-place WAL repair (data preserved); ` +
- `if that can't fix it, restore a backup of the store directory or run \`gbrain reinit-pglite\` (wipes + re-inits + re-syncs; ` +
- `defaults embedding flags from your config file).`,
- details: { scratch_ok: true, duration_ms: r.duration_ms },
- };
- }
- if (opts.realInitFailed) {
- // Runtime proven healthy, but no independent evidence of store DAMAGE
- // — engine=null also covers locks, config refusals, and transient
- // failures. Hedge rather than convict the store (#2674 review).
- return {
- name,
- status: 'warn',
- message:
- `A scratch PGLite store initialized, wrote and read back fine on this machine (${secs}s), ` +
- `so the WASM runtime is healthy — the failure opening your brain is specific to your store, ` +
- `its lock, or its configuration. See the \`pglite_data_dir\` check for the on-disk diagnosis; ` +
- `\`gbrain pglite-repair --dry-run\` diagnoses without mutating anything.`,
- details: { scratch_ok: true, duration_ms: r.duration_ms },
- };
- }
- return {
- name,
- status: 'ok',
- message: `PGLite runtime healthy: scratch store round-trip in ${secs}s.`,
- details: { scratch_ok: true, duration_ms: r.duration_ms },
- };
- }
- const errLine = (r.error ?? 'unknown error').split('\n')[0];
- if (opts.realInitFailed) {
- return {
- name,
- status: 'fail',
- message:
- `A fresh scratch PGLite store ALSO failed to start (${secs}s), so the WASM runtime cannot run ` +
- `on this machine — your store is not necessarily damaged. Report your OS and Bun versions on ` +
- `https://github.com/garrytan/gbrain/issues/223. Scratch error: ${errLine}`,
- details: { scratch_ok: false, duration_ms: r.duration_ms, error: r.error, verdict: r.verdict },
- };
- }
- return {
- name,
- status: 'warn',
- message:
- `Your real store opened, but a fresh scratch PGLite store failed to initialize (${secs}s) — ` +
- `new stores can't be created on this machine. Report your OS and Bun versions on ` +
- `https://github.com/garrytan/gbrain/issues/223. Scratch error: ${errLine}`,
- details: { scratch_ok: false, duration_ms: r.duration_ms, error: r.error, verdict: r.verdict },
- };
- } catch (e) {
- // Includes the never-touch-the-real-store guard refusal. The probe not
- // running is a diagnostic gap, not a diagnosis — warn, don't fail.
- const msg = e instanceof Error ? e.message : String(e);
- return { name, status: 'warn', message: `scratch probe could not run: ${msg}` };
- }
-}
-
-export async function doctorReportRemote(
- engine: BrainEngine,
- opts: { sourceIds?: string[] } = {},
-): Promise<DoctorReport> {
- const checks: Check[] = [];
-
- // 1. Connection
- let pageCount = 0;
- try {
- const stats = await engine.getStats();
- pageCount = stats.page_count ?? 0;
- checks.push({
- name: 'connection',
- status: 'ok',
- message: `Connected, ${pageCount} pages`,
- });
- } catch (e) {
- checks.push({
- name: 'connection',
- status: 'fail',
- message: e instanceof Error ? e.message : String(e),
- });
- // #2674: on PGLite, a dead connection is exactly the ambiguous case the
- // scratch probe exists for — pay its cold start only on this failure path.
- // Unlike buildChecks (where the connect error was swallowed upstream), the
- // real error IS in hand here: classify it, and only let the probe assert
- // store damage on a damage-class verdict (wasm-abort/corrupt) — a lock or
- // config refusal classifies 'unknown' and gets the hedged message.
- if (engine.kind === 'pglite') {
- let realStorePath: string | undefined;
- try { realStorePath = loadConfig()?.database_path; } catch { /* no config */ }
- let storeDamageEvidence = false;
- try {
- const { classifyPgliteInitError, stringifyPgliteInitError } = await import('../core/pglite-engine.ts');
- const verdict = classifyPgliteInitError(stringifyPgliteInitError(e));
- storeDamageEvidence = verdict === 'wasm-abort' || verdict === 'corrupt';
- } catch { /* classifier unavailable — stay hedged (fail-closed) */ }
- checks.push(await checkPgliteScratchProbe({ realInitFailed: true, storeDamageEvidence, realStorePath }));
- }
- // Without a connection, every other check is meaningless — short-circuit.
- return computeDoctorReport(checks);
- }
-
- // 2. Schema version. Uses engine.getConfig('version') — the same engine-
- // agnostic API the local doctor uses, works on both Postgres and PGLite.
- try {
- const versionStr = await engine.getConfig('version');
- const version = parseInt(versionStr || '0', 10);
- if (version >= LATEST_VERSION) {
- checks.push({ name: 'schema_version', status: 'ok', message: `Version ${version} (latest: ${LATEST_VERSION})` });
- } else if (version === 0) {
- checks.push({
- name: 'schema_version',
- status: 'fail',
- message: `No schema version recorded. Migrations never ran. Run \`gbrain apply-migrations --yes\` on the host.`,
- });
- } else {
- checks.push({
- name: 'schema_version',
- status: 'warn',
- message: `Version ${version}, latest is ${LATEST_VERSION}. Run \`gbrain apply-migrations --yes\` on the host.`,
- });
- }
- } catch {
- checks.push({ name: 'schema_version', status: 'warn', message: 'Could not check schema version' });
- }
-
- // 2b. #2038: idx_timeline_dedup shape. A renumbered-during-merge migration
- // (v102) can be recorded-as-applied without its DDL running, leaving the
- // 3-column index in place — every timeline write then fails the 4-column
- // ON CONFLICT. The version counter can't see this, so check the index SHAPE.
- try {
- const { checkTimelineDedupIndex } = await import('../core/timeline-dedup-repair.ts');
- const idx = await checkTimelineDedupIndex(engine);
- if (!idx.tablePresent || !idx.needsRepair) {
- checks.push({
- name: 'timeline_dedup_index',
- status: 'ok',
- message: idx.tablePresent ? 'idx_timeline_dedup has the 4-column shape' : 'no timeline_entries table yet',
- });
- } else {
- checks.push({
- name: 'timeline_dedup_index',
- status: 'fail',
- message:
- `idx_timeline_dedup is ${idx.indexPresent ? `(${idx.columns.join(', ')})` : 'absent'}, ` +
- `expected (page_id, date, summary, source) — timeline writes are failing (#2038). ` +
- `Run \`gbrain apply-migrations --force-schema\` to heal it.`,
- });
- }
- } catch {
- checks.push({ name: 'timeline_dedup_index', status: 'warn', message: 'Could not check idx_timeline_dedup shape' });
- }
-
- // v0.42.x — Life Chronicle (#2390): orphaned event projections. Reads already
- // hide projections whose event page is soft-deleted (read-time correctness);
- // this always-run probe surfaces the cleanup backlog. Keyed off the real
- // schema (event_page_id), NOT a migration verify-hook, per
- // migration-verify-hook-never-runs-on-stamped-brains.
- try {
- const orphans = await engine.executeRaw<{ n: number }>(
- `SELECT count(*)::int AS n FROM timeline_entries te
- JOIN pages ep ON ep.id = te.event_page_id
- WHERE te.event_page_id IS NOT NULL AND ep.deleted_at IS NOT NULL`,
- );
- const n = Number(orphans[0]?.n ?? 0);
- checks.push(
- n === 0
- ? { name: 'chronicle_projection_health', status: 'ok', message: 'No orphaned event projections' }
- : {
- name: 'chronicle_projection_health',
- status: 'warn',
- message:
- `${n} timeline projection(s) point to soft-deleted event pages ` +
- '(hidden at read time; clean up with `gbrain integrity auto`).',
- },
- );
- } catch {
- checks.push({ name: 'chronicle_projection_health', status: 'ok', message: 'no event projections yet' });
- }
-
- // 3. Brain score
- try {
- const health = await engine.getHealth();
- const score = health.brain_score ?? 0;
- checks.push({
- name: 'brain_score',
- status: score >= 70 ? 'ok' : score >= 50 ? 'warn' : 'fail',
- message: `Brain score ${score}/100`,
- });
- } catch (e) {
- checks.push({
- name: 'brain_score',
- status: 'warn',
- message: `Could not compute: ${e instanceof Error ? e.message : String(e)}`,
- });
- }
-
- // 3b. Migration wedge hint (v0.31.8 — D14 + D19). The brain server's
- // filesystem holds the migration ledger; the wedge condition (>=3 consecutive
- // partials with no later complete) needs the force-retry hint, not plain
- // --yes. Same shape as the local doctor at line ~336.
- try {
- const completed = loadCompletedMigrations();
- const byVersion = new Map<string, { complete: boolean; partial: boolean }>();
- for (const entry of completed) {
- const seen = byVersion.get(entry.version) ?? { complete: false, partial: false };
- if (entry.status === 'complete') seen.complete = true;
- if (entry.status === 'partial') seen.partial = true;
- byVersion.set(entry.version, seen);
- }
- const completedVersions = Array.from(byVersion.entries()).filter(([, s]) => s.complete).map(([v]) => v);
- const stuck = Array.from(byVersion.entries())
- .filter(([v, s]) => {
- if (!s.partial || s.complete) return false;
- const supersededBy = completedVersions.find(cv => compareVersions(cv, v) >= 0);
- return supersededBy === undefined;
- })
- .map(([v]) => v);
- const wedged: string[] = [];
- for (const v of stuck) {
- const partialCount = completed.filter(e => e.version === v && e.status === 'partial').length;
- if (partialCount >= 3) wedged.push(v);
- }
- if (wedged.length > 0) {
- const cmd = wedged.map(v => `gbrain apply-migrations --force-retry ${v}`).join(' && ');
- checks.push({
- name: 'minions_migration',
- status: 'fail',
- message: `WEDGED MIGRATION(s) on brain host: ${wedged.join(', ')}. Run on the host: ${cmd}`,
- });
- } else if (stuck.length > 0) {
- checks.push({
- name: 'minions_migration',
- status: 'fail',
- message: `MINIONS HALF-INSTALLED on brain host: ${stuck.join(', ')}. Run on the host: gbrain apply-migrations --yes`,
- });
- }
- } catch {
- // Best-effort. A broken JSONL on the brain server should not stop the
- // remote doctor.
- }
-
- // 4. Sync failures (file-plane ledger; see src/core/sync-failure-ledger.ts).
- // issue #1939: read via the shared loader + severity decision so this remote
- // surface agrees with the local buildChecks emitter by construction. Stays
- // subprocess-free (file read + Date.parse only, no git), preserving the remote
- // trust boundary. Escalates to FAIL when a stuck bookmark has blocked past the
- // sync-freshness fail cadence or unresolved count is large.
- try {
- const { loadSyncFailures, decideSyncFailureSeverity } = await import('../core/sync.ts');
- const entries = loadSyncFailures();
- const failHours = _resolveSyncFreshnessHours('GBRAIN_SYNC_FRESHNESS_FAIL_HOURS', 72);
- const sev = decideSyncFailureSeverity({ entries, nowMs: Date.now(), failHours });
- const msg =
- sev.unresolved === 0
- ? 'No unresolved sync failures'
- : `${sev.unresolved} unresolved sync failure(s)` +
- (sev.auto_skipped > 0 ? ` (${sev.auto_skipped} auto-skipped — pages NOT indexed)` : '') +
- ` — run \`gbrain sync --skip-failed\` on the host to acknowledge`;
- checks.push({ name: 'sync_failures', status: sev.status, message: msg });
- } catch {
- checks.push({ name: 'sync_failures', status: 'ok', message: 'No failures recorded' });
- }
-
- // 4b. Multi-source drift (v0.31.8 — D8 + D14). Same shape as the local
- // doctor's check at the same name. Runs server-side; the result is
- // returned to the thin-client over MCP.
- try {
- const { findMisroutedPages } = await import('../core/multi-source-drift.ts');
- const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
- `SELECT id, local_path FROM sources`,
- );
- const nonDefaultWithPath = sources.filter(s => s.id !== 'default' && s.local_path);
- if (sources.length > 1 && nonDefaultWithPath.length > 0) {
- const result = await findMisroutedPages(
- engine,
- nonDefaultWithPath.map(s => ({ id: s.id, local_path: s.local_path as string })),
- );
- if (result.walk_truncated) {
- checks.push({
- name: 'multi_source_drift',
- status: 'warn',
- message: 'Multi-source drift check skipped — FS walk hit limit/timeout on the brain server.',
- });
- } else if (result.count > 0) {
- const sampleStr = result.sample.map(s => `${s.slug} (intended=${s.intended_source})`).join(', ');
- checks.push({
- name: 'multi_source_drift',
- status: 'warn',
- message:
- `${result.count} page slug(s) appear at 'default' but NOT at the intended source ` +
- `(e.g., ${sampleStr}). Likely pre-v0.30.3 misroutes OR an incomplete initial sync. ` +
- `Verify on the brain host: \`gbrain sources status\` then \`gbrain sync --source <id> --full\`.`,
- });
- } else {
- checks.push({
- name: 'multi_source_drift',
- status: 'ok',
- message: 'No cross-source slug drift detected.',
- });
- }
- }
- } catch {
- // Best-effort, like the rest of doctorReportRemote.
- }
-
- // 5. Queue health (Postgres-only). PGLite has no minion_jobs in the same
- // shape; skip the check there with an informational message.
- checks.push(await computeQueueHealthCheck(engine));
-
- // issue #1801 — wedged_queue (cross-surface parity with buildChecks).
- checks.push(await computeWedgedQueueCheck(engine));
-
- // #2194 fix #5 — warn when autopilot fan-out exceeds worker concurrency.
- checks.push(await computeAutopilotFanoutConcurrencyCheck(engine));
-
- // v0.41 Bug 2 / Eng D8 — subagent_health surfaces rate-lease pressure to the operator.
- checks.push(await checkSubagentHealth(engine));
-
- // v0.41.18.0 — batch_retry_health (cross-surface parity with buildChecks).
- // Surfaces Supavisor circuit-breaker incidents over MCP so remote operators
- // see the same signal local doctor surfaces.
- checks.push(await checkBatchRetryHealth(engine));
-
- // v0.41.2.1 — embedding_env_override (cross-surface parity with
- // buildChecks). Surfaces when GBRAIN_EMBEDDING_* env vars disagree
- // with DB config; closes the silent-override class that caused the
- // 716K-chunk damage incident from PR #1421's description.
- checks.push(await checkEmbeddingEnvOverride(engine));
-
- // v0.31.12 subagent runtime enforcement (Layer 3 of 3 — Codex F13).
- // The subagent loop requires native tool-calling. If models.subagent,
- // models.tier.subagent, or models.default resolves to a limited provider, warn here
- // so the user sees it at the next `gbrain doctor` run instead of at the
- // next subagent job submission. (Layers 1+2 also enforce — this is the
- // surfacing layer.)
- checks.push(await checkSubagentCapability(engine));
-
- // Harness hook adapters — per-channel push-context visibility (sibling of
- // the engine-free retrieval_reflex_health heartbeat check). Source-scoped
- // for remote callers (cross-model P1): a source-bound token must not see
- // other sources' activity counts/timestamps.
- checks.push(await checkVolunteerChannels(engine, { sourceIds: opts.sourceIds }));
-
- // 6. Sync freshness check
- checks.push(await checkSyncFreshness(engine));
-
- // v0.41.19.0 (Issue 5): sync --all consolidation nudge for multi-source brains.
- checks.push(await checkSyncConsolidation(engine));
-
- // v0.42.x (#1794, 4A): pool-budget nudge when GBRAIN_MAX_CONNECTIONS is set.
- checks.push(await checkPoolBudget(engine));
-
- // v0.42.7 (#1696): link-extraction lag. Strictly SQL (single indexed COUNT),
- // safe on the thin-client/remote path — remote operators on checkout-less
- // Postgres brains are exactly who can't otherwise see the extraction backlog.
- // Brain-wide here (remote --source scoping is a separate TODO, like orphan_ratio).
- checks.push(await checkLinksExtractionLag(engine));
-
- // v0.39 T7 + T9 — schema-pack health checks (3 checks per v0.38 plan):
- // schema_pack_active — active pack resolves cleanly
- // schema_pack_consistency — % of pages typed against active pack
- // schema_pack_source_drift — per-source pack divergence
- checks.push(await checkSchemaPackActive(engine));
- checks.push(await checkSchemaPackConsistency(engine));
- checks.push(await checkSchemaPackSourceDrift(engine));
-
- // 7. v0.32.3 search-lite mode + per-key drift surface.
- checks.push(await checkSearchMode(engine));
-
- // 8. v0.32.3 eval_drift: retrieval-affecting files changed since last
- // eval run? Non-blocking — surfaces as ok + hint.
- checks.push(await checkEvalDrift(engine));
-
- // 9. v0.35.0.0+ reranker_health: surfaces rerank-audit failures from
- // ~/.gbrain/audit/rerank-failures-*.jsonl. Failure-only (no success
- // logging on the search hot path per CDX2-F22). Reads
- // search.reranker.enabled FIRST so absence-of-failures means different
- // things when reranker is on vs off.
- checks.push(await checkRerankerHealth(engine));
-
- // 9a. v0.40.4 graph_signals_coverage: when graph_signals is enabled
- // (via mode bundle default or explicit config override), surface
- // whether link density is high enough for the signal to fire
- // meaningfully. <10% inbound coverage warns; >=30% ok with metric.
- checks.push(await checkGraphSignalsCoverage(engine));
-
- // 9b. v0.37.0 brainstorm_health: surfaces three brainstorm/lsd readiness
- // signals: (a) migration v79 applied (last_retrieved_at column exists),
- // (b) calibration cold-start status (active_bias_tags empty), (c)
- // search.track_retrieval enabled/disabled. Each surfaces a paste-ready
- // fix hint.
- checks.push(await checkBrainstormHealth(engine));
-
- // 10. v0.36.1.0 Hindsight calibration wave (T12) — four new checks:
- // - abandoned_threads: high-conviction takes never revisited
- // - calibration_freshness: profile is older than 7 days
- // - grade_confidence_drift: judge self-reported confidence vs actual accuracy (CDX-11 mitigation)
- // - voice_gate_health: voice gate failure rate over the last 7 days
- checks.push(await checkAbandonedThreads(engine));
- checks.push(await checkCalibrationFreshness(engine));
- checks.push(await checkGradeConfidenceDrift(engine));
- checks.push(await checkVoiceGateHealth(engine));
-
- // 11. v0.40.3.0 contextual_retrieval_coverage — surfaces pages with
- // - chunker_version drift (pre-v40 pages not yet re-embedded)
- // - contextual_retrieval_mode IS NULL (mode never evaluated)
- // - synopsis-failures audit JSONL entries from the last 7 days
- checks.push(await checkContextualRetrievalCoverage(engine));
-
- // issue #1777 — hidden_by_search_policy: chunked pages withheld from default
- // search by the hard-exclude prefix policy. Pure SQL COUNT, safe on the
- // remote/thin-client path.
- checks.push(await checkHiddenBySearchPolicy(engine));
-
- // 11a. issue #972 link_resolution_opportunity — same check the local
- // doctor runs at the equivalent slot in buildChecks. Mirrored for
- // thin-client parity so `gbrain remote doctor` sees the same hint.
- checks.push(await checkLinkResolutionOpportunity(engine));
-
- // 12. v0.40.5.0 Federated Sync v2 (T12) — federation_health:
- // - Per-source lag, embed coverage, failed-job rate.
- // - Single-source brain short-circuits to ok.
- // - Three-state: ok / warn / fail.
- checks.push(await checkFederationHealth(engine));
-
- // 13. v0.42 self_upgrade_health: mode, whether behind, recent failures.
- // File-plane only (no engine) — works on thin clients too.
- checks.push(checkSelfUpgradeHealth());
-
- return computeDoctorReport(checks);
-}
-
-/**
- * v0.42 self_upgrade_health. Surfaces the self-upgrade mode, whether an update
- * is pending (from the cache), and any recent failed auto-upgrade attempts.
- * File-plane only (no DB) so it runs on thin clients. Three-state: warn on
- * recent failures, otherwise ok.
- */
-export function checkSelfUpgradeHealth(): Check {
- try {
- const { loadConfig } = require('../core/config.ts');
- const {
- resolveSelfUpgradeMode,
- pendingUpgradeVersion,
- } = require('../core/self-upgrade.ts');
- const { readRecentSelfUpgrades } = require('../core/audit/self-upgrade-audit.ts');
-
- const cfg = loadConfig();
- const mode = resolveSelfUpgradeMode(cfg);
- if (mode === 'off') {
- return {
- name: 'self_upgrade_health',
- status: 'ok',
- message: 'Self-upgrade disabled (mode=off). Enable: gbrain config set self_upgrade.mode notify',
- };
- }
-
- const parts: string[] = [`mode=${mode}`];
- // Shared stale/foreign-cache guard: only report an upgrade strictly newer
- // than the RUNNING binary (pendingUpgradeVersion owns the rule).
- const pendingLatest = pendingUpgradeVersion(GBRAIN_BINARY_VERSION, Date.now());
- if (pendingLatest) {
- parts.push(`update available: ${GBRAIN_BINARY_VERSION} -> ${pendingLatest} (run: gbrain self-upgrade)`);
+ const parts: string[] = [`mode=${mode}`];
+ // Shared stale/foreign-cache guard: only report an upgrade strictly newer
+ // than the RUNNING binary (pendingUpgradeVersion owns the rule).
+ const pendingLatest = pendingUpgradeVersion(GBRAIN_BINARY_VERSION, Date.now());
+ if (pendingLatest) {
+ parts.push(`update available: ${GBRAIN_BINARY_VERSION} -> ${pendingLatest} (run: gbrain self-upgrade)`);
}
const failedVersions: string[] = cfg?.self_upgrade?.failed_versions ?? [];
if (failedVersions.length > 0) {
- parts.push(`skipping known-bad: ${failedVersions.join(', ')}`);
- }
-
- const recent = readRecentSelfUpgrades(7) as Array<{ outcome?: string; error?: string; latest?: string | null }>;
- const failures = recent.filter((e) => e.outcome === 'failed');
- if (failures.length > 0) {
- const last = failures[failures.length - 1];
- return {
- name: 'self_upgrade_health',
- status: 'warn',
- message:
- `${failures.length} self-upgrade failure(s) in 7d (${parts.join('; ')}). ` +
- `Last: ${last.latest ?? '?'}${last.error ? ` — ${last.error}` : ''}. ` +
- `Check ~/.gbrain/upgrade-errors.jsonl; apply manually with gbrain self-upgrade.`,
- };
- }
-
- return { name: 'self_upgrade_health', status: 'ok', message: parts.join('; ') };
- } catch (e) {
- return {
- name: 'self_upgrade_health',
- status: 'ok',
- message: `Self-upgrade status unavailable (${e instanceof Error ? e.message : String(e)})`,
- };
- }
-}
-
-// --- v0.36.1.0 calibration doctor checks (T12) ---
-
-/**
- * abandoned_threads: surfaces active high-conviction takes (weight >= 0.7)
- * older than 12 months that have neither been superseded nor linked to a
- * follow-up page. These are commitments the user made and never revisited.
- * Status 'ok' with a count; never warns/fails (this is signal, not error).
- */
-/**
- * v0.40.3.0 contextual_retrieval_coverage check.
- *
- * Surfaces drift between the active CR mode + the per-page
- * `contextual_retrieval_mode` column. Three signals:
- *
- * 1. Pages with chunker_version < current — pre-v40 pages that need
- * to be re-embedded for the wrapper to apply. Paste-ready fix:
- * `gbrain reindex --markdown`.
- * 2. Pages with contextual_retrieval_mode IS NULL — never evaluated
- * against the CR ladder. Same fix as (1).
- * 3. Synopsis-failure events in the audit JSONL over the last 7 days
- * — surfaces refusals + page-level fallbacks. >5% refusal rate
- * warns; otherwise reported as informational.
- *
- * Reads `~/.gbrain/audit/synopsis-failures-YYYY-Www.jsonl` via
- * readRecentSynopsisFailures + summarizeSynopsisFailures from
- * `src/core/audit-synopsis.ts`. Failure-only audit means low write
- * volume on healthy brains.
- */
-export async function checkContextualRetrievalCoverage(engine: BrainEngine): Promise<Check> {
- try {
- const { MARKDOWN_CHUNKER_VERSION } = await import('../core/chunkers/recursive.ts');
- const rows = await engine.executeRaw<{ chunker_drift: number; mode_null: number }>(
- `SELECT
- COUNT(*) FILTER (WHERE chunker_version < $1)::int AS chunker_drift,
- COUNT(*) FILTER (WHERE contextual_retrieval_mode IS NULL)::int AS mode_null
- FROM pages
- WHERE page_kind = 'markdown'
- AND deleted_at IS NULL`,
- [MARKDOWN_CHUNKER_VERSION],
- );
- const chunkerDrift = rows[0]?.chunker_drift ?? 0;
- const modeNull = rows[0]?.mode_null ?? 0;
-
- // Synopsis-failures audit summary (best-effort; missing audit file = 0).
- let failureSummaryLine = '';
- try {
- const audit = await import('../core/audit-synopsis.ts');
- const events = audit.readRecentSynopsisFailures(7);
- const summary = audit.summarizeSynopsisFailures(events);
- if (summary && summary.total > 0) {
- const rate = (summary.page_level_fallback_rate * 100).toFixed(1);
- failureSummaryLine =
- ` ${summary.total} synopsis failure(s) in last 7d ` +
- `(${summary.page_level_fallback_count} triggered page-level fall-back, ${rate}%).`;
- }
- } catch {
- // Audit module unavailable — skip the summary line.
- }
-
- if (chunkerDrift === 0 && modeNull === 0 && failureSummaryLine === '') {
- return {
- name: 'contextual_retrieval_coverage',
- status: 'ok',
- message: 'All markdown pages aligned to current chunker + CR mode.',
- };
- }
-
- const parts: string[] = [];
- if (chunkerDrift > 0) {
- parts.push(`${chunkerDrift} page(s) at older chunker_version`);
- }
- if (modeNull > 0) {
- parts.push(`${modeNull} page(s) never evaluated against CR ladder`);
- }
- const fixHint =
- chunkerDrift > 0 || modeNull > 0
- ? ` Run \`gbrain reindex --markdown\` to align.`
- : '';
- return {
- name: 'contextual_retrieval_coverage',
- status: chunkerDrift > 0 || modeNull > 0 ? 'warn' : 'ok',
- message: `${parts.join('; ')}.${fixHint}${failureSummaryLine}`,
- };
- } catch (e) {
- return {
- name: 'contextual_retrieval_coverage',
- status: 'warn',
- message: `Could not check contextual retrieval coverage: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * issue #1777 — hidden_by_search_policy
- *
- * Counts CHUNKED pages that are withheld from default search by the
- * hard-exclude prefix policy (`test/`, `attachments/`, `.raw/`, plus any
- * `GBRAIN_SEARCH_EXCLUDE` env additions). Makes the surviving exclude policy
- * auditable so an empty search result is distinguishable from "withheld by
- * policy" — the deeper bug the archive-demote fix only half-closes.
- *
- * HONEST SUPERSET: the count is "chunked pages under an excluded prefix", NOT
- * "searchable pages". Keyword search additionally filters
- * `search_vector @@ ... AND modality='text'` and vector search filters text
- * modality + non-null embedding, so `EXISTS (content_chunks)` over-includes
- * image-only / non-text pages. Tightening to the exact per-modality predicate
- * would couple this check to search internals for a number nobody paginates on;
- * the superset is the right operator signal. The message says "chunked page(s)".
- *
- * Status (CV-1a): pages hidden ONLY under DEFAULT excludes → `ok` (intentional
- * noise; warning would make every healthy brain look unhealthy). Pages hidden
- * under a NON-default (env-supplied) prefix → `warn`. The message is
- * agent-prescriptive: move content out of the excluded prefix or pass
- * `include_slug_prefixes` on the query.
- *
- * NOTE: this does NOT verify `archive/` pages are embedded/graphed — after the
- * #1777 fix `archive/` is no longer excluded, so it never appears here.
- */
-export async function checkHiddenBySearchPolicy(engine: BrainEngine): Promise<Check> {
- const name = 'hidden_by_search_policy';
- try {
- const prefixes = resolveHardExcludes();
- if (prefixes.length === 0) {
- return { name, status: 'ok', message: 'No search-exclude prefixes active.' };
- }
-
- // ONE query: COUNT(DISTINCT p.id) per prefix in a single pass. Prefixes are
- // bound params, LIKE-escaped (env-supplied prefixes may contain %/_/\) with
- // an explicit ESCAPE clause. Candidate gate is EXISTS(content_chunks);
- // buildVisibilityClause mirrors search's page-level visibility (soft-delete,
- // archived source, quarantine) and REQUIRES the `sources s` join.
- const visibility = buildVisibilityClause('p', 's');
- const filters = prefixes
- .map((_, i) => `COUNT(DISTINCT p.id) FILTER (WHERE p.slug LIKE $${i + 1} ESCAPE '\\')::int AS c${i}`)
- .join(',\n ');
- const params = prefixes.map((pfx) => `${escapeLikePattern(pfx)}%`);
- const sql =
- `SELECT
- ${filters}
- FROM pages p
- JOIN sources s ON s.id = p.source_id
- WHERE EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
- ${visibility}`;
- const rows = await engine.executeRaw<Record<string, number>>(sql, params);
- const row = rows[0] ?? {};
-
- const defaults = new Set(DEFAULT_HARD_EXCLUDES);
- const perPrefix = prefixes
- .map((pfx, i) => ({ prefix: pfx, count: Number(row[`c${i}`] ?? 0), isDefault: defaults.has(pfx) }))
- .filter((e) => e.count > 0);
-
- if (perPrefix.length === 0) {
- return {
- name,
- status: 'ok',
- message: 'No pages hidden by search-exclude policy.',
- details: { prefixes, counts: {} },
- };
- }
-
- const counts: Record<string, number> = {};
- for (const e of perPrefix) counts[e.prefix] = e.count;
- const breakdown = perPrefix.map((e) => `${e.count} under '${e.prefix}'`).join(', ');
- const hasNonDefault = perPrefix.some((e) => !e.isDefault);
- const guidance =
- 'If any hold content you want findable, move them out of the excluded ' +
- "prefix or pass `include_slug_prefixes` on the query.";
- return {
- name,
- status: hasNonDefault ? 'warn' : 'ok',
- message: `${breakdown} chunked page(s) are excluded from default search by prefix policy. ${guidance}`,
- details: { prefixes, counts },
- };
- } catch (e) {
- return {
- name,
- status: 'warn',
- message: `Could not check hidden-by-search-policy: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * Issue #972 — link_resolution_opportunity check.
- *
- * Walks every page in the brain, scans for bare wikilinks
- * (`[[struktura]]` outside DIR_PATTERN) that would resolve to at least
- * one page under global-basename mode, and surfaces a paste-ready
- * `gbrain config set link_resolution.global_basename true` hint when
- * the count is meaningful (>=5 would-resolve AND >=20% of bare
- * wikilinks have matches). Skipped silently when the flag is already
- * enabled (no signal to surface) or the brain is empty.
- *
- * Bounded scan: batch-loads the 1000 most-recent pages in one query (not a
- * per-page getPage walk) with a 60s backstop. On DB error, downgrades to an
- * informational `ok` so doctor never blocks on this check.
- */
-export async function checkLinkResolutionOpportunity(
- engine: BrainEngine,
- progress?: ProgressReporter,
-): Promise<Check> {
- const name = 'link_resolution_opportunity';
- try {
- if (await isGlobalBasenameEnabled(engine)) {
- return { name, status: 'ok', message: 'global_basename mode already enabled' };
- }
- const allSlugs = await engine.getAllSlugs();
- if (allSlugs.size === 0) {
- return { name, status: 'ok', message: 'Brain is empty — nothing to scan' };
- }
- // Build a basename → slug[] index ONCE for the entire scan via the shared
- // builder (issue #972 codex [P2] DRY) — same key set (raw/lower/slugified)
- // as extraction, so this estimate matches what extraction actually
- // resolves. Pre-fix the doctor omitted the slugified key and undercounted.
- const basenameIndex = buildBasenameIndex(allSlugs);
-
- let bareCount = 0;
- let wouldResolveCount = 0;
- const distinctTargets = new Set<string>();
-
- // Issue #972 (codex [P2] perf): batch-load the most-recent N pages in ONE
- // query instead of listAllPageRefs() + a getPage() per page. The prior
- // full N-page walk hit the 60s budget every run on large brains and
- // returned a perpetual partial; this bounds the work to a fixed sample.
- const SAMPLE_LIMIT = 1000;
- const sampled = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null }>(
- `SELECT compiled_truth, timeline FROM pages WHERE deleted_at IS NULL ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}`,
- );
- const totalPages = allSlugs.size;
- const sampledNote = totalPages > SAMPLE_LIMIT
- ? ` (scanned the ${SAMPLE_LIMIT} most-recent of ${totalPages} pages)`
- : '';
- const deadline = Date.now() + 60_000;
- const hb = progress ? startHeartbeat(progress, `scanning ${sampled.length} pages for bare wikilinks…`) : null;
- try {
- for (const row of sampled) {
- if (Date.now() > deadline) break; // backstop; in-memory scan rarely hits it
- const content = (row.compiled_truth ?? '') + '\n' + (row.timeline ?? '');
- for (const e of extractEntityRefs(content)) {
- if (!e.needsResolution) continue;
- bareCount++;
- // Issue #972 (codex): match on the wikilink TARGET (e.slug), not
- // the display alias (e.name), via the shared query so the doctor
- // estimate equals what extraction actually resolves.
- const matches = queryBasenameIndex(basenameIndex, e.slug);
- if (matches.length > 0) {
- wouldResolveCount++;
- for (const m of matches) distinctTargets.add(m);
- }
- }
- }
- } finally {
- hb?.();
- }
-
- if (bareCount === 0) {
- return { name, status: 'ok', message: 'No bare wikilinks found' };
- }
- if (wouldResolveCount === 0) {
- return {
- name,
- status: 'ok',
- message: `${bareCount} bare wikilink(s) found, but none have basename matches in the brain.`,
- };
- }
- const ratio = wouldResolveCount / bareCount;
- if (wouldResolveCount >= 5 && ratio >= 0.20) {
- const pct = Math.round(ratio * 100);
- return {
- name,
- status: 'warn',
- message:
- `${wouldResolveCount} of ${bareCount} bare wikilinks (${pct}%) would resolve to ` +
- `${distinctTargets.size} distinct page(s) under global_basename mode${sampledNote}. ` +
- `Enable with: gbrain config set link_resolution.global_basename true`,
- };
- }
- const pct = Math.round(ratio * 100);
- return {
- name,
- status: 'ok',
- message: `${wouldResolveCount}/${bareCount} bare wikilinks (${pct}%) would resolve — below the 20% / 5-link threshold for surfacing a hint${sampledNote}.`,
- };
- } catch (e) {
- return {
- name,
- status: 'ok',
- message: `Skipped (${e instanceof Error ? e.message : String(e)})`,
- };
- }
-}
-
-export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ count: number }>(
- `SELECT COUNT(*)::int AS count FROM takes
- WHERE active = true
- AND resolved_at IS NULL
- AND superseded_by IS NULL
- AND weight >= 0.7
- AND since_date IS NOT NULL
- AND since_date::date < (now() - INTERVAL '12 months')`,
- );
- const count = rows[0]?.count ?? 0;
- if (count === 0) {
- return {
- name: 'abandoned_threads',
- status: 'ok',
- message: 'No abandoned high-conviction threads',
- };
- }
- return {
- name: 'abandoned_threads',
- status: 'ok',
- message: `${count} high-conviction take(s) older than 12 months and never revisited — see \`gbrain calibration\` for details`,
- };
- } catch (e) {
- return {
- name: 'abandoned_threads',
- status: 'warn',
- message: `Could not check abandoned threads: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * calibration_freshness: warns when the active calibration profile is
- * older than 7 days (configurable). Default holder resolves via resolveOwnerHolder
- * (config emotional_weight.user_holder, else 'self'). Multi-source
- * brains see one row per source; this check uses the most recent across
- * all sources.
- */
-export async function checkCalibrationFreshness(engine: BrainEngine): Promise<Check> {
- try {
- const ownerHolder = resolveOwnerHolder({
- configValue: await engine.getConfig('emotional_weight.user_holder'),
- });
- const rows = await engine.executeRaw<{ generated_at: Date | null }>(
- `SELECT MAX(generated_at) AS generated_at FROM calibration_profiles WHERE holder = $1`,
- [ownerHolder],
- );
- const generated = rows[0]?.generated_at;
- if (!generated) {
- return {
- name: 'calibration_freshness',
- status: 'ok',
- message: 'No calibration profile yet (builds after 5+ resolved takes)',
- };
- }
- const ageMs = Date.now() - new Date(generated).getTime();
- const ageDays = Math.floor(ageMs / (1000 * 60 * 60 * 24));
- const staleDays = 7;
- if (ageDays > staleDays) {
- return {
- name: 'calibration_freshness',
- status: 'warn',
- message: `Calibration profile is ${ageDays} days old (stale at >${staleDays}d). Run \`gbrain calibration --regenerate\``,
- };
- }
- return {
- name: 'calibration_freshness',
- status: 'ok',
- message: `Calibration profile generated ${ageDays}d ago`,
- };
- } catch (e) {
- return {
- name: 'calibration_freshness',
- status: 'warn',
- message: `Could not check calibration freshness: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * grade_confidence_drift (CDX-11 mitigation): compare the judge's
- * self-reported confidence on auto-applied verdicts against the eventual
- * accuracy on those same takes. When auto-resolutions diverge from
- * confidence prediction, the judge is mis-calibrated and the operator
- * should retune the prompt or revisit the threshold.
- *
- * v0.36.1.0 ship state: returns 'ok' with a counter — actual drift math
- * requires a measurement window we haven't accumulated yet. The check
- * exists so the surface is wired; the math arrives once we have N >= 30
- * auto-applied verdicts to compare.
- */
-export async function checkGradeConfidenceDrift(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ applied_count: number }>(
- `SELECT COUNT(*)::int AS applied_count FROM take_grade_cache WHERE applied = true`,
- );
- const applied = rows[0]?.applied_count ?? 0;
- if (applied < 30) {
- return {
- name: 'grade_confidence_drift',
- status: 'ok',
- message: `Only ${applied} auto-applied verdicts — need 30+ for drift detection`,
- };
- }
- // v0.37+ TODO: compute confidence-vs-accuracy correlation; warn when
- // mean(applied verdicts' confidence) deviates from the actual accuracy
- // rate (cross-checked against later manual corrections via the
- // contradictions probe). For v0.36.1.0 the check surfaces only the
- // count and a "calibration math pending" status.
- return {
- name: 'grade_confidence_drift',
- status: 'ok',
- message: `${applied} auto-applied verdicts; drift math arrives in v0.37+`,
- };
- } catch (e) {
- return {
- name: 'grade_confidence_drift',
- status: 'warn',
- message: `Could not check grade confidence drift: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * voice_gate_health: warns when calibration_profiles rows show a high rate
- * of voice gate failures over the last 7 days. Failures aren't bad in
- * isolation (template fallback is fine), but a sustained high rate signals
- * the rubric needs tuning.
- */
-/**
- * v0.41 Bug 2 / Eng D8 — surfaces rate-lease pressure from
- * `minion_lease_pressure_log` (populated by the worker's lease-full bypass
- * path). The operator's primary forensic signal for "is the lease cap too
- * tight" — without this check, the v0.41 bypass would be invisible (no
- * dead-letter, but also no operator awareness).
- *
- * Thresholds (windowed at 24h):
- * 0 bounces → ok ("no pressure")
- * 1-99 bounces → ok ("transient")
- * 100+ bounces + subagent jobs completed in same window → ok ("healthy backpressure")
- * 100+ bounces + ZERO completed subagent jobs → warn (paste-ready cap-raise hint)
- * 1000+ bounces → fail ("blocking real work")
- *
- * Works on both Postgres + PGLite (migration v94 creates the table on both).
- * Pre-v93 brains (no table) silently skip with an OK message.
- */
-export async function checkSubagentHealth(engine: BrainEngine): Promise<Check> {
- try {
- const bounceRows = await engine.executeRaw<{ count: string }>(
- `SELECT count(*)::text AS count FROM minion_lease_pressure_log
- WHERE bounced_at > now() - interval '24 hours'`,
- );
- const bounces = parseInt(bounceRows[0]?.count ?? '0', 10);
- if (bounces === 0) {
- return {
- name: 'subagent_health',
- status: 'ok',
- message: 'No rate-lease pressure in last 24h',
- };
- }
- if (bounces >= 1000) {
- return {
- name: 'subagent_health',
- status: 'fail',
- message: `${bounces} lease-pressure bounces in last 24h — this is blocking real work. Raise the cap: \`export GBRAIN_ANTHROPIC_MAX_INFLIGHT=64\` (or \`unlimited\` for Azure / Bedrock / self-hosted upstreams with no provider-side rate limit). After raising, restart \`gbrain jobs work\`.`,
- };
- }
- // 1-999 bounces: cross-check forward progress.
- const completedRows = await engine.executeRaw<{ count: string }>(
- `SELECT count(*)::text AS count FROM minion_jobs
- WHERE finished_at > now() - interval '24 hours'
- AND status = 'completed'
- AND name = 'subagent'`,
- ).catch(() => [{ count: '0' }]);
- const completed = parseInt(completedRows[0]?.count ?? '0', 10);
- if (bounces >= 100 && completed === 0) {
- return {
- name: 'subagent_health',
- status: 'warn',
- message: `${bounces} lease-pressure bounces in last 24h with no completed subagent jobs — cap is too tight. Raise via \`export GBRAIN_ANTHROPIC_MAX_INFLIGHT=64\` (or \`unlimited\` for upstreams with no provider-side cap).`,
- };
- }
- return {
- name: 'subagent_health',
- status: 'ok',
- message: `Lease pressure: ${bounces} bounces in last 24h, ${completed} subagent jobs completed — backpressure is binding but throughput is healthy`,
- };
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- if (process.env.GBRAIN_DEBUG === '1') {
- process.stderr.write(`[doctor] subagent_health skipped: ${msg}\n`);
- }
- return {
- name: 'subagent_health',
- status: 'ok',
- message: 'Skipped (minion_lease_pressure_log unavailable — pre-v0.41 brain)',
- };
- }
-}
-
-export async function checkVoiceGateHealth(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ total: number; failures: number }>(
- `SELECT COUNT(*)::int AS total,
- COALESCE(SUM(CASE WHEN voice_gate_passed = false THEN 1 ELSE 0 END), 0)::int AS failures
- FROM calibration_profiles
- WHERE generated_at >= (now() - INTERVAL '7 days')`,
- );
- const total = rows[0]?.total ?? 0;
- const failures = rows[0]?.failures ?? 0;
- if (total === 0) {
- return {
- name: 'voice_gate_health',
- status: 'ok',
- message: 'No calibration profile generation in the last 7 days',
- };
- }
- const failRate = failures / total;
- if (failRate >= 0.3) {
- return {
- name: 'voice_gate_health',
- status: 'warn',
- message: `Voice gate failed ${failures}/${total} (${Math.round(failRate * 100)}%) in last 7 days. Review src/core/calibration/voice-gate.ts rubric.`,
- };
- }
- return {
- name: 'voice_gate_health',
- status: 'ok',
- message: `Voice gate ${failures}/${total} failed in last 7 days (${Math.round(failRate * 100)}%)`,
- };
- } catch (e) {
- return {
- name: 'voice_gate_health',
- status: 'warn',
- message: `Could not check voice gate health: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * v0.35.0.0+ reranker_health doctor check.
- *
- * Logic (post-CDX2 review):
- * 1) Read `search.reranker.enabled` first. When disabled and no
- * failures in window → 'ok: reranker disabled'. Avoids interpreting
- * "no events" as "broken" when reranker is simply not in use.
- * 2) Walk last 7 days of `~/.gbrain/audit/rerank-failures-*.jsonl`.
- * 3) Auth failures: ANY single one warns (config-time problem doctor's
- * own probe should have caught — surface it).
- * 4) Transient (network/timeout/rate_limit): warn at >=5 in window.
- * Below that they're noise; reranker fails open anyway.
- * 5) Payload-too-large failures: warn at >=1 (indicates a workload
- * mismatch that the operator should know about).
- * 6) Budget/pricing failures: warn at >=1 with the rerank pricing surface
- * and --max-cost escape hatch.
- *
- * Engine-agnostic (file-based + one config-key read).
- */
-export async function checkRerankerHealth(engine: BrainEngine): Promise<Check> {
- try {
- const { readRecentRerankFailures } = await import('../core/rerank-audit.ts');
- const cfg = await engine.getConfig('search.reranker.enabled');
- const rerankerEnabled = cfg === 'true' || cfg === '1';
-
- const failures = readRecentRerankFailures(7);
- if (failures.length === 0) {
- return {
- name: 'reranker_health',
- status: 'ok',
- message: rerankerEnabled
- ? 'No rerank failures in last 7 days'
- : 'Reranker disabled — no failures expected',
- };
- }
-
- const authFails = failures.filter((f) => f.reason === 'auth');
- if (authFails.length > 0) {
- return {
- name: 'reranker_health',
- status: 'warn',
- message: `${authFails.length} reranker auth failure(s) in last 7 days. Fix: verify the reranker provider's API key (e.g. VOYAGE_API_KEY) and run \`gbrain models doctor\`.`,
- };
- }
-
- const payloadFails = failures.filter((f) => f.reason === 'payload_too_large');
- if (payloadFails.length > 0) {
- return {
- name: 'reranker_health',
- status: 'warn',
- message: `${payloadFails.length} reranker payload-too-large failure(s) in last 7 days. Fix: lower \`search.reranker.top_n_in\` (default 30) or split very large documents.`,
- };
- }
-
- const budgetFails = failures.filter((f) => f.reason === 'budget');
- if (budgetFails.length > 0) {
- return {
- name: 'reranker_health',
- status: 'warn',
- message: `${budgetFails.length} reranker budget/pricing failure(s) in last 7 days. Fix: add rerank pricing to src/core/embedding-pricing.ts or drop --max-cost.`,
- };
- }
-
- const transientFails = failures.filter(
- (f) => f.reason === 'network' || f.reason === 'timeout' || f.reason === 'rate_limit',
- );
- if (transientFails.length >= 5) {
- return {
- name: 'reranker_health',
- status: 'warn',
- message: `${transientFails.length} transient reranker failure(s) in last 7 days. Search fails open to RRF order; check ZE status if persistent.`,
- };
- }
-
- // Historical #2059 rows were logged as `unknown` before missing reranker
- // auth was classified at the gateway. Surface repeated unknowns instead of
- // reporting "ok" while every rerank fails open.
- const unknownFails = failures.filter((f) => f.reason === 'unknown');
- if (unknownFails.length >= 3) {
- const setupHint = unknownFails.some((f) => {
- const summary = String(f.error_summary ?? '');
- return (
- summary.includes('ZEROENTROPY_API_KEY') ||
- summary.includes('VOYAGE_API_KEY') ||
- summary.toLowerCase().includes('api key')
- );
- })
- ? " Fix: verify the reranker provider's API key (e.g. VOYAGE_API_KEY) and run `gbrain models doctor`."
- : '';
- return {
- name: 'reranker_health',
- status: 'warn',
- message: `${unknownFails.length} unknown reranker failure(s) in last 7 days.${setupHint}`,
- };
- }
-
- return {
- name: 'reranker_health',
- status: 'ok',
- message: `${failures.length} reranker failure(s) in last 7 days (below threshold)`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'reranker_health',
- status: 'warn',
- message: `Could not check reranker audit: ${msg}`,
- };
- }
-}
-
-/**
- * v0.41.18.0 batch_retry_health doctor check (codex H-9 thresholds).
- *
- * Surfaces sustained Supavisor circuit-breaker incidents from the
- * engine-level batch retry wrap. Reads the last 24h of audit events from
- * `~/.gbrain/audit/batch-retry-YYYY-Www.jsonl`.
- *
- * Threshold ladder (codex H-9 — avoid permanent noise from one historical blip):
- * ok — zero exhausted events in 24h, OR <3 exhausted from a single site
- * warn — >=3 exhausted from same site in 24h, OR >=5 cross-site
- * fail — >=20 exhausted in 24h (sustained breaker; operator intervention)
- *
- * Also surfaces (codex H-9 corruption tolerance):
- * - corrupted_lines count when audit JSONL has malformed rows
- * - files_unreadable count for permission errors (NOT ENOENT which is normal)
- *
- * Also surfaces (codex M-10): runs resolveBulkRetryOpts(process.env) at
- * startup so bad GBRAIN_BULK_* config fails at doctor time, not first-retry.
- */
-/**
- * queue_health: Postgres Minion queue diagnostics.
- *
- * Includes the original stalled/depth/memory/prompt checks plus the #2557
- * no-worker signal: old `embed-backfill` jobs waiting on a queue with no live
- * registered worker for that queue. That catches the default deployment shape
- * where `sync` enqueues deferred embedding work but the operator never started
- * `gbrain jobs work` or a supervisor.
- */
-export async function computeQueueHealthCheck(
- engine: BrainEngine,
- opts: {
- waitingDepthThreshold?: number;
- oldWaitingHours?: number;
- readWorkers?: () => Array<{ queue: string }>;
- } = {},
-): Promise<Check> {
- if (engine.kind === 'pglite') {
- return {
- name: 'queue_health',
- status: 'ok',
- message: 'Skipped (PGLite — no multi-process worker surface)',
- };
- }
-
- try {
- // issue #1801: column is `status`, not `state` (schema.sql:780).
- const stalledRows: Array<{ id: number; name: string; started_at: string }> =
- await engine.executeRaw(
- `SELECT id, name, started_at::text AS started_at
- FROM minion_jobs
- WHERE status = 'active'
- AND started_at IS NOT NULL
- AND started_at < now() - interval '1 hour'
- ORDER BY started_at ASC
- LIMIT 5`,
- );
-
- const threshold = opts.waitingDepthThreshold
- ?? _resolveEnvNumber('GBRAIN_QUEUE_WAITING_THRESHOLD', 10);
- const depthRows: Array<{ name: string; queue: string; depth: number }> =
- await engine.executeRaw(
- `SELECT name, queue, count(*)::int AS depth
- FROM minion_jobs
- WHERE status = 'waiting'
- GROUP BY name, queue
- HAVING count(*) > $1
- ORDER BY depth DESC
- LIMIT 5`,
- [threshold],
- );
-
- const rssKillRows: Array<{ cnt: number }> = await engine.executeRaw(
- `SELECT count(*)::int AS cnt
- FROM minion_jobs
- WHERE status IN ('dead', 'failed')
- AND finished_at > now() - interval '24 hours'
- AND error_text = 'aborted: watchdog'`,
- );
- const rssKillCount = Number(rssKillRows[0]?.cnt ?? 0);
-
- const promptTooLongRows: Array<{ cnt: number }> = await engine.executeRaw(
- `SELECT count(*)::int AS cnt
- FROM minion_jobs
- WHERE name = 'subagent'
- AND status = 'dead'
- AND finished_at > now() - interval '24 hours'
- AND error_text LIKE 'prompt_too_long:%'`,
- );
- const promptTooLongCount = Number(promptTooLongRows[0]?.cnt ?? 0);
-
- const oldWaitingHours = opts.oldWaitingHours
- ?? _resolveEnvNumber('GBRAIN_QUEUE_NO_WORKER_WARN_HOURS', 1);
- const oldWaitingRows: Array<{
- name: string;
- queue: string;
- depth: number;
- oldest_age_seconds: number;
- }> = await engine.executeRaw(
- `SELECT name,
- queue,
- count(*)::int AS depth,
- EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS oldest_age_seconds
- FROM minion_jobs
- WHERE status = 'waiting'
- AND name = 'embed-backfill'
- GROUP BY name, queue
- HAVING min(created_at) < now() - ($1::text::interval)
- ORDER BY oldest_age_seconds DESC
- LIMIT 5`,
- [`${oldWaitingHours} hours`],
- );
-
- // Read the live-worker registry unconditionally (was: only when old
- // embed-backfill rows existed) — the structured `details.worker_alive`
- // below needs it on every run. Cheap: one directory enumeration.
- const workers = opts.readWorkers
- ? opts.readWorkers()
- : (await import('../core/minions/worker-registry.ts')).readWorkers();
- const liveWorkerQueues = new Set(workers.map((w) => w.queue));
-
- // Minions-visibility wave: structured details so machine callers stop
- // parsing prose. depth = total waiting jobs; oldest_age_seconds = age of
- // the oldest waiting job (null when the queue is empty); worker_alive =
- // every queue holding waiting work has a live registered worker
- // (vacuously true with zero waiting jobs). Messages stay unchanged.
- // Perf note (twin of buildQueueDepths in status.ts): WHERE constrains
- // only `status` — the second column of the (queue, status, updated_at)
- // wedge index — so this GROUP BY full-scans minion_jobs today. Acceptable
- // at doctor frequency over pruned waiting sets; a partial
- // (queue, created_at) WHERE status='waiting' index is the fix if hot.
- const waitingByQueue: Array<{
- queue: string;
- depth: number | string;
- oldest_age_seconds: number | string | null;
- }> = await engine.executeRaw(
- `SELECT queue,
- count(*)::int AS depth,
- EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS oldest_age_seconds
- FROM minion_jobs
- WHERE status = 'waiting'
- GROUP BY queue`,
- );
- const details: Record<string, unknown> = {
- depth: waitingByQueue.reduce((n, r) => n + Number(r.depth), 0),
- oldest_age_seconds: waitingByQueue.reduce<number | null>(
- (max, r) => {
- const age = r.oldest_age_seconds === null ? null : Number(r.oldest_age_seconds);
- if (age === null) return max;
- return max === null ? age : Math.max(max, age);
- },
- null,
- ),
- worker_alive: waitingByQueue.every((r) => liveWorkerQueues.has(r.queue)),
- };
-
- const problems: string[] = [];
- if (stalledRows.length > 0) {
- const sample = stalledRows
- .map(r => `#${r.id}(${r.name})`)
- .join(', ');
- problems.push(
- `${stalledRows.length} stalled-forever job(s): ${sample}. ` +
- `Fix: gbrain jobs get <id> to inspect; gbrain jobs cancel <id> to force-kill.`
- );
- }
- if (depthRows.length > 0) {
- const sample = depthRows
- .map(r => `${r.name}@${r.queue}=${r.depth}`)
- .join(', ');
- problems.push(
- `waiting-queue depth exceeds ${threshold} for: ${sample}. ` +
- `Fix: set maxWaiting on the submitter (or raise GBRAIN_QUEUE_WAITING_THRESHOLD).`
- );
- }
- for (const row of oldWaitingRows) {
- if (liveWorkerQueues.has(row.queue)) continue;
- const hours = Math.max(1, Math.round(Number(row.oldest_age_seconds ?? 0) / 3600));
- problems.push(
- `${row.depth} ${row.name} job(s) have waited on queue '${row.queue}' for up to ${hours}h ` +
- `and no live worker is registered for that queue. ` +
- `Start one with \`gbrain jobs work --queue ${row.queue}\` or ` +
- `\`gbrain jobs supervisor start --queue ${row.queue}\`.`
- );
- }
- if (rssKillCount > 0) {
- problems.push(
- `${rssKillCount} job(s) dead-lettered for RSS-watchdog memory-limit kills in last 24h. ` +
- `Fix: raise the limit (e.g. \`gbrain jobs work --max-rss 4096\`) or opt out (\`--max-rss 0\`). ` +
- `→ see worker_oom_loop for the cap + fix (the authoritative OOM-loop signal).`
- );
- }
- if (promptTooLongCount > 0) {
- problems.push(
- `${promptTooLongCount} subagent job(s) dead-lettered with prompt_too_long in last 24h. ` +
- `Dream/synthesize transcripts exceeded the model's input context. ` +
- `Fix: \`gbrain dream --phase synthesize --dry-run --json\` to identify fat transcripts; ` +
- `set \`dream.synthesize.max_prompt_tokens\` to bound the per-chunk budget, or use a ` +
- `larger-context model (Opus 4.7 = 1M tokens vs Sonnet 4.6 = 200K).`
- );
- }
-
- if (problems.length === 0) {
- return {
- name: 'queue_health',
- status: 'ok',
- message: `No stalled-forever jobs; no queue over depth ${threshold}; no old embed-backfill jobs without a worker.`,
- details,
- };
- }
- return {
- name: 'queue_health',
- status: 'warn',
- message: problems.join(' '),
- details,
- };
- } catch (e) {
- return {
- name: 'queue_health',
- status: 'warn',
- message: `queue_health scan skipped: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * issue #1801 — `wedged_queue` check. Surfaces the alive-but-wedged-worker
- * signature (a queue with claimable work waiting, zero live-lock active jobs,
- * and stale completions) as a health ERROR, so an operator / the daily doctor
- * catches a silent processing halt in minutes, not 15 hours.
- *
- * Postgres-only (PGLite has no multi-process worker surface). Grouped BY queue
- * (Codex #15) so a healthy worker on one queue can't mask a wedged one.
- * `active_healthy` counts only live-lock active rows, so an expired-lock active
- * row (a worker that died mid-job) does NOT mask the wedge (Codex #6). The
- * check is conservative for the advisory surface: it fails only on stale-after-
- * progress (mins_since_completion > threshold, non-null); a queue that never
- * completed anything is left to the supervisor's startup-grace-aware watchdog
- * to avoid crying wolf on a freshly-submitted queue with no worker yet.
- *
- * Exported so `test/doctor.test.ts` drives it directly. Reads
- * GBRAIN_WEDGED_QUEUE_WARN_MINUTES (default 15).
- */
-export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Check> {
- if (engine.kind !== 'postgres') {
- return { name: 'wedged_queue', status: 'ok', message: 'PGLite — no queue to check' };
- }
- const thresholdMin = _resolveEnvNumber('GBRAIN_WEDGED_QUEUE_WARN_MINUTES', 15);
- try {
- const rows = await engine.executeRaw<{
- queue: string;
- active_healthy: string | number;
- waiting: string | number;
- mins_since_completion: string | number | null;
- }>(
- `SELECT queue,
- count(*) FILTER (WHERE status = 'active' AND lock_until > now()) AS active_healthy,
- count(*) FILTER (WHERE status = 'waiting') AS waiting,
- EXTRACT(EPOCH FROM (now() - max(updated_at) FILTER (WHERE status = 'completed'))) / 60
- AS mins_since_completion
- FROM minion_jobs
- GROUP BY queue`,
- );
- const wedged: string[] = [];
- for (const r of rows) {
- const activeHealthy = Number(r.active_healthy ?? 0);
- const waiting = Number(r.waiting ?? 0);
- const mins = r.mins_since_completion === null ? null : Number(r.mins_since_completion);
- // Conservative: only flag stale-after-progress (non-null mins past
- // threshold). The null-completions case is the supervisor's job.
- if (activeHealthy === 0 && waiting > 0 && mins !== null && mins > thresholdMin) {
- wedged.push(`'${r.queue}' (${waiting} waiting, 0 active, ${Math.round(mins)}m since last completion)`);
- }
- }
- if (wedged.length === 0) {
- return { name: 'wedged_queue', status: 'ok', message: 'No wedged queues' };
- }
- return {
- name: 'wedged_queue',
- status: 'fail',
- message:
- `Wedged queue(s) — worker alive but not claiming work: ${wedged.join('; ')}. ` +
- `Restart the worker so it rebuilds a fresh DB pool: ` +
- `\`gbrain jobs supervisor stop && gbrain jobs supervisor start\`, ` +
- `then \`gbrain jobs retry <id>\` on any dead-lettered jobs.`,
- details: { wedged_queues: wedged.length, threshold_minutes: thresholdMin },
- };
- } catch (e) {
- // Pre-migration brains / transient errors: advisory check stays ok.
- return {
- name: 'wedged_queue',
- status: 'ok',
- message: `Skipped (${e instanceof Error ? e.message : String(e)})`,
- };
- }
-}
-
-/**
- * #2194 fix #5: warn when autopilot's per-tick fan-out exceeds the worker's
- * effective concurrency. Fanning out more cycles than there are worker slots
- * guarantees waiters that race the stalled-sweeper — a silent misconfig today.
- * Advisory (started-event concurrency is fine here; the behavior-changing clamp
- * in resolveEffectiveFanoutMax is the one that gates on liveness). Surfaces only
- * when a supervisor has actually started (no noise on never-supervised brains).
- */
-export async function computeAutopilotFanoutConcurrencyCheck(engine: BrainEngine): Promise<Check> {
- if (engine.kind !== 'postgres') {
- return { name: 'autopilot_fanout_concurrency', status: 'ok', message: 'PGLite — single-writer, fan-out is 1' };
- }
- try {
- const { resolveFanoutMax, readSupervisorConcurrency } = await import('./autopilot-fanout.ts');
- const concurrency = await readSupervisorConcurrency('default');
- if (concurrency === null) {
- return { name: 'autopilot_fanout_concurrency', status: 'ok', message: 'No supervisor observed — skipping fan-out/concurrency check' };
- }
- const fanoutMax = await resolveFanoutMax(engine);
- const effectiveSlots = Math.max(1, concurrency - 1);
- if (fanoutMax > effectiveSlots) {
- return {
- name: 'autopilot_fanout_concurrency',
- status: 'warn',
- message:
- `autopilot fan-out (${fanoutMax}/tick) exceeds worker concurrency (${concurrency}). ` +
- `Surplus cycles queue behind the worker and race the stalled-sweeper. ` +
- `Lower fan-out: \`gbrain config set autopilot.fanout_max_per_tick ${effectiveSlots}\`, ` +
- `or raise the supervisor's \`--concurrency\` to ${fanoutMax + 1}. ` +
- `(The clamp in autopilot does this automatically unless disabled.)`,
- details: { fanout_max: fanoutMax, concurrency, effective_slots: effectiveSlots },
- };
- }
- return {
- name: 'autopilot_fanout_concurrency',
- status: 'ok',
- message: `fan-out ${fanoutMax}/tick within worker concurrency ${concurrency}`,
- };
- } catch (e) {
- return { name: 'autopilot_fanout_concurrency', status: 'ok', message: `Skipped (${e instanceof Error ? e.message : String(e)})` };
- }
-}
-
-export async function checkBatchRetryHealth(_engine: BrainEngine): Promise<Check> {
- try {
- // Codex M-10: surface bad env config at doctor time.
- try {
- const { resolveBulkRetryOpts } = await import('../core/retry.ts');
- resolveBulkRetryOpts();
- } catch (e) {
- return {
- name: 'batch_retry_health',
- status: 'warn',
- message: `GBRAIN_BULK_* env override invalid: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-
- const { readRecentBatchRetryEvents } = await import('../core/audit/batch-retry-audit.ts');
- const result = readRecentBatchRetryEvents(24);
-
- // Surface corruption / permission errors at warn so operators investigate.
- if (result.files_unreadable > 0) {
- return {
- name: 'batch_retry_health',
- status: 'warn',
- message: `${result.files_unreadable} audit file(s) unreadable (permission / IO). Fix: check ~/.gbrain/audit/ (or $GBRAIN_AUDIT_DIR if set).`,
- };
- }
-
- const exhausted = result.events.filter((e) => e.outcome === 'exhausted');
- const successful = result.events.filter((e) => e.outcome === 'success');
-
- // v0.41.25.0 (#1570) — read the db-disconnect audit so the existing
- // batch_retry_health check surfaces ALL connection-incident signal in
- // one place (per codex finding 11: extend, don't add a new check).
- // Disconnect events are informational — every CLI command legitimately
- // disconnects at end-of-life. The value is the most_recent_caller
- // frame: when the v0.41.25 retry reconnect callback fires, the
- // operator runs `gbrain doctor` and the stack trace tells them which
- // code path triggered the mid-process disconnect. v0.41.26 fixes
- // that specific ownership boundary.
- let disconnectNote = '';
- try {
- const { readRecentDbDisconnects } = await import('../core/audit/db-disconnect-audit.ts');
- const dc = readRecentDbDisconnects(24);
- if (dc.count > 0) {
- // First-line of stack trace is the caller of logDbDisconnect; show
- // it so the operator sees something compact in human output.
- const firstFrame = (dc.most_recent_caller ?? '').split('\n')[0]?.trim() ?? '';
- const frameSlug = firstFrame.length > 0 ? ` (most recent caller: ${firstFrame.slice(0, 200)})` : '';
- disconnectNote = ` Disconnect-call audit: ${dc.count} call(s) in 24h${frameSlug}.`;
- }
- } catch { /* audit module unavailable; older brain, fine */ }
-
- if (exhausted.length === 0) {
- const note = result.corrupted_lines > 0
- ? ` (note: ${result.corrupted_lines} corrupt JSONL line(s) skipped)`
- : '';
- const recoveredNote = successful.length > 0
- ? ` ${successful.length} transient retry(s) succeeded.`
- : '';
- return {
- name: 'batch_retry_health',
- status: 'ok',
- message: `No exhausted batch retries in last 24h.${recoveredNote}${note}${disconnectNote}`,
- };
- }
-
- // Group exhausted events by site for per-site threshold detection.
- const bySite = new Map<string, number>();
- for (const e of exhausted) bySite.set(e.site, (bySite.get(e.site) ?? 0) + 1);
- const worstSite = [...bySite.entries()].sort((a, b) => b[1] - a[1])[0];
-
- // codex H-9 fail threshold: >=20 in 24h = sustained breaker.
- if (exhausted.length >= 20) {
- return {
- name: 'batch_retry_health',
- status: 'fail',
- message: `${exhausted.length} exhausted batch retries in last 24h (worst: ${worstSite[0]} = ${worstSite[1]}). Sustained circuit-breaker incident. Fix: check pooler status; consider raising GBRAIN_BULK_MAX_RETRIES or moving to direct-connection.${disconnectNote}`,
- };
- }
-
- // warn thresholds: >=3 same-site OR >=5 cross-site.
- if (worstSite[1] >= 3 || exhausted.length >= 5) {
- return {
- name: 'batch_retry_health',
- status: 'warn',
- message: `${exhausted.length} exhausted batch retries in last 24h (worst: ${worstSite[0]} = ${worstSite[1]}). Tune via GBRAIN_BULK_MAX_RETRIES / GBRAIN_BULK_RETRY_MAX_MS.${disconnectNote}`,
- };
- }
-
- // Single-incident noise tolerance.
- return {
- name: 'batch_retry_health',
- status: 'ok',
- message: `${exhausted.length} exhausted batch retry(s) in last 24h (below per-site threshold of 3)${disconnectNote}`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'batch_retry_health',
- status: 'warn',
- message: `Could not check batch_retry audit: ${msg}`,
- };
- }
-}
-
-/**
- * v0.40.4 graph_signals_coverage doctor check.
- *
- * Surfaces whether the brain's link density is high enough for the
- * v0.40.4 graph-signals stage to meaningfully fire. Logic:
- *
- * 1. Resolve the active graph_signals setting (config override OR
- * mode-bundle default). When OFF → silent ok (no metric noise on
- * installs that don't use the feature).
- *
- * 2. When ON, compute the global density: % of pages with >=1
- * inbound link. This is a STRUCTURAL lower bound — top-K
- * subgraphs need at least some edges to fire any signal.
- * Codex outside-voice #14 noted this is an imperfect proxy
- * (T-todo-5 will replace it with actual fire-rate measurement
- * from search-stats after 30 days of data).
- *
- * 3. >=30% → ok with the percentage.
- * <10% → warn (mismatch: signal enabled but link graph is too
- * sparse to fire often; fix: `gbrain extract all` to
- * populate the link graph from frontmatter + markdown).
- * 10-29% → ok with note (signal will fire occasionally).
- *
- * Errors during the SQL count → warn with the underlying message.
- * Best-effort: this check never breaks doctor.
- */
-export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Check> {
- try {
- // Resolve the active graph_signals setting. Read the config key
- // explicitly; when unset, fall through to the mode bundle default.
- const cfgVal = await engine.getConfig('search.graph_signals');
- let enabled: boolean;
- if (cfgVal !== null && cfgVal !== undefined) {
- // v0.40.4 codex F1 — case-insensitive + trim, parity with
- // loadOverridesFromConfig in src/core/search/mode.ts. Without
- // this, `gbrain config set search.graph_signals TRUE` enables
- // the feature in production but doctor reports "disabled".
- const v = cfgVal.trim().toLowerCase();
- enabled = v === 'true' || v === '1';
- } else {
- // Mode bundle default. Read search.mode (case-insensitive + trim
- // parity with isSearchMode + DEFAULT_SEARCH_MODE fallback).
- const modeRaw = await engine.getConfig('search.mode');
- const modeVal = typeof modeRaw === 'string' ? modeRaw.trim().toLowerCase() : '';
- const mode = modeVal === 'conservative' || modeVal === 'tokenmax' ? modeVal : 'balanced';
- // Hardcoded knowledge of the mode bundle defaults — keeps the
- // doctor check from pulling in the full search/mode.ts surface.
- enabled = mode !== 'conservative';
- }
-
- if (!enabled) {
- return {
- name: 'graph_signals_coverage',
- status: 'ok',
- message: 'graph_signals disabled — coverage not checked',
- };
- }
-
- // Compute global inbound-link density. Counts DISTINCT pages with
- // at least one inbound edge / total pages.
- const totalRows = await engine.executeRaw(`SELECT COUNT(*)::int AS n FROM pages WHERE deleted_at IS NULL`);
- const totalPages = Number((totalRows as any)[0]?.n ?? 0);
-
- if (totalPages === 0) {
- return {
- name: 'graph_signals_coverage',
- status: 'ok',
- message: 'Empty brain — no pages to compute coverage against',
- };
- }
-
- const linkedRows = await engine.executeRaw(
- `SELECT COUNT(DISTINCT l.to_page_id)::int AS n
- FROM links l
- JOIN pages p ON p.id = l.to_page_id
- WHERE p.deleted_at IS NULL`
- );
- const linkedPages = Number((linkedRows as any)[0]?.n ?? 0);
- const pct = (linkedPages / totalPages) * 100;
- const pctStr = pct.toFixed(1);
-
- if (pct < 10) {
- return {
- name: 'graph_signals_coverage',
- status: 'warn',
- message: `graph_signals enabled but only ${pctStr}% of pages have inbound links (<10%). Signal will rarely fire. Fix: \`gbrain extract all\` to populate the link graph from frontmatter + markdown.`,
- };
- }
-
- return {
- name: 'graph_signals_coverage',
- status: 'ok',
- message: pct >= 30
- ? `${pctStr}% of pages have inbound links (>=30% — graph signals fire on most queries)`
- : `${pctStr}% of pages have inbound links (10-29% — graph signals fire occasionally)`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'graph_signals_coverage',
- status: 'warn',
- message: `Could not check graph_signals_coverage: ${msg}`,
- };
- }
-}
-
-/**
- * v0.37.0 brainstorm_health doctor check.
- *
- * Surfaces three readiness signals for `gbrain brainstorm` / `gbrain lsd`:
- *
- * 1. Migration v79 applied — the `pages.last_retrieved_at` column exists.
- * If missing, LSD's stale-page signal degrades silently (corpus-sampling
- * fallback only). Fix: `gbrain apply-migrations --yes`.
- *
- * 2. search.track_retrieval — when explicitly off, LSD never accumulates
- * stale signal (every page stays at NULL last_retrieved_at). Default-on
- * is fine; explicit-off is a warning so the user notices the setting.
- * Fix: `gbrain config set search.track_retrieval true`.
- *
- * 3. Calibration cold-start — the latest calibration profile has empty
- * `active_bias_tags`. brainstorm + LSD judge fall back to no-anti-bias
- * mode with a stderr warning at run time; this surfaces it earlier.
- * Fix: `gbrain calibration --regenerate` once enough takes are resolved.
- *
- * Returns the FIRST non-ok signal as the status — column-missing dominates,
- * then disabled-tracking, then cold-start. All three are non-blocking warnings;
- * brainstorm + LSD still work, just with degraded signal.
- */
-export async function checkBrainstormHealth(engine: BrainEngine): Promise<Check> {
- // (1) Column probe — fast, single-query.
- try {
- const probeRows = await engine.executeRaw<{ exists: boolean }>(
- `SELECT EXISTS (
- SELECT 1 FROM information_schema.columns
- WHERE table_name = 'pages' AND column_name = 'last_retrieved_at'
- ) AS exists`,
- []
- );
- const columnPresent = probeRows[0]?.exists === true;
- if (!columnPresent) {
- return {
- name: 'brainstorm_health',
- status: 'warn',
- message: `pages.last_retrieved_at column missing. LSD stale-bias degraded to corpus-sampling. Fix: \`gbrain apply-migrations --yes\``,
- };
- }
- } catch (e) {
- // Information schema may not be queryable on every engine variant.
- // Don't fail the doctor over this — degrade to skip.
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'brainstorm_health',
- status: 'warn',
- message: `Could not probe pages.last_retrieved_at (${msg}); brainstorm/lsd may run with degraded signal.`,
- };
- }
-
- // (2) search.track_retrieval — explicit-off surfaces as a warning.
- try {
- const trackCfg = await engine.getConfig('search.track_retrieval');
- if (trackCfg === 'false' || trackCfg === '0' || trackCfg === 'off' || trackCfg === 'no') {
- return {
- name: 'brainstorm_health',
- status: 'warn',
- message: `search.track_retrieval is explicitly off — LSD's stale-page signal never accumulates. Fix: \`gbrain config set search.track_retrieval true\` (or accept and use brainstorm only).`,
- };
- }
- } catch {
- // Config read miss is benign; default-on applies.
- }
-
- // (3) Calibration cold-start — empty active_bias_tags.
- try {
- const calibRows = await engine.executeRaw<{ active_bias_tags: string[] | null }>(
- `SELECT active_bias_tags
- FROM calibration_profiles
- ORDER BY generated_at DESC
- LIMIT 1`,
- []
- );
- if (calibRows.length === 0) {
- return {
- name: 'brainstorm_health',
- status: 'ok',
- message: `Migration v79 applied; tracking enabled. Calibration profile not yet generated — brainstorm/lsd will run unbiased until enough takes are resolved.`,
- };
- }
- const tags = calibRows[0].active_bias_tags;
- if (!Array.isArray(tags) || tags.length === 0) {
- return {
- name: 'brainstorm_health',
- status: 'ok',
- message: `Migration v79 applied; tracking enabled. Calibration cold-start (no active_bias_tags) — judge runs unbiased. Fix when ready: \`gbrain calibration --regenerate\`.`,
- };
- }
- return {
- name: 'brainstorm_health',
- status: 'ok',
- message: `Migration v79 applied; tracking enabled; calibration profile with ${tags.length} bias tag(s) loaded.`,
- };
- } catch {
- // Pre-v0.36.1 brain (no calibration_profiles table). Brainstorm/lsd still
- // work without anti-bias context — orchestrator stderr-warns at run time.
- return {
- name: 'brainstorm_health',
- status: 'ok',
- message: `Migration v79 applied; tracking enabled. calibration_profiles table missing (pre-v0.36.1 brain) — judge runs unbiased.`,
- };
- }
-}
-
-/**
- * v0.36.0.0 (A5): ze_embedding_health doctor check.
- *
- * When the configured embedding_model starts with `zeroentropyai:`, verify
- * the API key is set. Doesn't make a network call by default — the existing
- * `gbrain models doctor` probe covers that, and we don't want every
- * `gbrain doctor` run to spend tokens. Surfaces a paste-ready fix when the
- * key is missing.
- */
-export async function checkZeEmbeddingHealth(engine: BrainEngine): Promise<Check> {
- try {
- // v0.37 fix wave (Lane E.3 + CDX2-10): read from gateway, not DB.
- // The file plane is canonical post-v0.37; the DB config table is
- // schema-applied metadata. Reading DB here would skip the warning
- // when the user has a fresh install with no DB config row yet.
- const { getEmbeddingModel } = await import('../core/ai/gateway.ts');
- const { loadConfigFileOnly } = await import('../core/config.ts');
- let model = '';
- try { model = getEmbeddingModel(); } catch { /* gateway unconfigured */ }
- if (!model.startsWith('zeroentropyai:')) {
- return {
- name: 'ze_embedding_health',
- status: 'ok',
- message: `Configured embedding model "${model || 'default'}" is not ZeroEntropy — skip.`,
- };
- }
- const envKey = process.env.ZEROENTROPY_API_KEY;
- // File plane: zeroentropy_api_key on GBrainConfig (added by C.3).
- const fileKey = loadConfigFileOnly()?.zeroentropy_api_key;
- if (!envKey && !fileKey) {
- return {
- name: 'ze_embedding_health',
- status: 'warn',
- message:
- `embedding_model="${model}" but ZEROENTROPY_API_KEY is not set. ` +
- `Fix: get a key at https://dashboard.zeroentropy.dev and either ` +
- `\`export ZEROENTROPY_API_KEY=...\` or edit ~/.gbrain/config.json ` +
- `to add "zeroentropy_api_key": "...". (gbrain config set writes the DB plane, which the embed pipeline ignores.)`,
- };
- }
- return {
- name: 'ze_embedding_health',
- status: 'ok',
- message: `embedding_model="${model}" with key configured`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'ze_embedding_health',
- status: 'warn',
- message: `Could not check ZE embedding health: ${msg}`,
- };
- }
-}
-
-/**
- * provider_sunset doctor check (#3390 follow-up).
- *
- * Detects a brain whose EFFECTIVE embedding model (gateway-resolved, which is
- * how default-config brains land on the shipped default) is on a provider
- * with an announced hosted-API shutdown, and prints a paste-ready migration
- * command with the brain's ACTUAL `content_chunks.embedding` column width
- * filled in — not the config value, which can drift. Keeping the current
- * width avoids a needless dimension transition + index rebuild when the
- * target supports it.
- *
- * Unlike the one-shot upgrade banner (`ze_sunset_notice_shown`), this fires
- * on every `gbrain doctor` run until the brain is off the provider —
- * warn before the shutdown date; fail after it ONLY when the brain is
- * actually exposed (embedded vectors exist in the affected column, so
- * retrieval is genuinely down). A zero-vector brain whose config merely
- * RESOLVES to the dead default stays warn — otherwise every stock fresh
- * install (and every doctor-as-CI-gate) starts exiting 1 on the date with
- * no code change. Suppress entirely (accepted-risk installs) via
- * `gbrain config set doctor.suppress_provider_sunset true`.
- * No network call; one catalog query for the column width.
- *
- * `now` is injectable so tests can pin BOTH sides of the date without
- * waiting for the calendar (the date itself is a compile-time constant).
- */
-export async function checkProviderSunset(engine: BrainEngine, now: number = Date.now()): Promise<Check> {
- const name = 'provider_sunset';
- try {
- const suppressed = await engine.getConfig('doctor.suppress_provider_sunset').catch(() => null);
- if (suppressed === 'true' || suppressed === '1') {
- return {
- name,
- status: 'ok',
- message: 'Check suppressed via doctor.suppress_provider_sunset (unset it to re-enable).',
- };
- }
- const { DEFAULT_EMBEDDING_MODEL, ZEROENTROPY_SUNSET_DATE } = await import('../core/ai/defaults.ts');
- // Effective model: gateway when configured (file/env plane, the runtime
- // truth); the shipped default otherwise — an unset-config brain resolves
- // to the default at runtime, so it is just as affected.
- let model = DEFAULT_EMBEDDING_MODEL;
- try {
- const { getEmbeddingModel } = await import('../core/ai/gateway.ts');
- model = getEmbeddingModel();
- } catch {
- // Gateway unconfigured — runtime resolves the shipped default.
- }
- // Effective reranker: resolve through the SAME plane search actually
- // reranks with — resolveSearchMode (mode bundle + search.reranker.*
- // config overrides; hybrid.ts passes `resolvedMode.reranker_model`).
- // The gateway plane is unset by default while balanced/tokenmax rerank
- // with the bundle's zeroentropyai model — reading the gateway here
- // would false-ok the exact brains this check exists to protect.
- let reranker: string | undefined;
- try {
- const { loadSearchModeConfig, resolveSearchMode } = await import('../core/search/mode.ts');
- const knobs = resolveSearchMode(await loadSearchModeConfig(engine));
- if (knobs.reranker_enabled) reranker = knobs.reranker_model;
- } catch {
- // Mode resolution failed — make no reranker-exposure claim.
- }
- const onSunsetEmbedding = model.startsWith('zeroentropyai:');
- const onSunsetReranker = !!reranker?.startsWith('zeroentropyai:');
- // Custom embedding columns can route queries through a ZE-backed model
- // even when the primary embedding + reranker are clear — without this arm
- // the check reports ok while those columns die on the date.
- let zeColumns: string[] = [];
- try {
- const { detectZeCustomColumns } = await import('../core/ze-exposure.ts');
- zeColumns = (await detectZeCustomColumns(engine)).columns;
- } catch {
- // Probe failed — make no custom-column claim.
- }
- const onSunsetColumns = zeColumns.length > 0;
- if (!onSunsetEmbedding && !onSunsetReranker && !onSunsetColumns) {
- return {
- name,
- status: 'ok',
- message: `No configured provider has an announced shutdown (embedding: ${model}).`,
- };
- }
- const past = now >= Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`);
- const parts: string[] = [];
- let hasVectors = false;
- if (onSunsetEmbedding) {
- let dims: number | null = null;
- try {
- const { readContentChunksEmbeddingDim } = await import('../core/embedding-dim-check.ts');
- dims = (await readContentChunksEmbeddingDim(engine)).dims;
- } catch {
- // Column probe failed (fresh/odd brain) — omit --dim from the hint.
- }
- try {
- const rows = await engine.executeRaw(
- `SELECT 1 AS one FROM content_chunks WHERE embedding IS NOT NULL LIMIT 1`,
- );
- hasVectors = rows.length > 0;
- } catch {
- // Probe failed (fresh/odd brain) — no exposure claim, warn-only.
- }
- parts.push(
- past
- ? hasVectors
- ? `embedding_model="${model}": the hosted API shut down on ${ZEROENTROPY_SUNSET_DATE} — semantic retrieval is offline (queries can no longer be embedded against your existing vectors).`
- : `embedding_model="${model}": the hosted API shut down on ${ZEROENTROPY_SUNSET_DATE}. No embedded vectors exist yet, so retrieval is not impacted — but embedding will fail until the config points elsewhere.`
- : `embedding_model="${model}": the hosted API shuts down on ${ZEROENTROPY_SUNSET_DATE}. On that date semantic retrieval stops entirely — existing vectors become unqueryable (query embedding uses the same endpoint), not just new content.`,
- );
- // v0.46.3: the paste-ready fix is TARGET-AWARE on dimensions. Voyage's
- // valid widths are {256, 512, 1024, 2048} — blindly preserving this
- // brain's actual width (usually 1280) would emit a command Voyage
- // rejects. OpenAI text-3 supports flexible widths up to its native
- // size, so the keep-width form is offered only when valid there.
- const openaiDimFlag = dims && dims <= 1536 ? ` --dim ${dims}` : ' --dim 1536';
- const openaiKeepsWidth = !!(dims && dims <= 1536);
- parts.push(
- `Two fixes, either works: ` +
- `[1] self-host the same model — zembed-1 weights are Apache-2.0; keep the zeroentropyai:zembed-1 id and point provider_base_urls.zeroentropyai at a ZE-wire-compatible endpoint (NOT a generic OpenAI-compatible server — the id speaks ZE's /models/embed dialect). Keeps every existing vector, no re-embed (docs/guides/embedding-migration.md). ` +
- `[2] migrate (resumable; preview cost first): ` +
- `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` +
- (dims && dims !== 1024 ? ` (${dims} is not a valid Voyage width — the migration rebuilds the index at 1024)` : '') +
- `; OpenAI alternative${openaiKeepsWidth ? ` keeps this brain's ${dims}d width` : ''}: ` +
- `gbrain migrate embeddings --to openai:text-embedding-3-small${openaiDimFlag} --dry-run.`,
- );
- }
- if (onSunsetReranker) {
- parts.push(
- `The reranker (${reranker}) is on the same provider; after the shutdown search falls back to unreranked ordering. ` +
- `Fix: gbrain config set search.reranker.model voyage:rerank-2.5 (needs VOYAGE_API_KEY), or disable: gbrain config set search.reranker.enabled false.`,
- );
- }
- if (onSunsetColumns) {
- parts.push(
- `Custom embedding column(s) backed by the shutting-down provider: ${zeColumns.join(', ')}. ` +
- `No automated off-ramp exists for custom columns yet (migrate embeddings covers the primary column only) — ` +
- `re-declare them on a new provider and re-embed (skills/migrations/v0.46.3.0.md).`,
- );
- }
- if (onSunsetEmbedding || onSunsetReranker || onSunsetColumns) {
- parts.push('Accepted the risk? Silence this check: gbrain config set doctor.suppress_provider_sunset true');
- }
- // fail = retrieval is ACTUALLY down (past the date AND embedded vectors
- // exist on the dead provider). Reranker-only exposure stays warn — search
- // fails open to unreranked ordering (degraded, not down).
- const failNow = past && onSunsetEmbedding && hasVectors;
- return { name, status: failNow ? 'fail' : 'warn', message: parts.join(' ') };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return { name, status: 'warn', message: `Could not check provider sunset status: ${msg}` };
- }
-}
-
-/**
- * v0.36.0.0 (A5): embedding_width_consistency doctor check.
- *
- * Cross-checks that `config.embedding_dimensions` matches the actual
- * `vector(N)` width on `content_chunks.embedding`. Drift here means an
- * embedding migration was interrupted mid-flight (schema changed but the
- * config write crashed, or vice versa). Recovery path: `gbrain migrate
- * embeddings` (resumable).
- */
-export async function checkEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
- try {
- // v0.37 fix wave (Lane E.1 + CDX-8): read from gateway, not DB. The
- // file plane is canonical post-v0.37; the DB config table is
- // schema-applied metadata. Reading DB here silently skipped the
- // check on fresh installs whose DB config row hadn't been written
- // yet.
- const { getEmbeddingDimensions, getEmbeddingModel } = await import('../core/ai/gateway.ts');
- let configDim: number;
- let resolvedModel: string;
- try {
- configDim = getEmbeddingDimensions();
- resolvedModel = getEmbeddingModel();
- } catch {
- return {
- name: 'embedding_width_consistency',
- status: 'ok',
- message: 'gateway not configured — skipping width check.',
- };
- }
- if (!Number.isFinite(configDim) || configDim <= 0) {
- return {
- name: 'embedding_width_consistency',
- status: 'warn',
- message: `gateway returned non-positive embedding dimension "${configDim}".`,
- };
- }
-
- // Read the actual column width via the existing helper (shared with
- // init.ts and embed.ts dim-mismatch pre-flight). One source of truth.
- const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../core/embedding-dim-check.ts');
- const existing = await readContentChunksEmbeddingDim(engine);
- if (!existing.exists) {
- return {
- name: 'embedding_width_consistency',
- status: 'warn',
- message: 'content_chunks.embedding column not found. Fix: run `gbrain init --migrate-only` or check schema.',
- };
- }
- if (existing.dims === null) {
- return {
- name: 'embedding_width_consistency',
- status: 'warn',
- message: 'content_chunks.embedding is not a vector type. Schema may be corrupt.',
- };
- }
- if (existing.dims !== configDim) {
- // E.2: use the engine-kind-branched recipe instead of pointing at
- // the no-op `gbrain config set` path. The recipe is paste-ready
- // for the brain's actual engine.
- const databasePath = (engine as { _savedConfig?: { database_path?: string } })._savedConfig?.database_path;
- const recipe = embeddingMismatchMessage({
- currentDims: existing.dims,
- requestedDims: configDim,
- requestedModel: resolvedModel,
- source: 'doctor',
- engineKind: engine.kind,
- databasePath,
- });
- return {
- name: 'embedding_width_consistency',
- status: 'warn',
- message:
- `Schema width mismatch: content_chunks.embedding is vector(${existing.dims}) but ` +
- `gateway resolved embedding_dimensions = ${configDim}.\n\n${recipe}`,
- };
- }
- return {
- name: 'embedding_width_consistency',
- status: 'ok',
- message: `Schema width (${existing.dims}d) matches gateway embedding_dimensions`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'embedding_width_consistency',
- status: 'warn',
- message: `Could not check embedding width: ${msg}`,
- };
- }
-}
-
-/**
- * v0.41.15.0 (T6, codex #19/#20) — facts.embedding column drift check.
- *
- * Parallel surface to `checkEmbeddingWidthConsistency` but for the
- * facts table. Migration v40 creates `facts.embedding` from
- * `config.embedding_dimensions` AT MIGRATION TIME — if the user later
- * swaps embedding providers (e.g. OpenAI 1536 → zembed-1 1280) without
- * re-running migrations, the column width drifts. The first insert
- * dies with the opaque pgvector "expected vector(N), got vector(M)"
- * error.
- *
- * Covers BOTH vector(N) AND halfvec(N) shapes (codex #19 — v40 falls
- * back to vector on pgvector < 0.7). Surfaces the paste-ready DROP
- * INDEX → ALTER USING → CREATE INDEX recipe from
- * `buildFactsAlterRecipe` instead of the unsafe REINDEX-only path
- * codex #18 caught in the original plan.
- */
-export async function checkFactsEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
- // PGLite ships a single pgvector version; column + config wire
- // together at initSchema time. No possible drift.
- if (engine.kind !== 'postgres') {
- return {
- name: 'facts_embedding_width_consistency',
- status: 'ok',
- message: 'Skipped on PGLite (single bundled pgvector version).',
- };
- }
-
- try {
- const {
- readFactsEmbeddingDim,
- buildFactsAlterRecipe,
- } = await import('../core/embedding-dim-check.ts');
-
- const col = await readFactsEmbeddingDim(engine);
- if (!col.exists) {
- return {
- name: 'facts_embedding_width_consistency',
- status: 'ok',
- message: 'facts.embedding column not present (pre-v40 brain or migration pending).',
- };
- }
- if (col.dims === null || col.columnType === null) {
- return {
- name: 'facts_embedding_width_consistency',
- status: 'warn',
- message: 'facts.embedding column type is unrecognized (not vector or halfvec). Schema may be corrupt.',
- };
- }
-
- let configDim: number;
- let resolvedModel = 'unknown';
- try {
- const { getEmbeddingDimensions, getEmbeddingModel } = await import('../core/ai/gateway.ts');
- configDim = getEmbeddingDimensions();
- resolvedModel = getEmbeddingModel();
- } catch {
- return {
- name: 'facts_embedding_width_consistency',
- status: 'ok',
- message: 'gateway not configured — facts.embedding width check skipped.',
- };
- }
- if (!Number.isFinite(configDim) || configDim <= 0) {
- return {
- name: 'facts_embedding_width_consistency',
- status: 'warn',
- message: `gateway returned non-positive embedding dimension "${configDim}".`,
- };
- }
-
- if (col.dims === configDim) {
- return {
- name: 'facts_embedding_width_consistency',
- status: 'ok',
- message:
- `facts.embedding is ${col.columnType}(${col.dims}) — matches gateway embedding_dimensions ` +
- `(${resolvedModel}).`,
- };
- }
-
- // Drift detected. Surface the paste-ready ALTER recipe.
- const recipe = buildFactsAlterRecipe(col.dims, configDim, col.columnType);
- return {
- name: 'facts_embedding_width_consistency',
- status: 'warn',
- message:
- `facts.embedding is ${col.columnType}(${col.dims}) but gateway resolved ` +
- `embedding_dimensions = ${configDim} (${resolvedModel}). ` +
- `New fact inserts will fail with an opaque pgvector error.\n\n` +
- recipe,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return {
- name: 'facts_embedding_width_consistency',
- status: 'warn',
- message: `Could not check facts.embedding width: ${msg}`,
- };
- }
-}
-
-/**
- * v0.32.3 [CDX-20]: surface mode + per-key override drift.
- *
- * Status stays `ok` (never warns; never docks health score). If
- * search.mode is unset → suggest picking one. If overrides contradict
- * the mode (e.g. mode=conservative but cache.enabled=false), say so in
- * the message and paste a `gbrain search modes --reset` fix command.
- */
-
-/**
- * v0.37.7.0 — Tier 5K source_routing_health (D5 lock: 200-page total cap).
- *
- * On a multi-source brain, sample up to 200 recent pages across all
- * non-default sources (per-source cap = min(50, ceil(200/N))). Warn
- * when:
- * - A non-default source has zero pages (silent-collapse-to-default
- * fingerprint from #1167 + #1222).
- * - The brain repo has a `.gitignore` file but
- * `sync.respect_gitignore` is unset/false (info-line nudge for
- * Tier 4I's opt-in flag).
- *
- * Cost-bounded: total cap of 200 means a 20-source CEO brain pays
- * 20*10 = 200 selects rather than 20*50 = 1000.
- */
-export async function checkSourceRoutingHealth(engine: BrainEngine): Promise<Check> {
- try {
- const sources = await engine.executeRaw<{ id: string }>(
- `SELECT id FROM sources WHERE id <> 'default'`,
- );
- if (sources.length === 0) {
- return { name: 'source_routing_health', status: 'ok', message: 'Single-source brain (no federation to check)' };
- }
- const perSourceCap = Math.min(50, Math.ceil(200 / Math.max(1, sources.length)));
- const emptySources: string[] = [];
- for (const s of sources) {
- const rows = await engine.executeRaw<{ n: string }>(
- `SELECT COUNT(*)::text AS n FROM pages WHERE source_id = $1 LIMIT $2`,
- [s.id, perSourceCap],
- );
- if (Number(rows[0]?.n ?? 0) === 0) {
- emptySources.push(s.id);
- }
- }
- if (emptySources.length > 0) {
- return {
- name: 'source_routing_health',
- status: 'warn',
- message:
- `${emptySources.length} non-default source(s) have zero pages: ${emptySources.join(', ')}. ` +
- `If you've recently run \`gbrain import --source-id <id>\` against these, the writes may have ` +
- `silently fallen to the default source pre-v0.37.7.0. Re-run with --source-id; verify via ` +
- `\`gbrain sources current --json\`.`,
- };
- }
- return {
- name: 'source_routing_health',
- status: 'ok',
- message: `Multi-source brain (${sources.length} non-default source(s)); all populated`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return { name: 'source_routing_health', status: 'warn', message: `Check failed: ${msg}` };
- }
-}
-
-/**
- * v0.40 Federated Sync v2 (T12) — federation_health.
- *
- * Per-source dashboard surface for the autopilot/operator.
- * Three-state per-source (then aggregated to single Check):
- *
- * ok — all federated sources synced within 1h AND embed coverage >=95%
- * (or chunks <100), AND failed_jobs_24h < 3
- * warn — any source has lag > 1h + federated, OR coverage < 95% with
- * chunks > 100, OR failed_jobs_24h >= 3
- * fail — any source has lag > 24h, OR coverage < 50% with chunks > 1000
- *
- * Single-source brain short-circuits to ok (no federation to check).
- * Each warning carries a paste-ready remediation hint.
- */
-export async function checkFederationHealth(engine: BrainEngine): Promise<Check> {
- try {
- const { loadAllSources } = await import('../core/sources-load.ts');
- const { computeAllSourceMetrics } = await import('../core/source-health.ts');
- const sources = await loadAllSources(engine, { includeArchived: false });
- if (sources.length <= 1) {
- return {
- name: 'federation_health',
- status: 'ok',
- message: 'Single-source brain (no federation to check)',
- };
- }
- const metrics = await computeAllSourceMetrics(engine, sources);
-
- const warns: string[] = [];
- const fails: string[] = [];
- for (const m of metrics) {
- // Fail thresholds first (most severe)
- if (m.lag_seconds !== null && m.lag_seconds > 24 * 3600) {
- fails.push(`${m.source_id}: stale ${Math.floor(m.lag_seconds / 3600)}h — run \`gbrain sync trigger --source ${m.source_id}\``);
- continue;
- }
- if (m.embed_coverage_pct < 50 && m.total_chunks > 1000) {
- fails.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage (${m.total_chunks.toLocaleString()} chunks) — run \`gbrain jobs submit embed-backfill --params '{"sourceId":"${m.source_id}"}'\``);
- continue;
- }
- // Warns
- if (m.federated && m.lag_seconds !== null && m.lag_seconds > 3600) {
- warns.push(`${m.source_id}: federated source ${Math.floor(m.lag_seconds / 3600)}h+ stale — run \`gbrain sync trigger --source ${m.source_id}\``);
- }
- if (m.embed_coverage_pct < 95 && m.total_chunks > 100) {
- warns.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage — run \`gbrain jobs submit embed-backfill --params '{"sourceId":"${m.source_id}"}'\``);
- }
- if (m.failed_jobs_24h >= 3) {
- warns.push(`${m.source_id}: ${m.failed_jobs_24h} failures in 24h — check \`gbrain jobs list --status failed\``);
- }
- }
-
- if (fails.length > 0) {
- return {
- name: 'federation_health',
- status: 'fail',
- message: `${fails.length} federation failure(s):\n ${fails.join('\n ')}`,
- };
- }
- if (warns.length > 0) {
- return {
- name: 'federation_health',
- status: 'warn',
- message: `${warns.length} federation warning(s):\n ${warns.join('\n ')}`,
- };
- }
- return {
- name: 'federation_health',
- status: 'ok',
- message: `${metrics.length} source(s) healthy (parallel sync, async embed)`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return { name: 'federation_health', status: 'warn', message: `Check failed: ${msg}` };
- }
-}
-
-/**
- * v0.37.7.0 — Tier 5L oauth_confidential_client_health.
- *
- * Confidential OAuth clients (token_endpoint_auth_method != 'none')
- * MUST have a non-NULL client_secret_hash. v0.34.1.0's #909 fix
- * intentionally NULLs the column for public PKCE clients; if any
- * row claims confidential auth but has NULL hash, that's the
- * regression fingerprint from #1166.
- */
-export async function checkOauthConfidentialHealth(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ client_id: string; method: string | null; hash: string | null }>(
- `SELECT client_id,
- token_endpoint_auth_method AS method,
- client_secret_hash AS hash
- FROM oauth_clients`,
- );
- if (rows.length === 0) {
- return { name: 'oauth_confidential_client_health', status: 'ok', message: 'No OAuth clients registered' };
- }
- const broken = rows.filter(r => {
- const isPublic = r.method === 'none';
- return !isPublic && (r.hash == null || r.hash === '');
- });
- if (broken.length > 0) {
- return {
- name: 'oauth_confidential_client_health',
- status: 'fail',
- message:
- `${broken.length} confidential OAuth client(s) have NULL/empty secret hash: ${broken.map(b => b.client_id).slice(0, 5).join(', ')}` +
- (broken.length > 5 ? ` (+${broken.length - 5} more)` : '') +
- `. Fix: \`gbrain auth revoke-client <id> && gbrain auth register-client …\` for each, OR \`gbrain upgrade\` if pre-v0.37.7.0.`,
- };
- }
- return {
- name: 'oauth_confidential_client_health',
- status: 'ok',
- message: `${rows.length} OAuth client(s) registered; all auth shapes consistent`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- // Pre-OAuth schema (oauth_clients table missing) → ok.
- if (msg.toLowerCase().includes('relation') && msg.toLowerCase().includes('does not exist')) {
- return { name: 'oauth_confidential_client_health', status: 'ok', message: 'OAuth not configured (skipping)' };
- }
- return { name: 'oauth_confidential_client_health', status: 'warn', message: `Check failed: ${msg}` };
- }
-}
-
-/**
- * v0.37.7.0 — Tier 5M autopilot_lock_scope (PID-safe hint per codex CF11).
- *
- * Detects stale autopilot lockfiles. When `GBRAIN_HOME` is set, the
- * canonical lock path lives under `gbrainPath('autopilot.lock')`.
- * If a hardcoded `~/.gbrain/autopilot.lock` ALSO exists outside the
- * current `GBRAIN_HOME`, that's a pre-v0.37.7.0 leftover or a
- * different brain's lock. Hint includes PID + a `ps -p` check so
- * the user verifies before deleting.
- */
-export function checkAutopilotLockScope(): Check {
- try {
- const canonical = gbrainPath('autopilot.lock');
- const home = process.env.HOME || '';
- const legacy = home ? `${home}/.gbrain/autopilot.lock` : '';
- // Same path → nothing to surface.
- if (canonical === legacy || !legacy || !existsSync(legacy)) {
- return { name: 'autopilot_lock_scope', status: 'ok', message: `Lock path: ${canonical}` };
- }
- // legacy lock exists outside GBRAIN_HOME. Read its PID for a safe hint.
- let owningPid: string = 'unknown';
- try {
- const raw = readFileSync(legacy, 'utf8').trim();
- if (/^\d+$/.test(raw)) owningPid = raw;
- } catch { /* unreadable → leave 'unknown' */ }
- return {
- name: 'autopilot_lock_scope',
- status: 'warn',
- message:
- `Stale lockfile outside GBRAIN_HOME: ${legacy} (owning PID: ${owningPid}). ` +
- `Verify with \`ps -p ${owningPid}\` — if the process is dead, \`rm ${legacy}\`. ` +
- `If alive, identify it (\`ps -fp ${owningPid}\`) and stop before deleting.`,
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return { name: 'autopilot_lock_scope', status: 'warn', message: `Check failed: ${msg}` };
- }
-}
-
-/**
- * v0.41.6.0 D3 — stale_locks doctor check.
- *
- * Surfaces every row in `gbrain_cycle_locks` whose `ttl_expires_at < NOW()`.
- * The TTL is the canonical staleness signal already trusted by
- * tryAcquireDbLock's UPDATE-on-conflict SQL — when TTL is in the past,
- * the next acquire attempt will sweep the row anyway. Doctor's job is to
- * warn the user proactively so the next sync doesn't get a surprise
- * "Another sync is in progress" with no fix hint.
- *
- * Paste-ready hint per stale lock: names the source-id from the
- * `gbrain-sync:<source>` lock-key shape so users can copy-paste the
- * exact recovery command.
- *
- * Out of scope (filed as v0.41+ follow-up TODO): detection of
- * "wedged but TTL-refreshing" locks where a refresh thread is alive
- * but the main work is blocked. Requires explicit heartbeat probe;
- * speculation until production data shows the case.
- */
-export async function checkStaleLocks(
- engine: BrainEngine,
- opts: { fix?: boolean; dryRun?: boolean } = {},
-): Promise<Check> {
- try {
- const { listStaleLocks, reapDeadHolderLocks } = await import('../core/db-lock.ts');
-
- // #1972: under `gbrain doctor --fix`, reap dead-holder sync/cycle locks
- // using the SAME namespace-scoped, host-scoped, snapshot-matched reaper the
- // cycle runs at start. This is the self-heal path for no-autopilot brains: a
- // brain that never runs `gbrain dream` never hits the cycle-start sweep, so
- // doctor --fix is how its crashed-sync locks get cleared. DB-only, so it's
- // orthogonal to (and unaffected by) the skills-dir --fix safety gate above.
- // Best-effort: a reap failure falls through to the warn path below.
- let reapedIds: string[] = [];
- if (opts.fix && !opts.dryRun) {
- try {
- reapedIds = (await reapDeadHolderLocks(engine)).reapedIds;
- } catch { /* fall through; listStaleLocks still surfaces remaining locks */ }
- }
- const reapedNote = reapedIds.length > 0
- ? `Reaped ${reapedIds.length} dead-holder lock(s): ${reapedIds.join(', ')}.`
- : null;
-
- const stale = await listStaleLocks(engine);
- if (stale.length === 0) {
- return {
- name: 'stale_locks',
- status: 'ok',
- message: reapedNote
- ? `${reapedNote} No stale locks remain.`
- : 'No stale locks (no rows with ttl_expires_at < NOW())',
- };
- }
- const lines = stale.slice(0, 10).map(s => {
- const ageH = Math.floor(s.age_ms / 3600_000);
- let breakHint = 'gbrain doctor';
- if (s.id.startsWith('gbrain-sync:')) {
- breakHint = `gbrain sync --break-lock --source ${s.id.slice('gbrain-sync:'.length)}`;
- } else if (s.id.startsWith('gbrain-cycle:')) {
- breakHint = `gbrain dream --break-lock --source ${s.id.slice('gbrain-cycle:'.length)}`;
- } else if (s.id === 'gbrain-cycle') {
- breakHint = 'gbrain dream --break-lock';
- }
- return ` ${s.id} (pid ${s.holder_pid} on ${s.holder_host}, age ${ageH}h) → ${breakHint}`;
- });
- const tail = stale.length > 10 ? ` ... and ${stale.length - 10} more.` : null;
- const header = opts.fix
- ? `${stale.length} stale lock(s) remain that could not be auto-reaped (live holder, cross-host, or within the PID-reuse grace):`
- : `${stale.length} stale lock(s) detected (ttl_expires_at < NOW()):`;
- return {
- name: 'stale_locks',
- status: 'warn',
- message: [
- reapedNote,
- header,
- ...lines,
- tail,
- ].filter(Boolean).join('\n'),
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- // Pre-v0.30 brains may not have the gbrain_cycle_locks table yet.
- if (/relation .* does not exist|no such table/i.test(msg)) {
- return { name: 'stale_locks', status: 'ok', message: 'gbrain_cycle_locks table not yet provisioned (skipping)' };
- }
- return { name: 'stale_locks', status: 'warn', message: `Check failed: ${msg}` };
- }
-}
-
-/**
- * v0.38 — cycle_phase_scope check (informational).
- *
- * Renders the static `PHASE_SCOPE` taxonomy from `src/core/cycle.ts` so
- * operators (and future automation) can see at a glance which phases
- * are safe to parallelize per source vs which serialize brain-wide.
- *
- * Always returns 'ok' — this is documentation, not enforcement. The
- * runtime-enforcement TODO is deferred per plan.
- */
-export function checkCyclePhaseScope(): Check {
- try {
- // Lazy require to avoid pulling cycle.ts into doctor's import graph
- // for non-cycle-related doctor runs. Same pattern as the existing
- // dynamic imports elsewhere in this file.
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const { ALL_PHASES, PHASE_SCOPE } = require('../core/cycle.ts') as {
- ALL_PHASES: ReadonlyArray<string>;
- PHASE_SCOPE: Record<string, 'source' | 'global' | 'mixed'>;
- };
- const counts: Record<'source' | 'global' | 'mixed', number> = { source: 0, global: 0, mixed: 0 };
- const breakdown: Record<string, string[]> = { source: [], global: [], mixed: [] };
- for (const phase of ALL_PHASES) {
- const scope = PHASE_SCOPE[phase];
- if (scope) {
- counts[scope]++;
- breakdown[scope].push(phase);
- }
- }
- return {
- name: 'cycle_phase_scope',
- status: 'ok',
- message:
- `Phase taxonomy: ${counts.source} source-scoped, ${counts.global} brain-global, ` +
- `${counts.mixed} mixed. Source-safe: [${breakdown.source.join(', ')}]. ` +
- `Brain-global: [${breakdown.global.join(', ')}]. Mixed: [${breakdown.mixed.join(', ')}].`,
- details: {
- phase_scope_map: PHASE_SCOPE,
- counts,
- },
- };
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- return { name: 'cycle_phase_scope', status: 'warn', message: `Check failed: ${msg}` };
- }
-}
-
-export async function checkSearchMode(engine: BrainEngine): Promise<Check> {
- try {
- const mode = await engine.getConfig('search.mode');
- const overrides = await engine.listConfigKeys('search.');
- // Exclude search.mode itself + the upgrade-notice state key from the
- // override roster — they aren't knobs.
- const overrideKeys = overrides.filter(k => k !== 'search.mode' && k !== 'search.mode_upgrade_notice_shown');
-
- if (!mode) {
- return {
- name: 'search_mode',
- status: 'ok',
- message: 'search.mode is unset (using balanced fallback). Run `gbrain search modes` to see what is running and pick a mode explicitly.',
- };
- }
-
- if (overrideKeys.length === 0) {
- return {
- name: 'search_mode',
- status: 'ok',
- message: `Mode: ${mode} (no per-key overrides — mode bundle is canonical).`,
- };
- }
-
- return {
- name: 'search_mode',
- status: 'ok',
- message: `Mode: ${mode} with ${overrideKeys.length} per-key override(s) (${overrideKeys.join(', ')}). To consolidate to the pure mode bundle: gbrain search modes --reset`,
- };
- } catch (e) {
- return {
- name: 'search_mode',
- status: 'ok',
- message: `Could not read search mode config (${(e as Error).message ?? 'unknown'}).`,
- };
- }
-}
-
-/**
- * v0.32.3 [CDX-6]: surface when retrieval-affecting files have changed
- * since the most recent published eval. Curated watch-list in
- * src/core/eval/drift-watch.ts; additions to that list require a
- * CHANGELOG line.
- *
- * Status stays `ok` — operator-facing reminder, not a hard gate.
- */
-export async function checkEvalDrift(engine: BrainEngine): Promise<Check> {
- try {
- const { watchedFilesDrifted } = await import('../core/eval/drift-watch.ts');
- // Working tree vs HEAD (uncommitted retrieval changes). The fuller
- // version (vs the commit of the last published eval) is wired when
- // eval_results lands; today we just probe for uncommitted retrieval
- // changes so the operator sees them before re-running evals.
- const repoRoot = process.cwd();
- const drifted = watchedFilesDrifted(repoRoot);
- if (drifted.length === 0) {
- return {
- name: 'eval_drift',
- status: 'ok',
- message: 'No retrieval-affecting files changed in working tree.',
- };
- }
- const summary = drifted.slice(0, 3).join(', ') + (drifted.length > 3 ? ', …' : '');
- return {
- name: 'eval_drift',
- status: 'ok',
- message: `${drifted.length} retrieval-affecting file(s) changed since HEAD: ${summary}. Re-run \`gbrain eval run-all\` after committing these changes.`,
- };
- } catch (e) {
- return {
- name: 'eval_drift',
- status: 'ok',
- message: `Could not probe retrieval drift (${(e as Error).message ?? 'unknown'}).`,
- };
- }
-}
-
-/**
- * v0.31.12 — surface a warn when models.tier.subagent or models.default
- * resolves to a non-Anthropic provider. The subagent loop in
- * src/core/minions/handlers/subagent.ts uses Anthropic Messages API with
- * prompt caching on system + tools; non-Anthropic providers would break
- * the loop at runtime. This check makes the configuration drift visible
- * before a job is submitted.
- */
-
-/**
- * v0.41.2.1 — embedding_env_override (D9 #9). Defense-in-depth for the
- * ze-switch env-override class (the 716K-chunk damage incident from
- * PR #1421's description).
- *
- * GBRAIN_EMBEDDING_MODEL / GBRAIN_EMBEDDING_DIMENSIONS win over DB+file
- * config in loadConfig(). When env disagrees with DB, the gateway embeds
- * with the env-selected model — even after ze-switch wrote a different
- * value to DB. This check surfaces that disagreement on every hourly
- * doctor run so users can spot the drift before the embed sweep corrupts
- * vectors at the wrong width.
- *
- * Uses Check.details (NOT Check.issues, which has a different schema)
- * so the structured `mismatches[]` payload is consumable by monitoring
- * pipelines without ad-hoc type widening.
- *
- * Cross-surface parity: wired into BOTH buildChecks() and
- * doctorReportRemote() — operators running thin-client doctor against
- * a remote brain see the server's env, which is the env that matters
- * for the embed pipeline running there.
- */
-async function checkEmbeddingEnvOverride(engine: BrainEngine): Promise<Check> {
- const envModel = process.env.GBRAIN_EMBEDDING_MODEL?.trim();
- const envDim = process.env.GBRAIN_EMBEDDING_DIMENSIONS?.trim();
- if (!envModel && !envDim) {
- return {
- name: 'embedding_env_override',
- status: 'ok',
- message: 'no embedding env overrides set',
- };
- }
- let dbModel: string | null = null;
- let dbDim: string | null = null;
- try {
- dbModel = await engine.getConfig('embedding_model');
- dbDim = await engine.getConfig('embedding_dimensions');
- } catch (err) {
- return {
- name: 'embedding_env_override',
- status: 'warn',
- message: `couldn't read DB config to compare env: ${err instanceof Error ? err.message : String(err)}`,
- };
- }
- const mismatches: Array<{ key: string; env: string; db: string }> = [];
- if (envModel && dbModel && envModel !== dbModel) {
- mismatches.push({ key: 'GBRAIN_EMBEDDING_MODEL', env: envModel, db: dbModel });
- }
- if (envDim && dbDim && envDim !== dbDim) {
- mismatches.push({ key: 'GBRAIN_EMBEDDING_DIMENSIONS', env: envDim, db: dbDim });
- }
- if (mismatches.length === 0) {
- return {
- name: 'embedding_env_override',
- status: 'ok',
- message: 'env vars agree with DB config',
- };
- }
- return {
- name: 'embedding_env_override',
- status: 'warn',
- message:
- `${mismatches.length} embedding env var(s) disagree with DB config (env wins at runtime). ` +
- `Fix: \`unset ${mismatches.map((m) => m.key).join(' ')}\` in your shell profile / .env, ` +
- `or update DB config to match.`,
- details: { mismatches },
- };
-}
-
-export async function checkSubagentCapability(engine: BrainEngine): Promise<Check> {
- try {
- const { classifyCapabilities } = await import('../core/ai/capabilities.ts');
- const modelsSubagent = await engine.getConfig('models.subagent');
- const tierSubagent = await engine.getConfig('models.tier.subagent');
- const modelsDefault = await engine.getConfig('models.default');
-
- // Helper: explain a verdict in user-facing terms.
- const explain = (resolved: string, source: string): Check | null => {
- const verdict = classifyCapabilities(resolved);
- if (verdict === 'unusable:no_tools') {
- return {
- name: 'subagent_capability',
- status: 'warn',
- message:
- `${source} is "${resolved}" but that provider/model lacks native tool calling. ` +
- `The subagent loop cannot run on this model — runtime will fall back to claude-sonnet-4-6. ` +
- `Fix: \`gbrain config set ${source} <provider>:<model-with-tools>\` (e.g. anthropic:claude-sonnet-4-6 or openai:gpt-5.2).`,
- };
- }
- if (verdict === 'unknown') {
- return {
- name: 'subagent_capability',
- status: 'warn',
- message:
- `${source} is "${resolved}" which references an unknown provider. ` +
- `Use a recipe-declared provider. ` +
- `Fix: \`gbrain config set ${source} anthropic:claude-sonnet-4-6\` or pick another known provider.`,
- };
- }
- if (verdict === 'degraded:no_caching') {
- return {
- name: 'subagent_capability',
- status: 'warn',
- message:
- `${source} is "${resolved}" — provider does not support prompt caching. ` +
- `The subagent loop runs hot (cost scales linearly with conversation length). ` +
- `For lower cost on long loops, use an Anthropic model: ` +
- `\`gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6\`.`,
- };
- }
- return null;
- };
-
- let resolvedSource: string | null = null;
- let resolvedModel: string | null = null;
- if (modelsSubagent) {
- resolvedSource = 'models.subagent';
- resolvedModel = modelsSubagent;
- const issue = explain(modelsSubagent, resolvedSource);
- if (issue) return issue;
- } else if (modelsDefault) {
- resolvedSource = 'models.default';
- resolvedModel = modelsDefault;
- const issue = explain(modelsDefault, 'models.default');
- if (issue) return issue;
- } else if (tierSubagent) {
- resolvedSource = 'models.tier.subagent';
- resolvedModel = tierSubagent;
- const issue = explain(tierSubagent, resolvedSource);
- if (issue) return issue;
- }
- // v0.37 (T10 / D7) + v0.38 (D7 capability rename): warn when the configured
- // chat_model is non-Anthropic AND ANTHROPIC_API_KEY isn't set. With
- // agent.use_gateway_loop=false (the v0.38 default), subagent jobs still
- // require Anthropic at runtime; without the key, gbrain dream / gbrain
- // agent run / gbrain autopilot will all fail at job submission. Catches
- // the post-init drift case the init-time caveat would have shown if init
- // had been re-run.
- try {
- const { loadConfig } = await import('../core/config.ts');
- const cfg = loadConfig();
- const chatModel = cfg?.chat_model;
- const { isConfigTruthy } = await import('../core/config.ts');
- const gatewayLoopRaw = await engine.getConfig('agent.use_gateway_loop').catch(() => null);
- const gatewayLoopEnabled = isConfigTruthy(gatewayLoopRaw);
- const { isAnthropicProvider } = await import('../core/model-config.ts');
- if (chatModel && !isAnthropicProvider(chatModel) && !process.env.ANTHROPIC_API_KEY && !gatewayLoopEnabled) {
- return {
- name: 'subagent_capability',
- status: 'warn',
- message:
- `chat_model is "${chatModel}" (non-Anthropic) and ANTHROPIC_API_KEY is not set. ` +
- `Subagent features (gbrain dream, gbrain agent run, gbrain autopilot) will fail at job submission ` +
- `unless agent.use_gateway_loop=true. Chat alone (gbrain think) still works. ` +
- `Either set ANTHROPIC_API_KEY or enable: \`gbrain config set agent.use_gateway_loop true\`.`,
- };
- }
- } catch { /* loadConfig may throw; fall through */ }
-
- return {
- name: 'subagent_capability',
- status: 'ok',
- message: resolvedModel && resolvedSource
- ? `Subagent model resolves via ${resolvedSource} to "${resolvedModel}" with full tool-loop capability`
- : `Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability`,
- };
- } catch (e) {
- return {
- name: 'subagent_capability',
- status: 'warn',
- message: `Could not check subagent capability: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-// v0.38 — `checkSubagentProvider` was renamed to `checkSubagentCapability` (D7).
-// Back-compat alias preserved for any external doctor extensions importing it.
-const checkSubagentProvider = checkSubagentCapability;
-void checkSubagentProvider;
-
-/**
- * v0.42.7 (#1696): single source of truth for the extraction-lag warn
- * threshold (percent). Both the `links_extraction_lag` doctor check AND the
- * end-of-sync nudge (`sync.ts:maybeExtractionNudge`) resolve through this +
- * `_resolveEnvNumber` so "the nudge fires iff doctor would warn" can't drift.
- */
-export const EXTRACTION_LAG_WARN_PCT_DEFAULT = 20;
-/** Min non-deleted page count below which extraction-lag is vacuous-skipped
- * (unless an explicit --source scope is set). Shared by doctor + the sync
- * nudge (D6/C4) so their skip predicates match exactly. */
-export const EXTRACTION_LAG_MIN_PAGES = 100;
-
-/**
- * Re-exported from `src/core/env-number.ts`, which now owns the implementation
- * AND the warn-once memo. `source-health.ts` needs the hours resolver for the
- * staleness ceiling, and doctor already imports from source-health — so the
- * helper had to move to core or the import graph would cycle.
- *
- * The `_resolveEnvNumber` name is kept because `sync.ts:5730` dynamically
- * imports it from this module.
- */
-export { resolveEnvNumber as _resolveEnvNumber };
-
-/** Local aliases; the shared memo lives in core so it can't fork per module. */
-const _resolveEnvNumber = resolveEnvNumber;
-const _resolveSyncFreshnessHours = resolveHoursEnv;
-
-/**
- * Sync freshness check (v0.32.4) — verify that sources with local_path have
- * been synced recently. Detects the silent failure mode where `gbrain sync`
- * stopped running and brain search now misses recent pages.
- *
- * Pure staleness check. Reads `sources.last_sync_at` only — no filesystem
- * access. Filesystem-vs-DB drift detection is intentionally out of scope:
- * - doctorReportRemote runs in the HTTP MCP server (src/commands/serve-http.ts);
- * walking arbitrary DB-supplied paths from a remote-callable endpoint
- * crosses a trust boundary (OAuth write scope could mutate local_path).
- * - Drift detection belongs in `multi_source_drift` which already has
- * GBRAIN_DRIFT_LIMIT + GBRAIN_DRIFT_TIMEOUT_MS guards.
- *
- * Thresholds (env-overridable, default = 24h warn / 72h fail):
- * - GBRAIN_SYNC_FRESHNESS_WARN_HOURS
- * - GBRAIN_SYNC_FRESHNESS_FAIL_HOURS
- * Invalid values (NaN, ≤0) fall back to defaults with a once-per-process warn.
- *
- * Edge cases handled:
- * - last_sync_at IS NULL → fail "never synced"
- * - last_sync_at > now() (clock skew / corrupted timestamp) → warn
- * - mixed sources → highest-severity drives the overall status
- * - executeRaw throws → outer-catch warn so doctor keeps running
- *
- * Failure messages embed `source.id` so the fix command
- * `gbrain sync --source <id>` matches what the user copy-pastes.
- */
-/**
- * v0.40.1.0 Track D / T7 — pure function form of the nightly_quality_probe_health
- * check. Extracted from the inline runDoctor block so tests can drive every
- * branch (disabled / enabled-no-events / enabled-all-pass / enabled-with-failures)
- * without spinning up the audit JSONL or a real config file.
- */
-/**
- * Pure function form of the conversation_parser_probe_health check.
- * Mirrors computeNightlyQualityProbeHealthCheck: skip-with-hint when the
- * probe is off and silent, surface the last 7 days of audit events when
- * it has run, WARN on any non-pass outcome.
- *
- * `effectiveEnabled` folds the D10 mode-gate in: explicitly enabled OR
- * search.mode=tokenmax (where the probe is default-on).
- */
-export function computeConversationParserProbeHealthCheck(
- effectiveEnabled: boolean,
- events: ReadonlyArray<{ outcome: string; ts: string; reason?: string }>,
-): Check {
- const name = 'conversation_parser_probe_health';
- if (!effectiveEnabled && events.length === 0) {
- return {
- name,
- status: 'ok',
- message:
- 'disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: ' +
- '`gbrain config set autopilot.conversation_parser_probe.enabled true`',
- };
- }
- if (events.length === 0) {
- return {
- name,
- status: 'ok',
- message: 'enabled but no probe events in the last 7 days (next run by autopilot; fixtures require a source-checkout install).',
- };
- }
- const bad = events.filter(e => e.outcome !== 'pass');
- const latest = events[events.length - 1]!;
- if (bad.length > 0) {
- return {
- name,
- status: 'warn',
- message:
- `${bad.length}/${events.length} probe run(s) in the last 7 days did not pass; ` +
- `latest: ${latest.outcome}${latest.reason ? ` (${latest.reason})` : ''}`,
- };
- }
- return {
- name,
- status: 'ok',
- message: `${events.length} probe run(s) in the last 7 days, all pass (latest ${latest.ts}).`,
- };
-}
-
-export function computeNightlyQualityProbeHealthCheck(
- probeEnabled: boolean,
- events: ReadonlyArray<{ outcome: string; ts: string; detail?: string }>,
-): Check {
- const name = 'nightly_quality_probe_health';
- if (!probeEnabled && events.length === 0) {
- // Quiet skip — surface enable hint only when explicitly asked to.
- return {
- name,
- status: 'ok',
- message: `disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true`,
- };
- }
- if (events.length === 0) {
- return {
- name,
- status: 'ok',
- message: `enabled but no probe events in the last 7 days (next run by autopilot).`,
- };
- }
- // v0.40.1.0 Track D (codex CDX-5): any non-PASS outcome is bad signal.
- // Previously only fail / error / budget_exceeded triggered warn —
- // no_embedding_key / rate_limited / inconclusive were silently reported
- // as PASS, hiding real misconfigurations.
- const bad = events.filter(e => e.outcome !== 'pass');
- const latest = events[events.length - 1]!;
- if (bad.length > 0) {
- const counts =
- `pass=${events.filter(e => e.outcome === 'pass').length} ` +
- `fail=${events.filter(e => e.outcome === 'fail').length} ` +
- `error=${events.filter(e => e.outcome === 'error').length} ` +
- `inconclusive=${events.filter(e => e.outcome === 'inconclusive').length} ` +
- `budget=${events.filter(e => e.outcome === 'budget_exceeded').length} ` +
- `no_embed_key=${events.filter(e => e.outcome === 'no_embedding_key').length} ` +
- `rate_limited=${events.filter(e => e.outcome === 'rate_limited').length}`;
- return {
- name,
- status: 'warn',
- message: `${bad.length} non-PASS run${bad.length === 1 ? '' : 's'} in last 7d (${counts}). Latest: ${latest.outcome} at ${latest.ts}${latest.detail ? ` (${latest.detail})` : ''}.`,
- };
- }
- return {
- name,
- status: 'ok',
- message: `${events.length} PASS run${events.length === 1 ? '' : 's'} in last 7d. Latest: ${latest.ts}.`,
- };
-}
-
-/**
- * v0.41.11.0 — conversation_facts_backlog doctor check.
- *
- * 3-state status:
- * - SKIPPED when cycle.conversation_facts_backfill.enabled=false
- * (with paste-ready enable hint). No backlog enumeration; cheap probe.
- * This is the Eng-v2 C9 "don't degrade health for opt-out users" gate.
- * - OK when enabled=true AND backlog==0 OR no eligible pages exist.
- * - WARN when enabled=true AND backlog>10.
- *
- * Backlog uses versioned, source-scoped outcomes. Regular pages bind the marker
- * to pages.updated_at; raw-transcript sidecars carry a SHA-256 snapshot token
- * and are revalidated by the extraction command before it skips model work.
- * Legacy/unversioned rows and partial extraction remain in backlog.
- */
-export async function computeConversationFactsBacklogCheck(
- engine: BrainEngine,
-): Promise<Check> {
- const name = 'conversation_facts_backlog';
- try {
- // Read the same config the cycle phase reads (Eng-v2 A2 single SoT).
- const enabledRaw = await engine.getConfig(
- 'cycle.conversation_facts_backfill.enabled',
- );
- const enabled = enabledRaw != null &&
- !['false', '0', 'no', 'off', ''].includes(enabledRaw.trim().toLowerCase());
-
- if (!enabled) {
- return {
- name,
- status: 'ok',
- message:
- 'disabled (opt-in). Enable with: gbrain config set cycle.conversation_facts_backfill.enabled true',
- };
- }
-
- // Resolve types from same key as cycle phase + CLI default.
- const typesRaw = await engine.getConfig(
- 'cycle.conversation_facts_backfill.types',
- );
- let types = ['conversation', 'meeting', 'slack', 'email', 'imessage', 'imessage-daily'];
- if (typesRaw) {
- try {
- const parsed = JSON.parse(typesRaw);
- if (Array.isArray(parsed)) {
- const filtered = parsed.filter(
- (t): t is string => typeof t === 'string',
- );
- if (filtered.length > 0) types = filtered;
- }
- } catch {
- // fall through to default
- }
- }
-
- const rows = await engine.executeRaw<{
- backlog: string | number;
- completed: string | number;
- non_extractable: string | number;
- }>(
- `WITH outcomes AS (
- SELECT
- p.source_id,
- p.slug,
- MAX(CASE WHEN f.source = 'cli:extract-conversation-facts:terminal:v2' THEN 1 ELSE 0 END) AS completed,
- MAX(CASE WHEN f.source = 'cli:extract-conversation-facts:non-extractable:v2' THEN 1 ELSE 0 END) AS non_extractable
- FROM pages p
- LEFT JOIN facts f
- ON f.source_id = p.source_id
- AND f.source_markdown_slug = p.slug
- AND f.source IN (
- 'cli:extract-conversation-facts:terminal:v2',
- 'cli:extract-conversation-facts:non-extractable:v2'
- )
- AND p.content_hash IS NOT NULL
- AND f.source_session = f.source || ':' || p.slug || ':page-' ||
- p.content_hash || '-' ||
- COALESCE(TO_CHAR(p.effective_date AT TIME ZONE 'UTC', 'YYYY-MM-DD'), 'none')
- WHERE p.type = ANY($1::text[])
- AND p.deleted_at IS NULL
- AND COALESCE(BTRIM(p.frontmatter->>'raw_transcript'), '') = ''
- AND p.content_hash IS NOT NULL
- GROUP BY p.source_id, p.slug
- )
- SELECT
- COALESCE(SUM(CASE WHEN completed = 0 AND non_extractable = 0 THEN 1 ELSE 0 END), 0) AS backlog,
- COALESCE(SUM(completed), 0) AS completed,
- COALESCE(SUM(CASE WHEN completed = 0 THEN non_extractable ELSE 0 END), 0) AS non_extractable
- FROM outcomes`,
- [types],
- );
-
- let backlog = Number(rows[0]?.backlog ?? 0);
- let completed = Number(rows[0]?.completed ?? 0);
- let nonExtractable = Number(rows[0]?.non_extractable ?? 0);
-
- // SQL cannot read raw_transcript files or reproduce the fallback hash for a
- // legacy NULL content_hash. Recompute those tokens through the command's
- // canonical verifier. Pagination keeps memory bounded.
- const { findFreshExtractionOutcomes } = await import(
- './extract-conversation-facts.ts'
- );
- const verifierSources = await engine.executeRaw<{ source_id: string }>(
- `SELECT DISTINCT source_id
- FROM pages
- WHERE type = ANY($1::text[])
- AND deleted_at IS NULL
- AND (
- COALESCE(BTRIM(frontmatter->>'raw_transcript'), '') <> ''
- OR content_hash IS NULL
- )
- ORDER BY source_id`,
- [types],
- );
- for (const { source_id: sourceId } of verifierSources) {
- for (const type of types) {
- let offset = 0;
- // eslint-disable-next-line no-constant-condition
- while (true) {
- const batch = await engine.listPages({
- type: type as NonNullable<Parameters<BrainEngine['listPages']>[0]>['type'],
- sourceId,
- limit: 10,
- offset,
- });
- if (batch.length === 0) break;
- const verifyInProcess = batch.filter((page) => {
- const raw = page.frontmatter?.raw_transcript;
- return (typeof raw === 'string' && raw.trim().length > 0) ||
- page.content_hash == null;
- });
- if (verifyInProcess.length > 0) {
- const outcomes = await findFreshExtractionOutcomes(
- engine,
- sourceId,
- verifyInProcess,
- );
- for (const page of verifyInProcess) {
- const outcome = outcomes.get(page.slug);
- if (outcome === 'complete') completed++;
- else if (outcome === 'non_extractable') nonExtractable++;
- else backlog++;
- }
- }
- offset += batch.length;
- if (batch.length < 10) break;
- }
- }
- }
-
- if (backlog === 0) {
- return {
- name,
- status: 'ok',
- message: 'all eligible pages have fresh durable extraction outcomes',
- details: {
- backlog,
- completed,
- scanned_not_extractable: nonExtractable,
- types,
- freshness_rule: 'v2 snapshot token (content hash + effective date or sidecar sha256)',
- },
- };
- }
-
- if (backlog > 10) {
- const fixHint =
- 'gbrain extract-conversation-facts --background --max-cost-usd 5';
- return {
- name,
- status: 'warn',
- message: `${backlog} eligible pages without extraction. Fix: ${fixHint}`,
- details: {
- backlog,
- completed,
- scanned_not_extractable: nonExtractable,
- types,
- fix_hint: fixHint,
- freshness_rule: 'v2 snapshot token (content hash + effective date or sidecar sha256)',
- },
- };
- }
-
- return {
- name,
- status: 'ok',
- message: `${backlog} eligible page(s) below warn threshold (>10)`,
- details: {
- backlog,
- completed,
- scanned_not_extractable: nonExtractable,
- types,
- freshness_rule: 'v2 snapshot token (content hash + effective date or sidecar sha256)',
- },
- };
- } catch (err) {
- return {
- name,
- status: 'warn',
- message: `backlog query failed: ${(err as Error).message}`,
- };
- }
-}
-
-/**
- * v0.42.7 (#1696) — links_extraction_lag doctor check.
- *
- * The signal that surfaces the "imported ≠ curated" root cause: pages whose
- * link/timeline extraction is stale (never run, edited-since, or extractor
- * bumped). Without it, a brain can run for months at 0% typed-edge coverage
- * with nothing warning the operator.
- *
- * Warn-only by DEFAULT (>20% stale). Hard-fail ONLY when the operator opts in
- * via GBRAIN_EXTRACTION_LAG_FAIL_PCT — so a just-upgraded 280K-page brain
- * (every page NULL → 100% stale) gets a loud WARN, never a non-zero exit that
- * would break a CI/cron pipeline gating on `gbrain doctor`.
- *
- * Vacuous-skip on tiny brains (<100 pages, no --source) like orphan_ratio.
- * Pre-v112 brains (column missing) degrade to OK via isUndefinedColumnError.
- * Strictly SQL — no filesystem/git access — so it's safe to wire into the
- * thin-client doctorReportRemote path (CDX-5 trust boundary).
- *
- * `opts.sourceId` scopes both the denominator and the stale count to one
- * source (the explicit-only `--source` parse, like orphan_ratio).
- */
-export async function checkLinksExtractionLag(
- engine: BrainEngine,
- opts?: { sourceId?: string },
-): Promise<Check> {
- const name = 'links_extraction_lag';
- const sourceId = opts?.sourceId;
- const fix = "Run: gbrain extract --stale";
- try {
- const totalRows = await engine.executeRaw<{ count: number }>(
- sourceId
- ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND source_id = $1`
- : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL`,
- sourceId ? [sourceId] : [],
- );
- const total = Number(totalRows[0]?.count ?? 0);
- if (total === 0) {
- return { name, status: 'ok', message: 'Extraction lag not applicable (no pages)' };
- }
- // Vacuous-skip tiny brains unless explicitly source-scoped. Shared floor
- // const so the sync nudge (D6/C4) skips on the exact same predicate.
- if (total < EXTRACTION_LAG_MIN_PAGES && !sourceId) {
- return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)` };
- }
-
- const stale = await engine.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS });
- const pct = (stale / total) * 100;
- const pctStr = pct.toFixed(0);
- const scope = sourceId ? ` in source '${sourceId}'` : '';
-
- const warnPct = _resolveEnvNumber('GBRAIN_EXTRACTION_LAG_WARN_PCT', EXTRACTION_LAG_WARN_PCT_DEFAULT, { unit: '%' });
- // Fail threshold is DISABLED unless explicitly set (warn-only default). A
- // bare unset env var → no hard-fail; invalid value → warn-once + disabled.
- let failPct: number | undefined;
- const failRaw = process.env.GBRAIN_EXTRACTION_LAG_FAIL_PCT;
- if (failRaw !== undefined && failRaw !== '') {
- const n = Number(failRaw);
- if (Number.isFinite(n) && n > 0) {
- failPct = n;
- } else {
- warnOnceForEnv(
- 'GBRAIN_EXTRACTION_LAG_FAIL_PCT',
- `[gbrain] Ignoring invalid GBRAIN_EXTRACTION_LAG_FAIL_PCT=${failRaw}; hard-fail stays disabled.`,
- );
- }
- }
-
- const details = { total, stale, pct: Number(pctStr), warn_pct: warnPct, fail_pct: failPct ?? null, source_id: sourceId ?? null };
- if (failPct !== undefined && pct > failPct) {
- return { name, status: 'fail', message: `${stale}/${total} pages (${pctStr}%)${scope} need link/timeline extraction (> ${failPct}% fail threshold). ${fix}`, details };
- }
- if (pct > warnPct) {
- return { name, status: 'warn', message: `${stale}/${total} pages (${pctStr}%)${scope} have un-extracted edges. ${fix}`, details };
- }
- return { name, status: 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}`, details };
- } catch (e) {
- // Pre-v112 brain: links_extracted_at column doesn't exist yet. Graceful OK
- // (migration/bootstrap adds it; nothing to assess until then).
- if (isUndefinedColumnError(e, 'links_extracted_at')) {
- return { name, status: 'ok', message: 'links_extracted_at not present (pre-v112 brain)' };
- }
- return { name, status: 'warn', message: `Could not check links_extraction_lag: ${(e as Error).message}` };
- }
-}
-
-/**
- * issue #160 — unverified_extractions doctor check.
- *
- * The extraction quarantine lane parks auto-extracted entity stubs
- * (frontmatter `provenance: 'auto-extracted'` + `status: 'unverified'`)
- * until the owner promotes or rejects them. A queue nobody reviews decays
- * into invisible clutter, so this check counts stubs older than N days
- * (default 7) and nudges toward the review surface. Exported for direct
- * testing (mirrors checkLinksExtractionLag).
- */
-export async function checkUnverifiedExtractions(
- engine: BrainEngine,
- opts?: { sourceId?: string; days?: number },
-): Promise<Check> {
- const name = 'unverified_extractions';
- const days = opts?.days ?? 7;
- const sourceId = opts?.sourceId;
- try {
- const params: unknown[] = [String(days)];
- let srcClause = '';
- if (sourceId) {
- params.push(sourceId);
- srcClause = 'AND p.source_id = $2';
- }
- const rows = await engine.executeRaw<{ n: string | number }>(
- `SELECT COUNT(*)::int AS n FROM pages p
- WHERE p.deleted_at IS NULL
- AND ${unverifiedExtractionFragment('p')}
- AND p.created_at < now() - ($1 || ' days')::interval
- ${srcClause}`,
- params,
- );
- const n = Number(rows[0]?.n ?? 0);
- return {
- name,
- status: n > 0 ? 'warn' : 'ok',
- message: n > 0
- ? `${n} unverified auto-extracted entity stub(s) older than ${days} days awaiting review. List with 'gbrain extraction-pending'; promote/reject with 'gbrain extraction-review <promote|reject> --slugs <slug,...>'.`
- : 'No stale unverified extraction stubs',
- details: { count: n, days, source_id: sourceId ?? null },
- };
- } catch (e) {
- return { name, status: 'warn', message: `Could not check unverified_extractions: ${(e as Error).message}` };
- }
-}
-
-/**
- * issue #2250 (reported by @615Works) — content_hash_duplicates.
- *
- * `gbrain import` run from the wrong root (one level too deep) drops the
- * path prefix from every slug, leaving `people/x` and `x` coexisting with
- * identical content. `dream --phase purge` never removes them (they aren't
- * file-backed orphans) and nothing surfaced the condition. One GROUP BY —
- * never an N² hash comparison — flags hash groups that contain BOTH a bare
- * slug (no '/') and a path-prefixed slug.
- */
-export async function checkContentHashDuplicates(engine: BrainEngine): Promise<Check> {
- const name = 'content_hash_duplicates';
- const fix = 'Fix: gbrain pages delete <bare-slug> for each pair, then gbrain pages purge-deleted --older-than 0';
- try {
- const rows = await engine.executeRaw<{ source_id: string; content_hash: string; slugs: string }>(
- `SELECT source_id, content_hash,
- string_agg(slug, '|' ORDER BY length(slug), slug) AS slugs
- FROM pages
- WHERE deleted_at IS NULL AND content_hash IS NOT NULL AND content_hash <> ''
- GROUP BY source_id, content_hash
- HAVING count(*) > 1
- AND count(*) FILTER (WHERE strpos(slug, '/') = 0) > 0
- AND count(*) FILTER (WHERE strpos(slug, '/') > 0) > 0
- LIMIT 50`,
- );
- if (rows.length === 0) {
- return { name, status: 'ok', message: 'No content-hash duplicate pairs (bare vs path-prefixed slugs)' };
- }
- let pairCount = 0;
- const samples: string[] = [];
- for (const r of rows) {
- const slugs = String(r.slugs).split('|');
- const prefixed = slugs.filter(s => s.includes('/'));
- for (const bare of slugs.filter(s => !s.includes('/'))) {
- const twin = prefixed.find(p => p.endsWith('/' + bare)) ?? prefixed[0];
- pairCount++;
- if (samples.length < 5) samples.push(`${bare} <-> ${twin}`);
- }
- }
- return {
- name,
- status: 'warn',
- message: `${pairCount} content-hash duplicate pair(s) detected (same content, differing slug forms — usually an import run from the wrong root, which drops the path prefix). Sample: ${samples.join('; ')}. ${fix}`,
- details: { pair_count: pairCount, hash_groups: rows.length, sample_pairs: samples },
- };
- } catch (e) {
- return { name, status: 'warn', message: `Could not check content-hash duplicates: ${(e as Error).message}` };
- }
-}
-
-/** Walk a repo for markdown files and return their slugified (lowercased) slugs. */
-function collectMarkdownSlugs(root: string): Set<string> {
- const out = new Set<string>();
- const stack = [''];
- while (stack.length > 0) {
- const rel = stack.pop()!;
- let entries;
- try {
- entries = readdirSync(rel ? join(root, rel) : root, { withFileTypes: true });
- } catch {
- continue;
- }
- for (const e of entries) {
- // Hidden directories can contain canonical, tracked knowledge (for
- // example `.archive/`). Only implementation metadata is never a page.
- if (e.name === '.git' || e.name === 'node_modules') continue;
- const childRel = rel ? `${rel}/${e.name}` : e.name;
- if (e.isDirectory()) stack.push(childRel);
- else if (/\.mdx?$/i.test(e.name)) out.add(slugifyPath(childRel).toLowerCase());
- }
- }
- return out;
-}
-
-/**
- * issue #2784 (reported by @alexputici) — undeclared_db_only_pages.
- *
- * A markdown page with no backing file that sits outside every declared
- * db_only path is invisible to any file-lane backup/recovery reasoning: an
- * operator auditing "what would survive a DB loss" gets a silently wrong
- * answer. The engine's own derive-phase output prefixes
- * (DERIVE_PHASE_DB_ONLY_DEFAULTS) count as implicitly declared so the check
- * stays quiet on healthy brains. Deliberately allowed to stat the source
- * repo (the one thing the SQL-only check registry could never see).
- */
-export async function checkUndeclaredDbOnlyPages(engine: BrainEngine): Promise<Check> {
- const name = 'undeclared_db_only_pages';
- try {
- const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
- `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
- );
- const checkable = sources.filter(s => s.local_path && existsSync(s.local_path));
- if (checkable.length === 0) {
- return { name, status: 'ok', message: 'Not applicable (no sources with a local repo path on this host)' };
- }
- let total = 0;
- const samples: string[] = [];
- const perSource: Record<string, number> = {};
- for (const src of checkable) {
- let declared: string[] = [];
- try {
- declared = loadStorageConfig(src.local_path)?.db_only ?? [];
- } catch {
- // invalid gbrain.yml — treated as no declarations; the sync path
- // already surfaces the config error itself.
- }
- const dbOnlyDirs = effectiveDbOnlyDirs(declared);
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND page_kind = 'markdown'`,
- [src.id],
- );
- if (rows.length === 0) continue;
- const backed = collectMarkdownSlugs(src.local_path!);
- for (const { slug } of rows) {
- if (dbOnlyDirs.some(dir => slug.startsWith(dir))) continue;
- if (backed.has(slug)) continue;
- total++;
- perSource[src.id] = (perSource[src.id] ?? 0) + 1;
- if (samples.length < 5) samples.push(`${slug} (src=${src.id})`);
- }
- }
- if (total === 0) {
- return {
- name,
- status: 'ok',
- message: `Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: ${DERIVE_PHASE_DB_ONLY_DEFAULTS.join(' ')})`,
- };
- }
- return {
- name,
- status: 'warn',
- message: `${total} DB page(s) have no backing file and sit outside every declared/default db_only path — invisible to file-lane backup/recovery. Sample: ${samples.join('; ')}. Fix: restore or export the files, or declare their prefixes under storage.db_only in gbrain.yml (derive-phase defaults already cover: ${DERIVE_PHASE_DB_ONLY_DEFAULTS.join(' ')})`,
- details: { total, per_source: perSource, sample_slugs: samples },
- };
- } catch (e) {
- return { name, status: 'warn', message: `Could not check undeclared db-only pages: ${(e as Error).message}` };
- }
-}
-
-/**
- * issue #2788 (reported by @alexputici) — db_only_collector_collision.
- *
- * Declaring a collector's output dir in storage.db_only silently kills its
- * ingestion: manageGitignore auto-gitignores the dir, the git-walking sync
- * never sees the files, and import honors .gitignore too — everything stays
- * green while nothing reaches the DB (a 7-week outage in the field). The
- * recipe's `output_paths` frontmatter is the ground truth; the same warning
- * also fires at .gitignore-write time inside sync's manageGitignore.
- */
-export async function checkDbOnlyCollectorCollision(
- engine: BrainEngine,
- opts?: { collectors?: Array<{ id: string; output_path: string }> },
-): Promise<Check> {
- const name = 'db_only_collector_collision';
- try {
- let collectors = opts?.collectors;
- if (!collectors) {
- const { getConfiguredCollectorOutputs } = await import('./integrations.ts');
- collectors = getConfiguredCollectorOutputs();
- }
- if (collectors.length === 0) {
- return { name, status: 'ok', message: 'No configured collectors declare output paths' };
- }
- const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
- `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
- );
- const hits: string[] = [];
- for (const src of sources) {
- if (!src.local_path || !existsSync(src.local_path)) continue;
- let dbOnly: string[] = [];
- try {
- dbOnly = loadStorageConfig(src.local_path)?.db_only ?? [];
- } catch {
- continue;
- }
- if (dbOnly.length === 0) continue;
- for (const hit of findDbOnlyCollisions(collectors, dbOnly)) {
- hits.push(`collector '${hit.id}' writes to '${hit.output_path}' which is inside db_only path '${hit.db_only_dir}' (source ${src.id})`);
- }
- }
- if (hits.length === 0) {
- return { name, status: 'ok', message: 'No collector output dir falls inside a db_only path' };
- }
- return {
- name,
- status: 'warn',
- message: `${hits.length} collector/db_only collision(s): ${hits.join('; ')}. db_only dirs are auto-gitignored, so sync AND import silently skip files there — the collector runs green while nothing reaches the DB. Fix: remove the prefix from storage.db_only in gbrain.yml, or move the collector output.`,
- details: { collisions: hits },
- };
- } catch (e) {
- return { name, status: 'warn', message: `Could not check collector/db_only collisions: ${(e as Error).message}` };
- }
-}
-
-/**
- * issue #1678 — extract_atoms_backlog doctor check.
- *
- * Closes the "silent backlog" gap: extract_atoms is pack-gated, so on a brain
- * whose active pack doesn't declare the phase it NEVER runs in the routine
- * cycle and pages accumulate forever with zero signal (the cycle reports a
- * clean `skipped`). This check counts the eligible-but-unextracted pages and,
- * when the pack doesn't run the phase AND the backlog is real, WARNs with the
- * exact `--drain` command.
- *
- * PAGE-BACKLOG-ONLY (Codex #11): extract_atoms also discovers transcript files
- * at runtime; this counts DB pages only — labeled in details. No
- * synthesize_concepts sibling this wave (Codex #12: that phase is a stub with
- * no real eligibility predicate; a check would be a fake signal).
- */
-export async function computeExtractAtomsBacklogCheck(
- engine: BrainEngine,
-): Promise<Check> {
- const name = 'extract_atoms_backlog';
- const approx = 'page backlog only; transcript corpus not counted';
- try {
- const { countExtractAtomsBacklog } = await import('../core/cycle/extract-atoms.ts');
- const backlog = await countExtractAtomsBacklog(engine); // brain-wide
- if (backlog === null) {
- return { name, status: 'warn', message: 'backlog query failed (could not count eligible pages)' };
- }
-
- const { packDeclaresPhase } = await import('../core/cycle.ts');
- let declared = false;
- try { declared = await packDeclaresPhase(engine, 'extract_atoms'); } catch { declared = false; }
-
- if (backlog === 0) {
- return {
- name, status: 'ok',
- message: 'no pages awaiting atom extraction',
- details: { backlog, pack_declares_phase: declared, known_approximation: approx },
- };
- }
-
- // The incident: pack does NOT run the phase but a real backlog exists →
- // it will grow forever without a signal. WARN with the drain command.
- if (!declared && backlog > 10) {
- const fix = 'gbrain dream --phase extract_atoms --drain --window 120 (or declare extract_atoms in your active schema pack)';
- return {
- name, status: 'warn',
- message: `${backlog} pages eligible for atom extraction but the active pack does not run extract_atoms — backlog growing. Fix: ${fix}`,
- details: { backlog, pack_declares_phase: false, fix_hint: fix, known_approximation: approx },
- };
- }
-
- if (declared) {
- // Pack runs it; the routine cycle drains in bounded batches. Informational.
- return {
- name, status: 'ok',
- message: `${backlog} page(s) pending; active pack runs extract_atoms each cycle`,
- details: { backlog, pack_declares_phase: true, known_approximation: approx },
- };
- }
-
- // Not declared but below the warn threshold.
- return {
- name, status: 'ok',
- message: `${backlog} page(s) eligible (below warn threshold; pack does not run extract_atoms)`,
- details: { backlog, pack_declares_phase: false, known_approximation: approx },
- };
- } catch (err) {
- return { name, status: 'warn', message: `extract_atoms_backlog check failed: ${(err as Error).message}` };
- }
-}
-
-/**
- * v0.42 — extract_health doctor check.
- *
- * Reads the extract_rollup_7d table (migration v106) for the last 7 days
- * and reports per-kind aggregates. Stable JSON envelope schema_version:1.
- *
- * 3-state status:
- * - OK when rollup is empty (no extractions yet) OR every per-kind
- * halt rate is below the warn threshold.
- * - WARN when any per-kind halt rate exceeds 10% (operator-visible
- * signal that an extractor is failing too often).
- * - WARN when rollup_write_failures > 0 (audit JSONL is the source of
- * truth but operator should know the DB cache is degraded).
- *
- * Per-kind columns (per plan A5 + D-EXTRACT-32 spec):
- * cost_7d_usd, eval_pass_count, eval_fail_count, halt_count,
- * round_completed_count, last_updated_at
- *
- * The check is empty-rollup-tolerant: a brain that has never extracted
- * shows OK with `kinds: []` rather than warning. Doctor latency stays
- * under 100ms regardless of brain size because the rollup table
- * pre-aggregates (rolled-up at audit-emitter time per F-OUT-19).
- *
- * Empty rollup short-circuits BEFORE hitting the rollup_write_failures
- * branch so a brand-new brain doesn't surface a "0 failures" warning.
- */
-export async function computeExtractHealthCheck(
- engine: BrainEngine,
-): Promise<Check> {
- const name = 'extract_health';
- try {
- type RollupRow = {
- kind: string;
- cost_7d_usd: number;
- eval_pass_count: number;
- eval_fail_count: number;
- halt_count: number;
- round_completed_count: number;
- rollup_write_failures: number;
- last_updated_at: Date | string | null;
- };
-
- const rows = await engine.executeRaw<RollupRow>(
- `SELECT
- kind,
- SUM(cost_usd) AS cost_7d_usd,
- SUM(eval_pass_count) AS eval_pass_count,
- SUM(eval_fail_count) AS eval_fail_count,
- SUM(halt_count) AS halt_count,
- SUM(round_completed_count) AS round_completed_count,
- SUM(rollup_write_failures) AS rollup_write_failures,
- MAX(updated_at) AS last_updated_at
- FROM extract_rollup_7d
- WHERE day >= CURRENT_DATE - 7
- GROUP BY kind
- ORDER BY kind`,
- [],
- );
-
- if (rows.length === 0) {
- return {
- name,
- status: 'ok',
- message: 'no extractions in last 7 days',
- details: {
- schema_version: 1,
- kinds: [],
- },
- };
- }
-
- type KindAggregate = {
- kind: string;
- cost_7d_usd: number;
- eval_pass_count: number;
- eval_fail_count: number;
- halt_count: number;
- round_completed_count: number;
- halt_rate: number;
- last_updated_at: string | null;
- };
-
- const kinds: KindAggregate[] = rows.map(r => {
- const halts = Number(r.halt_count) || 0;
- const completed = Number(r.round_completed_count) || 0;
- const total = halts + completed;
- return {
- kind: r.kind,
- cost_7d_usd: Number(r.cost_7d_usd) || 0,
- eval_pass_count: Number(r.eval_pass_count) || 0,
- eval_fail_count: Number(r.eval_fail_count) || 0,
- halt_count: halts,
- round_completed_count: completed,
- halt_rate: total > 0 ? halts / total : 0,
- last_updated_at: r.last_updated_at
- ? new Date(r.last_updated_at).toISOString()
- : null,
- };
- });
-
- const totalRollupFailures = rows.reduce(
- (acc, r) => acc + (Number(r.rollup_write_failures) || 0),
- 0,
- );
-
- // High halt rates: per F-OUT-19 doctor surfaces extractor health
- // distinctly from rollup write health.
- const highHaltKinds = kinds.filter(k => k.halt_rate > 0.10);
-
- if (highHaltKinds.length > 0) {
- const top3 = [...highHaltKinds]
- .sort((a, b) => b.halt_rate - a.halt_rate)
- .slice(0, 3)
- .map(k => `${k.kind}=${(k.halt_rate * 100).toFixed(1)}%`)
- .join(', ');
- return {
- name,
- status: 'warn',
- message: `${highHaltKinds.length} kind(s) with halt rate > 10% (top: ${top3})`,
- details: {
- schema_version: 1,
- kinds,
- rollup_write_failures_7d: totalRollupFailures,
- },
- };
- }
-
- if (totalRollupFailures > 0) {
- return {
- name,
- status: 'warn',
- message: `${totalRollupFailures} rollup write failure(s) in last 7d (audit JSONL is source of truth; rebuild via gbrain extract status --rebuild-rollup)`,
- details: {
- schema_version: 1,
- kinds,
- rollup_write_failures_7d: totalRollupFailures,
- },
- };
- }
-
- return {
- name,
- status: 'ok',
- message: `${kinds.length} kind(s) tracked, all halt rates below 10%`,
- details: {
- schema_version: 1,
- kinds,
- rollup_write_failures_7d: totalRollupFailures,
- },
- };
- } catch (err) {
- // Pre-v106 brains lack the extract_rollup_7d table. Don't warn — the
- // bootstrap-coverage / migration framework brings the schema forward
- // and the next run resolves naturally. Stay quiet.
- const msg = (err as Error).message || String(err);
- if (/extract_rollup_7d.*does not exist|no such table/i.test(msg)) {
- return {
- name,
- status: 'ok',
- message: 'extract_rollup_7d not yet present (pre-v0.42 brain or fresh init)',
- };
- }
- return {
- name,
- status: 'warn',
- message: `rollup query failed: ${msg}`,
- };
- }
-}
-
-export async function checkSyncFreshness(
- engine: BrainEngine,
- opts?: { nowMs?: number; localOnly?: boolean },
-): Promise<Check> {
- try {
- // v0.41.27.0: SELECT widens to carry last_commit + chunker_version so
- // the git short-circuit gate (below) can compare against what
- // `gbrain sync`'s up-to-date predicate at sync.ts:1057+1075 checks.
- // Columns existed pre-v0.41 (writeSyncAnchor / writeChunkerVersion);
- // no schema migration needed.
- const sources = await engine.executeRaw<{
- id: string;
- name: string;
- local_path: string | null;
- last_sync_at: Date | null;
- last_commit: string | null;
- chunker_version: string | null;
- newest_content_at: Date | null;
- }>(
- // v0.41.32.0: newest_content_at feeds the REMOTE (non-localOnly) lag so
- // doctorReportRemote never shells out to git on a DB-supplied local_path.
- `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at FROM sources WHERE local_path IS NOT NULL`,
- );
-
- if (sources.length === 0) {
- return {
- name: 'sync_freshness',
- status: 'ok',
- message: 'No federated sources to sync',
- details: { unchanged_count: 0, synced_recently_count: 0, stale_count: 0 },
- };
- }
-
- const warnHours = _resolveSyncFreshnessHours('GBRAIN_SYNC_FRESHNESS_WARN_HOURS', 24);
- const failHours = _resolveSyncFreshnessHours('GBRAIN_SYNC_FRESHNESS_FAIL_HOURS', 72);
- const warnMs = warnHours * 60 * 60 * 1000;
- const failMs = failHours * 60 * 60 * 1000;
-
- // `opts.nowMs` is a test-only injection seam for the boundary tests.
- // Without it, the two `Date.now()` calls (one in the test's `agoMs`
- // helper, one here) drift apart by microseconds-to-milliseconds, which
- // pushes "exactly 72h ago" above the strict `>` threshold and flips the
- // status from warn to fail (CI-flaky, see PR #1138 ship). Production
- // callers omit `nowMs` and get live wall-clock semantics.
- const now = opts?.nowMs ?? Date.now();
-
- // v0.41.27.0: D4 trust boundary. The git short-circuit runs ONLY when
- // the caller explicitly opts in via `localOnly: true`. Default (false)
- // preserves the v0.32.4 trust boundary for `doctorReportRemote` (the
- // HTTP MCP path) — a remote-callable code path must NOT walk
- // DB-supplied `local_path` values with subprocess calls. runDoctor
- // (local CLI) passes true; doctorReportRemote keeps the default.
- const localOnly = opts?.localOnly === true;
-
- // v0.41.27.0: D7 narrowed predicate. The CHUNKER_VERSION caller-side
- // check mirrors sync.ts:1057's chunker-version gate so doctor agrees
- // with sync on "is there work to do?". `sources.chunker_version` is
- // a TEXT column storing String(CHUNKER_VERSION).
- const currentChunkerVersion = String(CHUNKER_VERSION);
-
- const issues: string[] = [];
- // v0.41.27.0: D6 three-bucket count math. Every source falls into
- // EXACTLY ONE bucket per iteration. Invariant pinned by unit test:
- // unchanged_count + synced_recently_count + stale_count === sources.length
- // Stale subsumes warn + fail + never-synced + future-timestamp; we keep
- // hasWarnings/hasFailures for the existing return-status logic.
- let unchanged_count = 0;
- let synced_recently_count = 0;
- let stale_count = 0;
- let hasWarnings = false;
- let hasFailures = false;
-
- // BUG 4 (v0.42.x): a source with a LIVE, non-expired per-source sync lock is
- // actively syncing RIGHT NOW — it must not read as stale or never-synced.
- // The live lock is the only honest "in progress" signal. Checkpoint banking
- // is NOT usable: a blocked sync banks the good files then writes no anchor
- // (test/sync-resumable-import.serial.test.ts), so banking can't tell
- // in-progress from wedged. A blocked/failed sync's process has exited (no
- // lock row) and a wedged holder stops refreshing (TTL lapses), so either
- // correctly falls through to the stale path and is NEVER masked. Same
- // dynamic import as the stale_locks check; any throw (stub engine in unit
- // tests, pre-lock-table brain) is swallowed to false, so this can only ADD
- // an in-progress verdict, never suppress a real stale one.
- // Notes for sources caught actively syncing (surfaced in the result
- // message so the operator sees "in progress", not just a silent healthy
- // bucket). Empty when nothing is syncing — keeps the steady-state messages
- // byte-for-byte unchanged.
- const inProgress: string[] = [];
- let liveSyncSnap: (sourceId: string) => Promise<{ holder_pid: number; holder_host: string; age_ms: number } | null> =
- async () => null;
- try {
- const { inspectLock, syncLockId } = await import('../core/db-lock.ts');
- liveSyncSnap = async (sourceId: string) => {
- try {
- const snap = await inspectLock(engine, syncLockId(sourceId));
- return snap && !snap.ttl_expired
- ? { holder_pid: snap.holder_pid, holder_host: snap.holder_host, age_ms: snap.age_ms }
- : null;
- } catch {
- return null;
- }
- };
- } catch {
- /* db-lock unavailable — skip in-progress detection, staleness stands. */
- }
-
- // One ceiling for the whole report: hoisted out of the loop so every
- // source is judged against the same number (and the env read + warn-once
- // machinery runs once, not once per source).
- const stalenessCeilingSeconds = resolveStalenessCeilingSeconds();
- for (const source of sources) {
- // Embed source.id in user-visible messages so `gbrain sync --source <id>`
- // matches what the user copy-pastes. Show display name in parens when set.
- const display = source.name && source.name !== source.id
- ? `'${source.id}' (${source.name})`
- : `'${source.id}'`;
-
- // BUG 4: actively syncing (live lock) → healthy, count as synced_recently
- // and skip the staleness checks. Keeps the 3-bucket invariant intact.
- //
- // ...but ONLY up to the staleness ceiling. `withRefreshingLock` bumps the
- // heartbeat on its own timer regardless of whether the import is making
- // forward progress (`liveSyncStatus`'s docstring is explicit: callers may
- // report "running", NOT "healthy"). So a holder blocked inside a query
- // keeps refreshing forever, and an uncapped in-progress verdict would
- // mask that source from every staleness check indefinitely — the same
- // invisible-failure class this whole pass exists to close, just reached
- // through the lock table instead of the freshness column.
- const liveSnap = await liveSyncSnap(source.id);
- if (liveSnap) {
- const ceilingMs = stalenessCeilingSeconds * 1000;
- if (liveSnap.age_ms <= ceilingMs) {
- inProgress.push(`${display} sync in progress (pid ${liveSnap.holder_pid} on ${liveSnap.holder_host})`);
- synced_recently_count++;
- continue;
- }
- // Sub-hour ceilings are legal (fractional env override), and an alarm
- // that names a zero duration ("held the lock for 0h") reads as broken.
- const heldFor = liveSnap.age_ms >= 3600_000
- ? `${Math.floor(liveSnap.age_ms / 3600_000)}h`
- : `${Math.max(1, Math.floor(liveSnap.age_ms / 60_000))}m`;
- issues.push(
- `Source ${display} has held the sync lock for ${heldFor} ` +
- `(pid ${liveSnap.holder_pid} on ${liveSnap.holder_host}) — heartbeating but not finishing. ` +
- `Run \`gbrain sync --break-lock --source ${source.id}\` after confirming the holder is wedged.`,
- );
- hasFailures = true;
- stale_count++;
- continue;
- }
-
- if (!source.last_sync_at) {
- issues.push(`Source ${display} has never been synced`);
- hasFailures = true;
- stale_count++;
- continue;
- }
-
- const lastSync = new Date(source.last_sync_at).getTime();
- const ageMs = now - lastSync;
-
- if (ageMs < 0) {
- issues.push(
- `Source ${display} has future last_sync_at — clock skew or corrupted timestamp`,
- );
- hasWarnings = true;
- stale_count++;
- continue;
- }
-
- // v0.41.27.0: git short-circuit (D4 + D7 combined). Only fires when:
- // 1. caller opted in via localOnly=true (trust boundary)
- // 2. HEAD === last_commit (no new commits to sync)
- // 3. working tree has no TRACKED changes — untracked files ignored
- // (v0.41.32.0: `'ignore-untracked'`. Sync's incremental path keys off
- // the commit diff and never imports untracked files, so a quiet repo
- // with stray untracked dirs is genuinely caught up. The pre-v0.41.30
- // `true` mode counted those as dirty and produced the false-SEVERE
- // alarm this wave fixes.)
- // 4. chunker_version matches CURRENT (no post-upgrade re-chunk pending —
- // still ANDed, so a re-chunk need is never masked)
- // All four must hold; otherwise fall through to the time-based check.
- // The chunker version match is computed here (not in the helper)
- // because it depends on engine state, not git state.
- //
- // Clone-unavailable fallback: on stateless deploys (Docker on EB /
- // K8s / Fly — the platforms the cloud recipes produce), a container
- // restart wipes `local_path` and each clone is only re-materialized
- // when that source's next sync job runs. Until then the HEAD probe
- // cannot run at all ('unavailable'), which previously fell through to
- // raw wall-clock age — and since a no-op sync doesn't advance
- // `last_sync_at`, every QUIET source read as stale/FAIL after a
- // restart (score-sinking alert storm; observed live: 16-source brain,
- // 12 clones gone after a config-update restart, doctor 70→30).
- // 'unavailable' + chunker match now reuses the v0.41.32.0 REMOTE lag
- // signal (newest_content_at) below — DB-only, no subprocess, and it
- // still reports staleness whenever content really is newer than the
- // last sync. 'changed' (readable clone with real work) keeps
- // wall-clock exactly as before, and a chunker mismatch is never
- // masked (D7): it disables the fallback too.
- let cloneUnavailable = false;
- if (localOnly) {
- const gitState = probeSourceGitState(
- source.local_path,
- source.last_commit,
- { requireCleanWorkingTree: 'ignore-untracked' },
- );
- const chunkerMatch = source.chunker_version === currentChunkerVersion;
- if (gitState === 'unchanged' && chunkerMatch) {
- unchanged_count++;
- continue;
- }
- cloneUnavailable = gitState === 'unavailable' && chunkerMatch;
- }
-
- // v0.41.32.0: REMOTE path (doctorReportRemote, !localOnly) computes lag
- // from the stored newest_content_at column — NO git subprocess on a
- // DB-supplied local_path (preserves the v0.41.27.0 trust boundary). A
- // quiet repo whose newest commit predates its last sync reports 0; NULL
- // column → wall-clock fallback. LOCAL fall-through keeps wall-clock when
- // the clone is READABLE: the short-circuit failed on real evidence
- // (HEAD moved / dirty tree), so the source genuinely has work and
- // "hours since last sync" is the right staleness measure. A local clone
- // that is UNAVAILABLE (not yet re-materialized, see above) carries no
- // evidence either way, so it borrows this same DB-only lag. The
- // `ageMs < 0` skew check above still runs on raw wall-clock for both
- // paths (A1).
- let thresholdAgeMs = ageMs;
- if (!localOnly || cloneUnavailable) {
- const contentMs = source.newest_content_at
- ? new Date(source.newest_content_at).getTime()
- : null;
- const lagSec = lagFromContentMs(
- contentMs !== null && Number.isFinite(contentMs) ? contentMs : null,
- lastSync,
- now,
- stalenessCeilingSeconds,
- );
- thresholdAgeMs = lagSec === null ? ageMs : lagSec * 1000;
- }
-
- const ageHours = Math.floor(thresholdAgeMs / (1000 * 60 * 60));
- const ageDays = Math.floor(ageHours / 24);
-
- if (thresholdAgeMs > failMs) {
- issues.push(`Source ${display} last synced ${ageDays}d ago — brain search is stale!`);
- hasFailures = true;
- stale_count++;
- } else if (thresholdAgeMs > warnMs) {
- issues.push(`Source ${display} last synced ${ageHours}h ago`);
- hasWarnings = true;
- stale_count++;
- } else {
- synced_recently_count++;
- }
- }
-
- // D6 invariant: every source incremented exactly one bucket.
- const details = { unchanged_count, synced_recently_count, stale_count };
- // BUG 4: append in-progress context when any source is actively syncing.
- // Empty otherwise, so steady-state messages are byte-for-byte unchanged.
- const inProgressNote = inProgress.length ? `. ${inProgress.join('; ')}` : '';
-
- if (hasFailures) {
- return {
- name: 'sync_freshness',
- status: 'fail',
- message: `${issues.join('; ')}. Run \`gbrain sync --source <id>\` for each stale source${inProgressNote}`,
- details,
- };
- }
- if (hasWarnings) {
- return {
- name: 'sync_freshness',
- status: 'warn',
- message: `${issues.join('; ')}. Run \`gbrain sync --source <id>\` to refresh${inProgressNote}`,
- details,
- };
- }
- // v0.41.27.0: D2 ok-message reshape. Three branches surface what the
- // git short-circuit actually did so operators understand "unchanged
- // since last sync" vs "synced recently".
- if (unchanged_count === sources.length) {
- return {
- name: 'sync_freshness',
- status: 'ok',
- message: `All ${sources.length} federated source(s) up to date (no new commits since last sync)${inProgressNote}`,
- details,
- };
- }
- if (unchanged_count > 0) {
- return {
- name: 'sync_freshness',
- status: 'ok',
- message: `${sources.length} federated source(s): ${synced_recently_count} synced recently, ${unchanged_count} unchanged since last sync${inProgressNote}`,
- details,
- };
- }
- return {
- name: 'sync_freshness',
- status: 'ok',
- message: `All ${sources.length} federated source(s) synced recently${inProgressNote}`,
- details,
- };
- } catch (e) {
- return {
- name: 'sync_freshness',
- status: 'warn',
- message: `Could not check sync freshness: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * v0.41.19.0 (Issue 5 of ops-fix-wave) — surface `sync --all --parallel`
- * to operators with multi-source brains.
- *
- * Background: `gbrain sync --all --parallel N --workers N --skip-failed`
- * has existed since v0.40.3.0 but most operators still maintain separate
- * per-source cron entries with manual deconfliction. One `--all` line
- * replaces N per-source lines AND auto-picks-up future sources without
- * a crontab edit.
- *
- * Surgical scope: we can't reach into the user's crontab (host-specific,
- * portability risk). What we CAN do is surface the paste-ready command
- * inside `gbrain doctor` so the operator sees it whenever they run a
- * health check on a multi-source brain.
- *
- * Posture: never failure-state. Always `ok` with the paste-ready cmd
- * embedded in the message (matches how sync_freshness embeds fix hints).
- * Single-source brains get `ok` with a "not applicable" message.
- * SQL error → `warn` (own try/catch, not relying on the outer doctor
- * dispatcher — codex flagged this).
- */
-export async function checkSyncConsolidation(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ id: string }>(
- `SELECT id FROM sources
- WHERE archived IS NOT TRUE
- AND local_path IS NOT NULL`,
- );
- const sourceCount = rows.length;
- if (sourceCount < 2) {
- return {
- name: 'sync_consolidation',
- status: 'ok',
- message: 'Single-source brain — sync --all consolidation not applicable.',
- };
- }
- return {
- name: 'sync_consolidation',
- status: 'ok',
- message:
- `${sourceCount} active sources detected. Recommended cron: ` +
- '`gbrain sync --all --parallel 4 --workers 4 --skip-failed`. ' +
- 'If your crontab has separate per-source entries, replace them with one --all line — ' +
- 'future sources auto-pick-up without a crontab edit.',
- };
- } catch (err) {
- return {
- name: 'sync_consolidation',
- status: 'warn',
- message: `Could not check sync consolidation: ${err instanceof Error ? err.message : String(err)}`,
- };
- }
-}
-
-/**
- * v0.42.x (#1794, 4A) — pure pool-budget check. When `GBRAIN_MAX_CONNECTIONS`
- * is set (the operator opted into the single-source connection clamp), verify
- * the parent pool leaves room for at least one parallel worker. If even the
- * parent pool alone is at/over the budget, sync clamps to serial AND every
- * other gbrain process competes for the same cap — the operator should lower
- * `GBRAIN_POOL_SIZE`. Pure so it's unit-testable without env/engine.
- */
-export function computePoolBudgetCheck(
- maxConnections: number | undefined,
- parentPool: number,
- perWorkerPool: number,
-): Check {
- if (maxConnections === undefined) {
- return {
- name: 'pool_budget',
- status: 'ok',
- message: 'GBRAIN_MAX_CONNECTIONS not set — connection budget clamp disabled (default behavior).',
- };
- }
- if (parentPool + perWorkerPool > maxConnections) {
- return {
- name: 'pool_budget',
- status: 'warn',
- message:
- `GBRAIN_MAX_CONNECTIONS=${maxConnections} leaves no room for a parallel sync worker ` +
- `(parent pool ${parentPool} + ${perWorkerPool} per-worker > ${maxConnections}). ` +
- `Sync will run serial. If you hit EMAXCONNSESSION, lower the parent pool: ` +
- '`gbrain config` / set GBRAIN_POOL_SIZE=2 (recommended for low-cap poolers like Supabase Supavisor).',
- };
- }
- const maxWorkers = Math.floor((maxConnections - parentPool) / perWorkerPool);
- return {
- name: 'pool_budget',
- status: 'ok',
- message:
- `GBRAIN_MAX_CONNECTIONS=${maxConnections}: room for up to ${maxWorkers} parallel sync ` +
- `worker(s) (parent pool ${parentPool} + ${perWorkerPool} per-worker).`,
- };
-}
-
-/** Thin env/engine wrapper over `computePoolBudgetCheck`. */
-export async function checkPoolBudget(_engine: BrainEngine): Promise<Check> {
- try {
- const { resolveMaxConnections } = await import('../core/sync-concurrency.ts');
- const { resolvePoolSize } = await import('../core/db.ts');
- const maxConnections = resolveMaxConnections();
- const parentPool = resolvePoolSize();
- const perWorkerPool = Math.min(2, resolvePoolSize(2));
- return computePoolBudgetCheck(maxConnections, parentPool, perWorkerPool);
- } catch (err) {
- return {
- name: 'pool_budget',
- status: 'ok',
- message: `Skipped (${err instanceof Error ? err.message : String(err)})`,
- };
- }
-}
-
-/**
- * v0.38 — per-source `last_full_cycle_at` freshness check.
- *
- * Sibling to `sync_freshness`. Where sync_freshness reads `last_sync_at`
- * (one phase of the cycle), this check reads `sources.config->>'last_full_cycle_at'`
- * which is the canonical "this whole cycle completed" timestamp written
- * by runCycle's exit hook. Autopilot's per-source fan-out gate (the
- * v0.38 fan-out wave) reads the same field — so this check surfaces
- * exactly what autopilot sees when deciding to skip a source.
- *
- * Default thresholds: warn at 6h, fail at 24h. Tighter than sync_freshness
- * because full-cycle staleness compounds (sync stale → extract stale →
- * embed stale → search stale). Env overrides:
- * - GBRAIN_CYCLE_FRESHNESS_WARN_HOURS (default 6)
- * - GBRAIN_CYCLE_FRESHNESS_FAIL_HOURS (default 24)
- */
-export async function checkCycleFreshness(
- engine: BrainEngine,
- opts?: { nowMs?: number },
-): Promise<Check> {
- try {
- const sources = await engine.listAllSources({ localPathOnly: true });
- if (sources.length === 0) {
- return {
- name: 'cycle_freshness',
- status: 'ok',
- message: 'No federated sources to cycle',
- };
- }
-
- const warnHours = _resolveSyncFreshnessHours('GBRAIN_CYCLE_FRESHNESS_WARN_HOURS', 6);
- const failHours = _resolveSyncFreshnessHours('GBRAIN_CYCLE_FRESHNESS_FAIL_HOURS', 24);
- const warnMs = warnHours * 60 * 60 * 1000;
- const failMs = failHours * 60 * 60 * 1000;
- const now = opts?.nowMs ?? Date.now();
-
- const issues: string[] = [];
- let hasWarnings = false;
- let hasFailures = false;
-
- for (const source of sources) {
- const display = source.name && source.name !== source.id
- ? `'${source.id}' (${source.name})`
- : `'${source.id}'`;
- const raw = source.config?.last_full_cycle_at;
- if (typeof raw !== 'string') {
- // #2540: WARN, not FAIL. This check iterates EVERY local_path source,
- // so on a multi-source install where only some vaults are cycled
- // (e.g. one nightly `gbrain dream --dir <vault>`), a never-cycled
- // sibling source turned doctor permanently red — which erodes the
- // check's signal until real staleness hides inside the noise (the
- // reporter's install masked genuinely stale sources for weeks this
- // way). "Never cycled" also fires on a source added minutes ago.
- // A source that HAS cycled and then went stale still escalates
- // through the warn/fail age thresholds below — that is the
- // regression signal this check exists for.
- issues.push(`Source ${display} has never completed a full cycle`);
- hasWarnings = true;
- continue;
- }
- const last = new Date(raw).getTime();
- if (!Number.isFinite(last)) {
- issues.push(`Source ${display} has unparseable last_full_cycle_at: ${raw}`);
- hasWarnings = true;
- continue;
- }
- const ageMs = now - last;
- if (ageMs < 0) {
- issues.push(`Source ${display} has future last_full_cycle_at — clock skew`);
- hasWarnings = true;
- continue;
- }
- const ageHours = Math.floor(ageMs / (1000 * 60 * 60));
- if (ageMs > failMs) {
- issues.push(`Source ${display} last cycled ${ageHours}h ago`);
- hasFailures = true;
- } else if (ageMs > warnMs) {
- issues.push(`Source ${display} last cycled ${ageHours}h ago`);
- hasWarnings = true;
- }
- }
-
- if (hasFailures) {
- return {
- name: 'cycle_freshness',
- status: 'fail',
- message: `${issues.join('; ')}. Run \`gbrain dream --source <id>\` for each stale source, or start \`gbrain autopilot\`.`,
- };
- }
- if (hasWarnings) {
- return {
- name: 'cycle_freshness',
- status: 'warn',
- message: `${issues.join('; ')}. Run \`gbrain dream --source <id>\` to cycle a source, or start \`gbrain autopilot\`.`,
- };
- }
- return {
- name: 'cycle_freshness',
- status: 'ok',
- message: `All ${sources.length} federated source(s) cycled recently`,
- };
- } catch (e) {
- return {
- name: 'cycle_freshness',
- status: 'warn',
- message: `Could not check cycle freshness: ${e instanceof Error ? e.message : String(e)}`,
- };
- }
-}
-
-/**
- * Run doctor with filesystem-first, DB-second architecture.
- * Filesystem checks (resolver, conformance) run without engine.
- * DB checks run only if engine is provided.
- *
- * `dbSource` is passed only from the `--fast` and DB-unavailable paths in
- * cli.ts so we can emit a precise "why no DB check" message. When null, the
- * user has no DB configured anywhere; otherwise the caller chose --fast or
- * we failed to connect despite a configured URL.
- */
-/**
- * Build the full check list for `gbrain doctor` against an engine + arg vector.
- *
- * The check-building seam: takes the same args as `runDoctor` minus the
- * --locks shortcut (locks-mode is a focused diagnostic the CLI wrapper
- * handles separately). Returns a `Check[]` array; the caller renders it
- * via `outputResults` and decides exit code. Early-exit cases (no engine,
- * connection failure) return a partial check array without calling
- * `process.exit` directly — the caller still renders + exits.
- *
- * v0.39 narrow-seam extract (audit-driven). The 10 `process.exit` sites
- * in this file all live in CLI wrappers (`runDoctor`, `runLocksCheck`,
- * the remediation subcommands). Behavioral tests drive `buildChecks`
- * directly via PGLite; the wrapper-level subprocess smoke in
- * `test/doctor-cli-smoke.test.ts` covers the render + exit paths that
- * a unit test can't reach in-process.
- *
- * Side effects retained inside buildChecks (kept for "no behavior change"):
- * - `printAutoFixReport` on `--fix` non-JSON path
- * - `progress` reporter writes to stderr (heartbeats per check)
- * - `engine.executeRaw` / handler-leaf calls (the actual probe work)
- */
-// ≥2 failed repair attempts inside 7 days = the corruption keeps regenerating.
-const REPAIR_RECURRENCE_WINDOW_MS = 7 * 24 * 3600 * 1000;
-const REPAIR_RECURRENCE_THRESHOLD = 2;
-
-/**
- * WAL-repair wave (#223/#1670/#2575): when the DB failed to connect on a
- * PGLite brain, diagnose the data dir from the FILESYSTEM (the connect error
- * itself was swallowed by doctor's fs-only fallback — this check re-derives
- * the state from disk). Pure: interprets an `inspectPgliteDataDir` diagnosis
- * into a Check; exported so `test/doctor-pglite-datadir.test.ts` drives it
- * directly (same convention as computeWorkerOomLoopCheck). Returns a Check
- * always — the call site only runs it when connect already failed, so even a
- * healthy-looking dir warrants a pointer at the repair tooling.
- *
- * Recurrence escalation (eng-review 2A): repeated failed repair attempts on
- * record mean the corruption keeps regenerating (unclean-shutdown genesis) —
- * escalate to the engine-switch ladder instead of letting the brain silently
- * lose a WAL tail per cycle. Backup-dir inventory rides along (same
- * disk-visibility class as orphan_clones).
- */
-export function computePgliteDataDirCheck(
- dataDir: string,
- diagnosis: import('../core/pglite-repair.ts').PgliteDirDiagnosis,
-): Check {
- const backupNote = diagnosis.backupDirs.length > 0
- ? ` ${diagnosis.backupDirs.length} repair backup dir(s) on disk (newest: ${diagnosis.backupDirs[0]}) — delete old ones to reclaim space once the brain is healthy.`
- : '';
- // Count BOTH outcomes (adversarial review F12): a >1h-period crash loop where
- // each repair "succeeds" discards a WAL tail per cycle with zero FAILED
- // attempts on record — escalation must still fire.
- const recentAttempts = diagnosis.recentAttempts.filter(
- (a) => Date.now() - a.ts < REPAIR_RECURRENCE_WINDOW_MS,
- ).length;
- const recurrence = recentAttempts >= REPAIR_RECURRENCE_THRESHOLD
- ? ` Auto-repair has run ${recentAttempts}x this week — the corruption keeps regenerating (likely an unclean-shutdown loop). Consider switching engines (docs/ENGINES.md: \`gbrain init --supabase\` or native Postgres).`
- : '';
-
- switch (diagnosis.verdict) {
- case 'locked':
- return {
- name: 'pglite_data_dir',
- status: 'warn',
- message:
- `Could not connect, and the PGLite data-dir lock is held by live PID ${diagnosis.lockHolderPid} — ` +
- `another gbrain process (often \`gbrain serve\`) has the brain open. Stop it and re-run.${backupNote}`,
- remediation_status: 'human_only',
- };
- case 'missing':
- return {
- name: 'pglite_data_dir',
- status: 'warn',
- message: `No PGLite data dir at ${dataDir}. Run \`gbrain init --pglite\` to create one.`,
- remediation_status: 'human_only',
- };
- case 'unsupported-layout':
- return {
- name: 'pglite_data_dir',
- status: 'fail',
- message:
- `PGLite data dir at ${dataDir} is not repairable in place (${diagnosis.detail}). ` +
- `Rebuild from your brain repo: \`gbrain reinit-pglite\` (or back up ~/.gbrain, move the dir aside, ` +
- `\`gbrain init --pglite\`, re-add sources + sync + embed).${backupNote}${recurrence}`,
- remediation_status: 'human_only',
- };
- case 'wal-corruption-likely':
- return {
- name: 'pglite_data_dir',
- status: 'fail',
- message:
- `PGLite failed to open and the data dir shows unclean-shutdown state (${diagnosis.detail}). ` +
- `This is the torn-WAL class behind issue #223 — repairable in place, data preserved: ` +
- `\`gbrain pglite-repair --dry-run\` to diagnose, \`gbrain pglite-repair --yes\` to repair.${backupNote}${recurrence}`,
- remediation_status: 'human_only',
- };
- case 'looks-healthy':
- default:
- return {
- name: 'pglite_data_dir',
- status: 'fail',
- message:
- `PGLite failed to open but the data dir layout validates (${diagnosis.detail}). ` +
- `IF the connect error mentions \`Aborted()\` this is likely torn WAL state — ` +
- `\`gbrain pglite-repair --dry-run\` to diagnose, \`gbrain pglite-repair --yes\` to repair in place ` +
- `(repair discards the un-checkpointed WAL tail — don't run it for lock-contention or ` +
- `catalog-corruption errors; 58P01/pgvector load failures need \`gbrain reinit-pglite\` instead).${backupNote}${recurrence}`,
- remediation_status: 'human_only',
- };
- }
-}
-
-/**
- * issue #1685 (GAP A) — the single authoritative "worker is OOM-looping" signal.
- *
- * One `gbrain doctor` line replaces the hours of log archaeology the #1678
- * incident required: `cap=8192MB, N watchdog kills/24h → raise --max-rss`.
- *
- * UNIONS two sources so it's authoritative for BOTH worker modes (CODEX #5):
- * - SUPERVISED workers: supervisor audit `worker_exited likely_cause=rss_watchdog`,
- * read cross-week (CODEX #7) so a Mon read doesn't lose a Sun loop.
- * - BARE `gbrain jobs work`: NO supervisor event is written; the only trace is
- * `minion_jobs.error_text = 'aborted: watchdog'` (the same source queue_health
- * subcheck 3 reads). Reading supervisor-only would miss bare workers entirely
- * and the queue_health cross-reference would point at an unemitted check.
- *
- * Cap (CODEX #6): the breaker alert stamps `max_rss_mb`, but a fail from
- * oomKills>=5 spread over 24h may have no breaker event → no stamped cap. Fall
- * back to `resolveDefaultMaxRssMb()` so the message always renders a number.
- *
- * Returns null when the worker never OOM'd (don't warn installs that never hit
- * it). Pure-ish: filesystem audit read + one minion_jobs count; no process.exit.
- * Exported so `test/doctor-worker-oom-loop.test.ts` drives it directly.
- */
-export async function computeWorkerOomLoopCheck(
- engine: BrainEngine | null,
-): Promise<Check | null> {
- let supervisorKills = 0;
- let capFromBreaker: number | null = null;
- let breakerTripped = false;
- try {
- const { readRecentSupervisorEvents, summarizeCrashes } = await import(
- '../core/minions/handlers/supervisor-audit.ts'
- );
- const events = readRecentSupervisorEvents(24);
- supervisorKills = summarizeCrashes(events).by_cause.rss_watchdog;
- // Latest rss_watchdog_loop breaker alert carries the cap the supervisor
- // spawned with (supervisor.ts:521); its presence also means the breaker
- // tripped. Walk all events; last one wins for the cap.
- for (const e of events) {
- const row = e as Record<string, unknown>;
- if (e.event === 'health_warn' && row.reason === 'rss_watchdog_loop') {
- breakerTripped = true;
- const cap = Number(row.max_rss_mb);
- if (Number.isFinite(cap) && cap > 0) capFromBreaker = cap;
- }
- }
- } catch {
- // supervisor-audit read is best-effort; fall through to minion_jobs.
- }
-
- let bareWorkerKills = 0;
- if (engine && engine.kind !== 'pglite') {
- try {
- const sql = db.getConnection();
- const rows: Array<{ cnt: number }> = await sql`
- SELECT count(*)::int AS cnt
- FROM minion_jobs
- WHERE status IN ('dead', 'failed')
- AND finished_at > now() - interval '24 hours'
- AND error_text = 'aborted: watchdog'
- `;
- bareWorkerKills = rows[0]?.cnt ?? 0;
- } catch {
- // minion_jobs may not exist on a fresh brain; best-effort.
- }
- }
-
- // De-dup note (CODEX #5 accepted trade-off): a supervised watchdog kill aborts
- // in-flight jobs, so it can show in BOTH counts. We accept slight over-count
- // rather than miss bare workers — the signal is "is it OOM-looping," not an
- // exact tally. `details` keeps the two sources separate for honesty.
- const oomKills = supervisorKills + bareWorkerKills;
- if (oomKills < 1 && !breakerTripped) return null;
-
- let capMb: number;
- let capSource: 'breaker' | 'default';
- if (capFromBreaker !== null) {
- capMb = capFromBreaker;
- capSource = 'breaker';
- } else {
- let def = 16384;
- try {
- const { resolveDefaultMaxRssMb } = await import('../core/minions/rss-default.ts');
- def = resolveDefaultMaxRssMb();
- } catch {
- // keep the conservative ceiling fallback.
- }
- capMb = def;
- capSource = 'default';
- }
-
- const fixHint =
- 'raise --max-rss (gbrain jobs work --max-rss <bigger>; auto-sizes to min(0.5×RAM,16GB))';
- const capLabel = capSource === 'breaker' ? `cap=${capMb}MB` : `cap≈${capMb}MB (auto-sized default)`;
- const status: Check['status'] = breakerTripped || oomKills >= 5 ? 'fail' : 'warn';
- return {
- name: 'worker_oom_loop',
- status,
- message:
- `Worker OOM-looping: ${capLabel}, ${oomKills} watchdog kill(s)/24h → ${fixHint}. ` +
- `Peak RSS: see worker stderr.`,
- details: {
- oom_kills: oomKills,
- supervisor_kills: supervisorKills,
- bare_worker_kills: bareWorkerKills,
- cap_mb: capMb,
- cap_source: capSource,
- breaker_tripped: breakerTripped,
- fix_hint: fixHint,
- },
- };
-}
-
-/**
- * issue #1685 (GAP B) — DB pool reap health (Postgres-only).
- *
- * Answers the #1685 line "DB pool reaped N times/hr AND not auto-recovering"
- * that no existing signal expresses. Reads the pool-recovery audit
- * (`reconnect()` emits reap_detected / reconnect_succeeded / reconnect_failed):
- * - fail: reaps>0 AND reconnect failures>0 → the pool is being reaped and
- * rebuilds are throwing (genuinely not recovering).
- * - warn: reaps>=10/hr, all recovered → pooler thrash (self-heal works but the
- * cap is likely too low / concurrency too high).
- * - else: null (quiet — a few reaps that all recovered is normal).
- *
- * Returns null on PGLite / no engine / audit-read failure. Exported so
- * `test/doctor-pool-reap-health.test.ts` drives it directly.
- */
-export async function computePoolReapHealthCheck(
- engine: BrainEngine | null,
-): Promise<Check | null> {
- if (!engine || engine.kind === 'pglite') return null;
- let r: { reaps: number; recoveries: number; failures: number };
- try {
- const { readRecentPoolRecoveries } = await import('../core/audit/pool-recovery-audit.ts');
- r = readRecentPoolRecoveries(1);
- } catch {
- return null;
- }
-
- // CODEX (impl review #3): the audit counts independent event kinds — it does
- // NOT correlate a reconnect_failed to a preceding reap. So `reaps>0 AND
- // failures>0` would falsely report "not auto-recovering" when a recovered reap
- // and an unrelated reconnect failure merely co-occur in the same hour. Fail on
- // the reconnect FAILURES themselves (reconnect throwing is the real, actionable
- // problem regardless of reaps); report reaps as context, not as a causal claim.
- if (r.failures > 0) {
- const fix = 'check DB reachability / credentials (reconnect is throwing)';
- return {
- name: 'pool_reap_health',
- status: 'fail',
- message:
- `DB reconnect FAILED ${r.failures}× in last hour (${r.reaps} pooler reap(s) detected) ` +
- `— reconnect is throwing; ${fix}.`,
- details: { reaps: r.reaps, recoveries: r.recoveries, failures: r.failures, fix_hint: fix },
- };
- }
- if (r.reaps >= 10) {
- const fix = 'raise --max-rss or reduce worker concurrency (pooler thrash)';
- return {
- name: 'pool_reap_health',
- status: 'warn',
- message:
- `DB pool reaped ${r.reaps}× in last hour (self-heal recovered each) ` +
- `— ${fix}.`,
- details: { reaps: r.reaps, recoveries: r.recoveries, failures: r.failures, fix_hint: fix },
- };
- }
- return null;
-}
-
-/**
- * Retrieval Reflex health (#1981). Read-only, fail-open. The deterministic
- * pointer layer is on by default; this reports the TRUTH, not an aspiration:
- * - config/env disabled → warn (pointer layer off)
- * - heartbeat fired recently → ok, "active" (it's demonstrably working,
- * whatever path — Postgres/IPC/host)
- * - enabled, no recent heartbeat → ok if a viable path looks present
- * (postgres, or pglite serve socket),
- * else warn (likely inactive — policy
- * skill carries). Never claims a host
- * capability it can't observe.
- * Policy-skill install state is reported in details (it ships into the HOST
- * repo, so absence in gbrain's own skills dir is expected, not a failure).
- */
-/**
- * MEMORY_VERBS v1 (Cathedral 1, E4) — usage-sidecar health. Read-only,
- * fail-open. Stats only (local JSONL, never uploaded; never source of truth):
- * - no sidecar file → ok, "no verb calls recorded yet" (fresh install)
- * - recent events parse → ok, names the last verb + timestamp
- * - file exists, unreadable→ warn (observability degraded, verbs unaffected)
- */
-export async function buildMemoryVerbsCheck(): Promise<Check> {
- const name = 'memory_verbs_usage';
- try {
- const { readVerbUsage, usageLogPath } = await import('../core/verbs/usage-log.ts');
- if (!existsSync(usageLogPath())) {
- return {
- name,
- status: 'ok',
- message: 'no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)',
- };
- }
- const events = await readVerbUsage({ days: 30 });
- if (events.length === 0) {
- return { name, status: 'ok', message: 'sidecar present; no verb calls in the last 30 days' };
- }
- const last = events[events.length - 1];
- const byVerb = new Map<string, number>();
- for (const e of events) byVerb.set(e.verb, (byVerb.get(e.verb) ?? 0) + 1);
- const mix = [...byVerb.entries()].map(([v, n]) => `${v}:${n}`).join(' ');
- return {
- name,
- status: 'ok',
- message: `${events.length} verb calls in 30d (${mix}); last ${last.verb} at ${last.ts} — local JSONL only, never uploaded`,
- };
- } catch (e) {
- return {
- name,
- status: 'warn',
- message: `verb usage sidecar unreadable (${e instanceof Error ? e.message : String(e)}) — observability degraded; verbs unaffected`,
- };
- }
-}
-
-export function buildRetrievalReflexCheck(skillsDir: string | null): Check {
- const name = 'retrieval_reflex_health';
- try {
- const cfg = loadConfig();
- const enabled = reflexEnabled(cfg);
- const engineKind = cfg?.engine ?? 'unknown';
- const skillInstalled = !!skillsDir && existsSync(join(skillsDir, 'retrieval-reflex', 'SKILL.md'));
+ parts.push(`skipping known-bad: ${failedVersions.join(', ')}`);
+ }
- if (!enabled) {
+ const recent = readRecentSelfUpgrades(7) as Array<{ outcome?: string; error?: string; latest?: string | null }>;
+ const failures = recent.filter((e) => e.outcome === 'failed');
+ if (failures.length > 0) {
+ const last = failures[failures.length - 1];
return {
- name,
- status: 'ok',
- message: 'retrieval reflex intentionally disabled (config/env) — entity pointer layer off',
- details: { enabled: false, engine: engineKind, policy_skill_installed: skillInstalled },
+ name: 'self_upgrade_health',
+ status: 'warn',
+ message:
+ `${failures.length} self-upgrade failure(s) in 7d (${parts.join('; ')}). ` +
+ `Last: ${last.latest ?? '?'}${last.error ? ` — ${last.error}` : ''}. ` +
+ `Check ~/.gbrain/upgrade-errors.jsonl; apply manually with gbrain self-upgrade.`,
};
}
- // Heartbeat is the authority for "is it firing".
- const hbPath = join(homedir(), '.gbrain', 'integrations', 'retrieval-reflex', 'heartbeat.jsonl');
- let lastFired: string | null = null;
- try {
- if (existsSync(hbPath)) {
- const lines = readFileSync(hbPath, 'utf8').trim().split('\n').filter(Boolean);
- const last = lines.length ? JSON.parse(lines[lines.length - 1]) : null;
- if (last && typeof last.ts === 'string') lastFired = last.ts;
- }
- } catch { /* heartbeat unreadable — treat as never fired */ }
- const firedRecently =
- !!lastFired && Date.now() - new Date(lastFired).getTime() < 7 * 24 * 60 * 60 * 1000;
-
- // Detect a viable resolve path the doctor CAN see (host ctx.brainQuery is invisible).
- let pathDesc: string;
- let viablePathVisible: boolean;
- if (engineKind === 'postgres') {
- pathDesc = 'postgres direct';
- viablePathVisible = true;
- } else if (engineKind === 'pglite' && cfg?.database_path) {
- const socket = resolveSocketPath(cfg.database_path);
- viablePathVisible = existsSync(socket);
- pathDesc = viablePathVisible ? 'pglite via serve IPC' : 'pglite — serve IPC socket not present';
- } else {
- pathDesc = `engine ${engineKind}`;
- viablePathVisible = false;
- }
-
- const runtimeMsg = firedRecently
- ? `active (last fired ${lastFired})`
- : viablePathVisible
- ? 'enabled; not observed firing yet'
- : 'enabled but no observed activity and no visible resolve path (host capability may still supply it; policy skill carries otherwise)';
-
- const status: Check['status'] = firedRecently || viablePathVisible ? 'ok' : 'warn';
- const skillHint = skillInstalled
- ? ''
- : ' — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`';
+ return { name: 'self_upgrade_health', status: 'ok', message: parts.join('; ') };
+ } catch (e) {
return {
- name,
- status,
- message: `${pathDesc}; ${runtimeMsg}${skillHint}`,
- details: {
- enabled: true,
- engine: engineKind,
- path: pathDesc,
- fired_recently: firedRecently,
- last_fired: lastFired,
- policy_skill_installed: skillInstalled,
- },
+ name: 'self_upgrade_health',
+ status: 'ok',
+ message: `Self-upgrade status unavailable (${e instanceof Error ? e.message : String(e)})`,
};
- } catch (e) {
- return { name, status: 'warn', message: `could not check: ${(e as Error).message}` };
}
}
+/**
+ * Re-exported from `src/core/env-number.ts`, which now owns the implementation
+ * AND the warn-once memo. `source-health.ts` needs the hours resolver for the
+ * staleness ceiling, and doctor already imports from source-health — so the
+ * helper had to move to core or the import graph would cycle.
+ *
+ * The `_resolveEnvNumber` name is kept because `sync.ts:5730` dynamically
+ * imports it from this module.
+ */
+export { resolveEnvNumber as _resolveEnvNumber };
+
+/** Local aliases; the shared memo lives in core so it can't fork per module. */
+const _resolveEnvNumber = resolveEnvNumber;
+const _resolveSyncFreshnessHours = resolveHoursEnv;
+
+/**
+ * Run doctor with filesystem-first, DB-second architecture.
+ * Filesystem checks (resolver, conformance) run without engine.
+ * DB checks run only if engine is provided.
+ *
+ * `dbSource` is passed only from the `--fast` and DB-unavailable paths in
+ * cli.ts so we can emit a precise "why no DB check" message. When null, the
+ * user has no DB configured anywhere; otherwise the caller chose --fast or
+ * we failed to connect despite a configured URL.
+ */
+/**
+ * Build the full check list for `gbrain doctor` against an engine + arg vector.
+ *
+ * The check-building seam: takes the same args as `runDoctor` minus the
+ * --locks shortcut (locks-mode is a focused diagnostic the CLI wrapper
+ * handles separately). Returns a `Check[]` array; the caller renders it
+ * via `outputResults` and decides exit code. Early-exit cases (no engine,
+ * connection failure) return a partial check array without calling
+ * `process.exit` directly — the caller still renders + exits.
+ *
+ * v0.39 narrow-seam extract (audit-driven). The 10 `process.exit` sites
+ * in this file all live in CLI wrappers (`runDoctor`, `runLocksCheck`,
+ * the remediation subcommands). Behavioral tests drive `buildChecks`
+ * directly via PGLite; the wrapper-level subprocess smoke in
+ * `test/doctor-cli-smoke.test.ts` covers the render + exit paths that
+ * a unit test can't reach in-process.
+ *
+ * Side effects retained inside buildChecks (kept for "no behavior change"):
+ * - `printAutoFixReport` on `--fix` non-JSON path
+ * - `progress` reporter writes to stderr (heartbeats per check)
+ * - `engine.executeRaw` / handler-leaf calls (the actual probe work)
+ */
export async function buildChecks(
engine: BrainEngine | null,
args: string[],
@@ -8717,461 +3640,78 @@ export async function buildChecks(
// v0.37.0 brainstorm_health — migration v79, track_retrieval, calibration cold-start.
progress.heartbeat('brainstorm_health');
checks.push(await checkBrainstormHealth(engine));
- // issue #972 link_resolution_opportunity — full scan: count bare wikilinks
- // that would resolve under global_basename mode. Surfaces a paste-ready
- // enable hint when ≥5 hits AND ≥20% of bare wikilinks would resolve.
- // Skipped silently when the flag is already enabled. Bounded by a 60s
- // budget so a huge brain never wedges doctor on this check.
- progress.heartbeat('link_resolution_opportunity');
- checks.push(await checkLinkResolutionOpportunity(engine, progress));
- // v0.36.0.0 (A5): ZE embedding key health + schema/config width consistency.
- progress.heartbeat('ze_embedding_health');
- checks.push(await checkZeEmbeddingHealth(engine));
- // provider_sunset — brain pinned to a provider with an announced
- // hosted-API shutdown; paste-ready migration hint with the actual
- // column width. Warn before the date, fail after.
- progress.heartbeat('provider_sunset');
- checks.push(await checkProviderSunset(engine));
- progress.heartbeat('embedding_width_consistency');
- checks.push(await checkEmbeddingWidthConsistency(engine));
- // v0.41.15.0 (T6, codex #19/#20) — facts.embedding column drift
- // parity check. Same drift class as content_chunks, separate column.
- progress.heartbeat('facts_embedding_width_consistency');
- checks.push(await checkFactsEmbeddingWidthConsistency(engine));
-
- // v0.37.7.0 doctor checks (#1167, #1166, #1226) — fast-mode skipped
- // since these touch DB queries with cost on large brains.
- // 5K — source_routing_health (D5 lock: 200-page total cap)
- progress.heartbeat('source_routing_health');
- checks.push(await checkSourceRoutingHealth(engine));
- // 5L — oauth_confidential_client_health (success-path probe per codex CF8)
- progress.heartbeat('oauth_confidential_client_health');
- checks.push(await checkOauthConfidentialHealth(engine));
- // 5M — autopilot_lock_scope (PID-safe hint per codex CF11)
- progress.heartbeat('autopilot_lock_scope');
- checks.push(checkAutopilotLockScope());
- // v0.41.6.0 D3 — stale_locks (gbrain_cycle_locks rows with ttl_expires_at < NOW())
- progress.heartbeat('stale_locks');
- checks.push(await checkStaleLocks(engine, { fix: doFix, dryRun }));
- // v0.38 — cycle_phase_scope (informational; no DB cost)
- progress.heartbeat('cycle_phase_scope');
- checks.push(checkCyclePhaseScope());
-
- // v0.41.18.0 (A16, T4): 4 onboard checks — each emits a Check + its
- // own RemediationStep[] aggregated by onboard's plan path. The
- // checks themselves are cheap counts (backed by content_chunks_stale_idx
- // for embed_staleness, TABLESAMPLE on PG >50K for the coverage pair).
- progress.heartbeat('onboard_checks');
- const { runAllOnboardChecks } = await import('../core/onboard/checks.ts');
- const onboardResults = await runAllOnboardChecks(engine);
- for (const r of onboardResults) checks.push(r.check);
- }
-
- progress.finish();
-
- return checks;
-}
-
-/**
- * CLI entry point for `gbrain doctor`. Thin wrapper around buildChecks +
- * computeDoctorReport + render + process.exit.
- *
- * Concerns kept here (not pushed into buildChecks):
- * - --locks shortcut (focused diagnostic; calls runLocksCheck + returns)
- * - outputResults render (stdout)
- * - features teaser (non-JSON, non-failing only)
- * - process.exit (10 sites total across runDoctor + runLocksCheck +
- * runRemediationPlan + runRemediate)
- *
- * v0.39 narrow-seam extract — buildChecks is the unit-testable seam, this
- * wrapper is the wallclock + exit-code concerned function. See
- * test/doctor-behavioral.test.ts for the in-process seam coverage and
- * test/doctor-cli-smoke.test.ts for the subprocess wrapper coverage.
- */
-/**
- * Agent-bootstrap check group (plan B2, B4, ENG-4, one-live-serve, C1 skew).
- *
- * Gated on bootstrap state actually existing on this machine (install
- * receipt, hook heartbeat, or push-status) — machines that never ran
- * `gbrain bootstrap` get ZERO checks from this group. Every probe is
- * fail-soft: a broken telemetry file degrades to a warn, never a throw.
- */
-export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise<Check[]> {
- const checks: Check[] = [];
- let home: string;
- try {
- home = resolveGbrainHome();
- } catch {
- return [];
- }
-
- // 00. Plugin-lane coexistence. Runs BEFORE the bootstrap-state gate: a
- // hand-wired registration can coexist with a plugin on machines that never
- // ran `gbrain bootstrap`. Emits rows ONLY when a gbrain plugin is ENABLED
- // in a harness config (machines without the plugin get zero noise):
- // warn = a hand-wired registration also exists (duplicate tool
- // registration; which server wins is host-defined), ok = the plugin is the
- // sole owner. "Enabled" is a CONFIG signal, not a health signal — the row
- // says so. Fail-soft like every probe in this group.
- try {
- const {
- codexPluginProvidesName,
- claudePluginProvidesName,
- codexAnyRegistrationExists,
- claudeAnyRegistrationExists,
- } = await import('../core/bootstrap/harness.ts');
- const { codexConfigPath, claudeUserSettingsPath, claudeUserMcpConfigPath } = await import('../core/bootstrap/host-specs.ts');
- const claudeUserMcpConfig = claudeUserMcpConfigPath();
- const lanes: Array<{ harness: string; plugin: string; dup: boolean; disambiguate: string }> = [];
- const codexPlugin = codexPluginProvidesName(codexConfigPath(), 'gbrain');
- if (codexPlugin) {
- lanes.push({
- harness: 'codex',
- plugin: codexPlugin,
- dup: codexAnyRegistrationExists(codexConfigPath(), 'gbrain'),
- disambiguate: 'keep one owner: `codex mcp remove gbrain` (drop the hand-wired entry) or `codex plugin remove gbrain@gbrain` (drop the plugin)',
- });
- }
- const claudePlugin = claudePluginProvidesName(claudeUserSettingsPath(), 'gbrain');
- if (claudePlugin) {
- lanes.push({
- harness: 'claude-code',
- plugin: claudePlugin,
- dup: claudeAnyRegistrationExists(claudeUserMcpConfig, 'gbrain', process.cwd()),
- disambiguate: 'keep one owner: `claude mcp remove gbrain` (drop the hand-wired entry) or disable the plugin in Claude Code',
- });
- }
- for (const lane of lanes) {
- checks.push(
- lane.dup
- ? {
- name: 'plugin_lane_collision',
- status: 'warn',
- message:
- `${lane.harness}: the '${lane.plugin}' plugin AND a hand-wired gbrain MCP registration both exist — ` +
- `duplicate tool registration is host-defined behavior; ${lane.disambiguate}. ` +
- '(Plugin enabled is a config signal, not a health signal.)',
- }
- : {
- name: 'plugin_lane_collision',
- status: 'ok',
- message: `${lane.harness}: the '${lane.plugin}' plugin provides gbrain and no hand-wired registration was found in the scanned configs (user scope + this directory).`,
- },
- );
- }
- } catch {
- /* fail-soft: a broken harness config never breaks doctor */
- }
-
- const receipt = readReceipt(home);
- // One reader for every push-status surface [D8]; per-root files [D13].
- const { readPushStatuses, pushStatusFilesExist } = await import('../core/workspace-push.ts');
- const pushStatuses = readPushStatuses();
- const statusFilesOnDisk = pushStatusFilesExist();
- const heartbeatFile = join(home, 'integrations', 'hooks', 'heartbeat.jsonl');
- // #4043: a harness-only box (bootstrap harness, no workspace install) is
- // bootstrap state too — without this, such a machine gets ZERO checks.
- const harnessState = readHarnessReceiptState(home);
- const hasBootstrapState =
- receipt !== null || statusFilesOnDisk || existsSync(heartbeatFile) || harnessState.state !== 'absent';
- // Return the pre-gate rows (plugin-lane coexistence) even on machines with
- // no bootstrap state — the plugin lane needs no bootstrap to exist.
- if (!hasBootstrapState) return checks;
-
- const ws = receipt?.workspace_dir ?? null;
-
- // 0. Harness registration health (#4043): three states so it neither cries
- // wolf nor goes silent — skip (not a harness box) / warn (serve unreachable,
- // a normal transient; or receipt unreadable) / fail (a target failed, or a
- // prior rotation never converged). Token liveness needs the bearer (only
- // recoverable from host config) — that's `gbrain bootstrap harness
- // --status`'s job; doctor stays offline-cheap.
- if (harnessState.state === 'ok') {
- const hr = harnessState.receipt;
- const failed = hr.targets.filter((t) => t.state === 'failed');
- const pending = hr.targets.filter((t) => t.state === 'pending');
- if (failed.length > 0 || pending.length > 0) {
- checks.push({
- name: 'bootstrap_harness_health',
- status: 'fail',
- message:
- `harness wiring incomplete: ${failed.length} failed / ${pending.length} pending target(s)` +
- ` — re-run \`gbrain bootstrap harness\` to converge (details: gbrain bootstrap harness --status).`,
- });
- } else if (hr.token.previous_ids && hr.token.previous_ids.length > 0) {
- checks.push({
- name: 'bootstrap_harness_health',
- status: 'fail',
- message: `${hr.token.previous_ids.length} previous harness token(s) were never revoked (ids ${hr.token.previous_ids.join(', ')}) — re-run \`gbrain bootstrap harness\`, or run \`gbrain auth revoke\` with the id flag per id.`,
- });
- } else if (hr.targets.length === 0 && hr.token.minted && hr.token.id !== undefined) {
- // Half-removed state: a remove under a live PGLite serve strips every
- // host target but defers the revoke — the wiring is gone yet the minted
- // token stays ACTIVE. A vacuous all-confirmed must not read green.
- // (Flag names spelled without dashes here: the flag-registry generator
- // harvests bare flag tokens from comments one import level deep.)
- checks.push({
- name: 'bootstrap_harness_health',
- status: 'fail',
- message: `harness removal pending: host wiring removed but the minted token (id ${hr.token.id}) is not yet revoked — stop the serve and re-run \`gbrain bootstrap harness\` with the remove flag, or run \`gbrain auth revoke\` with the id flag.`,
- });
- } else {
- try {
- const base = hr.url.replace(/\/mcp$/, '');
- const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
- const body = res.ok ? ((await res.json()) as { status?: string }) : null;
- if (body?.status === 'ok') {
- checks.push({
- name: 'bootstrap_harness_health',
- status: 'ok',
- message: `harness wired to ${hr.url} (serve healthy; token check: gbrain bootstrap harness --status)`,
- });
- } else {
- checks.push({
- name: 'bootstrap_harness_health',
- status: 'warn',
- message: `harness wired to ${hr.url} but the serve is not answering /health — start \`gbrain serve\` in http mode (a down serve is a normal transient, sessions just lose brain access until it returns).`,
- });
- }
- } catch {
- checks.push({
- name: 'bootstrap_harness_health',
- status: 'warn',
- message: `harness wired to ${hr.url} but the serve is unreachable — start \`gbrain serve\` in http mode.`,
- });
- }
- }
- } else if (harnessState.state !== 'absent') {
- checks.push({
- name: 'bootstrap_harness_health',
- status: 'warn',
- message: `the harness receipt is unreadable (${harnessState.state}) — see \`gbrain bootstrap harness --status\`.`,
- });
- }
-
- // 1. Hook heartbeat failure rate [B3 read side]. Hard errors only —
- // degraded entries are DESIGNED fallbacks (pull-mode, no serve).
- let hooksSeen = false;
- try {
- const { readHeartbeatTail, HEARTBEAT_FAILURE_WINDOW, HEARTBEAT_FAILURE_RATE_THRESHOLD } =
- await import('./hook.ts');
- const tail = await readHeartbeatTail(HEARTBEAT_FAILURE_WINDOW);
- if (tail.length > 0) {
- hooksSeen = true;
- const failures = tail.filter((e) => e.outcome === 'error').length;
- const rate = failures / tail.length;
- if (rate > HEARTBEAT_FAILURE_RATE_THRESHOLD) {
- checks.push({
- name: 'bootstrap_hooks_heartbeat',
- status: 'fail',
- message: `${failures}/${tail.length} recent hook invocations hard-failed — brain context is not reaching the session. Check \`gbrain bootstrap verify\` and the serve process.`,
- });
- } else if (rate > 0.2) {
- checks.push({
- name: 'bootstrap_hooks_heartbeat',
- status: 'warn',
- message: `${failures}/${tail.length} recent hook invocations hard-failed. Watch it; hooks fail open so sessions still work.`,
- });
- } else {
- checks.push({
- name: 'bootstrap_hooks_heartbeat',
- status: 'ok',
- message: `hook heartbeat healthy (${failures}/${tail.length} hard failures in the trailing window)`,
- });
- }
- }
- } catch {
- checks.push({ name: 'bootstrap_hooks_heartbeat', status: 'warn', message: 'hook heartbeat unreadable' });
- }
-
- // 2. Push staleness [B4]: fail when the last successful push is >48h old
- // AND the workspace tree is dirty (recent work provably unpushed). Per-root
- // status files [D13]: the WORST entry decides, so one workspace's success
- // can never mask another's failure.
- try {
- if (pushStatuses.length > 0) {
- const { PUSH_STALE_MS } = await import('./hook.ts'); // hook.ts owns the threshold (single source)
- const failing = pushStatuses.filter((s) => s.ok === false);
- if (failing.length > 0) {
- const s = failing[0]!;
- const target = s.repoRoot ?? ws ?? undefined;
- const rest = failing.length > 1 ? ` [+${failing.length - 1} more workspace(s)]` : '';
- checks.push({
- name: 'bootstrap_push_health',
- status: 'warn',
- message: `last workspace push FAILED${target ? ` for ${target}` : ''} (${s.ts ?? 'unknown'}): ${s.reason ?? 'unknown'}${rest} — run \`gbrain sources push${target ? ` --path ${target}` : ''}\``,
- });
- } else {
- const stamps = pushStatuses.map((s) => Date.parse(s.ts ?? '')).filter((t) => Number.isFinite(t));
- const stalest = stamps.length > 0 ? Math.min(...stamps) : NaN;
- const staleIso = Number.isFinite(stalest) ? new Date(stalest).toISOString() : 'unknown';
- const stale = Number.isFinite(stalest) && Date.now() - stalest > PUSH_STALE_MS;
- let dirty = false;
- if (ws) {
- try {
- dirty = execFileSync('git', ['-C', ws, 'status', '--porcelain'], {
- stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000,
- }).toString().trim() !== '';
- } catch { dirty = false; }
- }
- if (stale && dirty) {
- checks.push({
- name: 'bootstrap_push_health',
- status: 'fail',
- message: `last successful push ${staleIso} (>48h) with a DIRTY workspace tree — recent agent memory is unpushed [B4]. Run \`gbrain sources push --path ${ws}\`.`,
- });
- } else if (stale) {
- checks.push({ name: 'bootstrap_push_health', status: 'warn', message: `last successful push ${staleIso} (>48h ago); tree clean — likely just idle` });
- } else {
- checks.push({ name: 'bootstrap_push_health', status: 'ok', message: `last push ok (${staleIso})` });
- }
- }
- } else if (statusFilesOnDisk) {
- // Files exist but none parsed — the tolerant reader skips corrupt
- // records; doctor must not let that read as "no news is good news".
- checks.push({ name: 'bootstrap_push_health', status: 'warn', message: 'push status unreadable' });
- }
- } catch {
- checks.push({ name: 'bootstrap_push_health', status: 'warn', message: 'push status unreadable' });
- }
-
- // 2b. Durability job [B7/D7]: presence + LIVENESS. A presence-only check
- // certifies dead jobs as healthy (the autopilot-status failure mode), so
- // this warns on plist-present-but-unloaded and stale pull logs. Only warns
- // when the user actually consented to the job; containers/cloud sandboxes
- // are expected to have none.
- try {
- if (ws !== null && receipt !== null) {
- const { detectExecutionEnvironment } = await import('../core/execution-env.ts');
- const envKind = detectExecutionEnvironment();
- if (envKind !== 'local') {
- // Answered BEFORE the subprocess probes — cloud/container doctor
- // runs must not pay launchctl/crontab spawns for an answer that is
- // discarded (no scheduler exists there by design).
- checks.push({
- name: 'bootstrap_durability_job',
- status: 'ok',
- message: `no scheduler in this environment (${envKind}) — expected; per-turn and session-end pushes cover persistence`,
- });
- } else {
- const { durabilityJobStatus } = await import('../core/brain-repo-durability.ts');
- const { readInterviewState } = await import('../core/bootstrap/interview.ts');
- const sourceId = receipt.source_id ?? 'workspace';
- const js = durabilityJobStatus(sourceId);
- let consented = false;
- try {
- const iv = readInterviewState(ws);
- consented = iv.ok && (iv.state.answers['PERSIST_CRON']?.value ?? '').toLowerCase() === 'yes';
- } catch { consented = false; }
- if (!consented) {
- if (js.kind !== 'none') {
- checks.push({ name: 'bootstrap_durability_job', status: 'ok', message: `${js.kind} pull job present (not required by consent — fine)` });
- }
- // no consent + no job → nothing to check; stay silent
- } else if (js.kind === 'none') {
- checks.push({
- name: 'bootstrap_durability_job',
- status: 'warn',
- message: `background persistence was consented (PERSIST_CRON=yes) but no scheduled job exists — run \`gbrain sources harden ${sourceId}\``,
- });
- } else if (js.live === false) {
- checks.push({
- name: 'bootstrap_durability_job',
- status: 'warn',
- message: `${js.kind} job is on disk but NOT loaded — a dead job looks healthy to presence checks. Re-run \`gbrain sources harden ${sourceId}\` to reload it.`,
- });
- } else if (!js.wrapperPresent) {
- checks.push({
- name: 'bootstrap_durability_job',
- status: 'warn',
- message: `${js.kind} job exists but its wrapper script is missing — re-run \`gbrain sources harden ${sourceId}\``,
- });
- } else if (js.logFresh === false) {
- checks.push({
- name: 'bootstrap_durability_job',
- status: 'warn',
- message: `${js.kind} job present but the pull log is stale (no run within 2× the interval) — the job may be dead; re-run \`gbrain sources harden ${sourceId}\``,
- });
- } else if (js.kind === 'crontab' && js.logFresh === undefined) {
- // The crontab LINE existing proves installation, not that the cron
- // daemon runs it — with no pull log yet we can't claim liveness.
- checks.push({ name: 'bootstrap_durability_job', status: 'ok', message: 'crontab pull job installed (no run logged yet — liveness confirmed once it first fires)' });
- } else {
- checks.push({ name: 'bootstrap_durability_job', status: 'ok', message: `${js.kind} pull job present and live` });
- }
- }
- }
- } catch { /* best-effort — durability probing never fails doctor */ }
-
- // 3. One-live-serve / lock collision note. A live serve is the healthy
- // shape (it provides hook IPC); the note names the v1 contract.
- try {
- const dataDir = resolveBrainDataDir(home);
- const holder = probeLivePgliteHolder(dataDir);
- if (holder) {
- checks.push({
- name: 'bootstrap_serve_lock',
- status: holder.serve ? 'ok' : 'warn',
- message: holder.serve
- ? `live serve (pid ${holder.pid}) owns the brain — hook IPC available. One live serve per brain is the v1 contract; a second simultaneous session collides politely.`
- : `a non-serve gbrain process (pid ${holder.pid}) holds the PGLite lock — hook IPC and new sessions will fail until it exits.`,
- });
- }
- } catch { /* probe is best-effort */ }
+ // issue #972 link_resolution_opportunity — full scan: count bare wikilinks
+ // that would resolve under global_basename mode. Surfaces a paste-ready
+ // enable hint when ≥5 hits AND ≥20% of bare wikilinks would resolve.
+ // Skipped silently when the flag is already enabled. Bounded by a 60s
+ // budget so a huge brain never wedges doctor on this check.
+ progress.heartbeat('link_resolution_opportunity');
+ checks.push(await checkLinkResolutionOpportunity(engine, progress));
+ // v0.36.0.0 (A5): ZE embedding key health + schema/config width consistency.
+ progress.heartbeat('ze_embedding_health');
+ checks.push(await checkZeEmbeddingHealth(engine));
+ // provider_sunset — brain pinned to a provider with an announced
+ // hosted-API shutdown; paste-ready migration hint with the actual
+ // column width. Warn before the date, fail after.
+ progress.heartbeat('provider_sunset');
+ checks.push(await checkProviderSunset(engine));
+ progress.heartbeat('embedding_width_consistency');
+ checks.push(await checkEmbeddingWidthConsistency(engine));
+ // v0.41.15.0 (T6, codex #19/#20) — facts.embedding column drift
+ // parity check. Same drift class as content_chunks, separate column.
+ progress.heartbeat('facts_embedding_width_consistency');
+ checks.push(await checkFactsEmbeddingWidthConsistency(engine));
- // 4. [ENG-4] Hooks-in-use + unmigrated brain: the direct-engine hook paths
- // swallow missing-table errors on pre-v110/v117 schemas, so context
- // degrades SILENTLY. Pair the two signals into a named warning.
- const hooksActive = hooksSeen || (ws !== null && hooksInstalled(ws));
- if (hooksActive && engine) {
- try {
- const versionStr = await engine.getConfig('version');
- const version = parseInt(versionStr || '0', 10);
- if (version < LATEST_VERSION) {
- checks.push({
- name: 'bootstrap_hook_schema_pairing',
- status: 'warn',
- message: `hooks are in use but the brain schema is v${version} (< v${LATEST_VERSION}) — hook context can degrade silently on missing tables [ENG-4]. Run \`gbrain apply-migrations --yes\`.`,
- });
- }
- } catch { /* schema_version check above already covers unreadable version */ }
- }
+ // v0.37.7.0 doctor checks (#1167, #1166, #1226) — fast-mode skipped
+ // since these touch DB queries with cost on large brains.
+ // 5K — source_routing_health (D5 lock: 200-page total cap)
+ progress.heartbeat('source_routing_health');
+ checks.push(await checkSourceRoutingHealth(engine));
+ // 5L — oauth_confidential_client_health (success-path probe per codex CF8)
+ progress.heartbeat('oauth_confidential_client_health');
+ checks.push(await checkOauthConfidentialHealth(engine));
+ // 5M — autopilot_lock_scope (PID-safe hint per codex CF11)
+ progress.heartbeat('autopilot_lock_scope');
+ checks.push(checkAutopilotLockScope());
+ // v0.41.6.0 D3 — stale_locks (gbrain_cycle_locks rows with ttl_expires_at < NOW())
+ progress.heartbeat('stale_locks');
+ checks.push(await checkStaleLocks(engine, { fix: doFix, dryRun }));
+ // v0.38 — cycle_phase_scope (informational; no DB cost)
+ progress.heartbeat('cycle_phase_scope');
+ checks.push(checkCyclePhaseScope());
- // 5. Runbook skew [C1]: the fetched runbook's stamp vs this binary.
- if (ws) {
- try {
- const stamp = readRunbookStamp(ws);
- if (stamp !== null && stamp !== GBRAIN_BINARY_VERSION) {
- checks.push({
- name: 'bootstrap_runbook_skew',
- status: 'warn',
- message: `BOOTSTRAP_FOR_AGENTS.md stamp ${stamp} != installed binary ${GBRAIN_BINARY_VERSION} — prefer the binary's instructions; re-fetch the runbook.`,
- });
- }
- } catch { /* best effort */ }
+ // v0.41.18.0 (A16, T4): 4 onboard checks — each emits a Check + its
+ // own RemediationStep[] aggregated by onboard's plan path. The
+ // checks themselves are cheap counts (backed by content_chunks_stale_idx
+ // for embed_staleness, TABLESAMPLE on PG >50K for the coverage pair).
+ progress.heartbeat('onboard_checks');
+ const { runAllOnboardChecks } = await import('../core/onboard/checks.ts');
+ const onboardResults = await runAllOnboardChecks(engine);
+ for (const r of onboardResults) checks.push(r.check);
}
- // 6. Last verify freshness [B2 read side] — surfaced so "verify weekly"
- // has a nag with teeth.
- try {
- const runs = listVerifyRuns(home);
- if (runs.length > 0) {
- const last = runs[0];
- const t = Date.parse(last.ts);
- const ageDays = Number.isFinite(t) ? (Date.now() - t) / 86_400_000 : NaN;
- if (!last.ok) {
- checks.push({ name: 'bootstrap_last_verify', status: 'warn', message: `last bootstrap verify FAILED (${last.ts}): ${last.checks_failed.join(', ') || 'see snapshot'} — re-run \`gbrain bootstrap verify\`` });
- } else if (Number.isFinite(ageDays) && ageDays > 14) {
- checks.push({ name: 'bootstrap_last_verify', status: 'warn', message: `last bootstrap verify passed ${Math.floor(ageDays)}d ago — re-run it as the workspace rot self-check` });
- } else {
- checks.push({ name: 'bootstrap_last_verify', status: 'ok', message: `last verify passed (${last.ts})` });
- }
- }
- } catch { /* best effort */ }
+ progress.finish();
return checks;
}
+/**
+ * CLI entry point for `gbrain doctor`. Thin wrapper around buildChecks +
+ * computeDoctorReport + render + process.exit.
+ *
+ * Concerns kept here (not pushed into buildChecks):
+ * - --locks shortcut (focused diagnostic; calls runLocksCheck + returns)
+ * - outputResults render (stdout)
+ * - features teaser (non-JSON, non-failing only)
+ * - process.exit (10 sites total across runDoctor + runLocksCheck +
+ * runRemediationPlan + runRemediate)
+ *
+ * v0.39 narrow-seam extract — buildChecks is the unit-testable seam, this
+ * wrapper is the wallclock + exit-code concerned function. See
+ * test/doctor-behavioral.test.ts for the in-process seam coverage and
+ * test/doctor-cli-smoke.test.ts for the subprocess wrapper coverage.
+ */
+
export async function runDoctor(
engine: BrainEngine | null,
args: string[],
@@ -9248,384 +3788,6 @@ function printAutoFixReport(report: AutoFixReport, dryRun: boolean, jsonOutput:
if (dryRun && n > 0) console.log('\nRun without --dry-run to apply.');
}
-
-/** Quick skill conformance check — frontmatter + required sections */
-export function skillConformanceCheck(skillsDir: string): Check {
- try {
- // Host workspaces are allowed to omit a gbrain-specific manifest. Keep
- // conformance aligned with resolver_health and skill_brain_first by using
- // the canonical fallback that derives entries from direct SKILL.md files.
- const manifest = loadOrDeriveManifest(skillsDir);
- const skills = manifest.skills;
- let passing = 0;
- const failing: string[] = [];
-
- for (const skill of skills) {
- const skillPath = join(skillsDir, skill.path);
- if (!existsSync(skillPath)) {
- failing.push(`${skill.name}: file missing`);
- continue;
- }
- const content = readFileSync(skillPath, 'utf-8');
- // Check frontmatter exists
- if (!content.startsWith('---')) {
- failing.push(`${skill.name}: no frontmatter`);
- continue;
- }
- passing++;
- }
-
- if (failing.length === 0) {
- const derivedNote = manifest.derived ? ' (derived from SKILL.md files)' : '';
- return { name: 'skill_conformance', status: 'ok', message: `${passing}/${skills.length} skills pass${derivedNote}` };
- }
- return {
- name: 'skill_conformance',
- status: 'warn',
- message: `${passing}/${skills.length} pass. Failing: ${failing.join(', ')}`,
- };
- } catch {
- return { name: 'skill_conformance', status: 'warn', message: 'Could not load or derive skills manifest' };
- }
-}
-
-/**
- * v0.36.x skill_brain_first doctor check (supersedes PR #1206).
- *
- * Walks the skills manifest, runs the pure `analyzeSkillBrainFirst()`
- * helper on each, surfaces violators with structured issues[]. Snapshot-
- * diff against the previous run drives audit JSONL writes (transition-
- * only) — stable brains produce zero audit churn per doctor invocation.
- *
- * Exit shape:
- * - 0 violators → status: 'ok', message: '<n> skills compliant or exempt'
- * - any violator → status: 'warn', message + per-skill summary lines +
- * formerly-EXEMPT_SKILLS hint when applicable (CMT1 replaces the
- * dropped upgrade migration with a guided opt-in)
- *
- * Test seam: pure function, no `process.exit`. Direct call from tests
- * with a synthetic skills dir under tempdir.
- */
-/**
- * Skills-manifest integrity check (#159). Verifies the skills tree against
- * the committed skills.lock.json tamper-evidence manifest. Advisory only:
- * drift is a WARN (local edits are legitimate), and a missing/unreadable
- * manifest is an ok/skip — a user's workspace skills dir or a compiled
- * binary far from the repo has no manifest, and that is not a problem.
- */
-export function skillsManifestIntegrityCheck(skillsDir: string): Check {
- const name = 'skills_manifest_integrity';
- const manifestPath = join(skillsDir, SKILLS_MANIFEST_FILENAME);
- if (!existsSync(manifestPath)) {
- return { name, status: 'ok', message: `No ${SKILLS_MANIFEST_FILENAME} in ${skillsDir} — integrity check not applicable` };
- }
- let drift: ReturnType<typeof verifySkillsManifest>;
- let tracked: number;
- try {
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as SkillsManifest;
- tracked = Object.keys(manifest).length;
- drift = verifySkillsManifest(skillsDir, manifest);
- } catch (err) {
- // Fail-safe: an unreadable/unparseable manifest or a filesystem error
- // skips the check rather than warning — this check must never block.
- const msg = err instanceof Error ? err.message : String(err);
- return { name, status: 'ok', message: `Could not verify ${SKILLS_MANIFEST_FILENAME} (${msg}) — integrity check skipped` };
- }
- const total = drift.modified.length + drift.missing.length + drift.extra.length;
- if (total === 0) {
- return { name, status: 'ok', message: `${tracked} bundled skill files match ${SKILLS_MANIFEST_FILENAME}` };
- }
- const sample = (files: string[]): string =>
- files.slice(0, 5).join(', ') + (files.length > 5 ? `, … +${files.length - 5} more` : '');
- const parts: string[] = [];
- if (drift.modified.length > 0) parts.push(`${drift.modified.length} modified (${sample(drift.modified)})`);
- if (drift.missing.length > 0) parts.push(`${drift.missing.length} missing (${sample(drift.missing)})`);
- if (drift.extra.length > 0) parts.push(`${drift.extra.length} extra (${sample(drift.extra)})`);
- return {
- name,
- status: 'warn',
- message:
- `skills/ drifted from ${SKILLS_MANIFEST_FILENAME} (advisory — local edits are fine): ${parts.join('; ')}. ` +
- `If intentional, regenerate: bun run scripts/generate-skills-manifest.ts`,
- details: { modified: drift.modified, missing: drift.missing, extra: drift.extra },
- };
-}
-
-/**
- * Skill currency check — compares the built-in skills bundle against what
- * the downstream workspace has scaffolded and surfaces NEW skills the user
- * doesn't have yet. Advisory: `new` skills are a WARN (you're missing
- * shipped capability); `drifted` skills are informational only (local edits
- * are legitimate — the ownership model). No-ops when running inside the
- * gbrain repo itself (bundle == install, always current) or when the bundle
- * can't be located.
- */
-export function skillCurrencyCheck(skillsDir: string): Check {
- const name = 'skill_currency';
- const targetWorkspace = resolvePath(skillsDir, '..');
- const gbrainRoot = findGbrainRoot();
- if (!gbrainRoot) {
- return { name, status: 'ok', message: 'skill currency not applicable (no bundled skills pack found)' };
- }
- if (resolvePath(targetWorkspace) === resolvePath(gbrainRoot)) {
- return { name, status: 'ok', message: 'skill currency not applicable (running inside the gbrain repo)' };
- }
- let report: ReturnType<typeof computeSkillCurrency>;
- try {
- report = computeSkillCurrency({ gbrainRoot, targetWorkspace });
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return { name, status: 'ok', message: `skill currency check skipped (${msg})` };
- }
- const { counts, skills } = report;
- const sample = (status: 'new' | 'drifted'): string => {
- const s = skills.filter(k => k.status === status).map(k => k.slug);
- return s.slice(0, 8).join(', ') + (s.length > 8 ? `, … +${s.length - 8} more` : '');
- };
- if (counts.new === 0) {
- const drift = counts.drifted > 0 ? ` (${counts.drifted} drifted — local edits are fine)` : '';
- return { name, status: 'ok', message: `${counts.current}/${counts.total} built-in skills current${drift}` };
- }
- return {
- name,
- status: 'warn',
- message:
- `${counts.new} new built-in skill(s) available that this workspace hasn't installed: ${sample('new')}. ` +
- `Add them with \`gbrain skillpack sync\`.` +
- (counts.drifted > 0 ? ` (${counts.drifted} drifted from the bundle — local edits are fine.)` : ''),
- details: {
- new: skills.filter(k => k.status === 'new').map(k => k.slug),
- drifted: skills.filter(k => k.status === 'drifted').map(k => k.slug),
- },
- };
-}
-
-/**
- * Skill preconditions check — the LIVE half of the `requires:` frontmatter
- * contract. For every skill INSTALLED in this workspace that declares
- * preconditions, verify each against the connected brain and WARN on unmet
- * ones with a paste-ready hint. Engine-dependent: skips cleanly when there
- * is no brain to check against (the static list lives in
- * `gbrain skillpack setup`).
- */
-export async function skillPreconditionsCheck(
- skillsDir: string,
- engine: BrainEngine | null,
-): Promise<Check> {
- const name = 'skill_preconditions';
- if (!engine) {
- return { name, status: 'ok', message: 'skill preconditions not checked (no connected brain)' };
- }
- // Collect installed skills declaring `requires:`.
- let installed: { slug: string; requires: string[] }[];
- try {
- installed = readdirSync(skillsDir, { withFileTypes: true })
- .filter(e => e.isDirectory())
- .map(e => {
- const md = join(skillsDir, e.name, 'SKILL.md');
- if (!existsSync(md)) return null;
- const fm = parseSkillFrontmatter(readFileSync(md, 'utf-8'));
- const requires = fm?.requires ?? [];
- return requires.length > 0 ? { slug: e.name, requires } : null;
- })
- .filter((x): x is { slug: string; requires: string[] } => x !== null);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return { name, status: 'ok', message: `skill preconditions check skipped (${msg})` };
- }
- if (installed.length === 0) {
- return { name, status: 'ok', message: 'no installed skills declare preconditions' };
- }
-
- // Engine-backed precondition context. Read-only COUNT/getConfig queries;
- // no source scoping (doctor is a trusted local context). Every accessor
- // fails soft to a conservative value so a query error never throws the check.
- const ctx: PreconditionContext = {
- async countPages() {
- try {
- const rows = await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM pages');
- return rows[0]?.n ?? 0;
- } catch { return 0; }
- },
- async countPagesInDir(dir: string) {
- const prefix = dir.endsWith('/') ? dir : `${dir}/`;
- try {
- const rows = await engine.executeRaw<{ n: number }>(
- `SELECT COUNT(*)::int AS n FROM pages WHERE slug LIKE $1 ESCAPE '\\'`,
- [`${prefix.replace(/[%_\\]/g, m => `\\${m}`)}%`],
- );
- return rows[0]?.n ?? 0;
- } catch { return 0; }
- },
- async listSourceIds() {
- try {
- const rows = await engine.executeRaw<{ id: string }>(`SELECT id FROM sources WHERE id <> 'default'`);
- return rows.map(r => r.id);
- } catch { return []; }
- },
- async countPagesForSource(id: string) {
- try {
- const rows = await engine.executeRaw<{ n: number }>(
- 'SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1',
- [id],
- );
- return rows[0]?.n ?? 0;
- } catch { return 0; }
- },
- async getConfig(key: string) {
- try {
- return (await engine.getConfig(key)) ?? undefined;
- } catch { return undefined; }
- },
- };
-
- const unmet: string[] = [];
- for (const skill of installed) {
- const results = await checkPreconditions(skill.requires, ctx);
- for (const r of results) {
- if (!r.met) unmet.push(`${skill.slug}: ${r.req.raw} — ${r.hint}`);
- }
- }
- if (unmet.length === 0) {
- return { name, status: 'ok', message: `${installed.length} skill(s) with preconditions, all met` };
- }
- return {
- name,
- status: 'warn',
- message:
- `${unmet.length} unmet skill precondition(s):\n ` +
- unmet.slice(0, 8).join('\n ') +
- (unmet.length > 8 ? `\n … +${unmet.length - 8} more` : ''),
- details: { unmet },
- };
-}
-
-export function skillBrainFirstCheck(skillsDir: string): Check {
- let manifest: ReturnType<typeof loadOrDeriveManifest>;
- try {
- manifest = loadOrDeriveManifest(skillsDir);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return {
- name: 'skill_brain_first',
- status: 'warn',
- message: `Could not load skills manifest from ${skillsDir} (${msg})`,
- };
- }
- if (manifest.skills.length === 0) {
- return {
- name: 'skill_brain_first',
- status: 'ok',
- message: 'No skills found — skill_brain_first not applicable',
- };
- }
-
- const violators: BrainFirstAnalysis[] = [];
- const typoSkills: BrainFirstAnalysis[] = [];
-
- for (const entry of manifest.skills) {
- const skillPath = join(skillsDir, entry.path);
- if (!existsSync(skillPath)) continue; // resolver_health already reports
- let content: string;
- try {
- content = readFileSync(skillPath, 'utf-8');
- } catch {
- continue; // best-effort; permissions etc.
- }
- const fm = parseSkillFrontmatter(content);
- const result = analyzeSkillBrainFirst(content, entry.name, fm);
- if (result.typo_hint) typoSkills.push(result);
- if (result.status === 'warn') violators.push(result);
- }
-
- // --- Snapshot + diff audit (A2 contract) ---------------------------------
- // Best-effort: snapshot/audit failures don't poison the check result.
- const violatorSlugs = new Set(violators.map(v => v.skill));
- const patternsBySlug = new Map<string, string[]>();
- for (const v of violators) {
- patternsBySlug.set(v.skill, v.external_patterns_matched);
- }
- let priorSnapshotPresent = true;
- try {
- const snapshot = loadSnapshot();
- priorSnapshotPresent = snapshot.present;
- const diff = diffAgainstSnapshot(violatorSlugs, snapshot.violators);
- const doctorRunId = `${process.pid}-${Date.now()}`;
- if (snapshot.present) {
- // Steady-state path: write events only for transitions.
- appendAuditEventsForTransitions(diff, patternsBySlug, doctorRunId);
- } else {
- // First run / corrupt snapshot: bootstrap by writing one
- // `detected` line per current violator. This is the only path
- // that writes more than `diff.added.length` lines in a single
- // doctor invocation.
- const bootstrapDiff = { added: Array.from(violatorSlugs).sort(), removed: [], unchanged: [] };
- appendAuditEventsForTransitions(bootstrapDiff, patternsBySlug, doctorRunId);
- }
- writeSnapshotAtomically(violatorSlugs);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- process.stderr.write(`[gbrain] skill_brain_first audit step failed (${msg}); check continues\n`);
- }
-
- // --- Build the check result ---------------------------------------------
- if (violators.length === 0) {
- const typoNote = typoSkills.length > 0
- ? ` (note: ${typoSkills.length} skill(s) have brain_first typo hints: ${typoSkills.map(t => t.skill).join(', ')})`
- : '';
- return {
- name: 'skill_brain_first',
- status: 'ok',
- message: `${manifest.skills.length} skill(s) compliant or exempt${typoNote}`,
- };
- }
-
- // Sort for deterministic message + issues order.
- violators.sort((a, b) => a.skill.localeCompare(b.skill));
-
- const formerlyExempt = violators.filter(v => v.formerly_hardcoded_exempt);
- const summary: string[] = [];
- summary.push(
- `${violators.length} skill(s) do external lookups without a brain-first compliance signal. ` +
- `Fix via 'gbrain doctor --fix' (adds canonical Convention callout) ` +
- `or set 'brain_first: exempt' in skill frontmatter for genuine infra skills.`,
- );
- if (formerlyExempt.length > 0) {
- summary.push(
- `Of these, ${formerlyExempt.length} were hardcoded-exempt in PR #1206 (${formerlyExempt.map(v => v.skill).slice(0, 6).join(', ')}${formerlyExempt.length > 6 ? ', ...' : ''}). ` +
- `These need explicit opt-out now: run 'gbrain doctor --fix' to add the canonical callout, ` +
- `or add 'brain_first: exempt' to frontmatter for skills that genuinely shouldn't consult the brain.`,
- );
- }
- if (typoSkills.length > 0) {
- summary.push(
- `${typoSkills.length} skill(s) have brain_first typo hints: ` +
- typoSkills.slice(0, 6).map(t => `${t.skill} — ${t.typo_hint}`).join('; ') +
- (typoSkills.length > 6 ? '; ...' : ''),
- );
- }
-
- return {
- name: 'skill_brain_first',
- status: 'warn',
- message: summary.join(' '),
- issues: violators.map(v => ({
- type: 'skill_missing_brain_first',
- skill: v.skill,
- action: v.formerly_hardcoded_exempt
- ? `Add canonical Convention callout OR set 'brain_first: exempt' (was hardcoded-exempt in PR #1206)`
- : `Add canonical Convention callout OR set 'brain_first: exempt'`,
- fix: {
- kind: 'add-convention-callout',
- external_patterns: v.external_patterns_matched,
- typo_hint: v.typo_hint,
- formerly_hardcoded_exempt: v.formerly_hardcoded_exempt,
- summary_line: buildBrainFirstSummaryLine(v),
- },
- })),
- };
-}
-
function outputResults(checks: Check[], json: boolean): boolean {
// v0.41.19.0 — render goes through computeDoctorReport so the human
// output, JSON output, and remote MCP envelope all share one shape.
@@ -10019,136 +4181,3 @@ function parseFloatFlag(args: string[], flag: string): number | null {
const v = parseFloat(args[i + 1] ?? '');
return isNaN(v) ? null : v;
}
-
-// =================================================================
-// v0.39 T7 + T9 — schema-pack doctor checks
-// =================================================================
-// Three checks per v0.38 CEO plan that never shipped at v0.38 time:
-// schema_pack_active — does the active pack resolve cleanly?
-// schema_pack_consistency — what % of pages match the active pack?
-// schema_pack_source_drift — do per-source packs disagree?
-// All three are warn-only; never fail-block.
-
-async function checkSchemaPackActive(engine: BrainEngine): Promise<Check> {
- try {
- const { loadActivePack } = await import('../core/schema-pack/load-active.ts');
- const { loadConfig } = await import('../core/config.ts');
- const pack = await loadActivePack({ cfg: loadConfig(), remote: false });
- return {
- name: 'schema_pack_active',
- status: 'ok',
- message: `Active pack: ${pack.manifest.name} v${pack.manifest.version} (${pack.manifest.page_types.length} types, ${pack.manifest.link_types?.length ?? 0} link verbs)`,
- };
- } catch (e) {
- return {
- name: 'schema_pack_active',
- status: 'warn',
- message: `Active pack failed to resolve: ${(e as Error).message}. Run \`gbrain schema active\` to debug.`,
- };
- }
-}
-
-async function checkSchemaPackConsistency(engine: BrainEngine): Promise<Check> {
- try {
- const rows = await engine.executeRaw<{ src: string; total: string | number; untyped: string | number }>(
- `SELECT
- source_id AS src,
- COUNT(*)::text AS total,
- COUNT(*) FILTER (WHERE type IS NULL OR type = '')::text AS untyped
- FROM pages
- WHERE deleted_at IS NULL
- GROUP BY source_id
- ORDER BY source_id`,
- );
- if (rows.length === 0) {
- return { name: 'schema_pack_consistency', status: 'ok', message: 'No pages in any source — schema consistency N/A.' };
- }
- let worstPct = 0;
- let worstSrc = '';
- let worstUntyped = 0;
- let worstTotal = 0;
- for (const r of rows) {
- const total = Number(r.total);
- const untyped = Number(r.untyped);
- if (total === 0) continue;
- const pct = untyped / total;
- if (pct > worstPct) {
- worstPct = pct;
- worstSrc = r.src;
- worstUntyped = untyped;
- worstTotal = total;
- }
- }
- if (worstPct === 0) {
- return { name: 'schema_pack_consistency', status: 'ok', message: 'All pages match the active schema pack across every source.' };
- }
- const pctStr = (worstPct * 100).toFixed(1);
- if (worstPct >= 0.1) {
- return {
- name: 'schema_pack_consistency',
- status: 'warn',
- message: `Source \`${worstSrc}\`: ${worstUntyped} of ${worstTotal} pages (${pctStr}%) have no type matching the active pack. Run \`gbrain schema detect --source ${worstSrc}\` to propose a pack matching your content shape.`,
- };
- }
- return {
- name: 'schema_pack_consistency',
- status: 'ok',
- message: `${pctStr}% untyped at worst (source \`${worstSrc}\`) — under the 10% warn threshold.`,
- };
- } catch (e) {
- return {
- name: 'schema_pack_consistency',
- status: 'ok',
- message: `Skipped: ${(e as Error).message}`,
- };
- }
-}
-
-async function checkSchemaPackSourceDrift(engine: BrainEngine): Promise<Check> {
- try {
- // Compare per-source schema_pack overrides (tier 3 DB config) to detect
- // multi-source brains where different sources point at conflicting packs.
- const rows = await engine.executeRaw<{ key: string; value: string }>(
- `SELECT key, value FROM config WHERE key LIKE 'schema_pack.source.%'`,
- );
- if (rows.length === 0) {
- return { name: 'schema_pack_source_drift', status: 'ok', message: 'No per-source pack overrides — drift N/A.' };
- }
- const distinctPacks = new Set(rows.map((r) => r.value).filter(Boolean));
- if (distinctPacks.size <= 1) {
- return { name: 'schema_pack_source_drift', status: 'ok', message: `${rows.length} per-source overrides; all point at the same pack.` };
- }
- return {
- name: 'schema_pack_source_drift',
- status: 'warn',
- message: `Per-source pack divergence detected: ${distinctPacks.size} distinct packs across ${rows.length} sources. Run \`gbrain sources list\` then \`gbrain schema active --source <id>\` per source to audit.`,
- };
- } catch (e) {
- return {
- name: 'schema_pack_source_drift',
- status: 'ok',
- message: `Skipped: ${(e as Error).message}`,
- };
- }
-}
-
-/**
- * #1123 — multi_source_drift remediation advice. Exported so the regression
- * test can pin that it only references CLI surfaces that actually exist
- * (the pre-fix text pointed at 'gbrain sources rehome', which was never
- * built, and at 'gbrain delete <slug>' without explaining that delete
- * targets the ACTIVE source — following it literally on a multi-source
- * brain deletes the correctly-routed row).
- */
-export function multiSourceDriftAdvice(count: number, sampleStr: string): string {
- return (
- `${count} page slug(s) appear at 'default' but NOT at the intended source ` +
- `(e.g., ${sampleStr}). Two possible causes: (1) pre-v0.30.3 putPage misroutes; ` +
- `(2) the intended source never completed initial sync and the default page is unrelated. ` +
- `Verify with 'gbrain sources status', then re-sync with ` +
- `'gbrain sync --source <id> --full' (reconciles drift without deleting data). ` +
- `If a misrouted default-source row remains after re-sync, remove it with ` +
- `'GBRAIN_SOURCE=default gbrain delete <slug>' — delete targets the active source, ` +
- `so pin it to 'default' explicitly.`
- );
-}
diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.ts
new file mode 100644
index 0000000000..9cd4e098cc
--- /dev/null
+++ b/src/commands/doctor/bootstrap-checks.ts
@@ -0,0 +1,401 @@
+/**
+ * bootstrapDoctorChecks — verbatim peel from src/commands/doctor.ts
+ * (containment sprint). No behavior change; doctor.ts re-exports the symbol
+ * and buildChecks consumes it.
+ */
+import { join } from 'path';
+import { existsSync } from 'fs';
+import { execFileSync } from 'child_process';
+import type { BrainEngine } from '../../core/engine.ts';
+import { LATEST_VERSION } from '../../core/migrate.ts';
+// Agent-bootstrap doctor group (plan B2/B4/ENG-4 + one-live-serve note).
+import { readHarnessReceiptState, readReceipt } from '../../core/bootstrap/format.ts';
+import { probeLivePgliteHolder, resolveBrainDataDir } from '../../core/bootstrap/uninstall.ts';
+import { readRunbookStamp, hooksInstalled, listVerifyRuns } from '../../core/bootstrap/status.ts';
+import { resolveGbrainHome } from '../../core/gbrain-home.ts';
+import { VERSION as GBRAIN_BINARY_VERSION } from '../../version.ts';
+import type { Check } from '../doctor.ts';
+
+/**
+ * Agent-bootstrap check group (plan B2, B4, ENG-4, one-live-serve, C1 skew).
+ *
+ * Gated on bootstrap state actually existing on this machine (install
+ * receipt, hook heartbeat, or push-status) — machines that never ran
+ * `gbrain bootstrap` get ZERO checks from this group. Every probe is
+ * fail-soft: a broken telemetry file degrades to a warn, never a throw.
+ */
+export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise<Check[]> {
+ const checks: Check[] = [];
+ let home: string;
+ try {
+ home = resolveGbrainHome();
+ } catch {
+ return [];
+ }
+
+ // 00. Plugin-lane coexistence. Runs BEFORE the bootstrap-state gate: a
+ // hand-wired registration can coexist with a plugin on machines that never
+ // ran `gbrain bootstrap`. Emits rows ONLY when a gbrain plugin is ENABLED
+ // in a harness config (machines without the plugin get zero noise):
+ // warn = a hand-wired registration also exists (duplicate tool
+ // registration; which server wins is host-defined), ok = the plugin is the
+ // sole owner. "Enabled" is a CONFIG signal, not a health signal — the row
+ // says so. Fail-soft like every probe in this group.
+ try {
+ const {
+ codexPluginProvidesName,
+ claudePluginProvidesName,
+ codexAnyRegistrationExists,
+ claudeAnyRegistrationExists,
+ } = await import('../../core/bootstrap/harness.ts');
+ const { codexConfigPath, claudeUserSettingsPath, claudeUserMcpConfigPath } = await import('../../core/bootstrap/host-specs.ts');
+ const claudeUserMcpConfig = claudeUserMcpConfigPath();
+ const lanes: Array<{ harness: string; plugin: string; dup: boolean; disambiguate: string }> = [];
+ const codexPlugin = codexPluginProvidesName(codexConfigPath(), 'gbrain');
+ if (codexPlugin) {
+ lanes.push({
+ harness: 'codex',
+ plugin: codexPlugin,
+ dup: codexAnyRegistrationExists(codexConfigPath(), 'gbrain'),
+ disambiguate: 'keep one owner: `codex mcp remove gbrain` (drop the hand-wired entry) or `codex plugin remove gbrain@gbrain` (drop the plugin)',
+ });
+ }
+ const claudePlugin = claudePluginProvidesName(claudeUserSettingsPath(), 'gbrain');
+ if (claudePlugin) {
+ lanes.push({
+ harness: 'claude-code',
+ plugin: claudePlugin,
+ dup: claudeAnyRegistrationExists(claudeUserMcpConfig, 'gbrain', process.cwd()),
+ disambiguate: 'keep one owner: `claude mcp remove gbrain` (drop the hand-wired entry) or disable the plugin in Claude Code',
+ });
+ }
+ for (const lane of lanes) {
+ checks.push(
+ lane.dup
+ ? {
+ name: 'plugin_lane_collision',
+ status: 'warn',
+ message:
+ `${lane.harness}: the '${lane.plugin}' plugin AND a hand-wired gbrain MCP registration both exist — ` +
+ `duplicate tool registration is host-defined behavior; ${lane.disambiguate}. ` +
+ '(Plugin enabled is a config signal, not a health signal.)',
+ }
+ : {
+ name: 'plugin_lane_collision',
+ status: 'ok',
+ message: `${lane.harness}: the '${lane.plugin}' plugin provides gbrain and no hand-wired registration was found in the scanned configs (user scope + this directory).`,
+ },
+ );
+ }
+ } catch {
+ /* fail-soft: a broken harness config never breaks doctor */
+ }
+
+ const receipt = readReceipt(home);
+ // One reader for every push-status surface [D8]; per-root files [D13].
+ const { readPushStatuses, pushStatusFilesExist } = await import('../../core/workspace-push.ts');
+ const pushStatuses = readPushStatuses();
+ const statusFilesOnDisk = pushStatusFilesExist();
+ const heartbeatFile = join(home, 'integrations', 'hooks', 'heartbeat.jsonl');
+ // #4043: a harness-only box (bootstrap harness, no workspace install) is
+ // bootstrap state too — without this, such a machine gets ZERO checks.
+ const harnessState = readHarnessReceiptState(home);
+ const hasBootstrapState =
+ receipt !== null || statusFilesOnDisk || existsSync(heartbeatFile) || harnessState.state !== 'absent';
+ // Return the pre-gate rows (plugin-lane coexistence) even on machines with
+ // no bootstrap state — the plugin lane needs no bootstrap to exist.
+ if (!hasBootstrapState) return checks;
+
+ const ws = receipt?.workspace_dir ?? null;
+
+ // 0. Harness registration health (#4043): three states so it neither cries
+ // wolf nor goes silent — skip (not a harness box) / warn (serve unreachable,
+ // a normal transient; or receipt unreadable) / fail (a target failed, or a
+ // prior rotation never converged). Token liveness needs the bearer (only
+ // recoverable from host config) — that's `gbrain bootstrap harness
+ // --status`'s job; doctor stays offline-cheap.
+ if (harnessState.state === 'ok') {
+ const hr = harnessState.receipt;
+ const failed = hr.targets.filter((t) => t.state === 'failed');
+ const pending = hr.targets.filter((t) => t.state === 'pending');
+ if (failed.length > 0 || pending.length > 0) {
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'fail',
+ message:
+ `harness wiring incomplete: ${failed.length} failed / ${pending.length} pending target(s)` +
+ ` — re-run \`gbrain bootstrap harness\` to converge (details: gbrain bootstrap harness --status).`,
+ });
+ } else if (hr.token.previous_ids && hr.token.previous_ids.length > 0) {
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'fail',
+ message: `${hr.token.previous_ids.length} previous harness token(s) were never revoked (ids ${hr.token.previous_ids.join(', ')}) — re-run \`gbrain bootstrap harness\`, or run \`gbrain auth revoke\` with the id flag per id.`,
+ });
+ } else if (hr.targets.length === 0 && hr.token.minted && hr.token.id !== undefined) {
+ // Half-removed state: a remove under a live PGLite serve strips every
+ // host target but defers the revoke — the wiring is gone yet the minted
+ // token stays ACTIVE. A vacuous all-confirmed must not read green.
+ // (Flag names spelled without dashes here: the flag-registry generator
+ // harvests bare flag tokens from comments one import level deep.)
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'fail',
+ message: `harness removal pending: host wiring removed but the minted token (id ${hr.token.id}) is not yet revoked — stop the serve and re-run \`gbrain bootstrap harness\` with the remove flag, or run \`gbrain auth revoke\` with the id flag.`,
+ });
+ } else {
+ try {
+ const base = hr.url.replace(/\/mcp$/, '');
+ const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
+ const body = res.ok ? ((await res.json()) as { status?: string }) : null;
+ if (body?.status === 'ok') {
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'ok',
+ message: `harness wired to ${hr.url} (serve healthy; token check: gbrain bootstrap harness --status)`,
+ });
+ } else {
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'warn',
+ message: `harness wired to ${hr.url} but the serve is not answering /health — start \`gbrain serve\` in http mode (a down serve is a normal transient, sessions just lose brain access until it returns).`,
+ });
+ }
+ } catch {
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'warn',
+ message: `harness wired to ${hr.url} but the serve is unreachable — start \`gbrain serve\` in http mode.`,
+ });
+ }
+ }
+ } else if (harnessState.state !== 'absent') {
+ checks.push({
+ name: 'bootstrap_harness_health',
+ status: 'warn',
+ message: `the harness receipt is unreadable (${harnessState.state}) — see \`gbrain bootstrap harness --status\`.`,
+ });
+ }
+
+ // 1. Hook heartbeat failure rate [B3 read side]. Hard errors only —
+ // degraded entries are DESIGNED fallbacks (pull-mode, no serve).
+ let hooksSeen = false;
+ try {
+ const { readHeartbeatTail, HEARTBEAT_FAILURE_WINDOW, HEARTBEAT_FAILURE_RATE_THRESHOLD } =
+ await import('../hook.ts');
+ const tail = await readHeartbeatTail(HEARTBEAT_FAILURE_WINDOW);
+ if (tail.length > 0) {
+ hooksSeen = true;
+ const failures = tail.filter((e) => e.outcome === 'error').length;
+ const rate = failures / tail.length;
+ if (rate > HEARTBEAT_FAILURE_RATE_THRESHOLD) {
+ checks.push({
+ name: 'bootstrap_hooks_heartbeat',
+ status: 'fail',
+ message: `${failures}/${tail.length} recent hook invocations hard-failed — brain context is not reaching the session. Check \`gbrain bootstrap verify\` and the serve process.`,
+ });
+ } else if (rate > 0.2) {
+ checks.push({
+ name: 'bootstrap_hooks_heartbeat',
+ status: 'warn',
+ message: `${failures}/${tail.length} recent hook invocations hard-failed. Watch it; hooks fail open so sessions still work.`,
+ });
+ } else {
+ checks.push({
+ name: 'bootstrap_hooks_heartbeat',
+ status: 'ok',
+ message: `hook heartbeat healthy (${failures}/${tail.length} hard failures in the trailing window)`,
+ });
+ }
+ }
+ } catch {
+ checks.push({ name: 'bootstrap_hooks_heartbeat', status: 'warn', message: 'hook heartbeat unreadable' });
+ }
+
+ // 2. Push staleness [B4]: fail when the last successful push is >48h old
+ // AND the workspace tree is dirty (recent work provably unpushed). Per-root
+ // status files [D13]: the WORST entry decides, so one workspace's success
+ // can never mask another's failure.
+ try {
+ if (pushStatuses.length > 0) {
+ const { PUSH_STALE_MS } = await import('../hook.ts'); // hook.ts owns the threshold (single source)
+ const failing = pushStatuses.filter((s) => s.ok === false);
+ if (failing.length > 0) {
+ const s = failing[0]!;
+ const target = s.repoRoot ?? ws ?? undefined;
+ const rest = failing.length > 1 ? ` [+${failing.length - 1} more workspace(s)]` : '';
+ checks.push({
+ name: 'bootstrap_push_health',
+ status: 'warn',
+ message: `last workspace push FAILED${target ? ` for ${target}` : ''} (${s.ts ?? 'unknown'}): ${s.reason ?? 'unknown'}${rest} — run \`gbrain sources push${target ? ` --path ${target}` : ''}\``,
+ });
+ } else {
+ const stamps = pushStatuses.map((s) => Date.parse(s.ts ?? '')).filter((t) => Number.isFinite(t));
+ const stalest = stamps.length > 0 ? Math.min(...stamps) : NaN;
+ const staleIso = Number.isFinite(stalest) ? new Date(stalest).toISOString() : 'unknown';
+ const stale = Number.isFinite(stalest) && Date.now() - stalest > PUSH_STALE_MS;
+ let dirty = false;
+ if (ws) {
+ try {
+ dirty = execFileSync('git', ['-C', ws, 'status', '--porcelain'], {
+ stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000,
+ }).toString().trim() !== '';
+ } catch { dirty = false; }
+ }
+ if (stale && dirty) {
+ checks.push({
+ name: 'bootstrap_push_health',
+ status: 'fail',
+ message: `last successful push ${staleIso} (>48h) with a DIRTY workspace tree — recent agent memory is unpushed [B4]. Run \`gbrain sources push --path ${ws}\`.`,
+ });
+ } else if (stale) {
+ checks.push({ name: 'bootstrap_push_health', status: 'warn', message: `last successful push ${staleIso} (>48h ago); tree clean — likely just idle` });
+ } else {
+ checks.push({ name: 'bootstrap_push_health', status: 'ok', message: `last push ok (${staleIso})` });
+ }
+ }
+ } else if (statusFilesOnDisk) {
+ // Files exist but none parsed — the tolerant reader skips corrupt
+ // records; doctor must not let that read as "no news is good news".
+ checks.push({ name: 'bootstrap_push_health', status: 'warn', message: 'push status unreadable' });
+ }
+ } catch {
+ checks.push({ name: 'bootstrap_push_health', status: 'warn', message: 'push status unreadable' });
+ }
+
+ // 2b. Durability job [B7/D7]: presence + LIVENESS. A presence-only check
+ // certifies dead jobs as healthy (the autopilot-status failure mode), so
+ // this warns on plist-present-but-unloaded and stale pull logs. Only warns
+ // when the user actually consented to the job; containers/cloud sandboxes
+ // are expected to have none.
+ try {
+ if (ws !== null && receipt !== null) {
+ const { detectExecutionEnvironment } = await import('../../core/execution-env.ts');
+ const envKind = detectExecutionEnvironment();
+ if (envKind !== 'local') {
+ // Answered BEFORE the subprocess probes — cloud/container doctor
+ // runs must not pay launchctl/crontab spawns for an answer that is
+ // discarded (no scheduler exists there by design).
+ checks.push({
+ name: 'bootstrap_durability_job',
+ status: 'ok',
+ message: `no scheduler in this environment (${envKind}) — expected; per-turn and session-end pushes cover persistence`,
+ });
+ } else {
+ const { durabilityJobStatus } = await import('../../core/brain-repo-durability.ts');
+ const { readInterviewState } = await import('../../core/bootstrap/interview.ts');
+ const sourceId = receipt.source_id ?? 'workspace';
+ const js = durabilityJobStatus(sourceId);
+ let consented = false;
+ try {
+ const iv = readInterviewState(ws);
+ consented = iv.ok && (iv.state.answers['PERSIST_CRON']?.value ?? '').toLowerCase() === 'yes';
+ } catch { consented = false; }
+ if (!consented) {
+ if (js.kind !== 'none') {
+ checks.push({ name: 'bootstrap_durability_job', status: 'ok', message: `${js.kind} pull job present (not required by consent — fine)` });
+ }
+ // no consent + no job → nothing to check; stay silent
+ } else if (js.kind === 'none') {
+ checks.push({
+ name: 'bootstrap_durability_job',
+ status: 'warn',
+ message: `background persistence was consented (PERSIST_CRON=yes) but no scheduled job exists — run \`gbrain sources harden ${sourceId}\``,
+ });
+ } else if (js.live === false) {
+ checks.push({
+ name: 'bootstrap_durability_job',
+ status: 'warn',
+ message: `${js.kind} job is on disk but NOT loaded — a dead job looks healthy to presence checks. Re-run \`gbrain sources harden ${sourceId}\` to reload it.`,
+ });
+ } else if (!js.wrapperPresent) {
+ checks.push({
+ name: 'bootstrap_durability_job',
+ status: 'warn',
+ message: `${js.kind} job exists but its wrapper script is missing — re-run \`gbrain sources harden ${sourceId}\``,
+ });
+ } else if (js.logFresh === false) {
+ checks.push({
+ name: 'bootstrap_durability_job',
+ status: 'warn',
+ message: `${js.kind} job present but the pull log is stale (no run within 2× the interval) — the job may be dead; re-run \`gbrain sources harden ${sourceId}\``,
+ });
+ } else if (js.kind === 'crontab' && js.logFresh === undefined) {
+ // The crontab LINE existing proves installation, not that the cron
+ // daemon runs it — with no pull log yet we can't claim liveness.
+ checks.push({ name: 'bootstrap_durability_job', status: 'ok', message: 'crontab pull job installed (no run logged yet — liveness confirmed once it first fires)' });
+ } else {
+ checks.push({ name: 'bootstrap_durability_job', status: 'ok', message: `${js.kind} pull job present and live` });
+ }
+ }
+ }
+ } catch { /* best-effort — durability probing never fails doctor */ }
+
+ // 3. One-live-serve / lock collision note. A live serve is the healthy
+ // shape (it provides hook IPC); the note names the v1 contract.
+ try {
+ const dataDir = resolveBrainDataDir(home);
+ const holder = probeLivePgliteHolder(dataDir);
+ if (holder) {
+ checks.push({
+ name: 'bootstrap_serve_lock',
+ status: holder.serve ? 'ok' : 'warn',
+ message: holder.serve
+ ? `live serve (pid ${holder.pid}) owns the brain — hook IPC available. One live serve per brain is the v1 contract; a second simultaneous session collides politely.`
+ : `a non-serve gbrain process (pid ${holder.pid}) holds the PGLite lock — hook IPC and new sessions will fail until it exits.`,
+ });
+ }
+ } catch { /* probe is best-effort */ }
+
+ // 4. [ENG-4] Hooks-in-use + unmigrated brain: the direct-engine hook paths
+ // swallow missing-table errors on pre-v110/v117 schemas, so context
+ // degrades SILENTLY. Pair the two signals into a named warning.
+ const hooksActive = hooksSeen || (ws !== null && hooksInstalled(ws));
+ if (hooksActive && engine) {
+ try {
+ const versionStr = await engine.getConfig('version');
+ const version = parseInt(versionStr || '0', 10);
+ if (version < LATEST_VERSION) {
+ checks.push({
+ name: 'bootstrap_hook_schema_pairing',
+ status: 'warn',
+ message: `hooks are in use but the brain schema is v${version} (< v${LATEST_VERSION}) — hook context can degrade silently on missing tables [ENG-4]. Run \`gbrain apply-migrations --yes\`.`,
+ });
+ }
+ } catch { /* schema_version check above already covers unreadable version */ }
+ }
+
+ // 5. Runbook skew [C1]: the fetched runbook's stamp vs this binary.
+ if (ws) {
+ try {
+ const stamp = readRunbookStamp(ws);
+ if (stamp !== null && stamp !== GBRAIN_BINARY_VERSION) {
+ checks.push({
+ name: 'bootstrap_runbook_skew',
+ status: 'warn',
+ message: `BOOTSTRAP_FOR_AGENTS.md stamp ${stamp} != installed binary ${GBRAIN_BINARY_VERSION} — prefer the binary's instructions; re-fetch the runbook.`,
+ });
+ }
+ } catch { /* best effort */ }
+ }
+
+ // 6. Last verify freshness [B2 read side] — surfaced so "verify weekly"
+ // has a nag with teeth.
+ try {
+ const runs = listVerifyRuns(home);
+ if (runs.length > 0) {
+ const last = runs[0];
+ const t = Date.parse(last.ts);
+ const ageDays = Number.isFinite(t) ? (Date.now() - t) / 86_400_000 : NaN;
+ if (!last.ok) {
+ checks.push({ name: 'bootstrap_last_verify', status: 'warn', message: `last bootstrap verify FAILED (${last.ts}): ${last.checks_failed.join(', ') || 'see snapshot'} — re-run \`gbrain bootstrap verify\`` });
+ } else if (Number.isFinite(ageDays) && ageDays > 14) {
+ checks.push({ name: 'bootstrap_last_verify', status: 'warn', message: `last bootstrap verify passed ${Math.floor(ageDays)}d ago — re-run it as the workspace rot self-check` });
+ } else {
+ checks.push({ name: 'bootstrap_last_verify', status: 'ok', message: `last verify passed (${last.ts})` });
+ }
+ }
+ } catch { /* best effort */ }
+
+ return checks;
+}
diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.ts
new file mode 100644
index 0000000000..4700b3152f
--- /dev/null
+++ b/src/commands/doctor/checks/calibration.ts
@@ -0,0 +1,667 @@
+/**
+ * Calibration + retrieval check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import { startHeartbeat, type ProgressReporter } from '../../../core/progress.ts';
+import { resolveOwnerHolder } from '../../../core/owner-holder.ts';
+import {
+ extractEntityRefs,
+ isGlobalBasenameEnabled,
+ buildBasenameIndex,
+ queryBasenameIndex,
+} from '../../../core/link-extraction.ts';
+// issue #1777: hidden_by_search_policy — count chunked pages withheld from
+// default search by the hard-exclude prefix policy. Reuses the canonical
+// exclude resolver + LIKE escaper + visibility clause so the doctor count can't
+// drift from what search actually filters.
+import { resolveHardExcludes, DEFAULT_HARD_EXCLUDES } from '../../../core/search/source-boost.ts';
+import { escapeLikePattern, buildVisibilityClause } from '../../../core/search/sql-ranking.ts';
+import type { Check } from '../../doctor.ts';
+
+// --- v0.36.1.0 calibration doctor checks (T12) ---
+
+/**
+ * abandoned_threads: surfaces active high-conviction takes (weight >= 0.7)
+ * older than 12 months that have neither been superseded nor linked to a
+ * follow-up page. These are commitments the user made and never revisited.
+ * Status 'ok' with a count; never warns/fails (this is signal, not error).
+ */
+/**
+ * v0.40.3.0 contextual_retrieval_coverage check.
+ *
+ * Surfaces drift between the active CR mode + the per-page
+ * `contextual_retrieval_mode` column. Three signals:
+ *
+ * 1. Pages with chunker_version < current — pre-v40 pages that need
+ * to be re-embedded for the wrapper to apply. Paste-ready fix:
+ * `gbrain reindex --markdown`.
+ * 2. Pages with contextual_retrieval_mode IS NULL — never evaluated
+ * against the CR ladder. Same fix as (1).
+ * 3. Synopsis-failure events in the audit JSONL over the last 7 days
+ * — surfaces refusals + page-level fallbacks. >5% refusal rate
+ * warns; otherwise reported as informational.
+ *
+ * Reads `~/.gbrain/audit/synopsis-failures-YYYY-Www.jsonl` via
+ * readRecentSynopsisFailures + summarizeSynopsisFailures from
+ * `src/core/audit-synopsis.ts`. Failure-only audit means low write
+ * volume on healthy brains.
+ */
+export async function checkContextualRetrievalCoverage(engine: BrainEngine): Promise<Check> {
+ try {
+ const { MARKDOWN_CHUNKER_VERSION } = await import('../../../core/chunkers/recursive.ts');
+ const rows = await engine.executeRaw<{ chunker_drift: number; mode_null: number }>(
+ `SELECT
+ COUNT(*) FILTER (WHERE chunker_version < $1)::int AS chunker_drift,
+ COUNT(*) FILTER (WHERE contextual_retrieval_mode IS NULL)::int AS mode_null
+ FROM pages
+ WHERE page_kind = 'markdown'
+ AND deleted_at IS NULL`,
+ [MARKDOWN_CHUNKER_VERSION],
+ );
+ const chunkerDrift = rows[0]?.chunker_drift ?? 0;
+ const modeNull = rows[0]?.mode_null ?? 0;
+
+ // Synopsis-failures audit summary (best-effort; missing audit file = 0).
+ let failureSummaryLine = '';
+ try {
+ const audit = await import('../../../core/audit-synopsis.ts');
+ const events = audit.readRecentSynopsisFailures(7);
+ const summary = audit.summarizeSynopsisFailures(events);
+ if (summary && summary.total > 0) {
+ const rate = (summary.page_level_fallback_rate * 100).toFixed(1);
+ failureSummaryLine =
+ ` ${summary.total} synopsis failure(s) in last 7d ` +
+ `(${summary.page_level_fallback_count} triggered page-level fall-back, ${rate}%).`;
+ }
+ } catch {
+ // Audit module unavailable — skip the summary line.
+ }
+
+ if (chunkerDrift === 0 && modeNull === 0 && failureSummaryLine === '') {
+ return {
+ name: 'contextual_retrieval_coverage',
+ status: 'ok',
+ message: 'All markdown pages aligned to current chunker + CR mode.',
+ };
+ }
+
+ const parts: string[] = [];
+ if (chunkerDrift > 0) {
+ parts.push(`${chunkerDrift} page(s) at older chunker_version`);
+ }
+ if (modeNull > 0) {
+ parts.push(`${modeNull} page(s) never evaluated against CR ladder`);
+ }
+ const fixHint =
+ chunkerDrift > 0 || modeNull > 0
+ ? ` Run \`gbrain reindex --markdown\` to align.`
+ : '';
+ return {
+ name: 'contextual_retrieval_coverage',
+ status: chunkerDrift > 0 || modeNull > 0 ? 'warn' : 'ok',
+ message: `${parts.join('; ')}.${fixHint}${failureSummaryLine}`,
+ };
+ } catch (e) {
+ return {
+ name: 'contextual_retrieval_coverage',
+ status: 'warn',
+ message: `Could not check contextual retrieval coverage: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+/**
+ * issue #1777 — hidden_by_search_policy
+ *
+ * Counts CHUNKED pages that are withheld from default search by the
+ * hard-exclude prefix policy (`test/`, `attachments/`, `.raw/`, plus any
+ * `GBRAIN_SEARCH_EXCLUDE` env additions). Makes the surviving exclude policy
+ * auditable so an empty search result is distinguishable from "withheld by
+ * policy" — the deeper bug the archive-demote fix only half-closes.
+ *
+ * HONEST SUPERSET: the count is "chunked pages under an excluded prefix", NOT
+ * "searchable pages". Keyword search additionally filters
+ * `search_vector @@ ... AND modality='text'` and vector search filters text
+ * modality + non-null embedding, so `EXISTS (content_chunks)` over-includes
+ * image-only / non-text pages. Tightening to the exact per-modality predicate
+ * would couple this check to search internals for a number nobody paginates on;
+ * the superset is the right operator signal. The message says "chunked page(s)".
+ *
+ * Status (CV-1a): pages hidden ONLY under DEFAULT excludes → `ok` (intentional
+ * noise; warning would make every healthy brain look unhealthy). Pages hidden
+ * under a NON-default (env-supplied) prefix → `warn`. The message is
+ * agent-prescriptive: move content out of the excluded prefix or pass
+ * `include_slug_prefixes` on the query.
+ *
+ * NOTE: this does NOT verify `archive/` pages are embedded/graphed — after the
+ * #1777 fix `archive/` is no longer excluded, so it never appears here.
+ */
+export async function checkHiddenBySearchPolicy(engine: BrainEngine): Promise<Check> {
+ const name = 'hidden_by_search_policy';
+ try {
+ const prefixes = resolveHardExcludes();
+ if (prefixes.length === 0) {
+ return { name, status: 'ok', message: 'No search-exclude prefixes active.' };
+ }
+
+ // ONE query: COUNT(DISTINCT p.id) per prefix in a single pass. Prefixes are
+ // bound params, LIKE-escaped (env-supplied prefixes may contain %/_/\) with
+ // an explicit ESCAPE clause. Candidate gate is EXISTS(content_chunks);
+ // buildVisibilityClause mirrors search's page-level visibility (soft-delete,
+ // archived source, quarantine) and REQUIRES the `sources s` join.
+ const visibility = buildVisibilityClause('p', 's');
+ const filters = prefixes
+ .map((_, i) => `COUNT(DISTINCT p.id) FILTER (WHERE p.slug LIKE $${i + 1} ESCAPE '\\')::int AS c${i}`)
+ .join(',\n ');
+ const params = prefixes.map((pfx) => `${escapeLikePattern(pfx)}%`);
+ const sql =
+ `SELECT
+ ${filters}
+ FROM pages p
+ JOIN sources s ON s.id = p.source_id
+ WHERE EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
+ ${visibility}`;
+ const rows = await engine.executeRaw<Record<string, number>>(sql, params);
+ const row = rows[0] ?? {};
+
+ const defaults = new Set(DEFAULT_HARD_EXCLUDES);
+ const perPrefix = prefixes
+ .map((pfx, i) => ({ prefix: pfx, count: Number(row[`c${i}`] ?? 0), isDefault: defaults.has(pfx) }))
+ .filter((e) => e.count > 0);
+
+ if (perPrefix.length === 0) {
+ return {
+ name,
+ status: 'ok',
+ message: 'No pages hidden by search-exclude policy.',
+ details: { prefixes, counts: {} },
+ };
+ }
+
+ const counts: Record<string, number> = {};
+ for (const e of perPrefix) counts[e.prefix] = e.count;
+ const breakdown = perPrefix.map((e) => `${e.count} under '${e.prefix}'`).join(', ');
+ const hasNonDefault = perPrefix.some((e) => !e.isDefault);
+ const guidance =
+ 'If any hold content you want findable, move them out of the excluded ' +
+ "prefix or pass `include_slug_prefixes` on the query.";
+ return {
+ name,
+ status: hasNonDefault ? 'warn' : 'ok',
+ message: `${breakdown} chunked page(s) are excluded from default search by prefix policy. ${guidance}`,
+ details: { prefixes, counts },
+ };
+ } catch (e) {
+ return {
+ name,
+ status: 'warn',
+ message: `Could not check hidden-by-search-policy: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+/**
+ * Issue #972 — link_resolution_opportunity check.
+ *
+ * Walks every page in the brain, scans for bare wikilinks
+ * (`[[struktura]]` outside DIR_PATTERN) that would resolve to at least
+ * one page under global-basename mode, and surfaces a paste-ready
+ * `gbrain config set link_resolution.global_basename true` hint when
+ * the count is meaningful (>=5 would-resolve AND >=20% of bare
+ * wikilinks have matches). Skipped silently when the flag is already
+ * enabled (no signal to surface) or the brain is empty.
+ *
+ * Bounded scan: batch-loads the 1000 most-recent pages in one query (not a
+ * per-page getPage walk) with a 60s backstop. On DB error, downgrades to an
+ * informational `ok` so doctor never blocks on this check.
+ */
+export async function checkLinkResolutionOpportunity(
+ engine: BrainEngine,
+ progress?: ProgressReporter,
+): Promise<Check> {
+ const name = 'link_resolution_opportunity';
+ try {
+ if (await isGlobalBasenameEnabled(engine)) {
+ return { name, status: 'ok', message: 'global_basename mode already enabled' };
+ }
+ const allSlugs = await engine.getAllSlugs();
+ if (allSlugs.size === 0) {
+ return { name, status: 'ok', message: 'Brain is empty — nothing to scan' };
+ }
+ // Build a basename → slug[] index ONCE for the entire scan via the shared
+ // builder (issue #972 codex [P2] DRY) — same key set (raw/lower/slugified)
+ // as extraction, so this estimate matches what extraction actually
+ // resolves. Pre-fix the doctor omitted the slugified key and undercounted.
+ const basenameIndex = buildBasenameIndex(allSlugs);
+
+ let bareCount = 0;
+ let wouldResolveCount = 0;
+ const distinctTargets = new Set<string>();
+
+ // Issue #972 (codex [P2] perf): batch-load the most-recent N pages in ONE
+ // query instead of listAllPageRefs() + a getPage() per page. The prior
+ // full N-page walk hit the 60s budget every run on large brains and
+ // returned a perpetual partial; this bounds the work to a fixed sample.
+ const SAMPLE_LIMIT = 1000;
+ const sampled = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null }>(
+ `SELECT compiled_truth, timeline FROM pages WHERE deleted_at IS NULL ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}`,
+ );
+ const totalPages = allSlugs.size;
+ const sampledNote = totalPages > SAMPLE_LIMIT
+ ? ` (scanned the ${SAMPLE_LIMIT} most-recent of ${totalPages} pages)`
+ : '';
+ const deadline = Date.now() + 60_000;
+ const hb = progress ? startHeartbeat(progress, `scanning ${sampled.length} pages for bare wikilinks…`) : null;
+ try {
+ for (const row of sampled) {
+ if (Date.now() > deadline) break; // backstop; in-memory scan rarely hits it
+ const content = (row.compiled_truth ?? '') + '\n' + (row.timeline ?? '');
+ for (const e of extractEntityRefs(content)) {
+ if (!e.needsResolution) continue;
+ bareCount++;
+ // Issue #972 (codex): match on the wikilink TARGET (e.slug), not
+ // the display alias (e.name), via the shared query so the doctor
+ // estimate equals what extraction actually resolves.
+ const matches = queryBasenameIndex(basenameIndex, e.slug);
+ if (matches.length > 0) {
+ wouldResolveCount++;
+ for (const m of matches) distinctTargets.add(m);
+ }
+ }
+ }
+ } finally {
+ hb?.();
+ }
+
+ if (bareCount === 0) {
+ return { name, status: 'ok', message: 'No bare wikilinks found' };
+ }
+ if (wouldResolveCount === 0) {
+ return {
+ name,
+ status: 'ok',
+ message: `${bareCount} bare wikilink(s) found, but none have basename matches in the brain.`,
+ };
+ }
+ const ratio = wouldResolveCount / bareCount;
+ if (wouldResolveCount >= 5 && ratio >= 0.20) {
+ const pct = Math.round(ratio * 100);
+ return {
+ name,
+ status: 'warn',
+ message:
+ `${wouldResolveCount} of ${bareCount} bare wikilinks (${pct}%) would resolve to ` +
+ `${distinctTargets.size} distinct page(s) under global_basename mode${sampledNote}. ` +
+ `Enable with: gbrain config set link_resolution.global_basename true`,
+ };
+ }
+ const pct = Math.round(ratio * 100);
+ return {
+ name,
+ status: 'ok',
+ message: `${wouldResolveCount}/${bareCount} bare wikilinks (${pct}%) would resolve — below the 20% / 5-link threshold for surfacing a hint${sampledNote}.`,
+ };
+ } catch (e) {
+ return {
+ name,
+ status: 'ok',
+ message: `Skipped (${e instanceof Error ? e.message : String(e)})`,
+ };
+ }
+}
+
+export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ count: number }>(
+ `SELECT COUNT(*)::int AS count FROM takes
+ WHERE active = true
+ AND resolved_at IS NULL
+ AND superseded_by IS NULL
+ AND weight >= 0.7
+ AND since_date IS NOT NULL
+ AND since_date::date < (now() - INTERVAL '12 months')`,
+ );
+ const count = rows[0]?.count ?? 0;
+ if (count === 0) {
+ return {
+ name: 'abandoned_threads',
+ status: 'ok',
+ message: 'No abandoned high-conviction threads',
+ };
+ }
+ return {
+ name: 'abandoned_threads',
+ status: 'ok',
+ message: `${count} high-conviction take(s) older than 12 months and never revisited — see \`gbrain calibration\` for details`,
+ };
+ } catch (e) {
+ return {
+ name: 'abandoned_threads',
+ status: 'warn',
+ message: `Could not check abandoned threads: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+/**
+ * calibration_freshness: warns when the active calibration profile is
+ * older than 7 days (configurable). Default holder resolves via resolveOwnerHolder
+ * (config emotional_weight.user_holder, else 'self'). Multi-source
+ * brains see one row per source; this check uses the most recent across
+ * all sources.
+ */
+export async function checkCalibrationFreshness(engine: BrainEngine): Promise<Check> {
+ try {
+ const ownerHolder = resolveOwnerHolder({
+ configValue: await engine.getConfig('emotional_weight.user_holder'),
+ });
+ const rows = await engine.executeRaw<{ generated_at: Date | null }>(
+ `SELECT MAX(generated_at) AS generated_at FROM calibration_profiles WHERE holder = $1`,
+ [ownerHolder],
+ );
+ const generated = rows[0]?.generated_at;
+ if (!generated) {
+ return {
+ name: 'calibration_freshness',
+ status: 'ok',
+ message: 'No calibration profile yet (builds after 5+ resolved takes)',
+ };
+ }
+ const ageMs = Date.now() - new Date(generated).getTime();
+ const ageDays = Math.floor(ageMs / (1000 * 60 * 60 * 24));
+ const staleDays = 7;
+ if (ageDays > staleDays) {
+ return {
+ name: 'calibration_freshness',
+ status: 'warn',
+ message: `Calibration profile is ${ageDays} days old (stale at >${staleDays}d). Run \`gbrain calibration --regenerate\``,
+ };
+ }
+ return {
+ name: 'calibration_freshness',
+ status: 'ok',
+ message: `Calibration profile generated ${ageDays}d ago`,
+ };
+ } catch (e) {
+ return {
+ name: 'calibration_freshness',
+ status: 'warn',
+ message: `Could not check calibration freshness: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+/**
+ * grade_confidence_drift (CDX-11 mitigation): compare the judge's
+ * self-reported confidence on auto-applied verdicts against the eventual
+ * accuracy on those same takes. When auto-resolutions diverge from
+ * confidence prediction, the judge is mis-calibrated and the operator
+ * should retune the prompt or revisit the threshold.
+ *
+ * v0.36.1.0 ship state: returns 'ok' with a counter — actual drift math
+ * requires a measurement window we haven't accumulated yet. The check
+ * exists so the surface is wired; the math arrives once we have N >= 30
+ * auto-applied verdicts to compare.
+ */
+export async function checkGradeConfidenceDrift(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ applied_count: number }>(
+ `SELECT COUNT(*)::int AS applied_count FROM take_grade_cache WHERE applied = true`,
+ );
+ const applied = rows[0]?.applied_count ?? 0;
+ if (applied < 30) {
+ return {
+ name: 'grade_confidence_drift',
+ status: 'ok',
+ message: `Only ${applied} auto-applied verdicts — need 30+ for drift detection`,
+ };
+ }
+ // v0.37+ TODO: compute confidence-vs-accuracy correlation; warn when
+ // mean(applied verdicts' confidence) deviates from the actual accuracy
+ // rate (cross-checked against later manual corrections via the
+ // contradictions probe). For v0.36.1.0 the check surfaces only the
+ // count and a "calibration math pending" status.
+ return {
+ name: 'grade_confidence_drift',
+ status: 'ok',
+ message: `${applied} auto-applied verdicts; drift math arrives in v0.37+`,
+ };
+ } catch (e) {
+ return {
+ name: 'grade_confidence_drift',
+ status: 'warn',
+ message: `Could not check grade confidence drift: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+/**
+ * voice_gate_health: warns when calibration_profiles rows show a high rate
+ * of voice gate failures over the last 7 days. Failures aren't bad in
+ * isolation (template fallback is fine), but a sustained high rate signals
+ * the rubric needs tuning.
+ */
+/**
+ * v0.41 Bug 2 / Eng D8 — surfaces rate-lease pressure from
+ * `minion_lease_pressure_log` (populated by the worker's lease-full bypass
+ * path). The operator's primary forensic signal for "is the lease cap too
+ * tight" — without this check, the v0.41 bypass would be invisible (no
+ * dead-letter, but also no operator awareness).
+ *
+ * Thresholds (windowed at 24h):
+ * 0 bounces → ok ("no pressure")
+ * 1-99 bounces → ok ("transient")
+ * 100+ bounces + subagent jobs completed in same window → ok ("healthy backpressure")
+ * 100+ bounces + ZERO completed subagent jobs → warn (paste-ready cap-raise hint)
+ * 1000+ bounces → fail ("blocking real work")
+ *
+ * Works on both Postgres + PGLite (migration v94 creates the table on both).
+ * Pre-v93 brains (no table) silently skip with an OK message.
+ */
+export async function checkSubagentHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ const bounceRows = await engine.executeRaw<{ count: string }>(
+ `SELECT count(*)::text AS count FROM minion_lease_pressure_log
+ WHERE bounced_at > now() - interval '24 hours'`,
+ );
+ const bounces = parseInt(bounceRows[0]?.count ?? '0', 10);
+ if (bounces === 0) {
+ return {
+ name: 'subagent_health',
+ status: 'ok',
+ message: 'No rate-lease pressure in last 24h',
+ };
+ }
+ if (bounces >= 1000) {
+ return {
+ name: 'subagent_health',
+ status: 'fail',
+ message: `${bounces} lease-pressure bounces in last 24h — this is blocking real work. Raise the cap: \`export GBRAIN_ANTHROPIC_MAX_INFLIGHT=64\` (or \`unlimited\` for Azure / Bedrock / self-hosted upstreams with no provider-side rate limit). After raising, restart \`gbrain jobs work\`.`,
+ };
+ }
+ // 1-999 bounces: cross-check forward progress.
+ const completedRows = await engine.executeRaw<{ count: string }>(
+ `SELECT count(*)::text AS count FROM minion_jobs
+ WHERE finished_at > now() - interval '24 hours'
+ AND status = 'completed'
+ AND name = 'subagent'`,
+ ).catch(() => [{ count: '0' }]);
+ const completed = parseInt(completedRows[0]?.count ?? '0', 10);
+ if (bounces >= 100 && completed === 0) {
+ return {
+ name: 'subagent_health',
+ status: 'warn',
+ message: `${bounces} lease-pressure bounces in last 24h with no completed subagent jobs — cap is too tight. Raise via \`export GBRAIN_ANTHROPIC_MAX_INFLIGHT=64\` (or \`unlimited\` for upstreams with no provider-side cap).`,
+ };
+ }
+ return {
+ name: 'subagent_health',
+ status: 'ok',
+ message: `Lease pressure: ${bounces} bounces in last 24h, ${completed} subagent jobs completed — backpressure is binding but throughput is healthy`,
+ };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (process.env.GBRAIN_DEBUG === '1') {
+ process.stderr.write(`[doctor] subagent_health skipped: ${msg}\n`);
+ }
+ return {
+ name: 'subagent_health',
+ status: 'ok',
+ message: 'Skipped (minion_lease_pressure_log unavailable — pre-v0.41 brain)',
+ };
+ }
+}
+
+export async function checkVoiceGateHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ total: number; failures: number }>(
+ `SELECT COUNT(*)::int AS total,
+ COALESCE(SUM(CASE WHEN voice_gate_passed = false THEN 1 ELSE 0 END), 0)::int AS failures
+ FROM calibration_profiles
+ WHERE generated_at >= (now() - INTERVAL '7 days')`,
+ );
+ const total = rows[0]?.total ?? 0;
+ const failures = rows[0]?.failures ?? 0;
+ if (total === 0) {
+ return {
+ name: 'voice_gate_health',
+ status: 'ok',
+ message: 'No calibration profile generation in the last 7 days',
+ };
+ }
+ const failRate = failures / total;
+ if (failRate >= 0.3) {
+ return {
+ name: 'voice_gate_health',
+ status: 'warn',
+ message: `Voice gate failed ${failures}/${total} (${Math.round(failRate * 100)}%) in last 7 days. Review src/core/calibration/voice-gate.ts rubric.`,
+ };
+ }
+ return {
+ name: 'voice_gate_health',
+ status: 'ok',
+ message: `Voice gate ${failures}/${total} failed in last 7 days (${Math.round(failRate * 100)}%)`,
+ };
+ } catch (e) {
+ return {
+ name: 'voice_gate_health',
+ status: 'warn',
+ message: `Could not check voice gate health: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+/**
+ * v0.35.0.0+ reranker_health doctor check.
+ *
+ * Logic (post-CDX2 review):
+ * 1) Read `search.reranker.enabled` first. When disabled and no
+ * failures in window → 'ok: reranker disabled'. Avoids interpreting
+ * "no events" as "broken" when reranker is simply not in use.
+ * 2) Walk last 7 days of `~/.gbrain/audit/rerank-failures-*.jsonl`.
+ * 3) Auth failures: ANY single one warns (config-time problem doctor's
+ * own probe should have caught — surface it).
+ * 4) Transient (network/timeout/rate_limit): warn at >=5 in window.
+ * Below that they're noise; reranker fails open anyway.
+ * 5) Payload-too-large failures: warn at >=1 (indicates a workload
+ * mismatch that the operator should know about).
+ * 6) Budget/pricing failures: warn at >=1 with the rerank pricing surface
+ * and --max-cost escape hatch.
+ *
+ * Engine-agnostic (file-based + one config-key read).
+ */
+export async function checkRerankerHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ const { readRecentRerankFailures } = await import('../../../core/rerank-audit.ts');
+ const cfg = await engine.getConfig('search.reranker.enabled');
+ const rerankerEnabled = cfg === 'true' || cfg === '1';
+
+ const failures = readRecentRerankFailures(7);
+ if (failures.length === 0) {
+ return {
+ name: 'reranker_health',
+ status: 'ok',
+ message: rerankerEnabled
+ ? 'No rerank failures in last 7 days'
+ : 'Reranker disabled — no failures expected',
+ };
+ }
+
+ const authFails = failures.filter((f) => f.reason === 'auth');
+ if (authFails.length > 0) {
+ return {
+ name: 'reranker_health',
+ status: 'warn',
+ message: `${authFails.length} reranker auth failure(s) in last 7 days. Fix: verify the reranker provider's API key (e.g. VOYAGE_API_KEY) and run \`gbrain models doctor\`.`,
+ };
+ }
+
+ const payloadFails = failures.filter((f) => f.reason === 'payload_too_large');
+ if (payloadFails.length > 0) {
+ return {
+ name: 'reranker_health',
+ status: 'warn',
+ message: `${payloadFails.length} reranker payload-too-large failure(s) in last 7 days. Fix: lower \`search.reranker.top_n_in\` (default 30) or split very large documents.`,
+ };
+ }
+
+ const budgetFails = failures.filter((f) => f.reason === 'budget');
+ if (budgetFails.length > 0) {
+ return {
+ name: 'reranker_health',
+ status: 'warn',
+ message: `${budgetFails.length} reranker budget/pricing failure(s) in last 7 days. Fix: add rerank pricing to src/core/embedding-pricing.ts or drop --max-cost.`,
+ };
+ }
+
+ const transientFails = failures.filter(
+ (f) => f.reason === 'network' || f.reason === 'timeout' || f.reason === 'rate_limit',
+ );
+ if (transientFails.length >= 5) {
+ return {
+ name: 'reranker_health',
+ status: 'warn',
+ message: `${transientFails.length} transient reranker failure(s) in last 7 days. Search fails open to RRF order; check ZE status if persistent.`,
+ };
+ }
+
+ // Historical #2059 rows were logged as `unknown` before missing reranker
+ // auth was classified at the gateway. Surface repeated unknowns instead of
+ // reporting "ok" while every rerank fails open.
+ const unknownFails = failures.filter((f) => f.reason === 'unknown');
+ if (unknownFails.length >= 3) {
+ const setupHint = unknownFails.some((f) => {
+ const summary = String(f.error_summary ?? '');
+ return (
+ summary.includes('ZEROENTROPY_API_KEY') ||
+ summary.includes('VOYAGE_API_KEY') ||
+ summary.toLowerCase().includes('api key')
+ );
+ })
+ ? " Fix: verify the reranker provider's API key (e.g. VOYAGE_API_KEY) and run `gbrain models doctor`."
+ : '';
+ return {
+ name: 'reranker_health',
+ status: 'warn',
+ message: `${unknownFails.length} unknown reranker failure(s) in last 7 days.${setupHint}`,
+ };
+ }
+
+ return {
+ name: 'reranker_health',
+ status: 'ok',
+ message: `${failures.length} reranker failure(s) in last 7 days (below threshold)`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'reranker_health',
+ status: 'warn',
+ message: `Could not check reranker audit: ${msg}`,
+ };
+ }
+}
+
diff --git a/src/commands/doctor/checks/consolidation-cycle.ts b/src/commands/doctor/checks/consolidation-cycle.ts
new file mode 100644
index 0000000000..e0b3d1d6f1
--- /dev/null
+++ b/src/commands/doctor/checks/consolidation-cycle.ts
@@ -0,0 +1,237 @@
+/**
+ * Consolidation / budget / cycle check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import { resolveHoursEnv } from '../../../core/env-number.ts';
+import type { Check } from '../../doctor.ts';
+
+/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */
+const _resolveSyncFreshnessHours = resolveHoursEnv;
+
+
+/**
+ * v0.41.19.0 (Issue 5 of ops-fix-wave) — surface `sync --all --parallel`
+ * to operators with multi-source brains.
+ *
+ * Background: `gbrain sync --all --parallel N --workers N --skip-failed`
+ * has existed since v0.40.3.0 but most operators still maintain separate
+ * per-source cron entries with manual deconfliction. One `--all` line
+ * replaces N per-source lines AND auto-picks-up future sources without
+ * a crontab edit.
+ *
+ * Surgical scope: we can't reach into the user's crontab (host-specific,
+ * portability risk). What we CAN do is surface the paste-ready command
+ * inside `gbrain doctor` so the operator sees it whenever they run a
+ * health check on a multi-source brain.
+ *
+ * Posture: never failure-state. Always `ok` with the paste-ready cmd
+ * embedded in the message (matches how sync_freshness embeds fix hints).
+ * Single-source brains get `ok` with a "not applicable" message.
+ * SQL error → `warn` (own try/catch, not relying on the outer doctor
+ * dispatcher — codex flagged this).
+ */
+export async function checkSyncConsolidation(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources
+ WHERE archived IS NOT TRUE
+ AND local_path IS NOT NULL`,
+ );
+ const sourceCount = rows.length;
+ if (sourceCount < 2) {
+ return {
+ name: 'sync_consolidation',
+ status: 'ok',
+ message: 'Single-source brain — sync --all consolidation not applicable.',
+ };
+ }
+ return {
+ name: 'sync_consolidation',
+ status: 'ok',
+ message:
+ `${sourceCount} active sources detected. Recommended cron: ` +
+ '`gbrain sync --all --parallel 4 --workers 4 --skip-failed`. ' +
+ 'If your crontab has separate per-source entries, replace them with one --all line — ' +
+ 'future sources auto-pick-up without a crontab edit.',
+ };
+ } catch (err) {
+ return {
+ name: 'sync_consolidation',
+ status: 'warn',
+ message: `Could not check sync consolidation: ${err instanceof Error ? err.message : String(err)}`,
+ };
+ }
+}
+
+/**
+ * v0.42.x (#1794, 4A) — pure pool-budget check. When `GBRAIN_MAX_CONNECTIONS`
+ * is set (the operator opted into the single-source connection clamp), verify
+ * the parent pool leaves room for at least one parallel worker. If even the
+ * parent pool alone is at/over the budget, sync clamps to serial AND every
+ * other gbrain process competes for the same cap — the operator should lower
+ * `GBRAIN_POOL_SIZE`. Pure so it's unit-testable without env/engine.
+ */
+export function computePoolBudgetCheck(
+ maxConnections: number | undefined,
+ parentPool: number,
+ perWorkerPool: number,
+): Check {
+ if (maxConnections === undefined) {
+ return {
+ name: 'pool_budget',
+ status: 'ok',
+ message: 'GBRAIN_MAX_CONNECTIONS not set — connection budget clamp disabled (default behavior).',
+ };
+ }
+ if (parentPool + perWorkerPool > maxConnections) {
+ return {
+ name: 'pool_budget',
+ status: 'warn',
+ message:
+ `GBRAIN_MAX_CONNECTIONS=${maxConnections} leaves no room for a parallel sync worker ` +
+ `(parent pool ${parentPool} + ${perWorkerPool} per-worker > ${maxConnections}). ` +
+ `Sync will run serial. If you hit EMAXCONNSESSION, lower the parent pool: ` +
+ '`gbrain config` / set GBRAIN_POOL_SIZE=2 (recommended for low-cap poolers like Supabase Supavisor).',
+ };
+ }
+ const maxWorkers = Math.floor((maxConnections - parentPool) / perWorkerPool);
+ return {
+ name: 'pool_budget',
+ status: 'ok',
+ message:
+ `GBRAIN_MAX_CONNECTIONS=${maxConnections}: room for up to ${maxWorkers} parallel sync ` +
+ `worker(s) (parent pool ${parentPool} + ${perWorkerPool} per-worker).`,
+ };
+}
+
+/** Thin env/engine wrapper over `computePoolBudgetCheck`. */
+export async function checkPoolBudget(_engine: BrainEngine): Promise<Check> {
+ try {
+ const { resolveMaxConnections } = await import('../../../core/sync-concurrency.ts');
+ const { resolvePoolSize } = await import('../../../core/db.ts');
+ const maxConnections = resolveMaxConnections();
+ const parentPool = resolvePoolSize();
+ const perWorkerPool = Math.min(2, resolvePoolSize(2));
+ return computePoolBudgetCheck(maxConnections, parentPool, perWorkerPool);
+ } catch (err) {
+ return {
+ name: 'pool_budget',
+ status: 'ok',
+ message: `Skipped (${err instanceof Error ? err.message : String(err)})`,
+ };
+ }
+}
+
+/**
+ * v0.38 — per-source `last_full_cycle_at` freshness check.
+ *
+ * Sibling to `sync_freshness`. Where sync_freshness reads `last_sync_at`
+ * (one phase of the cycle), this check reads `sources.config->>'last_full_cycle_at'`
+ * which is the canonical "this whole cycle completed" timestamp written
+ * by runCycle's exit hook. Autopilot's per-source fan-out gate (the
+ * v0.38 fan-out wave) reads the same field — so this check surfaces
+ * exactly what autopilot sees when deciding to skip a source.
+ *
+ * Default thresholds: warn at 6h, fail at 24h. Tighter than sync_freshness
+ * because full-cycle staleness compounds (sync stale → extract stale →
+ * embed stale → search stale). Env overrides:
+ * - GBRAIN_CYCLE_FRESHNESS_WARN_HOURS (default 6)
+ * - GBRAIN_CYCLE_FRESHNESS_FAIL_HOURS (default 24)
+ */
+export async function checkCycleFreshness(
+ engine: BrainEngine,
+ opts?: { nowMs?: number },
+): Promise<Check> {
+ try {
+ const sources = await engine.listAllSources({ localPathOnly: true });
+ if (sources.length === 0) {
+ return {
+ name: 'cycle_freshness',
+ status: 'ok',
+ message: 'No federated sources to cycle',
+ };
+ }
+
+ const warnHours = _resolveSyncFreshnessHours('GBRAIN_CYCLE_FRESHNESS_WARN_HOURS', 6);
+ const failHours = _resolveSyncFreshnessHours('GBRAIN_CYCLE_FRESHNESS_FAIL_HOURS', 24);
+ const warnMs = warnHours * 60 * 60 * 1000;
+ const failMs = failHours * 60 * 60 * 1000;
+ const now = opts?.nowMs ?? Date.now();
+
+ const issues: string[] = [];
+ let hasWarnings = false;
+ let hasFailures = false;
+
+ for (const source of sources) {
+ const display = source.name && source.name !== source.id
+ ? `'${source.id}' (${source.name})`
+ : `'${source.id}'`;
+ const raw = source.config?.last_full_cycle_at;
+ if (typeof raw !== 'string') {
+ // #2540: WARN, not FAIL. This check iterates EVERY local_path source,
+ // so on a multi-source install where only some vaults are cycled
+ // (e.g. one nightly `gbrain dream --dir <vault>`), a never-cycled
+ // sibling source turned doctor permanently red — which erodes the
+ // check's signal until real staleness hides inside the noise (the
+ // reporter's install masked genuinely stale sources for weeks this
+ // way). "Never cycled" also fires on a source added minutes ago.
+ // A source that HAS cycled and then went stale still escalates
+ // through the warn/fail age thresholds below — that is the
+ // regression signal this check exists for.
+ issues.push(`Source ${display} has never completed a full cycle`);
+ hasWarnings = true;
+ continue;
+ }
+ const last = new Date(raw).getTime();
+ if (!Number.isFinite(last)) {
+ issues.push(`Source ${display} has unparseable last_full_cycle_at: ${raw}`);
+ hasWarnings = true;
+ continue;
+ }
+ const ageMs = now - last;
+ if (ageMs < 0) {
+ issues.push(`Source ${display} has future last_full_cycle_at — clock skew`);
+ hasWarnings = true;
+ continue;
+ }
+ const ageHours = Math.floor(ageMs / (1000 * 60 * 60));
+ if (ageMs > failMs) {
+ issues.push(`Source ${display} last cycled ${ageHours}h ago`);
+ hasFailures = true;
+ } else if (ageMs > warnMs) {
+ issues.push(`Source ${display} last cycled ${ageHours}h ago`);
+ hasWarnings = true;
+ }
+ }
+
+ if (hasFailures) {
+ return {
+ name: 'cycle_freshness',
+ status: 'fail',
+ message: `${issues.join('; ')}. Run \`gbrain dream --source <id>\` for each stale source, or start \`gbrain autopilot\`.`,
+ };
+ }
+ if (hasWarnings) {
+ return {
+ name: 'cycle_freshness',
+ status: 'warn',
+ message: `${issues.join('; ')}. Run \`gbrain dream --source <id>\` to cycle a source, or start \`gbrain autopilot\`.`,
+ };
+ }
+ return {
+ name: 'cycle_freshness',
+ status: 'ok',
+ message: `All ${sources.length} federated source(s) cycled recently`,
+ };
+ } catch (e) {
+ return {
+ name: 'cycle_freshness',
+ status: 'warn',
+ message: `Could not check cycle freshness: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
diff --git a/src/commands/doctor/checks/core-health.ts b/src/commands/doctor/checks/core-health.ts
new file mode 100644
index 0000000000..b7812a5d04
--- /dev/null
+++ b/src/commands/doctor/checks/core-health.ts
@@ -0,0 +1,678 @@
+/**
+ * Core-health check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import { dirname, isAbsolute, join, resolve as resolvePath } from 'path';
+import { fileURLToPath } from 'url';
+import { existsSync, readFileSync, statSync } from 'fs';
+import type { BrainEngine } from '../../../core/engine.ts';
+import { REPAIR_SOURCE_CONFIG_SQL } from '../../../core/source-config-sql.ts';
+import { loadConfig } from '../../../core/config.ts';
+import type { ProgressReporter } from '../../../core/progress.ts';
+import type { Check } from '../../doctor.ts';
+
+/**
+ * Doctor check: takes.weight grid integrity (v0.32 — EXP-2).
+ *
+ * Pure helper — no `process.exit`, no side effects beyond the SQL probe.
+ * `runDoctor` calls this and pushes the result onto its check list.
+ * Tests can target this directly with a stubbed engine (codex review #7).
+ *
+ * Branches:
+ * - takes table doesn't exist (fresh brain pre-v37) → warn, "skipped"
+ * - 0 takes total → ok, "no takes yet" (avoids divide-by-zero)
+ * - off_grid / total > 10% → fail
+ * - off_grid / total > 1% → warn
+ * - else → ok
+ *
+ * Tolerance matches migration v48: any value with abs(weight - on_grid) > 1e-3
+ * is genuinely off-grid (the 0.05 grid is 5e-2; float32 noise is ~1e-7).
+ */
+const WHOKNOWS_FIXTURE_RELATIVE_PATH = 'test/fixtures/whoknows-eval.jsonl';
+
+function isGbrainSourceRoot(dir: string): boolean {
+ return (
+ existsSync(join(dir, 'src', 'cli.ts')) &&
+ existsSync(join(dir, 'skills', 'RESOLVER.md'))
+ );
+}
+
+export function resolveWhoknowsFixturePath(
+ env: NodeJS.ProcessEnv = process.env,
+ moduleUrl: string = import.meta.url,
+): string | null {
+ if (env.GBRAIN_WHOKNOWS_FIXTURE_PATH) {
+ return isAbsolute(env.GBRAIN_WHOKNOWS_FIXTURE_PATH)
+ ? env.GBRAIN_WHOKNOWS_FIXTURE_PATH
+ : resolvePath(process.cwd(), env.GBRAIN_WHOKNOWS_FIXTURE_PATH);
+ }
+
+ try {
+ let dir = dirname(fileURLToPath(moduleUrl));
+ for (let i = 0; i < 10; i++) {
+ if (isGbrainSourceRoot(dir)) return join(dir, WHOKNOWS_FIXTURE_RELATIVE_PATH);
+ const parent = dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ } catch {
+ // Some bundlers/runtimes may not expose a normal file: import URL.
+ // Doctor should surface an override hint instead of fabricating a path.
+ }
+
+ return null;
+}
+
+/**
+ * v0.33: whoknows_health — verify the eval fixture is present at the
+ * documented path. Lightweight; just checks file existence and row count,
+ * not the eval gate outcome (that runs via `gbrain eval whoknows`).
+ *
+ * Surface is intentionally narrow: a missing fixture means the eval
+ * cannot run at all, which is the highest-leverage signal. Hit-rate
+ * regression detection lives in `gbrain eval whoknows --json` and is
+ * the job of the eval command, not the doctor sweep.
+ */
+export async function whoknowsHealthCheck(_engine: BrainEngine): Promise<Check> {
+ try {
+ const fixturePath = resolveWhoknowsFixturePath();
+ if (!fixturePath) {
+ return {
+ name: 'whoknows_health',
+ status: 'warn',
+ message: 'whoknows eval fixture path could not be resolved. Set GBRAIN_WHOKNOWS_FIXTURE_PATH to the absolute path for test/fixtures/whoknows-eval.jsonl.',
+ };
+ }
+ if (!existsSync(fixturePath)) {
+ return {
+ name: 'whoknows_health',
+ status: 'warn',
+ message: `whoknows eval fixture missing at ${fixturePath}. Fix: hand-label 10 queries you'd actually run, format {query, expected_top_3_slugs, notes}.`,
+ };
+ }
+ const stat = statSync(fixturePath);
+ if (stat.size === 0) {
+ return {
+ name: 'whoknows_health',
+ status: 'warn',
+ message: 'whoknows eval fixture exists but is empty. The eval cannot pass without queries.',
+ };
+ }
+ const raw = readFileSync(fixturePath, 'utf-8');
+ const rows = raw
+ .split('\n')
+ .filter((l) => {
+ const t = l.trim();
+ return t && !t.startsWith('#') && !t.startsWith('//');
+ });
+ if (rows.length < 5) {
+ return {
+ name: 'whoknows_health',
+ status: 'warn',
+ message: `whoknows eval fixture has only ${rows.length} row(s); ENG-D2 recommends 10. Fix: add more hand-labeled queries.`,
+ };
+ }
+ return {
+ name: 'whoknows_health',
+ status: 'ok',
+ message: `whoknows eval fixture present (${rows.length} queries). Run \`gbrain eval whoknows test/fixtures/whoknows-eval.jsonl\` to grade.`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'whoknows_health',
+ status: 'warn',
+ message: `Could not check whoknows fixture: ${msg}`,
+ };
+ }
+}
+
+/**
+ * Doctor check: pgvector availability.
+ *
+ * Use the active engine instead of the module-level Postgres singleton.
+ * PGLite exposes pg_extension through its engine connection, but does not
+ * connect db.ts's Postgres singleton; using db.getConnection() here turns a
+ * healthy PGLite brain into a false warning.
+ */
+export async function pgvectorCheck(engine: BrainEngine): Promise<Check> {
+ try {
+ const ext = await engine.executeRaw<{ extname: string }>(
+ `SELECT extname FROM pg_extension WHERE extname = 'vector'`,
+ );
+ if (ext.length > 0) {
+ return { name: 'pgvector', status: 'ok', message: 'Extension installed' };
+ }
+ return { name: 'pgvector', status: 'fail', message: 'Extension not found. Run: CREATE EXTENSION vector;' };
+ } catch {
+ return { name: 'pgvector', status: 'warn', message: 'Could not check pgvector extension' };
+ }
+}
+
+/**
+ * Doctor check: JSONB columns are not double-encoded as strings.
+ *
+ * This check is valid on both Postgres and PGLite. Route through
+ * engine.executeRaw() so embedded PGLite brains are checked through their
+ * actual connection instead of the unrelated Postgres singleton.
+ */
+export async function jsonbIntegrityCheck(
+ engine: BrainEngine,
+ progress?: Pick<ProgressReporter, 'heartbeat'>,
+): Promise<Check> {
+ try {
+ const targets: Array<{ table: string; col: string; expected: 'object' | 'array'; jsonPayloadOnly?: boolean }> = [
+ { table: 'pages', col: 'frontmatter', expected: 'object' },
+ { table: 'raw_data', col: 'data', expected: 'object' },
+ { table: 'ingest_log', col: 'pages_updated', expected: 'array' },
+ { table: 'files', col: 'metadata', expected: 'object' },
+ { table: 'page_versions', col: 'frontmatter', expected: 'object' },
+ // Subagent persistence — second double-encode site (historical damage
+ // rows from the pre-v0.42.53.0 positional bind; write paths fixed in
+ // #2375). Mirrors repair-jsonb's targets incl. jsonPayloadOnly: these
+ // columns can legitimately hold jsonb STRING scalars (persistToolExec
+ // binds pre-serialized string payloads as-is), so only JSON-container
+ // content counts as damage.
+ { table: 'subagent_messages', col: 'content_blocks', expected: 'array', jsonPayloadOnly: true },
+ { table: 'subagent_tool_executions', col: 'input', expected: 'object', jsonPayloadOnly: true },
+ { table: 'subagent_tool_executions', col: 'output', expected: 'object', jsonPayloadOnly: true },
+ ];
+ let totalBad = 0;
+ const breakdown: string[] = [];
+ for (const { table, col, jsonPayloadOnly } of targets) {
+ progress?.heartbeat(`jsonb_integrity.${table}.${col}`);
+ // Skip targets whose table doesn't exist on this brain (subagent_*
+ // tables are v0.15+; pre-v0.15 brains naturally lack them).
+ const existsRows = await engine.executeRaw<{ exists: boolean }>(
+ `SELECT to_regclass($1) IS NOT NULL AS exists`,
+ [table],
+ );
+ if (!existsRows[0]?.exists) continue;
+ const damage = jsonPayloadOnly
+ ? `jsonb_typeof(${col}) = 'string' AND (${col} #>> '{}') ~ '^[[:space:]]*[\\[{]' AND pg_input_is_valid(${col} #>> '{}', 'jsonb')`
+ : `jsonb_typeof(${col}) = 'string'`;
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM ${table} WHERE ${damage}`,
+ );
+ const n = Number(rows[0]?.n ?? 0);
+ if (n > 0) { totalBad += n; breakdown.push(`${table}.${col}=${n}`); }
+ }
+ if (totalBad === 0) {
+ return { name: 'jsonb_integrity', status: 'ok', message: 'All JSONB columns store objects/arrays' };
+ }
+ return {
+ name: 'jsonb_integrity',
+ status: 'warn',
+ message: `${totalBad} row(s) double-encoded (${breakdown.join(', ')}). Fix: gbrain repair-jsonb`,
+ };
+ } catch {
+ return { name: 'jsonb_integrity', status: 'warn', message: 'Could not check JSONB integrity' };
+ }
+}
+
+/**
+ * Per-channel push-context visibility (harness hook adapters). Groups
+ * context_volunteer_events by channel over the last 7 days so the operator
+ * can see which adapters (ambient reflex / op / watch / claude-code / codex)
+ * are actually firing. Engine-aware SIBLING of buildRetrievalReflexCheck
+ * (which is engine-free and heartbeat-file based) — deliberately a separate
+ * check so the existing builder keeps its signature.
+ *
+ * Info-only (never warn/fail on quiet channels — most installs use a subset).
+ * The message distinguishes the two "installed but nothing happens" classes:
+ * a hook script that never registered (restart the harness session) vs a
+ * registered adapter whose channel went quiet. Pre-v117 brains (no events
+ * table) return ok with a note instead of throwing. A serve started before
+ * this build logs hook traffic as 'reflex' — restart serve after upgrade.
+ */
+export async function checkVolunteerChannels(
+ engine: BrainEngine,
+ opts: { sourceIds?: string[] } = {},
+): Promise<Check> {
+ const name = 'volunteer_channels';
+ try {
+ // Source scoping (cross-model P1): remote source-bound callers pass their
+ // authorized ids — an unqualified aggregate would leak other sources'
+ // activity counts/timestamps. Local trusted doctor passes none (brain-wide).
+ // Unscoped shape: no source_id predicate → the composite
+ // (source_id, volunteered_at DESC) index can't range-scan and this
+ // seq-scans the table. Accepted DELIBERATELY for the local info check
+ // (table is TTL-pruned at 90 days) — do NOT reuse on a hot path.
+ const scoped = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;
+ const rows = await engine.executeRaw<{ channel: string; n: string | number; last_fired: string | Date | null }>(
+ scoped
+ ? `SELECT channel, count(*)::int AS n, max(volunteered_at) AS last_fired
+ FROM context_volunteer_events
+ WHERE source_id = ANY($1::text[])
+ AND volunteered_at > now() - interval '7 days'
+ GROUP BY channel
+ ORDER BY channel`
+ : `SELECT channel, count(*)::int AS n, max(volunteered_at) AS last_fired
+ FROM context_volunteer_events
+ WHERE volunteered_at > now() - interval '7 days'
+ GROUP BY channel
+ ORDER BY channel`,
+ scoped ? [opts.sourceIds] : [],
+ );
+ const channels: Record<string, { count: number; last_fired: string | null }> = {};
+ for (const r of rows) {
+ channels[r.channel] = {
+ count: Number(r.n),
+ last_fired: r.last_fired ? new Date(r.last_fired).toISOString() : null,
+ };
+ }
+ const active = Object.keys(channels);
+
+ // RT reconciliation: server-side delivery counts fire at the response
+ // write — a hook client that timed out / hit its deadline / trimmed to
+ // nothing still gets counted. The hook's own heartbeat records those
+ // degradations, so surface the degraded rate next to the counts: a
+ // "healthy" channel with a mostly-degraded heartbeat is delivery failure.
+ let heartbeatNote = '';
+ let heartbeat: { user_prompt_ok: number; user_prompt_degraded: number } | undefined;
+ try {
+ const { readHeartbeatTail } = await import('../../hook.ts');
+ const tail = await readHeartbeatTail(200);
+ // Same 7-day window as the event counts (a month-old degraded streak
+ // must not indict a healthy current week), and a minimum sample floor
+ // so one bad entry can't trigger the caution.
+ const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
+ const up = tail.filter(
+ (e) => e.event === 'user-prompt' && Date.parse(e.ts ?? '') >= cutoff,
+ );
+ if (up.length >= 5) {
+ const degraded = up.filter((e) => e.outcome !== 'ok').length;
+ heartbeat = { user_prompt_ok: up.length - degraded, user_prompt_degraded: degraded };
+ if (degraded > up.length / 2) {
+ heartbeatNote = ` — CAUTION: the hook heartbeat shows ${degraded}/${up.length} user-prompt events degraded this week, so server-side counts may overstate what was actually injected`;
+ }
+ }
+ } catch { /* heartbeat surface is best-effort */ }
+
+ // Engine-aware quiet-channel guidance: the harness-hook lane rides the
+ // PGLite serve socket — on a Postgres brain, "check your registration and
+ // restart" can never make the channel fire (pull-mode covers Postgres).
+ const cfg = (() => { try { return loadConfig(); } catch { return null; } })();
+ const quietGuidance =
+ cfg?.engine === 'pglite'
+ ? 'if a hook adapter is installed, confirm its registration landed and the harness session was RESTARTED (hooks snapshot at session start); a serve older than this build logs NOTHING for the hook lane — restart serve on the new build to activate the feedback loop'
+ : 'note: the harness-hook channels require a PGLite serve socket — on this engine the hook lane stays quiet by design (pull-mode retrieval covers it)';
+ const message = active.length
+ ? `push-context channels active (7d): ${active.map((c) => `${c}=${channels[c].count}`).join(', ')}${heartbeatNote}`
+ : `no push-context activity in 7 days — ${quietGuidance}`;
+ return {
+ name,
+ status: 'ok',
+ message,
+ details: { window_days: 7, channels, ...(heartbeat ? { hook_heartbeat: heartbeat } : {}) },
+ };
+ } catch (e) {
+ // Discriminate table-absent (pre-v117 brain) from transient failures —
+ // a connection blip on a fully-migrated brain must not be misreported
+ // as an old schema. Info-only either way; never block doctor.
+ const msg = e instanceof Error ? e.message : String(e);
+ const tableAbsent = /does not exist|undefined table|no such table|42P01/i.test(msg);
+ return {
+ name,
+ status: 'ok',
+ message: tableAbsent
+ ? 'volunteer-events table not available (pre-v117 brain) — per-channel push visibility inactive'
+ : `volunteer_channels query failed (info-only check; may or may not be transient): ${msg}`,
+ details: { window_days: 7, channels: {} },
+ };
+ }
+}
+
+export async function takesWeightGridCheck(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ off_grid: string | number; total: string | number }>(
+ `SELECT
+ count(*) FILTER (WHERE weight IS NOT NULL
+ AND abs(weight::numeric - ROUND(weight::numeric * 20) / 20) > 0.001)::int AS off_grid,
+ count(*)::int AS total
+ FROM takes`,
+ );
+ const total = Number(rows[0]?.total ?? 0);
+ const offGrid = Number(rows[0]?.off_grid ?? 0);
+ if (total === 0) {
+ return { name: 'takes_weight_grid', status: 'ok', message: 'No takes yet' };
+ }
+ const ratio = offGrid / total;
+ if (ratio > 0.10) {
+ return {
+ name: 'takes_weight_grid',
+ status: 'fail',
+ message: `${offGrid}/${total} takes off the 0.05 grid (${(ratio * 100).toFixed(1)}%). Fix: gbrain apply-migrations --yes`,
+ };
+ }
+ if (ratio > 0.01) {
+ return {
+ name: 'takes_weight_grid',
+ status: 'warn',
+ message: `${offGrid}/${total} takes off the 0.05 grid (${(ratio * 100).toFixed(1)}%). Fix: gbrain apply-migrations --yes`,
+ };
+ }
+ return {
+ name: 'takes_weight_grid',
+ status: 'ok',
+ message: offGrid === 0
+ ? `${total} take(s) on grid`
+ : `${total} take(s) on grid (${offGrid} within tolerance)`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ // takes table missing on a fresh pre-v37 brain — warn, don't fail.
+ return {
+ name: 'takes_weight_grid',
+ status: 'warn',
+ message: `Could not check takes weight grid: ${msg}`,
+ };
+ }
+}
+
+/**
+ * Child-table orphan detection (closes #1063).
+ *
+ * The autopilot `orphans` phase (src/core/cycle.ts:runPhaseOrphans) detects
+ * orphan PAGES (pages with no inbound links via the page-graph). It does NOT
+ * scan FK-child tables for orphan rows. When a bulk page delete leaves
+ * orphans in `content_chunks` / `page_versions` / `tags` / `takes` / etc.
+ * — whether from pre-FK migrations, race conditions, or a code path that
+ * bypassed cascade — they persist indefinitely until manual SQL cleanup.
+ *
+ * All ten FK-to-pages tables declare `ON DELETE CASCADE` in the live schema
+ * (verified via `pg_constraint` snapshot in the issue body), so finding any
+ * orphan row is by definition unexpected. The check ships paste-ready
+ * cleanup SQL when orphans surface.
+ *
+ * Excluded: `files.page_id` and `links.origin_page_id` — both declared as
+ * `ON DELETE SET NULL`, so a NULL value is a valid state (file/link survives
+ * after page deletion); only NOT-NULL-but-page-missing is an orphan there.
+ * The check encodes that distinction for the two SET NULL columns.
+ *
+ * Pure helper for parity with `takesWeightGridCheck` so tests can target it
+ * directly without driving the full `runDoctor` pipeline.
+ */
+export async function childTableOrphansCheck(engine: BrainEngine): Promise<Check> {
+ // (table, fk_column, allow_null). When allow_null=true, NULL is a valid
+ // state (FK was declared ON DELETE SET NULL); the orphan predicate filters
+ // out NULL values. When false, NULL is impossible by NOT NULL constraint;
+ // any value not in pages.id is an orphan.
+ const targets: Array<{ table: string; col: string; allowNull: boolean }> = [
+ { table: 'content_chunks', col: 'page_id', allowNull: false },
+ { table: 'page_versions', col: 'page_id', allowNull: false },
+ { table: 'tags', col: 'page_id', allowNull: false },
+ { table: 'takes', col: 'page_id', allowNull: false },
+ { table: 'raw_data', col: 'page_id', allowNull: false },
+ { table: 'timeline_entries', col: 'page_id', allowNull: false },
+ { table: 'links', col: 'from_page_id', allowNull: false },
+ { table: 'links', col: 'to_page_id', allowNull: false },
+ { table: 'links', col: 'origin_page_id', allowNull: true },
+ { table: 'files', col: 'page_id', allowNull: true },
+ ];
+ let totalOrphans = 0;
+ const breakdown: string[] = [];
+ const cleanupSql: string[] = [];
+ const errors: string[] = [];
+ for (const { table, col, allowNull } of targets) {
+ try {
+ // NOT IN subquery is portable across postgres + PGLite. The `pages.id`
+ // subquery covers every existing parent row.
+ const nullFilter = allowNull ? `${col} IS NOT NULL AND ` : '';
+ const rows = await engine.executeRaw<{ n: string | number }>(
+ `SELECT COUNT(*)::int AS n FROM ${table} WHERE ${nullFilter}${col} NOT IN (SELECT id FROM pages)`,
+ );
+ const n = Number(rows[0]?.n ?? 0);
+ if (n > 0) {
+ totalOrphans += n;
+ breakdown.push(`${table}.${col}=${n}`);
+ cleanupSql.push(
+ `DELETE FROM ${table} WHERE ${nullFilter}${col} NOT IN (SELECT id FROM pages);`,
+ );
+ }
+ } catch (e) {
+ // Table or column may not exist on older schemas — skip and continue.
+ // Aggregate the errors so doctor surfaces "could not check N tables"
+ // when a real failure shape appears (network, lock, syntax).
+ const msg = e instanceof Error ? e.message : String(e);
+ errors.push(`${table}.${col}: ${msg.slice(0, 80)}`);
+ }
+ }
+ if (totalOrphans === 0 && errors.length === 0) {
+ return {
+ name: 'child_table_orphans',
+ status: 'ok',
+ message: 'All FK-child tables clean (10 tables checked)',
+ };
+ }
+ if (totalOrphans === 0 && errors.length > 0) {
+ return {
+ name: 'child_table_orphans',
+ status: 'warn',
+ message: `Could not check ${errors.length}/10 FK-child tables (older schema or transient error): ${errors.slice(0, 3).join('; ')}`,
+ };
+ }
+ return {
+ name: 'child_table_orphans',
+ status: 'warn',
+ message:
+ `${totalOrphans} orphan row(s) in FK-child tables (${breakdown.join(', ')}). ` +
+ `Cleanup: ${cleanupSql.join(' ')}`,
+ };
+}
+
+/**
+ * Raw-source persistence guarantee (#1978, warn-only v1).
+ *
+ * Invariant: every synthesized/derived page (dream_generated:true frontmatter
+ * or type:synthesis) must either carry a raw trace or declare an explicit
+ * exemption. Accepted traces:
+ * - frontmatter key `raw_trace` / `raw_source` / `source_uri`
+ * - an attached `raw_data` row
+ * - `synthesis_evidence` rows (think-op citations)
+ * - explicit `raw_trace_exempt: true` (reason in `raw_trace_exempt_reason`)
+ *
+ * v1 is deliberately warn-only — no write path is blocked. Escalation to
+ * fail-closed enforcement in the synthesis/import write paths is the v2
+ * follow-up once real brains run clean.
+ *
+ * Pure helper (engine.executeRaw only) for parity with
+ * childTableOrphansCheck so tests can target it directly.
+ */
+export async function rawProvenanceCheck(engine: BrainEngine): Promise<Check> {
+ const where = `
+ p.deleted_at IS NULL
+ AND (COALESCE(p.frontmatter->>'dream_generated', '') = 'true' OR p.type = 'synthesis')
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ?| ARRAY['raw_trace', 'raw_source', 'source_uri', 'raw_trace_exempt'])
+ AND NOT EXISTS (SELECT 1 FROM raw_data rd WHERE rd.page_id = p.id)
+ AND NOT EXISTS (SELECT 1 FROM synthesis_evidence se WHERE se.synthesis_page_id = p.id)`;
+ try {
+ const rows = await engine.executeRaw<{ n: string | number }>(
+ `SELECT COUNT(*)::int AS n FROM pages p WHERE ${where}`,
+ );
+ const n = Number(rows[0]?.n ?? 0);
+ if (n === 0) {
+ return {
+ name: 'raw_provenance',
+ status: 'ok',
+ message: 'All synthesized pages carry a raw trace or explicit exemption',
+ };
+ }
+ const sample = await engine.executeRaw<{ slug: string }>(
+ `SELECT p.slug FROM pages p WHERE ${where} ORDER BY p.slug LIMIT 5`,
+ );
+ const slugs = sample.map(r => r.slug).join(', ');
+ return {
+ name: 'raw_provenance',
+ status: 'warn',
+ message:
+ `${n} synthesized page(s) lack a raw trace (no raw_trace/raw_source/source_uri frontmatter, ` +
+ `raw_data row, or synthesis evidence) and carry no raw_trace_exempt marker. e.g. ${slugs}. ` +
+ `Fix: stamp raw_source (path/URI of the source material) or raw_trace_exempt: true + ` +
+ `raw_trace_exempt_reason in frontmatter. Warn-only (#1978).`,
+ };
+ } catch {
+ return { name: 'raw_provenance', status: 'warn', message: 'Could not check raw provenance (older schema?)' };
+ }
+}
+
+/**
+ * #2829: source `config` is a jsonb OBJECT column (`DEFAULT '{}'::jsonb`), but a
+ * re-wrapping bug could store it as a JSON string scalar ("{}", "\"{}\"", ...)
+ * that grows a layer on every read→write cycle. Any row where
+ * `jsonb_typeof(config) <> 'object'` is corrupted — federation and ACL settings
+ * on that source are read off a string instead of the settings object. Surface
+ * the affected sources with the repair path. The `gbrain sources` config writers
+ * now normalize before write, so any config-writing command self-heals the row
+ * (the app unwraps up to 10 nested layers); the SQL below repairs one layer
+ * directly for the common case.
+ */
+export async function checkSourceConfigShape(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ id: string; typ: string | null }>(
+ `SELECT id, jsonb_typeof(config) AS typ FROM sources WHERE jsonb_typeof(config) <> 'object'`,
+ );
+ if (rows.length === 0) {
+ return {
+ name: 'source_config_shape',
+ status: 'ok',
+ message: 'All source config values are JSON objects',
+ };
+ }
+ const affected = rows.map((r) => `${r.id} (${r.typ ?? 'null'})`).join(', ');
+ return {
+ name: 'source_config_shape',
+ status: 'warn',
+ message:
+ `${rows.length} source(s) have a non-object config — a JSON string/scalar ` +
+ `instead of an object (the #2829 re-wrapping bug): ${affected}. ` +
+ `Federation and ACL settings on these sources won't be read correctly. ` +
+ `Repair by running any 'gbrain sources' config write (self-heals nested ` +
+ `strings and recoverable arrays), or in SQL: ${REPAIR_SOURCE_CONFIG_SQL}`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return { name: 'source_config_shape', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
+/**
+ * #2674 — pglite_scratch_probe: distinguish a damaged PGLite store from a
+ * broken WASM runtime.
+ *
+ * PGLite reports only `Aborted()` to JS (the PANIC goes to its own stderr),
+ * so when init fails, the error string cannot say WHICH of the two it is.
+ * The probe initializes a throwaway store in a temp dir, round-trips a row,
+ * and reads the outcome:
+ *
+ * - scratch works, real init failed → the runtime is fine; the failure is
+ * specific to YOUR store. The store-damage verdict is only ASSERTED when
+ * the caller supplies positive evidence (`storeDamageEvidence`: a
+ * damage-class disk diagnosis from `inspectPgliteDataDir`, or a
+ * wasm-abort/corrupt classification of the real init error). engine=null
+ * alone also covers locks and config refusals — blaming the store for
+ * those was the original false-positive defect; without evidence the
+ * message hedges and points at the `pglite_data_dir` diagnosis instead.
+ * - scratch fails too → the runtime cannot start on this machine; report
+ * OS + Bun versions on #223.
+ *
+ * COST GATE: a PGLite cold start is 5–20s on loaded machines, so this never
+ * runs on a routine `gbrain doctor`. It runs only when (a) the real PGLite
+ * engine actually failed to open (engine=null, not --fast, configured engine
+ * is pglite) AND the disk diagnosis didn't already fully explain the failure
+ * (a live lock / missing dir needs no runtime probe), or (b) the operator
+ * asks with `--probe-pglite`.
+ *
+ * `probeFn` is a test seam so message routing can be pinned without paying
+ * real cold starts.
+ */
+export async function checkPgliteScratchProbe(opts: {
+ realInitFailed: boolean;
+ /**
+ * Positive evidence the REAL store is damaged: `inspectPgliteDataDir`
+ * verdict wal-corruption-likely/unsupported-layout (buildChecks path) or a
+ * wasm-abort/corrupt classification of the actual connect error (remote
+ * path). Without it the scratch-ok arm hedges instead of asserting damage.
+ */
+ storeDamageEvidence?: boolean;
+ realStorePath?: string;
+ probeFn?: () => Promise<import('../../../core/pglite-engine.ts').PgliteScratchProbeResult>;
+}): Promise<Check> {
+ const name = 'pglite_scratch_probe';
+ try {
+ const probe =
+ opts.probeFn ??
+ (async () => {
+ const { probePgliteScratchStore } = await import('../../../core/pglite-engine.ts');
+ return probePgliteScratchStore(opts.realStorePath);
+ });
+ const r = await probe();
+ const secs = (r.duration_ms / 1000).toFixed(1);
+ if (r.ok) {
+ if (opts.realInitFailed && opts.storeDamageEvidence) {
+ return {
+ name,
+ status: 'fail',
+ message:
+ `A scratch PGLite store initialized, wrote and read back fine on this machine (${secs}s), ` +
+ `so the runtime is healthy and YOUR STORE is damaged — not the WASM runtime. ` +
+ `Your markdown is unaffected: the DB holds derived data (chunks, embeddings, links, facts) that a re-sync rebuilds. ` +
+ `Recover: \`gbrain pglite-repair --dry-run\` to diagnose, \`gbrain pglite-repair --yes\` for in-place WAL repair (data preserved); ` +
+ `if that can't fix it, restore a backup of the store directory or run \`gbrain reinit-pglite\` (wipes + re-inits + re-syncs; ` +
+ `defaults embedding flags from your config file).`,
+ details: { scratch_ok: true, duration_ms: r.duration_ms },
+ };
+ }
+ if (opts.realInitFailed) {
+ // Runtime proven healthy, but no independent evidence of store DAMAGE
+ // — engine=null also covers locks, config refusals, and transient
+ // failures. Hedge rather than convict the store (#2674 review).
+ return {
+ name,
+ status: 'warn',
+ message:
+ `A scratch PGLite store initialized, wrote and read back fine on this machine (${secs}s), ` +
+ `so the WASM runtime is healthy — the failure opening your brain is specific to your store, ` +
+ `its lock, or its configuration. See the \`pglite_data_dir\` check for the on-disk diagnosis; ` +
+ `\`gbrain pglite-repair --dry-run\` diagnoses without mutating anything.`,
+ details: { scratch_ok: true, duration_ms: r.duration_ms },
+ };
+ }
+ return {
+ name,
+ status: 'ok',
+ message: `PGLite runtime healthy: scratch store round-trip in ${secs}s.`,
+ details: { scratch_ok: true, duration_ms: r.duration_ms },
+ };
+ }
+ const errLine = (r.error ?? 'unknown error').split('\n')[0];
+ if (opts.realInitFailed) {
+ return {
+ name,
+ status: 'fail',
+ message:
+ `A fresh scratch PGLite store ALSO failed to start (${secs}s), so the WASM runtime cannot run ` +
+ `on this machine — your store is not necessarily damaged. Report your OS and Bun versions on ` +
+ `https://github.com/garrytan/gbrain/issues/223. Scratch error: ${errLine}`,
+ details: { scratch_ok: false, duration_ms: r.duration_ms, error: r.error, verdict: r.verdict },
+ };
+ }
+ return {
+ name,
+ status: 'warn',
+ message:
+ `Your real store opened, but a fresh scratch PGLite store failed to initialize (${secs}s) — ` +
+ `new stores can't be created on this machine. Report your OS and Bun versions on ` +
+ `https://github.com/garrytan/gbrain/issues/223. Scratch error: ${errLine}`,
+ details: { scratch_ok: false, duration_ms: r.duration_ms, error: r.error, verdict: r.verdict },
+ };
+ } catch (e) {
+ // Includes the never-touch-the-real-store guard refusal. The probe not
+ // running is a diagnostic gap, not a diagnosis — warn, don't fail.
+ const msg = e instanceof Error ? e.message : String(e);
+ return { name, status: 'warn', message: `scratch probe could not run: ${msg}` };
+ }
+}
+
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
new file mode 100644
index 0000000000..d79704681b
--- /dev/null
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -0,0 +1,948 @@
+/**
+ * Extraction + sync-lag check cluster (incl. checkSyncFreshness) — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import { join } from 'path';
+import { existsSync, readdirSync } from 'fs';
+import type { BrainEngine } from '../../../core/engine.ts';
+import { probeSourceGitState } from '../../../core/git-head.ts';
+// v0.41.32.0: remote staleness reads the stored newest_content_at column via
+// this pure comparator (no git subprocess on the HTTP MCP doctor path).
+import { lagFromContentMs, resolveStalenessCeilingSeconds } from '../../../core/source-health.ts';
+import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core/env-number.ts';
+import { CHUNKER_VERSION } from '../../../core/chunkers/code.ts';
+import { LINK_EXTRACTOR_VERSION_TS } from '../../../core/link-extraction.ts';
+import { isUndefinedColumnError } from '../../../core/utils.ts';
+import {
+ loadStorageConfig,
+ effectiveDbOnlyDirs,
+ DERIVE_PHASE_DB_ONLY_DEFAULTS,
+ findDbOnlyCollisions,
+} from '../../../core/storage-config.ts';
+import { slugifyPath } from '../../../core/sync.ts';
+import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';
+import type { Check } from '../../doctor.ts';
+
+/** Local aliases; the shared warn-once memo lives in core so it can't fork per module. */
+const _resolveEnvNumber = resolveEnvNumber;
+const _resolveSyncFreshnessHours = resolveHoursEnv;
+
+/**
+ * v0.42.7 (#1696): single source of truth for the extraction-lag warn
+ * threshold (percent). Both the `links_extraction_lag` doctor check AND the
+ * end-of-sync nudge (`sync.ts:maybeExtractionNudge`) resolve through this +
+ * `_resolveEnvNumber` so "the nudge fires iff doctor would warn" can't drift.
+ */
+export const EXTRACTION_LAG_WARN_PCT_DEFAULT = 20;
+/** Min non-deleted page count below which extraction-lag is vacuous-skipped
+ * (unless an explicit --source scope is set). Shared by doctor + the sync
+ * nudge (D6/C4) so their skip predicates match exactly. */
+export const EXTRACTION_LAG_MIN_PAGES = 100;
+
+/**
+ * Sync freshness check (v0.32.4) — verify that sources with local_path have
+ * been synced recently. Detects the silent failure mode where `gbrain sync`
+ * stopped running and brain search now misses recent pages.
+ *
+ * Pure staleness check. Reads `sources.last_sync_at` only — no filesystem
+ * access. Filesystem-vs-DB drift detection is intentionally out of scope:
+ * - doctorReportRemote runs in the HTTP MCP server (src/commands/serve-http.ts);
+ * walking arbitrary DB-supplied paths from a remote-callable endpoint
+ * crosses a trust boundary (OAuth write scope could mutate local_path).
+ * - Drift detection belongs in `multi_source_drift` which already has
+ * GBRAIN_DRIFT_LIMIT + GBRAIN_DRIFT_TIMEOUT_MS guards.
+ *
+ * Thresholds (env-overridable, default = 24h warn / 72h fail):
+ * - GBRAIN_SYNC_FRESHNESS_WARN_HOURS
+ * - GBRAIN_SYNC_FRESHNESS_FAIL_HOURS
+ * Invalid values (NaN, ≤0) fall back to defaults with a once-per-process warn.
+ *
+ * Edge cases handled:
+ * - last_sync_at IS NULL → fail "never synced"
+ * - last_sync_at > now() (clock skew / corrupted timestamp) → warn
+ * - mixed sources → highest-severity drives the overall status
+ * - executeRaw throws → outer-catch warn so doctor keeps running
+ *
+ * Failure messages embed `source.id` so the fix command
+ * `gbrain sync --source <id>` matches what the user copy-pastes.
+ */
+
+/**
+ * v0.42.7 (#1696) — links_extraction_lag doctor check.
+ *
+ * The signal that surfaces the "imported ≠ curated" root cause: pages whose
+ * link/timeline extraction is stale (never run, edited-since, or extractor
+ * bumped). Without it, a brain can run for months at 0% typed-edge coverage
+ * with nothing warning the operator.
+ *
+ * Warn-only by DEFAULT (>20% stale). Hard-fail ONLY when the operator opts in
+ * via GBRAIN_EXTRACTION_LAG_FAIL_PCT — so a just-upgraded 280K-page brain
+ * (every page NULL → 100% stale) gets a loud WARN, never a non-zero exit that
+ * would break a CI/cron pipeline gating on `gbrain doctor`.
+ *
+ * Vacuous-skip on tiny brains (<100 pages, no --source) like orphan_ratio.
+ * Pre-v112 brains (column missing) degrade to OK via isUndefinedColumnError.
+ * Strictly SQL — no filesystem/git access — so it's safe to wire into the
+ * thin-client doctorReportRemote path (CDX-5 trust boundary).
+ *
+ * `opts.sourceId` scopes both the denominator and the stale count to one
+ * source (the explicit-only `--source` parse, like orphan_ratio).
+ */
+export async function checkLinksExtractionLag(
+ engine: BrainEngine,
+ opts?: { sourceId?: string },
+): Promise<Check> {
+ const name = 'links_extraction_lag';
+ const sourceId = opts?.sourceId;
+ const fix = "Run: gbrain extract --stale";
+ try {
+ const totalRows = await engine.executeRaw<{ count: number }>(
+ sourceId
+ ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND source_id = $1`
+ : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL`,
+ sourceId ? [sourceId] : [],
+ );
+ const total = Number(totalRows[0]?.count ?? 0);
+ if (total === 0) {
+ return { name, status: 'ok', message: 'Extraction lag not applicable (no pages)' };
+ }
+ // Vacuous-skip tiny brains unless explicitly source-scoped. Shared floor
+ // const so the sync nudge (D6/C4) skips on the exact same predicate.
+ if (total < EXTRACTION_LAG_MIN_PAGES && !sourceId) {
+ return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)` };
+ }
+
+ const stale = await engine.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS });
+ const pct = (stale / total) * 100;
+ const pctStr = pct.toFixed(0);
+ const scope = sourceId ? ` in source '${sourceId}'` : '';
+
+ const warnPct = _resolveEnvNumber('GBRAIN_EXTRACTION_LAG_WARN_PCT', EXTRACTION_LAG_WARN_PCT_DEFAULT, { unit: '%' });
+ // Fail threshold is DISABLED unless explicitly set (warn-only default). A
+ // bare unset env var → no hard-fail; invalid value → warn-once + disabled.
+ let failPct: number | undefined;
+ const failRaw = process.env.GBRAIN_EXTRACTION_LAG_FAIL_PCT;
+ if (failRaw !== undefined && failRaw !== '') {
+ const n = Number(failRaw);
+ if (Number.isFinite(n) && n > 0) {
+ failPct = n;
+ } else {
+ warnOnceForEnv(
+ 'GBRAIN_EXTRACTION_LAG_FAIL_PCT',
+ `[gbrain] Ignoring invalid GBRAIN_EXTRACTION_LAG_FAIL_PCT=${failRaw}; hard-fail stays disabled.`,
+ );
+ }
+ }
+
+ const details = { total, stale, pct: Number(pctStr), warn_pct: warnPct, fail_pct: failPct ?? null, source_id: sourceId ?? null };
+ if (failPct !== undefined && pct > failPct) {
+ return { name, status: 'fail', message: `${stale}/${total} pages (${pctStr}%)${scope} need link/timeline extraction (> ${failPct}% fail threshold). ${fix}`, details };
+ }
+ if (pct > warnPct) {
+ return { name, status: 'warn', message: `${stale}/${total} pages (${pctStr}%)${scope} have un-extracted edges. ${fix}`, details };
+ }
+ return { name, status: 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}`, details };
+ } catch (e) {
+ // Pre-v112 brain: links_extracted_at column doesn't exist yet. Graceful OK
+ // (migration/bootstrap adds it; nothing to assess until then).
+ if (isUndefinedColumnError(e, 'links_extracted_at')) {
+ return { name, status: 'ok', message: 'links_extracted_at not present (pre-v112 brain)' };
+ }
+ return { name, status: 'warn', message: `Could not check links_extraction_lag: ${(e as Error).message}` };
+ }
+}
+
+/**
+ * issue #160 — unverified_extractions doctor check.
+ *
+ * The extraction quarantine lane parks auto-extracted entity stubs
+ * (frontmatter `provenance: 'auto-extracted'` + `status: 'unverified'`)
+ * until the owner promotes or rejects them. A queue nobody reviews decays
+ * into invisible clutter, so this check counts stubs older than N days
+ * (default 7) and nudges toward the review surface. Exported for direct
+ * testing (mirrors checkLinksExtractionLag).
+ */
+export async function checkUnverifiedExtractions(
+ engine: BrainEngine,
+ opts?: { sourceId?: string; days?: number },
+): Promise<Check> {
+ const name = 'unverified_extractions';
+ const days = opts?.days ?? 7;
+ const sourceId = opts?.sourceId;
+ try {
+ const params: unknown[] = [String(days)];
+ let srcClause = '';
+ if (sourceId) {
+ params.push(sourceId);
+ srcClause = 'AND p.source_id = $2';
+ }
+ const rows = await engine.executeRaw<{ n: string | number }>(
+ `SELECT COUNT(*)::int AS n FROM pages p
+ WHERE p.deleted_at IS NULL
+ AND ${unverifiedExtractionFragment('p')}
+ AND p.created_at < now() - ($1 || ' days')::interval
+ ${srcClause}`,
+ params,
+ );
+ const n = Number(rows[0]?.n ?? 0);
+ return {
+ name,
+ status: n > 0 ? 'warn' : 'ok',
+ message: n > 0
+ ? `${n} unverified auto-extracted entity stub(s) older than ${days} days awaiting review. List with 'gbrain extraction-pending'; promote/reject with 'gbrain extraction-review <promote|reject> --slugs <slug,...>'.`
+ : 'No stale unverified extraction stubs',
+ details: { count: n, days, source_id: sourceId ?? null },
+ };
+ } catch (e) {
+ return { name, status: 'warn', message: `Could not check unverified_extractions: ${(e as Error).message}` };
+ }
+}
+
+/**
+ * issue #2250 (reported by @615Works) — content_hash_duplicates.
+ *
+ * `gbrain import` run from the wrong root (one level too deep) drops the
+ * path prefix from every slug, leaving `people/x` and `x` coexisting with
+ * identical content. `dream --phase purge` never removes them (they aren't
+ * file-backed orphans) and nothing surfaced the condition. One GROUP BY —
+ * never an N² hash comparison — flags hash groups that contain BOTH a bare
+ * slug (no '/') and a path-prefixed slug.
+ */
+export async function checkContentHashDuplicates(engine: BrainEngine): Promise<Check> {
+ const name = 'content_hash_duplicates';
+ const fix = 'Fix: gbrain pages delete <bare-slug> for each pair, then gbrain pages purge-deleted --older-than 0';
+ try {
+ const rows = await engine.executeRaw<{ source_id: string; content_hash: string; slugs: string }>(
+ `SELECT source_id, content_hash,
+ string_agg(slug, '|' ORDER BY length(slug), slug) AS slugs
+ FROM pages
+ WHERE deleted_at IS NULL AND content_hash IS NOT NULL AND content_hash <> ''
+ GROUP BY source_id, content_hash
+ HAVING count(*) > 1
+ AND count(*) FILTER (WHERE strpos(slug, '/') = 0) > 0
+ AND count(*) FILTER (WHERE strpos(slug, '/') > 0) > 0
+ LIMIT 50`,
+ );
+ if (rows.length === 0) {
+ return { name, status: 'ok', message: 'No content-hash duplicate pairs (bare vs path-prefixed slugs)' };
+ }
+ let pairCount = 0;
+ const samples: string[] = [];
+ for (const r of rows) {
+ const slugs = String(r.slugs).split('|');
+ const prefixed = slugs.filter(s => s.includes('/'));
+ for (const bare of slugs.filter(s => !s.includes('/'))) {
+ const twin = prefixed.find(p => p.endsWith('/' + bare)) ?? prefixed[0];
+ pairCount++;
+ if (samples.length < 5) samples.push(`${bare} <-> ${twin}`);
+ }
+ }
+ return {
+ name,
+ status: 'warn',
+ message: `${pairCount} content-hash duplicate pair(s) detected (same content, differing slug forms — usually an import run from the wrong root, which drops the path prefix). Sample: ${samples.join('; ')}. ${fix}`,
+ details: { pair_count: pairCount, hash_groups: rows.length, sample_pairs: samples },
+ };
+ } catch (e) {
+ return { name, status: 'warn', message: `Could not check content-hash duplicates: ${(e as Error).message}` };
+ }
+}
+
+/** Walk a repo for markdown files and return their slugified (lowercased) slugs. */
+function collectMarkdownSlugs(root: string): Set<string> {
+ const out = new Set<string>();
+ const stack = [''];
+ while (stack.length > 0) {
+ const rel = stack.pop()!;
+ let entries;
+ try {
+ entries = readdirSync(rel ? join(root, rel) : root, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const e of entries) {
+ // Hidden directories can contain canonical, tracked knowledge (for
+ // example `.archive/`). Only implementation metadata is never a page.
+ if (e.name === '.git' || e.name === 'node_modules') continue;
+ const childRel = rel ? `${rel}/${e.name}` : e.name;
+ if (e.isDirectory()) stack.push(childRel);
+ else if (/\.mdx?$/i.test(e.name)) out.add(slugifyPath(childRel).toLowerCase());
+ }
+ }
+ return out;
+}
+
+/**
+ * issue #2784 (reported by @alexputici) — undeclared_db_only_pages.
+ *
+ * A markdown page with no backing file that sits outside every declared
+ * db_only path is invisible to any file-lane backup/recovery reasoning: an
+ * operator auditing "what would survive a DB loss" gets a silently wrong
+ * answer. The engine's own derive-phase output prefixes
+ * (DERIVE_PHASE_DB_ONLY_DEFAULTS) count as implicitly declared so the check
+ * stays quiet on healthy brains. Deliberately allowed to stat the source
+ * repo (the one thing the SQL-only check registry could never see).
+ */
+export async function checkUndeclaredDbOnlyPages(engine: BrainEngine): Promise<Check> {
+ const name = 'undeclared_db_only_pages';
+ try {
+ const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
+ );
+ const checkable = sources.filter(s => s.local_path && existsSync(s.local_path));
+ if (checkable.length === 0) {
+ return { name, status: 'ok', message: 'Not applicable (no sources with a local repo path on this host)' };
+ }
+ let total = 0;
+ const samples: string[] = [];
+ const perSource: Record<string, number> = {};
+ for (const src of checkable) {
+ let declared: string[] = [];
+ try {
+ declared = loadStorageConfig(src.local_path)?.db_only ?? [];
+ } catch {
+ // invalid gbrain.yml — treated as no declarations; the sync path
+ // already surfaces the config error itself.
+ }
+ const dbOnlyDirs = effectiveDbOnlyDirs(declared);
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND page_kind = 'markdown'`,
+ [src.id],
+ );
+ if (rows.length === 0) continue;
+ const backed = collectMarkdownSlugs(src.local_path!);
+ for (const { slug } of rows) {
+ if (dbOnlyDirs.some(dir => slug.startsWith(dir))) continue;
+ if (backed.has(slug)) continue;
+ total++;
+ perSource[src.id] = (perSource[src.id] ?? 0) + 1;
+ if (samples.length < 5) samples.push(`${slug} (src=${src.id})`);
+ }
+ }
+ if (total === 0) {
+ return {
+ name,
+ status: 'ok',
+ message: `Every DB page is file-backed or under a declared/default db_only path (derive-phase defaults: ${DERIVE_PHASE_DB_ONLY_DEFAULTS.join(' ')})`,
+ };
+ }
+ return {
+ name,
+ status: 'warn',
+ message: `${total} DB page(s) have no backing file and sit outside every declared/default db_only path — invisible to file-lane backup/recovery. Sample: ${samples.join('; ')}. Fix: restore or export the files, or declare their prefixes under storage.db_only in gbrain.yml (derive-phase defaults already cover: ${DERIVE_PHASE_DB_ONLY_DEFAULTS.join(' ')})`,
+ details: { total, per_source: perSource, sample_slugs: samples },
+ };
+ } catch (e) {
+ return { name, status: 'warn', message: `Could not check undeclared db-only pages: ${(e as Error).message}` };
+ }
+}
+
+/**
+ * issue #2788 (reported by @alexputici) — db_only_collector_collision.
+ *
+ * Declaring a collector's output dir in storage.db_only silently kills its
+ * ingestion: manageGitignore auto-gitignores the dir, the git-walking sync
+ * never sees the files, and import honors .gitignore too — everything stays
+ * green while nothing reaches the DB (a 7-week outage in the field). The
+ * recipe's `output_paths` frontmatter is the ground truth; the same warning
+ * also fires at .gitignore-write time inside sync's manageGitignore.
+ */
+export async function checkDbOnlyCollectorCollision(
+ engine: BrainEngine,
+ opts?: { collectors?: Array<{ id: string; output_path: string }> },
+): Promise<Check> {
+ const name = 'db_only_collector_collision';
+ try {
+ let collectors = opts?.collectors;
+ if (!collectors) {
+ const { getConfiguredCollectorOutputs } = await import('../../integrations.ts');
+ collectors = getConfiguredCollectorOutputs();
+ }
+ if (collectors.length === 0) {
+ return { name, status: 'ok', message: 'No configured collectors declare output paths' };
+ }
+ const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
+ `SELECT id, local_path FROM sources WHERE local_path IS NOT NULL`,
+ );
+ const hits: string[] = [];
+ for (const src of sources) {
+ if (!src.local_path || !existsSync(src.local_path)) continue;
+ let dbOnly: string[] = [];
+ try {
+ dbOnly = loadStorageConfig(src.local_path)?.db_only ?? [];
+ } catch {
+ continue;
+ }
+ if (dbOnly.length === 0) continue;
+ for (const hit of findDbOnlyCollisions(collectors, dbOnly)) {
+ hits.push(`collector '${hit.id}' writes to '${hit.output_path}' which is inside db_only path '${hit.db_only_dir}' (source ${src.id})`);
+ }
+ }
+ if (hits.length === 0) {
+ return { name, status: 'ok', message: 'No collector output dir falls inside a db_only path' };
+ }
+ return {
+ name,
+ status: 'warn',
+ message: `${hits.length} collector/db_only collision(s): ${hits.join('; ')}. db_only dirs are auto-gitignored, so sync AND import silently skip files there — the collector runs green while nothing reaches the DB. Fix: remove the prefix from storage.db_only in gbrain.yml, or move the collector output.`,
+ details: { collisions: hits },
+ };
+ } catch (e) {
+ return { name, status: 'warn', message: `Could not check collector/db_only collisions: ${(e as Error).message}` };
+ }
+}
+
+/**
+ * issue #1678 — extract_atoms_backlog doctor check.
+ *
+ * Closes the "silent backlog" gap: extract_atoms is pack-gated, so on a brain
+ * whose active pack doesn't declare the phase it NEVER runs in the routine
+ * cycle and pages accumulate forever with zero signal (the cycle reports a
+ * clean `skipped`). This check counts the eligible-but-unextracted pages and,
+ * when the pack doesn't run the phase AND the backlog is real, WARNs with the
+ * exact `--drain` command.
+ *
+ * PAGE-BACKLOG-ONLY (Codex #11): extract_atoms also discovers transcript files
+ * at runtime; this counts DB pages only — labeled in details. No
+ * synthesize_concepts sibling this wave (Codex #12: that phase is a stub with
+ * no real eligibility predicate; a check would be a fake signal).
+ */
+export async function computeExtractAtomsBacklogCheck(
+ engine: BrainEngine,
+): Promise<Check> {
+ const name = 'extract_atoms_backlog';
+ const approx = 'page backlog only; transcript corpus not counted';
+ try {
+ const { countExtractAtomsBacklog } = await import('../../../core/cycle/extract-atoms.ts');
+ const backlog = await countExtractAtomsBacklog(engine); // brain-wide
+ if (backlog === null) {
+ return { name, status: 'warn', message: 'backlog query failed (could not count eligible pages)' };
+ }
+
+ const { packDeclaresPhase } = await import('../../../core/cycle.ts');
+ let declared = false;
+ try { declared = await packDeclaresPhase(engine, 'extract_atoms'); } catch { declared = false; }
+
+ if (backlog === 0) {
+ return {
+ name, status: 'ok',
+ message: 'no pages awaiting atom extraction',
+ details: { backlog, pack_declares_phase: declared, known_approximation: approx },
+ };
+ }
+
+ // The incident: pack does NOT run the phase but a real backlog exists →
+ // it will grow forever without a signal. WARN with the drain command.
+ if (!declared && backlog > 10) {
+ const fix = 'gbrain dream --phase extract_atoms --drain --window 120 (or declare extract_atoms in your active schema pack)';
+ return {
+ name, status: 'warn',
+ message: `${backlog} pages eligible for atom extraction but the active pack does not run extract_atoms — backlog growing. Fix: ${fix}`,
+ details: { backlog, pack_declares_phase: false, fix_hint: fix, known_approximation: approx },
+ };
+ }
+
+ if (declared) {
+ // Pack runs it; the routine cycle drains in bounded batches. Informational.
+ return {
+ name, status: 'ok',
+ message: `${backlog} page(s) pending; active pack runs extract_atoms each cycle`,
+ details: { backlog, pack_declares_phase: true, known_approximation: approx },
+ };
+ }
+
+ // Not declared but below the warn threshold.
+ return {
+ name, status: 'ok',
+ message: `${backlog} page(s) eligible (below warn threshold; pack does not run extract_atoms)`,
+ details: { backlog, pack_declares_phase: false, known_approximation: approx },
+ };
+ } catch (err) {
+ return { name, status: 'warn', message: `extract_atoms_backlog check failed: ${(err as Error).message}` };
+ }
+}
+
+/**
+ * v0.42 — extract_health doctor check.
+ *
+ * Reads the extract_rollup_7d table (migration v106) for the last 7 days
+ * and reports per-kind aggregates. Stable JSON envelope schema_version:1.
+ *
+ * 3-state status:
+ * - OK when rollup is empty (no extractions yet) OR every per-kind
+ * halt rate is below the warn threshold.
+ * - WARN when any per-kind halt rate exceeds 10% (operator-visible
+ * signal that an extractor is failing too often).
+ * - WARN when rollup_write_failures > 0 (audit JSONL is the source of
+ * truth but operator should know the DB cache is degraded).
+ *
+ * Per-kind columns (per plan A5 + D-EXTRACT-32 spec):
+ * cost_7d_usd, eval_pass_count, eval_fail_count, halt_count,
+ * round_completed_count, last_updated_at
+ *
+ * The check is empty-rollup-tolerant: a brain that has never extracted
+ * shows OK with `kinds: []` rather than warning. Doctor latency stays
+ * under 100ms regardless of brain size because the rollup table
+ * pre-aggregates (rolled-up at audit-emitter time per F-OUT-19).
+ *
+ * Empty rollup short-circuits BEFORE hitting the rollup_write_failures
+ * branch so a brand-new brain doesn't surface a "0 failures" warning.
+ */
+export async function computeExtractHealthCheck(
+ engine: BrainEngine,
+): Promise<Check> {
+ const name = 'extract_health';
+ try {
+ type RollupRow = {
+ kind: string;
+ cost_7d_usd: number;
+ eval_pass_count: number;
+ eval_fail_count: number;
+ halt_count: number;
+ round_completed_count: number;
+ rollup_write_failures: number;
+ last_updated_at: Date | string | null;
+ };
+
+ const rows = await engine.executeRaw<RollupRow>(
+ `SELECT
+ kind,
+ SUM(cost_usd) AS cost_7d_usd,
+ SUM(eval_pass_count) AS eval_pass_count,
+ SUM(eval_fail_count) AS eval_fail_count,
+ SUM(halt_count) AS halt_count,
+ SUM(round_completed_count) AS round_completed_count,
+ SUM(rollup_write_failures) AS rollup_write_failures,
+ MAX(updated_at) AS last_updated_at
+ FROM extract_rollup_7d
+ WHERE day >= CURRENT_DATE - 7
+ GROUP BY kind
+ ORDER BY kind`,
+ [],
+ );
+
+ if (rows.length === 0) {
+ return {
+ name,
+ status: 'ok',
+ message: 'no extractions in last 7 days',
+ details: {
+ schema_version: 1,
+ kinds: [],
+ },
+ };
+ }
+
+ type KindAggregate = {
+ kind: string;
+ cost_7d_usd: number;
+ eval_pass_count: number;
+ eval_fail_count: number;
+ halt_count: number;
+ round_completed_count: number;
+ halt_rate: number;
+ last_updated_at: string | null;
+ };
+
+ const kinds: KindAggregate[] = rows.map(r => {
+ const halts = Number(r.halt_count) || 0;
+ const completed = Number(r.round_completed_count) || 0;
+ const total = halts + completed;
+ return {
+ kind: r.kind,
+ cost_7d_usd: Number(r.cost_7d_usd) || 0,
+ eval_pass_count: Number(r.eval_pass_count) || 0,
+ eval_fail_count: Number(r.eval_fail_count) || 0,
+ halt_count: halts,
+ round_completed_count: completed,
+ halt_rate: total > 0 ? halts / total : 0,
+ last_updated_at: r.last_updated_at
+ ? new Date(r.last_updated_at).toISOString()
+ : null,
+ };
+ });
+
+ const totalRollupFailures = rows.reduce(
+ (acc, r) => acc + (Number(r.rollup_write_failures) || 0),
+ 0,
+ );
+
+ // High halt rates: per F-OUT-19 doctor surfaces extractor health
+ // distinctly from rollup write health.
+ const highHaltKinds = kinds.filter(k => k.halt_rate > 0.10);
+
+ if (highHaltKinds.length > 0) {
+ const top3 = [...highHaltKinds]
+ .sort((a, b) => b.halt_rate - a.halt_rate)
+ .slice(0, 3)
+ .map(k => `${k.kind}=${(k.halt_rate * 100).toFixed(1)}%`)
+ .join(', ');
+ return {
+ name,
+ status: 'warn',
+ message: `${highHaltKinds.length} kind(s) with halt rate > 10% (top: ${top3})`,
+ details: {
+ schema_version: 1,
+ kinds,
+ rollup_write_failures_7d: totalRollupFailures,
+ },
+ };
+ }
+
+ if (totalRollupFailures > 0) {
+ return {
+ name,
+ status: 'warn',
+ message: `${totalRollupFailures} rollup write failure(s) in last 7d (audit JSONL is source of truth; rebuild via gbrain extract status --rebuild-rollup)`,
+ details: {
+ schema_version: 1,
+ kinds,
+ rollup_write_failures_7d: totalRollupFailures,
+ },
+ };
+ }
+
+ return {
+ name,
+ status: 'ok',
+ message: `${kinds.length} kind(s) tracked, all halt rates below 10%`,
+ details: {
+ schema_version: 1,
+ kinds,
+ rollup_write_failures_7d: totalRollupFailures,
+ },
+ };
+ } catch (err) {
+ // Pre-v106 brains lack the extract_rollup_7d table. Don't warn — the
+ // bootstrap-coverage / migration framework brings the schema forward
+ // and the next run resolves naturally. Stay quiet.
+ const msg = (err as Error).message || String(err);
+ if (/extract_rollup_7d.*does not exist|no such table/i.test(msg)) {
+ return {
+ name,
+ status: 'ok',
+ message: 'extract_rollup_7d not yet present (pre-v0.42 brain or fresh init)',
+ };
+ }
+ return {
+ name,
+ status: 'warn',
+ message: `rollup query failed: ${msg}`,
+ };
+ }
+}
+
+export async function checkSyncFreshness(
+ engine: BrainEngine,
+ opts?: { nowMs?: number; localOnly?: boolean },
+): Promise<Check> {
+ try {
+ // v0.41.27.0: SELECT widens to carry last_commit + chunker_version so
+ // the git short-circuit gate (below) can compare against what
+ // `gbrain sync`'s up-to-date predicate at sync.ts:1057+1075 checks.
+ // Columns existed pre-v0.41 (writeSyncAnchor / writeChunkerVersion);
+ // no schema migration needed.
+ const sources = await engine.executeRaw<{
+ id: string;
+ name: string;
+ local_path: string | null;
+ last_sync_at: Date | null;
+ last_commit: string | null;
+ chunker_version: string | null;
+ newest_content_at: Date | null;
+ }>(
+ // v0.41.32.0: newest_content_at feeds the REMOTE (non-localOnly) lag so
+ // doctorReportRemote never shells out to git on a DB-supplied local_path.
+ `SELECT id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at FROM sources WHERE local_path IS NOT NULL`,
+ );
+
+ if (sources.length === 0) {
+ return {
+ name: 'sync_freshness',
+ status: 'ok',
+ message: 'No federated sources to sync',
+ details: { unchanged_count: 0, synced_recently_count: 0, stale_count: 0 },
+ };
+ }
+
+ const warnHours = _resolveSyncFreshnessHours('GBRAIN_SYNC_FRESHNESS_WARN_HOURS', 24);
+ const failHours = _resolveSyncFreshnessHours('GBRAIN_SYNC_FRESHNESS_FAIL_HOURS', 72);
+ const warnMs = warnHours * 60 * 60 * 1000;
+ const failMs = failHours * 60 * 60 * 1000;
+
+ // `opts.nowMs` is a test-only injection seam for the boundary tests.
+ // Without it, the two `Date.now()` calls (one in the test's `agoMs`
+ // helper, one here) drift apart by microseconds-to-milliseconds, which
+ // pushes "exactly 72h ago" above the strict `>` threshold and flips the
+ // status from warn to fail (CI-flaky, see PR #1138 ship). Production
+ // callers omit `nowMs` and get live wall-clock semantics.
+ const now = opts?.nowMs ?? Date.now();
+
+ // v0.41.27.0: D4 trust boundary. The git short-circuit runs ONLY when
+ // the caller explicitly opts in via `localOnly: true`. Default (false)
+ // preserves the v0.32.4 trust boundary for `doctorReportRemote` (the
+ // HTTP MCP path) — a remote-callable code path must NOT walk
+ // DB-supplied `local_path` values with subprocess calls. runDoctor
+ // (local CLI) passes true; doctorReportRemote keeps the default.
+ const localOnly = opts?.localOnly === true;
+
+ // v0.41.27.0: D7 narrowed predicate. The CHUNKER_VERSION caller-side
+ // check mirrors sync.ts:1057's chunker-version gate so doctor agrees
+ // with sync on "is there work to do?". `sources.chunker_version` is
+ // a TEXT column storing String(CHUNKER_VERSION).
+ const currentChunkerVersion = String(CHUNKER_VERSION);
+
+ const issues: string[] = [];
+ // v0.41.27.0: D6 three-bucket count math. Every source falls into
+ // EXACTLY ONE bucket per iteration. Invariant pinned by unit test:
+ // unchanged_count + synced_recently_count + stale_count === sources.length
+ // Stale subsumes warn + fail + never-synced + future-timestamp; we keep
+ // hasWarnings/hasFailures for the existing return-status logic.
+ let unchanged_count = 0;
+ let synced_recently_count = 0;
+ let stale_count = 0;
+ let hasWarnings = false;
+ let hasFailures = false;
+
+ // BUG 4 (v0.42.x): a source with a LIVE, non-expired per-source sync lock is
+ // actively syncing RIGHT NOW — it must not read as stale or never-synced.
+ // The live lock is the only honest "in progress" signal. Checkpoint banking
+ // is NOT usable: a blocked sync banks the good files then writes no anchor
+ // (test/sync-resumable-import.serial.test.ts), so banking can't tell
+ // in-progress from wedged. A blocked/failed sync's process has exited (no
+ // lock row) and a wedged holder stops refreshing (TTL lapses), so either
+ // correctly falls through to the stale path and is NEVER masked. Same
+ // dynamic import as the stale_locks check; any throw (stub engine in unit
+ // tests, pre-lock-table brain) is swallowed to false, so this can only ADD
+ // an in-progress verdict, never suppress a real stale one.
+ // Notes for sources caught actively syncing (surfaced in the result
+ // message so the operator sees "in progress", not just a silent healthy
+ // bucket). Empty when nothing is syncing — keeps the steady-state messages
+ // byte-for-byte unchanged.
+ const inProgress: string[] = [];
+ let liveSyncSnap: (sourceId: string) => Promise<{ holder_pid: number; holder_host: string; age_ms: number } | null> =
+ async () => null;
+ try {
+ const { inspectLock, syncLockId } = await import('../../../core/db-lock.ts');
+ liveSyncSnap = async (sourceId: string) => {
+ try {
+ const snap = await inspectLock(engine, syncLockId(sourceId));
+ return snap && !snap.ttl_expired
+ ? { holder_pid: snap.holder_pid, holder_host: snap.holder_host, age_ms: snap.age_ms }
+ : null;
+ } catch {
+ return null;
+ }
+ };
+ } catch {
+ /* db-lock unavailable — skip in-progress detection, staleness stands. */
+ }
+
+ // One ceiling for the whole report: hoisted out of the loop so every
+ // source is judged against the same number (and the env read + warn-once
+ // machinery runs once, not once per source).
+ const stalenessCeilingSeconds = resolveStalenessCeilingSeconds();
+ for (const source of sources) {
+ // Embed source.id in user-visible messages so `gbrain sync --source <id>`
+ // matches what the user copy-pastes. Show display name in parens when set.
+ const display = source.name && source.name !== source.id
+ ? `'${source.id}' (${source.name})`
+ : `'${source.id}'`;
+
+ // BUG 4: actively syncing (live lock) → healthy, count as synced_recently
+ // and skip the staleness checks. Keeps the 3-bucket invariant intact.
+ //
+ // ...but ONLY up to the staleness ceiling. `withRefreshingLock` bumps the
+ // heartbeat on its own timer regardless of whether the import is making
+ // forward progress (`liveSyncStatus`'s docstring is explicit: callers may
+ // report "running", NOT "healthy"). So a holder blocked inside a query
+ // keeps refreshing forever, and an uncapped in-progress verdict would
+ // mask that source from every staleness check indefinitely — the same
+ // invisible-failure class this whole pass exists to close, just reached
+ // through the lock table instead of the freshness column.
+ const liveSnap = await liveSyncSnap(source.id);
+ if (liveSnap) {
+ const ceilingMs = stalenessCeilingSeconds * 1000;
+ if (liveSnap.age_ms <= ceilingMs) {
+ inProgress.push(`${display} sync in progress (pid ${liveSnap.holder_pid} on ${liveSnap.holder_host})`);
+ synced_recently_count++;
+ continue;
+ }
+ // Sub-hour ceilings are legal (fractional env override), and an alarm
+ // that names a zero duration ("held the lock for 0h") reads as broken.
+ const heldFor = liveSnap.age_ms >= 3600_000
+ ? `${Math.floor(liveSnap.age_ms / 3600_000)}h`
+ : `${Math.max(1, Math.floor(liveSnap.age_ms / 60_000))}m`;
+ issues.push(
+ `Source ${display} has held the sync lock for ${heldFor} ` +
+ `(pid ${liveSnap.holder_pid} on ${liveSnap.holder_host}) — heartbeating but not finishing. ` +
+ `Run \`gbrain sync --break-lock --source ${source.id}\` after confirming the holder is wedged.`,
+ );
+ hasFailures = true;
+ stale_count++;
+ continue;
+ }
+
+ if (!source.last_sync_at) {
+ issues.push(`Source ${display} has never been synced`);
+ hasFailures = true;
+ stale_count++;
+ continue;
+ }
+
+ const lastSync = new Date(source.last_sync_at).getTime();
+ const ageMs = now - lastSync;
+
+ if (ageMs < 0) {
+ issues.push(
+ `Source ${display} has future last_sync_at — clock skew or corrupted timestamp`,
+ );
+ hasWarnings = true;
+ stale_count++;
+ continue;
+ }
+
+ // v0.41.27.0: git short-circuit (D4 + D7 combined). Only fires when:
+ // 1. caller opted in via localOnly=true (trust boundary)
+ // 2. HEAD === last_commit (no new commits to sync)
+ // 3. working tree has no TRACKED changes — untracked files ignored
+ // (v0.41.32.0: `'ignore-untracked'`. Sync's incremental path keys off
+ // the commit diff and never imports untracked files, so a quiet repo
+ // with stray untracked dirs is genuinely caught up. The pre-v0.41.30
+ // `true` mode counted those as dirty and produced the false-SEVERE
+ // alarm this wave fixes.)
+ // 4. chunker_version matches CURRENT (no post-upgrade re-chunk pending —
+ // still ANDed, so a re-chunk need is never masked)
+ // All four must hold; otherwise fall through to the time-based check.
+ // The chunker version match is computed here (not in the helper)
+ // because it depends on engine state, not git state.
+ //
+ // Clone-unavailable fallback: on stateless deploys (Docker on EB /
+ // K8s / Fly — the platforms the cloud recipes produce), a container
+ // restart wipes `local_path` and each clone is only re-materialized
+ // when that source's next sync job runs. Until then the HEAD probe
+ // cannot run at all ('unavailable'), which previously fell through to
+ // raw wall-clock age — and since a no-op sync doesn't advance
+ // `last_sync_at`, every QUIET source read as stale/FAIL after a
+ // restart (score-sinking alert storm; observed live: 16-source brain,
+ // 12 clones gone after a config-update restart, doctor 70→30).
+ // 'unavailable' + chunker match now reuses the v0.41.32.0 REMOTE lag
+ // signal (newest_content_at) below — DB-only, no subprocess, and it
+ // still reports staleness whenever content really is newer than the
+ // last sync. 'changed' (readable clone with real work) keeps
+ // wall-clock exactly as before, and a chunker mismatch is never
+ // masked (D7): it disables the fallback too.
+ let cloneUnavailable = false;
+ if (localOnly) {
+ const gitState = probeSourceGitState(
+ source.local_path,
+ source.last_commit,
+ { requireCleanWorkingTree: 'ignore-untracked' },
+ );
+ const chunkerMatch = source.chunker_version === currentChunkerVersion;
+ if (gitState === 'unchanged' && chunkerMatch) {
+ unchanged_count++;
+ continue;
+ }
+ cloneUnavailable = gitState === 'unavailable' && chunkerMatch;
+ }
+
+ // v0.41.32.0: REMOTE path (doctorReportRemote, !localOnly) computes lag
+ // from the stored newest_content_at column — NO git subprocess on a
+ // DB-supplied local_path (preserves the v0.41.27.0 trust boundary). A
+ // quiet repo whose newest commit predates its last sync reports 0; NULL
+ // column → wall-clock fallback. LOCAL fall-through keeps wall-clock when
+ // the clone is READABLE: the short-circuit failed on real evidence
+ // (HEAD moved / dirty tree), so the source genuinely has work and
+ // "hours since last sync" is the right staleness measure. A local clone
+ // that is UNAVAILABLE (not yet re-materialized, see above) carries no
+ // evidence either way, so it borrows this same DB-only lag. The
+ // `ageMs < 0` skew check above still runs on raw wall-clock for both
+ // paths (A1).
+ let thresholdAgeMs = ageMs;
+ if (!localOnly || cloneUnavailable) {
+ const contentMs = source.newest_content_at
+ ? new Date(source.newest_content_at).getTime()
+ : null;
+ const lagSec = lagFromContentMs(
+ contentMs !== null && Number.isFinite(contentMs) ? contentMs : null,
+ lastSync,
+ now,
+ stalenessCeilingSeconds,
+ );
+ thresholdAgeMs = lagSec === null ? ageMs : lagSec * 1000;
+ }
+
+ const ageHours = Math.floor(thresholdAgeMs / (1000 * 60 * 60));
+ const ageDays = Math.floor(ageHours / 24);
+
+ if (thresholdAgeMs > failMs) {
+ issues.push(`Source ${display} last synced ${ageDays}d ago — brain search is stale!`);
+ hasFailures = true;
+ stale_count++;
+ } else if (thresholdAgeMs > warnMs) {
+ issues.push(`Source ${display} last synced ${ageHours}h ago`);
+ hasWarnings = true;
+ stale_count++;
+ } else {
+ synced_recently_count++;
+ }
+ }
+
+ // D6 invariant: every source incremented exactly one bucket.
+ const details = { unchanged_count, synced_recently_count, stale_count };
+ // BUG 4: append in-progress context when any source is actively syncing.
+ // Empty otherwise, so steady-state messages are byte-for-byte unchanged.
+ const inProgressNote = inProgress.length ? `. ${inProgress.join('; ')}` : '';
+
+ if (hasFailures) {
+ return {
+ name: 'sync_freshness',
+ status: 'fail',
+ message: `${issues.join('; ')}. Run \`gbrain sync --source <id>\` for each stale source${inProgressNote}`,
+ details,
+ };
+ }
+ if (hasWarnings) {
+ return {
+ name: 'sync_freshness',
+ status: 'warn',
+ message: `${issues.join('; ')}. Run \`gbrain sync --source <id>\` to refresh${inProgressNote}`,
+ details,
+ };
+ }
+ // v0.41.27.0: D2 ok-message reshape. Three branches surface what the
+ // git short-circuit actually did so operators understand "unchanged
+ // since last sync" vs "synced recently".
+ if (unchanged_count === sources.length) {
+ return {
+ name: 'sync_freshness',
+ status: 'ok',
+ message: `All ${sources.length} federated source(s) up to date (no new commits since last sync)${inProgressNote}`,
+ details,
+ };
+ }
+ if (unchanged_count > 0) {
+ return {
+ name: 'sync_freshness',
+ status: 'ok',
+ message: `${sources.length} federated source(s): ${synced_recently_count} synced recently, ${unchanged_count} unchanged since last sync${inProgressNote}`,
+ details,
+ };
+ }
+ return {
+ name: 'sync_freshness',
+ status: 'ok',
+ message: `All ${sources.length} federated source(s) synced recently${inProgressNote}`,
+ details,
+ };
+ } catch (e) {
+ return {
+ name: 'sync_freshness',
+ status: 'warn',
+ message: `Could not check sync freshness: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
new file mode 100644
index 0000000000..55dbf1a458
--- /dev/null
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -0,0 +1,620 @@
+/**
+ * Graph / brainstorm / embedding-width check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+
+/**
+ * v0.40.4 graph_signals_coverage doctor check.
+ *
+ * Surfaces whether the brain's link density is high enough for the
+ * v0.40.4 graph-signals stage to meaningfully fire. Logic:
+ *
+ * 1. Resolve the active graph_signals setting (config override OR
+ * mode-bundle default). When OFF → silent ok (no metric noise on
+ * installs that don't use the feature).
+ *
+ * 2. When ON, compute the global density: % of pages with >=1
+ * inbound link. This is a STRUCTURAL lower bound — top-K
+ * subgraphs need at least some edges to fire any signal.
+ * Codex outside-voice #14 noted this is an imperfect proxy
+ * (T-todo-5 will replace it with actual fire-rate measurement
+ * from search-stats after 30 days of data).
+ *
+ * 3. >=30% → ok with the percentage.
+ * <10% → warn (mismatch: signal enabled but link graph is too
+ * sparse to fire often; fix: `gbrain extract all` to
+ * populate the link graph from frontmatter + markdown).
+ * 10-29% → ok with note (signal will fire occasionally).
+ *
+ * Errors during the SQL count → warn with the underlying message.
+ * Best-effort: this check never breaks doctor.
+ */
+export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Check> {
+ try {
+ // Resolve the active graph_signals setting. Read the config key
+ // explicitly; when unset, fall through to the mode bundle default.
+ const cfgVal = await engine.getConfig('search.graph_signals');
+ let enabled: boolean;
+ if (cfgVal !== null && cfgVal !== undefined) {
+ // v0.40.4 codex F1 — case-insensitive + trim, parity with
+ // loadOverridesFromConfig in src/core/search/mode.ts. Without
+ // this, `gbrain config set search.graph_signals TRUE` enables
+ // the feature in production but doctor reports "disabled".
+ const v = cfgVal.trim().toLowerCase();
+ enabled = v === 'true' || v === '1';
+ } else {
+ // Mode bundle default. Read search.mode (case-insensitive + trim
+ // parity with isSearchMode + DEFAULT_SEARCH_MODE fallback).
+ const modeRaw = await engine.getConfig('search.mode');
+ const modeVal = typeof modeRaw === 'string' ? modeRaw.trim().toLowerCase() : '';
+ const mode = modeVal === 'conservative' || modeVal === 'tokenmax' ? modeVal : 'balanced';
+ // Hardcoded knowledge of the mode bundle defaults — keeps the
+ // doctor check from pulling in the full search/mode.ts surface.
+ enabled = mode !== 'conservative';
+ }
+
+ if (!enabled) {
+ return {
+ name: 'graph_signals_coverage',
+ status: 'ok',
+ message: 'graph_signals disabled — coverage not checked',
+ };
+ }
+
+ // Compute global inbound-link density. Counts DISTINCT pages with
+ // at least one inbound edge / total pages.
+ const totalRows = await engine.executeRaw(`SELECT COUNT(*)::int AS n FROM pages WHERE deleted_at IS NULL`);
+ const totalPages = Number((totalRows as any)[0]?.n ?? 0);
+
+ if (totalPages === 0) {
+ return {
+ name: 'graph_signals_coverage',
+ status: 'ok',
+ message: 'Empty brain — no pages to compute coverage against',
+ };
+ }
+
+ const linkedRows = await engine.executeRaw(
+ `SELECT COUNT(DISTINCT l.to_page_id)::int AS n
+ FROM links l
+ JOIN pages p ON p.id = l.to_page_id
+ WHERE p.deleted_at IS NULL`
+ );
+ const linkedPages = Number((linkedRows as any)[0]?.n ?? 0);
+ const pct = (linkedPages / totalPages) * 100;
+ const pctStr = pct.toFixed(1);
+
+ if (pct < 10) {
+ return {
+ name: 'graph_signals_coverage',
+ status: 'warn',
+ message: `graph_signals enabled but only ${pctStr}% of pages have inbound links (<10%). Signal will rarely fire. Fix: \`gbrain extract all\` to populate the link graph from frontmatter + markdown.`,
+ };
+ }
+
+ return {
+ name: 'graph_signals_coverage',
+ status: 'ok',
+ message: pct >= 30
+ ? `${pctStr}% of pages have inbound links (>=30% — graph signals fire on most queries)`
+ : `${pctStr}% of pages have inbound links (10-29% — graph signals fire occasionally)`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'graph_signals_coverage',
+ status: 'warn',
+ message: `Could not check graph_signals_coverage: ${msg}`,
+ };
+ }
+}
+
+/**
+ * v0.37.0 brainstorm_health doctor check.
+ *
+ * Surfaces three readiness signals for `gbrain brainstorm` / `gbrain lsd`:
+ *
+ * 1. Migration v79 applied — the `pages.last_retrieved_at` column exists.
+ * If missing, LSD's stale-page signal degrades silently (corpus-sampling
+ * fallback only). Fix: `gbrain apply-migrations --yes`.
+ *
+ * 2. search.track_retrieval — when explicitly off, LSD never accumulates
+ * stale signal (every page stays at NULL last_retrieved_at). Default-on
+ * is fine; explicit-off is a warning so the user notices the setting.
+ * Fix: `gbrain config set search.track_retrieval true`.
+ *
+ * 3. Calibration cold-start — the latest calibration profile has empty
+ * `active_bias_tags`. brainstorm + LSD judge fall back to no-anti-bias
+ * mode with a stderr warning at run time; this surfaces it earlier.
+ * Fix: `gbrain calibration --regenerate` once enough takes are resolved.
+ *
+ * Returns the FIRST non-ok signal as the status — column-missing dominates,
+ * then disabled-tracking, then cold-start. All three are non-blocking warnings;
+ * brainstorm + LSD still work, just with degraded signal.
+ */
+export async function checkBrainstormHealth(engine: BrainEngine): Promise<Check> {
+ // (1) Column probe — fast, single-query.
+ try {
+ const probeRows = await engine.executeRaw<{ exists: boolean }>(
+ `SELECT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'pages' AND column_name = 'last_retrieved_at'
+ ) AS exists`,
+ []
+ );
+ const columnPresent = probeRows[0]?.exists === true;
+ if (!columnPresent) {
+ return {
+ name: 'brainstorm_health',
+ status: 'warn',
+ message: `pages.last_retrieved_at column missing. LSD stale-bias degraded to corpus-sampling. Fix: \`gbrain apply-migrations --yes\``,
+ };
+ }
+ } catch (e) {
+ // Information schema may not be queryable on every engine variant.
+ // Don't fail the doctor over this — degrade to skip.
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'brainstorm_health',
+ status: 'warn',
+ message: `Could not probe pages.last_retrieved_at (${msg}); brainstorm/lsd may run with degraded signal.`,
+ };
+ }
+
+ // (2) search.track_retrieval — explicit-off surfaces as a warning.
+ try {
+ const trackCfg = await engine.getConfig('search.track_retrieval');
+ if (trackCfg === 'false' || trackCfg === '0' || trackCfg === 'off' || trackCfg === 'no') {
+ return {
+ name: 'brainstorm_health',
+ status: 'warn',
+ message: `search.track_retrieval is explicitly off — LSD's stale-page signal never accumulates. Fix: \`gbrain config set search.track_retrieval true\` (or accept and use brainstorm only).`,
+ };
+ }
+ } catch {
+ // Config read miss is benign; default-on applies.
+ }
+
+ // (3) Calibration cold-start — empty active_bias_tags.
+ try {
+ const calibRows = await engine.executeRaw<{ active_bias_tags: string[] | null }>(
+ `SELECT active_bias_tags
+ FROM calibration_profiles
+ ORDER BY generated_at DESC
+ LIMIT 1`,
+ []
+ );
+ if (calibRows.length === 0) {
+ return {
+ name: 'brainstorm_health',
+ status: 'ok',
+ message: `Migration v79 applied; tracking enabled. Calibration profile not yet generated — brainstorm/lsd will run unbiased until enough takes are resolved.`,
+ };
+ }
+ const tags = calibRows[0].active_bias_tags;
+ if (!Array.isArray(tags) || tags.length === 0) {
+ return {
+ name: 'brainstorm_health',
+ status: 'ok',
+ message: `Migration v79 applied; tracking enabled. Calibration cold-start (no active_bias_tags) — judge runs unbiased. Fix when ready: \`gbrain calibration --regenerate\`.`,
+ };
+ }
+ return {
+ name: 'brainstorm_health',
+ status: 'ok',
+ message: `Migration v79 applied; tracking enabled; calibration profile with ${tags.length} bias tag(s) loaded.`,
+ };
+ } catch {
+ // Pre-v0.36.1 brain (no calibration_profiles table). Brainstorm/lsd still
+ // work without anti-bias context — orchestrator stderr-warns at run time.
+ return {
+ name: 'brainstorm_health',
+ status: 'ok',
+ message: `Migration v79 applied; tracking enabled. calibration_profiles table missing (pre-v0.36.1 brain) — judge runs unbiased.`,
+ };
+ }
+}
+
+/**
+ * v0.36.0.0 (A5): ze_embedding_health doctor check.
+ *
+ * When the configured embedding_model starts with `zeroentropyai:`, verify
+ * the API key is set. Doesn't make a network call by default — the existing
+ * `gbrain models doctor` probe covers that, and we don't want every
+ * `gbrain doctor` run to spend tokens. Surfaces a paste-ready fix when the
+ * key is missing.
+ */
+export async function checkZeEmbeddingHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ // v0.37 fix wave (Lane E.3 + CDX2-10): read from gateway, not DB.
+ // The file plane is canonical post-v0.37; the DB config table is
+ // schema-applied metadata. Reading DB here would skip the warning
+ // when the user has a fresh install with no DB config row yet.
+ const { getEmbeddingModel } = await import('../../../core/ai/gateway.ts');
+ const { loadConfigFileOnly } = await import('../../../core/config.ts');
+ let model = '';
+ try { model = getEmbeddingModel(); } catch { /* gateway unconfigured */ }
+ if (!model.startsWith('zeroentropyai:')) {
+ return {
+ name: 'ze_embedding_health',
+ status: 'ok',
+ message: `Configured embedding model "${model || 'default'}" is not ZeroEntropy — skip.`,
+ };
+ }
+ const envKey = process.env.ZEROENTROPY_API_KEY;
+ // File plane: zeroentropy_api_key on GBrainConfig (added by C.3).
+ const fileKey = loadConfigFileOnly()?.zeroentropy_api_key;
+ if (!envKey && !fileKey) {
+ return {
+ name: 'ze_embedding_health',
+ status: 'warn',
+ message:
+ `embedding_model="${model}" but ZEROENTROPY_API_KEY is not set. ` +
+ `Fix: get a key at https://dashboard.zeroentropy.dev and either ` +
+ `\`export ZEROENTROPY_API_KEY=...\` or edit ~/.gbrain/config.json ` +
+ `to add "zeroentropy_api_key": "...". (gbrain config set writes the DB plane, which the embed pipeline ignores.)`,
+ };
+ }
+ return {
+ name: 'ze_embedding_health',
+ status: 'ok',
+ message: `embedding_model="${model}" with key configured`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'ze_embedding_health',
+ status: 'warn',
+ message: `Could not check ZE embedding health: ${msg}`,
+ };
+ }
+}
+
+/**
+ * provider_sunset doctor check (#3390 follow-up).
+ *
+ * Detects a brain whose EFFECTIVE embedding model (gateway-resolved, which is
+ * how default-config brains land on the shipped default) is on a provider
+ * with an announced hosted-API shutdown, and prints a paste-ready migration
+ * command with the brain's ACTUAL `content_chunks.embedding` column width
+ * filled in — not the config value, which can drift. Keeping the current
+ * width avoids a needless dimension transition + index rebuild when the
+ * target supports it.
+ *
+ * Unlike the one-shot upgrade banner (`ze_sunset_notice_shown`), this fires
+ * on every `gbrain doctor` run until the brain is off the provider —
+ * warn before the shutdown date; fail after it ONLY when the brain is
+ * actually exposed (embedded vectors exist in the affected column, so
+ * retrieval is genuinely down). A zero-vector brain whose config merely
+ * RESOLVES to the dead default stays warn — otherwise every stock fresh
+ * install (and every doctor-as-CI-gate) starts exiting 1 on the date with
+ * no code change. Suppress entirely (accepted-risk installs) via
+ * `gbrain config set doctor.suppress_provider_sunset true`.
+ * No network call; one catalog query for the column width.
+ *
+ * `now` is injectable so tests can pin BOTH sides of the date without
+ * waiting for the calendar (the date itself is a compile-time constant).
+ */
+export async function checkProviderSunset(engine: BrainEngine, now: number = Date.now()): Promise<Check> {
+ const name = 'provider_sunset';
+ try {
+ const suppressed = await engine.getConfig('doctor.suppress_provider_sunset').catch(() => null);
+ if (suppressed === 'true' || suppressed === '1') {
+ return {
+ name,
+ status: 'ok',
+ message: 'Check suppressed via doctor.suppress_provider_sunset (unset it to re-enable).',
+ };
+ }
+ const { DEFAULT_EMBEDDING_MODEL, ZEROENTROPY_SUNSET_DATE } = await import('../../../core/ai/defaults.ts');
+ // Effective model: gateway when configured (file/env plane, the runtime
+ // truth); the shipped default otherwise — an unset-config brain resolves
+ // to the default at runtime, so it is just as affected.
+ let model = DEFAULT_EMBEDDING_MODEL;
+ try {
+ const { getEmbeddingModel } = await import('../../../core/ai/gateway.ts');
+ model = getEmbeddingModel();
+ } catch {
+ // Gateway unconfigured — runtime resolves the shipped default.
+ }
+ // Effective reranker: resolve through the SAME plane search actually
+ // reranks with — resolveSearchMode (mode bundle + search.reranker.*
+ // config overrides; hybrid.ts passes `resolvedMode.reranker_model`).
+ // The gateway plane is unset by default while balanced/tokenmax rerank
+ // with the bundle's zeroentropyai model — reading the gateway here
+ // would false-ok the exact brains this check exists to protect.
+ let reranker: string | undefined;
+ try {
+ const { loadSearchModeConfig, resolveSearchMode } = await import('../../../core/search/mode.ts');
+ const knobs = resolveSearchMode(await loadSearchModeConfig(engine));
+ if (knobs.reranker_enabled) reranker = knobs.reranker_model;
+ } catch {
+ // Mode resolution failed — make no reranker-exposure claim.
+ }
+ const onSunsetEmbedding = model.startsWith('zeroentropyai:');
+ const onSunsetReranker = !!reranker?.startsWith('zeroentropyai:');
+ // Custom embedding columns can route queries through a ZE-backed model
+ // even when the primary embedding + reranker are clear — without this arm
+ // the check reports ok while those columns die on the date.
+ let zeColumns: string[] = [];
+ try {
+ const { detectZeCustomColumns } = await import('../../../core/ze-exposure.ts');
+ zeColumns = (await detectZeCustomColumns(engine)).columns;
+ } catch {
+ // Probe failed — make no custom-column claim.
+ }
+ const onSunsetColumns = zeColumns.length > 0;
+ if (!onSunsetEmbedding && !onSunsetReranker && !onSunsetColumns) {
+ return {
+ name,
+ status: 'ok',
+ message: `No configured provider has an announced shutdown (embedding: ${model}).`,
+ };
+ }
+ const past = now >= Date.parse(`${ZEROENTROPY_SUNSET_DATE}T00:00:00Z`);
+ const parts: string[] = [];
+ let hasVectors = false;
+ if (onSunsetEmbedding) {
+ let dims: number | null = null;
+ try {
+ const { readContentChunksEmbeddingDim } = await import('../../../core/embedding-dim-check.ts');
+ dims = (await readContentChunksEmbeddingDim(engine)).dims;
+ } catch {
+ // Column probe failed (fresh/odd brain) — omit --dim from the hint.
+ }
+ try {
+ const rows = await engine.executeRaw(
+ `SELECT 1 AS one FROM content_chunks WHERE embedding IS NOT NULL LIMIT 1`,
+ );
+ hasVectors = rows.length > 0;
+ } catch {
+ // Probe failed (fresh/odd brain) — no exposure claim, warn-only.
+ }
+ parts.push(
+ past
+ ? hasVectors
+ ? `embedding_model="${model}": the hosted API shut down on ${ZEROENTROPY_SUNSET_DATE} — semantic retrieval is offline (queries can no longer be embedded against your existing vectors).`
+ : `embedding_model="${model}": the hosted API shut down on ${ZEROENTROPY_SUNSET_DATE}. No embedded vectors exist yet, so retrieval is not impacted — but embedding will fail until the config points elsewhere.`
+ : `embedding_model="${model}": the hosted API shuts down on ${ZEROENTROPY_SUNSET_DATE}. On that date semantic retrieval stops entirely — existing vectors become unqueryable (query embedding uses the same endpoint), not just new content.`,
+ );
+ // v0.46.3: the paste-ready fix is TARGET-AWARE on dimensions. Voyage's
+ // valid widths are {256, 512, 1024, 2048} — blindly preserving this
+ // brain's actual width (usually 1280) would emit a command Voyage
+ // rejects. OpenAI text-3 supports flexible widths up to its native
+ // size, so the keep-width form is offered only when valid there.
+ const openaiDimFlag = dims && dims <= 1536 ? ` --dim ${dims}` : ' --dim 1536';
+ const openaiKeepsWidth = !!(dims && dims <= 1536);
+ parts.push(
+ `Two fixes, either works: ` +
+ `[1] self-host the same model — zembed-1 weights are Apache-2.0; keep the zeroentropyai:zembed-1 id and point provider_base_urls.zeroentropyai at a ZE-wire-compatible endpoint (NOT a generic OpenAI-compatible server — the id speaks ZE's /models/embed dialect). Keeps every existing vector, no re-embed (docs/guides/embedding-migration.md). ` +
+ `[2] migrate (resumable; preview cost first): ` +
+ `gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run` +
+ (dims && dims !== 1024 ? ` (${dims} is not a valid Voyage width — the migration rebuilds the index at 1024)` : '') +
+ `; OpenAI alternative${openaiKeepsWidth ? ` keeps this brain's ${dims}d width` : ''}: ` +
+ `gbrain migrate embeddings --to openai:text-embedding-3-small${openaiDimFlag} --dry-run.`,
+ );
+ }
+ if (onSunsetReranker) {
+ parts.push(
+ `The reranker (${reranker}) is on the same provider; after the shutdown search falls back to unreranked ordering. ` +
+ `Fix: gbrain config set search.reranker.model voyage:rerank-2.5 (needs VOYAGE_API_KEY), or disable: gbrain config set search.reranker.enabled false.`,
+ );
+ }
+ if (onSunsetColumns) {
+ parts.push(
+ `Custom embedding column(s) backed by the shutting-down provider: ${zeColumns.join(', ')}. ` +
+ `No automated off-ramp exists for custom columns yet (migrate embeddings covers the primary column only) — ` +
+ `re-declare them on a new provider and re-embed (skills/migrations/v0.46.3.0.md).`,
+ );
+ }
+ if (onSunsetEmbedding || onSunsetReranker || onSunsetColumns) {
+ parts.push('Accepted the risk? Silence this check: gbrain config set doctor.suppress_provider_sunset true');
+ }
+ // fail = retrieval is ACTUALLY down (past the date AND embedded vectors
+ // exist on the dead provider). Reranker-only exposure stays warn — search
+ // fails open to unreranked ordering (degraded, not down).
+ const failNow = past && onSunsetEmbedding && hasVectors;
+ return { name, status: failNow ? 'fail' : 'warn', message: parts.join(' ') };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return { name, status: 'warn', message: `Could not check provider sunset status: ${msg}` };
+ }
+}
+
+/**
+ * v0.36.0.0 (A5): embedding_width_consistency doctor check.
+ *
+ * Cross-checks that `config.embedding_dimensions` matches the actual
+ * `vector(N)` width on `content_chunks.embedding`. Drift here means the
+ * ze-switch was interrupted mid-flight (schema changed but config write
+ * crashed, or vice versa). Surfaces a paste-ready `gbrain ze-switch
+ * --resume` hint.
+ */
+export async function checkEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
+ try {
+ // v0.37 fix wave (Lane E.1 + CDX-8): read from gateway, not DB. The
+ // file plane is canonical post-v0.37; the DB config table is
+ // schema-applied metadata. Reading DB here silently skipped the
+ // check on fresh installs whose DB config row hadn't been written
+ // yet.
+ const { getEmbeddingDimensions, getEmbeddingModel } = await import('../../../core/ai/gateway.ts');
+ let configDim: number;
+ let resolvedModel: string;
+ try {
+ configDim = getEmbeddingDimensions();
+ resolvedModel = getEmbeddingModel();
+ } catch {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'ok',
+ message: 'gateway not configured — skipping width check.',
+ };
+ }
+ if (!Number.isFinite(configDim) || configDim <= 0) {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: `gateway returned non-positive embedding dimension "${configDim}".`,
+ };
+ }
+
+ // Read the actual column width via the existing helper (shared with
+ // init.ts and embed.ts dim-mismatch pre-flight). One source of truth.
+ const { readContentChunksEmbeddingDim, embeddingMismatchMessage } = await import('../../../core/embedding-dim-check.ts');
+ const existing = await readContentChunksEmbeddingDim(engine);
+ if (!existing.exists) {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: 'content_chunks.embedding column not found. Fix: run `gbrain init --migrate-only` or check schema.',
+ };
+ }
+ if (existing.dims === null) {
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: 'content_chunks.embedding is not a vector type. Schema may be corrupt.',
+ };
+ }
+ if (existing.dims !== configDim) {
+ // E.2: use the engine-kind-branched recipe instead of pointing at
+ // the no-op `gbrain config set` path. The recipe is paste-ready
+ // for the brain's actual engine.
+ const databasePath = (engine as { _savedConfig?: { database_path?: string } })._savedConfig?.database_path;
+ const recipe = embeddingMismatchMessage({
+ currentDims: existing.dims,
+ requestedDims: configDim,
+ requestedModel: resolvedModel,
+ source: 'doctor',
+ engineKind: engine.kind,
+ databasePath,
+ });
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message:
+ `Schema width mismatch: content_chunks.embedding is vector(${existing.dims}) but ` +
+ `gateway resolved embedding_dimensions = ${configDim}.\n\n${recipe}`,
+ };
+ }
+ return {
+ name: 'embedding_width_consistency',
+ status: 'ok',
+ message: `Schema width (${existing.dims}d) matches gateway embedding_dimensions`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'embedding_width_consistency',
+ status: 'warn',
+ message: `Could not check embedding width: ${msg}`,
+ };
+ }
+}
+
+/**
+ * v0.41.15.0 (T6, codex #19/#20) — facts.embedding column drift check.
+ *
+ * Parallel surface to `checkEmbeddingWidthConsistency` but for the
+ * facts table. Migration v40 creates `facts.embedding` from
+ * `config.embedding_dimensions` AT MIGRATION TIME — if the user later
+ * swaps embedding providers (e.g. OpenAI 1536 → zembed-1 1280) without
+ * re-running migrations, the column width drifts. The first insert
+ * dies with the opaque pgvector "expected vector(N), got vector(M)"
+ * error.
+ *
+ * Covers BOTH vector(N) AND halfvec(N) shapes (codex #19 — v40 falls
+ * back to vector on pgvector < 0.7). Surfaces the paste-ready DROP
+ * INDEX → ALTER USING → CREATE INDEX recipe from
+ * `buildFactsAlterRecipe` instead of the unsafe REINDEX-only path
+ * codex #18 caught in the original plan.
+ */
+export async function checkFactsEmbeddingWidthConsistency(engine: BrainEngine): Promise<Check> {
+ // PGLite ships a single pgvector version; column + config wire
+ // together at initSchema time. No possible drift.
+ if (engine.kind !== 'postgres') {
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'ok',
+ message: 'Skipped on PGLite (single bundled pgvector version).',
+ };
+ }
+
+ try {
+ const {
+ readFactsEmbeddingDim,
+ buildFactsAlterRecipe,
+ } = await import('../../../core/embedding-dim-check.ts');
+
+ const col = await readFactsEmbeddingDim(engine);
+ if (!col.exists) {
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'ok',
+ message: 'facts.embedding column not present (pre-v40 brain or migration pending).',
+ };
+ }
+ if (col.dims === null || col.columnType === null) {
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'warn',
+ message: 'facts.embedding column type is unrecognized (not vector or halfvec). Schema may be corrupt.',
+ };
+ }
+
+ let configDim: number;
+ let resolvedModel = 'unknown';
+ try {
+ const { getEmbeddingDimensions, getEmbeddingModel } = await import('../../../core/ai/gateway.ts');
+ configDim = getEmbeddingDimensions();
+ resolvedModel = getEmbeddingModel();
+ } catch {
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'ok',
+ message: 'gateway not configured — facts.embedding width check skipped.',
+ };
+ }
+ if (!Number.isFinite(configDim) || configDim <= 0) {
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'warn',
+ message: `gateway returned non-positive embedding dimension "${configDim}".`,
+ };
+ }
+
+ if (col.dims === configDim) {
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'ok',
+ message:
+ `facts.embedding is ${col.columnType}(${col.dims}) — matches gateway embedding_dimensions ` +
+ `(${resolvedModel}).`,
+ };
+ }
+
+ // Drift detected. Surface the paste-ready ALTER recipe.
+ const recipe = buildFactsAlterRecipe(col.dims, configDim, col.columnType);
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'warn',
+ message:
+ `facts.embedding is ${col.columnType}(${col.dims}) but gateway resolved ` +
+ `embedding_dimensions = ${configDim} (${resolvedModel}). ` +
+ `New fact inserts will fail with an opaque pgvector error.\n\n` +
+ recipe,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'facts_embedding_width_consistency',
+ status: 'warn',
+ message: `Could not check facts.embedding width: ${msg}`,
+ };
+ }
+}
+
diff --git a/src/commands/doctor/checks/pglite-worker.ts b/src/commands/doctor/checks/pglite-worker.ts
new file mode 100644
index 0000000000..ec188e2061
--- /dev/null
+++ b/src/commands/doctor/checks/pglite-worker.ts
@@ -0,0 +1,270 @@
+/**
+ * PGLite / worker / pool check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import * as db from '../../../core/db.ts';
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+
+// ≥2 failed repair attempts inside 7 days = the corruption keeps regenerating.
+const REPAIR_RECURRENCE_WINDOW_MS = 7 * 24 * 3600 * 1000;
+const REPAIR_RECURRENCE_THRESHOLD = 2;
+
+/**
+ * WAL-repair wave (#223/#1670/#2575): when the DB failed to connect on a
+ * PGLite brain, diagnose the data dir from the FILESYSTEM (the connect error
+ * itself was swallowed by doctor's fs-only fallback — this check re-derives
+ * the state from disk). Pure: interprets an `inspectPgliteDataDir` diagnosis
+ * into a Check; exported so `test/doctor-pglite-datadir.test.ts` drives it
+ * directly (same convention as computeWorkerOomLoopCheck). Returns a Check
+ * always — the call site only runs it when connect already failed, so even a
+ * healthy-looking dir warrants a pointer at the repair tooling.
+ *
+ * Recurrence escalation (eng-review 2A): repeated failed repair attempts on
+ * record mean the corruption keeps regenerating (unclean-shutdown genesis) —
+ * escalate to the engine-switch ladder instead of letting the brain silently
+ * lose a WAL tail per cycle. Backup-dir inventory rides along (same
+ * disk-visibility class as orphan_clones).
+ */
+export function computePgliteDataDirCheck(
+ dataDir: string,
+ diagnosis: import('../../../core/pglite-repair.ts').PgliteDirDiagnosis,
+): Check {
+ const backupNote = diagnosis.backupDirs.length > 0
+ ? ` ${diagnosis.backupDirs.length} repair backup dir(s) on disk (newest: ${diagnosis.backupDirs[0]}) — delete old ones to reclaim space once the brain is healthy.`
+ : '';
+ // Count BOTH outcomes (adversarial review F12): a >1h-period crash loop where
+ // each repair "succeeds" discards a WAL tail per cycle with zero FAILED
+ // attempts on record — escalation must still fire.
+ const recentAttempts = diagnosis.recentAttempts.filter(
+ (a) => Date.now() - a.ts < REPAIR_RECURRENCE_WINDOW_MS,
+ ).length;
+ const recurrence = recentAttempts >= REPAIR_RECURRENCE_THRESHOLD
+ ? ` Auto-repair has run ${recentAttempts}x this week — the corruption keeps regenerating (likely an unclean-shutdown loop). Consider switching engines (docs/ENGINES.md: \`gbrain init --supabase\` or native Postgres).`
+ : '';
+
+ switch (diagnosis.verdict) {
+ case 'locked':
+ return {
+ name: 'pglite_data_dir',
+ status: 'warn',
+ message:
+ `Could not connect, and the PGLite data-dir lock is held by live PID ${diagnosis.lockHolderPid} — ` +
+ `another gbrain process (often \`gbrain serve\`) has the brain open. Stop it and re-run.${backupNote}`,
+ remediation_status: 'human_only',
+ };
+ case 'missing':
+ return {
+ name: 'pglite_data_dir',
+ status: 'warn',
+ message: `No PGLite data dir at ${dataDir}. Run \`gbrain init --pglite\` to create one.`,
+ remediation_status: 'human_only',
+ };
+ case 'unsupported-layout':
+ return {
+ name: 'pglite_data_dir',
+ status: 'fail',
+ message:
+ `PGLite data dir at ${dataDir} is not repairable in place (${diagnosis.detail}). ` +
+ `Rebuild from your brain repo: \`gbrain reinit-pglite\` (or back up ~/.gbrain, move the dir aside, ` +
+ `\`gbrain init --pglite\`, re-add sources + sync + embed).${backupNote}${recurrence}`,
+ remediation_status: 'human_only',
+ };
+ case 'wal-corruption-likely':
+ return {
+ name: 'pglite_data_dir',
+ status: 'fail',
+ message:
+ `PGLite failed to open and the data dir shows unclean-shutdown state (${diagnosis.detail}). ` +
+ `This is the torn-WAL class behind issue #223 — repairable in place, data preserved: ` +
+ `\`gbrain pglite-repair --dry-run\` to diagnose, \`gbrain pglite-repair --yes\` to repair.${backupNote}${recurrence}`,
+ remediation_status: 'human_only',
+ };
+ case 'looks-healthy':
+ default:
+ return {
+ name: 'pglite_data_dir',
+ status: 'fail',
+ message:
+ `PGLite failed to open but the data dir layout validates (${diagnosis.detail}). ` +
+ `IF the connect error mentions \`Aborted()\` this is likely torn WAL state — ` +
+ `\`gbrain pglite-repair --dry-run\` to diagnose, \`gbrain pglite-repair --yes\` to repair in place ` +
+ `(repair discards the un-checkpointed WAL tail — don't run it for lock-contention or ` +
+ `catalog-corruption errors; 58P01/pgvector load failures need \`gbrain reinit-pglite\` instead).${backupNote}${recurrence}`,
+ remediation_status: 'human_only',
+ };
+ }
+}
+
+/**
+ * issue #1685 (GAP A) — the single authoritative "worker is OOM-looping" signal.
+ *
+ * One `gbrain doctor` line replaces the hours of log archaeology the #1678
+ * incident required: `cap=8192MB, N watchdog kills/24h → raise --max-rss`.
+ *
+ * UNIONS two sources so it's authoritative for BOTH worker modes (CODEX #5):
+ * - SUPERVISED workers: supervisor audit `worker_exited likely_cause=rss_watchdog`,
+ * read cross-week (CODEX #7) so a Mon read doesn't lose a Sun loop.
+ * - BARE `gbrain jobs work`: NO supervisor event is written; the only trace is
+ * `minion_jobs.error_text = 'aborted: watchdog'` (the same source queue_health
+ * subcheck 3 reads). Reading supervisor-only would miss bare workers entirely
+ * and the queue_health cross-reference would point at an unemitted check.
+ *
+ * Cap (CODEX #6): the breaker alert stamps `max_rss_mb`, but a fail from
+ * oomKills>=5 spread over 24h may have no breaker event → no stamped cap. Fall
+ * back to `resolveDefaultMaxRssMb()` so the message always renders a number.
+ *
+ * Returns null when the worker never OOM'd (don't warn installs that never hit
+ * it). Pure-ish: filesystem audit read + one minion_jobs count; no process.exit.
+ * Exported so `test/doctor-worker-oom-loop.test.ts` drives it directly.
+ */
+export async function computeWorkerOomLoopCheck(
+ engine: BrainEngine | null,
+): Promise<Check | null> {
+ let supervisorKills = 0;
+ let capFromBreaker: number | null = null;
+ let breakerTripped = false;
+ try {
+ const { readRecentSupervisorEvents, summarizeCrashes } = await import(
+ '../../../core/minions/handlers/supervisor-audit.ts'
+ );
+ const events = readRecentSupervisorEvents(24);
+ supervisorKills = summarizeCrashes(events).by_cause.rss_watchdog;
+ // Latest rss_watchdog_loop breaker alert carries the cap the supervisor
+ // spawned with (supervisor.ts:521); its presence also means the breaker
+ // tripped. Walk all events; last one wins for the cap.
+ for (const e of events) {
+ const row = e as Record<string, unknown>;
+ if (e.event === 'health_warn' && row.reason === 'rss_watchdog_loop') {
+ breakerTripped = true;
+ const cap = Number(row.max_rss_mb);
+ if (Number.isFinite(cap) && cap > 0) capFromBreaker = cap;
+ }
+ }
+ } catch {
+ // supervisor-audit read is best-effort; fall through to minion_jobs.
+ }
+
+ let bareWorkerKills = 0;
+ if (engine && engine.kind !== 'pglite') {
+ try {
+ const sql = db.getConnection();
+ const rows: Array<{ cnt: number }> = await sql`
+ SELECT count(*)::int AS cnt
+ FROM minion_jobs
+ WHERE status IN ('dead', 'failed')
+ AND finished_at > now() - interval '24 hours'
+ AND error_text = 'aborted: watchdog'
+ `;
+ bareWorkerKills = rows[0]?.cnt ?? 0;
+ } catch {
+ // minion_jobs may not exist on a fresh brain; best-effort.
+ }
+ }
+
+ // De-dup note (CODEX #5 accepted trade-off): a supervised watchdog kill aborts
+ // in-flight jobs, so it can show in BOTH counts. We accept slight over-count
+ // rather than miss bare workers — the signal is "is it OOM-looping," not an
+ // exact tally. `details` keeps the two sources separate for honesty.
+ const oomKills = supervisorKills + bareWorkerKills;
+ if (oomKills < 1 && !breakerTripped) return null;
+
+ let capMb: number;
+ let capSource: 'breaker' | 'default';
+ if (capFromBreaker !== null) {
+ capMb = capFromBreaker;
+ capSource = 'breaker';
+ } else {
+ let def = 16384;
+ try {
+ const { resolveDefaultMaxRssMb } = await import('../../../core/minions/rss-default.ts');
+ def = resolveDefaultMaxRssMb();
+ } catch {
+ // keep the conservative ceiling fallback.
+ }
+ capMb = def;
+ capSource = 'default';
+ }
+
+ const fixHint =
+ 'raise --max-rss (gbrain jobs work --max-rss <bigger>; auto-sizes to min(0.5×RAM,16GB))';
+ const capLabel = capSource === 'breaker' ? `cap=${capMb}MB` : `cap≈${capMb}MB (auto-sized default)`;
+ const status: Check['status'] = breakerTripped || oomKills >= 5 ? 'fail' : 'warn';
+ return {
+ name: 'worker_oom_loop',
+ status,
+ message:
+ `Worker OOM-looping: ${capLabel}, ${oomKills} watchdog kill(s)/24h → ${fixHint}. ` +
+ `Peak RSS: see worker stderr.`,
+ details: {
+ oom_kills: oomKills,
+ supervisor_kills: supervisorKills,
+ bare_worker_kills: bareWorkerKills,
+ cap_mb: capMb,
+ cap_source: capSource,
+ breaker_tripped: breakerTripped,
+ fix_hint: fixHint,
+ },
+ };
+}
+
+/**
+ * issue #1685 (GAP B) — DB pool reap health (Postgres-only).
+ *
+ * Answers the #1685 line "DB pool reaped N times/hr AND not auto-recovering"
+ * that no existing signal expresses. Reads the pool-recovery audit
+ * (`reconnect()` emits reap_detected / reconnect_succeeded / reconnect_failed):
+ * - fail: reaps>0 AND reconnect failures>0 → the pool is being reaped and
+ * rebuilds are throwing (genuinely not recovering).
+ * - warn: reaps>=10/hr, all recovered → pooler thrash (self-heal works but the
+ * cap is likely too low / concurrency too high).
+ * - else: null (quiet — a few reaps that all recovered is normal).
+ *
+ * Returns null on PGLite / no engine / audit-read failure. Exported so
+ * `test/doctor-pool-reap-health.test.ts` drives it directly.
+ */
+export async function computePoolReapHealthCheck(
+ engine: BrainEngine | null,
+): Promise<Check | null> {
+ if (!engine || engine.kind === 'pglite') return null;
+ let r: { reaps: number; recoveries: number; failures: number };
+ try {
+ const { readRecentPoolRecoveries } = await import('../../../core/audit/pool-recovery-audit.ts');
+ r = readRecentPoolRecoveries(1);
+ } catch {
+ return null;
+ }
+
+ // CODEX (impl review #3): the audit counts independent event kinds — it does
+ // NOT correlate a reconnect_failed to a preceding reap. So `reaps>0 AND
+ // failures>0` would falsely report "not auto-recovering" when a recovered reap
+ // and an unrelated reconnect failure merely co-occur in the same hour. Fail on
+ // the reconnect FAILURES themselves (reconnect throwing is the real, actionable
+ // problem regardless of reaps); report reaps as context, not as a causal claim.
+ if (r.failures > 0) {
+ const fix = 'check DB reachability / credentials (reconnect is throwing)';
+ return {
+ name: 'pool_reap_health',
+ status: 'fail',
+ message:
+ `DB reconnect FAILED ${r.failures}× in last hour (${r.reaps} pooler reap(s) detected) ` +
+ `— reconnect is throwing; ${fix}.`,
+ details: { reaps: r.reaps, recoveries: r.recoveries, failures: r.failures, fix_hint: fix },
+ };
+ }
+ if (r.reaps >= 10) {
+ const fix = 'raise --max-rss or reduce worker concurrency (pooler thrash)';
+ return {
+ name: 'pool_reap_health',
+ status: 'warn',
+ message:
+ `DB pool reaped ${r.reaps}× in last hour (self-heal recovered each) ` +
+ `— ${fix}.`,
+ details: { reaps: r.reaps, recoveries: r.recoveries, failures: r.failures, fix_hint: fix },
+ };
+ }
+ return null;
+}
+
diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.ts
new file mode 100644
index 0000000000..db6ce66be7
--- /dev/null
+++ b/src/commands/doctor/checks/queue-jobs.ts
@@ -0,0 +1,456 @@
+/**
+ * Queue + jobs check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import { resolveEnvNumber } from '../../../core/env-number.ts';
+import type { Check } from '../../doctor.ts';
+
+/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */
+const _resolveEnvNumber = resolveEnvNumber;
+
+/**
+ * v0.41.18.0 batch_retry_health doctor check (codex H-9 thresholds).
+ *
+ * Surfaces sustained Supavisor circuit-breaker incidents from the
+ * engine-level batch retry wrap. Reads the last 24h of audit events from
+ * `~/.gbrain/audit/batch-retry-YYYY-Www.jsonl`.
+ *
+ * Threshold ladder (codex H-9 — avoid permanent noise from one historical blip):
+ * ok — zero exhausted events in 24h, OR <3 exhausted from a single site
+ * warn — >=3 exhausted from same site in 24h, OR >=5 cross-site
+ * fail — >=20 exhausted in 24h (sustained breaker; operator intervention)
+ *
+ * Also surfaces (codex H-9 corruption tolerance):
+ * - corrupted_lines count when audit JSONL has malformed rows
+ * - files_unreadable count for permission errors (NOT ENOENT which is normal)
+ *
+ * Also surfaces (codex M-10): runs resolveBulkRetryOpts(process.env) at
+ * startup so bad GBRAIN_BULK_* config fails at doctor time, not first-retry.
+ */
+/**
+ * queue_health: Postgres Minion queue diagnostics.
+ *
+ * Includes the original stalled/depth/memory/prompt checks plus the #2557
+ * no-worker signal: old `embed-backfill` jobs waiting on a queue with no live
+ * registered worker for that queue. That catches the default deployment shape
+ * where `sync` enqueues deferred embedding work but the operator never started
+ * `gbrain jobs work` or a supervisor.
+ */
+export async function computeQueueHealthCheck(
+ engine: BrainEngine,
+ opts: {
+ waitingDepthThreshold?: number;
+ oldWaitingHours?: number;
+ readWorkers?: () => Array<{ queue: string }>;
+ } = {},
+): Promise<Check> {
+ if (engine.kind === 'pglite') {
+ return {
+ name: 'queue_health',
+ status: 'ok',
+ message: 'Skipped (PGLite — no multi-process worker surface)',
+ };
+ }
+
+ try {
+ // issue #1801: column is `status`, not `state` (schema.sql:780).
+ const stalledRows: Array<{ id: number; name: string; started_at: string }> =
+ await engine.executeRaw(
+ `SELECT id, name, started_at::text AS started_at
+ FROM minion_jobs
+ WHERE status = 'active'
+ AND started_at IS NOT NULL
+ AND started_at < now() - interval '1 hour'
+ ORDER BY started_at ASC
+ LIMIT 5`,
+ );
+
+ const threshold = opts.waitingDepthThreshold
+ ?? _resolveEnvNumber('GBRAIN_QUEUE_WAITING_THRESHOLD', 10);
+ const depthRows: Array<{ name: string; queue: string; depth: number }> =
+ await engine.executeRaw(
+ `SELECT name, queue, count(*)::int AS depth
+ FROM minion_jobs
+ WHERE status = 'waiting'
+ GROUP BY name, queue
+ HAVING count(*) > $1
+ ORDER BY depth DESC
+ LIMIT 5`,
+ [threshold],
+ );
+
+ const rssKillRows: Array<{ cnt: number }> = await engine.executeRaw(
+ `SELECT count(*)::int AS cnt
+ FROM minion_jobs
+ WHERE status IN ('dead', 'failed')
+ AND finished_at > now() - interval '24 hours'
+ AND error_text = 'aborted: watchdog'`,
+ );
+ const rssKillCount = Number(rssKillRows[0]?.cnt ?? 0);
+
+ const promptTooLongRows: Array<{ cnt: number }> = await engine.executeRaw(
+ `SELECT count(*)::int AS cnt
+ FROM minion_jobs
+ WHERE name = 'subagent'
+ AND status = 'dead'
+ AND finished_at > now() - interval '24 hours'
+ AND error_text LIKE 'prompt_too_long:%'`,
+ );
+ const promptTooLongCount = Number(promptTooLongRows[0]?.cnt ?? 0);
+
+ const oldWaitingHours = opts.oldWaitingHours
+ ?? _resolveEnvNumber('GBRAIN_QUEUE_NO_WORKER_WARN_HOURS', 1);
+ const oldWaitingRows: Array<{
+ name: string;
+ queue: string;
+ depth: number;
+ oldest_age_seconds: number;
+ }> = await engine.executeRaw(
+ `SELECT name,
+ queue,
+ count(*)::int AS depth,
+ EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS oldest_age_seconds
+ FROM minion_jobs
+ WHERE status = 'waiting'
+ AND name = 'embed-backfill'
+ GROUP BY name, queue
+ HAVING min(created_at) < now() - ($1::text::interval)
+ ORDER BY oldest_age_seconds DESC
+ LIMIT 5`,
+ [`${oldWaitingHours} hours`],
+ );
+
+ // Read the live-worker registry unconditionally (was: only when old
+ // embed-backfill rows existed) — the structured `details.worker_alive`
+ // below needs it on every run. Cheap: one directory enumeration.
+ const workers = opts.readWorkers
+ ? opts.readWorkers()
+ : (await import('../../../core/minions/worker-registry.ts')).readWorkers();
+ const liveWorkerQueues = new Set(workers.map((w) => w.queue));
+
+ // Minions-visibility wave: structured details so machine callers stop
+ // parsing prose. depth = total waiting jobs; oldest_age_seconds = age of
+ // the oldest waiting job (null when the queue is empty); worker_alive =
+ // every queue holding waiting work has a live registered worker
+ // (vacuously true with zero waiting jobs). Messages stay unchanged.
+ // Perf note (twin of buildQueueDepths in status.ts): WHERE constrains
+ // only `status` — the second column of the (queue, status, updated_at)
+ // wedge index — so this GROUP BY full-scans minion_jobs today. Acceptable
+ // at doctor frequency over pruned waiting sets; a partial
+ // (queue, created_at) WHERE status='waiting' index is the fix if hot.
+ const waitingByQueue: Array<{
+ queue: string;
+ depth: number | string;
+ oldest_age_seconds: number | string | null;
+ }> = await engine.executeRaw(
+ `SELECT queue,
+ count(*)::int AS depth,
+ EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS oldest_age_seconds
+ FROM minion_jobs
+ WHERE status = 'waiting'
+ GROUP BY queue`,
+ );
+ const details: Record<string, unknown> = {
+ depth: waitingByQueue.reduce((n, r) => n + Number(r.depth), 0),
+ oldest_age_seconds: waitingByQueue.reduce<number | null>(
+ (max, r) => {
+ const age = r.oldest_age_seconds === null ? null : Number(r.oldest_age_seconds);
+ if (age === null) return max;
+ return max === null ? age : Math.max(max, age);
+ },
+ null,
+ ),
+ worker_alive: waitingByQueue.every((r) => liveWorkerQueues.has(r.queue)),
+ };
+
+ const problems: string[] = [];
+ if (stalledRows.length > 0) {
+ const sample = stalledRows
+ .map(r => `#${r.id}(${r.name})`)
+ .join(', ');
+ problems.push(
+ `${stalledRows.length} stalled-forever job(s): ${sample}. ` +
+ `Fix: gbrain jobs get <id> to inspect; gbrain jobs cancel <id> to force-kill.`
+ );
+ }
+ if (depthRows.length > 0) {
+ const sample = depthRows
+ .map(r => `${r.name}@${r.queue}=${r.depth}`)
+ .join(', ');
+ problems.push(
+ `waiting-queue depth exceeds ${threshold} for: ${sample}. ` +
+ `Fix: set maxWaiting on the submitter (or raise GBRAIN_QUEUE_WAITING_THRESHOLD).`
+ );
+ }
+ for (const row of oldWaitingRows) {
+ if (liveWorkerQueues.has(row.queue)) continue;
+ const hours = Math.max(1, Math.round(Number(row.oldest_age_seconds ?? 0) / 3600));
+ problems.push(
+ `${row.depth} ${row.name} job(s) have waited on queue '${row.queue}' for up to ${hours}h ` +
+ `and no live worker is registered for that queue. ` +
+ `Start one with \`gbrain jobs work --queue ${row.queue}\` or ` +
+ `\`gbrain jobs supervisor start --queue ${row.queue}\`.`
+ );
+ }
+ if (rssKillCount > 0) {
+ problems.push(
+ `${rssKillCount} job(s) dead-lettered for RSS-watchdog memory-limit kills in last 24h. ` +
+ `Fix: raise the limit (e.g. \`gbrain jobs work --max-rss 4096\`) or opt out (\`--max-rss 0\`). ` +
+ `→ see worker_oom_loop for the cap + fix (the authoritative OOM-loop signal).`
+ );
+ }
+ if (promptTooLongCount > 0) {
+ problems.push(
+ `${promptTooLongCount} subagent job(s) dead-lettered with prompt_too_long in last 24h. ` +
+ `Dream/synthesize transcripts exceeded the model's input context. ` +
+ `Fix: \`gbrain dream --phase synthesize --dry-run --json\` to identify fat transcripts; ` +
+ `set \`dream.synthesize.max_prompt_tokens\` to bound the per-chunk budget, or use a ` +
+ `larger-context model (Opus 4.7 = 1M tokens vs Sonnet 4.6 = 200K).`
+ );
+ }
+
+ if (problems.length === 0) {
+ return {
+ name: 'queue_health',
+ status: 'ok',
+ message: `No stalled-forever jobs; no queue over depth ${threshold}; no old embed-backfill jobs without a worker.`,
+ details,
+ };
+ }
+ return {
+ name: 'queue_health',
+ status: 'warn',
+ message: problems.join(' '),
+ details,
+ };
+ } catch (e) {
+ return {
+ name: 'queue_health',
+ status: 'warn',
+ message: `queue_health scan skipped: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+/**
+ * issue #1801 — `wedged_queue` check. Surfaces the alive-but-wedged-worker
+ * signature (a queue with claimable work waiting, zero live-lock active jobs,
+ * and stale completions) as a health ERROR, so an operator / the daily doctor
+ * catches a silent processing halt in minutes, not 15 hours.
+ *
+ * Postgres-only (PGLite has no multi-process worker surface). Grouped BY queue
+ * (Codex #15) so a healthy worker on one queue can't mask a wedged one.
+ * `active_healthy` counts only live-lock active rows, so an expired-lock active
+ * row (a worker that died mid-job) does NOT mask the wedge (Codex #6). The
+ * check is conservative for the advisory surface: it fails only on stale-after-
+ * progress (mins_since_completion > threshold, non-null); a queue that never
+ * completed anything is left to the supervisor's startup-grace-aware watchdog
+ * to avoid crying wolf on a freshly-submitted queue with no worker yet.
+ *
+ * Exported so `test/doctor.test.ts` drives it directly. Reads
+ * GBRAIN_WEDGED_QUEUE_WARN_MINUTES (default 15).
+ */
+export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Check> {
+ if (engine.kind !== 'postgres') {
+ return { name: 'wedged_queue', status: 'ok', message: 'PGLite — no queue to check' };
+ }
+ const thresholdMin = _resolveEnvNumber('GBRAIN_WEDGED_QUEUE_WARN_MINUTES', 15);
+ try {
+ const rows = await engine.executeRaw<{
+ queue: string;
+ active_healthy: string | number;
+ waiting: string | number;
+ mins_since_completion: string | number | null;
+ }>(
+ `SELECT queue,
+ count(*) FILTER (WHERE status = 'active' AND lock_until > now()) AS active_healthy,
+ count(*) FILTER (WHERE status = 'waiting') AS waiting,
+ EXTRACT(EPOCH FROM (now() - max(updated_at) FILTER (WHERE status = 'completed'))) / 60
+ AS mins_since_completion
+ FROM minion_jobs
+ GROUP BY queue`,
+ );
+ const wedged: string[] = [];
+ for (const r of rows) {
+ const activeHealthy = Number(r.active_healthy ?? 0);
+ const waiting = Number(r.waiting ?? 0);
+ const mins = r.mins_since_completion === null ? null : Number(r.mins_since_completion);
+ // Conservative: only flag stale-after-progress (non-null mins past
+ // threshold). The null-completions case is the supervisor's job.
+ if (activeHealthy === 0 && waiting > 0 && mins !== null && mins > thresholdMin) {
+ wedged.push(`'${r.queue}' (${waiting} waiting, 0 active, ${Math.round(mins)}m since last completion)`);
+ }
+ }
+ if (wedged.length === 0) {
+ return { name: 'wedged_queue', status: 'ok', message: 'No wedged queues' };
+ }
+ return {
+ name: 'wedged_queue',
+ status: 'fail',
+ message:
+ `Wedged queue(s) — worker alive but not claiming work: ${wedged.join('; ')}. ` +
+ `Restart the worker so it rebuilds a fresh DB pool: ` +
+ `\`gbrain jobs supervisor stop && gbrain jobs supervisor start\`, ` +
+ `then \`gbrain jobs retry <id>\` on any dead-lettered jobs.`,
+ details: { wedged_queues: wedged.length, threshold_minutes: thresholdMin },
+ };
+ } catch (e) {
+ // Pre-migration brains / transient errors: advisory check stays ok.
+ return {
+ name: 'wedged_queue',
+ status: 'ok',
+ message: `Skipped (${e instanceof Error ? e.message : String(e)})`,
+ };
+ }
+}
+
+/**
+ * #2194 fix #5: warn when autopilot's per-tick fan-out exceeds the worker's
+ * effective concurrency. Fanning out more cycles than there are worker slots
+ * guarantees waiters that race the stalled-sweeper — a silent misconfig today.
+ * Advisory (started-event concurrency is fine here; the behavior-changing clamp
+ * in resolveEffectiveFanoutMax is the one that gates on liveness). Surfaces only
+ * when a supervisor has actually started (no noise on never-supervised brains).
+ */
+export async function computeAutopilotFanoutConcurrencyCheck(engine: BrainEngine): Promise<Check> {
+ if (engine.kind !== 'postgres') {
+ return { name: 'autopilot_fanout_concurrency', status: 'ok', message: 'PGLite — single-writer, fan-out is 1' };
+ }
+ try {
+ const { resolveFanoutMax, readSupervisorConcurrency } = await import('../../autopilot-fanout.ts');
+ const concurrency = await readSupervisorConcurrency('default');
+ if (concurrency === null) {
+ return { name: 'autopilot_fanout_concurrency', status: 'ok', message: 'No supervisor observed — skipping fan-out/concurrency check' };
+ }
+ const fanoutMax = await resolveFanoutMax(engine);
+ const effectiveSlots = Math.max(1, concurrency - 1);
+ if (fanoutMax > effectiveSlots) {
+ return {
+ name: 'autopilot_fanout_concurrency',
+ status: 'warn',
+ message:
+ `autopilot fan-out (${fanoutMax}/tick) exceeds worker concurrency (${concurrency}). ` +
+ `Surplus cycles queue behind the worker and race the stalled-sweeper. ` +
+ `Lower fan-out: \`gbrain config set autopilot.fanout_max_per_tick ${effectiveSlots}\`, ` +
+ `or raise the supervisor's \`--concurrency\` to ${fanoutMax + 1}. ` +
+ `(The clamp in autopilot does this automatically unless disabled.)`,
+ details: { fanout_max: fanoutMax, concurrency, effective_slots: effectiveSlots },
+ };
+ }
+ return {
+ name: 'autopilot_fanout_concurrency',
+ status: 'ok',
+ message: `fan-out ${fanoutMax}/tick within worker concurrency ${concurrency}`,
+ };
+ } catch (e) {
+ return { name: 'autopilot_fanout_concurrency', status: 'ok', message: `Skipped (${e instanceof Error ? e.message : String(e)})` };
+ }
+}
+
+export async function checkBatchRetryHealth(_engine: BrainEngine): Promise<Check> {
+ try {
+ // Codex M-10: surface bad env config at doctor time.
+ try {
+ const { resolveBulkRetryOpts } = await import('../../../core/retry.ts');
+ resolveBulkRetryOpts();
+ } catch (e) {
+ return {
+ name: 'batch_retry_health',
+ status: 'warn',
+ message: `GBRAIN_BULK_* env override invalid: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+
+ const { readRecentBatchRetryEvents } = await import('../../../core/audit/batch-retry-audit.ts');
+ const result = readRecentBatchRetryEvents(24);
+
+ // Surface corruption / permission errors at warn so operators investigate.
+ if (result.files_unreadable > 0) {
+ return {
+ name: 'batch_retry_health',
+ status: 'warn',
+ message: `${result.files_unreadable} audit file(s) unreadable (permission / IO). Fix: check ~/.gbrain/audit/ (or $GBRAIN_AUDIT_DIR if set).`,
+ };
+ }
+
+ const exhausted = result.events.filter((e) => e.outcome === 'exhausted');
+ const successful = result.events.filter((e) => e.outcome === 'success');
+
+ // v0.41.25.0 (#1570) — read the db-disconnect audit so the existing
+ // batch_retry_health check surfaces ALL connection-incident signal in
+ // one place (per codex finding 11: extend, don't add a new check).
+ // Disconnect events are informational — every CLI command legitimately
+ // disconnects at end-of-life. The value is the most_recent_caller
+ // frame: when the v0.41.25 retry reconnect callback fires, the
+ // operator runs `gbrain doctor` and the stack trace tells them which
+ // code path triggered the mid-process disconnect. v0.41.26 fixes
+ // that specific ownership boundary.
+ let disconnectNote = '';
+ try {
+ const { readRecentDbDisconnects } = await import('../../../core/audit/db-disconnect-audit.ts');
+ const dc = readRecentDbDisconnects(24);
+ if (dc.count > 0) {
+ // First-line of stack trace is the caller of logDbDisconnect; show
+ // it so the operator sees something compact in human output.
+ const firstFrame = (dc.most_recent_caller ?? '').split('\n')[0]?.trim() ?? '';
+ const frameSlug = firstFrame.length > 0 ? ` (most recent caller: ${firstFrame.slice(0, 200)})` : '';
+ disconnectNote = ` Disconnect-call audit: ${dc.count} call(s) in 24h${frameSlug}.`;
+ }
+ } catch { /* audit module unavailable; older brain, fine */ }
+
+ if (exhausted.length === 0) {
+ const note = result.corrupted_lines > 0
+ ? ` (note: ${result.corrupted_lines} corrupt JSONL line(s) skipped)`
+ : '';
+ const recoveredNote = successful.length > 0
+ ? ` ${successful.length} transient retry(s) succeeded.`
+ : '';
+ return {
+ name: 'batch_retry_health',
+ status: 'ok',
+ message: `No exhausted batch retries in last 24h.${recoveredNote}${note}${disconnectNote}`,
+ };
+ }
+
+ // Group exhausted events by site for per-site threshold detection.
+ const bySite = new Map<string, number>();
+ for (const e of exhausted) bySite.set(e.site, (bySite.get(e.site) ?? 0) + 1);
+ const worstSite = [...bySite.entries()].sort((a, b) => b[1] - a[1])[0];
+
+ // codex H-9 fail threshold: >=20 in 24h = sustained breaker.
+ if (exhausted.length >= 20) {
+ return {
+ name: 'batch_retry_health',
+ status: 'fail',
+ message: `${exhausted.length} exhausted batch retries in last 24h (worst: ${worstSite[0]} = ${worstSite[1]}). Sustained circuit-breaker incident. Fix: check pooler status; consider raising GBRAIN_BULK_MAX_RETRIES or moving to direct-connection.${disconnectNote}`,
+ };
+ }
+
+ // warn thresholds: >=3 same-site OR >=5 cross-site.
+ if (worstSite[1] >= 3 || exhausted.length >= 5) {
+ return {
+ name: 'batch_retry_health',
+ status: 'warn',
+ message: `${exhausted.length} exhausted batch retries in last 24h (worst: ${worstSite[0]} = ${worstSite[1]}). Tune via GBRAIN_BULK_MAX_RETRIES / GBRAIN_BULK_RETRY_MAX_MS.${disconnectNote}`,
+ };
+ }
+
+ // Single-incident noise tolerance.
+ return {
+ name: 'batch_retry_health',
+ status: 'ok',
+ message: `${exhausted.length} exhausted batch retry(s) in last 24h (below per-site threshold of 3)${disconnectNote}`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return {
+ name: 'batch_retry_health',
+ status: 'warn',
+ message: `Could not check batch_retry audit: ${msg}`,
+ };
+ }
+}
+
diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.ts
new file mode 100644
index 0000000000..61afeda43d
--- /dev/null
+++ b/src/commands/doctor/checks/routing-federation.ts
@@ -0,0 +1,369 @@
+/**
+ * Routing / federation / oauth / locks check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import { existsSync, readFileSync } from 'fs';
+import type { BrainEngine } from '../../../core/engine.ts';
+import { gbrainPath } from '../../../core/config.ts';
+import type { Check } from '../../doctor.ts';
+
+/**
+ * v0.37.7.0 — Tier 5K source_routing_health (D5 lock: 200-page total cap).
+ *
+ * On a multi-source brain, sample up to 200 recent pages across all
+ * non-default sources (per-source cap = min(50, ceil(200/N))). Warn
+ * when:
+ * - A non-default source has zero pages (silent-collapse-to-default
+ * fingerprint from #1167 + #1222).
+ * - The brain repo has a `.gitignore` file but
+ * `sync.respect_gitignore` is unset/false (info-line nudge for
+ * Tier 4I's opt-in flag).
+ *
+ * Cost-bounded: total cap of 200 means a 20-source CEO brain pays
+ * 20*10 = 200 selects rather than 20*50 = 1000.
+ */
+export async function checkSourceRoutingHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ const sources = await engine.executeRaw<{ id: string }>(
+ `SELECT id FROM sources WHERE id <> 'default'`,
+ );
+ if (sources.length === 0) {
+ return { name: 'source_routing_health', status: 'ok', message: 'Single-source brain (no federation to check)' };
+ }
+ const perSourceCap = Math.min(50, Math.ceil(200 / Math.max(1, sources.length)));
+ const emptySources: string[] = [];
+ for (const s of sources) {
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT COUNT(*)::text AS n FROM pages WHERE source_id = $1 LIMIT $2`,
+ [s.id, perSourceCap],
+ );
+ if (Number(rows[0]?.n ?? 0) === 0) {
+ emptySources.push(s.id);
+ }
+ }
+ if (emptySources.length > 0) {
+ return {
+ name: 'source_routing_health',
+ status: 'warn',
+ message:
+ `${emptySources.length} non-default source(s) have zero pages: ${emptySources.join(', ')}. ` +
+ `If you've recently run \`gbrain import --source-id <id>\` against these, the writes may have ` +
+ `silently fallen to the default source pre-v0.37.7.0. Re-run with --source-id; verify via ` +
+ `\`gbrain sources current --json\`.`,
+ };
+ }
+ return {
+ name: 'source_routing_health',
+ status: 'ok',
+ message: `Multi-source brain (${sources.length} non-default source(s)); all populated`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return { name: 'source_routing_health', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
+/**
+ * v0.40 Federated Sync v2 (T12) — federation_health.
+ *
+ * Per-source dashboard surface for the autopilot/operator.
+ * Three-state per-source (then aggregated to single Check):
+ *
+ * ok — all federated sources synced within 1h AND embed coverage >=95%
+ * (or chunks <100), AND failed_jobs_24h < 3
+ * warn — any source has lag > 1h + federated, OR coverage < 95% with
+ * chunks > 100, OR failed_jobs_24h >= 3
+ * fail — any source has lag > 24h, OR coverage < 50% with chunks > 1000
+ *
+ * Single-source brain short-circuits to ok (no federation to check).
+ * Each warning carries a paste-ready remediation hint.
+ */
+export async function checkFederationHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ const { loadAllSources } = await import('../../../core/sources-load.ts');
+ const { computeAllSourceMetrics } = await import('../../../core/source-health.ts');
+ const sources = await loadAllSources(engine, { includeArchived: false });
+ if (sources.length <= 1) {
+ return {
+ name: 'federation_health',
+ status: 'ok',
+ message: 'Single-source brain (no federation to check)',
+ };
+ }
+ const metrics = await computeAllSourceMetrics(engine, sources);
+
+ const warns: string[] = [];
+ const fails: string[] = [];
+ for (const m of metrics) {
+ // Fail thresholds first (most severe)
+ if (m.lag_seconds !== null && m.lag_seconds > 24 * 3600) {
+ fails.push(`${m.source_id}: stale ${Math.floor(m.lag_seconds / 3600)}h — run \`gbrain sync trigger --source ${m.source_id}\``);
+ continue;
+ }
+ if (m.embed_coverage_pct < 50 && m.total_chunks > 1000) {
+ fails.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage (${m.total_chunks.toLocaleString()} chunks) — run \`gbrain jobs submit embed-backfill --params '{"sourceId":"${m.source_id}"}'\``);
+ continue;
+ }
+ // Warns
+ if (m.federated && m.lag_seconds !== null && m.lag_seconds > 3600) {
+ warns.push(`${m.source_id}: federated source ${Math.floor(m.lag_seconds / 3600)}h+ stale — run \`gbrain sync trigger --source ${m.source_id}\``);
+ }
+ if (m.embed_coverage_pct < 95 && m.total_chunks > 100) {
+ warns.push(`${m.source_id}: ${m.embed_coverage_pct.toFixed(1)}% embed coverage — run \`gbrain jobs submit embed-backfill --params '{"sourceId":"${m.source_id}"}'\``);
+ }
+ if (m.failed_jobs_24h >= 3) {
+ warns.push(`${m.source_id}: ${m.failed_jobs_24h} failures in 24h — check \`gbrain jobs list --status failed\``);
+ }
+ }
+
+ if (fails.length > 0) {
+ return {
+ name: 'federation_health',
+ status: 'fail',
+ message: `${fails.length} federation failure(s):\n ${fails.join('\n ')}`,
+ };
+ }
+ if (warns.length > 0) {
+ return {
+ name: 'federation_health',
+ status: 'warn',
+ message: `${warns.length} federation warning(s):\n ${warns.join('\n ')}`,
+ };
+ }
+ return {
+ name: 'federation_health',
+ status: 'ok',
+ message: `${metrics.length} source(s) healthy (parallel sync, async embed)`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return { name: 'federation_health', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
+/**
+ * v0.37.7.0 — Tier 5L oauth_confidential_client_health.
+ *
+ * Confidential OAuth clients (token_endpoint_auth_method != 'none')
+ * MUST have a non-NULL client_secret_hash. v0.34.1.0's #909 fix
+ * intentionally NULLs the column for public PKCE clients; if any
+ * row claims confidential auth but has NULL hash, that's the
+ * regression fingerprint from #1166.
+ */
+export async function checkOauthConfidentialHealth(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ client_id: string; method: string | null; hash: string | null }>(
+ `SELECT client_id,
+ token_endpoint_auth_method AS method,
+ client_secret_hash AS hash
+ FROM oauth_clients`,
+ );
+ if (rows.length === 0) {
+ return { name: 'oauth_confidential_client_health', status: 'ok', message: 'No OAuth clients registered' };
+ }
+ const broken = rows.filter(r => {
+ const isPublic = r.method === 'none';
+ return !isPublic && (r.hash == null || r.hash === '');
+ });
+ if (broken.length > 0) {
+ return {
+ name: 'oauth_confidential_client_health',
+ status: 'fail',
+ message:
+ `${broken.length} confidential OAuth client(s) have NULL/empty secret hash: ${broken.map(b => b.client_id).slice(0, 5).join(', ')}` +
+ (broken.length > 5 ? ` (+${broken.length - 5} more)` : '') +
+ `. Fix: \`gbrain auth revoke-client <id> && gbrain auth register-client …\` for each, OR \`gbrain upgrade\` if pre-v0.37.7.0.`,
+ };
+ }
+ return {
+ name: 'oauth_confidential_client_health',
+ status: 'ok',
+ message: `${rows.length} OAuth client(s) registered; all auth shapes consistent`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ // Pre-OAuth schema (oauth_clients table missing) → ok.
+ if (msg.toLowerCase().includes('relation') && msg.toLowerCase().includes('does not exist')) {
+ return { name: 'oauth_confidential_client_health', status: 'ok', message: 'OAuth not configured (skipping)' };
+ }
+ return { name: 'oauth_confidential_client_health', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
+/**
+ * v0.37.7.0 — Tier 5M autopilot_lock_scope (PID-safe hint per codex CF11).
+ *
+ * Detects stale autopilot lockfiles. When `GBRAIN_HOME` is set, the
+ * canonical lock path lives under `gbrainPath('autopilot.lock')`.
+ * If a hardcoded `~/.gbrain/autopilot.lock` ALSO exists outside the
+ * current `GBRAIN_HOME`, that's a pre-v0.37.7.0 leftover or a
+ * different brain's lock. Hint includes PID + a `ps -p` check so
+ * the user verifies before deleting.
+ */
+export function checkAutopilotLockScope(): Check {
+ try {
+ const canonical = gbrainPath('autopilot.lock');
+ const home = process.env.HOME || '';
+ const legacy = home ? `${home}/.gbrain/autopilot.lock` : '';
+ // Same path → nothing to surface.
+ if (canonical === legacy || !legacy || !existsSync(legacy)) {
+ return { name: 'autopilot_lock_scope', status: 'ok', message: `Lock path: ${canonical}` };
+ }
+ // legacy lock exists outside GBRAIN_HOME. Read its PID for a safe hint.
+ let owningPid: string = 'unknown';
+ try {
+ const raw = readFileSync(legacy, 'utf8').trim();
+ if (/^\d+$/.test(raw)) owningPid = raw;
+ } catch { /* unreadable → leave 'unknown' */ }
+ return {
+ name: 'autopilot_lock_scope',
+ status: 'warn',
+ message:
+ `Stale lockfile outside GBRAIN_HOME: ${legacy} (owning PID: ${owningPid}). ` +
+ `Verify with \`ps -p ${owningPid}\` — if the process is dead, \`rm ${legacy}\`. ` +
+ `If alive, identify it (\`ps -fp ${owningPid}\`) and stop before deleting.`,
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return { name: 'autopilot_lock_scope', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
+/**
+ * v0.41.6.0 D3 — stale_locks doctor check.
+ *
+ * Surfaces every row in `gbrain_cycle_locks` whose `ttl_expires_at < NOW()`.
+ * The TTL is the canonical staleness signal already trusted by
+ * tryAcquireDbLock's UPDATE-on-conflict SQL — when TTL is in the past,
+ * the next acquire attempt will sweep the row anyway. Doctor's job is to
+ * warn the user proactively so the next sync doesn't get a surprise
+ * "Another sync is in progress" with no fix hint.
+ *
+ * Paste-ready hint per stale lock: names the source-id from the
+ * `gbrain-sync:<source>` lock-key shape so users can copy-paste the
+ * exact recovery command.
+ *
+ * Out of scope (filed as v0.41+ follow-up TODO): detection of
+ * "wedged but TTL-refreshing" locks where a refresh thread is alive
+ * but the main work is blocked. Requires explicit heartbeat probe;
+ * speculation until production data shows the case.
+ */
+export async function checkStaleLocks(
+ engine: BrainEngine,
+ opts: { fix?: boolean; dryRun?: boolean } = {},
+): Promise<Check> {
+ try {
+ const { listStaleLocks, reapDeadHolderLocks } = await import('../../../core/db-lock.ts');
+
+ // #1972: under `gbrain doctor --fix`, reap dead-holder sync/cycle locks
+ // using the SAME namespace-scoped, host-scoped, snapshot-matched reaper the
+ // cycle runs at start. This is the self-heal path for no-autopilot brains: a
+ // brain that never runs `gbrain dream` never hits the cycle-start sweep, so
+ // doctor --fix is how its crashed-sync locks get cleared. DB-only, so it's
+ // orthogonal to (and unaffected by) the skills-dir --fix safety gate above.
+ // Best-effort: a reap failure falls through to the warn path below.
+ let reapedIds: string[] = [];
+ if (opts.fix && !opts.dryRun) {
+ try {
+ reapedIds = (await reapDeadHolderLocks(engine)).reapedIds;
+ } catch { /* fall through; listStaleLocks still surfaces remaining locks */ }
+ }
+ const reapedNote = reapedIds.length > 0
+ ? `Reaped ${reapedIds.length} dead-holder lock(s): ${reapedIds.join(', ')}.`
+ : null;
+
+ const stale = await listStaleLocks(engine);
+ if (stale.length === 0) {
+ return {
+ name: 'stale_locks',
+ status: 'ok',
+ message: reapedNote
+ ? `${reapedNote} No stale locks remain.`
+ : 'No stale locks (no rows with ttl_expires_at < NOW())',
+ };
+ }
+ const lines = stale.slice(0, 10).map(s => {
+ const ageH = Math.floor(s.age_ms / 3600_000);
+ let breakHint = 'gbrain doctor';
+ if (s.id.startsWith('gbrain-sync:')) {
+ breakHint = `gbrain sync --break-lock --source ${s.id.slice('gbrain-sync:'.length)}`;
+ } else if (s.id.startsWith('gbrain-cycle:')) {
+ breakHint = `gbrain dream --break-lock --source ${s.id.slice('gbrain-cycle:'.length)}`;
+ } else if (s.id === 'gbrain-cycle') {
+ breakHint = 'gbrain dream --break-lock';
+ }
+ return ` ${s.id} (pid ${s.holder_pid} on ${s.holder_host}, age ${ageH}h) → ${breakHint}`;
+ });
+ const tail = stale.length > 10 ? ` ... and ${stale.length - 10} more.` : null;
+ const header = opts.fix
+ ? `${stale.length} stale lock(s) remain that could not be auto-reaped (live holder, cross-host, or within the PID-reuse grace):`
+ : `${stale.length} stale lock(s) detected (ttl_expires_at < NOW()):`;
+ return {
+ name: 'stale_locks',
+ status: 'warn',
+ message: [
+ reapedNote,
+ header,
+ ...lines,
+ tail,
+ ].filter(Boolean).join('\n'),
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ // Pre-v0.30 brains may not have the gbrain_cycle_locks table yet.
+ if (/relation .* does not exist|no such table/i.test(msg)) {
+ return { name: 'stale_locks', status: 'ok', message: 'gbrain_cycle_locks table not yet provisioned (skipping)' };
+ }
+ return { name: 'stale_locks', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
+/**
+ * v0.38 — cycle_phase_scope check (informational).
+ *
+ * Renders the static `PHASE_SCOPE` taxonomy from `src/core/cycle.ts` so
+ * operators (and future automation) can see at a glance which phases
+ * are safe to parallelize per source vs which serialize brain-wide.
+ *
+ * Always returns 'ok' — this is documentation, not enforcement. The
+ * runtime-enforcement TODO is deferred per plan.
+ */
+export function checkCyclePhaseScope(): Check {
+ try {
+ // Lazy require to avoid pulling cycle.ts into doctor's import graph
+ // for non-cycle-related doctor runs. Same pattern as the existing
+ // dynamic imports elsewhere in this file.
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { ALL_PHASES, PHASE_SCOPE } = require('../../../core/cycle.ts') as {
+ ALL_PHASES: ReadonlyArray<string>;
+ PHASE_SCOPE: Record<string, 'source' | 'global' | 'mixed'>;
+ };
+ const counts: Record<'source' | 'global' | 'mixed', number> = { source: 0, global: 0, mixed: 0 };
+ const breakdown: Record<string, string[]> = { source: [], global: [], mixed: [] };
+ for (const phase of ALL_PHASES) {
+ const scope = PHASE_SCOPE[phase];
+ if (scope) {
+ counts[scope]++;
+ breakdown[scope].push(phase);
+ }
+ }
+ return {
+ name: 'cycle_phase_scope',
+ status: 'ok',
+ message:
+ `Phase taxonomy: ${counts.source} source-scoped, ${counts.global} brain-global, ` +
+ `${counts.mixed} mixed. Source-safe: [${breakdown.source.join(', ')}]. ` +
+ `Brain-global: [${breakdown.global.join(', ')}]. Mixed: [${breakdown.mixed.join(', ')}].`,
+ details: {
+ phase_scope_map: PHASE_SCOPE,
+ counts,
+ },
+ };
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ return { name: 'cycle_phase_scope', status: 'warn', message: `Check failed: ${msg}` };
+ }
+}
+
diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.ts
new file mode 100644
index 0000000000..5e11099811
--- /dev/null
+++ b/src/commands/doctor/checks/search-eval.ts
@@ -0,0 +1,588 @@
+/**
+ * Search / eval / subagent / probe check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+
+/**
+ * v0.32.3 [CDX-20]: surface mode + per-key override drift.
+ *
+ * Status stays `ok` (never warns; never docks health score). If
+ * search.mode is unset → suggest picking one. If overrides contradict
+ * the mode (e.g. mode=conservative but cache.enabled=false), say so in
+ * the message and paste a `gbrain search modes --reset` fix command.
+ */
+
+export async function checkSearchMode(engine: BrainEngine): Promise<Check> {
+ try {
+ const mode = await engine.getConfig('search.mode');
+ const overrides = await engine.listConfigKeys('search.');
+ // Exclude search.mode itself + the upgrade-notice state key from the
+ // override roster — they aren't knobs.
+ const overrideKeys = overrides.filter(k => k !== 'search.mode' && k !== 'search.mode_upgrade_notice_shown');
+
+ if (!mode) {
+ return {
+ name: 'search_mode',
+ status: 'ok',
+ message: 'search.mode is unset (using balanced fallback). Run `gbrain search modes` to see what is running and pick a mode explicitly.',
+ };
+ }
+
+ if (overrideKeys.length === 0) {
+ return {
+ name: 'search_mode',
+ status: 'ok',
+ message: `Mode: ${mode} (no per-key overrides — mode bundle is canonical).`,
+ };
+ }
+
+ return {
+ name: 'search_mode',
+ status: 'ok',
+ message: `Mode: ${mode} with ${overrideKeys.length} per-key override(s) (${overrideKeys.join(', ')}). To consolidate to the pure mode bundle: gbrain search modes --reset`,
+ };
+ } catch (e) {
+ return {
+ name: 'search_mode',
+ status: 'ok',
+ message: `Could not read search mode config (${(e as Error).message ?? 'unknown'}).`,
+ };
+ }
+}
+
+/**
+ * v0.32.3 [CDX-6]: surface when retrieval-affecting files have changed
+ * since the most recent published eval. Curated watch-list in
+ * src/core/eval/drift-watch.ts; additions to that list require a
+ * CHANGELOG line.
+ *
+ * Status stays `ok` — operator-facing reminder, not a hard gate.
+ */
+export async function checkEvalDrift(engine: BrainEngine): Promise<Check> {
+ try {
+ const { watchedFilesDrifted } = await import('../../../core/eval/drift-watch.ts');
+ // Working tree vs HEAD (uncommitted retrieval changes). The fuller
+ // version (vs the commit of the last published eval) is wired when
+ // eval_results lands; today we just probe for uncommitted retrieval
+ // changes so the operator sees them before re-running evals.
+ const repoRoot = process.cwd();
+ const drifted = watchedFilesDrifted(repoRoot);
+ if (drifted.length === 0) {
+ return {
+ name: 'eval_drift',
+ status: 'ok',
+ message: 'No retrieval-affecting files changed in working tree.',
+ };
+ }
+ const summary = drifted.slice(0, 3).join(', ') + (drifted.length > 3 ? ', …' : '');
+ return {
+ name: 'eval_drift',
+ status: 'ok',
+ message: `${drifted.length} retrieval-affecting file(s) changed since HEAD: ${summary}. Re-run \`gbrain eval run-all\` after committing these changes.`,
+ };
+ } catch (e) {
+ return {
+ name: 'eval_drift',
+ status: 'ok',
+ message: `Could not probe retrieval drift (${(e as Error).message ?? 'unknown'}).`,
+ };
+ }
+}
+
+/**
+ * v0.31.12 — surface a warn when models.tier.subagent or models.default
+ * resolves to a non-Anthropic provider. The subagent loop in
+ * src/core/minions/handlers/subagent.ts uses Anthropic Messages API with
+ * prompt caching on system + tools; non-Anthropic providers would break
+ * the loop at runtime. This check makes the configuration drift visible
+ * before a job is submitted.
+ */
+
+/**
+ * v0.41.2.1 — embedding_env_override (D9 #9). Defense-in-depth for the
+ * ze-switch env-override class (the 716K-chunk damage incident from
+ * PR #1421's description).
+ *
+ * GBRAIN_EMBEDDING_MODEL / GBRAIN_EMBEDDING_DIMENSIONS win over DB+file
+ * config in loadConfig(). When env disagrees with DB, the gateway embeds
+ * with the env-selected model — even after ze-switch wrote a different
+ * value to DB. This check surfaces that disagreement on every hourly
+ * doctor run so users can spot the drift before the embed sweep corrupts
+ * vectors at the wrong width.
+ *
+ * Uses Check.details (NOT Check.issues, which has a different schema)
+ * so the structured `mismatches[]` payload is consumable by monitoring
+ * pipelines without ad-hoc type widening.
+ *
+ * Cross-surface parity: wired into BOTH buildChecks() and
+ * doctorReportRemote() — operators running thin-client doctor against
+ * a remote brain see the server's env, which is the env that matters
+ * for the embed pipeline running there.
+ */
+export async function checkEmbeddingEnvOverride(engine: BrainEngine): Promise<Check> {
+ const envModel = process.env.GBRAIN_EMBEDDING_MODEL?.trim();
+ const envDim = process.env.GBRAIN_EMBEDDING_DIMENSIONS?.trim();
+ if (!envModel && !envDim) {
+ return {
+ name: 'embedding_env_override',
+ status: 'ok',
+ message: 'no embedding env overrides set',
+ };
+ }
+ let dbModel: string | null = null;
+ let dbDim: string | null = null;
+ try {
+ dbModel = await engine.getConfig('embedding_model');
+ dbDim = await engine.getConfig('embedding_dimensions');
+ } catch (err) {
+ return {
+ name: 'embedding_env_override',
+ status: 'warn',
+ message: `couldn't read DB config to compare env: ${err instanceof Error ? err.message : String(err)}`,
+ };
+ }
+ const mismatches: Array<{ key: string; env: string; db: string }> = [];
+ if (envModel && dbModel && envModel !== dbModel) {
+ mismatches.push({ key: 'GBRAIN_EMBEDDING_MODEL', env: envModel, db: dbModel });
+ }
+ if (envDim && dbDim && envDim !== dbDim) {
+ mismatches.push({ key: 'GBRAIN_EMBEDDING_DIMENSIONS', env: envDim, db: dbDim });
+ }
+ if (mismatches.length === 0) {
+ return {
+ name: 'embedding_env_override',
+ status: 'ok',
+ message: 'env vars agree with DB config',
+ };
+ }
+ return {
+ name: 'embedding_env_override',
+ status: 'warn',
+ message:
+ `${mismatches.length} embedding env var(s) disagree with DB config (env wins at runtime). ` +
+ `Fix: \`unset ${mismatches.map((m) => m.key).join(' ')}\` in your shell profile / .env, ` +
+ `or update DB config to match.`,
+ details: { mismatches },
+ };
+}
+
+export async function checkSubagentCapability(engine: BrainEngine): Promise<Check> {
+ try {
+ const { classifyCapabilities } = await import('../../../core/ai/capabilities.ts');
+ const modelsSubagent = await engine.getConfig('models.subagent');
+ const tierSubagent = await engine.getConfig('models.tier.subagent');
+ const modelsDefault = await engine.getConfig('models.default');
+
+ // Helper: explain a verdict in user-facing terms.
+ const explain = (resolved: string, source: string): Check | null => {
+ const verdict = classifyCapabilities(resolved);
+ if (verdict === 'unusable:no_tools') {
+ return {
+ name: 'subagent_capability',
+ status: 'warn',
+ message:
+ `${source} is "${resolved}" but that provider/model lacks native tool calling. ` +
+ `The subagent loop cannot run on this model — runtime will fall back to claude-sonnet-4-6. ` +
+ `Fix: \`gbrain config set ${source} <provider>:<model-with-tools>\` (e.g. anthropic:claude-sonnet-4-6 or openai:gpt-5.2).`,
+ };
+ }
+ if (verdict === 'unknown') {
+ return {
+ name: 'subagent_capability',
+ status: 'warn',
+ message:
+ `${source} is "${resolved}" which references an unknown provider. ` +
+ `Use a recipe-declared provider. ` +
+ `Fix: \`gbrain config set ${source} anthropic:claude-sonnet-4-6\` or pick another known provider.`,
+ };
+ }
+ if (verdict === 'degraded:no_caching') {
+ return {
+ name: 'subagent_capability',
+ status: 'warn',
+ message:
+ `${source} is "${resolved}" — provider does not support prompt caching. ` +
+ `The subagent loop runs hot (cost scales linearly with conversation length). ` +
+ `For lower cost on long loops, use an Anthropic model: ` +
+ `\`gbrain config set models.tier.subagent anthropic:claude-sonnet-4-6\`.`,
+ };
+ }
+ return null;
+ };
+
+ let resolvedSource: string | null = null;
+ let resolvedModel: string | null = null;
+ if (modelsSubagent) {
+ resolvedSource = 'models.subagent';
+ resolvedModel = modelsSubagent;
+ const issue = explain(modelsSubagent, resolvedSource);
+ if (issue) return issue;
+ } else if (modelsDefault) {
+ resolvedSource = 'models.default';
+ resolvedModel = modelsDefault;
+ const issue = explain(modelsDefault, 'models.default');
+ if (issue) return issue;
+ } else if (tierSubagent) {
+ resolvedSource = 'models.tier.subagent';
+ resolvedModel = tierSubagent;
+ const issue = explain(tierSubagent, resolvedSource);
+ if (issue) return issue;
+ }
+ // v0.37 (T10 / D7) + v0.38 (D7 capability rename): warn when the configured
+ // chat_model is non-Anthropic AND ANTHROPIC_API_KEY isn't set. With
+ // agent.use_gateway_loop=false (the v0.38 default), subagent jobs still
+ // require Anthropic at runtime; without the key, gbrain dream / gbrain
+ // agent run / gbrain autopilot will all fail at job submission. Catches
+ // the post-init drift case the init-time caveat would have shown if init
+ // had been re-run.
+ try {
+ const { loadConfig } = await import('../../../core/config.ts');
+ const cfg = loadConfig();
+ const chatModel = cfg?.chat_model;
+ const { isConfigTruthy } = await import('../../../core/config.ts');
+ const gatewayLoopRaw = await engine.getConfig('agent.use_gateway_loop').catch(() => null);
+ const gatewayLoopEnabled = isConfigTruthy(gatewayLoopRaw);
+ const { isAnthropicProvider } = await import('../../../core/model-config.ts');
+ if (chatModel && !isAnthropicProvider(chatModel) && !process.env.ANTHROPIC_API_KEY && !gatewayLoopEnabled) {
+ return {
+ name: 'subagent_capability',
+ status: 'warn',
+ message:
+ `chat_model is "${chatModel}" (non-Anthropic) and ANTHROPIC_API_KEY is not set. ` +
+ `Subagent features (gbrain dream, gbrain agent run, gbrain autopilot) will fail at job submission ` +
+ `unless agent.use_gateway_loop=true. Chat alone (gbrain think) still works. ` +
+ `Either set ANTHROPIC_API_KEY or enable: \`gbrain config set agent.use_gateway_loop true\`.`,
+ };
+ }
+ } catch { /* loadConfig may throw; fall through */ }
+
+ return {
+ name: 'subagent_capability',
+ status: 'ok',
+ message: resolvedModel && resolvedSource
+ ? `Subagent model resolves via ${resolvedSource} to "${resolvedModel}" with full tool-loop capability`
+ : `Subagent tier resolves to default (claude-sonnet-4-6) — full tool-loop capability`,
+ };
+ } catch (e) {
+ return {
+ name: 'subagent_capability',
+ status: 'warn',
+ message: `Could not check subagent capability: ${e instanceof Error ? e.message : String(e)}`,
+ };
+ }
+}
+
+// v0.38 — `checkSubagentProvider` was renamed to `checkSubagentCapability` (D7).
+// Back-compat alias preserved for any external doctor extensions importing it.
+const checkSubagentProvider = checkSubagentCapability;
+void checkSubagentProvider;
+
+/**
+ * v0.40.1.0 Track D / T7 — pure function form of the nightly_quality_probe_health
+ * check. Extracted from the inline runDoctor block so tests can drive every
+ * branch (disabled / enabled-no-events / enabled-all-pass / enabled-with-failures)
+ * without spinning up the audit JSONL or a real config file.
+ */
+/**
+ * Pure function form of the conversation_parser_probe_health check.
+ * Mirrors computeNightlyQualityProbeHealthCheck: skip-with-hint when the
+ * probe is off and silent, surface the last 7 days of audit events when
+ * it has run, WARN on any non-pass outcome.
+ *
+ * `effectiveEnabled` folds the D10 mode-gate in: explicitly enabled OR
+ * search.mode=tokenmax (where the probe is default-on).
+ */
+export function computeConversationParserProbeHealthCheck(
+ effectiveEnabled: boolean,
+ events: ReadonlyArray<{ outcome: string; ts: string; reason?: string }>,
+): Check {
+ const name = 'conversation_parser_probe_health';
+ if (!effectiveEnabled && events.length === 0) {
+ return {
+ name,
+ status: 'ok',
+ message:
+ 'disabled (opt-in; default-on only for search.mode=tokenmax). Enable with: ' +
+ '`gbrain config set autopilot.conversation_parser_probe.enabled true`',
+ };
+ }
+ if (events.length === 0) {
+ return {
+ name,
+ status: 'ok',
+ message: 'enabled but no probe events in the last 7 days (next run by autopilot; fixtures require a source-checkout install).',
+ };
+ }
+ const bad = events.filter(e => e.outcome !== 'pass');
+ const latest = events[events.length - 1]!;
+ if (bad.length > 0) {
+ return {
+ name,
+ status: 'warn',
+ message:
+ `${bad.length}/${events.length} probe run(s) in the last 7 days did not pass; ` +
+ `latest: ${latest.outcome}${latest.reason ? ` (${latest.reason})` : ''}`,
+ };
+ }
+ return {
+ name,
+ status: 'ok',
+ message: `${events.length} probe run(s) in the last 7 days, all pass (latest ${latest.ts}).`,
+ };
+}
+
+export function computeNightlyQualityProbeHealthCheck(
+ probeEnabled: boolean,
+ events: ReadonlyArray<{ outcome: string; ts: string; detail?: string }>,
+): Check {
+ const name = 'nightly_quality_probe_health';
+ if (!probeEnabled && events.length === 0) {
+ // Quiet skip — surface enable hint only when explicitly asked to.
+ return {
+ name,
+ status: 'ok',
+ message: `disabled (opt-in). Enable with: gbrain config set autopilot.nightly_quality_probe.enabled true`,
+ };
+ }
+ if (events.length === 0) {
+ return {
+ name,
+ status: 'ok',
+ message: `enabled but no probe events in the last 7 days (next run by autopilot).`,
+ };
+ }
+ // v0.40.1.0 Track D (codex CDX-5): any non-PASS outcome is bad signal.
+ // Previously only fail / error / budget_exceeded triggered warn —
+ // no_embedding_key / rate_limited / inconclusive were silently reported
+ // as PASS, hiding real misconfigurations.
+ const bad = events.filter(e => e.outcome !== 'pass');
+ const latest = events[events.length - 1]!;
+ if (bad.length > 0) {
+ const counts =
+ `pass=${events.filter(e => e.outcome === 'pass').length} ` +
+ `fail=${events.filter(e => e.outcome === 'fail').length} ` +
+ `error=${events.filter(e => e.outcome === 'error').length} ` +
+ `inconclusive=${events.filter(e => e.outcome === 'inconclusive').length} ` +
+ `budget=${events.filter(e => e.outcome === 'budget_exceeded').length} ` +
+ `no_embed_key=${events.filter(e => e.outcome === 'no_embedding_key').length} ` +
+ `rate_limited=${events.filter(e => e.outcome === 'rate_limited').length}`;
+ return {
+ name,
+ status: 'warn',
+ message: `${bad.length} non-PASS run${bad.length === 1 ? '' : 's'} in last 7d (${counts}). Latest: ${latest.outcome} at ${latest.ts}${latest.detail ? ` (${latest.detail})` : ''}.`,
+ };
+ }
+ return {
+ name,
+ status: 'ok',
+ message: `${events.length} PASS run${events.length === 1 ? '' : 's'} in last 7d. Latest: ${latest.ts}.`,
+ };
+}
+
+/**
+ * v0.41.11.0 — conversation_facts_backlog doctor check.
+ *
+ * 3-state status:
+ * - SKIPPED when cycle.conversation_facts_backfill.enabled=false
+ * (with paste-ready enable hint). No backlog enumeration; cheap probe.
+ * This is the Eng-v2 C9 "don't degrade health for opt-out users" gate.
+ * - OK when enabled=true AND backlog==0 OR no eligible pages exist.
+ * - WARN when enabled=true AND backlog>10.
+ *
+ * Backlog uses versioned, source-scoped outcomes. Regular pages bind the marker
+ * to pages.updated_at; raw-transcript sidecars carry a SHA-256 snapshot token
+ * and are revalidated by the extraction command before it skips model work.
+ * Legacy/unversioned rows and partial extraction remain in backlog.
+ */
+export async function computeConversationFactsBacklogCheck(
+ engine: BrainEngine,
+): Promise<Check> {
+ const name = 'conversation_facts_backlog';
+ try {
+ // Read the same config the cycle phase reads (Eng-v2 A2 single SoT).
+ const enabledRaw = await engine.getConfig(
+ 'cycle.conversation_facts_backfill.enabled',
+ );
+ const enabled = enabledRaw != null &&
+ !['false', '0', 'no', 'off', ''].includes(enabledRaw.trim().toLowerCase());
+
+ if (!enabled) {
+ return {
+ name,
+ status: 'ok',
+ message:
+ 'disabled (opt-in). Enable with: gbrain config set cycle.conversation_facts_backfill.enabled true',
+ };
+ }
+
+ // Resolve types from same key as cycle phase + CLI default.
+ const typesRaw = await engine.getConfig(
+ 'cycle.conversation_facts_backfill.types',
+ );
+ let types = ['conversation', 'meeting', 'slack', 'email', 'imessage', 'imessage-daily'];
+ if (typesRaw) {
+ try {
+ const parsed = JSON.parse(typesRaw);
+ if (Array.isArray(parsed)) {
+ const filtered = parsed.filter(
+ (t): t is string => typeof t === 'string',
+ );
+ if (filtered.length > 0) types = filtered;
+ }
+ } catch {
+ // fall through to default
+ }
+ }
+
+ const rows = await engine.executeRaw<{
+ backlog: string | number;
+ completed: string | number;
+ non_extractable: string | number;
+ }>(
+ `WITH outcomes AS (
+ SELECT
+ p.source_id,
+ p.slug,
+ MAX(CASE WHEN f.source = 'cli:extract-conversation-facts:terminal:v2' THEN 1 ELSE 0 END) AS completed,
+ MAX(CASE WHEN f.source = 'cli:extract-conversation-facts:non-extractable:v2' THEN 1 ELSE 0 END) AS non_extractable
+ FROM pages p
+ LEFT JOIN facts f
+ ON f.source_id = p.source_id
+ AND f.source_markdown_slug = p.slug
+ AND f.source IN (
+ 'cli:extract-conversation-facts:terminal:v2',
+ 'cli:extract-conversation-facts:non-extractable:v2'
+ )
+ AND p.content_hash IS NOT NULL
+ AND f.source_session = f.source || ':' || p.slug || ':page-' ||
+ p.content_hash || '-' ||
+ COALESCE(TO_CHAR(p.effective_date AT TIME ZONE 'UTC', 'YYYY-MM-DD'), 'none')
+ WHERE p.type = ANY($1::text[])
+ AND p.deleted_at IS NULL
+ AND COALESCE(BTRIM(p.frontmatter->>'raw_transcript'), '') = ''
+ AND p.content_hash IS NOT NULL
+ GROUP BY p.source_id, p.slug
+ )
+ SELECT
+ COALESCE(SUM(CASE WHEN completed = 0 AND non_extractable = 0 THEN 1 ELSE 0 END), 0) AS backlog,
+ COALESCE(SUM(completed), 0) AS completed,
+ COALESCE(SUM(CASE WHEN completed = 0 THEN non_extractable ELSE 0 END), 0) AS non_extractable
+ FROM outcomes`,
+ [types],
+ );
+
+ let backlog = Number(rows[0]?.backlog ?? 0);
+ let completed = Number(rows[0]?.completed ?? 0);
+ let nonExtractable = Number(rows[0]?.non_extractable ?? 0);
+
+ // SQL cannot read raw_transcript files or reproduce the fallback hash for a
+ // legacy NULL content_hash. Recompute those tokens through the command's
+ // canonical verifier. Pagination keeps memory bounded.
+ const { findFreshExtractionOutcomes } = await import(
+ '../../extract-conversation-facts.ts'
+ );
+ const verifierSources = await engine.executeRaw<{ source_id: string }>(
+ `SELECT DISTINCT source_id
+ FROM pages
+ WHERE type = ANY($1::text[])
+ AND deleted_at IS NULL
+ AND (
+ COALESCE(BTRIM(frontmatter->>'raw_transcript'), '') <> ''
+ OR content_hash IS NULL
+ )
+ ORDER BY source_id`,
+ [types],
+ );
+ for (const { source_id: sourceId } of verifierSources) {
+ for (const type of types) {
+ let offset = 0;
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const batch = await engine.listPages({
+ type: type as NonNullable<Parameters<BrainEngine['listPages']>[0]>['type'],
+ sourceId,
+ limit: 10,
+ offset,
+ });
+ if (batch.length === 0) break;
+ const verifyInProcess = batch.filter((page) => {
+ const raw = page.frontmatter?.raw_transcript;
+ return (typeof raw === 'string' && raw.trim().length > 0) ||
+ page.content_hash == null;
+ });
+ if (verifyInProcess.length > 0) {
+ const outcomes = await findFreshExtractionOutcomes(
+ engine,
+ sourceId,
+ verifyInProcess,
+ );
+ for (const page of verifyInProcess) {
+ const outcome = outcomes.get(page.slug);
+ if (outcome === 'complete') completed++;
+ else if (outcome === 'non_extractable') nonExtractable++;
+ else backlog++;
+ }
+ }
+ offset += batch.length;
+ if (batch.length < 10) break;
+ }
+ }
+ }
+
+ if (backlog === 0) {
+ return {
+ name,
+ status: 'ok',
+ message: 'all eligible pages have fresh durable extraction outcomes',
+ details: {
+ backlog,
+ completed,
+ scanned_not_extractable: nonExtractable,
+ types,
+ freshness_rule: 'v2 snapshot token (content hash + effective date or sidecar sha256)',
+ },
+ };
+ }
+
+ if (backlog > 10) {
+ const fixHint =
+ 'gbrain extract-conversation-facts --background --max-cost-usd 5';
+ return {
+ name,
+ status: 'warn',
+ message: `${backlog} eligible pages without extraction. Fix: ${fixHint}`,
+ details: {
+ backlog,
+ completed,
+ scanned_not_extractable: nonExtractable,
+ types,
+ fix_hint: fixHint,
+ freshness_rule: 'v2 snapshot token (content hash + effective date or sidecar sha256)',
+ },
+ };
+ }
+
+ return {
+ name,
+ status: 'ok',
+ message: `${backlog} eligible page(s) below warn threshold (>10)`,
+ details: {
+ backlog,
+ completed,
+ scanned_not_extractable: nonExtractable,
+ types,
+ freshness_rule: 'v2 snapshot token (content hash + effective date or sidecar sha256)',
+ },
+ };
+ } catch (err) {
+ return {
+ name,
+ status: 'warn',
+ message: `backlog query failed: ${(err as Error).message}`,
+ };
+ }
+}
diff --git a/src/commands/doctor/checks/verbs-reflex.ts b/src/commands/doctor/checks/verbs-reflex.ts
new file mode 100644
index 0000000000..1d73290e18
--- /dev/null
+++ b/src/commands/doctor/checks/verbs-reflex.ts
@@ -0,0 +1,141 @@
+/**
+ * Memory-verbs + retrieval-reflex check cluster — verbatim peel from src/commands/doctor.ts (containment
+ * sprint). No behavior change; doctor.ts re-exports every exported symbol
+ * under its original name (tests and external callers import them from
+ * doctor.ts) and buildChecks / doctorReportRemote consume them.
+ */
+import { homedir } from 'os';
+import { join } from 'path';
+import { existsSync, readFileSync } from 'fs';
+import { loadConfig } from '../../../core/config.ts';
+import { reflexEnabled } from '../../../core/context/reflex.ts';
+import { resolveSocketPath } from '../../../core/context/resolve-ipc.ts';
+import type { Check } from '../../doctor.ts';
+
+/**
+ * Retrieval Reflex health (#1981). Read-only, fail-open. The deterministic
+ * pointer layer is on by default; this reports the TRUTH, not an aspiration:
+ * - config/env disabled → warn (pointer layer off)
+ * - heartbeat fired recently → ok, "active" (it's demonstrably working,
+ * whatever path — Postgres/IPC/host)
+ * - enabled, no recent heartbeat → ok if a viable path looks present
+ * (postgres, or pglite serve socket),
+ * else warn (likely inactive — policy
+ * skill carries). Never claims a host
+ * capability it can't observe.
+ * Policy-skill install state is reported in details (it ships into the HOST
+ * repo, so absence in gbrain's own skills dir is expected, not a failure).
+ */
+/**
+ * MEMORY_VERBS v1 (Cathedral 1, E4) — usage-sidecar health. Read-only,
+ * fail-open. Stats only (local JSONL, never uploaded; never source of truth):
+ * - no sidecar file → ok, "no verb calls recorded yet" (fresh install)
+ * - recent events parse → ok, names the last verb + timestamp
+ * - file exists, unreadable→ warn (observability degraded, verbs unaffected)
+ */
+export async function buildMemoryVerbsCheck(): Promise<Check> {
+ const name = 'memory_verbs_usage';
+ try {
+ const { readVerbUsage, usageLogPath } = await import('../../../core/verbs/usage-log.ts');
+ if (!existsSync(usageLogPath())) {
+ return {
+ name,
+ status: 'ok',
+ message: 'no verb calls recorded yet (sidecar appears on first remember/recall/entity/synthesize/forget)',
+ };
+ }
+ const events = await readVerbUsage({ days: 30 });
+ if (events.length === 0) {
+ return { name, status: 'ok', message: 'sidecar present; no verb calls in the last 30 days' };
+ }
+ const last = events[events.length - 1];
+ const byVerb = new Map<string, number>();
+ for (const e of events) byVerb.set(e.verb, (byVerb.get(e.verb) ?? 0) + 1);
+ const mix = [...byVerb.entries()].map(([v, n]) => `${v}:${n}`).join(' ');
+ return {
+ name,
+ status: 'ok',
+ message: `${events.length} verb calls in 30d (${mix}); last ${last.verb} at ${last.ts} — local JSONL only, never uploaded`,
+ };
+ } catch (e) {
+ return {
+ name,
+ status: 'warn',
+ message: `verb usage sidecar unreadable (${e instanceof Error ? e.message : String(e)}) — observability degraded; verbs unaffected`,
+ };
+ }
+}
+
+export function buildRetrievalReflexCheck(skillsDir: string | null): Check {
+ const name = 'retrieval_reflex_health';
+ try {
+ const cfg = loadConfig();
+ const enabled = reflexEnabled(cfg);
+ const engineKind = cfg?.engine ?? 'unknown';
+ const skillInstalled = !!skillsDir && existsSync(join(skillsDir, 'retrieval-reflex', 'SKILL.md'));
+
+ if (!enabled) {
+ return {
+ name,
+ status: 'ok',
+ message: 'retrieval reflex intentionally disabled (config/env) — entity pointer layer off',
+ details: { enabled: false, engine: engineKind, policy_skill_installed: skillInstalled },
+ };
+ }
+
+ // Heartbeat is the authority for "is it firing".
+ const hbPath = join(homedir(), '.gbrain', 'integrations', 'retrieval-reflex', 'heartbeat.jsonl');
+ let lastFired: string | null = null;
+ try {
+ if (existsSync(hbPath)) {
+ const lines = readFileSync(hbPath, 'utf8').trim().split('\n').filter(Boolean);
+ const last = lines.length ? JSON.parse(lines[lines.length - 1]) : null;
+ if (last && typeof last.ts === 'string') lastFired = last.ts;
+ }
+ } catch { /* heartbeat unreadable — treat as never fired */ }
+ const firedRecently =
+ !!lastFired && Date.now() - new Date(lastFired).getTime() < 7 * 24 * 60 * 60 * 1000;
+
+ // Detect a viable resolve path the doctor CAN see (host ctx.brainQuery is invisible).
+ let pathDesc: string;
+ let viablePathVisible: boolean;
+ if (engineKind === 'postgres') {
+ pathDesc = 'postgres direct';
+ viablePathVisible = true;
+ } else if (engineKind === 'pglite' && cfg?.database_path) {
+ const socket = resolveSocketPath(cfg.database_path);
+ viablePathVisible = existsSync(socket);
+ pathDesc = viablePathVisible ? 'pglite via serve IPC' : 'pglite — serve IPC socket not present';
+ } else {
+ pathDesc = `engine ${engineKind}`;
+ viablePathVisible = false;
+ }
+
+ const runtimeMsg = firedRecently
+ ? `active (last fired ${lastFired})`
+ : viablePathVisible
+ ? 'enabled; not observed firing yet'
+ : 'enabled but no observed activity and no visible resolve path (host capability may still supply it; policy skill carries otherwise)';
+
+ const status: Check['status'] = firedRecently || viablePathVisible ? 'ok' : 'warn';
+ const skillHint = skillInstalled
+ ? ''
+ : ' — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`';
+ return {
+ name,
+ status,
+ message: `${pathDesc}; ${runtimeMsg}${skillHint}`,
+ details: {
+ enabled: true,
+ engine: engineKind,
+ path: pathDesc,
+ fired_recently: firedRecently,
+ last_fired: lastFired,
+ policy_skill_installed: skillInstalled,
+ },
+ };
+ } catch (e) {
+ return { name, status: 'warn', message: `could not check: ${(e as Error).message}` };
+ }
+}
+
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
new file mode 100644
index 0000000000..ad790b3359
--- /dev/null
+++ b/src/commands/doctor/report-remote.ts
@@ -0,0 +1,433 @@
+/**
+ * doctorReportRemote — verbatim peel from src/commands/doctor.ts
+ * (containment sprint). The remote/thin-client doctor check registry; its
+ * sole external consumer is the run_doctor op, which dynamic-imports it via
+ * the doctor.ts re-export.
+ *
+ * NOTE: '../doctor.ts' imports this module (the re-export seam), so the
+ * import below is circular. This is safe: every binding pulled from
+ * doctor.ts is a hoisted function declaration referenced only at call time
+ * inside doctorReportRemote, never during module evaluation.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+import { LATEST_VERSION } from '../../core/migrate.ts';
+import { loadConfig } from '../../core/config.ts';
+import { loadCompletedMigrations } from '../../core/preferences.ts';
+import { compareVersions } from '../migrations/index.ts';
+import { resolveHoursEnv } from '../../core/env-number.ts';
+import {
+ type Check,
+ type DoctorReport,
+ computeDoctorReport,
+ checkPgliteScratchProbe,
+ computeQueueHealthCheck,
+ computeWedgedQueueCheck,
+ computeAutopilotFanoutConcurrencyCheck,
+ checkSubagentHealth,
+ checkBatchRetryHealth,
+ checkEmbeddingEnvOverride,
+ checkSubagentCapability,
+ checkVolunteerChannels,
+ checkSyncFreshness,
+ checkSyncConsolidation,
+ checkPoolBudget,
+ checkLinksExtractionLag,
+ checkSearchMode,
+ checkEvalDrift,
+ checkRerankerHealth,
+ checkGraphSignalsCoverage,
+ checkBrainstormHealth,
+ checkAbandonedThreads,
+ checkCalibrationFreshness,
+ checkGradeConfidenceDrift,
+ checkVoiceGateHealth,
+ checkContextualRetrievalCoverage,
+ checkHiddenBySearchPolicy,
+ checkLinkResolutionOpportunity,
+ checkFederationHealth,
+ checkSelfUpgradeHealth,
+} from '../doctor.ts';
+import {
+ checkSchemaPackActive,
+ checkSchemaPackConsistency,
+ checkSchemaPackSourceDrift,
+} from './schema-pack-checks.ts';
+
+// Same alias the local doctor keeps for its own freshness checks; the alias
+// is a private one-liner in doctor.ts's check-fn library, so this module
+// carries its own copy rather than widening that surface.
+const _resolveSyncFreshnessHours = resolveHoursEnv;
+
+export async function doctorReportRemote(
+ engine: BrainEngine,
+ opts: { sourceIds?: string[] } = {},
+): Promise<DoctorReport> {
+ const checks: Check[] = [];
+
+ // 1. Connection
+ let pageCount = 0;
+ try {
+ const stats = await engine.getStats();
+ pageCount = stats.page_count ?? 0;
+ checks.push({
+ name: 'connection',
+ status: 'ok',
+ message: `Connected, ${pageCount} pages`,
+ });
+ } catch (e) {
+ checks.push({
+ name: 'connection',
+ status: 'fail',
+ message: e instanceof Error ? e.message : String(e),
+ });
+ // #2674: on PGLite, a dead connection is exactly the ambiguous case the
+ // scratch probe exists for — pay its cold start only on this failure path.
+ // Unlike buildChecks (where the connect error was swallowed upstream), the
+ // real error IS in hand here: classify it, and only let the probe assert
+ // store damage on a damage-class verdict (wasm-abort/corrupt) — a lock or
+ // config refusal classifies 'unknown' and gets the hedged message.
+ if (engine.kind === 'pglite') {
+ let realStorePath: string | undefined;
+ try { realStorePath = loadConfig()?.database_path; } catch { /* no config */ }
+ let storeDamageEvidence = false;
+ try {
+ const { classifyPgliteInitError, stringifyPgliteInitError } = await import('../../core/pglite-engine.ts');
+ const verdict = classifyPgliteInitError(stringifyPgliteInitError(e));
+ storeDamageEvidence = verdict === 'wasm-abort' || verdict === 'corrupt';
+ } catch { /* classifier unavailable — stay hedged (fail-closed) */ }
+ checks.push(await checkPgliteScratchProbe({ realInitFailed: true, storeDamageEvidence, realStorePath }));
+ }
+ // Without a connection, every other check is meaningless — short-circuit.
+ return computeDoctorReport(checks);
+ }
+
+ // 2. Schema version. Uses engine.getConfig('version') — the same engine-
+ // agnostic API the local doctor uses, works on both Postgres and PGLite.
+ try {
+ const versionStr = await engine.getConfig('version');
+ const version = parseInt(versionStr || '0', 10);
+ if (version >= LATEST_VERSION) {
+ checks.push({ name: 'schema_version', status: 'ok', message: `Version ${version} (latest: ${LATEST_VERSION})` });
+ } else if (version === 0) {
+ checks.push({
+ name: 'schema_version',
+ status: 'fail',
+ message: `No schema version recorded. Migrations never ran. Run \`gbrain apply-migrations --yes\` on the host.`,
+ });
+ } else {
+ checks.push({
+ name: 'schema_version',
+ status: 'warn',
+ message: `Version ${version}, latest is ${LATEST_VERSION}. Run \`gbrain apply-migrations --yes\` on the host.`,
+ });
+ }
+ } catch {
+ checks.push({ name: 'schema_version', status: 'warn', message: 'Could not check schema version' });
+ }
+
+ // 2b. #2038: idx_timeline_dedup shape. A renumbered-during-merge migration
+ // (v102) can be recorded-as-applied without its DDL running, leaving the
+ // 3-column index in place — every timeline write then fails the 4-column
+ // ON CONFLICT. The version counter can't see this, so check the index SHAPE.
+ try {
+ const { checkTimelineDedupIndex } = await import('../../core/timeline-dedup-repair.ts');
+ const idx = await checkTimelineDedupIndex(engine);
+ if (!idx.tablePresent || !idx.needsRepair) {
+ checks.push({
+ name: 'timeline_dedup_index',
+ status: 'ok',
+ message: idx.tablePresent ? 'idx_timeline_dedup has the 4-column shape' : 'no timeline_entries table yet',
+ });
+ } else {
+ checks.push({
+ name: 'timeline_dedup_index',
+ status: 'fail',
+ message:
+ `idx_timeline_dedup is ${idx.indexPresent ? `(${idx.columns.join(', ')})` : 'absent'}, ` +
+ `expected (page_id, date, summary, source) — timeline writes are failing (#2038). ` +
+ `Run \`gbrain apply-migrations --force-schema\` to heal it.`,
+ });
+ }
+ } catch {
+ checks.push({ name: 'timeline_dedup_index', status: 'warn', message: 'Could not check idx_timeline_dedup shape' });
+ }
+
+ // v0.42.x — Life Chronicle (#2390): orphaned event projections. Reads already
+ // hide projections whose event page is soft-deleted (read-time correctness);
+ // this always-run probe surfaces the cleanup backlog. Keyed off the real
+ // schema (event_page_id), NOT a migration verify-hook, per
+ // migration-verify-hook-never-runs-on-stamped-brains.
+ try {
+ const orphans = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM timeline_entries te
+ JOIN pages ep ON ep.id = te.event_page_id
+ WHERE te.event_page_id IS NOT NULL AND ep.deleted_at IS NOT NULL`,
+ );
+ const n = Number(orphans[0]?.n ?? 0);
+ checks.push(
+ n === 0
+ ? { name: 'chronicle_projection_health', status: 'ok', message: 'No orphaned event projections' }
+ : {
+ name: 'chronicle_projection_health',
+ status: 'warn',
+ message:
+ `${n} timeline projection(s) point to soft-deleted event pages ` +
+ '(hidden at read time; clean up with `gbrain integrity auto`).',
+ },
+ );
+ } catch {
+ checks.push({ name: 'chronicle_projection_health', status: 'ok', message: 'no event projections yet' });
+ }
+
+ // 3. Brain score
+ try {
+ const health = await engine.getHealth();
+ const score = health.brain_score ?? 0;
+ checks.push({
+ name: 'brain_score',
+ status: score >= 70 ? 'ok' : score >= 50 ? 'warn' : 'fail',
+ message: `Brain score ${score}/100`,
+ });
+ } catch (e) {
+ checks.push({
+ name: 'brain_score',
+ status: 'warn',
+ message: `Could not compute: ${e instanceof Error ? e.message : String(e)}`,
+ });
+ }
+
+ // 3b. Migration wedge hint (v0.31.8 — D14 + D19). The brain server's
+ // filesystem holds the migration ledger; the wedge condition (>=3 consecutive
+ // partials with no later complete) needs the force-retry hint, not plain
+ // --yes. Same shape as the local doctor at line ~336.
+ try {
+ const completed = loadCompletedMigrations();
+ const byVersion = new Map<string, { complete: boolean; partial: boolean }>();
+ for (const entry of completed) {
+ const seen = byVersion.get(entry.version) ?? { complete: false, partial: false };
+ if (entry.status === 'complete') seen.complete = true;
+ if (entry.status === 'partial') seen.partial = true;
+ byVersion.set(entry.version, seen);
+ }
+ const completedVersions = Array.from(byVersion.entries()).filter(([, s]) => s.complete).map(([v]) => v);
+ const stuck = Array.from(byVersion.entries())
+ .filter(([v, s]) => {
+ if (!s.partial || s.complete) return false;
+ const supersededBy = completedVersions.find(cv => compareVersions(cv, v) >= 0);
+ return supersededBy === undefined;
+ })
+ .map(([v]) => v);
+ const wedged: string[] = [];
+ for (const v of stuck) {
+ const partialCount = completed.filter(e => e.version === v && e.status === 'partial').length;
+ if (partialCount >= 3) wedged.push(v);
+ }
+ if (wedged.length > 0) {
+ const cmd = wedged.map(v => `gbrain apply-migrations --force-retry ${v}`).join(' && ');
+ checks.push({
+ name: 'minions_migration',
+ status: 'fail',
+ message: `WEDGED MIGRATION(s) on brain host: ${wedged.join(', ')}. Run on the host: ${cmd}`,
+ });
+ } else if (stuck.length > 0) {
+ checks.push({
+ name: 'minions_migration',
+ status: 'fail',
+ message: `MINIONS HALF-INSTALLED on brain host: ${stuck.join(', ')}. Run on the host: gbrain apply-migrations --yes`,
+ });
+ }
+ } catch {
+ // Best-effort. A broken JSONL on the brain server should not stop the
+ // remote doctor.
+ }
+
+ // 4. Sync failures (file-plane ledger; see src/core/sync-failure-ledger.ts).
+ // issue #1939: read via the shared loader + severity decision so this remote
+ // surface agrees with the local buildChecks emitter by construction. Stays
+ // subprocess-free (file read + Date.parse only, no git), preserving the remote
+ // trust boundary. Escalates to FAIL when a stuck bookmark has blocked past the
+ // sync-freshness fail cadence or unresolved count is large.
+ try {
+ const { loadSyncFailures, decideSyncFailureSeverity } = await import('../../core/sync.ts');
+ const entries = loadSyncFailures();
+ const failHours = _resolveSyncFreshnessHours('GBRAIN_SYNC_FRESHNESS_FAIL_HOURS', 72);
+ const sev = decideSyncFailureSeverity({ entries, nowMs: Date.now(), failHours });
+ const msg =
+ sev.unresolved === 0
+ ? 'No unresolved sync failures'
+ : `${sev.unresolved} unresolved sync failure(s)` +
+ (sev.auto_skipped > 0 ? ` (${sev.auto_skipped} auto-skipped — pages NOT indexed)` : '') +
+ ` — run \`gbrain sync --skip-failed\` on the host to acknowledge`;
+ checks.push({ name: 'sync_failures', status: sev.status, message: msg });
+ } catch {
+ checks.push({ name: 'sync_failures', status: 'ok', message: 'No failures recorded' });
+ }
+
+ // 4b. Multi-source drift (v0.31.8 — D8 + D14). Same shape as the local
+ // doctor's check at the same name. Runs server-side; the result is
+ // returned to the thin-client over MCP.
+ try {
+ const { findMisroutedPages } = await import('../../core/multi-source-drift.ts');
+ const sources = await engine.executeRaw<{ id: string; local_path: string | null }>(
+ `SELECT id, local_path FROM sources`,
+ );
+ const nonDefaultWithPath = sources.filter(s => s.id !== 'default' && s.local_path);
+ if (sources.length > 1 && nonDefaultWithPath.length > 0) {
+ const result = await findMisroutedPages(
+ engine,
+ nonDefaultWithPath.map(s => ({ id: s.id, local_path: s.local_path as string })),
+ );
+ if (result.walk_truncated) {
+ checks.push({
+ name: 'multi_source_drift',
+ status: 'warn',
+ message: 'Multi-source drift check skipped — FS walk hit limit/timeout on the brain server.',
+ });
+ } else if (result.count > 0) {
+ const sampleStr = result.sample.map(s => `${s.slug} (intended=${s.intended_source})`).join(', ');
+ checks.push({
+ name: 'multi_source_drift',
+ status: 'warn',
+ message:
+ `${result.count} page slug(s) appear at 'default' but NOT at the intended source ` +
+ `(e.g., ${sampleStr}). Likely pre-v0.30.3 misroutes OR an incomplete initial sync. ` +
+ `Verify on the brain host: \`gbrain sources status\` then \`gbrain sync --source <id> --full\`.`,
+ });
+ } else {
+ checks.push({
+ name: 'multi_source_drift',
+ status: 'ok',
+ message: 'No cross-source slug drift detected.',
+ });
+ }
+ }
+ } catch {
+ // Best-effort, like the rest of doctorReportRemote.
+ }
+
+ // 5. Queue health (Postgres-only). PGLite has no minion_jobs in the same
+ // shape; skip the check there with an informational message.
+ checks.push(await computeQueueHealthCheck(engine));
+
+ // issue #1801 — wedged_queue (cross-surface parity with buildChecks).
+ checks.push(await computeWedgedQueueCheck(engine));
+
+ // #2194 fix #5 — warn when autopilot fan-out exceeds worker concurrency.
+ checks.push(await computeAutopilotFanoutConcurrencyCheck(engine));
+
+ // v0.41 Bug 2 / Eng D8 — subagent_health surfaces rate-lease pressure to the operator.
+ checks.push(await checkSubagentHealth(engine));
+
+ // v0.41.18.0 — batch_retry_health (cross-surface parity with buildChecks).
+ // Surfaces Supavisor circuit-breaker incidents over MCP so remote operators
+ // see the same signal local doctor surfaces.
+ checks.push(await checkBatchRetryHealth(engine));
+
+ // v0.41.2.1 — embedding_env_override (cross-surface parity with
+ // buildChecks). Surfaces when GBRAIN_EMBEDDING_* env vars disagree
+ // with DB config; closes the silent-override class that caused the
+ // 716K-chunk damage incident from PR #1421's description.
+ checks.push(await checkEmbeddingEnvOverride(engine));
+
+ // v0.31.12 subagent runtime enforcement (Layer 3 of 3 — Codex F13).
+ // The subagent loop requires native tool-calling. If models.subagent,
+ // models.tier.subagent, or models.default resolves to a limited provider, warn here
+ // so the user sees it at the next `gbrain doctor` run instead of at the
+ // next subagent job submission. (Layers 1+2 also enforce — this is the
+ // surfacing layer.)
+ checks.push(await checkSubagentCapability(engine));
+
+ // Harness hook adapters — per-channel push-context visibility (sibling of
+ // the engine-free retrieval_reflex_health heartbeat check). Source-scoped
+ // for remote callers (cross-model P1): a source-bound token must not see
+ // other sources' activity counts/timestamps.
+ checks.push(await checkVolunteerChannels(engine, { sourceIds: opts.sourceIds }));
+
+ // 6. Sync freshness check
+ checks.push(await checkSyncFreshness(engine));
+
+ // v0.41.19.0 (Issue 5): sync --all consolidation nudge for multi-source brains.
+ checks.push(await checkSyncConsolidation(engine));
+
+ // v0.42.x (#1794, 4A): pool-budget nudge when GBRAIN_MAX_CONNECTIONS is set.
+ checks.push(await checkPoolBudget(engine));
+
+ // v0.42.7 (#1696): link-extraction lag. Strictly SQL (single indexed COUNT),
+ // safe on the thin-client/remote path — remote operators on checkout-less
+ // Postgres brains are exactly who can't otherwise see the extraction backlog.
+ // Brain-wide here (remote --source scoping is a separate TODO, like orphan_ratio).
+ checks.push(await checkLinksExtractionLag(engine));
+
+ // v0.39 T7 + T9 — schema-pack health checks (3 checks per v0.38 plan):
+ // schema_pack_active — active pack resolves cleanly
+ // schema_pack_consistency — % of pages typed against active pack
+ // schema_pack_source_drift — per-source pack divergence
+ checks.push(await checkSchemaPackActive(engine));
+ checks.push(await checkSchemaPackConsistency(engine));
+ checks.push(await checkSchemaPackSourceDrift(engine));
+
+ // 7. v0.32.3 search-lite mode + per-key drift surface.
+ checks.push(await checkSearchMode(engine));
+
+ // 8. v0.32.3 eval_drift: retrieval-affecting files changed since last
+ // eval run? Non-blocking — surfaces as ok + hint.
+ checks.push(await checkEvalDrift(engine));
+
+ // 9. v0.35.0.0+ reranker_health: surfaces rerank-audit failures from
+ // ~/.gbrain/audit/rerank-failures-*.jsonl. Failure-only (no success
+ // logging on the search hot path per CDX2-F22). Reads
+ // search.reranker.enabled FIRST so absence-of-failures means different
+ // things when reranker is on vs off.
+ checks.push(await checkRerankerHealth(engine));
+
+ // 9a. v0.40.4 graph_signals_coverage: when graph_signals is enabled
+ // (via mode bundle default or explicit config override), surface
+ // whether link density is high enough for the signal to fire
+ // meaningfully. <10% inbound coverage warns; >=30% ok with metric.
+ checks.push(await checkGraphSignalsCoverage(engine));
+
+ // 9b. v0.37.0 brainstorm_health: surfaces three brainstorm/lsd readiness
+ // signals: (a) migration v79 applied (last_retrieved_at column exists),
+ // (b) calibration cold-start status (active_bias_tags empty), (c)
+ // search.track_retrieval enabled/disabled. Each surfaces a paste-ready
+ // fix hint.
+ checks.push(await checkBrainstormHealth(engine));
+
+ // 10. v0.36.1.0 Hindsight calibration wave (T12) — four new checks:
+ // - abandoned_threads: high-conviction takes never revisited
+ // - calibration_freshness: profile is older than 7 days
+ // - grade_confidence_drift: judge self-reported confidence vs actual accuracy (CDX-11 mitigation)
+ // - voice_gate_health: voice gate failure rate over the last 7 days
+ checks.push(await checkAbandonedThreads(engine));
+ checks.push(await checkCalibrationFreshness(engine));
+ checks.push(await checkGradeConfidenceDrift(engine));
+ checks.push(await checkVoiceGateHealth(engine));
+
+ // 11. v0.40.3.0 contextual_retrieval_coverage — surfaces pages with
+ // - chunker_version drift (pre-v40 pages not yet re-embedded)
+ // - contextual_retrieval_mode IS NULL (mode never evaluated)
+ // - synopsis-failures audit JSONL entries from the last 7 days
+ checks.push(await checkContextualRetrievalCoverage(engine));
+
+ // issue #1777 — hidden_by_search_policy: chunked pages withheld from default
+ // search by the hard-exclude prefix policy. Pure SQL COUNT, safe on the
+ // remote/thin-client path.
+ checks.push(await checkHiddenBySearchPolicy(engine));
+
+ // 11a. issue #972 link_resolution_opportunity — same check the local
+ // doctor runs at the equivalent slot in buildChecks. Mirrored for
+ // thin-client parity so `gbrain remote doctor` sees the same hint.
+ checks.push(await checkLinkResolutionOpportunity(engine));
+
+ // 12. v0.40.5.0 Federated Sync v2 (T12) — federation_health:
+ // - Per-source lag, embed coverage, failed-job rate.
+ // - Single-source brain short-circuits to ok.
+ // - Three-state: ok / warn / fail.
+ checks.push(await checkFederationHealth(engine));
+
+ // 13. v0.42 self_upgrade_health: mode, whether behind, recent failures.
+ // File-plane only (no engine) — works on thin clients too.
+ checks.push(checkSelfUpgradeHealth());
+
+ return computeDoctorReport(checks);
+}
diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.ts
new file mode 100644
index 0000000000..56fc169444
--- /dev/null
+++ b/src/commands/doctor/schema-pack-checks.ts
@@ -0,0 +1,140 @@
+/**
+ * Schema-pack doctor checks — verbatim peel from src/commands/doctor.ts
+ * (containment sprint). No behavior change; doctor.ts re-exports
+ * multiSourceDriftAdvice and doctorReportRemote consumes the three checks.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+import type { Check } from '../doctor.ts';
+
+// =================================================================
+// v0.39 T7 + T9 — schema-pack doctor checks
+// =================================================================
+// Three checks per v0.38 CEO plan that never shipped at v0.38 time:
+// schema_pack_active — does the active pack resolve cleanly?
+// schema_pack_consistency — what % of pages match the active pack?
+// schema_pack_source_drift — do per-source packs disagree?
+// All three are warn-only; never fail-block.
+
+export async function checkSchemaPackActive(engine: BrainEngine): Promise<Check> {
+ try {
+ const { loadActivePack } = await import('../../core/schema-pack/load-active.ts');
+ const { loadConfig } = await import('../../core/config.ts');
+ const pack = await loadActivePack({ cfg: loadConfig(), remote: false });
+ return {
+ name: 'schema_pack_active',
+ status: 'ok',
+ message: `Active pack: ${pack.manifest.name} v${pack.manifest.version} (${pack.manifest.page_types.length} types, ${pack.manifest.link_types?.length ?? 0} link verbs)`,
+ };
+ } catch (e) {
+ return {
+ name: 'schema_pack_active',
+ status: 'warn',
+ message: `Active pack failed to resolve: ${(e as Error).message}. Run \`gbrain schema active\` to debug.`,
+ };
+ }
+}
+
+export async function checkSchemaPackConsistency(engine: BrainEngine): Promise<Check> {
+ try {
+ const rows = await engine.executeRaw<{ src: string; total: string | number; untyped: string | number }>(
+ `SELECT
+ source_id AS src,
+ COUNT(*)::text AS total,
+ COUNT(*) FILTER (WHERE type IS NULL OR type = '')::text AS untyped
+ FROM pages
+ WHERE deleted_at IS NULL
+ GROUP BY source_id
+ ORDER BY source_id`,
+ );
+ if (rows.length === 0) {
+ return { name: 'schema_pack_consistency', status: 'ok', message: 'No pages in any source — schema consistency N/A.' };
+ }
+ let worstPct = 0;
+ let worstSrc = '';
+ let worstUntyped = 0;
+ let worstTotal = 0;
+ for (const r of rows) {
+ const total = Number(r.total);
+ const untyped = Number(r.untyped);
+ if (total === 0) continue;
+ const pct = untyped / total;
+ if (pct > worstPct) {
+ worstPct = pct;
+ worstSrc = r.src;
+ worstUntyped = untyped;
+ worstTotal = total;
+ }
+ }
+ if (worstPct === 0) {
+ return { name: 'schema_pack_consistency', status: 'ok', message: 'All pages match the active schema pack across every source.' };
+ }
+ const pctStr = (worstPct * 100).toFixed(1);
+ if (worstPct >= 0.1) {
+ return {
+ name: 'schema_pack_consistency',
+ status: 'warn',
+ message: `Source \`${worstSrc}\`: ${worstUntyped} of ${worstTotal} pages (${pctStr}%) have no type matching the active pack. Run \`gbrain schema detect --source ${worstSrc}\` to propose a pack matching your content shape.`,
+ };
+ }
+ return {
+ name: 'schema_pack_consistency',
+ status: 'ok',
+ message: `${pctStr}% untyped at worst (source \`${worstSrc}\`) — under the 10% warn threshold.`,
+ };
+ } catch (e) {
+ return {
+ name: 'schema_pack_consistency',
+ status: 'ok',
+ message: `Skipped: ${(e as Error).message}`,
+ };
+ }
+}
+
+export async function checkSchemaPackSourceDrift(engine: BrainEngine): Promise<Check> {
+ try {
+ // Compare per-source schema_pack overrides (tier 3 DB config) to detect
+ // multi-source brains where different sources point at conflicting packs.
+ const rows = await engine.executeRaw<{ key: string; value: string }>(
+ `SELECT key, value FROM config WHERE key LIKE 'schema_pack.source.%'`,
+ );
+ if (rows.length === 0) {
+ return { name: 'schema_pack_source_drift', status: 'ok', message: 'No per-source pack overrides — drift N/A.' };
+ }
+ const distinctPacks = new Set(rows.map((r) => r.value).filter(Boolean));
+ if (distinctPacks.size <= 1) {
+ return { name: 'schema_pack_source_drift', status: 'ok', message: `${rows.length} per-source overrides; all point at the same pack.` };
+ }
+ return {
+ name: 'schema_pack_source_drift',
+ status: 'warn',
+ message: `Per-source pack divergence detected: ${distinctPacks.size} distinct packs across ${rows.length} sources. Run \`gbrain sources list\` then \`gbrain schema active --source <id>\` per source to audit.`,
+ };
+ } catch (e) {
+ return {
+ name: 'schema_pack_source_drift',
+ status: 'ok',
+ message: `Skipped: ${(e as Error).message}`,
+ };
+ }
+}
+
+/**
+ * #1123 — multi_source_drift remediation advice. Exported so the regression
+ * test can pin that it only references CLI surfaces that actually exist
+ * (the pre-fix text pointed at 'gbrain sources rehome', which was never
+ * built, and at 'gbrain delete <slug>' without explaining that delete
+ * targets the ACTIVE source — following it literally on a multi-source
+ * brain deletes the correctly-routed row).
+ */
+export function multiSourceDriftAdvice(count: number, sampleStr: string): string {
+ return (
+ `${count} page slug(s) appear at 'default' but NOT at the intended source ` +
+ `(e.g., ${sampleStr}). Two possible causes: (1) pre-v0.30.3 putPage misroutes; ` +
+ `(2) the intended source never completed initial sync and the default page is unrelated. ` +
+ `Verify with 'gbrain sources status', then re-sync with ` +
+ `'gbrain sync --source <id> --full' (reconciles drift without deleting data). ` +
+ `If a misrouted default-source row remains after re-sync, remove it with ` +
+ `'GBRAIN_SOURCE=default gbrain delete <slug>' — delete targets the active source, ` +
+ `so pin it to 'default' explicitly.`
+ );
+}
diff --git a/src/commands/doctor/skill-checks.ts b/src/commands/doctor/skill-checks.ts
new file mode 100644
index 0000000000..3d1a89be49
--- /dev/null
+++ b/src/commands/doctor/skill-checks.ts
@@ -0,0 +1,408 @@
+/**
+ * Skill-check cluster — verbatim peel from src/commands/doctor.ts
+ * (containment sprint). No behavior change; doctor.ts re-exports every
+ * symbol (tests and scripts/live-brain-first-check.ts import them from
+ * doctor.ts) and buildChecks consumes them.
+ */
+import { join, resolve as resolvePath } from 'path';
+import { existsSync, readFileSync, readdirSync } from 'fs';
+import type { BrainEngine } from '../../core/engine.ts';
+import {
+ SKILLS_MANIFEST_FILENAME,
+ verifySkillsManifest,
+ type SkillsManifest,
+} from '../../core/skills-integrity.ts';
+import { loadOrDeriveManifest } from '../../core/skill-manifest.ts';
+import { computeSkillCurrency } from '../../core/skillpack/skill-currency.ts';
+import { findGbrainRoot } from '../../core/skillpack/bundle.ts';
+import { checkPreconditions, type PreconditionContext } from '../../core/skillpack/preconditions.ts';
+import { parseSkillFrontmatter } from '../../core/skill-frontmatter.ts';
+import {
+ analyzeSkillBrainFirst,
+ buildBrainFirstSummaryLine,
+ type BrainFirstAnalysis,
+} from '../../core/skill-brain-first.ts';
+import {
+ loadSnapshot,
+ writeSnapshotAtomically,
+ diffAgainstSnapshot,
+ appendAuditEventsForTransitions,
+} from '../../core/audit-skill-brain-first.ts';
+import type { Check } from '../doctor.ts';
+
+/** Quick skill conformance check — frontmatter + required sections */
+export function skillConformanceCheck(skillsDir: string): Check {
+ try {
+ // Host workspaces are allowed to omit a gbrain-specific manifest. Keep
+ // conformance aligned with resolver_health and skill_brain_first by using
+ // the canonical fallback that derives entries from direct SKILL.md files.
+ const manifest = loadOrDeriveManifest(skillsDir);
+ const skills = manifest.skills;
+ let passing = 0;
+ const failing: string[] = [];
+
+ for (const skill of skills) {
+ const skillPath = join(skillsDir, skill.path);
+ if (!existsSync(skillPath)) {
+ failing.push(`${skill.name}: file missing`);
+ continue;
+ }
+ const content = readFileSync(skillPath, 'utf-8');
+ // Check frontmatter exists
+ if (!content.startsWith('---')) {
+ failing.push(`${skill.name}: no frontmatter`);
+ continue;
+ }
+ passing++;
+ }
+
+ if (failing.length === 0) {
+ const derivedNote = manifest.derived ? ' (derived from SKILL.md files)' : '';
+ return { name: 'skill_conformance', status: 'ok', message: `${passing}/${skills.length} skills pass${derivedNote}` };
+ }
+ return {
+ name: 'skill_conformance',
+ status: 'warn',
+ message: `${passing}/${skills.length} pass. Failing: ${failing.join(', ')}`,
+ };
+ } catch {
+ return { name: 'skill_conformance', status: 'warn', message: 'Could not load or derive skills manifest' };
+ }
+}
+
+/**
+ * v0.36.x skill_brain_first doctor check (supersedes PR #1206).
+ *
+ * Walks the skills manifest, runs the pure `analyzeSkillBrainFirst()`
+ * helper on each, surfaces violators with structured issues[]. Snapshot-
+ * diff against the previous run drives audit JSONL writes (transition-
+ * only) — stable brains produce zero audit churn per doctor invocation.
+ *
+ * Exit shape:
+ * - 0 violators → status: 'ok', message: '<n> skills compliant or exempt'
+ * - any violator → status: 'warn', message + per-skill summary lines +
+ * formerly-EXEMPT_SKILLS hint when applicable (CMT1 replaces the
+ * dropped upgrade migration with a guided opt-in)
+ *
+ * Test seam: pure function, no `process.exit`. Direct call from tests
+ * with a synthetic skills dir under tempdir.
+ */
+/**
+ * Skills-manifest integrity check (#159). Verifies the skills tree against
+ * the committed skills.lock.json tamper-evidence manifest. Advisory only:
+ * drift is a WARN (local edits are legitimate), and a missing/unreadable
+ * manifest is an ok/skip — a user's workspace skills dir or a compiled
+ * binary far from the repo has no manifest, and that is not a problem.
+ */
+export function skillsManifestIntegrityCheck(skillsDir: string): Check {
+ const name = 'skills_manifest_integrity';
+ const manifestPath = join(skillsDir, SKILLS_MANIFEST_FILENAME);
+ if (!existsSync(manifestPath)) {
+ return { name, status: 'ok', message: `No ${SKILLS_MANIFEST_FILENAME} in ${skillsDir} — integrity check not applicable` };
+ }
+ let drift: ReturnType<typeof verifySkillsManifest>;
+ let tracked: number;
+ try {
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as SkillsManifest;
+ tracked = Object.keys(manifest).length;
+ drift = verifySkillsManifest(skillsDir, manifest);
+ } catch (err) {
+ // Fail-safe: an unreadable/unparseable manifest or a filesystem error
+ // skips the check rather than warning — this check must never block.
+ const msg = err instanceof Error ? err.message : String(err);
+ return { name, status: 'ok', message: `Could not verify ${SKILLS_MANIFEST_FILENAME} (${msg}) — integrity check skipped` };
+ }
+ const total = drift.modified.length + drift.missing.length + drift.extra.length;
+ if (total === 0) {
+ return { name, status: 'ok', message: `${tracked} bundled skill files match ${SKILLS_MANIFEST_FILENAME}` };
+ }
+ const sample = (files: string[]): string =>
+ files.slice(0, 5).join(', ') + (files.length > 5 ? `, … +${files.length - 5} more` : '');
+ const parts: string[] = [];
+ if (drift.modified.length > 0) parts.push(`${drift.modified.length} modified (${sample(drift.modified)})`);
+ if (drift.missing.length > 0) parts.push(`${drift.missing.length} missing (${sample(drift.missing)})`);
+ if (drift.extra.length > 0) parts.push(`${drift.extra.length} extra (${sample(drift.extra)})`);
+ return {
+ name,
+ status: 'warn',
+ message:
+ `skills/ drifted from ${SKILLS_MANIFEST_FILENAME} (advisory — local edits are fine): ${parts.join('; ')}. ` +
+ `If intentional, regenerate: bun run scripts/generate-skills-manifest.ts`,
+ details: { modified: drift.modified, missing: drift.missing, extra: drift.extra },
+ };
+}
+
+/**
+ * Skill currency check — compares the built-in skills bundle against what
+ * the downstream workspace has scaffolded and surfaces NEW skills the user
+ * doesn't have yet. Advisory: `new` skills are a WARN (you're missing
+ * shipped capability); `drifted` skills are informational only (local edits
+ * are legitimate — the ownership model). No-ops when running inside the
+ * gbrain repo itself (bundle == install, always current) or when the bundle
+ * can't be located.
+ */
+export function skillCurrencyCheck(skillsDir: string): Check {
+ const name = 'skill_currency';
+ const targetWorkspace = resolvePath(skillsDir, '..');
+ const gbrainRoot = findGbrainRoot();
+ if (!gbrainRoot) {
+ return { name, status: 'ok', message: 'skill currency not applicable (no bundled skills pack found)' };
+ }
+ if (resolvePath(targetWorkspace) === resolvePath(gbrainRoot)) {
+ return { name, status: 'ok', message: 'skill currency not applicable (running inside the gbrain repo)' };
+ }
+ let report: ReturnType<typeof computeSkillCurrency>;
+ try {
+ report = computeSkillCurrency({ gbrainRoot, targetWorkspace });
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { name, status: 'ok', message: `skill currency check skipped (${msg})` };
+ }
+ const { counts, skills } = report;
+ const sample = (status: 'new' | 'drifted'): string => {
+ const s = skills.filter(k => k.status === status).map(k => k.slug);
+ return s.slice(0, 8).join(', ') + (s.length > 8 ? `, … +${s.length - 8} more` : '');
+ };
+ if (counts.new === 0) {
+ const drift = counts.drifted > 0 ? ` (${counts.drifted} drifted — local edits are fine)` : '';
+ return { name, status: 'ok', message: `${counts.current}/${counts.total} built-in skills current${drift}` };
+ }
+ return {
+ name,
+ status: 'warn',
+ message:
+ `${counts.new} new built-in skill(s) available that this workspace hasn't installed: ${sample('new')}. ` +
+ `Add them with \`gbrain skillpack sync\`.` +
+ (counts.drifted > 0 ? ` (${counts.drifted} drifted from the bundle — local edits are fine.)` : ''),
+ details: {
+ new: skills.filter(k => k.status === 'new').map(k => k.slug),
+ drifted: skills.filter(k => k.status === 'drifted').map(k => k.slug),
+ },
+ };
+}
+
+/**
+ * Skill preconditions check — the LIVE half of the `requires:` frontmatter
+ * contract. For every skill INSTALLED in this workspace that declares
+ * preconditions, verify each against the connected brain and WARN on unmet
+ * ones with a paste-ready hint. Engine-dependent: skips cleanly when there
+ * is no brain to check against (the static list lives in
+ * `gbrain skillpack setup`).
+ */
+export async function skillPreconditionsCheck(
+ skillsDir: string,
+ engine: BrainEngine | null,
+): Promise<Check> {
+ const name = 'skill_preconditions';
+ if (!engine) {
+ return { name, status: 'ok', message: 'skill preconditions not checked (no connected brain)' };
+ }
+ // Collect installed skills declaring `requires:`.
+ let installed: { slug: string; requires: string[] }[];
+ try {
+ installed = readdirSync(skillsDir, { withFileTypes: true })
+ .filter(e => e.isDirectory())
+ .map(e => {
+ const md = join(skillsDir, e.name, 'SKILL.md');
+ if (!existsSync(md)) return null;
+ const fm = parseSkillFrontmatter(readFileSync(md, 'utf-8'));
+ const requires = fm?.requires ?? [];
+ return requires.length > 0 ? { slug: e.name, requires } : null;
+ })
+ .filter((x): x is { slug: string; requires: string[] } => x !== null);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { name, status: 'ok', message: `skill preconditions check skipped (${msg})` };
+ }
+ if (installed.length === 0) {
+ return { name, status: 'ok', message: 'no installed skills declare preconditions' };
+ }
+
+ // Engine-backed precondition context. Read-only COUNT/getConfig queries;
+ // no source scoping (doctor is a trusted local context). Every accessor
+ // fails soft to a conservative value so a query error never throws the check.
+ const ctx: PreconditionContext = {
+ async countPages() {
+ try {
+ const rows = await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM pages');
+ return rows[0]?.n ?? 0;
+ } catch { return 0; }
+ },
+ async countPagesInDir(dir: string) {
+ const prefix = dir.endsWith('/') ? dir : `${dir}/`;
+ try {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages WHERE slug LIKE $1 ESCAPE '\\'`,
+ [`${prefix.replace(/[%_\\]/g, m => `\\${m}`)}%`],
+ );
+ return rows[0]?.n ?? 0;
+ } catch { return 0; }
+ },
+ async listSourceIds() {
+ try {
+ const rows = await engine.executeRaw<{ id: string }>(`SELECT id FROM sources WHERE id <> 'default'`);
+ return rows.map(r => r.id);
+ } catch { return []; }
+ },
+ async countPagesForSource(id: string) {
+ try {
+ const rows = await engine.executeRaw<{ n: number }>(
+ 'SELECT COUNT(*)::int AS n FROM pages WHERE source_id = $1',
+ [id],
+ );
+ return rows[0]?.n ?? 0;
+ } catch { return 0; }
+ },
+ async getConfig(key: string) {
+ try {
+ return (await engine.getConfig(key)) ?? undefined;
+ } catch { return undefined; }
+ },
+ };
+
+ const unmet: string[] = [];
+ for (const skill of installed) {
+ const results = await checkPreconditions(skill.requires, ctx);
+ for (const r of results) {
+ if (!r.met) unmet.push(`${skill.slug}: ${r.req.raw} — ${r.hint}`);
+ }
+ }
+ if (unmet.length === 0) {
+ return { name, status: 'ok', message: `${installed.length} skill(s) with preconditions, all met` };
+ }
+ return {
+ name,
+ status: 'warn',
+ message:
+ `${unmet.length} unmet skill precondition(s):\n ` +
+ unmet.slice(0, 8).join('\n ') +
+ (unmet.length > 8 ? `\n … +${unmet.length - 8} more` : ''),
+ details: { unmet },
+ };
+}
+
+export function skillBrainFirstCheck(skillsDir: string): Check {
+ let manifest: ReturnType<typeof loadOrDeriveManifest>;
+ try {
+ manifest = loadOrDeriveManifest(skillsDir);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return {
+ name: 'skill_brain_first',
+ status: 'warn',
+ message: `Could not load skills manifest from ${skillsDir} (${msg})`,
+ };
+ }
+ if (manifest.skills.length === 0) {
+ return {
+ name: 'skill_brain_first',
+ status: 'ok',
+ message: 'No skills found — skill_brain_first not applicable',
+ };
+ }
+
+ const violators: BrainFirstAnalysis[] = [];
+ const typoSkills: BrainFirstAnalysis[] = [];
+
+ for (const entry of manifest.skills) {
+ const skillPath = join(skillsDir, entry.path);
+ if (!existsSync(skillPath)) continue; // resolver_health already reports
+ let content: string;
+ try {
+ content = readFileSync(skillPath, 'utf-8');
+ } catch {
+ continue; // best-effort; permissions etc.
+ }
+ const fm = parseSkillFrontmatter(content);
+ const result = analyzeSkillBrainFirst(content, entry.name, fm);
+ if (result.typo_hint) typoSkills.push(result);
+ if (result.status === 'warn') violators.push(result);
+ }
+
+ // --- Snapshot + diff audit (A2 contract) ---------------------------------
+ // Best-effort: snapshot/audit failures don't poison the check result.
+ const violatorSlugs = new Set(violators.map(v => v.skill));
+ const patternsBySlug = new Map<string, string[]>();
+ for (const v of violators) {
+ patternsBySlug.set(v.skill, v.external_patterns_matched);
+ }
+ let priorSnapshotPresent = true;
+ try {
+ const snapshot = loadSnapshot();
+ priorSnapshotPresent = snapshot.present;
+ const diff = diffAgainstSnapshot(violatorSlugs, snapshot.violators);
+ const doctorRunId = `${process.pid}-${Date.now()}`;
+ if (snapshot.present) {
+ // Steady-state path: write events only for transitions.
+ appendAuditEventsForTransitions(diff, patternsBySlug, doctorRunId);
+ } else {
+ // First run / corrupt snapshot: bootstrap by writing one
+ // `detected` line per current violator. This is the only path
+ // that writes more than `diff.added.length` lines in a single
+ // doctor invocation.
+ const bootstrapDiff = { added: Array.from(violatorSlugs).sort(), removed: [], unchanged: [] };
+ appendAuditEventsForTransitions(bootstrapDiff, patternsBySlug, doctorRunId);
+ }
+ writeSnapshotAtomically(violatorSlugs);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ process.stderr.write(`[gbrain] skill_brain_first audit step failed (${msg}); check continues\n`);
+ }
+
+ // --- Build the check result ---------------------------------------------
+ if (violators.length === 0) {
+ const typoNote = typoSkills.length > 0
+ ? ` (note: ${typoSkills.length} skill(s) have brain_first typo hints: ${typoSkills.map(t => t.skill).join(', ')})`
+ : '';
+ return {
+ name: 'skill_brain_first',
+ status: 'ok',
+ message: `${manifest.skills.length} skill(s) compliant or exempt${typoNote}`,
+ };
+ }
+
+ // Sort for deterministic message + issues order.
+ violators.sort((a, b) => a.skill.localeCompare(b.skill));
+
+ const formerlyExempt = violators.filter(v => v.formerly_hardcoded_exempt);
+ const summary: string[] = [];
+ summary.push(
+ `${violators.length} skill(s) do external lookups without a brain-first compliance signal. ` +
+ `Fix via 'gbrain doctor --fix' (adds canonical Convention callout) ` +
+ `or set 'brain_first: exempt' in skill frontmatter for genuine infra skills.`,
+ );
+ if (formerlyExempt.length > 0) {
+ summary.push(
+ `Of these, ${formerlyExempt.length} were hardcoded-exempt in PR #1206 (${formerlyExempt.map(v => v.skill).slice(0, 6).join(', ')}${formerlyExempt.length > 6 ? ', ...' : ''}). ` +
+ `These need explicit opt-out now: run 'gbrain doctor --fix' to add the canonical callout, ` +
+ `or add 'brain_first: exempt' to frontmatter for skills that genuinely shouldn't consult the brain.`,
+ );
+ }
+ if (typoSkills.length > 0) {
+ summary.push(
+ `${typoSkills.length} skill(s) have brain_first typo hints: ` +
+ typoSkills.slice(0, 6).map(t => `${t.skill} — ${t.typo_hint}`).join('; ') +
+ (typoSkills.length > 6 ? '; ...' : ''),
+ );
+ }
+
+ return {
+ name: 'skill_brain_first',
+ status: 'warn',
+ message: summary.join(' '),
+ issues: violators.map(v => ({
+ type: 'skill_missing_brain_first',
+ skill: v.skill,
+ action: v.formerly_hardcoded_exempt
+ ? `Add canonical Convention callout OR set 'brain_first: exempt' (was hardcoded-exempt in PR #1206)`
+ : `Add canonical Convention callout OR set 'brain_first: exempt'`,
+ fix: {
+ kind: 'add-convention-callout',
+ external_patterns: v.external_patterns_matched,
+ typo_hint: v.typo_hint,
+ formerly_hardcoded_exempt: v.formerly_hardcoded_exempt,
+ summary_line: buildBrainFirstSummaryLine(v),
+ },
+ })),
+ };
+}
diff --git a/src/commands/search.ts b/src/commands/search.ts
index c37eef37f3..e96717d318 100644
--- a/src/commands/search.ts
+++ b/src/commands/search.ts
@@ -301,7 +301,7 @@ interface GraphSignalsStatsSection {
async function readGraphSignalsStats(engine: BrainEngine, days: number): Promise<GraphSignalsStatsSection> {
// Resolve graph_signals on/off. Mirrors the resolution chain in
- // src/commands/doctor.ts:checkGraphSignalsCoverage.
+ // src/commands/doctor/checks/graph-embedding.ts:checkGraphSignalsCoverage.
// v0.40.4 codex F1: case-insensitive + trim parity with
// loadOverridesFromConfig (mode.ts). Without this, search-stats would
// silently report the opposite of what the parser actually enables on
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index b61543cca5..a92dca3da2 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -1,11 +1,9 @@
import { existsSync, readFileSync, writeFileSync, statSync, realpathSync } from 'fs';
-import { execFileSync } from 'child_process';
-import { isAbsolute, join, relative, sep } from 'path';
+import { join, relative } from 'path';
import type { BrainEngine } from '../core/engine.ts';
import { DELETE_BATCH_SIZE } from '../core/engine-constants.ts';
import { importFile } from '../core/import-file.ts';
import { collectSyncableFiles } from './import.ts';
-import { createInterface } from 'readline';
import {
isSyncable,
unsyncableReason,
@@ -19,30 +17,13 @@ import {
isSkippablePath,
resolveAutoSkipThreshold,
DEFAULT_SOURCE_ID,
- ownsGlobalSyncAnchor,
} from '../core/sync.ts';
import {
computeSyncDelta,
buildDetachedWorkingTreeManifest,
} from '../core/sync-delta.ts';
-import { fetchRemote } from '../core/git-remote.ts';
-import {
- parseUsdLimit,
- formatUsdLimit,
- resolveSpendPosture,
-} from '../core/spend-posture.ts';
-import { estimateTokens, CHUNKER_VERSION } from '../core/chunkers/code.ts';
-import {
- estimateEmbeddingCostUsd,
- getEmbeddingModelName,
- currentEmbeddingPricePerMTok,
- currentEmbeddingSignature,
- willEmbedSynchronously,
- shouldBlockSync,
- type SyncEmbedMode,
-} from '../core/embedding.ts';
-import { estimateCostFromChars } from '../core/embedding-pricing.ts';
-import { SPEND_CAP_CONFIG_KEY } from '../core/embed-backfill-submit.ts';
+import { CHUNKER_VERSION } from '../core/chunkers/code.ts';
+import { willEmbedSynchronously } from '../core/embedding.ts';
import type { SyncManifest } from '../core/sync.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -74,9 +55,7 @@ import { getConfiguredCollectorOutputs } from './integrations.ts';
import { getDefaultSourcePath } from '../core/source-resolver.ts';
// v0.41.32.0: stamp the durable newest-COMMIT timestamp at sync time so the
// remote staleness path reads a column instead of shelling out to git.
-// lagFromContentMs is the remote/column comparator (buildSyncStatusReport
-// backs the get_status_snapshot MCP op — must NOT shell out to git).
-import { newestCommitMs, commitTimeMs, lagFromContentMs } from '../core/source-health.ts';
+import { newestCommitMs, commitTimeMs } from '../core/source-health.ts';
import { sortNewestFirst } from '../core/sort-newest-first.ts';
import {
loadOpCheckpoint,
@@ -92,6 +71,44 @@ import { registerCleanup } from '../core/process-cleanup.ts';
import { type DbPacer, createDbPacer, createNoopPacer, observed } from '../core/db-pacer.ts';
import { resolvePaceMode, loadPaceModeConfig, readPaceEnv } from '../core/pace-mode.ts';
import { AbortError } from '../core/abort-check.ts';
+// Peeled sync clusters (containment sprint C13-C14) — pure moves. Each module
+// below also has a re-export block at its original site in this file so
+// existing importers keep working; these imports are the symbols the code
+// remaining here still uses directly.
+import { runInlineCostGate } from '../core/sync-cost-gate.ts';
+import {
+ git,
+ isPathSafe,
+ hasOriginRemote,
+ isDetachedHead,
+ unique,
+ resolveSlugByPathOrSourcePath,
+ createSyncBaselineCommit,
+ isWithinRoot,
+ resolveNoEmbed,
+ discoverGitRoot,
+} from '../core/sync-git.ts';
+import {
+ readSyncAnchor,
+ isAnchorOwnedSyncPath,
+ writeSyncAnchor,
+ readChunkerVersion,
+ writeChunkerVersion,
+} from '../core/sync-anchor.ts';
+import {
+ SyncLockBusyError,
+ formatLockBusyMessage,
+ runBreakLock,
+ buildPartialResult,
+} from '../core/sync-lock.ts';
+import {
+ MASS_RECONCILE_RATIO,
+ planReconcileDeletes,
+ listEverCommittedPaths,
+ massReconcileAllowed,
+ resolveStallAbortSeconds,
+ composeAbortSignals,
+} from '../core/sync-reconcile.ts';
/**
* v0.42.x (#1794) -- resumable incremental sync checkpoint.
@@ -229,507 +246,16 @@ export interface SyncResult {
bankedFiles?: number;
}
-/**
- * Walk ONE source's working tree and sum tokens for every syncable file.
- * Conservative full-tree CEILING (full file content, not the incremental
- * diff) — over-counts, never under-counts. Used only on the ceiling rungs of
- * `estimateInlineNewTokens` (first sync, chunker drift, git-unavailable),
- * where the delta is genuinely the whole tree or can't be computed.
- *
- * v0.31.2: routed through collectSyncableFiles (lstat + inode-cycle +
- * max-depth) so the preview walks exactly what the real sync walks.
- *
- * Exported (v0.42.42.0, #2139) for direct unit testing.
- */
-export function estimateSourceTreeTokens(
- localPath: string,
- strategy: 'markdown' | 'code' | 'auto',
- opts: { includeGitignored?: boolean } = {},
-): { tokens: number; files: number } {
- let tokens = 0;
- let files = 0;
- try {
- const fileList = collectSyncableFiles(localPath, { strategy, includeGitignored: opts.includeGitignored });
- for (const fullPath of fileList) {
- try {
- const stat = statSync(fullPath);
- if (stat.size > 5_000_000) continue; // skip large binaries
- const content = readFileSync(fullPath, 'utf-8');
- tokens += estimateTokens(content);
- files++;
- } catch {
- // Best-effort per file; sync itself tolerates the same.
- }
- }
- } catch {
- // Best-effort: a source whose local_path is gone/unreadable contributes 0.
- }
- return { tokens, files };
-}
-
-/** Sum tokens for an explicit set of repo-relative paths read at live working-tree content. */
-function estimateDeltaTokens(localPath: string, relPaths: string[]): number {
- let tokens = 0;
- for (const rel of relPaths) {
- try {
- const full = join(localPath, rel);
- const stat = statSync(full);
- if (stat.size > 5_000_000) continue; // skip large binaries (matches tree walk)
- tokens += estimateTokens(readFileSync(full, 'utf-8'));
- } catch {
- // Listed in the diff but unreadable (e.g. since deleted) → 0, like the tree walk.
- }
- }
- return tokens;
-}
-
-/**
- * v0.42.42.0 (#2139): resolve the commit the estimate should diff AGAINST.
- *
- * The cost gate runs BEFORE sync's own `git pull`, so a stale local HEAD would
- * make the estimate blind to commits the run is about to pull (codex #1). So
- * we FETCH first (fail-open) and target `origin/<branch>` — the estimate then
- * prices exactly what this run will sync. The subsequent pull fast-forwards
- * the already-fetched objects, so net new network cost ≈ 0.
- *
- * - detached HEAD → no upstream; target = local HEAD (+ caller merges the
- * detached working-tree manifest, which sync imports on a detached repo).
- * - attached + origin remote → fetch origin/<branch> (best-effort), target =
- * origin/<branch> if resolvable, else local HEAD (offline / no upstream).
- * - HEAD unresolvable (not a git repo) → null (caller treats as unavailable).
- *
- * NOTE: this makes `--dry-run` perform a network fetch so the preview reflects
- * what a real run would pull. Fail-open: offline dry-run still previews against
- * local HEAD. Uses the shared `git()` 30s budget (the fetch cost is the pull
- * cost paid a few seconds early — a tighter cap would frequently fall back to
- * local HEAD and underestimate the remote delta).
- */
-function resolveEstimateTarget(localPath: string): { target: string; detached: boolean } | null {
- let head: string;
- try {
- head = git(localPath, ['rev-parse', 'HEAD']);
- } catch {
- return null;
- }
- const detached = isDetachedHead(localPath);
- if (detached) return { target: head, detached: true };
-
- let branch: string | null = null;
- try {
- branch = git(localPath, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() || null;
- } catch {
- branch = null;
- }
- if (branch && branch !== 'HEAD' && hasOriginRemote(localPath)) {
- try {
- // v0.42.42.0 (#2139): route through the SSRF-hardened fetch (same flags +
- // no-prompt env as pullRepo) — a cost preview / dry-run must NOT hit a
- // remote through a less-protected path than real sync.
- fetchRemote(localPath, branch, { timeoutMs: 30_000 });
- } catch {
- // fail-open: offline, auth failure, no upstream — fall through to local HEAD.
- }
- try {
- const remoteSha = git(localPath, ['rev-parse', `origin/${branch}`]);
- if (remoteSha) return { target: remoteSha, detached: false };
- } catch {
- // no remote-tracking ref for this branch — use local HEAD.
- }
- }
- return { target: head, detached: false };
-}
-
-export type EstimateKind = 'delta' | 'ceiling' | 'mixed' | 'unchanged';
-
-export interface InlineEstimate {
- tokens: number;
- changedSources: number;
- unchangedSources: number;
- estimateKind: EstimateKind;
- /** Per-source ceiling reasons (chunker_drift / first_sync / git_unavailable) for honest labeling. */
- ceilingReasons: string[];
-}
-
-/**
- * v0.42.42.0 (#2139) — INLINE-path new-content estimate. The estimate now
- * MIRRORS EXECUTION instead of pricing the whole tree on every dirty sync (the
- * 400x overestimate that wedged the daily cron). Per-source fail-open ladder:
- *
- * 1. syncEnabled === false → skip (unchanged)
- * 2. chunker drift (stored !== current) → full-tree CEILING (a drift forces
- * performFullSync → full re-chunk → full re-embed; a delta would
- * underestimate by the whole corpus). kind: ceiling_chunker_drift
- * 3. last_commit === fetch target → 0 (mirrors `up_to_date` at
- * sync.ts:1402 — NO clean-working-tree requirement; a dirty tree whose
- * commits are caught up imports nothing). kind: unchanged
- * 4. last_commit === null (first sync) → full-tree CEILING. kind: ceiling_first_sync
- * 5. computeSyncDelta ok → price added∪modified∪renamed.to
- * (syncable, live working-tree content); deletes cost 0. kind: delta
- * 6. computeSyncDelta unavailable → full-tree CEILING. kind: ceiling_git_unavailable
- *
- * The delta rung routes through the SAME `computeSyncDelta` the executor uses
- * (src/core/sync-delta.ts), so the gate's dollar figure can't drift from what
- * the sync imports. `--full`'s extra stale-backlog sweep is added by the gate
- * (it already has `staleCostUsd`), not here — see the call site.
- *
- * Exported for direct unit testing.
- */
-export function estimateInlineNewTokens(
- sources: Array<{
- local_path: string | null;
- config: Record<string, unknown>;
- last_commit: string | null;
- chunker_version: string | null;
- }>,
- currentChunkerVersion: string,
- opts: { forceFullTree?: boolean } = {},
-): InlineEstimate {
- let tokens = 0;
- let changedSources = 0;
- let unchangedSources = 0;
- let hadDelta = false;
- let hadCeiling = false;
- const ceilingReasons: string[] = [];
-
- const ceiling = (localPath: string, strategy: 'markdown' | 'code' | 'auto', reason: string) => {
- tokens += estimateSourceTreeTokens(localPath, strategy).tokens;
- changedSources++;
- hadCeiling = true;
- ceilingReasons.push(reason);
- };
-
- for (const src of sources) {
- if (!src.local_path) continue;
- const cfg = (src.config || {}) as { syncEnabled?: boolean; strategy?: 'markdown' | 'code' | 'auto' };
- if (cfg.syncEnabled === false) continue;
- const strategy = cfg.strategy ?? 'markdown';
- const localPath = src.local_path;
-
- if (opts.forceFullTree) {
- tokens += estimateSourceTreeTokens(localPath, strategy, { includeGitignored: true }).tokens;
- changedSources++;
- hadCeiling = true;
- ceilingReasons.push('include_gitignored');
- continue;
- }
-
- // Rung 2: chunker drift forces a full re-chunk → full re-embed. CEILING.
- if (src.chunker_version !== currentChunkerVersion) {
- ceiling(localPath, strategy, 'chunker_drift');
- continue;
- }
-
- // Rung 4 (early): no bookmark → first sync imports everything. CEILING.
- if (!src.last_commit) {
- ceiling(localPath, strategy, 'first_sync');
- continue;
- }
-
- const resolved = resolveEstimateTarget(localPath);
- if (!resolved) {
- // HEAD unresolvable (not a git repo / gone) — can't compute a delta. CEILING.
- ceiling(localPath, strategy, 'git_unavailable');
- continue;
- }
-
- // Rung 3: caught up to the fetch target AND no detached working-tree changes.
- // Mirrors the executor's `up_to_date` predicate — a dirty-but-committed-current
- // tree imports nothing, so it must price $0 (the heart of the false-fire fix).
- const detachedManifest = resolved.detached
- ? buildDetachedWorkingTreeManifest(localPath)
- : null;
- const detachedHasChanges = detachedManifest !== null &&
- (detachedManifest.added.length > 0 ||
- detachedManifest.modified.length > 0 ||
- detachedManifest.deleted.length > 0 ||
- detachedManifest.renamed.length > 0);
- if (src.last_commit === resolved.target && !detachedHasChanges) {
- unchangedSources++;
- continue;
- }
-
- // Rung 5/6: the delta itself — SAME helper the executor diffs with.
- const delta = computeSyncDelta(localPath, src.last_commit, resolved.target, {
- detachedManifest,
- });
- if (delta.status === 'unavailable') {
- ceiling(localPath, strategy, 'git_unavailable');
- continue;
- }
- const syncOpts = { strategy };
- const changedPaths = unique([
- ...delta.manifest.added.filter(p => isSyncable(p, syncOpts)),
- ...delta.manifest.modified.filter(p => isSyncable(p, syncOpts)),
- ...delta.manifest.renamed.filter(r => isSyncable(r.to, syncOpts)).map(r => r.to),
- ]);
- tokens += estimateDeltaTokens(localPath, changedPaths);
- changedSources++;
- hadDelta = true;
- }
-
- const estimateKind: EstimateKind =
- hadCeiling && hadDelta ? 'mixed' : hadCeiling ? 'ceiling' : hadDelta ? 'delta' : 'unchanged';
- return { tokens, changedSources, unchangedSources, estimateKind, ceilingReasons };
-}
-
-/**
- * Resolve the inline-path cost-gate floor in USD. Config key
- * `sync.cost_gate_min_usd` (DB plane), default $0.50. Below this estimate
- * the inline gate proceeds without blocking. Fail-open to the default on a
- * missing/invalid value or a config-read error (the gate must never crash
- * the sync). Accepts 0 (an operator can set the floor to $0 to make the
- * gate block on any nonzero inline cost).
- */
-async function resolveCostGateFloorUsd(engine: BrainEngine): Promise<number> {
- try {
- const raw = await engine.getConfig('sync.cost_gate_min_usd');
- // v0.42.42.0 (#2139): `0` keeps meaning "block on any nonzero spend"
- // (allowZero); `off`/`unlimited`/`none` → Infinity so the gate never
- // blocks (`costUsd > Infinity` is always false).
- return parseUsdLimit(raw, 0.5, { allowZero: true });
- } catch {
- return 0.5;
- }
-}
-
-/**
- * Resolve the per-source embed-backfill 24h spend cap (USD) for the deferred
- * notice. Mirrors embed-backfill-submit.ts's own resolution of
- * SPEND_CAP_CONFIG_KEY (default 25). Fail-open to the default.
- */
-async function resolveBackfillCapUsd(engine: BrainEngine): Promise<number> {
- try {
- const raw = await engine.getConfig(SPEND_CAP_CONFIG_KEY);
- // v0.42.42.0 (#2139): no allowZero — `0` falls back to the default
- // (off semantics ≠ 0); `off`/`unlimited`/`none` → Infinity (cap disabled).
- return parseUsdLimit(raw, 25);
- } catch {
- return 25;
- }
-}
-
-/** Interactive [y/N] prompt. Resolves false on non-y answers or EOF. */
-async function promptYesNo(question: string): Promise<boolean> {
- return new Promise((resolve) => {
- const rl = createInterface({ input: process.stdin, output: process.stdout });
- rl.question(question, (answer) => {
- rl.close();
- resolve(answer.trim().toLowerCase() === 'y' || answer.trim().toLowerCase() === 'yes');
- });
- rl.on('close', () => resolve(false));
- });
-}
-
-// v0.42.42.0 (#2139): paste-ready knobs appended to every gate message so the
-// spend-control surface is discoverable at the moment of need (humans + agents),
-// not only after reading source. Closes the issue's "takes archaeology" complaint.
-const SPEND_HINT =
- 'widen: gbrain config set sync.cost_gate_min_usd 5 | ' +
- 'never gate: gbrain config set spend.posture tokenmax | ' +
- 'docs: docs/operations/spend-controls.md';
-
-/** Honest token label — delta vs full-tree ceiling, with the ceiling reasons. */
-function labelEstimate(inline: InlineEstimate): string {
- if (inline.estimateKind === 'unchanged') return '0 new tokens (sources caught up)';
- if (inline.estimateKind === 'delta') {
- return `~${inline.tokens.toLocaleString()} new tokens (delta: changed files since last sync)`;
- }
- // ceiling | mixed — be explicit that this is an over-count, not the real spend.
- const reasons = unique(inline.ceilingReasons).join(', ') || 'unknown';
- return (
- `<=${inline.tokens.toLocaleString()} tokens (full-tree ceiling for ${inline.changedSources} ` +
- `source(s): ${reasons} — unchanged files skip via content_hash at execution)`
- );
-}
-
-type CostGateSource = {
- local_path: string | null;
- config: Record<string, unknown>;
- last_commit: string | null;
- chunker_version: string | null;
-};
-
-interface CostGateContext {
- sources: CostGateSource[];
- /** Resolved embed mode. Single-source is always 'inline' (not the parallel-deferred fan-out). */
- mode: SyncEmbedMode;
- dryRun: boolean;
- jsonOut: boolean;
- yesFlag: boolean;
- full: boolean;
- includeGitignored?: boolean;
- /** Message prefix ('sync --all' | 'sync'). */
- label: string;
-}
-
-type CostGateOutcome =
- | { action: 'proceed'; autoDeferEmbeds: boolean }
- | { action: 'stop' };
-
-/**
- * v0.42.42.0 (#2139): the inline-embed cost gate, shared by BOTH `sync --all`
- * and single-source `sync` so the spend surface is consistent. Runs at the
- * COMMAND layer (never inside performSync, which `runOne` also calls — that
- * would double-gate `--all`).
- *
- * Behavior:
- * - deferred mode → FYI only, never blocks (backfill cap is the money gate).
- * - inline + below floor → proceed quietly.
- * - inline + spend.posture=tokenmax → informational, proceed inline.
- * - inline + above floor + TTY → [y/N] prompt.
- * - inline + above floor + non-TTY/--json → AUTO-DEFER embeds to capped
- * backfill jobs, exit 0 (NEVER exit 2 — the wedged-cron fix). Caller sets
- * effectiveNoEmbed and enqueues the backfill.
- *
- * Output format splits on the EXPLICIT `--json` flag only (absorbs the
- * TODOS.md:340 #1784 conflation): JSON envelope iff `--json`, else human text.
- */
-async function runInlineCostGate(
- engine: BrainEngine,
- ctx: CostGateContext,
-): Promise<CostGateOutcome> {
- const { sources, mode, dryRun, jsonOut, yesFlag, full, label } = ctx;
-
- // Stale backlog: cheap single SQL; fail-open to 0 so a transient DB hiccup
- // never blocks the sync. Signature-aware (model/dims swap surfaces here).
- let staleChars = 0;
- try {
- staleChars = await engine.sumStaleChunkChars({ signature: currentEmbeddingSignature() });
- } catch {
- staleChars = 0;
- }
- const staleCostUsd = estimateCostFromChars(staleChars, currentEmbeddingPricePerMTok());
- const embeddingModelName = getEmbeddingModelName();
- const floorUsd = await resolveCostGateFloorUsd(engine);
- const posture = await resolveSpendPosture(engine);
-
- if (mode === 'deferred') {
- // Deferred path: print an FYI, NEVER block. The backfill cap is the real
- // money gate.
- const capUsd = await resolveBackfillCapUsd(engine);
- let queuedBackfills = 0;
- try {
- const r = await engine.executeRaw<{ n: number }>(
- `SELECT COUNT(*)::int AS n FROM minion_jobs
- WHERE name = 'embed-backfill'
- AND status IN ('waiting','active','delayed','waiting-children')`,
- );
- queuedBackfills = Number(r[0]?.n) || 0;
- } catch {
- queuedBackfills = 0;
- }
- const deferredMsg =
- `${label}: embedding deferred to backfill jobs ` +
- `(capped $${formatUsdLimit(capUsd)}/source/24h, not charged by this sync). ` +
- `Current backlog ~${staleChars.toLocaleString()} chars (~$${staleCostUsd.toFixed(2)} on ` +
- `${embeddingModelName}) across ${sources.length} source(s); ` +
- `${queuedBackfills} backfill job(s) queued.`;
- if (dryRun) {
- if (jsonOut) {
- console.log(JSON.stringify({ status: 'dry_run', mode, gate: 'dry_run', staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd), queuedBackfills, model: embeddingModelName }));
- } else {
- console.log(deferredMsg);
- console.log('--dry-run: exit without syncing.');
- }
- return { action: 'stop' };
- }
- if (jsonOut) {
- console.log(JSON.stringify({ status: 'deferred', mode, gate: 'deferred_notice', staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd), queuedBackfills, model: embeddingModelName }));
- } else {
- console.log(deferredMsg);
- }
- return { action: 'proceed', autoDeferEmbeds: false };
- }
-
- // ── Inline path ───────────────────────────────────────────────
- const inline = estimateInlineNewTokens(sources, String(CHUNKER_VERSION), {
- forceFullTree: ctx.includeGitignored === true,
- });
- // D7A: `--full` runs `performFullSync` → `runEmbedCore({stale:true})`, which
- // sweeps the pre-existing stale backlog INLINE on top of the delta. Price it.
- const costUsd = estimateEmbeddingCostUsd(inline.tokens) + (full ? staleCostUsd : 0);
- const fullNote = full && staleChars > 0
- ? ` (includes ~${staleChars.toLocaleString()} stale-backlog chars swept by --full)`
- : '';
- const staleNote = !full && staleChars > 0
- ? ` (plus ~${staleChars.toLocaleString()} stale-backlog chars pending \`gbrain embed --stale\`)`
- : '';
- const previewMsg =
- `${label} preview (inline embed): ${inline.changedSources} changed source(s), ` +
- `${inline.unchangedSources} unchanged; ${labelEstimate(inline)}, ` +
- `est. $${costUsd.toFixed(2)} on ${embeddingModelName}${fullNote}${staleNote}.`;
-
- if (dryRun) {
- if (jsonOut) {
- console.log(JSON.stringify({ status: 'dry_run', mode, gate: 'dry_run', newTokens: inline.tokens, estimateKind: inline.estimateKind, staleChars, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName }));
- } else {
- console.log(previewMsg);
- console.log('--dry-run: exit without syncing.');
- }
- return { action: 'stop' };
- }
-
- // --yes bypasses the gate entirely (embed inline, no preview).
- if (yesFlag) return { action: 'proceed', autoDeferEmbeds: false };
-
- // spend.posture=tokenmax → informational, proceed INLINE (operator declared
- // cost isn't the constraint; don't defer).
- if (posture === 'tokenmax') {
- if (jsonOut) {
- console.log(JSON.stringify({ status: 'proceeding', mode, gate: 'posture_tokenmax', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT }));
- } else {
- console.log(`${previewMsg} spend.posture=tokenmax: proceeding (informational). ${SPEND_HINT}`);
- }
- return { action: 'proceed', autoDeferEmbeds: false };
- }
-
- // Link intent: search.mode=tokenmax but spend posture unset → nudge once.
- let searchModeHint = '';
- try {
- const sm = await engine.getConfig('search.mode');
- if (typeof sm === 'string' && sm.trim().toLowerCase() === 'tokenmax') {
- searchModeHint =
- ` (search.mode=tokenmax detected — \`gbrain config set spend.posture tokenmax\` ` +
- `makes cost gates informational)`;
- }
- } catch {
- /* best-effort */
- }
-
- if (shouldBlockSync(costUsd, floorUsd, mode, posture)) {
- const isTTY = Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY);
- if (isTTY && !jsonOut) {
- // Interactive TTY: prompt [y/N].
- console.log(previewMsg + searchModeHint);
- const answer = await promptYesNo('Proceed? [y/N] ');
- if (!answer) {
- console.log('Cancelled.');
- return { action: 'stop' };
- }
- return { action: 'proceed', autoDeferEmbeds: false };
- }
- // Non-TTY or --json: AUTO-DEFER embeds to capped backfill jobs. NEVER exit 2
- // (the wedged-cron fix). Format splits on the explicit --json flag only.
- if (jsonOut) {
- console.log(JSON.stringify({ status: 'auto_deferred', mode, gate: 'auto_deferred_embeds', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT }));
- } else {
- console.log(
- `${previewMsg} Exceeds floor $${formatUsdLimit(floorUsd)} in a non-interactive ` +
- `session — importing now, deferring embeds to capped backfill jobs. ` +
- `Drain: run the jobs worker or \`gbrain embed --stale\`. Pass --yes to embed inline.\n${SPEND_HINT}`,
- );
- }
- return { action: 'proceed', autoDeferEmbeds: true };
- }
-
- // Below floor → proceed without blocking (kills inline-cron noise).
- if (jsonOut) {
- console.log(JSON.stringify({ status: 'below_floor', mode, gate: 'below_floor', newTokens: inline.tokens, estimateKind: inline.estimateKind, staleChars, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName }));
- } else {
- console.log(`${previewMsg} Below cost gate floor ($${formatUsdLimit(floorUsd)}), proceeding.`);
- }
- return { action: 'proceed', autoDeferEmbeds: false };
-}
+// The cost-gate / token-estimate cluster (estimateSourceTreeTokens,
+// estimateInlineNewTokens, runInlineCostGate, ...) was peeled to
+// src/core/sync-cost-gate.ts (pure move). Re-exported so existing importers
+// keep working.
+export {
+ estimateSourceTreeTokens,
+ estimateInlineNewTokens,
+ type EstimateKind,
+ type InlineEstimate,
+} from '../core/sync-cost-gate.ts';
export interface SyncOpts {
repoPath?: string;
@@ -868,616 +394,23 @@ export interface SyncOpts {
signal?: AbortSignal;
}
-/**
- * v0.32.7 CJK wave (codex post-merge F4): resolve a slug by `pages.source_path`
- * first, falling back to `resolveSlugForPath(path)`.
- *
- * Frontmatter-fallback pages (emoji-only / Thai / Arabic / exotic-script
- * filenames where `slugifyPath` returns empty and the slug came from the
- * frontmatter) have a slug that ISN'T derivable from the path. Delete and
- * rename operations that only know the path would otherwise orphan these
- * pages by trying to delete the path-derived (wrong) slug.
- *
- * Returns the actual stored slug when source_path matches a row, or the
- * path-derived slug when there's no match (normal-case path-derived pages).
- */
-export async function resolveSlugByPathOrSourcePath(
- engine: BrainEngine,
- path: string,
- sourceId?: string,
-): Promise<string> {
- // v0.41.19.0 (D8): when sourceId is set, delegate to the new batch
- // resolveSlugsByPaths so single-call and batched paths share one SQL
- // owner + one fallback semantic. One Map allocation per single-call;
- // negligible cost. When sourceId is undefined (legacy unscoped callers),
- // fall back to the original executeRaw shape — the batch method
- // requires sourceId to prevent the multi-source-bug-class on its new
- // surface (D5). The unscoped fallback preserves back-compat.
- try {
- if (sourceId) {
- const m = await engine.resolveSlugsByPaths([path], { sourceId });
- const slug = m.get(path);
- if (slug) return slug;
- } else {
- const rows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages WHERE source_path = $1 LIMIT 1`,
- [path],
- );
- if (rows.length > 0 && rows[0].slug) return rows[0].slug;
- }
- } catch {
- // Fall through — best-effort. Pre-migration brains or query errors
- // shouldn't break delete/rename for path-derived pages.
- }
- return resolveSlugForPath(path);
-}
-
-/**
- * git CLI helper.
- *
- * `configs` flags are emitted as `-c key=val` pairs BEFORE `-C repoPath` and
- * BEFORE the subcommand. `core.quotepath=false` is always emitted first so CJK
- * (and other non-ASCII) paths arrive as UTF-8 in `diff --name-status` and
- * sibling commands. Callers that need additional git config should pass via
- * the `configs` parameter; never inline `-c` into `args`.
- *
- * Exported for `test/sync.test.ts` invariant assertion only.
- */
-export function buildGitInvocation(repoPath: string, args: string[], configs: string[] = []): string[] {
- const cfg = ['core.quotepath=false', ...configs].flatMap(c => ['-c', c]);
- return [...cfg, '-C', repoPath, ...args];
-}
-
-export function buildAutoEmbedArgs(slugs: string[], sourceId?: string): string[] {
- return sourceId ? ['--source', sourceId, '--slugs', ...slugs] : ['--slugs', ...slugs];
-}
-
-/**
- * Resolve sync's effective no-embed mode from CLI args + config.
- *
- * The deferred-setup sentinel (`embedding_disabled: true`, written by
- * `gbrain init --no-embedding`) is an implicit `--no-embed`: without this,
- * the embed credential preflight demands provider credentials the user
- * deliberately deferred at init, and every `gbrain sync` on a keyless
- * brain exits 1. See embed-preflight.ts's skip protocol — the sentinel is
- * meant to be honored before the credential check ever runs.
- *
- * Exported for `test/sync-no-embed-sentinel.test.ts`.
- */
-export function resolveNoEmbed(
- args: string[],
- cfg: { embedding_disabled?: boolean } | null,
-): boolean {
- return args.includes('--no-embed') || cfg?.embedding_disabled === true;
-}
-
-/**
- * Shell out to git with a generous maxBuffer.
- *
- * Node's default maxBuffer is 1 MiB. `git diff --name-status -M` on a
- * 60–100K file repo easily exceeds that, causing an ENOBUFS crash that
- * kills the sync process with no error message in the log.
- *
- * 100 MiB is generous but still bounded — a 100K-file diff with long
- * paths tops out around 10–20 MiB in practice.
- *
- * `silenceStderr`: Node's `execFileSync` writes the child's stderr straight
- * through to the parent's real stderr by default (in addition to attaching
- * it to the thrown error's `.stderr`) *unless* an explicit `stdio` array is
- * given. Callers that treat a failure as an expected, self-handled outcome
- * (rather than a crash to surface) pass `silenceStderr: true` so git's raw
- * `fatal: ...` line never reaches the process's own stderr — only the
- * caller's own (usually friendlier) handling of the caught error does.
- * Default `false` preserves today's passthrough for every other call site.
- */
-function git(
- repoPath: string,
- args: string[],
- configs: string[] = [],
- timeoutMs = 30000,
- { silenceStderr = false }: { silenceStderr?: boolean } = {},
-): string {
- return execFileSync('git', buildGitInvocation(repoPath, args, configs), {
- encoding: 'utf-8',
- timeout: timeoutMs,
- maxBuffer: 100 * 1024 * 1024,
- ...(silenceStderr ? { stdio: ['ignore', 'pipe', 'pipe'] as const } : {}),
- }).trim();
-}
-
-/**
- * #753/#774: walk up from inputPath to the nearest git repo root via
- * `git -C <path> rev-parse --show-toplevel`. Handles worktrees and submodules
- * natively (git itself resolves them). Throws a user-friendly error when no
- * git repo is found.
- *
- * The probe's failure is expected and routine (a non-git-yet brain dir, a
- * scratch dir, a caller checking "is this a repo?") — `sync.ts` self-heals
- * it (git-init) or surfaces the message below, never the raw git stderr.
- * `silenceStderr: true` keeps git's own `fatal: not a git repository ...`
- * off the process's real stderr so operator log-scanning for `fatal:` as a
- * crash signature doesn't false-alarm on every routine probe miss (#2964
- * auto-recovery made the *outcome* self-healing; this keeps the *log* quiet
- * about the expected miss that triggered it).
- */
-export function discoverGitRoot(inputPath: string): string {
- try {
- return git(inputPath, ['rev-parse', '--show-toplevel'], [], 30000, { silenceStderr: true });
- } catch {
- throw new Error(
- `Not inside a git repository: ${inputPath}. GBrain sync requires a git-initialized repo (or a subdirectory of one).`,
- );
- }
-}
-
-/**
- * #2964: snapshot the CURRENT on-disk state of a gbrain-owned brain dir as
- * a baseline commit — used both right after a self-healing `git init` (no
- * `.git` at all) and to recover a repo left with `.git` but zero commits
- * (an interrupted prior self-heal, or a `git init` from some other source
- * that never got a first commit). Respects `.gitignore` (written first) so
- * future incremental syncs diff against what's actually here rather than
- * an empty tree — an empty initial commit would make every existing file
- * look "added" again on the next sync, even though the full-sync pass that
- * follows already imported them from disk directly.
- *
- * `--no-gpg-sign` + explicit `-c user.name/user.email`: this runs from a
- * headless nightly cron/launchd invocation, which has no reason to have
- * git signing/identity configured, and must not block on an unavailable
- * signing agent or pinentry prompt.
- *
- * db_only exclusion is recomputed directly and passed to `git add` as
- * negative pathspecs, rather than relying solely on `manageGitignore`
- * having written `.gitignore` successfully: that helper is deliberately
- * best-effort (a broken gbrain.yml parse, or an unwritable .gitignore,
- * only warns and returns — the right default for its OTHER callers, where
- * .gitignore management is a side effect that must never kill the sync
- * job). For a commit we are about to create ourselves, "fail open" there
- * would mean silently committing db_only content into git history. Fail
- * closed instead: db_only exclusion doesn't depend on the .gitignore
- * write having succeeded. `loadStorageConfig` throwing (unreadable
- * gbrain.yml, or a semantic overlap) propagates — better to leave this
- * self-heal wedged with a clear error than commit unknown content.
- */
-/**
- * Classify a caught `git rev-parse --verify --quiet HEAD` failure for the
- * baseline-commit guard. A genuinely UNBORN HEAD makes git exit with status
- * EXACTLY 1 and nothing on stderr — precisely what `--verify --quiet` emits
- * for an unresolvable HEAD (verified empirically: unborn => exit 1, empty
- * stderr; born => exit 0). Every OTHER failure shape — a 30s timeout (killed
- * by signal, so `status` is null), an index/ref lock (`fatal: Unable to
- * create ...lock`, non-empty stderr), or any nonzero-but-not-1 exit — is NOT
- * proof the repo is empty; it is the transient-probe-failure class that
- * corrupted the live brain on 2026-08-10. Return 'unborn' ONLY for the clean
- * signal so the caller fails CLOSED on 'ambiguous'. Pure (no I/O) so the
- * distinction is unit-testable without fault injection.
- */
-export function classifyHeadProbeError(err: unknown): 'unborn' | 'ambiguous' {
- const e = (err ?? {}) as { status?: number | null; signal?: string | null; stderr?: unknown };
- const stderr = e.stderr == null ? '' : String(e.stderr).trim();
- return e.status === 1 && e.signal == null && stderr === '' ? 'unborn' : 'ambiguous';
-}
-
-export function createSyncBaselineCommit(repoPath: string): void {
- // Fail-closed backstop (2026-08-10 auto-init incident). This function's
- // ENTIRE contract is "snapshot an unborn/uninitialized repo as its FIRST
- // commit". It must NEVER run on a repo that already has commits: doing so
- // stacks a spurious `gbrain: initial commit (auto-init by sync)` commit ON
- // TOP of real history and, on a case-insensitive filesystem, re-cases the
- // whole tree (`projects` -> `Projects`) as a `git add -A` side effect.
- //
- // Both call sites are *supposed* to reach here only on an unborn/non-git
- // repo, but each infers "unborn" from a FAILURE to observe git state
- // (`discoverGitRoot` threw / `git rev-parse HEAD` threw), and those probes
- // ALSO fail transiently — a 30s timeout on a large brain, or a concurrent
- // `gbrain-sync` holding a git lock — against a fully-populated repo, which
- // is exactly what corrupted the live brain on 2026-08-10. So we cannot
- // trust "the caller said it's unborn"; verify POSITIVELY here — and, since
- // this very probe is subject to the same transient failures, accept ONLY a
- // CLEAN unborn signal. A born HEAD (exit 0) OR an ambiguous probe failure
- // (timeout / lock / other) both REFUSE, so the backstop is fail-closed
- // against every corruption path, not just the born-HEAD one.
- // `classifyHeadProbeError` isolates that born/unborn/ambiguous distinction
- // as a pure, unit-tested predicate.
- //
- // Known non-incident edge (B2, documented not fixed): an orphan branch
- // (`git switch --orphan`) in a repo with history elsewhere probes as unborn
- // and would still be baselined. A gbrain brain is never in that state; it is
- // not the incident (no stacking on real history, no re-case of other
- // branches), so it is left as a limitation rather than complicating the
- // guard with a `rev-list --all` "commits anywhere" probe.
- let headState: 'born' | 'unborn' | 'ambiguous';
- try {
- git(repoPath, ['rev-parse', '--verify', '--quiet', 'HEAD'], [], 30000, { silenceStderr: true });
- headState = 'born';
- } catch (err) {
- headState = classifyHeadProbeError(err);
- }
- if (headState !== 'unborn') {
- throw new Error(
- `Refusing to create a sync baseline commit in ${repoPath}: HEAD probe is ` +
- `'${headState}', expected a clean unborn HEAD. 'born' = the repo already ` +
- `has commits (real history); 'ambiguous' = the HEAD check failed ` +
- `transiently (30s timeout, or a concurrent gbrain-sync holding a git ` +
- `lock), which is NOT proof the repo is empty. Committing either way ` +
- `would stack a bogus auto-init commit on real history and re-case the ` +
- `tree on a case-insensitive filesystem.`,
- );
- }
- // #2964: db_only exclusion is computed directly from loadStorageConfig
- // and passed to `git add` as pathspecs — deliberately NOT via
- // manageGitignore/.gitignore, for two independent reasons:
- //
- // 1. Ordering (Codex review round 6, P1): `collectSyncableFiles` — the
- // file enumeration `performFullSync` runs right after this function
- // returns — honors `.gitignore` via `git ls-files --exclude-standard`.
- // Writing db_only entries into `.gitignore` BEFORE that first import
- // would silently exclude those pages from the database entirely.
- // That's the exact bug class `runSync`'s existing "manage .gitignore
- // ONLY on successful sync" ordering (this file, `manageGitignoreAtGitRoot`
- // callers below — itself a prior Codex P1 fix) exists to prevent. Leave
- // `.gitignore` untouched here; the existing post-sync flow writes it
- // once this sync completes, same as it does for every other sync.
- // 2. Fail-closed (rounds 5-6): `manageGitignore`'s "warn and return" on a
- // broken gbrain.yml/unwritable .gitignore is the right default for its
- // OTHER callers (a side effect that must never kill the sync job), but
- // wrong for a commit we are creating ourselves — silently committing
- // db_only content into git history.
- const storageConfig = loadStorageConfig(repoPath);
- const dbOnlyDirs = storageConfig?.db_only ?? [];
- // Sniff-test fail-closed (round 6, P2): `loadStorageConfig` warns-and-
- // returns an EMPTY config for syntactically-valid-but-unsupported YAML
- // (e.g. flow-style `db_only: [dir/]` — the narrow custom parser only
- // handles block-style lists), which would silently resolve zero
- // exclusions from a file that clearly intended some. If gbrain.yml
- // exists and mentions db_only (or its deprecated pre-v0.22.11 alias
- // `supabase_only` — same keep-out-of-git semantics, still a supported
- // backward-compat key per storage-config.ts) but nothing resolved from
- // it, refuse rather than guess "genuinely empty" vs "syntax ignored".
- //
- // Known false-positive (round 8 review): a genuinely, intentionally
- // empty `db_only: []` mentioning the word also refuses, and can't be
- // told apart from the unsupported-syntax case — `loadStorageConfig`
- // returns the IDENTICAL `{db_tracked:[],db_only:[]}` for both (verified
- // directly: flow-style `[dir/]` and literal `[]` both collapse to that
- // same shape). Distinguishing them would mean teaching this function
- // about the parser's internal line-recognition rules, which belongs in
- // storage-config.ts, not here. Accepted trade-off: the false-positive
- // cost is low and self-resolving (the brain stays wedged with a clear,
- // actionable error until the user drops the pointless empty stanza or
- // fixes their syntax; retried on every subsequent sync); the
- // false-negative this guards against — silently committing db_only
- // content into permanent git history — is high-cost and hard to undo.
- if (dbOnlyDirs.length === 0) {
- const yamlPath = join(repoPath, 'gbrain.yml');
- const yamlContent = existsSync(yamlPath) ? readFileSync(yamlPath, 'utf-8') : '';
- // A YAML KEY line (`db_only:` / `supabase_only:`, ignoring leading
- // whitespace and `#` comments), not a bare substring search — round 9,
- // P2: a comment or unrelated prose value that happens to mention the
- // word (e.g. `# db_only handling TBD`) must not trip this guard on an
- // otherwise-genuinely-config-free gbrain.yml.
- const mentionsUnresolvedKey = yamlContent.split('\n').some((line) => {
- const trimmed = line.trim();
- return !trimmed.startsWith('#') && /^(db_only|supabase_only)\s*:/.test(trimmed);
- });
- if (mentionsUnresolvedKey) {
- throw new Error(
- `${yamlPath} mentions db_only but no directories resolved from it — refusing to ` +
- `auto-commit (cannot tell "genuinely empty" from "unsupported syntax silently ignored"). ` +
- `Fix gbrain.yml's storage.db_only syntax, or git-init this directory manually.`,
- );
- }
- }
- // #2964 (round 9, P1): every db_only dir is ALWAYS pathspec-excluded,
- // unconditionally — never pre-filtered against what an existing
- // `.gitignore` claims to already cover. An earlier version checked
- // `git check-ignore -q dir` first and skipped the pathspec when it
- // already reported "ignored" (to dodge the advisory error below), but
- // `check-ignore` on a directory can say "ignored" even when a
- // pre-existing `.gitignore` re-includes a child via negation (e.g.
- // `private-cache/*` + `!private-cache/index.md`) — the filter would
- // then skip excluding it via pathspec, and `git add -A` would stage
- // that re-included child despite the whole directory being declared
- // db_only. Our OWN pathspec exclusion is unconditional and doesn't
- // consult `.gitignore` at all, so it can't be defeated by ANY
- // .gitignore content, negated or not. `:(exclude,literal)dir` (not the
- // `:!dir` shorthand) so a db_only dir name that itself starts with a
- // pathspec magic character like `:` is excluded literally rather than
- // reinterpreted (round 9, P2).
- const excludePathspecs = dbOnlyDirs.map((dir) => `:(exclude,literal)${dir}`);
- // Clear the index before staging (round 6, P1): the unborn-HEAD
- // recovery site can reach this function with a repo whose index
- // already has entries staged from some OTHER prior operation (a manual
- // `git add`, an interrupted workflow) before gbrain ever touched it.
- // `add -A` only adds/updates — it does not drop an already-staged path
- // that our exclusion pathspecs above now want excluded. `read-tree
- // --empty` resets the index without touching the working tree; a
- // no-op on a freshly-`git init`-ed repo, whose index is already empty.
- git(repoPath, ['read-tree', '--empty']);
- try {
- // #2964: 10 minutes, not the shared git() helper's 30s default — this
- // full-tree `git add -A` walks a legacy brain that may hold years of
- // accumulated content. A 30s timeout would abort staging after `git
- // init` already created `.git`, leaving an unborn repo that every
- // subsequent sync would retry (and time out identically) forever;
- // the unborn-HEAD recovery path exists for OTHER causes of that
- // state, not to be this one's normal first outcome.
- git(repoPath, ['add', '-A', '--', '.', ...excludePathspecs], [], 600_000);
- } catch (err) {
- // Now that exclusion is always applied (never pre-filtered), an
- // explicit pathspec exclusion for a path a pre-existing `.gitignore`
- // ALSO happens to cover trips git's advice.addIgnoredFile: nonzero
- // exit + "paths ignored by one of your .gitignore files, use -f",
- // even though the add otherwise fully succeeded (verified directly:
- // `git status --short` right after this exact error shows every
- // non-excluded path staged correctly). Recognize and swallow ONLY
- // this exact advisory; anything else (timeout, permission denied,
- // real corruption) rethrows.
- const stderr = err && typeof err === 'object' && 'stderr' in err ? String((err as { stderr: unknown }).stderr) : '';
- if (!stderr.includes('ignored by one of your .gitignore files')) throw err;
- }
- git(
- repoPath,
- // --no-verify only skips pre-commit/commit-msg — prepare-commit-msg
- // and (worse, since it runs AFTER the commit object already exists,
- // synchronously inside this same git invocation) post-commit are
- // NOT covered by it. An operator's global core.hooksPath or
- // init.templateDir can wire either, expecting project tooling,
- // prompting interactively, or hanging — none of which a headless
- // self-heal commit can satisfy, and a hanging post-commit hook would
- // burn the 600s budget above without even being the slow step.
- // `-c core.hooksPath=/dev/null` (in configs, below) makes git look
- // for hook scripts inside a location that can't contain any,
- // disabling the entire hooks path for this one invocation — the
- // complete form of what --no-verify only partially covers, kept for
- // explicitness on the two hooks it does name.
- [
- 'commit', '--quiet', '--allow-empty', '--no-gpg-sign', '--no-verify',
- '-m', 'gbrain: initial commit (auto-init by sync)',
- ],
- ['user.name=gbrain', 'user.email=gbrain@localhost', 'core.hooksPath=/dev/null'],
- );
-}
-
-/**
- * True when `childReal` is `rootReal` itself or lives inside it. Both arguments
- * must already be realpath-resolved. Containment is decided by `relative()`
- * rather than a string prefix, so it holds on Windows too: `realpathSync`
- * returns backslash paths there, and a literal `rootReal + '/'` prefix can
- * never match one. A sibling (`root-evil`) is rejected because `relative`
- * yields `../root-evil`, and a cross-drive path because it yields an absolute.
- */
-export function isWithinRoot(childReal: string, rootReal: string): boolean {
- if (childReal === rootReal) return true;
- const rel = relative(rootReal, childReal);
- return rel !== '' && rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
-}
-
-/**
- * #774 NAV-1 TOCTOU: true only if filePath realpath-resolves inside gitRoot.
- * Guards symlink escape at the per-file level (a committed symlink whose
- * target lives outside the repo), not just at scope entry.
- */
-function isPathSafe(filePath: string, gitRoot: string): boolean {
- try {
- return isWithinRoot(realpathSync(filePath), realpathSync(gitRoot));
- } catch {
- return false;
- }
-}
-
-function hasOriginRemote(repoPath: string): boolean {
- try {
- execFileSync('git', buildGitInvocation(repoPath, ['remote', 'get-url', 'origin']), {
- encoding: 'utf-8',
- timeout: 30000,
- stdio: ['ignore', 'ignore', 'ignore'],
- });
- return true;
- } catch {
- return false;
- }
-}
-
-function isDetachedHead(repoPath: string): boolean {
- try {
- git(repoPath, ['symbolic-ref', '--quiet', 'HEAD']);
- return false;
- } catch {
- return true;
- }
-}
-
-function unique<T>(items: T[]): T[] {
- return [...new Set(items)];
-}
-
-// v0.42.42.0 (#2139): `buildDetachedWorkingTreeManifest` relocated to
-// `src/core/sync-delta.ts` (re-imported below) so the inline cost estimator
-// prices detached sources through the same code the executor imports them with.
-
-// v0.18.0 Step 5: source-scoped sync state helpers. When opts.sourceId
-// is set, read/write the per-source row instead of the global config
-// keys. These wrappers centralize the branch so every read/write site
-// picks the right storage — future Step 5 work (failure-tracking per
-// source) hooks here too.
-async function readSyncAnchor(
- engine: BrainEngine,
- sourceId: string | undefined,
- which: 'repo_path' | 'last_commit',
-): Promise<string | null> {
- if (sourceId) {
- const col = which === 'repo_path' ? 'local_path' : 'last_commit';
- const rows = await engine.executeRaw<Record<string, string | null>>(
- `SELECT ${col} AS value FROM sources WHERE id = $1`,
- [sourceId],
- );
- return rows[0]?.value ?? null;
- }
- return await engine.getConfig(`sync.${which}`);
-}
-
-/**
- * #2964: is `repoPath` gbrain's own default-brain anchor, as opposed to a
- * path some caller merely happened to pass through unchanged?
- *
- * `!opts.sourceId` alone is NOT sufficient — and neither is rejecting
- * `opts.sourceId` outright: migration `sources_table_additive` (v20)
- * seeds a `'default'` source row whose `local_path` is copied FROM
- * `config.sync.repo_path` on every brain that has ever run it (i.e.
- * effectively all of them by now), and `writeSyncAnchor` keeps that row's
- * `local_path` current on every sync thereafter. So on a real installed
- * brain, `resolveSourceForDir` (dream cycle) and the CLI's bare `gbrain
- * sync` both resolve `sourceId: 'default'`, NOT `undefined` — rejecting
- * all non-empty `sourceId` (an earlier, insufficiently-reviewed version
- * of this check) made self-heal never fire on that real path either,
- * masked in tests only because a freshly-`initSchema()`'d test brain's
- * `'default'` row has a null `local_path` (Codex review round 5).
- *
- * The actual boundary: `'default'` is gbrain's own bootstrap identity,
- * not something a caller names — a DIFFERENT, non-default `sourceId` is
- * what an explicit `sources add <id> --path <dir>` registration (a
- * user's own external directory) looks like, and that's what must keep
- * failing loudly. So: permit `sourceId` when it's exactly `undefined` or
- * `'default'`, reject any other id, and for BOTH permitted cases prove
- * ownership by VALUE — reread the live anchor for that same identity
- * (`sources.default.local_path` when sourceId='default', else
- * `config.sync.repo_path`) and require the resolved `repoPath` to
- * REALPATH-equal it (not raw string equality: `dream`'s `resolveBrainDir`
- * normalizes via `path.resolve`, so a trailing slash or `..` in the
- * stored anchor must not defeat the match — Codex review round 5, P2).
- * An arbitrary caller-supplied path (e.g. an admin-scope
- * `submit_job({name:'sync', data:{repoPath}})`) only passes this check
- * if it already equals gbrain's own anchor by realpath identity — at
- * which point self-healing it is exactly the legitimate case, not an
- * escalation.
- *
- * `opts.srcSubpath` disqualifies unconditionally: a subpath-scoped sync
- * only wants THAT subdirectory captured, but the self-heal baseline
- * commit runs `git add -A` at the git root (there's no file list yet to
- * scope it to — collection happens after this point) — see the P2 review
- * finding on `createSyncBaselineCommit`'s callers.
- */
-async function isAnchorOwnedSyncPath(
- engine: BrainEngine,
- opts: SyncOpts,
- repoPath: string,
-): Promise<boolean> {
- if (opts.srcSubpath) return false;
- if (opts.sourceId && opts.sourceId !== 'default') return false;
- const anchor = await readSyncAnchor(engine, opts.sourceId, 'repo_path');
- if (anchor === null) return false;
- try {
- return realpathSync(anchor) === realpathSync(repoPath);
- } catch {
- // Anchor or repoPath doesn't realpath-resolve (dangling/nonexistent) —
- // can't prove identity, so don't self-heal.
- return false;
- }
-}
-
-export async function writeSyncAnchor(
- engine: BrainEngine,
- sourceId: string | undefined,
- which: 'repo_path' | 'last_commit',
- value: string,
- // v0.41.32.0 (supersedes #1623): on `last_commit` advances, also stamp the
- // durable newest-COMMIT timestamp (HEAD committer time, epoch ms) in the SAME
- // atomic UPDATE as last_sync_at — no separate write to leave partial state,
- // no clock-domain split (last_sync_at = DB now(); newest_content_at = the
- // git-intrinsic committer time of the HEAD we just synced). `undefined` keeps
- // the legacy 2-column write; `null` clears the column (git unavailable).
- newestContentEpochMs?: number | null,
- // #2114: the repo dir this anchor write is FOR. Required to guard the
- // legacy branch's `last_commit` writes (where `value` is a hash, not a
- // dir). `repo_path` writes self-describe via `value`. Callers that omit
- // it on a legacy-path last_commit write keep pre-#2114 behavior.
- repoDir?: string,
-): Promise<void> {
- if (sourceId) {
- const col = which === 'repo_path' ? 'local_path' : 'last_commit';
- // last_sync_at bookmarked on every last_commit advance.
- if (which === 'last_commit') {
- if (newestContentEpochMs !== undefined) {
- const iso = newestContentEpochMs === null
- ? null
- : new Date(newestContentEpochMs).toISOString();
- await engine.executeRaw(
- `UPDATE sources SET last_commit = $1, last_sync_at = now(), newest_content_at = $3 WHERE id = $2`,
- [value, sourceId, iso],
- );
- } else {
- await engine.executeRaw(
- `UPDATE sources SET last_commit = $1, last_sync_at = now() WHERE id = $2`,
- [value, sourceId],
- );
- }
- } else {
- await engine.executeRaw(
- `UPDATE sources SET ${col} = $1 WHERE id = $2`,
- [value, sourceId],
- );
- }
- return;
- }
- // Legacy no-sourceId path (pre-v0.18 global config; also reached when a
- // caller could not resolve a source for the dir — dream --dir on an
- // unregistered directory, minion sync with an unmatched repoPath). #2114:
- // these globals describe THE brain repo, and this branch used to write
- // them unconditionally — a full-sync fallback against a foreign directory
- // silently repointed put_page write-through and poisoned the incremental
- // anchor. Refuse to move them for a directory that isn't the brain repo.
- const anchorDir = which === 'repo_path' ? value : repoDir;
- if (anchorDir !== undefined) {
- const { owns, configured } = await ownsGlobalSyncAnchor(engine, undefined, anchorDir);
- if (!owns) {
- serr(
- `[sync] sync.${which} stays at ${configured ?? '(unset)'} — not moving the ` +
- `global anchor for "${anchorDir}". To make that directory the brain repo: ` +
- `gbrain config set sync.repo_path "${anchorDir}"`,
- );
- return;
- }
- }
- await engine.setConfig(`sync.${which}`, value);
-}
-
-/**
- * v0.20.0 Cathedral II Layer 12 (SP-1 fix) — read/write the chunker version
- * last used to sync a given source. When it mismatches CURRENT_CHUNKER_VERSION,
- * `performSync` forces a full walk regardless of git HEAD equality. Without
- * this gate, bumping CHUNKER_VERSION does NOTHING on an unchanged repo
- * because sync short-circuits at `up_to_date` before reaching
- * `importCodeFile`'s content_hash check.
- *
- * Per-source storage matches writeSyncAnchor's shape — sources.chunker_version
- * TEXT column from the v27 migration. No global fallback: non-source syncs
- * (pre-v0.17 brains with no sources table) never had CHUNKER_VERSION
- * version-gating, so they keep the v0.19.0 behavior.
- */
-async function readChunkerVersion(
- engine: BrainEngine,
- sourceId: string | undefined,
-): Promise<string | null> {
- if (!sourceId) return null;
- const rows = await engine.executeRaw<{ chunker_version: string | null }>(
- `SELECT chunker_version FROM sources WHERE id = $1`,
- [sourceId],
- );
- return rows[0]?.chunker_version ?? null;
-}
-
-async function writeChunkerVersion(
- engine: BrainEngine,
- sourceId: string | undefined,
- version: string,
-): Promise<void> {
- if (!sourceId) return;
- await engine.executeRaw(
- `UPDATE sources SET chunker_version = $1 WHERE id = $2`,
- [version, sourceId],
- );
-}
+// The git-plumbing cluster (git(), discoverGitRoot, createSyncBaselineCommit,
+// path-containment guards, ...) was peeled to src/core/sync-git.ts (pure
+// move). Re-exported so existing importers keep working.
+export {
+ resolveSlugByPathOrSourcePath,
+ buildGitInvocation,
+ buildAutoEmbedArgs,
+ resolveNoEmbed,
+ discoverGitRoot,
+ classifyHeadProbeError,
+ createSyncBaselineCommit,
+ isWithinRoot,
+} from '../core/sync-git.ts';
+
+// The anchor / chunker-version cluster (readSyncAnchor, writeSyncAnchor,
+// readChunkerVersion, ...) was peeled to src/core/sync-anchor.ts (pure move).
+export { writeSyncAnchor } from '../core/sync-anchor.ts';
/**
* v0.40 Federated Sync v2: `gbrain sync trigger --source <id> [--priority high|normal|low]`
@@ -1557,22 +490,10 @@ See also:
console.log(`job_id=${job.id}`);
}
-/**
- * v0.42.x (#1794, Part B): typed lock-busy error so callers can distinguish a
- * benign "another sync holds the lock, skip cleanly" from a real failure.
- * Subclasses Error so existing CLI handlers that print `err.message` keep the
- * rich `formatLockBusyMessage` text verbatim. The Minion `sync` handler catches
- * this to mark the job skipped (not failed) — single-flight backpressure: the
- * cron/autopilot sync defers to the holder instead of erroring + retrying noisily.
- */
-export class SyncLockBusyError extends Error {
- readonly lockKey: string;
- constructor(message: string, lockKey: string) {
- super(message);
- this.name = 'SyncLockBusyError';
- this.lockKey = lockKey;
- }
-}
+// The lock layer minus performSync (SyncLockBusyError, formatLockBusyMessage,
+// runBreakLock, buildPartialResult) was peeled to src/core/sync-lock.ts
+// (pure move). Re-exported so existing importers keep working.
+export { SyncLockBusyError, runBreakLock } from '../core/sync-lock.ts';
export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {
// v0.22.13 CODEX-2: cross-process writer lock prevents two concurrent
@@ -1614,294 +535,6 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<
}
}
-/**
- * v0.41.6.0 D3: rich "Another sync is in progress" message that names the
- * holder PID, hostname, age, and the right --break-lock invocation to
- * recover. Falls back to the legacy message when inspectLock can't read
- * the row (best-effort — the lock itself was still busy).
- */
-async function formatLockBusyMessage(engine: BrainEngine, lockKey: string): Promise<string> {
- const { inspectLock } = await import('../core/db-lock.ts');
- let snap;
- try { snap = await inspectLock(engine, lockKey); }
- catch { snap = null; }
-
- if (!snap) {
- return (
- `Another sync is in progress (lock ${lockKey} held). ` +
- `Wait for it to finish, or run 'gbrain doctor' if it has been more than 30 minutes.`
- );
- }
-
- const ageHuman = formatAgeHuman(snap.age_ms);
- const breakHint = lockKey.startsWith('gbrain-sync:')
- ? `gbrain sync --break-lock --source ${lockKey.slice('gbrain-sync:'.length)}`
- : `gbrain sync --break-lock`;
- const ttlNote = snap.ttl_expired ? ' [TTL expired]' : '';
- return (
- `Another sync is in progress (lock ${lockKey} held by pid ${snap.holder_pid} on ${snap.holder_host}, ` +
- `started ${ageHuman} ago${ttlNote}).\n` +
- `If pid ${snap.holder_pid} is dead, re-run with --break-lock to clear it:\n` +
- ` ${breakHint}\n` +
- `Or wait for the holder to finish.`
- );
-}
-
-/**
- * v0.41.6.0 D3: `gbrain sync --break-lock` / `--force-break-lock` worker.
- * Returns the process exit code (0 = lock cleared or absent; 1 = refused).
- *
- * Safe path (`force=false`): refuses unless the holder is on this host
- * AND either (a) TTL has expired (the lock is structurally available
- * already) OR (b) the holder PID is dead AND the lock is older than 60s
- * (the age guard defeats PID-reuse coincidence — Linux PID space wraps
- * at 32768 so a 10-day-old lock with pid=12345 may be falsely
- * refused-to-clear because an unrelated process now owns pid 12345; 60s
- * is the codex F7-amended minimum age that makes coincidence unlikely).
- *
- * Force path (`force=true`): skips liveness check, deletes the row,
- * warns loudly that the holder may still be writing.
- *
- * Both paths use the same atomic `DELETE ... RETURNING id` so a race
- * with another break-lock or with TTL-eviction can't produce confusing
- * post-conditions.
- */
-export async function runBreakLock(
- engine: BrainEngine,
- lockKey: string,
- sourceId: string,
- opts: { force: boolean; json: boolean; maxAgeSeconds?: number },
-): Promise<number> {
- const { inspectLock, deleteLockRow, deleteLockRowIfStale, classifyHolderLiveness } = await import('../core/db-lock.ts');
- const { hostname } = await import('os');
- const localHost = hostname();
- let snap;
- try { snap = await inspectLock(engine, lockKey); }
- catch (e) {
- const msg = e instanceof Error ? e.message : String(e);
- if (opts.json) console.log(JSON.stringify({ status: 'error', error: msg, lock: lockKey }));
- else console.error(`Failed to inspect lock ${lockKey}: ${msg}`);
- return 1;
- }
-
- if (!snap) {
- // BUG 5 (v0.42.x): --force-break-lock used to emit the same terse "not
- // held" line and exit 0 even when a sync was genuinely wedged — sending the
- // operator down a dead end (the wedge was not a held lock). Keep rc=0
- // (breaking a non-existent lock is idempotently successful; flipping the
- // exit code would break automation that treats it as success), but under
- // --force say plainly that nothing was broken and point at the real next
- // step. The non-force path message is unchanged.
- if (opts.force) {
- const wedgeHint =
- `No lock is held on ${lockKey} — nothing to break. If a sync still ` +
- `appears wedged, the cause is not a held lock; inspect checkpoint/resume ` +
- `state with \`gbrain sync --source ${sourceId}\` or \`gbrain doctor\`.`;
- if (opts.json) {
- console.log(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId, wedge_hint: wedgeHint }));
- } else {
- console.log(wedgeHint);
- }
- return 0;
- }
- if (opts.json) console.log(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId }));
- else console.log(`Lock ${lockKey} is not held (nothing to break).`);
- return 0;
- }
-
- // v0.41.13.0 (T4 / D-V3-4 / D-V4-mech-4) — --max-age path: route through
- // deleteLockRowIfStale which runs a single atomic DELETE keyed on
- // (id, holder_pid, last_refreshed_at < NOW() - maxAge). Healthy refreshing
- // holders survive by construction (their last_refreshed_at is recent).
- // Wedged-but-alive holders (JS interval stopped firing) get broken.
- // No TOCTOU between inspect + delete; the WHERE clause is the gate.
- if (opts.maxAgeSeconds !== undefined && !opts.force) {
- // Cross-host guard preserved from the safe path: --max-age does NOT
- // bypass cross-host refusal because process.kill(pid, 0) is invalid
- // across hosts (PID is meaningful only on the same host). Operators
- // who need to clear a cross-host lock use --force-break-lock.
- if (snap.holder_host !== localHost) {
- if (opts.json) {
- console.log(JSON.stringify({
- status: 'refused', reason: 'cross_host', lock: lockKey, source_id: sourceId,
- snapshot: snap, local_host: localHost,
- }));
- } else {
- console.error(`Lock ${lockKey} is held on a different host (${snap.holder_host}, this host is ${localHost}).`);
- console.error('Cross-host --max-age is unsupported. Use --force-break-lock when certain the remote holder is dead.');
- }
- return 1;
- }
- const { deleted, lastRefreshedAt } = await deleteLockRowIfStale(
- engine, lockKey, snap.holder_pid, opts.maxAgeSeconds,
- );
- if (opts.json) {
- console.log(JSON.stringify({
- status: deleted ? 'broken' : 'refused',
- reason: deleted ? 'max_age_breached' : 'within_max_age',
- lock: lockKey,
- source_id: sourceId,
- snapshot: snap,
- max_age_seconds: opts.maxAgeSeconds,
- last_refreshed_at: lastRefreshedAt ? lastRefreshedAt.toISOString() : null,
- }));
- } else if (deleted) {
- const ageStr = lastRefreshedAt ? formatAgeHuman(Date.now() - lastRefreshedAt.getTime()) : 'unknown';
- console.log(`Broke lock ${lockKey} (pid ${snap.holder_pid} on ${snap.holder_host}; last refresh was ${ageStr} ago, > --max-age=${opts.maxAgeSeconds}s).`);
- } else {
- // last_refreshed_at within --max-age window OR null (pre-v98 brain).
- // Distinguish the two cases for the operator.
- if (snap.last_refreshed_at === null) {
- console.error(`Lock ${lockKey} has NULL last_refreshed_at (pre-v98 brain or migration window).`);
- console.error('Run `gbrain apply-migrations --yes` to land v98, OR use --force-break-lock if you know the holder is dead.');
- } else {
- const ageStr = snap.ms_since_last_refresh != null ? formatAgeHuman(snap.ms_since_last_refresh) : 'unknown';
- console.error(`Refusing to break lock ${lockKey}: last refresh was ${ageStr} ago, within --max-age=${opts.maxAgeSeconds}s window.`);
- console.error('The holder is actively refreshing — likely a healthy long-running sync.');
- }
- return 1;
- }
- return 0;
- }
-
- // Force path: skip all guards, atomic DELETE, warn.
- if (opts.force) {
- const { deleted } = await deleteLockRow(engine, lockKey, snap.holder_pid);
- if (opts.json) {
- console.log(JSON.stringify({
- status: deleted ? 'force_broken' : 'race_already_cleared',
- lock: lockKey, source_id: sourceId, snapshot: snap,
- }));
- } else if (deleted) {
- console.log(`Force-broke lock ${lockKey} (was held by pid ${snap.holder_pid} on ${snap.holder_host}, age ${formatAgeHuman(snap.age_ms)}).`);
- console.log('WARNING: the holder may still be writing. Verify with `gbrain doctor` before re-running.');
- } else {
- console.log(`Lock ${lockKey} was already cleared by another process between our check and DELETE (race-safe).`);
- }
- return 0;
- }
-
- // Safe path: must be local host AND (TTL-expired OR (PID-dead AND age >= 60s)).
- if (snap.holder_host !== localHost) {
- if (opts.json) {
- console.log(JSON.stringify({
- status: 'refused',
- reason: 'cross_host',
- lock: lockKey, source_id: sourceId, snapshot: snap, local_host: localHost,
- }));
- } else {
- console.error(`Lock ${lockKey} is held on a different host (${snap.holder_host}, this host is ${localHost}).`);
- console.error('Cross-host PID liveness is unsound. To break anyway, use --force-break-lock');
- console.error('(only safe when you KNOW the holder is dead — verify before forcing).');
- }
- return 1;
- }
-
- let safe = false;
- let reason: string;
- if (snap.ttl_expired) {
- safe = true;
- reason = 'ttl_expired';
- } else {
- // PID liveness on local host, via the shared predicate (v0.42 #1780 Gap 3).
- // Same gate as tryAcquireDbLock's auto-takeover: same-host + provably-dead
- // (ESRCH) + age >= 60s. EPERM is treated as ALIVE (the PID exists but isn't
- // ours) — never break a live lock. host is already == localHost here (the
- // cross-host branch returned above), so classify never yields 'cross_host'.
- const liveness = classifyHolderLiveness(snap.holder_pid, snap.holder_host, snap.age_ms);
- if (liveness === 'dead_eligible') {
- safe = true;
- reason = 'pid_dead_age_60s';
- } else if (liveness === 'too_young') {
- reason = 'pid_dead_but_lock_too_young';
- } else {
- // 'alive' | 'unknown' | 'cross_host' (the latter unreachable here).
- reason = 'pid_alive';
- }
- }
-
- if (!safe) {
- if (opts.json) {
- console.log(JSON.stringify({
- status: 'refused', reason, lock: lockKey, source_id: sourceId, snapshot: snap,
- }));
- } else {
- console.error(`Refusing to break lock ${lockKey}: holder pid ${snap.holder_pid} appears alive on ${snap.holder_host} (age ${formatAgeHuman(snap.age_ms)}).`);
- if (reason === 'pid_dead_but_lock_too_young') {
- console.error('(PID is dead but the lock is younger than 60s — the PID may have been reused. Wait or use --force-break-lock if you are certain.)');
- } else {
- console.error('If the holder is wedged, kill it first then re-run --break-lock,');
- console.error('OR use --force-break-lock to clear regardless (the holder may still write afterwards).');
- }
- }
- return 1;
- }
-
- const { deleted } = await deleteLockRow(engine, lockKey, snap.holder_pid);
- if (opts.json) {
- console.log(JSON.stringify({
- status: deleted ? 'broken' : 'race_already_cleared',
- reason, lock: lockKey, source_id: sourceId, snapshot: snap,
- }));
- } else if (deleted) {
- console.log(`Broke lock ${lockKey} (was held by pid ${snap.holder_pid} on ${snap.holder_host}, age ${formatAgeHuman(snap.age_ms)}; reason: ${reason}).`);
- } else {
- console.log(`Lock ${lockKey} was already cleared by another process between our check and DELETE (race-safe).`);
- }
- return 0;
-}
-
-function formatAgeHuman(ms: number): string {
- if (ms < 1000) return `${ms}ms`;
- const s = Math.floor(ms / 1000);
- if (s < 60) return `${s}s`;
- const m = Math.floor(s / 60);
- if (m < 60) return `${m}m${s % 60}s`;
- const h = Math.floor(m / 60);
- if (h < 24) return `${h}h${m % 60}m`;
- const d = Math.floor(h / 24);
- return `${d}d${h % 24}h`;
-}
-
-/**
- * v0.41.13.0 — build a SyncResult { status: 'partial' } envelope.
- *
- * D-V3-1 invariant: this is only ever called BEFORE the bookmark write at
- * sync.ts:writeSyncAnchor('last_commit'), so `last_commit` is NEVER advanced
- * on partial. The next sync re-walks last_commit..HEAD and `content_hash`
- * short-circuits already-imported files at ~10ms each. The caller's lock is
- * released by `withRefreshingLock`'s try/finally as soon as this returns.
- */
-function buildPartialResult(opts: {
- fromCommit: string | null;
- toCommit: string;
- filesImported: number;
- pagesAffected: string[];
- chunksCreated: number;
- added: number;
- modified: number;
- deleted: number;
- renamed: number;
- reason: 'timeout' | 'pull_timeout' | 'pull_failed' | 'stall_timeout' | 'checkpoint_unavailable';
- bankedFiles?: number;
-}): SyncResult {
- return {
- status: 'partial',
- fromCommit: opts.fromCommit,
- toCommit: opts.toCommit,
- added: opts.added,
- modified: opts.modified,
- deleted: opts.deleted,
- renamed: opts.renamed,
- chunksCreated: opts.chunksCreated,
- embedded: 0,
- pagesAffected: opts.pagesAffected,
- filesImported: opts.filesImported,
- reason: opts.reason,
- bankedFiles: opts.bankedFiles,
- };
-}
-
async function performSyncInner(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {
// v0.41.8.0 (D9 / #1342): phase breadcrumbs. The #1342 reporter saw
// ZERO stderr output before their sync hang, which made the bug
@@ -4144,208 +2777,24 @@ async function performFullSync(
};
}
-/**
- * #2828 full-sync reconcile safety-valve thresholds. A reconcile that would
- * delete more than MASS_RECONCILE_RATIO of the file-backed pages a strategy
- * manages, on a source that holds more than MASS_RECONCILE_MIN_PAGES of them, is
- * treated as a suspected path-comparison bug rather than a real bulk deletion.
- */
-export const MASS_RECONCILE_RATIO = 0.5;
-export const MASS_RECONCILE_MIN_PAGES = 20;
-
-/**
- * Normalize path separators so a page whose stored `source_path` was written
- * with a different separator than the local OS's `path.relative` produces (e.g.
- * git-derived forward-slash paths on a Windows checkout) still compares equal.
- * Without this, on Windows every file-backed page looks stale and the reconcile
- * wrongly deletes the whole source (#2828).
- */
-function normalizeReconcilePath(p: string): string {
- return p.replace(/\\/g, '/');
-}
-
-export interface ReconcilePlan {
- /** Slugs whose backing file is genuinely gone; safe to reconcile-delete. */
- staleSlugs: string[];
- /**
- * File-backed, in-strategy pages the reconcile can act on. This is the
- * denominator for the mass-delete valve (the exact population at risk).
- */
- reconcilableCount: number;
- /**
- * True when `staleSlugs` would sweep more than MASS_RECONCILE_RATIO of
- * `reconcilableCount`, on a source with more than MASS_RECONCILE_MIN_PAGES of
- * them — the mass-delete signal that trips the safety valve.
- */
- massDelete: boolean;
-}
-
-/**
- * #2828: decide which file-backed pages a full-sync reconcile should delete, and
- * whether that deletion is suspiciously large. Pure and exported so both the
- * separator normalization and the mass-delete valve are unit-testable without a
- * live engine or a Windows host.
- *
- * @param rows pages with a non-null `source_path` (deleted_at IS NULL).
- * @param currentFiles repo-relative paths present in the working tree.
- * @param isSyncablePath predicate excluding metafiles and the wrong strategy.
- */
-export function planReconcileDeletes(
- rows: ReadonlyArray<{ slug: string; source_path: string | null }>,
- currentFiles: Iterable<string>,
- isSyncablePath: (p: string) => boolean,
-): ReconcilePlan {
- const current = new Set<string>();
- for (const f of currentFiles) current.add(normalizeReconcilePath(f));
- const reconcilable = rows.filter(
- r => r.source_path != null && isSyncablePath(r.source_path),
- );
- const staleSlugs = reconcilable
- .filter(r => !current.has(normalizeReconcilePath(r.source_path as string)))
- .map(r => r.slug);
- const massDelete =
- reconcilable.length > MASS_RECONCILE_MIN_PAGES &&
- staleSlugs.length > reconcilable.length * MASS_RECONCILE_RATIO;
- return { staleSlugs, reconcilableCount: reconcilable.length, massDelete };
-}
-
-/**
- * #2426: every repo-relative path that ever appeared as an ADD in git history
- * (rename detection off, so a `git mv` destination still counts as an add).
- * Used by the full-sync reconcile to distinguish "file was committed and later
- * deleted" (genuine delete → reconcile) from "file was NEVER committed"
- * (DB-only write-through → preserve). Returns null when `repoPath` isn't a git
- * work tree or git is unavailable — callers keep the plain-directory behavior.
- * Forward-slash-normalized to match `normalizeReconcilePath` membership tests.
- */
-export function listEverCommittedPaths(repoPath: string): Set<string> | null {
- let stdout: string;
- try {
- stdout = execFileSync(
- 'git',
- ['-C', repoPath, '-c', 'core.quotepath=off', 'log', '--all', '--no-renames',
- '--diff-filter=A', '--format=', '--name-only'],
- { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },
- );
- } catch {
- return null;
- }
- const set = new Set<string>();
- for (const line of stdout.split('\n')) {
- if (line) set.add(line.replace(/\\/g, '/'));
- }
- return set;
-}
-
-/**
- * #2828 escape hatch: `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the pre-valve
- * behavior for the rare intentional bulk removal. Env-only (an incident-time
- * override), mirroring `resolveStallAbortSeconds`' pure, env-parameterized shape.
- */
-export function massReconcileAllowed(
- env: Record<string, string | undefined> = process.env,
-): boolean {
- return env.GBRAIN_ALLOW_MASS_RECONCILE === '1';
-}
-
-/**
- * Grace window (seconds) between the watchdog's SIGTERM and SIGKILL. SIGTERM
- * gives a responsive loop a clean shutdown; SIGKILL is the starvation backstop.
- */
-export const HARD_DEADLINE_GRACE_SEC = 30;
-
-export interface HardDeadlineResolution {
- deadlineMs: number;
- graceMs: number;
- /** Where the deadline came from (for the armed-log line + tests). */
- reason: string;
-}
-
-/**
- * #1950: default no-import-progress window before the in-band stall watchdog
- * aborts the drain. Generous on purpose — it must clear one legitimately large
- * file (cross-region, big page) without false-tripping; one file taking longer
- * than this trips it (documented limit). Distinct from the wall-clock hard
- * deadline (whole-run cap) and the lock heartbeat (refreshes regardless of
- * import progress). Env-tunable; <=0 disables.
- */
-export const DEFAULT_SYNC_STALL_ABORT_SEC = 900;
-
-export function resolveStallAbortSeconds(
- env: Record<string, string | undefined> = process.env,
-): number {
- const raw = env.GBRAIN_SYNC_STALL_ABORT_SECONDS;
- if (raw === undefined || raw === '') return DEFAULT_SYNC_STALL_ABORT_SEC;
- const n = Number(raw);
- if (!Number.isFinite(n)) return DEFAULT_SYNC_STALL_ABORT_SEC;
- return n; // n <= 0 disables the watchdog
-}
-
-/**
- * Resolve the out-of-band hard-deadline for a `gbrain sync` invocation (#1633).
- * Pure + argv/env-only so it runs BEFORE `connectEngine` (so a connect-phase hang
- * is also bounded — `timeout-layer-vs-connectengine` learning). DB-plane config
- * (`gbrain config set`) is unreadable pre-connect, so the operator knob is the
- * `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env var; bare cron is covered by the non-TTY
- * default. Returns null when no watchdog should arm (TTY interactive with no
- * flag, or an explicit opt-out / 0).
- *
- * Precedence: --no-hard-deadline > --hard-deadline > --timeout(non-all) > env >
- * non-TTY default (3600s) > none.
- */
-export function resolveSyncHardDeadline(
- args: string[],
- opts: { isTty: boolean; env?: Record<string, string | undefined>; defaultNonTtySec?: number },
-): HardDeadlineResolution | null {
- const env = opts.env ?? {};
- const graceMs = HARD_DEADLINE_GRACE_SEC * 1000;
- const mk = (sec: number, reason: string): HardDeadlineResolution | null =>
- sec > 0 ? { deadlineMs: sec * 1000, graceMs, reason } : null;
-
- if (args.includes('--no-hard-deadline')) return null;
-
- const hardStr = args.find((a, i) => args[i - 1] === '--hard-deadline');
- if (hardStr !== undefined) {
- // Throws on a bad value (cli.ts surfaces it + exits 1) — same posture as --timeout.
- const sec = parseDurationSeconds(hardStr, '--hard-deadline');
- return mk(sec ?? 0, 'flag:--hard-deadline');
- }
-
- // --timeout auto-arms a hard backstop at timeout(+grace), but ONLY single-source.
- // For --all, per-source budgets don't collapse to one wall-clock; fall through.
- const isAll = args.includes('--all');
- const timeoutStr = args.find((a, i) => args[i - 1] === '--timeout');
- if (timeoutStr !== undefined && !isAll) {
- const sec = parseDurationSeconds(timeoutStr, '--timeout');
- if (sec && sec > 0) return mk(sec, 'flag:--timeout');
- }
-
- const envRaw = env.GBRAIN_SYNC_MAX_RUNTIME_SECONDS;
- if (envRaw !== undefined && envRaw !== '') {
- const n = Number(envRaw);
- if (Number.isFinite(n)) return mk(n, 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS'); // n<=0 disables
- }
-
- if (!opts.isTty) return mk(opts.defaultNonTtySec ?? 3600, 'default:non-tty');
-
- return null;
-}
-
-/**
- * Compose 1..N AbortSignals into one (CQ2). Undefined inputs are dropped; the
- * result aborts when ANY input aborts. Returns a single signal directly (no
- * wrapper), `undefined` when nothing is set. Used at both performSync call sites
- * so the SIGINT graceful-cancel signal and the per-source `--timeout` signal
- * compose without duplicating `AbortSignal.any` logic.
- */
-export function composeAbortSignals(
- ...signals: Array<AbortSignal | undefined>
-): AbortSignal | undefined {
- const live = signals.filter((s): s is AbortSignal => s !== undefined);
- if (live.length === 0) return undefined;
- if (live.length === 1) return live[0];
- return AbortSignal.any(live);
-}
+// The reconcile + deadline cluster (planReconcileDeletes, the #2828
+// mass-delete valve, resolveSyncHardDeadline, composeAbortSignals, ...) was
+// peeled to src/core/sync-reconcile.ts (pure move). Re-exported so existing
+// importers keep working.
+export {
+ MASS_RECONCILE_RATIO,
+ MASS_RECONCILE_MIN_PAGES,
+ type ReconcilePlan,
+ planReconcileDeletes,
+ listEverCommittedPaths,
+ massReconcileAllowed,
+ HARD_DEADLINE_GRACE_SEC,
+ type HardDeadlineResolution,
+ DEFAULT_SYNC_STALL_ABORT_SEC,
+ resolveStallAbortSeconds,
+ resolveSyncHardDeadline,
+ composeAbortSignals,
+} from '../core/sync-reconcile.ts';
/**
* #753/#774: `.gitignore` must be managed at the git ROOT — when a source's
@@ -5414,335 +3863,15 @@ export async function syncOneSource(
return { result, log };
}
-/**
- * v0.40.3.0 — read-only per-source dashboard for `gbrain sources status`.
- *
- * Aggregates from existing tables (no schema changes):
- * - sources: last_commit, last_sync_at, archived, config.syncEnabled
- * (filtered: archived=false, local_path IS NOT NULL)
- * - pages: per-source page count (excluding soft-deleted)
- * - content_chunks: per-source total + count of unembedded chunks for
- * the ACTIVE embedding column (resolved via the
- * registry — see `src/core/search/embedding-column.ts`).
- * Voyage / multimodal / non-default-column brains
- * see counts against the column they actually use.
- * - sync-failures.jsonl: unacknowledged failures (brain-global; the
- * JSONL log isn't per-source. v0.40.4 TODO source-scopes it.)
- *
- * Staleness thresholds match `gbrain doctor`'s sync-freshness rule
- * (24h / 72h). Sources that have NEVER synced (last_sync_at IS NULL)
- * report `staleness_hours: null` so callers can disambiguate "first run
- * pending" from "32h since last successful sync".
- *
- * Errors propagate. Pre-v0.40.3.0 the dashboard swallowed all DB errors
- * and reported zero counts, which lied at exactly the moment it mattered
- * (Q2 sub-fix from Codex review). The dashboard is read-only — a thrown
- * error surfaces the real problem (DB down, permission denied, statement
- * timeout) instead of misleading the operator with a "0 chunks" report.
- */
-export interface SyncStatusReportSource {
- source_id: string;
- name: string;
- local_path: string | null;
- sync_enabled: boolean;
- last_sync_at: string | null;
- /** Raw wall-clock hours since the last successful sync — the honest human
- * number. Distinct from staleness_hours, which is threshold-relative. */
- hours_since_last_sync: number | null;
- /** Threshold-relative lag driving staleness_class. For a source whose
- * content is OLDER than its last sync this is the ceiling-ramped value
- * (see lagFromContentMs), which deliberately under-reads raw wall-clock so
- * the warn tier fires before the fail tier — display hours_since_last_sync
- * when a human asks "how long since we synced". */
- staleness_hours: number | null;
- staleness_class: 'fresh' | 'stale' | 'severe' | 'unknown';
- last_commit: string | null;
- pages: number;
- chunks_total: number;
- chunks_unembedded: number;
- embedding_coverage_pct: number;
- // v0.41.31: embed-backfill job visibility (federated_v2 defers embedding
- // to these jobs; without this an operator can't see queued/lagging work
- // after `sync --all` exits 0). Best-effort — all 0 / null on brains
- // without the minion_jobs table.
- backfill_queued: number;
- backfill_active: number;
- backfill_last_completed_at: string | null;
-}
-
-export interface SyncStatusReport {
- schema_version: 1;
- generated_at: string;
- sources: SyncStatusReportSource[];
- unacknowledged_failures: number;
- /** The embedding column counts were computed against. Useful for
- * operators verifying their Voyage / multimodal setup is reported
- * correctly. */
- embedding_column: string;
-}
-
-export async function buildSyncStatusReport(
- engine: BrainEngine,
- sources: Array<{ id: string; name: string; local_path: string | null; config: Record<string, unknown> }>,
-): Promise<SyncStatusReport> {
- // Resolve the active embedding column via the registry. Brains pointed
- // at Voyage / multimodal / any non-default column get accurate counts
- // for the column they actually use (D16 → A, Codex P2 #10).
- const { resolveEmbeddingColumn, quoteIdentifier } = await import('../core/search/embedding-column.ts');
- // loadConfig() returns null when ~/.gbrain/config.json is missing.
- // resolveEmbeddingColumn handles missing fields via its own
- // gateway-fallback chain, so a minimal stub satisfies the call shape.
- const cfg = loadConfig() ?? ({ engine: engine.kind } as Parameters<typeof resolveEmbeddingColumn>[1]);
- const resolved = resolveEmbeddingColumn(undefined, cfg);
- const embeddingColIdent = quoteIdentifier(resolved.name);
-
- const sourceIds = sources.map((s) => s.id);
- type SourceRow = {
- id: string;
- last_commit: string | null;
- last_sync_at: string | Date | null;
- // v0.41.32.0: remote staleness reads this column (no git subprocess).
- newest_content_at: string | Date | null;
- };
- type CountRow = {
- source_id: string;
- pages: string | number;
- chunks_total: string | number;
- chunks_unembedded: string | number;
- };
-
- // Pull last_commit + last_sync_at fresh (caller may have called us
- // with stale rows). Empty source list → skip the round-trip.
- const sourceRows = sourceIds.length === 0
- ? []
- : await engine.executeRaw<SourceRow>(
- `SELECT id, last_commit, last_sync_at, newest_content_at FROM sources WHERE id = ANY($1::text[])`,
- [sourceIds],
- );
- const sourceMap = new Map<string, SourceRow>();
- for (const r of sourceRows) sourceMap.set(r.id, r);
-
- // Per-source page + chunk + unembedded-chunk counts in a single
- // round-trip. Canonical SQL (verified against
- // src/commands/doctor.ts:2740): content_chunks joined on page_id
- // (NOT page_slug — Codex P0 #1), filtered for non-soft-deleted pages
- // (NOT NULL — soft-delete shipped v0.26.5), unembedded counted
- // against the resolved active embedding column (D16 → A).
- //
- // No try/catch swallow — a thrown error means DB down / permission
- // denied / statement timeout (NOT a schema variant). Surfacing the
- // real error is better than a misleading "0 chunks" report (Q2).
- let countRows: CountRow[] = [];
- if (sourceIds.length > 0) {
- countRows = await engine.executeRaw<CountRow>(
- `WITH s AS (
- SELECT unnest($1::text[]) AS source_id
- )
- SELECT
- s.source_id,
- COALESCE(p.pages, 0) AS pages,
- COALESCE(c.chunks_total, 0) AS chunks_total,
- COALESCE(c.chunks_unembedded, 0) AS chunks_unembedded
- FROM s
- LEFT JOIN (
- SELECT source_id, COUNT(*) AS pages
- FROM pages
- WHERE deleted_at IS NULL
- GROUP BY source_id
- ) p ON p.source_id = s.source_id
- LEFT JOIN (
- SELECT pg.source_id,
- COUNT(*) AS chunks_total,
- COUNT(*) FILTER (WHERE cc.${embeddingColIdent} IS NULL) AS chunks_unembedded
- FROM content_chunks cc
- JOIN pages pg ON pg.id = cc.page_id
- WHERE pg.deleted_at IS NULL
- GROUP BY pg.source_id
- ) c ON c.source_id = s.source_id`,
- [sourceIds],
- );
- }
- const countMap = new Map<string, { pages: number; chunks_total: number; chunks_unembedded: number }>();
- for (const r of countRows) {
- countMap.set(r.source_id, {
- pages: Number(r.pages) || 0,
- chunks_total: Number(r.chunks_total) || 0,
- chunks_unembedded: Number(r.chunks_unembedded) || 0,
- });
- }
-
- // v0.41.31: per-source embed-backfill job state. Best-effort — the
- // minion_jobs table doesn't exist on every brain (a brain that never ran
- // a worker has the pre-minions schema), and the dashboard must not crash
- // for that. A failure → empty map → all sources report 0/null.
- type BackfillRow = {
- source_id: string | null;
- queued: string | number;
- active: string | number;
- last_completed_at: string | Date | null;
- };
- const backfillMap = new Map<string, { queued: number; active: number; last_completed_at: string | null }>();
- if (sourceIds.length > 0) {
- try {
- const backfillRows = await engine.executeRaw<BackfillRow>(
- `SELECT data->>'sourceId' AS source_id,
- COUNT(*) FILTER (WHERE status IN ('waiting','delayed','waiting-children'))::int AS queued,
- COUNT(*) FILTER (WHERE status = 'active')::int AS active,
- MAX(finished_at) FILTER (WHERE status = 'completed') AS last_completed_at
- FROM minion_jobs
- WHERE name = 'embed-backfill' AND data->>'sourceId' = ANY($1::text[])
- GROUP BY data->>'sourceId'`,
- [sourceIds],
- );
- for (const r of backfillRows) {
- if (!r.source_id) continue;
- const last = r.last_completed_at;
- backfillMap.set(r.source_id, {
- queued: Number(r.queued) || 0,
- active: Number(r.active) || 0,
- last_completed_at: last == null ? null : (last instanceof Date ? last.toISOString() : last),
- });
- }
- } catch {
- // minion_jobs absent / unreadable → leave backfillMap empty.
- }
- }
-
- const now = Date.now();
- const out: SyncStatusReportSource[] = sources.map((src) => {
- const cfgEntry = (src.config || {}) as { syncEnabled?: boolean };
- const row = sourceMap.get(src.id) || { id: src.id, last_commit: null, last_sync_at: null, newest_content_at: null };
- const counts = countMap.get(src.id) || { pages: 0, chunks_total: 0, chunks_unembedded: 0 };
- const lastSyncMs = row.last_sync_at
- ? (row.last_sync_at instanceof Date ? row.last_sync_at.getTime() : Date.parse(row.last_sync_at))
- : null;
- // v0.41.32.0: commit-relative staleness from the stored column — NO git
- // subprocess (this function backs the remote get_status_snapshot MCP op,
- // so it must honor the v0.41.27.0 trust boundary). A quiet repo whose
- // newest commit predates its last sync reports 0; null column → wall-clock.
- const contentMs = row.newest_content_at
- ? (row.newest_content_at instanceof Date ? row.newest_content_at.getTime() : Date.parse(row.newest_content_at))
- : null;
- const lagSeconds = lagFromContentMs(
- Number.isFinite(contentMs as number) ? (contentMs as number) : null,
- lastSyncMs !== null && Number.isFinite(lastSyncMs) ? lastSyncMs : null,
- now,
- );
- const stalenessHours = lagSeconds === null ? null : lagSeconds / 3600;
- const hoursSinceLastSync = lastSyncMs !== null && Number.isFinite(lastSyncMs)
- ? Math.round(((now - lastSyncMs) / 3600_000) * 10) / 10
- : null;
- let stalenessClass: 'fresh' | 'stale' | 'severe' | 'unknown' = 'unknown';
- if (stalenessHours !== null) {
- if (stalenessHours < 24) stalenessClass = 'fresh';
- else if (stalenessHours < 72) stalenessClass = 'stale';
- else stalenessClass = 'severe';
- }
- const embeddingCoveragePct = counts.chunks_total === 0
- ? 100
- : Math.round(((counts.chunks_total - counts.chunks_unembedded) / counts.chunks_total) * 1000) / 10;
- const lastSyncIso = row.last_sync_at
- ? (row.last_sync_at instanceof Date ? row.last_sync_at.toISOString() : row.last_sync_at)
- : null;
- return {
- source_id: src.id,
- name: src.name,
- local_path: src.local_path,
- sync_enabled: cfgEntry.syncEnabled !== false,
- last_sync_at: lastSyncIso,
- hours_since_last_sync: hoursSinceLastSync,
- staleness_hours: stalenessHours === null ? null : Math.round(stalenessHours * 10) / 10,
- staleness_class: stalenessClass,
- last_commit: row.last_commit,
- pages: counts.pages,
- chunks_total: counts.chunks_total,
- chunks_unembedded: counts.chunks_unembedded,
- embedding_coverage_pct: embeddingCoveragePct,
- backfill_queued: backfillMap.get(src.id)?.queued ?? 0,
- backfill_active: backfillMap.get(src.id)?.active ?? 0,
- backfill_last_completed_at: backfillMap.get(src.id)?.last_completed_at ?? null,
- };
- });
-
- // Unacknowledged sync failures — brain-global (the JSONL log isn't
- // per-source). v0.40.4 TODO will source-scope this. Best-effort:
- // missing file / parse error returns 0, doesn't throw the dashboard.
- let unackedCount = 0;
- try {
- unackedCount = unacknowledgedSyncFailures().length;
- } catch {
- unackedCount = 0;
- }
-
- return {
- schema_version: 1,
- generated_at: new Date().toISOString(),
- sources: out,
- unacknowledged_failures: unackedCount,
- embedding_column: resolved.name,
- };
-}
-
-/**
- * v0.40.3.0 — render a `SyncStatusReport` as a human-readable table.
- *
- * `sink` defaults to `process.stdout` so the bare `gbrain sources status`
- * invocation writes its table to stdout. `--json` callers don't use
- * this — they emit `JSON.stringify(report)` to stdout directly.
- */
-export function printSyncStatusReport(
- report: SyncStatusReport,
- sink: NodeJS.WriteStream = process.stdout,
-): void {
- const write = (line: string) => sink.write(line + '\n');
- write(`\nSync status — generated ${report.generated_at}`);
- write(`Embedding column: ${report.embedding_column}\n`);
- if (report.sources.length === 0) {
- write(' (no sources registered)');
- return;
- }
- const headers = ['SOURCE', 'STATE', 'STALENESS', 'PAGES', 'EMBEDDED', 'BACKFILL', 'LAST SYNC'];
- const rows = report.sources.map((s) => {
- const stale = s.staleness_hours === null
- ? 'never'
- : `${s.staleness_hours.toFixed(1)}h`;
- const stateBits: string[] = [];
- if (!s.sync_enabled) stateBits.push('disabled');
- stateBits.push(s.staleness_class);
- // BACKFILL: active beats queued beats idle for the at-a-glance cell.
- const backfill = s.backfill_active > 0
- ? `active(${s.backfill_active})`
- : s.backfill_queued > 0
- ? `queued(${s.backfill_queued})`
- : 'idle';
- return [
- s.name,
- stateBits.join(','),
- stale,
- String(s.pages),
- `${s.embedding_coverage_pct}%`,
- backfill,
- s.last_sync_at ?? '(never)',
- ];
- });
- const widths = headers.map((h, i) =>
- Math.max(h.length, ...rows.map((r) => r[i].length)),
- );
- // Numeric columns (STALENESS=2, PAGES=3, EMBEDDED=4) right-pad-left so
- // digits align cleanly. Text columns (incl. BACKFILL=5) left-pad-right
- // per the existing `sources list` convention.
- const NUMERIC_COLS = new Set([2, 3, 4]);
- const fmt = (cells: string[]) =>
- cells.map((c, i) => (NUMERIC_COLS.has(i) ? c.padStart(widths[i]) : c.padEnd(widths[i]))).join(' ');
- write(fmt(headers));
- write(fmt(widths.map((w) => '-'.repeat(w))));
- for (const r of rows) write(fmt(r));
- write(`\nUnacknowledged sync failures (brain-wide): ${report.unacknowledged_failures}`);
- const severe = report.sources.filter((s) => s.staleness_class === 'severe').length;
- if (severe > 0) {
- write(`WARNING: ${severe} source(s) are SEVERELY stale (>72h). Run \`gbrain sync --all\` to refresh.`);
- }
-}
+// The status-report cluster (buildSyncStatusReport, printSyncStatusReport)
+// was peeled to src/core/sync-status-report.ts (pure move). Re-exported so
+// existing importers keep working.
+export {
+ buildSyncStatusReport,
+ printSyncStatusReport,
+ type SyncStatusReport,
+ type SyncStatusReportSource,
+} from '../core/sync-status-report.ts';
/**
* Auto-manage .gitignore entries for db_only directories.
diff --git a/src/core/audit/db-disconnect-audit.ts b/src/core/audit/db-disconnect-audit.ts
index d4df3e024b..a876783bb5 100644
--- a/src/core/audit/db-disconnect-audit.ts
+++ b/src/core/audit/db-disconnect-audit.ts
@@ -106,7 +106,7 @@ export function logDbDisconnect(
/**
* Read recent disconnect audit events. Consumed by
- * `doctor.ts:checkBatchRetryHealth` to surface the 24h count + most-
+ * `doctor/checks/queue-jobs.ts:checkBatchRetryHealth` to surface the 24h count + most-
* recent caller in the existing check (no new check needed per codex
* finding 11).
*
diff --git a/src/core/env-number.ts b/src/core/env-number.ts
index ef361d5b60..f98b062bf8 100644
--- a/src/core/env-number.ts
+++ b/src/core/env-number.ts
@@ -3,7 +3,7 @@
*
* Relocated from `src/commands/doctor.ts` (where `_resolveEnvNumber` was already
* exported but `_resolveSyncFreshnessHours` was module-private). `src/core/source-health.ts`
- * needs the hours resolver for the staleness ceiling, and `doctor.ts:51` already imports
+ * needs the hours resolver for the staleness ceiling, and doctor.ts already imports
* FROM `source-health.ts` — so having core reach back into commands would close an import
* cycle. Duplicating the helper instead would create a SECOND `_envNumberWarned` set, so
* the same bad env var would warn once per module and the "warn exactly once" contract
diff --git a/src/core/git-head.ts b/src/core/git-head.ts
index 4dd61fae85..1e29983bce 100644
--- a/src/core/git-head.ts
+++ b/src/core/git-head.ts
@@ -120,7 +120,7 @@ export type SourceGitState = 'unchanged' | 'changed' | 'unavailable';
* This is NOT a full mirror of `gbrain sync`'s "do work?" predicate.
* Chunker-version match is computed by the caller because it depends on
* engine state (`sources.chunker_version` vs `CURRENT_CHUNKER_VERSION`).
- * See `src/commands/doctor.ts:checkSyncFreshness` for the AND
+ * See `src/commands/doctor/checks/extraction-sync.ts:checkSyncFreshness` for the AND
* combination at the call site.
*
* NULL-input guard stays first: a NULL `last_commit` (legacy row) returns
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 86a52400b1..6f420ac6ee 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -3,7268 +3,119 @@
* Each operation defines its schema, handler, and optional CLI hints.
*/
-import { lstatSync, realpathSync } from 'fs';
-import { resolve, relative, sep } from 'path';
-import type { BrainEngine } from './engine.ts';
-import { clampSearchLimit } from './engine.ts';
-import type { GBrainConfig } from './config.ts';
-import type { PageType } from './types.ts';
-import { importFromContent } from './import-file.ts';
-import { writePageThrough, type WriteThroughResult } from './write-through.ts';
-import { hybridSearch, hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from './search/hybrid.ts';
-import { looksConceptShaped } from './search/query-intent.ts';
-import { expandQuery } from './search/expansion.ts';
-import { dedupResults } from './search/dedup.ts';
-import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from './eval-capture.ts';
-import type { HybridSearchMeta } from './types.ts';
-import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from './link-extraction.ts';
-import { isFactsBackstopEligible } from './facts/eligibility.ts';
-import { stripTakesFence } from './takes-fence.ts';
-import type { WriterLintPayload } from './output/post-write.ts';
-import { stripFactsFence } from './facts-fence.ts';
-import { getContentFlag } from './quarantine.ts';
-import { unverifiedExtractionFragment, isUnverifiedExtraction, EXTRACTION_STATUS_KEY, STATUS_VERIFIED } from './extraction-review.ts';
-import { buildVisibilityClause } from './search/sql-ranking.ts';
-import { bumpLastRetrievedAt } from './last-retrieved.ts';
-import { isSearchMode } from './search/mode.ts';
-import { stampEvidence } from './search/evidence.ts';
-import { packToBudget, estimateTokens, resultTokens } from './search/token-budget.ts';
-import { isAvailable } from './ai/gateway.ts';
import { verbOperations, MEMORY_VERBS_VERSION } from './verbs.ts';
export { MEMORY_VERBS_VERSION };
-import type { SearchResult } from './types.ts';
-import { CJK_SLUG_CHARS, PAGE_SLUG_SEG } from './cjk.ts';
-import { ALL_SOURCES } from './source-id.ts';
-import * as db from './db.ts';
-import { VERSION } from '../version.ts';
-import {
- GET_RECENT_SALIENCE_DESCRIPTION,
- FIND_ANOMALIES_DESCRIPTION,
- FIND_EXPERTS_DESCRIPTION,
- GET_RECENT_TRANSCRIPTS_DESCRIPTION,
- LIST_PAGES_DESCRIPTION,
- QUERY_DESCRIPTION,
- SEARCH_DESCRIPTION,
- FIND_CONTRADICTIONS_DESCRIPTION,
- FIND_TRAJECTORY_DESCRIPTION,
- CODE_CALLERS_DESCRIPTION,
- CODE_CALLEES_DESCRIPTION,
- CODE_DEF_DESCRIPTION,
- CODE_REFS_DESCRIPTION,
- LIST_SKILLS_DESCRIPTION,
- GET_SKILL_DESCRIPTION,
-} from './operations-descriptions.ts';
-// WP4 (request_tools): all three are runtime leaves relative to this module
-// (no import cycles back into operations.ts). The cyclic dependencies —
-// src/mcp/surface.ts (→ brain-allowlist → operations) and
-// src/mcp/publish-gates.ts (→ operations) — are loaded via dynamic import
-// inside the handler instead (the verbs.ts house pattern).
-import { isUndefinedColumnError } from './utils.ts';
-import { hasScope } from './scope.ts';
-import { RateLimiter } from '../mcp/rate-limit.ts';
-import { writeSurfaceChangeAudit } from './surface-audit.ts';
-// --- Types ---
-
-/**
- * v0.31 (eD6 / eE7): ErrorCode is now an OPEN union via the
- * `(string & {})` autocomplete-friendly hack. Downstream consumers (e.g.
- * gbrain-evals) get autocomplete on the named codes AND remain TS-forward-
- * compatible when gbrain adds new codes in future releases. This shape is
- * the standard Anthropic-API/OpenAI-API pattern.
- *
- * v0.31 added: 'rate_limited', 'extraction_failed', 'fact_not_found'.
- */
-export type ErrorCode =
- | 'page_not_found'
- | 'invalid_params'
- | 'embedding_failed'
- | 'storage_error'
- | 'bucket_not_found'
- | 'database_error'
- | 'permission_denied'
- | 'unknown_transport' // v0.28.1: whoami fail-closed for ambiguous transport
- | 'rate_limited' // v0.31: gateway rate-limit upstream
- | 'extraction_failed' // v0.31: facts extractor failed (refusal, parse, abort)
- | 'fact_not_found' // v0.31: forget_fact / recall on unknown id
- // MEMORY_VERBS v1 protocol codes (frozen — docs/protocol/MEMORY_VERBS_v1.md).
- // Coarse on purpose: codes are for branching (configure/retry vs caller bug
- // vs server bug); the freeform `detail` field carries specifics.
- | 'not_found' // unknown resource. Verb-level (forget: unknown fact id) AND
- // get_agent_job's uniform foreign-or-missing envelope (anti-enumeration:
- // a caller cannot distinguish another client's job from a nonexistent id)
- | 'scope_denied' // verb-level: OAuth scope / trust-boundary refusal
- | 'provenance_required' // remember: provenance missing or empty
- | 'unavailable' // a required dependency cannot serve (no API key, gateway down, model refusal)
- | 'budget_unsatisfiable' // RESERVED in v1 — schema-listed, never returned
- // eslint-disable-next-line @typescript-eslint/ban-types
- | (string & {}); // OPEN union for forward-compat (eE7 / D13)
-
-export class OperationError extends Error {
- /**
- * MEMORY_VERBS v1: verb handlers set `protocolVersion` (=1) and may set
- * `detail` (freeform specifics, e.g. which dependency failed). Both are
- * additive — non-verb ops never set them and their envelopes are unchanged
- * (undefined keys drop out of JSON.stringify).
- */
- public detail?: string;
- public protocolVersion?: number;
-
- constructor(
- public code: ErrorCode,
- message: string,
- public suggestion?: string,
- public docs?: string,
- ) {
- super(message);
- this.name = 'OperationError';
- }
-
- toJSON() {
- return {
- error: this.code,
- message: this.message,
- suggestion: this.suggestion,
- docs: this.docs,
- detail: this.detail,
- protocol_version: this.protocolVersion,
- };
- }
-}
-
-/**
- * MEMORY_VERBS v1 error constructor. Every verb error carries a populated
- * `suggestion` (problem + cause + fix — agents read it and self-correct;
- * conformance asserts non-empty) and `protocol_version: 1`.
- */
-export function verbError(
- code: ErrorCode,
- message: string,
- suggestion: string,
- detail?: string,
-): OperationError {
- const e = new OperationError(code, message, suggestion);
- e.protocolVersion = MEMORY_VERBS_VERSION;
- if (detail !== undefined) e.detail = detail;
- return e;
-}
-
-// --- Upload validators (Fix 1 / B5 / H5 / M4) ---
-
-/**
- * Validate an upload path. Two modes:
- * - strict (remote=true): confines the resolved path to `root` and rejects symlinks.
- * Used when the caller is untrusted (MCP over stdio/HTTP, agent-facing).
- * - loose (remote=false): only verifies the file exists and is not a symlink whose
- * target escapes the filesystem (no path traversal protection). Used for local CLI
- * where the user owns the filesystem.
- *
- * Either way: symlinks in the final component are always rejected (prevents
- * transparent redirection to a different file than the user typed).
- *
- * @param filePath caller-supplied path
- * @param root confinement root (only used when strict=true)
- * @param strict true → enforce cwd confinement (B5 + H1). false → allow any accessible path.
- * @throws OperationError(invalid_params) on symlink escape, traversal, or missing file
- */
-export function validateUploadPath(filePath: string, root: string, strict = true): string {
- let real: string;
- try {
- real = realpathSync(resolve(filePath));
- } catch (e: unknown) {
- const msg = e instanceof Error ? e.message : String(e);
- if (msg.includes('ENOENT')) {
- throw new OperationError('invalid_params', `File not found: ${filePath}`);
- }
- throw new OperationError('invalid_params', `Cannot resolve path: ${filePath}`);
- }
- // Always reject final-component symlinks (basic safety for both modes).
- try {
- if (lstatSync(resolve(filePath)).isSymbolicLink()) {
- throw new OperationError('invalid_params', `Symlinks are not allowed for upload: ${filePath}`);
- }
- } catch (e) {
- if (e instanceof OperationError) throw e;
- // lstat race with unlink — pass if realpath already succeeded.
- }
-
- if (!strict) return real;
-
- // Strict mode: confine to root via realpath + path.relative (catches parent-dir symlinks per B5).
- let realRoot: string;
- try {
- realRoot = realpathSync(root);
- } catch {
- throw new OperationError('invalid_params', `Confinement root not accessible: ${root}`);
- }
- const rel = relative(realRoot, real);
- if (rel === '' || rel.startsWith('..') || rel.startsWith(`..${sep}`) || resolve(realRoot, rel) !== real) {
- throw new OperationError('invalid_params', `Upload path must be within the working directory: ${filePath}`);
- }
- return real;
-}
-
-/**
- * Allowlist validator for page slugs. Rejects URL-encoded traversal, backslashes,
- * control chars, RTL overrides, Unicode lookalikes — anything outside the allowlist.
- * Format: lowercase alphanumeric + hyphen segments separated by single forward slashes.
- */
-export function validatePageSlug(slug: string): void {
- if (typeof slug !== 'string' || slug.length === 0) {
- throw new OperationError('invalid_params', 'page_slug must be a non-empty string');
- }
- if (slug.length > 255) {
- throw new OperationError('invalid_params', 'page_slug exceeds 255 characters');
- }
- // #3417: letters/numbers from any script allowed in segments (u flag required
- // for the \p{...} classes in PAGE_SLUG_SEG). Shape rules (lead char, hyphen
- // continuation) preserved.
- if (!new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`, 'iu').test(slug)) {
- throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, hyphens, forward-slash separated segments)`);
- }
-}
-
-/**
- * Match a slug against a list of allow-list prefix globs.
- *
- * Glob form: `<prefix>/*` matches any slug starting with `<prefix>/` and
- * having at least one more segment (single or multi). Bare `<prefix>` (no
- * trailing `/*`) matches that exact slug only. The `*` is intentionally
- * permissive — depth is unbounded, so `wiki/originals/*` matches both
- * `wiki/originals/idea-x` and `wiki/originals/ideas/2026-04-25-idea-y`.
- *
- * Used by the v0.23 dream-cycle trusted-workspace path. Order doesn't
- * matter; the first match wins (returns true on any match).
- */
-export function matchesSlugAllowList(slug: string, prefixes: readonly string[]): boolean {
- for (const p of prefixes) {
- if (p.endsWith('/*')) {
- const base = p.slice(0, -2);
- if (slug === base) continue;
- if (slug.startsWith(base + '/')) return true;
- } else if (p === slug) {
- return true;
- }
- }
- return false;
-}
-
-/**
- * Subagent slug-fence enforcement, shared by every mutating op a subagent
- * can reach (put_page, add_timeline_entry). FAIL-CLOSED: `viaSubagent=true`
- * enforces the check even if the dispatcher forgot to populate `subagentId`.
- *
- * - Trusted-workspace path (ctx.allowedSlugPrefixes set by cycle.ts under
- * PROTECTED_JOB_NAMES \u2014 MCP cannot reach it): slug must match the
- * allow-list globs.
- * - Legacy default: slug must live under `wiki/agents/<subagentId>/...`
- * (anchored, slash-boundary \u2014 `wiki/agents/12evil/*` can't impersonate
- * subagent 12).
- */
-function enforceSubagentSlugFence(ctx: OperationContext, slug: string, opName: string): void {
- if (ctx.viaSubagent !== true) return;
- if (typeof ctx.subagentId !== 'number' || Number.isNaN(ctx.subagentId)) {
- throw new OperationError('permission_denied', `${opName} via subagent requires ctx.subagentId`);
- }
- if (slugUnderSubagentFence(ctx, slug)) return;
- const allowList = ctx.allowedSlugPrefixes;
- throw new OperationError(
- 'permission_denied',
- allowList && allowList.length > 0
- ? `${opName} slug '${slug}' is not within the trusted-workspace allow-list (${allowList.join(', ')})`
- : `${opName} via subagent must write under 'wiki/agents/${ctx.subagentId}/...'`,
- );
-}
-
-/**
- * The subagent fence's MATCH RULE, without the throwing. Split out so the
- * resolved-slug re-check in put_page can ask the same question the entry
- * fence asks, instead of re-deriving the namespace literal and drifting.
- * Callers must have already established `ctx.viaSubagent === true`.
- */
-function slugUnderSubagentFence(ctx: OperationContext, slug: string): boolean {
- const allowList = ctx.allowedSlugPrefixes;
- if (allowList && allowList.length > 0) return matchesSlugAllowList(slug, allowList);
- const prefix = `wiki/agents/${ctx.subagentId}/`;
- return slug.startsWith(prefix) && slug.length > prefix.length;
-}
-
-/**
- * Is `slug` outside whatever slug confinement THIS caller is under?
- *
- * A caller can be confined by EITHER mechanism, and the two arrive on
- * different context fields: an OAuth binding lands on `ctx.auth
- * .boundSlugPrefixes` (plain-prefix grammar), while a delegated subagent
- * lands on `ctx.viaSubagent` + `ctx.allowedSlugPrefixes` (glob grammar) and
- * carries NO `ctx.auth` at all. Testing only the OAuth field therefore lets
- * a bound client that also holds `agent` scope re-open the path it is fenced
- * out of simply by delegating the write through submit_agent — the same
- * bypass shape the facts-backstop gate below is keyed against.
- *
- * Unconfined callers (local CLI, unbound client) match neither arm and are
- * never fenced.
- */
-function slugOutsideCallerFence(ctx: OperationContext, slug: string): boolean {
- const bound = ctx.auth?.boundSlugPrefixes;
- if (bound && !slugUnderBoundPrefixes(bound, slug)) return true;
- if (ctx.viaSubagent === true && !slugUnderSubagentFence(ctx, slug)) return true;
- return false;
-}
-
-/**
- * OAuth-client slug-fence enforcement (v0.42.72.0 — write-side isolation
- * symmetry). When the authenticated client was registered with
- * --bound-slug-prefixes, every direct slug-mutating write must target a
- * slug under one of those prefixes. Shared by put_page, delete_page,
- * restore_page, add_tag, remove_tag, add_link/remove_link (`from`
- * endpoint), add_timeline_entry, revert_version, and put_raw_data; runs
- * BEFORE each op's dry-run short-circuit so preview calls surface the
- * same rejection.
- *
- * Semantics deliberately match submit_agent's bound_slug_prefixes check
- * (plain startsWith, NOT the `/*` glob grammar of the subagent allow-list
- * above): a non-null binding fences fail-closed (empty array = deny all
- * writes), no binding / no auth = no fence (local CLI and unbound clients
- * keep full-source write authority). Register prefixes with a trailing
- * slash ('wiki/agents/alice/') — a bare 'notes' also admits
- * 'notes-archive/...' by startsWith construction.
- */
-function enforceClientSlugFence(ctx: OperationContext, slug: string, opName: string): void {
- if (ctx.auth?.fenceProjectionDegraded) {
- throw new OperationError(
- 'permission_denied',
- `${opName}: this brain's oauth_clients projection is missing bound_slug_prefixes, so the write fence cannot be evaluated. Refusing the write rather than running unfenced.`,
- 'Run `gbrain apply-migrations --yes` on the brain host.',
- );
- }
- const prefixes = ctx.auth?.boundSlugPrefixes;
- if (!prefixes) return;
- if (!slugUnderBoundPrefixes(prefixes, slug)) {
- throw new OperationError(
- 'permission_denied',
- `${opName}: slug '${slug}' is not under any of client ${ctx.auth?.clientId ?? '(unknown)'}'s bound_slug_prefixes (${prefixes.join(', ')})`,
- );
- }
-}
-
-/**
- * The one place the fence's match rule lives. Exported so non-op write
- * surfaces that never build an OperationContext (the `/ingest` route in
- * serve-http.ts) enforce byte-identical semantics instead of re-deriving
- * them.
- *
- * An empty-string prefix is IGNORED rather than honored: `startsWith('')`
- * is true for every slug, so a stray `''` (an unset shell variable in a
- * provisioning template) would silently turn a binding into a wildcard
- * while still rendering as "fenced" to the operator. Registration now
- * rejects empty prefixes outright; this is the second line of defence for
- * rows already in the database.
- */
-export function slugUnderBoundPrefixes(prefixes: readonly string[], slug: string): boolean {
- // Compare against the CANONICAL slug. `validateSlug` lowercases before the
- // row is written, so checking the caller's raw string let `EMP-ALICE/x`
- // satisfy an `EMP-ALICE/` binding, commit as `emp-alice/x`, and only then
- // trip the resolved-slug re-check — an error returned after the write had
- // already landed. Registration rejects non-lowercase prefixes going
- // forward; lowercasing both sides keeps pre-existing rows meaning what
- // their operator intended.
- const canonical = slug.toLowerCase();
- return prefixes.some((bp) => {
- const base = normalizeSlugPrefix(bp);
- if (base === '') return false;
- // Boundary-aware: a prefix must match whole SEGMENTS. Plain `startsWith`
- // let a boundary-less `emp-alice` admit `emp-alice-2/onboarding` — and
- // with the `emp-<slug>` naming this guide recommends, sibling collisions
- // (`alice` vs `alice-2`) are the common case, not a corner case.
- return base.endsWith('/')
- ? canonical.startsWith(base)
- : canonical === base || canonical.startsWith(`${base}/`);
- });
-}
-
-/**
- * Canonical form of one stored prefix, lowercased. `oauth_clients.bound_slug_prefixes`
- * predates this fence — migration v85 introduced it as submit_agent's binding,
- * whose grammar is the `<prefix>/*` glob of `matchesSlugAllowList` — so both
- * spellings have to mean the same span of slugs or upgrading silently changes
- * what an existing client may write.
- */
-export function normalizeSlugPrefix(prefix: string): string {
- return (prefix.endsWith('/*') ? prefix.slice(0, -1) : prefix).toLowerCase();
-}
-
-/**
- * Write ops a slug-bound client may call: every op that routes through
- * `enforceClientSlugFence`, plus `think` (scope `read` for remote callers;
- * it stays on this list because it is `mutating` locally, but remote callers
- * cannot persist — `save`/`take` are forced false for `remote !== false`).
- *
- * This list is an ALLOW-list on purpose. The fence used to be enforced op
- * by op, which made every unfenced write op a silent hole — `extract_entities`
- * mutating `people/*` timelines, `forget_fact` rewriting another source's
- * page by numeric id, `extract_facts` appending to any entity's fact fence.
- * Enumerating what is SAFE fails closed instead: a write op added later is
- * denied to bound clients until someone fences it and adds it here.
- */
-export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set([
- 'put_page', 'delete_page', 'restore_page', 'add_tag', 'remove_tag',
- 'add_link', 'remove_link', 'add_timeline_entry', 'revert_version',
- 'put_raw_data', 'think',
- // submit_agent enforces bound_slug_prefixes itself (it is the op the column
- // was introduced for — see its bound_* binding check), so denying it here
- // would break the original feature for clients that legitimately hold both
- // a binding and `agent` scope.
- 'submit_agent',
-]);
-
-/**
- * WP4 (D9) — discovery meta-ops exempt from the bound-client fence's
- * LISTING/dispatch denial. `request_tools` is `mutating: true` (its persist
- * branch writes oauth_clients.surface), which would otherwise hide discovery
- * from every slug-bound client. The exemption is safe because the persist
- * branch SELF-ENFORCES its own guards — server ceiling (D2), operator lock
- * (amendment 19), OAuth scopes, and a per-client rate limit (D14.5) — and it
- * never touches a slug. Lives here (not inline in the predicate) so the
- * tools/list filter and the dispatch fence consume the identical carve-out
- * (ENG-3 drift-proofing).
- */
-const BOUND_CLIENT_META_OPS: ReadonlySet<string> = new Set(['request_tools']);
-
-/**
- * Single source of truth for "may a slug-bound client use this op" (ENG-3).
- * Consumed by BOTH the dispatch-time fence below AND the tools/list filter
- * in serve-http, so the advertised catalog and the deny behavior cannot
- * drift — a bound client is never shown an op that will fence-deny at call
- * time. Gate on "mutates, or carries any non-read scope" rather than on the
- * two literal scope strings 'write'/'admin': `sources_add`/`sources_remove`
- * carry the bespoke `sources_admin` scope and are `mutating: true`, so a
- * scope-string check let a bound client DROP AN ENTIRE SOURCE — every page
- * in it, far outside any prefix. Anything that isn't a plain read must be
- * explicitly allow-listed. A degraded projection (binding unreadable) denies
- * every non-read op — the unfenceable ops must not stay reachable precisely
- * when the fence is unreadable. Exception: BOUND_CLIENT_META_OPS (D9) stay
- * allowed even degraded — they are slug-free discovery ops whose only write
- * self-enforces ceiling+lock+scopes+rate-limit (and a degraded projection
- * also dropped the surface columns, so that write fails 'migration pending'
- * rather than running unguarded).
- */
-export function opAllowedForBoundClient(
- auth: Pick<AuthInfo, 'boundSlugPrefixes' | 'fenceProjectionDegraded'> | undefined,
- op: Pick<Operation, 'name' | 'scope' | 'mutating'>,
-): boolean {
- const degraded = auth?.fenceProjectionDegraded === true;
- if (!degraded && !auth?.boundSlugPrefixes) return true;
- const isRead = op.scope === 'read' && op.mutating !== true;
- if (isRead) return true;
- if (BOUND_CLIENT_META_OPS.has(op.name)) return true;
- if (degraded) return false;
- return CLIENT_FENCED_WRITE_OPS.has(op.name);
-}
-
-/**
- * Fail-closed gate for slug-bound clients, applied at dispatch (the single
- * choke point both MCP transports share) so it cannot be forgotten per op.
- * Read ops are untouched — read scope is enforced by source federation.
- * Allow/deny derives from `opAllowedForBoundClient`; this wrapper only owns
- * the error envelopes.
- */
-export function enforceBoundClientOpAllowList(
- auth: AuthInfo | undefined,
- op: Pick<Operation, 'name' | 'scope' | 'mutating'>,
-): void {
- if (opAllowedForBoundClient(auth, op)) return;
- const degraded = auth?.fenceProjectionDegraded === true;
- if (degraded) {
- const err = new OperationError(
- 'permission_denied',
- `${op.name}: this brain's oauth_clients projection is missing bound_slug_prefixes, so client write bindings cannot be evaluated. Refusing every non-read operation rather than running unfenced.`,
- 'Run `gbrain apply-migrations --yes` on the brain host.',
- );
- // Amendment 33 / D10: OP-level fence denial — the tools/list filter
- // (opAllowedForBoundClient, the same predicate) should have hidden this
- // op, so serve-http counts it toward the honest-catalog metric
- // (status='denied_after_list'). key=value detail grammar (WP1).
- err.detail = 'fence=op';
- throw err;
- }
- const err = new OperationError(
- 'permission_denied',
- `${op.name} is not available to slug-bound clients: it can write outside client ${auth?.clientId ?? '(unknown)'}'s bound_slug_prefixes (${(auth?.boundSlugPrefixes ?? []).join(', ')}).`,
- 'Use put_page / add_timeline_entry / add_link under your own prefixes, or ask an operator to clear the binding with `gbrain auth rescope-client <id> --bound-slug-prefixes none`.',
- );
- // Amendment 33 / D10: op-level, not argument-level — see above. The
- // slug-prefix ARGUMENT denials (enforceClientSlugFence) deliberately do
- // NOT carry this marker: a listed write op denying an out-of-fence slug
- // is legitimate and excluded from the metric.
- err.detail = 'fence=op';
- throw err;
-}
-
-/**
- * Allowlist validator for uploaded file basenames. Rejects control chars, backslashes,
- * RTL overrides (\u202E), leading dot (hidden files) and leading dash (CLI flag confusion).
- * Allows extension dots and underscores. Max 255 chars.
- */
-export function validateFilename(name: string): void {
- if (typeof name !== 'string' || name.length === 0) {
- throw new OperationError('invalid_params', 'Filename must be a non-empty string');
- }
- if (name.length > 255) {
- throw new OperationError('invalid_params', 'Filename exceeds 255 characters');
- }
- // v0.32.7: CJK ranges (Han / Hiragana / Katakana / Hangul) allowed in filenames.
- // Leading-dot / leading-dash rejection preserved.
- const FILENAME_RE = new RegExp(`^[a-zA-Z0-9${CJK_SLUG_CHARS}][a-zA-Z0-9${CJK_SLUG_CHARS}._\\-]*$`);
- if (!FILENAME_RE.test(name)) {
- throw new OperationError('invalid_params', `Invalid filename: ${name} (allowed: alphanumeric, CJK, dot, underscore, hyphen — no leading dot/dash, no control chars or backslash)`);
- }
-}
-
-export interface ParamDef {
- type: 'string' | 'number' | 'boolean' | 'object' | 'array';
- required?: boolean;
- description?: string;
- default?: unknown;
- enum?: string[];
- items?: ParamDef;
-}
-
-export interface Logger {
- info(msg: string): void;
- warn(msg: string): void;
- error(msg: string): void;
-}
-
-export interface AuthInfo {
- token: string;
- clientId: string;
- /**
- * Human-readable agent name resolved at token-verification time.
- * For OAuth clients this is `oauth_clients.client_name`; for legacy
- * bearer tokens it is `access_tokens.name`. Threading this through
- * AuthInfo eliminates a per-request DB roundtrip in the /mcp handler
- * (was: SELECT client_name FROM oauth_clients WHERE client_id = ?
- * on every request — see PR #586 review note D14=B).
- */
- clientName?: string;
- scopes: string[];
- expiresAt?: number;
- /**
- * v0.34.1 (#861, D2): the source the calling OAuth client is scoped
- * to (write authority). Sourced from `oauth_clients.source_id` at
- * token-verification time. The HTTP transport ALSO threads this
- * value into `OperationContext.sourceId` at the same site so op
- * handlers can consume it via the canonical `ctx.sourceId` (D2
- * dual-write decision — identity surface symmetric with
- * `allowedSources` below).
- *
- * Undefined for legacy bearer tokens that predate v0.34.1 and for
- * clients that haven't been scoped yet. Migration v60 backfills
- * NULL → 'default' for pre-existing rows so this field is populated
- * on the upgrade path; brand-new public-client registrations may
- * still leave it null until an operator explicitly scopes via
- * `gbrain auth scope-client`.
- */
- sourceId?: string;
- /**
- * v0.34.1 (#876): array of source ids this OAuth client may READ
- * from (federation). Sourced from `oauth_clients.federated_read`.
- * Independent of `sourceId` (write authority): a "WeCare L3 dept"
- * client can write to `source_id='dept-x'` while reading the union
- * of `['dept-x', 'wecare-parent', 'shared']`.
- *
- * Empty array `[]` means "no federated reads beyond `sourceId`".
- * Undefined means "the post-v60 backfill hasn't populated this row
- * yet" — engines fall back to scalar `sourceId` filtering in that
- * case (back-compat).
- */
- allowedSources?: string[];
- /**
- * Per-token allow-list for the holder field on `takes`, populated at
- * token-verification time from `access_tokens.permissions.takes_holders`
- * for legacy bearer tokens (via `parseTakesHoldersAllowList` in
- * `src/core/legacy-token-scope.ts`). The HTTP transport threads this into
- * `OperationContext.takesHoldersAllowList` (documented below).
- *
- * `[]` is an explicit deny-all grant and is PRESERVED (never collapsed).
- * `undefined` means the token row carries no array grant — OAuth clients
- * have no per-client storage yet (see TODOS.md) — and consumers apply the
- * fail-closed `['world']` default at the dispatch site.
- *
- * Rides the same `as CoreAuthInfo as SdkAuthInfo` cast as `sourceId` /
- * `allowedSources` above.
- */
- takesHoldersAllowList?: string[];
- /**
- * v0.42.72.0: slug-prefix WRITE binding from
- * `oauth_clients.bound_slug_prefixes`, threaded at token-verification
- * time (same JOIN as sourceId/allowedSources — no per-op roundtrip).
- * When present, every direct slug-mutating write op is fenced to slugs
- * under one of these prefixes via `enforceClientSlugFence` — the same
- * plain-startsWith semantics (and the same fail-closed empty-array
- * posture) as submit_agent's bound_slug_prefixes check, so one column
- * means one thing everywhere it's read. Closes the write-side half of
- * shared-source isolation: reads were SQL-fenced via `allowedSources`,
- * but same-source writes were folder-convention-only.
- *
- * Undefined = client has no binding, or the brain predates the
- * bound_slug_prefixes column → no fence (unbound clients keep
- * full-source write authority, back-compat).
- */
- boundSlugPrefixes?: string[];
- /**
- * Set when token verification could not read `bound_slug_prefixes` (the
- * projection degraded on a brain missing an OAuth column). The fence can't
- * distinguish "no binding" from "binding unknown" otherwise, so writes are
- * refused rather than silently unfenced. Read/auth degradation is
- * unaffected — this axis alone fails closed.
- */
- fenceProjectionDegraded?: boolean;
- /**
- * WP4 (D2): per-client tool surface from `oauth_clients.surface`, threaded
- * at token-verification time (same JOIN as sourceId/allowedSources). The
- * serve-http transport resolves the request's effective surface as
- * `min(server ceiling, this ?? config default)` — the row can narrow, never
- * widen. Value space is OPEN (amendment 18: future client tiers write tier
- * names into the same column); unrecognized values are ignored at
- * resolution with a warn-log once per client. Undefined = column NULL,
- * projection degraded, or the brain predates migration v127.
- */
- surface?: string;
- /**
- * WP4 (amendment 19) — who set `surface`: 'operator' (rescope CLI/admin
- * endpoint; request_tools persist may NOT override it), 'self'
- * (request_tools persist), or 'dcr_default'. Undefined when surface is
- * unset or the projection degraded.
- */
- surfaceSetBy?: string;
-}
-
-export interface OperationContext {
- engine: BrainEngine;
- config: GBrainConfig;
- logger: Logger;
- dryRun: boolean;
- /**
- * OAuth auth info (v0.8+). Present when the caller authenticated via OAuth 2.1
- * through `gbrain serve --http`. Contains clientId and granted scopes for
- * per-operation scope enforcement.
- */
- auth?: AuthInfo;
- /**
- * True when the caller is remote/untrusted (MCP over stdio/HTTP, or any agent-facing entry point).
- * False for local CLI invocations by the owner of the machine.
- *
- * Security-sensitive operations (e.g., file_upload) tighten their filesystem
- * confinement when remote=true and allow unrestricted local-filesystem access
- * when remote=false.
- *
- * REQUIRED as of the F7b hardening — the type system is the first line of defense.
- * Every transport (CLI / stdio MCP / HTTP MCP / subagent dispatcher) sets this
- * explicitly. Consumers still treat anything that isn't strictly `false` as
- * remote/untrusted (defense in depth in case the type is bypassed via cast).
- */
- remote: boolean;
- /**
- * Transport marker for auth-less remote surfaces (#1061). The stdio MCP
- * dispatch sets 'stdio' — it is deliberately `remote: true` (agent-facing,
- * untrusted) but has no per-token auth (local pipe), so identity ops like
- * whoami need a way to distinguish "known auth-less transport" from "a
- * transport bug forgot to thread ctx.auth". Trust decisions MUST NOT key
- * off this field — only `ctx.remote === false` grants trust. It IS the
- * transport-LOCALITY axis: localOnly ops dispatch on 'stdio' (a local
- * pipe with the operator's own filesystem) and are denied on 'http'
- * (network transports), independent of the remote trust flag.
- */
- transport?: 'stdio' | 'http';
- /**
- * WP2/D3: response-meta side channel. Handlers that compute out-of-band
- * result metadata (retrieval degradation, strict-mode warnings) publish it
- * here under a namespaced top-level key; the MCP dispatch layer merges the
- * collected keys into `ToolResult._meta` (one producer per key — see
- * docs/protocol/MCP_META_CHANNELS.md). Unset on CLI/local dispatch paths,
- * which render the same meta directly; emissions are always optional-chained.
- */
- emitResponseMeta?: (key: string, value: unknown) => void;
- /**
- * WP4 (D2): the SERVER surface ceiling for this transport (force-clamped),
- * threaded by the MCP dispatch layer. Consumed by `request_tools`: the
- * catalog never names ops above the ceiling, and the persist branch
- * rejects widening past it with a machine-readable denial
- * (`detail: "ceiling=<surface>"`). Unset (local CLI / direct dispatch) is
- * treated as 'full'.
- */
- surfaceCeiling?: 'verbs' | 'starter' | 'full';
- /**
- * Subagent runtime context (v0.16+). Set by the subagent tool dispatcher when
- * dispatching an op as a tool call from an LLM loop. Used to enforce per-op
- * agent policy (e.g. put_page namespace rule).
- *
- * `viaSubagent` is the FAIL-CLOSED flag: when true, agent-facing policy MUST
- * be enforced even if `subagentId` happens to be undefined (a bug in the
- * dispatcher must not bypass the guard). `subagentId` is the owning subagent
- * job id; `jobId` is the current Minion job id (aggregator or subagent).
- */
- jobId?: number;
- subagentId?: number;
- viaSubagent?: boolean;
- /**
- * Trusted-workspace allow-list (v0.23 dream cycle). When the cycle's
- * synthesize/patterns phases dispatch a subagent, they thread an
- * explicit list of slug-prefix globs (e.g. "wiki/personal/reflections/*")
- * through this field. put_page enforces it BEFORE the legacy
- * `wiki/agents/<id>/...` namespace check.
- *
- * Trust comes from the SUBMITTER (subagent jobs are gated by
- * PROTECTED_JOB_NAMES — MCP cannot submit them), not from `remote`.
- * Every subagent tool call has `remote=true` for auto-link safety,
- * so basing trust on `remote` is incoherent (would always reject).
- *
- * Empty / unset → fall back to the legacy namespace check (existing
- * v0.15 behavior; pure addition, no regression).
- */
- allowedSlugPrefixes?: string[];
- /**
- * Resolved global CLI options (--quiet / --progress-json / --progress-interval).
- * CLI callers populate this from `getCliOptions()`. MCP / library callers
- * may leave it undefined — consumers default to quiet/no-progress for
- * background work.
- */
- cliOpts?: { quiet: boolean; progressJson: boolean; progressInterval: number };
- /**
- * v0.28: per-token allow-list for the holder field on `takes`. Threaded
- * by the MCP HTTP/stdio dispatch layer from `access_tokens.permissions.takes_holders`.
- *
- * When set (i.e., this OperationContext came from an MCP-bound token),
- * `takes_list`, `takes_search`, `takes_scorecard`, `takes_calibration`,
- * and `query` (when it returns takes) MUST apply `WHERE holder = ANY($takesHoldersAllowList)`.
- * This is the server-side filter that backs the v0.28+ visibility model.
- *
- * v0.30.0: aggregate ops (`takes_scorecard`, `takes_calibration`) require
- * the allow-list as a TS-required engine method param (fail-closed by
- * compiler). Hidden-holder rows contribute zero to aggregates. The CLI
- * callers (local + trusted) leave it undefined.
- *
- * Default behavior when unset: local CLI callers see all holders. v0.28
- * MCP dispatch sets it to `['world']` for tokens with no permissions row
- * (default-deny on private hunches).
- */
- takesHoldersAllowList?: string[];
- /**
- * Connected-gbrains brain id (v0.19+ / v0.26 mounts). Identifies which brain
- * this op is targeting. 'host' for the default brain configured in
- * ~/.gbrain/config.json; otherwise a mount id registered in ~/.gbrain/mounts.json.
- *
- * `ctx.engine` is the resolved BrainEngine for this id (populated by
- * BrainRegistry at dispatch time). `brainId` exists alongside for:
- * - audit logging (mount-ops JSONL carries the id)
- * - subagent inheritance (child jobs receive the parent's brainId)
- * - cross-brain citation prefixes in agent output
- *
- * Orthogonal to v0.18.0's source_id, which scopes per-repo WITHIN a brain.
- * See docs/architecture/brains-and-sources.md for the mental model.
- *
- * Omitted = 'host' (pre-v0.19 callers + single-brain deployments keep
- * working without change).
- */
- brainId?: string;
- /**
- * v0.31 (eD4 / eE2): the in-DB tenancy axis for facts hot memory.
- * `sources.id` is TEXT (not INTEGER) — keep this as a string.
- *
- * Resolved once in the dispatcher from CLI flag (--source) / env
- * (GBRAIN_SOURCE) / `.gbrain-source` dotfile / per-token sources scope
- * (HTTP). Defaults to 'default' when nothing else applies.
- *
- * Every facts read/write filter starts with `WHERE source_id = $X`
- * so the trust boundary is part of the index path, not a callback.
- *
- * v0.34 D4 — REQUIRED at the TypeScript level. Mirrors v0.26.9 `remote`
- * REQUIRED pattern that closed the HTTP RCE class. Every transport
- * (CLI / stdio MCP / HTTP MCP / subagent dispatcher) MUST populate
- * this field; `buildOperationContext` auto-fills 'default' for callers
- * who don't pass an explicit sourceId, so the type contract is
- * satisfied even on single-source brains.
- */
- sourceId: string;
- /**
- * CX2-11 — opaque per-session identity, set from MCP `_meta.session_id`
- * (clamped to 256 chars at the dispatch boundary). Cache/telemetry identity
- * ONLY — never an auth or trust surface. The hot-memory meta hook keys its
- * cache on (sourceId, sessionId, allowlist-hash); before this typed field
- * existed every caller collapsed onto the null-session cache key.
- */
- sessionId?: string;
- /**
- * #2561 / #3242 — federated read scope for UNQUALIFIED reads.
- *
- * Set ONLY by trusted server-side context builders — never from caller
- * params — and only when the caller carries no explicit source scope:
- * - local CLI (src/cli.ts makeContext) when the source resolved via a
- * non-explicit tier (local_path / brain_default / sole_non_default /
- * seed_default — NOT --source, NOT GBRAIN_SOURCE, NOT a dotfile);
- * - stdio MCP (src/mcp/server.ts) when GBRAIN_SOURCE is unset;
- * - HTTP MCP (src/mcp/http-transport.ts) for legacy bearer tokens with
- * NO operator-set `permissions.source_id` grant (the historical
- * 'default' floor). Tokens WITH an explicit grant never widen.
- *
- * Contains the resolved source first, then every other
- * `config.federated = true` source, so an unqualified read/search spans
- * federated sources as docs/guides/multi-source-brains.md promises.
- *
- * Consumed exclusively by `federatedSearchScope`. Fail-closed remains:
- * a grant (`ctx.auth.allowedSources`) or a per-call `source_id` always
- * wins, and a context without this field never widens.
- */
- localFederatedSourceIds?: string[];
-}
-
-/**
- * v0.34.1 (#861, D9 — P0 leak seal): resolve the source-scope filter for a
- * read-side op handler. Returns an opts fragment ready to spread into the
- * engine call.
- *
- * Precedence:
- * 1. `ctx.auth?.allowedSources` (federated read, #876) → emits
- * `{sourceIds: [...]}`. Federated semantics subsume the scalar case.
- * 2. `ctx.sourceId` (scalar) → emits `{sourceId: '...'}`.
- * 3. Neither set → emits `{}`. Local CLI callers (and tests that don't
- * populate ctx) keep the pre-v0.34 unscoped behavior.
- *
- * Both fields default to the engine's "no filter" behavior individually,
- * so unset values are safe — the engine sees the same shape it did
- * pre-v0.34. The leak this guards against is an authenticated MCP client
- * whose ctx.sourceId IS set but whose engine call was constructed without
- * threading it (operations.ts:968/1076/1092/935/1469/1471/2241 pre-fix).
- *
- * Helper rather than inline so every read-side handler routes through the
- * same precedence ladder — drift between sites is the bug class.
- */
-export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; sourceIds?: string[] } {
- const allowed = ctx.auth?.allowedSources;
- // Treat an empty `allowedSources: []` as "no federated read scope" — the
- // op-handler defers to scalar `ctx.sourceId` below. An attacker-controlled
- // value of `[]` MUST NOT widen scope to "all sources" by being interpreted
- // as "no filter."
- if (allowed && allowed.length > 0) return { sourceIds: allowed };
- // #1712: the __all__ sentinel spans the brain — but ONLY for trusted local
- // callers (strictly `remote === false`). For remote/untrusted callers the
- // literal stays as-is: it can never match a real source id (underscores are
- // rejected at creation), so the read fail-closes to empty rather than
- // widening past the caller's grant. Do NOT "simplify" this to `{}`.
- if (ctx.sourceId === ALL_SOURCES) {
- return ctx.remote === false ? {} : { sourceId: ctx.sourceId };
- }
- if (ctx.sourceId) return { sourceId: ctx.sourceId };
- return {};
-}
-
-/** Map the operation-layer scope names onto runThink's public options. */
-export function thinkSourceScopeOpts(ctx: OperationContext): {
- sourceId?: string;
- allowedSources?: string[];
-} {
- const scope = sourceScopeOpts(ctx);
- return scope.sourceIds !== undefined
- ? { allowedSources: scope.sourceIds }
- : scope.sourceId !== undefined
- ? { sourceId: scope.sourceId }
- : {};
-}
-
-/**
- * #2200: source scope for the LINK read ops (get_links / get_backlinks). A link
- * row references three pages (from, to, origin); the engine's federated
- * (`sourceIds[]`) branch scopes ALL THREE, but its scalar (`sourceId`) branch
- * scopes only the near endpoint — by design, because trusted internal callers
- * (reconcileLinks, back-link validators, enrich) call the engine directly with a
- * scalar scope and need the cross-source view.
- *
- * An UNTRUSTED remote caller carrying only a scalar scope (a legacy bearer token
- * or a pre-`federated_read` OAuth client) would otherwise hit that scalar branch
- * and have a foreign far/origin slug disclosed. So for remote callers we promote a
- * scalar scope to a single-element `sourceIds:[id]`, routing them through the
- * all-endpoint branch. Trusted local CLI (`ctx.remote === false`) keeps the scalar
- * cross-source view, and a federated array passes through unchanged.
- */
-export function linkReadScopeOpts(ctx: OperationContext): { sourceId?: string; sourceIds?: string[] } {
- const scope = sourceScopeOpts(ctx);
- if (ctx.remote !== false && scope.sourceId && !scope.sourceIds) {
- return { sourceIds: [scope.sourceId] };
- }
- return scope;
-}
-
-/**
- * Resolve a per-call requested source scope against the caller's trust + grant.
- * FAIL-CLOSED: anything not strictly `ctx.remote === false` is untrusted.
- *
- * This is the SINGLE resolver for every read op that accepts a per-call
- * `source_id` / `all_sources` parameter (query, code_callers, code_callees,
- * get_page, search_by_image, code_blast, code_flow). Inlining the `__all__`
- * branch per handler is the bug class that leaked cross-source reads (#1924,
- * #1371): a remote client could pass `source_id: '__all__'` to opt out of its
- * grant, or pass an explicit out-of-grant `source_id` that was never checked.
- *
- * - `__all__` / `all_sources`:
- * trusted local (remote === false) → `{}` (spans the whole brain)
- * remote → the caller's grant (sourceScopeOpts)
- * - explicit `source_id`:
- * remote + federated grant that doesn't include it → permission_denied
- * otherwise → `{ sourceId }`
- * - neither → the caller's grant (sourceScopeOpts).
- *
- * `code_traversal_cache_clear` is intentionally NOT a caller — it is localOnly
- * and carries its own destructive D8 all_sources guard.
- */
-export function resolveRequestedScope(
- ctx: OperationContext,
- sourceIdParam: string | undefined,
- allSourcesParam = false,
-): { sourceId?: string; sourceIds?: string[] } {
- const wantsAll = allSourcesParam || sourceIdParam === ALL_SOURCES;
- if (wantsAll) {
- return ctx.remote === false ? {} : sourceScopeOpts(ctx);
- }
- if (sourceIdParam !== undefined) {
- const allowed = ctx.auth?.allowedSources;
- if (ctx.remote !== false && allowed && allowed.length > 0 && !allowed.includes(sourceIdParam)) {
- throw new OperationError(
- 'permission_denied',
- `source '${sourceIdParam}' is outside your granted sources`,
- 'Request access to this source, or omit source_id to search within your grant.',
- );
- }
- return { sourceId: sourceIdParam };
- }
- return sourceScopeOpts(ctx);
-}
-
-/**
- * #2561 / #3242 — source scope for the page-visibility read ops (`search`,
- * `query`, `get_page`, `list_pages`, `resolve_slugs`).
- *
- * Delegates to `resolveRequestedScope` (the single trust+grant resolver), then
- * widens an UNQUALIFIED scalar scope to the transport-computed federated set
- * (`ctx.localFederatedSourceIds`, resolved source first). This is what makes
- * `sources add --federated` mean something: a federated source participates in
- * unqualified reads (#3242 — pages ingested into a `federated: true` source
- * were invisible to get_page/search/list_pages while resolve_slugs leaked them).
- *
- * The expansion NEVER applies when:
- * - a per-call `source_id` was passed (explicit wins, including `__all__`);
- * - the resolver already produced a federated array (OAuth grant governs);
- * - the transport didn't populate `localFederatedSourceIds` (see that
- * field's doc: it is only set for callers with NO explicit source scope,
- * and never from caller-controlled params — so trust stays fail-closed).
- *
- * Deliberately NOT inside `sourceScopeOpts`: code-intel ops collapse a
- * multi-element scope to an error (`resolveCodeIntelScope`), and the remaining
- * scalar reads (get_links, get_chunks, …) keep their long-standing behavior.
- */
-export function federatedSearchScope(
- ctx: OperationContext,
- sourceIdParam?: string,
-): { sourceId?: string; sourceIds?: string[] } {
- const scope = resolveRequestedScope(ctx, sourceIdParam);
- if (
- sourceIdParam === undefined &&
- scope.sourceId !== undefined &&
- scope.sourceIds === undefined &&
- ctx.localFederatedSourceIds !== undefined &&
- ctx.localFederatedSourceIds.length > 1
- ) {
- return { sourceIds: ctx.localFederatedSourceIds };
- }
- return scope;
-}
-
-/**
- * Code-intel adapter for `resolveRequestedScope`. Graph traversal
- * (code_callers/code_callees/code_blast/code_flow) is single-source by design —
- * the engine APIs and the traversal cache key take ONE `sourceId` string, not a
- * federated array. So this collapses the resolver's output to `{allSources,
- * sourceId}`, fail-closed:
- *
- * - resolver → one source (scalar or single-element grant) → that source
- * - resolver → multi-source grant (federated remote client) → reject: ask the
- * caller to specify which granted source (we must not silently span all)
- * - resolver → empty scope → `allSources` ONLY for trusted local callers; a
- * remote caller with no source in scope is denied, never widened to all.
- */
-export function resolveCodeIntelScope(
- ctx: OperationContext,
- sourceIdParam: string | undefined,
- allSourcesParam = false,
-): { allSources: boolean; sourceId?: string } {
- const scope = resolveRequestedScope(ctx, sourceIdParam, allSourcesParam);
- if (scope.sourceId) return { allSources: false, sourceId: scope.sourceId };
- if (scope.sourceIds && scope.sourceIds.length === 1) {
- return { allSources: false, sourceId: scope.sourceIds[0] };
- }
- if (scope.sourceIds && scope.sourceIds.length > 1) {
- throw new OperationError(
- 'invalid_params',
- 'Code traversal runs against a single source. Specify source_id (one of your granted sources).',
- 'Pass source_id=<one of your sources>.',
- );
- }
- // Empty scope: span everything only for trusted local callers; a remote caller
- // that reached here has no source in scope and must NOT get cross-source results.
- if (ctx.remote === false) return { allSources: true, sourceId: undefined };
- throw new OperationError(
- 'permission_denied',
- 'No source in scope for this request.',
- 'Specify source_id, or check your granted sources.',
- );
-}
-
-/**
- * T4/D5 — resolve a per-call search-mode override. Honored ONLY for trusted/
- * local callers (ctx.remote === false) so a remote OAuth client can't escalate
- * to the costly tokenmax bundle. Local + unknown mode → loud reject; remote +
- * mode → silently ignored (server-configured mode wins). Returns undefined to
- * mean "use the configured mode".
- */
-export function resolvePerCallMode(ctx: OperationContext, raw: unknown): string | undefined {
- if (typeof raw !== 'string' || raw.length === 0) return undefined;
- if (ctx.remote !== false) return undefined; // remote can't select mode
- if (!isSearchMode(raw)) {
- throw new OperationError(
- 'invalid_params',
- `Unknown search mode '${raw}'. Valid: conservative, balanced, tokenmax.`,
- `gbrain search "<query>" --mode balanced`,
- );
- }
- return raw;
-}
-
-/** T4 — stamp evidence/create_safety on a result set, fail-soft. */
-function stampEvidenceSafe(results: SearchResult[]): void {
- try { stampEvidence(results); } catch { /* non-fatal */ }
-}
-
-/** T4 — shared eval-capture for the `search` op (keyword-only + cheap-hybrid paths). */
-function maybeCaptureSearch(
- ctx: OperationContext,
- queryText: string,
- results: SearchResult[],
- latency_ms: number,
- vectorEnabled: boolean,
- meta?: HybridSearchMeta | null,
-): void {
- if (!isEvalCaptureEnabled(ctx.config)) return;
- void captureEvalCandidate(
- ctx.engine,
- {
- tool_name: 'search',
- query: queryText,
- results,
- meta: meta ?? { vector_enabled: vectorEnabled, detail_resolved: null, expansion_applied: false },
- latency_ms,
- remote: ctx.remote ?? false,
- expand_enabled: false,
- detail: null,
- job_id: ctx.jobId ?? null,
- subagent_id: ctx.subagentId ?? null,
- },
- { scrub_pii: isEvalScrubEnabled(ctx.config) },
- );
-}
-
-export interface Operation {
- name: string;
- description: string;
- params: Record<string, ParamDef>;
- handler: (ctx: OperationContext, params: Record<string, unknown>) => Promise<unknown>;
- mutating?: boolean;
- /**
- * Capability scope required to invoke this op over an authenticated
- * transport. v0.28 added `sources_admin` (manage federated sources) and
- * `users_admin` (reserved). The hierarchy lives in src/core/scope.ts —
- * `admin` implies all, `write` implies `read`, the two `*_admin` scopes
- * are siblings (different axes; neither implies the other). `agent` is
- * also a sibling NOT implied by admin (v0.38 D13): admin tokens must be
- * explicitly re-registered with bindings to touch the agent lane.
- *
- * Local CLI callers (ctx.remote === false) bypass scope enforcement
- * because the trust boundary there is the OS, not OAuth scopes.
- */
- scope?: 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin' | 'agent';
- localOnly?: boolean;
- /**
- * WP1 honest catalog: the op is callable by remote callers only when this
- * config gate resolves true (dual-plane, DB > file > absent=false). Network
- * transports hide the op from tools/list while the gate is off — a listed
- * tool that always denies reads as broken, not private. The in-handler
- * gate (assertPublishEnabled / the advisor inline check) stays as the
- * fail-closed call-time backstop; stdio (local pipe) bypasses publish
- * gates entirely. Resolution lives in src/mcp/publish-gates.ts.
- */
- publishGateKey?: 'mcp.publish_skills' | 'mcp.publish_advisor';
- /**
- * MEMORY_VERBS v1: marks the seven frozen protocol verbs (recall, remember,
- * entity, synthesize, forget, context_pack, delta). `gbrain serve --surface
- * verbs` exposes EXACTLY the ops with `verb: true`; 'starter' (the ~20-op
- * daily-driver tier) sits between verbs and `full` (default), which exposes
- * everything.
- */
- verb?: boolean;
- /**
- * WP4 (amendment 22) — coarse grouping label consumed by the
- * `request_tools` catalog and the generated tool-catalog doc. Area NAMES
- * ARE NON-CONTRACTUAL: they exist so an agent can scan ~20 groups instead
- * of ~100 flat names; renaming/regrouping is never a breaking change.
- * Required (by the CI walker in test/mcp-tool-defs.test.ts) on every
- * non-localOnly op; populated centrally via OP_AREAS at the bottom of
- * this file.
- */
- area?: string;
- /**
- * WP4 (FOV-4) — marks a discovery meta-op callable by the `agent` scope
- * IN ADDITION to its declared scope. `agent` deliberately implies only
- * itself (v0.38 D13), which would strand agent-only tokens with zero
- * discovery; the MCP scope checks (serve-http tools/list + tools/call)
- * add a one-line carve-out for ops with this flag. Currently only
- * `request_tools`.
- */
- agentCallable?: true;
- /**
- * MCP ToolAnnotations passthrough (SDK 1.29+). Emitted by buildToolDefs
- * ONLY when set — existing tools keep byte-identical definitions.
- */
- annotations?: {
- title?: string;
- readOnlyHint?: boolean;
- destructiveHint?: boolean;
- idempotentHint?: boolean;
- };
- cliHints?: {
- name?: string;
- /**
- * Alternate CLI command names that dispatch to this same op (v114 / #1941).
- * e.g. `link-add` aliasing `link`. Registered in `cli.ts`'s `cliAliases`
- * map; collisions with primary names or CLI_ONLY commands throw at startup.
- */
- aliases?: string[];
- positional?: string[];
- stdin?: string;
- hidden?: boolean;
- };
-}
-
-// --- Page CRUD ---
-
-const get_page: Operation = {
- name: 'get_page',
- description: 'Read a page by slug (supports optional fuzzy matching). Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (see v0.26.5 recovery window).',
- params: {
- slug: { type: 'string', required: true, description: 'Page slug' },
- fuzzy: { type: 'boolean', description: 'Enable fuzzy slug resolution (default: false)' },
- include_deleted: { type: 'boolean', description: 'v0.26.5: surface soft-deleted pages with deleted_at populated (default: false). Used by restore workflows.' },
- },
- handler: async (ctx, p) => {
- const slug = p.slug as string;
- const fuzzy = (p.fuzzy as boolean) || false;
- const includeDeleted = (p.include_deleted as boolean) === true;
- // #1393: route BOTH the exact-match read and the fuzzy resolveSlugs through
- // the canonical precedence ladder (federated array > scalar > nothing). The
- // exact path previously used scalar `ctx.sourceId` only, so a remote client
- // with a federated `allowedSources` grant (and no single ctx.sourceId) got
- // an UNSCOPED exact lookup — a cross-source read of any page by slug. getPage
- // now honors sourceIds[] (both engines), so the same scope closes both paths.
- // #3242: federatedSearchScope (not bare sourceScopeOpts) so an unqualified
- // read sees pages in `federated: true` sources, matching search/query.
- const sourceOpts = federatedSearchScope(ctx);
- const fuzzyScope = sourceOpts;
-
- let page = await ctx.engine.getPage(slug, { includeDeleted, ...sourceOpts });
- let resolved_slug: string | undefined;
-
- if (!page && fuzzy) {
- const candidates = await ctx.engine.resolveSlugs(slug, fuzzyScope);
- if (candidates.length === 1) {
- page = await ctx.engine.getPage(candidates[0], { includeDeleted, ...sourceOpts });
- resolved_slug = candidates[0];
- } else if (candidates.length > 1) {
- return { error: 'ambiguous_slug', candidates };
- }
- }
-
- if (!page) {
- throw new OperationError('page_not_found', `Page not found: ${slug}`, includeDeleted ? 'Check the slug or use fuzzy: true' : 'Page may be soft-deleted; pass include_deleted: true to verify');
- }
-
- // v0.37.0 (D11): op-layer write-back for the `last_retrieved_at` stale
- // signal. Fire-and-forget — caller does NOT await. Internal callers
- // (sync, migrations, dream cycle) bypass this op handler so the signal
- // stays clean. Throttled to ~1 write / 5 min per page via the SQL clause
- // inside bumpLastRetrievedAt (D2).
- bumpLastRetrievedAt(ctx.engine, [page.id]);
-
- // #2200: resolve tags against the concrete page's source. `sourceOpts` may
- // be { sourceIds:[...] } (federated) with no scalar sourceId, which getTags
- // would otherwise fall back to 'default' for — the wrong source for a
- // 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;
- const visibleBody = isUntrustedReader
- ? {
- ...page,
- compiled_truth: stripFactsFence(
- stripTakesFence(page.compiled_truth),
- { keepVisibility: ['world'] },
- ),
- }
- : page;
- // v0.42 (#1699) agent-warning channel: surface the page's content_flag
- // marker as a top-level field (parallel to SearchResult.content_flag) so
- // an agent reading a page directly gets the same "this looks odd, examine
- // it" signal it would get from search. The marker is also in frontmatter;
- // this is the clean, documented accessor.
- const content_flag = getContentFlag(page.frontmatter as Record<string, unknown> | null);
- return {
- ...visibleBody,
- tags,
- ...(resolved_slug ? { resolved_slug } : {}),
- ...(content_flag ? { content_flag } : {}),
- };
- },
- scope: 'read',
- cliHints: { name: 'get', positional: ['slug'] },
-};
-
-const put_page: Operation = {
- name: 'put_page',
- description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',
- params: {
- slug: { type: 'string', required: true, description: 'Page slug' },
- content: { type: 'string', required: true, description: 'Full markdown content with YAML frontmatter' },
- allow_empty: { type: 'boolean', required: false, description: 'Allow overwriting an existing non-empty page with empty/whitespace-only content (default: false). Without it, put_page rejects the empty overwrite — the empty-stdin failure class.' },
- // v0.39.3.0 provenance write-through (WARN-8 + A1 + CV6). Optional fields
- // for trusted local callers (capture CLI, autopilot, dream cycle). Remote
- // MCP callers (ctx.remote !== false) have their values OVERRIDDEN with
- // server stamps below; the params are accepted on the wire only so the
- // op schema stays uniform across transports. Audit-trail spoofing is
- // closed structurally — clients cannot poison source_kind labels.
- source_kind: { type: 'string', required: false, description: 'Ingestion channel taxonomy (capture-cli | put_page | webhook | …). Remote callers: SERVER-STAMPED, client value ignored.' },
- source_uri: { type: 'string', required: false, description: 'Original URI/path/message-id the event carried. Remote callers: SERVER-STAMPED null.' },
- ingested_via: { type: 'string', required: false, description: 'Richer label paired with source_kind. Remote callers: SERVER-STAMPED.' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- const slug = p.slug as string;
-
- // v0.39.3.0 CV6 trust gate for provenance write-through (WARN-8).
- // Only trusted LOCAL callers (ctx.remote === false — capture CLI,
- // autopilot, dream cycle, file watcher) may populate source_kind /
- // source_uri / ingested_via from their own state. Anything else
- // (HTTP MCP, stdio MCP, subagent) gets the server-stamped
- // `mcp:put_page` regardless of what was passed.
- //
- // Closes the spoofing surface CV6 identified: pre-fix a write-scope
- // OAuth token could send `source_kind: 'capture-cli'` to poison the
- // audit trail. Fail-closed: `ctx.remote === false` is the ONLY truthy
- // condition that admits client-supplied provenance.
- let provenanceKind: string | null;
- let provenanceUri: string | null;
- let provenanceVia: string | null;
- if (ctx.remote === false) {
- // Trusted local caller: honor the client params (may be null/undefined
- // for legacy local callers that don't set them).
- provenanceKind = (p.source_kind as string | undefined) ?? null;
- provenanceUri = (p.source_uri as string | undefined) ?? null;
- provenanceVia = (p.ingested_via as string | undefined) ?? null;
- } else {
- // Remote caller or unset trust: server stamps. Mirrors the existing
- // write-through stamping at the file-side (~:637).
- provenanceKind = 'mcp:put_page';
- provenanceUri = null;
- provenanceVia = 'mcp:put_page';
- }
-
- // Subagent namespace enforcement (v0.15+). Runs BEFORE the dry-run
- // short-circuit so preview calls surface the same rejection. See
- // enforceSubagentSlugFence for the fail-closed policy.
- enforceSubagentSlugFence(ctx, slug, 'put_page');
- enforceClientSlugFence(ctx, slug, 'put_page');
-
- if (ctx.dryRun) return { dry_run: true, action: 'put_page', slug: p.slug };
-
- // Empty-overwrite guard: empty/whitespace-only content over an existing
- // non-empty page is almost always an input-plumbing failure (e.g. a
- // caller that meant file input — put has no --file flag — so the missing
- // --content fell back to reading an empty non-interactive stdin), not an
- // intentional write. Refuse loudly unless the caller opts in with
- // allow_empty. The read is scoped to the exact (source_id, slug) row the
- // write below targets (engine.putPage defaults to 'default' when
- // sourceId is unset). New-slug creates and soft-deleted-page overwrites
- // stay allowed — nothing recoverable is lost there.
- if ((p.content as string).trim() === '' && p.allow_empty !== true) {
- const existing = await ctx.engine.getPage(slug, { sourceId: ctx.sourceId ?? 'default' });
- const existingBody = existing
- ? `${existing.compiled_truth ?? ''}\n${existing.timeline ?? ''}`.trim()
- : '';
- if (existingBody !== '') {
- throw new OperationError(
- 'invalid_params',
- `Refusing to overwrite existing non-empty page '${slug}' with empty content.`,
- 'For file input use `gbrain capture --file PATH --slug SLUG` (put has no --file flag). To intentionally blank the page, pass allow_empty: true (CLI: --allow-empty).',
- );
- }
- }
-
- // Skip embedding when the AI gateway has no embedding provider configured.
- // Checks all auth env vars for the resolved provider, not just OPENAI_API_KEY,
- // so Gemini / Ollama / Voyage brains don't silently drop embeddings (Codex C2).
- const { isAvailable } = await import('./ai/gateway.ts');
- const noEmbed = !isAvailable('embedding');
- // v0.31.8 (D7 / codex OV-1): thread ctx.sourceId so put_page on a
- // multi-source brain lands in the intended source instead of the
- // default-source clobber path. importFromContent already accepts
- // opts.sourceId (PR #707/#757 engine work); previously the op handler
- // just didn't pass it.
- // v0.39 T1.5: load active pack ONCE per put_page invocation; thread to
- // parseMarkdown via importFromContent so type inference honors user-defined
- // page_types. Best-effort: pack load failure falls back to legacy inferType
- // (parity gate preserved). Federated-read closure correction is T19's scope.
- let activePack: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string> }> } | undefined;
- try {
- const { loadActivePack } = await import('./schema-pack/load-active.ts');
- const { loadConfig } = await import('./config.ts');
- const resolved = await loadActivePack({
- cfg: loadConfig(),
- remote: ctx.remote === false ? false : true,
- sourceId: ctx.sourceId,
- });
- activePack = { page_types: resolved.manifest.page_types };
- } catch {
- // Pack load failed; fall through to legacy inferType behavior.
- activePack = undefined;
- }
- const result = await importFromContent(ctx.engine, slug, p.content as string, {
- noEmbed,
- // v0.42 (#1699): untrusted callers can't smuggle gate-owned frontmatter
- // markers (quarantine/content_flag/embed_skip). Fail-closed — anything
- // not strictly local is remote (matches CV6 / v0.26.9 F7b posture).
- remote: ctx.remote !== false,
- ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}),
- // v0.39.0.0 T1.5: pack-aware type inference (loaded above; legacy
- // inferType behavior when undefined).
- ...(activePack ? { activePack } : {}),
- // v0.39.3.0 provenance write-through (WARN-8). Trust-filtered values
- // computed above; ingested_at is server-stamped at the engine layer.
- // Null-valued fields signal "no provenance write this call" and the
- // engine's COALESCE-preserve UPDATE keeps the prior first-write
- // record intact (CV12 audit-trail survival).
- source_kind: provenanceKind,
- source_uri: provenanceUri,
- ingested_via: provenanceVia,
- });
-
- // The dedup pre-check in importFromContent can resolve the write to a
- // DIFFERENT page than the one requested (same content_hash, or the same
- // `frontmatter.id`), and the disk write-through below runs against that
- // RESOLVED slug. Fence it too: a bound client can read a victim page's
- // frontmatter id over its federated grant, echo it back in an in-prefix
- // put_page, and otherwise have write-through rewrite the victim's file
- // with falsified provenance. Dedup returns status 'skipped' without
- // touching the DB, so throwing here leaves nothing to roll back.
- if (result.slug && result.slug !== slug) {
- // Deliberately does NOT name the resolved slug: it belongs to a page
- // outside the fence, and echoing it would turn frontmatter-id guessing
- // into a slug-enumeration oracle.
- if (slugOutsideCallerFence(ctx, result.slug)) {
- ctx.logger.warn(`[put_page] dedup resolved '${slug}' to an out-of-fence page; refusing (client ${ctx.auth?.clientId ?? 'unknown'}, subagent ${ctx.subagentId ?? 'none'})`);
- throw new OperationError(
- 'permission_denied',
- `put_page: this content already exists on a page outside your write scope, so the write would have modified that page instead.`,
- 'Remove the `id:` frontmatter field (or change the content) to write a new page under your own prefix.',
- );
- }
- }
-
- // v0.39 T13 — auto-prompt on first unknown-type write.
- //
- // Contract (codex finding #8 honored — 7 cases covered):
- // - TTY callers: stderr prompt fires once per unique unknown type;
- // subsequent writes with the same type silently append to
- // candidate audit.
- // - Non-TTY callers: ALWAYS succeed; silently append to candidate
- // audit. NEVER block. Critical regression test:
- // test/put-page-unknown-type-prompt.test.ts pins this.
- // - Subagent / MCP / claw-test / autopilot all go through here;
- // non-TTY contract preserves their semantics.
- // - Pack-load failures (activePack undefined) skip the gate entirely
- // since "unknown" has no meaning without a pack reference.
- if (activePack && result.status === 'imported') {
- try {
- const pageType = (result as { page?: { type?: string } }).page?.type ?? null;
- const knownTypes = new Set(activePack.page_types.map((t) => t.name));
- if (pageType && !knownTypes.has(pageType)) {
- const { logSchemaEvent } = await import('./schema-events.ts');
- logSchemaEvent({
- verb: 'put_page:unknown_type',
- outcome: 'success',
- flags: [`type=${pageType.slice(0, 32)}`, `slug=${slug.slice(0, 64)}`],
- });
- if (process.stderr.isTTY && ctx.remote === false) {
- console.error(
- `[schema] put_page wrote type=\`${pageType}\` which isn't in active pack \`${activePack.page_types.length ? '<configured>' : 'gbrain-base'}\`. ` +
- `Run \`gbrain schema review-candidates\` to promote or ignore.`,
- );
- }
- }
- } catch {
- // best-effort; never block put_page
- }
- }
-
- // v0.38 put_page write-through (ingestion cathedral):
- // After importFromContent succeeds, if `sync.repo_path` resolves to a
- // real directory, persist the markdown file to disk alongside the DB
- // row. Failures non-fatal — DB write is durable; subsequent sync
- // reconciles drift.
- //
- // Trust gating:
- // - Subagent sandbox (viaSubagent without allowedSlugPrefixes) → DB-only.
- // - All other writes → write-through.
- // put_page's own trust-gating produces two skip reasons ('subagent_sandbox',
- // 'dry_run') that never come out of writePageThrough itself — widen the
- // field rather than losing the commit/pushed/lastPushStatus typing.
- let writeThrough: (Omit<WriteThroughResult, 'skipped'> & { skipped?: WriteThroughResult['skipped'] | 'subagent_sandbox' | 'dry_run' }) | undefined;
- const isSandboxSubagent = ctx.viaSubagent === true
- && !(Array.isArray(ctx.allowedSlugPrefixes) && ctx.allowedSlugPrefixes.length > 0);
- if (!ctx.dryRun && result.status !== 'error' && !isSandboxSubagent) {
- const sourceId = ctx.sourceId ?? 'default';
- const provenanceVia = ctx.remote === false ? 'put_page' : 'mcp:put_page';
- // Shared canonical write-through (also used by `gbrain brainstorm/lsd
- // --save`). Renders the file from the saved DB row and writes it
- // atomically; never throws (failures land in skipped/error).
- writeThrough = await writePageThrough(ctx.engine, result.slug, {
- sourceId,
- frontmatterOverrides: {
- ingested_via: provenanceVia,
- ingested_at: new Date().toISOString(),
- source_kind: provenanceVia,
- },
- logger: ctx.logger,
- });
- } else if (isSandboxSubagent) {
- writeThrough = { written: false, skipped: 'subagent_sandbox' };
- } else if (ctx.dryRun) {
- writeThrough = { written: false, skipped: 'dry_run' };
- }
-
- // Auto-link post-hook: runs AFTER importFromContent (which is its own
- // transaction). Runs even on status='skipped' so reconciliation catches drift
- // between the page text and the links table. Failures are non-blocking.
- //
- // SECURITY: skipped for remote (MCP) callers. Auto-link's bare-slug regex
- // matches `people/X` etc. anywhere in page text, including code fences,
- // quoted strings, and prompt-injected content. An untrusted page can plant
- // arbitrary outbound links by including `see meetings/board-q1` in its body.
- // Combined with the backlink boost in hybridSearch, attacker-placed targets
- // would surface higher in search. Local CLI users (ctx.remote=false) opt
- // into this behavior; MCP/remote writes do not.
- let autoLinks:
- | { created: number; removed: number; errors: number; unresolved: UnresolvedFrontmatterRef[] }
- | { error: string }
- | { skipped: 'remote' }
- | undefined;
- let autoTimeline: { created: number } | { error: string } | { skipped: 'remote' } | undefined;
- // Trusted-workspace path (v0.23 dream cycle) re-enables auto-link/timeline
- // even though ctx.remote=true, because the allow-list bounds the slug and
- // the synthesis prompt is itself the trusted dispatcher. Without this,
- // the cycle's `extract` phase would have to recompute every edge, and
- // patterns (which runs after extract) would still see the right graph
- // but auto_timeline would never fire on synth output.
- const trustedWorkspace = ctx.viaSubagent === true
- && Array.isArray(ctx.allowedSlugPrefixes)
- && ctx.allowedSlugPrefixes.length > 0;
- if (ctx.remote !== false && !trustedWorkspace) {
- autoLinks = { skipped: 'remote' };
- autoTimeline = { skipped: 'remote' };
- } else if (result.parsedPage) {
- try {
- const enabled = await isAutoLinkEnabled(ctx.engine);
- if (enabled) {
- autoLinks = await runAutoLink(ctx.engine, slug, result.parsedPage, ctx.sourceId ? { sourceId: ctx.sourceId } : undefined);
- }
- } catch (e) {
- autoLinks = { error: e instanceof Error ? e.message : String(e) };
- }
- // Timeline extraction mirrors auto-link: runs post-write, best-effort,
- // never blocks the write. ON CONFLICT DO NOTHING in
- // addTimelineEntriesBatch keeps it idempotent across re-writes, so a
- // page that's edited and re-written won't duplicate its own timeline.
- try {
- const enabled = await isAutoTimelineEnabled(ctx.engine);
- if (enabled) {
- const fullContent = result.parsedPage.compiled_truth + '\n' + result.parsedPage.timeline;
- const entries = parseTimelineEntries(fullContent);
- if (entries.length > 0) {
- const batch = entries.map(e => ({
- slug,
- date: e.date,
- summary: e.summary,
- detail: e.detail || '',
- }));
- // v0.41.18.0: engine self-retries on Supavisor circuit-breaker
- // recovery. auditSite label routes the audit JSONL emission so
- // operators can attribute losses to the agent-write path.
- const created = await ctx.engine.addTimelineEntriesBatch(batch, { auditSite: 'mcp.put_page.autolink' });
- autoTimeline = { created };
- } else {
- autoTimeline = { created: 0 };
- }
- }
- } catch (e) {
- autoTimeline = { error: e instanceof Error ? e.message : String(e) };
- }
- }
-
- // v0.31 (D23): facts compliance backstop. When an agent writes a page
- // on a conversation-shape slug AND the body has substantive prose, fire
- // a fact-extraction job into the bounded queue. Skipped on dry-run,
- // dream-generated content (anti-loop), and non-eligible kinds (sync,
- // ingest, file uploads, code pages). Never blocks the put_page response.
- // v0.31.2: routed through runFactsBackstop (PR1 commit 6) so put_page
- // and sync share the same eligibility/extract/dedup/insert pipeline.
- // Queue mode preserves the prior fire-and-forget shape (caller's
- // put_page response stays fast). Default 'all' notability filter
- // (MEDIUM facts wait for the dream cycle but DO land via put_page,
- // matching the pre-fix behavior on this surface).
- let factsQueued: { queued: boolean } | { skipped: string } | undefined;
- // Slug-bound clients do not get the facts backstop. It extracts entities
- // from the (attacker-controllable) page body and writes fact rows — and,
- // on a source with a local_path, a `## Facts` fence in the entity's own
- // .md — keyed to `people/…` / `companies/…` slugs the caller never named.
- // That is exactly the capability `extract_facts` is denied at dispatch
- // for, reachable indirectly through a perfectly in-prefix put_page. The
- // sibling post-hooks above already skip for untrusted callers (auto-link
- // at `remote !== false && !trustedWorkspace`, chronicle at
- // `remote !== false`); this one had no gate at all.
- // Keyed on "the caller is slug-confined at all", not on ctx.auth alone:
- // the delegated (submit_agent → subagent) context carries
- // `allowedSlugPrefixes` but NOT `auth`, so an auth-only test would let a
- // bound client re-open this path simply by delegating the write.
- if (ctx.auth?.boundSlugPrefixes || ctx.viaSubagent === true) {
- factsQueued = { skipped: 'slug_bound_client' };
- } else {
- try {
- const { runFactsBackstop } = await import('./facts/backstop.ts');
- const r = await runFactsBackstop(
- {
- slug,
- type: result.parsedPage!.type,
- compiled_truth: result.parsedPage!.compiled_truth,
- frontmatter: result.parsedPage!.frontmatter,
- },
- {
- engine: ctx.engine,
- sourceId: ctx.sourceId ?? 'default',
- sessionId: (ctx as { source_session?: string }).source_session ?? null,
- source: 'mcp:put_page',
- mode: 'queue',
- },
- );
- if (r.mode === 'queue' && r.enqueued) {
- factsQueued = { queued: true };
- } else if (r.mode === 'queue' && r.skipped) {
- // Preserve the pre-v0.31.2 response shape for MCP clients:
- // 'kind:guide' / 'too_short' / 'subagent_namespace' / 'dream_generated'
- // (bare reasons), not the helper's namespaced 'eligibility_failed:...'
- // discriminator. Map back here.
- const bare = r.skipped.startsWith('eligibility_failed:')
- ? r.skipped.slice('eligibility_failed:'.length)
- : r.skipped;
- factsQueued = { skipped: bare };
- }
- } catch {
- factsQueued = { skipped: 'backstop_error' };
- }
- }
-
- // v0.42.x (#2390): Life Chronicle backstop. ONLY on a real import
- // (status==='imported' — a skipped/unchanged rewrite still carries
- // parsedPage, so gating on parsedPage alone would re-enqueue forever),
- // behind the SAME trust gate as auto-link/timeline + the auto_chronicle
- // flag. Enqueues a chronicle_extract job; never blocks the write.
- let chronicleQueued: { queued: boolean } | { skipped: string } | undefined;
- if (result.status !== 'imported') {
- chronicleQueued = { skipped: 'not_imported' };
- } else if (ctx.remote !== false && !trustedWorkspace) {
- chronicleQueued = { skipped: 'remote' };
- } else if (result.parsedPage) {
- try {
- const { runChronicleBackstop } = await import('./chronicle/backstop.ts');
- const r = await runChronicleBackstop(
- {
- slug,
- type: result.parsedPage.type,
- compiled_truth: result.parsedPage.compiled_truth,
- frontmatter: result.parsedPage.frontmatter,
- },
- { engine: ctx.engine, sourceId: ctx.sourceId ?? 'default' },
- );
- chronicleQueued = r.enqueued ? { queued: true } : { skipped: r.skipped ?? 'skipped' };
- } catch {
- chronicleQueued = { skipped: 'backstop_error' };
- }
- }
-
- // Post-write validator lint (PR 2.5): feature-flag-gated, non-blocking.
- // When `writer.lint_on_put_page` is enabled, runs the BrainWriter's
- // validators on the freshly-written page and logs findings to
- // ingest_log + ~/.gbrain/validator-lint.jsonl. Does NOT reject the
- // write — that's the deferred strict-mode flip after the 7-day soak.
- // Response contract (T11): lint ran → full summary (counts, errors-first
- // top_findings with hints, by_validator histogram) even at zero findings;
- // lint crashed → {status: 'lint_error'}; lint off (flag / validate:false)
- // → key absent.
- let writerLint: WriterLintPayload | undefined;
- try {
- const { writerLintForPutPage } = await import('./output/post-write.ts');
- writerLint = await writerLintForPutPage(ctx.engine, result.slug, {
- sourceId: ctx.sourceId ?? 'default',
- });
- } catch {
- // Module-load failure gets the same crash marker; never blocks put_page.
- writerLint = { status: 'lint_error' };
- }
-
- return {
- slug: result.slug,
- status: result.status === 'imported' ? 'created_or_updated' : result.status,
- chunks: result.chunks,
- ...(autoLinks ? { auto_links: autoLinks } : {}),
- ...(autoTimeline ? { auto_timeline: autoTimeline } : {}),
- ...(writerLint ? { writer_lint: writerLint } : {}),
- ...(factsQueued ? { facts_backstop: factsQueued } : {}),
- ...(chronicleQueued ? { chronicle_backstop: chronicleQueued } : {}),
- ...(writeThrough ? { write_through: writeThrough } : {}),
- };
- },
- cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
-};
-
-// v0.31.2: isFactsBackstopEligible moved to src/core/facts/eligibility.ts
-// so sync.ts, file_upload, code_import, and runFactsBackstop all share one
-// predicate. Imported above.
-
-/**
- * Extract entity refs from a freshly-written page, sync the links table to match.
- * Creates new links via addLink, removes stale ones (links present in DB but no
- * longer referenced in content) via removeLink. Returns counts.
- *
- * Runs OUTSIDE importFromContent's transaction so it doesn't block the page write
- * or get rolled back if a single link operation fails. Per-link failures are
- * counted; the overall function never throws (catch in put_page handler covers
- * extraction errors).
- */
-async function runAutoLink(
- engine: BrainEngine,
- slug: string,
- parsed: { type: PageType; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> },
- opts?: { sourceId?: string },
-): Promise<{ created: number; removed: number; errors: number; unresolved: UnresolvedFrontmatterRef[] }> {
- const fullContent = parsed.compiled_truth + '\n' + parsed.timeline;
- // v0.31.8 (codex OV-2): thread sourceId through every read + write inside
- // reconcileLinks. Without this the FS walker reads cross-source links/slugs
- // but writes scoped to one source — phantom stale-deletions and duplicate
- // inserts. opts.sourceId is set when caller knows the source (put_page from
- // a multi-source-aware handler); when omitted, every read returns the
- // pre-v0.31.8 cross-source view (back-compat for any existing caller).
- const sourceOpts = opts?.sourceId ? { sourceId: opts.sourceId } : {};
- const linkSourceOpts = opts?.sourceId
- ? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId, originSourceId: opts.sourceId }
- : {};
- const removeSourceOpts = opts?.sourceId
- ? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId }
- : {};
-
- // Live-mode resolver: per-put throwaway cache, pg_trgm + optional search.
- // Issue #972 (codex [P1]): pass sourceId so basename resolution stays
- // within this page's source — no cross-source basename edges. Also scopes
- // the fuzzy fallback (findByTitleFuzzy) to the same source the put_page is
- // targeting — without it, cross-source slug suggestions get silently dropped
- // at the FK filter and the link looks like it failed to resolve. Twin of
- // #1436's `tryFuzzyMatch` fix.
- const resolver = makeResolver(engine, { mode: 'live', sourceId: opts?.sourceId });
- // Issue #972: opt-in bare-wikilink basename resolution. Off by default.
- const globalBasename = await isGlobalBasenameEnabled(engine);
- const { candidates, unresolved } = await extractPageLinks(
- slug, fullContent, parsed.frontmatter, parsed.type, resolver,
- { globalBasename },
- );
-
- // Resolve which targets exist (skip refs to non-existent pages to avoid FK
- // violation churn in addLink). One getAllSlugs call upfront, O(1) lookup.
- // v0.31.8 (D12): scoped to the source when opts.sourceId is set so wikilink
- // resolution doesn't span unrelated sources.
- const allSlugs = await engine.getAllSlugs(sourceOpts);
- const valid = candidates.filter(c =>
- allSlugs.has(c.targetSlug) && (!c.fromSlug || allSlugs.has(c.fromSlug))
- );
-
- // Split candidates by direction. Outgoing (fromSlug === slug or unset) are
- // this page's own edges, reconciled against getLinks(slug). Incoming
- // (fromSlug !== slug — frontmatter with `direction: incoming`) are edges
- // where this page is the TO side; reconciled against getBacklinks(slug)
- // but SCOPED to the frontmatter edges this page authored via
- // (link_source='frontmatter' AND origin_slug = slug). We never touch
- // frontmatter edges authored by OTHER pages.
- const out = valid.filter(c => !c.fromSlug || c.fromSlug === slug);
- const inc = valid.filter(c => c.fromSlug && c.fromSlug !== slug);
-
- // Run getLinks + addLink/removeLink loops inside a single transaction so that
- // concurrent put_page calls on the same slug can't race the reconciliation:
- // without this, two simultaneous writes both read stale `existingKeys` and
- // re-create links the other side just removed (lost-update).
- //
- // Row-level locks alone aren't enough: both writers can read the same
- // `existingKeys` set BEFORE either mutates a row, so the union-of-writes
- // race survives. A transaction-scoped advisory lock keyed on the slug
- // hash serializes the entire reconciliation across processes. Falls
- // through on engines that don't support pg_advisory_xact_lock (PGLite is
- // single-process so there's no cross-process concern there anyway).
- const result = await engine.transaction(async (tx) => {
- try {
- await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [`auto_link:${slug}`]);
- } catch {
- // engine doesn't support advisory locks — fall through
- }
- const existingOut = await tx.getLinks(slug, sourceOpts);
- // Incoming: we only look at frontmatter edges WE authored (origin_slug=slug).
- // Non-frontmatter and other-page frontmatter edges survive untouched.
- const existingInRaw = await tx.getBacklinks(slug, sourceOpts);
- const existingIn = existingInRaw.filter(
- l => l.link_source === 'frontmatter' && l.origin_slug === slug,
- );
-
- // Reconcilable outgoing edges: markdown + our own frontmatter edges +
- // basename-resolved wikilinks (issue #972). Manual edges
- // (link_source='manual') are NEVER touched by reconciliation.
- // 'wikilink-resolved' MUST be reconcilable (codex outside-voice [P1]):
- // auto-link writes these; if it weren't here, a basename edge would
- // survive after the wikilink is deleted from the page OR the
- // link_resolution.global_basename flag is turned off (out no longer
- // includes it, so the stale-removal loop below must be allowed to drop it).
- const reconcilableOut = existingOut.filter(
- l => l.link_source === 'markdown' || l.link_source == null ||
- l.link_source === 'wikilink-resolved' ||
- (l.link_source === 'frontmatter' && l.origin_slug === slug),
- );
-
- const outKeys = new Set(out.map(c =>
- `${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? 'markdown'}`
- ));
- const incKeys = new Set(inc.map(c =>
- `${c.fromSlug}\u0000${c.linkType}`
- ));
-
- let created = 0, removed = 0, errors = 0;
-
- // Add outgoing edges.
- for (const c of out) {
- try {
- await tx.addLink(
- slug, c.targetSlug, c.context, c.linkType,
- c.linkSource, c.originSlug, c.originField,
- linkSourceOpts,
- );
- const existKey = `${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? 'markdown'}`;
- const exists = reconcilableOut.some(l =>
- `${l.to_slug}\u0000${l.link_type}\u0000${l.link_source ?? 'markdown'}` === existKey
- );
- if (!exists) created++;
- } catch {
- errors++;
- }
- }
-
- // Add incoming edges (other page → slug).
- for (const c of inc) {
- try {
- await tx.addLink(
- c.fromSlug!, c.targetSlug, c.context, c.linkType,
- 'frontmatter', c.originSlug, c.originField,
- linkSourceOpts,
- );
- const existKey = `${c.fromSlug}\u0000${c.linkType}`;
- const exists = existingIn.some(l =>
- `${l.from_slug}\u0000${l.link_type}` === existKey
- );
- if (!exists) created++;
- } catch {
- errors++;
- }
- }
-
- // Remove stale outgoing (markdown or our-frontmatter, not in desired set).
- for (const l of reconcilableOut) {
- const key = `${l.to_slug}\u0000${l.link_type}\u0000${l.link_source ?? 'markdown'}`;
- if (!outKeys.has(key)) {
- try {
- await tx.removeLink(slug, l.to_slug, l.link_type, l.link_source ?? undefined, removeSourceOpts);
- removed++;
- } catch {
- errors++;
- }
- }
- }
-
- // Remove stale incoming (our frontmatter → slug, not in desired set).
- for (const l of existingIn) {
- const key = `${l.from_slug}\u0000${l.link_type}`;
- if (!incKeys.has(key)) {
- try {
- await tx.removeLink(l.from_slug, slug, l.link_type, 'frontmatter', removeSourceOpts);
- removed++;
- } catch {
- errors++;
- }
- }
- }
-
- return { created, removed, errors };
- });
-
- return { ...result, unresolved };
-}
-
-const delete_page: Operation = {
- name: 'delete_page',
- description: 'Soft-delete a page. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed.',
- params: {
- slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- const slug = p.slug as string;
- enforceClientSlugFence(ctx, slug, 'delete_page');
- if (ctx.dryRun) return { dry_run: true, action: 'soft_delete_page', slug };
- // v0.31.8 (D7): thread ctx.sourceId so multi-source brains soft-delete the
- // intended row instead of always targeting (default, slug).
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- // v0.26.5: rewired from hard-delete to soft-delete. The hard-delete primitive
- // (engine.deletePage) is now reserved for purgeDeletedPages and explicit
- // tests. softDeletePage returns null when the slug is unknown OR already
- // soft-deleted (idempotent-as-null) — preserve that as a clean no-op shape.
- const result = await ctx.engine.softDeletePage(slug, sourceOpts);
- if (result === null) {
- // Distinguish "not found" from "already soft-deleted" so the agent gets a
- // clear signal. Probe once with include_deleted to disambiguate.
- const existing = await ctx.engine.getPage(slug, { includeDeleted: true, ...sourceOpts });
- if (!existing) {
- throw new OperationError('page_not_found', `Page not found: ${slug}`, 'Check the slug.');
- }
- return { status: 'already_soft_deleted', slug, deleted_at: existing.deleted_at };
- }
- return { status: 'soft_deleted', slug, recoverable_until: 'now + 72h via restore_page' };
- },
- cliHints: { name: 'delete', positional: ['slug'] },
-};
-
-const restore_page: Operation = {
- name: 'restore_page',
- description: 'v0.26.5 — restore a soft-deleted page (clear deleted_at). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.',
- params: {
- slug: { type: 'string', required: true, description: "Slug of the soft-deleted page to restore, e.g. 'people/alice-example'." },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- const slug = p.slug as string;
- enforceClientSlugFence(ctx, slug, 'restore_page');
- if (ctx.dryRun) return { dry_run: true, action: 'restore_page', slug };
- // v0.31.8 (D7): thread ctx.sourceId.
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- const ok = await ctx.engine.restorePage(slug, sourceOpts);
- if (!ok) {
- // Distinguish "not found" from "already active" (idempotent-as-false).
- const existing = await ctx.engine.getPage(slug, { includeDeleted: true, ...sourceOpts });
- if (!existing) {
- throw new OperationError('page_not_found', `Page not found: ${slug}`, 'Check the slug.');
- }
- return { status: 'already_active', slug };
- }
- return { status: 'restored', slug };
- },
- cliHints: { name: 'restore', positional: ['slug'] },
-};
-
-const purge_deleted_pages: Operation = {
- name: 'purge_deleted_pages',
- description: 'v0.26.5 — admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72). Cascades through content_chunks, page_links, chunk_relations. Local CLI only (not exposed over HTTP MCP). Manual escape hatch alongside the autopilot purge phase.',
- params: {
- older_than_hours: { type: 'number', description: 'Age cutoff in hours. Default 72.' },
- },
- mutating: true,
- scope: 'admin',
- localOnly: true,
- handler: async (ctx, p) => {
- const olderThanHours = (p.older_than_hours as number | undefined) ?? 72;
- if (ctx.dryRun) return { dry_run: true, action: 'purge_deleted_pages', older_than_hours: olderThanHours };
- const result = await ctx.engine.purgeDeletedPages(olderThanHours);
- return { status: 'purged', count: result.count, slugs: result.slugs };
- },
- cliHints: { name: 'purge-deleted' },
-};
-
-const LIST_PAGES_SORT_VALUES = ['updated_desc', 'updated_asc', 'created_desc', 'slug'] as const;
-type ListPagesSort = typeof LIST_PAGES_SORT_VALUES[number];
-
-const list_pages: Operation = {
- name: 'list_pages',
- description: LIST_PAGES_DESCRIPTION,
- params: {
- type: { type: 'string', description: 'Filter by page type' },
- tag: { type: 'string', description: 'Filter by tag' },
- limit: { type: 'number', description: 'Max results (default 50; remote callers are capped at 100)' },
- offset: {
- type: 'number',
- description: 'Skip first N rows (pagination). Engine-supported since PageFilters gained offset; previously accepted at the CLI and silently dropped.',
- },
- // v0.29 — surface filter that already exists on PageFilters.
- updated_after: {
- type: 'string',
- description: 'ISO date (YYYY-MM-DD) or full timestamp. Returns pages with updated_at > value.',
- },
- sort: {
- type: 'string',
- enum: [...LIST_PAGES_SORT_VALUES],
- description: 'Sort order. Default updated_desc (matches pre-v0.29). Options: updated_desc, updated_asc, created_desc, slug.',
- },
- include_deleted: { type: 'boolean', description: 'v0.26.5: include soft-deleted pages (default: false). Used by restore workflows and operator diagnostics.' },
- },
- handler: async (ctx, p) => {
- // Whitelist the sort enum at the handler before passing to the engine.
- // Engines also whitelist via PAGE_SORT_SQL but defending here keeps
- // unsupported strings from reaching the SQL layer.
- const rawSort = p.sort as string | undefined;
- const sort = rawSort && (LIST_PAGES_SORT_VALUES as readonly string[]).includes(rawSort)
- ? (rawSort as ListPagesSort)
- : undefined;
- // v0.34.1 (#861 — P0 leak seal): thread the auth'd client's source scope
- // into the listPages filter so an OAuth client scoped to src-A cannot
- // enumerate src-B pages. Pre-fix, ctx.sourceId / ctx.auth?.allowedSources
- // were ignored at this op handler and the engine returned every source's
- // pages indiscriminately.
- // #3242: federatedSearchScope so unqualified listing spans federated
- // sources (same visibility set as search / get_page). Grants still win.
- const scope = federatedSearchScope(ctx);
- // The 100-row cap exists to protect remote MCP/OAuth transports from
- // unbounded result dumps. Local CLI callers (ctx.remote === false — the
- // same trust boundary that already bypasses scope enforcement, see the
- // Operation.scope doc above) own the machine, and a full enumeration is a
- // legitimate local operation, so an explicit limit above 100 is honored.
- // Anything that is not strictly `false` stays remote/untrusted (defense
- // in depth, matching the ctx.remote contract).
- const requestedLimit = p.limit as number | undefined;
- const isLocal = ctx.remote === false;
- const limit = isLocal
- ? clampSearchLimit(requestedLimit, 50, Number.MAX_SAFE_INTEGER)
- : clampSearchLimit(requestedLimit, 50, 100);
- if (!isLocal && requestedLimit !== undefined && Number.isFinite(requestedLimit) && requestedLimit > limit) {
- // Loud clamp, parity with the three search paths ("search limit clamped
- // from N to 100"). logger.warn goes to stderr — `list` stdout is
- // tab-separated and consumed by scripts, so it must stay clean.
- ctx.logger.warn(`[gbrain] Warning: list limit clamped from ${requestedLimit} to ${limit}; use offset to paginate`);
- }
- // Thread offset through — PageFilters has supported it all along; the op
- // layer just never passed it, so `--offset` was accepted and ignored.
- const requestedOffset = p.offset as number | undefined;
- const offset =
- requestedOffset !== undefined && Number.isFinite(requestedOffset) && requestedOffset > 0
- ? Math.floor(requestedOffset)
- : undefined;
- // Probe one row past the effective limit so truncation is detectable
- // without a COUNT query. The bug class sealed here is SILENT truncation
- // — an exhaustive consumer (audit, scan, backfill) gets a full-looking
- // list and never learns rows were dropped, and with the default
- // updated_desc sort the dropped rows are always the OLDEST, i.e. exactly
- // the pages such consumers exist to find.
- const rows = await ctx.engine.listPages({
- type: p.type as any,
- tag: p.tag as string,
- limit: limit + 1,
- offset,
- includeDeleted: (p.include_deleted as boolean) === true,
- updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,
- sort,
- ...scope,
- });
- const truncated = rows.length > limit;
- const pages = truncated ? rows.slice(0, limit) : rows;
- // Warn only when the caller's limit was NOT honored (unset → default 50):
- // an explicit honored limit that happens to land on more rows is ordinary
- // pagination, not a trap. Local (CLI) only — same operator-facing stderr
- // channel as the put_page unknown-type hint above — but with no isTTY
- // gate: scripted callers are precisely the consumers that cannot detect
- // truncation any other way, and stderr keeps stdout parseable for them.
- // (Local explicit limits are honored unbounded since #3322, so the
- // requestedLimit > limit arm is defense in depth only.)
- if (truncated && isLocal && (requestedLimit === undefined || requestedLimit > limit)) {
- console.error(
- `[list_pages] output truncated at ${limit} rows (default 50). ` +
- `Pass an explicit limit, page through with sort=updated_asc + ` +
- `updated_after=<last row's updated_at>, or narrow with type/tag.`,
- );
- }
- return pages.map(pg => ({
- slug: pg.slug,
- source_id: pg.source_id,
- type: pg.type,
- title: pg.title,
- updated_at: pg.updated_at,
- ...(pg.deleted_at ? { deleted_at: pg.deleted_at } : {}),
- }));
- },
- scope: 'read',
- cliHints: { name: 'list' },
-};
-
-// --- Search ---
-
-/**
- * WP2/D3 + E1: the `retrieval` response-meta payload for the search/query
- * ops. Carries the already-computed HybridSearchMeta signal (vector arm,
- * cache, budget, degradation stages — populated by the search pipeline) plus
- * the concept-shaped hint, so an MCP caller can distinguish "clean miss"
- * from "the pipeline degraded" without a second call. The `hint` is
- * non-contractual prose (agents read it; nothing should parse it).
- */
-function buildRetrievalResponseMeta(
- queryText: string,
- results: unknown[],
- meta: HybridSearchMeta | null,
- opts: { conceptHint?: boolean } = {},
-): Record<string, unknown> {
- const m = meta as (HybridSearchMeta & { degraded?: unknown; retrieved_count?: number }) | null;
- const hint = opts.conceptHint && looksConceptShaped(queryText)
- ? "concept-shaped question — the 'query' tool adds multi-query expansion and recovers " +
- 'synonym-phrased matches this keyword-leaning search can miss.'
- : undefined;
- return {
- returned_count: results.length,
- retrieved_count: m?.retrieved_count ?? results.length,
- ...(m ? {
- vector_enabled: m.vector_enabled,
- expansion_applied: m.expansion_applied,
- ...(m.cache ? { cache: m.cache.status } : {}),
- ...(m.token_budget ? { token_budget: m.token_budget } : {}),
- ...(m.degraded !== undefined ? { degraded: m.degraded } : {}),
- } : {}),
- ...(hint ? { hint } : {}),
- };
-}
-
-const search: Operation = {
- name: 'search',
- description: SEARCH_DESCRIPTION,
- params: {
- query: { type: 'string', required: true, description: "Search text. Exact tokens, names, and structured-field values work best here (e.g. 'acme-example series A'), since this op does no LLM expansion. This is the search text param — there is no `text` or `q` param." },
- limit: { type: 'number', description: 'Max results (default 20)' },
- offset: { type: 'number', description: 'Skip first N results (for pagination)' },
- mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only.' },
- },
- handler: async (ctx, p) => {
- const startedAt = Date.now();
- const queryText = p.query as string;
- const limit = (p.limit as number) || 20;
- const offset = (p.offset as number) || 0;
- // #2561: unqualified trusted-local search spans federated sources.
- const scope = federatedSearchScope(ctx);
-
- // T4/D5 — per-call mode honored ONLY for trusted/local callers so a remote
- // OAuth client can't escalate to the costly tokenmax bundle. Local + unknown
- // mode → loud reject; remote + mode set → silently ignored (uses config).
- const perCallMode = resolvePerCallMode(ctx, p.mode);
-
- // T4/D17 — escape hatch: keyword-only when the operator opts out of the
- // hybrid `search` contract (privacy/cost: no query text to an embedding
- // provider). Defaults to cheap-hybrid (D4/D15).
- const keywordOnly = (await ctx.engine.getConfig('search.mcp_keyword_only')) === 'true';
-
- if (keywordOnly) {
- const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, ...scope });
- const results = dedupResults(raw);
- stampEvidenceSafe(results);
- // #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);
- // #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);
- 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 }));
- return results;
- }
-
- // Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but
- // expansion OFF (no per-call LLM cost). `query` op is the full-control variant.
- let capturedMeta: HybridSearchMeta | null = null;
- const results = await hybridSearchCached(ctx.engine, queryText, {
- limit,
- offset,
- expansion: false,
- ...scope,
- ...(perCallMode ? { mode: perCallMode } : {}),
- onMeta: (m) => { capturedMeta = m; },
- });
- const latency_ms = Date.now() - startedAt;
- bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
- maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
- ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta, { conceptHint: true }));
- return results;
- },
- scope: 'read',
- cliHints: { name: 'search', positional: ['query'] },
-};
-
-const query: Operation = {
- name: 'query',
- description: QUERY_DESCRIPTION,
- params: {
- // v0.27.1: `query` is no longer strictly required — `--image <path>`
- // is the alternative entry point for image-similarity search. The CLI
- // validator at src/cli.ts honors `cliHints.altRequired` and admits the
- // image-only invocation. MCP / programmatic callers must still pass
- // `query` OR `image` (handler refuses if both are absent).
- query: { type: 'string', required: false, description: "Question or topic text for hybrid retrieval with expansion (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params." },
- /** v0.27.1: image-similarity search. Path resolved on the CLI side
- * before the op fires (the op receives raw bytes neither side; the
- * CLI loads the file, base64-encodes, and passes through `image`). */
- image: { type: 'string', description: 'Base64-encoded image bytes for image-similarity search (CLI: --image <path>).' },
- image_mime: { type: 'string', description: 'MIME type for the image bytes (auto-derived from path on CLI; required when calling op directly).' },
- limit: { type: 'number', description: 'Max results (default 20)' },
- offset: { type: 'number', description: 'Skip first N results (for pagination)' },
- expand: { type: 'boolean', description: 'Enable multi-query expansion (default: true)' },
- detail: { type: 'string', description: 'Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)' },
- mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.' },
- // v0.20.0 Cathedral II Layer 10 C1/C2: language + symbol-kind filters.
- lang: { type: 'string', description: 'Filter to chunks where content_chunks.language matches (e.g., typescript, python, ruby)' },
- symbol_kind: { type: 'string', description: 'Filter to chunks where content_chunks.symbol_type matches (e.g., function, class, method, type, interface)' },
- // v0.20.0 Cathedral II Layer 7 (A2) / Layer 10 C3: two-pass structural expansion.
- near_symbol: { type: 'string', description: 'Anchor retrieval at this qualified symbol name (e.g., BrainEngine.searchKeyword). Enables A2 two-pass.' },
- walk_depth: { type: 'number', description: 'Structural walk depth 1-2. Default 0 (off). Expands anchors through code_edges with 1/(1+hop) decay.' },
- // v0.29.1 — orthogonal recency + salience axes. YOU (the agent) decide.
- salience: {
- type: 'string',
- enum: ['off', 'on', 'strong'],
- description:
- "v0.29.1 salience boost — emotional_weight + take_count, NO time component.\n" +
- " 'off' — default for entity / canonical / definitional queries\n" +
- " 'on' — surface emotionally-weighted + take-rich pages\n" +
- " 'strong' — aggressive mattering tilt\n" +
- "Omit and gbrain auto-detects from query text. Independent of `recency`.",
- },
- recency: {
- type: 'string',
- enum: ['off', 'on', 'strong'],
- description:
- "v0.29.1 recency boost — per-prefix age decay, NO mattering signal.\n" +
- " 'off' — default for canonical truth\n" +
- " 'on' — daily/, media/x/, chat/ decay aggressively; concepts/, originals/, writing/ stay evergreen\n" +
- " 'strong' — multiplies the recency factor by 1.5 (use for 'today' / 'right now')\n" +
- "Omit and gbrain auto-detects. Independent of `salience` (orthogonal axes).",
- },
- since: {
- type: 'string',
- description:
- "v0.29.1 — filter to pages whose effective_date is >= this. ISO-8601 (YYYY-MM-DD or full timestamp) OR relative ('7d', '2w', '1y'). Replaces deprecated `afterDate`.",
- },
- until: {
- type: 'string',
- description:
- "v0.29.1 — filter to effective_date <= this. Same format as `since`. Replaces deprecated `beforeDate`. YYYY-MM-DD lands at end-of-day.",
- },
- source_id: {
- type: 'string',
- description:
- "v0.34: scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",
- },
- cross_modal: {
- type: 'string',
- enum: ['text', 'image', 'both', 'auto'],
- description:
- "v0.36 cross-modal search routing.\n" +
- " 'text' (default for non-image-intent queries) — text-only path, no behavior change vs v0.35.\n" +
- " 'image' — route the query through Voyage multimodal-3 + the embedding_image column. Best for 'show me photos of...' phrasings.\n" +
- " 'both' — run text AND image searches in parallel; merge via weighted RRF.\n" +
- " 'auto' — same effect as omitting the field; intent classifier decides based on query phrasing.",
- },
- embedding_column: {
- type: 'string',
- description:
- "v0.36: route vector search through a non-default embedding column. Defaults to 'embedding' (the brain's primary column) unless `search_embedding_column` config sets a different default. Per-call override for A/B benchmarking across providers (e.g. 'embedding_voyage', 'embedding_openai'). Column MUST be declared in the `embedding_columns` config registry — unknown names throw with a paste-ready hint listing valid columns.",
- },
- adaptive_return: {
- type: 'boolean',
- description:
- "v0.41.33 — return a TIGHT, intent-sized result set instead of the full top-K. YOU (the agent) set this per query to serve the user well:\n" +
- " TRUE when the user's question has a small, specific answer — a lookup ('what is X', 'who is Y', 'what's my <thing>', 'what did Z decide'), a single-fact recall, or when you'll route the result into a precise downstream step (a classifier, a decision, an exact citation). The user gets the answer, not a wall of loosely-related pages, and you spend fewer tokens reading noise.\n" +
- " Omit / FALSE for breadth — 'everything about X', 'list all', 'what do I know about Y', exploration, brainstorming, or any time you'd rather see more candidates and judge for yourself. Recall matters more there, so take the full top-K.\n" +
- "Safe by construction: it NEVER returns empty when there are matches (you always get at least the top hit), and it only applies to the first page (omit when paginating). Caps come from config (search.adaptive_return_entity_max / _other_max; default 2 / 6) — pass `limit` 1 alongside this for a hard single-answer cap.",
- },
- autocut: {
- type: 'boolean',
- description:
- "v0.42.3.0 — autocut is the SMART DEFAULT (already ON when the reranker runs, which it does in the default search mode). It returns only the confident cluster by cutting where the relevance score drops off a cliff, so an obvious single answer comes back as 1 result and a genuine handful comes back as that handful — not a fixed wall of 20+.\n" +
- " You almost never set this. Pass FALSE only to FORCE the full top-K when you deliberately want breadth — broad exploration, 'show me everything about X', enumeration where you'd rather over-collect and judge for yourself, or when you suspect the top hit is wrong and want to see the alternatives.\n" +
- " TRUE is redundant in default mode (it's already on); it only matters to override a brain whose config turned autocut off.\n" +
- "Safe by construction: never returns empty when there are matches, only applies to the first page (omit when paginating), and is a no-op when no reranker scored the results (so it can't cut on an untrustworthy signal). Distinct from `adaptive_return`: autocut cuts on the score cliff; adaptive_return caps by question intent. Leave both unset for the smart default.",
- },
- relational: {
- type: 'boolean',
- description:
- "v0.43 — relational recall arm. SMART DEFAULT (on in balanced/tokenmax). When the question is about a RELATIONSHIP ('who invested in widget-co', 'who introduced me to alice', 'what connects fund-a and fund-b'), the brain resolves the named entity and walks its typed-edge graph (invested_in, works_at, founded, …), surfacing the answer even when no passage mentions both sides. Pure no-op for non-relational questions. Pass FALSE to force lexical/vector-only retrieval (e.g. debugging why a graph answer appeared). You almost never set this.",
- },
- },
- handler: async (ctx, p) => {
- const startedAt = Date.now();
- const expand = p.expand !== false;
- const detail = (p.detail as 'low' | 'medium' | 'high') || undefined;
- const queryText = p.query as string | undefined;
- const imageData = p.image as string | undefined;
- const imageMime = (p.image_mime as string) || 'image/jpeg';
- const embeddingColumnParam =
- typeof p.embedding_column === 'string' && p.embedding_column.length > 0
- ? (p.embedding_column as string)
- : undefined;
- // Explicit per-call source_id must win over ctx.sourceId. `__all__` spans
- // every source for trusted local callers, but only the caller's granted
- // sources for remote callers (resolveRequestedScope is the single
- // trust+grant resolver shared by every source-scoped read op). This scope
- // is spread into BOTH the image-similarity searchVector path and the text
- // hybridSearch path below, so both honor the same grant.
- const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
- // #2561: unqualified trusted-local query spans federated sources (per-call
- // source_id / remote grants still resolve through resolveRequestedScope).
- const querySourceScope = federatedSearchScope(ctx, sourceIdParam);
-
- // v0.27.1: image-similarity branch. Bypasses hybridSearch (which is
- // text-only); embeds the image via embedMultimodal and runs a direct
- // vector search against the embedding_image column.
- if (imageData) {
- const { embedMultimodal } = await import('./ai/gateway.ts');
- const [vec] = await embedMultimodal([
- { kind: 'image_base64', data: imageData, mime: imageMime },
- ]);
- // v0.34.1 (#861 F2 — 6th leak surface): the image path bypasses
- // hybridSearch and calls searchVector directly, so it needs its
- // own thread of the source scope. Pre-fix, this branch leaked
- // image pages across sources independent of the text path's fix.
- const results = await ctx.engine.searchVector(vec, {
- limit: (p.limit as number) || 20,
- offset: (p.offset as number) || 0,
- embeddingColumn: 'embedding_image',
- ...querySourceScope,
- });
- return results;
- }
-
- if (!queryText) {
- // WP3: typed envelope — a caller mistake must classify as invalid_params
- // over MCP, not the internal_error a plain throw produced.
- throw new OperationError(
- 'invalid_params',
- 'query requires either `query` (text) or `image` (base64 bytes).',
- 'Pass `query` with your search text (e.g. {"query": "acme-example roadmap"}), or `image` with base64 image bytes.',
- );
- }
-
- // v0.25.0 — capture meta side-channel. hybridSearch's return contract
- // stays SearchResult[] (Cathedral II callers depend on that); meta
- // arrives via callback so eval capture can record what actually ran.
- //
- // v0.34 (Codex finding #2): thread ctx.sourceId so multi-source brains
- // get source-scoped retrieval. Explicit `source_id` param wins over
- // ctx.sourceId for callers that want to override (per-call multi-source
- // search). When the param is the literal '__all__', force-allow
- // 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.
- const results = await hybridSearchCached(ctx.engine, queryText, {
- limit: (p.limit as number) || 20,
- offset: (p.offset as number) || 0,
- expansion: expand,
- expandFn: expand ? expandQuery : undefined,
- // T4/D5 — per-call mode (local/trusted only; remote ignored).
- ...((): { mode?: string } => { const m = resolvePerCallMode(ctx, p.mode); return m ? { mode: m } : {}; })(),
- detail,
- language: (p.lang as string) || undefined,
- symbolKind: (p.symbol_kind as string) || undefined,
- nearSymbol: (p.near_symbol as string) || undefined,
- walkDepth: typeof p.walk_depth === 'number' ? (p.walk_depth as number) : undefined,
- ...querySourceScope,
- // v0.29.1 — agent-explicit recency + salience. Omitted = heuristic defaults.
- salience: p.salience as 'off' | 'on' | 'strong' | undefined,
- recency: p.recency as 'off' | 'on' | 'strong' | undefined,
- since: typeof p.since === 'string' ? p.since : undefined,
- until: typeof p.until === 'string' ? p.until : undefined,
- // v0.32.x search-lite: token budget + cache opt-outs.
- tokenBudget: typeof p.token_budget === 'number' ? (p.token_budget as number) : undefined,
- useCache: typeof p.use_cache === 'boolean' ? (p.use_cache as boolean) : undefined,
- intentWeighting: typeof p.intent_weighting === 'boolean' ? (p.intent_weighting as boolean) : undefined,
- // v0.36 cross-modal routing param.
- crossModal: p.cross_modal as 'text' | 'image' | 'both' | 'auto' | undefined,
- onMeta: (m) => { capturedMeta = m; },
- // v0.36 (D15): per-call embedding column override. Resolver rejects
- // unknown names at hybrid entry with EmbeddingColumnNotRegisteredError;
- // the error surfaces back to the agent as the op error envelope.
- // Source scope is already threaded via ...querySourceScope above
- // (master's #1182 cleanup of the duplicate sourceScopeOpts spread).
- embeddingColumn: embeddingColumnParam,
- // v0.41.33 — agent-explicit adaptive return-sizing. Omitted = off
- // (config default applies). hybridSearchCached skips the cache when on.
- 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.
- autocut: typeof p.autocut === 'boolean' ? (p.autocut as boolean) : undefined,
- // v0.43 — relational recall override. Omitted = smart default (mode bundle).
- relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
- });
- const latency_ms = Date.now() - startedAt;
-
- // v0.37.0 (D11): op-layer last_retrieved_at write-back. Same shape as the
- // search handler — fire-and-forget, internal callers bypass this path.
- bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
-
- // Op-layer capture (v0.25.0). Fire-and-forget. meta tells gbrain-evals
- // what hybridSearch *actually* did so replay can distinguish "with API
- // key" from "keyword-only fallback" and "expansion fired" from
- // "expansion requested + silently fell back."
- if (isEvalCaptureEnabled(ctx.config)) {
- const meta: HybridSearchMeta = capturedMeta ?? {
- vector_enabled: false, detail_resolved: detail ?? null, expansion_applied: false,
- };
- void captureEvalCandidate(
- ctx.engine,
- {
- tool_name: 'query',
- query: queryText,
- results,
- meta,
- latency_ms,
- remote: ctx.remote ?? false,
- expand_enabled: expand,
- detail: detail ?? null,
- job_id: ctx.jobId ?? null,
- subagent_id: ctx.subagentId ?? null,
- },
- { scrub_pii: isEvalScrubEnabled(ctx.config) },
- );
- }
-
- // WP2/D3: query never nudges toward itself — no concept hint here.
- ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta));
- return results;
- },
- scope: 'read',
- cliHints: { name: 'query', positional: ['query'] },
-};
-
-// --- v0.28: Takes ---
-
-const takes_list: Operation = {
- name: 'takes_list',
- description: 'List takes (typed/weighted/attributed claims) filtered by holder/kind/active/etc.',
- scope: 'read',
- params: {
- page_slug: { type: 'string', description: 'Filter to this page' },
- holder: { type: 'string', description: 'Filter to this holder (world|garry|brain|<slug>)' },
- kind: { type: 'string', description: 'Filter to this kind (fact|take|bet|hunch)' },
- active: { type: 'boolean', description: 'Active rows only (default true)' },
- resolved: { type: 'boolean', description: 'true → only resolved bets; false → only unresolved' },
- sort_by: { type: 'string', description: 'weight | since_date | created_at (default created_at)' },
- limit: { type: 'number', description: 'Max rows (default 100, cap 500)' },
- offset: { type: 'number', description: 'Skip first N rows' },
- },
- handler: async (ctx, p) => {
- return ctx.engine.listTakes({
- // #2200-class: honor federated/source scope (via the take's page.source_id).
- ...sourceScopeOpts(ctx),
- page_slug: p.page_slug as string | undefined,
- holder: p.holder as string | undefined,
- kind: p.kind as never,
- active: p.active as boolean | undefined,
- resolved: p.resolved as boolean | undefined,
- sortBy: p.sort_by as never,
- limit: p.limit as number | undefined,
- 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,
- });
- },
- cliHints: { name: 'takes-list' },
-};
-
-const takes_search: Operation = {
- name: 'takes_search',
- description: 'Keyword search across takes (pg_trgm similarity over claim text)',
- scope: 'read',
- params: {
- query: { type: 'string', required: true, description: "Search text matched against take claim text via trigram similarity, e.g. 'valuation cap'. This is the search text param — there is no `text` param." },
- limit: { type: 'number', description: 'Max results (default 30, cap 100)' },
- },
- handler: async (ctx, p) => {
- return ctx.engine.searchTakes(p.query as string, {
- ...sourceScopeOpts(ctx),
- limit: p.limit as number | undefined,
- takesHoldersAllowList: ctx.takesHoldersAllowList,
- });
- },
- cliHints: { name: 'takes-search', positional: ['query'] },
-};
-
-/**
- * v0.30.0 (Slice A1): aggregate calibration scorecard. Pure SQL aggregation.
- *
- * Privacy (D4 fail-closed): the engine method REQUIRES the takesHoldersAllowList
- * param. The handler threads it from the OperationContext so MCP-bound callers
- * see only their permitted holders' aggregate counts. Local CLI callers
- * (ctx.takesHoldersAllowList=undefined) get the full scorecard.
- */
-const takes_scorecard: Operation = {
- name: 'takes_scorecard',
- description: 'Calibration scorecard for resolved bets: counts, accuracy, Brier (correct ∨ incorrect only), partial_rate.',
- scope: 'read',
- params: {
- holder: { type: 'string', description: 'Filter to this holder (world|garry|brain|<slug>)' },
- domain_prefix: { type: 'string', description: 'Slug prefix (e.g. companies/) to scope the scorecard' },
- since: { type: 'string', description: 'Window start (YYYY-MM-DD)' },
- until: { type: 'string', description: 'Window end (YYYY-MM-DD)' },
- },
- handler: async (ctx, p) => {
- return ctx.engine.getScorecard(
- {
- ...sourceScopeOpts(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,
- );
- },
- cliHints: { name: 'takes-scorecard' },
-};
-
-/**
- * v0.30.0 (Slice A1): calibration curve binned by stated weight. Pure SQL.
- * Same allow-list contract as takes_scorecard.
- */
-const takes_calibration: Operation = {
- name: 'takes_calibration',
- description: 'Calibration curve: resolved correct/incorrect bets binned by stated weight; observed vs predicted per bucket.',
- scope: 'read',
- params: {
- holder: { type: 'string', description: 'Filter to this holder' },
- bucket_size: { type: 'number', description: 'Bucket width in (0,1]; default 0.1' },
- },
- handler: async (ctx, p) => {
- return ctx.engine.getCalibrationCurve(
- {
- ...sourceScopeOpts(ctx),
- holder: p.holder as string | undefined,
- bucketSize: p.bucket_size as number | undefined,
- },
- ctx.takesHoldersAllowList,
- );
- },
- cliHints: { name: 'takes-calibration' },
-};
-
-const think: Operation = {
- name: 'think',
- description: 'Multi-hop synthesis across pages + takes + graph. Pulls relevant evidence and produces a cited answer with conflict + gap analysis.',
- scope: 'read',
- params: {
- question: { type: 'string', required: true, description: 'The question to think about' },
- anchor: { type: 'string', description: 'Pull the entity subgraph around this slug' },
- rounds: { type: 'number', description: 'Multi-pass: 1 (default). Round-loop scaffolding is in place; gap-driven retrieval ships in v0.29.' },
- save: { type: 'boolean', description: 'Persist a synthesis page (local-CLI only; ignored for MCP)' },
- take: { type: 'boolean', description: 'Append a take row to the anchor page (requires anchor)' },
- model: { type: 'string', description: 'Model override (alias or full id). Falls through models.think → models.default → GBRAIN_MODEL → opus.' },
- since: { type: 'string', description: 'Start of temporal window (YYYY-MM-DD or YYYY-MM)' },
- until: { type: 'string', description: 'End of temporal window' },
- },
- // Local CLI can persist with save/take; remote/MCP callers are forced
- // read-only below before runThink/persistSynthesis sees those flags.
- mutating: true,
- handler: async (ctx, p) => {
- const remote = ctx.remote ?? true;
- // Codex P1 #7 + privacy: remote callers cannot persist via MCP.
- const safeSave = remote ? false : Boolean(p.save);
- const safeTake = remote ? false : Boolean(p.take);
- // v0.40.2.0: thread source-scope scalars + remote flag for trajectory
- // injection. `sourceScopeOpts(ctx)` returns the federated array (when
- // present) OR the scalar; we pass both through to runThink which
- // forwards to findTrajectory. CLI callers don't go through this op
- // and get default scope + remote=false from runThink's CLI path.
- const thinkScope = thinkSourceScopeOpts(ctx);
- const { runThink, persistSynthesis } = await import('./think/index.ts');
- const result = await runThink(ctx.engine, {
- question: String(p.question),
- anchor: p.anchor ? String(p.anchor) : undefined,
- rounds: typeof p.rounds === 'number' ? (p.rounds as number) : undefined,
- save: safeSave,
- take: safeTake,
- model: p.model ? String(p.model) : undefined,
- // #1698 (C3): a remote caller that explicitly supplies a model gets the same
- // hard-error-on-unresolvable behavior as the CLI (loud op error envelope),
- // instead of silently degrading to a no-LLM stub answer. No model param →
- // false → configured/default model keeps its graceful path.
- modelExplicit: !!p.model,
- since: p.since ? String(p.since) : undefined,
- until: p.until ? String(p.until) : undefined,
- takesHoldersAllowList: ctx.takesHoldersAllowList,
- ...thinkScope,
- remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)
- });
-
- // Persist if --save was passed locally
- let savedSlug: string | undefined;
- let evidenceInserted = 0;
- if (safeSave) {
- const persisted = await persistSynthesis(ctx.engine, result);
- savedSlug = persisted.slug;
- evidenceInserted = persisted.evidenceInserted;
- for (const w of persisted.warnings) result.warnings.push(w);
- }
-
- return {
- ...result,
- // #1698 (#10): the persist-skip signal returns slug '' — map it (and any
- // falsy) to null so callers never see an empty-string "slug".
- saved_slug: savedSlug || null,
- evidence_inserted: evidenceInserted,
- remote_persisted_blocked: remote && (Boolean(p.save) || Boolean(p.take)),
- };
- },
- cliHints: { name: 'think', positional: ['question'] },
-};
-
-// --- Tags ---
-
-const add_tag: Operation = {
- name: 'add_tag',
- description: 'Add tag to page',
- params: {
- slug: { type: 'string', required: true, description: "Slug of the page to tag, e.g. 'people/alice-example'." },
- tag: { type: 'string', required: true, description: "Tag to add — a plain string like 'founder' or 'follow-up', not a slug." },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- enforceClientSlugFence(ctx, p.slug as string, 'add_tag');
- if (ctx.dryRun) return { dry_run: true, action: 'add_tag', slug: p.slug, tag: p.tag };
- // v0.31.8 (D7): thread ctx.sourceId.
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- await ctx.engine.addTag(p.slug as string, p.tag as string, sourceOpts);
- return { status: 'ok' };
- },
- cliHints: { name: 'tag', positional: ['slug', 'tag'] },
-};
-
-const remove_tag: Operation = {
- name: 'remove_tag',
- description: 'Remove tag from page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page to untag.' },
- tag: { type: 'string', required: true, description: 'Tag to remove (exact match against the tags get_tags returns).' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- enforceClientSlugFence(ctx, p.slug as string, 'remove_tag');
- if (ctx.dryRun) return { dry_run: true, action: 'remove_tag', slug: p.slug, tag: p.tag };
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- await ctx.engine.removeTag(p.slug as string, p.tag as string, sourceOpts);
- return { status: 'ok' };
- },
- cliHints: { name: 'untag', positional: ['slug', 'tag'] },
-};
-
-const get_tags: Operation = {
- name: 'get_tags',
- description: 'List tags for a page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose tags to list.' },
- },
- handler: async (ctx, p) => {
- // #2200: route through sourceScopeOpts so a federated read grant
- // (ctx.auth.allowedSources) reaches the engine, not just scalar ctx.sourceId.
- // Was `ctx.sourceId ? {sourceId} : {}` — a federated client got '{}' →
- // engine fell back to 'default' (functionality gap + cross-source leak).
- const sourceOpts = sourceScopeOpts(ctx);
- return ctx.engine.getTags(p.slug as string, sourceOpts);
- },
- scope: 'read',
- cliHints: { name: 'tags', positional: ['slug'] },
-};
-
-// --- Links ---
-
-/**
- * v114 (#1941): reconciliation-managed provenances a CALLER must not forge via
- * the add_link op. Internal writers (import-file frontmatter reconciliation,
- * extract --by-mention, wikilink resolution) write these straight through the
- * engine — they're excluded here, not at the DB CHECK. A hand-created edge
- * tagged 'frontmatter' with no origin_page_id would be a phantom that put_page
- * reconciliation (link_source='frontmatter' AND origin_page_id=written_page)
- * never cleans (see src/schema.sql). `manual` is intentionally absent — it IS
- * the user-facing provenance and the default for omitted link_source.
- */
-export const MANAGED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-resolved'];
-
-const add_link: Operation = {
- name: 'add_link',
- description: 'Create link between pages',
- params: {
- from: { type: 'string', required: true, description: "Slug of the page the link originates from (the edge renders on this page), e.g. 'people/alice-example'. These are page slugs — there is no `source`/`target` pair." },
- to: { type: 'string', required: true, description: "Slug of the page the link points to, e.g. 'companies/acme-example'." },
- link_type: { type: 'string', description: 'Link type (e.g., invested_in, works_at)' },
- context: { type: 'string', description: 'Context for the link' },
- link_source: { type: 'string', description: "Provenance tag (kebab-case, e.g. 'citation-graph'). Defaults to 'manual'. Reconciliation-managed built-ins (markdown/frontmatter/mentions/wikilink-resolved) are rejected." },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- // Client fence on the `from` endpoint only: the edge originates from
- // (and renders on) the from page; linking TO a page outside the
- // binding is a reference, not a mutation of the target.
- enforceClientSlugFence(ctx, p.from as string, 'add_link');
- if (ctx.dryRun) return { dry_run: true, action: 'add_link', from: p.from, to: p.to };
- // v114 (#1941): default omitted provenance to 'manual' (NOT the engine's
- // 'markdown' default) so hand/tool-created CLI edges are honestly manual,
- // and forbid forging the reconciliation-managed built-ins.
- const linkSource = ((p.link_source as string) || 'manual').trim();
- if (MANAGED_LINK_SOURCES.includes(linkSource)) {
- throw new Error(
- `link_source '${linkSource}' is reconciliation-managed and cannot be set manually; ` +
- `use 'manual' (the default) or a custom kebab tag like 'citation-graph'`,
- );
- }
- // v0.31.8 (D7): single ctx.sourceId scopes both endpoints + origin. Cross-
- // source link creation is out of scope for this wave; use the engine API
- // directly for that edge case.
- const linkOpts = ctx.sourceId
- ? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId, originSourceId: ctx.sourceId }
- : undefined;
- await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hook
- p.from as string, p.to as string,
- (p.context as string) || '', (p.link_type as string) || '',
- linkSource, undefined, undefined,
- linkOpts,
- );
- return { status: 'ok' };
- },
- cliHints: { name: 'link', aliases: ['link-add'], positional: ['from', 'to'] },
-};
-
-const remove_link: Operation = {
- name: 'remove_link',
- description: 'Remove link between pages',
- params: {
- from: { type: 'string', required: true, description: 'Slug of the page the link originates from (same endpoint order as add_link).' },
- to: { type: 'string', required: true, description: 'Slug of the page the link points to.' },
- link_type: { type: 'string', description: 'Only remove edges of this link type (omit = all types)' },
- link_source: { type: 'string', description: 'Only remove edges of this provenance (e.g. citation-graph); omit = any provenance' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- enforceClientSlugFence(ctx, p.from as string, 'remove_link');
- if (ctx.dryRun) return { dry_run: true, action: 'remove_link', from: p.from, to: p.to };
- const linkOpts = ctx.sourceId
- ? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId }
- : undefined;
- await ctx.engine.removeLink(
- p.from as string, p.to as string,
- (p.link_type as string) || undefined,
- (p.link_source as string) || undefined,
- linkOpts,
- );
- return { status: 'ok' };
- },
- cliHints: { name: 'unlink', aliases: ['link-rm'], positional: ['from', 'to'] },
-};
-
-const get_links: Operation = {
- name: 'get_links',
- description: 'List outgoing links from a page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },
- },
- handler: async (ctx, p) => {
- // #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);
- return ctx.engine.getLinks(p.slug as string, sourceOpts);
- },
- scope: 'read',
-};
-
-const get_backlinks: Operation = {
- name: 'get_backlinks',
- description: 'List incoming links to a page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose incoming links to list.' },
- },
- 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);
- return ctx.engine.getBacklinks(p.slug as string, sourceOpts);
- },
- scope: 'read',
- cliHints: { name: 'backlinks', positional: ['slug'] },
-};
-
-const list_link_sources: Operation = {
- name: 'list_link_sources',
- // v114 (#1941): the read-side counterpart to link-add/link-rm. Since
- // link_source is now an open kebab provenance (no allowlist), this is how an
- // agent discovers which provenances a brain actually carries.
- description: 'List distinct link_source provenances in the brain with edge counts (e.g. citation-graph, manual, markdown)',
- params: {},
- handler: async (ctx) => {
- // Route through sourceScopeOpts so the read honors both scalar ctx.sourceId
- // and federated ctx.auth.allowedSources (no cross-source provenance leak).
- return ctx.engine.listLinkSources(sourceScopeOpts(ctx));
- },
- scope: 'read',
- cliHints: { name: 'link-sources' },
-};
-
-/**
- * Hard cap on traverse_graph depth from MCP callers. Each recursive CTE iteration
- * grows a `visited` array per path; in `direction=both` the join is `OR`-based and
- * fans out exponentially. Without a cap, a remote MCP caller can pass depth=1e6
- * and burn memory/CPU on the database. 10 hops is well beyond any realistic
- * relationship query (your OpenClaw's "people who attended meetings with Alice"
- * is 2 hops; the deepest meaningful chain in our test data is 4).
- */
-const TRAVERSE_DEPTH_CAP = 10;
-
-const traverse_graph: Operation = {
- name: 'traverse_graph',
- description: 'Traverse link graph from a page. With link_type/direction, returns edges (GraphPath[]) instead of nodes.',
- params: {
- slug: { type: 'string', required: true, description: "Slug of the page to start the traversal from, e.g. 'people/alice-example'. This is the start-node param — there is no `start` or `root` param." },
- depth: { type: 'number', description: `Max traversal depth (default 5, capped at ${TRAVERSE_DEPTH_CAP})` },
- link_type: { type: 'string', description: 'Filter to one link type (per-edge filter, traversal only follows matching edges)' },
- direction: { type: 'string', enum: ['in', 'out', 'both'], description: 'Traversal direction (default out)' },
- },
- handler: async (ctx, p) => {
- const slug = p.slug as string;
- const requestedDepth = (p.depth as number) || 5;
- if (requestedDepth > TRAVERSE_DEPTH_CAP) {
- ctx.logger.warn(`[gbrain] traverse_graph depth clamped from ${requestedDepth} to ${TRAVERSE_DEPTH_CAP}`);
- }
- const depth = Math.max(1, Math.min(requestedDepth, TRAVERSE_DEPTH_CAP));
- const linkType = p.link_type as string | undefined;
- const direction = p.direction as 'in' | 'out' | 'both' | undefined;
- // v0.34.1 (#861 — P0 leak seal): thread caller's source scope so graph
- // 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);
- // Backward compat: when neither link_type nor direction is provided, return
- // the legacy GraphNode[] shape. Once either is set, switch to GraphPath[].
- if (linkType === undefined && direction === undefined) {
- return ctx.engine.traverseGraph(slug, depth, scope);
- }
- return ctx.engine.traversePaths(slug, { depth, linkType, direction, ...scope });
- },
- scope: 'read',
- cliHints: { name: 'graph', positional: ['slug'] },
-};
-
-// --- Timeline ---
-
-const add_timeline_entry: Operation = {
- name: 'add_timeline_entry',
- description: 'Add timeline entry to a page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose timeline to append to.' },
- date: { type: 'string', required: true, description: "Entry date, strict YYYY-MM-DD (e.g. '2026-04-03'). Timestamps and non-calendar dates are rejected." },
- summary: { type: 'string', required: true, description: 'One-line summary of what happened on that date.' },
- detail: { type: 'string', description: 'Longer free-text detail behind the summary.' },
- source: { type: 'string', description: "Provenance ref for the entry, e.g. a meeting slug like 'meetings/2026-04-03' or a URL." },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- // #2778: same fail-closed slug fence as put_page. add_timeline_entry is
- // subagent-allowlisted (brain-allowlist.ts), so timeline writes must be
- // confined to the same namespace/allow-list as page writes. Runs before
- // the dry-run short-circuit so preview calls surface the same rejection.
- enforceSubagentSlugFence(ctx, p.slug as string, 'add_timeline_entry');
- enforceClientSlugFence(ctx, p.slug as string, 'add_timeline_entry');
- if (ctx.dryRun) return { dry_run: true, action: 'add_timeline_entry', slug: p.slug };
- const date = p.date as string;
- // Reject anything that isn't a strict YYYY-MM-DD with year 1900-2199 and
- // a real calendar day. PG DATE accepts year 5874897 silently — that's a
- // semantic bug nobody actually wants.
- if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
- throw new Error(`Invalid date format "${date}" (expected YYYY-MM-DD)`);
- }
- const [y, m, d] = date.split('-').map(Number);
- if (y < 1900 || y > 2199 || m < 1 || m > 12 || d < 1 || d > 31) {
- throw new Error(`Invalid date "${date}" (year 1900-2199, month 1-12, day 1-31)`);
- }
- // Round-trip through Date to catch e.g. Feb 30.
- const parsed = new Date(date);
- if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
- throw new Error(`Invalid calendar date "${date}"`);
- }
- // v0.31.8 (D7): thread ctx.sourceId.
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- await ctx.engine.addTimelineEntry(p.slug as string, { // gbrain-allow-direct-insert: add_timeline_entry MCP op is the explicit canonical surface for manual timeline entries
- date,
- source: (p.source as string) || '',
- summary: p.summary as string,
- detail: (p.detail as string) || '',
- }, sourceOpts);
- return { status: 'ok' };
- },
- cliHints: { name: 'timeline-add', positional: ['slug', 'date', 'summary'] },
-};
-
-const get_timeline: Operation = {
- name: 'get_timeline',
- description: 'Get timeline entries for a page, optionally filtered by date window',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose timeline entries to return.' },
- after: { type: 'string', description: 'Return entries on or after this date (YYYY-MM-DD)' },
- before: { type: 'string', description: 'Return entries on or before this date (YYYY-MM-DD)' },
- since: { type: 'string', description: 'Alias for after; accepted for agent callers' },
- until: { type: 'string', description: 'Alias for before; accepted for agent callers' },
- limit: { type: 'number', description: 'Maximum number of timeline entries to return' },
- },
- handler: async (ctx, p) => {
- // #2200: route through sourceScopeOpts so a federated grant reaches the
- // engine via TimelineOpts.sourceIds; scalar/unset unchanged.
- 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;
- return ctx.engine.getTimeline(p.slug as string, {
- ...sourceScopeOpts(ctx),
- ...(after ? { after } : {}),
- ...(before ? { before } : {}),
- ...(limit !== undefined ? { limit } : {}),
- });
- },
- scope: 'read',
- cliHints: { name: 'timeline', positional: ['slug'] },
-};
-
-// --- Admin ---
-
-const get_stats: Operation = {
- name: 'get_stats',
- description: 'Brain statistics (page count, chunk count, etc.)',
- params: {},
- handler: async (ctx) => {
- return ctx.engine.getStats();
- },
- scope: 'admin',
- cliHints: { name: 'stats' },
-};
-
-const get_health: Operation = {
- name: 'get_health',
- description: 'Brain health dashboard (embed coverage, stale pages, orphans)',
- params: {},
- handler: async (ctx) => {
- return ctx.engine.getHealth();
- },
- scope: 'admin',
- cliHints: { name: 'health' },
-};
-
-/**
- * v0.31.1 (Issue #734): lightweight identity packet for the thin-client
- * banner. Read-scope so any authenticated client can surface "thin-client →
- * <host> · brain: 102k pages, 265k chunks · v0.31.1" without needing admin.
- *
- * Reuses engine.getStats() for counters (banner cache TTL bounds frequency
- * to ≤1/60s per CLI process; well below the Fly.io health-check cadence
- * that motivated the `getStats` cost warning in CLAUDE.md).
- *
- * No CLI surface (no cliHints) — this op exists only for thin-client banner
- * data. `last_sync_iso` deferred (no canonical source field today; would
- * need autopilot cycle to write a config key — TODO in v0.31.x).
- */
-const get_brain_identity: Operation = {
- name: 'get_brain_identity',
- description: 'Brain identity + counters for thin-client banner. Returns version, engine kind, and page/chunk counts. Read-scope.',
- params: {},
- handler: async (ctx) => {
- const stats = await ctx.engine.getStats();
- // v0.42 self-upgrade: surface a pending update on the thin-client banner
- // (bonus channel; the CLI stderr marker + `gbrain self-upgrade` are the
- // load-bearing surface). Cache-read-only, no network, fail-open.
- let update_available = false;
- let latest_version: string | null = null;
- try {
- const su = await import('./self-upgrade.ts');
- // Shared stale/foreign-cache guard (pendingUpgradeVersion): only an
- // upgrade strictly newer than the RUNNING version counts.
- const latest = su.pendingUpgradeVersion(VERSION, Date.now());
- if (latest) {
- update_available = true;
- latest_version = latest;
- }
- } catch {
- /* never let the banner break the op */
- }
- return {
- version: VERSION,
- engine: ctx.engine.kind,
- page_count: stats.page_count,
- chunk_count: stats.chunk_count,
- last_sync_iso: null as string | null,
- update_available,
- latest_version,
- };
- },
- scope: 'read',
- // intentionally no cliHints — banner-only op
-};
-
-// --- PR1: skill catalog over MCP (host-repo skills for thin clients) ---
-// Both ops dynamically import ./skill-catalog.ts to avoid an import cycle
-// (skill-catalog statically imports the `operations` array for D7 tool honesty).
-// Read-scope, non-localOnly: a thin client (Codex/Perplexity/Cowork) reaches
-// these over HTTP. The host-filesystem read is gated by mcp.publish_skills +
-// path confinement — see the trust-boundary memo in skill-catalog.ts.
-
-const list_skills: Operation = {
- name: 'list_skills',
- description: LIST_SKILLS_DESCRIPTION,
- publishGateKey: 'mcp.publish_skills',
- params: {
- section: {
- type: 'string',
- description: 'Optional: only skills whose routing section matches this exactly.',
- },
- },
- handler: async (ctx, p) => {
- const sc = await import('./skill-catalog.ts');
- const publish = await sc.readMcpPublishSkills(ctx);
- sc.assertPublishEnabled(ctx, publish);
- const override = await sc.readMcpSkillsDir(ctx);
- const { dir, source } = sc.resolveSkillsDir(ctx, override);
- const section = typeof p.section === 'string' ? p.section : undefined;
- return sc.buildSkillCatalog(ctx, dir, source, { section });
- },
- scope: 'read',
- cliHints: { name: 'skills', positional: [] },
-};
-
-const get_skill: Operation = {
- name: 'get_skill',
- description: GET_SKILL_DESCRIPTION,
- publishGateKey: 'mcp.publish_skills',
- params: {
- name: {
- type: 'string',
- required: true,
- description: 'Skill name exactly as returned by list_skills (or the brain-pack skill slug when source_id is set).',
- },
- source_id: {
- type: 'string',
- description:
- 'Optional: fetch a brain-resident pack skill from this source instead of the host catalog. ' +
- 'Disambiguates a slug that exists on more than one source (see list_brain_skillpack).',
- },
- },
- handler: async (ctx, p) => {
- const sc = await import('./skill-catalog.ts');
- const publish = await sc.readMcpPublishSkills(ctx);
- sc.assertPublishEnabled(ctx, publish);
- // Brain-resident path: when source_id is supplied, fetch the per-source pack
- // skill (confined to that source's pack root) rather than the host catalog.
- if (typeof p.source_id === 'string' && p.source_id.length > 0) {
- const brl = await import('./skillpack/brain-resident-locate.ts');
- const slug = typeof p.name === 'string' ? p.name : '';
- return brl.getResidentSkillDetail(ctx, p.source_id, slug);
- }
- const override = await sc.readMcpSkillsDir(ctx);
- const { dir } = sc.resolveSkillsDir(ctx, override);
- const name = typeof p.name === 'string' ? p.name : '';
- return sc.getSkillDetail(ctx, dir, name);
- },
- scope: 'read',
- cliHints: { name: 'skill', positional: ['name'] },
-};
-
-const list_brain_skillpack: Operation = {
- name: 'list_brain_skillpack',
- description:
- 'List brain-resident skillpacks this brain ships (per-source). Returns each pack\'s skills, ' +
- 'one-line descriptions, the schema pack it targets + whether that matches this brain, and a ' +
- 'git scaffold spec. Read-only; gated by mcp.publish_skills. After orienting, call this and ' +
- 'ask the user whether to install any pack the brain offers (gbrain skillpack scaffold <spec>).',
- publishGateKey: 'mcp.publish_skills',
- params: {},
- handler: async (ctx) => {
- const sc = await import('./skill-catalog.ts');
- const publish = await sc.readMcpPublishSkills(ctx);
- sc.assertPublishEnabled(ctx, publish);
- const brl = await import('./skillpack/brain-resident-locate.ts');
- return brl.loadResidentPacksForServer(ctx);
- },
- scope: 'read',
- cliHints: { name: 'brain-skillpack', positional: [] },
-};
-
-const advisor: Operation = {
- name: 'advisor',
- description:
- 'Ranked, read-only "what to do next" for this brain: version drift, pending migrations, ' +
- 'schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. Each finding has a ' +
- 'severity, why-it-matters, and the exact fix command. Never mutates. Tell the user; ask ' +
- 'before running any fix. Gated by mcp.publish_advisor (separate from mcp.publish_skills ' +
- 'because diagnostics are not prose skills).',
- publishGateKey: 'mcp.publish_advisor',
- params: {},
- handler: async (ctx) => {
- // Publish gate: a remote caller needs mcp.publish_advisor=true. Local
- // (ctx.remote === false) callers bypass — the trust boundary is the OS.
- if (ctx.remote !== false) {
- let enabled = false;
- try {
- const dbVal = await ctx.engine.getConfig('mcp.publish_advisor');
- enabled = dbVal != null ? dbVal === 'true' : ctx.config?.mcp?.publish_advisor === true;
- } catch {
- enabled = ctx.config?.mcp?.publish_advisor === true;
- }
- if (!enabled) {
- // Same k=v detail grammar as assertPublishEnabled (WP1): honest
- // catalogs hide this op at list time; the throw is the backstop.
- const err = new OperationError(
- 'permission_denied',
- 'The advisor is not published over MCP by the brain owner, so it is hidden from your ' +
- 'tool catalog. Ask the owner to enable it if you need it.',
- 'The owner can enable it with `gbrain config set mcp.publish_advisor true`.',
- );
- err.detail = 'config_key=mcp.publish_advisor';
- throw err;
- }
- }
- const { runAdvisor } = await import('./advisor/run.ts');
- const { VERSION } = await import('../version.ts');
- // Over MCP there is no agent workspace on the server side: remote=true makes
- // runAdvisor drop workspace-dependent collectors (A1). The op never writes
- // history or nag state — it is strictly read-only.
- const report = await runAdvisor({
- engine: ctx.engine,
- config: ctx.config,
- version: VERSION,
- workspace: null,
- skillsDir: null,
- now: new Date(),
- remote: ctx.remote !== false,
- });
- return report;
- },
- scope: 'read',
- // NOT localOnly — exposed over MCP (E1) behind mcp.publish_advisor.
- // No cliHints: the CLI surface is the richer `gbrain advisor` command
- // (commands/advisor.ts) which adds --json exit codes + --apply.
- cliHints: { name: 'advisor', hidden: true },
-};
-
-/**
- * v0.41.19.0 — `gbrain status` thin-client surface.
- *
- * Returns a snapshot of sync freshness + last cycle state for thin-client
- * `gbrain status` callers. Per D2/D10 in the plan:
- *
- * - Scope: admin (NOT localOnly). The op exposes operational state
- * including sync timestamps and cycle metadata. Locking it to admin
- * matches the `run_doctor` posture and prevents future feature creep
- * from quietly leaking ops state to read-scoped clients.
- *
- * - Payload (schema_version 2, Minions-visibility wave): `{schema_version,
- * version, sync, cycle, queue, workers}`. `queue` (status counts +
- * per-queue waiting depth + oldest-waiting age) and `workers`
- * (supervisor liveness via pidfile/DB-lock + last completed job) were
- * added so a remote submitter can see whether the lane its job ids point
- * at is actually alive. Locks and Autopilot stay deliberately omitted —
- * host-local concerns the thin client renders as "N/A on remote brain".
- *
- * - Fail-soft (amendment 26): each v2 section computes in its own
- * try/catch and degrades to `{error: 'unavailable'}` without failing
- * the whole snapshot.
- *
- * - The local CLI composes the same data plus the local-only sections
- * directly (no MCP round-trip when running against ~/.gbrain).
- */
-const get_status_snapshot: Operation = {
- name: 'get_status_snapshot',
- description: 'Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. Admin-scope.',
- params: {},
- handler: async (ctx) => {
- const { buildSyncStatusReport } = await import('../commands/sync.ts');
- const { buildCycleSnapshot } = await import('../commands/status.ts');
- // Pull sources first (handles brains with zero declared sources too).
- let sources: Array<{ id: string; name: string; local_path: string | null; config: Record<string, unknown> }> = [];
- try {
- const rows = await ctx.engine.executeRaw<{
- id: string;
- name: string;
- local_path: string | null;
- config: Record<string, unknown> | null;
- }>(
- `SELECT id, name, local_path, config FROM sources WHERE COALESCE(archived, FALSE) = FALSE ORDER BY id`,
- );
- sources = rows.map((r) => ({
- id: r.id,
- name: r.name,
- local_path: r.local_path,
- config: r.config ?? {},
- }));
- } catch {
- // Pre-v0.26.5 brains may lack the `archived` column; degrade to all rows.
- const rows = await ctx.engine.executeRaw<{
- id: string;
- name: string;
- local_path: string | null;
- config: Record<string, unknown> | null;
- }>(`SELECT id, name, local_path, config FROM sources ORDER BY id`);
- sources = rows.map((r) => ({
- id: r.id,
- name: r.name,
- local_path: r.local_path,
- config: r.config ?? {},
- }));
- }
- const sync = await buildSyncStatusReport(ctx.engine, sources);
- const cycle = await buildCycleSnapshot(ctx.engine);
- // v2 sections, each fail-soft (amendment 26): a broken/pre-migration
- // queue table must not take down the sync/cycle payload that v1 clients
- // already depend on.
- let queue: unknown;
- try {
- const { buildQueueCounts, buildQueueDepths } = await import('../commands/status.ts');
- queue = { counts: await buildQueueCounts(ctx.engine), by_queue: await buildQueueDepths(ctx.engine) };
- } catch {
- queue = { error: 'unavailable' as const };
- }
- let workers: unknown;
- try {
- const { buildWorkersSnapshot } = await import('../commands/status.ts');
- workers = await buildWorkersSnapshot(ctx.engine);
- } catch {
- workers = { error: 'unavailable' as const };
- }
- // #1984: report the brain server's version so a thin-client `gbrain status`
- // can surface remote_version alongside its own local CLI version.
- const { VERSION } = await import('../version.ts');
- return { schema_version: 2 as const, version: VERSION, sync, cycle, queue, workers };
- },
- scope: 'admin',
- localOnly: false,
-};
-
-/**
- * Multi-topology v1 (Tier B): structured doctor report for remote callers.
- *
- * First read-only diagnostic op exposed over HTTP MCP. Wraps the focused
- * thin-client check set in `src/commands/doctor.ts:doctorReportRemote()` and
- * returns the structured `DoctorReport` JSON verbatim. The matching client-
- * side renderer lives in `src/commands/remote.ts` (used by `gbrain remote
- * doctor`). Local doctor is unchanged — operators on the host still get the
- * full check set.
- *
- * scope=admin because some checks expose system-state (queue depth, schema
- * version) that read-only consumers don't need. localOnly=false so HTTP
- * callers can invoke it. No mutation; safe to call repeatedly.
- *
- * Precedent: doctor only. Generalizing to lint/integrity/orphans is filed as
- * follow-up work pending demand.
- */
-const run_doctor: Operation = {
- name: 'run_doctor',
- description: 'Run brain health checks and return a structured DoctorReport (thin-client doctor surface).',
- params: {},
- handler: async (ctx) => {
- const { doctorReportRemote } = await import('../commands/doctor.ts');
- // Source isolation (cross-model P1): a source-bound caller's report must
- // not aggregate other sources' activity. Scope-aware checks (currently
- // volunteer_channels) filter on these ids; unscoped ctx = brain-wide.
- const scope = sourceScopeOpts(ctx);
- const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined);
- return doctorReportRemote(ctx.engine, { sourceIds });
- },
- scope: 'admin',
- localOnly: false,
-};
-
-const get_versions: Operation = {
- name: 'get_versions',
- description: 'Page version history',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },
- },
- handler: async (ctx, p) => {
- const versions = await ctx.engine.getVersions(p.slug as string, sourceScopeOpts(ctx));
- // 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) }));
- },
- scope: 'read',
- cliHints: { name: 'history', positional: ['slug'] },
-};
-
-const revert_version: Operation = {
- name: 'revert_version',
- description: 'Revert page to a previous version',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page to revert.' },
- version_id: { type: 'number', required: true, description: 'Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field.' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- enforceClientSlugFence(ctx, p.slug as string, 'revert_version');
- if (ctx.dryRun) return { dry_run: true, action: 'revert_version', slug: p.slug, version_id: p.version_id };
- // v0.31.8 (D7): thread ctx.sourceId so multi-source brains revert the
- // intended page row instead of whichever same-slug row Postgres returns
- // first.
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- await ctx.engine.createVersion(p.slug as string, sourceOpts);
- await ctx.engine.revertToVersion(p.slug as string, p.version_id as number, sourceOpts);
- return { status: 'reverted' };
- },
- cliHints: { name: 'revert', positional: ['slug', 'version_id'] },
-};
-
-// --- Sync ---
-
-const sync_brain: Operation = {
- name: 'sync_brain',
- description: 'Sync git repo to brain (incremental)',
- params: {
- repo: { type: 'string', description: 'Path to git repo (optional if configured)' },
- dry_run: { type: 'boolean', description: 'Preview changes without applying' },
- full: { type: 'boolean', description: 'Full re-sync (ignore checkpoint)' },
- no_pull: { type: 'boolean', description: 'Skip git pull' },
- no_embed: { type: 'boolean', description: 'Skip embedding generation' },
- },
- mutating: true,
- scope: 'admin',
- localOnly: true,
- handler: async (ctx, p) => {
- const { performSync } = await import('../commands/sync.ts');
- // #2830: thread ctx.sourceId (D7 pattern, same as revert_version /
- // put_page) so a no-`repo` call resolves the CALLER's sync anchor.
- // Without it, performSync read the default source's repo_path/last_commit
- // and silently synced against the wrong repo on multi-source brains.
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- return performSync(ctx.engine, {
- repoPath: p.repo as string | undefined,
- dryRun: ctx.dryRun || (p.dry_run as boolean) || false,
- noEmbed: (p.no_embed as boolean) || false,
- noPull: (p.no_pull as boolean) || false,
- full: (p.full as boolean) || false,
- ...sourceOpts,
- });
- },
- cliHints: { name: 'sync', hidden: true },
-};
-
-// --- Raw Data ---
-
-const put_raw_data: Operation = {
- name: 'put_raw_data',
- description: 'Store raw API response data for a page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page to attach the raw data to.' },
- source: { type: 'string', required: true, description: 'Data source (e.g., crustdata, happenstance)' },
- data: { type: 'object', required: true, description: 'Raw data object' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- enforceClientSlugFence(ctx, p.slug as string, 'put_raw_data');
- if (ctx.dryRun) return { dry_run: true, action: 'put_raw_data', slug: p.slug, source: p.source };
- // v0.31.8 (D7 + D21): thread ctx.sourceId.
- const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
- await ctx.engine.putRawData(p.slug as string, p.source as string, p.data as object, sourceOpts);
- return { status: 'ok' };
- },
-};
-
-const get_raw_data: Operation = {
- name: 'get_raw_data',
- description: 'Retrieve raw data for a page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose raw data to fetch.' },
- source: { type: 'string', description: 'Filter by source' },
- },
- handler: async (ctx, p) => {
- return ctx.engine.getRawData(p.slug as string, p.source as string | undefined, sourceScopeOpts(ctx));
- },
- scope: 'read',
-};
-
-// --- Resolution & Chunks ---
-
-const resolve_slugs: Operation = {
- name: 'resolve_slugs',
- description: 'Fuzzy-resolve a partial slug to matching page slugs',
- params: {
- partial: { type: 'string', required: true, description: "Partial slug or title text to match, e.g. 'alice-ex' or 'meeting notes'. This is the search text param — there is no `text` param." },
- },
- handler: async (ctx, p) => {
- // #3242: was fully UNSCOPED — the one read that leaked every source's
- // slugs to any caller (the reporter's "resolve_slugs sees them but
- // get_page doesn't" matrix). Route through the same visibility set as
- // get_page/search: grant > federated set > scalar source.
- return ctx.engine.resolveSlugs(p.partial as string, federatedSearchScope(ctx));
- },
- scope: 'read',
-};
-
-const get_chunks: Operation = {
- name: 'get_chunks',
- description: 'Get content chunks for a page',
- params: {
- slug: { type: 'string', required: true, description: 'Slug of the page whose content chunks to return.' },
- },
- handler: async (ctx, p) => {
- // #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.
- return ctx.engine.getChunks(p.slug as string, sourceScopeOpts(ctx));
- },
- scope: 'read',
-};
-
-// --- Ingest Log ---
-
-const log_ingest: Operation = {
- name: 'log_ingest',
- description: 'Log an ingestion event',
- params: {
- source_type: { type: 'string', required: true, description: "Kind of ingest source, e.g. 'email', 'meeting', 'rss', 'api'." },
- source_ref: { type: 'string', required: true, description: 'Identifier of the ingested item — a URL, message id, or file path.' },
- pages_updated: { type: 'array', required: true, items: { type: 'string' }, description: 'Slugs of the pages this ingest created or updated.' },
- summary: { type: 'string', required: true, description: 'One-line human-readable summary of what was ingested.' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'log_ingest' };
- await ctx.engine.logIngest({
- // Thread ctx.sourceId (same pattern as get_chunks/get_page above): on a
- // multi-source brain the ingest event must be attributed to the caller's
- // source, not the shared 'default' bucket. Absent sourceId still falls to
- // the engine's 'default' (single-source brains unchanged).
- ...(ctx.sourceId ? { source_id: ctx.sourceId } : {}),
- source_type: p.source_type as string,
- source_ref: p.source_ref as string,
- pages_updated: p.pages_updated as string[],
- summary: p.summary as string,
- });
- return { status: 'ok' };
- },
-};
-
-const get_ingest_log: Operation = {
- name: 'get_ingest_log',
- description: 'Get recent ingestion log entries',
- params: {
- limit: { type: 'number', description: 'Max entries (default 20)' },
- },
- handler: async (ctx, p) => {
- // Source-scope the log for remote callers (scalar grant → single-element
- // array; federated grant → the granted array — linkReadScopeOpts collapse
- // rule). Trusted local callers (remote === false) keep the whole-brain
- // view, matching every other read op's local posture. Ingest summaries
- // can carry another source's private context, so an unscoped remote read
- // is a cross-source leak.
- const scope = ctx.remote !== false ? linkReadScopeOpts(ctx) : {};
- return ctx.engine.getIngestLog({
- limit: clampSearchLimit(p.limit as number | undefined, 20, 50),
- ...(scope.sourceIds ? { sourceIds: scope.sourceIds } : scope.sourceId ? { sourceIds: [scope.sourceId] } : {}),
- });
- },
- scope: 'read',
-};
-
-// --- File Operations ---
-
-// Both branches need a LIMIT. Without one, the slug-filtered branch materializes
-// every file for that slug — an MCP caller can force unbounded memory consumption
-// by targeting a page with many attachments.
-const FILE_LIST_LIMIT = 100;
-
-const file_list: Operation = {
- name: 'file_list',
- description: 'List stored files',
- params: {
- slug: { type: 'string', description: 'Filter by page slug' },
- },
- scope: 'admin',
- localOnly: true,
- handler: async (ctx, p) => {
- const { sqlQueryForEngine } = await import('./sql-query.ts');
- const sql = sqlQueryForEngine(ctx.engine);
- const slug = p.slug as string | undefined;
- const rows = slug
- ? await sql`SELECT id, page_slug, filename, storage_path, mime_type, size_bytes, content_hash, created_at FROM files WHERE page_slug = ${slug} ORDER BY filename LIMIT ${FILE_LIST_LIMIT}`
- : await sql`SELECT id, page_slug, filename, storage_path, mime_type, size_bytes, content_hash, created_at FROM files ORDER BY page_slug, filename LIMIT ${FILE_LIST_LIMIT}`;
- // Postgres returns size_bytes (BIGINT) as native BigInt — JSON.stringify
- // throws on those, breaking MCP callers. PGLite returns Number already.
- // 9 PB ceiling (2^53 bytes) is far above any plausible file size.
- return rows.map((r: Record<string, unknown>) => ({
- ...r,
- size_bytes: r.size_bytes == null ? null : Number(r.size_bytes),
- }));
- },
-};
-
-const file_upload: Operation = {
- name: 'file_upload',
- description: 'Upload a file to storage',
- params: {
- path: { type: 'string', required: true, description: 'Local file path' },
- page_slug: { type: 'string', description: 'Associate with page' },
- },
- mutating: true,
- scope: 'admin',
- localOnly: true,
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'file_upload', path: p.path };
-
- const { readFileSync, statSync } = await import('fs');
- const { basename, extname } = await import('path');
- const { createHash } = await import('crypto');
-
- const filePath = p.path as string;
- const pageSlug = (p.page_slug as string) || null;
-
- // Fix 1 / B5 / H5 / M4: validate path, slug, filename before any filesystem read.
- // Remote callers (MCP, agent) are confined to cwd (strict). Local CLI callers
- // can upload from anywhere on the filesystem (loose) — the user owns the machine.
- // Default is strict when ctx.remote is undefined (defense-in-depth).
- const strict = ctx.remote !== false;
- validateUploadPath(filePath, process.cwd(), strict);
- if (pageSlug) validatePageSlug(pageSlug);
- const filename = basename(filePath);
- validateFilename(filename);
-
- const stat = statSync(filePath);
- const content = readFileSync(filePath);
- const hash = createHash('sha256').update(content).digest('hex');
- const storagePath = pageSlug ? `${pageSlug}/${filename}` : `unsorted/${hash.slice(0, 8)}-${filename}`;
-
- const MIME_TYPES: Record<string, string> = {
- '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
- '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
- '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.mp3': 'audio/mpeg',
- };
- const mimeType = MIME_TYPES[extname(filePath).toLowerCase()] || null;
-
- const { sqlQueryForEngine } = await import('./sql-query.ts');
- const sql = sqlQueryForEngine(ctx.engine);
- const existing = await sql`SELECT id FROM files WHERE content_hash = ${hash} AND storage_path = ${storagePath}`;
- if (existing.length > 0) {
- return { status: 'already_exists', storage_path: storagePath };
- }
-
- // Upload to storage backend if configured
- if (ctx.config.storage) {
- const { createStorage } = await import('./storage.ts');
- const storage = await createStorage(ctx.config.storage as any);
- try {
- await storage.upload(storagePath, content, mimeType || undefined);
- } catch (uploadErr) {
- throw new OperationError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`);
- }
- }
-
- try {
- await sql`
- INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
- VALUES (${pageSlug}, ${filename}, ${storagePath}, ${mimeType}, ${stat.size}, ${hash}, ${'{}'}::jsonb)
- ON CONFLICT (storage_path) DO UPDATE SET
- content_hash = EXCLUDED.content_hash,
- size_bytes = EXCLUDED.size_bytes,
- mime_type = EXCLUDED.mime_type
- `;
- } catch (dbErr) {
- // Rollback: clean up storage if DB write failed
- if (ctx.config.storage) {
- try {
- const { createStorage } = await import('./storage.ts');
- const storage = await createStorage(ctx.config.storage as any);
- await storage.delete(storagePath);
- } catch { /* best effort cleanup */ }
- }
- throw dbErr;
- }
-
- return { status: 'uploaded', storage_path: storagePath, size_bytes: stat.size };
- },
-};
-
-const file_url: Operation = {
- name: 'file_url',
- description: 'Get a URL for a stored file',
- params: {
- storage_path: { type: 'string', required: true },
- },
- scope: 'admin',
- localOnly: true,
- handler: async (ctx, p) => {
- const { sqlQueryForEngine } = await import('./sql-query.ts');
- const sql = sqlQueryForEngine(ctx.engine);
- const rows = await sql`SELECT storage_path, mime_type, size_bytes FROM files WHERE storage_path = ${p.storage_path as string}`;
- if (rows.length === 0) {
- throw new OperationError('storage_error', `File not found: ${p.storage_path}`);
- }
- // TODO: generate signed URL from Supabase Storage
- return { storage_path: rows[0].storage_path, url: `gbrain:files/${rows[0].storage_path}` };
- },
-};
-
-// --- Jobs (Minions) ---
-
-const submit_job: Operation = {
- name: 'submit_job',
- description: 'Submit a background job to the Minions queue. Built-in types are registered by registerBuiltinHandlers (src/commands/jobs.ts) — e.g. sync, embed, lint, import, extract, backlinks, autopilot-cycle, subagent, and more; submitting an unknown name with --follow prints the full list. The `shell` type is CLI-only and rejected over MCP.',
- params: {
- name: { type: 'string', required: true, description: 'Job type (e.g. sync, embed, lint, import, extract, backlinks, autopilot-cycle; shell is CLI-only). Full registry: registerBuiltinHandlers in src/commands/jobs.ts.' },
- data: { type: 'object', description: 'Job payload (JSON)' },
- queue: { type: 'string', description: 'Queue name (default: "default")' },
- priority: { type: 'number', description: 'Priority (0 = highest, default: 0)' },
- max_attempts: { type: 'number', description: 'Max retry attempts (default: 3)' },
- delay: { type: 'number', description: 'Delay in ms before eligible' },
- timeout_ms: { type: 'number', description: 'Per-job wall-clock timeout in ms; aborted job goes to dead' },
- lock_duration_ms: { type: 'number', description: 'Per-job lock lease in ms (#4145). Out-of-range values are clamped to [5000, 3600000] — remote writers cannot pin an immortal lock. Omit to use the handler-type default (300s for long LLM handlers) or the worker default (30s).' },
- },
- mutating: true,
- scope: 'admin',
- handler: async (ctx, p) => {
- const name = typeof p.name === 'string' ? p.name.trim() : '';
- if (ctx.dryRun) return { dry_run: true, action: 'submit_job', name };
-
- // Submit-side MCP guard: reject protected job names from untrusted callers
- // BEFORE we touch the DB. This is the first of the two security layers
- // (the second is MinionQueue.add's check). Independent of the worker-side
- // GBRAIN_ALLOW_SHELL_JOBS env flag — even if that flag is on, MCP callers
- // cannot submit protected-type jobs.
- const { isProtectedJobName } = await import('./minions/protected-names.ts');
- // F7b fail-closed: anything that is not strictly false (i.e., remote=true OR
- // the field somehow leaks in undefined despite the required type) rejects
- // protected job submissions. Closes the HTTP MCP shell-job RCE that surfaced
- // when the HTTP transport's OperationContext literal forgot to set remote.
- if (ctx.remote !== false && isProtectedJobName(name)) {
- throw new OperationError('permission_denied', `'${name}' jobs cannot be submitted over MCP (CLI-only for security)`);
- }
-
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- // Trusted flag fires ONLY for an explicit local CLI submission of a protected
- // name. Strict `=== false` so an untyped/cast context can't escalate.
- const trusted = ctx.remote === false && isProtectedJobName(name) ? { allowProtectedSubmit: true } : undefined;
-
- const jobData = (p.data as Record<string, unknown>) || {};
-
- // v0.35.8.0: pre-enqueue shell-job validation, parity with the CLI submit
- // path. Closes the bug class where shell.ts handler-time validation ran
- // AFTER queue.add() persisted the row (codex F-CDX-1). Note: this branch
- // only fires for trusted local submitters (`ctx.remote === false` AND
- // protected-name allowlist), so remote MCP callers never reach it — but
- // it stays here as defense-in-depth in case a future code path widens
- // the trust gate above.
- if (name === 'shell' && trusted) {
- const { validateShellJobParams } = await import('./minions/handlers/shell-validate.ts');
- validateShellJobParams(jobData);
- }
-
- const job = await queue.add(name, jobData, {
- queue: (p.queue as string) || 'default',
- priority: (p.priority as number) || 0,
- max_attempts: (p.max_attempts as number) || 3,
- delay: (p.delay as number) || undefined,
- timeout_ms: (p.timeout_ms as number) || undefined,
- // #4145 [CEO-F7/R2-6]: range enforcement lives in queue.add's
- // clampLockDurationMs (ParamDef has no min/max support; wrong TYPE is
- // rejected by the shared number validation upstream of this handler).
- lock_duration_ms: (p.lock_duration_ms as number) || undefined,
- }, trusted);
-
- // v0.35.8.0: submit_job audit-log parity with the CLI path (codex F-CDX-4).
- // Pre-v0.35.8.0 the op handler bypassed the shell-audit JSONL writer
- // entirely. Lift the call here so both submit surfaces produce one
- // operational-trace line per shell submission. Best-effort; audit
- // failures never block submission.
- if (name === 'shell' && trusted) {
- try {
- const { logShellSubmission } = await import('./minions/handlers/shell-audit.ts');
- const inheritNames = Array.isArray(jobData.inherit)
- ? (jobData.inherit as unknown[]).filter((s): s is string => typeof s === 'string')
- : undefined;
- logShellSubmission({
- caller: 'mcp',
- // Gated on `trusted` (which requires ctx.remote === false), so
- // we know this path is a local trusted submitter — log it that way.
- remote: false,
- job_id: job.id,
- cwd: typeof jobData.cwd === 'string' ? jobData.cwd : '',
- cmd_display: typeof jobData.cmd === 'string' ? (jobData.cmd as string).slice(0, 80) : undefined,
- argv_display: Array.isArray(jobData.argv)
- ? (jobData.argv as unknown[]).filter((a): a is string => typeof a === 'string').map((a) => a.slice(0, 80))
- : undefined,
- inherit: inheritNames && inheritNames.length > 0 ? inheritNames : undefined,
- });
- } catch { /* audit failures never block submission */ }
- }
-
- // Amendments 24/25: post-enqueue queue-state probe (time-bounded,
- // fail-open). The job is already persisted; a probe failure degrades to
- // {probe_failed: true}, never an error on a successful submission.
- return { ...job, queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };
- },
-};
-
-/**
- * Wrapper around `probeQueueState` that also swallows module-load failures,
- * so BOTH submit surfaces (submit_job, submit_agent) satisfy amendment 24's
- * "probe failure NEVER errors a successful submission" — even when the
- * supervisor module itself cannot load.
- */
-async function probeQueueStateSafe(
- ctx: OperationContext,
- queue: string,
- handlerNames: string[],
-): Promise<Record<string, unknown>> {
- try {
- const { probeQueueState } = await import('./minions/supervisor.ts');
- return (await probeQueueState(ctx.engine, queue, handlerNames)) as unknown as Record<string, unknown>;
- } catch {
- return { probe_failed: true };
- }
-}
-
-// v0.38 Slice 3 — D13 — remote-callable submit_agent with registration-time
-// binding enforcement. Distinct from `submit_job` because:
-// 1. It's the FIRST op that lets remote MCP callers spawn paid LLM work
-// (cost concerns + audit trail differ from generic submit_job).
-// 2. The trust boundary lives in oauth_clients.bound_* fields, not in the
-// protected-name guard. Bindings are enforced PER-OP, not per-name.
-// 3. The dispatcher is the subagent handler with the gateway-native loop
-// (agent.use_gateway_loop is auto-on for submit_agent jobs).
-const submit_agent: Operation = {
- name: 'submit_agent',
- description: 'Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. Requires the `agent` OAuth scope. Tools, source, slug prefixes, max concurrency, and daily budget are bound at OAuth client registration time.',
- params: {
- prompt: { type: 'string', required: true, description: 'User prompt for the agent' },
- model: { type: 'string', description: 'provider:model string (defaults to models.tier.subagent)' },
- allowed_tools: { type: 'array', description: 'Subset of bound_tools the agent may invoke', items: { type: 'string' } },
- allowed_slug_prefixes: { type: 'array', description: 'Subset of bound_slug_prefixes for put_page writes', items: { type: 'string' } },
- max_turns: { type: 'number', description: 'Max LLM turns (default 20, hard cap 100)' },
- queue: { type: 'string', description: 'Queue name (default "default")' },
- },
- mutating: true,
- scope: 'agent',
- handler: async (ctx, p) => {
- // Remote-callable but only when the OAuth client has scope=agent AND
- // a binding row. Local CLI callers (ctx.remote === false) skip the
- // binding check — `gbrain agent run` already runs through subagent.ts
- // directly without going through this op.
- if (ctx.remote === false) {
- throw new OperationError('invalid_request', 'submit_agent over the local CLI: use `gbrain agent run` instead.');
- }
-
- const clientId = (ctx as { auth?: { clientId?: string } }).auth?.clientId;
- if (!clientId || typeof clientId !== 'string') {
- throw new OperationError('permission_denied', 'submit_agent requires an OAuth client with the `agent` scope.');
- }
-
- // Load the binding row.
- const { sqlQueryForEngine } = await import('./sql-query.ts');
- const sql = sqlQueryForEngine(ctx.engine);
- let bindingRows: Array<Record<string, unknown>>;
- try {
- bindingRows = await sql`
- SELECT bound_tools, bound_source_id, bound_brain_id, bound_slug_prefixes,
- bound_max_concurrent, budget_usd_per_day::text AS budget_cap
- FROM oauth_clients
- WHERE client_id = ${clientId}
- `;
- } catch (err) {
- throw new OperationError(
- 'internal',
- `submit_agent: could not load OAuth client binding: ${err instanceof Error ? err.message : String(err)}`,
- );
- }
- if (bindingRows.length === 0) {
- throw new OperationError('permission_denied', `submit_agent: client_id ${clientId} not found.`);
- }
- const binding = bindingRows[0];
- const boundTools = (binding.bound_tools as string[] | null) ?? null;
- const boundSource = (binding.bound_source_id as string | null) ?? null;
- const boundSlugPrefixes = (binding.bound_slug_prefixes as string[] | null) ?? null;
- const boundMaxConcurrent = Number(binding.bound_max_concurrent ?? 1);
- const budgetCapText = (binding.budget_cap as string | null) ?? null;
-
- if (boundTools === null) {
- throw new OperationError(
- 'permission_denied',
- `submit_agent: client ${clientId} has the agent scope but no bindings. Re-register with --bound-tools, --bound-source, --bound-slug-prefixes, --bound-max-concurrent, --budget-usd-per-day.`,
- );
- }
-
- // Validate each param against the binding.
- //
- // An EXPLICIT empty array is not "no restriction" here — downstream the
- // subagent worker reads empty `allowed_tools` as "the full tool registry"
- // and empty `allowed_slug_prefixes` as "fall back to the legacy
- // wiki/agents/<job-id>/ namespace". Both subset loops below pass
- // vacuously over an empty list, so `{allowed_tools: [], allowed_slug_prefixes: []}`
- // from a client bound to `['search']` + `['emp-alice/']` would hand its
- // subagent the whole registry (including put_page) writing outside the
- // binding. `??` only substitutes null/undefined, so collapse the empty
- // case to the binding explicitly.
- const requestedToolsRaw = p.allowed_tools as string[] | undefined;
- const requestedTools = requestedToolsRaw === undefined || requestedToolsRaw.length === 0
- ? boundTools
- : requestedToolsRaw;
- for (const t of requestedTools) {
- if (!boundTools.includes(t)) {
- throw new OperationError(
- 'permission_denied',
- `submit_agent: tool "${t}" is not in client ${clientId}'s bound_tools (${boundTools.join(', ')}).`,
- );
- }
- }
- const requestedSlugPrefixesRaw = p.allowed_slug_prefixes as string[] | undefined;
- const requestedSlugPrefixes =
- requestedSlugPrefixesRaw === undefined || requestedSlugPrefixesRaw.length === 0
- ? (boundSlugPrefixes ?? [])
- : requestedSlugPrefixesRaw;
- // A bound client must end up with a non-empty delegated fence: an empty
- // list reaches the subagent as "use the legacy wiki/agents/<id>/ namespace",
- // which is outside every bound prefix.
- if (boundSlugPrefixes !== null && requestedSlugPrefixes.length === 0) {
- throw new OperationError(
- 'permission_denied',
- `submit_agent: client ${clientId} is slug-bound but its binding resolved to an empty prefix list, which the subagent would read as the unfenced legacy namespace.`,
- 'Re-scope the client with a non-empty --bound-slug-prefixes.',
- );
- }
- if (boundSlugPrefixes !== null) {
- for (const sp of requestedSlugPrefixes) {
- // Boundary-aware, same rule as the direct fence: a raw `startsWith`
- // let a boundary-less binding (`emp-alice`) authorize a requested
- // prefix in a SIBLING namespace (`emp-alice-2/`), which is then handed
- // to the child as a full glob grant over another employee's pages.
- if (!boundSlugPrefixes.some(bp => {
- const base = normalizeSlugPrefix(bp);
- const req = normalizeSlugPrefix(sp);
- if (base === '') return false;
- return base.endsWith('/')
- ? req.startsWith(base)
- : req === base || req.startsWith(`${base}/`);
- })) {
- throw new OperationError(
- 'permission_denied',
- `submit_agent: slug_prefix "${sp}" is not under any of client ${clientId}'s bound_slug_prefixes.`,
- );
- }
- }
- }
-
- // Concurrency cap: count active+waiting agent jobs for this client.
- const inflight = await sql`
- SELECT COUNT(*)::int AS n
- FROM minion_jobs j
- WHERE j.name = 'subagent'
- AND j.status IN ('waiting', 'active', 'waiting-children')
- AND j.data->>'__owner_client_id' = ${clientId}
- `;
- const inflightCount = Number((inflight[0]?.n as number | string | undefined) ?? 0);
- if (inflightCount >= boundMaxConcurrent) {
- throw new OperationError(
- 'rate_limited',
- `submit_agent: client ${clientId} at concurrency cap (${inflightCount}/${boundMaxConcurrent}).`,
- );
- }
-
- // Dry-run echo.
- // The subagent fence uses `matchesSlugAllowList`, whose grammar makes a
- // BARE entry match that one slug exactly — so a plain `emp-alice/` binding
- // would let the delegated agent write nothing. Normalize the
- // trailing-slash form into the glob the delegated matcher expects, so one
- // stored column means the same span of slugs on both paths.
- const delegatedSlugPrefixes = requestedSlugPrefixes.map(sp =>
- sp.endsWith('/') ? `${sp}*` : sp);
-
- if (ctx.dryRun) {
- return {
- dry_run: true,
- action: 'submit_agent',
- client_id: clientId,
- bound_tools: boundTools,
- bound_source: boundSource,
- bound_max_concurrent: boundMaxConcurrent,
- // What the delegated job would ACTUALLY be granted, after the binding
- // is applied — a preview that hides this can't show a widening bug.
- resolved_tools: requestedTools,
- resolved_slug_prefixes: delegatedSlugPrefixes,
- };
- }
-
- // Submit via MinionQueue with allowProtectedSubmit (the agent op is
- // remote-callable but the underlying job name 'subagent' is protected;
- // the OAuth scope check above stands in for the protected-name guard).
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
-
- const jobData: Record<string, unknown> = {
- prompt: p.prompt as string,
- max_turns: Math.min((p.max_turns as number) ?? 20, 100),
- allowed_tools: requestedTools,
- allowed_slug_prefixes: delegatedSlugPrefixes,
- __owner_client_id: clientId,
- };
- if (typeof p.model === 'string') jobData.model = p.model;
- // Write source for the delegated job comes from the AUTHENTICATED client
- // whenever we have it. `bound_source_id` is an optional, separately-set
- // column: unset it defaulted the child to 'default', and if it disagreed
- // with the token's own source the child followed the column — either way
- // a correctly slug-fenced client could act on the wrong source.
- const delegatedSource = ctx.auth?.sourceId ?? boundSource;
- if (boundSource && ctx.auth?.sourceId && boundSource !== ctx.auth.sourceId) {
- throw new OperationError(
- 'permission_denied',
- `submit_agent: client ${clientId}'s bound_source_id (${boundSource}) disagrees with its authenticated source (${ctx.auth.sourceId}); refusing to guess which one governs the delegated write.`,
- 'Re-scope the client so the two agree: `gbrain auth rescope-client <id> --source <source>`.',
- );
- }
- if (delegatedSource) jobData.source_id = delegatedSource;
- const job = await queue.add(
- 'subagent',
- jobData,
- { queue: (p.queue as string) || 'default' },
- { allowProtectedSubmit: true },
- );
-
- // Audit trail (D4) — best-effort JSONL.
- try {
- const { logAgentSubmission } = await import('./minions/agent-audit.ts');
- const budgetCapCents = budgetCapText ? Math.round(parseFloat(budgetCapText) * 100) : null;
- const promptText = typeof p.prompt === 'string' ? p.prompt : '';
- logAgentSubmission({
- client_id: clientId,
- job_id: job.id,
- model: typeof p.model === 'string' ? p.model : '<default>',
- bound_tools: requestedTools,
- bound_source: boundSource,
- slug_prefixes: requestedSlugPrefixes,
- max_concurrent: boundMaxConcurrent,
- budget_remaining_cents: budgetCapCents,
- prompt_byte_count: Buffer.byteLength(promptText, 'utf8'),
- outcome: 'submitted',
- });
- } catch { /* never block submission */ }
-
- // Amendments 24/25: the returned job id means nothing if the lane is
- // dead — attach a time-bounded, fail-open queue-state probe.
- return {
- id: job.id,
- name: 'subagent',
- client_id: clientId,
- queue_state: await probeQueueStateSafe(ctx, job.queue, ['subagent']),
- };
- },
-};
-
-/**
- * Minions-visibility wave — ownership-fenced agent-job status (amendment 27).
- *
- * The companion read for `submit_agent`: an agent-scoped client can poll ONLY
- * its own delegated jobs. Deliberate posture:
- * - `ctx.auth.clientId` is REQUIRED on EVERY transport — stdio and legacy
- * bearer callers carry no client identity and are refused
- * (permission_denied) rather than silently unfenced. This is stricter
- * than scope enforcement alone (which local/stdio callers bypass).
- * - The ownership filter is a fail-closed SQL WHERE on
- * `data->>'__owner_client_id'` (the JSONB predicate submit_agent already
- * uses for its concurrency cap — identical semantics on both engines),
- * never a post-fetch JS check.
- * - Foreign and missing ids return one uniform `not_found` envelope so the
- * op is not a job-id enumeration oracle (ENG-13; the ErrorCode comment
- * was widened accordingly). Shell/admin jobs stay on admin-scope
- * `get_job` — this op reads the agent lane (`name = 'subagent'`) only.
- * - `queue_position` = count of waiting jobs ahead in claim order
- * (priority ASC, created_at ASC — the exact ORDER BY of
- * `MinionQueue.claim`), computed only while status = 'waiting'.
- */
-const get_agent_job: Operation = {
- name: 'get_agent_job',
- description: 'Poll an agent job submitted via submit_agent. Returns a trimmed status view (id, status, timestamps, error_text, result) plus queue_position (waiting jobs ahead in claim order; 0 = next) while the job is still waiting. Requires the `agent` OAuth scope; only jobs owned by the calling client are visible.',
- params: {
- id: { type: 'number', required: true, description: 'Job id returned by submit_agent' },
- },
- scope: 'agent',
- handler: async (ctx, p) => {
- const clientId = ctx.auth?.clientId;
- if (!clientId || typeof clientId !== 'string') {
- throw new OperationError(
- 'permission_denied',
- 'get_agent_job requires an authenticated OAuth client identity.',
- 'Call over HTTP MCP with an `agent`-scoped token. Transports without a per-client identity (stdio, legacy bearer) cannot read agent jobs; use admin-scope get_job from a trusted context instead.',
- );
- }
- const id = p.id;
- if (typeof id !== 'number' || !Number.isInteger(id)) {
- throw new OperationError('invalid_params', 'id must be an integer job id');
- }
-
- // One round-trip: the ownership fence rides the WHERE, and the
- // queue_position subselect mirrors MinionQueue.claim's candidate set
- // (same queue, status='waiting') and ORDER BY (priority, created_at),
- // with the row id as the deterministic tie-break. Perf: the outer lookup
- // is a primary-key read; the subselect's (queue, status) filter is
- // covered by the wave's wedge-index prefix once that migration (another
- // lane) lands, and stays a small scan until then.
- const rows = await ctx.engine.executeRaw<{
- id: number;
- status: string;
- created_at: string | Date | null;
- started_at: string | Date | null;
- finished_at: string | Date | null;
- error_text: string | null;
- result: unknown;
- queue_position: number | string | null;
- }>(
- `SELECT j.id, j.status, j.created_at, j.started_at, j.finished_at, j.error_text, j.result,
- CASE WHEN j.status = 'waiting' THEN (
- SELECT count(*)::int FROM minion_jobs q
- WHERE q.queue = j.queue AND q.status = 'waiting'
- AND (q.priority < j.priority
- OR (q.priority = j.priority AND q.created_at < j.created_at)
- OR (q.priority = j.priority AND q.created_at = j.created_at AND q.id < j.id))
- ) ELSE NULL END AS queue_position
- FROM minion_jobs j
- WHERE j.id = $1
- AND j.name = 'subagent'
- AND j.data->>'__owner_client_id' = $2`,
- [id, clientId],
- );
- if (rows.length === 0) {
- // Uniform envelope: foreign-owned and nonexistent ids are
- // indistinguishable by design (anti-enumeration).
- throw new OperationError('not_found', `Job not found: ${id}`);
- }
- const row = rows[0];
- const iso = (v: string | Date | null): string | null =>
- v ? (v instanceof Date ? v.toISOString() : new Date(v).toISOString()) : null;
- // PGLite may hand jsonb back as text; postgres.js parses it.
- let result: unknown = row.result ?? null;
- if (typeof result === 'string') {
- try { result = JSON.parse(result); } catch { /* keep raw text */ }
- }
- return {
- id: row.id,
- status: row.status,
- created_at: iso(row.created_at),
- started_at: iso(row.started_at),
- finished_at: iso(row.finished_at),
- // Cap: error_text is an unbounded worker-written field (stack traces,
- // provider dumps); a remote polling view shouldn't ship megabytes.
- error_text: row.error_text ? row.error_text.slice(0, 2000) : null,
- result,
- ...(row.status === 'waiting' && row.queue_position !== null
- ? { queue_position: Number(row.queue_position) }
- : {}),
- };
- },
-};
-
-const get_job: Operation = {
- name: 'get_job',
- description: 'Get job status and details by ID',
- params: {
- id: { type: 'number', required: true, description: 'Job ID' },
- },
- scope: 'admin',
- handler: async (ctx, p) => {
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const job = await queue.getJob(p.id as number);
- if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);
- return job;
- },
-};
-
-const list_jobs: Operation = {
- name: 'list_jobs',
- description: 'List jobs with optional filters',
- params: {
- status: { type: 'string', description: 'Filter by status (waiting, active, completed, failed, delayed, dead, cancelled)' },
- queue: { type: 'string', description: 'Filter by queue name' },
- name: { type: 'string', description: 'Filter by job type' },
- limit: { type: 'number', description: 'Max results (default: 50)' },
- },
- scope: 'admin',
- handler: async (ctx, p) => {
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- return queue.getJobs({
- status: p.status as string | undefined,
- queue: p.queue as string | undefined,
- name: p.name as string | undefined,
- limit: (p.limit as number) || 50,
- } as Parameters<typeof queue.getJobs>[0]);
- },
-};
-
-const cancel_job: Operation = {
- name: 'cancel_job',
- description: 'Cancel a waiting, active, or delayed job',
- params: {
- id: { type: 'number', required: true, description: 'Job ID' },
- },
- mutating: true,
- scope: 'admin',
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'cancel_job', id: p.id };
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const cancelled = await queue.cancelJob(p.id as number);
- if (!cancelled) throw new OperationError('invalid_params', `Cannot cancel job ${p.id} (may already be in terminal status)`);
- return cancelled;
- },
-};
-
-const retry_job: Operation = {
- name: 'retry_job',
- description: 'Re-queue a failed or dead job for retry',
- params: {
- id: { type: 'number', required: true, description: 'Job ID' },
- },
- mutating: true,
- scope: 'admin',
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'retry_job', id: p.id };
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const retried = await queue.retryJob(p.id as number);
- if (!retried) throw new OperationError('invalid_params', `Cannot retry job ${p.id} (must be failed or dead)`);
- return retried;
- },
-};
-
-const get_job_progress: Operation = {
- name: 'get_job_progress',
- description: 'Get structured progress for a running job',
- params: {
- id: { type: 'number', required: true, description: 'Job ID' },
- },
- scope: 'admin',
- handler: async (ctx, p) => {
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const job = await queue.getJob(p.id as number);
- if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);
- return { id: job.id, name: job.name, status: job.status, progress: job.progress };
- },
-};
-
-const pause_job: Operation = {
- name: 'pause_job',
- description: 'Pause a waiting, active, or delayed job',
- params: {
- id: { type: 'number', required: true, description: 'Job ID' },
- },
- scope: 'admin',
- handler: async (ctx, p) => {
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const job = await queue.pauseJob(p.id as number);
- if (!job) throw new OperationError('invalid_params', `Job not found or not pausable: ${p.id}`);
- return { id: job.id, status: job.status };
- },
-};
-
-const resume_job: Operation = {
- name: 'resume_job',
- description: 'Resume a paused job back to waiting',
- params: {
- id: { type: 'number', required: true, description: 'Job ID' },
- },
- scope: 'admin',
- handler: async (ctx, p) => {
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const job = await queue.resumeJob(p.id as number);
- if (!job) throw new OperationError('invalid_params', `Job not found or not paused: ${p.id}`);
- return { id: job.id, status: job.status };
- },
-};
-
-const replay_job: Operation = {
- name: 'replay_job',
- description: 'Replay a completed/failed/dead job, optionally with modified data',
- params: {
- id: { type: 'number', required: true, description: 'Source job ID to replay' },
- data_overrides: { type: 'object', required: false, description: 'Data fields to override (merged with original)' },
- },
- scope: 'admin',
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'replay_job', id: p.id };
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const job = await queue.replayJob(p.id as number, p.data_overrides as Record<string, unknown> | undefined);
- if (!job) throw new OperationError('invalid_params', `Job not found or not in terminal state: ${p.id}`);
- return { id: job.id, name: job.name, status: job.status, source_id: p.id };
- },
-};
-
-const send_job_message: Operation = {
- name: 'send_job_message',
- description: 'Send a sidechannel message to a running job\'s inbox',
- params: {
- id: { type: 'number', required: true, description: 'Job ID to message' },
- payload: { type: 'object', required: true, description: 'Message payload (arbitrary JSON)' },
- sender: { type: 'string', required: false, description: 'Sender identity (default: admin)' },
- },
- scope: 'admin',
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'send_job_message', id: p.id };
- const { MinionQueue } = await import('./minions/queue.ts');
- const queue = new MinionQueue(ctx.engine);
- const msg = await queue.sendMessage(p.id as number, p.payload, (p.sender as string) ?? 'admin');
- if (!msg) throw new OperationError('invalid_params', `Job not found, not messageable, or sender unauthorized: ${p.id}`);
- return { sent: true, message_id: msg.id, job_id: p.id };
- },
-};
-
-// --- Orphans ---
-
-const find_orphans: Operation = {
- name: 'find_orphans',
- description: 'Find pages with no inbound wikilinks. Essential for content enrichment cycles.',
- params: {
- include_pseudo: {
- type: 'boolean',
- description: 'Include auto-generated and pseudo pages (default: false)',
- },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { findOrphans } = await import('../commands/orphans.ts');
- // v0.41.29.0 (Codex F8): scope by the caller's source (ctx.sourceId /
- // ctx.auth.allowedSources) via the canonical sourceScopeOpts ladder.
- // Pre-fix, find_orphans returned brain-wide orphans regardless of a
- // 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).
- return findOrphans(ctx.engine, {
- includePseudo: (p.include_pseudo as boolean) || false,
- ...sourceScopeOpts(ctx),
- });
- },
- cliHints: { name: 'orphans', hidden: true },
-};
-
-// --- v0.36.1.0 (T7): calibration profile read op ---
-
-const get_calibration_profile: Operation = {
- name: 'get_calibration_profile',
- description:
- 'Read the active calibration profile for a holder. Returns the latest row from calibration_profiles ' +
- '(per-source, per-holder) including Brier score, accuracy, pattern statements, and active bias tags. ' +
- 'Source-scoped via sourceScopeOpts — federated_read scopes see the union of allowed sources, ' +
- 'scalar source-bound clients see only their source. Returns null when no profile exists yet ' +
- '(cold-brain branch: builds after 5+ resolved takes + a calibration_profile phase run).',
- scope: 'read',
- params: {
- holder: {
- type: 'string',
- description:
- "Holder slug, e.g. 'self' or 'people/charlie-example'. Defaults to config emotional_weight.user_holder, else 'self', when omitted.",
- },
- },
- handler: async (ctx, p) => {
- const { getCalibrationProfileOp } = await import('../commands/calibration.ts');
- return getCalibrationProfileOp(ctx, {
- ...(typeof p.holder === 'string' ? { holder: p.holder } : {}),
- });
- },
-};
-
-// --- v0.29: Salience + Anomaly Detection ---
-
-const get_recent_salience: Operation = {
- name: 'get_recent_salience',
- description: GET_RECENT_SALIENCE_DESCRIPTION,
- scope: 'read',
- params: {
- days: { type: 'number', description: 'Window in days. Default 14.' },
- limit: { type: 'number', description: 'Max results (default 20, capped at 100).' },
- slugPrefix: {
- type: 'string',
- description: "Optional slug-prefix filter, e.g. 'personal' or 'wiki/people'.",
- },
- recency_bias: {
- type: 'string',
- enum: ['flat', 'on'],
- description:
- "v0.29.1: how to weight recency in the salience score.\n" +
- " 'flat' (DEFAULT) — v0.29.0 behavior. Every page gets 1/(1+days_old).\n" +
- " Stable, predictable; what most callers want.\n" +
- " 'on' — Per-prefix decay map. concepts/originals/writing/\n" +
- " become evergreen (recency component = 0); daily/,\n" +
- " media/x/, chat/ decay aggressively. Use when the\n" +
- " user explicitly biases for recency-aware salience\n" +
- " ('what's been salient lately' vs 'what matters\n" +
- " in this brain regardless of when').",
- },
- },
- handler: async (ctx, p) => {
- const recencyBias = p.recency_bias === 'on' ? 'on' : 'flat';
- return ctx.engine.getRecentSalience({
- days: typeof p.days === 'number' ? p.days : undefined,
- limit: typeof p.limit === 'number' ? p.limit : undefined,
- slugPrefix: typeof p.slugPrefix === 'string' ? p.slugPrefix : undefined,
- recency_bias: recencyBias,
- });
- },
- cliHints: { name: 'salience' },
-};
-
-// --- v0.43 (#2095): push-based context — the brain volunteers pages ---
-
-const volunteer_context: Operation = {
- name: 'volunteer_context',
- description:
- 'Push-based context: volunteer brain pages relevant to a rolling conversation window ' +
- 'WITHOUT being asked. Zero-LLM, confidence-gated (alias 0.9 / exact-title 0.8 / ' +
- 'slug-suffix 0.6, +0.05 for multi-turn or newest-turn mentions; default gate 0.7), ' +
- 'capped at 3 pages (max 5). Returns pointers with one-line rationales + synopses — ' +
- 'open the page (get_page) before relying on details. Pass stats: true for the ' +
- 'approximate volunteered-vs-used precision summary (the feedback loop).',
- scope: 'read',
- params: {
- window: {
- type: 'string',
- description:
- "Recent conversation turns, oldest → newest, as 'user:' / 'assistant:' prefixed " +
- 'lines (unprefixed text = one user turn). Required unless stats: true. ' +
- 'CLI: piped stdin fills this.',
- },
- prior_context: {
- type: 'string',
- description:
- 'Already-surfaced context (pointer blocks / opened page bodies). Pages whose slug ' +
- 'appears here are not re-volunteered.',
- },
- max_pages: { type: 'number', description: 'Max pages to volunteer (default 3, hard cap 5).' },
- min_confidence: {
- type: 'number',
- description:
- 'Confidence gate 0..1 (default 0.7 — slug-suffix matches need an explicit lower gate).',
- },
- session_id: { type: 'string', description: 'Optional caller session id, logged for attribution.' },
- turn: { type: 'number', description: 'Optional caller turn number, logged for attribution.' },
- stats: {
- type: 'boolean',
- description:
- 'Return the volunteered-vs-used precision summary instead of volunteering. ' +
- 'APPROXIMATE: "used" = pages.last_retrieved_at > volunteered_at.',
- },
- days: { type: 'number', description: 'Stats window in days (default 30; stats mode only).' },
- },
- handler: async (ctx, p) => {
- const { parseWindow, volunteerContext, volunteerUsageStats } = await import('./context/volunteer.ts');
- const scope = sourceScopeOpts(ctx);
- const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : ['default']);
-
- if (p.stats === true) {
- return volunteerUsageStats(ctx.engine, sourceIds, typeof p.days === 'number' ? p.days : undefined);
- }
-
- if (typeof p.window !== 'string' || !p.window.trim()) {
- throw new OperationError(
- 'invalid_params',
- 'window is required unless stats: true',
- 'Pass the recent turns as a string (CLI: pipe them on stdin), or use --stats.',
- );
- }
- const turns = parseWindow(p.window);
- const pages = await volunteerContext(ctx.engine, turns, {
- sourceIds,
- priorContext: typeof p.prior_context === 'string' ? p.prior_context : undefined,
- maxPages: typeof p.max_pages === 'number' ? p.max_pages : undefined,
- minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
- });
-
- // Feedback-loop logging: fire-and-forget batched INSERT through the
- // volunteer-events sink (drained at exit). Never fails the op.
- if (pages.length) {
- try {
- const { logVolunteerEventsFireAndForget, volunteerEventRowsFrom, SESSION_ID_MAX_LEN } = await import('./context/volunteer-events.ts');
- // Trust-boundary clamps (remote MCP callers): cap session_id length so
- // a read-scoped token can't bank unbounded TEXT per request, and only
- // log integer turns — a non-integer would throw inside the single
- // multi-row INSERT and silently drop the whole batch.
- const sessionId = typeof p.session_id === 'string' ? p.session_id.slice(0, SESSION_ID_MAX_LEN) : null;
- const turn =
- typeof p.turn === 'number' && Number.isInteger(p.turn) && Math.abs(p.turn) <= 2_147_483_647
- ? p.turn
- : null;
- logVolunteerEventsFireAndForget(
- ctx.engine,
- volunteerEventRowsFrom(pages, { channel: 'op', session_id: sessionId, turn }),
- );
- } catch {
- /* telemetry only */
- }
- }
- return { pages, count: pages.length, window_turns: turns.length };
- },
- cliHints: { name: 'volunteer-context', stdin: 'window' },
-};
-
-const find_anomalies: Operation = {
- name: 'find_anomalies',
- description: FIND_ANOMALIES_DESCRIPTION,
- scope: 'read',
- params: {
- since: {
- type: 'string',
- description: 'ISO date YYYY-MM-DD. Default = today (UTC).',
- },
- lookback_days: {
- type: 'number',
- description: 'Days of history for the baseline. Default 30.',
- },
- sigma: {
- type: 'number',
- description: 'Sigma threshold. Default 3.0.',
- },
- },
- handler: async (ctx, p) => {
- return ctx.engine.findAnomalies({
- 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,
- });
- },
- cliHints: { name: 'anomalies' },
-};
-
-// v0.33: expertise + relationship-proximity routing. CLI: gbrain whoknows.
-const find_experts: Operation = {
- name: 'find_experts',
- description: FIND_EXPERTS_DESCRIPTION,
- scope: 'read',
- params: {
- topic: {
- type: 'string',
- description: 'The topic to route. Free-form natural language.',
- },
- limit: {
- type: 'number',
- description: 'Max results (default 5).',
- },
- explain: {
- type: 'boolean',
- description: 'Include factor breakdown per result (expertise, recency, salience).',
- },
- },
- handler: async (ctx, p) => {
- const { findExperts } = await import('../commands/whoknows.ts');
- const topic = typeof p.topic === 'string' ? p.topic : '';
- if (!topic.trim()) {
- throw new OperationError('invalid_params', '`topic` is required and must be a non-empty string.');
- }
- // v0.34.1 (#861, D3 — 5th leak surface): find_experts (whoknows) was
- // authored against v0.33 after PR #861 was drafted, so the source-scope
- // thread was missing entirely. The op calls findExperts → hybridSearch
- // internally; without the thread an auth'd src-A whoknows query would
- // surface src-B people in the rankings.
- // v0.40.6.0 T1.5 wiring (D4): consult the active pack for expert
- // types; pack-load failure → empty filter (NOT hardcoded defaults
- // per the silent-violation bug class Finding 1.3 closed).
- const { loadActivePackBestEffort, expertTypesFromPack } = await import('./schema-pack/index.ts');
- const pack = await loadActivePackBestEffort(ctx);
- const types = pack ? expertTypesFromPack(pack.manifest) : [];
- return findExperts(ctx.engine, {
- topic,
- limit: typeof p.limit === 'number' ? p.limit : undefined,
- explain: p.explain === true,
- types: types as never,
- ...sourceScopeOpts(ctx),
- });
- },
- cliHints: { name: 'whoknows', positional: ['topic'] },
-};
-
-// v0.32.6: contradiction probe MCP surface (M3)
-const find_contradictions: Operation = {
- name: 'find_contradictions',
- description: FIND_CONTRADICTIONS_DESCRIPTION,
- scope: 'read',
- // Reads eval_contradictions_runs.report_json for the latest run, then
- // filters in-memory by slug and severity. No new probe is triggered;
- // the agent surfaces what's already on disk.
- params: {
- slug: {
- type: 'string',
- description: 'Optional slug filter; matches either side of a pair (substring match on slug).',
- },
- severity: {
- type: 'string',
- enum: ['low', 'medium', 'high'],
- description: 'Optional severity filter.',
- },
- limit: {
- type: 'number',
- description: 'Max findings to return. Default 20.',
- },
- },
- handler: async (ctx, p) => {
- 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')
- ? p.severity
- : null;
- const rows = await ctx.engine.loadContradictionsTrend(30);
- if (rows.length === 0) {
- return { contradictions: [], note: 'No probe runs in the last 30 days; run `gbrain eval suspected-contradictions` first.' };
- }
- const latest = rows[0];
- const report = latest.report_json as Record<string, unknown> | null;
- const perQuery = (report?.per_query as Array<{
- contradictions: Array<{
- kind: string;
- severity: 'low' | 'medium' | 'high';
- axis: string;
- confidence: number;
- a: { slug: string; chunk_id: number | null; take_id: number | null };
- b: { slug: string; chunk_id: number | null; take_id: number | null };
- resolution_kind: string;
- resolution_command: string;
- }>;
- }> | undefined) ?? [];
- const findings = perQuery.flatMap((q) => q.contradictions);
- const filtered = findings.filter((f) => {
- if (sevFilter && f.severity !== sevFilter) return false;
- if (slugFilter) {
- const sA = f.a.slug.toLowerCase();
- const sB = f.b.slug.toLowerCase();
- if (!sA.includes(slugFilter) && !sB.includes(slugFilter)) return false;
- }
- return true;
- });
- return {
- run_id: latest.run_id,
- ran_at: latest.ran_at,
- contradictions: filtered.slice(0, limit),
- total_in_run: findings.length,
- };
- },
- cliHints: { name: 'find-contradictions' },
-};
-
-const find_trajectory: Operation = {
- name: 'find_trajectory',
- description: FIND_TRAJECTORY_DESCRIPTION,
- scope: 'read',
- // localOnly intentionally NOT set — federated OAuth clients should be
- // able to query trajectories for entities in their scope. Visibility
- // filtering (D-CDX-1) inside the engine restricts remote callers to
- // visibility='world' facts.
- params: {
- entity_slug: {
- type: 'string',
- description: 'Required. Entity slug to chart (e.g. "companies/acme-example", "people/alice-example").',
- },
- metric: {
- type: 'string',
- description: 'Optional. Filter to a single canonical metric (e.g. "mrr", "arr", "team_size"). When omitted, all metrics return.',
- },
- kind: {
- type: 'string',
- enum: ['metric', 'event', 'all'],
- description: 'Optional. Filter by row shape: "metric" (typed-claim rows only), "event" (event_type rows only), or "all" (default). v0.40.2.0+.',
- },
- since: {
- type: 'string',
- description: 'Optional lower bound on valid_from (YYYY-MM-DD or ISO).',
- },
- until: {
- type: 'string',
- description: 'Optional upper bound on valid_from (YYYY-MM-DD or ISO).',
- },
- limit: {
- type: 'number',
- description: 'Max points returned. Default 100, max 500.',
- },
- },
- handler: async (ctx, p) => {
- if (typeof p.entity_slug !== 'string' || !p.entity_slug.trim()) {
- throw new Error('find_trajectory requires entity_slug (string)');
- }
- const metric = typeof p.metric === 'string' ? p.metric : undefined;
- const kind = (p.kind === 'metric' || p.kind === 'event' || p.kind === 'all')
- ? (p.kind as 'metric' | 'event' | 'all')
- : undefined;
- const since = typeof p.since === 'string' ? p.since : undefined;
- const until = typeof p.until === 'string' ? p.until : undefined;
- const limit = typeof p.limit === 'number' ? p.limit : undefined;
- const scope = sourceScopeOpts(ctx);
-
- // D-CDX-1: thread ctx.remote into the engine so visibility filtering
- // happens at SQL level. Mirrors recall's posture for untrusted callers.
- const points = await ctx.engine.findTrajectory({
- entitySlug: p.entity_slug,
- ...scope,
- remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)
- metric,
- kind,
- since,
- until,
- limit,
- });
-
- const { computeTrajectoryStats, TRAJECTORY_SCHEMA_VERSION } = await import('./trajectory.ts');
- const { regressions, drift_score } = computeTrajectoryStats(points);
-
- // Engine result includes raw embeddings (Float32Array); strip those
- // before sending over MCP — they're bulky binary noise that consumers
- // never need at this layer.
- // v0.40.2.0: event_type surfaces on the wire so remote callers (thin-
- // client think, founder-scorecard) see the event-shaped rows.
- const wirePoints = points.map(pt => ({
- fact_id: pt.fact_id,
- valid_from: pt.valid_from.toISOString().slice(0, 10),
- metric: pt.metric,
- value: pt.value,
- unit: pt.unit,
- period: pt.period,
- event_type: pt.event_type,
- text: pt.text,
- source_session: pt.source_session,
- source_markdown_slug: pt.source_markdown_slug,
- }));
-
- return {
- points: wirePoints,
- regressions,
- drift_score,
- schema_version: TRAJECTORY_SCHEMA_VERSION,
- };
- },
- cliHints: { name: 'find-trajectory' },
-};
-
-const get_recent_transcripts: Operation = {
- name: 'get_recent_transcripts',
- description: GET_RECENT_TRANSCRIPTS_DESCRIPTION,
- scope: 'read',
- // Local-only: rejects HTTP-borne MCP traffic at tool-list time
- // (serve-http.ts filters on `localOnly`) AND at runtime via the in-handler
- // ctx.remote check. Defense in depth: hidden + rejected.
- localOnly: true,
- params: {
- days: { type: 'number', description: 'Window in days. Default 7.' },
- summary: {
- type: 'boolean',
- description: 'When true (default), return first ~300 chars per transcript. When false, full content (capped at 100 KB per file).',
- },
- limit: { type: 'number', description: 'Max transcripts (default 50).' },
- },
- handler: async (ctx, p) => {
- // Trust gate (eng review D2 + codex C3): MCP / HTTP callers (`remote=true`)
- // are blocked. Local CLI callers (`remote=false`) and the trusted-workspace
- // dream cycle pass through. This op is intentionally NOT in the subagent
- // allow-list (subagents always run with remote=true; they would always be
- // rejected, which is a footgun if the op is visible).
- if (ctx.remote === true) {
- throw new OperationError(
- 'permission_denied',
- 'get_recent_transcripts is local-only — call via the gbrain CLI.',
- );
- }
- const { listRecentTranscripts } = await import('./transcripts.ts');
- return listRecentTranscripts(ctx.engine, {
- days: typeof p.days === 'number' ? p.days : undefined,
- summary: typeof p.summary === 'boolean' ? p.summary : undefined,
- limit: typeof p.limit === 'number' ? p.limit : undefined,
- });
- },
- cliHints: { name: 'transcripts', hidden: true },
-};
-
-// --- v0.28: whoami + sources management ---
-
-const whoami: Operation = {
- name: 'whoami',
- description:
- 'Introspect the calling identity. Returns one of three transport shapes: ' +
- '{transport: "oauth", client_id, client_name, scopes, expires_at, source_id, federated_read}, ' +
- '{transport: "legacy", token_name, scopes, expires_at: null}, or ' +
- '{transport: "local", scopes: []}, or {transport: "stdio", scopes: []} ' +
- 'for the auth-less stdio MCP pipe. Throws unknown_transport when the ' +
- 'context is ambiguous (remote=true without auth and no transport marker) ' +
- '— fail-closed posture mirroring the v0.26.9 trust-boundary contract.',
- params: {},
- scope: 'read',
- handler: async (ctx) => {
- // Trust boundary: ctx.remote === false is the trusted local CLI surface.
- // Returning OAuth-shaped scopes here would resurrect the v0.26.9 footgun
- // where code conditionally trusted on `scopes.includes('admin')` instead
- // of `ctx.remote === false`. Empty scopes array forces clients to
- // special-case `transport: 'local'` explicitly.
- if (ctx.remote === false) {
- return { transport: 'local', scopes: [] };
- }
- // #1061: stdio MCP is remote/untrusted by design but has no per-token
- // auth (local pipe) — a known transport, not a bug. Report it instead of
- // throwing. Empty scopes: nothing here may be used to gate anything.
- if (!ctx.auth && ctx.transport === 'stdio') {
- return { transport: 'stdio', scopes: [] };
- }
- if (!ctx.auth) {
- throw new OperationError(
- 'unknown_transport',
- 'whoami called over a remote transport that did not thread ctx.auth. ' +
- 'This is a transport bug — every remote call site must populate ctx.auth ' +
- 'or set ctx.remote === false.',
- );
- }
- // OAuth tokens have client_id starting with 'gbrain_cl_'; legacy
- // access_tokens reuse `name` as both clientId and clientName (verifyAccessToken
- // at oauth-provider.ts:417-430). Detect by inspecting the prefix.
- const isOauth = ctx.auth.clientId.startsWith('gbrain_cl_');
- if (isOauth) {
- return {
- transport: 'oauth',
- client_id: ctx.auth.clientId,
- client_name: ctx.auth.clientName ?? ctx.auth.clientId,
- scopes: ctx.auth.scopes,
- expires_at: ctx.auth.expiresAt ?? null,
- // Read-only self-introspection of the token's source grants —
- // widens nothing; absent grants serialize fail-closed (null / []).
- source_id: ctx.auth.sourceId ?? null,
- federated_read: ctx.auth.allowedSources ?? [],
- };
- }
- return {
- transport: 'legacy',
- token_name: ctx.auth.clientName ?? ctx.auth.clientId,
- scopes: ctx.auth.scopes,
- expires_at: null,
- };
- },
- cliHints: { name: 'whoami' },
-};
-
-const sources_add: Operation = {
- name: 'sources_add',
- description:
- 'Register a new source. Supports either --path (existing v0.17 behavior) ' +
- 'or --url (v0.28 federated remote-clone path: parses the URL through the ' +
- 'SSRF gate, clones into $GBRAIN_HOME/clones/<id>/ via temp-dir + rename ' +
- 'atomicity, and stores remote_url in sources.config). Pre-flight collision ' +
- 'check on id; rollback on either-side failure.',
- params: {
- id: {
- type: 'string',
- required: true,
- description: 'Source id ([a-z0-9-]{1,32}). Immutable citation key.',
- },
- name: { type: 'string', description: 'Display name (defaults to id).' },
- path: { type: 'string', description: 'Local path. Mutually optional with url.' },
- url: {
- type: 'string',
- description:
- 'HTTPS git URL. Cloned into $GBRAIN_HOME/clones/<id>/. SSRF-guarded.',
- },
- federated: {
- type: 'boolean',
- description: 'true → cross-source default search. false → isolated.',
- },
- clone_dir: {
- type: 'string',
- description:
- 'Override clone destination (only valid with url). Default: $GBRAIN_HOME/clones/<id>/.',
- },
- },
- mutating: true,
- scope: 'sources_admin',
- handler: async (ctx, p) => {
- const { addSource } = await import('./sources-ops.ts');
-
- // v0.28.1 codex finding (CRITICAL + HIGH): a `sources_admin` token over
- // HTTP MCP must not be able to plant content at arbitrary host paths.
- //
- // - `path` lets a remote caller register `/etc/` (or any host dir) as a
- // "source"; later `gbrain sync --all` walks every sources.local_path,
- // which exfiltrates host content into the brain.
- // - `clone_dir` lets a remote caller name the destination directly;
- // addSource's renameSync places the cloned tree there with no
- // confinement, AND validateRepoState's degraded-state recovery later
- // does rm -rf on src.local_path, so the same primitive doubles as
- // arbitrary-delete.
- //
- // Both fields are CLI-only (the operator runs `gbrain sources add --path
- // /home/me/notes`). For HTTP MCP, ignore overrides — clone_dir defaults
- // to $GBRAIN_HOME/clones/<id>/ and path is rejected. Local CLI callers
- // (ctx.remote === false, per F7b fail-closed contract) keep the override.
- const isLocal = ctx.remote === false;
- const remotePath = isLocal ? (p.path as string | undefined) ?? null : null;
- const remoteCloneDir = isLocal ? (p.clone_dir as string | undefined) : undefined;
- if (!isLocal && p.path !== undefined) {
- throw new OperationError(
- 'invalid_params',
- 'sources_add: path is not honored over MCP (security confinement). ' +
- 'Register with --url instead, or run `gbrain sources add --path ...` on the host CLI.',
- 'Use --url to register a remote source, or run the command locally with --path.',
- );
- }
-
- const row = await addSource(ctx.engine, {
- id: p.id as string,
- name: p.name as string | undefined,
- localPath: remotePath,
- remoteUrl: p.url as string | undefined,
- federated:
- p.federated === undefined ? null : (p.federated as boolean),
- cloneDir: remoteCloneDir,
- });
- return row;
- },
- cliHints: { name: 'sources_add', hidden: true },
-};
-
-const sources_list: Operation = {
- name: 'sources_list',
- description:
- 'List registered sources with page counts and remote_url. v0.28 surfaces ' +
- 'the new remote_url field so a remote MCP caller can confirm a source is ' +
- 'managed by clone+pull rather than user-supplied path.',
- params: {
- include_archived: { type: 'boolean', description: 'Include soft-deleted sources.' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { listSources } = await import('./sources-ops.ts');
- return {
- sources: await listSources(ctx.engine, {
- includeArchived: (p.include_archived as boolean) === true,
- }),
- };
- },
- cliHints: { name: 'sources_list', hidden: true },
-};
-
-const sources_remove: Operation = {
- name: 'sources_remove',
- description:
- 'Hard-remove a source (cascades pages/chunks/embeddings). Refuses to ' +
- 'delete the auto-managed clone dir unless its resolved path is confined ' +
- 'under $GBRAIN_HOME/clones/ (realpath+lstat — symlink-safe). For most ' +
- 'workflows prefer sources_archive for the soft-delete path.',
- params: {
- id: { type: 'string', required: true, description: "Source id to remove, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },
- confirm_destructive: {
- type: 'boolean',
- description:
- 'Required when the source has data (pages, chunks). Without it the op refuses.',
- },
- dry_run: { type: 'boolean', description: 'Preview impact without side effects.' },
- keep_storage: {
- type: 'boolean',
- description: 'Skip clone-dir cleanup even when the source is auto-managed.',
- },
- },
- mutating: true,
- scope: 'sources_admin',
- handler: async (ctx, p) => {
- const { removeSource } = await import('./sources-ops.ts');
- return removeSource(ctx.engine, {
- id: p.id as string,
- confirmDestructive: (p.confirm_destructive as boolean) === true,
- dryRun: (p.dry_run as boolean) === true || ctx.dryRun,
- keepStorage: (p.keep_storage as boolean) === true,
- });
- },
- cliHints: { name: 'sources_remove', hidden: true },
-};
-
-const sources_status: Operation = {
- name: 'sources_status',
- description:
- 'Per-source diagnostic. Returns clone_state ("healthy" | "missing" | ' +
- '"not-a-dir" | "no-git" | "url-drift" | "corrupted" | "not-applicable") ' +
- 'so a remote MCP caller can diagnose whether the on-disk clone is ' +
- 'syncable without SSH access to the brain host.',
- params: {
- id: { type: 'string', required: true, description: "Source id to diagnose, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { getSourceStatus } = await import('./sources-ops.ts');
- return getSourceStatus(ctx.engine, p.id as string);
- },
- cliHints: { name: 'sources_status', hidden: true },
-};
-
-// ============================================================
-// v0.31 — Hot memory ops: extract_facts / recall / forget_fact
-// ============================================================
-
-const extract_facts: Operation = {
- name: 'extract_facts',
- description:
- 'v0.31: extract personal-knowledge facts (events, preferences, commitments, beliefs) from a conversation turn into the per-source hot memory. Sanitizes turn_text via INJECTION_PATTERNS, calls Haiku to extract structured claims, runs the cosine fast-path + classifier dedup pipeline, INSERTs into facts. Returns counts by status. Skips extraction when the turn is dream-generated content (anti-loop). For agent memory writes of a SINGLE already-formed fact, prefer the `remember` verb (zero LLM, mandatory provenance).',
- params: {
- turn_text: { type: 'string', required: true, description: 'The user message or page body to extract facts from. Sanitized via INJECTION_PATTERNS before the LLM call.' },
- session_id: { type: 'string', description: 'Opaque session id (e.g. topic-id from MCP _meta.session_id, or CLI --session). Stored on each fact for the recall --session filter. Not an auth surface.' },
- entity_hints: { type: 'array', items: { type: 'string' }, description: 'Existing canonical entity slugs the agent has already resolved. Helps the extractor pick the right slug.' },
- is_dream_generated: { type: 'boolean', description: 'When true, extraction is skipped (anti-loop). Caller flips this on for pages with dream_generated:true frontmatter.' },
- visibility: { type: 'string', description: 'Default visibility for extracted facts. private (default) | world.' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'extract_facts' };
- const { isFactsExtractionEnabled } = await import('./facts/extract.ts');
- const { runFactsPipeline } = await import('./facts/backstop.ts');
-
- // D15: kill switch. Operator can disable facts extraction across the
- // brain without binary downgrade by setting `facts.extraction_enabled`
- // to false. Returns zero-counts envelope so callers see a clean
- // success rather than a 'permission_denied' false alarm.
- if (!(await isFactsExtractionEnabled(ctx.engine))) {
- return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'extraction_disabled' };
- }
-
- // v0.31.2: routed through the shared pipeline (PR1 commit 9). Anti-loop
- // dream-generated check stays at the op layer because extract_facts is
- // an explicit user op without a parsedPage — the eligibility predicate
- // doesn't apply, but the dream-generated guard still does.
- if (p.is_dream_generated === true) {
- return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'dream_generated' };
- }
-
- const sourceId = ctx.sourceId ?? 'default';
- // [ENG-8] Explicit caller value wins; UNSET resolves through the shared
- // facts.default_visibility helper (the old ternary coerced unset →
- // 'private' before any config default could run). Garbage stays 'private'.
- const { resolveVisibilityParam } = await import('./facts/visibility.ts');
- const visibility: 'private' | 'world' = await resolveVisibilityParam(ctx.engine, p.visibility);
-
- const r = await runFactsPipeline(p.turn_text as string, {
- engine: ctx.engine,
- sourceId,
- sessionId: typeof p.session_id === 'string' ? p.session_id : null,
- entityHints: Array.isArray(p.entity_hints) ? (p.entity_hints as string[]) : undefined,
- source: 'mcp:extract_facts',
- visibility,
- mode: 'inline', // declarative; runFactsPipeline always inline
- });
-
- return {
- inserted: r.inserted,
- duplicate: r.duplicate,
- superseded: r.superseded,
- fact_ids: r.fact_ids,
- };
- },
-};
-
-const recall: Operation = {
- name: 'recall',
- description:
- 'MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.',
- params: {
- entity: { type: 'string', description: 'Entity slug (canonical). Returns facts about this entity newest first.' },
- query: { type: 'string', description: 'MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error).' },
- budget_tokens: { type: 'number', description: 'MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count.' },
- since: { type: 'string', description: 'ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only.' },
- session_id: { type: 'string', description: 'Source session id (e.g. topic-A). Returns facts captured in that session.' },
- include_expired: { type: 'boolean', description: 'When true, include expired_at IS NOT NULL rows. Default false.' },
- supersessions: { type: 'boolean', description: 'When true, return only the supersession audit log (expired_at + superseded_by both set).' },
- limit: { type: 'number', description: 'Per-arm cap: max fact rows AND max search results. Default 50, cap 100.' },
- grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied client-side after recall.' },
- include_pending: { type: 'boolean', description: 'v0.32: when true, response includes pending_consolidation_count (facts not yet promoted to takes by the dream-cycle consolidate phase). One round trip; backward-compatible (field omitted when false).' },
- },
- scope: 'read',
- verb: true,
- annotations: { title: 'recall (memory read)', readOnlyHint: true },
- handler: async (ctx, p) => {
- const sourceId = ctx.sourceId ?? 'default';
- const limit = typeof p.limit === 'number' ? p.limit : 50;
- const includeExpired = p.include_expired === true;
- const grep = typeof p.grep === 'string' ? p.grep.toLowerCase() : null;
-
- // Visibility filter: remote callers see world-only unless their token
- // grants elevated visibility (future-proofing; v0.31 ships world-only
- // for remote, all for local CLI).
- const visibility =
- ctx.remote === false
- ? undefined
- : ['world'] as ('private' | 'world')[];
-
- let rows: Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>> = [];
-
- if (p.supersessions === true) {
- const since = parseSinceParam(p.since);
- rows = await ctx.engine.listSupersessions(sourceId, { since: since ?? undefined, limit });
- } else if (typeof p.entity === 'string' && p.entity.length > 0) {
- const { resolveEntitySlug } = await import('./entities/resolve.ts');
- const slug = (await resolveEntitySlug(ctx.engine, sourceId, p.entity)) ?? p.entity;
- rows = await ctx.engine.listFactsByEntity(sourceId, slug, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
- } else if (typeof p.session_id === 'string' && p.session_id.length > 0) {
- rows = await ctx.engine.listFactsBySession(sourceId, p.session_id, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
- } else if (p.since !== undefined) {
- const since = parseSinceParam(p.since);
- if (since) {
- rows = await ctx.engine.listFactsSince(sourceId, since, {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
- }
- } else {
- // No filter: return recent across the source.
- rows = await ctx.engine.listFactsSince(sourceId, new Date(0), {
- activeOnly: !includeExpired,
- limit,
- visibility,
- });
- }
-
- if (grep) rows = rows.filter(r => r.fact.toLowerCase().includes(grep));
-
- // v0.32: optional pending-consolidation count piggy-backed on the recall
- // response. Single round trip on thin-client; omitted when not requested
- // so existing callers see no shape change.
- let pending_consolidation_count: number | undefined;
- if (p.include_pending === true) {
- try {
- pending_consolidation_count = await ctx.engine.countUnconsolidatedFacts(sourceId);
- } catch (e) {
- // Best-effort: if the count query fails we still return facts. Field
- // stays undefined so callers can tell the difference between "0
- // pending" and "we couldn't ask."
- process.stderr.write(
- `[recall] countUnconsolidatedFacts failed: ${(e as Error).message}\n`,
- );
- }
- }
-
- // ── MEMORY_VERBS v1 — query arm (G1B superset). Hybrid search over pages
- // when `query` is present; degrades to keyword-only with a note (never an
- // error) when no embedding provider is configured [F-B].
- const queryText = typeof p.query === 'string' && p.query.trim().length > 0 ? p.query.trim() : null;
- const budgetTokens =
- typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
- ? Math.floor(p.budget_tokens)
- : null;
-
- let searchResults: SearchResult[] = [];
- let searchDegraded: string | undefined;
- if (queryText) {
- const searchScope = sourceScopeOpts(ctx);
- if (!isAvailable('embedding')) {
- const raw = await ctx.engine.searchKeyword(queryText, { limit, ...searchScope });
- searchResults = dedupResults(raw);
- stampEvidenceSafe(searchResults);
- await stampContentFlags(ctx.engine, searchResults);
- searchDegraded = 'keyword_only_no_embedding_provider';
- } else {
- searchResults = await hybridSearchCached(ctx.engine, queryText, {
- limit,
- expansion: false,
- ...searchScope,
- });
- }
- bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));
- }
-
- // ── MEMORY_VERBS v1 — server-side budget packing. Facts pack first (cheap,
- // high-precision one-liners, per-arm limit-capped so starvation is bounded),
- // then search results take the remainder. packToBudget treats budget<=0 as
- // a no-op, so an exhausted remainder must drop explicitly.
- let packedFacts = rows;
- let packedResults = searchResults;
- let budgetUsed: number | undefined;
- let droppedCount: number | undefined;
- if (budgetTokens !== null) {
- const factsPack = packToBudget(rows, r => estimateTokens(r.fact), budgetTokens);
- packedFacts = factsPack.items;
- const remaining = budgetTokens - factsPack.meta.used;
- const resultsPack =
- remaining > 0
- ? packToBudget(searchResults, resultTokens, remaining)
- : { items: [] as SearchResult[], meta: { budget: 0, used: 0, dropped: searchResults.length, kept: 0 } };
- packedResults = resultsPack.items;
- budgetUsed = factsPack.meta.used + resultsPack.meta.used;
- droppedCount = factsPack.meta.dropped + resultsPack.meta.dropped;
- }
-
- return {
- facts: packedFacts.map(r => ({
- id: r.id,
- fact: r.fact,
- kind: r.kind,
- entity_slug: r.entity_slug,
- visibility: r.visibility,
- // v0.31.2: notability surfaced to recall consumers (CLI, MCP, admin).
- // Pre-v46 brains return 'medium' via the row mapper's fallback so the
- // contract stays total.
- notability: r.notability,
- valid_from: r.valid_from.toISOString(),
- valid_until: r.valid_until?.toISOString() ?? null,
- expired_at: r.expired_at?.toISOString() ?? null,
- superseded_by: r.superseded_by,
- consolidated_at: r.consolidated_at?.toISOString() ?? null,
- consolidated_into: r.consolidated_into,
- source: r.source,
- source_session: r.source_session,
- confidence: r.confidence,
- created_at: r.created_at.toISOString(),
- // MEMORY_VERBS v1 additive fields (G1B). `fact_id` is the opaque
- // STRING id the `forget` verb accepts (legacy numeric `id` stays for
- // pre-v1 consumers — legacy fields are frozen byte-equal). `provenance`
- // is the protocol name for the stored source attribution.
- fact_id: String(r.id),
- provenance: r.source,
- })),
- total: packedFacts.length,
- ...(pending_consolidation_count !== undefined ? { pending_consolidation_count } : {}),
- // MEMORY_VERBS v1 envelope (G1B superset — additive on every response).
- protocol_version: MEMORY_VERBS_VERSION,
- ...(queryText
- ? {
- results: packedResults.map(r => ({
- slug: r.slug,
- title: r.title,
- chunk: r.chunk_text,
- evidence: r.evidence,
- create_safety: r.create_safety,
- provenance: r.slug,
- })),
- ...(searchDegraded ? { search_degraded: searchDegraded } : {}),
- }
- : {}),
- ...(budgetTokens !== null
- ? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
- : {}),
- };
- },
-};
-
-/** Parse an `entities` param (comma-string or array) to a trimmed name list. */
-function parseEntityList(v: unknown): string[] {
- if (Array.isArray(v)) return v.filter((x) => typeof x === 'string' && x.trim()).map((x) => (x as string).trim());
- if (typeof v === 'string') return v.split(',').map((s) => s.trim()).filter(Boolean);
- return [];
-}
-
-const context_pack: Operation = {
- name: 'context_pack',
- description:
- 'MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing entities — entity cards + open threads + hot facts, zero-LLM, sub-second. Call at session start (warm cold context) and after compaction (rehydrate what the summary lost). WORLD-ONLY by default; pass include_private (honored for LOCAL trusted callers only) to widen all arms. budget_tokens packs server-side (response reports budget_used + dropped_count; cards pack first, then facts). Branch on structured fields, never prose. protocol_version rides every response.',
- params: {
- entities: { type: 'string', required: true, description: 'Comma-separated entity names/slugs to bundle. Capped at 8.' },
- budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Cards pack first, then facts. Response adds budget_tokens, budget_used, dropped_count.' },
- since: { type: 'string', description: 'ISO 8601 datetime. When set, open-thread events are filtered to those after this cursor.' },
- session_id: { type: 'string', description: 'Opaque session id; keys the hot-memory cache and (on the push path) the session cursor.' },
- include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
- },
- scope: 'read',
- verb: true,
- cliHints: { name: 'context-pack' },
- annotations: { title: 'context_pack (boundary bundle)', readOnlyHint: true },
- handler: async (ctx, p) => {
- const { assembleContextPack, renderPack, isAfter, PACK_DEFAULT_MAX_ENTITIES } = await import('./context/turn-context.ts');
- const sourceId = ctx.sourceId ?? 'default';
- const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : undefined;
- if (rawSince !== undefined && !Number.isFinite(Date.parse(rawSince))) {
- throw verbError(
- 'invalid_params',
- `context_pack: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`,
- 'Pass an ISO 8601 datetime, e.g. since: "2026-08-11T00:00:00Z".',
- );
- }
- // Normalize to ISO (red-team F4): the filter + rendered text use it.
- const since = rawSince !== undefined ? new Date(Date.parse(rawSince)).toISOString() : undefined;
- // Echo the CAPPED list (pre-landing review): the assembler bundles at most
- // PACK_DEFAULT_MAX_ENTITIES, so echoing more would claim entities were
- // bundled that produced no cards.
- const entities = parseEntityList(p.entities).slice(0, PACK_DEFAULT_MAX_ENTITIES);
- // Fail-closed: private only when EXPLICITLY requested AND the caller is
- // trusted-local (ctx.remote === false). A remote caller never widens.
- const includePrivate = p.include_private === true && ctx.remote === false;
- const budgetTokens =
- typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
- ? Math.floor(p.budget_tokens)
- : null;
- const res = await assembleContextPack(ctx.engine, {
- sourceId,
- entities,
- since,
- sessionId: typeof p.session_id === 'string' ? p.session_id : undefined,
- includePrivate,
- maxEntities: PACK_DEFAULT_MAX_ENTITIES,
- });
-
- let cards = res.cards ?? [];
- let facts = res.facts ?? [];
- let budgetUsed: number | undefined;
- let droppedCount: number | undefined;
- if (budgetTokens !== null) {
- const cardCost = (c: (typeof cards)[number]) =>
- estimateTokens(`${c.entity.title} ${c.summary} ${(c.open_threads ?? []).map((t) => t.text).join(' ')}`);
- const cardPack = packToBudget(cards, cardCost, budgetTokens);
- cards = cardPack.items;
- const remaining = budgetTokens - cardPack.meta.used;
- const factPack =
- remaining > 0
- ? packToBudget(facts, (f) => estimateTokens(f.fact), remaining)
- : { items: [] as typeof facts, meta: { budget: 0, used: 0, dropped: facts.length, kept: 0 } };
- facts = factPack.items;
- budgetUsed = cardPack.meta.used + factPack.meta.used;
- droppedCount = cardPack.meta.dropped + factPack.meta.dropped;
- }
- // Recompute open_threads with the SAME since filter the assembler applied
- // (pre-landing review: the raw flatMap silently dropped the documented
- // `since` contract from the structured array whenever budget packing ran).
- const open_threads = cards
- .flatMap((c) => c.open_threads ?? [])
- .filter((t) => !since || (t.date !== null && isAfter(t.date, since)));
- // Re-render the injectable block from the FINAL sets (adversarial review):
- // `text` is what harnesses inject, so it must honor the same budget the
- // structured arrays report — the assembler's pre-budget rendering would
- // overrun the declared budget_tokens.
- const text = budgetTokens !== null ? renderPack(cards, open_threads, facts) : res.text;
-
- return {
- protocol_version: MEMORY_VERBS_VERSION,
- entities,
- cards: cards.map((c) => ({
- slug: c.entity.slug,
- title: c.entity.title,
- type: c.entity.type,
- summary: c.summary,
- open_threads: c.open_threads,
- edges: c.edges,
- backlink_count: c.backlink_count,
- })),
- open_threads,
- facts: facts.map((f) => ({
- fact: f.fact,
- kind: f.kind,
- entity_slug: f.entity_slug,
- valid_from: f.valid_from,
- confidence: f.confidence,
- })),
- text,
- ...(res.degradedReason ? { degraded_reason: res.degradedReason } : {}),
- ...(budgetTokens !== null
- ? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
- : {}),
- };
- },
-};
-
-const delta: Operation = {
- name: 'delta',
- description:
- 'MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts). protocol_version rides every response.',
- params: {
- since: { type: 'string', description: 'ISO 8601 cursor. Returns pages/facts/thread-events newer than this timestamp. Optional when session_id carries an established cursor.' },
- since_slug: { type: 'string', description: 'Stateless keyset resume: pass back `next_cursor.slug` from the previous response (paired with `since`=next_cursor.since) to page through pages sharing one timestamp. Ignored when session_id is set (the session cursor carries it).' },
- entities: { type: 'string', description: 'Optional comma-separated entity scope for thread-event deltas. Capped at 8.' },
- budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Pages pack first, then facts. Response adds budget_tokens, budget_used, dropped_count.' },
- session_id: { type: 'string', description: 'Opaque session id. Drives the per-session cursor: the first call establishes it, each call advances it to the newest DELIVERED change (at-least-once — with has_more:true the undelivered tail returns on the next wake). Without it, pass an explicit `since` for a stateless delta.' },
- include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
- },
- scope: 'read',
- verb: true,
- cliHints: { name: 'delta' },
- annotations: { title: 'delta (what changed since)', readOnlyHint: true },
- handler: async (ctx, p) => {
- const { assembleDeltaContext, renderDelta, PACK_DEFAULT_MAX_ENTITIES } = await import('./context/turn-context.ts');
- const { getSessionContextState, upsertSessionContextState } = await import('./context/session-state.ts');
- const sourceId = ctx.sourceId ?? 'default';
- const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : null;
- if (rawSince !== null && !Number.isFinite(Date.parse(rawSince))) {
- throw verbError(
- 'invalid_params',
- `delta: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`,
- 'Pass an ISO 8601 datetime, e.g. since: "2026-08-11T00:00:00Z".',
- );
- }
- // NORMALIZE to ISO immediately (red-team F4): the raw string is echoed
- // into the injectable `text` block, so an attacker-shaped-but-parseable
- // `since` must never reach rendering verbatim.
- const explicitSince = rawSince !== null ? new Date(Date.parse(rawSince)).toISOString() : null;
- const sessionId = typeof p.session_id === 'string' && p.session_id.trim() ? p.session_id : null;
- // Cursor namespace (pre-landing review, fail-closed): 'local' is RESERVED
- // for the trusted CLI/hook lane, gated on STRICT ctx.remote === false —
- // anything else (true, undefined via cast bypass) is remote. Remote callers
- // use their auth client id; an auth-LESS or blank-id remote (stdio MCP)
- // gets the shared 'remote' sentinel — never collapsed into 'local'.
- const clientId = ctx.remote === false ? null : ctx.auth?.clientId?.trim() || 'remote';
- const includePrivate = p.include_private === true && ctx.remote === false;
- const budgetTokens =
- typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
- ? Math.floor(p.budget_tokens)
- : null;
-
- const state = sessionId ? await getSessionContextState(ctx.engine, sourceId, clientId, sessionId) : null;
- const effectiveSince = explicitSince ?? state?.last_wake_at ?? null;
-
- if (!effectiveSince) {
- if (!sessionId) {
- throw verbError(
- 'invalid_params',
- 'delta requires `since` (ISO 8601) or a `session_id` with an established cursor.',
- 'Pass since ("2026-08-11T00:00:00Z") for a stateless delta, or a stable session_id — the first call establishes the cursor and later calls return only newer changes.',
- );
- }
- // First wake for this session: establish the cursor at now and report an
- // empty delta (there is no prior point to diff against yet). Opportunistic
- // GC on row creation bounds session-row accumulation on serve-less CLI
- // lanes and remote read callers minting session ids (pre-landing review).
- // AWAITED (v0.45.7): a floating engine promise here races the CLI lane's
- // engine teardown and wedges the process — `gbrain delta --session-id`
- // printed its response but never exited (the exact command the shipped
- // HEARTBEAT.md ambient-delta row tells agents to run). GC is two fast
- // DELETEs on a capped table and internally fail-open, so awaiting costs
- // one first-wake round-trip, never an error. The serve-boot call site
- // (src/mcp/server.ts) stays fire-and-forget — that process is long-lived.
- const now = new Date().toISOString();
- const { gcSessionContextState } = await import('./context/session-state.ts');
- await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, { lastWakeAt: now });
- await gcSessionContextState(ctx.engine);
- return {
- protocol_version: MEMORY_VERBS_VERSION,
- since: now, pages: [], facts: [], threads: [], text: '', has_more: false,
- next_cursor: { since: now, slug: '' },
- ...(budgetTokens !== null
- ? { budget_tokens: budgetTokens, budget_used: 0, dropped_count: 0 }
- : {}),
- };
- }
-
- // Keyset cursor (red-team F1/F2 fix): pages page by (updated_at, slug), so
- // a >limit cluster at one timestamp is reachable and a delivered page never
- // re-appears unless it changes. The keyset slug lives in the session row
- // (surfaced_slugs[0]); an explicit-`since` caller has no stored slug and
- // resumes via the returned `next_cursor`.
- const cursorSlug = sessionId ? state?.surfaced_slugs?.[0] : undefined;
- const explicitSlug = typeof p.since_slug === 'string' ? p.since_slug : undefined;
- const sinceSlug = explicitSlug ?? cursorSlug;
-
- const res = await assembleDeltaContext(ctx.engine, {
- sourceId,
- since: effectiveSince,
- ...(sinceSlug !== undefined ? { sinceSlug } : {}),
- entities: parseEntityList(p.entities),
- sessionId: sessionId ?? undefined,
- includePrivate,
- maxEntities: PACK_DEFAULT_MAX_ENTITIES,
- });
-
- // Pages arrive OLDEST first by (updated_at, slug) — no client-side dedup
- // needed; the keyset already excludes everything at/before the cursor.
- let pages = res.deltaPages ?? [];
- let facts = res.facts ?? [];
- const threads = res.openThreads ?? [];
- let budgetUsed: number | undefined;
- let droppedCount: number | undefined;
- let factsDropped = 0;
- const fetchedPages = pages.length;
- if (budgetTokens !== null) {
- // packToBudget keeps a contiguous PREFIX (order-preserving, stops at the
- // first overflow) — with oldest-first pages the kept set stays contiguous
- // from the cursor, which the advance logic below depends on.
- const pagePack = packToBudget(pages, (pg) => estimateTokens(`${pg.title} ${pg.slug}`), budgetTokens);
- pages = pagePack.items;
- const remaining = budgetTokens - pagePack.meta.used;
- const factPack =
- remaining > 0
- ? packToBudget(facts, (f) => estimateTokens(f.fact), remaining)
- : { items: [] as typeof facts, meta: { budget: 0, used: 0, dropped: facts.length, kept: 0 } };
- facts = factPack.items;
- budgetUsed = pagePack.meta.used + factPack.meta.used;
- droppedCount = pagePack.meta.dropped + factPack.meta.dropped;
- factsDropped = factPack.meta.dropped;
- }
- const pagesDropped = fetchedPages - pages.length;
- // has_more covers ALL undelivered content — fetch-limit overflow, budget-
- // dropped pages, AND budget-dropped facts (pre-landing review: facts were
- // silently lost when pages fit but facts overflowed).
- const hasMore = res.deltaOverflow === true || pagesDropped > 0 || factsDropped > 0;
-
- // Cursor advance (keyset, at-least-once): advance to the last DELIVERED
- // (updated_at, slug). The keyset's strict `>` means the next wake starts
- // exactly after it — a >limit same-timestamp cluster drains one page at a
- // time across wakes (F1), and a delivered page never re-appears (F2). On a
- // page-less wake with nothing dropped, advance the TIME cursor to now()
- // minus a safety lag (in-flight write txns stamp updated_at at txn START)
- // and clear the keyset slug. If nothing delivered but something dropped, do
- // NOT advance (deliver-before-advance; a too-small budget must not eat it).
- const nextCursor =
- pages.length > 0
- ? { since: pages[pages.length - 1].updated_at, slug: pages[pages.length - 1].slug }
- : { since: effectiveSince, slug: sinceSlug ?? '' };
- if (sessionId) {
- if (pages.length > 0) {
- await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
- lastWakeAt: nextCursor.since,
- cursorSlug: nextCursor.slug,
- });
- } else if (!hasMore) {
- await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
- lastWakeAt: new Date(Date.now() - 2000).toISOString(),
- cursorSlug: '',
- });
- }
- }
-
- // Re-render the injectable block from the FINAL sets (adversarial review):
- // `text` must honor the budget AND the boundary-tie exclusion the
- // structured arrays reflect — the assembler's render predates both.
- const text = renderDelta(pages, facts, threads, effectiveSince);
-
- return {
- protocol_version: MEMORY_VERBS_VERSION,
- since: effectiveSince,
- pages,
- facts: facts.map((f) => ({
- fact: f.fact,
- kind: f.kind,
- entity_slug: f.entity_slug,
- valid_from: f.valid_from,
- confidence: f.confidence,
- })),
- threads,
- text,
- has_more: hasMore,
- // Stateless resume: a caller with no session_id passes these back as
- // `since` + `since_slug` on the next call to page deterministically.
- next_cursor: nextCursor,
- ...(res.degradedReason ? { degraded_reason: res.degradedReason } : {}),
- ...(budgetTokens !== null
- ? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
- : {}),
- };
- },
-};
-
-const forget_fact: Operation = {
- name: 'forget_fact',
- description: 'v0.32.2: forget a fact. Rewrites the page\'s `## Facts` fence to strike through the row and set valid_until=today (the DB\'s expired_at derives via valid_until + now() on the next reconcile so the forget survives `gbrain rebuild`). Falls back to legacy DB-only expire for pre-v51 / thin-client rows. Idempotent on already-expired or unknown ids.',
- params: {
- id: { type: 'number', required: true, description: 'Fact id to forget.' },
- reason: { type: 'string', required: false, description: 'Optional reason; written to the fence row\'s context cell as "forgotten: <reason>". Default: "forgotten".' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- if (ctx.dryRun) return { dry_run: true, action: 'forget_fact', id: p.id };
- const id = p.id as number;
- const reason = typeof p.reason === 'string' ? p.reason : undefined;
- const { forgetFactInFence } = await import('./facts/forget.ts');
- const result = await forgetFactInFence(ctx.engine, id, { reason });
- if (!result.ok && result.path === 'not_found') {
- throw new OperationError('fact_not_found', `Fact id ${id} not found.`);
- }
- if (!result.ok && result.path === 'already_expired') {
- throw new OperationError('fact_already_expired', `Fact id ${id} already expired.`);
- }
- return { id, expired: true, path: result.path, reason: result.reason };
- },
-};
-
-/**
- * Parse a `since` parameter into a Date. Accepts ISO 8601, plain duration
- * shorthand ("8 hours ago", "3 days ago", "30m", "1h", "2d", "7d"), or
- * Unix epoch millis. Returns null on unparseable input.
- */
-function parseSinceParam(raw: unknown): Date | null {
- if (raw == null) return null;
- if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw);
- if (typeof raw !== 'string') return null;
- const s = raw.trim();
- if (!s) return null;
-
- // Try ISO first.
- const iso = Date.parse(s);
- if (Number.isFinite(iso)) return new Date(iso);
-
- // "N (minutes|hours|days) ago" or compact forms.
- const ago = s.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)(?:\s+ago)?$/i);
- if (ago) {
- const n = parseInt(ago[1], 10);
- const unit = ago[2].toLowerCase();
- const ms =
- unit.startsWith('s') ? n * 1000 :
- unit.startsWith('m') ? n * 60 * 1000 :
- unit.startsWith('h') ? n * 60 * 60 * 1000 :
- n * 24 * 60 * 60 * 1000;
- return new Date(Date.now() - ms);
- }
- return null;
-}
-
-/**
- * MEMORY_VERBS v1 — parse the `remember` verb's `ttl` param into a
- * `valid_until` Date. Sibling of parseSinceParam, pointed FORWARD.
- *
- * Accepted forms (frozen in docs/protocol/MEMORY_VERBS_v1.md):
- * - relative duration shorthand: '30d', '12h', '45m', '90s' (also
- * spelled-out: '30 days', '12 hours') → now + duration
- * - absolute ISO 8601 date or datetime: '2026-07-12', '2026-07-12T00:00:00Z'
- *
- * Explicitly REJECTED with a self-correcting suggestion: ISO-8601 duration
- * syntax ('P30D', 'PT12H') — agents that read "ISO 8601" as durations get a
- * fix, not a mystery. Returns null for null/undefined/empty (= never expires).
- * Throws verbError('invalid_params') on anything unparseable.
- */
-export function parseTtlParam(raw: unknown): Date | null {
- if (raw == null) return null;
- if (typeof raw !== 'string') {
- throw verbError(
- 'invalid_params',
- `ttl must be a string, got ${typeof raw}.`,
- 'Pass a duration like "30d" or "12h", or an absolute ISO 8601 timestamp like "2026-07-12T00:00:00Z".',
- );
- }
- const s = raw.trim();
- if (!s) return null;
-
- // ISO-8601 DURATION syntax is a documented trap — reject with the fix.
- if (/^P(T|\d)/i.test(s) && /^P(?:\d+[YMWD])*(?:T(?:\d+[HMS])+)?$/i.test(s)) {
- throw verbError(
- 'invalid_params',
- `ttl "${s}" looks like an ISO-8601 duration, which is not accepted.`,
- `Use the shorthand form instead (e.g. "${s.replace(/^PT?/i, '').toLowerCase()}" style: "30d", "12h"), or an absolute ISO 8601 expiry timestamp.`,
- );
- }
-
- // Relative duration shorthand → now + duration.
- const dur = s.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)$/i);
- if (dur) {
- const n = parseInt(dur[1], 10);
- const unit = dur[2].toLowerCase();
- const ms =
- unit.startsWith('s') ? n * 1000 :
- unit.startsWith('m') ? n * 60 * 1000 :
- unit.startsWith('h') ? n * 60 * 60 * 1000 :
- n * 24 * 60 * 60 * 1000;
- return new Date(Date.now() + ms);
- }
-
- // Absolute ISO 8601 date or datetime.
- const iso = Date.parse(s);
- if (Number.isFinite(iso)) return new Date(iso);
-
- throw verbError(
- 'invalid_params',
- `Cannot parse ttl "${s}".`,
- 'Pass a duration like "30d" or "12h", or an absolute ISO 8601 timestamp like "2026-07-12T00:00:00Z". Omit ttl for a fact that never expires.',
- );
-}
-
-// ──────────────────────────────────────────────────────────────────────────────
-// v0.34 Cathedral III — code-intelligence ops (MCP-exposed).
-//
-// Pre-v0.34 code-callers / code-callees / code-def / code-refs lived only in
-// the CLI_ONLY set at cli.ts:30 — agents calling gbrain via MCP couldn't reach
-// them and fell through to text search. These wrappers expose the existing
-// engine + library functions to the MCP surface with resolver-grade
-// descriptions (operations-descriptions.ts) so agents route to them
-// automatically during plan-mode.
-//
-// All four are scope:'read'. Source-scoped via ctx.sourceId when set.
-// Both `source_id` and `all_sources` are params so per-call overrides work.
-// ──────────────────────────────────────────────────────────────────────────────
-
-const code_callers: Operation = {
- name: 'code_callers',
- description: CODE_CALLERS_DESCRIPTION,
- params: {
- symbol: { type: 'string', required: true, description: 'Symbol to find callers of (bare or qualified name).' },
- limit: { type: 'number', description: 'Max edges returned. Default 100.' },
- source_id: { type: 'string', description: "Scope to a single source. Defaults to ctx.sourceId; '__all__' spans every source for trusted local callers, your granted sources for remote callers." },
- all_sources: { type: 'boolean', description: 'Span sources (equivalent to source_id=__all__): every source locally, your grant remotely.' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const symbol = p.symbol as string;
- const limit = (p.limit as number) ?? 100;
- const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
- // Single trust+grant resolver: remote callers can't span sources outside
- // their grant, and `__all__` collapses to their grant (not the whole brain).
- const { allSources, sourceId } = resolveCodeIntelScope(ctx, sourceIdParam, p.all_sources === true);
- const edges = await ctx.engine.getCallersOf(symbol, {
- limit,
- allSources,
- sourceId,
- });
- const { resolveCodeReadiness } = await import('./code-graph-readiness.ts');
- const readiness = await resolveCodeReadiness(ctx.engine, {
- kind: 'edge', count: edges.length, sourceId, allSources,
- });
- return { symbol, count: edges.length, status: readiness.status, ready: readiness.ready, callers: edges };
- },
- cliHints: { name: 'code_callers', hidden: true },
-};
-
-const code_callees: Operation = {
- name: 'code_callees',
- description: CODE_CALLEES_DESCRIPTION,
- params: {
- symbol: { type: 'string', required: true, description: 'Symbol to find callees of (bare or qualified name).' },
- limit: { type: 'number', description: 'Max edges returned. Default 100.' },
- source_id: { type: 'string', description: "Scope to a single source. Defaults to ctx.sourceId; '__all__' spans every source for trusted local callers, your granted sources for remote callers." },
- all_sources: { type: 'boolean', description: 'Span sources: every source locally, your grant remotely.' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const symbol = p.symbol as string;
- const limit = (p.limit as number) ?? 100;
- const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
- // Single trust+grant resolver (see code_callers).
- const { allSources, sourceId } = resolveCodeIntelScope(ctx, sourceIdParam, p.all_sources === true);
- const edges = await ctx.engine.getCalleesOf(symbol, {
- limit,
- allSources,
- sourceId,
- });
- const { resolveCodeReadiness } = await import('./code-graph-readiness.ts');
- const readiness = await resolveCodeReadiness(ctx.engine, {
- kind: 'edge', count: edges.length, sourceId, allSources,
- });
- return { symbol, count: edges.length, status: readiness.status, ready: readiness.ready, callees: edges };
- },
- cliHints: { name: 'code_callees', hidden: true },
-};
-
-const code_def: Operation = {
- name: 'code_def',
- description: CODE_DEF_DESCRIPTION,
- params: {
- symbol: { type: 'string', required: true, description: 'Symbol name (bare token; e.g., parseMarkdown, BrainEngine).' },
- limit: { type: 'number', description: 'Max definition sites returned. Default 20.' },
- lang: { type: 'string', description: "Filter by content_chunks.language (e.g. 'typescript', 'python')." },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { findCodeDef } = await import('../commands/code-def.ts');
- const defs = await findCodeDef(ctx.engine, p.symbol as string, {
- limit: (p.limit as number) ?? 20,
- language: (p.lang as string) || undefined,
- });
- // code_def is brain-wide (not source-scoped); readiness is 'symbol' grain.
- const { resolveCodeReadiness } = await import('./code-graph-readiness.ts');
- const readiness = await resolveCodeReadiness(ctx.engine, { kind: 'symbol', count: defs.length });
- return { symbol: p.symbol as string, count: defs.length, status: readiness.status, ready: readiness.ready, defs };
- },
- cliHints: { name: 'code_def', hidden: true },
-};
-
-const code_refs: Operation = {
- name: 'code_refs',
- description: CODE_REFS_DESCRIPTION,
- params: {
- symbol: { type: 'string', required: true, description: 'Symbol to find references to.' },
- limit: { type: 'number', description: 'Max references returned. Default 50.' },
- lang: { type: 'string', description: "Filter by content_chunks.language." },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { findCodeRefs } = await import('../commands/code-refs.ts');
- const refs = await findCodeRefs(ctx.engine, p.symbol as string, {
- limit: (p.limit as number) ?? 50,
- language: (p.lang as string) || undefined,
- });
- // code_refs is brain-wide (not source-scoped); readiness is 'symbol' grain.
- const { resolveCodeReadiness } = await import('./code-graph-readiness.ts');
- const readiness = await resolveCodeReadiness(ctx.engine, { kind: 'symbol', count: refs.length });
- return { symbol: p.symbol as string, count: refs.length, status: readiness.status, ready: readiness.ready, refs };
- },
- cliHints: { name: 'code_refs', hidden: true },
-};
-
-// --- v0.34 W3: recursive code_blast + code_flow ---
-
-const code_blast: Operation = {
- name: 'code_blast',
- description: 'BEFORE editing any function, run code_blast with the symbol name to surface every transitive caller grouped by depth (direct → 2-hop → 3-hop). Use this during plan-mode to size the change. Returns up to 200 nodes. Returns: {result, depth_groups?, truncation?, cycles_detected?, did_you_mean?, candidates?}. Example ok: {result:"ok", depth_groups:[{depth:1, nodes:[{symbol,chunk_id}], confidence:0.77}], truncation:"none"}.',
- params: {
- symbol: { type: 'string', required: true, description: 'Bare or qualified symbol name (e.g. "performSync" or "src/foo::performSync")' },
- depth: { type: 'number', description: 'Hop cap (default 5, max 8)' },
- max_nodes: { type: 'number', description: 'Result-set cap (default 200)' },
- exact: { type: 'boolean', description: 'Skip bare-name disambiguation; treat symbol as exact qualified name' },
- source_id: { type: 'string', description: 'Source to traverse. Defaults to ctx.sourceId; federated clients with multiple granted sources must specify one.' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { runRecursiveWalk } = await import('./code-intel/recursive-walk.ts');
- const { getCachedOrCompute } = await import('./code-intel/traversal-cache.ts');
- const symbol = p.symbol as string;
- const depth = Math.min((p.depth as number) ?? 5, 8);
- const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200);
- const exact = (p.exact as boolean) ?? false;
- // Single trust+grant resolver: a remote federated client can't traverse a
- // source outside its grant (pre-fix this scoped by bare ctx.sourceId only).
- // Falls back to ctx.sourceId (a required string) for the trusted-local case,
- // exactly preserving pre-fix local behavior.
- const { sourceId: scopedSourceId } = resolveCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
- const sourceId = scopedSourceId ?? ctx.sourceId;
- return getCachedOrCompute(
- ctx.engine,
- { symbol_qualified: symbol, depth, source_id: sourceId },
- () => runRecursiveWalk(ctx.engine, symbol, {
- direction: 'callers',
- depth,
- maxNodes: max_nodes,
- sourceId,
- exact,
- }),
- );
- },
- cliHints: { name: 'code_blast', hidden: true },
-};
-
-const code_flow: Operation = {
- name: 'code_flow',
- description: 'When tracing how a request flows through the codebase from entry point to side effect (DB write, HTTP call, file I/O), run code_flow from the entry point. Returns ordered execution chain with terminal-node tags. Returns: same envelope as code_blast plus terminal_nodes: [{symbol, sink_kind}] where sink_kind ∈ "db_call"|"http_call"|"file_io"|"process_exec"|"unknown".',
- params: {
- entry_point: { type: 'string', required: true, description: 'Entry-point symbol name (bare or qualified)' },
- depth: { type: 'number', description: 'Hop cap (default 8, max 12)' },
- max_nodes: { type: 'number', description: 'Result-set cap (default 200)' },
- exact: { type: 'boolean', description: 'Skip bare-name disambiguation' },
- source_id: { type: 'string', description: 'Source to traverse. Defaults to ctx.sourceId; federated clients with multiple granted sources must specify one.' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { runRecursiveWalk } = await import('./code-intel/recursive-walk.ts');
- const { getCachedOrCompute } = await import('./code-intel/traversal-cache.ts');
- const symbol = p.entry_point as string;
- const depth = Math.min((p.depth as number) ?? 8, 12);
- const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200);
- const exact = (p.exact as boolean) ?? false;
- // Single trust+grant resolver (see code_blast).
- const { sourceId: scopedSourceId } = resolveCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
- const sourceId = scopedSourceId ?? ctx.sourceId;
- return getCachedOrCompute(
- ctx.engine,
- { symbol_qualified: symbol + ':flow', depth, source_id: sourceId },
- () => runRecursiveWalk(ctx.engine, symbol, {
- direction: 'callees',
- depth,
- maxNodes: max_nodes,
- sourceId,
- exact,
- }),
- );
- },
- cliHints: { name: 'code_flow', hidden: true },
-};
-
-// --- v0.34 W3b: code_traversal_cache admin op ---
-
-const code_traversal_cache_clear: Operation = {
- name: 'code_traversal_cache_clear',
- description: 'Clear cached code_blast / code_flow traversal results. Source-scoped by default; pass all_sources=true to wipe everything (D8 destructive-guard).',
- params: {
- source_id: { type: 'string', description: 'Source to clear. Required unless all_sources=true.' },
- all_sources: { type: 'boolean', description: 'Wipe cache across every source. Explicit opt-out of source-scoping.' },
- },
- mutating: true,
- scope: 'admin',
- localOnly: true,
- handler: async (ctx, p) => {
- // INTENTIONAL exemption from resolveRequestedScope: this is a localOnly
- // admin/destructive op with its own D8 all_sources guard. The read-side
- // trust+grant resolver does not apply here (no remote caller reaches it).
- const { clearTraversalCache } = await import('./code-intel/traversal-cache.ts');
- const sourceId = (p.source_id as string | undefined) ?? ctx.sourceId;
- const allSources = (p.all_sources as boolean) ?? false;
- if (ctx.dryRun) {
- return { dry_run: true, action: 'code_traversal_cache_clear', source_id: sourceId, all_sources: allSources };
- }
- const deleted = await clearTraversalCache(ctx.engine, {
- sourceId: allSources ? undefined : sourceId,
- allSources,
- });
- return { deleted, source_id: allSources ? null : sourceId, all_sources: allSources };
- },
- cliHints: { name: 'code_traversal_cache_clear', hidden: true },
-};
-
-// --- #3390: provider-agnostic embedding migration ---
-
-const migrate_embeddings: Operation = {
- name: 'migrate_embeddings',
- description: 'Re-embed the brain onto a different embedding provider/model (#3390): schema dimension transition, NULL-signature (#3391) invalidation, query-cache purge, resumable re-embed. Without yes=true returns the plan + cost estimate only. Local-only admin op; the primary surface is `gbrain migrate embeddings`.',
- params: {
- to: { type: 'string', required: true, description: 'Target provider:model (e.g. openai:text-embedding-3-small).' },
- dim: { type: 'number', description: "Target dimensions. Defaults to the provider recipe's declared width; required when the recipe declares none." },
- dry_run: { type: 'boolean', description: 'Plan + cost estimate only; change nothing.' },
- yes: { type: 'boolean', description: 'Confirm the re-embed spend + destructive schema change. Required for a live run.' },
- },
- mutating: true,
- scope: 'admin',
- localOnly: true,
- handler: async (ctx, p) => {
- // Belt-and-braces on top of localOnly (the get_recent_transcripts
- // pattern): a schema-rebuilding, money-spending op must never be
- // reachable from a remote transport even if a future dispatch path
- // forgets the localOnly filter.
- if (ctx.remote !== false) {
- throw new Error('migrate_embeddings is local-only. Run `gbrain migrate embeddings` on the host.');
- }
- const {
- planEmbeddingMigration, applyEmbeddingMigration, completeEmbeddingMigration,
- reconcilePageSignatures, migrationSignature,
- } = await import('./embedding-migration.ts');
- const to = p.to as string;
- const dim = p.dim as number | undefined;
- let fromModel: string | undefined;
- let fromDims: number | undefined;
- try {
- const { getEmbeddingModel, getEmbeddingDimensions } = await import('./ai/gateway.ts');
- fromModel = getEmbeddingModel();
- fromDims = getEmbeddingDimensions();
- } catch { /* gateway unconfigured — plan falls back to defaults */ }
- const plan = await planEmbeddingMigration(ctx.engine, {
- to,
- ...(dim !== undefined && { dim }),
- ...(fromModel !== undefined && { fromModel }),
- ...(fromDims !== undefined && { fromDims }),
- });
- if (ctx.dryRun || p.dry_run === true || p.yes !== true) {
- return { status: p.yes === true || p.dry_run === true ? 'planned' : 'needs_confirmation', plan };
- }
- const { persistEmbeddingFileConfig, probeTargetProvider } = await import('../commands/migrate-embeddings.ts');
- // Safety parity with the CLI path: probe the target provider BEFORE any
- // mutation. Without this, `yes:true` would drop the embedding column and
- // only then discover the key/model/dim is wrong.
- const probe = await probeTargetProvider(plan.to_model, plan.to_dims);
- if (!probe.ok) return { status: 'failed', reason: probe.message, plan };
- const applied = await applyEmbeddingMigration(ctx.engine, plan, {
- persistConfig: (m, d) => persistEmbeddingFileConfig(m, d),
- });
- if (applied.status !== 'applied') return { ...applied, plan };
- const { runEmbedCore } = await import('../commands/embed.ts');
- // singleFlight parity with the CLI path: takes the same per-source
- // embed-backfill lock so this can't race a queued embed-backfill job on
- // the NULL→non-NULL upsert (the TODOS:2299 class).
- const embedResult = await runEmbedCore(ctx.engine, {
- stale: true, catchUp: true, singleFlight: true, includeNullSignature: true, quiet: true,
- });
- // Stamp batch-boundary pages before probing for completion (see
- // reconcilePageSignatures — the embed loop's all-or-nothing stamp rule
- // skips any page split across two stale batches).
- const reconciled = await reconcilePageSignatures(ctx.engine, plan);
- const remaining = await ctx.engine.countStaleChunks({
- signature: migrationSignature(plan.to_model, plan.to_dims),
- includeNullSignature: true,
- });
- if (remaining === 0) await completeEmbeddingMigration(ctx.engine, plan);
- return {
- status: remaining === 0 ? 'completed' : 'incomplete',
- plan,
- embedded: embedResult.embedded,
- remaining,
- signatures_reconciled: reconciled,
- invalidated: applied.invalidated,
- schema_transitioned: applied.schema_transitioned,
- cache_cleared: applied.cache_cleared,
- };
- },
- cliHints: { name: 'migrate-embeddings', hidden: true },
-};
-
-// --- v0.36 Phase 2: search_by_image (image-as-query) ---
-
-const search_by_image: Operation = {
- name: 'search_by_image',
- description:
- 'v0.36 cross-modal Phase 2: image-as-query retrieval. Accepts a local path (CLI), data: URI, or http(s):// URL ' +
- '(SSRF-defended). Returns visually-similar image chunks plus any OCR text they carry. Optional `query` text ' +
- 'refinement merges via weighted RRF (D13 hybrid intersect). True image→full-text-knowledge requires Phase 3 ' +
- '(`gbrain reindex --multimodal` + `search.unified_multimodal: true`).',
- params: {
- image_path: { type: 'string', description: 'Absolute path to image (local CLI callers only — rejected for remote MCP per D18).' },
- image_url: { type: 'string', description: 'http(s):// URL to image. SSRF-defended; max 3 redirect hops; 10MB cap.' },
- image_data: { type: 'string', description: 'Base64-encoded image bytes (preferred for remote MCP callers). PNG/JPEG/WebP only.' },
- image_mime: { type: 'string', description: 'Optional MIME hint when ambiguous. Magic-byte sniff is authoritative.' },
- query: { type: 'string', description: 'Optional text refinement; runs hybrid intersect via D13 weighted RRF.' },
- limit: { type: 'number', description: 'Max results (default 20)' },
- offset: { type: 'number', description: 'Skip first N results (for pagination)' },
- source_id: { type: 'string', description: "Scope to a single source. Defaults to ctx.sourceId. '__all__' spans every source for trusted local callers, your granted sources for remote callers." },
- },
- scope: 'read',
- // NOT localOnly: remote MCP callers can pass image_url or image_data
- // (subject to D18 image_path ban + D12 size cap + D23-#6 spend cap).
- handler: async (ctx, p) => {
- const imagePath = p.image_path as string | undefined;
- const imageUrl = p.image_url as string | undefined;
- const imageData = p.image_data as string | undefined;
- const imageMime = (p.image_mime as string) || undefined;
- const queryRefinement = p.query as string | undefined;
- const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
-
- // D18 P0 — remote callers cannot pass image_path. Rejecting at handler
- // entry, before any file I/O fires. validateParams catches it too at the
- // dispatch layer; this is defense-in-depth.
- if (ctx.remote === true && imagePath) {
- throw new Error(
- 'permission_denied: image_path is not permitted for remote callers (D18). ' +
- 'Use image_url or image_data instead.',
- );
- }
-
- if (!imagePath && !imageUrl && !imageData) {
- throw new Error('search_by_image requires one of: image_path, image_url, image_data');
- }
- if ([imagePath, imageUrl, imageData].filter(Boolean).length > 1) {
- throw new Error('search_by_image accepts only one of: image_path, image_url, image_data');
- }
-
- // D23-#6 — remote OAuth clients are charged through the durable
- // reserve-then-settle ledger below. Local CLI callers bypass the cap
- // (clientId="") because they use their own provider credentials.
- const clientId = (ctx.remote === true ? (ctx.auth?.clientId ?? '') : '');
-
- // Resolve image bytes via the SSRF-defended loader. For remote callers,
- // tighter byte cap.
- const remoteCap = await getRemoteMaxBytes(ctx.engine);
- const localCap = await getLocalMaxBytes(ctx.engine);
- const cap = ctx.remote === true ? remoteCap : localCap;
- const { loadImageInput } = await import('./search/image-loader.ts');
- const loaded = await loadImageInput(
- (imagePath ?? imageUrl ?? `data:${imageMime ?? 'image/png'};base64,${imageData}`)!,
- { maxBytes: cap },
- );
-
- // Resolve source-scope through the single trust+grant resolver. Pre-fix
- // this branch computed resolvedSourceId then spread sourceScopeOpts(ctx)
- // after it (double-application: the spread silently won, and `__all__`
- // didn't opt out for local callers with ctx.sourceId set). One resolver,
- // one spread — `__all__` spans the brain only for trusted local callers.
- const imageSourceScope = resolveRequestedScope(ctx, sourceIdParam);
-
- // Reserve immediately before entering the paid search routine. Validation,
- // image loading, and scope resolution happen first so known no-charge
- // failures do not strand reservations. An ambiguous provider failure is
- // settled at this operation's fixed-price upper bound below; pessimistic
- // accounting is safer than reopening daily headroom after the TTL.
- let spendReservationId: string | null = null;
- let estimatedSpendCents = 0;
- if (clientId) {
- const { VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS } = await import('./spend-log.ts');
- const { reserve } = await import('./minions/budget-meter.ts');
- const calls = 1 + (queryRefinement ? 1 : 0);
- estimatedSpendCents = VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS * calls;
- const budgetUsd = await getDailyImageBudgetUsd(ctx.engine);
- const reservation = await reserve(ctx.engine, {
- clientId,
- estimatedCents: estimatedSpendCents,
- capCents: budgetUsd * 100,
- provider: 'voyage',
- model: 'voyage-multimodal-3',
- });
- spendReservationId = reservation.reservationId;
- }
-
- const { searchByImage } = await import('./search/by-image.ts');
- let results: Awaited<ReturnType<typeof searchByImage>>;
- try {
- results = await searchByImage(
- ctx.engine,
- { base64: loaded.base64, mime: loaded.contentType },
- {
- limit: (p.limit as number) || 20,
- offset: (p.offset as number) || 0,
- query: queryRefinement,
- ...imageSourceScope,
- },
- );
- } catch (providerError) {
- if (spendReservationId) {
- const { settle } = await import('./minions/budget-meter.ts');
- try {
- await settle(
- ctx.engine,
- spendReservationId,
- estimatedSpendCents,
- 'search_by_image_error_pessimistic',
- ctx.auth?.clientName ?? null,
- );
- } catch (accountingError) {
- throw new AggregateError(
- [providerError, accountingError],
- 'search_by_image provider call failed and its spend reservation could not be settled',
- );
- }
- }
- throw providerError;
- }
-
- // Settlement and the spend-log mirror commit in one transaction. A
- // database/accounting failure blocks the response and leaves the pending
- // reservation holding headroom rather than returning an unmetered success.
- if (spendReservationId) {
- const { settle } = await import('./minions/budget-meter.ts');
- await settle(
- ctx.engine,
- spendReservationId,
- estimatedSpendCents,
- 'search_by_image',
- ctx.auth?.clientName ?? null,
- );
- }
-
- return results;
- },
- cliHints: { name: 'search-by-image' },
-};
-
-async function getDailyImageBudgetUsd(engine: BrainEngine): Promise<number> {
- try {
- const v = await engine.getConfig('search.image_query.daily_budget_usd_per_client');
- if (v == null) return 5; // default $5
- const n = parseFloat(v);
- return Number.isFinite(n) && n > 0 ? n : 5;
- } catch {
- return 5;
- }
-}
-
-async function getLocalMaxBytes(engine: BrainEngine): Promise<number> {
- try {
- const v = await engine.getConfig('search.image_query.max_bytes');
- if (v == null) return 10 * 1024 * 1024;
- const n = parseInt(v, 10);
- return Number.isFinite(n) && n > 0 ? n : 10 * 1024 * 1024;
- } catch {
- return 10 * 1024 * 1024;
- }
-}
-
-async function getRemoteMaxBytes(engine: BrainEngine): Promise<number> {
- try {
- const v = await engine.getConfig('search.image_query.remote_max_bytes');
- if (v == null) return 2 * 1024 * 1024;
- const n = parseInt(v, 10);
- return Number.isFinite(n) && n > 0 ? n : 2 * 1024 * 1024;
- } catch {
- return 2 * 1024 * 1024;
- }
-}
-
-// --- Exports ---
-
-// ──────────────────────────────────────────────────────────────────────
-// v0.40.6.0 Schema Cathedral v3 — 9 new MCP ops for the agent on-ramp.
-//
-// Read ops (scope: read; NOT localOnly) — any read-scope OAuth client.
-// Write ops (scope: admin; NOT localOnly per D2) — admin-scope client
-// (your OpenClaw and similar remote agents) can author schema packs
-// remotely. Audit log captures actor=mcp:<clientId8> on every mutation
-// (see src/core/schema-pack/mutate-audit.ts privacy posture per D20).
-//
-// Per-call schema_pack opt STAYS rejected for remote callers — that
-// trust boundary is enforced by op-trust-gate.ts and is separate from
-// the localOnly posture (R2 regression preserved).
-// ──────────────────────────────────────────────────────────────────────
-
-const get_active_schema_pack: Operation = {
- name: 'get_active_schema_pack',
- description: 'v0.40.6.0: cheap identity packet for the active schema pack. Returns {pack_name, version, sha8, page_types_count, link_types_count, primitive_summary, source_tier}. Useful for agents to know which pack they are operating against without paying full manifest load cost.',
- params: {},
- scope: 'read',
- handler: async (ctx) => {
- const { loadActivePack, resolveActivePackNameOnly } = await import('./schema-pack/load-active.ts');
- const { loadConfig } = await import('./config.ts');
- const cfg = loadConfig();
- const sourceOpts: Record<string, unknown> = {};
- if (ctx.sourceId) sourceOpts.sourceId = ctx.sourceId;
- const resolution = resolveActivePackNameOnly({ cfg, remote: ctx.remote ?? true, ...sourceOpts });
- const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, ...sourceOpts });
- const primitiveSummary: Record<string, number> = {};
- for (const t of pack.manifest.page_types) {
- primitiveSummary[t.primitive] = (primitiveSummary[t.primitive] ?? 0) + 1;
- }
- return {
- pack_name: pack.manifest.name,
- version: pack.manifest.version,
- sha8: pack.manifest_sha8,
- identity: pack.identity,
- page_types_count: pack.manifest.page_types.length,
- link_types_count: pack.manifest.link_types.length,
- primitive_summary: primitiveSummary,
- source_tier: resolution.source,
- };
- },
-};
-
-const list_schema_packs: Operation = {
- name: 'list_schema_packs',
- description: 'v0.40.6.0: list installed schema packs (bundled + user-installed). Returns {bundled: string[], installed: string[]}. Read-only directory listing.',
- params: {},
- scope: 'read',
- handler: async (_ctx) => {
- const { existsSync, readdirSync } = await import('node:fs');
- const { join } = await import('node:path');
- const { gbrainPath } = await import('./config.ts');
- const { BUNDLED_PACK_NAMES } = await import('./schema-pack/bundled.ts');
- const bundled = [...BUNDLED_PACK_NAMES];
- const installedDir = gbrainPath('schema-packs');
- const installed: string[] = [];
- if (existsSync(installedDir)) {
- for (const entry of readdirSync(installedDir)) {
- const candidates = ['pack.yaml', 'pack.yml', 'pack.json'];
- for (const c of candidates) {
- if (existsSync(join(installedDir, entry, c))) { installed.push(entry); break; }
- }
- }
- }
- return { bundled, installed };
- },
-};
-
-const schema_stats: Operation = {
- name: 'schema_stats',
- description: 'v0.40.6.0: per-type page counts + typed-coverage from the DB. Returns {schema_version:1, pack_identity, aggregate, per_source, dead_prefixes}. Multi-source aware via ctx.sourceId/allowedSources.',
- params: {},
- scope: 'read',
- handler: async (ctx) => {
- const { runStatsCore } = await import('./schema-pack/stats.ts');
- const scope = sourceScopeOpts(ctx);
- const opts: { sourceId?: string; sourceIds?: string[] } = {};
- if (scope.sourceIds && scope.sourceIds.length > 0) opts.sourceIds = scope.sourceIds;
- else if (scope.sourceId) opts.sourceId = scope.sourceId;
- return runStatsCore(ctx, opts);
- },
-};
-
-const schema_lint: Operation = {
- name: 'schema_lint',
- description: 'v0.40.6.0: lint the active (or named) schema pack. File-plane rules only over MCP — the with_db option is rejected for remote callers (DB-aware rules require local CLI). Returns {ok, errors, warnings} structured report.',
- params: {
- pack: { type: 'string', description: 'Pack name (default: active pack)' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { runAllLintRules } = await import('./schema-pack/lint-rules.ts');
- const { loadActivePack } = await import('./schema-pack/load-active.ts');
- const { loadConfig, gbrainPath } = await import('./config.ts');
- const { existsSync } = await import('node:fs');
- const { join } = await import('node:path');
- const cfg = loadConfig();
- let manifest;
- if (p.pack) {
- // Locate by name without trust-gating per-call schema_pack opt
- // (that's a separate axis — this is just file lookup).
- const packName = p.pack as string;
- const candidates = ['pack.yaml', 'pack.yml', 'pack.json'];
- let path: string | null = null;
- for (const c of candidates) {
- const candidate = join(gbrainPath('schema-packs', packName), c);
- if (existsSync(candidate)) { path = candidate; break; }
- }
- if (!path) return { error: 'pack_not_found', pack: packName };
- const { loadPackFromFile: loader } = await import('./schema-pack/loader.ts');
- manifest = loader(path);
- } else {
- const resolved = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
- manifest = resolved.manifest;
- }
- // File-plane only over MCP; the engine-aware --with-db opt-in is
- // CLI-only (Phase 5 wiring). MCP callers get the 9 file-plane rules.
- return await runAllLintRules(manifest);
- },
-};
-
-const schema_graph: Operation = {
- name: 'schema_graph',
- description: 'v0.40.6.0: schema pack graph as JSON edges. Returns {nodes: [{name, primitive}], edges: [{from, verb, to}]} derived from link_types inference + frontmatter_links.',
- params: {},
- scope: 'read',
- handler: async (ctx) => {
- const { loadActivePack } = await import('./schema-pack/load-active.ts');
- const { loadConfig } = await import('./config.ts');
- const cfg = loadConfig();
- const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
- const nodes = pack.manifest.page_types.map((t) => ({ name: t.name, primitive: t.primitive }));
- const edges: Array<{ from: string; verb: string; to: string }> = [];
- for (const lt of pack.manifest.link_types) {
- if (lt.inference?.page_type) {
- edges.push({
- from: lt.inference.page_type,
- verb: lt.name,
- to: lt.inference.target_type ?? '*',
- });
- }
- }
- for (const fl of pack.manifest.frontmatter_links) {
- edges.push({ from: fl.page_type, verb: fl.link_type, to: '*' });
- }
- return { schema_version: 1, pack: pack.manifest.name, nodes, edges };
- },
-};
-
-const schema_explain_type: Operation = {
- name: 'schema_explain_type',
- description: 'v0.40.6.0: resolved settings for a single page_type in the active pack. Returns {pack, type, primitive, path_prefixes, aliases, extractable, expert_routing}.',
- params: {
- type: { type: 'string', required: true, description: 'Page type name to explain' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const { loadActivePack } = await import('./schema-pack/load-active.ts');
- const { loadConfig } = await import('./config.ts');
- const cfg = loadConfig();
- const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
- const found = pack.manifest.page_types.find((t) => t.name === p.type);
- if (!found) return { error: 'type_not_found', type: p.type as string, pack: pack.manifest.name };
- return { schema_version: 1, pack: pack.manifest.name, type: found };
- },
-};
-
-const schema_review_orphans: Operation = {
- name: 'schema_review_orphans',
- description: 'v0.40.6.0: list pages with no active-pack type match. Returns {orphan_count, orphans: [{slug, source_id}]}.',
- params: {
- limit: { type: 'number', description: 'Max orphans to return (default 100)' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const limit = Math.max(1, Math.min(10000, (p.limit as number) ?? 100));
- const scope = sourceScopeOpts(ctx);
- let where = `WHERE deleted_at IS NULL AND (type IS NULL OR type = '')`;
- const params: unknown[] = [];
- if (scope.sourceIds && scope.sourceIds.length > 0) {
- where += ` AND source_id = ANY($1::text[])`;
- params.push(scope.sourceIds);
- } else if (scope.sourceId) {
- where += ` AND source_id = $1`;
- params.push(scope.sourceId);
- }
- try {
- const rows = await ctx.engine.executeRaw<{ slug: string; source_id: string }>(
- `SELECT slug, COALESCE(source_id, 'default') AS source_id FROM pages ${where} ORDER BY source_id, slug LIMIT ${limit}`,
- params,
- );
- return {
- schema_version: 1,
- orphan_count: rows.length,
- orphans: rows.map((r) => ({ slug: r.slug, source_id: r.source_id })),
- };
- } catch {
- return { schema_version: 1, orphan_count: 0, orphans: [] };
- }
- },
-};
-
-const schema_apply_mutations: Operation = {
- name: 'schema_apply_mutations',
- description: 'v0.40.7.0: batched schema pack mutation. ATOMIC: every mutation is validated against an in-memory manifest first, and the pack file is written to disk at most once, after the FULL batch has proven valid — so a failure at any point leaves the pack file byte-identical to its pre-batch state (never a partial write). Audit log records one batch_id. Admin scope; NOT localOnly so remote agents (your OpenClaw, etc.) can author packs over normal MCP. Mutation shape per ApplyMutationsRequest type — supports add_type / remove_type / update_type / add_alias / remove_alias / add_prefix / remove_prefix / add_link_type / remove_link_type / set_extractable / set_expert_routing.',
- params: {
- pack: { type: 'string', required: true, description: 'Pack to mutate (must not be bundled)' },
- mutations: {
- type: 'array',
- required: true,
- description: 'Array of {op, ...args} mutation records to apply atomically',
- items: { type: 'object' },
- },
- force: { type: 'boolean', description: 'Steal stale per-pack lock' },
- },
- scope: 'admin',
- mutating: true,
- handler: async (ctx, p) => {
- const pack = p.pack as string;
- const mutations = p.mutations as Array<{ op: string; [k: string]: unknown }>;
- const force = p.force === true;
- if (!Array.isArray(mutations) || mutations.length === 0) {
- return { error: 'invalid_request', message: 'mutations must be a non-empty array' };
- }
- const batchId = `batch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
- const actor = ctx.auth?.clientId ? `mcp:${ctx.auth.clientId.slice(0, 8)}` : 'cli';
- const sourceId = ctx.sourceId; // codex C5: write-side scoping
- // `applyMutationsAtomic` (issue #2581) owns the lock + single read +
- // single write for the whole batch: every mutation is validated
- // in-memory first, and the pack file is written at most once, only
- // after the FULL batch checks out. That is what makes this actually
- // atomic (a failure at any index can never leave earlier mutations on
- // disk), vs. the old per-mutation-writes-as-it-goes shape.
- const { applyMutationsAtomic } = await import('./schema-pack/mutate.ts');
- try {
- const results = await applyMutationsAtomic(pack, mutations, {
- actor: actor as 'cli' | `mcp:${string}`,
- batchId,
- engine: ctx.engine,
- ...(sourceId ? { sourceId } : {}),
- ...(force ? { force: true } : {}),
- });
- return {
- schema_version: 1,
- pack,
- batch_id: batchId,
- mutations_applied: results.length,
- results,
- };
- } catch (e) {
- const code = (e as { code?: string }).code ?? 'UNKNOWN';
- const failedAtIndex = (e as { details?: { index?: number } }).details?.index;
- return {
- error: 'mutation_failed',
- code,
- message: (e as Error).message,
- batch_id: batchId,
- // Nothing was written to disk — applyMutationsAtomic only writes
- // once, after every mutation in the batch has validated cleanly.
- // (Pre-fix, this field was `partial_results` and listed mutations
- // that HAD already landed on disk, because the old implementation
- // wrote as it went — that shape is gone; a failed batch can no
- // longer imply partial application.)
- mutations_applied: 0,
- pack_unchanged: true,
- ...(failedAtIndex !== undefined ? { failed_at_index: failedAtIndex } : {}),
- };
- }
- },
-};
-
-const reload_schema_pack: Operation = {
- name: 'reload_schema_pack',
- description: 'v0.40.6.0: flush the in-process schema pack cache so the next loadActivePack re-reads from disk. Cascades through extends-chain (codex C6). Admin scope; NOT localOnly. Returns {invalidated: string[]}.',
- params: {
- pack: { type: 'string', description: 'Pack name to invalidate (omit to flush all)' },
- },
- scope: 'admin',
- mutating: false, // no DB writes
- handler: async (_ctx, p) => {
- const { invalidatePackCache } = await import('./schema-pack/registry.ts');
- return invalidatePackCache(p.pack as string | undefined);
- },
-};
-
-// v0.41.18.0 (A7 + T16, codex finding #5): MCP op for federated / thin-client
-// brain installs to drive `gbrain onboard --auto` over MCP. Admin scope
-// (NOT localOnly) so remote agents authenticated via OAuth can probe
-// brain health + submit auto-eligible remediation handlers.
-//
-// Critical security gate (codex #5): admin scope alone is NOT sufficient
-// to submit handlers in PROTECTED_JOB_NAMES (synthesize, patterns,
-// consolidate, extract-takes-from-pages, contextual_reindex_per_chunk).
-// Without this gate, an admin-scoped OAuth token would bypass the same
-// guard that `submit_job` enforces. The new NAMED scope
-// `run_protected_onboard` MUST be granted IN ADDITION TO admin for any
-// protected child handler to fire.
-//
-// Behavior:
-// - mode='check' (default): returns the OnboardReport JSON envelope,
-// never submits jobs. Admin scope sufficient.
-// - mode='auto': submits auto_apply tier. Admin + non-protected
-// handlers only.
-// - mode='auto-with-prompt': submits auto_apply + prompt_required tier.
-// Same protection check.
-//
-// Any LLM-bearing handler the plan would have submitted gets filtered out
-// unless the caller has run_protected_onboard. Filtered items appear in
-// the response with status='skipped_missing_scope' so the caller knows
-// what they would have gotten with the right grants.
-const run_onboard: Operation = {
- name: 'run_onboard',
- description: 'Probe brain health + optionally submit onboard remediations. Admin scope required. Protected handlers (LLM-bearing) require run_protected_onboard scope ADDITIONALLY.',
- params: {
- mode: { type: 'string', description: "'check' (default), 'auto', or 'auto-with-prompt'" },
- target_score: { type: 'number', description: 'Target brain_score (default 90)' },
- max_usd: { type: 'number', description: 'USD cap for autopilot path (required for auto modes)' },
- },
- mutating: true,
- scope: 'admin',
- handler: async (ctx, p) => {
- const mode = (typeof p.mode === 'string' ? p.mode : 'check') as 'check' | 'auto' | 'auto-with-prompt';
- const targetScore = typeof p.target_score === 'number' ? p.target_score : 90;
- const maxUsd = typeof p.max_usd === 'number' ? p.max_usd : undefined;
-
- const { computeRemediationPlan, runRemediation } = await import('./remediation/index.ts');
- const { runAllOnboardChecks } = await import('./onboard/checks.ts');
- const { buildOnboardReport } = await import('./onboard/render.ts');
-
- // Per A26: source-scope via sourceScopeOpts(ctx). The recommendation
- // planner is brain-wide today; future extension can scope by reading
- // ctx.sourceId / ctx.auth.allowedSources for per-source plans.
-
- let extraRemediations: import('./remediation-step.ts').RemediationStep[] = [];
- try {
- const checkResults = await runAllOnboardChecks(ctx.engine);
- extraRemediations = checkResults.flatMap((r) => r.remediations);
- } catch {
- // Fail-open per A19 — return plan without extras rather than error.
- }
-
- // 'check' mode: just return the plan + JSON envelope. No submission.
- if (mode === 'check') {
- const plan = await computeRemediationPlan(ctx.engine, { targetScore, extraRemediations });
- const report = buildOnboardReport(plan);
- return report;
- }
-
- // 'auto' and 'auto-with-prompt' modes: require --max-usd per A12 + A20
- // safety posture (cron-safety; refuses surprise spend).
- if (maxUsd === undefined) {
- throw new OperationError('invalid_params', `mode='${mode}' requires max_usd (cron-safety cap)`);
- }
-
- // Critical T16 + codex #5 security gate: filter out PROTECTED_JOB_NAMES
- // unless the caller has the run_protected_onboard scope IN ADDITION
- // to admin. Admin alone is insufficient.
- const grantedScopes = ctx.auth?.scopes ?? [];
- const canRunProtected = grantedScopes.includes('run_protected_onboard');
- const { isProtectedJobName } = await import('./minions/protected-names.ts');
-
- const skippedMissingScope: Array<{ id: string; job: string; reason: string }> = [];
- const allowedExtras = extraRemediations.filter((r) => {
- if (canRunProtected) return true;
- if (isProtectedJobName(r.job)) {
- skippedMissingScope.push({ id: r.id, job: r.job, reason: 'requires run_protected_onboard scope' });
- return false;
- }
- return true;
- });
-
- // Run remediation with filtered extras. Hooks emit nothing — MCP
- // returns structured result. Per A23 client_id attribution: stamp
- // job.data.client_id on each submission so the spend chain (T10)
- // attributes correctly. The library doesn't do this today; the
- // upstream submit-side gating in submit_job filters protected names
- // for ctx.remote !== false callers, so even if MCP run_onboard had a
- // typo, the underlying queue.add would reject. Defense-in-depth.
- const result = await runRemediation(
- ctx.engine,
- { targetScore, maxUsd, extraRemediations: allowedExtras },
- {},
- );
-
- return {
- ...result,
- skipped_missing_scope: skippedMissingScope,
- };
- },
-};
-
-// v0.41.20.0 SkillOpt — MCP exposure (admin scope + per-skill allowlist
-// via the resolver inside the handler). Designed for trusted admin tokens
-// that want to drive optimization remotely; the same trust gates as the
-// CLI fire (working tree, install path, lock acquisition, bundled-skill
-// guard). NOT localOnly so admin HTTP MCP clients can invoke.
-const run_skillopt: Operation = {
- name: 'run_skillopt',
- description: 'Run SkillOpt against a single skill. Admin scope; mutating; rate-limited per-skill via DB lock. See gbrain skillopt CLI for the full flag surface.',
- params: {
- skill_name: { type: 'string', required: true, description: 'Kebab-case skill name (resolves to skills/<name>/SKILL.md)' },
- benchmark_path: { type: 'string', description: 'Absolute path to benchmark JSONL; defaults to skills/<name>/skillopt-benchmark.jsonl' },
- epochs: { type: 'number', description: 'Default 4' },
- batch_size: { type: 'number', description: 'Default 8' },
- lr: { type: 'number', description: 'Default 4' },
- max_cost_usd: { type: 'number', description: 'Default 5.00' },
- no_mutate: { type: 'boolean', description: 'Write proposed.md without replacing SKILL.md' },
- allow_mutate_bundled: { type: 'boolean', description: 'Required to mutate bundled skills' },
- held_out_path: { type: 'string', description: 'Path to a held-out test set (JSONL). REQUIRED (>=5 rows) to mutate a bundled skill in place — otherwise the run hard-refuses. Remote callers: must resolve within the skills directory.' },
- dry_run: { type: 'boolean', description: 'Cost preview, no LLM calls' },
- },
- mutating: true,
- scope: 'admin',
- localOnly: false,
- handler: async (ctx, p) => {
- // SECURITY: skill_name is joined into filesystem paths (SKILL.md, default
- // benchmark, checkpoint, history, best.md, proposed.md). A traversal-shaped
- // name (`../`, absolute) would escape the skills dir even WITH the
- // caller-supplied-path confinement below. Validate kebab-only up front so
- // every derived path is contained by construction. Applies to all callers.
- const skillNameRaw = (p.skill_name as string) ?? '';
- if (!/^[a-z0-9][a-z0-9-]*$/.test(skillNameRaw)) {
- throw new OperationError(`run_skillopt: skill_name must be kebab-case (matching ^[a-z0-9][a-z0-9-]*$); got '${skillNameRaw}'`, 'invalid_params');
- }
- if (ctx.remote !== false) {
- // Remote: enforce per-skill allowlist read from config.
- // `skillopt.allowed_skills` is a JSON-array config of skill names
- // an admin-scoped OAuth client may target. Default DENY-ALL: when
- // unset, MCP cannot drive skillopt on any skill.
- const allowedRaw = await ctx.engine.getConfig('skillopt.allowed_skills');
- let allowed: string[] = [];
- try {
- if (allowedRaw) allowed = JSON.parse(allowedRaw) as string[];
- } catch { /* fall through to deny */ }
- const skillName = (p.skill_name as string) ?? '';
- if (!allowed.includes(skillName)) {
- throw new OperationError(`run_skillopt: skill '${skillName}' is not in skillopt.allowed_skills allowlist (default deny-all for remote callers)`, 'permission_denied');
- }
- }
- const { runSkillOpt } = await import('./skillopt/orchestrator.ts');
- const { autoDetectSkillsDirReadOnly } = await import('./repo-root.ts');
- const { resolveModel } = await import('./model-config.ts');
- const detected = autoDetectSkillsDirReadOnly(process.cwd());
- const skillsDir = detected.dir;
- if (!skillsDir) {
- throw new OperationError('run_skillopt: skills directory not found', 'config_error');
- }
- const optimizerModel = await resolveModel(ctx.engine, { tier: 'deep', fallback: 'anthropic:claude-opus-4-7' });
- const targetModel = await resolveModel(ctx.engine, { tier: 'subagent', fallback: 'anthropic:claude-sonnet-4-6' });
- const judgeModel = await resolveModel(ctx.engine, { tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' });
- const skillName = p.skill_name as string;
- const benchmarkPath = (p.benchmark_path as string) ??
- `${skillsDir}/${skillName}/skillopt-benchmark.jsonl`;
- const heldOutPath = p.held_out_path as string | undefined;
- // SECURITY: remote callers must NOT be able to point benchmark/held-out at
- // arbitrary host files (loadBenchmark → fs.readFileSync would otherwise be an
- // arbitrary-read + existence oracle). Confine any caller-supplied path to the
- // skills directory. Local CLI callers (ctx.remote === false) are unconfined.
- if (ctx.remote !== false) {
- const nodePath = await import('node:path');
- const nodeFs = await import('node:fs');
- const rootReal = (() => {
- try { return nodeFs.realpathSync(skillsDir); } catch { return nodePath.resolve(skillsDir); }
- })();
- const confine = (label: string, candidate: string | undefined): void => {
- if (!candidate) return;
- const resolved = nodePath.resolve(candidate);
- let real = resolved;
- try {
- real = nodeFs.realpathSync(resolved);
- } catch {
- // Not yet present: canonicalize the nearest existing ancestor so a
- // legit in-dir path under a symlinked skillsDir (e.g. macOS /tmp ->
- // /private/tmp, Conductor worktrees) isn't wrongly rejected.
- try { real = nodePath.join(nodeFs.realpathSync(nodePath.dirname(resolved)), nodePath.basename(resolved)); }
- catch { /* parent also missing; fall back to resolved form */ }
- }
- if (real !== rootReal && !real.startsWith(rootReal + nodePath.sep)) {
- throw new OperationError(`run_skillopt: ${label} must resolve within the skills directory for remote callers`, 'permission_denied');
- }
- };
- confine('benchmark_path', p.benchmark_path as string | undefined);
- confine('held_out_path', heldOutPath);
- }
- const result = await runSkillOpt({
- engine: ctx.engine,
- skillName,
- skillsDir,
- benchmarkPath,
- epochs: (p.epochs as number) ?? 4,
- batchSize: (p.batch_size as number) ?? 8,
- lr: (p.lr as number) ?? 4,
- lrSchedule: 'cosine',
- split: [4, 1, 5],
- optimizerModel,
- targetModel,
- judgeModel,
- mode: 'patch',
- dryRun: (p.dry_run as boolean) === true,
- noMutate: (p.no_mutate as boolean) === true,
- allowMutateBundled: (p.allow_mutate_bundled as boolean) === true,
- bootstrapReviewed: false,
- ...(heldOutPath ? { heldOutPath } : {}),
- json: true,
- maxCostUsd: (p.max_cost_usd as number) ?? 5.0,
- maxRuntimeMin: 30,
- force: false,
- });
- return {
- outcome: result.outcome,
- receipt: result.receipt,
- mutated_skill_file: result.mutatedSkillFile,
- proposed_path: result.proposedPath,
- };
- },
-};
-
-// ── v0.42.x — Life Chronicle (#2390) timeline read ops ───────────────────
-// CLI names avoid the existing `timeline` (get_timeline, a page's own timeline):
-// `gbrain day <date>` / `gbrain since <date>` / `gbrain last-seen <entity>`.
-// All route through sourceScopeOpts(ctx) so reads honor source isolation.
-const chronicle_day: Operation = {
- name: 'chronicle_day',
- description:
- 'Life Chronicle: events + timeline entries on a given day (or its ISO week when week=true), ' +
- "ordered chronologically; each row backlinks to its depth page. Distinct from `get_timeline`/" +
- "`gbrain timeline <slug>`, which shows ONE page's timeline. CLI: `gbrain day <date>`.",
- scope: 'read',
- params: {
- date: { type: 'string', required: true, description: 'Day as YYYY-MM-DD.' },
- week: { type: 'boolean', description: 'Expand to the ISO week (Mon–Sun) containing the date.' },
- limit: { type: 'number', description: 'Max rows (default 200).' },
- narrative: { type: 'boolean', description: 'Also return a prose day-by-day narrative.' },
- },
- handler: async (ctx, p) => {
- const rows = await ctx.engine.getTimelineForDate(String(p.date), {
- week: p.week === true,
- limit: typeof p.limit === 'number' ? p.limit : undefined,
- ...sourceScopeOpts(ctx),
- });
- if (p.narrative === true) {
- const { renderTimelineNarrative } = await import('./chronicle/narrative.ts');
- return { date: String(p.date), narrative: renderTimelineNarrative(rows), events: rows };
- }
- return rows;
- },
- cliHints: { name: 'day', positional: ['date'] },
-};
-
-const chronicle_on_this_day: Operation = {
- name: 'chronicle_on_this_day',
- description:
- 'Life Chronicle: events from the same calendar day in PRIOR years ("on this day"). ' +
- 'CLI: `gbrain on-this-day [--date YYYY-MM-DD]`.',
- scope: 'read',
- params: {
- date: { type: 'string', description: 'Anchor day YYYY-MM-DD (default today); matches its month-day in prior years.' },
- limit: { type: 'number', description: 'Max rows (default 50).' },
- },
- handler: async (ctx, p) => ctx.engine.getOnThisDay({
- date: typeof p.date === 'string' ? p.date : undefined,
- limit: typeof p.limit === 'number' ? p.limit : undefined,
- ...sourceScopeOpts(ctx),
- }),
- cliHints: { name: 'on-this-day' },
-};
-
-const chronicle_since: Operation = {
- name: 'chronicle_since',
- description:
- 'Life Chronicle: events + timeline entries on or after a date, optionally filtered by event kind. ' +
- 'CLI: `gbrain since <date> [--kind commitment]`.',
- scope: 'read',
- params: {
- date: { type: 'string', required: true, description: 'Lower-bound day as YYYY-MM-DD (inclusive).' },
- kind: { type: 'string', description: "Filter event projections by event.kind (e.g. 'commitment')." },
- limit: { type: 'number', description: 'Max rows (default 200).' },
- },
- handler: async (ctx, p) => {
- return ctx.engine.getSince(String(p.date), {
- kind: typeof p.kind === 'string' ? p.kind : undefined,
- limit: typeof p.limit === 'number' ? p.limit : undefined,
- ...sourceScopeOpts(ctx),
- });
- },
- cliHints: { name: 'since', positional: ['date'] },
-};
-
-const chronicle_last_seen: Operation = {
- name: 'chronicle_last_seen',
- description:
- "Life Chronicle: when an entity was last seen — its own timeline rows OR an event's `who`. " +
- 'Returns last_date, the event slug, and days_ago. CLI: `gbrain last-seen <entity-slug>`.',
- scope: 'read',
- params: {
- entity: { type: 'string', required: true, description: 'Entity page slug (e.g. people/sarah-chen).' },
- asof: { type: 'string', description: 'Reference day YYYY-MM-DD for days_ago (default today).' },
- },
- handler: async (ctx, p) => {
- return ctx.engine.getLastSeen(String(p.entity), {
- asof: typeof p.asof === 'string' ? p.asof : undefined,
- ...sourceScopeOpts(ctx),
- });
- },
- cliHints: { name: 'last-seen', positional: ['entity'] },
-};
-
-const ontology_get: Operation = {
- name: 'ontology_get',
- description:
- "Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` " +
- "(default now), with provenance + confidence + validity. CLI: `gbrain ontology <entity> [--asof YYYY-MM-DD]`.",
- scope: 'read',
- params: {
- entity: { type: 'string', required: true, description: 'Entity page slug (e.g. people/sarah-chen).' },
- asof: { type: 'string', description: 'Valid-time as-of day YYYY-MM-DD (time-travel; default now).' },
- min_confidence: { type: 'number', description: 'Only return observations at/above this confidence (0..1).' },
- include_quarantined: { type: 'boolean', description: 'Include quarantined novel dimensions (default false).' },
- },
- handler: async (ctx, p) => {
- const rows = await ctx.engine.getOntology(String(p.entity), {
- asof: typeof p.asof === 'string' ? p.asof : undefined,
- minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
- includeQuarantined: p.include_quarantined === true,
- ...sourceScopeOpts(ctx),
- });
- // Remote redaction: never surface diary-sourced ontology to untrusted callers.
- return ctx.remote !== false ? rows.filter((r) => !(r.source ?? '').startsWith('life/diary/')) : rows;
- },
- cliHints: { name: 'ontology', positional: ['entity'] },
-};
-
-const ontology_propose: Operation = {
- name: 'ontology_propose',
- description:
- 'Life Chronicle: record one ontology observation (entity has dimension=value), sourced + ' +
- 'confidence-weighted + bi-temporal. Idempotent on (entity,dimension,value,source). A new value ' +
- 'supersedes the prior; a backdated conflict is flagged not rewritten. CLI: `gbrain ontology-add <entity> <dimension> <value>`.',
- scope: 'write',
- mutating: true,
- params: {
- entity: { type: 'string', required: true, description: 'Entity page slug.' },
- dimension: { type: 'string', required: true, description: 'Dimension (e.g. role, risk_tolerance). Normalized at write.' },
- value: { type: 'string', required: true, description: 'The resolved value (e.g. advisor).' },
- confidence: { type: 'number', description: '0..1; default 0.7.' },
- source: { type: 'string', description: 'Provenance (page slug / uri); default "manual".' },
- valid_from: { type: 'string', description: 'ISO date the value became true (default: now).' },
- valid_to: { type: 'string', description: 'ISO date the value stopped being true (default: open).' },
- visibility: { type: 'string', enum: ['private', 'world'], description: 'Default private.' },
- },
- handler: async (ctx, p) => {
- // [ENG-8] Same unset-vs-explicit ladder as extract_facts: explicit
- // caller visibility wins; unset resolves facts.default_visibility.
- const { resolveVisibilityParam } = await import('./facts/visibility.ts');
- return ctx.engine.mergeOntologyFact({
- entitySlug: String(p.entity),
- dimension: String(p.dimension),
- value: String(p.value),
- confidence: typeof p.confidence === 'number' ? p.confidence : undefined,
- source: typeof p.source === 'string' && p.source ? p.source : 'manual',
- validFrom: typeof p.valid_from === 'string' ? p.valid_from : undefined,
- validTo: typeof p.valid_to === 'string' ? p.valid_to : undefined,
- visibility: await resolveVisibilityParam(ctx.engine, p.visibility),
- sourceId: ctx.sourceId,
- });
- },
- cliHints: { name: 'ontology-add', positional: ['entity', 'dimension', 'value'] },
-};
-
-const ontology_dimensions: Operation = {
- name: 'ontology_dimensions',
- description:
- 'Life Chronicle meta-ontology: which dimensions the brain tracks across entities, with ' +
- 'entity + observation counts. CLI: `gbrain ontology-dimensions`.',
- scope: 'read',
- params: {},
- handler: async (ctx) => ctx.engine.discoverOntologyDimensions(sourceScopeOpts(ctx)),
- cliHints: { name: 'ontology-dimensions' },
-};
-
-const ontology_conflicts: Operation = {
- name: 'ontology_conflicts',
- description:
- 'Life Chronicle: dimensions with ≥2 distinct current values from ≥2 provenances (genuine ' +
- 'disagreement, not temporal supersession). CLI: `gbrain ontology-contradictions`.',
- scope: 'read',
- params: {
- min_confidence: { type: 'number', description: 'Only consider observations at/above this confidence (0..1).' },
- },
- handler: async (ctx, p) => {
- const conflicts = await ctx.engine.findOntologyConflicts({
- minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
- ...sourceScopeOpts(ctx),
- });
- if (ctx.remote === false) return conflicts;
- // Remote: redact diary-sourced values; drop conflicts that no longer have
- // ≥2 distinct values once diary provenance is removed (no leak via conflicts).
- return conflicts
- .map((c) => ({ ...c, values: c.values.filter((v) => !(v.source ?? '').startsWith('life/diary/')) }))
- .filter((c) => new Set(c.values.map((v) => v.value)).size >= 2);
- },
- cliHints: { name: 'ontology-contradictions' },
-};
-
-const volunteer_chronicle: Operation = {
- name: 'volunteer_chronicle',
- description:
- 'Life Chronicle agent-orientation: the recent timeline (last N days) + the current ' +
- 'validity-resolved ontology for the named entities, in one zero-LLM payload, so an agent ' +
- 'orients before acting. Diary-sourced ontology is redacted for remote callers. ' +
- 'CLI: `gbrain orient [--days 7] [--entities people/a,people/b]`.',
- scope: 'read',
- params: {
- days: { type: 'number', description: 'Recent-timeline lookback in days (default 7).' },
- entities: { type: 'string', description: 'Comma-separated entity slugs to resolve ontology for.' },
- limit: { type: 'number', description: 'Max timeline rows (default 50).' },
- },
- handler: async (ctx, p) => {
- const { loadChronicleContext } = await import('./context/chronicle-context.ts');
- const entities = typeof p.entities === 'string'
- ? p.entities.split(',').map((s) => s.trim()).filter(Boolean)
- : undefined;
- return loadChronicleContext(ctx.engine, {
- days: typeof p.days === 'number' ? p.days : undefined,
- entities,
- limit: typeof p.limit === 'number' ? p.limit : undefined,
- remote: ctx.remote !== false,
- ...sourceScopeOpts(ctx),
- });
- },
- cliHints: { name: 'orient' },
-};
-
-const chronicle_backfill: Operation = {
- name: 'chronicle_backfill',
- description:
- 'Life Chronicle: sweep existing meeting/conversation/calendar pages into timeline events by ' +
- 'enqueuing chronicle_extract jobs (one per eligible page). --dry-run counts without enqueuing. ' +
- 'Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--limit N] [--dry-run]`.',
- scope: 'admin',
- mutating: true,
- localOnly: true,
- params: {
- since: { type: 'string', description: 'Only pages updated on/after this date (YYYY-MM-DD).' },
- limit: { type: 'number', description: 'Max pages per type to sweep (default 1000).' },
- dry_run: { type: 'boolean', description: 'Count eligible pages without enqueuing.' },
- },
- handler: async (ctx, p) => {
- const { isChronicleEligible } = await import('./chronicle/eligibility.ts');
- const TYPES = ['meeting', 'conversation', 'calendar-event'] as const;
- const limit = typeof p.limit === 'number' ? p.limit : 1000;
- const updated_after = typeof p.since === 'string' ? p.since : undefined;
- const dryRun = p.dry_run === true;
- const scope = sourceScopeOpts(ctx);
- type QueueLike = { add: (n: string, d: Record<string, unknown>) => Promise<unknown> };
- let queue: QueueLike | null = null;
- if (!dryRun) {
- const { MinionQueue } = await import('./minions/queue.ts');
- queue = new MinionQueue(ctx.engine) as unknown as QueueLike;
- }
- let scanned = 0, eligible = 0, enqueued = 0;
- const errors: { slug: string; error: string }[] = [];
- for (const type of TYPES) {
- const pages = await ctx.engine.listPages({ type, updated_after, limit, ...scope });
- for (const page of pages) {
- scanned++;
- const dreamGenerated = (page.frontmatter as Record<string, unknown> | undefined)?.dream_generated === true;
- const elig = isChronicleEligible({ type: page.type, slug: page.slug, body: page.compiled_truth, dreamGenerated });
- if (!elig.ok) continue;
- eligible++;
- if (dryRun || !queue) continue;
- try {
- await queue.add('chronicle_extract', { slug: page.slug, sourceId: ctx.sourceId ?? 'default' });
- enqueued++;
- } catch (e) {
- // Never swallow — surface per-page failures (the #2057 no-swallow pattern).
- errors.push({ slug: page.slug, error: e instanceof Error ? e.message : String(e) });
- }
- }
- }
- return { scanned, eligible, enqueued, dry_run: dryRun, errors };
- },
- cliHints: { name: 'chronicle-backfill' },
-};
-
-// ---------------------------------------------------------------------------
-// Extraction quarantine lane (issue #160)
-//
-// `extractAndEnrich` regex-extracts entity names from arbitrary text and
-// creates people/ + companies/ stub pages. These three ops are its ONLY
-// sanctioned surface:
-// - extract_entities — run extraction. Direct authoritative writes need
-// BOTH the trusted local CLI (ctx.remote === false)
-// AND the explicit --trusted-extraction flag;
-// everything else lands in the quarantine lane
-// (frontmatter provenance/status markers).
-// - extraction_pending — list unverified stubs awaiting review.
-// - extraction_review — promote (status → verified) or reject
-// (soft-delete) in batch. Owner-only (fail-closed
-// on ctx.remote): THIS surface never lets a remote
-// caller flip the status markers. Scope note: the
-// markers are ordinary frontmatter, so a caller who
-// already holds generic remote put_page write scope
-// can rewrite the page (markers included) — that
-// caller could equally author an unmarked people/
-// page directly, so the lane adds no privilege
-// there; put_page authz is its own boundary.
-// ---------------------------------------------------------------------------
-
-// Resource guards for extract_entities (#160 hardening): bound the work a
-// single remote write-scope call can trigger. ponytail: flat caps; make them
-// config knobs only if a real workload hits them.
-const MAX_EXTRACT_TEXT_CHARS = 200_000;
-const MAX_EXTRACT_ENTITIES = 200;
-
-const extract_entities: Operation = {
- name: 'extract_entities',
- description: 'Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI AND --trusted-extraction.',
- params: {
- text: { type: 'string', required: true, description: 'The text to extract entities from (email, transcript, pasted content, …). Max 200k characters — split larger inputs.' },
- source_slug: { type: 'string', required: true, description: 'Slug of the source page the text came from (used for backlinks + timeline attribution).' },
- trusted_extraction: { type: 'boolean', required: false, description: 'Local CLI only: write stubs directly as authoritative pages, skipping the quarantine lane. Ignored (always quarantined) for remote callers.' },
- },
- mutating: true,
- scope: 'write',
- handler: async (ctx, p) => {
- // Trust rule (#160, fail-closed like the CV6 provenance gate above):
- // `ctx.remote === false` is the ONLY truthy condition that can admit a
- // direct authoritative write, and even then the caller must opt in
- // explicitly. Remote/unset trust → quarantine lane, flag ignored.
- const trusted = ctx.remote === false && p.trusted_extraction === true;
- const text = p.text as string;
- // Resource guards: the greedy name regex on a huge paste can yield tens
- // of thousands of "entities", each costing several DB round-trips. Cap
- // input size loudly and entity count softly (surfaced as `truncated`).
- if (text.length > MAX_EXTRACT_TEXT_CHARS) {
- throw new OperationError(
- 'invalid_params',
- `extract_entities: text is ${text.length} chars (max ${MAX_EXTRACT_TEXT_CHARS}).`,
- 'Split the input and call extract_entities per section.',
- );
- }
- if (ctx.dryRun) return { dry_run: true, action: 'extract_entities', trusted };
- const { extractEntities, enrichEntities } = await import('./enrichment-service.ts');
- const found = extractEntities(text);
- const capped = found.slice(0, MAX_EXTRACT_ENTITIES);
- const results = await enrichEntities(
- ctx.engine,
- capped.map((e) => ({ entityName: e.name, entityType: e.type, context: e.context, sourceSlug: p.source_slug as string })),
- {
- trusted,
- ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}),
- // Pure local DB writes — no external API call to pace, so the
- // system-load capacity gate would only stall the caller.
- throttle: false,
- },
- );
- return {
- status: 'ok',
- trusted,
- quarantined: results.filter((r) => r.quarantined === true).length,
- count: results.length,
- entities_found: found.length,
- truncated: found.length > capped.length,
- entities: results,
- };
- },
- cliHints: { name: 'extract-entities' },
-};
-
-const extraction_pending: Operation = {
- name: 'extraction_pending',
- description: 'List unverified auto-extracted entity stubs awaiting owner review (the quarantine lane from extract_entities). Promote or reject them with extraction_review.',
- params: {
- limit: { type: 'number', required: false, description: 'Max rows (default 100, cap 500).' },
- offset: { type: 'number', required: false, description: 'Pagination offset.' },
- },
- scope: 'read',
- handler: async (ctx, p) => {
- const limit = Math.min(Math.max(Number(p.limit ?? 100) || 100, 1), 500);
- const offset = Math.max(Number(p.offset ?? 0) || 0, 0);
- // Read-side source isolation: route through sourceScopeOpts (federated
- // array > scalar > nothing), applied in SQL below.
- const scope = sourceScopeOpts(ctx);
- const params: unknown[] = [];
- let srcClause = '';
- if (scope.sourceIds && scope.sourceIds.length > 0) {
- params.push(scope.sourceIds);
- srcClause = `AND p.source_id = ANY($${params.length}::text[])`;
- } else if (scope.sourceId) {
- params.push(scope.sourceId);
- srcClause = `AND p.source_id = $${params.length}`;
- }
- params.push(limit, offset);
- const rows = await ctx.engine.executeRaw<{
- slug: string; title: string; type: string; source_id: string;
- extracted_from: string | null; created_at: string;
- }>(
- `SELECT p.slug, p.title, p.type, p.source_id,
- p.frontmatter ->> 'source' AS extracted_from,
- p.created_at::text AS created_at
- FROM pages p
- JOIN sources s ON s.id = p.source_id
- WHERE ${unverifiedExtractionFragment('p')}
- ${buildVisibilityClause('p', 's')}
- ${srcClause}
- ORDER BY p.created_at DESC
- LIMIT $${params.length - 1} OFFSET $${params.length}`,
- params,
- );
- return { count: rows.length, pending: rows };
- },
- cliHints: { name: 'extraction-pending' },
-};
-
-const extraction_review: Operation = {
- name: 'extraction_review',
- description: 'Promote or reject unverified auto-extracted entity stubs (batch). Promote flips `status` to verified (provenance kept for audit); reject soft-deletes the stub. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)',
- params: {
- action: { type: 'string', required: true, description: "'promote' or 'reject'." },
- slugs: { type: 'array', required: true, items: { type: 'string' }, description: 'Stub slugs to act on (batch).' },
- },
- mutating: true,
- scope: 'write',
- localOnly: true,
- handler: async (ctx, p) => {
- // The review decision IS the trust gate — if a remote caller could
- // promote, injected content could self-promote and the quarantine lane
- // would be decorative. Fail-closed: only strictly-local callers pass.
- if (ctx.remote !== false) {
- throw new OperationError(
- 'permission_denied',
- 'extraction_review is owner-only: promote/reject decisions must come from the trusted local CLI.',
- 'Run `gbrain extraction-review <promote|reject> --slugs ...` on the host machine.',
- );
- }
- const action = p.action as string;
- if (action !== 'promote' && action !== 'reject') {
- throw new OperationError('invalid_params', `extraction_review: action must be 'promote' or 'reject'; got '${action}'.`);
- }
- // CLI passes `--slugs a,b,c` as one string; MCP passes a real array.
- const slugs = Array.isArray(p.slugs)
- ? (p.slugs as string[])
- : typeof p.slugs === 'string'
- ? p.slugs.split(',').map((s) => s.trim()).filter(Boolean)
- : [];
- if (slugs.length === 0) {
- throw new OperationError('invalid_params', 'extraction_review: slugs must be a non-empty array (CLI: --slugs slug1,slug2).');
- }
- if (ctx.dryRun) return { dry_run: true, action: `extraction_review:${action}`, slugs };
- const results: Array<{ slug: string; status: string }> = [];
- for (const slug of slugs) {
- const page = await ctx.engine.getPage(slug, ctx.sourceId ? { sourceId: ctx.sourceId } : undefined);
- if (!page) {
- results.push({ slug, status: 'not_found' });
- continue;
- }
- if (!isUnverifiedExtraction(page.frontmatter)) {
- results.push({ slug, status: 'not_unverified' });
- continue;
- }
- if (action === 'promote') {
- // Frontmatter-only flip via a targeted JSONB merge — NOT putPage,
- // whose upsert would reset non-carried columns (page_kind →
- // 'markdown', content_hash, …) for a change that only touches one
- // frontmatter key. provenance stays 'auto-extracted' as the audit
- // trail of HOW the page came to exist; status → 'verified' records
- // the owner's call. jsonb_build_object binds as text (no
- // JSON.stringify-into-::jsonb hazard); identical on both engines.
- await ctx.engine.executeRaw(
- `UPDATE pages
- SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || jsonb_build_object($1::text, $2::text),
- updated_at = now()
- WHERE slug = $3 AND source_id = $4`,
- [EXTRACTION_STATUS_KEY, STATUS_VERIFIED, slug, page.source_id],
- );
- results.push({ slug, status: 'promoted' });
- } else {
- await ctx.engine.softDeletePage(slug, { sourceId: page.source_id });
- results.push({ slug, status: 'rejected' });
- }
- }
- return { status: 'ok', action, results };
- },
- cliHints: { name: 'extraction-review', positional: ['action'] },
-};
-
-// --- WP4 (T9): request_tools — discovery + pull-based per-client unlock ---
-
-/**
- * D14.5: per-client rate limit on the persist branch (~5 surface persists /
- * hour / client). Module-level token bucket (bounded LRU — attacker-chosen
- * client ids can't grow memory); `let` + reset seam so tests don't leak
- * bucket state across files.
- */
-let requestToolsPersistLimiter = new RateLimiter({ limit: 5, windowMs: 3_600_000, lruCap: 5_000 });
-
-/** Test seam: fresh persist-rate-limit buckets. */
-export function __resetRequestToolsPersistLimiterForTests(): void {
- requestToolsPersistLimiter = new RateLimiter({ limit: 5, windowMs: 3_600_000, lruCap: 5_000 });
-}
-
-/**
- * One-line catalog summary: the first sentence of an op description,
- * capped. Non-contractual rendering — full schemas come from the
- * `{tools: [...]}` branch.
- */
-function firstSentenceOf(description: string): string {
- const t = description.trim();
- const m = t.match(/^.*?[.!?](?=\s|$)/);
- const s = (m ? m[0] : t).trim();
- return s.length > 160 ? `${s.slice(0, 157)}...` : s;
-}
-
-/**
- * The set of ops VISIBLE to this caller (never leak hidden names — C8/
- * amendment 11 class): bounded by the server ceiling (ops above it can
- * never be served, so naming them would recreate listed-but-denied at the
- * persist level), minus localOnly on network transports (stdio and the
- * trusted local CLI keep them — D7), minus ops outside the caller's scopes
- * (agent-callable carve-out per FOV-4), minus bound-client-fenced ops (same
- * predicate as tools/list, ENG-3), minus publish-gated ops whose gate is off
- * (stdio and the trusted local CLI bypass gates — the D7 local-surface
- * posture, matching assertPublishEnabled's remote===false exemption; a
- * failed gate read hides the gated ops, fail-closed).
- */
-async function visibleOpsForCaller(
- ctx: OperationContext,
- ceiling: 'verbs' | 'starter' | 'full',
-): Promise<Operation[]> {
- const { filterOpsForSurface } = await import('../mcp/surface.ts');
- // Trusted local callers: the stdio pipe, or the local CLI (remote is
- // strictly false — the fail-closed trust marker). Both CAN call localOnly
- // and gated ops, so hiding them would make the catalog dishonest.
- const isLocal = ctx.transport === 'stdio' || ctx.remote === false;
-
- let gateDisabled: ReadonlySet<string> = new Set();
- if (!isLocal) {
- try {
- const { disabledOpsForPublishGates } = await import('../mcp/publish-gates.ts');
- gateDisabled = await disabledOpsForPublishGates(ctx.engine, ctx.config);
- } catch {
- // Fail-closed: if the resolver can't even load, hide every gated op.
- gateDisabled = new Set(operations.filter(o => o.publishGateKey).map(o => o.name));
- }
- }
-
- // Auth-less transports (stdio) and grandfathered legacy bearer tokens
- // (empty scopes array — that transport does no call-time scope checks
- // either) skip scope filtering: for them the whole surface IS callable,
- // so hiding by scope would make the catalog LESS honest, not more.
- const scopes = ctx.auth?.scopes && ctx.auth.scopes.length > 0 ? ctx.auth.scopes : null;
-
- return filterOpsForSurface(operations, ceiling).filter(op =>
- (isLocal || !op.localOnly)
- && (scopes === null
- || hasScope(scopes, op.scope ?? 'read')
- || (op.agentCallable === true && hasScope(scopes, 'agent')))
- && opAllowedForBoundClient(ctx.auth, op)
- && !gateDisabled.has(op.name),
- );
-}
-
-const request_tools: Operation = {
- name: 'request_tools',
- description:
- 'Discover this brain\'s tool catalog and optionally unlock a wider tool surface for your client. ' +
- 'No arguments → the catalog visible to YOUR credentials, grouped by area (tool names + one-line summaries). ' +
- '{tools: ["name", ...]} → full read-only schemas for the visible subset of those names (unknown/hidden names are silently omitted). ' +
- '{surface: "verbs"|"starter"|"full"} → persist that tool surface for this client (bounded by the server ceiling; denied when an operator pinned the surface; ~5 changes/hour), then re-issue tools/list to see the new catalog.',
- area: 'discovery',
- // FOV-4: callable by read OR agent scope — discovery for every token class.
- agentCallable: true,
- params: {
- tools: {
- type: 'array',
- items: { type: 'string', description: 'A tool name from the catalog.' },
- description: 'Fetch full read-only tool schemas for these names. Names outside your visible surface are silently omitted (D5).',
- },
- surface: {
- type: 'string',
- enum: ['verbs', 'starter', 'full'],
- description: 'Persist this tool surface for your client. Must not exceed the server ceiling; ignored surfaces stay available via no-arg discovery. Takes effect on your next tools/list.',
- },
- },
- scope: 'read',
- // D9: mutating because the persist branch writes oauth_clients.surface.
- // The bound-client fence exempts it via BOUND_CLIENT_META_OPS (see the
- // carve-out comment at opAllowedForBoundClient); the persist branch
- // self-enforces ceiling + operator lock + scopes + rate limit.
- mutating: true,
- handler: async (ctx, p) => {
- const { surfaceWiderThan, isMcpSurface } = await import('../mcp/surface.ts');
- // Unset ceiling (local CLI / direct dispatch) = 'full' — trusted-local
- // callers were never surface-bounded.
- const ceiling = ctx.surfaceCeiling ?? 'full';
-
- // D5: the three branches are mutually exclusive. {surface, tools}
- // together is ambiguous (persist vs descriptor fetch) — reject loudly
- // rather than silently persisting and ignoring the tools list.
- if (p.surface !== undefined && p.tools !== undefined) {
- throw new OperationError(
- 'invalid_params',
- 'pass either {surface} (persist) or {tools} (descriptor fetch), not both.',
- );
- }
-
- // ── persist branch (D5: accepts ONLY {surface}) ─────────────────────
- if (p.surface !== undefined) {
- const requested = p.surface as string;
- if (!isMcpSurface(requested)) {
- // Backstop for direct handler calls — MCP dispatch already rejects
- // via the enum in validateParams (invalid_params naming the valid set).
- throw new OperationError('invalid_params', `surface must be one of: verbs, starter, full (got an unrecognized value)`);
- }
- const clientId = ctx.auth?.clientId;
- if (!clientId) {
- // stdio has no per-token identity; a surface persist has nowhere to land.
- return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };
- }
- if (surfaceWiderThan(requested, ceiling)) {
- const e = new OperationError(
- 'permission_denied',
- `surface '${requested}' is above this server's ceiling '${ceiling}' (D2: per-client surfaces narrow, never widen).`,
- `The operator caps this transport at --surface ${ceiling}; widening requires a server restart with a wider --surface.`,
- );
- e.detail = `ceiling=${ceiling}`; // amendment 4 key=value denial grammar; ENG-11 assign-after
- throw e;
- }
- let rows: Record<string, unknown>[];
- try {
- rows = await ctx.engine.executeRaw(
- `SELECT surface, surface_set_by FROM oauth_clients WHERE client_id = $1`,
- [clientId],
- );
- } catch (err) {
- if (isUndefinedColumnError(err, 'surface') || isUndefinedColumnError(err, 'surface_set_by')) {
- // D5: a capability-negotiation op never returns internal_error for
- // a pre-migration brain — report the gap and keep serving.
- return { persisted: false, reason: 'migration pending' };
- }
- throw err;
- }
- if (rows.length === 0) {
- // Legacy bearer tokens carry a clientId that is not an oauth_clients row.
- return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };
- }
- const current = rows[0] as { surface?: string | null; surface_set_by?: string | null };
- const operatorLocked = () => {
- const e = new OperationError(
- 'permission_denied',
- "this client's surface is operator-pinned and cannot be self-changed (amendment 19).",
- `Ask the brain operator to change it: gbrain auth rescope-client ${clientId} --surface ${requested}`,
- );
- e.detail = 'locked_by=operator';
- return e;
- };
- if (current.surface_set_by === 'operator') throw operatorLocked();
- // A dry-run preview exercises every denial above but must not consume
- // the persist budget — the limiter meters actual writes only.
- if (ctx.dryRun) {
- return { persisted: false, dry_run: true, surface: requested, reason: 'dry_run' };
- }
- const rl = requestToolsPersistLimiter.check(clientId);
- if (!rl.allowed) {
- throw new OperationError(
- 'rate_limited',
- 'surface persistence is rate-limited to ~5 changes per hour per client (D14.5).',
- `Retry after ~${rl.retryAfter ?? 60}s.`,
- );
- }
- // Atomic re-check: a concurrent operator pin between the SELECT and
- // this UPDATE must still win.
- const updated = await ctx.engine.executeRaw(
- `UPDATE oauth_clients SET surface = $1, surface_set_by = 'self'
- WHERE client_id = $2 AND (surface_set_by IS DISTINCT FROM 'operator')
- RETURNING client_id`,
- [requested, clientId],
- );
- if (updated.length === 0) {
- // Concurrent operator pin won the race: the denial must not consume
- // the client's persist budget (the limiter meters actual writes).
- requestToolsPersistLimiter.refund(clientId);
- throw operatorLocked();
- }
- await writeSurfaceChangeAudit(ctx.engine, {
- actor: clientId,
- client_id: clientId,
- old: (current.surface as string | null) ?? null,
- new: requested,
- via: 'request_tools',
- });
- return { persisted: true, surface: requested, note: 're-issue tools/list to see the new catalog' };
- }
-
- const visible = await visibleOpsForCaller(ctx, ceiling);
-
- // ── descriptor branch (D5: read-only) ───────────────────────────────
- if (p.tools !== undefined) {
- const requested = (p.tools as unknown[]).filter((t): t is string => typeof t === 'string');
- const byName = new Map(visible.map(o => [o.name, o]));
- const picked: Operation[] = [];
- const seen = new Set<string>();
- for (const name of requested) {
- if (seen.has(name)) continue;
- seen.add(name);
- const op = byName.get(name);
- if (op) picked.push(op); // invisible names silently omitted (D5)
- }
- const { buildToolDefs } = await import('../mcp/tool-defs.ts');
- const { resolveStrictParamsMode } = await import('../mcp/validate-params.ts');
- const strictParams = (await resolveStrictParamsMode(ctx.engine, ctx.config)) === 'reject';
- return { tools: buildToolDefs(picked, { strictParams }) };
- }
-
- // ── catalog branch (no args) ────────────────────────────────────────
- const groups = new Map<string, Array<{ name: string; one_line: string }>>();
- for (const op of visible) {
- // Area names are non-contractual grouping labels (amendment 22).
- const area = op.area ?? 'other';
- const bucket = groups.get(area) ?? [];
- bucket.push({ name: op.name, one_line: firstSentenceOf(op.description) });
- groups.set(area, bucket);
- }
- const catalog = [...groups.entries()]
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([area, tools]) => ({ area, tools }));
- return {
- catalog,
- total_tools: visible.length,
- note: 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to persist a wider tool surface (within the server ceiling), then re-issue tools/list.',
- };
- },
-};
+// --- Foundation (pure move, v0.46.x): the contract types + error envelope live
+// in ops/contract.ts; the validators, slug fences, and source-scope resolvers
+// live in ops/context.ts. Re-exported so every existing importer of
+// operations.ts is unchanged.
+
+import type { Operation } from './ops/contract.ts';
+
+// Re-exports: the full previously-exported foundation surface of this module.
+// The formerly file-private helpers (enforceSubagentSlugFence, slugUnderSubagentFence,
+// slugOutsideCallerFence, enforceClientSlugFence, BOUND_CLIENT_META_OPS,
+// stampEvidenceSafe, maybeCaptureSearch) are deliberately NOT re-exported —
+// they were never part of this module's surface; import them from ops/context.ts.
+export { OperationError, verbError } from './ops/contract.ts';
+export type {
+ ErrorCode,
+ ParamDef,
+ Logger,
+ AuthInfo,
+ OperationContext,
+ Operation,
+} from './ops/contract.ts';
+export {
+ validateUploadPath,
+ validatePageSlug,
+ matchesSlugAllowList,
+ slugUnderBoundPrefixes,
+ normalizeSlugPrefix,
+ CLIENT_FENCED_WRITE_OPS,
+ opAllowedForBoundClient,
+ enforceBoundClientOpAllowList,
+ validateFilename,
+ sourceScopeOpts,
+ thinkSourceScopeOpts,
+ linkReadScopeOpts,
+ resolveRequestedScope,
+ federatedSearchScope,
+ resolveCodeIntelScope,
+ resolvePerCallMode,
+} from './ops/context.ts';
+
+// --- Tranche 1 (pure move, v0.46.x): the Page CRUD, Search (search/query),
+// Takes+think, Tags, Links+graph, and Timeline op clusters live in
+// ops/pages.ts, ops/search.ts, ops/takes.ts, ops/tags.ts, ops/links.ts, and
+// ops/timeline.ts. Their ordered arrays are spliced into the canonical
+// `operations` array below at the clusters' original positions (order is
+// contractual — docs/TOOL_CATALOG.md is generated from it).
+
+import { pagesOperations } from './ops/pages.ts';
+import { searchOperations } from './ops/search.ts';
+import { takesOperations } from './ops/takes.ts';
+import { tagsOperations } from './ops/tags.ts';
+import { linksOperations } from './ops/links.ts';
+import { timelineOperations } from './ops/timeline.ts';
+
+// MANAGED_LINK_SOURCES moved to ops/links.ts with the add_link op; re-exported
+// so every existing importer of operations.ts is unchanged.
+export { MANAGED_LINK_SOURCES } from './ops/links.ts';
+
+// --- Tranche 2 (pure move, v0.46.x): the Admin, skill-catalog (+advisor/
+// status-snapshot), Sync, Raw Data, Resolution & Chunks, Ingest Log, File
+// Operations, Jobs (Minions + agent lane), Orphans, calibration, and
+// Salience + Anomaly op clusters live in ops/admin.ts, ops/skills-catalog.ts,
+// ops/sync-status.ts, ops/raw-data.ts, ops/chunks.ts, ops/ingest-log.ts,
+// ops/files.ts, ops/jobs.ts, ops/orphans.ts, ops/calibration.ts, and
+// ops/salience.ts. Their ordered arrays are spliced into the canonical
+// `operations` array below at the clusters' original positions (order is
+// contractual — docs/TOOL_CATALOG.md is generated from it).
+
+import { adminOperations } from './ops/admin.ts';
+import { skillsCatalogOperations } from './ops/skills-catalog.ts';
+import { syncStatusOperations } from './ops/sync-status.ts';
+import { rawDataOperations } from './ops/raw-data.ts';
+import { chunksOperations } from './ops/chunks.ts';
+import { ingestLogOperations } from './ops/ingest-log.ts';
+import { filesOperations } from './ops/files.ts';
+import { jobsOperations } from './ops/jobs.ts';
+import { orphansOperations } from './ops/orphans.ts';
+import { calibrationOperations } from './ops/calibration.ts';
+import { salienceOperations } from './ops/salience.ts';
+
+// --- Tranche 3 (pure move, v0.46.x): the remaining inline clusters live in
+// ops/insights.ts (push-based volunteer_context + the find_* insight reads —
+// exported individually because their array slots are non-adjacent),
+// ops/transcripts.ts, ops/sources.ts, ops/facts.ts, ops/code-intel.ts,
+// ops/embedding-migration.ts, ops/image.ts, ops/schema-packs.ts,
+// ops/skillopt.ts, ops/chronicle.ts, ops/extraction.ts, and
+// ops/request-tools.ts. Their ordered arrays / ops are spliced into the
+// canonical `operations` array below at the clusters' original positions
+// (order is contractual — docs/TOOL_CATALOG.md is generated from it).
+
+import { volunteer_context, find_experts, find_contradictions, find_trajectory } from './ops/insights.ts';
+import { transcriptsOperations } from './ops/transcripts.ts';
+import { sourcesOperations } from './ops/sources.ts';
+import { factsOperations } from './ops/facts.ts';
+import { codeIntelOperations } from './ops/code-intel.ts';
+import { embeddingMigrationOperations } from './ops/embedding-migration.ts';
+import { imageOperations } from './ops/image.ts';
+import { schemaPacksOperations } from './ops/schema-packs.ts';
+import { skilloptOperations } from './ops/skillopt.ts';
+import { chronicleOperations } from './ops/chronicle.ts';
+import { extractionOperations } from './ops/extraction.ts';
+import { requestToolsOperations } from './ops/request-tools.ts';
+
+// parseTtlParam moved to ops/facts.ts with the facts cluster; the `remember`
+// verb (verbs.ts) loads it from THIS module at runtime — re-exported so every
+// existing importer of operations.ts is unchanged.
+export { parseTtlParam } from './ops/facts.ts';
+// The request_tools persist-limiter test seam moved with its cluster —
+// re-exported for the same reason.
+export { __resetRequestToolsPersistLimiterForTests } from './ops/request-tools.ts';
export const operations: Operation[] = [
// MEMORY_VERBS v1 (Cathedral 1) — remember/entity/synthesize/forget live in
@@ -7272,97 +123,85 @@ export const operations: Operation[] = [
// plus the v0.45.x boundary verbs `context_pack`/`delta`) are defined below.
// Spread first so `--surface verbs` agents see them at the top of the list.
...verbOperations,
- // Page CRUD
- get_page, put_page, delete_page, list_pages,
- // v0.26.5 destructive-guard ops (page-level soft-delete + recovery + admin purge)
- restore_page, purge_deleted_pages,
- // Search
- search, query,
- // v0.36 Phase 2: image-as-query
- search_by_image,
- // Tags
- add_tag, remove_tag, get_tags,
- // Links
- add_link, remove_link, get_links, get_backlinks, list_link_sources, traverse_graph,
- // Timeline
- add_timeline_entry, get_timeline,
- // Admin
- get_stats, get_health, run_doctor, get_versions, revert_version,
- // v0.31.1 (Issue #734): thin-client banner identity packet (read-scope, banner-only)
- get_brain_identity,
- // PR1: skill catalog over MCP — discover + fetch host-repo skills (read-scope)
- list_skills, get_skill, list_brain_skillpack, advisor,
- // v0.41.19.0: thin-client `gbrain status` payload (admin-scope, sync + cycle only)
- get_status_snapshot,
- // Sync
- sync_brain,
- // Raw data
- put_raw_data, get_raw_data,
- // Resolution & chunks
- resolve_slugs, get_chunks,
- // Ingest log
- log_ingest, get_ingest_log,
- // Files
- file_list, file_upload, file_url,
- // Jobs (Minions)
- submit_job, get_job, list_jobs, cancel_job, retry_job, get_job_progress,
- pause_job, resume_job, replay_job, send_job_message,
- // v0.38 Slice 3: remote-callable agent dispatch with OAuth-bound trust boundary
- // + Minions-visibility wave: ownership-fenced agent-job polling
- submit_agent, get_agent_job,
- // Orphans
- find_orphans,
- // v0.36.1.0 (T7) — Hindsight calibration wave: read profile via MCP
- get_calibration_profile,
- // v0.28: Takes + think
- takes_list, takes_search, think,
- // v0.30: calibration aggregates over takes
- takes_scorecard, takes_calibration,
- // v0.28: whoami + scoped sources management
- whoami, sources_add, sources_list, sources_remove, sources_status,
- // WP4 (T9): discovery + pull-based per-client surface unlock (D4/D5/D9)
- request_tools,
- // v0.29: Salience + anomalies + recent transcripts
- get_recent_salience, find_anomalies, get_recent_transcripts,
- // v0.42.x (#2390): Life Chronicle timeline reads
- chronicle_day, chronicle_on_this_day, chronicle_since, chronicle_last_seen,
- ontology_get, ontology_propose, ontology_dimensions, ontology_conflicts,
- volunteer_chronicle, chronicle_backfill,
- // v0.43 (#2095): push-based context
+ // Page CRUD (get_page, put_page, delete_page, list_pages + the v0.26.5
+ // destructive-guard ops restore_page, purge_deleted_pages) — ops/pages.ts
+ ...pagesOperations,
+ // Search (search, query) — ops/search.ts
+ ...searchOperations,
+ // v0.36 Phase 2: image-as-query (search_by_image) — ops/image.ts
+ ...imageOperations,
+ // Tags (add_tag, remove_tag, get_tags) — ops/tags.ts
+ ...tagsOperations,
+ // Links (add_link, remove_link, get_links, get_backlinks,
+ // list_link_sources, traverse_graph) — ops/links.ts
+ ...linksOperations,
+ // Timeline (add_timeline_entry, get_timeline) — ops/timeline.ts
+ ...timelineOperations,
+ // Admin (get_stats, get_health, run_doctor, get_versions, revert_version
+ // + the v0.31.1 banner packet get_brain_identity) — ops/admin.ts
+ ...adminOperations,
+ // PR1: skill catalog over MCP (list_skills, get_skill, list_brain_skillpack,
+ // advisor) + v0.41.19.0 get_status_snapshot — ops/skills-catalog.ts
+ ...skillsCatalogOperations,
+ // Sync (sync_brain) — ops/sync-status.ts
+ ...syncStatusOperations,
+ // Raw data (put_raw_data, get_raw_data) — ops/raw-data.ts
+ ...rawDataOperations,
+ // Resolution & chunks (resolve_slugs, get_chunks) — ops/chunks.ts
+ ...chunksOperations,
+ // Ingest log (log_ingest, get_ingest_log) — ops/ingest-log.ts
+ ...ingestLogOperations,
+ // Files (file_list, file_upload, file_url) — ops/files.ts
+ ...filesOperations,
+ // Jobs (Minions: submit_job, get_job, list_jobs, cancel_job, retry_job,
+ // get_job_progress, pause_job, resume_job, replay_job, send_job_message)
+ // + v0.38 Slice 3 agent lane (submit_agent, get_agent_job) — ops/jobs.ts
+ ...jobsOperations,
+ // Orphans (find_orphans) — ops/orphans.ts
+ ...orphansOperations,
+ // v0.36.1.0 (T7) — Hindsight calibration wave (get_calibration_profile) —
+ // ops/calibration.ts
+ ...calibrationOperations,
+ // v0.28: Takes + think (takes_list, takes_search, think) + v0.30
+ // calibration aggregates (takes_scorecard, takes_calibration) — ops/takes.ts
+ ...takesOperations,
+ // v0.28: whoami + scoped sources management — ops/sources.ts
+ ...sourcesOperations,
+ // WP4 (T9): discovery + pull-based per-client surface unlock (D4/D5/D9) —
+ // ops/request-tools.ts
+ ...requestToolsOperations,
+ // v0.29: Salience + anomalies (get_recent_salience, find_anomalies —
+ // ops/salience.ts) + recent transcripts (ops/transcripts.ts)
+ ...salienceOperations, ...transcriptsOperations,
+ // v0.42.x (#2390): Life Chronicle timeline reads + ontology +
+ // volunteer_chronicle/backfill — ops/chronicle.ts
+ ...chronicleOperations,
+ // v0.43 (#2095): push-based context — ops/insights.ts
volunteer_context,
- // Extraction quarantine lane (#160): gated entity extraction + review queue
- extract_entities, extraction_pending, extraction_review,
- // v0.31: hot memory (facts table)
- extract_facts, recall, context_pack, delta, forget_fact,
- // v0.32.6: contradiction probe MCP surface (M3)
+ // Extraction quarantine lane (#160): gated entity extraction + review
+ // queue — ops/extraction.ts
+ ...extractionOperations,
+ // v0.31: hot memory (extract_facts, recall, context_pack, delta,
+ // forget_fact) — ops/facts.ts
+ ...factsOperations,
+ // v0.32.6: contradiction probe MCP surface (M3) — ops/insights.ts
find_contradictions,
- // v0.33: expertise + relationship-proximity routing
+ // v0.33: expertise + relationship-proximity routing — ops/insights.ts
find_experts,
- // v0.35.4: temporal trajectory (typed claims over time + regression detection)
+ // v0.35.4: temporal trajectory (typed claims over time + regression
+ // detection) — ops/insights.ts
find_trajectory,
- // v0.33.3: Cathedral III code-intelligence (MCP-exposed; were CLI_ONLY pre-v0.33.3)
- code_callers, code_callees, code_def, code_refs,
- // v0.34 W3: recursive code_blast + code_flow
- code_blast, code_flow,
- // v0.34 W3b: code_traversal_cache admin clear op
- code_traversal_cache_clear,
- // #3390: provider-agnostic embedding migration (local-only admin)
- migrate_embeddings,
- // v0.40.6.0 Schema Cathedral v3: 9 new ops — 7 read + 2 admin (NOT
- // localOnly per D2 so remote agents (your OpenClaw, etc.) can author packs).
- // schema_apply_mutations is batched per D10 — one MCP tool, N
- // mutations applied atomically inside one withPackLock scope.
- get_active_schema_pack, list_schema_packs,
- schema_stats, schema_lint, schema_graph, schema_explain_type,
- schema_review_orphans,
- schema_apply_mutations, reload_schema_pack,
- // v0.41.18.0 (T16, A7, codex #5)
- run_onboard,
- // v0.41.20.0 SkillOpt — admin-scoped MCP op for remote optimization.
- // Per-skill allowlist via `skillopt.allowed_skills` config (default
- // deny-all for remote callers). NOT localOnly so admin OAuth clients
- // can submit; CLI bypass via ctx.remote === false.
- run_skillopt,
+ // v0.33.3 Cathedral III code-intelligence + v0.34 W3 code_blast/code_flow
+ // + W3b cache-clear — ops/code-intel.ts
+ ...codeIntelOperations,
+ // #3390: provider-agnostic embedding migration (local-only admin) —
+ // ops/embedding-migration.ts
+ ...embeddingMigrationOperations,
+ // v0.40.6.0 Schema Cathedral v3: 9 ops — 7 read + 2 admin —
+ // ops/schema-packs.ts
+ ...schemaPacksOperations,
+ // v0.41.18.0 run_onboard + v0.41.20.0 run_skillopt — ops/skillopt.ts
+ ...skilloptOperations,
];
// ---------------------------------------------------------------------------
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
new file mode 100644
index 0000000000..f1ec50faf0
--- /dev/null
+++ b/src/core/ops/admin.ts
@@ -0,0 +1,171 @@
+/**
+ * Admin operation cluster — pure move from operations.ts (v0.46.x tranche 2).
+ * Op consts stay module-private; `adminOperations` below lists them in
+ * EXACTLY the order they appear in the canonical `operations` array in
+ * ../operations.ts (run_doctor / get_versions / revert_version were defined
+ * under the skill-catalog divider in the original file but have always
+ * occupied the Admin slots of the array — the array order is the contract).
+ * Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';
+import { stripTakesFence } from '../takes-fence.ts';
+import { VERSION } from '../../version.ts';
+
+// --- Admin ---
+
+const get_stats: Operation = {
+ name: 'get_stats',
+ description: 'Brain statistics (page count, chunk count, etc.)',
+ params: {},
+ handler: async (ctx) => {
+ return ctx.engine.getStats();
+ },
+ scope: 'admin',
+ cliHints: { name: 'stats' },
+};
+
+const get_health: Operation = {
+ name: 'get_health',
+ description: 'Brain health dashboard (embed coverage, stale pages, orphans)',
+ params: {},
+ handler: async (ctx) => {
+ return ctx.engine.getHealth();
+ },
+ scope: 'admin',
+ cliHints: { name: 'health' },
+};
+
+/**
+ * v0.31.1 (Issue #734): lightweight identity packet for the thin-client
+ * banner. Read-scope so any authenticated client can surface "thin-client →
+ * <host> · brain: 102k pages, 265k chunks · v0.31.1" without needing admin.
+ *
+ * Reuses engine.getStats() for counters (banner cache TTL bounds frequency
+ * to ≤1/60s per CLI process; well below the Fly.io health-check cadence
+ * that motivated the `getStats` cost warning in CLAUDE.md).
+ *
+ * No CLI surface (no cliHints) — this op exists only for thin-client banner
+ * data. `last_sync_iso` deferred (no canonical source field today; would
+ * need autopilot cycle to write a config key — TODO in v0.31.x).
+ */
+const get_brain_identity: Operation = {
+ name: 'get_brain_identity',
+ description: 'Brain identity + counters for thin-client banner. Returns version, engine kind, and page/chunk counts. Read-scope.',
+ params: {},
+ handler: async (ctx) => {
+ const stats = await ctx.engine.getStats();
+ // v0.42 self-upgrade: surface a pending update on the thin-client banner
+ // (bonus channel; the CLI stderr marker + `gbrain self-upgrade` are the
+ // load-bearing surface). Cache-read-only, no network, fail-open.
+ let update_available = false;
+ let latest_version: string | null = null;
+ try {
+ const su = await import('../self-upgrade.ts');
+ // Shared stale/foreign-cache guard (pendingUpgradeVersion): only an
+ // upgrade strictly newer than the RUNNING version counts.
+ const latest = su.pendingUpgradeVersion(VERSION, Date.now());
+ if (latest) {
+ update_available = true;
+ latest_version = latest;
+ }
+ } catch {
+ /* never let the banner break the op */
+ }
+ return {
+ version: VERSION,
+ engine: ctx.engine.kind,
+ page_count: stats.page_count,
+ chunk_count: stats.chunk_count,
+ last_sync_iso: null as string | null,
+ update_available,
+ latest_version,
+ };
+ },
+ scope: 'read',
+ // intentionally no cliHints — banner-only op
+};
+
+/**
+ * Multi-topology v1 (Tier B): structured doctor report for remote callers.
+ *
+ * First read-only diagnostic op exposed over HTTP MCP. Wraps the focused
+ * thin-client check set in `src/commands/doctor.ts:doctorReportRemote()` and
+ * returns the structured `DoctorReport` JSON verbatim. The matching client-
+ * side renderer lives in `src/commands/remote.ts` (used by `gbrain remote
+ * doctor`). Local doctor is unchanged — operators on the host still get the
+ * full check set.
+ *
+ * scope=admin because some checks expose system-state (queue depth, schema
+ * version) that read-only consumers don't need. localOnly=false so HTTP
+ * callers can invoke it. No mutation; safe to call repeatedly.
+ *
+ * Precedent: doctor only. Generalizing to lint/integrity/orphans is filed as
+ * follow-up work pending demand.
+ */
+const run_doctor: Operation = {
+ name: 'run_doctor',
+ description: 'Run brain health checks and return a structured DoctorReport (thin-client doctor surface).',
+ params: {},
+ handler: async (ctx) => {
+ const { doctorReportRemote } = await import('../../commands/doctor.ts');
+ // Source isolation (cross-model P1): a source-bound caller's report must
+ // not aggregate other sources' activity. Scope-aware checks (currently
+ // volunteer_channels) filter on these ids; unscoped ctx = brain-wide.
+ const scope = sourceScopeOpts(ctx);
+ const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : undefined);
+ return doctorReportRemote(ctx.engine, { sourceIds });
+ },
+ scope: 'admin',
+ localOnly: false,
+};
+
+const get_versions: Operation = {
+ name: 'get_versions',
+ description: 'Page version history',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },
+ },
+ handler: async (ctx, p) => {
+ const versions = await ctx.engine.getVersions(p.slug as string, sourceScopeOpts(ctx));
+ // 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) }));
+ },
+ scope: 'read',
+ cliHints: { name: 'history', positional: ['slug'] },
+};
+
+const revert_version: Operation = {
+ name: 'revert_version',
+ description: 'Revert page to a previous version',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page to revert.' },
+ version_id: { type: 'number', required: true, description: 'Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field.' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ enforceClientSlugFence(ctx, p.slug as string, 'revert_version');
+ if (ctx.dryRun) return { dry_run: true, action: 'revert_version', slug: p.slug, version_id: p.version_id };
+ // v0.31.8 (D7): thread ctx.sourceId so multi-source brains revert the
+ // intended page row instead of whichever same-slug row Postgres returns
+ // first.
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ await ctx.engine.createVersion(p.slug as string, sourceOpts);
+ await ctx.engine.revertToVersion(p.slug as string, p.version_id as number, sourceOpts);
+ return { status: 'reverted' };
+ },
+ cliHints: { name: 'revert', positional: ['slug', 'version_id'] },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const adminOperations: Operation[] = [
+ get_stats, get_health, run_doctor, get_versions, revert_version,
+ get_brain_identity,
+];
diff --git a/src/core/ops/calibration.ts b/src/core/ops/calibration.ts
new file mode 100644
index 0000000000..f524a58f35
--- /dev/null
+++ b/src/core/ops/calibration.ts
@@ -0,0 +1,39 @@
+/**
+ * Calibration-profile operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 2). Op consts stay module-private;
+ * `calibrationOperations` below lists them in EXACTLY the order they appear
+ * in the canonical `operations` array in ../operations.ts. Never import
+ * from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+
+// --- v0.36.1.0 (T7): calibration profile read op ---
+
+const get_calibration_profile: Operation = {
+ name: 'get_calibration_profile',
+ description:
+ 'Read the active calibration profile for a holder. Returns the latest row from calibration_profiles ' +
+ '(per-source, per-holder) including Brier score, accuracy, pattern statements, and active bias tags. ' +
+ 'Source-scoped via sourceScopeOpts — federated_read scopes see the union of allowed sources, ' +
+ 'scalar source-bound clients see only their source. Returns null when no profile exists yet ' +
+ '(cold-brain branch: builds after 5+ resolved takes + a calibration_profile phase run).',
+ scope: 'read',
+ params: {
+ holder: {
+ type: 'string',
+ description:
+ "Holder slug, e.g. 'self' or 'people/charlie-example'. Defaults to config emotional_weight.user_holder, else 'self', when omitted.",
+ },
+ },
+ handler: async (ctx, p) => {
+ const { getCalibrationProfileOp } = await import('../../commands/calibration.ts');
+ return getCalibrationProfileOp(ctx, {
+ ...(typeof p.holder === 'string' ? { holder: p.holder } : {}),
+ });
+ },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const calibrationOperations: Operation[] = [get_calibration_profile];
diff --git a/src/core/ops/chronicle.ts b/src/core/ops/chronicle.ts
new file mode 100644
index 0000000000..0dd1a51517
--- /dev/null
+++ b/src/core/ops/chronicle.ts
@@ -0,0 +1,285 @@
+/**
+ * Life Chronicle + ontology operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 3): the v0.42.x (#2390) timeline reads, the ontology
+ * read/write ops, volunteer_chronicle, and the chronicle_backfill sweep. Op
+ * consts stay module-private; `chronicleOperations` below lists them in
+ * EXACTLY the order they appear in the canonical `operations` array in
+ * ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { sourceScopeOpts } from './context.ts';
+
+// ── v0.42.x — Life Chronicle (#2390) timeline read ops ───────────────────
+// CLI names avoid the existing `timeline` (get_timeline, a page's own timeline):
+// `gbrain day <date>` / `gbrain since <date>` / `gbrain last-seen <entity>`.
+// All route through sourceScopeOpts(ctx) so reads honor source isolation.
+const chronicle_day: Operation = {
+ name: 'chronicle_day',
+ description:
+ 'Life Chronicle: events + timeline entries on a given day (or its ISO week when week=true), ' +
+ "ordered chronologically; each row backlinks to its depth page. Distinct from `get_timeline`/" +
+ "`gbrain timeline <slug>`, which shows ONE page's timeline. CLI: `gbrain day <date>`.",
+ scope: 'read',
+ params: {
+ date: { type: 'string', required: true, description: 'Day as YYYY-MM-DD.' },
+ week: { type: 'boolean', description: 'Expand to the ISO week (Mon–Sun) containing the date.' },
+ limit: { type: 'number', description: 'Max rows (default 200).' },
+ narrative: { type: 'boolean', description: 'Also return a prose day-by-day narrative.' },
+ },
+ handler: async (ctx, p) => {
+ const rows = await ctx.engine.getTimelineForDate(String(p.date), {
+ week: p.week === true,
+ limit: typeof p.limit === 'number' ? p.limit : undefined,
+ ...sourceScopeOpts(ctx),
+ });
+ if (p.narrative === true) {
+ const { renderTimelineNarrative } = await import('../chronicle/narrative.ts');
+ return { date: String(p.date), narrative: renderTimelineNarrative(rows), events: rows };
+ }
+ return rows;
+ },
+ cliHints: { name: 'day', positional: ['date'] },
+};
+
+const chronicle_on_this_day: Operation = {
+ name: 'chronicle_on_this_day',
+ description:
+ 'Life Chronicle: events from the same calendar day in PRIOR years ("on this day"). ' +
+ 'CLI: `gbrain on-this-day [--date YYYY-MM-DD]`.',
+ scope: 'read',
+ params: {
+ date: { type: 'string', description: 'Anchor day YYYY-MM-DD (default today); matches its month-day in prior years.' },
+ limit: { type: 'number', description: 'Max rows (default 50).' },
+ },
+ handler: async (ctx, p) => ctx.engine.getOnThisDay({
+ date: typeof p.date === 'string' ? p.date : undefined,
+ limit: typeof p.limit === 'number' ? p.limit : undefined,
+ ...sourceScopeOpts(ctx),
+ }),
+ cliHints: { name: 'on-this-day' },
+};
+
+const chronicle_since: Operation = {
+ name: 'chronicle_since',
+ description:
+ 'Life Chronicle: events + timeline entries on or after a date, optionally filtered by event kind. ' +
+ 'CLI: `gbrain since <date> [--kind commitment]`.',
+ scope: 'read',
+ params: {
+ date: { type: 'string', required: true, description: 'Lower-bound day as YYYY-MM-DD (inclusive).' },
+ kind: { type: 'string', description: "Filter event projections by event.kind (e.g. 'commitment')." },
+ limit: { type: 'number', description: 'Max rows (default 200).' },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.getSince(String(p.date), {
+ kind: typeof p.kind === 'string' ? p.kind : undefined,
+ limit: typeof p.limit === 'number' ? p.limit : undefined,
+ ...sourceScopeOpts(ctx),
+ });
+ },
+ cliHints: { name: 'since', positional: ['date'] },
+};
+
+const chronicle_last_seen: Operation = {
+ name: 'chronicle_last_seen',
+ description:
+ "Life Chronicle: when an entity was last seen — its own timeline rows OR an event's `who`. " +
+ 'Returns last_date, the event slug, and days_ago. CLI: `gbrain last-seen <entity-slug>`.',
+ scope: 'read',
+ params: {
+ entity: { type: 'string', required: true, description: 'Entity page slug (e.g. people/sarah-chen).' },
+ asof: { type: 'string', description: 'Reference day YYYY-MM-DD for days_ago (default today).' },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.getLastSeen(String(p.entity), {
+ asof: typeof p.asof === 'string' ? p.asof : undefined,
+ ...sourceScopeOpts(ctx),
+ });
+ },
+ cliHints: { name: 'last-seen', positional: ['entity'] },
+};
+
+const ontology_get: Operation = {
+ name: 'ontology_get',
+ description:
+ "Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` " +
+ "(default now), with provenance + confidence + validity. CLI: `gbrain ontology <entity> [--asof YYYY-MM-DD]`.",
+ scope: 'read',
+ params: {
+ entity: { type: 'string', required: true, description: 'Entity page slug (e.g. people/sarah-chen).' },
+ asof: { type: 'string', description: 'Valid-time as-of day YYYY-MM-DD (time-travel; default now).' },
+ min_confidence: { type: 'number', description: 'Only return observations at/above this confidence (0..1).' },
+ include_quarantined: { type: 'boolean', description: 'Include quarantined novel dimensions (default false).' },
+ },
+ handler: async (ctx, p) => {
+ const rows = await ctx.engine.getOntology(String(p.entity), {
+ asof: typeof p.asof === 'string' ? p.asof : undefined,
+ minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
+ includeQuarantined: p.include_quarantined === true,
+ ...sourceScopeOpts(ctx),
+ });
+ // Remote redaction: never surface diary-sourced ontology to untrusted callers.
+ return ctx.remote !== false ? rows.filter((r) => !(r.source ?? '').startsWith('life/diary/')) : rows;
+ },
+ cliHints: { name: 'ontology', positional: ['entity'] },
+};
+
+const ontology_propose: Operation = {
+ name: 'ontology_propose',
+ description:
+ 'Life Chronicle: record one ontology observation (entity has dimension=value), sourced + ' +
+ 'confidence-weighted + bi-temporal. Idempotent on (entity,dimension,value,source). A new value ' +
+ 'supersedes the prior; a backdated conflict is flagged not rewritten. CLI: `gbrain ontology-add <entity> <dimension> <value>`.',
+ scope: 'write',
+ mutating: true,
+ params: {
+ entity: { type: 'string', required: true, description: 'Entity page slug.' },
+ dimension: { type: 'string', required: true, description: 'Dimension (e.g. role, risk_tolerance). Normalized at write.' },
+ value: { type: 'string', required: true, description: 'The resolved value (e.g. advisor).' },
+ confidence: { type: 'number', description: '0..1; default 0.7.' },
+ source: { type: 'string', description: 'Provenance (page slug / uri); default "manual".' },
+ valid_from: { type: 'string', description: 'ISO date the value became true (default: now).' },
+ valid_to: { type: 'string', description: 'ISO date the value stopped being true (default: open).' },
+ visibility: { type: 'string', enum: ['private', 'world'], description: 'Default private.' },
+ },
+ handler: async (ctx, p) => {
+ // [ENG-8] Same unset-vs-explicit ladder as extract_facts: explicit
+ // caller visibility wins; unset resolves facts.default_visibility.
+ const { resolveVisibilityParam } = await import('../facts/visibility.ts');
+ return ctx.engine.mergeOntologyFact({
+ entitySlug: String(p.entity),
+ dimension: String(p.dimension),
+ value: String(p.value),
+ confidence: typeof p.confidence === 'number' ? p.confidence : undefined,
+ source: typeof p.source === 'string' && p.source ? p.source : 'manual',
+ validFrom: typeof p.valid_from === 'string' ? p.valid_from : undefined,
+ validTo: typeof p.valid_to === 'string' ? p.valid_to : undefined,
+ visibility: await resolveVisibilityParam(ctx.engine, p.visibility),
+ sourceId: ctx.sourceId,
+ });
+ },
+ cliHints: { name: 'ontology-add', positional: ['entity', 'dimension', 'value'] },
+};
+
+const ontology_dimensions: Operation = {
+ name: 'ontology_dimensions',
+ description:
+ 'Life Chronicle meta-ontology: which dimensions the brain tracks across entities, with ' +
+ 'entity + observation counts. CLI: `gbrain ontology-dimensions`.',
+ scope: 'read',
+ params: {},
+ handler: async (ctx) => ctx.engine.discoverOntologyDimensions(sourceScopeOpts(ctx)),
+ cliHints: { name: 'ontology-dimensions' },
+};
+
+const ontology_conflicts: Operation = {
+ name: 'ontology_conflicts',
+ description:
+ 'Life Chronicle: dimensions with ≥2 distinct current values from ≥2 provenances (genuine ' +
+ 'disagreement, not temporal supersession). CLI: `gbrain ontology-contradictions`.',
+ scope: 'read',
+ params: {
+ min_confidence: { type: 'number', description: 'Only consider observations at/above this confidence (0..1).' },
+ },
+ handler: async (ctx, p) => {
+ const conflicts = await ctx.engine.findOntologyConflicts({
+ minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
+ ...sourceScopeOpts(ctx),
+ });
+ if (ctx.remote === false) return conflicts;
+ // Remote: redact diary-sourced values; drop conflicts that no longer have
+ // ≥2 distinct values once diary provenance is removed (no leak via conflicts).
+ return conflicts
+ .map((c) => ({ ...c, values: c.values.filter((v) => !(v.source ?? '').startsWith('life/diary/')) }))
+ .filter((c) => new Set(c.values.map((v) => v.value)).size >= 2);
+ },
+ cliHints: { name: 'ontology-contradictions' },
+};
+
+const volunteer_chronicle: Operation = {
+ name: 'volunteer_chronicle',
+ description:
+ 'Life Chronicle agent-orientation: the recent timeline (last N days) + the current ' +
+ 'validity-resolved ontology for the named entities, in one zero-LLM payload, so an agent ' +
+ 'orients before acting. Diary-sourced ontology is redacted for remote callers. ' +
+ 'CLI: `gbrain orient [--days 7] [--entities people/a,people/b]`.',
+ scope: 'read',
+ params: {
+ days: { type: 'number', description: 'Recent-timeline lookback in days (default 7).' },
+ entities: { type: 'string', description: 'Comma-separated entity slugs to resolve ontology for.' },
+ limit: { type: 'number', description: 'Max timeline rows (default 50).' },
+ },
+ handler: async (ctx, p) => {
+ const { loadChronicleContext } = await import('../context/chronicle-context.ts');
+ const entities = typeof p.entities === 'string'
+ ? p.entities.split(',').map((s) => s.trim()).filter(Boolean)
+ : undefined;
+ return loadChronicleContext(ctx.engine, {
+ days: typeof p.days === 'number' ? p.days : undefined,
+ entities,
+ limit: typeof p.limit === 'number' ? p.limit : undefined,
+ remote: ctx.remote !== false,
+ ...sourceScopeOpts(ctx),
+ });
+ },
+ cliHints: { name: 'orient' },
+};
+
+const chronicle_backfill: Operation = {
+ name: 'chronicle_backfill',
+ description:
+ 'Life Chronicle: sweep existing meeting/conversation/calendar pages into timeline events by ' +
+ 'enqueuing chronicle_extract jobs (one per eligible page). --dry-run counts without enqueuing. ' +
+ 'Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--limit N] [--dry-run]`.',
+ scope: 'admin',
+ mutating: true,
+ localOnly: true,
+ params: {
+ since: { type: 'string', description: 'Only pages updated on/after this date (YYYY-MM-DD).' },
+ limit: { type: 'number', description: 'Max pages per type to sweep (default 1000).' },
+ dry_run: { type: 'boolean', description: 'Count eligible pages without enqueuing.' },
+ },
+ handler: async (ctx, p) => {
+ const { isChronicleEligible } = await import('../chronicle/eligibility.ts');
+ const TYPES = ['meeting', 'conversation', 'calendar-event'] as const;
+ const limit = typeof p.limit === 'number' ? p.limit : 1000;
+ const updated_after = typeof p.since === 'string' ? p.since : undefined;
+ const dryRun = p.dry_run === true;
+ const scope = sourceScopeOpts(ctx);
+ type QueueLike = { add: (n: string, d: Record<string, unknown>) => Promise<unknown> };
+ let queue: QueueLike | null = null;
+ if (!dryRun) {
+ const { MinionQueue } = await import('../minions/queue.ts');
+ queue = new MinionQueue(ctx.engine) as unknown as QueueLike;
+ }
+ let scanned = 0, eligible = 0, enqueued = 0;
+ const errors: { slug: string; error: string }[] = [];
+ for (const type of TYPES) {
+ const pages = await ctx.engine.listPages({ type, updated_after, limit, ...scope });
+ for (const page of pages) {
+ scanned++;
+ const dreamGenerated = (page.frontmatter as Record<string, unknown> | undefined)?.dream_generated === true;
+ const elig = isChronicleEligible({ type: page.type, slug: page.slug, body: page.compiled_truth, dreamGenerated });
+ if (!elig.ok) continue;
+ eligible++;
+ if (dryRun || !queue) continue;
+ try {
+ await queue.add('chronicle_extract', { slug: page.slug, sourceId: ctx.sourceId ?? 'default' });
+ enqueued++;
+ } catch (e) {
+ // Never swallow — surface per-page failures (the #2057 no-swallow pattern).
+ errors.push({ slug: page.slug, error: e instanceof Error ? e.message : String(e) });
+ }
+ }
+ }
+ return { scanned, eligible, enqueued, dry_run: dryRun, errors };
+ },
+ cliHints: { name: 'chronicle-backfill' },
+};
+
+export const chronicleOperations: Operation[] = [
+ chronicle_day, chronicle_on_this_day, chronicle_since, chronicle_last_seen,
+ ontology_get, ontology_propose, ontology_dimensions, ontology_conflicts,
+ volunteer_chronicle, chronicle_backfill,
+];
diff --git a/src/core/ops/chunks.ts b/src/core/ops/chunks.ts
new file mode 100644
index 0000000000..f475b1b74a
--- /dev/null
+++ b/src/core/ops/chunks.ts
@@ -0,0 +1,47 @@
+/**
+ * Resolution & Chunks operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 2). Op consts stay module-private; `chunksOperations`
+ * below lists them in EXACTLY the order they appear in the canonical
+ * `operations` array in ../operations.ts. Never import from
+ * '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { federatedSearchScope, sourceScopeOpts } from './context.ts';
+
+// --- Resolution & Chunks ---
+
+const resolve_slugs: Operation = {
+ name: 'resolve_slugs',
+ description: 'Fuzzy-resolve a partial slug to matching page slugs',
+ params: {
+ partial: { type: 'string', required: true, description: "Partial slug or title text to match, e.g. 'alice-ex' or 'meeting notes'. This is the search text param — there is no `text` param." },
+ },
+ handler: async (ctx, p) => {
+ // #3242: was fully UNSCOPED — the one read that leaked every source's
+ // slugs to any caller (the reporter's "resolve_slugs sees them but
+ // get_page doesn't" matrix). Route through the same visibility set as
+ // get_page/search: grant > federated set > scalar source.
+ return ctx.engine.resolveSlugs(p.partial as string, federatedSearchScope(ctx));
+ },
+ scope: 'read',
+};
+
+const get_chunks: Operation = {
+ name: 'get_chunks',
+ description: 'Get content chunks for a page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose content chunks to return.' },
+ },
+ handler: async (ctx, p) => {
+ // #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.
+ return ctx.engine.getChunks(p.slug as string, sourceScopeOpts(ctx));
+ },
+ scope: 'read',
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const chunksOperations: Operation[] = [resolve_slugs, get_chunks];
diff --git a/src/core/ops/code-intel.ts b/src/core/ops/code-intel.ts
new file mode 100644
index 0000000000..e8a498c2b5
--- /dev/null
+++ b/src/core/ops/code-intel.ts
@@ -0,0 +1,253 @@
+/**
+ * Code-intelligence operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 3): the v0.34 Cathedral III MCP wrappers (code_callers /
+ * code_callees / code_def / code_refs), the W3 recursive code_blast +
+ * code_flow, and the W3b code_traversal_cache_clear admin op. Op consts stay
+ * module-private; `codeIntelOperations` below lists them in EXACTLY the
+ * order they appear in the canonical `operations` array in ../operations.ts.
+ * Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { resolveCodeIntelScope } from './context.ts';
+import {
+ CODE_CALLERS_DESCRIPTION,
+ CODE_CALLEES_DESCRIPTION,
+ CODE_DEF_DESCRIPTION,
+ CODE_REFS_DESCRIPTION,
+} from '../operations-descriptions.ts';
+
+// ──────────────────────────────────────────────────────────────────────────────
+// v0.34 Cathedral III — code-intelligence ops (MCP-exposed).
+//
+// Pre-v0.34 code-callers / code-callees / code-def / code-refs lived only in
+// the CLI_ONLY set at cli.ts:30 — agents calling gbrain via MCP couldn't reach
+// them and fell through to text search. These wrappers expose the existing
+// engine + library functions to the MCP surface with resolver-grade
+// descriptions (operations-descriptions.ts) so agents route to them
+// automatically during plan-mode.
+//
+// All four are scope:'read'. Source-scoped via ctx.sourceId when set.
+// Both `source_id` and `all_sources` are params so per-call overrides work.
+// ──────────────────────────────────────────────────────────────────────────────
+
+const code_callers: Operation = {
+ name: 'code_callers',
+ description: CODE_CALLERS_DESCRIPTION,
+ params: {
+ symbol: { type: 'string', required: true, description: 'Symbol to find callers of (bare or qualified name).' },
+ limit: { type: 'number', description: 'Max edges returned. Default 100.' },
+ source_id: { type: 'string', description: "Scope to a single source. Defaults to ctx.sourceId; '__all__' spans every source for trusted local callers, your granted sources for remote callers." },
+ all_sources: { type: 'boolean', description: 'Span sources (equivalent to source_id=__all__): every source locally, your grant remotely.' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const symbol = p.symbol as string;
+ const limit = (p.limit as number) ?? 100;
+ const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
+ // Single trust+grant resolver: remote callers can't span sources outside
+ // their grant, and `__all__` collapses to their grant (not the whole brain).
+ const { allSources, sourceId } = resolveCodeIntelScope(ctx, sourceIdParam, p.all_sources === true);
+ const edges = await ctx.engine.getCallersOf(symbol, {
+ limit,
+ allSources,
+ sourceId,
+ });
+ const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
+ const readiness = await resolveCodeReadiness(ctx.engine, {
+ kind: 'edge', count: edges.length, sourceId, allSources,
+ });
+ return { symbol, count: edges.length, status: readiness.status, ready: readiness.ready, callers: edges };
+ },
+ cliHints: { name: 'code_callers', hidden: true },
+};
+
+const code_callees: Operation = {
+ name: 'code_callees',
+ description: CODE_CALLEES_DESCRIPTION,
+ params: {
+ symbol: { type: 'string', required: true, description: 'Symbol to find callees of (bare or qualified name).' },
+ limit: { type: 'number', description: 'Max edges returned. Default 100.' },
+ source_id: { type: 'string', description: "Scope to a single source. Defaults to ctx.sourceId; '__all__' spans every source for trusted local callers, your granted sources for remote callers." },
+ all_sources: { type: 'boolean', description: 'Span sources: every source locally, your grant remotely.' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const symbol = p.symbol as string;
+ const limit = (p.limit as number) ?? 100;
+ const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
+ // Single trust+grant resolver (see code_callers).
+ const { allSources, sourceId } = resolveCodeIntelScope(ctx, sourceIdParam, p.all_sources === true);
+ const edges = await ctx.engine.getCalleesOf(symbol, {
+ limit,
+ allSources,
+ sourceId,
+ });
+ const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
+ const readiness = await resolveCodeReadiness(ctx.engine, {
+ kind: 'edge', count: edges.length, sourceId, allSources,
+ });
+ return { symbol, count: edges.length, status: readiness.status, ready: readiness.ready, callees: edges };
+ },
+ cliHints: { name: 'code_callees', hidden: true },
+};
+
+const code_def: Operation = {
+ name: 'code_def',
+ description: CODE_DEF_DESCRIPTION,
+ params: {
+ symbol: { type: 'string', required: true, description: 'Symbol name (bare token; e.g., parseMarkdown, BrainEngine).' },
+ limit: { type: 'number', description: 'Max definition sites returned. Default 20.' },
+ lang: { type: 'string', description: "Filter by content_chunks.language (e.g. 'typescript', 'python')." },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { findCodeDef } = await import('../../commands/code-def.ts');
+ const defs = await findCodeDef(ctx.engine, p.symbol as string, {
+ limit: (p.limit as number) ?? 20,
+ language: (p.lang as string) || undefined,
+ });
+ // code_def is brain-wide (not source-scoped); readiness is 'symbol' grain.
+ const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
+ const readiness = await resolveCodeReadiness(ctx.engine, { kind: 'symbol', count: defs.length });
+ return { symbol: p.symbol as string, count: defs.length, status: readiness.status, ready: readiness.ready, defs };
+ },
+ cliHints: { name: 'code_def', hidden: true },
+};
+
+const code_refs: Operation = {
+ name: 'code_refs',
+ description: CODE_REFS_DESCRIPTION,
+ params: {
+ symbol: { type: 'string', required: true, description: 'Symbol to find references to.' },
+ limit: { type: 'number', description: 'Max references returned. Default 50.' },
+ lang: { type: 'string', description: "Filter by content_chunks.language." },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { findCodeRefs } = await import('../../commands/code-refs.ts');
+ const refs = await findCodeRefs(ctx.engine, p.symbol as string, {
+ limit: (p.limit as number) ?? 50,
+ language: (p.lang as string) || undefined,
+ });
+ // code_refs is brain-wide (not source-scoped); readiness is 'symbol' grain.
+ const { resolveCodeReadiness } = await import('../code-graph-readiness.ts');
+ const readiness = await resolveCodeReadiness(ctx.engine, { kind: 'symbol', count: refs.length });
+ return { symbol: p.symbol as string, count: refs.length, status: readiness.status, ready: readiness.ready, refs };
+ },
+ cliHints: { name: 'code_refs', hidden: true },
+};
+
+// --- v0.34 W3: recursive code_blast + code_flow ---
+
+const code_blast: Operation = {
+ name: 'code_blast',
+ description: 'BEFORE editing any function, run code_blast with the symbol name to surface every transitive caller grouped by depth (direct → 2-hop → 3-hop). Use this during plan-mode to size the change. Returns up to 200 nodes. Returns: {result, depth_groups?, truncation?, cycles_detected?, did_you_mean?, candidates?}. Example ok: {result:"ok", depth_groups:[{depth:1, nodes:[{symbol,chunk_id}], confidence:0.77}], truncation:"none"}.',
+ params: {
+ symbol: { type: 'string', required: true, description: 'Bare or qualified symbol name (e.g. "performSync" or "src/foo::performSync")' },
+ depth: { type: 'number', description: 'Hop cap (default 5, max 8)' },
+ max_nodes: { type: 'number', description: 'Result-set cap (default 200)' },
+ exact: { type: 'boolean', description: 'Skip bare-name disambiguation; treat symbol as exact qualified name' },
+ source_id: { type: 'string', description: 'Source to traverse. Defaults to ctx.sourceId; federated clients with multiple granted sources must specify one.' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { runRecursiveWalk } = await import('../code-intel/recursive-walk.ts');
+ const { getCachedOrCompute } = await import('../code-intel/traversal-cache.ts');
+ const symbol = p.symbol as string;
+ const depth = Math.min((p.depth as number) ?? 5, 8);
+ const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200);
+ const exact = (p.exact as boolean) ?? false;
+ // Single trust+grant resolver: a remote federated client can't traverse a
+ // source outside its grant (pre-fix this scoped by bare ctx.sourceId only).
+ // Falls back to ctx.sourceId (a required string) for the trusted-local case,
+ // exactly preserving pre-fix local behavior.
+ const { sourceId: scopedSourceId } = resolveCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
+ const sourceId = scopedSourceId ?? ctx.sourceId;
+ return getCachedOrCompute(
+ ctx.engine,
+ { symbol_qualified: symbol, depth, source_id: sourceId },
+ () => runRecursiveWalk(ctx.engine, symbol, {
+ direction: 'callers',
+ depth,
+ maxNodes: max_nodes,
+ sourceId,
+ exact,
+ }),
+ );
+ },
+ cliHints: { name: 'code_blast', hidden: true },
+};
+
+const code_flow: Operation = {
+ name: 'code_flow',
+ description: 'When tracing how a request flows through the codebase from entry point to side effect (DB write, HTTP call, file I/O), run code_flow from the entry point. Returns ordered execution chain with terminal-node tags. Returns: same envelope as code_blast plus terminal_nodes: [{symbol, sink_kind}] where sink_kind ∈ "db_call"|"http_call"|"file_io"|"process_exec"|"unknown".',
+ params: {
+ entry_point: { type: 'string', required: true, description: 'Entry-point symbol name (bare or qualified)' },
+ depth: { type: 'number', description: 'Hop cap (default 8, max 12)' },
+ max_nodes: { type: 'number', description: 'Result-set cap (default 200)' },
+ exact: { type: 'boolean', description: 'Skip bare-name disambiguation' },
+ source_id: { type: 'string', description: 'Source to traverse. Defaults to ctx.sourceId; federated clients with multiple granted sources must specify one.' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { runRecursiveWalk } = await import('../code-intel/recursive-walk.ts');
+ const { getCachedOrCompute } = await import('../code-intel/traversal-cache.ts');
+ const symbol = p.entry_point as string;
+ const depth = Math.min((p.depth as number) ?? 8, 12);
+ const max_nodes = Math.min((p.max_nodes as number) ?? 200, 200);
+ const exact = (p.exact as boolean) ?? false;
+ // Single trust+grant resolver (see code_blast).
+ const { sourceId: scopedSourceId } = resolveCodeIntelScope(ctx, typeof p.source_id === 'string' ? p.source_id : undefined);
+ const sourceId = scopedSourceId ?? ctx.sourceId;
+ return getCachedOrCompute(
+ ctx.engine,
+ { symbol_qualified: symbol + ':flow', depth, source_id: sourceId },
+ () => runRecursiveWalk(ctx.engine, symbol, {
+ direction: 'callees',
+ depth,
+ maxNodes: max_nodes,
+ sourceId,
+ exact,
+ }),
+ );
+ },
+ cliHints: { name: 'code_flow', hidden: true },
+};
+
+// --- v0.34 W3b: code_traversal_cache admin op ---
+
+const code_traversal_cache_clear: Operation = {
+ name: 'code_traversal_cache_clear',
+ description: 'Clear cached code_blast / code_flow traversal results. Source-scoped by default; pass all_sources=true to wipe everything (D8 destructive-guard).',
+ params: {
+ source_id: { type: 'string', description: 'Source to clear. Required unless all_sources=true.' },
+ all_sources: { type: 'boolean', description: 'Wipe cache across every source. Explicit opt-out of source-scoping.' },
+ },
+ mutating: true,
+ scope: 'admin',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ // INTENTIONAL exemption from resolveRequestedScope: this is a localOnly
+ // admin/destructive op with its own D8 all_sources guard. The read-side
+ // trust+grant resolver does not apply here (no remote caller reaches it).
+ const { clearTraversalCache } = await import('../code-intel/traversal-cache.ts');
+ const sourceId = (p.source_id as string | undefined) ?? ctx.sourceId;
+ const allSources = (p.all_sources as boolean) ?? false;
+ if (ctx.dryRun) {
+ return { dry_run: true, action: 'code_traversal_cache_clear', source_id: sourceId, all_sources: allSources };
+ }
+ const deleted = await clearTraversalCache(ctx.engine, {
+ sourceId: allSources ? undefined : sourceId,
+ allSources,
+ });
+ return { deleted, source_id: allSources ? null : sourceId, all_sources: allSources };
+ },
+ cliHints: { name: 'code_traversal_cache_clear', hidden: true },
+};
+
+export const codeIntelOperations: Operation[] = [
+ code_callers, code_callees, code_def, code_refs,
+ code_blast, code_flow,
+ code_traversal_cache_clear,
+];
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
new file mode 100644
index 0000000000..2e5c79d95d
--- /dev/null
+++ b/src/core/ops/context.ts
@@ -0,0 +1,646 @@
+/**
+ * Context validators + scope resolvers for the operations layer (pure move
+ * from src/core/operations.ts): upload/slug/filename validators, the
+ * subagent + bound-client slug fences, and the source-scope resolution
+ * ladder every read-side op routes through. Helpers that were file-private
+ * in operations.ts (enforceSubagentSlugFence, slugUnderSubagentFence,
+ * slugOutsideCallerFence, enforceClientSlugFence, BOUND_CLIENT_META_OPS,
+ * stampEvidenceSafe, maybeCaptureSearch) are exported HERE for future domain
+ * modules, but are deliberately NOT re-exported from operations.ts — they
+ * were never part of its public surface.
+ */
+
+import { lstatSync, realpathSync } from 'fs';
+import { resolve, relative, sep } from 'path';
+import { OperationError } from './contract.ts';
+import type { AuthInfo, Operation, OperationContext } from './contract.ts';
+import { CJK_SLUG_CHARS, PAGE_SLUG_SEG } from '../cjk.ts';
+import { ALL_SOURCES } 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';
+
+// --- Upload validators (Fix 1 / B5 / H5 / M4) ---
+
+/**
+ * Validate an upload path. Two modes:
+ * - strict (remote=true): confines the resolved path to `root` and rejects symlinks.
+ * Used when the caller is untrusted (MCP over stdio/HTTP, agent-facing).
+ * - loose (remote=false): only verifies the file exists and is not a symlink whose
+ * target escapes the filesystem (no path traversal protection). Used for local CLI
+ * where the user owns the filesystem.
+ *
+ * Either way: symlinks in the final component are always rejected (prevents
+ * transparent redirection to a different file than the user typed).
+ *
+ * @param filePath caller-supplied path
+ * @param root confinement root (only used when strict=true)
+ * @param strict true → enforce cwd confinement (B5 + H1). false → allow any accessible path.
+ * @throws OperationError(invalid_params) on symlink escape, traversal, or missing file
+ */
+export function validateUploadPath(filePath: string, root: string, strict = true): string {
+ let real: string;
+ try {
+ real = realpathSync(resolve(filePath));
+ } catch (e: unknown) {
+ const msg = e instanceof Error ? e.message : String(e);
+ if (msg.includes('ENOENT')) {
+ throw new OperationError('invalid_params', `File not found: ${filePath}`);
+ }
+ throw new OperationError('invalid_params', `Cannot resolve path: ${filePath}`);
+ }
+ // Always reject final-component symlinks (basic safety for both modes).
+ try {
+ if (lstatSync(resolve(filePath)).isSymbolicLink()) {
+ throw new OperationError('invalid_params', `Symlinks are not allowed for upload: ${filePath}`);
+ }
+ } catch (e) {
+ if (e instanceof OperationError) throw e;
+ // lstat race with unlink — pass if realpath already succeeded.
+ }
+
+ if (!strict) return real;
+
+ // Strict mode: confine to root via realpath + path.relative (catches parent-dir symlinks per B5).
+ let realRoot: string;
+ try {
+ realRoot = realpathSync(root);
+ } catch {
+ throw new OperationError('invalid_params', `Confinement root not accessible: ${root}`);
+ }
+ const rel = relative(realRoot, real);
+ if (rel === '' || rel.startsWith('..') || rel.startsWith(`..${sep}`) || resolve(realRoot, rel) !== real) {
+ throw new OperationError('invalid_params', `Upload path must be within the working directory: ${filePath}`);
+ }
+ return real;
+}
+
+/**
+ * Allowlist validator for page slugs. Rejects URL-encoded traversal, backslashes,
+ * control chars, RTL overrides, Unicode lookalikes — anything outside the allowlist.
+ * Format: lowercase alphanumeric + hyphen segments separated by single forward slashes.
+ */
+export function validatePageSlug(slug: string): void {
+ if (typeof slug !== 'string' || slug.length === 0) {
+ throw new OperationError('invalid_params', 'page_slug must be a non-empty string');
+ }
+ if (slug.length > 255) {
+ throw new OperationError('invalid_params', 'page_slug exceeds 255 characters');
+ }
+ // #3417: letters/numbers from any script allowed in segments (u flag required
+ // for the \p{...} classes in PAGE_SLUG_SEG). Shape rules (lead char, hyphen
+ // continuation) preserved.
+ if (!new RegExp(`^${PAGE_SLUG_SEG}(\\/${PAGE_SLUG_SEG})*$`, 'iu').test(slug)) {
+ throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, hyphens, forward-slash separated segments)`);
+ }
+}
+
+/**
+ * Match a slug against a list of allow-list prefix globs.
+ *
+ * Glob form: `<prefix>/*` matches any slug starting with `<prefix>/` and
+ * having at least one more segment (single or multi). Bare `<prefix>` (no
+ * trailing `/*`) matches that exact slug only. The `*` is intentionally
+ * permissive — depth is unbounded, so `wiki/originals/*` matches both
+ * `wiki/originals/idea-x` and `wiki/originals/ideas/2026-04-25-idea-y`.
+ *
+ * Used by the v0.23 dream-cycle trusted-workspace path. Order doesn't
+ * matter; the first match wins (returns true on any match).
+ */
+export function matchesSlugAllowList(slug: string, prefixes: readonly string[]): boolean {
+ for (const p of prefixes) {
+ if (p.endsWith('/*')) {
+ const base = p.slice(0, -2);
+ if (slug === base) continue;
+ if (slug.startsWith(base + '/')) return true;
+ } else if (p === slug) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Subagent slug-fence enforcement, shared by every mutating op a subagent
+ * can reach (put_page, add_timeline_entry). FAIL-CLOSED: `viaSubagent=true`
+ * enforces the check even if the dispatcher forgot to populate `subagentId`.
+ *
+ * - Trusted-workspace path (ctx.allowedSlugPrefixes set by cycle.ts under
+ * PROTECTED_JOB_NAMES \u2014 MCP cannot reach it): slug must match the
+ * allow-list globs.
+ * - Legacy default: slug must live under `wiki/agents/<subagentId>/...`
+ * (anchored, slash-boundary \u2014 `wiki/agents/12evil/*` can't impersonate
+ * subagent 12).
+ */
+export function enforceSubagentSlugFence(ctx: OperationContext, slug: string, opName: string): void {
+ if (ctx.viaSubagent !== true) return;
+ if (typeof ctx.subagentId !== 'number' || Number.isNaN(ctx.subagentId)) {
+ throw new OperationError('permission_denied', `${opName} via subagent requires ctx.subagentId`);
+ }
+ if (slugUnderSubagentFence(ctx, slug)) return;
+ const allowList = ctx.allowedSlugPrefixes;
+ throw new OperationError(
+ 'permission_denied',
+ allowList && allowList.length > 0
+ ? `${opName} slug '${slug}' is not within the trusted-workspace allow-list (${allowList.join(', ')})`
+ : `${opName} via subagent must write under 'wiki/agents/${ctx.subagentId}/...'`,
+ );
+}
+
+/**
+ * The subagent fence's MATCH RULE, without the throwing. Split out so the
+ * resolved-slug re-check in put_page can ask the same question the entry
+ * fence asks, instead of re-deriving the namespace literal and drifting.
+ * Callers must have already established `ctx.viaSubagent === true`.
+ */
+export function slugUnderSubagentFence(ctx: OperationContext, slug: string): boolean {
+ const allowList = ctx.allowedSlugPrefixes;
+ if (allowList && allowList.length > 0) return matchesSlugAllowList(slug, allowList);
+ const prefix = `wiki/agents/${ctx.subagentId}/`;
+ return slug.startsWith(prefix) && slug.length > prefix.length;
+}
+
+/**
+ * Is `slug` outside whatever slug confinement THIS caller is under?
+ *
+ * A caller can be confined by EITHER mechanism, and the two arrive on
+ * different context fields: an OAuth binding lands on `ctx.auth
+ * .boundSlugPrefixes` (plain-prefix grammar), while a delegated subagent
+ * lands on `ctx.viaSubagent` + `ctx.allowedSlugPrefixes` (glob grammar) and
+ * carries NO `ctx.auth` at all. Testing only the OAuth field therefore lets
+ * a bound client that also holds `agent` scope re-open the path it is fenced
+ * out of simply by delegating the write through submit_agent — the same
+ * bypass shape the facts-backstop gate below is keyed against.
+ *
+ * Unconfined callers (local CLI, unbound client) match neither arm and are
+ * never fenced.
+ */
+export function slugOutsideCallerFence(ctx: OperationContext, slug: string): boolean {
+ const bound = ctx.auth?.boundSlugPrefixes;
+ if (bound && !slugUnderBoundPrefixes(bound, slug)) return true;
+ if (ctx.viaSubagent === true && !slugUnderSubagentFence(ctx, slug)) return true;
+ return false;
+}
+
+/**
+ * OAuth-client slug-fence enforcement (v0.42.72.0 — write-side isolation
+ * symmetry). When the authenticated client was registered with
+ * --bound-slug-prefixes, every direct slug-mutating write must target a
+ * slug under one of those prefixes. Shared by put_page, delete_page,
+ * restore_page, add_tag, remove_tag, add_link/remove_link (`from`
+ * endpoint), add_timeline_entry, revert_version, and put_raw_data; runs
+ * BEFORE each op's dry-run short-circuit so preview calls surface the
+ * same rejection.
+ *
+ * Semantics deliberately match submit_agent's bound_slug_prefixes check
+ * (plain startsWith, NOT the `/*` glob grammar of the subagent allow-list
+ * above): a non-null binding fences fail-closed (empty array = deny all
+ * writes), no binding / no auth = no fence (local CLI and unbound clients
+ * keep full-source write authority). Register prefixes with a trailing
+ * slash ('wiki/agents/alice/') — a bare 'notes' also admits
+ * 'notes-archive/...' by startsWith construction.
+ */
+export function enforceClientSlugFence(ctx: OperationContext, slug: string, opName: string): void {
+ if (ctx.auth?.fenceProjectionDegraded) {
+ throw new OperationError(
+ 'permission_denied',
+ `${opName}: this brain's oauth_clients projection is missing bound_slug_prefixes, so the write fence cannot be evaluated. Refusing the write rather than running unfenced.`,
+ 'Run `gbrain apply-migrations --yes` on the brain host.',
+ );
+ }
+ const prefixes = ctx.auth?.boundSlugPrefixes;
+ if (!prefixes) return;
+ if (!slugUnderBoundPrefixes(prefixes, slug)) {
+ throw new OperationError(
+ 'permission_denied',
+ `${opName}: slug '${slug}' is not under any of client ${ctx.auth?.clientId ?? '(unknown)'}'s bound_slug_prefixes (${prefixes.join(', ')})`,
+ );
+ }
+}
+
+/**
+ * The one place the fence's match rule lives. Exported so non-op write
+ * surfaces that never build an OperationContext (the `/ingest` route in
+ * serve-http.ts) enforce byte-identical semantics instead of re-deriving
+ * them.
+ *
+ * An empty-string prefix is IGNORED rather than honored: `startsWith('')`
+ * is true for every slug, so a stray `''` (an unset shell variable in a
+ * provisioning template) would silently turn a binding into a wildcard
+ * while still rendering as "fenced" to the operator. Registration now
+ * rejects empty prefixes outright; this is the second line of defence for
+ * rows already in the database.
+ */
+export function slugUnderBoundPrefixes(prefixes: readonly string[], slug: string): boolean {
+ // Compare against the CANONICAL slug. `validateSlug` lowercases before the
+ // row is written, so checking the caller's raw string let `EMP-ALICE/x`
+ // satisfy an `EMP-ALICE/` binding, commit as `emp-alice/x`, and only then
+ // trip the resolved-slug re-check — an error returned after the write had
+ // already landed. Registration rejects non-lowercase prefixes going
+ // forward; lowercasing both sides keeps pre-existing rows meaning what
+ // their operator intended.
+ const canonical = slug.toLowerCase();
+ return prefixes.some((bp) => {
+ const base = normalizeSlugPrefix(bp);
+ if (base === '') return false;
+ // Boundary-aware: a prefix must match whole SEGMENTS. Plain `startsWith`
+ // let a boundary-less `emp-alice` admit `emp-alice-2/onboarding` — and
+ // with the `emp-<slug>` naming this guide recommends, sibling collisions
+ // (`alice` vs `alice-2`) are the common case, not a corner case.
+ return base.endsWith('/')
+ ? canonical.startsWith(base)
+ : canonical === base || canonical.startsWith(`${base}/`);
+ });
+}
+
+/**
+ * Canonical form of one stored prefix, lowercased. `oauth_clients.bound_slug_prefixes`
+ * predates this fence — migration v85 introduced it as submit_agent's binding,
+ * whose grammar is the `<prefix>/*` glob of `matchesSlugAllowList` — so both
+ * spellings have to mean the same span of slugs or upgrading silently changes
+ * what an existing client may write.
+ */
+export function normalizeSlugPrefix(prefix: string): string {
+ return (prefix.endsWith('/*') ? prefix.slice(0, -1) : prefix).toLowerCase();
+}
+
+/**
+ * Write ops a slug-bound client may call: every op that routes through
+ * `enforceClientSlugFence`, plus `think` (scope `read` for remote callers;
+ * it stays on this list because it is `mutating` locally, but remote callers
+ * cannot persist — `save`/`take` are forced false for `remote !== false`).
+ *
+ * This list is an ALLOW-list on purpose. The fence used to be enforced op
+ * by op, which made every unfenced write op a silent hole — `extract_entities`
+ * mutating `people/*` timelines, `forget_fact` rewriting another source's
+ * page by numeric id, `extract_facts` appending to any entity's fact fence.
+ * Enumerating what is SAFE fails closed instead: a write op added later is
+ * denied to bound clients until someone fences it and adds it here.
+ */
+export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set([
+ 'put_page', 'delete_page', 'restore_page', 'add_tag', 'remove_tag',
+ 'add_link', 'remove_link', 'add_timeline_entry', 'revert_version',
+ 'put_raw_data', 'think',
+ // submit_agent enforces bound_slug_prefixes itself (it is the op the column
+ // was introduced for — see its bound_* binding check), so denying it here
+ // would break the original feature for clients that legitimately hold both
+ // a binding and `agent` scope.
+ 'submit_agent',
+]);
+
+/**
+ * WP4 (D9) — discovery meta-ops exempt from the bound-client fence's
+ * LISTING/dispatch denial. `request_tools` is `mutating: true` (its persist
+ * branch writes oauth_clients.surface), which would otherwise hide discovery
+ * from every slug-bound client. The exemption is safe because the persist
+ * branch SELF-ENFORCES its own guards — server ceiling (D2), operator lock
+ * (amendment 19), OAuth scopes, and a per-client rate limit (D14.5) — and it
+ * never touches a slug. Lives here (not inline in the predicate) so the
+ * tools/list filter and the dispatch fence consume the identical carve-out
+ * (ENG-3 drift-proofing).
+ */
+export const BOUND_CLIENT_META_OPS: ReadonlySet<string> = new Set(['request_tools']);
+
+/**
+ * Single source of truth for "may a slug-bound client use this op" (ENG-3).
+ * Consumed by BOTH the dispatch-time fence below AND the tools/list filter
+ * in serve-http, so the advertised catalog and the deny behavior cannot
+ * drift — a bound client is never shown an op that will fence-deny at call
+ * time. Gate on "mutates, or carries any non-read scope" rather than on the
+ * two literal scope strings 'write'/'admin': `sources_add`/`sources_remove`
+ * carry the bespoke `sources_admin` scope and are `mutating: true`, so a
+ * scope-string check let a bound client DROP AN ENTIRE SOURCE — every page
+ * in it, far outside any prefix. Anything that isn't a plain read must be
+ * explicitly allow-listed. A degraded projection (binding unreadable) denies
+ * every non-read op — the unfenceable ops must not stay reachable precisely
+ * when the fence is unreadable. Exception: BOUND_CLIENT_META_OPS (D9) stay
+ * allowed even degraded — they are slug-free discovery ops whose only write
+ * self-enforces ceiling+lock+scopes+rate-limit (and a degraded projection
+ * also dropped the surface columns, so that write fails 'migration pending'
+ * rather than running unguarded).
+ */
+export function opAllowedForBoundClient(
+ auth: Pick<AuthInfo, 'boundSlugPrefixes' | 'fenceProjectionDegraded'> | undefined,
+ op: Pick<Operation, 'name' | 'scope' | 'mutating'>,
+): boolean {
+ const degraded = auth?.fenceProjectionDegraded === true;
+ if (!degraded && !auth?.boundSlugPrefixes) return true;
+ const isRead = op.scope === 'read' && op.mutating !== true;
+ if (isRead) return true;
+ if (BOUND_CLIENT_META_OPS.has(op.name)) return true;
+ if (degraded) return false;
+ return CLIENT_FENCED_WRITE_OPS.has(op.name);
+}
+
+/**
+ * Fail-closed gate for slug-bound clients, applied at dispatch (the single
+ * choke point both MCP transports share) so it cannot be forgotten per op.
+ * Read ops are untouched — read scope is enforced by source federation.
+ * Allow/deny derives from `opAllowedForBoundClient`; this wrapper only owns
+ * the error envelopes.
+ */
+export function enforceBoundClientOpAllowList(
+ auth: AuthInfo | undefined,
+ op: Pick<Operation, 'name' | 'scope' | 'mutating'>,
+): void {
+ if (opAllowedForBoundClient(auth, op)) return;
+ const degraded = auth?.fenceProjectionDegraded === true;
+ if (degraded) {
+ const err = new OperationError(
+ 'permission_denied',
+ `${op.name}: this brain's oauth_clients projection is missing bound_slug_prefixes, so client write bindings cannot be evaluated. Refusing every non-read operation rather than running unfenced.`,
+ 'Run `gbrain apply-migrations --yes` on the brain host.',
+ );
+ // Amendment 33 / D10: OP-level fence denial — the tools/list filter
+ // (opAllowedForBoundClient, the same predicate) should have hidden this
+ // op, so serve-http counts it toward the honest-catalog metric
+ // (status='denied_after_list'). key=value detail grammar (WP1).
+ err.detail = 'fence=op';
+ throw err;
+ }
+ const err = new OperationError(
+ 'permission_denied',
+ `${op.name} is not available to slug-bound clients: it can write outside client ${auth?.clientId ?? '(unknown)'}'s bound_slug_prefixes (${(auth?.boundSlugPrefixes ?? []).join(', ')}).`,
+ 'Use put_page / add_timeline_entry / add_link under your own prefixes, or ask an operator to clear the binding with `gbrain auth rescope-client <id> --bound-slug-prefixes none`.',
+ );
+ // Amendment 33 / D10: op-level, not argument-level — see above. The
+ // slug-prefix ARGUMENT denials (enforceClientSlugFence) deliberately do
+ // NOT carry this marker: a listed write op denying an out-of-fence slug
+ // is legitimate and excluded from the metric.
+ err.detail = 'fence=op';
+ throw err;
+}
+
+/**
+ * Allowlist validator for uploaded file basenames. Rejects control chars, backslashes,
+ * RTL overrides (\u202E), leading dot (hidden files) and leading dash (CLI flag confusion).
+ * Allows extension dots and underscores. Max 255 chars.
+ */
+export function validateFilename(name: string): void {
+ if (typeof name !== 'string' || name.length === 0) {
+ throw new OperationError('invalid_params', 'Filename must be a non-empty string');
+ }
+ if (name.length > 255) {
+ throw new OperationError('invalid_params', 'Filename exceeds 255 characters');
+ }
+ // v0.32.7: CJK ranges (Han / Hiragana / Katakana / Hangul) allowed in filenames.
+ // Leading-dot / leading-dash rejection preserved.
+ const FILENAME_RE = new RegExp(`^[a-zA-Z0-9${CJK_SLUG_CHARS}][a-zA-Z0-9${CJK_SLUG_CHARS}._\\-]*$`);
+ if (!FILENAME_RE.test(name)) {
+ throw new OperationError('invalid_params', `Invalid filename: ${name} (allowed: alphanumeric, CJK, dot, underscore, hyphen — no leading dot/dash, no control chars or backslash)`);
+ }
+}
+
+/**
+ * v0.34.1 (#861, D9 — P0 leak seal): resolve the source-scope filter for a
+ * read-side op handler. Returns an opts fragment ready to spread into the
+ * engine call.
+ *
+ * Precedence:
+ * 1. `ctx.auth?.allowedSources` (federated read, #876) → emits
+ * `{sourceIds: [...]}`. Federated semantics subsume the scalar case.
+ * 2. `ctx.sourceId` (scalar) → emits `{sourceId: '...'}`.
+ * 3. Neither set → emits `{}`. Local CLI callers (and tests that don't
+ * populate ctx) keep the pre-v0.34 unscoped behavior.
+ *
+ * Both fields default to the engine's "no filter" behavior individually,
+ * so unset values are safe — the engine sees the same shape it did
+ * pre-v0.34. The leak this guards against is an authenticated MCP client
+ * whose ctx.sourceId IS set but whose engine call was constructed without
+ * threading it (operations.ts:968/1076/1092/935/1469/1471/2241 pre-fix).
+ *
+ * Helper rather than inline so every read-side handler routes through the
+ * same precedence ladder — drift between sites is the bug class.
+ */
+export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; sourceIds?: string[] } {
+ const allowed = ctx.auth?.allowedSources;
+ // Treat an empty `allowedSources: []` as "no federated read scope" — the
+ // op-handler defers to scalar `ctx.sourceId` below. An attacker-controlled
+ // value of `[]` MUST NOT widen scope to "all sources" by being interpreted
+ // as "no filter."
+ if (allowed && allowed.length > 0) return { sourceIds: allowed };
+ // #1712: the __all__ sentinel spans the brain — but ONLY for trusted local
+ // callers (strictly `remote === false`). For remote/untrusted callers the
+ // literal stays as-is: it can never match a real source id (underscores are
+ // rejected at creation), so the read fail-closes to empty rather than
+ // widening past the caller's grant. Do NOT "simplify" this to `{}`.
+ if (ctx.sourceId === ALL_SOURCES) {
+ return ctx.remote === false ? {} : { sourceId: ctx.sourceId };
+ }
+ if (ctx.sourceId) return { sourceId: ctx.sourceId };
+ return {};
+}
+
+/** Map the operation-layer scope names onto runThink's public options. */
+export function thinkSourceScopeOpts(ctx: OperationContext): {
+ sourceId?: string;
+ allowedSources?: string[];
+} {
+ const scope = sourceScopeOpts(ctx);
+ return scope.sourceIds !== undefined
+ ? { allowedSources: scope.sourceIds }
+ : scope.sourceId !== undefined
+ ? { sourceId: scope.sourceId }
+ : {};
+}
+
+/**
+ * #2200: source scope for the LINK read ops (get_links / get_backlinks). A link
+ * row references three pages (from, to, origin); the engine's federated
+ * (`sourceIds[]`) branch scopes ALL THREE, but its scalar (`sourceId`) branch
+ * scopes only the near endpoint — by design, because trusted internal callers
+ * (reconcileLinks, back-link validators, enrich) call the engine directly with a
+ * scalar scope and need the cross-source view.
+ *
+ * An UNTRUSTED remote caller carrying only a scalar scope (a legacy bearer token
+ * or a pre-`federated_read` OAuth client) would otherwise hit that scalar branch
+ * and have a foreign far/origin slug disclosed. So for remote callers we promote a
+ * scalar scope to a single-element `sourceIds:[id]`, routing them through the
+ * all-endpoint branch. Trusted local CLI (`ctx.remote === false`) keeps the scalar
+ * cross-source view, and a federated array passes through unchanged.
+ */
+export function linkReadScopeOpts(ctx: OperationContext): { sourceId?: string; sourceIds?: string[] } {
+ const scope = sourceScopeOpts(ctx);
+ if (ctx.remote !== false && scope.sourceId && !scope.sourceIds) {
+ return { sourceIds: [scope.sourceId] };
+ }
+ return scope;
+}
+
+/**
+ * Resolve a per-call requested source scope against the caller's trust + grant.
+ * FAIL-CLOSED: anything not strictly `ctx.remote === false` is untrusted.
+ *
+ * This is the SINGLE resolver for every read op that accepts a per-call
+ * `source_id` / `all_sources` parameter (query, code_callers, code_callees,
+ * get_page, search_by_image, code_blast, code_flow). Inlining the `__all__`
+ * branch per handler is the bug class that leaked cross-source reads (#1924,
+ * #1371): a remote client could pass `source_id: '__all__'` to opt out of its
+ * grant, or pass an explicit out-of-grant `source_id` that was never checked.
+ *
+ * - `__all__` / `all_sources`:
+ * trusted local (remote === false) → `{}` (spans the whole brain)
+ * remote → the caller's grant (sourceScopeOpts)
+ * - explicit `source_id`:
+ * remote + federated grant that doesn't include it → permission_denied
+ * otherwise → `{ sourceId }`
+ * - neither → the caller's grant (sourceScopeOpts).
+ *
+ * `code_traversal_cache_clear` is intentionally NOT a caller — it is localOnly
+ * and carries its own destructive D8 all_sources guard.
+ */
+export function resolveRequestedScope(
+ ctx: OperationContext,
+ sourceIdParam: string | undefined,
+ allSourcesParam = false,
+): { sourceId?: string; sourceIds?: string[] } {
+ const wantsAll = allSourcesParam || sourceIdParam === ALL_SOURCES;
+ if (wantsAll) {
+ return ctx.remote === false ? {} : sourceScopeOpts(ctx);
+ }
+ if (sourceIdParam !== undefined) {
+ const allowed = ctx.auth?.allowedSources;
+ if (ctx.remote !== false && allowed && allowed.length > 0 && !allowed.includes(sourceIdParam)) {
+ throw new OperationError(
+ 'permission_denied',
+ `source '${sourceIdParam}' is outside your granted sources`,
+ 'Request access to this source, or omit source_id to search within your grant.',
+ );
+ }
+ return { sourceId: sourceIdParam };
+ }
+ return sourceScopeOpts(ctx);
+}
+
+/**
+ * #2561 / #3242 — source scope for the page-visibility read ops (`search`,
+ * `query`, `get_page`, `list_pages`, `resolve_slugs`).
+ *
+ * Delegates to `resolveRequestedScope` (the single trust+grant resolver), then
+ * widens an UNQUALIFIED scalar scope to the transport-computed federated set
+ * (`ctx.localFederatedSourceIds`, resolved source first). This is what makes
+ * `sources add --federated` mean something: a federated source participates in
+ * unqualified reads (#3242 — pages ingested into a `federated: true` source
+ * were invisible to get_page/search/list_pages while resolve_slugs leaked them).
+ *
+ * The expansion NEVER applies when:
+ * - a per-call `source_id` was passed (explicit wins, including `__all__`);
+ * - the resolver already produced a federated array (OAuth grant governs);
+ * - the transport didn't populate `localFederatedSourceIds` (see that
+ * field's doc: it is only set for callers with NO explicit source scope,
+ * and never from caller-controlled params — so trust stays fail-closed).
+ *
+ * Deliberately NOT inside `sourceScopeOpts`: code-intel ops collapse a
+ * multi-element scope to an error (`resolveCodeIntelScope`), and the remaining
+ * scalar reads (get_links, get_chunks, …) keep their long-standing behavior.
+ */
+export function federatedSearchScope(
+ ctx: OperationContext,
+ sourceIdParam?: string,
+): { sourceId?: string; sourceIds?: string[] } {
+ const scope = resolveRequestedScope(ctx, sourceIdParam);
+ if (
+ sourceIdParam === undefined &&
+ scope.sourceId !== undefined &&
+ scope.sourceIds === undefined &&
+ ctx.localFederatedSourceIds !== undefined &&
+ ctx.localFederatedSourceIds.length > 1
+ ) {
+ return { sourceIds: ctx.localFederatedSourceIds };
+ }
+ return scope;
+}
+
+/**
+ * Code-intel adapter for `resolveRequestedScope`. Graph traversal
+ * (code_callers/code_callees/code_blast/code_flow) is single-source by design —
+ * the engine APIs and the traversal cache key take ONE `sourceId` string, not a
+ * federated array. So this collapses the resolver's output to `{allSources,
+ * sourceId}`, fail-closed:
+ *
+ * - resolver → one source (scalar or single-element grant) → that source
+ * - resolver → multi-source grant (federated remote client) → reject: ask the
+ * caller to specify which granted source (we must not silently span all)
+ * - resolver → empty scope → `allSources` ONLY for trusted local callers; a
+ * remote caller with no source in scope is denied, never widened to all.
+ */
+export function resolveCodeIntelScope(
+ ctx: OperationContext,
+ sourceIdParam: string | undefined,
+ allSourcesParam = false,
+): { allSources: boolean; sourceId?: string } {
+ const scope = resolveRequestedScope(ctx, sourceIdParam, allSourcesParam);
+ if (scope.sourceId) return { allSources: false, sourceId: scope.sourceId };
+ if (scope.sourceIds && scope.sourceIds.length === 1) {
+ return { allSources: false, sourceId: scope.sourceIds[0] };
+ }
+ if (scope.sourceIds && scope.sourceIds.length > 1) {
+ throw new OperationError(
+ 'invalid_params',
+ 'Code traversal runs against a single source. Specify source_id (one of your granted sources).',
+ 'Pass source_id=<one of your sources>.',
+ );
+ }
+ // Empty scope: span everything only for trusted local callers; a remote caller
+ // that reached here has no source in scope and must NOT get cross-source results.
+ if (ctx.remote === false) return { allSources: true, sourceId: undefined };
+ throw new OperationError(
+ 'permission_denied',
+ 'No source in scope for this request.',
+ 'Specify source_id, or check your granted sources.',
+ );
+}
+
+/**
+ * T4/D5 — resolve a per-call search-mode override. Honored ONLY for trusted/
+ * local callers (ctx.remote === false) so a remote OAuth client can't escalate
+ * to the costly tokenmax bundle. Local + unknown mode → loud reject; remote +
+ * mode → silently ignored (server-configured mode wins). Returns undefined to
+ * mean "use the configured mode".
+ */
+export function resolvePerCallMode(ctx: OperationContext, raw: unknown): string | undefined {
+ if (typeof raw !== 'string' || raw.length === 0) return undefined;
+ if (ctx.remote !== false) return undefined; // remote can't select mode
+ if (!isSearchMode(raw)) {
+ throw new OperationError(
+ 'invalid_params',
+ `Unknown search mode '${raw}'. Valid: conservative, balanced, tokenmax.`,
+ `gbrain search "<query>" --mode balanced`,
+ );
+ }
+ return raw;
+}
+
+/** T4 — stamp evidence/create_safety on a result set, fail-soft. */
+export function stampEvidenceSafe(results: SearchResult[]): void {
+ try { stampEvidence(results); } catch { /* non-fatal */ }
+}
+
+/** T4 — shared eval-capture for the `search` op (keyword-only + cheap-hybrid paths). */
+export function maybeCaptureSearch(
+ ctx: OperationContext,
+ queryText: string,
+ results: SearchResult[],
+ latency_ms: number,
+ vectorEnabled: boolean,
+ meta?: HybridSearchMeta | null,
+): void {
+ if (!isEvalCaptureEnabled(ctx.config)) return;
+ void captureEvalCandidate(
+ ctx.engine,
+ {
+ tool_name: 'search',
+ query: queryText,
+ results,
+ meta: meta ?? { vector_enabled: vectorEnabled, detail_resolved: null, expansion_applied: false },
+ latency_ms,
+ remote: ctx.remote ?? false,
+ expand_enabled: false,
+ detail: null,
+ job_id: ctx.jobId ?? null,
+ subagent_id: ctx.subagentId ?? null,
+ },
+ { scrub_pii: isEvalScrubEnabled(ctx.config) },
+ );
+}
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
new file mode 100644
index 0000000000..ee2301ee42
--- /dev/null
+++ b/src/core/ops/contract.ts
@@ -0,0 +1,476 @@
+/**
+ * Foundation contract for the operations layer (pure move from
+ * src/core/operations.ts): the error envelope (ErrorCode / OperationError /
+ * verbError), the shared param/logger/auth/context types, and the Operation
+ * interface that every op declaration conforms to. operations.ts re-exports
+ * this entire surface, so existing importers are unchanged.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { MEMORY_VERBS_VERSION } from '../verbs.ts';
+
+// --- Types ---
+
+/**
+ * v0.31 (eD6 / eE7): ErrorCode is now an OPEN union via the
+ * `(string & {})` autocomplete-friendly hack. Downstream consumers (e.g.
+ * gbrain-evals) get autocomplete on the named codes AND remain TS-forward-
+ * compatible when gbrain adds new codes in future releases. This shape is
+ * the standard Anthropic-API/OpenAI-API pattern.
+ *
+ * v0.31 added: 'rate_limited', 'extraction_failed', 'fact_not_found'.
+ */
+export type ErrorCode =
+ | 'page_not_found'
+ | 'invalid_params'
+ | 'embedding_failed'
+ | 'storage_error'
+ | 'bucket_not_found'
+ | 'database_error'
+ | 'permission_denied'
+ | 'unknown_transport' // v0.28.1: whoami fail-closed for ambiguous transport
+ | 'rate_limited' // v0.31: gateway rate-limit upstream
+ | 'extraction_failed' // v0.31: facts extractor failed (refusal, parse, abort)
+ | 'fact_not_found' // v0.31: forget_fact / recall on unknown id
+ // MEMORY_VERBS v1 protocol codes (frozen — docs/protocol/MEMORY_VERBS_v1.md).
+ // Coarse on purpose: codes are for branching (configure/retry vs caller bug
+ // vs server bug); the freeform `detail` field carries specifics.
+ | 'not_found' // unknown resource. Verb-level (forget: unknown fact id) AND
+ // get_agent_job's uniform foreign-or-missing envelope (anti-enumeration:
+ // a caller cannot distinguish another client's job from a nonexistent id)
+ | 'scope_denied' // verb-level: OAuth scope / trust-boundary refusal
+ | 'provenance_required' // remember: provenance missing or empty
+ | 'unavailable' // a required dependency cannot serve (no API key, gateway down, model refusal)
+ | 'budget_unsatisfiable' // RESERVED in v1 — schema-listed, never returned
+ // eslint-disable-next-line @typescript-eslint/ban-types
+ | (string & {}); // OPEN union for forward-compat (eE7 / D13)
+
+export class OperationError extends Error {
+ /**
+ * MEMORY_VERBS v1: verb handlers set `protocolVersion` (=1) and may set
+ * `detail` (freeform specifics, e.g. which dependency failed). Both are
+ * additive — non-verb ops never set them and their envelopes are unchanged
+ * (undefined keys drop out of JSON.stringify).
+ */
+ public detail?: string;
+ public protocolVersion?: number;
+
+ constructor(
+ public code: ErrorCode,
+ message: string,
+ public suggestion?: string,
+ public docs?: string,
+ ) {
+ super(message);
+ this.name = 'OperationError';
+ }
+
+ toJSON() {
+ return {
+ error: this.code,
+ message: this.message,
+ suggestion: this.suggestion,
+ docs: this.docs,
+ detail: this.detail,
+ protocol_version: this.protocolVersion,
+ };
+ }
+}
+
+/**
+ * MEMORY_VERBS v1 error constructor. Every verb error carries a populated
+ * `suggestion` (problem + cause + fix — agents read it and self-correct;
+ * conformance asserts non-empty) and `protocol_version: 1`.
+ */
+export function verbError(
+ code: ErrorCode,
+ message: string,
+ suggestion: string,
+ detail?: string,
+): OperationError {
+ const e = new OperationError(code, message, suggestion);
+ e.protocolVersion = MEMORY_VERBS_VERSION;
+ if (detail !== undefined) e.detail = detail;
+ return e;
+}
+
+export interface ParamDef {
+ type: 'string' | 'number' | 'boolean' | 'object' | 'array';
+ required?: boolean;
+ description?: string;
+ default?: unknown;
+ enum?: string[];
+ items?: ParamDef;
+}
+
+export interface Logger {
+ info(msg: string): void;
+ warn(msg: string): void;
+ error(msg: string): void;
+}
+
+export interface AuthInfo {
+ token: string;
+ clientId: string;
+ /**
+ * Human-readable agent name resolved at token-verification time.
+ * For OAuth clients this is `oauth_clients.client_name`; for legacy
+ * bearer tokens it is `access_tokens.name`. Threading this through
+ * AuthInfo eliminates a per-request DB roundtrip in the /mcp handler
+ * (was: SELECT client_name FROM oauth_clients WHERE client_id = ?
+ * on every request — see PR #586 review note D14=B).
+ */
+ clientName?: string;
+ scopes: string[];
+ expiresAt?: number;
+ /**
+ * v0.34.1 (#861, D2): the source the calling OAuth client is scoped
+ * to (write authority). Sourced from `oauth_clients.source_id` at
+ * token-verification time. The HTTP transport ALSO threads this
+ * value into `OperationContext.sourceId` at the same site so op
+ * handlers can consume it via the canonical `ctx.sourceId` (D2
+ * dual-write decision — identity surface symmetric with
+ * `allowedSources` below).
+ *
+ * Undefined for legacy bearer tokens that predate v0.34.1 and for
+ * clients that haven't been scoped yet. Migration v60 backfills
+ * NULL → 'default' for pre-existing rows so this field is populated
+ * on the upgrade path; brand-new public-client registrations may
+ * still leave it null until an operator explicitly scopes via
+ * `gbrain auth scope-client`.
+ */
+ sourceId?: string;
+ /**
+ * v0.34.1 (#876): array of source ids this OAuth client may READ
+ * from (federation). Sourced from `oauth_clients.federated_read`.
+ * Independent of `sourceId` (write authority): a "WeCare L3 dept"
+ * client can write to `source_id='dept-x'` while reading the union
+ * of `['dept-x', 'wecare-parent', 'shared']`.
+ *
+ * Empty array `[]` means "no federated reads beyond `sourceId`".
+ * Undefined means "the post-v60 backfill hasn't populated this row
+ * yet" — engines fall back to scalar `sourceId` filtering in that
+ * case (back-compat).
+ */
+ allowedSources?: string[];
+ /**
+ * Per-token allow-list for the holder field on `takes`, populated at
+ * token-verification time from `access_tokens.permissions.takes_holders`
+ * for legacy bearer tokens (via `parseTakesHoldersAllowList` in
+ * `src/core/legacy-token-scope.ts`). The HTTP transport threads this into
+ * `OperationContext.takesHoldersAllowList` (documented below).
+ *
+ * `[]` is an explicit deny-all grant and is PRESERVED (never collapsed).
+ * `undefined` means the token row carries no array grant — OAuth clients
+ * have no per-client storage yet (see TODOS.md) — and consumers apply the
+ * fail-closed `['world']` default at the dispatch site.
+ *
+ * Rides the same `as CoreAuthInfo as SdkAuthInfo` cast as `sourceId` /
+ * `allowedSources` above.
+ */
+ takesHoldersAllowList?: string[];
+ /**
+ * v0.42.72.0: slug-prefix WRITE binding from
+ * `oauth_clients.bound_slug_prefixes`, threaded at token-verification
+ * time (same JOIN as sourceId/allowedSources — no per-op roundtrip).
+ * When present, every direct slug-mutating write op is fenced to slugs
+ * under one of these prefixes via `enforceClientSlugFence` — the same
+ * plain-startsWith semantics (and the same fail-closed empty-array
+ * posture) as submit_agent's bound_slug_prefixes check, so one column
+ * means one thing everywhere it's read. Closes the write-side half of
+ * shared-source isolation: reads were SQL-fenced via `allowedSources`,
+ * but same-source writes were folder-convention-only.
+ *
+ * Undefined = client has no binding, or the brain predates the
+ * bound_slug_prefixes column → no fence (unbound clients keep
+ * full-source write authority, back-compat).
+ */
+ boundSlugPrefixes?: string[];
+ /**
+ * Set when token verification could not read `bound_slug_prefixes` (the
+ * projection degraded on a brain missing an OAuth column). The fence can't
+ * distinguish "no binding" from "binding unknown" otherwise, so writes are
+ * refused rather than silently unfenced. Read/auth degradation is
+ * unaffected — this axis alone fails closed.
+ */
+ fenceProjectionDegraded?: boolean;
+ /**
+ * WP4 (D2): per-client tool surface from `oauth_clients.surface`, threaded
+ * at token-verification time (same JOIN as sourceId/allowedSources). The
+ * serve-http transport resolves the request's effective surface as
+ * `min(server ceiling, this ?? config default)` — the row can narrow, never
+ * widen. Value space is OPEN (amendment 18: future client tiers write tier
+ * names into the same column); unrecognized values are ignored at
+ * resolution with a warn-log once per client. Undefined = column NULL,
+ * projection degraded, or the brain predates migration v127.
+ */
+ surface?: string;
+ /**
+ * WP4 (amendment 19) — who set `surface`: 'operator' (rescope CLI/admin
+ * endpoint; request_tools persist may NOT override it), 'self'
+ * (request_tools persist), or 'dcr_default'. Undefined when surface is
+ * unset or the projection degraded.
+ */
+ surfaceSetBy?: string;
+}
+
+export interface OperationContext {
+ engine: BrainEngine;
+ config: GBrainConfig;
+ logger: Logger;
+ dryRun: boolean;
+ /**
+ * OAuth auth info (v0.8+). Present when the caller authenticated via OAuth 2.1
+ * through `gbrain serve --http`. Contains clientId and granted scopes for
+ * per-operation scope enforcement.
+ */
+ auth?: AuthInfo;
+ /**
+ * True when the caller is remote/untrusted (MCP over stdio/HTTP, or any agent-facing entry point).
+ * False for local CLI invocations by the owner of the machine.
+ *
+ * Security-sensitive operations (e.g., file_upload) tighten their filesystem
+ * confinement when remote=true and allow unrestricted local-filesystem access
+ * when remote=false.
+ *
+ * REQUIRED as of the F7b hardening — the type system is the first line of defense.
+ * Every transport (CLI / stdio MCP / HTTP MCP / subagent dispatcher) sets this
+ * explicitly. Consumers still treat anything that isn't strictly `false` as
+ * remote/untrusted (defense in depth in case the type is bypassed via cast).
+ */
+ remote: boolean;
+ /**
+ * Transport marker for auth-less remote surfaces (#1061). The stdio MCP
+ * dispatch sets 'stdio' — it is deliberately `remote: true` (agent-facing,
+ * untrusted) but has no per-token auth (local pipe), so identity ops like
+ * whoami need a way to distinguish "known auth-less transport" from "a
+ * transport bug forgot to thread ctx.auth". Trust decisions MUST NOT key
+ * off this field — only `ctx.remote === false` grants trust. It IS the
+ * transport-LOCALITY axis: localOnly ops dispatch on 'stdio' (a local
+ * pipe with the operator's own filesystem) and are denied on 'http'
+ * (network transports), independent of the remote trust flag.
+ */
+ transport?: 'stdio' | 'http';
+ /**
+ * WP2/D3: response-meta side channel. Handlers that compute out-of-band
+ * result metadata (retrieval degradation, strict-mode warnings) publish it
+ * here under a namespaced top-level key; the MCP dispatch layer merges the
+ * collected keys into `ToolResult._meta` (one producer per key — see
+ * docs/protocol/MCP_META_CHANNELS.md). Unset on CLI/local dispatch paths,
+ * which render the same meta directly; emissions are always optional-chained.
+ */
+ emitResponseMeta?: (key: string, value: unknown) => void;
+ /**
+ * WP4 (D2): the SERVER surface ceiling for this transport (force-clamped),
+ * threaded by the MCP dispatch layer. Consumed by `request_tools`: the
+ * catalog never names ops above the ceiling, and the persist branch
+ * rejects widening past it with a machine-readable denial
+ * (`detail: "ceiling=<surface>"`). Unset (local CLI / direct dispatch) is
+ * treated as 'full'.
+ */
+ surfaceCeiling?: 'verbs' | 'starter' | 'full';
+ /**
+ * Subagent runtime context (v0.16+). Set by the subagent tool dispatcher when
+ * dispatching an op as a tool call from an LLM loop. Used to enforce per-op
+ * agent policy (e.g. put_page namespace rule).
+ *
+ * `viaSubagent` is the FAIL-CLOSED flag: when true, agent-facing policy MUST
+ * be enforced even if `subagentId` happens to be undefined (a bug in the
+ * dispatcher must not bypass the guard). `subagentId` is the owning subagent
+ * job id; `jobId` is the current Minion job id (aggregator or subagent).
+ */
+ jobId?: number;
+ subagentId?: number;
+ viaSubagent?: boolean;
+ /**
+ * Trusted-workspace allow-list (v0.23 dream cycle). When the cycle's
+ * synthesize/patterns phases dispatch a subagent, they thread an
+ * explicit list of slug-prefix globs (e.g. "wiki/personal/reflections/*")
+ * through this field. put_page enforces it BEFORE the legacy
+ * `wiki/agents/<id>/...` namespace check.
+ *
+ * Trust comes from the SUBMITTER (subagent jobs are gated by
+ * PROTECTED_JOB_NAMES — MCP cannot submit them), not from `remote`.
+ * Every subagent tool call has `remote=true` for auto-link safety,
+ * so basing trust on `remote` is incoherent (would always reject).
+ *
+ * Empty / unset → fall back to the legacy namespace check (existing
+ * v0.15 behavior; pure addition, no regression).
+ */
+ allowedSlugPrefixes?: string[];
+ /**
+ * Resolved global CLI options (--quiet / --progress-json / --progress-interval).
+ * CLI callers populate this from `getCliOptions()`. MCP / library callers
+ * may leave it undefined — consumers default to quiet/no-progress for
+ * background work.
+ */
+ cliOpts?: { quiet: boolean; progressJson: boolean; progressInterval: number };
+ /**
+ * v0.28: per-token allow-list for the holder field on `takes`. Threaded
+ * by the MCP HTTP/stdio dispatch layer from `access_tokens.permissions.takes_holders`.
+ *
+ * When set (i.e., this OperationContext came from an MCP-bound token),
+ * `takes_list`, `takes_search`, `takes_scorecard`, `takes_calibration`,
+ * and `query` (when it returns takes) MUST apply `WHERE holder = ANY($takesHoldersAllowList)`.
+ * This is the server-side filter that backs the v0.28+ visibility model.
+ *
+ * v0.30.0: aggregate ops (`takes_scorecard`, `takes_calibration`) require
+ * the allow-list as a TS-required engine method param (fail-closed by
+ * compiler). Hidden-holder rows contribute zero to aggregates. The CLI
+ * callers (local + trusted) leave it undefined.
+ *
+ * Default behavior when unset: local CLI callers see all holders. v0.28
+ * MCP dispatch sets it to `['world']` for tokens with no permissions row
+ * (default-deny on private hunches).
+ */
+ takesHoldersAllowList?: string[];
+ /**
+ * Connected-gbrains brain id (v0.19+ / v0.26 mounts). Identifies which brain
+ * this op is targeting. 'host' for the default brain configured in
+ * ~/.gbrain/config.json; otherwise a mount id registered in ~/.gbrain/mounts.json.
+ *
+ * `ctx.engine` is the resolved BrainEngine for this id (populated by
+ * BrainRegistry at dispatch time). `brainId` exists alongside for:
+ * - audit logging (mount-ops JSONL carries the id)
+ * - subagent inheritance (child jobs receive the parent's brainId)
+ * - cross-brain citation prefixes in agent output
+ *
+ * Orthogonal to v0.18.0's source_id, which scopes per-repo WITHIN a brain.
+ * See docs/architecture/brains-and-sources.md for the mental model.
+ *
+ * Omitted = 'host' (pre-v0.19 callers + single-brain deployments keep
+ * working without change).
+ */
+ brainId?: string;
+ /**
+ * v0.31 (eD4 / eE2): the in-DB tenancy axis for facts hot memory.
+ * `sources.id` is TEXT (not INTEGER) — keep this as a string.
+ *
+ * Resolved once in the dispatcher from CLI flag (--source) / env
+ * (GBRAIN_SOURCE) / `.gbrain-source` dotfile / per-token sources scope
+ * (HTTP). Defaults to 'default' when nothing else applies.
+ *
+ * Every facts read/write filter starts with `WHERE source_id = $X`
+ * so the trust boundary is part of the index path, not a callback.
+ *
+ * v0.34 D4 — REQUIRED at the TypeScript level. Mirrors v0.26.9 `remote`
+ * REQUIRED pattern that closed the HTTP RCE class. Every transport
+ * (CLI / stdio MCP / HTTP MCP / subagent dispatcher) MUST populate
+ * this field; `buildOperationContext` auto-fills 'default' for callers
+ * who don't pass an explicit sourceId, so the type contract is
+ * satisfied even on single-source brains.
+ */
+ sourceId: string;
+ /**
+ * CX2-11 — opaque per-session identity, set from MCP `_meta.session_id`
+ * (clamped to 256 chars at the dispatch boundary). Cache/telemetry identity
+ * ONLY — never an auth or trust surface. The hot-memory meta hook keys its
+ * cache on (sourceId, sessionId, allowlist-hash); before this typed field
+ * existed every caller collapsed onto the null-session cache key.
+ */
+ sessionId?: string;
+ /**
+ * #2561 / #3242 — federated read scope for UNQUALIFIED reads.
+ *
+ * Set ONLY by trusted server-side context builders — never from caller
+ * params — and only when the caller carries no explicit source scope:
+ * - local CLI (src/cli.ts makeContext) when the source resolved via a
+ * non-explicit tier (local_path / brain_default / sole_non_default /
+ * seed_default — NOT --source, NOT GBRAIN_SOURCE, NOT a dotfile);
+ * - stdio MCP (src/mcp/server.ts) when GBRAIN_SOURCE is unset;
+ * - HTTP MCP (src/mcp/http-transport.ts) for legacy bearer tokens with
+ * NO operator-set `permissions.source_id` grant (the historical
+ * 'default' floor). Tokens WITH an explicit grant never widen.
+ *
+ * Contains the resolved source first, then every other
+ * `config.federated = true` source, so an unqualified read/search spans
+ * federated sources as docs/guides/multi-source-brains.md promises.
+ *
+ * Consumed exclusively by `federatedSearchScope`. Fail-closed remains:
+ * a grant (`ctx.auth.allowedSources`) or a per-call `source_id` always
+ * wins, and a context without this field never widens.
+ */
+ localFederatedSourceIds?: string[];
+}
+
+export interface Operation {
+ name: string;
+ description: string;
+ params: Record<string, ParamDef>;
+ handler: (ctx: OperationContext, params: Record<string, unknown>) => Promise<unknown>;
+ mutating?: boolean;
+ /**
+ * Capability scope required to invoke this op over an authenticated
+ * transport. v0.28 added `sources_admin` (manage federated sources) and
+ * `users_admin` (reserved). The hierarchy lives in src/core/scope.ts —
+ * `admin` implies all, `write` implies `read`, the two `*_admin` scopes
+ * are siblings (different axes; neither implies the other). `agent` is
+ * also a sibling NOT implied by admin (v0.38 D13): admin tokens must be
+ * explicitly re-registered with bindings to touch the agent lane.
+ *
+ * Local CLI callers (ctx.remote === false) bypass scope enforcement
+ * because the trust boundary there is the OS, not OAuth scopes.
+ */
+ scope?: 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin' | 'agent';
+ localOnly?: boolean;
+ /**
+ * WP1 honest catalog: the op is callable by remote callers only when this
+ * config gate resolves true (dual-plane, DB > file > absent=false). Network
+ * transports hide the op from tools/list while the gate is off — a listed
+ * tool that always denies reads as broken, not private. The in-handler
+ * gate (assertPublishEnabled / the advisor inline check) stays as the
+ * fail-closed call-time backstop; stdio (local pipe) bypasses publish
+ * gates entirely. Resolution lives in src/mcp/publish-gates.ts.
+ */
+ publishGateKey?: 'mcp.publish_skills' | 'mcp.publish_advisor';
+ /**
+ * MEMORY_VERBS v1: marks the seven frozen protocol verbs (recall, remember,
+ * entity, synthesize, forget, context_pack, delta). `gbrain serve --surface
+ * verbs` exposes EXACTLY the ops with `verb: true`; 'starter' (the ~20-op
+ * daily-driver tier) sits between verbs and `full` (default), which exposes
+ * everything.
+ */
+ verb?: boolean;
+ /**
+ * WP4 (amendment 22) — coarse grouping label consumed by the
+ * `request_tools` catalog and the generated tool-catalog doc. Area NAMES
+ * ARE NON-CONTRACTUAL: they exist so an agent can scan ~20 groups instead
+ * of ~100 flat names; renaming/regrouping is never a breaking change.
+ * Required (by the CI walker in test/mcp-tool-defs.test.ts) on every
+ * non-localOnly op; populated centrally via OP_AREAS at the bottom of
+ * this file.
+ */
+ area?: string;
+ /**
+ * WP4 (FOV-4) — marks a discovery meta-op callable by the `agent` scope
+ * IN ADDITION to its declared scope. `agent` deliberately implies only
+ * itself (v0.38 D13), which would strand agent-only tokens with zero
+ * discovery; the MCP scope checks (serve-http tools/list + tools/call)
+ * add a one-line carve-out for ops with this flag. Currently only
+ * `request_tools`.
+ */
+ agentCallable?: true;
+ /**
+ * MCP ToolAnnotations passthrough (SDK 1.29+). Emitted by buildToolDefs
+ * ONLY when set — existing tools keep byte-identical definitions.
+ */
+ annotations?: {
+ title?: string;
+ readOnlyHint?: boolean;
+ destructiveHint?: boolean;
+ idempotentHint?: boolean;
+ };
+ cliHints?: {
+ name?: string;
+ /**
+ * Alternate CLI command names that dispatch to this same op (v114 / #1941).
+ * e.g. `link-add` aliasing `link`. Registered in `cli.ts`'s `cliAliases`
+ * map; collisions with primary names or CLI_ONLY commands throw at startup.
+ */
+ aliases?: string[];
+ positional?: string[];
+ stdin?: string;
+ hidden?: boolean;
+ };
+}
diff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.ts
new file mode 100644
index 0000000000..d33408a639
--- /dev/null
+++ b/src/core/ops/embedding-migration.ts
@@ -0,0 +1,96 @@
+/**
+ * Embedding-migration operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 3): the #3390 provider-agnostic migrate_embeddings
+ * local-only admin op. Op const stays module-private;
+ * `embeddingMigrationOperations` below is spliced into the canonical
+ * `operations` array in ../operations.ts at the cluster's original position.
+ * Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+
+// --- #3390: provider-agnostic embedding migration ---
+
+const migrate_embeddings: Operation = {
+ name: 'migrate_embeddings',
+ description: 'Re-embed the brain onto a different embedding provider/model (#3390): schema dimension transition, NULL-signature (#3391) invalidation, query-cache purge, resumable re-embed. Without yes=true returns the plan + cost estimate only. Local-only admin op; the primary surface is `gbrain migrate embeddings`.',
+ params: {
+ to: { type: 'string', required: true, description: 'Target provider:model (e.g. openai:text-embedding-3-small).' },
+ dim: { type: 'number', description: "Target dimensions. Defaults to the provider recipe's declared width; required when the recipe declares none." },
+ dry_run: { type: 'boolean', description: 'Plan + cost estimate only; change nothing.' },
+ yes: { type: 'boolean', description: 'Confirm the re-embed spend + destructive schema change. Required for a live run.' },
+ },
+ mutating: true,
+ scope: 'admin',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ // Belt-and-braces on top of localOnly (the get_recent_transcripts
+ // pattern): a schema-rebuilding, money-spending op must never be
+ // reachable from a remote transport even if a future dispatch path
+ // forgets the localOnly filter.
+ if (ctx.remote !== false) {
+ throw new Error('migrate_embeddings is local-only. Run `gbrain migrate embeddings` on the host.');
+ }
+ const {
+ planEmbeddingMigration, applyEmbeddingMigration, completeEmbeddingMigration,
+ reconcilePageSignatures, migrationSignature,
+ } = await import('../embedding-migration.ts');
+ const to = p.to as string;
+ const dim = p.dim as number | undefined;
+ let fromModel: string | undefined;
+ let fromDims: number | undefined;
+ try {
+ const { getEmbeddingModel, getEmbeddingDimensions } = await import('../ai/gateway.ts');
+ fromModel = getEmbeddingModel();
+ fromDims = getEmbeddingDimensions();
+ } catch { /* gateway unconfigured — plan falls back to defaults */ }
+ const plan = await planEmbeddingMigration(ctx.engine, {
+ to,
+ ...(dim !== undefined && { dim }),
+ ...(fromModel !== undefined && { fromModel }),
+ ...(fromDims !== undefined && { fromDims }),
+ });
+ if (ctx.dryRun || p.dry_run === true || p.yes !== true) {
+ return { status: p.yes === true || p.dry_run === true ? 'planned' : 'needs_confirmation', plan };
+ }
+ const { persistEmbeddingFileConfig, probeTargetProvider } = await import('../../commands/migrate-embeddings.ts');
+ // Safety parity with the CLI path: probe the target provider BEFORE any
+ // mutation. Without this, `yes:true` would drop the embedding column and
+ // only then discover the key/model/dim is wrong.
+ const probe = await probeTargetProvider(plan.to_model, plan.to_dims);
+ if (!probe.ok) return { status: 'failed', reason: probe.message, plan };
+ const applied = await applyEmbeddingMigration(ctx.engine, plan, {
+ persistConfig: (m, d) => persistEmbeddingFileConfig(m, d),
+ });
+ if (applied.status !== 'applied') return { ...applied, plan };
+ const { runEmbedCore } = await import('../../commands/embed.ts');
+ // singleFlight parity with the CLI path: takes the same per-source
+ // embed-backfill lock so this can't race a queued embed-backfill job on
+ // the NULL→non-NULL upsert (the TODOS:2299 class).
+ const embedResult = await runEmbedCore(ctx.engine, {
+ stale: true, catchUp: true, singleFlight: true, includeNullSignature: true, quiet: true,
+ });
+ // Stamp batch-boundary pages before probing for completion (see
+ // reconcilePageSignatures — the embed loop's all-or-nothing stamp rule
+ // skips any page split across two stale batches).
+ const reconciled = await reconcilePageSignatures(ctx.engine, plan);
+ const remaining = await ctx.engine.countStaleChunks({
+ signature: migrationSignature(plan.to_model, plan.to_dims),
+ includeNullSignature: true,
+ });
+ if (remaining === 0) await completeEmbeddingMigration(ctx.engine, plan);
+ return {
+ status: remaining === 0 ? 'completed' : 'incomplete',
+ plan,
+ embedded: embedResult.embedded,
+ remaining,
+ signatures_reconciled: reconciled,
+ invalidated: applied.invalidated,
+ schema_transitioned: applied.schema_transitioned,
+ cache_cleared: applied.cache_cleared,
+ };
+ },
+ cliHints: { name: 'migrate-embeddings', hidden: true },
+};
+
+export const embeddingMigrationOperations: Operation[] = [migrate_embeddings];
diff --git a/src/core/ops/extraction.ts b/src/core/ops/extraction.ts
new file mode 100644
index 0000000000..75a2e6dfa9
--- /dev/null
+++ b/src/core/ops/extraction.ts
@@ -0,0 +1,221 @@
+/**
+ * Entity-extraction quarantine-lane operation cluster — pure move from
+ * operations.ts (v0.46.x tranche 3): the issue-#160 extract_entities /
+ * extraction_pending / extraction_review lane plus its cluster-local
+ * resource-guard caps. Op consts stay module-private; `extractionOperations`
+ * below lists them in EXACTLY the order they appear in the canonical
+ * `operations` array in ../operations.ts. Never import from
+ * '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
+import { sourceScopeOpts } from './context.ts';
+import { unverifiedExtractionFragment, isUnverifiedExtraction, EXTRACTION_STATUS_KEY, STATUS_VERIFIED } from '../extraction-review.ts';
+import { buildVisibilityClause } from '../search/sql-ranking.ts';
+
+// ---------------------------------------------------------------------------
+// Extraction quarantine lane (issue #160)
+//
+// `extractAndEnrich` regex-extracts entity names from arbitrary text and
+// creates people/ + companies/ stub pages. These three ops are its ONLY
+// sanctioned surface:
+// - extract_entities — run extraction. Direct authoritative writes need
+// BOTH the trusted local CLI (ctx.remote === false)
+// AND the explicit --trusted-extraction flag;
+// everything else lands in the quarantine lane
+// (frontmatter provenance/status markers).
+// - extraction_pending — list unverified stubs awaiting review.
+// - extraction_review — promote (status → verified) or reject
+// (soft-delete) in batch. Owner-only (fail-closed
+// on ctx.remote): THIS surface never lets a remote
+// caller flip the status markers. Scope note: the
+// markers are ordinary frontmatter, so a caller who
+// already holds generic remote put_page write scope
+// can rewrite the page (markers included) — that
+// caller could equally author an unmarked people/
+// page directly, so the lane adds no privilege
+// there; put_page authz is its own boundary.
+// ---------------------------------------------------------------------------
+
+// Resource guards for extract_entities (#160 hardening): bound the work a
+// single remote write-scope call can trigger. ponytail: flat caps; make them
+// config knobs only if a real workload hits them.
+const MAX_EXTRACT_TEXT_CHARS = 200_000;
+const MAX_EXTRACT_ENTITIES = 200;
+
+const extract_entities: Operation = {
+ name: 'extract_entities',
+ description: 'Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI AND --trusted-extraction.',
+ params: {
+ text: { type: 'string', required: true, description: 'The text to extract entities from (email, transcript, pasted content, …). Max 200k characters — split larger inputs.' },
+ source_slug: { type: 'string', required: true, description: 'Slug of the source page the text came from (used for backlinks + timeline attribution).' },
+ trusted_extraction: { type: 'boolean', required: false, description: 'Local CLI only: write stubs directly as authoritative pages, skipping the quarantine lane. Ignored (always quarantined) for remote callers.' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ // Trust rule (#160, fail-closed like the CV6 provenance gate above):
+ // `ctx.remote === false` is the ONLY truthy condition that can admit a
+ // direct authoritative write, and even then the caller must opt in
+ // explicitly. Remote/unset trust → quarantine lane, flag ignored.
+ const trusted = ctx.remote === false && p.trusted_extraction === true;
+ const text = p.text as string;
+ // Resource guards: the greedy name regex on a huge paste can yield tens
+ // of thousands of "entities", each costing several DB round-trips. Cap
+ // input size loudly and entity count softly (surfaced as `truncated`).
+ if (text.length > MAX_EXTRACT_TEXT_CHARS) {
+ throw new OperationError(
+ 'invalid_params',
+ `extract_entities: text is ${text.length} chars (max ${MAX_EXTRACT_TEXT_CHARS}).`,
+ 'Split the input and call extract_entities per section.',
+ );
+ }
+ if (ctx.dryRun) return { dry_run: true, action: 'extract_entities', trusted };
+ const { extractEntities, enrichEntities } = await import('../enrichment-service.ts');
+ const found = extractEntities(text);
+ const capped = found.slice(0, MAX_EXTRACT_ENTITIES);
+ const results = await enrichEntities(
+ ctx.engine,
+ capped.map((e) => ({ entityName: e.name, entityType: e.type, context: e.context, sourceSlug: p.source_slug as string })),
+ {
+ trusted,
+ ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}),
+ // Pure local DB writes — no external API call to pace, so the
+ // system-load capacity gate would only stall the caller.
+ throttle: false,
+ },
+ );
+ return {
+ status: 'ok',
+ trusted,
+ quarantined: results.filter((r) => r.quarantined === true).length,
+ count: results.length,
+ entities_found: found.length,
+ truncated: found.length > capped.length,
+ entities: results,
+ };
+ },
+ cliHints: { name: 'extract-entities' },
+};
+
+const extraction_pending: Operation = {
+ name: 'extraction_pending',
+ description: 'List unverified auto-extracted entity stubs awaiting owner review (the quarantine lane from extract_entities). Promote or reject them with extraction_review.',
+ params: {
+ limit: { type: 'number', required: false, description: 'Max rows (default 100, cap 500).' },
+ offset: { type: 'number', required: false, description: 'Pagination offset.' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const limit = Math.min(Math.max(Number(p.limit ?? 100) || 100, 1), 500);
+ const offset = Math.max(Number(p.offset ?? 0) || 0, 0);
+ // Read-side source isolation: route through sourceScopeOpts (federated
+ // array > scalar > nothing), applied in SQL below.
+ const scope = sourceScopeOpts(ctx);
+ const params: unknown[] = [];
+ let srcClause = '';
+ if (scope.sourceIds && scope.sourceIds.length > 0) {
+ params.push(scope.sourceIds);
+ srcClause = `AND p.source_id = ANY($${params.length}::text[])`;
+ } else if (scope.sourceId) {
+ params.push(scope.sourceId);
+ srcClause = `AND p.source_id = $${params.length}`;
+ }
+ params.push(limit, offset);
+ const rows = await ctx.engine.executeRaw<{
+ slug: string; title: string; type: string; source_id: string;
+ extracted_from: string | null; created_at: string;
+ }>(
+ `SELECT p.slug, p.title, p.type, p.source_id,
+ p.frontmatter ->> 'source' AS extracted_from,
+ p.created_at::text AS created_at
+ FROM pages p
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${unverifiedExtractionFragment('p')}
+ ${buildVisibilityClause('p', 's')}
+ ${srcClause}
+ ORDER BY p.created_at DESC
+ LIMIT $${params.length - 1} OFFSET $${params.length}`,
+ params,
+ );
+ return { count: rows.length, pending: rows };
+ },
+ cliHints: { name: 'extraction-pending' },
+};
+
+const extraction_review: Operation = {
+ name: 'extraction_review',
+ description: 'Promote or reject unverified auto-extracted entity stubs (batch). Promote flips `status` to verified (provenance kept for audit); reject soft-deletes the stub. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)',
+ params: {
+ action: { type: 'string', required: true, description: "'promote' or 'reject'." },
+ slugs: { type: 'array', required: true, items: { type: 'string' }, description: 'Stub slugs to act on (batch).' },
+ },
+ mutating: true,
+ scope: 'write',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ // The review decision IS the trust gate — if a remote caller could
+ // promote, injected content could self-promote and the quarantine lane
+ // would be decorative. Fail-closed: only strictly-local callers pass.
+ if (ctx.remote !== false) {
+ throw new OperationError(
+ 'permission_denied',
+ 'extraction_review is owner-only: promote/reject decisions must come from the trusted local CLI.',
+ 'Run `gbrain extraction-review <promote|reject> --slugs ...` on the host machine.',
+ );
+ }
+ const action = p.action as string;
+ if (action !== 'promote' && action !== 'reject') {
+ throw new OperationError('invalid_params', `extraction_review: action must be 'promote' or 'reject'; got '${action}'.`);
+ }
+ // CLI passes `--slugs a,b,c` as one string; MCP passes a real array.
+ const slugs = Array.isArray(p.slugs)
+ ? (p.slugs as string[])
+ : typeof p.slugs === 'string'
+ ? p.slugs.split(',').map((s) => s.trim()).filter(Boolean)
+ : [];
+ if (slugs.length === 0) {
+ throw new OperationError('invalid_params', 'extraction_review: slugs must be a non-empty array (CLI: --slugs slug1,slug2).');
+ }
+ if (ctx.dryRun) return { dry_run: true, action: `extraction_review:${action}`, slugs };
+ const results: Array<{ slug: string; status: string }> = [];
+ for (const slug of slugs) {
+ const page = await ctx.engine.getPage(slug, ctx.sourceId ? { sourceId: ctx.sourceId } : undefined);
+ if (!page) {
+ results.push({ slug, status: 'not_found' });
+ continue;
+ }
+ if (!isUnverifiedExtraction(page.frontmatter)) {
+ results.push({ slug, status: 'not_unverified' });
+ continue;
+ }
+ if (action === 'promote') {
+ // Frontmatter-only flip via a targeted JSONB merge — NOT putPage,
+ // whose upsert would reset non-carried columns (page_kind →
+ // 'markdown', content_hash, …) for a change that only touches one
+ // frontmatter key. provenance stays 'auto-extracted' as the audit
+ // trail of HOW the page came to exist; status → 'verified' records
+ // the owner's call. jsonb_build_object binds as text (no
+ // JSON.stringify-into-::jsonb hazard); identical on both engines.
+ await ctx.engine.executeRaw(
+ `UPDATE pages
+ SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || jsonb_build_object($1::text, $2::text),
+ updated_at = now()
+ WHERE slug = $3 AND source_id = $4`,
+ [EXTRACTION_STATUS_KEY, STATUS_VERIFIED, slug, page.source_id],
+ );
+ results.push({ slug, status: 'promoted' });
+ } else {
+ await ctx.engine.softDeletePage(slug, { sourceId: page.source_id });
+ results.push({ slug, status: 'rejected' });
+ }
+ }
+ return { status: 'ok', action, results };
+ },
+ cliHints: { name: 'extraction-review', positional: ['action'] },
+};
+
+export const extractionOperations: Operation[] = [
+ extract_entities, extraction_pending, extraction_review,
+];
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
new file mode 100644
index 0000000000..09b07b97a0
--- /dev/null
+++ b/src/core/ops/facts.ts
@@ -0,0 +1,699 @@
+/**
+ * Hot-memory (facts) operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 3): extract_facts, the extended `recall` verb, the
+ * v0.45.x boundary verbs context_pack/delta, and forget_fact, plus the
+ * cluster-local parsers (parseEntityList, parseSinceParam, parseTtlParam).
+ * The other four frozen memory verbs (remember/entity/synthesize/forget)
+ * live in ../verbs.ts and are NOT part of this module. Op consts stay
+ * module-private; `factsOperations` below lists them in EXACTLY the order
+ * they appear in the canonical `operations` array in ../operations.ts.
+ * parseTtlParam stays exported — the `remember` verb (../verbs.ts) loads it
+ * from operations.ts at runtime, which re-exports it from here. Never import
+ * from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError, verbError } from './contract.ts';
+import { sourceScopeOpts, stampEvidenceSafe } from './context.ts';
+import { hybridSearchCached, stampContentFlags } from '../search/hybrid.ts';
+import { dedupResults } from '../search/dedup.ts';
+import { bumpLastRetrievedAt } from '../last-retrieved.ts';
+import { packToBudget, estimateTokens, resultTokens } from '../search/token-budget.ts';
+import { isAvailable } from '../ai/gateway.ts';
+import { MEMORY_VERBS_VERSION } from '../verbs.ts';
+import type { SearchResult } from '../types.ts';
+
+// ============================================================
+// v0.31 — Hot memory ops: extract_facts / recall / forget_fact
+// ============================================================
+
+const extract_facts: Operation = {
+ name: 'extract_facts',
+ description:
+ 'v0.31: extract personal-knowledge facts (events, preferences, commitments, beliefs) from a conversation turn into the per-source hot memory. Sanitizes turn_text via INJECTION_PATTERNS, calls Haiku to extract structured claims, runs the cosine fast-path + classifier dedup pipeline, INSERTs into facts. Returns counts by status. Skips extraction when the turn is dream-generated content (anti-loop). For agent memory writes of a SINGLE already-formed fact, prefer the `remember` verb (zero LLM, mandatory provenance).',
+ params: {
+ turn_text: { type: 'string', required: true, description: 'The user message or page body to extract facts from. Sanitized via INJECTION_PATTERNS before the LLM call.' },
+ session_id: { type: 'string', description: 'Opaque session id (e.g. topic-id from MCP _meta.session_id, or CLI --session). Stored on each fact for the recall --session filter. Not an auth surface.' },
+ entity_hints: { type: 'array', items: { type: 'string' }, description: 'Existing canonical entity slugs the agent has already resolved. Helps the extractor pick the right slug.' },
+ is_dream_generated: { type: 'boolean', description: 'When true, extraction is skipped (anti-loop). Caller flips this on for pages with dream_generated:true frontmatter.' },
+ visibility: { type: 'string', description: 'Default visibility for extracted facts. private (default) | world.' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'extract_facts' };
+ const { isFactsExtractionEnabled } = await import('../facts/extract.ts');
+ const { runFactsPipeline } = await import('../facts/backstop.ts');
+
+ // D15: kill switch. Operator can disable facts extraction across the
+ // brain without binary downgrade by setting `facts.extraction_enabled`
+ // to false. Returns zero-counts envelope so callers see a clean
+ // success rather than a 'permission_denied' false alarm.
+ if (!(await isFactsExtractionEnabled(ctx.engine))) {
+ return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'extraction_disabled' };
+ }
+
+ // v0.31.2: routed through the shared pipeline (PR1 commit 9). Anti-loop
+ // dream-generated check stays at the op layer because extract_facts is
+ // an explicit user op without a parsedPage — the eligibility predicate
+ // doesn't apply, but the dream-generated guard still does.
+ if (p.is_dream_generated === true) {
+ return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped: 'dream_generated' };
+ }
+
+ const sourceId = ctx.sourceId ?? 'default';
+ // [ENG-8] Explicit caller value wins; UNSET resolves through the shared
+ // facts.default_visibility helper (the old ternary coerced unset →
+ // 'private' before any config default could run). Garbage stays 'private'.
+ const { resolveVisibilityParam } = await import('../facts/visibility.ts');
+ const visibility: 'private' | 'world' = await resolveVisibilityParam(ctx.engine, p.visibility);
+
+ const r = await runFactsPipeline(p.turn_text as string, {
+ engine: ctx.engine,
+ sourceId,
+ sessionId: typeof p.session_id === 'string' ? p.session_id : null,
+ entityHints: Array.isArray(p.entity_hints) ? (p.entity_hints as string[]) : undefined,
+ source: 'mcp:extract_facts',
+ visibility,
+ mode: 'inline', // declarative; runFactsPipeline always inline
+ });
+
+ return {
+ inserted: r.inserted,
+ duplicate: r.duplicate,
+ superseded: r.superseded,
+ fact_ids: r.fact_ids,
+ };
+ },
+};
+
+const recall: Operation = {
+ name: 'recall',
+ description:
+ 'MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filters hot-memory facts by entity / since / session_id; pass `query` to ALSO run hybrid search over pages (results[] arm); pass `budget_tokens` for server-side packing (response reports budget_used + dropped_count — never trims client-side). Remote callers see visibility=world facts only. Routing: for ONE known person/company/project card use `entity` (zero LLM); for broad questions needing reasoning use `synthesize` (expensive). Branch on structured fields (status/kind/evidence), never on prose. Every response carries protocol_version.',
+ params: {
+ entity: { type: 'string', description: 'Entity slug (canonical). Returns facts about this entity newest first.' },
+ query: { type: 'string', description: 'MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error).' },
+ budget_tokens: { type: 'number', description: 'MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count.' },
+ since: { type: 'string', description: 'ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only.' },
+ session_id: { type: 'string', description: 'Source session id (e.g. topic-A). Returns facts captured in that session.' },
+ include_expired: { type: 'boolean', description: 'When true, include expired_at IS NOT NULL rows. Default false.' },
+ supersessions: { type: 'boolean', description: 'When true, return only the supersession audit log (expired_at + superseded_by both set).' },
+ limit: { type: 'number', description: 'Per-arm cap: max fact rows AND max search results. Default 50, cap 100.' },
+ grep: { type: 'string', description: 'Substring filter on fact text (case-insensitive). Applied client-side after recall.' },
+ include_pending: { type: 'boolean', description: 'v0.32: when true, response includes pending_consolidation_count (facts not yet promoted to takes by the dream-cycle consolidate phase). One round trip; backward-compatible (field omitted when false).' },
+ },
+ scope: 'read',
+ verb: true,
+ annotations: { title: 'recall (memory read)', readOnlyHint: true },
+ handler: async (ctx, p) => {
+ const sourceId = ctx.sourceId ?? 'default';
+ const limit = typeof p.limit === 'number' ? p.limit : 50;
+ const includeExpired = p.include_expired === true;
+ const grep = typeof p.grep === 'string' ? p.grep.toLowerCase() : null;
+
+ // Visibility filter: remote callers see world-only unless their token
+ // grants elevated visibility (future-proofing; v0.31 ships world-only
+ // for remote, all for local CLI).
+ const visibility =
+ ctx.remote === false
+ ? undefined
+ : ['world'] as ('private' | 'world')[];
+
+ let rows: Awaited<ReturnType<typeof ctx.engine.listFactsByEntity>> = [];
+
+ if (p.supersessions === true) {
+ const since = parseSinceParam(p.since);
+ rows = await ctx.engine.listSupersessions(sourceId, { since: since ?? undefined, limit });
+ } else if (typeof p.entity === 'string' && p.entity.length > 0) {
+ const { resolveEntitySlug } = await import('../entities/resolve.ts');
+ const slug = (await resolveEntitySlug(ctx.engine, sourceId, p.entity)) ?? p.entity;
+ rows = await ctx.engine.listFactsByEntity(sourceId, slug, {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ });
+ } else if (typeof p.session_id === 'string' && p.session_id.length > 0) {
+ rows = await ctx.engine.listFactsBySession(sourceId, p.session_id, {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ });
+ } else if (p.since !== undefined) {
+ const since = parseSinceParam(p.since);
+ if (since) {
+ rows = await ctx.engine.listFactsSince(sourceId, since, {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ });
+ }
+ } else {
+ // No filter: return recent across the source.
+ rows = await ctx.engine.listFactsSince(sourceId, new Date(0), {
+ activeOnly: !includeExpired,
+ limit,
+ visibility,
+ });
+ }
+
+ if (grep) rows = rows.filter(r => r.fact.toLowerCase().includes(grep));
+
+ // v0.32: optional pending-consolidation count piggy-backed on the recall
+ // response. Single round trip on thin-client; omitted when not requested
+ // so existing callers see no shape change.
+ let pending_consolidation_count: number | undefined;
+ if (p.include_pending === true) {
+ try {
+ pending_consolidation_count = await ctx.engine.countUnconsolidatedFacts(sourceId);
+ } catch (e) {
+ // Best-effort: if the count query fails we still return facts. Field
+ // stays undefined so callers can tell the difference between "0
+ // pending" and "we couldn't ask."
+ process.stderr.write(
+ `[recall] countUnconsolidatedFacts failed: ${(e as Error).message}\n`,
+ );
+ }
+ }
+
+ // ── MEMORY_VERBS v1 — query arm (G1B superset). Hybrid search over pages
+ // when `query` is present; degrades to keyword-only with a note (never an
+ // error) when no embedding provider is configured [F-B].
+ const queryText = typeof p.query === 'string' && p.query.trim().length > 0 ? p.query.trim() : null;
+ const budgetTokens =
+ typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
+ ? Math.floor(p.budget_tokens)
+ : null;
+
+ let searchResults: SearchResult[] = [];
+ let searchDegraded: string | undefined;
+ if (queryText) {
+ const searchScope = sourceScopeOpts(ctx);
+ if (!isAvailable('embedding')) {
+ const raw = await ctx.engine.searchKeyword(queryText, { limit, ...searchScope });
+ searchResults = dedupResults(raw);
+ stampEvidenceSafe(searchResults);
+ await stampContentFlags(ctx.engine, searchResults);
+ searchDegraded = 'keyword_only_no_embedding_provider';
+ } else {
+ searchResults = await hybridSearchCached(ctx.engine, queryText, {
+ limit,
+ expansion: false,
+ ...searchScope,
+ });
+ }
+ bumpLastRetrievedAt(ctx.engine, searchResults.map(r => r.page_id));
+ }
+
+ // ── MEMORY_VERBS v1 — server-side budget packing. Facts pack first (cheap,
+ // high-precision one-liners, per-arm limit-capped so starvation is bounded),
+ // then search results take the remainder. packToBudget treats budget<=0 as
+ // a no-op, so an exhausted remainder must drop explicitly.
+ let packedFacts = rows;
+ let packedResults = searchResults;
+ let budgetUsed: number | undefined;
+ let droppedCount: number | undefined;
+ if (budgetTokens !== null) {
+ const factsPack = packToBudget(rows, r => estimateTokens(r.fact), budgetTokens);
+ packedFacts = factsPack.items;
+ const remaining = budgetTokens - factsPack.meta.used;
+ const resultsPack =
+ remaining > 0
+ ? packToBudget(searchResults, resultTokens, remaining)
+ : { items: [] as SearchResult[], meta: { budget: 0, used: 0, dropped: searchResults.length, kept: 0 } };
+ packedResults = resultsPack.items;
+ budgetUsed = factsPack.meta.used + resultsPack.meta.used;
+ droppedCount = factsPack.meta.dropped + resultsPack.meta.dropped;
+ }
+
+ return {
+ facts: packedFacts.map(r => ({
+ id: r.id,
+ fact: r.fact,
+ kind: r.kind,
+ entity_slug: r.entity_slug,
+ visibility: r.visibility,
+ // v0.31.2: notability surfaced to recall consumers (CLI, MCP, admin).
+ // Pre-v46 brains return 'medium' via the row mapper's fallback so the
+ // contract stays total.
+ notability: r.notability,
+ valid_from: r.valid_from.toISOString(),
+ valid_until: r.valid_until?.toISOString() ?? null,
+ expired_at: r.expired_at?.toISOString() ?? null,
+ superseded_by: r.superseded_by,
+ consolidated_at: r.consolidated_at?.toISOString() ?? null,
+ consolidated_into: r.consolidated_into,
+ source: r.source,
+ source_session: r.source_session,
+ confidence: r.confidence,
+ created_at: r.created_at.toISOString(),
+ // MEMORY_VERBS v1 additive fields (G1B). `fact_id` is the opaque
+ // STRING id the `forget` verb accepts (legacy numeric `id` stays for
+ // pre-v1 consumers — legacy fields are frozen byte-equal). `provenance`
+ // is the protocol name for the stored source attribution.
+ fact_id: String(r.id),
+ provenance: r.source,
+ })),
+ total: packedFacts.length,
+ ...(pending_consolidation_count !== undefined ? { pending_consolidation_count } : {}),
+ // MEMORY_VERBS v1 envelope (G1B superset — additive on every response).
+ protocol_version: MEMORY_VERBS_VERSION,
+ ...(queryText
+ ? {
+ results: packedResults.map(r => ({
+ slug: r.slug,
+ title: r.title,
+ chunk: r.chunk_text,
+ evidence: r.evidence,
+ create_safety: r.create_safety,
+ provenance: r.slug,
+ })),
+ ...(searchDegraded ? { search_degraded: searchDegraded } : {}),
+ }
+ : {}),
+ ...(budgetTokens !== null
+ ? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
+ : {}),
+ };
+ },
+};
+
+/** Parse an `entities` param (comma-string or array) to a trimmed name list. */
+function parseEntityList(v: unknown): string[] {
+ if (Array.isArray(v)) return v.filter((x) => typeof x === 'string' && x.trim()).map((x) => (x as string).trim());
+ if (typeof v === 'string') return v.split(',').map((s) => s.trim()).filter(Boolean);
+ return [];
+}
+
+const context_pack: Operation = {
+ name: 'context_pack',
+ description:
+ 'MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing entities — entity cards + open threads + hot facts, zero-LLM, sub-second. Call at session start (warm cold context) and after compaction (rehydrate what the summary lost). WORLD-ONLY by default; pass include_private (honored for LOCAL trusted callers only) to widen all arms. budget_tokens packs server-side (response reports budget_used + dropped_count; cards pack first, then facts). Branch on structured fields, never prose. protocol_version rides every response.',
+ params: {
+ entities: { type: 'string', required: true, description: 'Comma-separated entity names/slugs to bundle. Capped at 8.' },
+ budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Cards pack first, then facts. Response adds budget_tokens, budget_used, dropped_count.' },
+ since: { type: 'string', description: 'ISO 8601 datetime. When set, open-thread events are filtered to those after this cursor.' },
+ session_id: { type: 'string', description: 'Opaque session id; keys the hot-memory cache and (on the push path) the session cursor.' },
+ include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
+ },
+ scope: 'read',
+ verb: true,
+ cliHints: { name: 'context-pack' },
+ annotations: { title: 'context_pack (boundary bundle)', readOnlyHint: true },
+ handler: async (ctx, p) => {
+ const { assembleContextPack, renderPack, isAfter, PACK_DEFAULT_MAX_ENTITIES } = await import('../context/turn-context.ts');
+ const sourceId = ctx.sourceId ?? 'default';
+ const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : undefined;
+ if (rawSince !== undefined && !Number.isFinite(Date.parse(rawSince))) {
+ throw verbError(
+ 'invalid_params',
+ `context_pack: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`,
+ 'Pass an ISO 8601 datetime, e.g. since: "2026-08-11T00:00:00Z".',
+ );
+ }
+ // Normalize to ISO (red-team F4): the filter + rendered text use it.
+ const since = rawSince !== undefined ? new Date(Date.parse(rawSince)).toISOString() : undefined;
+ // Echo the CAPPED list (pre-landing review): the assembler bundles at most
+ // PACK_DEFAULT_MAX_ENTITIES, so echoing more would claim entities were
+ // bundled that produced no cards.
+ const entities = parseEntityList(p.entities).slice(0, PACK_DEFAULT_MAX_ENTITIES);
+ // Fail-closed: private only when EXPLICITLY requested AND the caller is
+ // trusted-local (ctx.remote === false). A remote caller never widens.
+ const includePrivate = p.include_private === true && ctx.remote === false;
+ const budgetTokens =
+ typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
+ ? Math.floor(p.budget_tokens)
+ : null;
+ const res = await assembleContextPack(ctx.engine, {
+ sourceId,
+ entities,
+ since,
+ sessionId: typeof p.session_id === 'string' ? p.session_id : undefined,
+ includePrivate,
+ maxEntities: PACK_DEFAULT_MAX_ENTITIES,
+ });
+
+ let cards = res.cards ?? [];
+ let facts = res.facts ?? [];
+ let budgetUsed: number | undefined;
+ let droppedCount: number | undefined;
+ if (budgetTokens !== null) {
+ const cardCost = (c: (typeof cards)[number]) =>
+ estimateTokens(`${c.entity.title} ${c.summary} ${(c.open_threads ?? []).map((t) => t.text).join(' ')}`);
+ const cardPack = packToBudget(cards, cardCost, budgetTokens);
+ cards = cardPack.items;
+ const remaining = budgetTokens - cardPack.meta.used;
+ const factPack =
+ remaining > 0
+ ? packToBudget(facts, (f) => estimateTokens(f.fact), remaining)
+ : { items: [] as typeof facts, meta: { budget: 0, used: 0, dropped: facts.length, kept: 0 } };
+ facts = factPack.items;
+ budgetUsed = cardPack.meta.used + factPack.meta.used;
+ droppedCount = cardPack.meta.dropped + factPack.meta.dropped;
+ }
+ // Recompute open_threads with the SAME since filter the assembler applied
+ // (pre-landing review: the raw flatMap silently dropped the documented
+ // `since` contract from the structured array whenever budget packing ran).
+ const open_threads = cards
+ .flatMap((c) => c.open_threads ?? [])
+ .filter((t) => !since || (t.date !== null && isAfter(t.date, since)));
+ // Re-render the injectable block from the FINAL sets (adversarial review):
+ // `text` is what harnesses inject, so it must honor the same budget the
+ // structured arrays report — the assembler's pre-budget rendering would
+ // overrun the declared budget_tokens.
+ const text = budgetTokens !== null ? renderPack(cards, open_threads, facts) : res.text;
+
+ return {
+ protocol_version: MEMORY_VERBS_VERSION,
+ entities,
+ cards: cards.map((c) => ({
+ slug: c.entity.slug,
+ title: c.entity.title,
+ type: c.entity.type,
+ summary: c.summary,
+ open_threads: c.open_threads,
+ edges: c.edges,
+ backlink_count: c.backlink_count,
+ })),
+ open_threads,
+ facts: facts.map((f) => ({
+ fact: f.fact,
+ kind: f.kind,
+ entity_slug: f.entity_slug,
+ valid_from: f.valid_from,
+ confidence: f.confidence,
+ })),
+ text,
+ ...(res.degradedReason ? { degraded_reason: res.degradedReason } : {}),
+ ...(budgetTokens !== null
+ ? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
+ : {}),
+ };
+ },
+};
+
+const delta: Operation = {
+ name: 'delta',
+ description:
+ 'MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. Lets a periodic wake maintain warm state in O(changes) instead of re-deriving. Optionally scope thread deltas to `entities`. WORLD-ONLY by default; include_private honored for local trusted callers only. budget_tokens packs server-side (pages first, then facts). protocol_version rides every response.',
+ params: {
+ since: { type: 'string', description: 'ISO 8601 cursor. Returns pages/facts/thread-events newer than this timestamp. Optional when session_id carries an established cursor.' },
+ since_slug: { type: 'string', description: 'Stateless keyset resume: pass back `next_cursor.slug` from the previous response (paired with `since`=next_cursor.since) to page through pages sharing one timestamp. Ignored when session_id is set (the session cursor carries it).' },
+ entities: { type: 'string', description: 'Optional comma-separated entity scope for thread-event deltas. Capped at 8.' },
+ budget_tokens: { type: 'number', description: 'Server-side token budget (char/4). Pages pack first, then facts. Response adds budget_tokens, budget_used, dropped_count.' },
+ session_id: { type: 'string', description: 'Opaque session id. Drives the per-session cursor: the first call establishes it, each call advances it to the newest DELIVERED change (at-least-once — with has_more:true the undelivered tail returns on the next wake). Without it, pass an explicit `since` for a stateless delta.' },
+ include_private: { type: 'boolean', description: 'Local trusted callers only: widen ALL arms to include private facts. Ignored (world-only) for remote callers. Default false.' },
+ },
+ scope: 'read',
+ verb: true,
+ cliHints: { name: 'delta' },
+ annotations: { title: 'delta (what changed since)', readOnlyHint: true },
+ handler: async (ctx, p) => {
+ const { assembleDeltaContext, renderDelta, PACK_DEFAULT_MAX_ENTITIES } = await import('../context/turn-context.ts');
+ const { getSessionContextState, upsertSessionContextState } = await import('../context/session-state.ts');
+ const sourceId = ctx.sourceId ?? 'default';
+ const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : null;
+ if (rawSince !== null && !Number.isFinite(Date.parse(rawSince))) {
+ throw verbError(
+ 'invalid_params',
+ `delta: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`,
+ 'Pass an ISO 8601 datetime, e.g. since: "2026-08-11T00:00:00Z".',
+ );
+ }
+ // NORMALIZE to ISO immediately (red-team F4): the raw string is echoed
+ // into the injectable `text` block, so an attacker-shaped-but-parseable
+ // `since` must never reach rendering verbatim.
+ const explicitSince = rawSince !== null ? new Date(Date.parse(rawSince)).toISOString() : null;
+ const sessionId = typeof p.session_id === 'string' && p.session_id.trim() ? p.session_id : null;
+ // Cursor namespace (pre-landing review, fail-closed): 'local' is RESERVED
+ // for the trusted CLI/hook lane, gated on STRICT ctx.remote === false —
+ // anything else (true, undefined via cast bypass) is remote. Remote callers
+ // use their auth client id; an auth-LESS or blank-id remote (stdio MCP)
+ // gets the shared 'remote' sentinel — never collapsed into 'local'.
+ const clientId = ctx.remote === false ? null : ctx.auth?.clientId?.trim() || 'remote';
+ const includePrivate = p.include_private === true && ctx.remote === false;
+ const budgetTokens =
+ typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
+ ? Math.floor(p.budget_tokens)
+ : null;
+
+ const state = sessionId ? await getSessionContextState(ctx.engine, sourceId, clientId, sessionId) : null;
+ const effectiveSince = explicitSince ?? state?.last_wake_at ?? null;
+
+ if (!effectiveSince) {
+ if (!sessionId) {
+ throw verbError(
+ 'invalid_params',
+ 'delta requires `since` (ISO 8601) or a `session_id` with an established cursor.',
+ 'Pass since ("2026-08-11T00:00:00Z") for a stateless delta, or a stable session_id — the first call establishes the cursor and later calls return only newer changes.',
+ );
+ }
+ // First wake for this session: establish the cursor at now and report an
+ // empty delta (there is no prior point to diff against yet). Opportunistic
+ // GC on row creation bounds session-row accumulation on serve-less CLI
+ // lanes and remote read callers minting session ids (pre-landing review).
+ // AWAITED (v0.45.7): a floating engine promise here races the CLI lane's
+ // engine teardown and wedges the process — `gbrain delta --session-id`
+ // printed its response but never exited (the exact command the shipped
+ // HEARTBEAT.md ambient-delta row tells agents to run). GC is two fast
+ // DELETEs on a capped table and internally fail-open, so awaiting costs
+ // one first-wake round-trip, never an error. The serve-boot call site
+ // (src/mcp/server.ts) stays fire-and-forget — that process is long-lived.
+ const now = new Date().toISOString();
+ const { gcSessionContextState } = await import('../context/session-state.ts');
+ await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, { lastWakeAt: now });
+ await gcSessionContextState(ctx.engine);
+ return {
+ protocol_version: MEMORY_VERBS_VERSION,
+ since: now, pages: [], facts: [], threads: [], text: '', has_more: false,
+ next_cursor: { since: now, slug: '' },
+ ...(budgetTokens !== null
+ ? { budget_tokens: budgetTokens, budget_used: 0, dropped_count: 0 }
+ : {}),
+ };
+ }
+
+ // Keyset cursor (red-team F1/F2 fix): pages page by (updated_at, slug), so
+ // a >limit cluster at one timestamp is reachable and a delivered page never
+ // re-appears unless it changes. The keyset slug lives in the session row
+ // (surfaced_slugs[0]); an explicit-`since` caller has no stored slug and
+ // resumes via the returned `next_cursor`.
+ const cursorSlug = sessionId ? state?.surfaced_slugs?.[0] : undefined;
+ const explicitSlug = typeof p.since_slug === 'string' ? p.since_slug : undefined;
+ const sinceSlug = explicitSlug ?? cursorSlug;
+
+ const res = await assembleDeltaContext(ctx.engine, {
+ sourceId,
+ since: effectiveSince,
+ ...(sinceSlug !== undefined ? { sinceSlug } : {}),
+ entities: parseEntityList(p.entities),
+ sessionId: sessionId ?? undefined,
+ includePrivate,
+ maxEntities: PACK_DEFAULT_MAX_ENTITIES,
+ });
+
+ // Pages arrive OLDEST first by (updated_at, slug) — no client-side dedup
+ // needed; the keyset already excludes everything at/before the cursor.
+ let pages = res.deltaPages ?? [];
+ let facts = res.facts ?? [];
+ const threads = res.openThreads ?? [];
+ let budgetUsed: number | undefined;
+ let droppedCount: number | undefined;
+ let factsDropped = 0;
+ const fetchedPages = pages.length;
+ if (budgetTokens !== null) {
+ // packToBudget keeps a contiguous PREFIX (order-preserving, stops at the
+ // first overflow) — with oldest-first pages the kept set stays contiguous
+ // from the cursor, which the advance logic below depends on.
+ const pagePack = packToBudget(pages, (pg) => estimateTokens(`${pg.title} ${pg.slug}`), budgetTokens);
+ pages = pagePack.items;
+ const remaining = budgetTokens - pagePack.meta.used;
+ const factPack =
+ remaining > 0
+ ? packToBudget(facts, (f) => estimateTokens(f.fact), remaining)
+ : { items: [] as typeof facts, meta: { budget: 0, used: 0, dropped: facts.length, kept: 0 } };
+ facts = factPack.items;
+ budgetUsed = pagePack.meta.used + factPack.meta.used;
+ droppedCount = pagePack.meta.dropped + factPack.meta.dropped;
+ factsDropped = factPack.meta.dropped;
+ }
+ const pagesDropped = fetchedPages - pages.length;
+ // has_more covers ALL undelivered content — fetch-limit overflow, budget-
+ // dropped pages, AND budget-dropped facts (pre-landing review: facts were
+ // silently lost when pages fit but facts overflowed).
+ const hasMore = res.deltaOverflow === true || pagesDropped > 0 || factsDropped > 0;
+
+ // Cursor advance (keyset, at-least-once): advance to the last DELIVERED
+ // (updated_at, slug). The keyset's strict `>` means the next wake starts
+ // exactly after it — a >limit same-timestamp cluster drains one page at a
+ // time across wakes (F1), and a delivered page never re-appears (F2). On a
+ // page-less wake with nothing dropped, advance the TIME cursor to now()
+ // minus a safety lag (in-flight write txns stamp updated_at at txn START)
+ // and clear the keyset slug. If nothing delivered but something dropped, do
+ // NOT advance (deliver-before-advance; a too-small budget must not eat it).
+ const nextCursor =
+ pages.length > 0
+ ? { since: pages[pages.length - 1].updated_at, slug: pages[pages.length - 1].slug }
+ : { since: effectiveSince, slug: sinceSlug ?? '' };
+ if (sessionId) {
+ if (pages.length > 0) {
+ await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
+ lastWakeAt: nextCursor.since,
+ cursorSlug: nextCursor.slug,
+ });
+ } else if (!hasMore) {
+ await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
+ lastWakeAt: new Date(Date.now() - 2000).toISOString(),
+ cursorSlug: '',
+ });
+ }
+ }
+
+ // Re-render the injectable block from the FINAL sets (adversarial review):
+ // `text` must honor the budget AND the boundary-tie exclusion the
+ // structured arrays reflect — the assembler's render predates both.
+ const text = renderDelta(pages, facts, threads, effectiveSince);
+
+ return {
+ protocol_version: MEMORY_VERBS_VERSION,
+ since: effectiveSince,
+ pages,
+ facts: facts.map((f) => ({
+ fact: f.fact,
+ kind: f.kind,
+ entity_slug: f.entity_slug,
+ valid_from: f.valid_from,
+ confidence: f.confidence,
+ })),
+ threads,
+ text,
+ has_more: hasMore,
+ // Stateless resume: a caller with no session_id passes these back as
+ // `since` + `since_slug` on the next call to page deterministically.
+ next_cursor: nextCursor,
+ ...(res.degradedReason ? { degraded_reason: res.degradedReason } : {}),
+ ...(budgetTokens !== null
+ ? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
+ : {}),
+ };
+ },
+};
+
+const forget_fact: Operation = {
+ name: 'forget_fact',
+ description: 'v0.32.2: forget a fact. Rewrites the page\'s `## Facts` fence to strike through the row and set valid_until=today (the DB\'s expired_at derives via valid_until + now() on the next reconcile so the forget survives `gbrain rebuild`). Falls back to legacy DB-only expire for pre-v51 / thin-client rows. Idempotent on already-expired or unknown ids.',
+ params: {
+ id: { type: 'number', required: true, description: 'Fact id to forget.' },
+ reason: { type: 'string', required: false, description: 'Optional reason; written to the fence row\'s context cell as "forgotten: <reason>". Default: "forgotten".' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'forget_fact', id: p.id };
+ const id = p.id as number;
+ const reason = typeof p.reason === 'string' ? p.reason : undefined;
+ const { forgetFactInFence } = await import('../facts/forget.ts');
+ const result = await forgetFactInFence(ctx.engine, id, { reason });
+ if (!result.ok && result.path === 'not_found') {
+ throw new OperationError('fact_not_found', `Fact id ${id} not found.`);
+ }
+ if (!result.ok && result.path === 'already_expired') {
+ throw new OperationError('fact_already_expired', `Fact id ${id} already expired.`);
+ }
+ return { id, expired: true, path: result.path, reason: result.reason };
+ },
+};
+
+/**
+ * Parse a `since` parameter into a Date. Accepts ISO 8601, plain duration
+ * shorthand ("8 hours ago", "3 days ago", "30m", "1h", "2d", "7d"), or
+ * Unix epoch millis. Returns null on unparseable input.
+ */
+function parseSinceParam(raw: unknown): Date | null {
+ if (raw == null) return null;
+ if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw);
+ if (typeof raw !== 'string') return null;
+ const s = raw.trim();
+ if (!s) return null;
+
+ // Try ISO first.
+ const iso = Date.parse(s);
+ if (Number.isFinite(iso)) return new Date(iso);
+
+ // "N (minutes|hours|days) ago" or compact forms.
+ const ago = s.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)(?:\s+ago)?$/i);
+ if (ago) {
+ const n = parseInt(ago[1], 10);
+ const unit = ago[2].toLowerCase();
+ const ms =
+ unit.startsWith('s') ? n * 1000 :
+ unit.startsWith('m') ? n * 60 * 1000 :
+ unit.startsWith('h') ? n * 60 * 60 * 1000 :
+ n * 24 * 60 * 60 * 1000;
+ return new Date(Date.now() - ms);
+ }
+ return null;
+}
+
+/**
+ * MEMORY_VERBS v1 — parse the `remember` verb's `ttl` param into a
+ * `valid_until` Date. Sibling of parseSinceParam, pointed FORWARD.
+ *
+ * Accepted forms (frozen in docs/protocol/MEMORY_VERBS_v1.md):
+ * - relative duration shorthand: '30d', '12h', '45m', '90s' (also
+ * spelled-out: '30 days', '12 hours') → now + duration
+ * - absolute ISO 8601 date or datetime: '2026-07-12', '2026-07-12T00:00:00Z'
+ *
+ * Explicitly REJECTED with a self-correcting suggestion: ISO-8601 duration
+ * syntax ('P30D', 'PT12H') — agents that read "ISO 8601" as durations get a
+ * fix, not a mystery. Returns null for null/undefined/empty (= never expires).
+ * Throws verbError('invalid_params') on anything unparseable.
+ */
+export function parseTtlParam(raw: unknown): Date | null {
+ if (raw == null) return null;
+ if (typeof raw !== 'string') {
+ throw verbError(
+ 'invalid_params',
+ `ttl must be a string, got ${typeof raw}.`,
+ 'Pass a duration like "30d" or "12h", or an absolute ISO 8601 timestamp like "2026-07-12T00:00:00Z".',
+ );
+ }
+ const s = raw.trim();
+ if (!s) return null;
+
+ // ISO-8601 DURATION syntax is a documented trap — reject with the fix.
+ if (/^P(T|\d)/i.test(s) && /^P(?:\d+[YMWD])*(?:T(?:\d+[HMS])+)?$/i.test(s)) {
+ throw verbError(
+ 'invalid_params',
+ `ttl "${s}" looks like an ISO-8601 duration, which is not accepted.`,
+ `Use the shorthand form instead (e.g. "${s.replace(/^PT?/i, '').toLowerCase()}" style: "30d", "12h"), or an absolute ISO 8601 expiry timestamp.`,
+ );
+ }
+
+ // Relative duration shorthand → now + duration.
+ const dur = s.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)$/i);
+ if (dur) {
+ const n = parseInt(dur[1], 10);
+ const unit = dur[2].toLowerCase();
+ const ms =
+ unit.startsWith('s') ? n * 1000 :
+ unit.startsWith('m') ? n * 60 * 1000 :
+ unit.startsWith('h') ? n * 60 * 60 * 1000 :
+ n * 24 * 60 * 60 * 1000;
+ return new Date(Date.now() + ms);
+ }
+
+ // Absolute ISO 8601 date or datetime.
+ const iso = Date.parse(s);
+ if (Number.isFinite(iso)) return new Date(iso);
+
+ throw verbError(
+ 'invalid_params',
+ `Cannot parse ttl "${s}".`,
+ 'Pass a duration like "30d" or "12h", or an absolute ISO 8601 timestamp like "2026-07-12T00:00:00Z". Omit ttl for a fact that never expires.',
+ );
+}
+
+export const factsOperations: Operation[] = [
+ extract_facts, recall, context_pack, delta, forget_fact,
+];
diff --git a/src/core/ops/files.ts b/src/core/ops/files.ts
new file mode 100644
index 0000000000..1b1085d28d
--- /dev/null
+++ b/src/core/ops/files.ts
@@ -0,0 +1,151 @@
+/**
+ * File Operations cluster — pure move from operations.ts (v0.46.x tranche 2).
+ * Op consts stay module-private; `filesOperations` below lists them in
+ * EXACTLY the order they appear in the canonical `operations` array in
+ * ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
+import { validateFilename, validatePageSlug, validateUploadPath } from './context.ts';
+
+// --- File Operations ---
+
+// Both branches need a LIMIT. Without one, the slug-filtered branch materializes
+// every file for that slug — an MCP caller can force unbounded memory consumption
+// by targeting a page with many attachments.
+const FILE_LIST_LIMIT = 100;
+
+const file_list: Operation = {
+ name: 'file_list',
+ description: 'List stored files',
+ params: {
+ slug: { type: 'string', description: 'Filter by page slug' },
+ },
+ scope: 'admin',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ const { sqlQueryForEngine } = await import('../sql-query.ts');
+ const sql = sqlQueryForEngine(ctx.engine);
+ const slug = p.slug as string | undefined;
+ const rows = slug
+ ? await sql`SELECT id, page_slug, filename, storage_path, mime_type, size_bytes, content_hash, created_at FROM files WHERE page_slug = ${slug} ORDER BY filename LIMIT ${FILE_LIST_LIMIT}`
+ : await sql`SELECT id, page_slug, filename, storage_path, mime_type, size_bytes, content_hash, created_at FROM files ORDER BY page_slug, filename LIMIT ${FILE_LIST_LIMIT}`;
+ // Postgres returns size_bytes (BIGINT) as native BigInt — JSON.stringify
+ // throws on those, breaking MCP callers. PGLite returns Number already.
+ // 9 PB ceiling (2^53 bytes) is far above any plausible file size.
+ return rows.map((r: Record<string, unknown>) => ({
+ ...r,
+ size_bytes: r.size_bytes == null ? null : Number(r.size_bytes),
+ }));
+ },
+};
+
+const file_upload: Operation = {
+ name: 'file_upload',
+ description: 'Upload a file to storage',
+ params: {
+ path: { type: 'string', required: true, description: 'Local file path' },
+ page_slug: { type: 'string', description: 'Associate with page' },
+ },
+ mutating: true,
+ scope: 'admin',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'file_upload', path: p.path };
+
+ const { readFileSync, statSync } = await import('fs');
+ const { basename, extname } = await import('path');
+ const { createHash } = await import('crypto');
+
+ const filePath = p.path as string;
+ const pageSlug = (p.page_slug as string) || null;
+
+ // Fix 1 / B5 / H5 / M4: validate path, slug, filename before any filesystem read.
+ // Remote callers (MCP, agent) are confined to cwd (strict). Local CLI callers
+ // can upload from anywhere on the filesystem (loose) — the user owns the machine.
+ // Default is strict when ctx.remote is undefined (defense-in-depth).
+ const strict = ctx.remote !== false;
+ validateUploadPath(filePath, process.cwd(), strict);
+ if (pageSlug) validatePageSlug(pageSlug);
+ const filename = basename(filePath);
+ validateFilename(filename);
+
+ const stat = statSync(filePath);
+ const content = readFileSync(filePath);
+ const hash = createHash('sha256').update(content).digest('hex');
+ const storagePath = pageSlug ? `${pageSlug}/${filename}` : `unsorted/${hash.slice(0, 8)}-${filename}`;
+
+ const MIME_TYPES: Record<string, string> = {
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
+ '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
+ '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.mp3': 'audio/mpeg',
+ };
+ const mimeType = MIME_TYPES[extname(filePath).toLowerCase()] || null;
+
+ const { sqlQueryForEngine } = await import('../sql-query.ts');
+ const sql = sqlQueryForEngine(ctx.engine);
+ const existing = await sql`SELECT id FROM files WHERE content_hash = ${hash} AND storage_path = ${storagePath}`;
+ if (existing.length > 0) {
+ return { status: 'already_exists', storage_path: storagePath };
+ }
+
+ // Upload to storage backend if configured
+ if (ctx.config.storage) {
+ const { createStorage } = await import('../storage.ts');
+ const storage = await createStorage(ctx.config.storage as any);
+ try {
+ await storage.upload(storagePath, content, mimeType || undefined);
+ } catch (uploadErr) {
+ throw new OperationError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`);
+ }
+ }
+
+ try {
+ await sql`
+ INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
+ VALUES (${pageSlug}, ${filename}, ${storagePath}, ${mimeType}, ${stat.size}, ${hash}, ${'{}'}::jsonb)
+ ON CONFLICT (storage_path) DO UPDATE SET
+ content_hash = EXCLUDED.content_hash,
+ size_bytes = EXCLUDED.size_bytes,
+ mime_type = EXCLUDED.mime_type
+ `;
+ } catch (dbErr) {
+ // Rollback: clean up storage if DB write failed
+ if (ctx.config.storage) {
+ try {
+ const { createStorage } = await import('../storage.ts');
+ const storage = await createStorage(ctx.config.storage as any);
+ await storage.delete(storagePath);
+ } catch { /* best effort cleanup */ }
+ }
+ throw dbErr;
+ }
+
+ return { status: 'uploaded', storage_path: storagePath, size_bytes: stat.size };
+ },
+};
+
+const file_url: Operation = {
+ name: 'file_url',
+ description: 'Get a URL for a stored file',
+ params: {
+ storage_path: { type: 'string', required: true },
+ },
+ scope: 'admin',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ const { sqlQueryForEngine } = await import('../sql-query.ts');
+ const sql = sqlQueryForEngine(ctx.engine);
+ const rows = await sql`SELECT storage_path, mime_type, size_bytes FROM files WHERE storage_path = ${p.storage_path as string}`;
+ if (rows.length === 0) {
+ throw new OperationError('storage_error', `File not found: ${p.storage_path}`);
+ }
+ // TODO: generate signed URL from Supabase Storage
+ return { storage_path: rows[0].storage_path, url: `gbrain:files/${rows[0].storage_path}` };
+ },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const filesOperations: Operation[] = [file_list, file_upload, file_url];
diff --git a/src/core/ops/image.ts b/src/core/ops/image.ts
new file mode 100644
index 0000000000..e0417e57f8
--- /dev/null
+++ b/src/core/ops/image.ts
@@ -0,0 +1,194 @@
+/**
+ * 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
+ * budget/size config readers. Op const stays module-private;
+ * `imageOperations` below is spliced into the canonical `operations` array
+ * in ../operations.ts at the cluster's original position (between the
+ * search and tags spreads). Never import from '../operations.ts' here
+ * (cycle).
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { Operation } from './contract.ts';
+import { resolveRequestedScope } from './context.ts';
+
+// --- v0.36 Phase 2: search_by_image (image-as-query) ---
+
+const search_by_image: Operation = {
+ name: 'search_by_image',
+ description:
+ 'v0.36 cross-modal Phase 2: image-as-query retrieval. Accepts a local path (CLI), data: URI, or http(s):// URL ' +
+ '(SSRF-defended). Returns visually-similar image chunks plus any OCR text they carry. Optional `query` text ' +
+ 'refinement merges via weighted RRF (D13 hybrid intersect). True image→full-text-knowledge requires Phase 3 ' +
+ '(`gbrain reindex --multimodal` + `search.unified_multimodal: true`).',
+ params: {
+ image_path: { type: 'string', description: 'Absolute path to image (local CLI callers only — rejected for remote MCP per D18).' },
+ image_url: { type: 'string', description: 'http(s):// URL to image. SSRF-defended; max 3 redirect hops; 10MB cap.' },
+ image_data: { type: 'string', description: 'Base64-encoded image bytes (preferred for remote MCP callers). PNG/JPEG/WebP only.' },
+ image_mime: { type: 'string', description: 'Optional MIME hint when ambiguous. Magic-byte sniff is authoritative.' },
+ query: { type: 'string', description: 'Optional text refinement; runs hybrid intersect via D13 weighted RRF.' },
+ limit: { type: 'number', description: 'Max results (default 20)' },
+ offset: { type: 'number', description: 'Skip first N results (for pagination)' },
+ source_id: { type: 'string', description: "Scope to a single source. Defaults to ctx.sourceId. '__all__' spans every source for trusted local callers, your granted sources for remote callers." },
+ },
+ scope: 'read',
+ // NOT localOnly: remote MCP callers can pass image_url or image_data
+ // (subject to D18 image_path ban + D12 size cap + D23-#6 spend cap).
+ handler: async (ctx, p) => {
+ const imagePath = p.image_path as string | undefined;
+ const imageUrl = p.image_url as string | undefined;
+ const imageData = p.image_data as string | undefined;
+ const imageMime = (p.image_mime as string) || undefined;
+ const queryRefinement = p.query as string | undefined;
+ const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
+
+ // D18 P0 — remote callers cannot pass image_path. Rejecting at handler
+ // entry, before any file I/O fires. validateParams catches it too at the
+ // dispatch layer; this is defense-in-depth.
+ if (ctx.remote === true && imagePath) {
+ throw new Error(
+ 'permission_denied: image_path is not permitted for remote callers (D18). ' +
+ 'Use image_url or image_data instead.',
+ );
+ }
+
+ if (!imagePath && !imageUrl && !imageData) {
+ throw new Error('search_by_image requires one of: image_path, image_url, image_data');
+ }
+ if ([imagePath, imageUrl, imageData].filter(Boolean).length > 1) {
+ throw new Error('search_by_image accepts only one of: image_path, image_url, image_data');
+ }
+
+ // D23-#6 — remote OAuth clients are charged through the durable
+ // reserve-then-settle ledger below. Local CLI callers bypass the cap
+ // (clientId="") because they use their own provider credentials.
+ const clientId = (ctx.remote === true ? (ctx.auth?.clientId ?? '') : '');
+
+ // Resolve image bytes via the SSRF-defended loader. For remote callers,
+ // tighter byte cap.
+ const remoteCap = await getRemoteMaxBytes(ctx.engine);
+ const localCap = await getLocalMaxBytes(ctx.engine);
+ const cap = ctx.remote === true ? remoteCap : localCap;
+ const { loadImageInput } = await import('../search/image-loader.ts');
+ const loaded = await loadImageInput(
+ (imagePath ?? imageUrl ?? `data:${imageMime ?? 'image/png'};base64,${imageData}`)!,
+ { maxBytes: cap },
+ );
+
+ // Resolve source-scope through the single trust+grant resolver. Pre-fix
+ // this branch computed resolvedSourceId then spread sourceScopeOpts(ctx)
+ // after it (double-application: the spread silently won, and `__all__`
+ // didn't opt out for local callers with ctx.sourceId set). One resolver,
+ // one spread — `__all__` spans the brain only for trusted local callers.
+ const imageSourceScope = resolveRequestedScope(ctx, sourceIdParam);
+
+ // Reserve immediately before entering the paid search routine. Validation,
+ // image loading, and scope resolution happen first so known no-charge
+ // failures do not strand reservations. An ambiguous provider failure is
+ // settled at this operation's fixed-price upper bound below; pessimistic
+ // accounting is safer than reopening daily headroom after the TTL.
+ let spendReservationId: string | null = null;
+ let estimatedSpendCents = 0;
+ if (clientId) {
+ const { VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS } = await import('../spend-log.ts');
+ const { reserve } = await import('../minions/budget-meter.ts');
+ const calls = 1 + (queryRefinement ? 1 : 0);
+ estimatedSpendCents = VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS * calls;
+ const budgetUsd = await getDailyImageBudgetUsd(ctx.engine);
+ const reservation = await reserve(ctx.engine, {
+ clientId,
+ estimatedCents: estimatedSpendCents,
+ capCents: budgetUsd * 100,
+ provider: 'voyage',
+ model: 'voyage-multimodal-3',
+ });
+ spendReservationId = reservation.reservationId;
+ }
+
+ const { searchByImage } = await import('../search/by-image.ts');
+ let results: Awaited<ReturnType<typeof searchByImage>>;
+ try {
+ results = await searchByImage(
+ ctx.engine,
+ { base64: loaded.base64, mime: loaded.contentType },
+ {
+ limit: (p.limit as number) || 20,
+ offset: (p.offset as number) || 0,
+ query: queryRefinement,
+ ...imageSourceScope,
+ },
+ );
+ } catch (providerError) {
+ if (spendReservationId) {
+ const { settle } = await import('../minions/budget-meter.ts');
+ try {
+ await settle(
+ ctx.engine,
+ spendReservationId,
+ estimatedSpendCents,
+ 'search_by_image_error_pessimistic',
+ ctx.auth?.clientName ?? null,
+ );
+ } catch (accountingError) {
+ throw new AggregateError(
+ [providerError, accountingError],
+ 'search_by_image provider call failed and its spend reservation could not be settled',
+ );
+ }
+ }
+ throw providerError;
+ }
+
+ // Settlement and the spend-log mirror commit in one transaction. A
+ // database/accounting failure blocks the response and leaves the pending
+ // reservation holding headroom rather than returning an unmetered success.
+ if (spendReservationId) {
+ const { settle } = await import('../minions/budget-meter.ts');
+ await settle(
+ ctx.engine,
+ spendReservationId,
+ estimatedSpendCents,
+ 'search_by_image',
+ ctx.auth?.clientName ?? null,
+ );
+ }
+
+ return results;
+ },
+ cliHints: { name: 'search-by-image' },
+};
+
+async function getDailyImageBudgetUsd(engine: BrainEngine): Promise<number> {
+ try {
+ const v = await engine.getConfig('search.image_query.daily_budget_usd_per_client');
+ if (v == null) return 5; // default $5
+ const n = parseFloat(v);
+ return Number.isFinite(n) && n > 0 ? n : 5;
+ } catch {
+ return 5;
+ }
+}
+
+async function getLocalMaxBytes(engine: BrainEngine): Promise<number> {
+ try {
+ const v = await engine.getConfig('search.image_query.max_bytes');
+ if (v == null) return 10 * 1024 * 1024;
+ const n = parseInt(v, 10);
+ return Number.isFinite(n) && n > 0 ? n : 10 * 1024 * 1024;
+ } catch {
+ return 10 * 1024 * 1024;
+ }
+}
+
+async function getRemoteMaxBytes(engine: BrainEngine): Promise<number> {
+ try {
+ const v = await engine.getConfig('search.image_query.remote_max_bytes');
+ if (v == null) return 2 * 1024 * 1024;
+ const n = parseInt(v, 10);
+ return Number.isFinite(n) && n > 0 ? n : 2 * 1024 * 1024;
+ } catch {
+ return 2 * 1024 * 1024;
+ }
+}
+
+export const imageOperations: Operation[] = [search_by_image];
diff --git a/src/core/ops/ingest-log.ts b/src/core/ops/ingest-log.ts
new file mode 100644
index 0000000000..b770e2cd98
--- /dev/null
+++ b/src/core/ops/ingest-log.ts
@@ -0,0 +1,67 @@
+/**
+ * Ingest Log operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 2). Op consts stay module-private; `ingestLogOperations` below
+ * lists them in EXACTLY the order they appear in the canonical `operations`
+ * array in ../operations.ts. Never import from '../operations.ts' here
+ * (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { clampSearchLimit } from '../engine.ts';
+import { linkReadScopeOpts } from './context.ts';
+
+// --- Ingest Log ---
+
+const log_ingest: Operation = {
+ name: 'log_ingest',
+ description: 'Log an ingestion event',
+ params: {
+ source_type: { type: 'string', required: true, description: "Kind of ingest source, e.g. 'email', 'meeting', 'rss', 'api'." },
+ source_ref: { type: 'string', required: true, description: 'Identifier of the ingested item — a URL, message id, or file path.' },
+ pages_updated: { type: 'array', required: true, items: { type: 'string' }, description: 'Slugs of the pages this ingest created or updated.' },
+ summary: { type: 'string', required: true, description: 'One-line human-readable summary of what was ingested.' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'log_ingest' };
+ await ctx.engine.logIngest({
+ // Thread ctx.sourceId (same pattern as get_chunks/get_page above): on a
+ // multi-source brain the ingest event must be attributed to the caller's
+ // source, not the shared 'default' bucket. Absent sourceId still falls to
+ // the engine's 'default' (single-source brains unchanged).
+ ...(ctx.sourceId ? { source_id: ctx.sourceId } : {}),
+ source_type: p.source_type as string,
+ source_ref: p.source_ref as string,
+ pages_updated: p.pages_updated as string[],
+ summary: p.summary as string,
+ });
+ return { status: 'ok' };
+ },
+};
+
+const get_ingest_log: Operation = {
+ name: 'get_ingest_log',
+ description: 'Get recent ingestion log entries',
+ params: {
+ limit: { type: 'number', description: 'Max entries (default 20)' },
+ },
+ handler: async (ctx, p) => {
+ // Source-scope the log for remote callers (scalar grant → single-element
+ // array; federated grant → the granted array — linkReadScopeOpts collapse
+ // rule). Trusted local callers (remote === false) keep the whole-brain
+ // view, matching every other read op's local posture. Ingest summaries
+ // can carry another source's private context, so an unscoped remote read
+ // is a cross-source leak.
+ const scope = ctx.remote !== false ? linkReadScopeOpts(ctx) : {};
+ return ctx.engine.getIngestLog({
+ limit: clampSearchLimit(p.limit as number | undefined, 20, 50),
+ ...(scope.sourceIds ? { sourceIds: scope.sourceIds } : scope.sourceId ? { sourceIds: [scope.sourceId] } : {}),
+ });
+ },
+ scope: 'read',
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const ingestLogOperations: Operation[] = [log_ingest, get_ingest_log];
diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.ts
new file mode 100644
index 0000000000..51e68f001e
--- /dev/null
+++ b/src/core/ops/insights.ts
@@ -0,0 +1,320 @@
+/**
+ * Insight-read operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 3): the v0.43 push-based-context op (volunteer_context) plus the
+ * find_* insight reads (find_experts, find_contradictions, find_trajectory).
+ * Unlike the other tranche-3 clusters these four occupy NON-adjacent slots of
+ * the canonical `operations` array in ../operations.ts, so the ops are
+ * exported individually and spliced as bare entries at their original
+ * positions (order is contractual — docs/TOOL_CATALOG.md is generated from
+ * it). Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
+import { sourceScopeOpts } from './context.ts';
+import {
+ FIND_EXPERTS_DESCRIPTION,
+ FIND_CONTRADICTIONS_DESCRIPTION,
+ FIND_TRAJECTORY_DESCRIPTION,
+} from '../operations-descriptions.ts';
+
+// --- v0.43 (#2095): push-based context — the brain volunteers pages ---
+
+const volunteer_context: Operation = {
+ name: 'volunteer_context',
+ description:
+ 'Push-based context: volunteer brain pages relevant to a rolling conversation window ' +
+ 'WITHOUT being asked. Zero-LLM, confidence-gated (alias 0.9 / exact-title 0.8 / ' +
+ 'slug-suffix 0.6, +0.05 for multi-turn or newest-turn mentions; default gate 0.7), ' +
+ 'capped at 3 pages (max 5). Returns pointers with one-line rationales + synopses — ' +
+ 'open the page (get_page) before relying on details. Pass stats: true for the ' +
+ 'approximate volunteered-vs-used precision summary (the feedback loop).',
+ scope: 'read',
+ params: {
+ window: {
+ type: 'string',
+ description:
+ "Recent conversation turns, oldest → newest, as 'user:' / 'assistant:' prefixed " +
+ 'lines (unprefixed text = one user turn). Required unless stats: true. ' +
+ 'CLI: piped stdin fills this.',
+ },
+ prior_context: {
+ type: 'string',
+ description:
+ 'Already-surfaced context (pointer blocks / opened page bodies). Pages whose slug ' +
+ 'appears here are not re-volunteered.',
+ },
+ max_pages: { type: 'number', description: 'Max pages to volunteer (default 3, hard cap 5).' },
+ min_confidence: {
+ type: 'number',
+ description:
+ 'Confidence gate 0..1 (default 0.7 — slug-suffix matches need an explicit lower gate).',
+ },
+ session_id: { type: 'string', description: 'Optional caller session id, logged for attribution.' },
+ turn: { type: 'number', description: 'Optional caller turn number, logged for attribution.' },
+ stats: {
+ type: 'boolean',
+ description:
+ 'Return the volunteered-vs-used precision summary instead of volunteering. ' +
+ 'APPROXIMATE: "used" = pages.last_retrieved_at > volunteered_at.',
+ },
+ days: { type: 'number', description: 'Stats window in days (default 30; stats mode only).' },
+ },
+ handler: async (ctx, p) => {
+ const { parseWindow, volunteerContext, volunteerUsageStats } = await import('../context/volunteer.ts');
+ const scope = sourceScopeOpts(ctx);
+ const sourceIds = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : ['default']);
+
+ if (p.stats === true) {
+ return volunteerUsageStats(ctx.engine, sourceIds, typeof p.days === 'number' ? p.days : undefined);
+ }
+
+ if (typeof p.window !== 'string' || !p.window.trim()) {
+ throw new OperationError(
+ 'invalid_params',
+ 'window is required unless stats: true',
+ 'Pass the recent turns as a string (CLI: pipe them on stdin), or use --stats.',
+ );
+ }
+ const turns = parseWindow(p.window);
+ const pages = await volunteerContext(ctx.engine, turns, {
+ sourceIds,
+ priorContext: typeof p.prior_context === 'string' ? p.prior_context : undefined,
+ maxPages: typeof p.max_pages === 'number' ? p.max_pages : undefined,
+ minConfidence: typeof p.min_confidence === 'number' ? p.min_confidence : undefined,
+ });
+
+ // Feedback-loop logging: fire-and-forget batched INSERT through the
+ // volunteer-events sink (drained at exit). Never fails the op.
+ if (pages.length) {
+ try {
+ const { logVolunteerEventsFireAndForget, volunteerEventRowsFrom, SESSION_ID_MAX_LEN } = await import('../context/volunteer-events.ts');
+ // Trust-boundary clamps (remote MCP callers): cap session_id length so
+ // a read-scoped token can't bank unbounded TEXT per request, and only
+ // log integer turns — a non-integer would throw inside the single
+ // multi-row INSERT and silently drop the whole batch.
+ const sessionId = typeof p.session_id === 'string' ? p.session_id.slice(0, SESSION_ID_MAX_LEN) : null;
+ const turn =
+ typeof p.turn === 'number' && Number.isInteger(p.turn) && Math.abs(p.turn) <= 2_147_483_647
+ ? p.turn
+ : null;
+ logVolunteerEventsFireAndForget(
+ ctx.engine,
+ volunteerEventRowsFrom(pages, { channel: 'op', session_id: sessionId, turn }),
+ );
+ } catch {
+ /* telemetry only */
+ }
+ }
+ return { pages, count: pages.length, window_turns: turns.length };
+ },
+ cliHints: { name: 'volunteer-context', stdin: 'window' },
+};
+
+// v0.33: expertise + relationship-proximity routing. CLI: gbrain whoknows.
+const find_experts: Operation = {
+ name: 'find_experts',
+ description: FIND_EXPERTS_DESCRIPTION,
+ scope: 'read',
+ params: {
+ topic: {
+ type: 'string',
+ description: 'The topic to route. Free-form natural language.',
+ },
+ limit: {
+ type: 'number',
+ description: 'Max results (default 5).',
+ },
+ explain: {
+ type: 'boolean',
+ description: 'Include factor breakdown per result (expertise, recency, salience).',
+ },
+ },
+ handler: async (ctx, p) => {
+ const { findExperts } = await import('../../commands/whoknows.ts');
+ const topic = typeof p.topic === 'string' ? p.topic : '';
+ if (!topic.trim()) {
+ throw new OperationError('invalid_params', '`topic` is required and must be a non-empty string.');
+ }
+ // v0.34.1 (#861, D3 — 5th leak surface): find_experts (whoknows) was
+ // authored against v0.33 after PR #861 was drafted, so the source-scope
+ // thread was missing entirely. The op calls findExperts → hybridSearch
+ // internally; without the thread an auth'd src-A whoknows query would
+ // surface src-B people in the rankings.
+ // v0.40.6.0 T1.5 wiring (D4): consult the active pack for expert
+ // types; pack-load failure → empty filter (NOT hardcoded defaults
+ // per the silent-violation bug class Finding 1.3 closed).
+ const { loadActivePackBestEffort, expertTypesFromPack } = await import('../schema-pack/index.ts');
+ const pack = await loadActivePackBestEffort(ctx);
+ const types = pack ? expertTypesFromPack(pack.manifest) : [];
+ return findExperts(ctx.engine, {
+ topic,
+ limit: typeof p.limit === 'number' ? p.limit : undefined,
+ explain: p.explain === true,
+ types: types as never,
+ ...sourceScopeOpts(ctx),
+ });
+ },
+ cliHints: { name: 'whoknows', positional: ['topic'] },
+};
+
+// v0.32.6: contradiction probe MCP surface (M3)
+const find_contradictions: Operation = {
+ name: 'find_contradictions',
+ description: FIND_CONTRADICTIONS_DESCRIPTION,
+ scope: 'read',
+ // Reads eval_contradictions_runs.report_json for the latest run, then
+ // filters in-memory by slug and severity. No new probe is triggered;
+ // the agent surfaces what's already on disk.
+ params: {
+ slug: {
+ type: 'string',
+ description: 'Optional slug filter; matches either side of a pair (substring match on slug).',
+ },
+ severity: {
+ type: 'string',
+ enum: ['low', 'medium', 'high'],
+ description: 'Optional severity filter.',
+ },
+ limit: {
+ type: 'number',
+ description: 'Max findings to return. Default 20.',
+ },
+ },
+ handler: async (ctx, p) => {
+ 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')
+ ? p.severity
+ : null;
+ const rows = await ctx.engine.loadContradictionsTrend(30);
+ if (rows.length === 0) {
+ return { contradictions: [], note: 'No probe runs in the last 30 days; run `gbrain eval suspected-contradictions` first.' };
+ }
+ const latest = rows[0];
+ const report = latest.report_json as Record<string, unknown> | null;
+ const perQuery = (report?.per_query as Array<{
+ contradictions: Array<{
+ kind: string;
+ severity: 'low' | 'medium' | 'high';
+ axis: string;
+ confidence: number;
+ a: { slug: string; chunk_id: number | null; take_id: number | null };
+ b: { slug: string; chunk_id: number | null; take_id: number | null };
+ resolution_kind: string;
+ resolution_command: string;
+ }>;
+ }> | undefined) ?? [];
+ const findings = perQuery.flatMap((q) => q.contradictions);
+ const filtered = findings.filter((f) => {
+ if (sevFilter && f.severity !== sevFilter) return false;
+ if (slugFilter) {
+ const sA = f.a.slug.toLowerCase();
+ const sB = f.b.slug.toLowerCase();
+ if (!sA.includes(slugFilter) && !sB.includes(slugFilter)) return false;
+ }
+ return true;
+ });
+ return {
+ run_id: latest.run_id,
+ ran_at: latest.ran_at,
+ contradictions: filtered.slice(0, limit),
+ total_in_run: findings.length,
+ };
+ },
+ cliHints: { name: 'find-contradictions' },
+};
+
+const find_trajectory: Operation = {
+ name: 'find_trajectory',
+ description: FIND_TRAJECTORY_DESCRIPTION,
+ scope: 'read',
+ // localOnly intentionally NOT set — federated OAuth clients should be
+ // able to query trajectories for entities in their scope. Visibility
+ // filtering (D-CDX-1) inside the engine restricts remote callers to
+ // visibility='world' facts.
+ params: {
+ entity_slug: {
+ type: 'string',
+ description: 'Required. Entity slug to chart (e.g. "companies/acme-example", "people/alice-example").',
+ },
+ metric: {
+ type: 'string',
+ description: 'Optional. Filter to a single canonical metric (e.g. "mrr", "arr", "team_size"). When omitted, all metrics return.',
+ },
+ kind: {
+ type: 'string',
+ enum: ['metric', 'event', 'all'],
+ description: 'Optional. Filter by row shape: "metric" (typed-claim rows only), "event" (event_type rows only), or "all" (default). v0.40.2.0+.',
+ },
+ since: {
+ type: 'string',
+ description: 'Optional lower bound on valid_from (YYYY-MM-DD or ISO).',
+ },
+ until: {
+ type: 'string',
+ description: 'Optional upper bound on valid_from (YYYY-MM-DD or ISO).',
+ },
+ limit: {
+ type: 'number',
+ description: 'Max points returned. Default 100, max 500.',
+ },
+ },
+ handler: async (ctx, p) => {
+ if (typeof p.entity_slug !== 'string' || !p.entity_slug.trim()) {
+ throw new Error('find_trajectory requires entity_slug (string)');
+ }
+ const metric = typeof p.metric === 'string' ? p.metric : undefined;
+ const kind = (p.kind === 'metric' || p.kind === 'event' || p.kind === 'all')
+ ? (p.kind as 'metric' | 'event' | 'all')
+ : undefined;
+ const since = typeof p.since === 'string' ? p.since : undefined;
+ const until = typeof p.until === 'string' ? p.until : undefined;
+ const limit = typeof p.limit === 'number' ? p.limit : undefined;
+ const scope = sourceScopeOpts(ctx);
+
+ // D-CDX-1: thread ctx.remote into the engine so visibility filtering
+ // happens at SQL level. Mirrors recall's posture for untrusted callers.
+ const points = await ctx.engine.findTrajectory({
+ entitySlug: p.entity_slug,
+ ...scope,
+ remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)
+ metric,
+ kind,
+ since,
+ until,
+ limit,
+ });
+
+ const { computeTrajectoryStats, TRAJECTORY_SCHEMA_VERSION } = await import('../trajectory.ts');
+ const { regressions, drift_score } = computeTrajectoryStats(points);
+
+ // Engine result includes raw embeddings (Float32Array); strip those
+ // before sending over MCP — they're bulky binary noise that consumers
+ // never need at this layer.
+ // v0.40.2.0: event_type surfaces on the wire so remote callers (thin-
+ // client think, founder-scorecard) see the event-shaped rows.
+ const wirePoints = points.map(pt => ({
+ fact_id: pt.fact_id,
+ valid_from: pt.valid_from.toISOString().slice(0, 10),
+ metric: pt.metric,
+ value: pt.value,
+ unit: pt.unit,
+ period: pt.period,
+ event_type: pt.event_type,
+ text: pt.text,
+ source_session: pt.source_session,
+ source_markdown_slug: pt.source_markdown_slug,
+ }));
+
+ return {
+ points: wirePoints,
+ regressions,
+ drift_score,
+ schema_version: TRAJECTORY_SCHEMA_VERSION,
+ };
+ },
+ cliHints: { name: 'find-trajectory' },
+};
+
+export { volunteer_context, find_experts, find_contradictions, find_trajectory };
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.ts
new file mode 100644
index 0000000000..5326009921
--- /dev/null
+++ b/src/core/ops/jobs.ts
@@ -0,0 +1,636 @@
+/**
+ * Jobs (Minions) operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 2). Op consts stay module-private; `jobsOperations` below lists
+ * them in EXACTLY the order they appear in the canonical `operations` array
+ * in ../operations.ts (the array interleaves the generic queue ops before
+ * the agent-lane pair, unlike the definition order here — the array order is
+ * the contract). Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation, OperationContext } from './contract.ts';
+import { OperationError } from './contract.ts';
+import { normalizeSlugPrefix } from './context.ts';
+
+// --- Jobs (Minions) ---
+
+const submit_job: Operation = {
+ name: 'submit_job',
+ description: 'Submit a background job to the Minions queue. Built-in types are registered by registerBuiltinHandlers (src/commands/jobs.ts) — e.g. sync, embed, lint, import, extract, backlinks, autopilot-cycle, subagent, and more; submitting an unknown name with --follow prints the full list. The `shell` type is CLI-only and rejected over MCP.',
+ params: {
+ name: { type: 'string', required: true, description: 'Job type (e.g. sync, embed, lint, import, extract, backlinks, autopilot-cycle; shell is CLI-only). Full registry: registerBuiltinHandlers in src/commands/jobs.ts.' },
+ data: { type: 'object', description: 'Job payload (JSON)' },
+ queue: { type: 'string', description: 'Queue name (default: "default")' },
+ priority: { type: 'number', description: 'Priority (0 = highest, default: 0)' },
+ max_attempts: { type: 'number', description: 'Max retry attempts (default: 3)' },
+ delay: { type: 'number', description: 'Delay in ms before eligible' },
+ timeout_ms: { type: 'number', description: 'Per-job wall-clock timeout in ms; aborted job goes to dead' },
+ lock_duration_ms: { type: 'number', description: 'Per-job lock lease in ms (#4145). Out-of-range values are clamped to [5000, 3600000] — remote writers cannot pin an immortal lock. Omit to use the handler-type default (300s for long LLM handlers) or the worker default (30s).' },
+ },
+ mutating: true,
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const name = typeof p.name === 'string' ? p.name.trim() : '';
+ if (ctx.dryRun) return { dry_run: true, action: 'submit_job', name };
+
+ // Submit-side MCP guard: reject protected job names from untrusted callers
+ // BEFORE we touch the DB. This is the first of the two security layers
+ // (the second is MinionQueue.add's check). Independent of the worker-side
+ // GBRAIN_ALLOW_SHELL_JOBS env flag — even if that flag is on, MCP callers
+ // cannot submit protected-type jobs.
+ const { isProtectedJobName } = await import('../minions/protected-names.ts');
+ // F7b fail-closed: anything that is not strictly false (i.e., remote=true OR
+ // the field somehow leaks in undefined despite the required type) rejects
+ // protected job submissions. Closes the HTTP MCP shell-job RCE that surfaced
+ // when the HTTP transport's OperationContext literal forgot to set remote.
+ if (ctx.remote !== false && isProtectedJobName(name)) {
+ throw new OperationError('permission_denied', `'${name}' jobs cannot be submitted over MCP (CLI-only for security)`);
+ }
+
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ // Trusted flag fires ONLY for an explicit local CLI submission of a protected
+ // name. Strict `=== false` so an untyped/cast context can't escalate.
+ const trusted = ctx.remote === false && isProtectedJobName(name) ? { allowProtectedSubmit: true } : undefined;
+
+ const jobData = (p.data as Record<string, unknown>) || {};
+
+ // v0.35.8.0: pre-enqueue shell-job validation, parity with the CLI submit
+ // path. Closes the bug class where shell.ts handler-time validation ran
+ // AFTER queue.add() persisted the row (codex F-CDX-1). Note: this branch
+ // only fires for trusted local submitters (`ctx.remote === false` AND
+ // protected-name allowlist), so remote MCP callers never reach it — but
+ // it stays here as defense-in-depth in case a future code path widens
+ // the trust gate above.
+ if (name === 'shell' && trusted) {
+ const { validateShellJobParams } = await import('../minions/handlers/shell-validate.ts');
+ validateShellJobParams(jobData);
+ }
+
+ const job = await queue.add(name, jobData, {
+ queue: (p.queue as string) || 'default',
+ priority: (p.priority as number) || 0,
+ max_attempts: (p.max_attempts as number) || 3,
+ delay: (p.delay as number) || undefined,
+ timeout_ms: (p.timeout_ms as number) || undefined,
+ // #4145 [CEO-F7/R2-6]: range enforcement lives in queue.add's
+ // clampLockDurationMs (ParamDef has no min/max support; wrong TYPE is
+ // rejected by the shared number validation upstream of this handler).
+ lock_duration_ms: (p.lock_duration_ms as number) || undefined,
+ }, trusted);
+
+ // v0.35.8.0: submit_job audit-log parity with the CLI path (codex F-CDX-4).
+ // Pre-v0.35.8.0 the op handler bypassed the shell-audit JSONL writer
+ // entirely. Lift the call here so both submit surfaces produce one
+ // operational-trace line per shell submission. Best-effort; audit
+ // failures never block submission.
+ if (name === 'shell' && trusted) {
+ try {
+ const { logShellSubmission } = await import('../minions/handlers/shell-audit.ts');
+ const inheritNames = Array.isArray(jobData.inherit)
+ ? (jobData.inherit as unknown[]).filter((s): s is string => typeof s === 'string')
+ : undefined;
+ logShellSubmission({
+ caller: 'mcp',
+ // Gated on `trusted` (which requires ctx.remote === false), so
+ // we know this path is a local trusted submitter — log it that way.
+ remote: false,
+ job_id: job.id,
+ cwd: typeof jobData.cwd === 'string' ? jobData.cwd : '',
+ cmd_display: typeof jobData.cmd === 'string' ? (jobData.cmd as string).slice(0, 80) : undefined,
+ argv_display: Array.isArray(jobData.argv)
+ ? (jobData.argv as unknown[]).filter((a): a is string => typeof a === 'string').map((a) => a.slice(0, 80))
+ : undefined,
+ inherit: inheritNames && inheritNames.length > 0 ? inheritNames : undefined,
+ });
+ } catch { /* audit failures never block submission */ }
+ }
+
+ // Amendments 24/25: post-enqueue queue-state probe (time-bounded,
+ // fail-open). The job is already persisted; a probe failure degrades to
+ // {probe_failed: true}, never an error on a successful submission.
+ return { ...job, queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };
+ },
+};
+
+/**
+ * Wrapper around `probeQueueState` that also swallows module-load failures,
+ * so BOTH submit surfaces (submit_job, submit_agent) satisfy amendment 24's
+ * "probe failure NEVER errors a successful submission" — even when the
+ * supervisor module itself cannot load.
+ */
+async function probeQueueStateSafe(
+ ctx: OperationContext,
+ queue: string,
+ handlerNames: string[],
+): Promise<Record<string, unknown>> {
+ try {
+ const { probeQueueState } = await import('../minions/supervisor.ts');
+ return (await probeQueueState(ctx.engine, queue, handlerNames)) as unknown as Record<string, unknown>;
+ } catch {
+ return { probe_failed: true };
+ }
+}
+
+// v0.38 Slice 3 — D13 — remote-callable submit_agent with registration-time
+// binding enforcement. Distinct from `submit_job` because:
+// 1. It's the FIRST op that lets remote MCP callers spawn paid LLM work
+// (cost concerns + audit trail differ from generic submit_job).
+// 2. The trust boundary lives in oauth_clients.bound_* fields, not in the
+// protected-name guard. Bindings are enforced PER-OP, not per-name.
+// 3. The dispatcher is the subagent handler with the gateway-native loop
+// (agent.use_gateway_loop is auto-on for submit_agent jobs).
+const submit_agent: Operation = {
+ name: 'submit_agent',
+ description: 'Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. Requires the `agent` OAuth scope. Tools, source, slug prefixes, max concurrency, and daily budget are bound at OAuth client registration time.',
+ params: {
+ prompt: { type: 'string', required: true, description: 'User prompt for the agent' },
+ model: { type: 'string', description: 'provider:model string (defaults to models.tier.subagent)' },
+ allowed_tools: { type: 'array', description: 'Subset of bound_tools the agent may invoke', items: { type: 'string' } },
+ allowed_slug_prefixes: { type: 'array', description: 'Subset of bound_slug_prefixes for put_page writes', items: { type: 'string' } },
+ max_turns: { type: 'number', description: 'Max LLM turns (default 20, hard cap 100)' },
+ queue: { type: 'string', description: 'Queue name (default "default")' },
+ },
+ mutating: true,
+ scope: 'agent',
+ handler: async (ctx, p) => {
+ // Remote-callable but only when the OAuth client has scope=agent AND
+ // a binding row. Local CLI callers (ctx.remote === false) skip the
+ // binding check — `gbrain agent run` already runs through subagent.ts
+ // directly without going through this op.
+ if (ctx.remote === false) {
+ throw new OperationError('invalid_request', 'submit_agent over the local CLI: use `gbrain agent run` instead.');
+ }
+
+ const clientId = (ctx as { auth?: { clientId?: string } }).auth?.clientId;
+ if (!clientId || typeof clientId !== 'string') {
+ throw new OperationError('permission_denied', 'submit_agent requires an OAuth client with the `agent` scope.');
+ }
+
+ // Load the binding row.
+ const { sqlQueryForEngine } = await import('../sql-query.ts');
+ const sql = sqlQueryForEngine(ctx.engine);
+ let bindingRows: Array<Record<string, unknown>>;
+ try {
+ bindingRows = await sql`
+ SELECT bound_tools, bound_source_id, bound_brain_id, bound_slug_prefixes,
+ bound_max_concurrent, budget_usd_per_day::text AS budget_cap
+ FROM oauth_clients
+ WHERE client_id = ${clientId}
+ `;
+ } catch (err) {
+ throw new OperationError(
+ 'internal',
+ `submit_agent: could not load OAuth client binding: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (bindingRows.length === 0) {
+ throw new OperationError('permission_denied', `submit_agent: client_id ${clientId} not found.`);
+ }
+ const binding = bindingRows[0];
+ const boundTools = (binding.bound_tools as string[] | null) ?? null;
+ const boundSource = (binding.bound_source_id as string | null) ?? null;
+ const boundSlugPrefixes = (binding.bound_slug_prefixes as string[] | null) ?? null;
+ const boundMaxConcurrent = Number(binding.bound_max_concurrent ?? 1);
+ const budgetCapText = (binding.budget_cap as string | null) ?? null;
+
+ if (boundTools === null) {
+ throw new OperationError(
+ 'permission_denied',
+ `submit_agent: client ${clientId} has the agent scope but no bindings. Re-register with --bound-tools, --bound-source, --bound-slug-prefixes, --bound-max-concurrent, --budget-usd-per-day.`,
+ );
+ }
+
+ // Validate each param against the binding.
+ //
+ // An EXPLICIT empty array is not "no restriction" here — downstream the
+ // subagent worker reads empty `allowed_tools` as "the full tool registry"
+ // and empty `allowed_slug_prefixes` as "fall back to the legacy
+ // wiki/agents/<job-id>/ namespace". Both subset loops below pass
+ // vacuously over an empty list, so `{allowed_tools: [], allowed_slug_prefixes: []}`
+ // from a client bound to `['search']` + `['emp-alice/']` would hand its
+ // subagent the whole registry (including put_page) writing outside the
+ // binding. `??` only substitutes null/undefined, so collapse the empty
+ // case to the binding explicitly.
+ const requestedToolsRaw = p.allowed_tools as string[] | undefined;
+ const requestedTools = requestedToolsRaw === undefined || requestedToolsRaw.length === 0
+ ? boundTools
+ : requestedToolsRaw;
+ for (const t of requestedTools) {
+ if (!boundTools.includes(t)) {
+ throw new OperationError(
+ 'permission_denied',
+ `submit_agent: tool "${t}" is not in client ${clientId}'s bound_tools (${boundTools.join(', ')}).`,
+ );
+ }
+ }
+ const requestedSlugPrefixesRaw = p.allowed_slug_prefixes as string[] | undefined;
+ const requestedSlugPrefixes =
+ requestedSlugPrefixesRaw === undefined || requestedSlugPrefixesRaw.length === 0
+ ? (boundSlugPrefixes ?? [])
+ : requestedSlugPrefixesRaw;
+ // A bound client must end up with a non-empty delegated fence: an empty
+ // list reaches the subagent as "use the legacy wiki/agents/<id>/ namespace",
+ // which is outside every bound prefix.
+ if (boundSlugPrefixes !== null && requestedSlugPrefixes.length === 0) {
+ throw new OperationError(
+ 'permission_denied',
+ `submit_agent: client ${clientId} is slug-bound but its binding resolved to an empty prefix list, which the subagent would read as the unfenced legacy namespace.`,
+ 'Re-scope the client with a non-empty --bound-slug-prefixes.',
+ );
+ }
+ if (boundSlugPrefixes !== null) {
+ for (const sp of requestedSlugPrefixes) {
+ // Boundary-aware, same rule as the direct fence: a raw `startsWith`
+ // let a boundary-less binding (`emp-alice`) authorize a requested
+ // prefix in a SIBLING namespace (`emp-alice-2/`), which is then handed
+ // to the child as a full glob grant over another employee's pages.
+ if (!boundSlugPrefixes.some(bp => {
+ const base = normalizeSlugPrefix(bp);
+ const req = normalizeSlugPrefix(sp);
+ if (base === '') return false;
+ return base.endsWith('/')
+ ? req.startsWith(base)
+ : req === base || req.startsWith(`${base}/`);
+ })) {
+ throw new OperationError(
+ 'permission_denied',
+ `submit_agent: slug_prefix "${sp}" is not under any of client ${clientId}'s bound_slug_prefixes.`,
+ );
+ }
+ }
+ }
+
+ // Concurrency cap: count active+waiting agent jobs for this client.
+ const inflight = await sql`
+ SELECT COUNT(*)::int AS n
+ FROM minion_jobs j
+ WHERE j.name = 'subagent'
+ AND j.status IN ('waiting', 'active', 'waiting-children')
+ AND j.data->>'__owner_client_id' = ${clientId}
+ `;
+ const inflightCount = Number((inflight[0]?.n as number | string | undefined) ?? 0);
+ if (inflightCount >= boundMaxConcurrent) {
+ throw new OperationError(
+ 'rate_limited',
+ `submit_agent: client ${clientId} at concurrency cap (${inflightCount}/${boundMaxConcurrent}).`,
+ );
+ }
+
+ // Dry-run echo.
+ // The subagent fence uses `matchesSlugAllowList`, whose grammar makes a
+ // BARE entry match that one slug exactly — so a plain `emp-alice/` binding
+ // would let the delegated agent write nothing. Normalize the
+ // trailing-slash form into the glob the delegated matcher expects, so one
+ // stored column means the same span of slugs on both paths.
+ const delegatedSlugPrefixes = requestedSlugPrefixes.map(sp =>
+ sp.endsWith('/') ? `${sp}*` : sp);
+
+ if (ctx.dryRun) {
+ return {
+ dry_run: true,
+ action: 'submit_agent',
+ client_id: clientId,
+ bound_tools: boundTools,
+ bound_source: boundSource,
+ bound_max_concurrent: boundMaxConcurrent,
+ // What the delegated job would ACTUALLY be granted, after the binding
+ // is applied — a preview that hides this can't show a widening bug.
+ resolved_tools: requestedTools,
+ resolved_slug_prefixes: delegatedSlugPrefixes,
+ };
+ }
+
+ // Submit via MinionQueue with allowProtectedSubmit (the agent op is
+ // remote-callable but the underlying job name 'subagent' is protected;
+ // the OAuth scope check above stands in for the protected-name guard).
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+
+ const jobData: Record<string, unknown> = {
+ prompt: p.prompt as string,
+ max_turns: Math.min((p.max_turns as number) ?? 20, 100),
+ allowed_tools: requestedTools,
+ allowed_slug_prefixes: delegatedSlugPrefixes,
+ __owner_client_id: clientId,
+ };
+ if (typeof p.model === 'string') jobData.model = p.model;
+ // Write source for the delegated job comes from the AUTHENTICATED client
+ // whenever we have it. `bound_source_id` is an optional, separately-set
+ // column: unset it defaulted the child to 'default', and if it disagreed
+ // with the token's own source the child followed the column — either way
+ // a correctly slug-fenced client could act on the wrong source.
+ const delegatedSource = ctx.auth?.sourceId ?? boundSource;
+ if (boundSource && ctx.auth?.sourceId && boundSource !== ctx.auth.sourceId) {
+ throw new OperationError(
+ 'permission_denied',
+ `submit_agent: client ${clientId}'s bound_source_id (${boundSource}) disagrees with its authenticated source (${ctx.auth.sourceId}); refusing to guess which one governs the delegated write.`,
+ 'Re-scope the client so the two agree: `gbrain auth rescope-client <id> --source <source>`.',
+ );
+ }
+ if (delegatedSource) jobData.source_id = delegatedSource;
+ const job = await queue.add(
+ 'subagent',
+ jobData,
+ { queue: (p.queue as string) || 'default' },
+ { allowProtectedSubmit: true },
+ );
+
+ // Audit trail (D4) — best-effort JSONL.
+ try {
+ const { logAgentSubmission } = await import('../minions/agent-audit.ts');
+ const budgetCapCents = budgetCapText ? Math.round(parseFloat(budgetCapText) * 100) : null;
+ const promptText = typeof p.prompt === 'string' ? p.prompt : '';
+ logAgentSubmission({
+ client_id: clientId,
+ job_id: job.id,
+ model: typeof p.model === 'string' ? p.model : '<default>',
+ bound_tools: requestedTools,
+ bound_source: boundSource,
+ slug_prefixes: requestedSlugPrefixes,
+ max_concurrent: boundMaxConcurrent,
+ budget_remaining_cents: budgetCapCents,
+ prompt_byte_count: Buffer.byteLength(promptText, 'utf8'),
+ outcome: 'submitted',
+ });
+ } catch { /* never block submission */ }
+
+ // Amendments 24/25: the returned job id means nothing if the lane is
+ // dead — attach a time-bounded, fail-open queue-state probe.
+ return {
+ id: job.id,
+ name: 'subagent',
+ client_id: clientId,
+ queue_state: await probeQueueStateSafe(ctx, job.queue, ['subagent']),
+ };
+ },
+};
+
+/**
+ * Minions-visibility wave — ownership-fenced agent-job status (amendment 27).
+ *
+ * The companion read for `submit_agent`: an agent-scoped client can poll ONLY
+ * its own delegated jobs. Deliberate posture:
+ * - `ctx.auth.clientId` is REQUIRED on EVERY transport — stdio and legacy
+ * bearer callers carry no client identity and are refused
+ * (permission_denied) rather than silently unfenced. This is stricter
+ * than scope enforcement alone (which local/stdio callers bypass).
+ * - The ownership filter is a fail-closed SQL WHERE on
+ * `data->>'__owner_client_id'` (the JSONB predicate submit_agent already
+ * uses for its concurrency cap — identical semantics on both engines),
+ * never a post-fetch JS check.
+ * - Foreign and missing ids return one uniform `not_found` envelope so the
+ * op is not a job-id enumeration oracle (ENG-13; the ErrorCode comment
+ * was widened accordingly). Shell/admin jobs stay on admin-scope
+ * `get_job` — this op reads the agent lane (`name = 'subagent'`) only.
+ * - `queue_position` = count of waiting jobs ahead in claim order
+ * (priority ASC, created_at ASC — the exact ORDER BY of
+ * `MinionQueue.claim`), computed only while status = 'waiting'.
+ */
+const get_agent_job: Operation = {
+ name: 'get_agent_job',
+ description: 'Poll an agent job submitted via submit_agent. Returns a trimmed status view (id, status, timestamps, error_text, result) plus queue_position (waiting jobs ahead in claim order; 0 = next) while the job is still waiting. Requires the `agent` OAuth scope; only jobs owned by the calling client are visible.',
+ params: {
+ id: { type: 'number', required: true, description: 'Job id returned by submit_agent' },
+ },
+ scope: 'agent',
+ handler: async (ctx, p) => {
+ const clientId = ctx.auth?.clientId;
+ if (!clientId || typeof clientId !== 'string') {
+ throw new OperationError(
+ 'permission_denied',
+ 'get_agent_job requires an authenticated OAuth client identity.',
+ 'Call over HTTP MCP with an `agent`-scoped token. Transports without a per-client identity (stdio, legacy bearer) cannot read agent jobs; use admin-scope get_job from a trusted context instead.',
+ );
+ }
+ const id = p.id;
+ if (typeof id !== 'number' || !Number.isInteger(id)) {
+ throw new OperationError('invalid_params', 'id must be an integer job id');
+ }
+
+ // One round-trip: the ownership fence rides the WHERE, and the
+ // queue_position subselect mirrors MinionQueue.claim's candidate set
+ // (same queue, status='waiting') and ORDER BY (priority, created_at),
+ // with the row id as the deterministic tie-break. Perf: the outer lookup
+ // is a primary-key read; the subselect's (queue, status) filter is
+ // covered by the wave's wedge-index prefix once that migration (another
+ // lane) lands, and stays a small scan until then.
+ const rows = await ctx.engine.executeRaw<{
+ id: number;
+ status: string;
+ created_at: string | Date | null;
+ started_at: string | Date | null;
+ finished_at: string | Date | null;
+ error_text: string | null;
+ result: unknown;
+ queue_position: number | string | null;
+ }>(
+ `SELECT j.id, j.status, j.created_at, j.started_at, j.finished_at, j.error_text, j.result,
+ CASE WHEN j.status = 'waiting' THEN (
+ SELECT count(*)::int FROM minion_jobs q
+ WHERE q.queue = j.queue AND q.status = 'waiting'
+ AND (q.priority < j.priority
+ OR (q.priority = j.priority AND q.created_at < j.created_at)
+ OR (q.priority = j.priority AND q.created_at = j.created_at AND q.id < j.id))
+ ) ELSE NULL END AS queue_position
+ FROM minion_jobs j
+ WHERE j.id = $1
+ AND j.name = 'subagent'
+ AND j.data->>'__owner_client_id' = $2`,
+ [id, clientId],
+ );
+ if (rows.length === 0) {
+ // Uniform envelope: foreign-owned and nonexistent ids are
+ // indistinguishable by design (anti-enumeration).
+ throw new OperationError('not_found', `Job not found: ${id}`);
+ }
+ const row = rows[0];
+ const iso = (v: string | Date | null): string | null =>
+ v ? (v instanceof Date ? v.toISOString() : new Date(v).toISOString()) : null;
+ // PGLite may hand jsonb back as text; postgres.js parses it.
+ let result: unknown = row.result ?? null;
+ if (typeof result === 'string') {
+ try { result = JSON.parse(result); } catch { /* keep raw text */ }
+ }
+ return {
+ id: row.id,
+ status: row.status,
+ created_at: iso(row.created_at),
+ started_at: iso(row.started_at),
+ finished_at: iso(row.finished_at),
+ // Cap: error_text is an unbounded worker-written field (stack traces,
+ // provider dumps); a remote polling view shouldn't ship megabytes.
+ error_text: row.error_text ? row.error_text.slice(0, 2000) : null,
+ result,
+ ...(row.status === 'waiting' && row.queue_position !== null
+ ? { queue_position: Number(row.queue_position) }
+ : {}),
+ };
+ },
+};
+
+const get_job: Operation = {
+ name: 'get_job',
+ description: 'Get job status and details by ID',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID' },
+ },
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const job = await queue.getJob(p.id as number);
+ if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);
+ return job;
+ },
+};
+
+const list_jobs: Operation = {
+ name: 'list_jobs',
+ description: 'List jobs with optional filters',
+ params: {
+ status: { type: 'string', description: 'Filter by status (waiting, active, completed, failed, delayed, dead, cancelled)' },
+ queue: { type: 'string', description: 'Filter by queue name' },
+ name: { type: 'string', description: 'Filter by job type' },
+ limit: { type: 'number', description: 'Max results (default: 50)' },
+ },
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ return queue.getJobs({
+ status: p.status as string | undefined,
+ queue: p.queue as string | undefined,
+ name: p.name as string | undefined,
+ limit: (p.limit as number) || 50,
+ } as Parameters<typeof queue.getJobs>[0]);
+ },
+};
+
+const cancel_job: Operation = {
+ name: 'cancel_job',
+ description: 'Cancel a waiting, active, or delayed job',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID' },
+ },
+ mutating: true,
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'cancel_job', id: p.id };
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const cancelled = await queue.cancelJob(p.id as number);
+ if (!cancelled) throw new OperationError('invalid_params', `Cannot cancel job ${p.id} (may already be in terminal status)`);
+ return cancelled;
+ },
+};
+
+const retry_job: Operation = {
+ name: 'retry_job',
+ description: 'Re-queue a failed or dead job for retry',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID' },
+ },
+ mutating: true,
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'retry_job', id: p.id };
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const retried = await queue.retryJob(p.id as number);
+ if (!retried) throw new OperationError('invalid_params', `Cannot retry job ${p.id} (must be failed or dead)`);
+ return retried;
+ },
+};
+
+const get_job_progress: Operation = {
+ name: 'get_job_progress',
+ description: 'Get structured progress for a running job',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID' },
+ },
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const job = await queue.getJob(p.id as number);
+ if (!job) throw new OperationError('invalid_params', `Job not found: ${p.id}`);
+ return { id: job.id, name: job.name, status: job.status, progress: job.progress };
+ },
+};
+
+const pause_job: Operation = {
+ name: 'pause_job',
+ description: 'Pause a waiting, active, or delayed job',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID' },
+ },
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const job = await queue.pauseJob(p.id as number);
+ if (!job) throw new OperationError('invalid_params', `Job not found or not pausable: ${p.id}`);
+ return { id: job.id, status: job.status };
+ },
+};
+
+const resume_job: Operation = {
+ name: 'resume_job',
+ description: 'Resume a paused job back to waiting',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID' },
+ },
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const job = await queue.resumeJob(p.id as number);
+ if (!job) throw new OperationError('invalid_params', `Job not found or not paused: ${p.id}`);
+ return { id: job.id, status: job.status };
+ },
+};
+
+const replay_job: Operation = {
+ name: 'replay_job',
+ description: 'Replay a completed/failed/dead job, optionally with modified data',
+ params: {
+ id: { type: 'number', required: true, description: 'Source job ID to replay' },
+ data_overrides: { type: 'object', required: false, description: 'Data fields to override (merged with original)' },
+ },
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'replay_job', id: p.id };
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const job = await queue.replayJob(p.id as number, p.data_overrides as Record<string, unknown> | undefined);
+ if (!job) throw new OperationError('invalid_params', `Job not found or not in terminal state: ${p.id}`);
+ return { id: job.id, name: job.name, status: job.status, source_id: p.id };
+ },
+};
+
+const send_job_message: Operation = {
+ name: 'send_job_message',
+ description: 'Send a sidechannel message to a running job\'s inbox',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID to message' },
+ payload: { type: 'object', required: true, description: 'Message payload (arbitrary JSON)' },
+ sender: { type: 'string', required: false, description: 'Sender identity (default: admin)' },
+ },
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ if (ctx.dryRun) return { dry_run: true, action: 'send_job_message', id: p.id };
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ const msg = await queue.sendMessage(p.id as number, p.payload, (p.sender as string) ?? 'admin');
+ if (!msg) throw new OperationError('invalid_params', `Job not found, not messageable, or sender unauthorized: ${p.id}`);
+ return { sent: true, message_id: msg.id, job_id: p.id };
+ },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const jobsOperations: Operation[] = [
+ submit_job, get_job, list_jobs, cancel_job, retry_job, get_job_progress,
+ pause_job, resume_job, replay_job, send_job_message,
+ submit_agent, get_agent_job,
+];
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
new file mode 100644
index 0000000000..5895fd82c9
--- /dev/null
+++ b/src/core/ops/links.ts
@@ -0,0 +1,196 @@
+/**
+ * Links + graph operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 1). MANAGED_LINK_SOURCES stays exported (test suite + operations.ts
+ * re-export depend on it); op consts stay module-private. `linksOperations`
+ * below lists them in EXACTLY the order they appear in the canonical
+ * `operations` array in ../operations.ts. Never import from
+ * '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { enforceClientSlugFence, linkReadScopeOpts, sourceScopeOpts } from './context.ts';
+
+// --- Links ---
+
+/**
+ * v114 (#1941): reconciliation-managed provenances a CALLER must not forge via
+ * the add_link op. Internal writers (import-file frontmatter reconciliation,
+ * extract --by-mention, wikilink resolution) write these straight through the
+ * engine — they're excluded here, not at the DB CHECK. A hand-created edge
+ * tagged 'frontmatter' with no origin_page_id would be a phantom that put_page
+ * reconciliation (link_source='frontmatter' AND origin_page_id=written_page)
+ * never cleans (see src/schema.sql). `manual` is intentionally absent — it IS
+ * the user-facing provenance and the default for omitted link_source.
+ */
+export const MANAGED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-resolved'];
+
+const add_link: Operation = {
+ name: 'add_link',
+ description: 'Create link between pages',
+ params: {
+ from: { type: 'string', required: true, description: "Slug of the page the link originates from (the edge renders on this page), e.g. 'people/alice-example'. These are page slugs — there is no `source`/`target` pair." },
+ to: { type: 'string', required: true, description: "Slug of the page the link points to, e.g. 'companies/acme-example'." },
+ link_type: { type: 'string', description: 'Link type (e.g., invested_in, works_at)' },
+ context: { type: 'string', description: 'Context for the link' },
+ link_source: { type: 'string', description: "Provenance tag (kebab-case, e.g. 'citation-graph'). Defaults to 'manual'. Reconciliation-managed built-ins (markdown/frontmatter/mentions/wikilink-resolved) are rejected." },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ // Client fence on the `from` endpoint only: the edge originates from
+ // (and renders on) the from page; linking TO a page outside the
+ // binding is a reference, not a mutation of the target.
+ enforceClientSlugFence(ctx, p.from as string, 'add_link');
+ if (ctx.dryRun) return { dry_run: true, action: 'add_link', from: p.from, to: p.to };
+ // v114 (#1941): default omitted provenance to 'manual' (NOT the engine's
+ // 'markdown' default) so hand/tool-created CLI edges are honestly manual,
+ // and forbid forging the reconciliation-managed built-ins.
+ const linkSource = ((p.link_source as string) || 'manual').trim();
+ if (MANAGED_LINK_SOURCES.includes(linkSource)) {
+ throw new Error(
+ `link_source '${linkSource}' is reconciliation-managed and cannot be set manually; ` +
+ `use 'manual' (the default) or a custom kebab tag like 'citation-graph'`,
+ );
+ }
+ // v0.31.8 (D7): single ctx.sourceId scopes both endpoints + origin. Cross-
+ // source link creation is out of scope for this wave; use the engine API
+ // directly for that edge case.
+ const linkOpts = ctx.sourceId
+ ? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId, originSourceId: ctx.sourceId }
+ : undefined;
+ await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hook
+ p.from as string, p.to as string,
+ (p.context as string) || '', (p.link_type as string) || '',
+ linkSource, undefined, undefined,
+ linkOpts,
+ );
+ return { status: 'ok' };
+ },
+ cliHints: { name: 'link', aliases: ['link-add'], positional: ['from', 'to'] },
+};
+
+const remove_link: Operation = {
+ name: 'remove_link',
+ description: 'Remove link between pages',
+ params: {
+ from: { type: 'string', required: true, description: 'Slug of the page the link originates from (same endpoint order as add_link).' },
+ to: { type: 'string', required: true, description: 'Slug of the page the link points to.' },
+ link_type: { type: 'string', description: 'Only remove edges of this link type (omit = all types)' },
+ link_source: { type: 'string', description: 'Only remove edges of this provenance (e.g. citation-graph); omit = any provenance' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ enforceClientSlugFence(ctx, p.from as string, 'remove_link');
+ if (ctx.dryRun) return { dry_run: true, action: 'remove_link', from: p.from, to: p.to };
+ const linkOpts = ctx.sourceId
+ ? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId }
+ : undefined;
+ await ctx.engine.removeLink(
+ p.from as string, p.to as string,
+ (p.link_type as string) || undefined,
+ (p.link_source as string) || undefined,
+ linkOpts,
+ );
+ return { status: 'ok' };
+ },
+ cliHints: { name: 'unlink', aliases: ['link-rm'], positional: ['from', 'to'] },
+};
+
+const get_links: Operation = {
+ name: 'get_links',
+ description: 'List outgoing links from a page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },
+ },
+ handler: async (ctx, p) => {
+ // #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);
+ return ctx.engine.getLinks(p.slug as string, sourceOpts);
+ },
+ scope: 'read',
+};
+
+const get_backlinks: Operation = {
+ name: 'get_backlinks',
+ description: 'List incoming links to a page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose incoming links to list.' },
+ },
+ 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);
+ return ctx.engine.getBacklinks(p.slug as string, sourceOpts);
+ },
+ scope: 'read',
+ cliHints: { name: 'backlinks', positional: ['slug'] },
+};
+
+const list_link_sources: Operation = {
+ name: 'list_link_sources',
+ // v114 (#1941): the read-side counterpart to link-add/link-rm. Since
+ // link_source is now an open kebab provenance (no allowlist), this is how an
+ // agent discovers which provenances a brain actually carries.
+ description: 'List distinct link_source provenances in the brain with edge counts (e.g. citation-graph, manual, markdown)',
+ params: {},
+ handler: async (ctx) => {
+ // Route through sourceScopeOpts so the read honors both scalar ctx.sourceId
+ // and federated ctx.auth.allowedSources (no cross-source provenance leak).
+ return ctx.engine.listLinkSources(sourceScopeOpts(ctx));
+ },
+ scope: 'read',
+ cliHints: { name: 'link-sources' },
+};
+
+/**
+ * Hard cap on traverse_graph depth from MCP callers. Each recursive CTE iteration
+ * grows a `visited` array per path; in `direction=both` the join is `OR`-based and
+ * fans out exponentially. Without a cap, a remote MCP caller can pass depth=1e6
+ * and burn memory/CPU on the database. 10 hops is well beyond any realistic
+ * relationship query (your OpenClaw's "people who attended meetings with Alice"
+ * is 2 hops; the deepest meaningful chain in our test data is 4).
+ */
+const TRAVERSE_DEPTH_CAP = 10;
+
+const traverse_graph: Operation = {
+ name: 'traverse_graph',
+ description: 'Traverse link graph from a page. With link_type/direction, returns edges (GraphPath[]) instead of nodes.',
+ params: {
+ slug: { type: 'string', required: true, description: "Slug of the page to start the traversal from, e.g. 'people/alice-example'. This is the start-node param — there is no `start` or `root` param." },
+ depth: { type: 'number', description: `Max traversal depth (default 5, capped at ${TRAVERSE_DEPTH_CAP})` },
+ link_type: { type: 'string', description: 'Filter to one link type (per-edge filter, traversal only follows matching edges)' },
+ direction: { type: 'string', enum: ['in', 'out', 'both'], description: 'Traversal direction (default out)' },
+ },
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ const requestedDepth = (p.depth as number) || 5;
+ if (requestedDepth > TRAVERSE_DEPTH_CAP) {
+ ctx.logger.warn(`[gbrain] traverse_graph depth clamped from ${requestedDepth} to ${TRAVERSE_DEPTH_CAP}`);
+ }
+ const depth = Math.max(1, Math.min(requestedDepth, TRAVERSE_DEPTH_CAP));
+ const linkType = p.link_type as string | undefined;
+ const direction = p.direction as 'in' | 'out' | 'both' | undefined;
+ // v0.34.1 (#861 — P0 leak seal): thread caller's source scope so graph
+ // 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);
+ // Backward compat: when neither link_type nor direction is provided, return
+ // the legacy GraphNode[] shape. Once either is set, switch to GraphPath[].
+ if (linkType === undefined && direction === undefined) {
+ return ctx.engine.traverseGraph(slug, depth, scope);
+ }
+ return ctx.engine.traversePaths(slug, { depth, linkType, direction, ...scope });
+ },
+ scope: 'read',
+ cliHints: { name: 'graph', positional: ['slug'] },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const linksOperations: Operation[] = [
+ add_link, remove_link, get_links, get_backlinks, list_link_sources, traverse_graph,
+];
diff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.ts
new file mode 100644
index 0000000000..5cceb13afa
--- /dev/null
+++ b/src/core/ops/orphans.ts
@@ -0,0 +1,41 @@
+/**
+ * Orphans operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 2). Op consts stay module-private; `orphansOperations` below lists
+ * them in EXACTLY the order they appear in the canonical `operations` array
+ * in ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { sourceScopeOpts } from './context.ts';
+
+// --- Orphans ---
+
+const find_orphans: Operation = {
+ name: 'find_orphans',
+ description: 'Find pages with no inbound wikilinks. Essential for content enrichment cycles.',
+ params: {
+ include_pseudo: {
+ type: 'boolean',
+ description: 'Include auto-generated and pseudo pages (default: false)',
+ },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { findOrphans } = await import('../../commands/orphans.ts');
+ // v0.41.29.0 (Codex F8): scope by the caller's source (ctx.sourceId /
+ // ctx.auth.allowedSources) via the canonical sourceScopeOpts ladder.
+ // Pre-fix, find_orphans returned brain-wide orphans regardless of a
+ // 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).
+ return findOrphans(ctx.engine, {
+ includePseudo: (p.include_pseudo as boolean) || false,
+ ...sourceScopeOpts(ctx),
+ });
+ },
+ cliHints: { name: 'orphans', hidden: true },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const orphansOperations: Operation[] = [find_orphans];
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
new file mode 100644
index 0000000000..a3643307b5
--- /dev/null
+++ b/src/core/ops/pages.ts
@@ -0,0 +1,938 @@
+/**
+ * Page CRUD operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 1). Op consts stay module-private; `pagesOperations` below lists
+ * them in EXACTLY the order they appear in the canonical `operations` array
+ * in ../operations.ts (order is contractual — docs/TOOL_CATALOG.md is
+ * generated from that array). Never import from '../operations.ts' here
+ * (cycle); shared contract/context helpers come from the ops/ foundation.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { clampSearchLimit } from '../engine.ts';
+import type { PageType } from '../types.ts';
+import { importFromContent } from '../import-file.ts';
+import { writePageThrough, type WriteThroughResult } from '../write-through.ts';
+import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from '../link-extraction.ts';
+import { isFactsBackstopEligible } from '../facts/eligibility.ts';
+import { stripTakesFence } from '../takes-fence.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 { LIST_PAGES_DESCRIPTION } from '../operations-descriptions.ts';
+import { OperationError } from './contract.ts';
+import type { Operation } from './contract.ts';
+import {
+ enforceSubagentSlugFence,
+ slugOutsideCallerFence,
+ enforceClientSlugFence,
+ federatedSearchScope,
+} from './context.ts';
+
+// --- Page CRUD ---
+
+const get_page: Operation = {
+ name: 'get_page',
+ description: 'Read a page by slug (supports optional fuzzy matching). Soft-deleted pages are hidden by default; pass include_deleted: true to surface them with deleted_at populated (see v0.26.5 recovery window).',
+ params: {
+ slug: { type: 'string', required: true, description: 'Page slug' },
+ fuzzy: { type: 'boolean', description: 'Enable fuzzy slug resolution (default: false)' },
+ include_deleted: { type: 'boolean', description: 'v0.26.5: surface soft-deleted pages with deleted_at populated (default: false). Used by restore workflows.' },
+ },
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ const fuzzy = (p.fuzzy as boolean) || false;
+ const includeDeleted = (p.include_deleted as boolean) === true;
+ // #1393: route BOTH the exact-match read and the fuzzy resolveSlugs through
+ // the canonical precedence ladder (federated array > scalar > nothing). The
+ // exact path previously used scalar `ctx.sourceId` only, so a remote client
+ // with a federated `allowedSources` grant (and no single ctx.sourceId) got
+ // an UNSCOPED exact lookup — a cross-source read of any page by slug. getPage
+ // now honors sourceIds[] (both engines), so the same scope closes both paths.
+ // #3242: federatedSearchScope (not bare sourceScopeOpts) so an unqualified
+ // read sees pages in `federated: true` sources, matching search/query.
+ const sourceOpts = federatedSearchScope(ctx);
+ const fuzzyScope = sourceOpts;
+
+ let page = await ctx.engine.getPage(slug, { includeDeleted, ...sourceOpts });
+ let resolved_slug: string | undefined;
+
+ if (!page && fuzzy) {
+ const candidates = await ctx.engine.resolveSlugs(slug, fuzzyScope);
+ if (candidates.length === 1) {
+ page = await ctx.engine.getPage(candidates[0], { includeDeleted, ...sourceOpts });
+ resolved_slug = candidates[0];
+ } else if (candidates.length > 1) {
+ return { error: 'ambiguous_slug', candidates };
+ }
+ }
+
+ if (!page) {
+ throw new OperationError('page_not_found', `Page not found: ${slug}`, includeDeleted ? 'Check the slug or use fuzzy: true' : 'Page may be soft-deleted; pass include_deleted: true to verify');
+ }
+
+ // v0.37.0 (D11): op-layer write-back for the `last_retrieved_at` stale
+ // signal. Fire-and-forget — caller does NOT await. Internal callers
+ // (sync, migrations, dream cycle) bypass this op handler so the signal
+ // stays clean. Throttled to ~1 write / 5 min per page via the SQL clause
+ // inside bumpLastRetrievedAt (D2).
+ bumpLastRetrievedAt(ctx.engine, [page.id]);
+
+ // #2200: resolve tags against the concrete page's source. `sourceOpts` may
+ // be { sourceIds:[...] } (federated) with no scalar sourceId, which getTags
+ // would otherwise fall back to 'default' for — the wrong source for a
+ // 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;
+ const visibleBody = isUntrustedReader
+ ? {
+ ...page,
+ compiled_truth: stripFactsFence(
+ stripTakesFence(page.compiled_truth),
+ { keepVisibility: ['world'] },
+ ),
+ }
+ : page;
+ // v0.42 (#1699) agent-warning channel: surface the page's content_flag
+ // marker as a top-level field (parallel to SearchResult.content_flag) so
+ // an agent reading a page directly gets the same "this looks odd, examine
+ // it" signal it would get from search. The marker is also in frontmatter;
+ // this is the clean, documented accessor.
+ const content_flag = getContentFlag(page.frontmatter as Record<string, unknown> | null);
+ return {
+ ...visibleBody,
+ tags,
+ ...(resolved_slug ? { resolved_slug } : {}),
+ ...(content_flag ? { content_flag } : {}),
+ };
+ },
+ scope: 'read',
+ cliHints: { name: 'get', positional: ['slug'] },
+};
+
+const put_page: Operation = {
+ name: 'put_page',
+ description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',
+ params: {
+ slug: { type: 'string', required: true, description: 'Page slug' },
+ content: { type: 'string', required: true, description: 'Full markdown content with YAML frontmatter' },
+ allow_empty: { type: 'boolean', required: false, description: 'Allow overwriting an existing non-empty page with empty/whitespace-only content (default: false). Without it, put_page rejects the empty overwrite — the empty-stdin failure class.' },
+ // v0.39.3.0 provenance write-through (WARN-8 + A1 + CV6). Optional fields
+ // for trusted local callers (capture CLI, autopilot, dream cycle). Remote
+ // MCP callers (ctx.remote !== false) have their values OVERRIDDEN with
+ // server stamps below; the params are accepted on the wire only so the
+ // op schema stays uniform across transports. Audit-trail spoofing is
+ // closed structurally — clients cannot poison source_kind labels.
+ source_kind: { type: 'string', required: false, description: 'Ingestion channel taxonomy (capture-cli | put_page | webhook | …). Remote callers: SERVER-STAMPED, client value ignored.' },
+ source_uri: { type: 'string', required: false, description: 'Original URI/path/message-id the event carried. Remote callers: SERVER-STAMPED null.' },
+ ingested_via: { type: 'string', required: false, description: 'Richer label paired with source_kind. Remote callers: SERVER-STAMPED.' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+
+ // v0.39.3.0 CV6 trust gate for provenance write-through (WARN-8).
+ // Only trusted LOCAL callers (ctx.remote === false — capture CLI,
+ // autopilot, dream cycle, file watcher) may populate source_kind /
+ // source_uri / ingested_via from their own state. Anything else
+ // (HTTP MCP, stdio MCP, subagent) gets the server-stamped
+ // `mcp:put_page` regardless of what was passed.
+ //
+ // Closes the spoofing surface CV6 identified: pre-fix a write-scope
+ // OAuth token could send `source_kind: 'capture-cli'` to poison the
+ // audit trail. Fail-closed: `ctx.remote === false` is the ONLY truthy
+ // condition that admits client-supplied provenance.
+ let provenanceKind: string | null;
+ let provenanceUri: string | null;
+ let provenanceVia: string | null;
+ if (ctx.remote === false) {
+ // Trusted local caller: honor the client params (may be null/undefined
+ // for legacy local callers that don't set them).
+ provenanceKind = (p.source_kind as string | undefined) ?? null;
+ provenanceUri = (p.source_uri as string | undefined) ?? null;
+ provenanceVia = (p.ingested_via as string | undefined) ?? null;
+ } else {
+ // Remote caller or unset trust: server stamps. Mirrors the existing
+ // write-through stamping at the file-side (~:637).
+ provenanceKind = 'mcp:put_page';
+ provenanceUri = null;
+ provenanceVia = 'mcp:put_page';
+ }
+
+ // Subagent namespace enforcement (v0.15+). Runs BEFORE the dry-run
+ // short-circuit so preview calls surface the same rejection. See
+ // enforceSubagentSlugFence for the fail-closed policy.
+ enforceSubagentSlugFence(ctx, slug, 'put_page');
+ enforceClientSlugFence(ctx, slug, 'put_page');
+
+ if (ctx.dryRun) return { dry_run: true, action: 'put_page', slug: p.slug };
+
+ // Empty-overwrite guard: empty/whitespace-only content over an existing
+ // non-empty page is almost always an input-plumbing failure (e.g. a
+ // caller that meant file input — put has no --file flag — so the missing
+ // --content fell back to reading an empty non-interactive stdin), not an
+ // intentional write. Refuse loudly unless the caller opts in with
+ // allow_empty. The read is scoped to the exact (source_id, slug) row the
+ // write below targets (engine.putPage defaults to 'default' when
+ // sourceId is unset). New-slug creates and soft-deleted-page overwrites
+ // stay allowed — nothing recoverable is lost there.
+ if ((p.content as string).trim() === '' && p.allow_empty !== true) {
+ const existing = await ctx.engine.getPage(slug, { sourceId: ctx.sourceId ?? 'default' });
+ const existingBody = existing
+ ? `${existing.compiled_truth ?? ''}\n${existing.timeline ?? ''}`.trim()
+ : '';
+ if (existingBody !== '') {
+ throw new OperationError(
+ 'invalid_params',
+ `Refusing to overwrite existing non-empty page '${slug}' with empty content.`,
+ 'For file input use `gbrain capture --file PATH --slug SLUG` (put has no --file flag). To intentionally blank the page, pass allow_empty: true (CLI: --allow-empty).',
+ );
+ }
+ }
+
+ // Skip embedding when the AI gateway has no embedding provider configured.
+ // Checks all auth env vars for the resolved provider, not just OPENAI_API_KEY,
+ // so Gemini / Ollama / Voyage brains don't silently drop embeddings (Codex C2).
+ const { isAvailable } = await import('../ai/gateway.ts');
+ const noEmbed = !isAvailable('embedding');
+ // v0.31.8 (D7 / codex OV-1): thread ctx.sourceId so put_page on a
+ // multi-source brain lands in the intended source instead of the
+ // default-source clobber path. importFromContent already accepts
+ // opts.sourceId (PR #707/#757 engine work); previously the op handler
+ // just didn't pass it.
+ // v0.39 T1.5: load active pack ONCE per put_page invocation; thread to
+ // parseMarkdown via importFromContent so type inference honors user-defined
+ // page_types. Best-effort: pack load failure falls back to legacy inferType
+ // (parity gate preserved). Federated-read closure correction is T19's scope.
+ let activePack: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string> }> } | undefined;
+ try {
+ const { loadActivePack } = await import('../schema-pack/load-active.ts');
+ const { loadConfig } = await import('../config.ts');
+ const resolved = await loadActivePack({
+ cfg: loadConfig(),
+ remote: ctx.remote === false ? false : true,
+ sourceId: ctx.sourceId,
+ });
+ activePack = { page_types: resolved.manifest.page_types };
+ } catch {
+ // Pack load failed; fall through to legacy inferType behavior.
+ activePack = undefined;
+ }
+ const result = await importFromContent(ctx.engine, slug, p.content as string, {
+ noEmbed,
+ // v0.42 (#1699): untrusted callers can't smuggle gate-owned frontmatter
+ // markers (quarantine/content_flag/embed_skip). Fail-closed — anything
+ // not strictly local is remote (matches CV6 / v0.26.9 F7b posture).
+ remote: ctx.remote !== false,
+ ...(ctx.sourceId ? { sourceId: ctx.sourceId } : {}),
+ // v0.39.0.0 T1.5: pack-aware type inference (loaded above; legacy
+ // inferType behavior when undefined).
+ ...(activePack ? { activePack } : {}),
+ // v0.39.3.0 provenance write-through (WARN-8). Trust-filtered values
+ // computed above; ingested_at is server-stamped at the engine layer.
+ // Null-valued fields signal "no provenance write this call" and the
+ // engine's COALESCE-preserve UPDATE keeps the prior first-write
+ // record intact (CV12 audit-trail survival).
+ source_kind: provenanceKind,
+ source_uri: provenanceUri,
+ ingested_via: provenanceVia,
+ });
+
+ // The dedup pre-check in importFromContent can resolve the write to a
+ // DIFFERENT page than the one requested (same content_hash, or the same
+ // `frontmatter.id`), and the disk write-through below runs against that
+ // RESOLVED slug. Fence it too: a bound client can read a victim page's
+ // frontmatter id over its federated grant, echo it back in an in-prefix
+ // put_page, and otherwise have write-through rewrite the victim's file
+ // with falsified provenance. Dedup returns status 'skipped' without
+ // touching the DB, so throwing here leaves nothing to roll back.
+ if (result.slug && result.slug !== slug) {
+ // Deliberately does NOT name the resolved slug: it belongs to a page
+ // outside the fence, and echoing it would turn frontmatter-id guessing
+ // into a slug-enumeration oracle.
+ if (slugOutsideCallerFence(ctx, result.slug)) {
+ ctx.logger.warn(`[put_page] dedup resolved '${slug}' to an out-of-fence page; refusing (client ${ctx.auth?.clientId ?? 'unknown'}, subagent ${ctx.subagentId ?? 'none'})`);
+ throw new OperationError(
+ 'permission_denied',
+ `put_page: this content already exists on a page outside your write scope, so the write would have modified that page instead.`,
+ 'Remove the `id:` frontmatter field (or change the content) to write a new page under your own prefix.',
+ );
+ }
+ }
+
+ // v0.39 T13 — auto-prompt on first unknown-type write.
+ //
+ // Contract (codex finding #8 honored — 7 cases covered):
+ // - TTY callers: stderr prompt fires once per unique unknown type;
+ // subsequent writes with the same type silently append to
+ // candidate audit.
+ // - Non-TTY callers: ALWAYS succeed; silently append to candidate
+ // audit. NEVER block. Critical regression test:
+ // test/put-page-unknown-type-prompt.test.ts pins this.
+ // - Subagent / MCP / claw-test / autopilot all go through here;
+ // non-TTY contract preserves their semantics.
+ // - Pack-load failures (activePack undefined) skip the gate entirely
+ // since "unknown" has no meaning without a pack reference.
+ if (activePack && result.status === 'imported') {
+ try {
+ const pageType = (result as { page?: { type?: string } }).page?.type ?? null;
+ const knownTypes = new Set(activePack.page_types.map((t) => t.name));
+ if (pageType && !knownTypes.has(pageType)) {
+ const { logSchemaEvent } = await import('../schema-events.ts');
+ logSchemaEvent({
+ verb: 'put_page:unknown_type',
+ outcome: 'success',
+ flags: [`type=${pageType.slice(0, 32)}`, `slug=${slug.slice(0, 64)}`],
+ });
+ if (process.stderr.isTTY && ctx.remote === false) {
+ console.error(
+ `[schema] put_page wrote type=\`${pageType}\` which isn't in active pack \`${activePack.page_types.length ? '<configured>' : 'gbrain-base'}\`. ` +
+ `Run \`gbrain schema review-candidates\` to promote or ignore.`,
+ );
+ }
+ }
+ } catch {
+ // best-effort; never block put_page
+ }
+ }
+
+ // v0.38 put_page write-through (ingestion cathedral):
+ // After importFromContent succeeds, if `sync.repo_path` resolves to a
+ // real directory, persist the markdown file to disk alongside the DB
+ // row. Failures non-fatal — DB write is durable; subsequent sync
+ // reconciles drift.
+ //
+ // Trust gating:
+ // - Subagent sandbox (viaSubagent without allowedSlugPrefixes) → DB-only.
+ // - All other writes → write-through.
+ // put_page's own trust-gating produces two skip reasons ('subagent_sandbox',
+ // 'dry_run') that never come out of writePageThrough itself — widen the
+ // field rather than losing the commit/pushed/lastPushStatus typing.
+ let writeThrough: (Omit<WriteThroughResult, 'skipped'> & { skipped?: WriteThroughResult['skipped'] | 'subagent_sandbox' | 'dry_run' }) | undefined;
+ const isSandboxSubagent = ctx.viaSubagent === true
+ && !(Array.isArray(ctx.allowedSlugPrefixes) && ctx.allowedSlugPrefixes.length > 0);
+ if (!ctx.dryRun && result.status !== 'error' && !isSandboxSubagent) {
+ const sourceId = ctx.sourceId ?? 'default';
+ const provenanceVia = ctx.remote === false ? 'put_page' : 'mcp:put_page';
+ // Shared canonical write-through (also used by `gbrain brainstorm/lsd
+ // --save`). Renders the file from the saved DB row and writes it
+ // atomically; never throws (failures land in skipped/error).
+ writeThrough = await writePageThrough(ctx.engine, result.slug, {
+ sourceId,
+ frontmatterOverrides: {
+ ingested_via: provenanceVia,
+ ingested_at: new Date().toISOString(),
+ source_kind: provenanceVia,
+ },
+ logger: ctx.logger,
+ });
+ } else if (isSandboxSubagent) {
+ writeThrough = { written: false, skipped: 'subagent_sandbox' };
+ } else if (ctx.dryRun) {
+ writeThrough = { written: false, skipped: 'dry_run' };
+ }
+
+ // Auto-link post-hook: runs AFTER importFromContent (which is its own
+ // transaction). Runs even on status='skipped' so reconciliation catches drift
+ // between the page text and the links table. Failures are non-blocking.
+ //
+ // SECURITY: skipped for remote (MCP) callers. Auto-link's bare-slug regex
+ // matches `people/X` etc. anywhere in page text, including code fences,
+ // quoted strings, and prompt-injected content. An untrusted page can plant
+ // arbitrary outbound links by including `see meetings/board-q1` in its body.
+ // Combined with the backlink boost in hybridSearch, attacker-placed targets
+ // would surface higher in search. Local CLI users (ctx.remote=false) opt
+ // into this behavior; MCP/remote writes do not.
+ let autoLinks:
+ | { created: number; removed: number; errors: number; unresolved: UnresolvedFrontmatterRef[] }
+ | { error: string }
+ | { skipped: 'remote' }
+ | undefined;
+ let autoTimeline: { created: number } | { error: string } | { skipped: 'remote' } | undefined;
+ // Trusted-workspace path (v0.23 dream cycle) re-enables auto-link/timeline
+ // even though ctx.remote=true, because the allow-list bounds the slug and
+ // the synthesis prompt is itself the trusted dispatcher. Without this,
+ // the cycle's `extract` phase would have to recompute every edge, and
+ // patterns (which runs after extract) would still see the right graph
+ // but auto_timeline would never fire on synth output.
+ const trustedWorkspace = ctx.viaSubagent === true
+ && Array.isArray(ctx.allowedSlugPrefixes)
+ && ctx.allowedSlugPrefixes.length > 0;
+ if (ctx.remote !== false && !trustedWorkspace) {
+ autoLinks = { skipped: 'remote' };
+ autoTimeline = { skipped: 'remote' };
+ } else if (result.parsedPage) {
+ try {
+ const enabled = await isAutoLinkEnabled(ctx.engine);
+ if (enabled) {
+ autoLinks = await runAutoLink(ctx.engine, slug, result.parsedPage, ctx.sourceId ? { sourceId: ctx.sourceId } : undefined);
+ }
+ } catch (e) {
+ autoLinks = { error: e instanceof Error ? e.message : String(e) };
+ }
+ // Timeline extraction mirrors auto-link: runs post-write, best-effort,
+ // never blocks the write. ON CONFLICT DO NOTHING in
+ // addTimelineEntriesBatch keeps it idempotent across re-writes, so a
+ // page that's edited and re-written won't duplicate its own timeline.
+ try {
+ const enabled = await isAutoTimelineEnabled(ctx.engine);
+ if (enabled) {
+ const fullContent = result.parsedPage.compiled_truth + '\n' + result.parsedPage.timeline;
+ const entries = parseTimelineEntries(fullContent);
+ if (entries.length > 0) {
+ const batch = entries.map(e => ({
+ slug,
+ date: e.date,
+ summary: e.summary,
+ detail: e.detail || '',
+ }));
+ // v0.41.18.0: engine self-retries on Supavisor circuit-breaker
+ // recovery. auditSite label routes the audit JSONL emission so
+ // operators can attribute losses to the agent-write path.
+ const created = await ctx.engine.addTimelineEntriesBatch(batch, { auditSite: 'mcp.put_page.autolink' });
+ autoTimeline = { created };
+ } else {
+ autoTimeline = { created: 0 };
+ }
+ }
+ } catch (e) {
+ autoTimeline = { error: e instanceof Error ? e.message : String(e) };
+ }
+ }
+
+ // v0.31 (D23): facts compliance backstop. When an agent writes a page
+ // on a conversation-shape slug AND the body has substantive prose, fire
+ // a fact-extraction job into the bounded queue. Skipped on dry-run,
+ // dream-generated content (anti-loop), and non-eligible kinds (sync,
+ // ingest, file uploads, code pages). Never blocks the put_page response.
+ // v0.31.2: routed through runFactsBackstop (PR1 commit 6) so put_page
+ // and sync share the same eligibility/extract/dedup/insert pipeline.
+ // Queue mode preserves the prior fire-and-forget shape (caller's
+ // put_page response stays fast). Default 'all' notability filter
+ // (MEDIUM facts wait for the dream cycle but DO land via put_page,
+ // matching the pre-fix behavior on this surface).
+ let factsQueued: { queued: boolean } | { skipped: string } | undefined;
+ // Slug-bound clients do not get the facts backstop. It extracts entities
+ // from the (attacker-controllable) page body and writes fact rows — and,
+ // on a source with a local_path, a `## Facts` fence in the entity's own
+ // .md — keyed to `people/…` / `companies/…` slugs the caller never named.
+ // That is exactly the capability `extract_facts` is denied at dispatch
+ // for, reachable indirectly through a perfectly in-prefix put_page. The
+ // sibling post-hooks above already skip for untrusted callers (auto-link
+ // at `remote !== false && !trustedWorkspace`, chronicle at
+ // `remote !== false`); this one had no gate at all.
+ // Keyed on "the caller is slug-confined at all", not on ctx.auth alone:
+ // the delegated (submit_agent → subagent) context carries
+ // `allowedSlugPrefixes` but NOT `auth`, so an auth-only test would let a
+ // bound client re-open this path simply by delegating the write.
+ if (ctx.auth?.boundSlugPrefixes || ctx.viaSubagent === true) {
+ factsQueued = { skipped: 'slug_bound_client' };
+ } else {
+ try {
+ const { runFactsBackstop } = await import('../facts/backstop.ts');
+ const r = await runFactsBackstop(
+ {
+ slug,
+ type: result.parsedPage!.type,
+ compiled_truth: result.parsedPage!.compiled_truth,
+ frontmatter: result.parsedPage!.frontmatter,
+ },
+ {
+ engine: ctx.engine,
+ sourceId: ctx.sourceId ?? 'default',
+ sessionId: (ctx as { source_session?: string }).source_session ?? null,
+ source: 'mcp:put_page',
+ mode: 'queue',
+ },
+ );
+ if (r.mode === 'queue' && r.enqueued) {
+ factsQueued = { queued: true };
+ } else if (r.mode === 'queue' && r.skipped) {
+ // Preserve the pre-v0.31.2 response shape for MCP clients:
+ // 'kind:guide' / 'too_short' / 'subagent_namespace' / 'dream_generated'
+ // (bare reasons), not the helper's namespaced 'eligibility_failed:...'
+ // discriminator. Map back here.
+ const bare = r.skipped.startsWith('eligibility_failed:')
+ ? r.skipped.slice('eligibility_failed:'.length)
+ : r.skipped;
+ factsQueued = { skipped: bare };
+ }
+ } catch {
+ factsQueued = { skipped: 'backstop_error' };
+ }
+ }
+
+ // v0.42.x (#2390): Life Chronicle backstop. ONLY on a real import
+ // (status==='imported' — a skipped/unchanged rewrite still carries
+ // parsedPage, so gating on parsedPage alone would re-enqueue forever),
+ // behind the SAME trust gate as auto-link/timeline + the auto_chronicle
+ // flag. Enqueues a chronicle_extract job; never blocks the write.
+ let chronicleQueued: { queued: boolean } | { skipped: string } | undefined;
+ if (result.status !== 'imported') {
+ chronicleQueued = { skipped: 'not_imported' };
+ } else if (ctx.remote !== false && !trustedWorkspace) {
+ chronicleQueued = { skipped: 'remote' };
+ } else if (result.parsedPage) {
+ try {
+ const { runChronicleBackstop } = await import('../chronicle/backstop.ts');
+ const r = await runChronicleBackstop(
+ {
+ slug,
+ type: result.parsedPage.type,
+ compiled_truth: result.parsedPage.compiled_truth,
+ frontmatter: result.parsedPage.frontmatter,
+ },
+ { engine: ctx.engine, sourceId: ctx.sourceId ?? 'default' },
+ );
+ chronicleQueued = r.enqueued ? { queued: true } : { skipped: r.skipped ?? 'skipped' };
+ } catch {
+ chronicleQueued = { skipped: 'backstop_error' };
+ }
+ }
+
+ // Post-write validator lint (PR 2.5): feature-flag-gated, non-blocking.
+ // When `writer.lint_on_put_page` is enabled, runs the BrainWriter's
+ // validators on the freshly-written page and logs findings to
+ // ingest_log + ~/.gbrain/validator-lint.jsonl. Does NOT reject the
+ // write — that's the deferred strict-mode flip after the 7-day soak.
+ // Response contract (T11): lint ran → full summary (counts, errors-first
+ // top_findings with hints, by_validator histogram) even at zero findings;
+ // lint crashed → {status: 'lint_error'}; lint off (flag / validate:false)
+ // → key absent.
+ let writerLint: WriterLintPayload | undefined;
+ try {
+ const { writerLintForPutPage } = await import('../output/post-write.ts');
+ writerLint = await writerLintForPutPage(ctx.engine, result.slug, {
+ sourceId: ctx.sourceId ?? 'default',
+ });
+ } catch {
+ // Module-load failure gets the same crash marker; never blocks put_page.
+ writerLint = { status: 'lint_error' };
+ }
+
+ return {
+ slug: result.slug,
+ status: result.status === 'imported' ? 'created_or_updated' : result.status,
+ chunks: result.chunks,
+ ...(autoLinks ? { auto_links: autoLinks } : {}),
+ ...(autoTimeline ? { auto_timeline: autoTimeline } : {}),
+ ...(writerLint ? { writer_lint: writerLint } : {}),
+ ...(factsQueued ? { facts_backstop: factsQueued } : {}),
+ ...(chronicleQueued ? { chronicle_backstop: chronicleQueued } : {}),
+ ...(writeThrough ? { write_through: writeThrough } : {}),
+ };
+ },
+ cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
+};
+
+// v0.31.2: isFactsBackstopEligible moved to src/core/facts/eligibility.ts
+// so sync.ts, file_upload, code_import, and runFactsBackstop all share one
+// predicate. Imported above.
+
+/**
+ * Extract entity refs from a freshly-written page, sync the links table to match.
+ * Creates new links via addLink, removes stale ones (links present in DB but no
+ * longer referenced in content) via removeLink. Returns counts.
+ *
+ * Runs OUTSIDE importFromContent's transaction so it doesn't block the page write
+ * or get rolled back if a single link operation fails. Per-link failures are
+ * counted; the overall function never throws (catch in put_page handler covers
+ * extraction errors).
+ */
+async function runAutoLink(
+ engine: BrainEngine,
+ slug: string,
+ parsed: { type: PageType; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> },
+ opts?: { sourceId?: string },
+): Promise<{ created: number; removed: number; errors: number; unresolved: UnresolvedFrontmatterRef[] }> {
+ const fullContent = parsed.compiled_truth + '\n' + parsed.timeline;
+ // v0.31.8 (codex OV-2): thread sourceId through every read + write inside
+ // reconcileLinks. Without this the FS walker reads cross-source links/slugs
+ // but writes scoped to one source — phantom stale-deletions and duplicate
+ // inserts. opts.sourceId is set when caller knows the source (put_page from
+ // a multi-source-aware handler); when omitted, every read returns the
+ // pre-v0.31.8 cross-source view (back-compat for any existing caller).
+ const sourceOpts = opts?.sourceId ? { sourceId: opts.sourceId } : {};
+ const linkSourceOpts = opts?.sourceId
+ ? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId, originSourceId: opts.sourceId }
+ : {};
+ const removeSourceOpts = opts?.sourceId
+ ? { fromSourceId: opts.sourceId, toSourceId: opts.sourceId }
+ : {};
+
+ // Live-mode resolver: per-put throwaway cache, pg_trgm + optional search.
+ // Issue #972 (codex [P1]): pass sourceId so basename resolution stays
+ // within this page's source — no cross-source basename edges. Also scopes
+ // the fuzzy fallback (findByTitleFuzzy) to the same source the put_page is
+ // targeting — without it, cross-source slug suggestions get silently dropped
+ // at the FK filter and the link looks like it failed to resolve. Twin of
+ // #1436's `tryFuzzyMatch` fix.
+ const resolver = makeResolver(engine, { mode: 'live', sourceId: opts?.sourceId });
+ // Issue #972: opt-in bare-wikilink basename resolution. Off by default.
+ const globalBasename = await isGlobalBasenameEnabled(engine);
+ const { candidates, unresolved } = await extractPageLinks(
+ slug, fullContent, parsed.frontmatter, parsed.type, resolver,
+ { globalBasename },
+ );
+
+ // Resolve which targets exist (skip refs to non-existent pages to avoid FK
+ // violation churn in addLink). One getAllSlugs call upfront, O(1) lookup.
+ // v0.31.8 (D12): scoped to the source when opts.sourceId is set so wikilink
+ // resolution doesn't span unrelated sources.
+ const allSlugs = await engine.getAllSlugs(sourceOpts);
+ const valid = candidates.filter(c =>
+ allSlugs.has(c.targetSlug) && (!c.fromSlug || allSlugs.has(c.fromSlug))
+ );
+
+ // Split candidates by direction. Outgoing (fromSlug === slug or unset) are
+ // this page's own edges, reconciled against getLinks(slug). Incoming
+ // (fromSlug !== slug — frontmatter with `direction: incoming`) are edges
+ // where this page is the TO side; reconciled against getBacklinks(slug)
+ // but SCOPED to the frontmatter edges this page authored via
+ // (link_source='frontmatter' AND origin_slug = slug). We never touch
+ // frontmatter edges authored by OTHER pages.
+ const out = valid.filter(c => !c.fromSlug || c.fromSlug === slug);
+ const inc = valid.filter(c => c.fromSlug && c.fromSlug !== slug);
+
+ // Run getLinks + addLink/removeLink loops inside a single transaction so that
+ // concurrent put_page calls on the same slug can't race the reconciliation:
+ // without this, two simultaneous writes both read stale `existingKeys` and
+ // re-create links the other side just removed (lost-update).
+ //
+ // Row-level locks alone aren't enough: both writers can read the same
+ // `existingKeys` set BEFORE either mutates a row, so the union-of-writes
+ // race survives. A transaction-scoped advisory lock keyed on the slug
+ // hash serializes the entire reconciliation across processes. Falls
+ // through on engines that don't support pg_advisory_xact_lock (PGLite is
+ // single-process so there's no cross-process concern there anyway).
+ const result = await engine.transaction(async (tx) => {
+ try {
+ await tx.executeRaw(`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, [`auto_link:${slug}`]);
+ } catch {
+ // engine doesn't support advisory locks — fall through
+ }
+ const existingOut = await tx.getLinks(slug, sourceOpts);
+ // Incoming: we only look at frontmatter edges WE authored (origin_slug=slug).
+ // Non-frontmatter and other-page frontmatter edges survive untouched.
+ const existingInRaw = await tx.getBacklinks(slug, sourceOpts);
+ const existingIn = existingInRaw.filter(
+ l => l.link_source === 'frontmatter' && l.origin_slug === slug,
+ );
+
+ // Reconcilable outgoing edges: markdown + our own frontmatter edges +
+ // basename-resolved wikilinks (issue #972). Manual edges
+ // (link_source='manual') are NEVER touched by reconciliation.
+ // 'wikilink-resolved' MUST be reconcilable (codex outside-voice [P1]):
+ // auto-link writes these; if it weren't here, a basename edge would
+ // survive after the wikilink is deleted from the page OR the
+ // link_resolution.global_basename flag is turned off (out no longer
+ // includes it, so the stale-removal loop below must be allowed to drop it).
+ const reconcilableOut = existingOut.filter(
+ l => l.link_source === 'markdown' || l.link_source == null ||
+ l.link_source === 'wikilink-resolved' ||
+ (l.link_source === 'frontmatter' && l.origin_slug === slug),
+ );
+
+ const outKeys = new Set(out.map(c =>
+ `${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? 'markdown'}`
+ ));
+ const incKeys = new Set(inc.map(c =>
+ `${c.fromSlug}\u0000${c.linkType}`
+ ));
+
+ let created = 0, removed = 0, errors = 0;
+
+ // Add outgoing edges.
+ for (const c of out) {
+ try {
+ await tx.addLink(
+ slug, c.targetSlug, c.context, c.linkType,
+ c.linkSource, c.originSlug, c.originField,
+ linkSourceOpts,
+ );
+ const existKey = `${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? 'markdown'}`;
+ const exists = reconcilableOut.some(l =>
+ `${l.to_slug}\u0000${l.link_type}\u0000${l.link_source ?? 'markdown'}` === existKey
+ );
+ if (!exists) created++;
+ } catch {
+ errors++;
+ }
+ }
+
+ // Add incoming edges (other page → slug).
+ for (const c of inc) {
+ try {
+ await tx.addLink(
+ c.fromSlug!, c.targetSlug, c.context, c.linkType,
+ 'frontmatter', c.originSlug, c.originField,
+ linkSourceOpts,
+ );
+ const existKey = `${c.fromSlug}\u0000${c.linkType}`;
+ const exists = existingIn.some(l =>
+ `${l.from_slug}\u0000${l.link_type}` === existKey
+ );
+ if (!exists) created++;
+ } catch {
+ errors++;
+ }
+ }
+
+ // Remove stale outgoing (markdown or our-frontmatter, not in desired set).
+ for (const l of reconcilableOut) {
+ const key = `${l.to_slug}\u0000${l.link_type}\u0000${l.link_source ?? 'markdown'}`;
+ if (!outKeys.has(key)) {
+ try {
+ await tx.removeLink(slug, l.to_slug, l.link_type, l.link_source ?? undefined, removeSourceOpts);
+ removed++;
+ } catch {
+ errors++;
+ }
+ }
+ }
+
+ // Remove stale incoming (our frontmatter → slug, not in desired set).
+ for (const l of existingIn) {
+ const key = `${l.from_slug}\u0000${l.link_type}`;
+ if (!incKeys.has(key)) {
+ try {
+ await tx.removeLink(l.from_slug, slug, l.link_type, 'frontmatter', removeSourceOpts);
+ removed++;
+ } catch {
+ errors++;
+ }
+ }
+ }
+
+ return { created, removed, errors };
+ });
+
+ return { ...result, unresolved };
+}
+
+const delete_page: Operation = {
+ name: 'delete_page',
+ description: 'Soft-delete a page. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed.',
+ params: {
+ slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ enforceClientSlugFence(ctx, slug, 'delete_page');
+ if (ctx.dryRun) return { dry_run: true, action: 'soft_delete_page', slug };
+ // v0.31.8 (D7): thread ctx.sourceId so multi-source brains soft-delete the
+ // intended row instead of always targeting (default, slug).
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ // v0.26.5: rewired from hard-delete to soft-delete. The hard-delete primitive
+ // (engine.deletePage) is now reserved for purgeDeletedPages and explicit
+ // tests. softDeletePage returns null when the slug is unknown OR already
+ // soft-deleted (idempotent-as-null) — preserve that as a clean no-op shape.
+ const result = await ctx.engine.softDeletePage(slug, sourceOpts);
+ if (result === null) {
+ // Distinguish "not found" from "already soft-deleted" so the agent gets a
+ // clear signal. Probe once with include_deleted to disambiguate.
+ const existing = await ctx.engine.getPage(slug, { includeDeleted: true, ...sourceOpts });
+ if (!existing) {
+ throw new OperationError('page_not_found', `Page not found: ${slug}`, 'Check the slug.');
+ }
+ return { status: 'already_soft_deleted', slug, deleted_at: existing.deleted_at };
+ }
+ return { status: 'soft_deleted', slug, recoverable_until: 'now + 72h via restore_page' };
+ },
+ cliHints: { name: 'delete', positional: ['slug'] },
+};
+
+const restore_page: Operation = {
+ name: 'restore_page',
+ description: 'v0.26.5 — restore a soft-deleted page (clear deleted_at). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.',
+ params: {
+ slug: { type: 'string', required: true, description: "Slug of the soft-deleted page to restore, e.g. 'people/alice-example'." },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ const slug = p.slug as string;
+ enforceClientSlugFence(ctx, slug, 'restore_page');
+ if (ctx.dryRun) return { dry_run: true, action: 'restore_page', slug };
+ // v0.31.8 (D7): thread ctx.sourceId.
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ const ok = await ctx.engine.restorePage(slug, sourceOpts);
+ if (!ok) {
+ // Distinguish "not found" from "already active" (idempotent-as-false).
+ const existing = await ctx.engine.getPage(slug, { includeDeleted: true, ...sourceOpts });
+ if (!existing) {
+ throw new OperationError('page_not_found', `Page not found: ${slug}`, 'Check the slug.');
+ }
+ return { status: 'already_active', slug };
+ }
+ return { status: 'restored', slug };
+ },
+ cliHints: { name: 'restore', positional: ['slug'] },
+};
+
+const purge_deleted_pages: Operation = {
+ name: 'purge_deleted_pages',
+ description: 'v0.26.5 — admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72). Cascades through content_chunks, page_links, chunk_relations. Local CLI only (not exposed over HTTP MCP). Manual escape hatch alongside the autopilot purge phase.',
+ params: {
+ older_than_hours: { type: 'number', description: 'Age cutoff in hours. Default 72.' },
+ },
+ mutating: true,
+ scope: 'admin',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ const olderThanHours = (p.older_than_hours as number | undefined) ?? 72;
+ if (ctx.dryRun) return { dry_run: true, action: 'purge_deleted_pages', older_than_hours: olderThanHours };
+ const result = await ctx.engine.purgeDeletedPages(olderThanHours);
+ return { status: 'purged', count: result.count, slugs: result.slugs };
+ },
+ cliHints: { name: 'purge-deleted' },
+};
+
+const LIST_PAGES_SORT_VALUES = ['updated_desc', 'updated_asc', 'created_desc', 'slug'] as const;
+type ListPagesSort = typeof LIST_PAGES_SORT_VALUES[number];
+
+const list_pages: Operation = {
+ name: 'list_pages',
+ description: LIST_PAGES_DESCRIPTION,
+ params: {
+ type: { type: 'string', description: 'Filter by page type' },
+ tag: { type: 'string', description: 'Filter by tag' },
+ limit: { type: 'number', description: 'Max results (default 50; remote callers are capped at 100)' },
+ offset: {
+ type: 'number',
+ description: 'Skip first N rows (pagination). Engine-supported since PageFilters gained offset; previously accepted at the CLI and silently dropped.',
+ },
+ // v0.29 — surface filter that already exists on PageFilters.
+ updated_after: {
+ type: 'string',
+ description: 'ISO date (YYYY-MM-DD) or full timestamp. Returns pages with updated_at > value.',
+ },
+ sort: {
+ type: 'string',
+ enum: [...LIST_PAGES_SORT_VALUES],
+ description: 'Sort order. Default updated_desc (matches pre-v0.29). Options: updated_desc, updated_asc, created_desc, slug.',
+ },
+ include_deleted: { type: 'boolean', description: 'v0.26.5: include soft-deleted pages (default: false). Used by restore workflows and operator diagnostics.' },
+ },
+ handler: async (ctx, p) => {
+ // Whitelist the sort enum at the handler before passing to the engine.
+ // Engines also whitelist via PAGE_SORT_SQL but defending here keeps
+ // unsupported strings from reaching the SQL layer.
+ const rawSort = p.sort as string | undefined;
+ const sort = rawSort && (LIST_PAGES_SORT_VALUES as readonly string[]).includes(rawSort)
+ ? (rawSort as ListPagesSort)
+ : undefined;
+ // v0.34.1 (#861 — P0 leak seal): thread the auth'd client's source scope
+ // into the listPages filter so an OAuth client scoped to src-A cannot
+ // enumerate src-B pages. Pre-fix, ctx.sourceId / ctx.auth?.allowedSources
+ // were ignored at this op handler and the engine returned every source's
+ // pages indiscriminately.
+ // #3242: federatedSearchScope so unqualified listing spans federated
+ // sources (same visibility set as search / get_page). Grants still win.
+ const scope = federatedSearchScope(ctx);
+ // The 100-row cap exists to protect remote MCP/OAuth transports from
+ // unbounded result dumps. Local CLI callers (ctx.remote === false — the
+ // same trust boundary that already bypasses scope enforcement, see the
+ // Operation.scope doc above) own the machine, and a full enumeration is a
+ // legitimate local operation, so an explicit limit above 100 is honored.
+ // Anything that is not strictly `false` stays remote/untrusted (defense
+ // in depth, matching the ctx.remote contract).
+ const requestedLimit = p.limit as number | undefined;
+ const isLocal = ctx.remote === false;
+ const limit = isLocal
+ ? clampSearchLimit(requestedLimit, 50, Number.MAX_SAFE_INTEGER)
+ : clampSearchLimit(requestedLimit, 50, 100);
+ if (!isLocal && requestedLimit !== undefined && Number.isFinite(requestedLimit) && requestedLimit > limit) {
+ // Loud clamp, parity with the three search paths ("search limit clamped
+ // from N to 100"). logger.warn goes to stderr — `list` stdout is
+ // tab-separated and consumed by scripts, so it must stay clean.
+ ctx.logger.warn(`[gbrain] Warning: list limit clamped from ${requestedLimit} to ${limit}; use offset to paginate`);
+ }
+ // Thread offset through — PageFilters has supported it all along; the op
+ // layer just never passed it, so `--offset` was accepted and ignored.
+ const requestedOffset = p.offset as number | undefined;
+ const offset =
+ requestedOffset !== undefined && Number.isFinite(requestedOffset) && requestedOffset > 0
+ ? Math.floor(requestedOffset)
+ : undefined;
+ // Probe one row past the effective limit so truncation is detectable
+ // without a COUNT query. The bug class sealed here is SILENT truncation
+ // — an exhaustive consumer (audit, scan, backfill) gets a full-looking
+ // list and never learns rows were dropped, and with the default
+ // updated_desc sort the dropped rows are always the OLDEST, i.e. exactly
+ // the pages such consumers exist to find.
+ const rows = await ctx.engine.listPages({
+ type: p.type as any,
+ tag: p.tag as string,
+ limit: limit + 1,
+ offset,
+ includeDeleted: (p.include_deleted as boolean) === true,
+ updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,
+ sort,
+ ...scope,
+ });
+ const truncated = rows.length > limit;
+ const pages = truncated ? rows.slice(0, limit) : rows;
+ // Warn only when the caller's limit was NOT honored (unset → default 50):
+ // an explicit honored limit that happens to land on more rows is ordinary
+ // pagination, not a trap. Local (CLI) only — same operator-facing stderr
+ // channel as the put_page unknown-type hint above — but with no isTTY
+ // gate: scripted callers are precisely the consumers that cannot detect
+ // truncation any other way, and stderr keeps stdout parseable for them.
+ // (Local explicit limits are honored unbounded since #3322, so the
+ // requestedLimit > limit arm is defense in depth only.)
+ if (truncated && isLocal && (requestedLimit === undefined || requestedLimit > limit)) {
+ console.error(
+ `[list_pages] output truncated at ${limit} rows (default 50). ` +
+ `Pass an explicit limit, page through with sort=updated_asc + ` +
+ `updated_after=<last row's updated_at>, or narrow with type/tag.`,
+ );
+ }
+ return pages.map(pg => ({
+ slug: pg.slug,
+ source_id: pg.source_id,
+ type: pg.type,
+ title: pg.title,
+ updated_at: pg.updated_at,
+ ...(pg.deleted_at ? { deleted_at: pg.deleted_at } : {}),
+ }));
+ },
+ scope: 'read',
+ cliHints: { name: 'list' },
+};
+
+
+// Ops in EXACTLY the order they appear in the canonical `operations` array
+// (Page CRUD quartet first, then the v0.26.5 destructive-guard ops:
+// page-level soft-delete recovery + admin purge).
+export const pagesOperations: Operation[] = [
+ get_page, put_page, delete_page, list_pages,
+ restore_page, purge_deleted_pages,
+];
diff --git a/src/core/ops/raw-data.ts b/src/core/ops/raw-data.ts
new file mode 100644
index 0000000000..f91088d0ba
--- /dev/null
+++ b/src/core/ops/raw-data.ts
@@ -0,0 +1,48 @@
+/**
+ * Raw Data operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 2). Op consts stay module-private; `rawDataOperations` below lists
+ * them in EXACTLY the order they appear in the canonical `operations` array
+ * in ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';
+
+// --- Raw Data ---
+
+const put_raw_data: Operation = {
+ name: 'put_raw_data',
+ description: 'Store raw API response data for a page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page to attach the raw data to.' },
+ source: { type: 'string', required: true, description: 'Data source (e.g., crustdata, happenstance)' },
+ data: { type: 'object', required: true, description: 'Raw data object' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ enforceClientSlugFence(ctx, p.slug as string, 'put_raw_data');
+ if (ctx.dryRun) return { dry_run: true, action: 'put_raw_data', slug: p.slug, source: p.source };
+ // v0.31.8 (D7 + D21): thread ctx.sourceId.
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ await ctx.engine.putRawData(p.slug as string, p.source as string, p.data as object, sourceOpts);
+ return { status: 'ok' };
+ },
+};
+
+const get_raw_data: Operation = {
+ name: 'get_raw_data',
+ description: 'Retrieve raw data for a page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose raw data to fetch.' },
+ source: { type: 'string', description: 'Filter by source' },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.getRawData(p.slug as string, p.source as string | undefined, sourceScopeOpts(ctx));
+ },
+ scope: 'read',
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const rawDataOperations: Operation[] = [put_raw_data, get_raw_data];
diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.ts
new file mode 100644
index 0000000000..94d2170f0b
--- /dev/null
+++ b/src/core/ops/request-tools.ts
@@ -0,0 +1,280 @@
+/**
+ * request_tools operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 3): the WP4 (T9) discovery + pull-based per-client surface-unlock
+ * op, its persist rate limiter (+ test seam), and the visibleOpsForCaller
+ * catalog filter. Op const stays module-private; `requestToolsOperations`
+ * below is spliced into the canonical `operations` array in ../operations.ts
+ * at the cluster's original position. Never import from '../operations.ts'
+ * here STATICALLY (cycle) — visibleOpsForCaller needs the assembled op list,
+ * so it loads it via dynamic import inside the call path (the verbs.ts house
+ * pattern: by the time a handler runs, operations.ts has finished loading).
+ */
+
+// WP4 (request_tools): the four static imports below are runtime leaves
+// relative to operations.ts (no import cycles back into it). The cyclic
+// dependencies — src/mcp/surface.ts (→ brain-allowlist → operations),
+// src/mcp/publish-gates.ts (→ operations), and the assembled `operations`
+// array itself — are loaded via dynamic import inside the handler instead
+// (the verbs.ts house pattern).
+import { isUndefinedColumnError } from '../utils.ts';
+import { hasScope } from '../scope.ts';
+import { RateLimiter } from '../../mcp/rate-limit.ts';
+import { writeSurfaceChangeAudit } from '../surface-audit.ts';
+import type { Operation, OperationContext } from './contract.ts';
+import { OperationError } from './contract.ts';
+import { opAllowedForBoundClient } from './context.ts';
+
+// --- WP4 (T9): request_tools — discovery + pull-based per-client unlock ---
+
+/**
+ * D14.5: per-client rate limit on the persist branch (~5 surface persists /
+ * hour / client). Module-level token bucket (bounded LRU — attacker-chosen
+ * client ids can't grow memory); `let` + reset seam so tests don't leak
+ * bucket state across files.
+ */
+let requestToolsPersistLimiter = new RateLimiter({ limit: 5, windowMs: 3_600_000, lruCap: 5_000 });
+
+/** Test seam: fresh persist-rate-limit buckets. */
+export function __resetRequestToolsPersistLimiterForTests(): void {
+ requestToolsPersistLimiter = new RateLimiter({ limit: 5, windowMs: 3_600_000, lruCap: 5_000 });
+}
+
+/**
+ * One-line catalog summary: the first sentence of an op description,
+ * capped. Non-contractual rendering — full schemas come from the
+ * `{tools: [...]}` branch.
+ */
+function firstSentenceOf(description: string): string {
+ const t = description.trim();
+ const m = t.match(/^.*?[.!?](?=\s|$)/);
+ const s = (m ? m[0] : t).trim();
+ return s.length > 160 ? `${s.slice(0, 157)}...` : s;
+}
+
+/**
+ * The set of ops VISIBLE to this caller (never leak hidden names — C8/
+ * amendment 11 class): bounded by the server ceiling (ops above it can
+ * never be served, so naming them would recreate listed-but-denied at the
+ * persist level), minus localOnly on network transports (stdio and the
+ * trusted local CLI keep them — D7), minus ops outside the caller's scopes
+ * (agent-callable carve-out per FOV-4), minus bound-client-fenced ops (same
+ * predicate as tools/list, ENG-3), minus publish-gated ops whose gate is off
+ * (stdio and the trusted local CLI bypass gates — the D7 local-surface
+ * posture, matching assertPublishEnabled's remote===false exemption; a
+ * failed gate read hides the gated ops, fail-closed).
+ */
+async function visibleOpsForCaller(
+ ctx: OperationContext,
+ ceiling: 'verbs' | 'starter' | 'full',
+): Promise<Operation[]> {
+ // The assembled op list lives in ../operations.ts, which spreads THIS
+ // module's array — so it must never be imported statically here. Loaded
+ // lazily instead (the verbs.ts house pattern); by the time any handler
+ // runs, operations.ts has finished evaluating.
+ const { operations } = await import('../operations.ts');
+ const { filterOpsForSurface } = await import('../../mcp/surface.ts');
+ // Trusted local callers: the stdio pipe, or the local CLI (remote is
+ // strictly false — the fail-closed trust marker). Both CAN call localOnly
+ // and gated ops, so hiding them would make the catalog dishonest.
+ const isLocal = ctx.transport === 'stdio' || ctx.remote === false;
+
+ let gateDisabled: ReadonlySet<string> = new Set();
+ if (!isLocal) {
+ try {
+ const { disabledOpsForPublishGates } = await import('../../mcp/publish-gates.ts');
+ gateDisabled = await disabledOpsForPublishGates(ctx.engine, ctx.config);
+ } catch {
+ // Fail-closed: if the resolver can't even load, hide every gated op.
+ gateDisabled = new Set(operations.filter(o => o.publishGateKey).map(o => o.name));
+ }
+ }
+
+ // Auth-less transports (stdio) and grandfathered legacy bearer tokens
+ // (empty scopes array — that transport does no call-time scope checks
+ // either) skip scope filtering: for them the whole surface IS callable,
+ // so hiding by scope would make the catalog LESS honest, not more.
+ const scopes = ctx.auth?.scopes && ctx.auth.scopes.length > 0 ? ctx.auth.scopes : null;
+
+ return filterOpsForSurface(operations, ceiling).filter(op =>
+ (isLocal || !op.localOnly)
+ && (scopes === null
+ || hasScope(scopes, op.scope ?? 'read')
+ || (op.agentCallable === true && hasScope(scopes, 'agent')))
+ && opAllowedForBoundClient(ctx.auth, op)
+ && !gateDisabled.has(op.name),
+ );
+}
+
+const request_tools: Operation = {
+ name: 'request_tools',
+ description:
+ 'Discover this brain\'s tool catalog and optionally unlock a wider tool surface for your client. ' +
+ 'No arguments → the catalog visible to YOUR credentials, grouped by area (tool names + one-line summaries). ' +
+ '{tools: ["name", ...]} → full read-only schemas for the visible subset of those names (unknown/hidden names are silently omitted). ' +
+ '{surface: "verbs"|"starter"|"full"} → persist that tool surface for this client (bounded by the server ceiling; denied when an operator pinned the surface; ~5 changes/hour), then re-issue tools/list to see the new catalog.',
+ area: 'discovery',
+ // FOV-4: callable by read OR agent scope — discovery for every token class.
+ agentCallable: true,
+ params: {
+ tools: {
+ type: 'array',
+ items: { type: 'string', description: 'A tool name from the catalog.' },
+ description: 'Fetch full read-only tool schemas for these names. Names outside your visible surface are silently omitted (D5).',
+ },
+ surface: {
+ type: 'string',
+ enum: ['verbs', 'starter', 'full'],
+ description: 'Persist this tool surface for your client. Must not exceed the server ceiling; ignored surfaces stay available via no-arg discovery. Takes effect on your next tools/list.',
+ },
+ },
+ scope: 'read',
+ // D9: mutating because the persist branch writes oauth_clients.surface.
+ // The bound-client fence exempts it via BOUND_CLIENT_META_OPS (see the
+ // carve-out comment at opAllowedForBoundClient); the persist branch
+ // self-enforces ceiling + operator lock + scopes + rate limit.
+ mutating: true,
+ handler: async (ctx, p) => {
+ const { surfaceWiderThan, isMcpSurface } = await import('../../mcp/surface.ts');
+ // Unset ceiling (local CLI / direct dispatch) = 'full' — trusted-local
+ // callers were never surface-bounded.
+ const ceiling = ctx.surfaceCeiling ?? 'full';
+
+ // D5: the three branches are mutually exclusive. {surface, tools}
+ // together is ambiguous (persist vs descriptor fetch) — reject loudly
+ // rather than silently persisting and ignoring the tools list.
+ if (p.surface !== undefined && p.tools !== undefined) {
+ throw new OperationError(
+ 'invalid_params',
+ 'pass either {surface} (persist) or {tools} (descriptor fetch), not both.',
+ );
+ }
+
+ // ── persist branch (D5: accepts ONLY {surface}) ─────────────────────
+ if (p.surface !== undefined) {
+ const requested = p.surface as string;
+ if (!isMcpSurface(requested)) {
+ // Backstop for direct handler calls — MCP dispatch already rejects
+ // via the enum in validateParams (invalid_params naming the valid set).
+ throw new OperationError('invalid_params', `surface must be one of: verbs, starter, full (got an unrecognized value)`);
+ }
+ const clientId = ctx.auth?.clientId;
+ if (!clientId) {
+ // stdio has no per-token identity; a surface persist has nowhere to land.
+ return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };
+ }
+ if (surfaceWiderThan(requested, ceiling)) {
+ const e = new OperationError(
+ 'permission_denied',
+ `surface '${requested}' is above this server's ceiling '${ceiling}' (D2: per-client surfaces narrow, never widen).`,
+ `The operator caps this transport at --surface ${ceiling}; widening requires a server restart with a wider --surface.`,
+ );
+ e.detail = `ceiling=${ceiling}`; // amendment 4 key=value denial grammar; ENG-11 assign-after
+ throw e;
+ }
+ let rows: Record<string, unknown>[];
+ try {
+ rows = await ctx.engine.executeRaw(
+ `SELECT surface, surface_set_by FROM oauth_clients WHERE client_id = $1`,
+ [clientId],
+ );
+ } catch (err) {
+ if (isUndefinedColumnError(err, 'surface') || isUndefinedColumnError(err, 'surface_set_by')) {
+ // D5: a capability-negotiation op never returns internal_error for
+ // a pre-migration brain — report the gap and keep serving.
+ return { persisted: false, reason: 'migration pending' };
+ }
+ throw err;
+ }
+ if (rows.length === 0) {
+ // Legacy bearer tokens carry a clientId that is not an oauth_clients row.
+ return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };
+ }
+ const current = rows[0] as { surface?: string | null; surface_set_by?: string | null };
+ const operatorLocked = () => {
+ const e = new OperationError(
+ 'permission_denied',
+ "this client's surface is operator-pinned and cannot be self-changed (amendment 19).",
+ `Ask the brain operator to change it: gbrain auth rescope-client ${clientId} --surface ${requested}`,
+ );
+ e.detail = 'locked_by=operator';
+ return e;
+ };
+ if (current.surface_set_by === 'operator') throw operatorLocked();
+ // A dry-run preview exercises every denial above but must not consume
+ // the persist budget — the limiter meters actual writes only.
+ if (ctx.dryRun) {
+ return { persisted: false, dry_run: true, surface: requested, reason: 'dry_run' };
+ }
+ const rl = requestToolsPersistLimiter.check(clientId);
+ if (!rl.allowed) {
+ throw new OperationError(
+ 'rate_limited',
+ 'surface persistence is rate-limited to ~5 changes per hour per client (D14.5).',
+ `Retry after ~${rl.retryAfter ?? 60}s.`,
+ );
+ }
+ // Atomic re-check: a concurrent operator pin between the SELECT and
+ // this UPDATE must still win.
+ const updated = await ctx.engine.executeRaw(
+ `UPDATE oauth_clients SET surface = $1, surface_set_by = 'self'
+ WHERE client_id = $2 AND (surface_set_by IS DISTINCT FROM 'operator')
+ RETURNING client_id`,
+ [requested, clientId],
+ );
+ if (updated.length === 0) {
+ // Concurrent operator pin won the race: the denial must not consume
+ // the client's persist budget (the limiter meters actual writes).
+ requestToolsPersistLimiter.refund(clientId);
+ throw operatorLocked();
+ }
+ await writeSurfaceChangeAudit(ctx.engine, {
+ actor: clientId,
+ client_id: clientId,
+ old: (current.surface as string | null) ?? null,
+ new: requested,
+ via: 'request_tools',
+ });
+ return { persisted: true, surface: requested, note: 're-issue tools/list to see the new catalog' };
+ }
+
+ const visible = await visibleOpsForCaller(ctx, ceiling);
+
+ // ── descriptor branch (D5: read-only) ───────────────────────────────
+ if (p.tools !== undefined) {
+ const requested = (p.tools as unknown[]).filter((t): t is string => typeof t === 'string');
+ const byName = new Map(visible.map(o => [o.name, o]));
+ const picked: Operation[] = [];
+ const seen = new Set<string>();
+ for (const name of requested) {
+ if (seen.has(name)) continue;
+ seen.add(name);
+ const op = byName.get(name);
+ if (op) picked.push(op); // invisible names silently omitted (D5)
+ }
+ const { buildToolDefs } = await import('../../mcp/tool-defs.ts');
+ const { resolveStrictParamsMode } = await import('../../mcp/validate-params.ts');
+ const strictParams = (await resolveStrictParamsMode(ctx.engine, ctx.config)) === 'reject';
+ return { tools: buildToolDefs(picked, { strictParams }) };
+ }
+
+ // ── catalog branch (no args) ────────────────────────────────────────
+ const groups = new Map<string, Array<{ name: string; one_line: string }>>();
+ for (const op of visible) {
+ // Area names are non-contractual grouping labels (amendment 22).
+ const area = op.area ?? 'other';
+ const bucket = groups.get(area) ?? [];
+ bucket.push({ name: op.name, one_line: firstSentenceOf(op.description) });
+ groups.set(area, bucket);
+ }
+ const catalog = [...groups.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([area, tools]) => ({ area, tools }));
+ return {
+ catalog,
+ total_tools: visible.length,
+ note: 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to persist a wider tool surface (within the server ceiling), then re-issue tools/list.',
+ };
+ },
+};
+
+export const requestToolsOperations: Operation[] = [request_tools];
diff --git a/src/core/ops/salience.ts b/src/core/ops/salience.ts
new file mode 100644
index 0000000000..d21ece94d7
--- /dev/null
+++ b/src/core/ops/salience.ts
@@ -0,0 +1,87 @@
+/**
+ * Salience + Anomaly operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 2). Op consts stay module-private; `salienceOperations`
+ * below lists them in EXACTLY the order they appear in the canonical
+ * `operations` array in ../operations.ts (find_anomalies was defined after
+ * the push-context divider in the original file but has always occupied the
+ * slot right after get_recent_salience in the array — the array order is
+ * the contract). Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import {
+ GET_RECENT_SALIENCE_DESCRIPTION,
+ FIND_ANOMALIES_DESCRIPTION,
+} from '../operations-descriptions.ts';
+
+// --- v0.29: Salience + Anomaly Detection ---
+
+const get_recent_salience: Operation = {
+ name: 'get_recent_salience',
+ description: GET_RECENT_SALIENCE_DESCRIPTION,
+ scope: 'read',
+ params: {
+ days: { type: 'number', description: 'Window in days. Default 14.' },
+ limit: { type: 'number', description: 'Max results (default 20, capped at 100).' },
+ slugPrefix: {
+ type: 'string',
+ description: "Optional slug-prefix filter, e.g. 'personal' or 'wiki/people'.",
+ },
+ recency_bias: {
+ type: 'string',
+ enum: ['flat', 'on'],
+ description:
+ "v0.29.1: how to weight recency in the salience score.\n" +
+ " 'flat' (DEFAULT) — v0.29.0 behavior. Every page gets 1/(1+days_old).\n" +
+ " Stable, predictable; what most callers want.\n" +
+ " 'on' — Per-prefix decay map. concepts/originals/writing/\n" +
+ " become evergreen (recency component = 0); daily/,\n" +
+ " media/x/, chat/ decay aggressively. Use when the\n" +
+ " user explicitly biases for recency-aware salience\n" +
+ " ('what's been salient lately' vs 'what matters\n" +
+ " in this brain regardless of when').",
+ },
+ },
+ handler: async (ctx, p) => {
+ const recencyBias = p.recency_bias === 'on' ? 'on' : 'flat';
+ return ctx.engine.getRecentSalience({
+ days: typeof p.days === 'number' ? p.days : undefined,
+ limit: typeof p.limit === 'number' ? p.limit : undefined,
+ slugPrefix: typeof p.slugPrefix === 'string' ? p.slugPrefix : undefined,
+ recency_bias: recencyBias,
+ });
+ },
+ cliHints: { name: 'salience' },
+};
+
+const find_anomalies: Operation = {
+ name: 'find_anomalies',
+ description: FIND_ANOMALIES_DESCRIPTION,
+ scope: 'read',
+ params: {
+ since: {
+ type: 'string',
+ description: 'ISO date YYYY-MM-DD. Default = today (UTC).',
+ },
+ lookback_days: {
+ type: 'number',
+ description: 'Days of history for the baseline. Default 30.',
+ },
+ sigma: {
+ type: 'number',
+ description: 'Sigma threshold. Default 3.0.',
+ },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.findAnomalies({
+ 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,
+ });
+ },
+ cliHints: { name: 'anomalies' },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const salienceOperations: Operation[] = [get_recent_salience, find_anomalies];
diff --git a/src/core/ops/schema-packs.ts b/src/core/ops/schema-packs.ts
new file mode 100644
index 0000000000..0ca661e52e
--- /dev/null
+++ b/src/core/ops/schema-packs.ts
@@ -0,0 +1,305 @@
+/**
+ * Schema-pack operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 3): the v0.40.6.0 Schema Cathedral v3 ops (7 read + 2 admin —
+ * the admin pair is deliberately NOT localOnly per D2, so remote agents
+ * (your OpenClaw, etc.) can author packs behind admin OAuth scope). Op
+ * consts stay module-private; `schemaPacksOperations` below lists them in
+ * EXACTLY the order they appear in the canonical `operations` array in
+ * ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { sourceScopeOpts } from './context.ts';
+
+// ──────────────────────────────────────────────────────────────────────
+// v0.40.6.0 Schema Cathedral v3 — 9 new MCP ops for the agent on-ramp.
+//
+// Read ops (scope: read; NOT localOnly) — any read-scope OAuth client.
+// Write ops (scope: admin; NOT localOnly per D2) — admin-scope client
+// (your OpenClaw and similar remote agents) can author schema packs
+// remotely. Audit log captures actor=mcp:<clientId8> on every mutation
+// (see src/core/schema-pack/mutate-audit.ts privacy posture per D20).
+//
+// Per-call schema_pack opt STAYS rejected for remote callers — that
+// trust boundary is enforced by op-trust-gate.ts and is separate from
+// the localOnly posture (R2 regression preserved).
+// ──────────────────────────────────────────────────────────────────────
+
+const get_active_schema_pack: Operation = {
+ name: 'get_active_schema_pack',
+ description: 'v0.40.6.0: cheap identity packet for the active schema pack. Returns {pack_name, version, sha8, page_types_count, link_types_count, primitive_summary, source_tier}. Useful for agents to know which pack they are operating against without paying full manifest load cost.',
+ params: {},
+ scope: 'read',
+ handler: async (ctx) => {
+ const { loadActivePack, resolveActivePackNameOnly } = await import('../schema-pack/load-active.ts');
+ const { loadConfig } = await import('../config.ts');
+ const cfg = loadConfig();
+ const sourceOpts: Record<string, unknown> = {};
+ if (ctx.sourceId) sourceOpts.sourceId = ctx.sourceId;
+ const resolution = resolveActivePackNameOnly({ cfg, remote: ctx.remote ?? true, ...sourceOpts });
+ const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, ...sourceOpts });
+ const primitiveSummary: Record<string, number> = {};
+ for (const t of pack.manifest.page_types) {
+ primitiveSummary[t.primitive] = (primitiveSummary[t.primitive] ?? 0) + 1;
+ }
+ return {
+ pack_name: pack.manifest.name,
+ version: pack.manifest.version,
+ sha8: pack.manifest_sha8,
+ identity: pack.identity,
+ page_types_count: pack.manifest.page_types.length,
+ link_types_count: pack.manifest.link_types.length,
+ primitive_summary: primitiveSummary,
+ source_tier: resolution.source,
+ };
+ },
+};
+
+const list_schema_packs: Operation = {
+ name: 'list_schema_packs',
+ description: 'v0.40.6.0: list installed schema packs (bundled + user-installed). Returns {bundled: string[], installed: string[]}. Read-only directory listing.',
+ params: {},
+ scope: 'read',
+ handler: async (_ctx) => {
+ const { existsSync, readdirSync } = await import('node:fs');
+ const { join } = await import('node:path');
+ const { gbrainPath } = await import('../config.ts');
+ const { BUNDLED_PACK_NAMES } = await import('../schema-pack/bundled.ts');
+ const bundled = [...BUNDLED_PACK_NAMES];
+ const installedDir = gbrainPath('schema-packs');
+ const installed: string[] = [];
+ if (existsSync(installedDir)) {
+ for (const entry of readdirSync(installedDir)) {
+ const candidates = ['pack.yaml', 'pack.yml', 'pack.json'];
+ for (const c of candidates) {
+ if (existsSync(join(installedDir, entry, c))) { installed.push(entry); break; }
+ }
+ }
+ }
+ return { bundled, installed };
+ },
+};
+
+const schema_stats: Operation = {
+ name: 'schema_stats',
+ description: 'v0.40.6.0: per-type page counts + typed-coverage from the DB. Returns {schema_version:1, pack_identity, aggregate, per_source, dead_prefixes}. Multi-source aware via ctx.sourceId/allowedSources.',
+ params: {},
+ scope: 'read',
+ handler: async (ctx) => {
+ const { runStatsCore } = await import('../schema-pack/stats.ts');
+ const scope = sourceScopeOpts(ctx);
+ const opts: { sourceId?: string; sourceIds?: string[] } = {};
+ if (scope.sourceIds && scope.sourceIds.length > 0) opts.sourceIds = scope.sourceIds;
+ else if (scope.sourceId) opts.sourceId = scope.sourceId;
+ return runStatsCore(ctx, opts);
+ },
+};
+
+const schema_lint: Operation = {
+ name: 'schema_lint',
+ description: 'v0.40.6.0: lint the active (or named) schema pack. File-plane rules only over MCP — the with_db option is rejected for remote callers (DB-aware rules require local CLI). Returns {ok, errors, warnings} structured report.',
+ params: {
+ pack: { type: 'string', description: 'Pack name (default: active pack)' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { runAllLintRules } = await import('../schema-pack/lint-rules.ts');
+ const { loadActivePack } = await import('../schema-pack/load-active.ts');
+ const { loadConfig, gbrainPath } = await import('../config.ts');
+ const { existsSync } = await import('node:fs');
+ const { join } = await import('node:path');
+ const cfg = loadConfig();
+ let manifest;
+ if (p.pack) {
+ // Locate by name without trust-gating per-call schema_pack opt
+ // (that's a separate axis — this is just file lookup).
+ const packName = p.pack as string;
+ const candidates = ['pack.yaml', 'pack.yml', 'pack.json'];
+ let path: string | null = null;
+ for (const c of candidates) {
+ const candidate = join(gbrainPath('schema-packs', packName), c);
+ if (existsSync(candidate)) { path = candidate; break; }
+ }
+ if (!path) return { error: 'pack_not_found', pack: packName };
+ const { loadPackFromFile: loader } = await import('../schema-pack/loader.ts');
+ manifest = loader(path);
+ } else {
+ const resolved = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
+ manifest = resolved.manifest;
+ }
+ // File-plane only over MCP; the engine-aware --with-db opt-in is
+ // CLI-only (Phase 5 wiring). MCP callers get the 9 file-plane rules.
+ return await runAllLintRules(manifest);
+ },
+};
+
+const schema_graph: Operation = {
+ name: 'schema_graph',
+ description: 'v0.40.6.0: schema pack graph as JSON edges. Returns {nodes: [{name, primitive}], edges: [{from, verb, to}]} derived from link_types inference + frontmatter_links.',
+ params: {},
+ scope: 'read',
+ handler: async (ctx) => {
+ const { loadActivePack } = await import('../schema-pack/load-active.ts');
+ const { loadConfig } = await import('../config.ts');
+ const cfg = loadConfig();
+ const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
+ const nodes = pack.manifest.page_types.map((t) => ({ name: t.name, primitive: t.primitive }));
+ const edges: Array<{ from: string; verb: string; to: string }> = [];
+ for (const lt of pack.manifest.link_types) {
+ if (lt.inference?.page_type) {
+ edges.push({
+ from: lt.inference.page_type,
+ verb: lt.name,
+ to: lt.inference.target_type ?? '*',
+ });
+ }
+ }
+ for (const fl of pack.manifest.frontmatter_links) {
+ edges.push({ from: fl.page_type, verb: fl.link_type, to: '*' });
+ }
+ return { schema_version: 1, pack: pack.manifest.name, nodes, edges };
+ },
+};
+
+const schema_explain_type: Operation = {
+ name: 'schema_explain_type',
+ description: 'v0.40.6.0: resolved settings for a single page_type in the active pack. Returns {pack, type, primitive, path_prefixes, aliases, extractable, expert_routing}.',
+ params: {
+ type: { type: 'string', required: true, description: 'Page type name to explain' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { loadActivePack } = await import('../schema-pack/load-active.ts');
+ const { loadConfig } = await import('../config.ts');
+ const cfg = loadConfig();
+ const pack = await loadActivePack({ cfg, remote: ctx.remote ?? true, sourceId: ctx.sourceId });
+ const found = pack.manifest.page_types.find((t) => t.name === p.type);
+ if (!found) return { error: 'type_not_found', type: p.type as string, pack: pack.manifest.name };
+ return { schema_version: 1, pack: pack.manifest.name, type: found };
+ },
+};
+
+const schema_review_orphans: Operation = {
+ name: 'schema_review_orphans',
+ description: 'v0.40.6.0: list pages with no active-pack type match. Returns {orphan_count, orphans: [{slug, source_id}]}.',
+ params: {
+ limit: { type: 'number', description: 'Max orphans to return (default 100)' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const limit = Math.max(1, Math.min(10000, (p.limit as number) ?? 100));
+ const scope = sourceScopeOpts(ctx);
+ let where = `WHERE deleted_at IS NULL AND (type IS NULL OR type = '')`;
+ const params: unknown[] = [];
+ if (scope.sourceIds && scope.sourceIds.length > 0) {
+ where += ` AND source_id = ANY($1::text[])`;
+ params.push(scope.sourceIds);
+ } else if (scope.sourceId) {
+ where += ` AND source_id = $1`;
+ params.push(scope.sourceId);
+ }
+ try {
+ const rows = await ctx.engine.executeRaw<{ slug: string; source_id: string }>(
+ `SELECT slug, COALESCE(source_id, 'default') AS source_id FROM pages ${where} ORDER BY source_id, slug LIMIT ${limit}`,
+ params,
+ );
+ return {
+ schema_version: 1,
+ orphan_count: rows.length,
+ orphans: rows.map((r) => ({ slug: r.slug, source_id: r.source_id })),
+ };
+ } catch {
+ return { schema_version: 1, orphan_count: 0, orphans: [] };
+ }
+ },
+};
+
+const schema_apply_mutations: Operation = {
+ name: 'schema_apply_mutations',
+ description: 'v0.40.7.0: batched schema pack mutation. ATOMIC: every mutation is validated against an in-memory manifest first, and the pack file is written to disk at most once, after the FULL batch has proven valid — so a failure at any point leaves the pack file byte-identical to its pre-batch state (never a partial write). Audit log records one batch_id. Admin scope; NOT localOnly so remote agents (your OpenClaw, etc.) can author packs over normal MCP. Mutation shape per ApplyMutationsRequest type — supports add_type / remove_type / update_type / add_alias / remove_alias / add_prefix / remove_prefix / add_link_type / remove_link_type / set_extractable / set_expert_routing.',
+ params: {
+ pack: { type: 'string', required: true, description: 'Pack to mutate (must not be bundled)' },
+ mutations: {
+ type: 'array',
+ required: true,
+ description: 'Array of {op, ...args} mutation records to apply atomically',
+ items: { type: 'object' },
+ },
+ force: { type: 'boolean', description: 'Steal stale per-pack lock' },
+ },
+ scope: 'admin',
+ mutating: true,
+ handler: async (ctx, p) => {
+ const pack = p.pack as string;
+ const mutations = p.mutations as Array<{ op: string; [k: string]: unknown }>;
+ const force = p.force === true;
+ if (!Array.isArray(mutations) || mutations.length === 0) {
+ return { error: 'invalid_request', message: 'mutations must be a non-empty array' };
+ }
+ const batchId = `batch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const actor = ctx.auth?.clientId ? `mcp:${ctx.auth.clientId.slice(0, 8)}` : 'cli';
+ const sourceId = ctx.sourceId; // codex C5: write-side scoping
+ // `applyMutationsAtomic` (issue #2581) owns the lock + single read +
+ // single write for the whole batch: every mutation is validated
+ // in-memory first, and the pack file is written at most once, only
+ // after the FULL batch checks out. That is what makes this actually
+ // atomic (a failure at any index can never leave earlier mutations on
+ // disk), vs. the old per-mutation-writes-as-it-goes shape.
+ const { applyMutationsAtomic } = await import('../schema-pack/mutate.ts');
+ try {
+ const results = await applyMutationsAtomic(pack, mutations, {
+ actor: actor as 'cli' | `mcp:${string}`,
+ batchId,
+ engine: ctx.engine,
+ ...(sourceId ? { sourceId } : {}),
+ ...(force ? { force: true } : {}),
+ });
+ return {
+ schema_version: 1,
+ pack,
+ batch_id: batchId,
+ mutations_applied: results.length,
+ results,
+ };
+ } catch (e) {
+ const code = (e as { code?: string }).code ?? 'UNKNOWN';
+ const failedAtIndex = (e as { details?: { index?: number } }).details?.index;
+ return {
+ error: 'mutation_failed',
+ code,
+ message: (e as Error).message,
+ batch_id: batchId,
+ // Nothing was written to disk — applyMutationsAtomic only writes
+ // once, after every mutation in the batch has validated cleanly.
+ // (Pre-fix, this field was `partial_results` and listed mutations
+ // that HAD already landed on disk, because the old implementation
+ // wrote as it went — that shape is gone; a failed batch can no
+ // longer imply partial application.)
+ mutations_applied: 0,
+ pack_unchanged: true,
+ ...(failedAtIndex !== undefined ? { failed_at_index: failedAtIndex } : {}),
+ };
+ }
+ },
+};
+
+const reload_schema_pack: Operation = {
+ name: 'reload_schema_pack',
+ description: 'v0.40.6.0: flush the in-process schema pack cache so the next loadActivePack re-reads from disk. Cascades through extends-chain (codex C6). Admin scope; NOT localOnly. Returns {invalidated: string[]}.',
+ params: {
+ pack: { type: 'string', description: 'Pack name to invalidate (omit to flush all)' },
+ },
+ scope: 'admin',
+ mutating: false, // no DB writes
+ handler: async (_ctx, p) => {
+ const { invalidatePackCache } = await import('../schema-pack/registry.ts');
+ return invalidatePackCache(p.pack as string | undefined);
+ },
+};
+
+export const schemaPacksOperations: Operation[] = [
+ get_active_schema_pack, list_schema_packs,
+ schema_stats, schema_lint, schema_graph, schema_explain_type,
+ schema_review_orphans,
+ schema_apply_mutations, reload_schema_pack,
+];
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
new file mode 100644
index 0000000000..8710923c32
--- /dev/null
+++ b/src/core/ops/search.ts
@@ -0,0 +1,374 @@
+/**
+ * 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
+ * cluster). Op consts stay module-private; `searchOperations` below lists
+ * them in EXACTLY the order they appear in the canonical `operations` array
+ * in ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import { hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from '../search/hybrid.ts';
+import { looksConceptShaped } from '../search/query-intent.ts';
+import { expandQuery } from '../search/expansion.ts';
+import { dedupResults } from '../search/dedup.ts';
+import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from '../eval-capture.ts';
+import type { HybridSearchMeta } from '../types.ts';
+import { bumpLastRetrievedAt } from '../last-retrieved.ts';
+import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';
+import { OperationError } from './contract.ts';
+import type { Operation } from './contract.ts';
+import {
+ federatedSearchScope,
+ resolvePerCallMode,
+ stampEvidenceSafe,
+ maybeCaptureSearch,
+} from './context.ts';
+
+// --- Search ---
+
+/**
+ * WP2/D3 + E1: the `retrieval` response-meta payload for the search/query
+ * ops. Carries the already-computed HybridSearchMeta signal (vector arm,
+ * cache, budget, degradation stages — populated by the search pipeline) plus
+ * the concept-shaped hint, so an MCP caller can distinguish "clean miss"
+ * from "the pipeline degraded" without a second call. The `hint` is
+ * non-contractual prose (agents read it; nothing should parse it).
+ */
+function buildRetrievalResponseMeta(
+ queryText: string,
+ results: unknown[],
+ meta: HybridSearchMeta | null,
+ opts: { conceptHint?: boolean } = {},
+): Record<string, unknown> {
+ const m = meta as (HybridSearchMeta & { degraded?: unknown; retrieved_count?: number }) | null;
+ const hint = opts.conceptHint && looksConceptShaped(queryText)
+ ? "concept-shaped question — the 'query' tool adds multi-query expansion and recovers " +
+ 'synonym-phrased matches this keyword-leaning search can miss.'
+ : undefined;
+ return {
+ returned_count: results.length,
+ retrieved_count: m?.retrieved_count ?? results.length,
+ ...(m ? {
+ vector_enabled: m.vector_enabled,
+ expansion_applied: m.expansion_applied,
+ ...(m.cache ? { cache: m.cache.status } : {}),
+ ...(m.token_budget ? { token_budget: m.token_budget } : {}),
+ ...(m.degraded !== undefined ? { degraded: m.degraded } : {}),
+ } : {}),
+ ...(hint ? { hint } : {}),
+ };
+}
+
+const search: Operation = {
+ name: 'search',
+ description: SEARCH_DESCRIPTION,
+ params: {
+ query: { type: 'string', required: true, description: "Search text. Exact tokens, names, and structured-field values work best here (e.g. 'acme-example series A'), since this op does no LLM expansion. This is the search text param — there is no `text` or `q` param." },
+ limit: { type: 'number', description: 'Max results (default 20)' },
+ offset: { type: 'number', description: 'Skip first N results (for pagination)' },
+ mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only.' },
+ },
+ handler: async (ctx, p) => {
+ const startedAt = Date.now();
+ const queryText = p.query as string;
+ const limit = (p.limit as number) || 20;
+ const offset = (p.offset as number) || 0;
+ // #2561: unqualified trusted-local search spans federated sources.
+ const scope = federatedSearchScope(ctx);
+
+ // T4/D5 — per-call mode honored ONLY for trusted/local callers so a remote
+ // OAuth client can't escalate to the costly tokenmax bundle. Local + unknown
+ // mode → loud reject; remote + mode set → silently ignored (uses config).
+ const perCallMode = resolvePerCallMode(ctx, p.mode);
+
+ // T4/D17 — escape hatch: keyword-only when the operator opts out of the
+ // hybrid `search` contract (privacy/cost: no query text to an embedding
+ // provider). Defaults to cheap-hybrid (D4/D15).
+ const keywordOnly = (await ctx.engine.getConfig('search.mcp_keyword_only')) === 'true';
+
+ if (keywordOnly) {
+ const raw = await ctx.engine.searchKeyword(queryText, { limit, offset, ...scope });
+ const results = dedupResults(raw);
+ stampEvidenceSafe(results);
+ // #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);
+ // #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);
+ 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 }));
+ return results;
+ }
+
+ // Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but
+ // expansion OFF (no per-call LLM cost). `query` op is the full-control variant.
+ let capturedMeta: HybridSearchMeta | null = null;
+ const results = await hybridSearchCached(ctx.engine, queryText, {
+ limit,
+ offset,
+ expansion: false,
+ ...scope,
+ ...(perCallMode ? { mode: perCallMode } : {}),
+ onMeta: (m) => { capturedMeta = m; },
+ });
+ const latency_ms = Date.now() - startedAt;
+ bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
+ maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
+ ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta, { conceptHint: true }));
+ return results;
+ },
+ scope: 'read',
+ cliHints: { name: 'search', positional: ['query'] },
+};
+
+const query: Operation = {
+ name: 'query',
+ description: QUERY_DESCRIPTION,
+ params: {
+ // v0.27.1: `query` is no longer strictly required — `--image <path>`
+ // is the alternative entry point for image-similarity search. The CLI
+ // validator at src/cli.ts honors `cliHints.altRequired` and admits the
+ // image-only invocation. MCP / programmatic callers must still pass
+ // `query` OR `image` (handler refuses if both are absent).
+ query: { type: 'string', required: false, description: "Question or topic text for hybrid retrieval with expansion (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params." },
+ /** v0.27.1: image-similarity search. Path resolved on the CLI side
+ * before the op fires (the op receives raw bytes neither side; the
+ * CLI loads the file, base64-encodes, and passes through `image`). */
+ image: { type: 'string', description: 'Base64-encoded image bytes for image-similarity search (CLI: --image <path>).' },
+ image_mime: { type: 'string', description: 'MIME type for the image bytes (auto-derived from path on CLI; required when calling op directly).' },
+ limit: { type: 'number', description: 'Max results (default 20)' },
+ offset: { type: 'number', description: 'Skip first N results (for pagination)' },
+ expand: { type: 'boolean', description: 'Enable multi-query expansion (default: true)' },
+ detail: { type: 'string', description: 'Result detail level: low (compiled truth only), medium (default, all with dedup), high (all chunks)' },
+ mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only; remote uses configured mode.' },
+ // v0.20.0 Cathedral II Layer 10 C1/C2: language + symbol-kind filters.
+ lang: { type: 'string', description: 'Filter to chunks where content_chunks.language matches (e.g., typescript, python, ruby)' },
+ symbol_kind: { type: 'string', description: 'Filter to chunks where content_chunks.symbol_type matches (e.g., function, class, method, type, interface)' },
+ // v0.20.0 Cathedral II Layer 7 (A2) / Layer 10 C3: two-pass structural expansion.
+ near_symbol: { type: 'string', description: 'Anchor retrieval at this qualified symbol name (e.g., BrainEngine.searchKeyword). Enables A2 two-pass.' },
+ walk_depth: { type: 'number', description: 'Structural walk depth 1-2. Default 0 (off). Expands anchors through code_edges with 1/(1+hop) decay.' },
+ // v0.29.1 — orthogonal recency + salience axes. YOU (the agent) decide.
+ salience: {
+ type: 'string',
+ enum: ['off', 'on', 'strong'],
+ description:
+ "v0.29.1 salience boost — emotional_weight + take_count, NO time component.\n" +
+ " 'off' — default for entity / canonical / definitional queries\n" +
+ " 'on' — surface emotionally-weighted + take-rich pages\n" +
+ " 'strong' — aggressive mattering tilt\n" +
+ "Omit and gbrain auto-detects from query text. Independent of `recency`.",
+ },
+ recency: {
+ type: 'string',
+ enum: ['off', 'on', 'strong'],
+ description:
+ "v0.29.1 recency boost — per-prefix age decay, NO mattering signal.\n" +
+ " 'off' — default for canonical truth\n" +
+ " 'on' — daily/, media/x/, chat/ decay aggressively; concepts/, originals/, writing/ stay evergreen\n" +
+ " 'strong' — multiplies the recency factor by 1.5 (use for 'today' / 'right now')\n" +
+ "Omit and gbrain auto-detects. Independent of `salience` (orthogonal axes).",
+ },
+ since: {
+ type: 'string',
+ description:
+ "v0.29.1 — filter to pages whose effective_date is >= this. ISO-8601 (YYYY-MM-DD or full timestamp) OR relative ('7d', '2w', '1y'). Replaces deprecated `afterDate`.",
+ },
+ until: {
+ type: 'string',
+ description:
+ "v0.29.1 — filter to effective_date <= this. Same format as `since`. Replaces deprecated `beforeDate`. YYYY-MM-DD lands at end-of-day.",
+ },
+ source_id: {
+ type: 'string',
+ description:
+ "v0.34: scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources.",
+ },
+ cross_modal: {
+ type: 'string',
+ enum: ['text', 'image', 'both', 'auto'],
+ description:
+ "v0.36 cross-modal search routing.\n" +
+ " 'text' (default for non-image-intent queries) — text-only path, no behavior change vs v0.35.\n" +
+ " 'image' — route the query through Voyage multimodal-3 + the embedding_image column. Best for 'show me photos of...' phrasings.\n" +
+ " 'both' — run text AND image searches in parallel; merge via weighted RRF.\n" +
+ " 'auto' — same effect as omitting the field; intent classifier decides based on query phrasing.",
+ },
+ embedding_column: {
+ type: 'string',
+ description:
+ "v0.36: route vector search through a non-default embedding column. Defaults to 'embedding' (the brain's primary column) unless `search_embedding_column` config sets a different default. Per-call override for A/B benchmarking across providers (e.g. 'embedding_voyage', 'embedding_openai'). Column MUST be declared in the `embedding_columns` config registry — unknown names throw with a paste-ready hint listing valid columns.",
+ },
+ adaptive_return: {
+ type: 'boolean',
+ description:
+ "v0.41.33 — return a TIGHT, intent-sized result set instead of the full top-K. YOU (the agent) set this per query to serve the user well:\n" +
+ " TRUE when the user's question has a small, specific answer — a lookup ('what is X', 'who is Y', 'what's my <thing>', 'what did Z decide'), a single-fact recall, or when you'll route the result into a precise downstream step (a classifier, a decision, an exact citation). The user gets the answer, not a wall of loosely-related pages, and you spend fewer tokens reading noise.\n" +
+ " Omit / FALSE for breadth — 'everything about X', 'list all', 'what do I know about Y', exploration, brainstorming, or any time you'd rather see more candidates and judge for yourself. Recall matters more there, so take the full top-K.\n" +
+ "Safe by construction: it NEVER returns empty when there are matches (you always get at least the top hit), and it only applies to the first page (omit when paginating). Caps come from config (search.adaptive_return_entity_max / _other_max; default 2 / 6) — pass `limit` 1 alongside this for a hard single-answer cap.",
+ },
+ autocut: {
+ type: 'boolean',
+ description:
+ "v0.42.3.0 — autocut is the SMART DEFAULT (already ON when the reranker runs, which it does in the default search mode). It returns only the confident cluster by cutting where the relevance score drops off a cliff, so an obvious single answer comes back as 1 result and a genuine handful comes back as that handful — not a fixed wall of 20+.\n" +
+ " You almost never set this. Pass FALSE only to FORCE the full top-K when you deliberately want breadth — broad exploration, 'show me everything about X', enumeration where you'd rather over-collect and judge for yourself, or when you suspect the top hit is wrong and want to see the alternatives.\n" +
+ " TRUE is redundant in default mode (it's already on); it only matters to override a brain whose config turned autocut off.\n" +
+ "Safe by construction: never returns empty when there are matches, only applies to the first page (omit when paginating), and is a no-op when no reranker scored the results (so it can't cut on an untrustworthy signal). Distinct from `adaptive_return`: autocut cuts on the score cliff; adaptive_return caps by question intent. Leave both unset for the smart default.",
+ },
+ relational: {
+ type: 'boolean',
+ description:
+ "v0.43 — relational recall arm. SMART DEFAULT (on in balanced/tokenmax). When the question is about a RELATIONSHIP ('who invested in widget-co', 'who introduced me to alice', 'what connects fund-a and fund-b'), the brain resolves the named entity and walks its typed-edge graph (invested_in, works_at, founded, …), surfacing the answer even when no passage mentions both sides. Pure no-op for non-relational questions. Pass FALSE to force lexical/vector-only retrieval (e.g. debugging why a graph answer appeared). You almost never set this.",
+ },
+ },
+ handler: async (ctx, p) => {
+ const startedAt = Date.now();
+ const expand = p.expand !== false;
+ const detail = (p.detail as 'low' | 'medium' | 'high') || undefined;
+ const queryText = p.query as string | undefined;
+ const imageData = p.image as string | undefined;
+ const imageMime = (p.image_mime as string) || 'image/jpeg';
+ const embeddingColumnParam =
+ typeof p.embedding_column === 'string' && p.embedding_column.length > 0
+ ? (p.embedding_column as string)
+ : undefined;
+ // Explicit per-call source_id must win over ctx.sourceId. `__all__` spans
+ // every source for trusted local callers, but only the caller's granted
+ // sources for remote callers (resolveRequestedScope is the single
+ // trust+grant resolver shared by every source-scoped read op). This scope
+ // is spread into BOTH the image-similarity searchVector path and the text
+ // hybridSearch path below, so both honor the same grant.
+ const sourceIdParam = typeof p.source_id === 'string' ? p.source_id : undefined;
+ // #2561: unqualified trusted-local query spans federated sources (per-call
+ // source_id / remote grants still resolve through resolveRequestedScope).
+ const querySourceScope = federatedSearchScope(ctx, sourceIdParam);
+
+ // v0.27.1: image-similarity branch. Bypasses hybridSearch (which is
+ // text-only); embeds the image via embedMultimodal and runs a direct
+ // vector search against the embedding_image column.
+ if (imageData) {
+ const { embedMultimodal } = await import('../ai/gateway.ts');
+ const [vec] = await embedMultimodal([
+ { kind: 'image_base64', data: imageData, mime: imageMime },
+ ]);
+ // v0.34.1 (#861 F2 — 6th leak surface): the image path bypasses
+ // hybridSearch and calls searchVector directly, so it needs its
+ // own thread of the source scope. Pre-fix, this branch leaked
+ // image pages across sources independent of the text path's fix.
+ const results = await ctx.engine.searchVector(vec, {
+ limit: (p.limit as number) || 20,
+ offset: (p.offset as number) || 0,
+ embeddingColumn: 'embedding_image',
+ ...querySourceScope,
+ });
+ return results;
+ }
+
+ if (!queryText) {
+ // WP3: typed envelope — a caller mistake must classify as invalid_params
+ // over MCP, not the internal_error a plain throw produced.
+ throw new OperationError(
+ 'invalid_params',
+ 'query requires either `query` (text) or `image` (base64 bytes).',
+ 'Pass `query` with your search text (e.g. {"query": "acme-example roadmap"}), or `image` with base64 image bytes.',
+ );
+ }
+
+ // v0.25.0 — capture meta side-channel. hybridSearch's return contract
+ // stays SearchResult[] (Cathedral II callers depend on that); meta
+ // arrives via callback so eval capture can record what actually ran.
+ //
+ // v0.34 (Codex finding #2): thread ctx.sourceId so multi-source brains
+ // get source-scoped retrieval. Explicit `source_id` param wins over
+ // ctx.sourceId for callers that want to override (per-call multi-source
+ // search). When the param is the literal '__all__', force-allow
+ // 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.
+ const results = await hybridSearchCached(ctx.engine, queryText, {
+ limit: (p.limit as number) || 20,
+ offset: (p.offset as number) || 0,
+ expansion: expand,
+ expandFn: expand ? expandQuery : undefined,
+ // T4/D5 — per-call mode (local/trusted only; remote ignored).
+ ...((): { mode?: string } => { const m = resolvePerCallMode(ctx, p.mode); return m ? { mode: m } : {}; })(),
+ detail,
+ language: (p.lang as string) || undefined,
+ symbolKind: (p.symbol_kind as string) || undefined,
+ nearSymbol: (p.near_symbol as string) || undefined,
+ walkDepth: typeof p.walk_depth === 'number' ? (p.walk_depth as number) : undefined,
+ ...querySourceScope,
+ // v0.29.1 — agent-explicit recency + salience. Omitted = heuristic defaults.
+ salience: p.salience as 'off' | 'on' | 'strong' | undefined,
+ recency: p.recency as 'off' | 'on' | 'strong' | undefined,
+ since: typeof p.since === 'string' ? p.since : undefined,
+ until: typeof p.until === 'string' ? p.until : undefined,
+ // v0.32.x search-lite: token budget + cache opt-outs.
+ tokenBudget: typeof p.token_budget === 'number' ? (p.token_budget as number) : undefined,
+ useCache: typeof p.use_cache === 'boolean' ? (p.use_cache as boolean) : undefined,
+ intentWeighting: typeof p.intent_weighting === 'boolean' ? (p.intent_weighting as boolean) : undefined,
+ // v0.36 cross-modal routing param.
+ crossModal: p.cross_modal as 'text' | 'image' | 'both' | 'auto' | undefined,
+ onMeta: (m) => { capturedMeta = m; },
+ // v0.36 (D15): per-call embedding column override. Resolver rejects
+ // unknown names at hybrid entry with EmbeddingColumnNotRegisteredError;
+ // the error surfaces back to the agent as the op error envelope.
+ // Source scope is already threaded via ...querySourceScope above
+ // (master's #1182 cleanup of the duplicate sourceScopeOpts spread).
+ embeddingColumn: embeddingColumnParam,
+ // v0.41.33 — agent-explicit adaptive return-sizing. Omitted = off
+ // (config default applies). hybridSearchCached skips the cache when on.
+ 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.
+ autocut: typeof p.autocut === 'boolean' ? (p.autocut as boolean) : undefined,
+ // v0.43 — relational recall override. Omitted = smart default (mode bundle).
+ relationalRetrieval: typeof p.relational === 'boolean' ? (p.relational as boolean) : undefined,
+ });
+ const latency_ms = Date.now() - startedAt;
+
+ // v0.37.0 (D11): op-layer last_retrieved_at write-back. Same shape as the
+ // search handler — fire-and-forget, internal callers bypass this path.
+ bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));
+
+ // Op-layer capture (v0.25.0). Fire-and-forget. meta tells gbrain-evals
+ // what hybridSearch *actually* did so replay can distinguish "with API
+ // key" from "keyword-only fallback" and "expansion fired" from
+ // "expansion requested + silently fell back."
+ if (isEvalCaptureEnabled(ctx.config)) {
+ const meta: HybridSearchMeta = capturedMeta ?? {
+ vector_enabled: false, detail_resolved: detail ?? null, expansion_applied: false,
+ };
+ void captureEvalCandidate(
+ ctx.engine,
+ {
+ tool_name: 'query',
+ query: queryText,
+ results,
+ meta,
+ latency_ms,
+ remote: ctx.remote ?? false,
+ expand_enabled: expand,
+ detail: detail ?? null,
+ job_id: ctx.jobId ?? null,
+ subagent_id: ctx.subagentId ?? null,
+ },
+ { scrub_pii: isEvalScrubEnabled(ctx.config) },
+ );
+ }
+
+ // WP2/D3: query never nudges toward itself — no concept hint here.
+ ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta));
+ return results;
+ },
+ scope: 'read',
+ cliHints: { name: 'query', positional: ['query'] },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const searchOperations: Operation[] = [search, query];
diff --git a/src/core/ops/skillopt.ts b/src/core/ops/skillopt.ts
new file mode 100644
index 0000000000..45a16e73df
--- /dev/null
+++ b/src/core/ops/skillopt.ts
@@ -0,0 +1,247 @@
+/**
+ * Onboard + SkillOpt operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 3): the v0.41.18.0 run_onboard remediation op and the
+ * v0.41.20.0 run_skillopt optimization op (adjacent slots at the tail of the
+ * canonical array). Op consts stay module-private; `skilloptOperations`
+ * below lists them in EXACTLY the order they appear in the canonical
+ * `operations` array in ../operations.ts. Never import from
+ * '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
+
+// v0.41.18.0 (A7 + T16, codex finding #5): MCP op for federated / thin-client
+// brain installs to drive `gbrain onboard --auto` over MCP. Admin scope
+// (NOT localOnly) so remote agents authenticated via OAuth can probe
+// brain health + submit auto-eligible remediation handlers.
+//
+// Critical security gate (codex #5): admin scope alone is NOT sufficient
+// to submit handlers in PROTECTED_JOB_NAMES (synthesize, patterns,
+// consolidate, extract-takes-from-pages, contextual_reindex_per_chunk).
+// Without this gate, an admin-scoped OAuth token would bypass the same
+// guard that `submit_job` enforces. The new NAMED scope
+// `run_protected_onboard` MUST be granted IN ADDITION TO admin for any
+// protected child handler to fire.
+//
+// Behavior:
+// - mode='check' (default): returns the OnboardReport JSON envelope,
+// never submits jobs. Admin scope sufficient.
+// - mode='auto': submits auto_apply tier. Admin + non-protected
+// handlers only.
+// - mode='auto-with-prompt': submits auto_apply + prompt_required tier.
+// Same protection check.
+//
+// Any LLM-bearing handler the plan would have submitted gets filtered out
+// unless the caller has run_protected_onboard. Filtered items appear in
+// the response with status='skipped_missing_scope' so the caller knows
+// what they would have gotten with the right grants.
+const run_onboard: Operation = {
+ name: 'run_onboard',
+ description: 'Probe brain health + optionally submit onboard remediations. Admin scope required. Protected handlers (LLM-bearing) require run_protected_onboard scope ADDITIONALLY.',
+ params: {
+ mode: { type: 'string', description: "'check' (default), 'auto', or 'auto-with-prompt'" },
+ target_score: { type: 'number', description: 'Target brain_score (default 90)' },
+ max_usd: { type: 'number', description: 'USD cap for autopilot path (required for auto modes)' },
+ },
+ mutating: true,
+ scope: 'admin',
+ handler: async (ctx, p) => {
+ const mode = (typeof p.mode === 'string' ? p.mode : 'check') as 'check' | 'auto' | 'auto-with-prompt';
+ const targetScore = typeof p.target_score === 'number' ? p.target_score : 90;
+ const maxUsd = typeof p.max_usd === 'number' ? p.max_usd : undefined;
+
+ const { computeRemediationPlan, runRemediation } = await import('../remediation/index.ts');
+ const { runAllOnboardChecks } = await import('../onboard/checks.ts');
+ const { buildOnboardReport } = await import('../onboard/render.ts');
+
+ // Per A26: source-scope via sourceScopeOpts(ctx). The recommendation
+ // planner is brain-wide today; future extension can scope by reading
+ // ctx.sourceId / ctx.auth.allowedSources for per-source plans.
+
+ let extraRemediations: import('../remediation-step.ts').RemediationStep[] = [];
+ try {
+ const checkResults = await runAllOnboardChecks(ctx.engine);
+ extraRemediations = checkResults.flatMap((r) => r.remediations);
+ } catch {
+ // Fail-open per A19 — return plan without extras rather than error.
+ }
+
+ // 'check' mode: just return the plan + JSON envelope. No submission.
+ if (mode === 'check') {
+ const plan = await computeRemediationPlan(ctx.engine, { targetScore, extraRemediations });
+ const report = buildOnboardReport(plan);
+ return report;
+ }
+
+ // 'auto' and 'auto-with-prompt' modes: require --max-usd per A12 + A20
+ // safety posture (cron-safety; refuses surprise spend).
+ if (maxUsd === undefined) {
+ throw new OperationError('invalid_params', `mode='${mode}' requires max_usd (cron-safety cap)`);
+ }
+
+ // Critical T16 + codex #5 security gate: filter out PROTECTED_JOB_NAMES
+ // unless the caller has the run_protected_onboard scope IN ADDITION
+ // to admin. Admin alone is insufficient.
+ const grantedScopes = ctx.auth?.scopes ?? [];
+ const canRunProtected = grantedScopes.includes('run_protected_onboard');
+ const { isProtectedJobName } = await import('../minions/protected-names.ts');
+
+ const skippedMissingScope: Array<{ id: string; job: string; reason: string }> = [];
+ const allowedExtras = extraRemediations.filter((r) => {
+ if (canRunProtected) return true;
+ if (isProtectedJobName(r.job)) {
+ skippedMissingScope.push({ id: r.id, job: r.job, reason: 'requires run_protected_onboard scope' });
+ return false;
+ }
+ return true;
+ });
+
+ // Run remediation with filtered extras. Hooks emit nothing — MCP
+ // returns structured result. Per A23 client_id attribution: stamp
+ // job.data.client_id on each submission so the spend chain (T10)
+ // attributes correctly. The library doesn't do this today; the
+ // upstream submit-side gating in submit_job filters protected names
+ // for ctx.remote !== false callers, so even if MCP run_onboard had a
+ // typo, the underlying queue.add would reject. Defense-in-depth.
+ const result = await runRemediation(
+ ctx.engine,
+ { targetScore, maxUsd, extraRemediations: allowedExtras },
+ {},
+ );
+
+ return {
+ ...result,
+ skipped_missing_scope: skippedMissingScope,
+ };
+ },
+};
+
+// v0.41.20.0 SkillOpt — MCP exposure (admin scope + per-skill allowlist
+// via `skillopt.allowed_skills` config, DEFAULT DENY-ALL for remote
+// callers; CLI bypasses via ctx.remote === false). Designed for trusted
+// admin tokens that want to drive optimization remotely; the same trust
+// gates as the CLI fire (working tree, install path, lock acquisition,
+// bundled-skill guard). NOT localOnly so admin HTTP MCP clients can invoke.
+const run_skillopt: Operation = {
+ name: 'run_skillopt',
+ description: 'Run SkillOpt against a single skill. Admin scope; mutating; rate-limited per-skill via DB lock. See gbrain skillopt CLI for the full flag surface.',
+ params: {
+ skill_name: { type: 'string', required: true, description: 'Kebab-case skill name (resolves to skills/<name>/SKILL.md)' },
+ benchmark_path: { type: 'string', description: 'Absolute path to benchmark JSONL; defaults to skills/<name>/skillopt-benchmark.jsonl' },
+ epochs: { type: 'number', description: 'Default 4' },
+ batch_size: { type: 'number', description: 'Default 8' },
+ lr: { type: 'number', description: 'Default 4' },
+ max_cost_usd: { type: 'number', description: 'Default 5.00' },
+ no_mutate: { type: 'boolean', description: 'Write proposed.md without replacing SKILL.md' },
+ allow_mutate_bundled: { type: 'boolean', description: 'Required to mutate bundled skills' },
+ held_out_path: { type: 'string', description: 'Path to a held-out test set (JSONL). REQUIRED (>=5 rows) to mutate a bundled skill in place — otherwise the run hard-refuses. Remote callers: must resolve within the skills directory.' },
+ dry_run: { type: 'boolean', description: 'Cost preview, no LLM calls' },
+ },
+ mutating: true,
+ scope: 'admin',
+ localOnly: false,
+ handler: async (ctx, p) => {
+ // SECURITY: skill_name is joined into filesystem paths (SKILL.md, default
+ // benchmark, checkpoint, history, best.md, proposed.md). A traversal-shaped
+ // name (`../`, absolute) would escape the skills dir even WITH the
+ // caller-supplied-path confinement below. Validate kebab-only up front so
+ // every derived path is contained by construction. Applies to all callers.
+ const skillNameRaw = (p.skill_name as string) ?? '';
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(skillNameRaw)) {
+ throw new OperationError(`run_skillopt: skill_name must be kebab-case (matching ^[a-z0-9][a-z0-9-]*$); got '${skillNameRaw}'`, 'invalid_params');
+ }
+ if (ctx.remote !== false) {
+ // Remote: enforce per-skill allowlist read from config.
+ // `skillopt.allowed_skills` is a JSON-array config of skill names
+ // an admin-scoped OAuth client may target. Default DENY-ALL: when
+ // unset, MCP cannot drive skillopt on any skill.
+ const allowedRaw = await ctx.engine.getConfig('skillopt.allowed_skills');
+ let allowed: string[] = [];
+ try {
+ if (allowedRaw) allowed = JSON.parse(allowedRaw) as string[];
+ } catch { /* fall through to deny */ }
+ const skillName = (p.skill_name as string) ?? '';
+ if (!allowed.includes(skillName)) {
+ throw new OperationError(`run_skillopt: skill '${skillName}' is not in skillopt.allowed_skills allowlist (default deny-all for remote callers)`, 'permission_denied');
+ }
+ }
+ const { runSkillOpt } = await import('../skillopt/orchestrator.ts');
+ const { autoDetectSkillsDirReadOnly } = await import('../repo-root.ts');
+ const { resolveModel } = await import('../model-config.ts');
+ const detected = autoDetectSkillsDirReadOnly(process.cwd());
+ const skillsDir = detected.dir;
+ if (!skillsDir) {
+ throw new OperationError('run_skillopt: skills directory not found', 'config_error');
+ }
+ const optimizerModel = await resolveModel(ctx.engine, { tier: 'deep', fallback: 'anthropic:claude-opus-4-7' });
+ const targetModel = await resolveModel(ctx.engine, { tier: 'subagent', fallback: 'anthropic:claude-sonnet-4-6' });
+ const judgeModel = await resolveModel(ctx.engine, { tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' });
+ const skillName = p.skill_name as string;
+ const benchmarkPath = (p.benchmark_path as string) ??
+ `${skillsDir}/${skillName}/skillopt-benchmark.jsonl`;
+ const heldOutPath = p.held_out_path as string | undefined;
+ // SECURITY: remote callers must NOT be able to point benchmark/held-out at
+ // arbitrary host files (loadBenchmark → fs.readFileSync would otherwise be an
+ // arbitrary-read + existence oracle). Confine any caller-supplied path to the
+ // skills directory. Local CLI callers (ctx.remote === false) are unconfined.
+ if (ctx.remote !== false) {
+ const nodePath = await import('node:path');
+ const nodeFs = await import('node:fs');
+ const rootReal = (() => {
+ try { return nodeFs.realpathSync(skillsDir); } catch { return nodePath.resolve(skillsDir); }
+ })();
+ const confine = (label: string, candidate: string | undefined): void => {
+ if (!candidate) return;
+ const resolved = nodePath.resolve(candidate);
+ let real = resolved;
+ try {
+ real = nodeFs.realpathSync(resolved);
+ } catch {
+ // Not yet present: canonicalize the nearest existing ancestor so a
+ // legit in-dir path under a symlinked skillsDir (e.g. macOS /tmp ->
+ // /private/tmp, Conductor worktrees) isn't wrongly rejected.
+ try { real = nodePath.join(nodeFs.realpathSync(nodePath.dirname(resolved)), nodePath.basename(resolved)); }
+ catch { /* parent also missing; fall back to resolved form */ }
+ }
+ if (real !== rootReal && !real.startsWith(rootReal + nodePath.sep)) {
+ throw new OperationError(`run_skillopt: ${label} must resolve within the skills directory for remote callers`, 'permission_denied');
+ }
+ };
+ confine('benchmark_path', p.benchmark_path as string | undefined);
+ confine('held_out_path', heldOutPath);
+ }
+ const result = await runSkillOpt({
+ engine: ctx.engine,
+ skillName,
+ skillsDir,
+ benchmarkPath,
+ epochs: (p.epochs as number) ?? 4,
+ batchSize: (p.batch_size as number) ?? 8,
+ lr: (p.lr as number) ?? 4,
+ lrSchedule: 'cosine',
+ split: [4, 1, 5],
+ optimizerModel,
+ targetModel,
+ judgeModel,
+ mode: 'patch',
+ dryRun: (p.dry_run as boolean) === true,
+ noMutate: (p.no_mutate as boolean) === true,
+ allowMutateBundled: (p.allow_mutate_bundled as boolean) === true,
+ bootstrapReviewed: false,
+ ...(heldOutPath ? { heldOutPath } : {}),
+ json: true,
+ maxCostUsd: (p.max_cost_usd as number) ?? 5.0,
+ maxRuntimeMin: 30,
+ force: false,
+ });
+ return {
+ outcome: result.outcome,
+ receipt: result.receipt,
+ mutated_skill_file: result.mutatedSkillFile,
+ proposed_path: result.proposedPath,
+ };
+ },
+};
+
+export const skilloptOperations: Operation[] = [run_onboard, run_skillopt];
diff --git a/src/core/ops/skills-catalog.ts b/src/core/ops/skills-catalog.ts
new file mode 100644
index 0000000000..49b8f705b2
--- /dev/null
+++ b/src/core/ops/skills-catalog.ts
@@ -0,0 +1,257 @@
+/**
+ * Skill catalog + advisor + status-snapshot operation cluster — pure move
+ * from operations.ts (v0.46.x tranche 2). Op consts stay module-private;
+ * `skillsCatalogOperations` below lists them in EXACTLY the order they
+ * appear in the canonical `operations` array in ../operations.ts. Never
+ * import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
+import {
+ LIST_SKILLS_DESCRIPTION,
+ GET_SKILL_DESCRIPTION,
+} from '../operations-descriptions.ts';
+
+// --- PR1: skill catalog over MCP (host-repo skills for thin clients) ---
+// Both ops dynamically import ./skill-catalog.ts to avoid an import cycle
+// (skill-catalog statically imports the `operations` array for D7 tool honesty).
+// Read-scope, non-localOnly: a thin client (Codex/Perplexity/Cowork) reaches
+// these over HTTP. The host-filesystem read is gated by mcp.publish_skills +
+// path confinement — see the trust-boundary memo in skill-catalog.ts.
+
+const list_skills: Operation = {
+ name: 'list_skills',
+ description: LIST_SKILLS_DESCRIPTION,
+ publishGateKey: 'mcp.publish_skills',
+ params: {
+ section: {
+ type: 'string',
+ description: 'Optional: only skills whose routing section matches this exactly.',
+ },
+ },
+ handler: async (ctx, p) => {
+ const sc = await import('../skill-catalog.ts');
+ const publish = await sc.readMcpPublishSkills(ctx);
+ sc.assertPublishEnabled(ctx, publish);
+ const override = await sc.readMcpSkillsDir(ctx);
+ const { dir, source } = sc.resolveSkillsDir(ctx, override);
+ const section = typeof p.section === 'string' ? p.section : undefined;
+ return sc.buildSkillCatalog(ctx, dir, source, { section });
+ },
+ scope: 'read',
+ cliHints: { name: 'skills', positional: [] },
+};
+
+const get_skill: Operation = {
+ name: 'get_skill',
+ description: GET_SKILL_DESCRIPTION,
+ publishGateKey: 'mcp.publish_skills',
+ params: {
+ name: {
+ type: 'string',
+ required: true,
+ description: 'Skill name exactly as returned by list_skills (or the brain-pack skill slug when source_id is set).',
+ },
+ source_id: {
+ type: 'string',
+ description:
+ 'Optional: fetch a brain-resident pack skill from this source instead of the host catalog. ' +
+ 'Disambiguates a slug that exists on more than one source (see list_brain_skillpack).',
+ },
+ },
+ handler: async (ctx, p) => {
+ const sc = await import('../skill-catalog.ts');
+ const publish = await sc.readMcpPublishSkills(ctx);
+ sc.assertPublishEnabled(ctx, publish);
+ // Brain-resident path: when source_id is supplied, fetch the per-source pack
+ // skill (confined to that source's pack root) rather than the host catalog.
+ if (typeof p.source_id === 'string' && p.source_id.length > 0) {
+ const brl = await import('../skillpack/brain-resident-locate.ts');
+ const slug = typeof p.name === 'string' ? p.name : '';
+ return brl.getResidentSkillDetail(ctx, p.source_id, slug);
+ }
+ const override = await sc.readMcpSkillsDir(ctx);
+ const { dir } = sc.resolveSkillsDir(ctx, override);
+ const name = typeof p.name === 'string' ? p.name : '';
+ return sc.getSkillDetail(ctx, dir, name);
+ },
+ scope: 'read',
+ cliHints: { name: 'skill', positional: ['name'] },
+};
+
+const list_brain_skillpack: Operation = {
+ name: 'list_brain_skillpack',
+ description:
+ 'List brain-resident skillpacks this brain ships (per-source). Returns each pack\'s skills, ' +
+ 'one-line descriptions, the schema pack it targets + whether that matches this brain, and a ' +
+ 'git scaffold spec. Read-only; gated by mcp.publish_skills. After orienting, call this and ' +
+ 'ask the user whether to install any pack the brain offers (gbrain skillpack scaffold <spec>).',
+ publishGateKey: 'mcp.publish_skills',
+ params: {},
+ handler: async (ctx) => {
+ const sc = await import('../skill-catalog.ts');
+ const publish = await sc.readMcpPublishSkills(ctx);
+ sc.assertPublishEnabled(ctx, publish);
+ const brl = await import('../skillpack/brain-resident-locate.ts');
+ return brl.loadResidentPacksForServer(ctx);
+ },
+ scope: 'read',
+ cliHints: { name: 'brain-skillpack', positional: [] },
+};
+
+const advisor: Operation = {
+ name: 'advisor',
+ description:
+ 'Ranked, read-only "what to do next" for this brain: version drift, pending migrations, ' +
+ 'schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. Each finding has a ' +
+ 'severity, why-it-matters, and the exact fix command. Never mutates. Tell the user; ask ' +
+ 'before running any fix. Gated by mcp.publish_advisor (separate from mcp.publish_skills ' +
+ 'because diagnostics are not prose skills).',
+ publishGateKey: 'mcp.publish_advisor',
+ params: {},
+ handler: async (ctx) => {
+ // Publish gate: a remote caller needs mcp.publish_advisor=true. Local
+ // (ctx.remote === false) callers bypass — the trust boundary is the OS.
+ if (ctx.remote !== false) {
+ let enabled = false;
+ try {
+ const dbVal = await ctx.engine.getConfig('mcp.publish_advisor');
+ enabled = dbVal != null ? dbVal === 'true' : ctx.config?.mcp?.publish_advisor === true;
+ } catch {
+ enabled = ctx.config?.mcp?.publish_advisor === true;
+ }
+ if (!enabled) {
+ // Same k=v detail grammar as assertPublishEnabled (WP1): honest
+ // catalogs hide this op at list time; the throw is the backstop.
+ const err = new OperationError(
+ 'permission_denied',
+ 'The advisor is not published over MCP by the brain owner, so it is hidden from your ' +
+ 'tool catalog. Ask the owner to enable it if you need it.',
+ 'The owner can enable it with `gbrain config set mcp.publish_advisor true`.',
+ );
+ err.detail = 'config_key=mcp.publish_advisor';
+ throw err;
+ }
+ }
+ const { runAdvisor } = await import('../advisor/run.ts');
+ const { VERSION } = await import('../../version.ts');
+ // Over MCP there is no agent workspace on the server side: remote=true makes
+ // runAdvisor drop workspace-dependent collectors (A1). The op never writes
+ // history or nag state — it is strictly read-only.
+ const report = await runAdvisor({
+ engine: ctx.engine,
+ config: ctx.config,
+ version: VERSION,
+ workspace: null,
+ skillsDir: null,
+ now: new Date(),
+ remote: ctx.remote !== false,
+ });
+ return report;
+ },
+ scope: 'read',
+ // NOT localOnly — exposed over MCP (E1) behind mcp.publish_advisor.
+ // No cliHints: the CLI surface is the richer `gbrain advisor` command
+ // (commands/advisor.ts) which adds --json exit codes + --apply.
+ cliHints: { name: 'advisor', hidden: true },
+};
+
+/**
+ * v0.41.19.0 — `gbrain status` thin-client surface.
+ *
+ * Returns a snapshot of sync freshness + last cycle state for thin-client
+ * `gbrain status` callers. Per D2/D10 in the plan:
+ *
+ * - Scope: admin (NOT localOnly). The op exposes operational state
+ * including sync timestamps and cycle metadata. Locking it to admin
+ * matches the `run_doctor` posture and prevents future feature creep
+ * from quietly leaking ops state to read-scoped clients.
+ *
+ * - Payload (schema_version 2, Minions-visibility wave): `{schema_version,
+ * version, sync, cycle, queue, workers}`. `queue` (status counts +
+ * per-queue waiting depth + oldest-waiting age) and `workers`
+ * (supervisor liveness via pidfile/DB-lock + last completed job) were
+ * added so a remote submitter can see whether the lane its job ids point
+ * at is actually alive. Locks and Autopilot stay deliberately omitted —
+ * host-local concerns the thin client renders as "N/A on remote brain".
+ *
+ * - Fail-soft (amendment 26): each v2 section computes in its own
+ * try/catch and degrades to `{error: 'unavailable'}` without failing
+ * the whole snapshot.
+ *
+ * - The local CLI composes the same data plus the local-only sections
+ * directly (no MCP round-trip when running against ~/.gbrain).
+ */
+const get_status_snapshot: Operation = {
+ name: 'get_status_snapshot',
+ description: 'Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. Admin-scope.',
+ params: {},
+ handler: async (ctx) => {
+ const { buildSyncStatusReport } = await import('../../commands/sync.ts');
+ const { buildCycleSnapshot } = await import('../../commands/status.ts');
+ // Pull sources first (handles brains with zero declared sources too).
+ let sources: Array<{ id: string; name: string; local_path: string | null; config: Record<string, unknown> }> = [];
+ try {
+ const rows = await ctx.engine.executeRaw<{
+ id: string;
+ name: string;
+ local_path: string | null;
+ config: Record<string, unknown> | null;
+ }>(
+ `SELECT id, name, local_path, config FROM sources WHERE COALESCE(archived, FALSE) = FALSE ORDER BY id`,
+ );
+ sources = rows.map((r) => ({
+ id: r.id,
+ name: r.name,
+ local_path: r.local_path,
+ config: r.config ?? {},
+ }));
+ } catch {
+ // Pre-v0.26.5 brains may lack the `archived` column; degrade to all rows.
+ const rows = await ctx.engine.executeRaw<{
+ id: string;
+ name: string;
+ local_path: string | null;
+ config: Record<string, unknown> | null;
+ }>(`SELECT id, name, local_path, config FROM sources ORDER BY id`);
+ sources = rows.map((r) => ({
+ id: r.id,
+ name: r.name,
+ local_path: r.local_path,
+ config: r.config ?? {},
+ }));
+ }
+ const sync = await buildSyncStatusReport(ctx.engine, sources);
+ const cycle = await buildCycleSnapshot(ctx.engine);
+ // v2 sections, each fail-soft (amendment 26): a broken/pre-migration
+ // queue table must not take down the sync/cycle payload that v1 clients
+ // already depend on.
+ let queue: unknown;
+ try {
+ const { buildQueueCounts, buildQueueDepths } = await import('../../commands/status.ts');
+ queue = { counts: await buildQueueCounts(ctx.engine), by_queue: await buildQueueDepths(ctx.engine) };
+ } catch {
+ queue = { error: 'unavailable' as const };
+ }
+ let workers: unknown;
+ try {
+ const { buildWorkersSnapshot } = await import('../../commands/status.ts');
+ workers = await buildWorkersSnapshot(ctx.engine);
+ } catch {
+ workers = { error: 'unavailable' as const };
+ }
+ // #1984: report the brain server's version so a thin-client `gbrain status`
+ // can surface remote_version alongside its own local CLI version.
+ const { VERSION } = await import('../../version.ts');
+ return { schema_version: 2 as const, version: VERSION, sync, cycle, queue, workers };
+ },
+ scope: 'admin',
+ localOnly: false,
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const skillsCatalogOperations: Operation[] = [
+ list_skills, get_skill, list_brain_skillpack, advisor, get_status_snapshot,
+];
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
new file mode 100644
index 0000000000..e65cfaa9a6
--- /dev/null
+++ b/src/core/ops/sources.ts
@@ -0,0 +1,229 @@
+/**
+ * whoami + sources-management operation cluster — pure move from
+ * operations.ts (v0.46.x tranche 3). Op consts stay module-private;
+ * `sourcesOperations` below lists them in EXACTLY the order they appear in
+ * the canonical `operations` array in ../operations.ts. Never import from
+ * '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
+
+// --- v0.28: whoami + sources management ---
+
+const whoami: Operation = {
+ name: 'whoami',
+ description:
+ 'Introspect the calling identity. Returns one of three transport shapes: ' +
+ '{transport: "oauth", client_id, client_name, scopes, expires_at, source_id, federated_read}, ' +
+ '{transport: "legacy", token_name, scopes, expires_at: null}, or ' +
+ '{transport: "local", scopes: []}, or {transport: "stdio", scopes: []} ' +
+ 'for the auth-less stdio MCP pipe. Throws unknown_transport when the ' +
+ 'context is ambiguous (remote=true without auth and no transport marker) ' +
+ '— fail-closed posture mirroring the v0.26.9 trust-boundary contract.',
+ params: {},
+ scope: 'read',
+ handler: async (ctx) => {
+ // Trust boundary: ctx.remote === false is the trusted local CLI surface.
+ // Returning OAuth-shaped scopes here would resurrect the v0.26.9 footgun
+ // where code conditionally trusted on `scopes.includes('admin')` instead
+ // of `ctx.remote === false`. Empty scopes array forces clients to
+ // special-case `transport: 'local'` explicitly.
+ if (ctx.remote === false) {
+ return { transport: 'local', scopes: [] };
+ }
+ // #1061: stdio MCP is remote/untrusted by design but has no per-token
+ // auth (local pipe) — a known transport, not a bug. Report it instead of
+ // throwing. Empty scopes: nothing here may be used to gate anything.
+ if (!ctx.auth && ctx.transport === 'stdio') {
+ return { transport: 'stdio', scopes: [] };
+ }
+ if (!ctx.auth) {
+ throw new OperationError(
+ 'unknown_transport',
+ 'whoami called over a remote transport that did not thread ctx.auth. ' +
+ 'This is a transport bug — every remote call site must populate ctx.auth ' +
+ 'or set ctx.remote === false.',
+ );
+ }
+ // OAuth tokens have client_id starting with 'gbrain_cl_'; legacy
+ // access_tokens reuse `name` as both clientId and clientName (verifyAccessToken
+ // at oauth-provider.ts:417-430). Detect by inspecting the prefix.
+ const isOauth = ctx.auth.clientId.startsWith('gbrain_cl_');
+ if (isOauth) {
+ return {
+ transport: 'oauth',
+ client_id: ctx.auth.clientId,
+ client_name: ctx.auth.clientName ?? ctx.auth.clientId,
+ scopes: ctx.auth.scopes,
+ expires_at: ctx.auth.expiresAt ?? null,
+ // Read-only self-introspection of the token's source grants —
+ // widens nothing; absent grants serialize fail-closed (null / []).
+ source_id: ctx.auth.sourceId ?? null,
+ federated_read: ctx.auth.allowedSources ?? [],
+ };
+ }
+ return {
+ transport: 'legacy',
+ token_name: ctx.auth.clientName ?? ctx.auth.clientId,
+ scopes: ctx.auth.scopes,
+ expires_at: null,
+ };
+ },
+ cliHints: { name: 'whoami' },
+};
+
+const sources_add: Operation = {
+ name: 'sources_add',
+ description:
+ 'Register a new source. Supports either --path (existing v0.17 behavior) ' +
+ 'or --url (v0.28 federated remote-clone path: parses the URL through the ' +
+ 'SSRF gate, clones into $GBRAIN_HOME/clones/<id>/ via temp-dir + rename ' +
+ 'atomicity, and stores remote_url in sources.config). Pre-flight collision ' +
+ 'check on id; rollback on either-side failure.',
+ params: {
+ id: {
+ type: 'string',
+ required: true,
+ description: 'Source id ([a-z0-9-]{1,32}). Immutable citation key.',
+ },
+ name: { type: 'string', description: 'Display name (defaults to id).' },
+ path: { type: 'string', description: 'Local path. Mutually optional with url.' },
+ url: {
+ type: 'string',
+ description:
+ 'HTTPS git URL. Cloned into $GBRAIN_HOME/clones/<id>/. SSRF-guarded.',
+ },
+ federated: {
+ type: 'boolean',
+ description: 'true → cross-source default search. false → isolated.',
+ },
+ clone_dir: {
+ type: 'string',
+ description:
+ 'Override clone destination (only valid with url). Default: $GBRAIN_HOME/clones/<id>/.',
+ },
+ },
+ mutating: true,
+ scope: 'sources_admin',
+ handler: async (ctx, p) => {
+ const { addSource } = await import('../sources-ops.ts');
+
+ // v0.28.1 codex finding (CRITICAL + HIGH): a `sources_admin` token over
+ // HTTP MCP must not be able to plant content at arbitrary host paths.
+ //
+ // - `path` lets a remote caller register `/etc/` (or any host dir) as a
+ // "source"; later `gbrain sync --all` walks every sources.local_path,
+ // which exfiltrates host content into the brain.
+ // - `clone_dir` lets a remote caller name the destination directly;
+ // addSource's renameSync places the cloned tree there with no
+ // confinement, AND validateRepoState's degraded-state recovery later
+ // does rm -rf on src.local_path, so the same primitive doubles as
+ // arbitrary-delete.
+ //
+ // Both fields are CLI-only (the operator runs `gbrain sources add --path
+ // /home/me/notes`). For HTTP MCP, ignore overrides — clone_dir defaults
+ // to $GBRAIN_HOME/clones/<id>/ and path is rejected. Local CLI callers
+ // (ctx.remote === false, per F7b fail-closed contract) keep the override.
+ const isLocal = ctx.remote === false;
+ const remotePath = isLocal ? (p.path as string | undefined) ?? null : null;
+ const remoteCloneDir = isLocal ? (p.clone_dir as string | undefined) : undefined;
+ if (!isLocal && p.path !== undefined) {
+ throw new OperationError(
+ 'invalid_params',
+ 'sources_add: path is not honored over MCP (security confinement). ' +
+ 'Register with --url instead, or run `gbrain sources add --path ...` on the host CLI.',
+ 'Use --url to register a remote source, or run the command locally with --path.',
+ );
+ }
+
+ const row = await addSource(ctx.engine, {
+ id: p.id as string,
+ name: p.name as string | undefined,
+ localPath: remotePath,
+ remoteUrl: p.url as string | undefined,
+ federated:
+ p.federated === undefined ? null : (p.federated as boolean),
+ cloneDir: remoteCloneDir,
+ });
+ return row;
+ },
+ cliHints: { name: 'sources_add', hidden: true },
+};
+
+const sources_list: Operation = {
+ name: 'sources_list',
+ description:
+ 'List registered sources with page counts and remote_url. v0.28 surfaces ' +
+ 'the new remote_url field so a remote MCP caller can confirm a source is ' +
+ 'managed by clone+pull rather than user-supplied path.',
+ params: {
+ include_archived: { type: 'boolean', description: 'Include soft-deleted sources.' },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { listSources } = await import('../sources-ops.ts');
+ return {
+ sources: await listSources(ctx.engine, {
+ includeArchived: (p.include_archived as boolean) === true,
+ }),
+ };
+ },
+ cliHints: { name: 'sources_list', hidden: true },
+};
+
+const sources_remove: Operation = {
+ name: 'sources_remove',
+ description:
+ 'Hard-remove a source (cascades pages/chunks/embeddings). Refuses to ' +
+ 'delete the auto-managed clone dir unless its resolved path is confined ' +
+ 'under $GBRAIN_HOME/clones/ (realpath+lstat — symlink-safe). For most ' +
+ 'workflows prefer sources_archive for the soft-delete path.',
+ params: {
+ id: { type: 'string', required: true, description: "Source id to remove, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },
+ confirm_destructive: {
+ type: 'boolean',
+ description:
+ 'Required when the source has data (pages, chunks). Without it the op refuses.',
+ },
+ dry_run: { type: 'boolean', description: 'Preview impact without side effects.' },
+ keep_storage: {
+ type: 'boolean',
+ description: 'Skip clone-dir cleanup even when the source is auto-managed.',
+ },
+ },
+ mutating: true,
+ scope: 'sources_admin',
+ handler: async (ctx, p) => {
+ const { removeSource } = await import('../sources-ops.ts');
+ return removeSource(ctx.engine, {
+ id: p.id as string,
+ confirmDestructive: (p.confirm_destructive as boolean) === true,
+ dryRun: (p.dry_run as boolean) === true || ctx.dryRun,
+ keepStorage: (p.keep_storage as boolean) === true,
+ });
+ },
+ cliHints: { name: 'sources_remove', hidden: true },
+};
+
+const sources_status: Operation = {
+ name: 'sources_status',
+ description:
+ 'Per-source diagnostic. Returns clone_state ("healthy" | "missing" | ' +
+ '"not-a-dir" | "no-git" | "url-drift" | "corrupted" | "not-applicable") ' +
+ 'so a remote MCP caller can diagnose whether the on-disk clone is ' +
+ 'syncable without SSH access to the brain host.',
+ params: {
+ id: { type: 'string', required: true, description: "Source id to diagnose, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },
+ },
+ scope: 'read',
+ handler: async (ctx, p) => {
+ const { getSourceStatus } = await import('../sources-ops.ts');
+ return getSourceStatus(ctx.engine, p.id as string);
+ },
+ cliHints: { name: 'sources_status', hidden: true },
+};
+
+export const sourcesOperations: Operation[] = [
+ whoami, sources_add, sources_list, sources_remove, sources_status,
+];
diff --git a/src/core/ops/sync-status.ts b/src/core/ops/sync-status.ts
new file mode 100644
index 0000000000..f0ed29aa64
--- /dev/null
+++ b/src/core/ops/sync-status.ts
@@ -0,0 +1,46 @@
+/**
+ * Sync operation cluster — pure move from operations.ts (v0.46.x tranche 2).
+ * Op consts stay module-private; `syncStatusOperations` below lists them in
+ * EXACTLY the order they appear in the canonical `operations` array in
+ * ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+
+// --- Sync ---
+
+const sync_brain: Operation = {
+ name: 'sync_brain',
+ description: 'Sync git repo to brain (incremental)',
+ params: {
+ repo: { type: 'string', description: 'Path to git repo (optional if configured)' },
+ dry_run: { type: 'boolean', description: 'Preview changes without applying' },
+ full: { type: 'boolean', description: 'Full re-sync (ignore checkpoint)' },
+ no_pull: { type: 'boolean', description: 'Skip git pull' },
+ no_embed: { type: 'boolean', description: 'Skip embedding generation' },
+ },
+ mutating: true,
+ scope: 'admin',
+ localOnly: true,
+ handler: async (ctx, p) => {
+ const { performSync } = await import('../../commands/sync.ts');
+ // #2830: thread ctx.sourceId (D7 pattern, same as revert_version /
+ // put_page) so a no-`repo` call resolves the CALLER's sync anchor.
+ // Without it, performSync read the default source's repo_path/last_commit
+ // and silently synced against the wrong repo on multi-source brains.
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ return performSync(ctx.engine, {
+ repoPath: p.repo as string | undefined,
+ dryRun: ctx.dryRun || (p.dry_run as boolean) || false,
+ noEmbed: (p.no_embed as boolean) || false,
+ noPull: (p.no_pull as boolean) || false,
+ full: (p.full as boolean) || false,
+ ...sourceOpts,
+ });
+ },
+ cliHints: { name: 'sync', hidden: true },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const syncStatusOperations: Operation[] = [sync_brain];
diff --git a/src/core/ops/tags.ts b/src/core/ops/tags.ts
new file mode 100644
index 0000000000..3e86eda381
--- /dev/null
+++ b/src/core/ops/tags.ts
@@ -0,0 +1,72 @@
+/**
+ * Tags operation cluster — pure move from operations.ts (v0.46.x tranche 1).
+ * Op consts stay module-private; `tagsOperations` below lists them in
+ * EXACTLY the order they appear in the canonical `operations` array in
+ * ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';
+
+// --- Tags ---
+
+const add_tag: Operation = {
+ name: 'add_tag',
+ description: 'Add tag to page',
+ params: {
+ slug: { type: 'string', required: true, description: "Slug of the page to tag, e.g. 'people/alice-example'." },
+ tag: { type: 'string', required: true, description: "Tag to add — a plain string like 'founder' or 'follow-up', not a slug." },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ enforceClientSlugFence(ctx, p.slug as string, 'add_tag');
+ if (ctx.dryRun) return { dry_run: true, action: 'add_tag', slug: p.slug, tag: p.tag };
+ // v0.31.8 (D7): thread ctx.sourceId.
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ await ctx.engine.addTag(p.slug as string, p.tag as string, sourceOpts);
+ return { status: 'ok' };
+ },
+ cliHints: { name: 'tag', positional: ['slug', 'tag'] },
+};
+
+const remove_tag: Operation = {
+ name: 'remove_tag',
+ description: 'Remove tag from page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page to untag.' },
+ tag: { type: 'string', required: true, description: 'Tag to remove (exact match against the tags get_tags returns).' },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ enforceClientSlugFence(ctx, p.slug as string, 'remove_tag');
+ if (ctx.dryRun) return { dry_run: true, action: 'remove_tag', slug: p.slug, tag: p.tag };
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ await ctx.engine.removeTag(p.slug as string, p.tag as string, sourceOpts);
+ return { status: 'ok' };
+ },
+ cliHints: { name: 'untag', positional: ['slug', 'tag'] },
+};
+
+const get_tags: Operation = {
+ name: 'get_tags',
+ description: 'List tags for a page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose tags to list.' },
+ },
+ handler: async (ctx, p) => {
+ // #2200: route through sourceScopeOpts so a federated read grant
+ // (ctx.auth.allowedSources) reaches the engine, not just scalar ctx.sourceId.
+ // Was `ctx.sourceId ? {sourceId} : {}` — a federated client got '{}' →
+ // engine fell back to 'default' (functionality gap + cross-source leak).
+ const sourceOpts = sourceScopeOpts(ctx);
+ return ctx.engine.getTags(p.slug as string, sourceOpts);
+ },
+ scope: 'read',
+ cliHints: { name: 'tags', positional: ['slug'] },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const tagsOperations: Operation[] = [add_tag, remove_tag, get_tags];
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
new file mode 100644
index 0000000000..2d856aa9fc
--- /dev/null
+++ b/src/core/ops/takes.ts
@@ -0,0 +1,199 @@
+/**
+ * Takes + think operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 1). Op consts stay module-private; `takesOperations` below lists
+ * them in EXACTLY the order they appear in the canonical `operations` array
+ * in ../operations.ts. Never import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { sourceScopeOpts, thinkSourceScopeOpts } from './context.ts';
+
+// --- v0.28: Takes ---
+
+const takes_list: Operation = {
+ name: 'takes_list',
+ description: 'List takes (typed/weighted/attributed claims) filtered by holder/kind/active/etc.',
+ scope: 'read',
+ params: {
+ page_slug: { type: 'string', description: 'Filter to this page' },
+ holder: { type: 'string', description: 'Filter to this holder (world|garry|brain|<slug>)' },
+ kind: { type: 'string', description: 'Filter to this kind (fact|take|bet|hunch)' },
+ active: { type: 'boolean', description: 'Active rows only (default true)' },
+ resolved: { type: 'boolean', description: 'true → only resolved bets; false → only unresolved' },
+ sort_by: { type: 'string', description: 'weight | since_date | created_at (default created_at)' },
+ limit: { type: 'number', description: 'Max rows (default 100, cap 500)' },
+ offset: { type: 'number', description: 'Skip first N rows' },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.listTakes({
+ // #2200-class: honor federated/source scope (via the take's page.source_id).
+ ...sourceScopeOpts(ctx),
+ page_slug: p.page_slug as string | undefined,
+ holder: p.holder as string | undefined,
+ kind: p.kind as never,
+ active: p.active as boolean | undefined,
+ resolved: p.resolved as boolean | undefined,
+ sortBy: p.sort_by as never,
+ limit: p.limit as number | undefined,
+ 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,
+ });
+ },
+ cliHints: { name: 'takes-list' },
+};
+
+const takes_search: Operation = {
+ name: 'takes_search',
+ description: 'Keyword search across takes (pg_trgm similarity over claim text)',
+ scope: 'read',
+ params: {
+ query: { type: 'string', required: true, description: "Search text matched against take claim text via trigram similarity, e.g. 'valuation cap'. This is the search text param — there is no `text` param." },
+ limit: { type: 'number', description: 'Max results (default 30, cap 100)' },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.searchTakes(p.query as string, {
+ ...sourceScopeOpts(ctx),
+ limit: p.limit as number | undefined,
+ takesHoldersAllowList: ctx.takesHoldersAllowList,
+ });
+ },
+ cliHints: { name: 'takes-search', positional: ['query'] },
+};
+
+/**
+ * v0.30.0 (Slice A1): aggregate calibration scorecard. Pure SQL aggregation.
+ *
+ * Privacy (D4 fail-closed): the engine method REQUIRES the takesHoldersAllowList
+ * param. The handler threads it from the OperationContext so MCP-bound callers
+ * see only their permitted holders' aggregate counts. Local CLI callers
+ * (ctx.takesHoldersAllowList=undefined) get the full scorecard.
+ */
+const takes_scorecard: Operation = {
+ name: 'takes_scorecard',
+ description: 'Calibration scorecard for resolved bets: counts, accuracy, Brier (correct ∨ incorrect only), partial_rate.',
+ scope: 'read',
+ params: {
+ holder: { type: 'string', description: 'Filter to this holder (world|garry|brain|<slug>)' },
+ domain_prefix: { type: 'string', description: 'Slug prefix (e.g. companies/) to scope the scorecard' },
+ since: { type: 'string', description: 'Window start (YYYY-MM-DD)' },
+ until: { type: 'string', description: 'Window end (YYYY-MM-DD)' },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.getScorecard(
+ {
+ ...sourceScopeOpts(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,
+ );
+ },
+ cliHints: { name: 'takes-scorecard' },
+};
+
+/**
+ * v0.30.0 (Slice A1): calibration curve binned by stated weight. Pure SQL.
+ * Same allow-list contract as takes_scorecard.
+ */
+const takes_calibration: Operation = {
+ name: 'takes_calibration',
+ description: 'Calibration curve: resolved correct/incorrect bets binned by stated weight; observed vs predicted per bucket.',
+ scope: 'read',
+ params: {
+ holder: { type: 'string', description: 'Filter to this holder' },
+ bucket_size: { type: 'number', description: 'Bucket width in (0,1]; default 0.1' },
+ },
+ handler: async (ctx, p) => {
+ return ctx.engine.getCalibrationCurve(
+ {
+ ...sourceScopeOpts(ctx),
+ holder: p.holder as string | undefined,
+ bucketSize: p.bucket_size as number | undefined,
+ },
+ ctx.takesHoldersAllowList,
+ );
+ },
+ cliHints: { name: 'takes-calibration' },
+};
+
+const think: Operation = {
+ name: 'think',
+ description: 'Multi-hop synthesis across pages + takes + graph. Pulls relevant evidence and produces a cited answer with conflict + gap analysis.',
+ scope: 'read',
+ params: {
+ question: { type: 'string', required: true, description: 'The question to think about' },
+ anchor: { type: 'string', description: 'Pull the entity subgraph around this slug' },
+ rounds: { type: 'number', description: 'Multi-pass: 1 (default). Round-loop scaffolding is in place; gap-driven retrieval ships in v0.29.' },
+ save: { type: 'boolean', description: 'Persist a synthesis page (local-CLI only; ignored for MCP)' },
+ take: { type: 'boolean', description: 'Append a take row to the anchor page (requires anchor)' },
+ model: { type: 'string', description: 'Model override (alias or full id). Falls through models.think → models.default → GBRAIN_MODEL → opus.' },
+ since: { type: 'string', description: 'Start of temporal window (YYYY-MM-DD or YYYY-MM)' },
+ until: { type: 'string', description: 'End of temporal window' },
+ },
+ // Local CLI can persist with save/take; remote/MCP callers are forced
+ // read-only below before runThink/persistSynthesis sees those flags.
+ mutating: true,
+ handler: async (ctx, p) => {
+ const remote = ctx.remote ?? true;
+ // Codex P1 #7 + privacy: remote callers cannot persist via MCP.
+ const safeSave = remote ? false : Boolean(p.save);
+ const safeTake = remote ? false : Boolean(p.take);
+ // v0.40.2.0: thread source-scope scalars + remote flag for trajectory
+ // injection. `sourceScopeOpts(ctx)` returns the federated array (when
+ // present) OR the scalar; we pass both through to runThink which
+ // forwards to findTrajectory. CLI callers don't go through this op
+ // and get default scope + remote=false from runThink's CLI path.
+ const thinkScope = thinkSourceScopeOpts(ctx);
+ const { runThink, persistSynthesis } = await import('../think/index.ts');
+ const result = await runThink(ctx.engine, {
+ question: String(p.question),
+ anchor: p.anchor ? String(p.anchor) : undefined,
+ rounds: typeof p.rounds === 'number' ? (p.rounds as number) : undefined,
+ save: safeSave,
+ take: safeTake,
+ model: p.model ? String(p.model) : undefined,
+ // #1698 (C3): a remote caller that explicitly supplies a model gets the same
+ // hard-error-on-unresolvable behavior as the CLI (loud op error envelope),
+ // instead of silently degrading to a no-LLM stub answer. No model param →
+ // false → configured/default model keeps its graceful path.
+ modelExplicit: !!p.model,
+ since: p.since ? String(p.since) : undefined,
+ until: p.until ? String(p.until) : undefined,
+ takesHoldersAllowList: ctx.takesHoldersAllowList,
+ ...thinkScope,
+ remote: ctx.remote !== false, // fail-closed: anything not strictly false is untrusted (CLAUDE.md invariant)
+ });
+
+ // Persist if --save was passed locally
+ let savedSlug: string | undefined;
+ let evidenceInserted = 0;
+ if (safeSave) {
+ const persisted = await persistSynthesis(ctx.engine, result);
+ savedSlug = persisted.slug;
+ evidenceInserted = persisted.evidenceInserted;
+ for (const w of persisted.warnings) result.warnings.push(w);
+ }
+
+ return {
+ ...result,
+ // #1698 (#10): the persist-skip signal returns slug '' — map it (and any
+ // falsy) to null so callers never see an empty-string "slug".
+ saved_slug: savedSlug || null,
+ evidence_inserted: evidenceInserted,
+ remote_persisted_blocked: remote && (Boolean(p.save) || Boolean(p.take)),
+ };
+ },
+ cliHints: { name: 'think', positional: ['question'] },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order: the v0.28 trio
+// (takes_list, takes_search, think), then the v0.30 calibration aggregates.
+export const takesOperations: Operation[] = [
+ takes_list, takes_search, think,
+ takes_scorecard, takes_calibration,
+];
diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.ts
new file mode 100644
index 0000000000..d402767bac
--- /dev/null
+++ b/src/core/ops/timeline.ts
@@ -0,0 +1,93 @@
+/**
+ * Timeline operation cluster — pure move from operations.ts (v0.46.x
+ * tranche 1). Op consts stay module-private; `timelineOperations` below
+ * lists them in EXACTLY the order they appear in the canonical `operations`
+ * array in ../operations.ts. Never import from '../operations.ts' here
+ * (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { enforceSubagentSlugFence, enforceClientSlugFence, sourceScopeOpts } from './context.ts';
+
+// --- Timeline ---
+
+const add_timeline_entry: Operation = {
+ name: 'add_timeline_entry',
+ description: 'Add timeline entry to a page',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose timeline to append to.' },
+ date: { type: 'string', required: true, description: "Entry date, strict YYYY-MM-DD (e.g. '2026-04-03'). Timestamps and non-calendar dates are rejected." },
+ summary: { type: 'string', required: true, description: 'One-line summary of what happened on that date.' },
+ detail: { type: 'string', description: 'Longer free-text detail behind the summary.' },
+ source: { type: 'string', description: "Provenance ref for the entry, e.g. a meeting slug like 'meetings/2026-04-03' or a URL." },
+ },
+ mutating: true,
+ scope: 'write',
+ handler: async (ctx, p) => {
+ // #2778: same fail-closed slug fence as put_page. add_timeline_entry is
+ // subagent-allowlisted (brain-allowlist.ts), so timeline writes must be
+ // confined to the same namespace/allow-list as page writes. Runs before
+ // the dry-run short-circuit so preview calls surface the same rejection.
+ enforceSubagentSlugFence(ctx, p.slug as string, 'add_timeline_entry');
+ enforceClientSlugFence(ctx, p.slug as string, 'add_timeline_entry');
+ if (ctx.dryRun) return { dry_run: true, action: 'add_timeline_entry', slug: p.slug };
+ const date = p.date as string;
+ // Reject anything that isn't a strict YYYY-MM-DD with year 1900-2199 and
+ // a real calendar day. PG DATE accepts year 5874897 silently — that's a
+ // semantic bug nobody actually wants.
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
+ throw new Error(`Invalid date format "${date}" (expected YYYY-MM-DD)`);
+ }
+ const [y, m, d] = date.split('-').map(Number);
+ if (y < 1900 || y > 2199 || m < 1 || m > 12 || d < 1 || d > 31) {
+ throw new Error(`Invalid date "${date}" (year 1900-2199, month 1-12, day 1-31)`);
+ }
+ // Round-trip through Date to catch e.g. Feb 30.
+ const parsed = new Date(date);
+ if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {
+ throw new Error(`Invalid calendar date "${date}"`);
+ }
+ // v0.31.8 (D7): thread ctx.sourceId.
+ const sourceOpts = ctx.sourceId ? { sourceId: ctx.sourceId } : {};
+ await ctx.engine.addTimelineEntry(p.slug as string, { // gbrain-allow-direct-insert: add_timeline_entry MCP op is the explicit canonical surface for manual timeline entries
+ date,
+ source: (p.source as string) || '',
+ summary: p.summary as string,
+ detail: (p.detail as string) || '',
+ }, sourceOpts);
+ return { status: 'ok' };
+ },
+ cliHints: { name: 'timeline-add', positional: ['slug', 'date', 'summary'] },
+};
+
+const get_timeline: Operation = {
+ name: 'get_timeline',
+ description: 'Get timeline entries for a page, optionally filtered by date window',
+ params: {
+ slug: { type: 'string', required: true, description: 'Slug of the page whose timeline entries to return.' },
+ after: { type: 'string', description: 'Return entries on or after this date (YYYY-MM-DD)' },
+ before: { type: 'string', description: 'Return entries on or before this date (YYYY-MM-DD)' },
+ since: { type: 'string', description: 'Alias for after; accepted for agent callers' },
+ until: { type: 'string', description: 'Alias for before; accepted for agent callers' },
+ limit: { type: 'number', description: 'Maximum number of timeline entries to return' },
+ },
+ handler: async (ctx, p) => {
+ // #2200: route through sourceScopeOpts so a federated grant reaches the
+ // engine via TimelineOpts.sourceIds; scalar/unset unchanged.
+ 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;
+ return ctx.engine.getTimeline(p.slug as string, {
+ ...sourceScopeOpts(ctx),
+ ...(after ? { after } : {}),
+ ...(before ? { before } : {}),
+ ...(limit !== undefined ? { limit } : {}),
+ });
+ },
+ scope: 'read',
+ cliHints: { name: 'timeline', positional: ['slug'] },
+};
+
+
+// Ops in EXACTLY the canonical `operations` array order.
+export const timelineOperations: Operation[] = [add_timeline_entry, get_timeline];
diff --git a/src/core/ops/transcripts.ts b/src/core/ops/transcripts.ts
new file mode 100644
index 0000000000..731ec22260
--- /dev/null
+++ b/src/core/ops/transcripts.ts
@@ -0,0 +1,51 @@
+/**
+ * Recent-transcripts operation cluster — pure move from operations.ts
+ * (v0.46.x tranche 3). Op const stays module-private; `transcriptsOperations`
+ * below is spliced into the canonical `operations` array in ../operations.ts
+ * at the cluster's original position (right after the salience spread). Never
+ * import from '../operations.ts' here (cycle).
+ */
+
+import type { Operation } from './contract.ts';
+import { OperationError } from './contract.ts';
+import { GET_RECENT_TRANSCRIPTS_DESCRIPTION } from '../operations-descriptions.ts';
+
+const get_recent_transcripts: Operation = {
+ name: 'get_recent_transcripts',
+ description: GET_RECENT_TRANSCRIPTS_DESCRIPTION,
+ scope: 'read',
+ // Local-only: rejects HTTP-borne MCP traffic at tool-list time
+ // (serve-http.ts filters on `localOnly`) AND at runtime via the in-handler
+ // ctx.remote check. Defense in depth: hidden + rejected.
+ localOnly: true,
+ params: {
+ days: { type: 'number', description: 'Window in days. Default 7.' },
+ summary: {
+ type: 'boolean',
+ description: 'When true (default), return first ~300 chars per transcript. When false, full content (capped at 100 KB per file).',
+ },
+ limit: { type: 'number', description: 'Max transcripts (default 50).' },
+ },
+ handler: async (ctx, p) => {
+ // Trust gate (eng review D2 + codex C3): MCP / HTTP callers (`remote=true`)
+ // are blocked. Local CLI callers (`remote=false`) and the trusted-workspace
+ // dream cycle pass through. This op is intentionally NOT in the subagent
+ // allow-list (subagents always run with remote=true; they would always be
+ // rejected, which is a footgun if the op is visible).
+ if (ctx.remote === true) {
+ throw new OperationError(
+ 'permission_denied',
+ 'get_recent_transcripts is local-only — call via the gbrain CLI.',
+ );
+ }
+ const { listRecentTranscripts } = await import('../transcripts.ts');
+ return listRecentTranscripts(ctx.engine, {
+ days: typeof p.days === 'number' ? p.days : undefined,
+ summary: typeof p.summary === 'boolean' ? p.summary : undefined,
+ limit: typeof p.limit === 'number' ? p.limit : undefined,
+ });
+ },
+ cliHints: { name: 'transcripts', hidden: true },
+};
+
+export const transcriptsOperations: Operation[] = [get_recent_transcripts];
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 6d8a2018fc..9d04385f51 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -20,7 +20,7 @@ import type {
TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,
TakeResolution, SynthesisEvidenceInput,
TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,
- FactRow, FactKind, FactVisibility, FactInsertStatus,
+ FactRow, FactInsertStatus,
NewFact, FactListOpts, FactsHealth,
SourceRow,
} from './engine.ts';
@@ -41,10 +41,6 @@ import {
normalizeDimension,
isNovelDimension,
} from './chronicle/ontology.ts';
-import {
- resolveRecencyDecayMap,
- DEFAULT_FALLBACK,
-} from './search/recency-decay.ts';
import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';
import { runMigrations } from './migrate.ts';
import { hnswEfSearchFor } from './vector-index.ts';
@@ -79,16 +75,13 @@ import type {
DomainBankSampleOpts, CorpusSampleOpts, DomainBankRow,
EnrichCandidatesOpts, EnrichCandidate,
} from './types.ts';
-import { validateSlug, contentHash, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, takeRowToTake, takeHitRowToHit, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
-import { deriveResolutionTuple, finalizeScorecard } from './takes-resolution.ts';
-import { normalizeWeightForStorage } from './takes-fence.ts';
-import { executeRawJsonb } from './sql-query.ts';
-import { sanitizeForJsonb, buildLinkRows, buildTimelineRows, buildTakeRows } from './batch-rows.ts';
-import { GBrainError, PAGE_SORT_SQL, ENRICH_ORDER_SQL } from './types.ts';
+import { validateSlug, contentHash, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
+import { executeRawJsonb, type SqlValue } from './sql-query.ts';
+import { sanitizeForJsonb, buildLinkRows, buildTimelineRows } from './batch-rows.ts';
+import { PAGE_SORT_SQL } from './types.ts';
import { finalizeLastSeen } from './chronicle/last-seen.ts';
-import { computeAnomaliesFromBuckets } from './cycle/anomaly.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
-import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
+import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
import { unverifiedExtractionFragment } from './extraction-review.ts';
import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';
import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
@@ -102,15 +95,17 @@ import {
EmbeddingColumnNotRegisteredError,
} from './search/embedding-column.ts';
import { hasCJK, escapeLikePattern } from './cjk.ts';
+import * as factsImpl from './pglite-engine/facts.ts';
+import type { PgliteFactsDeps } from './pglite-engine/facts.ts';
+import * as takesImpl from './pglite-engine/takes.ts';
+import type { PgliteTakesDeps } from './pglite-engine/takes.ts';
+import * as codeEdgesImpl from './pglite-engine/code-edges.ts';
+import type { PgliteCodeEdgesDeps } from './pglite-engine/code-edges.ts';
+import * as salienceImpl from './pglite-engine/salience.ts';
+import type { PgliteSalienceDeps } from './pglite-engine/salience.ts';
type PGLiteDB = PGlite;
-// PGLite's parameter bridge corrupts the current engine session when a single
-// statement crosses the signed-int16 bind ceiling (32,767 parameters). Keep
-// bulk code-edge writes comfortably below it; the two edge shapes use 7 and 6
-// binds per row respectively.
-const PGLITE_EDGE_BATCH_MAX_BIND_PARAMS = 30_000;
-
// Tier 3 snapshot fast-restore. Reads a tar dump produced by
// `bun run scripts/build-pglite-snapshot.ts`. Snapshot is matched against
// the current MIGRATIONS hash via a sidecar `.version` file; on mismatch we
@@ -4744,193 +4739,32 @@ export class PGLiteEngine implements BrainEngine {
// v0.31: Hot memory — facts table operations
// ============================================================
+ // Peeled into ./pglite-engine/facts.ts (containment sprint C15): the
+ // methods below are one-line delegates over free functions with a narrow
+ // deps surface.
+
+ /** Narrow deps for the peeled facts module. */
+ private get factsDeps(): PgliteFactsDeps {
+ const self = this;
+ return { get db() { return self.db; } };
+ }
+
async insertFact(
input: NewFact,
ctx: { source_id: string; supersedeId?: number },
): Promise<{ id: number; status: FactInsertStatus }> {
- const validFrom = input.valid_from ?? new Date();
- const validUntil = input.valid_until ?? null;
- const kind = input.kind ?? 'fact';
- const visibility = input.visibility ?? 'private';
- const notability = input.notability ?? 'medium';
- const confidence = input.confidence ?? 1.0;
- const entitySlug = input.entity_slug ?? null;
- const context = input.context ?? null;
- const sourceSession = input.source_session ?? null;
- const embedding = input.embedding ?? null;
- const embeddedAt = embedding ? new Date() : null;
- const embedStr = embedding ? toPgVectorLiteral(embedding) : null;
- // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
- const claimMetric = input.claim_metric ?? null;
- const claimValue = input.claim_value ?? null;
- const claimUnit = input.claim_unit ?? null;
- const claimPeriod = input.claim_period ?? null;
-
- if (ctx.supersedeId !== undefined) {
- // Supersede flow: insert new + expire old in one txn so observers never
- // see both rows active simultaneously.
- const result = await this.db.transaction(async (tx) => {
- const ins = await tx.query<{ id: number }>(
- embedStr === null
- ? `INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
- ) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- NULL, NULL,
- $13, $14, $15, $16
- ) RETURNING id`
- : `INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
- ) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- $13::vector, $14,
- $15, $16, $17, $18
- ) RETURNING id`,
- embedStr === null
- ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, claimMetric, claimValue, claimUnit, claimPeriod]
- : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod],
- );
- const newId = ins.rows[0].id;
- await tx.query(
- `UPDATE facts SET expired_at = now(), superseded_by = $1
- WHERE id = $2 AND expired_at IS NULL`,
- [newId, ctx.supersedeId],
- );
- return newId;
- });
- return { id: result, status: 'superseded' };
- }
-
- const ins = await this.db.query<{ id: number }>(
- embedStr === null
- ? `INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
- ) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- NULL, NULL,
- $13, $14, $15, $16
- ) RETURNING id`
- : `INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
- ) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- $13::vector, $14,
- $15, $16, $17, $18
- ) RETURNING id`,
- embedStr === null
- ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, claimMetric, claimValue, claimUnit, claimPeriod]
- : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod],
- );
- return { id: ins.rows[0].id, status: 'inserted' };
+ return factsImpl.insertFact(this.factsDeps, input, ctx);
}
async expireFact(id: number, opts?: { supersededBy?: number; at?: Date }): Promise<boolean> {
- const at = opts?.at ?? new Date();
- const result = await this.db.query(
- `UPDATE facts SET expired_at = $1, superseded_by = COALESCE($2, superseded_by)
- WHERE id = $3 AND expired_at IS NULL`,
- [at, opts?.supersededBy ?? null, id],
- );
- return (result.affectedRows ?? 0) > 0;
+ return factsImpl.expireFact(this.factsDeps, id, opts);
}
async insertFacts(
rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
ctx: { source_id: string },
): Promise<{ inserted: number; ids: number[] }> {
- if (rows.length === 0) return { inserted: 0, ids: [] };
-
- // Single transaction so the v51 partial UNIQUE index can roll back the
- // whole batch on constraint violation. Per-row INSERTs (not multi-row
- // VALUES) keep the embedding-vs-no-embedding branching readable; batch
- // sizes are small (5-30 rows per page in practice) so the loop overhead
- // is negligible vs the embedding compute cost.
- const ids = await this.db.transaction(async (tx) => {
- const out: number[] = [];
- for (const input of rows) {
- const validFrom = input.valid_from ?? new Date();
- const validUntil = input.valid_until ?? null;
- const kind = input.kind ?? 'fact';
- const visibility = input.visibility ?? 'private';
- const notability = input.notability ?? 'medium';
- const confidence = input.confidence ?? 1.0;
- const entitySlug = input.entity_slug ?? null;
- const context = input.context ?? null;
- const sourceSession = input.source_session ?? null;
- const embedding = input.embedding ?? null;
- const embeddedAt = embedding ? new Date() : null;
- const embedStr = embedding ? toPgVectorLiteral(embedding) : null;
- // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
- const claimMetric = input.claim_metric ?? null;
- const claimValue = input.claim_value ?? null;
- const claimUnit = input.claim_unit ?? null;
- const claimPeriod = input.claim_period ?? null;
- // v0.40.2.0 — event_type column (Commit 1 migration v89).
- const eventType = input.event_type ?? null;
-
- // Param-positional dispatch: embedStr presence shifts the trailing
- // slots by one. Order of named slots stays stable across both
- // branches: embedded_at, row_num, source_markdown_slug,
- // claim_metric, claim_value, claim_unit, claim_period, event_type.
- const ins = await tx.query<{ id: number }>(
- embedStr === null
- ? `INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- row_num, source_markdown_slug,
- claim_metric, claim_value, claim_unit, claim_period,
- event_type
- ) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- NULL, $13,
- $14, $15,
- $16, $17, $18, $19,
- $20
- )
- ON CONFLICT (source_id, source_markdown_slug, row_num)
- WHERE row_num IS NOT NULL
- DO NOTHING
- RETURNING id`
- : `INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- row_num, source_markdown_slug,
- claim_metric, claim_value, claim_unit, claim_period,
- event_type
- ) VALUES (
- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
- $13::vector, $14,
- $15, $16,
- $17, $18, $19, $20,
- $21
- )
- ON CONFLICT (source_id, source_markdown_slug, row_num)
- WHERE row_num IS NOT NULL
- DO NOTHING
- RETURNING id`,
- embedStr === null
- ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType]
- : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType],
- );
- if (ins.rows[0]) out.push(ins.rows[0].id);
- }
- return out;
- });
- return { inserted: ids.length, ids };
+ return factsImpl.insertFacts(this.factsDeps, rows, ctx);
}
async deleteFactsForPage(
@@ -4938,31 +4772,7 @@ export class PGLiteEngine implements BrainEngine {
source_id: string,
opts?: { excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean },
): Promise<{ deleted: number }> {
- const prefixes = opts?.excludeSourcePrefixes;
- // #2646: keep soft-expired legacy rows (row_num NULL — never
- // fence-owned) so a fence reconcile can't destroy forget_fact's
- // legacy DB-only forget record.
- const expiredLegacyFilter = opts?.preserveExpiredLegacy
- ? ` AND NOT (row_num IS NULL AND expired_at IS NOT NULL)`
- : '';
- if (prefixes && prefixes.length > 0) {
- // #1928: keep rows whose `source` matches an excluded prefix (e.g.
- // `cli:` conversation facts). COALESCE so NULL/empty-source fence rows
- // stay deletable — only the explicitly-protected prefixes survive.
- const patterns = prefixes.map(p => `${p}%`);
- const result = await this.db.query(
- `DELETE FROM facts
- WHERE source_id = $1 AND source_markdown_slug = $2
- AND NOT (COALESCE(source, '') LIKE ANY($3::text[]))${expiredLegacyFilter}`,
- [source_id, slug, patterns],
- );
- return { deleted: result.affectedRows ?? 0 };
- }
- const result = await this.db.query(
- `DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2${expiredLegacyFilter}`,
- [source_id, slug],
- );
- return { deleted: result.affectedRows ?? 0 };
+ return factsImpl.deleteFactsForPage(this.factsDeps, slug, source_id, opts);
}
async listFactsByEntity(
@@ -4970,12 +4780,7 @@ export class PGLiteEngine implements BrainEngine {
entitySlug: string,
opts?: FactListOpts,
): Promise<FactRow[]> {
- return this._listFacts(source_id, {
- ...opts,
- whereClauses: [`entity_slug = $entitySlug`],
- whereParams: { entitySlug },
- order: 'valid_from DESC, id DESC',
- });
+ return factsImpl.listFactsByEntity(this.factsDeps, source_id, entitySlug, opts);
}
async listFactsSince(
@@ -4983,18 +4788,7 @@ export class PGLiteEngine implements BrainEngine {
since: Date,
opts?: FactListOpts & { entitySlug?: string },
): Promise<FactRow[]> {
- const where: string[] = [`created_at >= $since`];
- const params: Record<string, unknown> = { since };
- if (opts?.entitySlug) {
- where.push(`entity_slug = $entitySlug`);
- params.entitySlug = opts.entitySlug;
- }
- return this._listFacts(source_id, {
- ...opts,
- whereClauses: where,
- whereParams: params,
- order: 'created_at DESC, id DESC',
- });
+ return factsImpl.listFactsSince(this.factsDeps, source_id, since, opts);
}
async listFactsBySession(
@@ -5002,40 +4796,18 @@ export class PGLiteEngine implements BrainEngine {
sessionId: string,
opts?: FactListOpts,
): Promise<FactRow[]> {
- return this._listFacts(source_id, {
- ...opts,
- whereClauses: [`source_session = $sessionId`],
- whereParams: { sessionId },
- order: 'created_at DESC, id DESC',
- });
+ return factsImpl.listFactsBySession(this.factsDeps, source_id, sessionId, opts);
}
async listSupersessions(
source_id: string,
opts?: { since?: Date; limit?: number },
): Promise<FactRow[]> {
- const where: string[] = [`expired_at IS NOT NULL`, `superseded_by IS NOT NULL`];
- const params: Record<string, unknown> = {};
- if (opts?.since) {
- where.push(`expired_at >= $since`);
- params.since = opts.since;
- }
- return this._listFacts(source_id, {
- activeOnly: false,
- limit: opts?.limit,
- whereClauses: where,
- whereParams: params,
- order: 'expired_at DESC, id DESC',
- });
+ return factsImpl.listSupersessions(this.factsDeps, source_id, opts);
}
async countUnconsolidatedFacts(source_id: string): Promise<number> {
- const r = await this.db.query<{ count: number }>(
- `SELECT COUNT(*)::int AS count FROM facts
- WHERE source_id = $1 AND consolidated_at IS NULL AND expired_at IS NULL`,
- [source_id],
- );
- return Number(r.rows[0]?.count ?? 0);
+ return factsImpl.countUnconsolidatedFacts(this.factsDeps, source_id);
}
async findCandidateDuplicates(
@@ -5044,299 +4816,50 @@ export class PGLiteEngine implements BrainEngine {
factText: string,
opts?: { k?: number; embedding?: Float32Array },
): Promise<FactRow[]> {
- const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
- if (opts?.embedding) {
- // Embedding-cosine ordered candidates within the entity bucket.
- const vec = toPgVectorLiteral(opts.embedding);
- const result = await this.db.query<FactRowSqlShape>(
- `SELECT * FROM facts
- WHERE source_id = $1
- AND entity_slug = $2
- AND expired_at IS NULL
- AND embedding IS NOT NULL
- ORDER BY embedding <=> $3::vector
- LIMIT $4`,
- [source_id, entitySlug, vec, k],
- );
- return result.rows.map(rowToFact);
- }
- // Recency fallback when no embedding.
- const result = await this.db.query<FactRowSqlShape>(
- `SELECT * FROM facts
- WHERE source_id = $1
- AND entity_slug = $2
- AND expired_at IS NULL
- ORDER BY created_at DESC, id DESC
- LIMIT $3`,
- [source_id, entitySlug, k],
- );
- return result.rows.map(rowToFact);
+ return factsImpl.findCandidateDuplicates(this.factsDeps, source_id, entitySlug, factText, opts);
}
async findTrajectory(opts: import('./engine.ts').TrajectoryOpts): Promise<import('./engine.ts').TrajectoryPoint[]> {
- const limit = clampSearchLimit(opts.limit, 100, 500);
- const sinceDate = opts.since ? new Date(opts.since) : null;
- const untilDate = opts.until ? new Date(opts.until) : null;
- const metric = opts.metric ?? null;
- const kind = opts.kind ?? 'all';
- const useArray = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;
- const sourceIds = useArray ? opts.sourceIds! : null;
- const sourceId = opts.sourceId ?? 'default';
- const remoteFilter = opts.remote === true;
-
- // Build SQL dynamically. PGLite uses $N positional params; we
- // assemble the WHERE clauses + params array in tandem to keep them
- // aligned. Final shape is single SELECT, ORDER BY (valid_from, id) ASC.
- const where: string[] = [
- useArray ? `source_id = ANY($1::text[])` : `source_id = $1`,
- `entity_slug = $2`,
- `expired_at IS NULL`,
- ];
- const params: unknown[] = [useArray ? sourceIds : sourceId, opts.entitySlug];
- let p = 3;
- if (remoteFilter) {
- where.push(`visibility = 'world'`);
- }
- if (metric !== null) {
- where.push(`claim_metric = $${p}`);
- params.push(metric);
- p += 1;
- }
- // v0.40.2.0 — kind filter. 'all' (default) no-ops. 'metric' restricts
- // to typed-claim rows; 'event' restricts to event-shaped rows.
- if (kind === 'metric') {
- where.push(`claim_metric IS NOT NULL`);
- } else if (kind === 'event') {
- where.push(`event_type IS NOT NULL`);
- }
- if (sinceDate) {
- where.push(`valid_from >= $${p}`);
- params.push(sinceDate);
- p += 1;
- }
- if (untilDate) {
- where.push(`valid_from <= $${p}`);
- params.push(untilDate);
- p += 1;
- }
- params.push(limit);
- const limitPlaceholder = p;
-
- const sqlText = `
- SELECT id, valid_from,
- claim_metric, claim_value, claim_unit, claim_period,
- event_type,
- fact, source_session, source_markdown_slug,
- embedding
- FROM facts
- WHERE ${where.join(' AND ')}
- ORDER BY valid_from ASC, id ASC
- LIMIT $${limitPlaceholder}
- `;
- const result = await this.db.query<{
- id: number;
- valid_from: Date | string;
- claim_metric: string | null;
- claim_value: number | null;
- claim_unit: string | null;
- claim_period: string | null;
- event_type: string | null;
- fact: string;
- source_session: string | null;
- source_markdown_slug: string | null;
- embedding: string | number[] | Float32Array | null;
- }>(sqlText, params);
-
- return result.rows.map(r => {
- // Inline embedding parser — mirrors rowToFact() at line 3911.
- let embedding: Float32Array | null = null;
- if (r.embedding != null) {
- if (r.embedding instanceof Float32Array) embedding = r.embedding;
- else if (Array.isArray(r.embedding)) embedding = new Float32Array(r.embedding);
- else if (typeof r.embedding === 'string') {
- const trimmed = r.embedding.trim();
- const inner = trimmed.startsWith('[') ? trimmed.slice(1, -1) : trimmed;
- const parts = inner.split(',').map(s => parseFloat(s.trim())).filter(Number.isFinite);
- embedding = parts.length > 0 ? new Float32Array(parts) : null;
- }
- }
- return {
- fact_id: Number(r.id),
- valid_from: r.valid_from instanceof Date ? r.valid_from : new Date(r.valid_from),
- metric: r.claim_metric,
- value: r.claim_value === null ? null : Number(r.claim_value),
- unit: r.claim_unit,
- period: r.claim_period,
- event_type: r.event_type,
- text: r.fact,
- source_session: r.source_session,
- source_markdown_slug: r.source_markdown_slug,
- embedding,
- };
- });
+ return factsImpl.findTrajectory(this.factsDeps, opts);
}
async consolidateFact(id: number, takeId: number): Promise<void> {
- await this.db.query(
- `UPDATE facts SET consolidated_at = now(), consolidated_into = $1 WHERE id = $2`,
- [takeId, id],
- );
+ return factsImpl.consolidateFact(this.factsDeps, id, takeId);
}
async getFactsHealth(source_id: string): Promise<FactsHealth> {
- const total = await this.db.query<{
- total_active: number; total_today: number; total_week: number;
- total_expired: number; total_consolidated: number;
- }>(
- `SELECT
- COUNT(*) FILTER (WHERE expired_at IS NULL) AS total_active,
- COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '24 hours') AS total_today,
- COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '7 days') AS total_week,
- COUNT(*) FILTER (WHERE expired_at IS NOT NULL) AS total_expired,
- COUNT(*) FILTER (WHERE consolidated_at IS NOT NULL) AS total_consolidated
- FROM facts WHERE source_id = $1`,
- [source_id],
- );
- const top = await this.db.query<{ entity_slug: string; count: number }>(
- `SELECT entity_slug, COUNT(*)::int AS count
- FROM facts
- WHERE source_id = $1 AND expired_at IS NULL AND entity_slug IS NOT NULL
- GROUP BY entity_slug
- ORDER BY count DESC, entity_slug ASC
- LIMIT 5`,
- [source_id],
- );
- const r = total.rows[0] ?? {
- total_active: 0, total_today: 0, total_week: 0, total_expired: 0, total_consolidated: 0,
- };
- return {
- source_id,
- total_active: Number(r.total_active),
- total_today: Number(r.total_today),
- total_week: Number(r.total_week),
- total_expired: Number(r.total_expired),
- total_consolidated: Number(r.total_consolidated),
- top_entities: top.rows.map(t => ({ entity_slug: t.entity_slug, count: Number(t.count) })),
- };
- }
-
- /**
- * Internal helper: shared list-facts query builder.
- * Supports source_id always, plus arbitrary additional WHERE clauses.
- */
- private async _listFacts(
- source_id: string,
- opts: FactListOpts & {
- whereClauses?: string[];
- whereParams?: Record<string, unknown>;
- order: string;
- },
- ): Promise<FactRow[]> {
- const limit = clampSearchLimit(opts.limit, 50, MAX_SEARCH_LIMIT);
- const offset = Math.max(0, opts.offset ?? 0);
- const whereParts: string[] = [`source_id = $source_id`];
- const params: Record<string, unknown> = { source_id };
- if (opts.activeOnly !== false) {
- whereParts.push(`expired_at IS NULL`);
- }
- if (opts.kinds && opts.kinds.length > 0) {
- whereParts.push(`kind = ANY($kinds)`);
- params.kinds = opts.kinds;
- }
- if (opts.visibility && opts.visibility.length > 0) {
- whereParts.push(`visibility = ANY($visibility)`);
- params.visibility = opts.visibility;
- }
- for (const c of opts.whereClauses ?? []) whereParts.push(c);
- Object.assign(params, opts.whereParams ?? {});
-
- // Convert $name placeholders to numbered $1, $2, ... for PGLite.
- const orderedKeys = Object.keys(params);
- const indexFor = (name: string): number => orderedKeys.indexOf(name) + 1;
- const sql = `SELECT * FROM facts
- WHERE ${whereParts.join(' AND ').replace(/\$(\w+)/g, (_m, k) => `$${indexFor(k)}`)}
- ORDER BY ${opts.order}
- LIMIT ${limit} OFFSET ${offset}`;
- const result = await this.db.query<FactRowSqlShape>(sql, orderedKeys.map(k => params[k]));
- return result.rows.map(rowToFact);
+ return factsImpl.getFactsHealth(this.factsDeps, source_id);
}
// ============================================================
// v0.28: Takes (typed/weighted/attributed claims) + synthesis_evidence
// ============================================================
+ // Peeled into ./pglite-engine/takes.ts (containment sprint C15).
+
+ /** Narrow deps for the peeled takes module. */
+ private get takesDeps(): PgliteTakesDeps {
+ const self = this;
+ return {
+ get db() { return self.db; },
+ batchRetry: <T>(auditSite: BatchAuditSite, signal: AbortSignal | undefined, fn: () => Promise<T>, batchSize: number) =>
+ self.batchRetry(auditSite, signal, fn, batchSize),
+ executeRawJsonb: <R = Record<string, unknown>>(sqlText: string, scalarParams: SqlValue[], jsonbParams: unknown[]) =>
+ executeRawJsonb<R>(self, sqlText, scalarParams, jsonbParams),
+ };
+ }
+
async addTakesBatch(rowsIn: TakeBatchInput[], opts?: BatchOpts): Promise<number> {
- if (rowsIn.length === 0) return 0;
- // v0.42.26: wrap in batchRetry to match links/timeline (takes was the only
- // batch primitive without retry resilience).
- return this.batchRetry(opts?.auditSite ?? 'addTakesBatch', opts?.signal, () => this._addTakesBatchOnce(rowsIn), rowsIn.length);
- }
-
- private async _addTakesBatchOnce(rowsIn: TakeBatchInput[]): Promise<number> {
- // #1861: JSONB jsonb_to_recordset instead of unnest(${arr}::text[]). Mirrors
- // PostgresEngine: `claim` is free LLM prose (array-literal crash hazard);
- // native recordset types + JSON-native numbers/booleans retire the per-engine
- // element-type casts. Weight clamp/round + NUL strip live in buildTakeRows.
- // ON CONFLICT DO UPDATE — intra-batch dup (page_id, row_num) errors, same as
- // the pre-#1861 unnest path.
- const { rows, weightClamped } = buildTakeRows(rowsIn);
- if (weightClamped > 0) {
- process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: ${weightClamped} row(s) had weight outside [0,1]; clamped\n`);
- }
- const result = await executeRawJsonb(
- this,
- `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active)
- SELECT v.page_id, v.row_num, v.claim, v.kind, v.holder, v.weight,
- v.since_date, v.until_date, v.source, v.superseded_by, v.active
- FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(
- page_id int, row_num int, claim text, kind text, holder text, weight real,
- since_date text, until_date text, source text, superseded_by int, active boolean
- )
- ON CONFLICT (page_id, row_num) DO UPDATE SET
- claim = EXCLUDED.claim,
- kind = EXCLUDED.kind,
- holder = EXCLUDED.holder,
- weight = EXCLUDED.weight,
- since_date = EXCLUDED.since_date,
- until_date = EXCLUDED.until_date,
- source = EXCLUDED.source,
- superseded_by = EXCLUDED.superseded_by,
- active = EXCLUDED.active,
- updated_at = now()
- RETURNING 1`,
- [],
- [{ rows }],
- );
- return result.length;
+ return takesImpl.addTakesBatch(this.takesDeps, rowsIn, opts);
}
- /** v0.32.6 P1 — batched per-page active-takes fetch for the contradiction probe. */
async listActiveTakesForPages(
pageIds: number[],
opts: { takesHoldersAllowList?: string[] } = {},
): Promise<Map<number, Take[]>> {
- const out = new Map<number, Take[]>();
- for (const pid of pageIds) out.set(pid, []);
- if (pageIds.length === 0) return out;
- const { rows } = await this.db.query(
- `SELECT t.*, p.slug AS page_slug
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.page_id = ANY($1::int[])
- AND t.active = true
- AND ($2::text[] IS NULL OR t.holder = ANY($2::text[]))
- ORDER BY t.page_id, t.row_num`,
- [pageIds, opts.takesHoldersAllowList ?? null]
- );
- for (const r of rows) {
- const take = takeRowToTake(r as Record<string, unknown>);
- const bucket = out.get(take.page_id);
- if (bucket) bucket.push(take);
- }
- return out;
+ return takesImpl.listActiveTakesForPages(this.takesDeps, pageIds, opts);
}
- /** v0.32.6 M5 — persist a probe run row. Idempotent on run_id. */
async writeContradictionsRun(row: {
run_id: string;
judge_model: string;
@@ -5352,33 +4875,9 @@ export class PGLiteEngine implements BrainEngine {
source_tier_breakdown: Record<string, unknown>;
report_json: Record<string, unknown>;
}): Promise<boolean> {
- const result = await this.db.query(
- `INSERT INTO eval_contradictions_runs (
- run_id, judge_model, prompt_version,
- queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
- wilson_ci_lower, wilson_ci_upper, judge_errors_total,
- cost_usd_total, duration_ms,
- source_tier_breakdown, report_json
- ) VALUES (
- $1, $2, $3,
- $4, $5, $6,
- $7, $8, $9,
- $10, $11,
- $12::jsonb, $13::jsonb
- )
- ON CONFLICT (run_id) DO NOTHING`,
- [
- row.run_id, row.judge_model, row.prompt_version,
- row.queries_evaluated, row.queries_with_contradiction, row.total_contradictions_flagged,
- row.wilson_ci_lower, row.wilson_ci_upper, row.judge_errors_total,
- row.cost_usd_total, row.duration_ms,
- row.source_tier_breakdown, row.report_json,
- ]
- );
- return (result.affectedRows ?? 0) > 0;
+ return takesImpl.writeContradictionsRun(this.takesDeps, row);
}
- /** v0.32.6 M5 — read probe runs from the last N days. */
async loadContradictionsTrend(days: number): Promise<Array<{
run_id: string;
ran_at: string;
@@ -5394,36 +4893,9 @@ export class PGLiteEngine implements BrainEngine {
source_tier_breakdown: Record<string, unknown>;
report_json: Record<string, unknown>;
}>> {
- const cutoff = new Date(Date.now() - Math.max(0, days) * 86400000);
- const { rows } = await this.db.query(
- `SELECT run_id, ran_at, judge_model,
- queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
- wilson_ci_lower, wilson_ci_upper, judge_errors_total,
- cost_usd_total, duration_ms,
- source_tier_breakdown, report_json
- FROM eval_contradictions_runs
- WHERE ran_at >= $1
- ORDER BY ran_at DESC`,
- [cutoff]
- );
- return (rows as Record<string, unknown>[]).map((r) => ({
- run_id: r.run_id as string,
- ran_at: r.ran_at instanceof Date ? (r.ran_at as Date).toISOString() : String(r.ran_at),
- judge_model: r.judge_model as string,
- queries_evaluated: Number(r.queries_evaluated),
- queries_with_contradiction: Number(r.queries_with_contradiction),
- total_contradictions_flagged: Number(r.total_contradictions_flagged),
- wilson_ci_lower: Number(r.wilson_ci_lower),
- wilson_ci_upper: Number(r.wilson_ci_upper),
- judge_errors_total: Number(r.judge_errors_total),
- cost_usd_total: Number(r.cost_usd_total),
- duration_ms: Number(r.duration_ms),
- source_tier_breakdown: r.source_tier_breakdown as Record<string, unknown>,
- report_json: r.report_json as Record<string, unknown>,
- }));
+ return takesImpl.loadContradictionsTrend(this.takesDeps, days);
}
- /** v0.32.6 P2 — cache lookup; returns verdict JSON or null. */
async getContradictionCacheEntry(key: {
chunk_a_hash: string;
chunk_b_hash: string;
@@ -5431,22 +4903,9 @@ export class PGLiteEngine implements BrainEngine {
prompt_version: string;
truncation_policy: string;
}): Promise<Record<string, unknown> | null> {
- const { rows } = await this.db.query(
- `SELECT verdict FROM eval_contradictions_cache
- WHERE chunk_a_hash = $1
- AND chunk_b_hash = $2
- AND model_id = $3
- AND prompt_version = $4
- AND truncation_policy = $5
- AND expires_at > now()
- LIMIT 1`,
- [key.chunk_a_hash, key.chunk_b_hash, key.model_id, key.prompt_version, key.truncation_policy]
- );
- if (rows.length === 0) return null;
- return (rows[0] as Record<string, unknown>).verdict as Record<string, unknown>;
+ return takesImpl.getContradictionCacheEntry(this.takesDeps, key);
}
- /** v0.32.6 P2 — cache upsert with TTL refresh on conflict. */
async putContradictionCacheEntry(opts: {
chunk_a_hash: string;
chunk_b_hash: string;
@@ -5456,181 +4915,41 @@ export class PGLiteEngine implements BrainEngine {
verdict: Record<string, unknown>;
ttl_seconds?: number;
}): Promise<void> {
- const ttl = Math.max(60, opts.ttl_seconds ?? 30 * 86400);
- const expiresAt = new Date(Date.now() + ttl * 1000);
- await this.db.query(
- `INSERT INTO eval_contradictions_cache (
- chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy,
- verdict, expires_at
- ) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)
- ON CONFLICT (chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)
- DO UPDATE SET
- verdict = EXCLUDED.verdict,
- expires_at = EXCLUDED.expires_at,
- created_at = now()`,
- [
- opts.chunk_a_hash, opts.chunk_b_hash, opts.model_id,
- opts.prompt_version, opts.truncation_policy,
- opts.verdict, expiresAt,
- ]
- );
+ return takesImpl.putContradictionCacheEntry(this.takesDeps, opts);
}
- /** v0.32.6 P2 — periodic sweep of expired cache rows. */
async sweepContradictionCache(): Promise<number> {
- const result = await this.db.query(
- `DELETE FROM eval_contradictions_cache WHERE expires_at <= now()`
- );
- return result.affectedRows ?? 0;
+ return takesImpl.sweepContradictionCache(this.takesDeps);
}
async listTakes(opts: TakesListOpts = {}): Promise<Take[]> {
- const limit = clampSearchLimit(opts.limit, 100, 500);
- const offset = Math.max(0, Math.floor(opts.offset ?? 0));
- const active = opts.active ?? true;
- const sortBy = opts.sortBy ?? 'created_at';
- const { rows } = await this.db.query(
- `SELECT t.*, p.slug AS page_slug
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE 1=1
- AND ($1::int IS NULL OR t.page_id = $1::int)
- AND ($2::text IS NULL OR p.slug = $2::text)
- AND ($3::text IS NULL OR t.holder = $3::text)
- AND ($4::text IS NULL OR t.kind = $4::text)
- AND ($5::boolean IS NULL OR t.active = $5::boolean)
- AND (
- $6::boolean IS NULL
- OR ($6::boolean = true AND t.resolved_at IS NOT NULL)
- OR ($6::boolean = false AND t.resolved_at IS NULL)
- )
- 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)
- ORDER BY
- CASE WHEN $8 = 'weight' THEN t.weight END DESC NULLS LAST,
- CASE WHEN $8 = 'since_date' THEN t.since_date END DESC NULLS LAST,
- CASE WHEN $8 = 'created_at' THEN t.created_at END DESC NULLS LAST
- LIMIT $9 OFFSET $10`,
- [
- opts.page_id ?? null,
- opts.page_slug ?? null,
- opts.holder ?? null,
- opts.kind ?? null,
- active,
- opts.resolved === undefined ? null : opts.resolved,
- opts.takesHoldersAllowList ?? null,
- sortBy,
- limit,
- offset,
- // #2200-class: source scope via the take's page.source_id (array wins over scalar).
- opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null,
- opts.sourceIds && opts.sourceIds.length > 0 ? null : (opts.sourceId ?? null),
- ]
- );
- return rows.map((r) => takeRowToTake(r as Record<string, unknown>));
+ return takesImpl.listTakes(this.takesDeps, opts);
}
async searchTakes(
query: string,
opts: SearchOpts & { takesHoldersAllowList?: string[] } = {},
): Promise<TakeHit[]> {
- const limit = clampSearchLimit(opts.limit, 30, 100);
- const { rows } = await this.db.query(
- `SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
- t.claim, t.kind, t.holder, t.weight,
- word_similarity($1, t.claim)::real AS score
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.active
- AND $1 <% t.claim
- 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)
- ORDER BY score DESC, t.weight DESC
- LIMIT $3`,
- [
- query,
- opts.takesHoldersAllowList ?? null,
- limit,
- opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null,
- opts.sourceIds && opts.sourceIds.length > 0 ? null : (opts.sourceId ?? null),
- ]
- );
- // Engine parity with PostgresEngine: coerce hit rows through the shared
- // helper so both engines return the same TakeHit runtime shape (#2450).
- return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ return takesImpl.searchTakes(this.takesDeps, query, opts);
}
async searchTakesVector(
embedding: Float32Array,
opts: SearchOpts & { takesHoldersAllowList?: string[] } = {},
): Promise<TakeHit[]> {
- const limit = clampSearchLimit(opts.limit, 30, 100);
- const vec = `[${Array.from(embedding).join(',')}]`;
- const { rows } = await this.db.query(
- `SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
- t.claim, t.kind, t.holder, t.weight,
- (1 - (t.embedding <=> $1::vector))::real AS score
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.active
- AND t.embedding IS NOT NULL
- 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)
- ORDER BY t.embedding <=> $1::vector
- LIMIT $3`,
- [
- vec,
- opts.takesHoldersAllowList ?? null,
- limit,
- opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null,
- opts.sourceIds && opts.sourceIds.length > 0 ? null : (opts.sourceId ?? null),
- ]
- );
- // Engine parity with PostgresEngine: coerce hit rows through the shared
- // helper so both engines return the same TakeHit runtime shape (#2450).
- return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ return takesImpl.searchTakesVector(this.takesDeps, embedding, opts);
}
async getTakeEmbeddings(ids: number[]): Promise<Map<number, Float32Array>> {
- if (ids.length === 0) return new Map();
- const { rows } = await this.db.query(
- `SELECT id, embedding FROM takes WHERE id = ANY($1::bigint[]) AND embedding IS NOT NULL`,
- [ids]
- );
- const out = new Map<number, Float32Array>();
- for (const r of rows as Array<{ id: number; embedding: unknown }>) {
- const v = r.embedding;
- if (typeof v === 'string') {
- const trimmed = v.replace(/^\[|\]$/g, '');
- const arr = trimmed.split(',').map(parseFloat).filter(n => !Number.isNaN(n));
- out.set(Number(r.id), new Float32Array(arr));
- } else if (Array.isArray(v)) {
- out.set(Number(r.id), new Float32Array(v as number[]));
- }
- }
- return out;
+ return takesImpl.getTakeEmbeddings(this.takesDeps, ids);
}
async countStaleTakes(): Promise<number> {
- const { rows } = await this.db.query(
- `SELECT count(*)::int AS count FROM takes WHERE active AND embedding IS NULL`
- );
- return Number((rows[0] as { count?: number } | undefined)?.count ?? 0);
+ return takesImpl.countStaleTakes(this.takesDeps);
}
async listStaleTakes(): Promise<StaleTakeRow[]> {
- const { rows } = await this.db.query(
- `SELECT t.id AS take_id, p.slug AS page_slug, t.row_num, t.claim
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.active AND t.embedding IS NULL
- ORDER BY t.id
- LIMIT 100000`
- );
- return rows as unknown as StaleTakeRow[];
+ return takesImpl.listStaleTakes(this.takesDeps);
}
async updateTake(
@@ -5638,31 +4957,7 @@ export class PGLiteEngine implements BrainEngine {
rowNum: number,
fields: { weight?: number; since_date?: string; source?: string },
): Promise<void> {
- let weight = fields.weight;
- if (weight !== undefined) {
- const norm = normalizeWeightForStorage(weight);
- if (norm.clamped) {
- process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: updateTake clamped weight ${weight} → ${norm.weight}\n`);
- }
- weight = norm.weight;
- }
- const result = await this.db.query(
- `UPDATE takes SET
- weight = COALESCE($3::real, weight),
- since_date = COALESCE($4::text, since_date),
- source = COALESCE($5::text, source),
- updated_at = now()
- WHERE page_id = $1 AND row_num = $2
- RETURNING 1`,
- [pageId, rowNum, weight ?? null, fields.since_date ?? null, fields.source ?? null]
- );
- if (result.rows.length === 0) {
- throw new GBrainError(
- 'TAKE_ROW_NOT_FOUND',
- `take not found at page_id=${pageId} row=${rowNum}`,
- 'list takes for this page with `gbrain takes <slug>` to see valid row numbers',
- );
- }
+ return takesImpl.updateTake(this.takesDeps, pageId, rowNum, fields);
}
async supersedeTake(
@@ -5670,190 +4965,23 @@ export class PGLiteEngine implements BrainEngine {
oldRow: number,
newRow: Omit<TakeBatchInput, 'page_id' | 'row_num' | 'superseded_by'>,
): Promise<{ oldRow: number; newRow: number }> {
- return await this.db.transaction(async (tx) => {
- const existingRes = await tx.query(
- `SELECT resolved_at FROM takes WHERE page_id = $1 AND row_num = $2`,
- [pageId, oldRow]
- );
- const existing = existingRes.rows[0] as { resolved_at?: unknown } | undefined;
- if (!existing) {
- throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${oldRow}`, 'list takes with `gbrain takes <slug>`');
- }
- if (existing.resolved_at) {
- throw new GBrainError('TAKE_RESOLVED_IMMUTABLE', `take ${pageId}#${oldRow} is resolved`, 'resolved bets are immutable; add a new take instead');
- }
- const maxRowRes = await tx.query(
- `SELECT COALESCE(MAX(row_num), 0) + 1 AS next FROM takes WHERE page_id = $1`,
- [pageId]
- );
- const newRowNum = Number((maxRowRes.rows[0] as { next?: number })?.next ?? 1);
- const w = Math.max(0, Math.min(1, newRow.weight ?? 0.5));
- await tx.query(
- `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, active)
- VALUES ($1, $2, $3, $4, $5, $6, $7::text, $8::text, $9, $10)`,
- [
- pageId, newRowNum, newRow.claim, newRow.kind, newRow.holder, w,
- newRow.since_date ?? null, newRow.until_date ?? null, newRow.source ?? null,
- newRow.active ?? true,
- ]
- );
- await tx.query(
- `UPDATE takes SET active = false, superseded_by = $3, updated_at = now()
- WHERE page_id = $1 AND row_num = $2`,
- [pageId, oldRow, newRowNum]
- );
- return { oldRow, newRow: newRowNum };
- });
+ return takesImpl.supersedeTake(this.takesDeps, pageId, oldRow, newRow);
}
async resolveTake(pageId: number, rowNum: number, resolution: TakeResolution): Promise<void> {
- const existingRes = await this.db.query(
- `SELECT resolved_at FROM takes WHERE page_id = $1 AND row_num = $2`,
- [pageId, rowNum]
- );
- const existing = existingRes.rows[0] as { resolved_at?: unknown } | undefined;
- if (!existing) {
- throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${rowNum}`, 'list takes with `gbrain takes <slug>`');
- }
- if (existing.resolved_at) {
- throw new GBrainError('TAKE_ALREADY_RESOLVED', `take ${pageId}#${rowNum} already resolved`, 'resolution is immutable; add a new take to record a new outcome');
- }
- // v0.30.0: derive (quality, outcome) tuple. quality wins when both set.
- const { quality, outcome } = deriveResolutionTuple(resolution);
- await this.db.query(
- `UPDATE takes SET
- resolved_at = now(),
- resolved_quality = $3::text,
- resolved_outcome = $4,
- resolved_value = $5::real,
- resolved_unit = $6::text,
- resolved_source = $7::text,
- resolved_by = $8,
- updated_at = now()
- WHERE page_id = $1 AND row_num = $2`,
- [
- pageId, rowNum,
- quality,
- outcome,
- resolution.value ?? null,
- resolution.unit ?? null,
- resolution.source ?? null,
- resolution.resolvedBy,
- ]
- );
+ return takesImpl.resolveTake(this.takesDeps, pageId, rowNum, resolution);
}
- /**
- * v0.30.0: aggregate scorecard. SQL-level allow-list filter (D4 fail-closed).
- * Hidden-holder rows contribute zero to aggregates.
- */
async getScorecard(opts: TakesScorecardOpts, allowList: string[] | undefined): Promise<TakesScorecard> {
- // Build the WHERE clause with positional params. PGLite (postgres-via-WASM)
- // shares the SQL dialect with real Postgres so the math expressions match.
- const params: unknown[] = [];
- const clauses: string[] = [];
- if (opts.holder !== undefined) { params.push(opts.holder); clauses.push(`AND holder = $${params.length}`); }
- if (opts.domainPrefix !== undefined) {
- params.push(opts.domainPrefix + '%');
- clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.slug LIKE $${params.length})`);
- }
- if (opts.since !== undefined) { params.push(opts.since); clauses.push(`AND since_date >= $${params.length}`); }
- if (opts.until !== undefined) { params.push(opts.until); clauses.push(`AND since_date <= $${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).
- const srcIds = opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null;
- if (srcIds) { params.push(srcIds); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($${params.length}::text[]))`); }
- else if (opts.sourceId) { params.push(opts.sourceId); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = $${params.length})`); }
- const where = clauses.join(' ');
- // v0.36.1.1 T1c: `resolved` deliberately filters to the 3-state subset
- // (correct|incorrect|partial) — NOT `resolved_quality IS NOT NULL` — so
- // historical comparisons against pre-v74 scorecards stay valid.
- // `unresolvable_count` is a sibling field counting the new 4th state.
- const res = await this.db.query(
- `SELECT
- COUNT(*) FILTER (WHERE kind = 'bet')::int AS total_bets,
- COUNT(*) FILTER (WHERE resolved_quality IN ('correct','incorrect','partial'))::int AS resolved,
- COUNT(*) FILTER (WHERE resolved_quality = 'correct')::int AS correct,
- COUNT(*) FILTER (WHERE resolved_quality = 'incorrect')::int AS incorrect,
- COUNT(*) FILTER (WHERE resolved_quality = 'partial')::int AS partial,
- COUNT(*) FILTER (WHERE resolved_quality = 'unresolvable')::int AS unresolvable_count,
- AVG(
- CASE WHEN resolved_quality IN ('correct','incorrect')
- THEN POWER(weight - (CASE resolved_quality WHEN 'correct' THEN 1 ELSE 0 END), 2)
- END
- )::float AS brier
- FROM takes
- WHERE 1=1 ${where}`,
- params,
- );
- const r = res.rows[0] as { total_bets: number; resolved: number; correct: number; incorrect: number; partial: number; unresolvable_count: number; brier: number | null };
- return finalizeScorecard(r);
+ return takesImpl.getScorecard(this.takesDeps, opts, allowList);
}
- /**
- * v0.30.0: calibration curve. Bins resolved correct/incorrect bets by stated weight.
- */
async getCalibrationCurve(opts: CalibrationCurveOpts, allowList: string[] | undefined): Promise<CalibrationBucket[]> {
- const bucketSize = opts.bucketSize && opts.bucketSize > 0 && opts.bucketSize <= 1 ? opts.bucketSize : 0.1;
- const maxIdx = Math.floor(1 / bucketSize) - 1;
- const params: unknown[] = [bucketSize, maxIdx];
- const clauses: string[] = [];
- 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).
- const srcIds = opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null;
- if (srcIds) { params.push(srcIds); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($${params.length}::text[]))`); }
- else if (opts.sourceId) { params.push(opts.sourceId); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = $${params.length})`); }
- const where = clauses.join(' ');
- // NUMERIC casts for exact decimal arithmetic — keeps PGLite + Postgres
- // bucket boundaries identical at FP-edge weights (e.g. 0.7/0.1).
- // See parity test in test/e2e/takes-scorecard-parity.test.ts.
- const res = await this.db.query(
- `WITH binned AS (
- SELECT
- LEAST(FLOOR(weight::numeric / $1::numeric)::int, $2::int)::int AS bucket_idx,
- weight,
- (resolved_quality = 'correct')::int AS hit
- FROM takes
- WHERE resolved_quality IN ('correct','incorrect')
- ${where}
- )
- SELECT
- (bucket_idx::numeric * $1::numeric)::float AS bucket_lo,
- ((bucket_idx + 1)::numeric * $1::numeric)::float AS bucket_hi,
- COUNT(*)::int AS n,
- AVG(hit)::float AS observed,
- AVG(weight)::float AS predicted
- FROM binned
- GROUP BY bucket_idx
- ORDER BY bucket_idx`,
- params,
- );
- return (res.rows as { bucket_lo: number; bucket_hi: number; n: number; observed: number | null; predicted: number | null }[]).map(r => ({
- bucket_lo: r.bucket_lo,
- bucket_hi: r.bucket_hi,
- n: r.n,
- observed: r.n > 0 ? r.observed : null,
- predicted: r.n > 0 ? r.predicted : null,
- }));
+ return takesImpl.getCalibrationCurve(this.takesDeps, opts, allowList);
}
async addSynthesisEvidence(rowsIn: SynthesisEvidenceInput[]): Promise<number> {
- if (rowsIn.length === 0) return 0;
- const synthesisIds = rowsIn.map(r => r.synthesis_page_id);
- const takePageIds = rowsIn.map(r => r.take_page_id);
- const takeRowNums = rowsIn.map(r => r.take_row_num);
- const citationIxs = rowsIn.map(r => r.citation_index);
- const result = await this.db.query(
- `INSERT INTO synthesis_evidence (synthesis_page_id, take_page_id, take_row_num, citation_index)
- SELECT v.synthesis_page_id::int, v.take_page_id::int, v.take_row_num::int, v.citation_index::int
- FROM unnest($1::int[], $2::int[], $3::int[], $4::int[])
- AS v(synthesis_page_id, take_page_id, take_row_num, citation_index)
- ON CONFLICT (synthesis_page_id, take_page_id, take_row_num) DO NOTHING
- RETURNING 1`,
- [synthesisIds, takePageIds, takeRowNums, citationIxs]
- );
- return result.rows.length;
+ return takesImpl.addSynthesisEvidence(this.takesDeps, rowsIn);
}
// Versions
@@ -6332,166 +5460,41 @@ export class PGLiteEngine implements BrainEngine {
// per-lang tree-sitter queries land in Layer 5/6.
// ============================================================
+ // Peeled into ./pglite-engine/code-edges.ts (containment sprint C15).
+
+ /** Narrow deps for the peeled code-edges module. */
+ private get codeEdgesDeps(): PgliteCodeEdgesDeps {
+ const self = this;
+ return { get db() { return self.db; } };
+ }
+
async addCodeEdges(edges: import('./types.ts').CodeEdgeInput[]): Promise<number> {
- if (edges.length === 0) return 0;
- let inserted = 0;
- // Split into resolved vs unresolved. Resolved rows carry to_chunk_id
- // (known target chunk); unresolved rows only know the qualified name.
- const resolved = edges.filter(e => e.to_chunk_id != null);
- const unresolved = edges.filter(e => e.to_chunk_id == null);
-
- const resolvedBatchSize = Math.floor(PGLITE_EDGE_BATCH_MAX_BIND_PARAMS / 7);
- for (let offset = 0; offset < resolved.length; offset += resolvedBatchSize) {
- const batch = resolved.slice(offset, offset + resolvedBatchSize);
- const rowParts: string[] = [];
- const params: unknown[] = [];
- let p = 1;
- for (const e of batch) {
- rowParts.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}::jsonb, $${p++})`);
- params.push(
- e.from_chunk_id, e.to_chunk_id, e.from_symbol_qualified,
- e.to_symbol_qualified, e.edge_type,
- JSON.stringify(e.edge_metadata ?? {}),
- e.source_id ?? 'default',
- );
- }
- const res = await this.db.query(
- `INSERT INTO code_edges_chunk
- (from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
- VALUES ${rowParts.join(', ')}
- ON CONFLICT (from_chunk_id, to_chunk_id, edge_type) DO NOTHING`,
- params,
- );
- inserted += res.affectedRows ?? 0;
- }
-
- const unresolvedBatchSize = Math.floor(PGLITE_EDGE_BATCH_MAX_BIND_PARAMS / 6);
- for (let offset = 0; offset < unresolved.length; offset += unresolvedBatchSize) {
- const batch = unresolved.slice(offset, offset + unresolvedBatchSize);
- const rowParts: string[] = [];
- const params: unknown[] = [];
- let p = 1;
- for (const e of batch) {
- rowParts.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++}::jsonb, $${p++})`);
- params.push(
- e.from_chunk_id, e.from_symbol_qualified, e.to_symbol_qualified, e.edge_type,
- JSON.stringify(e.edge_metadata ?? {}),
- e.source_id ?? 'default',
- );
- }
- const res = await this.db.query(
- `INSERT INTO code_edges_symbol
- (from_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
- VALUES ${rowParts.join(', ')}
- ON CONFLICT (from_chunk_id, to_symbol_qualified, edge_type) DO NOTHING`,
- params,
- );
- inserted += res.affectedRows ?? 0;
- }
- return inserted;
+ return codeEdgesImpl.addCodeEdges(this.codeEdgesDeps, edges);
}
async deleteCodeEdgesForChunks(chunkIds: number[]): Promise<void> {
- if (chunkIds.length === 0) return;
- // Both directions on code_edges_chunk; from-only on code_edges_symbol
- // (unresolved edges don't have a to_chunk_id to match against).
- await this.db.query(
- `DELETE FROM code_edges_chunk WHERE from_chunk_id = ANY($1::int[]) OR to_chunk_id = ANY($1::int[])`,
- [chunkIds],
- );
- await this.db.query(
- `DELETE FROM code_edges_symbol WHERE from_chunk_id = ANY($1::int[])`,
- [chunkIds],
- );
+ return codeEdgesImpl.deleteCodeEdgesForChunks(this.codeEdgesDeps, chunkIds);
}
async getCallersOf(
qualifiedName: string,
opts?: { sourceId?: string; allSources?: boolean; limit?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
- const limit = Math.min(opts?.limit ?? 100, 500);
- const sourceClause = opts?.allSources || !opts?.sourceId
- ? ''
- : `AND source_id = '${opts.sourceId.replace(/'/g, "''")}'`;
- const { rows } = await this.db.query(
- `SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, true as resolved
- FROM code_edges_chunk
- WHERE to_symbol_qualified = $1 ${sourceClause}
- UNION ALL
- SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, false as resolved
- FROM code_edges_symbol
- WHERE to_symbol_qualified = $1 ${sourceClause}
- LIMIT $2`,
- [qualifiedName, limit],
- );
- return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
+ return codeEdgesImpl.getCallersOf(this.codeEdgesDeps, qualifiedName, opts);
}
async getCalleesOf(
qualifiedName: string,
opts?: { sourceId?: string; allSources?: boolean; limit?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
- const limit = Math.min(opts?.limit ?? 100, 500);
- const sourceClause = opts?.allSources || !opts?.sourceId
- ? ''
- : `AND source_id = '${opts.sourceId.replace(/'/g, "''")}'`;
- const { rows } = await this.db.query(
- `SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, true as resolved
- FROM code_edges_chunk
- WHERE from_symbol_qualified = $1 ${sourceClause}
- UNION ALL
- SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, false as resolved
- FROM code_edges_symbol
- WHERE from_symbol_qualified = $1 ${sourceClause}
- LIMIT $2`,
- [qualifiedName, limit],
- );
- return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
+ return codeEdgesImpl.getCalleesOf(this.codeEdgesDeps, qualifiedName, opts);
}
async getEdgesByChunk(
chunkId: number,
opts?: { direction?: 'in' | 'out' | 'both'; edgeType?: string; limit?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
- const direction = opts?.direction ?? 'both';
- const limit = Math.min(opts?.limit ?? 50, 200);
- const edgeTypeClause = opts?.edgeType ? `AND edge_type = '${opts.edgeType.replace(/'/g, "''")}'` : '';
- // Build the chunk-table filter based on direction. Unresolved edges
- // (code_edges_symbol) only carry from_chunk_id — there's no inbound
- // direction into them from a chunk ID, so we include them only when
- // direction is 'out' or 'both'.
- let chunkFilter = '';
- if (direction === 'in') chunkFilter = `WHERE to_chunk_id = $1`;
- else if (direction === 'out') chunkFilter = `WHERE from_chunk_id = $1`;
- else chunkFilter = `WHERE from_chunk_id = $1 OR to_chunk_id = $1`;
-
- let symbolFilter = '';
- if (direction === 'out' || direction === 'both') {
- symbolFilter = `WHERE from_chunk_id = $1`;
- }
-
- const unionClause = symbolFilter ? `
- UNION ALL
- SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, false as resolved
- FROM code_edges_symbol
- ${symbolFilter} ${edgeTypeClause}
- ` : '';
-
- const { rows } = await this.db.query(
- `SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, true as resolved
- FROM code_edges_chunk
- ${chunkFilter} ${edgeTypeClause}
- ${unionClause}
- LIMIT $2`,
- [chunkId, limit],
- );
- return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
+ return codeEdgesImpl.getEdgesByChunk(this.codeEdgesDeps, chunkId, opts);
}
// Eval capture (v0.25.0). See BrainEngine interface docs.
@@ -6576,409 +5579,31 @@ export class PGLiteEngine implements BrainEngine {
// v0.29 — Salience + Anomaly Detection
// ============================================================
+ // Peeled into ./pglite-engine/salience.ts (containment sprint C15).
+
+ /** Narrow deps for the peeled salience module. */
+ private get salienceDeps(): PgliteSalienceDeps {
+ const self = this;
+ return { get db() { return self.db; } };
+ }
+
async batchLoadEmotionalInputs(slugs?: string[]): Promise<EmotionalWeightInputRow[]> {
- // Two CTEs avoid the N×M cartesian product (codex C4#4).
- const baseSql = `
- WITH page_tags AS (
- SELECT page_id, array_agg(DISTINCT tag) AS tags
- FROM tags GROUP BY page_id
- ),
- page_takes AS (
- SELECT page_id, json_agg(json_build_object(
- 'holder', holder, 'weight', weight, 'kind', kind, 'active', active
- )) AS takes
- FROM takes WHERE active = TRUE GROUP BY page_id
- )
- SELECT p.slug, p.source_id,
- COALESCE(pt.tags, ARRAY[]::text[]) AS tags,
- COALESCE(pk.takes, '[]'::json) AS takes
- FROM pages p
- LEFT JOIN page_tags pt ON pt.page_id = p.id
- LEFT JOIN page_takes pk ON pk.page_id = p.id
- `;
- const { rows } = slugs
- ? await this.db.query(`${baseSql} WHERE p.slug = ANY($1::text[])`, [slugs])
- : await this.db.query(baseSql);
- return (rows as Record<string, unknown>[]).map(r => ({
- slug: String(r.slug),
- source_id: String(r.source_id),
- tags: (r.tags as string[]) ?? [],
- takes: (r.takes as EmotionalWeightInputRow['takes']) ?? [],
- }));
+ return salienceImpl.batchLoadEmotionalInputs(this.salienceDeps, slugs);
}
async setEmotionalWeightBatch(rows: EmotionalWeightWriteRow[]): Promise<number> {
- if (rows.length === 0) return 0;
- const slugs = rows.map(r => r.slug);
- const sourceIds = rows.map(r => r.source_id);
- const weights = rows.map(r => r.weight);
- // Composite-keyed UPDATE FROM unnest (codex C4#3).
- // v0.29.1: bump salience_touched_at when emotional_weight actually changes
- // so the salience query window picks up newly-salient old pages. Mirror
- // of postgres-engine.ts.
- const result = await this.db.query(
- `UPDATE pages
- SET emotional_weight = u.weight,
- salience_touched_at = CASE
- WHEN pages.emotional_weight IS DISTINCT FROM u.weight THEN now()
- ELSE pages.salience_touched_at
- END
- FROM unnest($1::text[], $2::text[], $3::real[])
- AS u(slug, source_id, weight)
- WHERE pages.slug = u.slug AND pages.source_id = u.source_id
- RETURNING 1`,
- [slugs, sourceIds, weights]
- );
- return result.rows.length;
+ return salienceImpl.setEmotionalWeightBatch(this.salienceDeps, rows);
}
async getRecentSalience(opts: SalienceOpts): Promise<SalienceResult[]> {
- const days = Math.max(0, opts.days ?? 14);
- const limit = clampSearchLimit(opts.limit, 20, 100);
- const slugPrefix = opts.slugPrefix;
- const boundaryIso = new Date(Date.now() - days * 86400000).toISOString();
-
- const params: unknown[] = [boundaryIso];
- let prefixCondition = '';
- if (slugPrefix) {
- const escaped = slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%';
- params.push(escaped);
- prefixCondition = `AND p.slug LIKE $${params.length} ESCAPE '\\'`;
- }
- // TIM-37: exclude briefing pages from their own Brain Pulse. See the
- // matching block in postgres-engine.ts getRecentSalience() for context.
- const excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))
- ? `AND p.slug NOT LIKE 'briefings/%'`
- : '';
- params.push(limit);
- const limitParam = `$${params.length}`;
-
- // v0.29.1: third score term via buildRecencyComponentSql. Default
- // 'flat' = v0.29.0 behavior. 'on' opts into per-prefix decay.
- const recencyBias = opts.recency_bias ?? 'flat';
- let recencySql: string;
- if (recencyBias === 'on') {
- recencySql = buildRecencyComponentSql({
- slugColumn: 'p.slug',
- dateExpr: 'COALESCE(p.effective_date, p.updated_at)',
- decayMap: resolveRecencyDecayMap(),
- fallback: DEFAULT_FALLBACK,
- });
- } else {
- recencySql = buildRecencyComponentSql({
- slugColumn: 'p.slug',
- dateExpr: 'p.updated_at',
- decayMap: {},
- fallback: { halflifeDays: 1, coefficient: 1.0 },
- });
- }
- const { rows } = await this.db.query(
- `SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, p.emotional_weight,
- COUNT(DISTINCT t.id) AS take_count,
- COALESCE(AVG(t.weight), 0) AS take_avg_weight,
- (p.emotional_weight * 5)
- + ln(1 + COUNT(DISTINCT t.id))
- + ${recencySql}
- AS score
- FROM 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
- ${prefixCondition}
- ${excludeBriefings}
- GROUP BY p.id
- ORDER BY score DESC
- LIMIT ${limitParam}`,
- params
- );
- return (rows as Record<string, unknown>[]).map(r => ({
- slug: String(r.slug),
- source_id: String(r.source_id),
- title: String(r.title ?? ''),
- type: r.type as SalienceResult['type'],
- updated_at: r.updated_at as Date,
- emotional_weight: Number(r.emotional_weight ?? 0),
- take_count: Number(r.take_count ?? 0),
- take_avg_weight: Number(r.take_avg_weight ?? 0),
- score: Number(r.score ?? 0),
- }));
+ return salienceImpl.getRecentSalience(this.salienceDeps, opts);
}
async listEnrichCandidates(opts: EnrichCandidatesOpts): Promise<EnrichCandidate[]> {
- // v0.41.39 (issue #1700). Parity with postgres-engine.listEnrichCandidates.
- if (!opts.types || opts.types.length === 0) return [];
- const limit = Math.max(1, Math.min(opts.limit ?? 50, 5000));
- const threshold = Math.max(0, opts.thinThreshold);
-
- const params: unknown[] = [];
- params.push(opts.types);
- const typesParam = `$${params.length}`;
- params.push(threshold);
- const thresholdParam = `$${params.length}`;
-
- const where: string[] = [
- 'p.deleted_at IS NULL',
- `p.type = ANY(${typesParam}::text[])`,
- `(char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < ${thresholdParam}`,
- ];
-
- // Source scope: array wins over scalar.
- if (opts.sourceIds && opts.sourceIds.length > 0) {
- params.push(opts.sourceIds);
- where.push(`p.source_id = ANY($${params.length}::text[])`);
- } else if (opts.sourceId) {
- params.push(opts.sourceId);
- where.push(`p.source_id = $${params.length}`);
- }
-
- // Re-enrich recency guard. Lexical text compare on the ISO `enriched_at`
- // (never cast → can't throw on a malformed value). NULL → eligible.
- const reenrichMs = opts.reenrichAfterMs ?? 0;
- if (reenrichMs > 0) {
- params.push(new Date(Date.now() - reenrichMs).toISOString());
- where.push(
- `NOT (p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $${params.length})`,
- );
- }
-
- // Exclude dream/synthesize-generated pages (parity with postgres-engine).
- where.push(`(p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true'`);
-
- const orderKey = ENRICH_ORDER_SQL[opts.order] ? opts.order : 'inbound-links';
- const orderBy = ENRICH_ORDER_SQL[orderKey];
-
- params.push(limit);
- const limitParam = `$${params.length}`;
-
- const { rows } = await this.db.query(
- `SELECT
- p.slug,
- p.source_id,
- p.title,
- p.type,
- (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len,
- COALESCE((
- SELECT COUNT(*)
- FROM links l
- WHERE l.to_page_id = p.id
- AND l.link_source IS DISTINCT FROM 'mentions'
- ), 0)::int AS inbound_count
- FROM pages p
- WHERE ${where.join(' AND ')}
- ORDER BY ${orderBy}
- LIMIT ${limitParam}`,
- params,
- );
- return (rows as Record<string, unknown>[]).map((r) => ({
- slug: String(r.slug),
- source_id: String(r.source_id),
- title: String(r.title ?? ''),
- type: r.type as EnrichCandidate['type'],
- body_len: Number(r.body_len ?? 0),
- inbound_count: Number(r.inbound_count ?? 0),
- }));
+ return salienceImpl.listEnrichCandidates(this.salienceDeps, opts);
}
async findAnomalies(opts: AnomaliesOpts): Promise<AnomalyResult[]> {
- const sigma = opts.sigma ?? 3.0;
- const lookbackDays = Math.max(1, opts.lookback_days ?? 30);
- const sinceIso = (opts.since ?? new Date().toISOString().slice(0, 10));
- const sinceDate = new Date(sinceIso + 'T00:00:00Z');
- const sinceEnd = new Date(sinceDate.getTime() + 86400000);
- const baselineStart = new Date(sinceDate.getTime() - lookbackDays * 86400000);
-
- const tagBaselineRes = await this.db.query(
- `WITH days AS (
- SELECT day::date FROM generate_series(
- $1::date, $2::date - 1, '1 day'::interval
- ) AS day
- ),
- 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
- ),
- touched AS (
- SELECT t.tag,
- date_trunc('day', p.updated_at)::date AS day,
- COUNT(DISTINCT p.id) AS cnt
- FROM tags t JOIN pages p ON p.id = t.page_id
- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
- GROUP BY 1, 2
- )
- SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
- FROM cohort_keys cd CROSS JOIN days d
- LEFT JOIN touched t ON t.tag = cd.tag AND t.day = d.day`,
- [baselineStart.toISOString(), sinceDate.toISOString()]
- );
-
- const typeBaselineRes = await this.db.query(
- `WITH days AS (
- SELECT day::date FROM generate_series(
- $1::date, $2::date - 1, '1 day'::interval
- ) AS day
- ),
- cohort_keys AS (
- SELECT DISTINCT p.type FROM pages p
- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
- ),
- touched AS (
- SELECT p.type,
- date_trunc('day', p.updated_at)::date AS day,
- COUNT(DISTINCT p.id) AS cnt
- FROM pages p
- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
- GROUP BY 1, 2
- )
- SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
- FROM cohort_keys cd CROSS JOIN days d
- LEFT JOIN touched t ON t.type = cd.type AND t.day = d.day`,
- [baselineStart.toISOString(), sinceDate.toISOString()]
- );
-
- const tagTodayRes = await this.db.query(
- `SELECT t.tag AS cohort_value,
- COUNT(DISTINCT p.id)::int AS count,
- array_agg(DISTINCT p.slug) AS slugs
- FROM tags t JOIN pages p ON p.id = t.page_id
- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
- GROUP BY 1`,
- [sinceIso, sinceEnd.toISOString()]
- );
-
- const typeTodayRes = await this.db.query(
- `SELECT p.type AS cohort_value,
- COUNT(DISTINCT p.id)::int AS count,
- array_agg(DISTINCT p.slug) AS slugs
- FROM pages p
- WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
- GROUP BY 1`,
- [sinceIso, sinceEnd.toISOString()]
- );
-
- const baseline = [
- ...(tagBaselineRes.rows as Record<string, unknown>[]).map(r => ({
- cohort_kind: 'tag' as const,
- cohort_value: String(r.cohort_value),
- day: String(r.day),
- count: Number(r.count),
- })),
- ...(typeBaselineRes.rows as Record<string, unknown>[]).map(r => ({
- cohort_kind: 'type' as const,
- cohort_value: String(r.cohort_value),
- day: String(r.day),
- count: Number(r.count),
- })),
- ];
- const today = [
- ...(tagTodayRes.rows as Record<string, unknown>[]).map(r => ({
- cohort_kind: 'tag' as const,
- cohort_value: String(r.cohort_value),
- count: Number(r.count),
- page_slugs: (r.slugs as string[]) ?? [],
- })),
- ...(typeTodayRes.rows as Record<string, unknown>[]).map(r => ({
- cohort_kind: 'type' as const,
- cohort_value: String(r.cohort_value),
- count: Number(r.count),
- page_slugs: (r.slugs as string[]) ?? [],
- })),
- ];
-
- return computeAnomaliesFromBuckets(baseline, today, sigma);
+ return salienceImpl.findAnomalies(this.salienceDeps, opts);
}
}
-
-/**
- * Raw row shape returned from `SELECT * FROM facts`. The `embedding`
- * column comes back as a string (`[0.1,0.2,...]`) on PGLite when
- * postgres-style types aren't auto-decoded; we parse on the way out.
- */
-interface FactRowSqlShape {
- id: number;
- source_id: string;
- entity_slug: string | null;
- fact: string;
- kind: FactKind;
- visibility: FactVisibility;
- notability: 'high' | 'medium' | 'low';
- context: string | null;
- valid_from: Date | string;
- valid_until: Date | string | null;
- expired_at: Date | string | null;
- superseded_by: number | null;
- consolidated_at: Date | string | null;
- consolidated_into: number | null;
- source: string;
- source_session: string | null;
- confidence: number;
- embedding: string | number[] | Float32Array | null;
- embedded_at: Date | string | null;
- created_at: Date | string;
-}
-
-function toDate(v: Date | string | null): Date | null {
- if (v == null) return null;
- if (v instanceof Date) return v;
- return new Date(v);
-}
-
-function rowToFact(row: FactRowSqlShape): FactRow {
- let embedding: Float32Array | null = null;
- if (row.embedding != null) {
- if (row.embedding instanceof Float32Array) embedding = row.embedding;
- else if (Array.isArray(row.embedding)) embedding = new Float32Array(row.embedding);
- else if (typeof row.embedding === 'string') {
- // pgvector text format: "[0.1,0.2,...]"
- const trimmed = row.embedding.trim();
- const inner = trimmed.startsWith('[') ? trimmed.slice(1, -1) : trimmed;
- const parts = inner.split(',').map(p => parseFloat(p.trim())).filter(Number.isFinite);
- embedding = parts.length > 0 ? new Float32Array(parts) : null;
- }
- }
- return {
- id: Number(row.id),
- source_id: row.source_id,
- entity_slug: row.entity_slug,
- fact: row.fact,
- kind: row.kind,
- visibility: row.visibility,
- // v0.31.2: notability column added by migration v46. Same fallback
- // as Postgres (belt-and-suspenders with the NOT NULL DEFAULT).
- notability: row.notability ?? 'medium',
- context: row.context,
- valid_from: toDate(row.valid_from)!,
- valid_until: toDate(row.valid_until),
- expired_at: toDate(row.expired_at),
- superseded_by: row.superseded_by == null ? null : Number(row.superseded_by),
- consolidated_at: toDate(row.consolidated_at),
- consolidated_into: row.consolidated_into == null ? null : Number(row.consolidated_into),
- source: row.source,
- source_session: row.source_session,
- confidence: Number(row.confidence),
- embedding,
- embedded_at: toDate(row.embedded_at),
- created_at: toDate(row.created_at)!,
- };
-}
-
-/**
- * Encode a Float32Array as the pgvector text-form literal `[0.1,0.2,...]`.
- * Both PGLite and Postgres accept this when the parameter is cast to ::vector.
- */
-function toPgVectorLiteral(v: Float32Array | number[]): string {
- if (v instanceof Float32Array) return '[' + Array.from(v).join(',') + ']';
- return '[' + v.join(',') + ']';
-}
-
-function rowToCodeEdge(row: Record<string, unknown>): import('./types.ts').CodeEdgeResult {
- return {
- id: row.id as number,
- from_chunk_id: row.from_chunk_id as number,
- to_chunk_id: row.to_chunk_id == null ? null : (row.to_chunk_id as number),
- from_symbol_qualified: (row.from_symbol_qualified as string) ?? '',
- to_symbol_qualified: (row.to_symbol_qualified as string) ?? '',
- edge_type: (row.edge_type as string) ?? '',
- edge_metadata: (row.edge_metadata as Record<string, unknown>) ?? {},
- source_id: row.source_id == null ? null : (row.source_id as string),
- resolved: Boolean(row.resolved),
- };
-}
diff --git a/src/core/pglite-engine/code-edges.ts b/src/core/pglite-engine/code-edges.ts
new file mode 100644
index 0000000000..64dc468922
--- /dev/null
+++ b/src/core/pglite-engine/code-edges.ts
@@ -0,0 +1,197 @@
+/**
+ * v0.20.0 Cathedral II: code edges, peeled out of PGLiteEngine
+ * (containment sprint C15). Free functions over a NARROW deps surface —
+ * never the whole engine class.
+ */
+import type { PGlite } from '@electric-sql/pglite';
+
+// PGLite's parameter bridge corrupts the current engine session when a single
+// statement crosses the signed-int16 bind ceiling (32,767 parameters). Keep
+// bulk code-edge writes comfortably below it; the two edge shapes use 7 and 6
+// binds per row respectively.
+const PGLITE_EDGE_BATCH_MAX_BIND_PARAMS = 30_000;
+
+/** Narrow slice of PGLiteEngine the code-edge operations use. */
+export interface PgliteCodeEdgesDeps {
+ /** Live PGLite handle (getter-backed at the call site). */
+ readonly db: PGlite;
+}
+
+export async function addCodeEdges(deps: PgliteCodeEdgesDeps, edges: import('../types.ts').CodeEdgeInput[]): Promise<number> {
+ if (edges.length === 0) return 0;
+ let inserted = 0;
+ // Split into resolved vs unresolved. Resolved rows carry to_chunk_id
+ // (known target chunk); unresolved rows only know the qualified name.
+ const resolved = edges.filter(e => e.to_chunk_id != null);
+ const unresolved = edges.filter(e => e.to_chunk_id == null);
+
+ const resolvedBatchSize = Math.floor(PGLITE_EDGE_BATCH_MAX_BIND_PARAMS / 7);
+ for (let offset = 0; offset < resolved.length; offset += resolvedBatchSize) {
+ const batch = resolved.slice(offset, offset + resolvedBatchSize);
+ const rowParts: string[] = [];
+ const params: unknown[] = [];
+ let p = 1;
+ for (const e of batch) {
+ rowParts.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++}, $${p++}::jsonb, $${p++})`);
+ params.push(
+ e.from_chunk_id, e.to_chunk_id, e.from_symbol_qualified,
+ e.to_symbol_qualified, e.edge_type,
+ JSON.stringify(e.edge_metadata ?? {}),
+ e.source_id ?? 'default',
+ );
+ }
+ const res = await deps.db.query(
+ `INSERT INTO code_edges_chunk
+ (from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
+ VALUES ${rowParts.join(', ')}
+ ON CONFLICT (from_chunk_id, to_chunk_id, edge_type) DO NOTHING`,
+ params,
+ );
+ inserted += res.affectedRows ?? 0;
+ }
+
+ const unresolvedBatchSize = Math.floor(PGLITE_EDGE_BATCH_MAX_BIND_PARAMS / 6);
+ for (let offset = 0; offset < unresolved.length; offset += unresolvedBatchSize) {
+ const batch = unresolved.slice(offset, offset + unresolvedBatchSize);
+ const rowParts: string[] = [];
+ const params: unknown[] = [];
+ let p = 1;
+ for (const e of batch) {
+ rowParts.push(`($${p++}, $${p++}, $${p++}, $${p++}, $${p++}::jsonb, $${p++})`);
+ params.push(
+ e.from_chunk_id, e.from_symbol_qualified, e.to_symbol_qualified, e.edge_type,
+ JSON.stringify(e.edge_metadata ?? {}),
+ e.source_id ?? 'default',
+ );
+ }
+ const res = await deps.db.query(
+ `INSERT INTO code_edges_symbol
+ (from_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
+ VALUES ${rowParts.join(', ')}
+ ON CONFLICT (from_chunk_id, to_symbol_qualified, edge_type) DO NOTHING`,
+ params,
+ );
+ inserted += res.affectedRows ?? 0;
+ }
+ return inserted;
+ }
+
+export async function deleteCodeEdgesForChunks(deps: PgliteCodeEdgesDeps, chunkIds: number[]): Promise<void> {
+ if (chunkIds.length === 0) return;
+ // Both directions on code_edges_chunk; from-only on code_edges_symbol
+ // (unresolved edges don't have a to_chunk_id to match against).
+ await deps.db.query(
+ `DELETE FROM code_edges_chunk WHERE from_chunk_id = ANY($1::int[]) OR to_chunk_id = ANY($1::int[])`,
+ [chunkIds],
+ );
+ await deps.db.query(
+ `DELETE FROM code_edges_symbol WHERE from_chunk_id = ANY($1::int[])`,
+ [chunkIds],
+ );
+ }
+
+export async function getCallersOf(
+ deps: PgliteCodeEdgesDeps,
+ qualifiedName: string,
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ ): Promise<import('../types.ts').CodeEdgeResult[]> {
+ const limit = Math.min(opts?.limit ?? 100, 500);
+ const sourceClause = opts?.allSources || !opts?.sourceId
+ ? ''
+ : `AND source_id = '${opts.sourceId.replace(/'/g, "''")}'`;
+ const { rows } = await deps.db.query(
+ `SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, true as resolved
+ FROM code_edges_chunk
+ WHERE to_symbol_qualified = $1 ${sourceClause}
+ UNION ALL
+ SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, false as resolved
+ FROM code_edges_symbol
+ WHERE to_symbol_qualified = $1 ${sourceClause}
+ LIMIT $2`,
+ [qualifiedName, limit],
+ );
+ return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
+ }
+
+export async function getCalleesOf(
+ deps: PgliteCodeEdgesDeps,
+ qualifiedName: string,
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ ): Promise<import('../types.ts').CodeEdgeResult[]> {
+ const limit = Math.min(opts?.limit ?? 100, 500);
+ const sourceClause = opts?.allSources || !opts?.sourceId
+ ? ''
+ : `AND source_id = '${opts.sourceId.replace(/'/g, "''")}'`;
+ const { rows } = await deps.db.query(
+ `SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, true as resolved
+ FROM code_edges_chunk
+ WHERE from_symbol_qualified = $1 ${sourceClause}
+ UNION ALL
+ SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, false as resolved
+ FROM code_edges_symbol
+ WHERE from_symbol_qualified = $1 ${sourceClause}
+ LIMIT $2`,
+ [qualifiedName, limit],
+ );
+ return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
+ }
+
+export async function getEdgesByChunk(
+ deps: PgliteCodeEdgesDeps,
+ chunkId: number,
+ opts?: { direction?: 'in' | 'out' | 'both'; edgeType?: string; limit?: number },
+ ): Promise<import('../types.ts').CodeEdgeResult[]> {
+ const direction = opts?.direction ?? 'both';
+ const limit = Math.min(opts?.limit ?? 50, 200);
+ const edgeTypeClause = opts?.edgeType ? `AND edge_type = '${opts.edgeType.replace(/'/g, "''")}'` : '';
+ // Build the chunk-table filter based on direction. Unresolved edges
+ // (code_edges_symbol) only carry from_chunk_id — there's no inbound
+ // direction into them from a chunk ID, so we include them only when
+ // direction is 'out' or 'both'.
+ let chunkFilter = '';
+ if (direction === 'in') chunkFilter = `WHERE to_chunk_id = $1`;
+ else if (direction === 'out') chunkFilter = `WHERE from_chunk_id = $1`;
+ else chunkFilter = `WHERE from_chunk_id = $1 OR to_chunk_id = $1`;
+
+ let symbolFilter = '';
+ if (direction === 'out' || direction === 'both') {
+ symbolFilter = `WHERE from_chunk_id = $1`;
+ }
+
+ const unionClause = symbolFilter ? `
+ UNION ALL
+ SELECT id, from_chunk_id, NULL as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, false as resolved
+ FROM code_edges_symbol
+ ${symbolFilter} ${edgeTypeClause}
+ ` : '';
+
+ const { rows } = await deps.db.query(
+ `SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, true as resolved
+ FROM code_edges_chunk
+ ${chunkFilter} ${edgeTypeClause}
+ ${unionClause}
+ LIMIT $2`,
+ [chunkId, limit],
+ );
+ return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
+ }
+
+function rowToCodeEdge(row: Record<string, unknown>): import('../types.ts').CodeEdgeResult {
+ return {
+ id: row.id as number,
+ from_chunk_id: row.from_chunk_id as number,
+ to_chunk_id: row.to_chunk_id == null ? null : (row.to_chunk_id as number),
+ from_symbol_qualified: (row.from_symbol_qualified as string) ?? '',
+ to_symbol_qualified: (row.to_symbol_qualified as string) ?? '',
+ edge_type: (row.edge_type as string) ?? '',
+ edge_metadata: (row.edge_metadata as Record<string, unknown>) ?? {},
+ source_id: row.source_id == null ? null : (row.source_id as string),
+ resolved: Boolean(row.resolved),
+ };
+}
diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.ts
new file mode 100644
index 0000000000..ffa9f2f72f
--- /dev/null
+++ b/src/core/pglite-engine/facts.ts
@@ -0,0 +1,626 @@
+/**
+ * v0.31: Hot memory — facts table operations, peeled out of PGLiteEngine
+ * (containment sprint C15). Free functions over a NARROW deps surface — the
+ * live PGLite handle only. Never the whole engine class.
+ */
+import type { PGlite } from '@electric-sql/pglite';
+import type {
+ FactRow, FactKind, FactVisibility, FactInsertStatus,
+ NewFact, FactListOpts, FactsHealth,
+} from '../engine.ts';
+import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';
+
+/** Narrow slice of PGLiteEngine the facts operations use. */
+export interface PgliteFactsDeps {
+ /** Live PGLite handle. Getter-backed at the call site so the
+ * connect() check fires exactly when the original engine `db` read did. */
+ readonly db: PGlite;
+}
+
+export async function insertFact(
+ deps: PgliteFactsDeps,
+ input: NewFact,
+ ctx: { source_id: string; supersedeId?: number },
+ ): Promise<{ id: number; status: FactInsertStatus }> {
+ const validFrom = input.valid_from ?? new Date();
+ const validUntil = input.valid_until ?? null;
+ const kind = input.kind ?? 'fact';
+ const visibility = input.visibility ?? 'private';
+ const notability = input.notability ?? 'medium';
+ const confidence = input.confidence ?? 1.0;
+ const entitySlug = input.entity_slug ?? null;
+ const context = input.context ?? null;
+ const sourceSession = input.source_session ?? null;
+ const embedding = input.embedding ?? null;
+ const embeddedAt = embedding ? new Date() : null;
+ const embedStr = embedding ? toPgVectorLiteral(embedding) : null;
+ // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
+ const claimMetric = input.claim_metric ?? null;
+ const claimValue = input.claim_value ?? null;
+ const claimUnit = input.claim_unit ?? null;
+ const claimPeriod = input.claim_period ?? null;
+
+ if (ctx.supersedeId !== undefined) {
+ // Supersede flow: insert new + expire old in one txn so observers never
+ // see both rows active simultaneously.
+ const result = await deps.db.transaction(async (tx) => {
+ const ins = await tx.query<{ id: number }>(
+ embedStr === null
+ ? `INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ claim_metric, claim_value, claim_unit, claim_period
+ ) VALUES (
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
+ NULL, NULL,
+ $13, $14, $15, $16
+ ) RETURNING id`
+ : `INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ claim_metric, claim_value, claim_unit, claim_period
+ ) VALUES (
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
+ $13::vector, $14,
+ $15, $16, $17, $18
+ ) RETURNING id`,
+ embedStr === null
+ ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, claimMetric, claimValue, claimUnit, claimPeriod]
+ : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod],
+ );
+ const newId = ins.rows[0].id;
+ await tx.query(
+ `UPDATE facts SET expired_at = now(), superseded_by = $1
+ WHERE id = $2 AND expired_at IS NULL`,
+ [newId, ctx.supersedeId],
+ );
+ return newId;
+ });
+ return { id: result, status: 'superseded' };
+ }
+
+ const ins = await deps.db.query<{ id: number }>(
+ embedStr === null
+ ? `INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ claim_metric, claim_value, claim_unit, claim_period
+ ) VALUES (
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
+ NULL, NULL,
+ $13, $14, $15, $16
+ ) RETURNING id`
+ : `INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ claim_metric, claim_value, claim_unit, claim_period
+ ) VALUES (
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
+ $13::vector, $14,
+ $15, $16, $17, $18
+ ) RETURNING id`,
+ embedStr === null
+ ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, claimMetric, claimValue, claimUnit, claimPeriod]
+ : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod],
+ );
+ return { id: ins.rows[0].id, status: 'inserted' };
+ }
+
+export async function expireFact(deps: PgliteFactsDeps, id: number, opts?: { supersededBy?: number; at?: Date }): Promise<boolean> {
+ const at = opts?.at ?? new Date();
+ const result = await deps.db.query(
+ `UPDATE facts SET expired_at = $1, superseded_by = COALESCE($2, superseded_by)
+ WHERE id = $3 AND expired_at IS NULL`,
+ [at, opts?.supersededBy ?? null, id],
+ );
+ return (result.affectedRows ?? 0) > 0;
+ }
+
+export async function insertFacts(
+ deps: PgliteFactsDeps,
+ rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+ ctx: { source_id: string },
+ ): Promise<{ inserted: number; ids: number[] }> {
+ if (rows.length === 0) return { inserted: 0, ids: [] };
+
+ // Single transaction so the v51 partial UNIQUE index can roll back the
+ // whole batch on constraint violation. Per-row INSERTs (not multi-row
+ // VALUES) keep the embedding-vs-no-embedding branching readable; batch
+ // sizes are small (5-30 rows per page in practice) so the loop overhead
+ // is negligible vs the embedding compute cost.
+ const ids = await deps.db.transaction(async (tx) => {
+ const out: number[] = [];
+ for (const input of rows) {
+ const validFrom = input.valid_from ?? new Date();
+ const validUntil = input.valid_until ?? null;
+ const kind = input.kind ?? 'fact';
+ const visibility = input.visibility ?? 'private';
+ const notability = input.notability ?? 'medium';
+ const confidence = input.confidence ?? 1.0;
+ const entitySlug = input.entity_slug ?? null;
+ const context = input.context ?? null;
+ const sourceSession = input.source_session ?? null;
+ const embedding = input.embedding ?? null;
+ const embeddedAt = embedding ? new Date() : null;
+ const embedStr = embedding ? toPgVectorLiteral(embedding) : null;
+ // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
+ const claimMetric = input.claim_metric ?? null;
+ const claimValue = input.claim_value ?? null;
+ const claimUnit = input.claim_unit ?? null;
+ const claimPeriod = input.claim_period ?? null;
+ // v0.40.2.0 — event_type column (Commit 1 migration v89).
+ const eventType = input.event_type ?? null;
+
+ // Param-positional dispatch: embedStr presence shifts the trailing
+ // slots by one. Order of named slots stays stable across both
+ // branches: embedded_at, row_num, source_markdown_slug,
+ // claim_metric, claim_value, claim_unit, claim_period, event_type.
+ const ins = await tx.query<{ id: number }>(
+ embedStr === null
+ ? `INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ row_num, source_markdown_slug,
+ claim_metric, claim_value, claim_unit, claim_period,
+ event_type
+ ) VALUES (
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
+ NULL, $13,
+ $14, $15,
+ $16, $17, $18, $19,
+ $20
+ )
+ ON CONFLICT (source_id, source_markdown_slug, row_num)
+ WHERE row_num IS NOT NULL
+ DO NOTHING
+ RETURNING id`
+ : `INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ row_num, source_markdown_slug,
+ claim_metric, claim_value, claim_unit, claim_period,
+ event_type
+ ) VALUES (
+ $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
+ $13::vector, $14,
+ $15, $16,
+ $17, $18, $19, $20,
+ $21
+ )
+ ON CONFLICT (source_id, source_markdown_slug, row_num)
+ WHERE row_num IS NOT NULL
+ DO NOTHING
+ RETURNING id`,
+ embedStr === null
+ ? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType]
+ : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType],
+ );
+ if (ins.rows[0]) out.push(ins.rows[0].id);
+ }
+ return out;
+ });
+ return { inserted: ids.length, ids };
+ }
+
+export async function deleteFactsForPage(
+ deps: PgliteFactsDeps,
+ slug: string,
+ source_id: string,
+ opts?: { excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean },
+ ): Promise<{ deleted: number }> {
+ const prefixes = opts?.excludeSourcePrefixes;
+ // #2646: keep soft-expired legacy rows (row_num NULL — never
+ // fence-owned) so a fence reconcile can't destroy forget_fact's
+ // legacy DB-only forget record.
+ const expiredLegacyFilter = opts?.preserveExpiredLegacy
+ ? ` AND NOT (row_num IS NULL AND expired_at IS NOT NULL)`
+ : '';
+ if (prefixes && prefixes.length > 0) {
+ // #1928: keep rows whose `source` matches an excluded prefix (e.g.
+ // `cli:` conversation facts). COALESCE so NULL/empty-source fence rows
+ // stay deletable — only the explicitly-protected prefixes survive.
+ const patterns = prefixes.map(p => `${p}%`);
+ const result = await deps.db.query(
+ `DELETE FROM facts
+ WHERE source_id = $1 AND source_markdown_slug = $2
+ AND NOT (COALESCE(source, '') LIKE ANY($3::text[]))${expiredLegacyFilter}`,
+ [source_id, slug, patterns],
+ );
+ return { deleted: result.affectedRows ?? 0 };
+ }
+ const result = await deps.db.query(
+ `DELETE FROM facts WHERE source_id = $1 AND source_markdown_slug = $2${expiredLegacyFilter}`,
+ [source_id, slug],
+ );
+ return { deleted: result.affectedRows ?? 0 };
+ }
+
+export async function listFactsByEntity(
+ deps: PgliteFactsDeps,
+ source_id: string,
+ entitySlug: string,
+ opts?: FactListOpts,
+ ): Promise<FactRow[]> {
+ return _listFacts(deps, source_id, {
+ ...opts,
+ whereClauses: [`entity_slug = $entitySlug`],
+ whereParams: { entitySlug },
+ order: 'valid_from DESC, id DESC',
+ });
+ }
+
+export async function listFactsSince(
+ deps: PgliteFactsDeps,
+ source_id: string,
+ since: Date,
+ opts?: FactListOpts & { entitySlug?: string },
+ ): Promise<FactRow[]> {
+ const where: string[] = [`created_at >= $since`];
+ const params: Record<string, unknown> = { since };
+ if (opts?.entitySlug) {
+ where.push(`entity_slug = $entitySlug`);
+ params.entitySlug = opts.entitySlug;
+ }
+ return _listFacts(deps, source_id, {
+ ...opts,
+ whereClauses: where,
+ whereParams: params,
+ order: 'created_at DESC, id DESC',
+ });
+ }
+
+export async function listFactsBySession(
+ deps: PgliteFactsDeps,
+ source_id: string,
+ sessionId: string,
+ opts?: FactListOpts,
+ ): Promise<FactRow[]> {
+ return _listFacts(deps, source_id, {
+ ...opts,
+ whereClauses: [`source_session = $sessionId`],
+ whereParams: { sessionId },
+ order: 'created_at DESC, id DESC',
+ });
+ }
+
+export async function listSupersessions(
+ deps: PgliteFactsDeps,
+ source_id: string,
+ opts?: { since?: Date; limit?: number },
+ ): Promise<FactRow[]> {
+ const where: string[] = [`expired_at IS NOT NULL`, `superseded_by IS NOT NULL`];
+ const params: Record<string, unknown> = {};
+ if (opts?.since) {
+ where.push(`expired_at >= $since`);
+ params.since = opts.since;
+ }
+ return _listFacts(deps, source_id, {
+ activeOnly: false,
+ limit: opts?.limit,
+ whereClauses: where,
+ whereParams: params,
+ order: 'expired_at DESC, id DESC',
+ });
+ }
+
+export async function countUnconsolidatedFacts(deps: PgliteFactsDeps, source_id: string): Promise<number> {
+ const r = await deps.db.query<{ count: number }>(
+ `SELECT COUNT(*)::int AS count FROM facts
+ WHERE source_id = $1 AND consolidated_at IS NULL AND expired_at IS NULL`,
+ [source_id],
+ );
+ return Number(r.rows[0]?.count ?? 0);
+ }
+
+export async function findCandidateDuplicates(
+ deps: PgliteFactsDeps,
+ source_id: string,
+ entitySlug: string,
+ factText: string,
+ opts?: { k?: number; embedding?: Float32Array },
+ ): Promise<FactRow[]> {
+ const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
+ if (opts?.embedding) {
+ // Embedding-cosine ordered candidates within the entity bucket.
+ const vec = toPgVectorLiteral(opts.embedding);
+ const result = await deps.db.query<FactRowSqlShape>(
+ `SELECT * FROM facts
+ WHERE source_id = $1
+ AND entity_slug = $2
+ AND expired_at IS NULL
+ AND embedding IS NOT NULL
+ ORDER BY embedding <=> $3::vector
+ LIMIT $4`,
+ [source_id, entitySlug, vec, k],
+ );
+ return result.rows.map(rowToFact);
+ }
+ // Recency fallback when no embedding.
+ const result = await deps.db.query<FactRowSqlShape>(
+ `SELECT * FROM facts
+ WHERE source_id = $1
+ AND entity_slug = $2
+ AND expired_at IS NULL
+ ORDER BY created_at DESC, id DESC
+ LIMIT $3`,
+ [source_id, entitySlug, k],
+ );
+ return result.rows.map(rowToFact);
+ }
+
+export async function findTrajectory(deps: PgliteFactsDeps, opts: import('../engine.ts').TrajectoryOpts): Promise<import('../engine.ts').TrajectoryPoint[]> {
+ const limit = clampSearchLimit(opts.limit, 100, 500);
+ const sinceDate = opts.since ? new Date(opts.since) : null;
+ const untilDate = opts.until ? new Date(opts.until) : null;
+ const metric = opts.metric ?? null;
+ const kind = opts.kind ?? 'all';
+ const useArray = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;
+ const sourceIds = useArray ? opts.sourceIds! : null;
+ const sourceId = opts.sourceId ?? 'default';
+ const remoteFilter = opts.remote === true;
+
+ // Build SQL dynamically. PGLite uses $N positional params; we
+ // assemble the WHERE clauses + params array in tandem to keep them
+ // aligned. Final shape is single SELECT, ORDER BY (valid_from, id) ASC.
+ const where: string[] = [
+ useArray ? `source_id = ANY($1::text[])` : `source_id = $1`,
+ `entity_slug = $2`,
+ `expired_at IS NULL`,
+ ];
+ const params: unknown[] = [useArray ? sourceIds : sourceId, opts.entitySlug];
+ let p = 3;
+ if (remoteFilter) {
+ where.push(`visibility = 'world'`);
+ }
+ if (metric !== null) {
+ where.push(`claim_metric = $${p}`);
+ params.push(metric);
+ p += 1;
+ }
+ // v0.40.2.0 — kind filter. 'all' (default) no-ops. 'metric' restricts
+ // to typed-claim rows; 'event' restricts to event-shaped rows.
+ if (kind === 'metric') {
+ where.push(`claim_metric IS NOT NULL`);
+ } else if (kind === 'event') {
+ where.push(`event_type IS NOT NULL`);
+ }
+ if (sinceDate) {
+ where.push(`valid_from >= $${p}`);
+ params.push(sinceDate);
+ p += 1;
+ }
+ if (untilDate) {
+ where.push(`valid_from <= $${p}`);
+ params.push(untilDate);
+ p += 1;
+ }
+ params.push(limit);
+ const limitPlaceholder = p;
+
+ const sqlText = `
+ SELECT id, valid_from,
+ claim_metric, claim_value, claim_unit, claim_period,
+ event_type,
+ fact, source_session, source_markdown_slug,
+ embedding
+ FROM facts
+ WHERE ${where.join(' AND ')}
+ ORDER BY valid_from ASC, id ASC
+ LIMIT $${limitPlaceholder}
+ `;
+ const result = await deps.db.query<{
+ id: number;
+ valid_from: Date | string;
+ claim_metric: string | null;
+ claim_value: number | null;
+ claim_unit: string | null;
+ claim_period: string | null;
+ event_type: string | null;
+ fact: string;
+ source_session: string | null;
+ source_markdown_slug: string | null;
+ embedding: string | number[] | Float32Array | null;
+ }>(sqlText, params);
+
+ return result.rows.map(r => {
+ // Inline embedding parser — mirrors rowToFact() at line 3911.
+ let embedding: Float32Array | null = null;
+ if (r.embedding != null) {
+ if (r.embedding instanceof Float32Array) embedding = r.embedding;
+ else if (Array.isArray(r.embedding)) embedding = new Float32Array(r.embedding);
+ else if (typeof r.embedding === 'string') {
+ const trimmed = r.embedding.trim();
+ const inner = trimmed.startsWith('[') ? trimmed.slice(1, -1) : trimmed;
+ const parts = inner.split(',').map(s => parseFloat(s.trim())).filter(Number.isFinite);
+ embedding = parts.length > 0 ? new Float32Array(parts) : null;
+ }
+ }
+ return {
+ fact_id: Number(r.id),
+ valid_from: r.valid_from instanceof Date ? r.valid_from : new Date(r.valid_from),
+ metric: r.claim_metric,
+ value: r.claim_value === null ? null : Number(r.claim_value),
+ unit: r.claim_unit,
+ period: r.claim_period,
+ event_type: r.event_type,
+ text: r.fact,
+ source_session: r.source_session,
+ source_markdown_slug: r.source_markdown_slug,
+ embedding,
+ };
+ });
+ }
+
+export async function consolidateFact(deps: PgliteFactsDeps, id: number, takeId: number): Promise<void> {
+ await deps.db.query(
+ `UPDATE facts SET consolidated_at = now(), consolidated_into = $1 WHERE id = $2`,
+ [takeId, id],
+ );
+ }
+
+export async function getFactsHealth(deps: PgliteFactsDeps, source_id: string): Promise<FactsHealth> {
+ const total = await deps.db.query<{
+ total_active: number; total_today: number; total_week: number;
+ total_expired: number; total_consolidated: number;
+ }>(
+ `SELECT
+ COUNT(*) FILTER (WHERE expired_at IS NULL) AS total_active,
+ COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '24 hours') AS total_today,
+ COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '7 days') AS total_week,
+ COUNT(*) FILTER (WHERE expired_at IS NOT NULL) AS total_expired,
+ COUNT(*) FILTER (WHERE consolidated_at IS NOT NULL) AS total_consolidated
+ FROM facts WHERE source_id = $1`,
+ [source_id],
+ );
+ const top = await deps.db.query<{ entity_slug: string; count: number }>(
+ `SELECT entity_slug, COUNT(*)::int AS count
+ FROM facts
+ WHERE source_id = $1 AND expired_at IS NULL AND entity_slug IS NOT NULL
+ GROUP BY entity_slug
+ ORDER BY count DESC, entity_slug ASC
+ LIMIT 5`,
+ [source_id],
+ );
+ const r = total.rows[0] ?? {
+ total_active: 0, total_today: 0, total_week: 0, total_expired: 0, total_consolidated: 0,
+ };
+ return {
+ source_id,
+ total_active: Number(r.total_active),
+ total_today: Number(r.total_today),
+ total_week: Number(r.total_week),
+ total_expired: Number(r.total_expired),
+ total_consolidated: Number(r.total_consolidated),
+ top_entities: top.rows.map(t => ({ entity_slug: t.entity_slug, count: Number(t.count) })),
+ };
+ }
+
+ /**
+ * Internal helper: shared list-facts query builder.
+ * Supports source_id always, plus arbitrary additional WHERE clauses.
+ */
+async function _listFacts(
+ deps: PgliteFactsDeps,
+ source_id: string,
+ opts: FactListOpts & {
+ whereClauses?: string[];
+ whereParams?: Record<string, unknown>;
+ order: string;
+ },
+ ): Promise<FactRow[]> {
+ const limit = clampSearchLimit(opts.limit, 50, MAX_SEARCH_LIMIT);
+ const offset = Math.max(0, opts.offset ?? 0);
+ const whereParts: string[] = [`source_id = $source_id`];
+ const params: Record<string, unknown> = { source_id };
+ if (opts.activeOnly !== false) {
+ whereParts.push(`expired_at IS NULL`);
+ }
+ if (opts.kinds && opts.kinds.length > 0) {
+ whereParts.push(`kind = ANY($kinds)`);
+ params.kinds = opts.kinds;
+ }
+ if (opts.visibility && opts.visibility.length > 0) {
+ whereParts.push(`visibility = ANY($visibility)`);
+ params.visibility = opts.visibility;
+ }
+ for (const c of opts.whereClauses ?? []) whereParts.push(c);
+ Object.assign(params, opts.whereParams ?? {});
+
+ // Convert $name placeholders to numbered $1, $2, ... for PGLite.
+ const orderedKeys = Object.keys(params);
+ const indexFor = (name: string): number => orderedKeys.indexOf(name) + 1;
+ const sql = `SELECT * FROM facts
+ WHERE ${whereParts.join(' AND ').replace(/\$(\w+)/g, (_m, k) => `$${indexFor(k)}`)}
+ ORDER BY ${opts.order}
+ LIMIT ${limit} OFFSET ${offset}`;
+ const result = await deps.db.query<FactRowSqlShape>(sql, orderedKeys.map(k => params[k]));
+ return result.rows.map(rowToFact);
+ }
+
+/**
+ * Raw row shape returned from `SELECT * FROM facts`. The `embedding`
+ * column comes back as a string (`[0.1,0.2,...]`) on PGLite when
+ * postgres-style types aren't auto-decoded; we parse on the way out.
+ */
+interface FactRowSqlShape {
+ id: number;
+ source_id: string;
+ entity_slug: string | null;
+ fact: string;
+ kind: FactKind;
+ visibility: FactVisibility;
+ notability: 'high' | 'medium' | 'low';
+ context: string | null;
+ valid_from: Date | string;
+ valid_until: Date | string | null;
+ expired_at: Date | string | null;
+ superseded_by: number | null;
+ consolidated_at: Date | string | null;
+ consolidated_into: number | null;
+ source: string;
+ source_session: string | null;
+ confidence: number;
+ embedding: string | number[] | Float32Array | null;
+ embedded_at: Date | string | null;
+ created_at: Date | string;
+}
+
+function toDate(v: Date | string | null): Date | null {
+ if (v == null) return null;
+ if (v instanceof Date) return v;
+ return new Date(v);
+}
+
+function rowToFact(row: FactRowSqlShape): FactRow {
+ let embedding: Float32Array | null = null;
+ if (row.embedding != null) {
+ if (row.embedding instanceof Float32Array) embedding = row.embedding;
+ else if (Array.isArray(row.embedding)) embedding = new Float32Array(row.embedding);
+ else if (typeof row.embedding === 'string') {
+ // pgvector text format: "[0.1,0.2,...]"
+ const trimmed = row.embedding.trim();
+ const inner = trimmed.startsWith('[') ? trimmed.slice(1, -1) : trimmed;
+ const parts = inner.split(',').map(p => parseFloat(p.trim())).filter(Number.isFinite);
+ embedding = parts.length > 0 ? new Float32Array(parts) : null;
+ }
+ }
+ return {
+ id: Number(row.id),
+ source_id: row.source_id,
+ entity_slug: row.entity_slug,
+ fact: row.fact,
+ kind: row.kind,
+ visibility: row.visibility,
+ // v0.31.2: notability column added by migration v46. Same fallback
+ // as Postgres (belt-and-suspenders with the NOT NULL DEFAULT).
+ notability: row.notability ?? 'medium',
+ context: row.context,
+ valid_from: toDate(row.valid_from)!,
+ valid_until: toDate(row.valid_until),
+ expired_at: toDate(row.expired_at),
+ superseded_by: row.superseded_by == null ? null : Number(row.superseded_by),
+ consolidated_at: toDate(row.consolidated_at),
+ consolidated_into: row.consolidated_into == null ? null : Number(row.consolidated_into),
+ source: row.source,
+ source_session: row.source_session,
+ confidence: Number(row.confidence),
+ embedding,
+ embedded_at: toDate(row.embedded_at),
+ created_at: toDate(row.created_at)!,
+ };
+}
+
+/**
+ * Encode a Float32Array as the pgvector text-form literal `[0.1,0.2,...]`.
+ * Both PGLite and Postgres accept this when the parameter is cast to ::vector.
+ */
+function toPgVectorLiteral(v: Float32Array | number[]): string {
+ if (v instanceof Float32Array) return '[' + Array.from(v).join(',') + ']';
+ return '[' + v.join(',') + ']';
+}
diff --git a/src/core/pglite-engine/salience.ts b/src/core/pglite-engine/salience.ts
new file mode 100644
index 0000000000..bba093c909
--- /dev/null
+++ b/src/core/pglite-engine/salience.ts
@@ -0,0 +1,335 @@
+/**
+ * v0.29 — Salience + Anomaly Detection, peeled out of PGLiteEngine
+ * (containment sprint C15). Free functions over a NARROW deps surface —
+ * never the whole engine class.
+ */
+import type { PGlite } from '@electric-sql/pglite';
+import { clampSearchLimit } from '../engine.ts';
+import type {
+ SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
+ EmotionalWeightInputRow, EmotionalWeightWriteRow,
+ EnrichCandidatesOpts, EnrichCandidate,
+} from '../types.ts';
+import { ENRICH_ORDER_SQL } from '../types.ts';
+import {
+ resolveRecencyDecayMap,
+ DEFAULT_FALLBACK,
+} from '../search/recency-decay.ts';
+import { buildRecencyComponentSql } from '../search/sql-ranking.ts';
+import { computeAnomaliesFromBuckets } from '../cycle/anomaly.ts';
+
+/** Narrow slice of PGLiteEngine the salience/anomaly operations use. */
+export interface PgliteSalienceDeps {
+ /** Live PGLite handle (getter-backed at the call site). */
+ readonly db: PGlite;
+}
+
+export async function batchLoadEmotionalInputs(deps: PgliteSalienceDeps, slugs?: string[]): Promise<EmotionalWeightInputRow[]> {
+ // Two CTEs avoid the N×M cartesian product (codex C4#4).
+ const baseSql = `
+ WITH page_tags AS (
+ SELECT page_id, array_agg(DISTINCT tag) AS tags
+ FROM tags GROUP BY page_id
+ ),
+ page_takes AS (
+ SELECT page_id, json_agg(json_build_object(
+ 'holder', holder, 'weight', weight, 'kind', kind, 'active', active
+ )) AS takes
+ FROM takes WHERE active = TRUE GROUP BY page_id
+ )
+ SELECT p.slug, p.source_id,
+ COALESCE(pt.tags, ARRAY[]::text[]) AS tags,
+ COALESCE(pk.takes, '[]'::json) AS takes
+ FROM pages p
+ LEFT JOIN page_tags pt ON pt.page_id = p.id
+ LEFT JOIN page_takes pk ON pk.page_id = p.id
+ `;
+ const { rows } = slugs
+ ? await deps.db.query(`${baseSql} WHERE p.slug = ANY($1::text[])`, [slugs])
+ : await deps.db.query(baseSql);
+ return (rows as Record<string, unknown>[]).map(r => ({
+ slug: String(r.slug),
+ source_id: String(r.source_id),
+ tags: (r.tags as string[]) ?? [],
+ takes: (r.takes as EmotionalWeightInputRow['takes']) ?? [],
+ }));
+ }
+
+export async function setEmotionalWeightBatch(deps: PgliteSalienceDeps, rows: EmotionalWeightWriteRow[]): Promise<number> {
+ if (rows.length === 0) return 0;
+ const slugs = rows.map(r => r.slug);
+ const sourceIds = rows.map(r => r.source_id);
+ const weights = rows.map(r => r.weight);
+ // Composite-keyed UPDATE FROM unnest (codex C4#3).
+ // v0.29.1: bump salience_touched_at when emotional_weight actually changes
+ // so the salience query window picks up newly-salient old pages. Mirror
+ // of postgres-engine.ts.
+ const result = await deps.db.query(
+ `UPDATE pages
+ SET emotional_weight = u.weight,
+ salience_touched_at = CASE
+ WHEN pages.emotional_weight IS DISTINCT FROM u.weight THEN now()
+ ELSE pages.salience_touched_at
+ END
+ FROM unnest($1::text[], $2::text[], $3::real[])
+ AS u(slug, source_id, weight)
+ WHERE pages.slug = u.slug AND pages.source_id = u.source_id
+ RETURNING 1`,
+ [slugs, sourceIds, weights]
+ );
+ return result.rows.length;
+ }
+
+export async function getRecentSalience(deps: PgliteSalienceDeps, opts: SalienceOpts): Promise<SalienceResult[]> {
+ const days = Math.max(0, opts.days ?? 14);
+ const limit = clampSearchLimit(opts.limit, 20, 100);
+ const slugPrefix = opts.slugPrefix;
+ const boundaryIso = new Date(Date.now() - days * 86400000).toISOString();
+
+ const params: unknown[] = [boundaryIso];
+ let prefixCondition = '';
+ if (slugPrefix) {
+ const escaped = slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%';
+ params.push(escaped);
+ prefixCondition = `AND p.slug LIKE $${params.length} ESCAPE '\\'`;
+ }
+ // TIM-37: exclude briefing pages from their own Brain Pulse. See the
+ // matching block in postgres-engine.ts getRecentSalience() for context.
+ const excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))
+ ? `AND p.slug NOT LIKE 'briefings/%'`
+ : '';
+ params.push(limit);
+ const limitParam = `$${params.length}`;
+
+ // v0.29.1: third score term via buildRecencyComponentSql. Default
+ // 'flat' = v0.29.0 behavior. 'on' opts into per-prefix decay.
+ const recencyBias = opts.recency_bias ?? 'flat';
+ let recencySql: string;
+ if (recencyBias === 'on') {
+ recencySql = buildRecencyComponentSql({
+ slugColumn: 'p.slug',
+ dateExpr: 'COALESCE(p.effective_date, p.updated_at)',
+ decayMap: resolveRecencyDecayMap(),
+ fallback: DEFAULT_FALLBACK,
+ });
+ } else {
+ recencySql = buildRecencyComponentSql({
+ slugColumn: 'p.slug',
+ dateExpr: 'p.updated_at',
+ decayMap: {},
+ fallback: { halflifeDays: 1, coefficient: 1.0 },
+ });
+ }
+ const { rows } = await deps.db.query(
+ `SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, p.emotional_weight,
+ COUNT(DISTINCT t.id) AS take_count,
+ COALESCE(AVG(t.weight), 0) AS take_avg_weight,
+ (p.emotional_weight * 5)
+ + ln(1 + COUNT(DISTINCT t.id))
+ + ${recencySql}
+ AS score
+ FROM 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
+ ${prefixCondition}
+ ${excludeBriefings}
+ GROUP BY p.id
+ ORDER BY score DESC
+ LIMIT ${limitParam}`,
+ params
+ );
+ return (rows as Record<string, unknown>[]).map(r => ({
+ slug: String(r.slug),
+ source_id: String(r.source_id),
+ title: String(r.title ?? ''),
+ type: r.type as SalienceResult['type'],
+ updated_at: r.updated_at as Date,
+ emotional_weight: Number(r.emotional_weight ?? 0),
+ take_count: Number(r.take_count ?? 0),
+ take_avg_weight: Number(r.take_avg_weight ?? 0),
+ score: Number(r.score ?? 0),
+ }));
+ }
+
+export async function listEnrichCandidates(deps: PgliteSalienceDeps, opts: EnrichCandidatesOpts): Promise<EnrichCandidate[]> {
+ // v0.41.39 (issue #1700). Parity with postgres-engine.listEnrichCandidates.
+ if (!opts.types || opts.types.length === 0) return [];
+ const limit = Math.max(1, Math.min(opts.limit ?? 50, 5000));
+ const threshold = Math.max(0, opts.thinThreshold);
+
+ const params: unknown[] = [];
+ params.push(opts.types);
+ const typesParam = `$${params.length}`;
+ params.push(threshold);
+ const thresholdParam = `$${params.length}`;
+
+ const where: string[] = [
+ 'p.deleted_at IS NULL',
+ `p.type = ANY(${typesParam}::text[])`,
+ `(char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < ${thresholdParam}`,
+ ];
+
+ // Source scope: array wins over scalar.
+ if (opts.sourceIds && opts.sourceIds.length > 0) {
+ params.push(opts.sourceIds);
+ where.push(`p.source_id = ANY($${params.length}::text[])`);
+ } else if (opts.sourceId) {
+ params.push(opts.sourceId);
+ where.push(`p.source_id = $${params.length}`);
+ }
+
+ // Re-enrich recency guard. Lexical text compare on the ISO `enriched_at`
+ // (never cast → can't throw on a malformed value). NULL → eligible.
+ const reenrichMs = opts.reenrichAfterMs ?? 0;
+ if (reenrichMs > 0) {
+ params.push(new Date(Date.now() - reenrichMs).toISOString());
+ where.push(
+ `NOT (p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $${params.length})`,
+ );
+ }
+
+ // Exclude dream/synthesize-generated pages (parity with postgres-engine).
+ where.push(`(p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true'`);
+
+ const orderKey = ENRICH_ORDER_SQL[opts.order] ? opts.order : 'inbound-links';
+ const orderBy = ENRICH_ORDER_SQL[orderKey];
+
+ params.push(limit);
+ const limitParam = `$${params.length}`;
+
+ const { rows } = await deps.db.query(
+ `SELECT
+ p.slug,
+ p.source_id,
+ p.title,
+ p.type,
+ (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len,
+ COALESCE((
+ SELECT COUNT(*)
+ FROM links l
+ WHERE l.to_page_id = p.id
+ AND l.link_source IS DISTINCT FROM 'mentions'
+ ), 0)::int AS inbound_count
+ FROM pages p
+ WHERE ${where.join(' AND ')}
+ ORDER BY ${orderBy}
+ LIMIT ${limitParam}`,
+ params,
+ );
+ return (rows as Record<string, unknown>[]).map((r) => ({
+ slug: String(r.slug),
+ source_id: String(r.source_id),
+ title: String(r.title ?? ''),
+ type: r.type as EnrichCandidate['type'],
+ body_len: Number(r.body_len ?? 0),
+ inbound_count: Number(r.inbound_count ?? 0),
+ }));
+ }
+
+export async function findAnomalies(deps: PgliteSalienceDeps, opts: AnomaliesOpts): Promise<AnomalyResult[]> {
+ const sigma = opts.sigma ?? 3.0;
+ const lookbackDays = Math.max(1, opts.lookback_days ?? 30);
+ const sinceIso = (opts.since ?? new Date().toISOString().slice(0, 10));
+ const sinceDate = new Date(sinceIso + 'T00:00:00Z');
+ const sinceEnd = new Date(sinceDate.getTime() + 86400000);
+ const baselineStart = new Date(sinceDate.getTime() - lookbackDays * 86400000);
+
+ const tagBaselineRes = await deps.db.query(
+ `WITH days AS (
+ SELECT day::date FROM generate_series(
+ $1::date, $2::date - 1, '1 day'::interval
+ ) AS day
+ ),
+ 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
+ ),
+ touched AS (
+ SELECT t.tag,
+ date_trunc('day', p.updated_at)::date AS day,
+ COUNT(DISTINCT p.id) AS cnt
+ FROM tags t JOIN pages p ON p.id = t.page_id
+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
+ GROUP BY 1, 2
+ )
+ SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
+ FROM cohort_keys cd CROSS JOIN days d
+ LEFT JOIN touched t ON t.tag = cd.tag AND t.day = d.day`,
+ [baselineStart.toISOString(), sinceDate.toISOString()]
+ );
+
+ const typeBaselineRes = await deps.db.query(
+ `WITH days AS (
+ SELECT day::date FROM generate_series(
+ $1::date, $2::date - 1, '1 day'::interval
+ ) AS day
+ ),
+ cohort_keys AS (
+ SELECT DISTINCT p.type FROM pages p
+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
+ ),
+ touched AS (
+ SELECT p.type,
+ date_trunc('day', p.updated_at)::date AS day,
+ COUNT(DISTINCT p.id) AS cnt
+ FROM pages p
+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
+ GROUP BY 1, 2
+ )
+ SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
+ FROM cohort_keys cd CROSS JOIN days d
+ LEFT JOIN touched t ON t.type = cd.type AND t.day = d.day`,
+ [baselineStart.toISOString(), sinceDate.toISOString()]
+ );
+
+ const tagTodayRes = await deps.db.query(
+ `SELECT t.tag AS cohort_value,
+ COUNT(DISTINCT p.id)::int AS count,
+ array_agg(DISTINCT p.slug) AS slugs
+ FROM tags t JOIN pages p ON p.id = t.page_id
+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
+ GROUP BY 1`,
+ [sinceIso, sinceEnd.toISOString()]
+ );
+
+ const typeTodayRes = await deps.db.query(
+ `SELECT p.type AS cohort_value,
+ COUNT(DISTINCT p.id)::int AS count,
+ array_agg(DISTINCT p.slug) AS slugs
+ FROM pages p
+ WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz
+ GROUP BY 1`,
+ [sinceIso, sinceEnd.toISOString()]
+ );
+
+ const baseline = [
+ ...(tagBaselineRes.rows as Record<string, unknown>[]).map(r => ({
+ cohort_kind: 'tag' as const,
+ cohort_value: String(r.cohort_value),
+ day: String(r.day),
+ count: Number(r.count),
+ })),
+ ...(typeBaselineRes.rows as Record<string, unknown>[]).map(r => ({
+ cohort_kind: 'type' as const,
+ cohort_value: String(r.cohort_value),
+ day: String(r.day),
+ count: Number(r.count),
+ })),
+ ];
+ const today = [
+ ...(tagTodayRes.rows as Record<string, unknown>[]).map(r => ({
+ cohort_kind: 'tag' as const,
+ cohort_value: String(r.cohort_value),
+ count: Number(r.count),
+ page_slugs: (r.slugs as string[]) ?? [],
+ })),
+ ...(typeTodayRes.rows as Record<string, unknown>[]).map(r => ({
+ cohort_kind: 'type' as const,
+ cohort_value: String(r.cohort_value),
+ count: Number(r.count),
+ page_slugs: (r.slugs as string[]) ?? [],
+ })),
+ ];
+
+ return computeAnomaliesFromBuckets(baseline, today, sigma);
+ }
diff --git a/src/core/pglite-engine/takes.ts b/src/core/pglite-engine/takes.ts
new file mode 100644
index 0000000000..53fdb427ce
--- /dev/null
+++ b/src/core/pglite-engine/takes.ts
@@ -0,0 +1,635 @@
+/**
+ * v0.28: Takes (typed/weighted/attributed claims) + synthesis_evidence,
+ * peeled out of PGLiteEngine (containment sprint C15). Free functions over
+ * a NARROW deps surface — never the whole engine class.
+ */
+import type { PGlite } from '@electric-sql/pglite';
+import type {
+ BatchOpts,
+ TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,
+ TakeResolution, SynthesisEvidenceInput,
+ TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,
+} from '../engine.ts';
+import { clampSearchLimit } from '../engine.ts';
+import type { SearchOpts } from '../types.ts';
+import { GBrainError } from '../types.ts';
+import type { BatchAuditSite } from '../retry.ts';
+import type { SqlValue } from '../sql-query.ts';
+import { deriveResolutionTuple, finalizeScorecard } from '../takes-resolution.ts';
+import { normalizeWeightForStorage } from '../takes-fence.ts';
+import { buildTakeRows } from '../batch-rows.ts';
+import { takeRowToTake, takeHitRowToHit } from '../utils.ts';
+
+/** Narrow slice of PGLiteEngine the takes operations use. */
+export interface PgliteTakesDeps {
+ /** Live PGLite handle (getter-backed at the call site). */
+ readonly db: PGlite;
+ /** Engine batch retry wrapper (audit JSONL + backoff live on the engine). */
+ batchRetry<T>(
+ auditSite: BatchAuditSite,
+ signal: AbortSignal | undefined,
+ fn: () => Promise<T>,
+ batchSize: number,
+ ): Promise<T>;
+ /** JSONB-safe positional write helper, bound to the engine at the call site. */
+ executeRawJsonb<R = Record<string, unknown>>(
+ sql: string,
+ scalarParams: SqlValue[],
+ jsonbParams: unknown[],
+ ): Promise<R[]>;
+}
+
+export async function addTakesBatch(deps: PgliteTakesDeps, rowsIn: TakeBatchInput[], opts?: BatchOpts): Promise<number> {
+ if (rowsIn.length === 0) return 0;
+ // v0.42.26: wrap in batchRetry to match links/timeline (takes was the only
+ // batch primitive without retry resilience).
+ return deps.batchRetry(opts?.auditSite ?? 'addTakesBatch', opts?.signal, () => _addTakesBatchOnce(deps, rowsIn), rowsIn.length);
+ }
+
+async function _addTakesBatchOnce(deps: PgliteTakesDeps, rowsIn: TakeBatchInput[]): Promise<number> {
+ // #1861: JSONB jsonb_to_recordset instead of unnest(${arr}::text[]). Mirrors
+ // PostgresEngine: `claim` is free LLM prose (array-literal crash hazard);
+ // native recordset types + JSON-native numbers/booleans retire the per-engine
+ // element-type casts. Weight clamp/round + NUL strip live in buildTakeRows.
+ // ON CONFLICT DO UPDATE — intra-batch dup (page_id, row_num) errors, same as
+ // the pre-#1861 unnest path.
+ const { rows, weightClamped } = buildTakeRows(rowsIn);
+ if (weightClamped > 0) {
+ process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: ${weightClamped} row(s) had weight outside [0,1]; clamped\n`);
+ }
+ const result = await deps.executeRawJsonb(
+ `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active)
+ SELECT v.page_id, v.row_num, v.claim, v.kind, v.holder, v.weight,
+ v.since_date, v.until_date, v.source, v.superseded_by, v.active
+ FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(
+ page_id int, row_num int, claim text, kind text, holder text, weight real,
+ since_date text, until_date text, source text, superseded_by int, active boolean
+ )
+ ON CONFLICT (page_id, row_num) DO UPDATE SET
+ claim = EXCLUDED.claim,
+ kind = EXCLUDED.kind,
+ holder = EXCLUDED.holder,
+ weight = EXCLUDED.weight,
+ since_date = EXCLUDED.since_date,
+ until_date = EXCLUDED.until_date,
+ source = EXCLUDED.source,
+ superseded_by = EXCLUDED.superseded_by,
+ active = EXCLUDED.active,
+ updated_at = now()
+ RETURNING 1`,
+ [],
+ [{ rows }],
+ );
+ return result.length;
+ }
+
+ /** v0.32.6 P1 — batched per-page active-takes fetch for the contradiction probe. */
+export async function listActiveTakesForPages(
+ deps: PgliteTakesDeps,
+ pageIds: number[],
+ opts: { takesHoldersAllowList?: string[] } = {},
+ ): Promise<Map<number, Take[]>> {
+ const out = new Map<number, Take[]>();
+ for (const pid of pageIds) out.set(pid, []);
+ if (pageIds.length === 0) return out;
+ const { rows } = await deps.db.query(
+ `SELECT t.*, p.slug AS page_slug
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.page_id = ANY($1::int[])
+ AND t.active = true
+ AND ($2::text[] IS NULL OR t.holder = ANY($2::text[]))
+ ORDER BY t.page_id, t.row_num`,
+ [pageIds, opts.takesHoldersAllowList ?? null]
+ );
+ for (const r of rows) {
+ const take = takeRowToTake(r as Record<string, unknown>);
+ const bucket = out.get(take.page_id);
+ if (bucket) bucket.push(take);
+ }
+ return out;
+ }
+
+ /** v0.32.6 M5 — persist a probe run row. Idempotent on run_id. */
+export async function writeContradictionsRun(deps: PgliteTakesDeps, row: {
+ run_id: string;
+ judge_model: string;
+ prompt_version: string;
+ queries_evaluated: number;
+ queries_with_contradiction: number;
+ total_contradictions_flagged: number;
+ wilson_ci_lower: number;
+ wilson_ci_upper: number;
+ judge_errors_total: number;
+ cost_usd_total: number;
+ duration_ms: number;
+ source_tier_breakdown: Record<string, unknown>;
+ report_json: Record<string, unknown>;
+ }): Promise<boolean> {
+ const result = await deps.db.query(
+ `INSERT INTO eval_contradictions_runs (
+ run_id, judge_model, prompt_version,
+ queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
+ wilson_ci_lower, wilson_ci_upper, judge_errors_total,
+ cost_usd_total, duration_ms,
+ source_tier_breakdown, report_json
+ ) VALUES (
+ $1, $2, $3,
+ $4, $5, $6,
+ $7, $8, $9,
+ $10, $11,
+ $12::jsonb, $13::jsonb
+ )
+ ON CONFLICT (run_id) DO NOTHING`,
+ [
+ row.run_id, row.judge_model, row.prompt_version,
+ row.queries_evaluated, row.queries_with_contradiction, row.total_contradictions_flagged,
+ row.wilson_ci_lower, row.wilson_ci_upper, row.judge_errors_total,
+ row.cost_usd_total, row.duration_ms,
+ row.source_tier_breakdown, row.report_json,
+ ]
+ );
+ return (result.affectedRows ?? 0) > 0;
+ }
+
+ /** v0.32.6 M5 — read probe runs from the last N days. */
+export async function loadContradictionsTrend(deps: PgliteTakesDeps, days: number): Promise<Array<{
+ run_id: string;
+ ran_at: string;
+ judge_model: string;
+ queries_evaluated: number;
+ queries_with_contradiction: number;
+ total_contradictions_flagged: number;
+ wilson_ci_lower: number;
+ wilson_ci_upper: number;
+ judge_errors_total: number;
+ cost_usd_total: number;
+ duration_ms: number;
+ source_tier_breakdown: Record<string, unknown>;
+ report_json: Record<string, unknown>;
+ }>> {
+ const cutoff = new Date(Date.now() - Math.max(0, days) * 86400000);
+ const { rows } = await deps.db.query(
+ `SELECT run_id, ran_at, judge_model,
+ queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
+ wilson_ci_lower, wilson_ci_upper, judge_errors_total,
+ cost_usd_total, duration_ms,
+ source_tier_breakdown, report_json
+ FROM eval_contradictions_runs
+ WHERE ran_at >= $1
+ ORDER BY ran_at DESC`,
+ [cutoff]
+ );
+ return (rows as Record<string, unknown>[]).map((r) => ({
+ run_id: r.run_id as string,
+ ran_at: r.ran_at instanceof Date ? (r.ran_at as Date).toISOString() : String(r.ran_at),
+ judge_model: r.judge_model as string,
+ queries_evaluated: Number(r.queries_evaluated),
+ queries_with_contradiction: Number(r.queries_with_contradiction),
+ total_contradictions_flagged: Number(r.total_contradictions_flagged),
+ wilson_ci_lower: Number(r.wilson_ci_lower),
+ wilson_ci_upper: Number(r.wilson_ci_upper),
+ judge_errors_total: Number(r.judge_errors_total),
+ cost_usd_total: Number(r.cost_usd_total),
+ duration_ms: Number(r.duration_ms),
+ source_tier_breakdown: r.source_tier_breakdown as Record<string, unknown>,
+ report_json: r.report_json as Record<string, unknown>,
+ }));
+ }
+
+ /** v0.32.6 P2 — cache lookup; returns verdict JSON or null. */
+export async function getContradictionCacheEntry(deps: PgliteTakesDeps, key: {
+ chunk_a_hash: string;
+ chunk_b_hash: string;
+ model_id: string;
+ prompt_version: string;
+ truncation_policy: string;
+ }): Promise<Record<string, unknown> | null> {
+ const { rows } = await deps.db.query(
+ `SELECT verdict FROM eval_contradictions_cache
+ WHERE chunk_a_hash = $1
+ AND chunk_b_hash = $2
+ AND model_id = $3
+ AND prompt_version = $4
+ AND truncation_policy = $5
+ AND expires_at > now()
+ LIMIT 1`,
+ [key.chunk_a_hash, key.chunk_b_hash, key.model_id, key.prompt_version, key.truncation_policy]
+ );
+ if (rows.length === 0) return null;
+ return (rows[0] as Record<string, unknown>).verdict as Record<string, unknown>;
+ }
+
+ /** v0.32.6 P2 — cache upsert with TTL refresh on conflict. */
+export async function putContradictionCacheEntry(deps: PgliteTakesDeps, opts: {
+ chunk_a_hash: string;
+ chunk_b_hash: string;
+ model_id: string;
+ prompt_version: string;
+ truncation_policy: string;
+ verdict: Record<string, unknown>;
+ ttl_seconds?: number;
+ }): Promise<void> {
+ const ttl = Math.max(60, opts.ttl_seconds ?? 30 * 86400);
+ const expiresAt = new Date(Date.now() + ttl * 1000);
+ await deps.db.query(
+ `INSERT INTO eval_contradictions_cache (
+ chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy,
+ verdict, expires_at
+ ) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)
+ ON CONFLICT (chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)
+ DO UPDATE SET
+ verdict = EXCLUDED.verdict,
+ expires_at = EXCLUDED.expires_at,
+ created_at = now()`,
+ [
+ opts.chunk_a_hash, opts.chunk_b_hash, opts.model_id,
+ opts.prompt_version, opts.truncation_policy,
+ opts.verdict, expiresAt,
+ ]
+ );
+ }
+
+ /** v0.32.6 P2 — periodic sweep of expired cache rows. */
+export async function sweepContradictionCache(deps: PgliteTakesDeps): Promise<number> {
+ const result = await deps.db.query(
+ `DELETE FROM eval_contradictions_cache WHERE expires_at <= now()`
+ );
+ return result.affectedRows ?? 0;
+ }
+
+export async function listTakes(deps: PgliteTakesDeps, opts: TakesListOpts = {}): Promise<Take[]> {
+ const limit = clampSearchLimit(opts.limit, 100, 500);
+ const offset = Math.max(0, Math.floor(opts.offset ?? 0));
+ const active = opts.active ?? true;
+ const sortBy = opts.sortBy ?? 'created_at';
+ const { rows } = await deps.db.query(
+ `SELECT t.*, p.slug AS page_slug
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE 1=1
+ AND ($1::int IS NULL OR t.page_id = $1::int)
+ AND ($2::text IS NULL OR p.slug = $2::text)
+ AND ($3::text IS NULL OR t.holder = $3::text)
+ AND ($4::text IS NULL OR t.kind = $4::text)
+ AND ($5::boolean IS NULL OR t.active = $5::boolean)
+ AND (
+ $6::boolean IS NULL
+ OR ($6::boolean = true AND t.resolved_at IS NOT NULL)
+ OR ($6::boolean = false AND t.resolved_at IS NULL)
+ )
+ 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)
+ ORDER BY
+ CASE WHEN $8 = 'weight' THEN t.weight END DESC NULLS LAST,
+ CASE WHEN $8 = 'since_date' THEN t.since_date END DESC NULLS LAST,
+ CASE WHEN $8 = 'created_at' THEN t.created_at END DESC NULLS LAST
+ LIMIT $9 OFFSET $10`,
+ [
+ opts.page_id ?? null,
+ opts.page_slug ?? null,
+ opts.holder ?? null,
+ opts.kind ?? null,
+ active,
+ opts.resolved === undefined ? null : opts.resolved,
+ opts.takesHoldersAllowList ?? null,
+ sortBy,
+ limit,
+ offset,
+ // #2200-class: source scope via the take's page.source_id (array wins over scalar).
+ opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null,
+ opts.sourceIds && opts.sourceIds.length > 0 ? null : (opts.sourceId ?? null),
+ ]
+ );
+ return rows.map((r) => takeRowToTake(r as Record<string, unknown>));
+ }
+
+export async function searchTakes(
+ deps: PgliteTakesDeps,
+ query: string,
+ opts: SearchOpts & { takesHoldersAllowList?: string[] } = {},
+ ): Promise<TakeHit[]> {
+ const limit = clampSearchLimit(opts.limit, 30, 100);
+ const { rows } = await deps.db.query(
+ `SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
+ t.claim, t.kind, t.holder, t.weight,
+ word_similarity($1, t.claim)::real AS score
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.active
+ AND $1 <% t.claim
+ 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)
+ ORDER BY score DESC, t.weight DESC
+ LIMIT $3`,
+ [
+ query,
+ opts.takesHoldersAllowList ?? null,
+ limit,
+ opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null,
+ opts.sourceIds && opts.sourceIds.length > 0 ? null : (opts.sourceId ?? null),
+ ]
+ );
+ // Engine parity with PostgresEngine: coerce hit rows through the shared
+ // helper so both engines return the same TakeHit runtime shape (#2450).
+ return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ }
+
+export async function searchTakesVector(
+ deps: PgliteTakesDeps,
+ embedding: Float32Array,
+ opts: SearchOpts & { takesHoldersAllowList?: string[] } = {},
+ ): Promise<TakeHit[]> {
+ const limit = clampSearchLimit(opts.limit, 30, 100);
+ const vec = `[${Array.from(embedding).join(',')}]`;
+ const { rows } = await deps.db.query(
+ `SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
+ t.claim, t.kind, t.holder, t.weight,
+ (1 - (t.embedding <=> $1::vector))::real AS score
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.active
+ AND t.embedding IS NOT NULL
+ 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)
+ ORDER BY t.embedding <=> $1::vector
+ LIMIT $3`,
+ [
+ vec,
+ opts.takesHoldersAllowList ?? null,
+ limit,
+ opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null,
+ opts.sourceIds && opts.sourceIds.length > 0 ? null : (opts.sourceId ?? null),
+ ]
+ );
+ // Engine parity with PostgresEngine: coerce hit rows through the shared
+ // helper so both engines return the same TakeHit runtime shape (#2450).
+ return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ }
+
+export async function getTakeEmbeddings(deps: PgliteTakesDeps, ids: number[]): Promise<Map<number, Float32Array>> {
+ if (ids.length === 0) return new Map();
+ const { rows } = await deps.db.query(
+ `SELECT id, embedding FROM takes WHERE id = ANY($1::bigint[]) AND embedding IS NOT NULL`,
+ [ids]
+ );
+ const out = new Map<number, Float32Array>();
+ for (const r of rows as Array<{ id: number; embedding: unknown }>) {
+ const v = r.embedding;
+ if (typeof v === 'string') {
+ const trimmed = v.replace(/^\[|\]$/g, '');
+ const arr = trimmed.split(',').map(parseFloat).filter(n => !Number.isNaN(n));
+ out.set(Number(r.id), new Float32Array(arr));
+ } else if (Array.isArray(v)) {
+ out.set(Number(r.id), new Float32Array(v as number[]));
+ }
+ }
+ return out;
+ }
+
+export async function countStaleTakes(deps: PgliteTakesDeps): Promise<number> {
+ const { rows } = await deps.db.query(
+ `SELECT count(*)::int AS count FROM takes WHERE active AND embedding IS NULL`
+ );
+ return Number((rows[0] as { count?: number } | undefined)?.count ?? 0);
+ }
+
+export async function listStaleTakes(deps: PgliteTakesDeps): Promise<StaleTakeRow[]> {
+ const { rows } = await deps.db.query(
+ `SELECT t.id AS take_id, p.slug AS page_slug, t.row_num, t.claim
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.active AND t.embedding IS NULL
+ ORDER BY t.id
+ LIMIT 100000`
+ );
+ return rows as unknown as StaleTakeRow[];
+ }
+
+export async function updateTake(
+ deps: PgliteTakesDeps,
+ pageId: number,
+ rowNum: number,
+ fields: { weight?: number; since_date?: string; source?: string },
+ ): Promise<void> {
+ let weight = fields.weight;
+ if (weight !== undefined) {
+ const norm = normalizeWeightForStorage(weight);
+ if (norm.clamped) {
+ process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: updateTake clamped weight ${weight} → ${norm.weight}\n`);
+ }
+ weight = norm.weight;
+ }
+ const result = await deps.db.query(
+ `UPDATE takes SET
+ weight = COALESCE($3::real, weight),
+ since_date = COALESCE($4::text, since_date),
+ source = COALESCE($5::text, source),
+ updated_at = now()
+ WHERE page_id = $1 AND row_num = $2
+ RETURNING 1`,
+ [pageId, rowNum, weight ?? null, fields.since_date ?? null, fields.source ?? null]
+ );
+ if (result.rows.length === 0) {
+ throw new GBrainError(
+ 'TAKE_ROW_NOT_FOUND',
+ `take not found at page_id=${pageId} row=${rowNum}`,
+ 'list takes for this page with `gbrain takes <slug>` to see valid row numbers',
+ );
+ }
+ }
+
+export async function supersedeTake(
+ deps: PgliteTakesDeps,
+ pageId: number,
+ oldRow: number,
+ newRow: Omit<TakeBatchInput, 'page_id' | 'row_num' | 'superseded_by'>,
+ ): Promise<{ oldRow: number; newRow: number }> {
+ return await deps.db.transaction(async (tx) => {
+ const existingRes = await tx.query(
+ `SELECT resolved_at FROM takes WHERE page_id = $1 AND row_num = $2`,
+ [pageId, oldRow]
+ );
+ const existing = existingRes.rows[0] as { resolved_at?: unknown } | undefined;
+ if (!existing) {
+ throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${oldRow}`, 'list takes with `gbrain takes <slug>`');
+ }
+ if (existing.resolved_at) {
+ throw new GBrainError('TAKE_RESOLVED_IMMUTABLE', `take ${pageId}#${oldRow} is resolved`, 'resolved bets are immutable; add a new take instead');
+ }
+ const maxRowRes = await tx.query(
+ `SELECT COALESCE(MAX(row_num), 0) + 1 AS next FROM takes WHERE page_id = $1`,
+ [pageId]
+ );
+ const newRowNum = Number((maxRowRes.rows[0] as { next?: number })?.next ?? 1);
+ const w = Math.max(0, Math.min(1, newRow.weight ?? 0.5));
+ await tx.query(
+ `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, active)
+ VALUES ($1, $2, $3, $4, $5, $6, $7::text, $8::text, $9, $10)`,
+ [
+ pageId, newRowNum, newRow.claim, newRow.kind, newRow.holder, w,
+ newRow.since_date ?? null, newRow.until_date ?? null, newRow.source ?? null,
+ newRow.active ?? true,
+ ]
+ );
+ await tx.query(
+ `UPDATE takes SET active = false, superseded_by = $3, updated_at = now()
+ WHERE page_id = $1 AND row_num = $2`,
+ [pageId, oldRow, newRowNum]
+ );
+ return { oldRow, newRow: newRowNum };
+ });
+ }
+
+export async function resolveTake(deps: PgliteTakesDeps, pageId: number, rowNum: number, resolution: TakeResolution): Promise<void> {
+ const existingRes = await deps.db.query(
+ `SELECT resolved_at FROM takes WHERE page_id = $1 AND row_num = $2`,
+ [pageId, rowNum]
+ );
+ const existing = existingRes.rows[0] as { resolved_at?: unknown } | undefined;
+ if (!existing) {
+ throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${rowNum}`, 'list takes with `gbrain takes <slug>`');
+ }
+ if (existing.resolved_at) {
+ throw new GBrainError('TAKE_ALREADY_RESOLVED', `take ${pageId}#${rowNum} already resolved`, 'resolution is immutable; add a new take to record a new outcome');
+ }
+ // v0.30.0: derive (quality, outcome) tuple. quality wins when both set.
+ const { quality, outcome } = deriveResolutionTuple(resolution);
+ await deps.db.query(
+ `UPDATE takes SET
+ resolved_at = now(),
+ resolved_quality = $3::text,
+ resolved_outcome = $4,
+ resolved_value = $5::real,
+ resolved_unit = $6::text,
+ resolved_source = $7::text,
+ resolved_by = $8,
+ updated_at = now()
+ WHERE page_id = $1 AND row_num = $2`,
+ [
+ pageId, rowNum,
+ quality,
+ outcome,
+ resolution.value ?? null,
+ resolution.unit ?? null,
+ resolution.source ?? null,
+ resolution.resolvedBy,
+ ]
+ );
+ }
+
+ /**
+ * v0.30.0: aggregate scorecard. SQL-level allow-list filter (D4 fail-closed).
+ * Hidden-holder rows contribute zero to aggregates.
+ */
+export async function getScorecard(deps: PgliteTakesDeps, opts: TakesScorecardOpts, allowList: string[] | undefined): Promise<TakesScorecard> {
+ // Build the WHERE clause with positional params. PGLite (postgres-via-WASM)
+ // shares the SQL dialect with real Postgres so the math expressions match.
+ const params: unknown[] = [];
+ const clauses: string[] = [];
+ if (opts.holder !== undefined) { params.push(opts.holder); clauses.push(`AND holder = $${params.length}`); }
+ if (opts.domainPrefix !== undefined) {
+ params.push(opts.domainPrefix + '%');
+ clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.slug LIKE $${params.length})`);
+ }
+ if (opts.since !== undefined) { params.push(opts.since); clauses.push(`AND since_date >= $${params.length}`); }
+ if (opts.until !== undefined) { params.push(opts.until); clauses.push(`AND since_date <= $${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).
+ const srcIds = opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null;
+ if (srcIds) { params.push(srcIds); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($${params.length}::text[]))`); }
+ else if (opts.sourceId) { params.push(opts.sourceId); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = $${params.length})`); }
+ const where = clauses.join(' ');
+ // v0.36.1.1 T1c: `resolved` deliberately filters to the 3-state subset
+ // (correct|incorrect|partial) — NOT `resolved_quality IS NOT NULL` — so
+ // historical comparisons against pre-v74 scorecards stay valid.
+ // `unresolvable_count` is a sibling field counting the new 4th state.
+ const res = await deps.db.query(
+ `SELECT
+ COUNT(*) FILTER (WHERE kind = 'bet')::int AS total_bets,
+ COUNT(*) FILTER (WHERE resolved_quality IN ('correct','incorrect','partial'))::int AS resolved,
+ COUNT(*) FILTER (WHERE resolved_quality = 'correct')::int AS correct,
+ COUNT(*) FILTER (WHERE resolved_quality = 'incorrect')::int AS incorrect,
+ COUNT(*) FILTER (WHERE resolved_quality = 'partial')::int AS partial,
+ COUNT(*) FILTER (WHERE resolved_quality = 'unresolvable')::int AS unresolvable_count,
+ AVG(
+ CASE WHEN resolved_quality IN ('correct','incorrect')
+ THEN POWER(weight - (CASE resolved_quality WHEN 'correct' THEN 1 ELSE 0 END), 2)
+ END
+ )::float AS brier
+ FROM takes
+ WHERE 1=1 ${where}`,
+ params,
+ );
+ const r = res.rows[0] as { total_bets: number; resolved: number; correct: number; incorrect: number; partial: number; unresolvable_count: number; brier: number | null };
+ return finalizeScorecard(r);
+ }
+
+ /**
+ * v0.30.0: calibration curve. Bins resolved correct/incorrect bets by stated weight.
+ */
+export async function getCalibrationCurve(deps: PgliteTakesDeps, opts: CalibrationCurveOpts, allowList: string[] | undefined): Promise<CalibrationBucket[]> {
+ const bucketSize = opts.bucketSize && opts.bucketSize > 0 && opts.bucketSize <= 1 ? opts.bucketSize : 0.1;
+ const maxIdx = Math.floor(1 / bucketSize) - 1;
+ const params: unknown[] = [bucketSize, maxIdx];
+ const clauses: string[] = [];
+ 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).
+ const srcIds = opts.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : null;
+ if (srcIds) { params.push(srcIds); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($${params.length}::text[]))`); }
+ else if (opts.sourceId) { params.push(opts.sourceId); clauses.push(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = $${params.length})`); }
+ const where = clauses.join(' ');
+ // NUMERIC casts for exact decimal arithmetic — keeps PGLite + Postgres
+ // bucket boundaries identical at FP-edge weights (e.g. 0.7/0.1).
+ // See parity test in test/e2e/takes-scorecard-parity.test.ts.
+ const res = await deps.db.query(
+ `WITH binned AS (
+ SELECT
+ LEAST(FLOOR(weight::numeric / $1::numeric)::int, $2::int)::int AS bucket_idx,
+ weight,
+ (resolved_quality = 'correct')::int AS hit
+ FROM takes
+ WHERE resolved_quality IN ('correct','incorrect')
+ ${where}
+ )
+ SELECT
+ (bucket_idx::numeric * $1::numeric)::float AS bucket_lo,
+ ((bucket_idx + 1)::numeric * $1::numeric)::float AS bucket_hi,
+ COUNT(*)::int AS n,
+ AVG(hit)::float AS observed,
+ AVG(weight)::float AS predicted
+ FROM binned
+ GROUP BY bucket_idx
+ ORDER BY bucket_idx`,
+ params,
+ );
+ return (res.rows as { bucket_lo: number; bucket_hi: number; n: number; observed: number | null; predicted: number | null }[]).map(r => ({
+ bucket_lo: r.bucket_lo,
+ bucket_hi: r.bucket_hi,
+ n: r.n,
+ observed: r.n > 0 ? r.observed : null,
+ predicted: r.n > 0 ? r.predicted : null,
+ }));
+ }
+
+export async function addSynthesisEvidence(deps: PgliteTakesDeps, rowsIn: SynthesisEvidenceInput[]): Promise<number> {
+ if (rowsIn.length === 0) return 0;
+ const synthesisIds = rowsIn.map(r => r.synthesis_page_id);
+ const takePageIds = rowsIn.map(r => r.take_page_id);
+ const takeRowNums = rowsIn.map(r => r.take_row_num);
+ const citationIxs = rowsIn.map(r => r.citation_index);
+ const result = await deps.db.query(
+ `INSERT INTO synthesis_evidence (synthesis_page_id, take_page_id, take_row_num, citation_index)
+ SELECT v.synthesis_page_id::int, v.take_page_id::int, v.take_row_num::int, v.citation_index::int
+ FROM unnest($1::int[], $2::int[], $3::int[], $4::int[])
+ AS v(synthesis_page_id, take_page_id, take_row_num, citation_index)
+ ON CONFLICT (synthesis_page_id, take_page_id, take_row_num) DO NOTHING
+ RETURNING 1`,
+ [synthesisIds, takePageIds, takeRowNums, citationIxs]
+ );
+ return result.rows.length;
+ }
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 194a836561..2086cd9f23 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -9,7 +9,7 @@ import type {
TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,
TakeResolution, SynthesisEvidenceInput,
TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,
- FactRow, FactKind, FactVisibility, FactInsertStatus,
+ FactRow, FactInsertStatus,
NewFact, FactListOpts, FactsHealth,
SourceRow,
} from './engine.ts';
@@ -31,10 +31,6 @@ import {
normalizeDimension,
isNovelDimension,
} from './chronicle/ontology.ts';
-import {
- resolveRecencyDecayMap,
- DEFAULT_FALLBACK,
-} from './search/recency-decay.ts';
import { logDbDisconnect } from './audit/db-disconnect-audit.ts';
import { logPoolRecovery } from './audit/pool-recovery-audit.ts';
import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';
@@ -42,10 +38,8 @@ import type {
DomainBankSampleOpts, CorpusSampleOpts, DomainBankRow,
} from './types.ts';
import { MAX_SEARCH_LIMIT, clampSearchLimit } from './engine.ts';
-import { deriveResolutionTuple, finalizeScorecard } from './takes-resolution.ts';
-import { normalizeWeightForStorage } from './takes-fence.ts';
-import { executeRawJsonb } from './sql-query.ts';
-import { sanitizeForJsonb, buildLinkRows, buildTimelineRows, buildTakeRows } from './batch-rows.ts';
+import { executeRawJsonb, type SqlValue } from './sql-query.ts';
+import { sanitizeForJsonb, buildLinkRows, buildTimelineRows } from './batch-rows.ts';
import { runMigrations } from './migrate.ts';
import { SCHEMA_SQL } from './schema-embedded.ts';
import { verifySchema } from './schema-verify.ts';
@@ -79,15 +73,14 @@ import type {
EmotionalWeightInputRow, EmotionalWeightWriteRow,
EnrichCandidatesOpts, EnrichCandidate,
} from './types.ts';
-import { GBrainError, PAGE_SORT_SQL, ENRICH_ORDER_SQL } from './types.ts';
+import { GBrainError, PAGE_SORT_SQL } from './types.ts';
import { finalizeLastSeen } from './chronicle/last-seen.ts';
-import { computeAnomaliesFromBuckets } from './cycle/anomaly.ts';
import * as db from './db.ts';
import { ConnectionManager, DEFAULT_DIRECT_POOL_SIZE } from './connection-manager.ts';
import { logConnectionEvent } from './connection-audit.ts';
-import { validateSlug, contentHash, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, takeRowToTake, takeHitRowToHit, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
+import { validateSlug, contentHash, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, parseEmbedding, tryParseEmbedding, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
-import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
+import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
import { unverifiedExtractionFragment } from './extraction-review.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { DELETE_BATCH_SIZE } from './engine-constants.ts';
@@ -96,6 +89,14 @@ import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './o
import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';
+import * as factsImpl from './postgres-engine/facts.ts';
+import type { PgFactsDeps } from './postgres-engine/facts.ts';
+import * as takesImpl from './postgres-engine/takes.ts';
+import type { PgTakesDeps } from './postgres-engine/takes.ts';
+import * as codeEdgesImpl from './postgres-engine/code-edges.ts';
+import type { PgCodeEdgesDeps } from './postgres-engine/code-edges.ts';
+import * as salienceImpl from './postgres-engine/salience.ts';
+import type { PgSalienceDeps } from './postgres-engine/salience.ts';
function escapeSqlStringLiteral(value: string): string {
return value.replace(/'/g, "''");
@@ -4589,93 +4590,17 @@ export class PostgresEngine implements BrainEngine {
// v0.31: Hot memory — facts table operations
// ============================================================
- async insertFact(
- input: NewFact,
- ctx: { source_id: string; supersedeId?: number },
- ): Promise<{ id: number; status: FactInsertStatus }> {
- const sql = this.sql;
- const validFrom = input.valid_from ?? new Date();
- const validUntil = input.valid_until ?? null;
- const kind = input.kind ?? 'fact';
- const visibility = input.visibility ?? 'private';
- const notability = input.notability ?? 'medium';
- const confidence = input.confidence ?? 1.0;
- const entitySlug = input.entity_slug ?? null;
- const context = input.context ?? null;
- const sourceSession = input.source_session ?? null;
- const embedding = input.embedding ?? null;
- const embeddedAt = embedding ? new Date() : null;
- const embedLit = embedding ? toPgVectorLiteral(embedding) : null;
- // v0.41.15.0 (T6, codex #20): match cast to actual column type so
- // a halfvec(N) column doesn't pay an implicit-cast round-trip + can
- // run on pgvector versions that lack the auto vector→halfvec cast.
- const castSuffix = await this.resolveFactsEmbeddingCast();
- // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
- const claimMetric = input.claim_metric ?? null;
- const claimValue = input.claim_value ?? null;
- const claimUnit = input.claim_unit ?? null;
- const claimPeriod = input.claim_period ?? null;
-
- if (ctx.supersedeId !== undefined) {
- // Per-entity advisory lock + atomic insert + supersede in one txn.
- const supersedeId = ctx.supersedeId;
- const newId = await sql.begin(async (tx) => {
- if (entitySlug) {
- await tx`SELECT pg_advisory_xact_lock(hashtextextended(${ctx.source_id} || ':' || ${entitySlug}, 0))`;
- }
- const ins = await tx<Array<{ id: number }>>`
- INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
- ) VALUES (
- ${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
- ${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
- ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
- ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
- ) RETURNING id
- `;
- const id = Number(ins[0].id);
- await tx`UPDATE facts SET expired_at = now(), superseded_by = ${id}
- WHERE id = ${supersedeId} AND expired_at IS NULL`;
- return id;
- });
- return { id: newId, status: 'superseded' };
- }
-
- // Plain insert path with optional advisory lock for the dedup window.
- const id = await sql.begin(async (tx) => {
- if (entitySlug) {
- await tx`SELECT pg_advisory_xact_lock(hashtextextended(${ctx.source_id} || ':' || ${entitySlug}, 0))`;
- }
- const ins = await tx<Array<{ id: number }>>`
- INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
- ) VALUES (
- ${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
- ${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
- ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
- ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
- ) RETURNING id
- `;
- return Number(ins[0].id);
- });
- return { id, status: 'inserted' };
- }
+ // Peeled into ./postgres-engine/facts.ts (containment sprint C15): the
+ // methods below are one-line delegates over free functions with a narrow
+ // deps surface.
- async expireFact(id: number, opts?: { supersededBy?: number; at?: Date }): Promise<boolean> {
- const sql = this.sql;
- const at = opts?.at ?? new Date();
- const supersededBy = opts?.supersededBy ?? null;
- const result = await sql`
- UPDATE facts SET expired_at = ${at}, superseded_by = COALESCE(${supersededBy}, superseded_by)
- WHERE id = ${id} AND expired_at IS NULL
- `;
- return (result.count ?? 0) > 0;
+ /** Narrow deps for the peeled facts module. */
+ private get factsDeps(): PgFactsDeps {
+ const self = this;
+ return {
+ get sql() { return self.sql; },
+ resolveFactsEmbeddingCast: () => self.resolveFactsEmbeddingCast(),
+ };
}
/**
@@ -4731,72 +4656,22 @@ export class PostgresEngine implements BrainEngine {
return this._factsEmbeddingCastSuffix;
}
+ async insertFact(
+ input: NewFact,
+ ctx: { source_id: string; supersedeId?: number },
+ ): Promise<{ id: number; status: FactInsertStatus }> {
+ return factsImpl.insertFact(this.factsDeps, input, ctx);
+ }
+
+ async expireFact(id: number, opts?: { supersededBy?: number; at?: Date }): Promise<boolean> {
+ return factsImpl.expireFact(this.factsDeps, id, opts);
+ }
+
async insertFacts(
rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
ctx: { source_id: string },
): Promise<{ inserted: number; ids: number[] }> {
- if (rows.length === 0) return { inserted: 0, ids: [] };
-
- const sql = this.sql;
- // v0.41.15.0 (T6, codex #20): resolve the embedding-cast suffix
- // ONCE per process so the cast matches the actual column type
- // (halfvec vs vector). The probe is cached after first call.
- const castSuffix = await this.resolveFactsEmbeddingCast();
- // Single transaction so the v51 partial UNIQUE index can roll back
- // the whole batch on constraint violation. Per-row INSERTs (not
- // multi-row VALUES) keep the embedding-vs-no-embedding branching
- // readable; batch sizes are small (5-30 rows per page in practice).
- // No supersede flow in this path — fence reconciliation is the
- // canonical source-of-truth direction, not the consolidator path.
- const ids = await sql.begin(async (tx) => {
- const out: number[] = [];
- for (const input of rows) {
- const validFrom = input.valid_from ?? new Date();
- const validUntil = input.valid_until ?? null;
- const kind = input.kind ?? 'fact';
- const visibility = input.visibility ?? 'private';
- const notability = input.notability ?? 'medium';
- const confidence = input.confidence ?? 1.0;
- const entitySlug = input.entity_slug ?? null;
- const context = input.context ?? null;
- const sourceSession = input.source_session ?? null;
- const embedding = input.embedding ?? null;
- const embeddedAt = embedding ? new Date() : null;
- const embedLit = embedding ? toPgVectorLiteral(embedding) : null;
- // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
- const claimMetric = input.claim_metric ?? null;
- const claimValue = input.claim_value ?? null;
- const claimUnit = input.claim_unit ?? null;
- const claimPeriod = input.claim_period ?? null;
- // v0.40.2.0 — event_type column (Commit 1 migration v89).
- const eventType = input.event_type ?? null;
-
- const ins = await tx<Array<{ id: number }>>`
- INSERT INTO facts (
- source_id, entity_slug, fact, kind, visibility, notability, context,
- valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
- row_num, source_markdown_slug,
- claim_metric, claim_value, claim_unit, claim_period,
- event_type
- ) VALUES (
- ${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
- ${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
- ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
- ${input.row_num}, ${input.source_markdown_slug},
- ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
- ${eventType}
- )
- ON CONFLICT (source_id, source_markdown_slug, row_num)
- WHERE row_num IS NOT NULL
- DO NOTHING
- RETURNING id
- `;
- if (ins[0]) out.push(Number(ins[0].id));
- }
- return out;
- });
- return { inserted: ids.length, ids };
+ return factsImpl.insertFacts(this.factsDeps, rows, ctx);
}
async deleteFactsForPage(
@@ -4804,32 +4679,7 @@ export class PostgresEngine implements BrainEngine {
source_id: string,
opts?: { excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean },
): Promise<{ deleted: number }> {
- const sql = this.sql;
- const prefixes = opts?.excludeSourcePrefixes;
- // #2646: keep soft-expired legacy rows (row_num NULL — never
- // fence-owned) so a fence reconcile can't destroy forget_fact's
- // legacy DB-only forget record.
- const expiredLegacyFilter = opts?.preserveExpiredLegacy
- ? sql`AND NOT (row_num IS NULL AND expired_at IS NOT NULL)`
- : sql``;
- if (prefixes && prefixes.length > 0) {
- // #1928: keep rows whose `source` matches an excluded prefix (e.g.
- // `cli:` conversation facts). COALESCE so NULL/empty-source fence rows
- // stay deletable — only the explicitly-protected prefixes survive.
- const patterns = prefixes.map(p => `${p}%`);
- const result = await sql`
- DELETE FROM facts
- WHERE source_id = ${source_id}
- AND source_markdown_slug = ${slug}
- AND NOT (COALESCE(source, '') LIKE ANY(${patterns}))
- ${expiredLegacyFilter}
- `;
- return { deleted: result.count ?? 0 };
- }
- const result = await sql`
- DELETE FROM facts WHERE source_id = ${source_id} AND source_markdown_slug = ${slug} ${expiredLegacyFilter}
- `;
- return { deleted: result.count ?? 0 };
+ return factsImpl.deleteFactsForPage(this.factsDeps, slug, source_id, opts);
}
async listFactsByEntity(
@@ -4837,23 +4687,7 @@ export class PostgresEngine implements BrainEngine {
entitySlug: string,
opts?: FactListOpts,
): Promise<FactRow[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
- const offset = Math.max(0, opts?.offset ?? 0);
- const activeOnly = opts?.activeOnly !== false;
- const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;
- const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
- const rows = await sql<FactRowSqlShape[]>`
- SELECT * FROM facts
- WHERE source_id = ${source_id}
- AND entity_slug = ${entitySlug}
- ${activeOnly ? sql`AND expired_at IS NULL` : sql``}
- ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}
- ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
- ORDER BY valid_from DESC, id DESC
- LIMIT ${limit} OFFSET ${offset}
- `;
- return rows.map(rowToFactPg);
+ return factsImpl.listFactsByEntity(this.factsDeps, source_id, entitySlug, opts);
}
async listFactsSince(
@@ -4861,25 +4695,7 @@ export class PostgresEngine implements BrainEngine {
since: Date,
opts?: FactListOpts & { entitySlug?: string },
): Promise<FactRow[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
- const offset = Math.max(0, opts?.offset ?? 0);
- const activeOnly = opts?.activeOnly !== false;
- const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;
- const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
- const entitySlug = opts?.entitySlug ?? null;
- const rows = await sql<FactRowSqlShape[]>`
- SELECT * FROM facts
- WHERE source_id = ${source_id}
- AND created_at >= ${since}
- ${entitySlug ? sql`AND entity_slug = ${entitySlug}` : sql``}
- ${activeOnly ? sql`AND expired_at IS NULL` : sql``}
- ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}
- ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
- ORDER BY created_at DESC, id DESC
- LIMIT ${limit} OFFSET ${offset}
- `;
- return rows.map(rowToFactPg);
+ return factsImpl.listFactsSince(this.factsDeps, source_id, since, opts);
}
async listFactsBySession(
@@ -4887,53 +4703,18 @@ export class PostgresEngine implements BrainEngine {
sessionId: string,
opts?: FactListOpts,
): Promise<FactRow[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
- const offset = Math.max(0, opts?.offset ?? 0);
- const activeOnly = opts?.activeOnly !== false;
- const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;
- const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
- const rows = await sql<FactRowSqlShape[]>`
- SELECT * FROM facts
- WHERE source_id = ${source_id}
- AND source_session = ${sessionId}
- ${activeOnly ? sql`AND expired_at IS NULL` : sql``}
- ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}
- ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
- ORDER BY created_at DESC, id DESC
- LIMIT ${limit} OFFSET ${offset}
- `;
- return rows.map(rowToFactPg);
+ return factsImpl.listFactsBySession(this.factsDeps, source_id, sessionId, opts);
}
async listSupersessions(
source_id: string,
opts?: { since?: Date; limit?: number },
): Promise<FactRow[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
- const since = opts?.since ?? null;
- const rows = await sql<FactRowSqlShape[]>`
- SELECT * FROM facts
- WHERE source_id = ${source_id}
- AND expired_at IS NOT NULL
- AND superseded_by IS NOT NULL
- ${since ? sql`AND expired_at >= ${since}` : sql``}
- ORDER BY expired_at DESC, id DESC
- LIMIT ${limit}
- `;
- return rows.map(rowToFactPg);
+ return factsImpl.listSupersessions(this.factsDeps, source_id, opts);
}
async countUnconsolidatedFacts(source_id: string): Promise<number> {
- const sql = this.sql;
- const rows = await sql<{ count: number }[]>`
- SELECT COUNT(*)::int AS count FROM facts
- WHERE source_id = ${source_id}
- AND consolidated_at IS NULL
- AND expired_at IS NULL
- `;
- return Number(rows[0]?.count ?? 0);
+ return factsImpl.countUnconsolidatedFacts(this.factsDeps, source_id);
}
async findCandidateDuplicates(
@@ -4942,225 +4723,50 @@ export class PostgresEngine implements BrainEngine {
factText: string,
opts?: { k?: number; embedding?: Float32Array },
): Promise<FactRow[]> {
- const sql = this.sql;
- const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
- if (opts?.embedding) {
- const lit = toPgVectorLiteral(opts.embedding);
- const rows = await sql<FactRowSqlShape[]>`
- SELECT * FROM facts
- WHERE source_id = ${source_id}
- AND entity_slug = ${entitySlug}
- AND expired_at IS NULL
- AND embedding IS NOT NULL
- ORDER BY embedding <=> ${sql.unsafe(`'${lit}'::vector`)}
- LIMIT ${k}
- `;
- return rows.map(rowToFactPg);
- }
- const rows = await sql<FactRowSqlShape[]>`
- SELECT * FROM facts
- WHERE source_id = ${source_id}
- AND entity_slug = ${entitySlug}
- AND expired_at IS NULL
- ORDER BY created_at DESC, id DESC
- LIMIT ${k}
- `;
- return rows.map(rowToFactPg);
+ return factsImpl.findCandidateDuplicates(this.factsDeps, source_id, entitySlug, factText, opts);
}
async consolidateFact(id: number, takeId: number): Promise<void> {
- const sql = this.sql;
- await sql`UPDATE facts SET consolidated_at = now(), consolidated_into = ${takeId} WHERE id = ${id}`;
+ return factsImpl.consolidateFact(this.factsDeps, id, takeId);
}
async findTrajectory(opts: import('./engine.ts').TrajectoryOpts): Promise<import('./engine.ts').TrajectoryPoint[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts.limit, 100, 500);
- const sinceDate = opts.since ? new Date(opts.since) : null;
- const untilDate = opts.until ? new Date(opts.until) : null;
- const metric = opts.metric ?? null;
- const kind = opts.kind ?? 'all';
- const useArray = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;
- const sourceIds = useArray ? opts.sourceIds! : null;
- const sourceId = opts.sourceId ?? 'default';
- const remoteFilter = opts.remote === true;
-
- // Source-scope predicate: array path (federated) wins over scalar.
- // Engine.ts contract: returns chronological points; regressions +
- // drift_score are computed by the caller (src/core/trajectory.ts).
- // v0.40.2.0 — kind filter ('all'|'metric'|'event'); event_type column.
- const rows = await sql<Array<{
- id: number;
- valid_from: Date;
- claim_metric: string | null;
- claim_value: number | null;
- claim_unit: string | null;
- claim_period: string | null;
- event_type: string | null;
- fact: string;
- source_session: string | null;
- source_markdown_slug: string | null;
- embedding: string | null;
- }>>`
- SELECT id, valid_from,
- claim_metric, claim_value, claim_unit, claim_period,
- event_type,
- fact, source_session, source_markdown_slug,
- embedding::text AS embedding
- FROM facts
- WHERE ${useArray ? sql`source_id = ANY(${sourceIds}::text[])` : sql`source_id = ${sourceId}`}
- AND entity_slug = ${opts.entitySlug}
- AND expired_at IS NULL
- ${remoteFilter ? sql`AND visibility = 'world'` : sql``}
- ${metric !== null ? sql`AND claim_metric = ${metric}` : sql``}
- ${kind === 'metric' ? sql`AND claim_metric IS NOT NULL` : sql``}
- ${kind === 'event' ? sql`AND event_type IS NOT NULL` : sql``}
- ${sinceDate ? sql`AND valid_from >= ${sinceDate}` : sql``}
- ${untilDate ? sql`AND valid_from <= ${untilDate}` : sql``}
- ORDER BY valid_from ASC, id ASC
- LIMIT ${limit}
- `;
-
- return rows.map(r => ({
- fact_id: Number(r.id),
- valid_from: r.valid_from,
- metric: r.claim_metric,
- value: r.claim_value === null ? null : Number(r.claim_value),
- unit: r.claim_unit,
- period: r.claim_period,
- event_type: r.event_type,
- text: r.fact,
- source_session: r.source_session,
- source_markdown_slug: r.source_markdown_slug,
- embedding: tryParseEmbedding(r.embedding),
- }));
+ return factsImpl.findTrajectory(this.factsDeps, opts);
}
async getFactsHealth(source_id: string): Promise<FactsHealth> {
- const sql = this.sql;
- const totals = await sql<Array<{
- total_active: bigint; total_today: bigint; total_week: bigint;
- total_expired: bigint; total_consolidated: bigint;
- }>>`
- SELECT
- COUNT(*) FILTER (WHERE expired_at IS NULL) AS total_active,
- COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '24 hours') AS total_today,
- COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '7 days') AS total_week,
- COUNT(*) FILTER (WHERE expired_at IS NOT NULL) AS total_expired,
- COUNT(*) FILTER (WHERE consolidated_at IS NOT NULL) AS total_consolidated
- FROM facts WHERE source_id = ${source_id}
- `;
- const top = await sql<Array<{ entity_slug: string; count: bigint }>>`
- SELECT entity_slug, COUNT(*) AS count
- FROM facts
- WHERE source_id = ${source_id} AND expired_at IS NULL AND entity_slug IS NOT NULL
- GROUP BY entity_slug
- ORDER BY count DESC, entity_slug ASC
- LIMIT 5
- `;
- const r = totals[0] ?? {
- total_active: 0n, total_today: 0n, total_week: 0n, total_expired: 0n, total_consolidated: 0n,
- };
- return {
- source_id,
- total_active: Number(r.total_active),
- total_today: Number(r.total_today),
- total_week: Number(r.total_week),
- total_expired: Number(r.total_expired),
- total_consolidated: Number(r.total_consolidated),
- top_entities: top.map(t => ({ entity_slug: t.entity_slug, count: Number(t.count) })),
- };
+ return factsImpl.getFactsHealth(this.factsDeps, source_id);
}
// ============================================================
// v0.28: Takes (typed/weighted/attributed claims) + synthesis_evidence
// ============================================================
+ // Peeled into ./postgres-engine/takes.ts (containment sprint C15).
+
+ /** Narrow deps for the peeled takes module. */
+ private get takesDeps(): PgTakesDeps {
+ const self = this;
+ return {
+ get sql() { return self.sql; },
+ batchRetry: <T>(auditSite: BatchAuditSite, signal: AbortSignal | undefined, fn: () => Promise<T>, batchSize: number) =>
+ self.batchRetry(auditSite, signal, fn, batchSize),
+ executeRawJsonb: <R = Record<string, unknown>>(sqlText: string, scalarParams: SqlValue[], jsonbParams: unknown[]) =>
+ executeRawJsonb<R>(self, sqlText, scalarParams, jsonbParams),
+ };
+ }
+
async addTakesBatch(rowsIn: TakeBatchInput[], opts?: BatchOpts): Promise<number> {
- if (rowsIn.length === 0) return 0;
- // v0.42.26: takes is a batch primitive too — wrap in batchRetry so a
- // Supavisor circuit-breaker blip doesn't silently drop takes the way it
- // could before (links/timeline already had this; takes was the gap).
- return this.batchRetry(opts?.auditSite ?? 'addTakesBatch', opts?.signal, () => this._addTakesBatchOnce(rowsIn), rowsIn.length);
- }
-
- private async _addTakesBatchOnce(rowsIn: TakeBatchInput[]): Promise<number> {
- // #1861: JSONB jsonb_to_recordset instead of unnest(${arr}::text[]). `claim`
- // is free LLM-extracted prose with the same array-literal crash hazard as
- // link context. JSONB additionally lets us declare NATIVE recordset column
- // types and emit JSON-native numbers/booleans, which retires the old
- // postgres-js ${actives}::text[]::boolean[] element-type workaround entirely.
- // Weight clamp/round + NUL-stripping live in buildTakeRows (shared w/ PGLite).
- // NOTE: ON CONFLICT here is DO UPDATE (not DO NOTHING) — an intra-batch
- // duplicate (page_id, row_num) errors, identical to the pre-#1861 unnest path.
- const { rows, weightClamped } = buildTakeRows(rowsIn);
- if (weightClamped > 0) {
- process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: ${weightClamped} row(s) had weight outside [0,1]; clamped\n`);
- }
- const result = await executeRawJsonb(
- this,
- `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active)
- SELECT v.page_id, v.row_num, v.claim, v.kind, v.holder, v.weight,
- v.since_date, v.until_date, v.source, v.superseded_by, v.active
- FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(
- page_id int, row_num int, claim text, kind text, holder text, weight real,
- since_date text, until_date text, source text, superseded_by int, active boolean
- )
- ON CONFLICT (page_id, row_num) DO UPDATE SET
- claim = EXCLUDED.claim,
- kind = EXCLUDED.kind,
- holder = EXCLUDED.holder,
- weight = EXCLUDED.weight,
- since_date = EXCLUDED.since_date,
- until_date = EXCLUDED.until_date,
- source = EXCLUDED.source,
- superseded_by = EXCLUDED.superseded_by,
- active = EXCLUDED.active,
- updated_at = now()
- RETURNING 1`,
- [],
- [{ rows }],
- );
- return result.length;
+ return takesImpl.addTakesBatch(this.takesDeps, rowsIn, opts);
}
- /**
- * v0.32.6 — batched per-page active-takes fetch (P1). One round-trip
- * regardless of how many pages the caller passes. Honors holder allow-list
- * for MCP scope enforcement. Pages with no active takes get an empty array.
- */
async listActiveTakesForPages(
pageIds: number[],
opts: { takesHoldersAllowList?: string[] } = {},
): Promise<Map<number, Take[]>> {
- const out = new Map<number, Take[]>();
- for (const pid of pageIds) out.set(pid, []);
- if (pageIds.length === 0) return out;
- const sql = this.sql;
- const rows = await sql`
- SELECT t.*, p.slug AS page_slug
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.page_id = ANY(${pageIds}::int[])
- AND t.active = true
- AND (
- ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
- OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
- )
- ORDER BY t.page_id, t.row_num
- `;
- for (const r of rows) {
- const take = takeRowToTake(r as Record<string, unknown>);
- const bucket = out.get(take.page_id);
- if (bucket) bucket.push(take);
- }
- return out;
+ return takesImpl.listActiveTakesForPages(this.takesDeps, pageIds, opts);
}
- /**
- * v0.32.6 — persist a contradiction-probe run row (M5). Idempotent on
- * run_id via ON CONFLICT DO NOTHING. Returns true iff a row was inserted.
- */
async writeContradictionsRun(row: {
run_id: string;
judge_model: string;
@@ -5176,31 +4782,9 @@ export class PostgresEngine implements BrainEngine {
source_tier_breakdown: Record<string, unknown>;
report_json: Record<string, unknown>;
}): Promise<boolean> {
- const sql = this.sql;
- const result = await sql`
- INSERT INTO eval_contradictions_runs (
- run_id, judge_model, prompt_version,
- queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
- wilson_ci_lower, wilson_ci_upper, judge_errors_total,
- cost_usd_total, duration_ms,
- source_tier_breakdown, report_json
- ) VALUES (
- ${row.run_id}, ${row.judge_model}, ${row.prompt_version},
- ${row.queries_evaluated}, ${row.queries_with_contradiction}, ${row.total_contradictions_flagged},
- ${row.wilson_ci_lower}, ${row.wilson_ci_upper}, ${row.judge_errors_total},
- ${row.cost_usd_total}, ${row.duration_ms},
- ${sql.json(row.source_tier_breakdown as Parameters<typeof sql.json>[0])},
- ${sql.json(row.report_json as Parameters<typeof sql.json>[0])}
- )
- ON CONFLICT (run_id) DO NOTHING
- `;
- return result.count > 0;
+ return takesImpl.writeContradictionsRun(this.takesDeps, row);
}
- /**
- * v0.32.6 — load probe runs from the last N days, newest first (M5).
- * Used by `trend` sub-subcommand and the doctor `contradictions` check.
- */
async loadContradictionsTrend(days: number): Promise<Array<{
run_id: string;
ran_at: string;
@@ -5216,39 +4800,9 @@ export class PostgresEngine implements BrainEngine {
source_tier_breakdown: Record<string, unknown>;
report_json: Record<string, unknown>;
}>> {
- const sql = this.sql;
- const cutoff = new Date(Date.now() - Math.max(0, days) * 86400000);
- const rows = await sql`
- SELECT run_id, ran_at, judge_model,
- queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
- wilson_ci_lower, wilson_ci_upper, judge_errors_total,
- cost_usd_total, duration_ms,
- source_tier_breakdown, report_json
- FROM eval_contradictions_runs
- WHERE ran_at >= ${cutoff}
- ORDER BY ran_at DESC
- `;
- return rows.map((r) => ({
- run_id: r.run_id as string,
- ran_at: (r.ran_at instanceof Date ? r.ran_at.toISOString() : String(r.ran_at)),
- judge_model: r.judge_model as string,
- queries_evaluated: Number(r.queries_evaluated),
- queries_with_contradiction: Number(r.queries_with_contradiction),
- total_contradictions_flagged: Number(r.total_contradictions_flagged),
- wilson_ci_lower: Number(r.wilson_ci_lower),
- wilson_ci_upper: Number(r.wilson_ci_upper),
- judge_errors_total: Number(r.judge_errors_total),
- cost_usd_total: Number(r.cost_usd_total),
- duration_ms: Number(r.duration_ms),
- source_tier_breakdown: r.source_tier_breakdown as Record<string, unknown>,
- report_json: r.report_json as Record<string, unknown>,
- }));
+ return takesImpl.loadContradictionsTrend(this.takesDeps, days);
}
- /**
- * v0.32.6 — judge cache lookup (P2). Returns verdict JSON for a non-
- * expired row matching the full 5-component key, else NULL.
- */
async getContradictionCacheEntry(key: {
chunk_a_hash: string;
chunk_b_hash: string;
@@ -5256,26 +4810,9 @@ export class PostgresEngine implements BrainEngine {
prompt_version: string;
truncation_policy: string;
}): Promise<Record<string, unknown> | null> {
- const sql = this.sql;
- const rows = await sql`
- SELECT verdict
- FROM eval_contradictions_cache
- WHERE chunk_a_hash = ${key.chunk_a_hash}
- AND chunk_b_hash = ${key.chunk_b_hash}
- AND model_id = ${key.model_id}
- AND prompt_version = ${key.prompt_version}
- AND truncation_policy = ${key.truncation_policy}
- AND expires_at > now()
- LIMIT 1
- `;
- if (rows.length === 0) return null;
- return rows[0].verdict as Record<string, unknown>;
+ return takesImpl.getContradictionCacheEntry(this.takesDeps, key);
}
- /**
- * v0.32.6 — judge cache upsert. ON CONFLICT DO UPDATE refreshes verdict +
- * slides expires_at forward; same-key re-runs are safe.
- */
async putContradictionCacheEntry(opts: {
chunk_a_hash: string;
chunk_b_hash: string;
@@ -5285,174 +4822,38 @@ export class PostgresEngine implements BrainEngine {
verdict: Record<string, unknown>;
ttl_seconds?: number;
}): Promise<void> {
- const sql = this.sql;
- const ttl = Math.max(60, opts.ttl_seconds ?? 30 * 86400);
- const expiresAt = new Date(Date.now() + ttl * 1000);
- await sql`
- INSERT INTO eval_contradictions_cache (
- chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy,
- verdict, expires_at
- ) VALUES (
- ${opts.chunk_a_hash}, ${opts.chunk_b_hash}, ${opts.model_id},
- ${opts.prompt_version}, ${opts.truncation_policy},
- ${sql.json(opts.verdict as Parameters<typeof sql.json>[0])}, ${expiresAt}
- )
- ON CONFLICT (chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)
- DO UPDATE SET
- verdict = EXCLUDED.verdict,
- expires_at = EXCLUDED.expires_at,
- created_at = now()
- `;
+ return takesImpl.putContradictionCacheEntry(this.takesDeps, opts);
}
- /** v0.32.6 — periodic sweep of expired cache rows. */
async sweepContradictionCache(): Promise<number> {
- const sql = this.sql;
- const result = await sql`
- DELETE FROM eval_contradictions_cache WHERE expires_at <= now()
- `;
- return result.count ?? 0;
+ return takesImpl.sweepContradictionCache(this.takesDeps);
}
async listTakes(opts: TakesListOpts = {}): Promise<Take[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts.limit, 100, 500);
- const offset = Math.max(0, Math.floor(opts.offset ?? 0));
- const active = opts.active ?? true;
- // #2200-class: takes have no source_id of their own; scope via the page's
- // source_id (already JOINed). Array wins over scalar, matching sourceScopeOpts.
- const sourceFilter =
- opts.sourceIds && opts.sourceIds.length > 0
- ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
- : opts.sourceId
- ? sql`AND p.source_id = ${opts.sourceId}`
- : sql``;
- const rows = await sql`
- SELECT t.*, p.slug AS page_slug
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE 1=1
- 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)
- AND (${opts.kind ?? null}::text IS NULL OR t.kind = ${opts.kind ?? null}::text)
- AND (${active}::boolean IS NULL OR t.active = ${active}::boolean)
- AND (
- ${opts.resolved === undefined ? null : opts.resolved}::boolean IS NULL
- OR (${opts.resolved === undefined ? null : opts.resolved}::boolean = true AND t.resolved_at IS NOT NULL)
- OR (${opts.resolved === undefined ? null : opts.resolved}::boolean = false AND t.resolved_at IS NULL)
- )
- AND (
- ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
- OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
- )
- ${sourceFilter}
- ORDER BY
- CASE WHEN ${opts.sortBy ?? 'created_at'} = 'weight' THEN t.weight END DESC NULLS LAST,
- CASE WHEN ${opts.sortBy ?? 'created_at'} = 'since_date' THEN t.since_date END DESC NULLS LAST,
- CASE WHEN ${opts.sortBy ?? 'created_at'} = 'created_at' THEN t.created_at END DESC NULLS LAST
- LIMIT ${limit} OFFSET ${offset}
- `;
- return rows.map((r) => takeRowToTake(r as Record<string, unknown>));
+ return takesImpl.listTakes(this.takesDeps, opts);
}
async searchTakes(query: string, opts: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[] } = {}): Promise<TakeHit[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts.limit, 30, 100);
- const sourceFilter = opts.sourceIds && opts.sourceIds.length > 0
- ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
- : opts.sourceId
- ? sql`AND p.source_id = ${opts.sourceId}`
- : sql``;
- const rows = await sql`
- SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
- t.claim, t.kind, t.holder, t.weight,
- word_similarity(${query}, t.claim)::real AS score
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.active
- AND ${query} <% t.claim
- AND (
- ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
- OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
- )
- ${sourceFilter}
- ORDER BY score DESC, t.weight DESC
- LIMIT ${limit}
- `;
- // #2450-class: int8 columns arrive as native BigInt from the pg driver;
- // coerce per-row (takeRowToTake precedent) so MCP/CLI JSON.stringify
- // doesn't crash the moment a search actually matches.
- return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ return takesImpl.searchTakes(this.takesDeps, query, opts);
}
async searchTakesVector(
embedding: Float32Array,
opts: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[] } = {},
): Promise<TakeHit[]> {
- const sql = this.sql;
- const limit = clampSearchLimit(opts.limit, 30, 100);
- const vec = `[${Array.from(embedding).join(',')}]`;
- const sourceFilter = opts.sourceIds && opts.sourceIds.length > 0
- ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
- : opts.sourceId
- ? sql`AND p.source_id = ${opts.sourceId}`
- : sql``;
- const rows = await sql`
- SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
- t.claim, t.kind, t.holder, t.weight,
- (1 - (t.embedding <=> ${vec}::vector))::real AS score
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.active
- AND t.embedding IS NOT NULL
- AND (
- ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
- OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
- )
- ${sourceFilter}
- ORDER BY t.embedding <=> ${vec}::vector
- LIMIT ${limit}
- `;
- // #2450-class: int8 columns arrive as native BigInt from the pg driver;
- // coerce per-row (takeRowToTake precedent) so MCP/CLI JSON.stringify
- // doesn't crash the moment a search actually matches.
- return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ return takesImpl.searchTakesVector(this.takesDeps, embedding, opts);
}
async getTakeEmbeddings(ids: number[]): Promise<Map<number, Float32Array>> {
- if (ids.length === 0) return new Map();
- const sql = this.sql;
- const rows = await sql`
- SELECT id, embedding FROM takes WHERE id = ANY(${ids}::bigint[]) AND embedding IS NOT NULL
- `;
- const out = new Map<number, Float32Array>();
- for (const r of rows as unknown as Array<{ id: number; embedding: unknown }>) {
- const parsed = tryParseEmbedding(r.embedding);
- if (parsed) out.set(Number(r.id), parsed);
- }
- return out;
+ return takesImpl.getTakeEmbeddings(this.takesDeps, ids);
}
async countStaleTakes(): Promise<number> {
- const sql = this.sql;
- const [row] = await sql`
- SELECT count(*)::int AS count FROM takes WHERE active AND embedding IS NULL
- `;
- return Number((row as { count?: number } | undefined)?.count ?? 0);
+ return takesImpl.countStaleTakes(this.takesDeps);
}
async listStaleTakes(): Promise<StaleTakeRow[]> {
- const sql = this.sql;
- const rows = await sql`
- SELECT t.id AS take_id, p.slug AS page_slug, t.row_num, t.claim
- FROM takes t
- JOIN pages p ON p.id = t.page_id
- WHERE t.active AND t.embedding IS NULL
- ORDER BY t.id
- LIMIT 100000
- `;
- return rows as unknown as StaleTakeRow[];
+ return takesImpl.listStaleTakes(this.takesDeps);
}
async updateTake(
@@ -5460,27 +4861,7 @@ export class PostgresEngine implements BrainEngine {
rowNum: number,
fields: { weight?: number; since_date?: string; source?: string },
): Promise<void> {
- const sql = this.sql;
- let weight = fields.weight;
- if (weight !== undefined) {
- const norm = normalizeWeightForStorage(weight);
- if (norm.clamped) {
- process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: updateTake clamped weight ${weight} → ${norm.weight}\n`);
- }
- weight = norm.weight;
- }
- const result = await sql`
- UPDATE takes SET
- weight = COALESCE(${weight ?? null}::real, weight),
- since_date = COALESCE(${fields.since_date ?? null}::text, since_date),
- source = COALESCE(${fields.source ?? null}::text, source),
- updated_at = now()
- WHERE page_id = ${pageId} AND row_num = ${rowNum}
- RETURNING 1
- `;
- if (result.length === 0) {
- throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${rowNum}`, 'list takes for this page with `gbrain takes <slug>` to see valid row numbers');
- }
+ return takesImpl.updateTake(this.takesDeps, pageId, rowNum, fields);
}
async supersedeTake(
@@ -5488,175 +4869,23 @@ export class PostgresEngine implements BrainEngine {
oldRow: number,
newRow: Omit<TakeBatchInput, 'page_id' | 'row_num' | 'superseded_by'>,
): Promise<{ oldRow: number; newRow: number }> {
- const conn = this.sql;
- return await conn.begin(async (tx) => {
- const [existing] = await tx`
- SELECT resolved_at FROM takes WHERE page_id = ${pageId} AND row_num = ${oldRow}
- `;
- if (!existing) throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${oldRow}`, 'list takes with `gbrain takes <slug>`');
- if ((existing as { resolved_at?: unknown }).resolved_at) {
- throw new GBrainError('TAKE_RESOLVED_IMMUTABLE', `take ${pageId}#${oldRow} is resolved`, 'resolved bets are immutable; add a new take instead');
- }
- const [maxRow] = await tx`SELECT COALESCE(MAX(row_num), 0) + 1 AS next FROM takes WHERE page_id = ${pageId}`;
- const newRowNum = Number((maxRow as { next?: number })?.next ?? 1);
- const wClamped = Math.max(0, Math.min(1, newRow.weight ?? 0.5));
- await tx`
- INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, active)
- VALUES (${pageId}, ${newRowNum}, ${newRow.claim}, ${newRow.kind}, ${newRow.holder}, ${wClamped},
- ${newRow.since_date ?? null}::text, ${newRow.until_date ?? null}::text,
- ${newRow.source ?? null}, ${newRow.active ?? true})
- `;
- await tx`
- UPDATE takes SET active = false, superseded_by = ${newRowNum}, updated_at = now()
- WHERE page_id = ${pageId} AND row_num = ${oldRow}
- `;
- return { oldRow, newRow: newRowNum };
- }) as { oldRow: number; newRow: number };
+ return takesImpl.supersedeTake(this.takesDeps, pageId, oldRow, newRow);
}
async resolveTake(pageId: number, rowNum: number, resolution: TakeResolution): Promise<void> {
- const sql = this.sql;
- const [existing] = await sql`SELECT resolved_at FROM takes WHERE page_id = ${pageId} AND row_num = ${rowNum}`;
- if (!existing) throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${rowNum}`, 'list takes for this page with `gbrain takes <slug>` to see valid row numbers');
- if ((existing as { resolved_at?: unknown }).resolved_at) {
- throw new GBrainError('TAKE_ALREADY_RESOLVED', `take ${pageId}#${rowNum} already resolved`, 'resolution is immutable; add a new take to record a new outcome');
- }
- // v0.30.0: derive (quality, outcome) tuple. quality wins when both set.
- // Schema CHECK enforces consistency as a defense-in-depth backstop.
- const { quality, outcome } = deriveResolutionTuple(resolution);
- await sql`
- UPDATE takes SET
- resolved_at = now(),
- resolved_quality = ${quality}::text,
- resolved_outcome = ${outcome},
- resolved_value = ${resolution.value ?? null}::real,
- resolved_unit = ${resolution.unit ?? null}::text,
- resolved_source = ${resolution.source ?? null}::text,
- resolved_by = ${resolution.resolvedBy},
- updated_at = now()
- WHERE page_id = ${pageId} AND row_num = ${rowNum}
- `;
+ return takesImpl.resolveTake(this.takesDeps, pageId, rowNum, resolution);
}
- /**
- * v0.30.0: aggregate scorecard. SQL-level allow-list filter (D4 fail-closed).
- * Hidden-holder rows contribute zero to aggregates. NULL allowList means
- * trusted caller (no filtering). Empty array → zero results.
- */
async getScorecard(opts: TakesScorecardOpts, allowList: string[] | undefined): Promise<TakesScorecard> {
- const sql = this.sql;
- const allowed = allowList ? sql`AND holder = ANY(${allowList}::text[])` : sql``;
- const holderClause = opts.holder ? sql`AND holder = ${opts.holder}` : sql``;
- const domainClause = opts.domainPrefix
- ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.slug LIKE ${opts.domainPrefix + '%'})`
- : sql``;
- const sinceClause = opts.since ? sql`AND since_date >= ${opts.since}` : sql``;
- const untilClause = opts.until ? sql`AND since_date <= ${opts.until}` : sql``;
- // #2200-class: takes carry no source_id; scope via the take's page via EXISTS
- // (this query has no pages JOIN). Array wins over scalar (sourceScopeOpts shape).
- const sourceFilter =
- opts.sourceIds && opts.sourceIds.length > 0
- ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY(${opts.sourceIds}::text[]))`
- : opts.sourceId
- ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ${opts.sourceId})`
- : sql``;
- // v0.36.1.1 T1c: `resolved` deliberately filters to the 3-state subset
- // (correct|incorrect|partial) — NOT `resolved_quality IS NOT NULL` — so
- // historical comparisons against pre-v74 scorecards stay valid.
- // `unresolvable_count` is a sibling field counting the new 4th state.
- const rows = await sql`
- SELECT
- COUNT(*) FILTER (WHERE kind = 'bet')::int AS total_bets,
- COUNT(*) FILTER (WHERE resolved_quality IN ('correct','incorrect','partial'))::int AS resolved,
- COUNT(*) FILTER (WHERE resolved_quality = 'correct')::int AS correct,
- COUNT(*) FILTER (WHERE resolved_quality = 'incorrect')::int AS incorrect,
- COUNT(*) FILTER (WHERE resolved_quality = 'partial')::int AS partial,
- COUNT(*) FILTER (WHERE resolved_quality = 'unresolvable')::int AS unresolvable_count,
- AVG(
- CASE WHEN resolved_quality IN ('correct','incorrect')
- THEN POWER(weight - (CASE resolved_quality WHEN 'correct' THEN 1 ELSE 0 END), 2)
- END
- )::float AS brier
- FROM takes
- WHERE 1=1 ${holderClause} ${domainClause} ${sinceClause} ${untilClause} ${allowed} ${sourceFilter}
- `;
- 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);
+ return takesImpl.getScorecard(this.takesDeps, opts, allowList);
}
- /**
- * v0.30.0: calibration curve. Bins resolved correct/incorrect bets by stated
- * weight. Same allow-list contract as getScorecard.
- *
- * Real-Postgres-via-postgres.js sends scalar params as text by default, so
- * `${bucketSize}` arrives as the string `'0.1'`. Without explicit `::float`
- * casts the FLOOR/LEAST/multiplication contexts try to coerce text to int
- * and bomb with `invalid input syntax for type integer: "0.1"`. PGLite is
- * more permissive — caught at e2e parity by takes-scorecard-parity.test.ts.
- */
async getCalibrationCurve(opts: CalibrationCurveOpts, allowList: string[] | undefined): Promise<CalibrationBucket[]> {
- const sql = this.sql;
- const bucketSize = opts.bucketSize && opts.bucketSize > 0 && opts.bucketSize <= 1 ? opts.bucketSize : 0.1;
- const maxIdx = Math.floor(1 / bucketSize) - 1;
- const allowed = allowList ? sql`AND holder = ANY(${allowList}::text[])` : sql``;
- const holderClause = opts.holder ? sql`AND holder = ${opts.holder}` : sql``;
- const sourceFilter =
- opts.sourceIds && opts.sourceIds.length > 0
- ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY(${opts.sourceIds}::text[]))`
- : opts.sourceId
- ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ${opts.sourceId})`
- : sql``;
- // Bucketing uses NUMERIC for exact decimal arithmetic. Going through
- // FLOAT introduces IEEE 754 rounding (e.g. 0.7/0.1 = 6.9999..., FLOOR=6
- // instead of the expected 7), which makes Postgres and PGLite diverge
- // at bucket boundaries. NUMERIC is exact, so the bucket index is
- // engine-agnostic and the parity test holds.
- const rows = await sql`
- WITH binned AS (
- SELECT
- LEAST(FLOOR(weight::numeric / ${bucketSize}::numeric)::int, ${maxIdx}::int)::int AS bucket_idx,
- weight,
- (resolved_quality = 'correct')::int AS hit
- FROM takes
- WHERE resolved_quality IN ('correct','incorrect')
- ${holderClause} ${allowed} ${sourceFilter}
- )
- SELECT
- (bucket_idx::numeric * ${bucketSize}::numeric)::float AS bucket_lo,
- ((bucket_idx + 1)::numeric * ${bucketSize}::numeric)::float AS bucket_hi,
- COUNT(*)::int AS n,
- AVG(hit)::float AS observed,
- AVG(weight)::float AS predicted
- FROM binned
- GROUP BY bucket_idx
- ORDER BY bucket_idx
- `;
- return (rows as unknown as { bucket_lo: number; bucket_hi: number; n: number; observed: number | null; predicted: number | null }[]).map(r => ({
- bucket_lo: r.bucket_lo,
- bucket_hi: r.bucket_hi,
- n: r.n,
- observed: r.n > 0 ? r.observed : null,
- predicted: r.n > 0 ? r.predicted : null,
- }));
+ return takesImpl.getCalibrationCurve(this.takesDeps, opts, allowList);
}
async addSynthesisEvidence(rowsIn: SynthesisEvidenceInput[]): Promise<number> {
- if (rowsIn.length === 0) return 0;
- const sql = this.sql;
- const synthesisIds = rowsIn.map(r => r.synthesis_page_id);
- const takePageIds = rowsIn.map(r => r.take_page_id);
- const takeRowNums = rowsIn.map(r => r.take_row_num);
- const citationIxs = rowsIn.map(r => r.citation_index);
- const result = await sql`
- INSERT INTO synthesis_evidence (synthesis_page_id, take_page_id, take_row_num, citation_index)
- SELECT v.synthesis_page_id::int, v.take_page_id::int, v.take_row_num::int, v.citation_index::int
- FROM unnest(
- ${synthesisIds}::int[], ${takePageIds}::int[], ${takeRowNums}::int[], ${citationIxs}::int[]
- ) AS v(synthesis_page_id, take_page_id, take_row_num, citation_index)
- ON CONFLICT (synthesis_page_id, take_page_id, take_row_num) DO NOTHING
- RETURNING 1
- `;
- return result.length;
+ return takesImpl.addSynthesisEvidence(this.takesDeps, rowsIn);
}
// Versions
@@ -6347,157 +5576,41 @@ export class PostgresEngine implements BrainEngine {
// per-lang tree-sitter queries land in Layer 5/6.
// ============================================================
- async addCodeEdges(edges: import('./types.ts').CodeEdgeInput[]): Promise<number> {
- if (edges.length === 0) return 0;
- const sql = this.sql;
- let inserted = 0;
- const resolved = edges.filter(e => e.to_chunk_id != null);
- const unresolved = edges.filter(e => e.to_chunk_id == null);
-
- if (resolved.length > 0) {
- // Per-row placeholders with $n::text::jsonb for edge_metadata. Bun SQL
- // mis-encodes jsonb[] array binds (double-encoded strings landed in
- // edge_metadata — the resolver then read `"{}"` scalars and 0 edges ever
- // resolved). ::text::jsonb per row is the codebase-wide safe shape
- // (executeRawJsonb, PGLite's addCodeEdges).
- const rowParts: string[] = [];
- const params: unknown[] = [];
- let p = 1;
- for (const e of resolved) {
- rowParts.push(`($${p++}::int, $${p++}::int, $${p++}, $${p++}, $${p++}, $${p++}::text::jsonb, $${p++})`);
- params.push(
- e.from_chunk_id, e.to_chunk_id as number,
- e.from_symbol_qualified, e.to_symbol_qualified, e.edge_type,
- JSON.stringify(e.edge_metadata ?? {}),
- e.source_id ?? 'default',
- );
- }
- const res = await sql.unsafe(
- `INSERT INTO code_edges_chunk
- (from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
- VALUES ${rowParts.join(', ')}
- ON CONFLICT (from_chunk_id, to_chunk_id, edge_type) DO NOTHING`,
- params as never[],
- );
- inserted += (res as unknown as { count: number }).count ?? 0;
- }
+ // Peeled into ./postgres-engine/code-edges.ts (containment sprint C15).
- if (unresolved.length > 0) {
- const rowParts: string[] = [];
- const params: unknown[] = [];
- let p = 1;
- for (const e of unresolved) {
- rowParts.push(`($${p++}::int, $${p++}, $${p++}, $${p++}, $${p++}::text::jsonb, $${p++})`);
- params.push(
- e.from_chunk_id,
- e.from_symbol_qualified, e.to_symbol_qualified, e.edge_type,
- JSON.stringify(e.edge_metadata ?? {}),
- e.source_id ?? 'default',
- );
- }
- const res = await sql.unsafe(
- `INSERT INTO code_edges_symbol
- (from_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
- VALUES ${rowParts.join(', ')}
- ON CONFLICT (from_chunk_id, to_symbol_qualified, edge_type) DO NOTHING`,
- params as never[],
- );
- inserted += (res as unknown as { count: number }).count ?? 0;
- }
+ /** Narrow deps for the peeled code-edges module. */
+ private get codeEdgesDeps(): PgCodeEdgesDeps {
+ const self = this;
+ return { get sql() { return self.sql; } };
+ }
- return inserted;
+ async addCodeEdges(edges: import('./types.ts').CodeEdgeInput[]): Promise<number> {
+ return codeEdgesImpl.addCodeEdges(this.codeEdgesDeps, edges);
}
async deleteCodeEdgesForChunks(chunkIds: number[]): Promise<void> {
- if (chunkIds.length === 0) return;
- const sql = this.sql;
- await sql`DELETE FROM code_edges_chunk WHERE from_chunk_id = ANY(${chunkIds}::int[]) OR to_chunk_id = ANY(${chunkIds}::int[])`;
- await sql`DELETE FROM code_edges_symbol WHERE from_chunk_id = ANY(${chunkIds}::int[])`;
+ return codeEdgesImpl.deleteCodeEdgesForChunks(this.codeEdgesDeps, chunkIds);
}
async getCallersOf(
qualifiedName: string,
opts?: { sourceId?: string; allSources?: boolean; limit?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
- const sql = this.sql;
- const limit = Math.min(opts?.limit ?? 100, 500);
- const scopedSource: string | null =
- !opts?.allSources && opts?.sourceId ? opts.sourceId : null;
- const rows = await sql`
- SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, true as resolved
- FROM code_edges_chunk
- WHERE to_symbol_qualified = ${qualifiedName}
- ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
- UNION ALL
- SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, false as resolved
- FROM code_edges_symbol
- WHERE to_symbol_qualified = ${qualifiedName}
- ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
- LIMIT ${limit}
- `;
- return rows.map(r => pgRowToCodeEdge(r as Record<string, unknown>));
+ return codeEdgesImpl.getCallersOf(this.codeEdgesDeps, qualifiedName, opts);
}
async getCalleesOf(
qualifiedName: string,
opts?: { sourceId?: string; allSources?: boolean; limit?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
- const sql = this.sql;
- const limit = Math.min(opts?.limit ?? 100, 500);
- const scopedSource: string | null =
- !opts?.allSources && opts?.sourceId ? opts.sourceId : null;
- const rows = await sql`
- SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, true as resolved
- FROM code_edges_chunk
- WHERE from_symbol_qualified = ${qualifiedName}
- ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
- UNION ALL
- SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, false as resolved
- FROM code_edges_symbol
- WHERE from_symbol_qualified = ${qualifiedName}
- ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
- LIMIT ${limit}
- `;
- return rows.map(r => pgRowToCodeEdge(r as Record<string, unknown>));
+ return codeEdgesImpl.getCalleesOf(this.codeEdgesDeps, qualifiedName, opts);
}
async getEdgesByChunk(
chunkId: number,
opts?: { direction?: 'in' | 'out' | 'both'; edgeType?: string; limit?: number },
): Promise<import('./types.ts').CodeEdgeResult[]> {
- const sql = this.sql;
- const direction = opts?.direction ?? 'both';
- const limit = Math.min(opts?.limit ?? 50, 200);
- const typeFilter = opts?.edgeType;
-
- const chunkRows = await sql`
- SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, true as resolved
- FROM code_edges_chunk
- WHERE
- ${direction === 'in' ? sql`to_chunk_id = ${chunkId}`
- : direction === 'out' ? sql`from_chunk_id = ${chunkId}`
- : sql`(from_chunk_id = ${chunkId} OR to_chunk_id = ${chunkId})`}
- ${typeFilter ? sql`AND edge_type = ${typeFilter}` : sql``}
- LIMIT ${limit}
- `;
- let symbolRows: unknown[] = [];
- if (direction !== 'in') {
- const sRows = await sql`
- SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
- edge_type, edge_metadata, source_id, false as resolved
- FROM code_edges_symbol
- WHERE from_chunk_id = ${chunkId}
- ${typeFilter ? sql`AND edge_type = ${typeFilter}` : sql``}
- LIMIT ${limit}
- `;
- symbolRows = [...sRows];
- }
- return [...chunkRows, ...symbolRows].map(r => pgRowToCodeEdge(r as Record<string, unknown>));
+ return codeEdgesImpl.getEdgesByChunk(this.codeEdgesDeps, chunkId, opts);
}
// Eval capture (v0.25.0). See BrainEngine interface docs.
@@ -6573,425 +5686,31 @@ export class PostgresEngine implements BrainEngine {
// v0.29 — Salience + Anomaly Detection
// ============================================================
+ // Peeled into ./postgres-engine/salience.ts (containment sprint C15).
+
+ /** Narrow deps for the peeled salience module. */
+ private get salienceDeps(): PgSalienceDeps {
+ const self = this;
+ return { get sql() { return self.sql; } };
+ }
+
async batchLoadEmotionalInputs(slugs?: string[]): Promise<EmotionalWeightInputRow[]> {
- const sql = this.sql;
- // Two CTEs avoid the N×M cartesian product (codex C4#4): a page with N tags
- // and M takes joined directly would emit N×M rows and corrupt aggregates.
- // Per-table aggregation keeps each table's grouping correct.
- const rows = slugs
- ? await sql`
- WITH page_tags AS (
- SELECT page_id, array_agg(DISTINCT tag) AS tags
- FROM tags GROUP BY page_id
- ),
- page_takes AS (
- SELECT page_id, json_agg(json_build_object(
- 'holder', holder, 'weight', weight, 'kind', kind, 'active', active
- )) AS takes
- FROM takes WHERE active = TRUE GROUP BY page_id
- )
- SELECT p.slug, p.source_id,
- COALESCE(pt.tags, ARRAY[]::text[]) AS tags,
- COALESCE(pk.takes, '[]'::json) AS takes
- FROM pages p
- LEFT JOIN page_tags pt ON pt.page_id = p.id
- LEFT JOIN page_takes pk ON pk.page_id = p.id
- WHERE p.slug = ANY(${slugs}::text[])
- `
- : await sql`
- WITH page_tags AS (
- SELECT page_id, array_agg(DISTINCT tag) AS tags
- FROM tags GROUP BY page_id
- ),
- page_takes AS (
- SELECT page_id, json_agg(json_build_object(
- 'holder', holder, 'weight', weight, 'kind', kind, 'active', active
- )) AS takes
- FROM takes WHERE active = TRUE GROUP BY page_id
- )
- SELECT p.slug, p.source_id,
- COALESCE(pt.tags, ARRAY[]::text[]) AS tags,
- COALESCE(pk.takes, '[]'::json) AS takes
- FROM pages p
- LEFT JOIN page_tags pt ON pt.page_id = p.id
- LEFT JOIN page_takes pk ON pk.page_id = p.id
- `;
- return rows.map((r: Record<string, unknown>) => ({
- slug: String(r.slug),
- source_id: String(r.source_id),
- tags: (r.tags as string[]) ?? [],
- takes: (r.takes as EmotionalWeightInputRow['takes']) ?? [],
- }));
+ return salienceImpl.batchLoadEmotionalInputs(this.salienceDeps, slugs);
}
async setEmotionalWeightBatch(rows: EmotionalWeightWriteRow[]): Promise<number> {
- if (rows.length === 0) return 0;
- const sql = this.sql;
- const slugs = rows.map(r => r.slug);
- const sourceIds = rows.map(r => r.source_id);
- const weights = rows.map(r => r.weight);
- // Composite-keyed UPDATE FROM unnest (codex C4#3): pages.slug is unique
- // only within a source, so a slug-only join would fan out across sources.
- //
- // v0.29.1: bump salience_touched_at to NOW() ONLY when emotional_weight
- // actually changes. The salience query window then includes the page in
- // GREATEST(updated_at, salience_touched_at) >= boundary, so a previously
- // calm page that just became salient surfaces in the recent salience
- // results without a content edit. No-op writes (same weight) leave
- // salience_touched_at alone — preserves "actual change" semantics.
- const result = await sql`
- UPDATE pages
- SET emotional_weight = u.weight,
- salience_touched_at = CASE
- WHEN pages.emotional_weight IS DISTINCT FROM u.weight THEN now()
- ELSE pages.salience_touched_at
- END
- FROM unnest(${slugs}::text[], ${sourceIds}::text[], ${weights}::real[])
- AS u(slug, source_id, weight)
- WHERE pages.slug = u.slug AND pages.source_id = u.source_id
- RETURNING 1
- `;
- return result.length;
+ return salienceImpl.setEmotionalWeightBatch(this.salienceDeps, rows);
}
async getRecentSalience(opts: SalienceOpts): Promise<SalienceResult[]> {
- const sql = this.sql;
- const days = Math.max(0, opts.days ?? 14);
- const limit = clampSearchLimit(opts.limit, 20, 100);
- const slugPrefix = opts.slugPrefix;
- // Compute the boundary in JS so the SQL is identical across engines (eng review D5).
- const boundaryIso = new Date(Date.now() - days * 86400000).toISOString();
- // Escape LIKE meta for the optional prefix match.
- const prefixCondition = slugPrefix
- ? sql`AND p.slug LIKE ${slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%'} ESCAPE '\\'`
- : sql``;
- // TIM-37: exclude briefing pages from their own Brain Pulse. The cron
- // briefing writes to 90_Briefings/, gets re-ingested, and would otherwise
- // top tomorrow's salience as pure self-reference. Suppress unless the
- // caller explicitly asked for the briefings/ prefix.
- const excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))
- ? sql`AND p.slug NOT LIKE 'briefings/%'`
- : sql``;
- // v0.29.1: third score term via buildRecencyComponentSql. Default
- // 'flat' = v0.29.0 behavior (1 / (1 + days_old)). 'on' opts into the
- // per-prefix decay map (concepts/ evergreen, daily/ aggressive, etc.).
- const recencyBias = opts.recency_bias ?? 'flat';
- let recencySql: string;
- if (recencyBias === 'on') {
- recencySql = buildRecencyComponentSql({
- slugColumn: 'p.slug',
- dateExpr: 'COALESCE(p.effective_date, p.updated_at)',
- decayMap: resolveRecencyDecayMap(),
- fallback: DEFAULT_FALLBACK,
- });
- } else {
- recencySql = buildRecencyComponentSql({
- slugColumn: 'p.slug',
- dateExpr: 'p.updated_at',
- decayMap: {},
- fallback: { halflifeDays: 1, coefficient: 1.0 },
- });
- }
- const rows = await sql`
- SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, p.emotional_weight,
- COUNT(DISTINCT t.id) AS take_count,
- COALESCE(AVG(t.weight), 0) AS take_avg_weight,
- (p.emotional_weight * 5)
- + ln(1 + COUNT(DISTINCT t.id))
- + ${sql.unsafe(recencySql)}
- AS score
- FROM 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
- ${prefixCondition}
- ${excludeBriefings}
- GROUP BY p.id
- ORDER BY score DESC
- LIMIT ${limit}
- `;
- return rows.map((r: Record<string, unknown>) => ({
- slug: String(r.slug),
- source_id: String(r.source_id),
- title: String(r.title ?? ''),
- type: r.type as SalienceResult['type'],
- updated_at: r.updated_at as Date,
- emotional_weight: Number(r.emotional_weight ?? 0),
- take_count: Number(r.take_count ?? 0),
- take_avg_weight: Number(r.take_avg_weight ?? 0),
- score: Number(r.score ?? 0),
- }));
+ return salienceImpl.getRecentSalience(this.salienceDeps, opts);
}
async listEnrichCandidates(opts: EnrichCandidatesOpts): Promise<EnrichCandidate[]> {
- // v0.41.39 (issue #1700). Empty types → no rows (no SQL).
- if (!opts.types || opts.types.length === 0) return [];
- const sql = this.sql;
- const limit = Math.max(1, Math.min(opts.limit ?? 50, 5000));
- const threshold = Math.max(0, opts.thinThreshold);
-
- // Source scope: array wins over scalar (canonical precedence).
- const sourceCondition = opts.sourceIds && opts.sourceIds.length > 0
- ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
- : opts.sourceId
- ? sql`AND p.source_id = ${opts.sourceId}`
- : sql``;
-
- // Re-enrich recency guard. enriched_at is written as toISOString() so a
- // lexical text comparison is correct AND can't throw on a malformed value
- // (a ::timestamptz cast would). Pages never enriched (NULL) are eligible.
- const reenrichMs = opts.reenrichAfterMs ?? 0;
- const recencyCondition = reenrichMs > 0
- ? sql`AND NOT (
- p.frontmatter ->> 'enriched_at' IS NOT NULL
- AND p.frontmatter ->> 'enriched_at' > ${new Date(Date.now() - reenrichMs).toISOString()}
- )`
- : sql``;
-
- // Exclude dream/synthesize-generated pages (reflections, originals, cycle
- // logs carrying frontmatter dream_generated:true). enrich develops ENTITY
- // stubs; running it on a generated essay/log creates circular self-citation
- // and drops the H1. IS DISTINCT FROM 'true' keeps NULL/'false' rows.
- const dreamCondition = sql`AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true'`;
-
- // Whitelisted ORDER BY (no injection — enum maps to a literal fragment).
- const orderKey = ENRICH_ORDER_SQL[opts.order] ? opts.order : 'inbound-links';
- const orderBy = sql.unsafe(ENRICH_ORDER_SQL[orderKey]);
-
- const rows = await sql`
- SELECT
- p.slug,
- p.source_id,
- p.title,
- p.type,
- (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len,
- COALESCE((
- SELECT COUNT(*)
- FROM links l
- WHERE l.to_page_id = p.id
- AND l.link_source IS DISTINCT FROM 'mentions'
- ), 0)::int AS inbound_count
- FROM pages p
- WHERE p.deleted_at IS NULL
- AND p.type = ANY(${opts.types}::text[])
- AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < ${threshold}
- ${sourceCondition}
- ${recencyCondition}
- ${dreamCondition}
- ORDER BY ${orderBy}
- LIMIT ${limit}
- `;
- return rows.map((r: Record<string, unknown>) => ({
- slug: String(r.slug),
- source_id: String(r.source_id),
- title: String(r.title ?? ''),
- type: r.type as EnrichCandidate['type'],
- body_len: Number(r.body_len ?? 0),
- inbound_count: Number(r.inbound_count ?? 0),
- }));
+ return salienceImpl.listEnrichCandidates(this.salienceDeps, opts);
}
async findAnomalies(opts: AnomaliesOpts): Promise<AnomalyResult[]> {
- const sql = this.sql;
- const sigma = opts.sigma ?? 3.0;
- const lookbackDays = Math.max(1, opts.lookback_days ?? 30);
- // Boundaries: today's window is [since, since+1day); baseline is [since-lookback, since).
- const sinceIso = (opts.since ?? new Date().toISOString().slice(0, 10)); // YYYY-MM-DD
- const sinceDate = new Date(sinceIso + 'T00:00:00Z');
- const sinceEnd = new Date(sinceDate.getTime() + 86400000);
- const baselineStart = new Date(sinceDate.getTime() - lookbackDays * 86400000);
-
- // Tag cohort baseline with day densification + zero-fill (codex C4#6).
- const tagBaseline = await sql`
- WITH days AS (
- SELECT day::date FROM generate_series(
- ${baselineStart.toISOString()}::date,
- ${sinceDate.toISOString()}::date - 1,
- '1 day'::interval
- ) AS day
- ),
- cohort_keys AS (
- SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_id
- WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
- AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
- ),
- touched AS (
- SELECT t.tag,
- date_trunc('day', p.updated_at)::date AS day,
- COUNT(DISTINCT p.id) AS cnt
- FROM tags t JOIN pages p ON p.id = t.page_id
- WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
- AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
- GROUP BY 1, 2
- )
- SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
- FROM cohort_keys cd CROSS JOIN days d
- LEFT JOIN touched t ON t.tag = cd.tag AND t.day = d.day
- `;
-
- const typeBaseline = await sql`
- WITH days AS (
- SELECT day::date FROM generate_series(
- ${baselineStart.toISOString()}::date,
- ${sinceDate.toISOString()}::date - 1,
- '1 day'::interval
- ) AS day
- ),
- cohort_keys AS (
- SELECT DISTINCT p.type FROM pages p
- WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
- AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
- ),
- touched AS (
- SELECT p.type,
- date_trunc('day', p.updated_at)::date AS day,
- COUNT(DISTINCT p.id) AS cnt
- FROM pages p
- WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
- AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
- GROUP BY 1, 2
- )
- SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
- FROM cohort_keys cd CROSS JOIN days d
- LEFT JOIN touched t ON t.type = cd.type AND t.day = d.day
- `;
-
- // Today's window — current counts + slugs per cohort.
- const tagToday = await sql`
- SELECT t.tag AS cohort_value,
- COUNT(DISTINCT p.id)::int AS count,
- array_agg(DISTINCT p.slug) AS slugs
- FROM tags t JOIN pages p ON p.id = t.page_id
- WHERE p.updated_at >= ${sinceIso}::timestamptz
- AND p.updated_at < ${sinceEnd.toISOString()}::timestamptz
- GROUP BY 1
- `;
- const typeToday = await sql`
- SELECT p.type AS cohort_value,
- COUNT(DISTINCT p.id)::int AS count,
- array_agg(DISTINCT p.slug) AS slugs
- FROM pages p
- WHERE p.updated_at >= ${sinceIso}::timestamptz
- AND p.updated_at < ${sinceEnd.toISOString()}::timestamptz
- GROUP BY 1
- `;
-
- const baseline = [
- ...tagBaseline.map((r: Record<string, unknown>) => ({
- cohort_kind: 'tag' as const,
- cohort_value: String(r.cohort_value),
- day: String(r.day),
- count: Number(r.count),
- })),
- ...typeBaseline.map((r: Record<string, unknown>) => ({
- cohort_kind: 'type' as const,
- cohort_value: String(r.cohort_value),
- day: String(r.day),
- count: Number(r.count),
- })),
- ];
- const today = [
- ...tagToday.map((r: Record<string, unknown>) => ({
- cohort_kind: 'tag' as const,
- cohort_value: String(r.cohort_value),
- count: Number(r.count),
- page_slugs: (r.slugs as string[]) ?? [],
- })),
- ...typeToday.map((r: Record<string, unknown>) => ({
- cohort_kind: 'type' as const,
- cohort_value: String(r.cohort_value),
- count: Number(r.count),
- page_slugs: (r.slugs as string[]) ?? [],
- })),
- ];
-
- return computeAnomaliesFromBuckets(baseline, today, sigma);
+ return salienceImpl.findAnomalies(this.salienceDeps, opts);
}
}
-
-/**
- * Raw row shape returned from `SELECT * FROM facts` on Postgres.
- * postgres.js auto-decodes timestamps and numbers; embedding lands as
- * either a string ("[0.1,...]") or already-parsed array depending on type
- * codec — we handle both.
- */
-interface FactRowSqlShape {
- id: number | bigint;
- source_id: string;
- entity_slug: string | null;
- fact: string;
- kind: FactKind;
- visibility: FactVisibility;
- notability: 'high' | 'medium' | 'low';
- context: string | null;
- valid_from: Date;
- valid_until: Date | null;
- expired_at: Date | null;
- superseded_by: number | bigint | null;
- consolidated_at: Date | null;
- consolidated_into: number | bigint | null;
- source: string;
- source_session: string | null;
- confidence: number | string;
- embedding: string | number[] | Float32Array | null;
- embedded_at: Date | null;
- created_at: Date;
-}
-
-function rowToFactPg(row: FactRowSqlShape): FactRow {
- let embedding: Float32Array | null = null;
- if (row.embedding != null) {
- if (row.embedding instanceof Float32Array) embedding = row.embedding;
- else if (Array.isArray(row.embedding)) embedding = new Float32Array(row.embedding);
- else if (typeof row.embedding === 'string') {
- const trimmed = row.embedding.trim();
- const inner = trimmed.startsWith('[') ? trimmed.slice(1, -1) : trimmed;
- const parts = inner.split(',').map(p => parseFloat(p.trim())).filter(Number.isFinite);
- embedding = parts.length > 0 ? new Float32Array(parts) : null;
- }
- }
- return {
- id: Number(row.id),
- source_id: row.source_id,
- entity_slug: row.entity_slug,
- fact: row.fact,
- kind: row.kind,
- visibility: row.visibility,
- // v0.31.2: notability column added by migration v46. Pre-v46 rows that
- // somehow survive a SELECT (shouldn't on a fully-migrated brain) fall
- // back to 'medium' to keep the contract total. Belt-and-suspenders with
- // the migration's NOT NULL DEFAULT.
- notability: row.notability ?? 'medium',
- context: row.context,
- valid_from: row.valid_from,
- valid_until: row.valid_until,
- expired_at: row.expired_at,
- superseded_by: row.superseded_by == null ? null : Number(row.superseded_by),
- consolidated_at: row.consolidated_at,
- consolidated_into: row.consolidated_into == null ? null : Number(row.consolidated_into),
- source: row.source,
- source_session: row.source_session,
- confidence: typeof row.confidence === 'string' ? parseFloat(row.confidence) : row.confidence,
- embedding,
- embedded_at: row.embedded_at,
- created_at: row.created_at,
- };
-}
-
-function toPgVectorLiteral(v: Float32Array | number[]): string {
- if (v instanceof Float32Array) return '[' + Array.from(v).join(',') + ']';
- return '[' + v.join(',') + ']';
-}
-
-function pgRowToCodeEdge(row: Record<string, unknown>): import('./types.ts').CodeEdgeResult {
- return {
- id: row.id as number,
- from_chunk_id: row.from_chunk_id as number,
- to_chunk_id: row.to_chunk_id == null ? null : (row.to_chunk_id as number),
- from_symbol_qualified: (row.from_symbol_qualified as string) ?? '',
- to_symbol_qualified: (row.to_symbol_qualified as string) ?? '',
- edge_type: (row.edge_type as string) ?? '',
- edge_metadata: (row.edge_metadata as Record<string, unknown>) ?? {},
- source_id: row.source_id == null ? null : (row.source_id as string),
- resolved: Boolean(row.resolved),
- };
-}
diff --git a/src/core/postgres-engine/code-edges.ts b/src/core/postgres-engine/code-edges.ts
new file mode 100644
index 0000000000..b17752a8c6
--- /dev/null
+++ b/src/core/postgres-engine/code-edges.ts
@@ -0,0 +1,184 @@
+/**
+ * v0.20.0 Cathedral II: code edges, peeled out of PostgresEngine
+ * (containment sprint C15). Free functions over a NARROW deps surface —
+ * never the whole engine class.
+ */
+import type postgres from 'postgres';
+
+type PgSql = ReturnType<typeof postgres>;
+
+/** Narrow slice of PostgresEngine the code-edge operations use. */
+export interface PgCodeEdgesDeps {
+ /** Live postgres.js pool (getter-backed at the call site). */
+ readonly sql: PgSql;
+}
+
+export async function addCodeEdges(deps: PgCodeEdgesDeps, edges: import('../types.ts').CodeEdgeInput[]): Promise<number> {
+ if (edges.length === 0) return 0;
+ const sql = deps.sql;
+ let inserted = 0;
+ const resolved = edges.filter(e => e.to_chunk_id != null);
+ const unresolved = edges.filter(e => e.to_chunk_id == null);
+
+ if (resolved.length > 0) {
+ // Per-row placeholders with $n::text::jsonb for edge_metadata. Bun SQL
+ // mis-encodes jsonb[] array binds (double-encoded strings landed in
+ // edge_metadata — the resolver then read `"{}"` scalars and 0 edges ever
+ // resolved). ::text::jsonb per row is the codebase-wide safe shape
+ // (executeRawJsonb, PGLite's addCodeEdges).
+ const rowParts: string[] = [];
+ const params: unknown[] = [];
+ let p = 1;
+ for (const e of resolved) {
+ rowParts.push(`($${p++}::int, $${p++}::int, $${p++}, $${p++}, $${p++}, $${p++}::text::jsonb, $${p++})`);
+ params.push(
+ e.from_chunk_id, e.to_chunk_id as number,
+ e.from_symbol_qualified, e.to_symbol_qualified, e.edge_type,
+ JSON.stringify(e.edge_metadata ?? {}),
+ e.source_id ?? 'default',
+ );
+ }
+ const res = await sql.unsafe(
+ `INSERT INTO code_edges_chunk
+ (from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
+ VALUES ${rowParts.join(', ')}
+ ON CONFLICT (from_chunk_id, to_chunk_id, edge_type) DO NOTHING`,
+ params as never[],
+ );
+ inserted += (res as unknown as { count: number }).count ?? 0;
+ }
+
+ if (unresolved.length > 0) {
+ const rowParts: string[] = [];
+ const params: unknown[] = [];
+ let p = 1;
+ for (const e of unresolved) {
+ rowParts.push(`($${p++}::int, $${p++}, $${p++}, $${p++}, $${p++}::text::jsonb, $${p++})`);
+ params.push(
+ e.from_chunk_id,
+ e.from_symbol_qualified, e.to_symbol_qualified, e.edge_type,
+ JSON.stringify(e.edge_metadata ?? {}),
+ e.source_id ?? 'default',
+ );
+ }
+ const res = await sql.unsafe(
+ `INSERT INTO code_edges_symbol
+ (from_chunk_id, from_symbol_qualified, to_symbol_qualified, edge_type, edge_metadata, source_id)
+ VALUES ${rowParts.join(', ')}
+ ON CONFLICT (from_chunk_id, to_symbol_qualified, edge_type) DO NOTHING`,
+ params as never[],
+ );
+ inserted += (res as unknown as { count: number }).count ?? 0;
+ }
+
+ return inserted;
+ }
+
+export async function deleteCodeEdgesForChunks(deps: PgCodeEdgesDeps, chunkIds: number[]): Promise<void> {
+ if (chunkIds.length === 0) return;
+ const sql = deps.sql;
+ await sql`DELETE FROM code_edges_chunk WHERE from_chunk_id = ANY(${chunkIds}::int[]) OR to_chunk_id = ANY(${chunkIds}::int[])`;
+ await sql`DELETE FROM code_edges_symbol WHERE from_chunk_id = ANY(${chunkIds}::int[])`;
+ }
+
+export async function getCallersOf(
+ deps: PgCodeEdgesDeps,
+ qualifiedName: string,
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ ): Promise<import('../types.ts').CodeEdgeResult[]> {
+ const sql = deps.sql;
+ const limit = Math.min(opts?.limit ?? 100, 500);
+ const scopedSource: string | null =
+ !opts?.allSources && opts?.sourceId ? opts.sourceId : null;
+ const rows = await sql`
+ SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, true as resolved
+ FROM code_edges_chunk
+ WHERE to_symbol_qualified = ${qualifiedName}
+ ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
+ UNION ALL
+ SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, false as resolved
+ FROM code_edges_symbol
+ WHERE to_symbol_qualified = ${qualifiedName}
+ ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
+ LIMIT ${limit}
+ `;
+ return rows.map(r => pgRowToCodeEdge(r as Record<string, unknown>));
+ }
+
+export async function getCalleesOf(
+ deps: PgCodeEdgesDeps,
+ qualifiedName: string,
+ opts?: { sourceId?: string; allSources?: boolean; limit?: number },
+ ): Promise<import('../types.ts').CodeEdgeResult[]> {
+ const sql = deps.sql;
+ const limit = Math.min(opts?.limit ?? 100, 500);
+ const scopedSource: string | null =
+ !opts?.allSources && opts?.sourceId ? opts.sourceId : null;
+ const rows = await sql`
+ SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, true as resolved
+ FROM code_edges_chunk
+ WHERE from_symbol_qualified = ${qualifiedName}
+ ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
+ UNION ALL
+ SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, false as resolved
+ FROM code_edges_symbol
+ WHERE from_symbol_qualified = ${qualifiedName}
+ ${scopedSource ? sql`AND source_id = ${scopedSource}` : sql``}
+ LIMIT ${limit}
+ `;
+ return rows.map(r => pgRowToCodeEdge(r as Record<string, unknown>));
+ }
+
+export async function getEdgesByChunk(
+ deps: PgCodeEdgesDeps,
+ chunkId: number,
+ opts?: { direction?: 'in' | 'out' | 'both'; edgeType?: string; limit?: number },
+ ): Promise<import('../types.ts').CodeEdgeResult[]> {
+ const sql = deps.sql;
+ const direction = opts?.direction ?? 'both';
+ const limit = Math.min(opts?.limit ?? 50, 200);
+ const typeFilter = opts?.edgeType;
+
+ const chunkRows = await sql`
+ SELECT id, from_chunk_id, to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, true as resolved
+ FROM code_edges_chunk
+ WHERE
+ ${direction === 'in' ? sql`to_chunk_id = ${chunkId}`
+ : direction === 'out' ? sql`from_chunk_id = ${chunkId}`
+ : sql`(from_chunk_id = ${chunkId} OR to_chunk_id = ${chunkId})`}
+ ${typeFilter ? sql`AND edge_type = ${typeFilter}` : sql``}
+ LIMIT ${limit}
+ `;
+ let symbolRows: unknown[] = [];
+ if (direction !== 'in') {
+ const sRows = await sql`
+ SELECT id, from_chunk_id, NULL::int as to_chunk_id, from_symbol_qualified, to_symbol_qualified,
+ edge_type, edge_metadata, source_id, false as resolved
+ FROM code_edges_symbol
+ WHERE from_chunk_id = ${chunkId}
+ ${typeFilter ? sql`AND edge_type = ${typeFilter}` : sql``}
+ LIMIT ${limit}
+ `;
+ symbolRows = [...sRows];
+ }
+ return [...chunkRows, ...symbolRows].map(r => pgRowToCodeEdge(r as Record<string, unknown>));
+ }
+
+function pgRowToCodeEdge(row: Record<string, unknown>): import('../types.ts').CodeEdgeResult {
+ return {
+ id: row.id as number,
+ from_chunk_id: row.from_chunk_id as number,
+ to_chunk_id: row.to_chunk_id == null ? null : (row.to_chunk_id as number),
+ from_symbol_qualified: (row.from_symbol_qualified as string) ?? '',
+ to_symbol_qualified: (row.to_symbol_qualified as string) ?? '',
+ edge_type: (row.edge_type as string) ?? '',
+ edge_metadata: (row.edge_metadata as Record<string, unknown>) ?? {},
+ source_id: row.source_id == null ? null : (row.source_id as string),
+ resolved: Boolean(row.resolved),
+ };
+}
diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.ts
new file mode 100644
index 0000000000..70c63cf377
--- /dev/null
+++ b/src/core/postgres-engine/facts.ts
@@ -0,0 +1,537 @@
+/**
+ * v0.31: Hot memory — facts table operations, peeled out of PostgresEngine
+ * (containment sprint C15). Free functions over a NARROW deps surface — the
+ * live postgres.js pool + the engine's cached facts.embedding cast probe.
+ * Never the whole engine class.
+ */
+import type postgres from 'postgres';
+
+type PgSql = ReturnType<typeof postgres>;
+
+import type {
+ FactRow, FactKind, FactVisibility, FactInsertStatus,
+ NewFact, FactListOpts, FactsHealth,
+} from '../engine.ts';
+import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';
+import { tryParseEmbedding } from '../utils.ts';
+
+/** Narrow slice of PostgresEngine the facts operations use. */
+export interface PgFactsDeps {
+ /** Live postgres.js pool. Getter-backed at the call site so the
+ * connection check fires exactly when the original engine `sql` read did. */
+ readonly sql: PgSql;
+ /** Cast-suffix probe for facts.embedding (cache state lives on the engine). */
+ resolveFactsEmbeddingCast(): Promise<'::vector' | '::halfvec'>;
+}
+
+export async function insertFact(
+ deps: PgFactsDeps,
+ input: NewFact,
+ ctx: { source_id: string; supersedeId?: number },
+ ): Promise<{ id: number; status: FactInsertStatus }> {
+ const sql = deps.sql;
+ const validFrom = input.valid_from ?? new Date();
+ const validUntil = input.valid_until ?? null;
+ const kind = input.kind ?? 'fact';
+ const visibility = input.visibility ?? 'private';
+ const notability = input.notability ?? 'medium';
+ const confidence = input.confidence ?? 1.0;
+ const entitySlug = input.entity_slug ?? null;
+ const context = input.context ?? null;
+ const sourceSession = input.source_session ?? null;
+ const embedding = input.embedding ?? null;
+ const embeddedAt = embedding ? new Date() : null;
+ const embedLit = embedding ? toPgVectorLiteral(embedding) : null;
+ // v0.41.15.0 (T6, codex #20): match cast to actual column type so
+ // a halfvec(N) column doesn't pay an implicit-cast round-trip + can
+ // run on pgvector versions that lack the auto vector→halfvec cast.
+ const castSuffix = await deps.resolveFactsEmbeddingCast();
+ // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
+ const claimMetric = input.claim_metric ?? null;
+ const claimValue = input.claim_value ?? null;
+ const claimUnit = input.claim_unit ?? null;
+ const claimPeriod = input.claim_period ?? null;
+
+ if (ctx.supersedeId !== undefined) {
+ // Per-entity advisory lock + atomic insert + supersede in one txn.
+ const supersedeId = ctx.supersedeId;
+ const newId = await sql.begin(async (tx) => {
+ if (entitySlug) {
+ await tx`SELECT pg_advisory_xact_lock(hashtextextended(${ctx.source_id} || ':' || ${entitySlug}, 0))`;
+ }
+ const ins = await tx<Array<{ id: number }>>`
+ INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ claim_metric, claim_value, claim_unit, claim_period
+ ) VALUES (
+ ${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
+ ${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
+ ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
+ ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
+ ) RETURNING id
+ `;
+ const id = Number(ins[0].id);
+ await tx`UPDATE facts SET expired_at = now(), superseded_by = ${id}
+ WHERE id = ${supersedeId} AND expired_at IS NULL`;
+ return id;
+ });
+ return { id: newId, status: 'superseded' };
+ }
+
+ // Plain insert path with optional advisory lock for the dedup window.
+ const id = await sql.begin(async (tx) => {
+ if (entitySlug) {
+ await tx`SELECT pg_advisory_xact_lock(hashtextextended(${ctx.source_id} || ':' || ${entitySlug}, 0))`;
+ }
+ const ins = await tx<Array<{ id: number }>>`
+ INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ claim_metric, claim_value, claim_unit, claim_period
+ ) VALUES (
+ ${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
+ ${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
+ ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
+ ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
+ ) RETURNING id
+ `;
+ return Number(ins[0].id);
+ });
+ return { id, status: 'inserted' };
+ }
+
+export async function expireFact(deps: PgFactsDeps, id: number, opts?: { supersededBy?: number; at?: Date }): Promise<boolean> {
+ const sql = deps.sql;
+ const at = opts?.at ?? new Date();
+ const supersededBy = opts?.supersededBy ?? null;
+ const result = await sql`
+ UPDATE facts SET expired_at = ${at}, superseded_by = COALESCE(${supersededBy}, superseded_by)
+ WHERE id = ${id} AND expired_at IS NULL
+ `;
+ return (result.count ?? 0) > 0;
+ }
+
+export async function insertFacts(
+ deps: PgFactsDeps,
+ rows: Array<NewFact & { row_num: number; source_markdown_slug: string }>,
+ ctx: { source_id: string },
+ ): Promise<{ inserted: number; ids: number[] }> {
+ if (rows.length === 0) return { inserted: 0, ids: [] };
+
+ const sql = deps.sql;
+ // v0.41.15.0 (T6, codex #20): resolve the embedding-cast suffix
+ // ONCE per process so the cast matches the actual column type
+ // (halfvec vs vector). The probe is cached after first call.
+ const castSuffix = await deps.resolveFactsEmbeddingCast();
+ // Single transaction so the v51 partial UNIQUE index can roll back
+ // the whole batch on constraint violation. Per-row INSERTs (not
+ // multi-row VALUES) keep the embedding-vs-no-embedding branching
+ // readable; batch sizes are small (5-30 rows per page in practice).
+ // No supersede flow in this path — fence reconciliation is the
+ // canonical source-of-truth direction, not the consolidator path.
+ const ids = await sql.begin(async (tx) => {
+ const out: number[] = [];
+ for (const input of rows) {
+ const validFrom = input.valid_from ?? new Date();
+ const validUntil = input.valid_until ?? null;
+ const kind = input.kind ?? 'fact';
+ const visibility = input.visibility ?? 'private';
+ const notability = input.notability ?? 'medium';
+ const confidence = input.confidence ?? 1.0;
+ const entitySlug = input.entity_slug ?? null;
+ const context = input.context ?? null;
+ const sourceSession = input.source_session ?? null;
+ const embedding = input.embedding ?? null;
+ const embeddedAt = embedding ? new Date() : null;
+ const embedLit = embedding ? toPgVectorLiteral(embedding) : null;
+ // v0.35.4 (D-CDX-5) — typed-claim columns. All four nullable.
+ const claimMetric = input.claim_metric ?? null;
+ const claimValue = input.claim_value ?? null;
+ const claimUnit = input.claim_unit ?? null;
+ const claimPeriod = input.claim_period ?? null;
+ // v0.40.2.0 — event_type column (Commit 1 migration v89).
+ const eventType = input.event_type ?? null;
+
+ const ins = await tx<Array<{ id: number }>>`
+ INSERT INTO facts (
+ source_id, entity_slug, fact, kind, visibility, notability, context,
+ valid_from, valid_until, source, source_session, confidence,
+ embedding, embedded_at,
+ row_num, source_markdown_slug,
+ claim_metric, claim_value, claim_unit, claim_period,
+ event_type
+ ) VALUES (
+ ${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
+ ${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
+ ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
+ ${input.row_num}, ${input.source_markdown_slug},
+ ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
+ ${eventType}
+ )
+ ON CONFLICT (source_id, source_markdown_slug, row_num)
+ WHERE row_num IS NOT NULL
+ DO NOTHING
+ RETURNING id
+ `;
+ if (ins[0]) out.push(Number(ins[0].id));
+ }
+ return out;
+ });
+ return { inserted: ids.length, ids };
+ }
+
+export async function deleteFactsForPage(
+ deps: PgFactsDeps,
+ slug: string,
+ source_id: string,
+ opts?: { excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean },
+ ): Promise<{ deleted: number }> {
+ const sql = deps.sql;
+ const prefixes = opts?.excludeSourcePrefixes;
+ // #2646: keep soft-expired legacy rows (row_num NULL — never
+ // fence-owned) so a fence reconcile can't destroy forget_fact's
+ // legacy DB-only forget record.
+ const expiredLegacyFilter = opts?.preserveExpiredLegacy
+ ? sql`AND NOT (row_num IS NULL AND expired_at IS NOT NULL)`
+ : sql``;
+ if (prefixes && prefixes.length > 0) {
+ // #1928: keep rows whose `source` matches an excluded prefix (e.g.
+ // `cli:` conversation facts). COALESCE so NULL/empty-source fence rows
+ // stay deletable — only the explicitly-protected prefixes survive.
+ const patterns = prefixes.map(p => `${p}%`);
+ const result = await sql`
+ DELETE FROM facts
+ WHERE source_id = ${source_id}
+ AND source_markdown_slug = ${slug}
+ AND NOT (COALESCE(source, '') LIKE ANY(${patterns}))
+ ${expiredLegacyFilter}
+ `;
+ return { deleted: result.count ?? 0 };
+ }
+ const result = await sql`
+ DELETE FROM facts WHERE source_id = ${source_id} AND source_markdown_slug = ${slug} ${expiredLegacyFilter}
+ `;
+ return { deleted: result.count ?? 0 };
+ }
+
+export async function listFactsByEntity(
+ deps: PgFactsDeps,
+ source_id: string,
+ entitySlug: string,
+ opts?: FactListOpts,
+ ): Promise<FactRow[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
+ const offset = Math.max(0, opts?.offset ?? 0);
+ const activeOnly = opts?.activeOnly !== false;
+ const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;
+ const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
+ const rows = await sql<FactRowSqlShape[]>`
+ SELECT * FROM facts
+ WHERE source_id = ${source_id}
+ AND entity_slug = ${entitySlug}
+ ${activeOnly ? sql`AND expired_at IS NULL` : sql``}
+ ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}
+ ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
+ ORDER BY valid_from DESC, id DESC
+ LIMIT ${limit} OFFSET ${offset}
+ `;
+ return rows.map(rowToFactPg);
+ }
+
+export async function listFactsSince(
+ deps: PgFactsDeps,
+ source_id: string,
+ since: Date,
+ opts?: FactListOpts & { entitySlug?: string },
+ ): Promise<FactRow[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
+ const offset = Math.max(0, opts?.offset ?? 0);
+ const activeOnly = opts?.activeOnly !== false;
+ const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;
+ const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
+ const entitySlug = opts?.entitySlug ?? null;
+ const rows = await sql<FactRowSqlShape[]>`
+ SELECT * FROM facts
+ WHERE source_id = ${source_id}
+ AND created_at >= ${since}
+ ${entitySlug ? sql`AND entity_slug = ${entitySlug}` : sql``}
+ ${activeOnly ? sql`AND expired_at IS NULL` : sql``}
+ ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}
+ ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
+ ORDER BY created_at DESC, id DESC
+ LIMIT ${limit} OFFSET ${offset}
+ `;
+ return rows.map(rowToFactPg);
+ }
+
+export async function listFactsBySession(
+ deps: PgFactsDeps,
+ source_id: string,
+ sessionId: string,
+ opts?: FactListOpts,
+ ): Promise<FactRow[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
+ const offset = Math.max(0, opts?.offset ?? 0);
+ const activeOnly = opts?.activeOnly !== false;
+ const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;
+ const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
+ const rows = await sql<FactRowSqlShape[]>`
+ SELECT * FROM facts
+ WHERE source_id = ${source_id}
+ AND source_session = ${sessionId}
+ ${activeOnly ? sql`AND expired_at IS NULL` : sql``}
+ ${kinds ? sql`AND kind = ANY(${kinds}::text[])` : sql``}
+ ${visibility ? sql`AND visibility = ANY(${visibility}::text[])` : sql``}
+ ORDER BY created_at DESC, id DESC
+ LIMIT ${limit} OFFSET ${offset}
+ `;
+ return rows.map(rowToFactPg);
+ }
+
+export async function listSupersessions(
+ deps: PgFactsDeps,
+ source_id: string,
+ opts?: { since?: Date; limit?: number },
+ ): Promise<FactRow[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
+ const since = opts?.since ?? null;
+ const rows = await sql<FactRowSqlShape[]>`
+ SELECT * FROM facts
+ WHERE source_id = ${source_id}
+ AND expired_at IS NOT NULL
+ AND superseded_by IS NOT NULL
+ ${since ? sql`AND expired_at >= ${since}` : sql``}
+ ORDER BY expired_at DESC, id DESC
+ LIMIT ${limit}
+ `;
+ return rows.map(rowToFactPg);
+ }
+
+export async function countUnconsolidatedFacts(deps: PgFactsDeps, source_id: string): Promise<number> {
+ const sql = deps.sql;
+ const rows = await sql<{ count: number }[]>`
+ SELECT COUNT(*)::int AS count FROM facts
+ WHERE source_id = ${source_id}
+ AND consolidated_at IS NULL
+ AND expired_at IS NULL
+ `;
+ return Number(rows[0]?.count ?? 0);
+ }
+
+export async function findCandidateDuplicates(
+ deps: PgFactsDeps,
+ source_id: string,
+ entitySlug: string,
+ factText: string,
+ opts?: { k?: number; embedding?: Float32Array },
+ ): Promise<FactRow[]> {
+ const sql = deps.sql;
+ const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
+ if (opts?.embedding) {
+ const lit = toPgVectorLiteral(opts.embedding);
+ const rows = await sql<FactRowSqlShape[]>`
+ SELECT * FROM facts
+ WHERE source_id = ${source_id}
+ AND entity_slug = ${entitySlug}
+ AND expired_at IS NULL
+ AND embedding IS NOT NULL
+ ORDER BY embedding <=> ${sql.unsafe(`'${lit}'::vector`)}
+ LIMIT ${k}
+ `;
+ return rows.map(rowToFactPg);
+ }
+ const rows = await sql<FactRowSqlShape[]>`
+ SELECT * FROM facts
+ WHERE source_id = ${source_id}
+ AND entity_slug = ${entitySlug}
+ AND expired_at IS NULL
+ ORDER BY created_at DESC, id DESC
+ LIMIT ${k}
+ `;
+ return rows.map(rowToFactPg);
+ }
+
+export async function consolidateFact(deps: PgFactsDeps, id: number, takeId: number): Promise<void> {
+ const sql = deps.sql;
+ await sql`UPDATE facts SET consolidated_at = now(), consolidated_into = ${takeId} WHERE id = ${id}`;
+ }
+
+export async function findTrajectory(deps: PgFactsDeps, opts: import('../engine.ts').TrajectoryOpts): Promise<import('../engine.ts').TrajectoryPoint[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts.limit, 100, 500);
+ const sinceDate = opts.since ? new Date(opts.since) : null;
+ const untilDate = opts.until ? new Date(opts.until) : null;
+ const metric = opts.metric ?? null;
+ const kind = opts.kind ?? 'all';
+ const useArray = Array.isArray(opts.sourceIds) && opts.sourceIds.length > 0;
+ const sourceIds = useArray ? opts.sourceIds! : null;
+ const sourceId = opts.sourceId ?? 'default';
+ const remoteFilter = opts.remote === true;
+
+ // Source-scope predicate: array path (federated) wins over scalar.
+ // Engine.ts contract: returns chronological points; regressions +
+ // drift_score are computed by the caller (src/core/trajectory.ts).
+ // v0.40.2.0 — kind filter ('all'|'metric'|'event'); event_type column.
+ const rows = await sql<Array<{
+ id: number;
+ valid_from: Date;
+ claim_metric: string | null;
+ claim_value: number | null;
+ claim_unit: string | null;
+ claim_period: string | null;
+ event_type: string | null;
+ fact: string;
+ source_session: string | null;
+ source_markdown_slug: string | null;
+ embedding: string | null;
+ }>>`
+ SELECT id, valid_from,
+ claim_metric, claim_value, claim_unit, claim_period,
+ event_type,
+ fact, source_session, source_markdown_slug,
+ embedding::text AS embedding
+ FROM facts
+ WHERE ${useArray ? sql`source_id = ANY(${sourceIds}::text[])` : sql`source_id = ${sourceId}`}
+ AND entity_slug = ${opts.entitySlug}
+ AND expired_at IS NULL
+ ${remoteFilter ? sql`AND visibility = 'world'` : sql``}
+ ${metric !== null ? sql`AND claim_metric = ${metric}` : sql``}
+ ${kind === 'metric' ? sql`AND claim_metric IS NOT NULL` : sql``}
+ ${kind === 'event' ? sql`AND event_type IS NOT NULL` : sql``}
+ ${sinceDate ? sql`AND valid_from >= ${sinceDate}` : sql``}
+ ${untilDate ? sql`AND valid_from <= ${untilDate}` : sql``}
+ ORDER BY valid_from ASC, id ASC
+ LIMIT ${limit}
+ `;
+
+ return rows.map(r => ({
+ fact_id: Number(r.id),
+ valid_from: r.valid_from,
+ metric: r.claim_metric,
+ value: r.claim_value === null ? null : Number(r.claim_value),
+ unit: r.claim_unit,
+ period: r.claim_period,
+ event_type: r.event_type,
+ text: r.fact,
+ source_session: r.source_session,
+ source_markdown_slug: r.source_markdown_slug,
+ embedding: tryParseEmbedding(r.embedding),
+ }));
+ }
+
+export async function getFactsHealth(deps: PgFactsDeps, source_id: string): Promise<FactsHealth> {
+ const sql = deps.sql;
+ const totals = await sql<Array<{
+ total_active: bigint; total_today: bigint; total_week: bigint;
+ total_expired: bigint; total_consolidated: bigint;
+ }>>`
+ SELECT
+ COUNT(*) FILTER (WHERE expired_at IS NULL) AS total_active,
+ COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '24 hours') AS total_today,
+ COUNT(*) FILTER (WHERE expired_at IS NULL AND created_at > now() - interval '7 days') AS total_week,
+ COUNT(*) FILTER (WHERE expired_at IS NOT NULL) AS total_expired,
+ COUNT(*) FILTER (WHERE consolidated_at IS NOT NULL) AS total_consolidated
+ FROM facts WHERE source_id = ${source_id}
+ `;
+ const top = await sql<Array<{ entity_slug: string; count: bigint }>>`
+ SELECT entity_slug, COUNT(*) AS count
+ FROM facts
+ WHERE source_id = ${source_id} AND expired_at IS NULL AND entity_slug IS NOT NULL
+ GROUP BY entity_slug
+ ORDER BY count DESC, entity_slug ASC
+ LIMIT 5
+ `;
+ const r = totals[0] ?? {
+ total_active: 0n, total_today: 0n, total_week: 0n, total_expired: 0n, total_consolidated: 0n,
+ };
+ return {
+ source_id,
+ total_active: Number(r.total_active),
+ total_today: Number(r.total_today),
+ total_week: Number(r.total_week),
+ total_expired: Number(r.total_expired),
+ total_consolidated: Number(r.total_consolidated),
+ top_entities: top.map(t => ({ entity_slug: t.entity_slug, count: Number(t.count) })),
+ };
+ }
+
+/**
+ * Raw row shape returned from `SELECT * FROM facts` on Postgres.
+ * postgres.js auto-decodes timestamps and numbers; embedding lands as
+ * either a string ("[0.1,...]") or already-parsed array depending on type
+ * codec — we handle both.
+ */
+interface FactRowSqlShape {
+ id: number | bigint;
+ source_id: string;
+ entity_slug: string | null;
+ fact: string;
+ kind: FactKind;
+ visibility: FactVisibility;
+ notability: 'high' | 'medium' | 'low';
+ context: string | null;
+ valid_from: Date;
+ valid_until: Date | null;
+ expired_at: Date | null;
+ superseded_by: number | bigint | null;
+ consolidated_at: Date | null;
+ consolidated_into: number | bigint | null;
+ source: string;
+ source_session: string | null;
+ confidence: number | string;
+ embedding: string | number[] | Float32Array | null;
+ embedded_at: Date | null;
+ created_at: Date;
+}
+
+function rowToFactPg(row: FactRowSqlShape): FactRow {
+ let embedding: Float32Array | null = null;
+ if (row.embedding != null) {
+ if (row.embedding instanceof Float32Array) embedding = row.embedding;
+ else if (Array.isArray(row.embedding)) embedding = new Float32Array(row.embedding);
+ else if (typeof row.embedding === 'string') {
+ const trimmed = row.embedding.trim();
+ const inner = trimmed.startsWith('[') ? trimmed.slice(1, -1) : trimmed;
+ const parts = inner.split(',').map(p => parseFloat(p.trim())).filter(Number.isFinite);
+ embedding = parts.length > 0 ? new Float32Array(parts) : null;
+ }
+ }
+ return {
+ id: Number(row.id),
+ source_id: row.source_id,
+ entity_slug: row.entity_slug,
+ fact: row.fact,
+ kind: row.kind,
+ visibility: row.visibility,
+ // v0.31.2: notability column added by migration v46. Pre-v46 rows that
+ // somehow survive a SELECT (shouldn't on a fully-migrated brain) fall
+ // back to 'medium' to keep the contract total. Belt-and-suspenders with
+ // the migration's NOT NULL DEFAULT.
+ notability: row.notability ?? 'medium',
+ context: row.context,
+ valid_from: row.valid_from,
+ valid_until: row.valid_until,
+ expired_at: row.expired_at,
+ superseded_by: row.superseded_by == null ? null : Number(row.superseded_by),
+ consolidated_at: row.consolidated_at,
+ consolidated_into: row.consolidated_into == null ? null : Number(row.consolidated_into),
+ source: row.source,
+ source_session: row.source_session,
+ confidence: typeof row.confidence === 'string' ? parseFloat(row.confidence) : row.confidence,
+ embedding,
+ embedded_at: row.embedded_at,
+ created_at: row.created_at,
+ };
+}
+
+function toPgVectorLiteral(v: Float32Array | number[]): string {
+ if (v instanceof Float32Array) return '[' + Array.from(v).join(',') + ']';
+ return '[' + v.join(',') + ']';
+}
diff --git a/src/core/postgres-engine/salience.ts b/src/core/postgres-engine/salience.ts
new file mode 100644
index 0000000000..a3f0a68fa9
--- /dev/null
+++ b/src/core/postgres-engine/salience.ts
@@ -0,0 +1,362 @@
+/**
+ * v0.29 — Salience + Anomaly Detection, peeled out of PostgresEngine
+ * (containment sprint C15). Free functions over a NARROW deps surface —
+ * never the whole engine class.
+ */
+import type postgres from 'postgres';
+
+type PgSql = ReturnType<typeof postgres>;
+
+import { clampSearchLimit } from '../engine.ts';
+import type {
+ SalienceOpts, SalienceResult, AnomaliesOpts, AnomalyResult,
+ EmotionalWeightInputRow, EmotionalWeightWriteRow,
+ EnrichCandidatesOpts, EnrichCandidate,
+} from '../types.ts';
+import { ENRICH_ORDER_SQL } from '../types.ts';
+import {
+ resolveRecencyDecayMap,
+ DEFAULT_FALLBACK,
+} from '../search/recency-decay.ts';
+import { buildRecencyComponentSql } from '../search/sql-ranking.ts';
+import { computeAnomaliesFromBuckets } from '../cycle/anomaly.ts';
+
+/** Narrow slice of PostgresEngine the salience/anomaly operations use. */
+export interface PgSalienceDeps {
+ /** Live postgres.js pool (getter-backed at the call site). */
+ readonly sql: PgSql;
+}
+
+export async function batchLoadEmotionalInputs(deps: PgSalienceDeps, slugs?: string[]): Promise<EmotionalWeightInputRow[]> {
+ const sql = deps.sql;
+ // Two CTEs avoid the N×M cartesian product (codex C4#4): a page with N tags
+ // and M takes joined directly would emit N×M rows and corrupt aggregates.
+ // Per-table aggregation keeps each table's grouping correct.
+ const rows = slugs
+ ? await sql`
+ WITH page_tags AS (
+ SELECT page_id, array_agg(DISTINCT tag) AS tags
+ FROM tags GROUP BY page_id
+ ),
+ page_takes AS (
+ SELECT page_id, json_agg(json_build_object(
+ 'holder', holder, 'weight', weight, 'kind', kind, 'active', active
+ )) AS takes
+ FROM takes WHERE active = TRUE GROUP BY page_id
+ )
+ SELECT p.slug, p.source_id,
+ COALESCE(pt.tags, ARRAY[]::text[]) AS tags,
+ COALESCE(pk.takes, '[]'::json) AS takes
+ FROM pages p
+ LEFT JOIN page_tags pt ON pt.page_id = p.id
+ LEFT JOIN page_takes pk ON pk.page_id = p.id
+ WHERE p.slug = ANY(${slugs}::text[])
+ `
+ : await sql`
+ WITH page_tags AS (
+ SELECT page_id, array_agg(DISTINCT tag) AS tags
+ FROM tags GROUP BY page_id
+ ),
+ page_takes AS (
+ SELECT page_id, json_agg(json_build_object(
+ 'holder', holder, 'weight', weight, 'kind', kind, 'active', active
+ )) AS takes
+ FROM takes WHERE active = TRUE GROUP BY page_id
+ )
+ SELECT p.slug, p.source_id,
+ COALESCE(pt.tags, ARRAY[]::text[]) AS tags,
+ COALESCE(pk.takes, '[]'::json) AS takes
+ FROM pages p
+ LEFT JOIN page_tags pt ON pt.page_id = p.id
+ LEFT JOIN page_takes pk ON pk.page_id = p.id
+ `;
+ return rows.map((r: Record<string, unknown>) => ({
+ slug: String(r.slug),
+ source_id: String(r.source_id),
+ tags: (r.tags as string[]) ?? [],
+ takes: (r.takes as EmotionalWeightInputRow['takes']) ?? [],
+ }));
+ }
+
+export async function setEmotionalWeightBatch(deps: PgSalienceDeps, rows: EmotionalWeightWriteRow[]): Promise<number> {
+ if (rows.length === 0) return 0;
+ const sql = deps.sql;
+ const slugs = rows.map(r => r.slug);
+ const sourceIds = rows.map(r => r.source_id);
+ const weights = rows.map(r => r.weight);
+ // Composite-keyed UPDATE FROM unnest (codex C4#3): pages.slug is unique
+ // only within a source, so a slug-only join would fan out across sources.
+ //
+ // v0.29.1: bump salience_touched_at to NOW() ONLY when emotional_weight
+ // actually changes. The salience query window then includes the page in
+ // GREATEST(updated_at, salience_touched_at) >= boundary, so a previously
+ // calm page that just became salient surfaces in the recent salience
+ // results without a content edit. No-op writes (same weight) leave
+ // salience_touched_at alone — preserves "actual change" semantics.
+ const result = await sql`
+ UPDATE pages
+ SET emotional_weight = u.weight,
+ salience_touched_at = CASE
+ WHEN pages.emotional_weight IS DISTINCT FROM u.weight THEN now()
+ ELSE pages.salience_touched_at
+ END
+ FROM unnest(${slugs}::text[], ${sourceIds}::text[], ${weights}::real[])
+ AS u(slug, source_id, weight)
+ WHERE pages.slug = u.slug AND pages.source_id = u.source_id
+ RETURNING 1
+ `;
+ return result.length;
+ }
+
+export async function getRecentSalience(deps: PgSalienceDeps, opts: SalienceOpts): Promise<SalienceResult[]> {
+ const sql = deps.sql;
+ const days = Math.max(0, opts.days ?? 14);
+ const limit = clampSearchLimit(opts.limit, 20, 100);
+ const slugPrefix = opts.slugPrefix;
+ // Compute the boundary in JS so the SQL is identical across engines (eng review D5).
+ const boundaryIso = new Date(Date.now() - days * 86400000).toISOString();
+ // Escape LIKE meta for the optional prefix match.
+ const prefixCondition = slugPrefix
+ ? sql`AND p.slug LIKE ${slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%'} ESCAPE '\\'`
+ : sql``;
+ // TIM-37: exclude briefing pages from their own Brain Pulse. The cron
+ // briefing writes to 90_Briefings/, gets re-ingested, and would otherwise
+ // top tomorrow's salience as pure self-reference. Suppress unless the
+ // caller explicitly asked for the briefings/ prefix.
+ const excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))
+ ? sql`AND p.slug NOT LIKE 'briefings/%'`
+ : sql``;
+ // v0.29.1: third score term via buildRecencyComponentSql. Default
+ // 'flat' = v0.29.0 behavior (1 / (1 + days_old)). 'on' opts into the
+ // per-prefix decay map (concepts/ evergreen, daily/ aggressive, etc.).
+ const recencyBias = opts.recency_bias ?? 'flat';
+ let recencySql: string;
+ if (recencyBias === 'on') {
+ recencySql = buildRecencyComponentSql({
+ slugColumn: 'p.slug',
+ dateExpr: 'COALESCE(p.effective_date, p.updated_at)',
+ decayMap: resolveRecencyDecayMap(),
+ fallback: DEFAULT_FALLBACK,
+ });
+ } else {
+ recencySql = buildRecencyComponentSql({
+ slugColumn: 'p.slug',
+ dateExpr: 'p.updated_at',
+ decayMap: {},
+ fallback: { halflifeDays: 1, coefficient: 1.0 },
+ });
+ }
+ const rows = await sql`
+ SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, p.emotional_weight,
+ COUNT(DISTINCT t.id) AS take_count,
+ COALESCE(AVG(t.weight), 0) AS take_avg_weight,
+ (p.emotional_weight * 5)
+ + ln(1 + COUNT(DISTINCT t.id))
+ + ${sql.unsafe(recencySql)}
+ AS score
+ FROM 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
+ ${prefixCondition}
+ ${excludeBriefings}
+ GROUP BY p.id
+ ORDER BY score DESC
+ LIMIT ${limit}
+ `;
+ return rows.map((r: Record<string, unknown>) => ({
+ slug: String(r.slug),
+ source_id: String(r.source_id),
+ title: String(r.title ?? ''),
+ type: r.type as SalienceResult['type'],
+ updated_at: r.updated_at as Date,
+ emotional_weight: Number(r.emotional_weight ?? 0),
+ take_count: Number(r.take_count ?? 0),
+ take_avg_weight: Number(r.take_avg_weight ?? 0),
+ score: Number(r.score ?? 0),
+ }));
+ }
+
+export async function listEnrichCandidates(deps: PgSalienceDeps, opts: EnrichCandidatesOpts): Promise<EnrichCandidate[]> {
+ // v0.41.39 (issue #1700). Empty types → no rows (no SQL).
+ if (!opts.types || opts.types.length === 0) return [];
+ const sql = deps.sql;
+ const limit = Math.max(1, Math.min(opts.limit ?? 50, 5000));
+ const threshold = Math.max(0, opts.thinThreshold);
+
+ // Source scope: array wins over scalar (canonical precedence).
+ const sourceCondition = opts.sourceIds && opts.sourceIds.length > 0
+ ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
+ : opts.sourceId
+ ? sql`AND p.source_id = ${opts.sourceId}`
+ : sql``;
+
+ // Re-enrich recency guard. enriched_at is written as toISOString() so a
+ // lexical text comparison is correct AND can't throw on a malformed value
+ // (a ::timestamptz cast would). Pages never enriched (NULL) are eligible.
+ const reenrichMs = opts.reenrichAfterMs ?? 0;
+ const recencyCondition = reenrichMs > 0
+ ? sql`AND NOT (
+ p.frontmatter ->> 'enriched_at' IS NOT NULL
+ AND p.frontmatter ->> 'enriched_at' > ${new Date(Date.now() - reenrichMs).toISOString()}
+ )`
+ : sql``;
+
+ // Exclude dream/synthesize-generated pages (reflections, originals, cycle
+ // logs carrying frontmatter dream_generated:true). enrich develops ENTITY
+ // stubs; running it on a generated essay/log creates circular self-citation
+ // and drops the H1. IS DISTINCT FROM 'true' keeps NULL/'false' rows.
+ const dreamCondition = sql`AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true'`;
+
+ // Whitelisted ORDER BY (no injection — enum maps to a literal fragment).
+ const orderKey = ENRICH_ORDER_SQL[opts.order] ? opts.order : 'inbound-links';
+ const orderBy = sql.unsafe(ENRICH_ORDER_SQL[orderKey]);
+
+ const rows = await sql`
+ SELECT
+ p.slug,
+ p.source_id,
+ p.title,
+ p.type,
+ (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len,
+ COALESCE((
+ SELECT COUNT(*)
+ FROM links l
+ WHERE l.to_page_id = p.id
+ AND l.link_source IS DISTINCT FROM 'mentions'
+ ), 0)::int AS inbound_count
+ FROM pages p
+ WHERE p.deleted_at IS NULL
+ AND p.type = ANY(${opts.types}::text[])
+ AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < ${threshold}
+ ${sourceCondition}
+ ${recencyCondition}
+ ${dreamCondition}
+ ORDER BY ${orderBy}
+ LIMIT ${limit}
+ `;
+ return rows.map((r: Record<string, unknown>) => ({
+ slug: String(r.slug),
+ source_id: String(r.source_id),
+ title: String(r.title ?? ''),
+ type: r.type as EnrichCandidate['type'],
+ body_len: Number(r.body_len ?? 0),
+ inbound_count: Number(r.inbound_count ?? 0),
+ }));
+ }
+
+export async function findAnomalies(deps: PgSalienceDeps, opts: AnomaliesOpts): Promise<AnomalyResult[]> {
+ const sql = deps.sql;
+ const sigma = opts.sigma ?? 3.0;
+ const lookbackDays = Math.max(1, opts.lookback_days ?? 30);
+ // Boundaries: today's window is [since, since+1day); baseline is [since-lookback, since).
+ const sinceIso = (opts.since ?? new Date().toISOString().slice(0, 10)); // YYYY-MM-DD
+ const sinceDate = new Date(sinceIso + 'T00:00:00Z');
+ const sinceEnd = new Date(sinceDate.getTime() + 86400000);
+ const baselineStart = new Date(sinceDate.getTime() - lookbackDays * 86400000);
+
+ // Tag cohort baseline with day densification + zero-fill (codex C4#6).
+ const tagBaseline = await sql`
+ WITH days AS (
+ SELECT day::date FROM generate_series(
+ ${baselineStart.toISOString()}::date,
+ ${sinceDate.toISOString()}::date - 1,
+ '1 day'::interval
+ ) AS day
+ ),
+ cohort_keys AS (
+ SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_id
+ WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
+ AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
+ ),
+ touched AS (
+ SELECT t.tag,
+ date_trunc('day', p.updated_at)::date AS day,
+ COUNT(DISTINCT p.id) AS cnt
+ FROM tags t JOIN pages p ON p.id = t.page_id
+ WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
+ AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
+ GROUP BY 1, 2
+ )
+ SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
+ FROM cohort_keys cd CROSS JOIN days d
+ LEFT JOIN touched t ON t.tag = cd.tag AND t.day = d.day
+ `;
+
+ const typeBaseline = await sql`
+ WITH days AS (
+ SELECT day::date FROM generate_series(
+ ${baselineStart.toISOString()}::date,
+ ${sinceDate.toISOString()}::date - 1,
+ '1 day'::interval
+ ) AS day
+ ),
+ cohort_keys AS (
+ SELECT DISTINCT p.type FROM pages p
+ WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
+ AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
+ ),
+ touched AS (
+ SELECT p.type,
+ date_trunc('day', p.updated_at)::date AS day,
+ COUNT(DISTINCT p.id) AS cnt
+ FROM pages p
+ WHERE p.updated_at >= ${baselineStart.toISOString()}::timestamptz
+ AND p.updated_at < ${sinceDate.toISOString()}::timestamptz
+ GROUP BY 1, 2
+ )
+ SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count
+ FROM cohort_keys cd CROSS JOIN days d
+ LEFT JOIN touched t ON t.type = cd.type AND t.day = d.day
+ `;
+
+ // Today's window — current counts + slugs per cohort.
+ const tagToday = await sql`
+ SELECT t.tag AS cohort_value,
+ COUNT(DISTINCT p.id)::int AS count,
+ array_agg(DISTINCT p.slug) AS slugs
+ FROM tags t JOIN pages p ON p.id = t.page_id
+ WHERE p.updated_at >= ${sinceIso}::timestamptz
+ AND p.updated_at < ${sinceEnd.toISOString()}::timestamptz
+ GROUP BY 1
+ `;
+ const typeToday = await sql`
+ SELECT p.type AS cohort_value,
+ COUNT(DISTINCT p.id)::int AS count,
+ array_agg(DISTINCT p.slug) AS slugs
+ FROM pages p
+ WHERE p.updated_at >= ${sinceIso}::timestamptz
+ AND p.updated_at < ${sinceEnd.toISOString()}::timestamptz
+ GROUP BY 1
+ `;
+
+ const baseline = [
+ ...tagBaseline.map((r: Record<string, unknown>) => ({
+ cohort_kind: 'tag' as const,
+ cohort_value: String(r.cohort_value),
+ day: String(r.day),
+ count: Number(r.count),
+ })),
+ ...typeBaseline.map((r: Record<string, unknown>) => ({
+ cohort_kind: 'type' as const,
+ cohort_value: String(r.cohort_value),
+ day: String(r.day),
+ count: Number(r.count),
+ })),
+ ];
+ const today = [
+ ...tagToday.map((r: Record<string, unknown>) => ({
+ cohort_kind: 'tag' as const,
+ cohort_value: String(r.cohort_value),
+ count: Number(r.count),
+ page_slugs: (r.slugs as string[]) ?? [],
+ })),
+ ...typeToday.map((r: Record<string, unknown>) => ({
+ cohort_kind: 'type' as const,
+ cohort_value: String(r.cohort_value),
+ count: Number(r.count),
+ page_slugs: (r.slugs as string[]) ?? [],
+ })),
+ ];
+
+ return computeAnomaliesFromBuckets(baseline, today, sigma);
+ }
diff --git a/src/core/postgres-engine/takes.ts b/src/core/postgres-engine/takes.ts
new file mode 100644
index 0000000000..edd6f28149
--- /dev/null
+++ b/src/core/postgres-engine/takes.ts
@@ -0,0 +1,629 @@
+/**
+ * v0.28: Takes (typed/weighted/attributed claims) + synthesis_evidence,
+ * peeled out of PostgresEngine (containment sprint C15). Free functions over
+ * a NARROW deps surface — never the whole engine class.
+ */
+import type postgres from 'postgres';
+
+type PgSql = ReturnType<typeof postgres>;
+
+import type {
+ BatchOpts,
+ TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,
+ TakeResolution, SynthesisEvidenceInput,
+ TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,
+} from '../engine.ts';
+import { clampSearchLimit } from '../engine.ts';
+import type { SearchOpts } from '../types.ts';
+import { GBrainError } from '../types.ts';
+import type { BatchAuditSite } from '../retry.ts';
+import type { SqlValue } from '../sql-query.ts';
+import { deriveResolutionTuple, finalizeScorecard } from '../takes-resolution.ts';
+import { normalizeWeightForStorage } from '../takes-fence.ts';
+import { buildTakeRows } from '../batch-rows.ts';
+import { takeRowToTake, takeHitRowToHit, tryParseEmbedding } from '../utils.ts';
+
+/** Narrow slice of PostgresEngine the takes operations use. */
+export interface PgTakesDeps {
+ /** Live postgres.js pool (getter-backed at the call site). */
+ readonly sql: PgSql;
+ /** Engine batch retry wrapper (audit JSONL + backoff live on the engine). */
+ batchRetry<T>(
+ auditSite: BatchAuditSite,
+ signal: AbortSignal | undefined,
+ fn: () => Promise<T>,
+ batchSize: number,
+ ): Promise<T>;
+ /** JSONB-safe positional write helper, bound to the engine at the call site. */
+ executeRawJsonb<R = Record<string, unknown>>(
+ sql: string,
+ scalarParams: SqlValue[],
+ jsonbParams: unknown[],
+ ): Promise<R[]>;
+}
+
+export async function addTakesBatch(deps: PgTakesDeps, rowsIn: TakeBatchInput[], opts?: BatchOpts): Promise<number> {
+ if (rowsIn.length === 0) return 0;
+ // v0.42.26: takes is a batch primitive too — wrap in batchRetry so a
+ // Supavisor circuit-breaker blip doesn't silently drop takes the way it
+ // could before (links/timeline already had this; takes was the gap).
+ return deps.batchRetry(opts?.auditSite ?? 'addTakesBatch', opts?.signal, () => _addTakesBatchOnce(deps, rowsIn), rowsIn.length);
+ }
+
+async function _addTakesBatchOnce(deps: PgTakesDeps, rowsIn: TakeBatchInput[]): Promise<number> {
+ // #1861: JSONB jsonb_to_recordset instead of unnest(${arr}::text[]). `claim`
+ // is free LLM-extracted prose with the same array-literal crash hazard as
+ // link context. JSONB additionally lets us declare NATIVE recordset column
+ // types and emit JSON-native numbers/booleans, which retires the old
+ // postgres-js ${actives}::text[]::boolean[] element-type workaround entirely.
+ // Weight clamp/round + NUL-stripping live in buildTakeRows (shared w/ PGLite).
+ // NOTE: ON CONFLICT here is DO UPDATE (not DO NOTHING) — an intra-batch
+ // duplicate (page_id, row_num) errors, identical to the pre-#1861 unnest path.
+ const { rows, weightClamped } = buildTakeRows(rowsIn);
+ if (weightClamped > 0) {
+ process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: ${weightClamped} row(s) had weight outside [0,1]; clamped\n`);
+ }
+ const result = await deps.executeRawJsonb(
+ `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active)
+ SELECT v.page_id, v.row_num, v.claim, v.kind, v.holder, v.weight,
+ v.since_date, v.until_date, v.source, v.superseded_by, v.active
+ FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(
+ page_id int, row_num int, claim text, kind text, holder text, weight real,
+ since_date text, until_date text, source text, superseded_by int, active boolean
+ )
+ ON CONFLICT (page_id, row_num) DO UPDATE SET
+ claim = EXCLUDED.claim,
+ kind = EXCLUDED.kind,
+ holder = EXCLUDED.holder,
+ weight = EXCLUDED.weight,
+ since_date = EXCLUDED.since_date,
+ until_date = EXCLUDED.until_date,
+ source = EXCLUDED.source,
+ superseded_by = EXCLUDED.superseded_by,
+ active = EXCLUDED.active,
+ updated_at = now()
+ RETURNING 1`,
+ [],
+ [{ rows }],
+ );
+ return result.length;
+ }
+
+ /**
+ * v0.32.6 — batched per-page active-takes fetch (P1). One round-trip
+ * regardless of how many pages the caller passes. Honors holder allow-list
+ * for MCP scope enforcement. Pages with no active takes get an empty array.
+ */
+export async function listActiveTakesForPages(
+ deps: PgTakesDeps,
+ pageIds: number[],
+ opts: { takesHoldersAllowList?: string[] } = {},
+ ): Promise<Map<number, Take[]>> {
+ const out = new Map<number, Take[]>();
+ for (const pid of pageIds) out.set(pid, []);
+ if (pageIds.length === 0) return out;
+ const sql = deps.sql;
+ const rows = await sql`
+ SELECT t.*, p.slug AS page_slug
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.page_id = ANY(${pageIds}::int[])
+ AND t.active = true
+ AND (
+ ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
+ OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
+ )
+ ORDER BY t.page_id, t.row_num
+ `;
+ for (const r of rows) {
+ const take = takeRowToTake(r as Record<string, unknown>);
+ const bucket = out.get(take.page_id);
+ if (bucket) bucket.push(take);
+ }
+ return out;
+ }
+
+ /**
+ * v0.32.6 — persist a contradiction-probe run row (M5). Idempotent on
+ * run_id via ON CONFLICT DO NOTHING. Returns true iff a row was inserted.
+ */
+export async function writeContradictionsRun(deps: PgTakesDeps, row: {
+ run_id: string;
+ judge_model: string;
+ prompt_version: string;
+ queries_evaluated: number;
+ queries_with_contradiction: number;
+ total_contradictions_flagged: number;
+ wilson_ci_lower: number;
+ wilson_ci_upper: number;
+ judge_errors_total: number;
+ cost_usd_total: number;
+ duration_ms: number;
+ source_tier_breakdown: Record<string, unknown>;
+ report_json: Record<string, unknown>;
+ }): Promise<boolean> {
+ const sql = deps.sql;
+ const result = await sql`
+ INSERT INTO eval_contradictions_runs (
+ run_id, judge_model, prompt_version,
+ queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
+ wilson_ci_lower, wilson_ci_upper, judge_errors_total,
+ cost_usd_total, duration_ms,
+ source_tier_breakdown, report_json
+ ) VALUES (
+ ${row.run_id}, ${row.judge_model}, ${row.prompt_version},
+ ${row.queries_evaluated}, ${row.queries_with_contradiction}, ${row.total_contradictions_flagged},
+ ${row.wilson_ci_lower}, ${row.wilson_ci_upper}, ${row.judge_errors_total},
+ ${row.cost_usd_total}, ${row.duration_ms},
+ ${sql.json(row.source_tier_breakdown as Parameters<typeof sql.json>[0])},
+ ${sql.json(row.report_json as Parameters<typeof sql.json>[0])}
+ )
+ ON CONFLICT (run_id) DO NOTHING
+ `;
+ return result.count > 0;
+ }
+
+ /**
+ * v0.32.6 — load probe runs from the last N days, newest first (M5).
+ * Used by `trend` sub-subcommand and the doctor `contradictions` check.
+ */
+export async function loadContradictionsTrend(deps: PgTakesDeps, days: number): Promise<Array<{
+ run_id: string;
+ ran_at: string;
+ judge_model: string;
+ queries_evaluated: number;
+ queries_with_contradiction: number;
+ total_contradictions_flagged: number;
+ wilson_ci_lower: number;
+ wilson_ci_upper: number;
+ judge_errors_total: number;
+ cost_usd_total: number;
+ duration_ms: number;
+ source_tier_breakdown: Record<string, unknown>;
+ report_json: Record<string, unknown>;
+ }>> {
+ const sql = deps.sql;
+ const cutoff = new Date(Date.now() - Math.max(0, days) * 86400000);
+ const rows = await sql`
+ SELECT run_id, ran_at, judge_model,
+ queries_evaluated, queries_with_contradiction, total_contradictions_flagged,
+ wilson_ci_lower, wilson_ci_upper, judge_errors_total,
+ cost_usd_total, duration_ms,
+ source_tier_breakdown, report_json
+ FROM eval_contradictions_runs
+ WHERE ran_at >= ${cutoff}
+ ORDER BY ran_at DESC
+ `;
+ return rows.map((r) => ({
+ run_id: r.run_id as string,
+ ran_at: (r.ran_at instanceof Date ? r.ran_at.toISOString() : String(r.ran_at)),
+ judge_model: r.judge_model as string,
+ queries_evaluated: Number(r.queries_evaluated),
+ queries_with_contradiction: Number(r.queries_with_contradiction),
+ total_contradictions_flagged: Number(r.total_contradictions_flagged),
+ wilson_ci_lower: Number(r.wilson_ci_lower),
+ wilson_ci_upper: Number(r.wilson_ci_upper),
+ judge_errors_total: Number(r.judge_errors_total),
+ cost_usd_total: Number(r.cost_usd_total),
+ duration_ms: Number(r.duration_ms),
+ source_tier_breakdown: r.source_tier_breakdown as Record<string, unknown>,
+ report_json: r.report_json as Record<string, unknown>,
+ }));
+ }
+
+ /**
+ * v0.32.6 — judge cache lookup (P2). Returns verdict JSON for a non-
+ * expired row matching the full 5-component key, else NULL.
+ */
+export async function getContradictionCacheEntry(deps: PgTakesDeps, key: {
+ chunk_a_hash: string;
+ chunk_b_hash: string;
+ model_id: string;
+ prompt_version: string;
+ truncation_policy: string;
+ }): Promise<Record<string, unknown> | null> {
+ const sql = deps.sql;
+ const rows = await sql`
+ SELECT verdict
+ FROM eval_contradictions_cache
+ WHERE chunk_a_hash = ${key.chunk_a_hash}
+ AND chunk_b_hash = ${key.chunk_b_hash}
+ AND model_id = ${key.model_id}
+ AND prompt_version = ${key.prompt_version}
+ AND truncation_policy = ${key.truncation_policy}
+ AND expires_at > now()
+ LIMIT 1
+ `;
+ if (rows.length === 0) return null;
+ return rows[0].verdict as Record<string, unknown>;
+ }
+
+ /**
+ * v0.32.6 — judge cache upsert. ON CONFLICT DO UPDATE refreshes verdict +
+ * slides expires_at forward; same-key re-runs are safe.
+ */
+export async function putContradictionCacheEntry(deps: PgTakesDeps, opts: {
+ chunk_a_hash: string;
+ chunk_b_hash: string;
+ model_id: string;
+ prompt_version: string;
+ truncation_policy: string;
+ verdict: Record<string, unknown>;
+ ttl_seconds?: number;
+ }): Promise<void> {
+ const sql = deps.sql;
+ const ttl = Math.max(60, opts.ttl_seconds ?? 30 * 86400);
+ const expiresAt = new Date(Date.now() + ttl * 1000);
+ await sql`
+ INSERT INTO eval_contradictions_cache (
+ chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy,
+ verdict, expires_at
+ ) VALUES (
+ ${opts.chunk_a_hash}, ${opts.chunk_b_hash}, ${opts.model_id},
+ ${opts.prompt_version}, ${opts.truncation_policy},
+ ${sql.json(opts.verdict as Parameters<typeof sql.json>[0])}, ${expiresAt}
+ )
+ ON CONFLICT (chunk_a_hash, chunk_b_hash, model_id, prompt_version, truncation_policy)
+ DO UPDATE SET
+ verdict = EXCLUDED.verdict,
+ expires_at = EXCLUDED.expires_at,
+ created_at = now()
+ `;
+ }
+
+ /** v0.32.6 — periodic sweep of expired cache rows. */
+export async function sweepContradictionCache(deps: PgTakesDeps): Promise<number> {
+ const sql = deps.sql;
+ const result = await sql`
+ DELETE FROM eval_contradictions_cache WHERE expires_at <= now()
+ `;
+ return result.count ?? 0;
+ }
+
+export async function listTakes(deps: PgTakesDeps, opts: TakesListOpts = {}): Promise<Take[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts.limit, 100, 500);
+ const offset = Math.max(0, Math.floor(opts.offset ?? 0));
+ const active = opts.active ?? true;
+ // #2200-class: takes have no source_id of their own; scope via the page's
+ // source_id (already JOINed). Array wins over scalar, matching sourceScopeOpts.
+ const sourceFilter =
+ opts.sourceIds && opts.sourceIds.length > 0
+ ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
+ : opts.sourceId
+ ? sql`AND p.source_id = ${opts.sourceId}`
+ : sql``;
+ const rows = await sql`
+ SELECT t.*, p.slug AS page_slug
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE 1=1
+ 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)
+ AND (${opts.kind ?? null}::text IS NULL OR t.kind = ${opts.kind ?? null}::text)
+ AND (${active}::boolean IS NULL OR t.active = ${active}::boolean)
+ AND (
+ ${opts.resolved === undefined ? null : opts.resolved}::boolean IS NULL
+ OR (${opts.resolved === undefined ? null : opts.resolved}::boolean = true AND t.resolved_at IS NOT NULL)
+ OR (${opts.resolved === undefined ? null : opts.resolved}::boolean = false AND t.resolved_at IS NULL)
+ )
+ AND (
+ ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
+ OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
+ )
+ ${sourceFilter}
+ ORDER BY
+ CASE WHEN ${opts.sortBy ?? 'created_at'} = 'weight' THEN t.weight END DESC NULLS LAST,
+ CASE WHEN ${opts.sortBy ?? 'created_at'} = 'since_date' THEN t.since_date END DESC NULLS LAST,
+ CASE WHEN ${opts.sortBy ?? 'created_at'} = 'created_at' THEN t.created_at END DESC NULLS LAST
+ LIMIT ${limit} OFFSET ${offset}
+ `;
+ return rows.map((r) => takeRowToTake(r as Record<string, unknown>));
+ }
+
+export async function searchTakes(deps: PgTakesDeps, query: string, opts: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[] } = {}): Promise<TakeHit[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts.limit, 30, 100);
+ const sourceFilter = opts.sourceIds && opts.sourceIds.length > 0
+ ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
+ : opts.sourceId
+ ? sql`AND p.source_id = ${opts.sourceId}`
+ : sql``;
+ const rows = await sql`
+ SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
+ t.claim, t.kind, t.holder, t.weight,
+ word_similarity(${query}, t.claim)::real AS score
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.active
+ AND ${query} <% t.claim
+ AND (
+ ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
+ OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
+ )
+ ${sourceFilter}
+ ORDER BY score DESC, t.weight DESC
+ LIMIT ${limit}
+ `;
+ // #2450-class: int8 columns arrive as native BigInt from the pg driver;
+ // coerce per-row (takeRowToTake precedent) so MCP/CLI JSON.stringify
+ // doesn't crash the moment a search actually matches.
+ return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ }
+
+export async function searchTakesVector(
+ deps: PgTakesDeps,
+ embedding: Float32Array,
+ opts: SearchOpts & { takesHoldersAllowList?: string[]; sourceId?: string; sourceIds?: string[] } = {},
+ ): Promise<TakeHit[]> {
+ const sql = deps.sql;
+ const limit = clampSearchLimit(opts.limit, 30, 100);
+ const vec = `[${Array.from(embedding).join(',')}]`;
+ const sourceFilter = opts.sourceIds && opts.sourceIds.length > 0
+ ? sql`AND p.source_id = ANY(${opts.sourceIds}::text[])`
+ : opts.sourceId
+ ? sql`AND p.source_id = ${opts.sourceId}`
+ : sql``;
+ const rows = await sql`
+ SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num,
+ t.claim, t.kind, t.holder, t.weight,
+ (1 - (t.embedding <=> ${vec}::vector))::real AS score
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.active
+ AND t.embedding IS NOT NULL
+ AND (
+ ${opts.takesHoldersAllowList ?? null}::text[] IS NULL
+ OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
+ )
+ ${sourceFilter}
+ ORDER BY t.embedding <=> ${vec}::vector
+ LIMIT ${limit}
+ `;
+ // #2450-class: int8 columns arrive as native BigInt from the pg driver;
+ // coerce per-row (takeRowToTake precedent) so MCP/CLI JSON.stringify
+ // doesn't crash the moment a search actually matches.
+ return rows.map((r) => takeHitRowToHit(r as Record<string, unknown>));
+ }
+
+export async function getTakeEmbeddings(deps: PgTakesDeps, ids: number[]): Promise<Map<number, Float32Array>> {
+ if (ids.length === 0) return new Map();
+ const sql = deps.sql;
+ const rows = await sql`
+ SELECT id, embedding FROM takes WHERE id = ANY(${ids}::bigint[]) AND embedding IS NOT NULL
+ `;
+ const out = new Map<number, Float32Array>();
+ for (const r of rows as unknown as Array<{ id: number; embedding: unknown }>) {
+ const parsed = tryParseEmbedding(r.embedding);
+ if (parsed) out.set(Number(r.id), parsed);
+ }
+ return out;
+ }
+
+export async function countStaleTakes(deps: PgTakesDeps): Promise<number> {
+ const sql = deps.sql;
+ const [row] = await sql`
+ SELECT count(*)::int AS count FROM takes WHERE active AND embedding IS NULL
+ `;
+ return Number((row as { count?: number } | undefined)?.count ?? 0);
+ }
+
+export async function listStaleTakes(deps: PgTakesDeps): Promise<StaleTakeRow[]> {
+ const sql = deps.sql;
+ const rows = await sql`
+ SELECT t.id AS take_id, p.slug AS page_slug, t.row_num, t.claim
+ FROM takes t
+ JOIN pages p ON p.id = t.page_id
+ WHERE t.active AND t.embedding IS NULL
+ ORDER BY t.id
+ LIMIT 100000
+ `;
+ return rows as unknown as StaleTakeRow[];
+ }
+
+export async function updateTake(
+ deps: PgTakesDeps,
+ pageId: number,
+ rowNum: number,
+ fields: { weight?: number; since_date?: string; source?: string },
+ ): Promise<void> {
+ const sql = deps.sql;
+ let weight = fields.weight;
+ if (weight !== undefined) {
+ const norm = normalizeWeightForStorage(weight);
+ if (norm.clamped) {
+ process.stderr.write(`[takes] TAKES_WEIGHT_CLAMPED: updateTake clamped weight ${weight} → ${norm.weight}\n`);
+ }
+ weight = norm.weight;
+ }
+ const result = await sql`
+ UPDATE takes SET
+ weight = COALESCE(${weight ?? null}::real, weight),
+ since_date = COALESCE(${fields.since_date ?? null}::text, since_date),
+ source = COALESCE(${fields.source ?? null}::text, source),
+ updated_at = now()
+ WHERE page_id = ${pageId} AND row_num = ${rowNum}
+ RETURNING 1
+ `;
+ if (result.length === 0) {
+ throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${rowNum}`, 'list takes for this page with `gbrain takes <slug>` to see valid row numbers');
+ }
+ }
+
+export async function supersedeTake(
+ deps: PgTakesDeps,
+ pageId: number,
+ oldRow: number,
+ newRow: Omit<TakeBatchInput, 'page_id' | 'row_num' | 'superseded_by'>,
+ ): Promise<{ oldRow: number; newRow: number }> {
+ const conn = deps.sql;
+ return await conn.begin(async (tx) => {
+ const [existing] = await tx`
+ SELECT resolved_at FROM takes WHERE page_id = ${pageId} AND row_num = ${oldRow}
+ `;
+ if (!existing) throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${oldRow}`, 'list takes with `gbrain takes <slug>`');
+ if ((existing as { resolved_at?: unknown }).resolved_at) {
+ throw new GBrainError('TAKE_RESOLVED_IMMUTABLE', `take ${pageId}#${oldRow} is resolved`, 'resolved bets are immutable; add a new take instead');
+ }
+ const [maxRow] = await tx`SELECT COALESCE(MAX(row_num), 0) + 1 AS next FROM takes WHERE page_id = ${pageId}`;
+ const newRowNum = Number((maxRow as { next?: number })?.next ?? 1);
+ const wClamped = Math.max(0, Math.min(1, newRow.weight ?? 0.5));
+ await tx`
+ INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, active)
+ VALUES (${pageId}, ${newRowNum}, ${newRow.claim}, ${newRow.kind}, ${newRow.holder}, ${wClamped},
+ ${newRow.since_date ?? null}::text, ${newRow.until_date ?? null}::text,
+ ${newRow.source ?? null}, ${newRow.active ?? true})
+ `;
+ await tx`
+ UPDATE takes SET active = false, superseded_by = ${newRowNum}, updated_at = now()
+ WHERE page_id = ${pageId} AND row_num = ${oldRow}
+ `;
+ return { oldRow, newRow: newRowNum };
+ }) as { oldRow: number; newRow: number };
+ }
+
+export async function resolveTake(deps: PgTakesDeps, pageId: number, rowNum: number, resolution: TakeResolution): Promise<void> {
+ const sql = deps.sql;
+ const [existing] = await sql`SELECT resolved_at FROM takes WHERE page_id = ${pageId} AND row_num = ${rowNum}`;
+ if (!existing) throw new GBrainError('TAKE_ROW_NOT_FOUND', `take not found at page_id=${pageId} row=${rowNum}`, 'list takes for this page with `gbrain takes <slug>` to see valid row numbers');
+ if ((existing as { resolved_at?: unknown }).resolved_at) {
+ throw new GBrainError('TAKE_ALREADY_RESOLVED', `take ${pageId}#${rowNum} already resolved`, 'resolution is immutable; add a new take to record a new outcome');
+ }
+ // v0.30.0: derive (quality, outcome) tuple. quality wins when both set.
+ // Schema CHECK enforces consistency as a defense-in-depth backstop.
+ const { quality, outcome } = deriveResolutionTuple(resolution);
+ await sql`
+ UPDATE takes SET
+ resolved_at = now(),
+ resolved_quality = ${quality}::text,
+ resolved_outcome = ${outcome},
+ resolved_value = ${resolution.value ?? null}::real,
+ resolved_unit = ${resolution.unit ?? null}::text,
+ resolved_source = ${resolution.source ?? null}::text,
+ resolved_by = ${resolution.resolvedBy},
+ updated_at = now()
+ WHERE page_id = ${pageId} AND row_num = ${rowNum}
+ `;
+ }
+
+ /**
+ * v0.30.0: aggregate scorecard. SQL-level allow-list filter (D4 fail-closed).
+ * Hidden-holder rows contribute zero to aggregates. NULL allowList means
+ * trusted caller (no filtering). Empty array → zero results.
+ */
+export async function getScorecard(deps: PgTakesDeps, opts: TakesScorecardOpts, allowList: string[] | undefined): Promise<TakesScorecard> {
+ const sql = deps.sql;
+ const allowed = allowList ? sql`AND holder = ANY(${allowList}::text[])` : sql``;
+ const holderClause = opts.holder ? sql`AND holder = ${opts.holder}` : sql``;
+ const domainClause = opts.domainPrefix
+ ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.slug LIKE ${opts.domainPrefix + '%'})`
+ : sql``;
+ const sinceClause = opts.since ? sql`AND since_date >= ${opts.since}` : sql``;
+ const untilClause = opts.until ? sql`AND since_date <= ${opts.until}` : sql``;
+ // #2200-class: takes carry no source_id; scope via the take's page via EXISTS
+ // (this query has no pages JOIN). Array wins over scalar (sourceScopeOpts shape).
+ const sourceFilter =
+ opts.sourceIds && opts.sourceIds.length > 0
+ ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY(${opts.sourceIds}::text[]))`
+ : opts.sourceId
+ ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ${opts.sourceId})`
+ : sql``;
+ // v0.36.1.1 T1c: `resolved` deliberately filters to the 3-state subset
+ // (correct|incorrect|partial) — NOT `resolved_quality IS NOT NULL` — so
+ // historical comparisons against pre-v74 scorecards stay valid.
+ // `unresolvable_count` is a sibling field counting the new 4th state.
+ const rows = await sql`
+ SELECT
+ COUNT(*) FILTER (WHERE kind = 'bet')::int AS total_bets,
+ COUNT(*) FILTER (WHERE resolved_quality IN ('correct','incorrect','partial'))::int AS resolved,
+ COUNT(*) FILTER (WHERE resolved_quality = 'correct')::int AS correct,
+ COUNT(*) FILTER (WHERE resolved_quality = 'incorrect')::int AS incorrect,
+ COUNT(*) FILTER (WHERE resolved_quality = 'partial')::int AS partial,
+ COUNT(*) FILTER (WHERE resolved_quality = 'unresolvable')::int AS unresolvable_count,
+ AVG(
+ CASE WHEN resolved_quality IN ('correct','incorrect')
+ THEN POWER(weight - (CASE resolved_quality WHEN 'correct' THEN 1 ELSE 0 END), 2)
+ END
+ )::float AS brier
+ FROM takes
+ WHERE 1=1 ${holderClause} ${domainClause} ${sinceClause} ${untilClause} ${allowed} ${sourceFilter}
+ `;
+ 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);
+ }
+
+ /**
+ * v0.30.0: calibration curve. Bins resolved correct/incorrect bets by stated
+ * weight. Same allow-list contract as getScorecard.
+ *
+ * Real-Postgres-via-postgres.js sends scalar params as text by default, so
+ * `${bucketSize}` arrives as the string `'0.1'`. Without explicit `::float`
+ * casts the FLOOR/LEAST/multiplication contexts try to coerce text to int
+ * and bomb with `invalid input syntax for type integer: "0.1"`. PGLite is
+ * more permissive — caught at e2e parity by takes-scorecard-parity.test.ts.
+ */
+export async function getCalibrationCurve(deps: PgTakesDeps, opts: CalibrationCurveOpts, allowList: string[] | undefined): Promise<CalibrationBucket[]> {
+ const sql = deps.sql;
+ const bucketSize = opts.bucketSize && opts.bucketSize > 0 && opts.bucketSize <= 1 ? opts.bucketSize : 0.1;
+ const maxIdx = Math.floor(1 / bucketSize) - 1;
+ const allowed = allowList ? sql`AND holder = ANY(${allowList}::text[])` : sql``;
+ const holderClause = opts.holder ? sql`AND holder = ${opts.holder}` : sql``;
+ const sourceFilter =
+ opts.sourceIds && opts.sourceIds.length > 0
+ ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY(${opts.sourceIds}::text[]))`
+ : opts.sourceId
+ ? sql`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ${opts.sourceId})`
+ : sql``;
+ // Bucketing uses NUMERIC for exact decimal arithmetic. Going through
+ // FLOAT introduces IEEE 754 rounding (e.g. 0.7/0.1 = 6.9999..., FLOOR=6
+ // instead of the expected 7), which makes Postgres and PGLite diverge
+ // at bucket boundaries. NUMERIC is exact, so the bucket index is
+ // engine-agnostic and the parity test holds.
+ const rows = await sql`
+ WITH binned AS (
+ SELECT
+ LEAST(FLOOR(weight::numeric / ${bucketSize}::numeric)::int, ${maxIdx}::int)::int AS bucket_idx,
+ weight,
+ (resolved_quality = 'correct')::int AS hit
+ FROM takes
+ WHERE resolved_quality IN ('correct','incorrect')
+ ${holderClause} ${allowed} ${sourceFilter}
+ )
+ SELECT
+ (bucket_idx::numeric * ${bucketSize}::numeric)::float AS bucket_lo,
+ ((bucket_idx + 1)::numeric * ${bucketSize}::numeric)::float AS bucket_hi,
+ COUNT(*)::int AS n,
+ AVG(hit)::float AS observed,
+ AVG(weight)::float AS predicted
+ FROM binned
+ GROUP BY bucket_idx
+ ORDER BY bucket_idx
+ `;
+ return (rows as unknown as { bucket_lo: number; bucket_hi: number; n: number; observed: number | null; predicted: number | null }[]).map(r => ({
+ bucket_lo: r.bucket_lo,
+ bucket_hi: r.bucket_hi,
+ n: r.n,
+ observed: r.n > 0 ? r.observed : null,
+ predicted: r.n > 0 ? r.predicted : null,
+ }));
+ }
+
+export async function addSynthesisEvidence(deps: PgTakesDeps, rowsIn: SynthesisEvidenceInput[]): Promise<number> {
+ if (rowsIn.length === 0) return 0;
+ const sql = deps.sql;
+ const synthesisIds = rowsIn.map(r => r.synthesis_page_id);
+ const takePageIds = rowsIn.map(r => r.take_page_id);
+ const takeRowNums = rowsIn.map(r => r.take_row_num);
+ const citationIxs = rowsIn.map(r => r.citation_index);
+ const result = await sql`
+ INSERT INTO synthesis_evidence (synthesis_page_id, take_page_id, take_row_num, citation_index)
+ SELECT v.synthesis_page_id::int, v.take_page_id::int, v.take_row_num::int, v.citation_index::int
+ FROM unnest(
+ ${synthesisIds}::int[], ${takePageIds}::int[], ${takeRowNums}::int[], ${citationIxs}::int[]
+ ) AS v(synthesis_page_id, take_page_id, take_row_num, citation_index)
+ ON CONFLICT (synthesis_page_id, take_page_id, take_row_num) DO NOTHING
+ RETURNING 1
+ `;
+ return result.length;
+ }
diff --git a/src/core/sync-anchor.ts b/src/core/sync-anchor.ts
new file mode 100644
index 0000000000..db1e721e9c
--- /dev/null
+++ b/src/core/sync-anchor.ts
@@ -0,0 +1,193 @@
+/**
+ * Sync anchor + chunker-version state helpers (source-scoped vs legacy
+ * global-config storage). Peeled out of src/commands/sync.ts (containment
+ * sprint C13-C14) as a pure move.
+ */
+import { realpathSync } from 'fs';
+import type { BrainEngine } from './engine.ts';
+import type { SyncOpts } from '../commands/sync.ts';
+import { ownsGlobalSyncAnchor } from './sync.ts';
+import { serr } from './console-prefix.ts';
+
+// v0.18.0 Step 5: source-scoped sync state helpers. When opts.sourceId
+// is set, read/write the per-source row instead of the global config
+// keys. These wrappers centralize the branch so every read/write site
+// picks the right storage — future Step 5 work (failure-tracking per
+// source) hooks here too.
+export async function readSyncAnchor(
+ engine: BrainEngine,
+ sourceId: string | undefined,
+ which: 'repo_path' | 'last_commit',
+): Promise<string | null> {
+ if (sourceId) {
+ const col = which === 'repo_path' ? 'local_path' : 'last_commit';
+ const rows = await engine.executeRaw<Record<string, string | null>>(
+ `SELECT ${col} AS value FROM sources WHERE id = $1`,
+ [sourceId],
+ );
+ return rows[0]?.value ?? null;
+ }
+ return await engine.getConfig(`sync.${which}`);
+}
+
+/**
+ * #2964: is `repoPath` gbrain's own default-brain anchor, as opposed to a
+ * path some caller merely happened to pass through unchanged?
+ *
+ * `!opts.sourceId` alone is NOT sufficient — and neither is rejecting
+ * `opts.sourceId` outright: migration `sources_table_additive` (v20)
+ * seeds a `'default'` source row whose `local_path` is copied FROM
+ * `config.sync.repo_path` on every brain that has ever run it (i.e.
+ * effectively all of them by now), and `writeSyncAnchor` keeps that row's
+ * `local_path` current on every sync thereafter. So on a real installed
+ * brain, `resolveSourceForDir` (dream cycle) and the CLI's bare `gbrain
+ * sync` both resolve `sourceId: 'default'`, NOT `undefined` — rejecting
+ * all non-empty `sourceId` (an earlier, insufficiently-reviewed version
+ * of this check) made self-heal never fire on that real path either,
+ * masked in tests only because a freshly-`initSchema()`'d test brain's
+ * `'default'` row has a null `local_path` (Codex review round 5).
+ *
+ * The actual boundary: `'default'` is gbrain's own bootstrap identity,
+ * not something a caller names — a DIFFERENT, non-default `sourceId` is
+ * what an explicit `sources add <id> --path <dir>` registration (a
+ * user's own external directory) looks like, and that's what must keep
+ * failing loudly. So: permit `sourceId` when it's exactly `undefined` or
+ * `'default'`, reject any other id, and for BOTH permitted cases prove
+ * ownership by VALUE — reread the live anchor for that same identity
+ * (`sources.default.local_path` when sourceId='default', else
+ * `config.sync.repo_path`) and require the resolved `repoPath` to
+ * REALPATH-equal it (not raw string equality: `dream`'s `resolveBrainDir`
+ * normalizes via `path.resolve`, so a trailing slash or `..` in the
+ * stored anchor must not defeat the match — Codex review round 5, P2).
+ * An arbitrary caller-supplied path (e.g. an admin-scope
+ * `submit_job({name:'sync', data:{repoPath}})`) only passes this check
+ * if it already equals gbrain's own anchor by realpath identity — at
+ * which point self-healing it is exactly the legitimate case, not an
+ * escalation.
+ *
+ * `opts.srcSubpath` disqualifies unconditionally: a subpath-scoped sync
+ * only wants THAT subdirectory captured, but the self-heal baseline
+ * commit runs `git add -A` at the git root (there's no file list yet to
+ * scope it to — collection happens after this point) — see the P2 review
+ * finding on `createSyncBaselineCommit`'s callers.
+ */
+export async function isAnchorOwnedSyncPath(
+ engine: BrainEngine,
+ opts: SyncOpts,
+ repoPath: string,
+): Promise<boolean> {
+ if (opts.srcSubpath) return false;
+ if (opts.sourceId && opts.sourceId !== 'default') return false;
+ const anchor = await readSyncAnchor(engine, opts.sourceId, 'repo_path');
+ if (anchor === null) return false;
+ try {
+ return realpathSync(anchor) === realpathSync(repoPath);
+ } catch {
+ // Anchor or repoPath doesn't realpath-resolve (dangling/nonexistent) —
+ // can't prove identity, so don't self-heal.
+ return false;
+ }
+}
+
+export async function writeSyncAnchor(
+ engine: BrainEngine,
+ sourceId: string | undefined,
+ which: 'repo_path' | 'last_commit',
+ value: string,
+ // v0.41.32.0 (supersedes #1623): on `last_commit` advances, also stamp the
+ // durable newest-COMMIT timestamp (HEAD committer time, epoch ms) in the SAME
+ // atomic UPDATE as last_sync_at — no separate write to leave partial state,
+ // no clock-domain split (last_sync_at = DB now(); newest_content_at = the
+ // git-intrinsic committer time of the HEAD we just synced). `undefined` keeps
+ // the legacy 2-column write; `null` clears the column (git unavailable).
+ newestContentEpochMs?: number | null,
+ // #2114: the repo dir this anchor write is FOR. Required to guard the
+ // legacy branch's `last_commit` writes (where `value` is a hash, not a
+ // dir). `repo_path` writes self-describe via `value`. Callers that omit
+ // it on a legacy-path last_commit write keep pre-#2114 behavior.
+ repoDir?: string,
+): Promise<void> {
+ if (sourceId) {
+ const col = which === 'repo_path' ? 'local_path' : 'last_commit';
+ // last_sync_at bookmarked on every last_commit advance.
+ if (which === 'last_commit') {
+ if (newestContentEpochMs !== undefined) {
+ const iso = newestContentEpochMs === null
+ ? null
+ : new Date(newestContentEpochMs).toISOString();
+ await engine.executeRaw(
+ `UPDATE sources SET last_commit = $1, last_sync_at = now(), newest_content_at = $3 WHERE id = $2`,
+ [value, sourceId, iso],
+ );
+ } else {
+ await engine.executeRaw(
+ `UPDATE sources SET last_commit = $1, last_sync_at = now() WHERE id = $2`,
+ [value, sourceId],
+ );
+ }
+ } else {
+ await engine.executeRaw(
+ `UPDATE sources SET ${col} = $1 WHERE id = $2`,
+ [value, sourceId],
+ );
+ }
+ return;
+ }
+ // Legacy no-sourceId path (pre-v0.18 global config; also reached when a
+ // caller could not resolve a source for the dir — dream --dir on an
+ // unregistered directory, minion sync with an unmatched repoPath). #2114:
+ // these globals describe THE brain repo, and this branch used to write
+ // them unconditionally — a full-sync fallback against a foreign directory
+ // silently repointed put_page write-through and poisoned the incremental
+ // anchor. Refuse to move them for a directory that isn't the brain repo.
+ const anchorDir = which === 'repo_path' ? value : repoDir;
+ if (anchorDir !== undefined) {
+ const { owns, configured } = await ownsGlobalSyncAnchor(engine, undefined, anchorDir);
+ if (!owns) {
+ serr(
+ `[sync] sync.${which} stays at ${configured ?? '(unset)'} — not moving the ` +
+ `global anchor for "${anchorDir}". To make that directory the brain repo: ` +
+ `gbrain config set sync.repo_path "${anchorDir}"`,
+ );
+ return;
+ }
+ }
+ await engine.setConfig(`sync.${which}`, value);
+}
+
+/**
+ * v0.20.0 Cathedral II Layer 12 (SP-1 fix) — read/write the chunker version
+ * last used to sync a given source. When it mismatches CURRENT_CHUNKER_VERSION,
+ * `performSync` forces a full walk regardless of git HEAD equality. Without
+ * this gate, bumping CHUNKER_VERSION does NOTHING on an unchanged repo
+ * because sync short-circuits at `up_to_date` before reaching
+ * `importCodeFile`'s content_hash check.
+ *
+ * Per-source storage matches writeSyncAnchor's shape — sources.chunker_version
+ * TEXT column from the v27 migration. No global fallback: non-source syncs
+ * (pre-v0.17 brains with no sources table) never had CHUNKER_VERSION
+ * version-gating, so they keep the v0.19.0 behavior.
+ */
+export async function readChunkerVersion(
+ engine: BrainEngine,
+ sourceId: string | undefined,
+): Promise<string | null> {
+ if (!sourceId) return null;
+ const rows = await engine.executeRaw<{ chunker_version: string | null }>(
+ `SELECT chunker_version FROM sources WHERE id = $1`,
+ [sourceId],
+ );
+ return rows[0]?.chunker_version ?? null;
+}
+
+export async function writeChunkerVersion(
+ engine: BrainEngine,
+ sourceId: string | undefined,
+ version: string,
+): Promise<void> {
+ if (!sourceId) return;
+ await engine.executeRaw(
+ `UPDATE sources SET chunker_version = $1 WHERE id = $2`,
+ [version, sourceId],
+ );
+}
diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.ts
new file mode 100644
index 0000000000..1a3c3e0c9b
--- /dev/null
+++ b/src/core/sync-cost-gate.ts
@@ -0,0 +1,538 @@
+/**
+ * Inline-embed cost gate + token estimation for `gbrain sync` (#2139).
+ * Peeled out of src/commands/sync.ts (containment sprint C13-C14) as a pure
+ * move — see that file for the command surface that drives this gate.
+ */
+import { readFileSync, statSync } from 'fs';
+import { join } from 'path';
+import { createInterface } from 'readline';
+import type { BrainEngine } from './engine.ts';
+import { collectSyncableFiles } from '../commands/import.ts';
+import { isSyncable } from './sync.ts';
+// v0.42.42.0 (#2139): `buildDetachedWorkingTreeManifest` relocated to
+// `src/core/sync-delta.ts` (re-imported below) so the inline cost estimator
+// prices detached sources through the same code the executor imports them with.
+import {
+ computeSyncDelta,
+ buildDetachedWorkingTreeManifest,
+} from './sync-delta.ts';
+import { fetchRemote } from './git-remote.ts';
+import {
+ parseUsdLimit,
+ formatUsdLimit,
+ resolveSpendPosture,
+} from './spend-posture.ts';
+import { estimateTokens, CHUNKER_VERSION } from './chunkers/code.ts';
+import {
+ estimateEmbeddingCostUsd,
+ getEmbeddingModelName,
+ currentEmbeddingPricePerMTok,
+ currentEmbeddingSignature,
+ shouldBlockSync,
+ type SyncEmbedMode,
+} from './embedding.ts';
+import { estimateCostFromChars } from './embedding-pricing.ts';
+import { SPEND_CAP_CONFIG_KEY } from './embed-backfill-submit.ts';
+import { git, hasOriginRemote, isDetachedHead, unique } from './sync-git.ts';
+
+/**
+ * Walk ONE source's working tree and sum tokens for every syncable file.
+ * Conservative full-tree CEILING (full file content, not the incremental
+ * diff) — over-counts, never under-counts. Used only on the ceiling rungs of
+ * `estimateInlineNewTokens` (first sync, chunker drift, git-unavailable),
+ * where the delta is genuinely the whole tree or can't be computed.
+ *
+ * v0.31.2: routed through collectSyncableFiles (lstat + inode-cycle +
+ * max-depth) so the preview walks exactly what the real sync walks.
+ *
+ * Exported (v0.42.42.0, #2139) for direct unit testing.
+ */
+export function estimateSourceTreeTokens(
+ localPath: string,
+ strategy: 'markdown' | 'code' | 'auto',
+ opts: { includeGitignored?: boolean } = {},
+): { tokens: number; files: number } {
+ let tokens = 0;
+ let files = 0;
+ try {
+ const fileList = collectSyncableFiles(localPath, { strategy, includeGitignored: opts.includeGitignored });
+ for (const fullPath of fileList) {
+ try {
+ const stat = statSync(fullPath);
+ if (stat.size > 5_000_000) continue; // skip large binaries
+ const content = readFileSync(fullPath, 'utf-8');
+ tokens += estimateTokens(content);
+ files++;
+ } catch {
+ // Best-effort per file; sync itself tolerates the same.
+ }
+ }
+ } catch {
+ // Best-effort: a source whose local_path is gone/unreadable contributes 0.
+ }
+ return { tokens, files };
+}
+
+/** Sum tokens for an explicit set of repo-relative paths read at live working-tree content. */
+function estimateDeltaTokens(localPath: string, relPaths: string[]): number {
+ let tokens = 0;
+ for (const rel of relPaths) {
+ try {
+ const full = join(localPath, rel);
+ const stat = statSync(full);
+ if (stat.size > 5_000_000) continue; // skip large binaries (matches tree walk)
+ tokens += estimateTokens(readFileSync(full, 'utf-8'));
+ } catch {
+ // Listed in the diff but unreadable (e.g. since deleted) → 0, like the tree walk.
+ }
+ }
+ return tokens;
+}
+
+/**
+ * v0.42.42.0 (#2139): resolve the commit the estimate should diff AGAINST.
+ *
+ * The cost gate runs BEFORE sync's own `git pull`, so a stale local HEAD would
+ * make the estimate blind to commits the run is about to pull (codex #1). So
+ * we FETCH first (fail-open) and target `origin/<branch>` — the estimate then
+ * prices exactly what this run will sync. The subsequent pull fast-forwards
+ * the already-fetched objects, so net new network cost ≈ 0.
+ *
+ * - detached HEAD → no upstream; target = local HEAD (+ caller merges the
+ * detached working-tree manifest, which sync imports on a detached repo).
+ * - attached + origin remote → fetch origin/<branch> (best-effort), target =
+ * origin/<branch> if resolvable, else local HEAD (offline / no upstream).
+ * - HEAD unresolvable (not a git repo) → null (caller treats as unavailable).
+ *
+ * NOTE: this makes `--dry-run` perform a network fetch so the preview reflects
+ * what a real run would pull. Fail-open: offline dry-run still previews against
+ * local HEAD. Uses the shared `git()` 30s budget (the fetch cost is the pull
+ * cost paid a few seconds early — a tighter cap would frequently fall back to
+ * local HEAD and underestimate the remote delta).
+ */
+function resolveEstimateTarget(localPath: string): { target: string; detached: boolean } | null {
+ let head: string;
+ try {
+ head = git(localPath, ['rev-parse', 'HEAD']);
+ } catch {
+ return null;
+ }
+ const detached = isDetachedHead(localPath);
+ if (detached) return { target: head, detached: true };
+
+ let branch: string | null = null;
+ try {
+ branch = git(localPath, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() || null;
+ } catch {
+ branch = null;
+ }
+ if (branch && branch !== 'HEAD' && hasOriginRemote(localPath)) {
+ try {
+ // v0.42.42.0 (#2139): route through the SSRF-hardened fetch (same flags +
+ // no-prompt env as pullRepo) — a cost preview / dry-run must NOT hit a
+ // remote through a less-protected path than real sync.
+ fetchRemote(localPath, branch, { timeoutMs: 30_000 });
+ } catch {
+ // fail-open: offline, auth failure, no upstream — fall through to local HEAD.
+ }
+ try {
+ const remoteSha = git(localPath, ['rev-parse', `origin/${branch}`]);
+ if (remoteSha) return { target: remoteSha, detached: false };
+ } catch {
+ // no remote-tracking ref for this branch — use local HEAD.
+ }
+ }
+ return { target: head, detached: false };
+}
+
+export type EstimateKind = 'delta' | 'ceiling' | 'mixed' | 'unchanged';
+
+export interface InlineEstimate {
+ tokens: number;
+ changedSources: number;
+ unchangedSources: number;
+ estimateKind: EstimateKind;
+ /** Per-source ceiling reasons (chunker_drift / first_sync / git_unavailable) for honest labeling. */
+ ceilingReasons: string[];
+}
+
+/**
+ * v0.42.42.0 (#2139) — INLINE-path new-content estimate. The estimate now
+ * MIRRORS EXECUTION instead of pricing the whole tree on every dirty sync (the
+ * 400x overestimate that wedged the daily cron). Per-source fail-open ladder:
+ *
+ * 1. syncEnabled === false → skip (unchanged)
+ * 2. chunker drift (stored !== current) → full-tree CEILING (a drift forces
+ * performFullSync → full re-chunk → full re-embed; a delta would
+ * underestimate by the whole corpus). kind: ceiling_chunker_drift
+ * 3. last_commit === fetch target → 0 (mirrors `up_to_date` at
+ * sync.ts:1402 — NO clean-working-tree requirement; a dirty tree whose
+ * commits are caught up imports nothing). kind: unchanged
+ * 4. last_commit === null (first sync) → full-tree CEILING. kind: ceiling_first_sync
+ * 5. computeSyncDelta ok → price added∪modified∪renamed.to
+ * (syncable, live working-tree content); deletes cost 0. kind: delta
+ * 6. computeSyncDelta unavailable → full-tree CEILING. kind: ceiling_git_unavailable
+ *
+ * The delta rung routes through the SAME `computeSyncDelta` the executor uses
+ * (src/core/sync-delta.ts), so the gate's dollar figure can't drift from what
+ * the sync imports. `--full`'s extra stale-backlog sweep is added by the gate
+ * (it already has `staleCostUsd`), not here — see the call site.
+ *
+ * Exported for direct unit testing.
+ */
+export function estimateInlineNewTokens(
+ sources: Array<{
+ local_path: string | null;
+ config: Record<string, unknown>;
+ last_commit: string | null;
+ chunker_version: string | null;
+ }>,
+ currentChunkerVersion: string,
+ opts: { forceFullTree?: boolean } = {},
+): InlineEstimate {
+ let tokens = 0;
+ let changedSources = 0;
+ let unchangedSources = 0;
+ let hadDelta = false;
+ let hadCeiling = false;
+ const ceilingReasons: string[] = [];
+
+ const ceiling = (localPath: string, strategy: 'markdown' | 'code' | 'auto', reason: string) => {
+ tokens += estimateSourceTreeTokens(localPath, strategy).tokens;
+ changedSources++;
+ hadCeiling = true;
+ ceilingReasons.push(reason);
+ };
+
+ for (const src of sources) {
+ if (!src.local_path) continue;
+ const cfg = (src.config || {}) as { syncEnabled?: boolean; strategy?: 'markdown' | 'code' | 'auto' };
+ if (cfg.syncEnabled === false) continue;
+ const strategy = cfg.strategy ?? 'markdown';
+ const localPath = src.local_path;
+
+ if (opts.forceFullTree) {
+ tokens += estimateSourceTreeTokens(localPath, strategy, { includeGitignored: true }).tokens;
+ changedSources++;
+ hadCeiling = true;
+ ceilingReasons.push('include_gitignored');
+ continue;
+ }
+
+ // Rung 2: chunker drift forces a full re-chunk → full re-embed. CEILING.
+ if (src.chunker_version !== currentChunkerVersion) {
+ ceiling(localPath, strategy, 'chunker_drift');
+ continue;
+ }
+
+ // Rung 4 (early): no bookmark → first sync imports everything. CEILING.
+ if (!src.last_commit) {
+ ceiling(localPath, strategy, 'first_sync');
+ continue;
+ }
+
+ const resolved = resolveEstimateTarget(localPath);
+ if (!resolved) {
+ // HEAD unresolvable (not a git repo / gone) — can't compute a delta. CEILING.
+ ceiling(localPath, strategy, 'git_unavailable');
+ continue;
+ }
+
+ // Rung 3: caught up to the fetch target AND no detached working-tree changes.
+ // Mirrors the executor's `up_to_date` predicate — a dirty-but-committed-current
+ // tree imports nothing, so it must price $0 (the heart of the false-fire fix).
+ const detachedManifest = resolved.detached
+ ? buildDetachedWorkingTreeManifest(localPath)
+ : null;
+ const detachedHasChanges = detachedManifest !== null &&
+ (detachedManifest.added.length > 0 ||
+ detachedManifest.modified.length > 0 ||
+ detachedManifest.deleted.length > 0 ||
+ detachedManifest.renamed.length > 0);
+ if (src.last_commit === resolved.target && !detachedHasChanges) {
+ unchangedSources++;
+ continue;
+ }
+
+ // Rung 5/6: the delta itself — SAME helper the executor diffs with.
+ const delta = computeSyncDelta(localPath, src.last_commit, resolved.target, {
+ detachedManifest,
+ });
+ if (delta.status === 'unavailable') {
+ ceiling(localPath, strategy, 'git_unavailable');
+ continue;
+ }
+ const syncOpts = { strategy };
+ const changedPaths = unique([
+ ...delta.manifest.added.filter(p => isSyncable(p, syncOpts)),
+ ...delta.manifest.modified.filter(p => isSyncable(p, syncOpts)),
+ ...delta.manifest.renamed.filter(r => isSyncable(r.to, syncOpts)).map(r => r.to),
+ ]);
+ tokens += estimateDeltaTokens(localPath, changedPaths);
+ changedSources++;
+ hadDelta = true;
+ }
+
+ const estimateKind: EstimateKind =
+ hadCeiling && hadDelta ? 'mixed' : hadCeiling ? 'ceiling' : hadDelta ? 'delta' : 'unchanged';
+ return { tokens, changedSources, unchangedSources, estimateKind, ceilingReasons };
+}
+
+/**
+ * Resolve the inline-path cost-gate floor in USD. Config key
+ * `sync.cost_gate_min_usd` (DB plane), default $0.50. Below this estimate
+ * the inline gate proceeds without blocking. Fail-open to the default on a
+ * missing/invalid value or a config-read error (the gate must never crash
+ * the sync). Accepts 0 (an operator can set the floor to $0 to make the
+ * gate block on any nonzero inline cost).
+ */
+async function resolveCostGateFloorUsd(engine: BrainEngine): Promise<number> {
+ try {
+ const raw = await engine.getConfig('sync.cost_gate_min_usd');
+ // v0.42.42.0 (#2139): `0` keeps meaning "block on any nonzero spend"
+ // (allowZero); `off`/`unlimited`/`none` → Infinity so the gate never
+ // blocks (`costUsd > Infinity` is always false).
+ return parseUsdLimit(raw, 0.5, { allowZero: true });
+ } catch {
+ return 0.5;
+ }
+}
+
+/**
+ * Resolve the per-source embed-backfill 24h spend cap (USD) for the deferred
+ * notice. Mirrors embed-backfill-submit.ts's own resolution of
+ * SPEND_CAP_CONFIG_KEY (default 25). Fail-open to the default.
+ */
+async function resolveBackfillCapUsd(engine: BrainEngine): Promise<number> {
+ try {
+ const raw = await engine.getConfig(SPEND_CAP_CONFIG_KEY);
+ // v0.42.42.0 (#2139): no allowZero — `0` falls back to the default
+ // (off semantics ≠ 0); `off`/`unlimited`/`none` → Infinity (cap disabled).
+ return parseUsdLimit(raw, 25);
+ } catch {
+ return 25;
+ }
+}
+
+/** Interactive [y/N] prompt. Resolves false on non-y answers or EOF. */
+async function promptYesNo(question: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
+ rl.question(question, (answer) => {
+ rl.close();
+ resolve(answer.trim().toLowerCase() === 'y' || answer.trim().toLowerCase() === 'yes');
+ });
+ rl.on('close', () => resolve(false));
+ });
+}
+
+// v0.42.42.0 (#2139): paste-ready knobs appended to every gate message so the
+// spend-control surface is discoverable at the moment of need (humans + agents),
+// not only after reading source. Closes the issue's "takes archaeology" complaint.
+const SPEND_HINT =
+ 'widen: gbrain config set sync.cost_gate_min_usd 5 | ' +
+ 'never gate: gbrain config set spend.posture tokenmax | ' +
+ 'docs: docs/operations/spend-controls.md';
+
+/** Honest token label — delta vs full-tree ceiling, with the ceiling reasons. */
+function labelEstimate(inline: InlineEstimate): string {
+ if (inline.estimateKind === 'unchanged') return '0 new tokens (sources caught up)';
+ if (inline.estimateKind === 'delta') {
+ return `~${inline.tokens.toLocaleString()} new tokens (delta: changed files since last sync)`;
+ }
+ // ceiling | mixed — be explicit that this is an over-count, not the real spend.
+ const reasons = unique(inline.ceilingReasons).join(', ') || 'unknown';
+ return (
+ `<=${inline.tokens.toLocaleString()} tokens (full-tree ceiling for ${inline.changedSources} ` +
+ `source(s): ${reasons} — unchanged files skip via content_hash at execution)`
+ );
+}
+
+type CostGateSource = {
+ local_path: string | null;
+ config: Record<string, unknown>;
+ last_commit: string | null;
+ chunker_version: string | null;
+};
+
+interface CostGateContext {
+ sources: CostGateSource[];
+ /** Resolved embed mode. Single-source is always 'inline' (not the parallel-deferred fan-out). */
+ mode: SyncEmbedMode;
+ dryRun: boolean;
+ jsonOut: boolean;
+ yesFlag: boolean;
+ full: boolean;
+ includeGitignored?: boolean;
+ /** Message prefix ('sync --all' | 'sync'). */
+ label: string;
+}
+
+type CostGateOutcome =
+ | { action: 'proceed'; autoDeferEmbeds: boolean }
+ | { action: 'stop' };
+
+/**
+ * v0.42.42.0 (#2139): the inline-embed cost gate, shared by BOTH `sync --all`
+ * and single-source `sync` so the spend surface is consistent. Runs at the
+ * COMMAND layer (never inside performSync, which `runOne` also calls — that
+ * would double-gate `--all`).
+ *
+ * Behavior:
+ * - deferred mode → FYI only, never blocks (backfill cap is the money gate).
+ * - inline + below floor → proceed quietly.
+ * - inline + spend.posture=tokenmax → informational, proceed inline.
+ * - inline + above floor + TTY → [y/N] prompt.
+ * - inline + above floor + non-TTY/--json → AUTO-DEFER embeds to capped
+ * backfill jobs, exit 0 (NEVER exit 2 — the wedged-cron fix). Caller sets
+ * effectiveNoEmbed and enqueues the backfill.
+ *
+ * Output format splits on the EXPLICIT `--json` flag only (absorbs the
+ * TODOS.md:340 #1784 conflation): JSON envelope iff `--json`, else human text.
+ */
+export async function runInlineCostGate(
+ engine: BrainEngine,
+ ctx: CostGateContext,
+): Promise<CostGateOutcome> {
+ const { sources, mode, dryRun, jsonOut, yesFlag, full, label } = ctx;
+
+ // Stale backlog: cheap single SQL; fail-open to 0 so a transient DB hiccup
+ // never blocks the sync. Signature-aware (model/dims swap surfaces here).
+ let staleChars = 0;
+ try {
+ staleChars = await engine.sumStaleChunkChars({ signature: currentEmbeddingSignature() });
+ } catch {
+ staleChars = 0;
+ }
+ const staleCostUsd = estimateCostFromChars(staleChars, currentEmbeddingPricePerMTok());
+ const embeddingModelName = getEmbeddingModelName();
+ const floorUsd = await resolveCostGateFloorUsd(engine);
+ const posture = await resolveSpendPosture(engine);
+
+ if (mode === 'deferred') {
+ // Deferred path: print an FYI, NEVER block. The backfill cap is the real
+ // money gate.
+ const capUsd = await resolveBackfillCapUsd(engine);
+ let queuedBackfills = 0;
+ try {
+ const r = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM minion_jobs
+ WHERE name = 'embed-backfill'
+ AND status IN ('waiting','active','delayed','waiting-children')`,
+ );
+ queuedBackfills = Number(r[0]?.n) || 0;
+ } catch {
+ queuedBackfills = 0;
+ }
+ const deferredMsg =
+ `${label}: embedding deferred to backfill jobs ` +
+ `(capped $${formatUsdLimit(capUsd)}/source/24h, not charged by this sync). ` +
+ `Current backlog ~${staleChars.toLocaleString()} chars (~$${staleCostUsd.toFixed(2)} on ` +
+ `${embeddingModelName}) across ${sources.length} source(s); ` +
+ `${queuedBackfills} backfill job(s) queued.`;
+ if (dryRun) {
+ if (jsonOut) {
+ console.log(JSON.stringify({ status: 'dry_run', mode, gate: 'dry_run', staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd), queuedBackfills, model: embeddingModelName }));
+ } else {
+ console.log(deferredMsg);
+ console.log('--dry-run: exit without syncing.');
+ }
+ return { action: 'stop' };
+ }
+ if (jsonOut) {
+ console.log(JSON.stringify({ status: 'deferred', mode, gate: 'deferred_notice', staleChars, staleCostUsd, capUsd: formatUsdLimit(capUsd), floorUsd: formatUsdLimit(floorUsd), queuedBackfills, model: embeddingModelName }));
+ } else {
+ console.log(deferredMsg);
+ }
+ return { action: 'proceed', autoDeferEmbeds: false };
+ }
+
+ // ── Inline path ───────────────────────────────────────────────
+ const inline = estimateInlineNewTokens(sources, String(CHUNKER_VERSION), {
+ forceFullTree: ctx.includeGitignored === true,
+ });
+ // D7A: `--full` runs `performFullSync` → `runEmbedCore({stale:true})`, which
+ // sweeps the pre-existing stale backlog INLINE on top of the delta. Price it.
+ const costUsd = estimateEmbeddingCostUsd(inline.tokens) + (full ? staleCostUsd : 0);
+ const fullNote = full && staleChars > 0
+ ? ` (includes ~${staleChars.toLocaleString()} stale-backlog chars swept by --full)`
+ : '';
+ const staleNote = !full && staleChars > 0
+ ? ` (plus ~${staleChars.toLocaleString()} stale-backlog chars pending \`gbrain embed --stale\`)`
+ : '';
+ const previewMsg =
+ `${label} preview (inline embed): ${inline.changedSources} changed source(s), ` +
+ `${inline.unchangedSources} unchanged; ${labelEstimate(inline)}, ` +
+ `est. $${costUsd.toFixed(2)} on ${embeddingModelName}${fullNote}${staleNote}.`;
+
+ if (dryRun) {
+ if (jsonOut) {
+ console.log(JSON.stringify({ status: 'dry_run', mode, gate: 'dry_run', newTokens: inline.tokens, estimateKind: inline.estimateKind, staleChars, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName }));
+ } else {
+ console.log(previewMsg);
+ console.log('--dry-run: exit without syncing.');
+ }
+ return { action: 'stop' };
+ }
+
+ // --yes bypasses the gate entirely (embed inline, no preview).
+ if (yesFlag) return { action: 'proceed', autoDeferEmbeds: false };
+
+ // spend.posture=tokenmax → informational, proceed INLINE (operator declared
+ // cost isn't the constraint; don't defer).
+ if (posture === 'tokenmax') {
+ if (jsonOut) {
+ console.log(JSON.stringify({ status: 'proceeding', mode, gate: 'posture_tokenmax', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT }));
+ } else {
+ console.log(`${previewMsg} spend.posture=tokenmax: proceeding (informational). ${SPEND_HINT}`);
+ }
+ return { action: 'proceed', autoDeferEmbeds: false };
+ }
+
+ // Link intent: search.mode=tokenmax but spend posture unset → nudge once.
+ let searchModeHint = '';
+ try {
+ const sm = await engine.getConfig('search.mode');
+ if (typeof sm === 'string' && sm.trim().toLowerCase() === 'tokenmax') {
+ searchModeHint =
+ ` (search.mode=tokenmax detected — \`gbrain config set spend.posture tokenmax\` ` +
+ `makes cost gates informational)`;
+ }
+ } catch {
+ /* best-effort */
+ }
+
+ if (shouldBlockSync(costUsd, floorUsd, mode, posture)) {
+ const isTTY = Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY);
+ if (isTTY && !jsonOut) {
+ // Interactive TTY: prompt [y/N].
+ console.log(previewMsg + searchModeHint);
+ const answer = await promptYesNo('Proceed? [y/N] ');
+ if (!answer) {
+ console.log('Cancelled.');
+ return { action: 'stop' };
+ }
+ return { action: 'proceed', autoDeferEmbeds: false };
+ }
+ // Non-TTY or --json: AUTO-DEFER embeds to capped backfill jobs. NEVER exit 2
+ // (the wedged-cron fix). Format splits on the explicit --json flag only.
+ if (jsonOut) {
+ console.log(JSON.stringify({ status: 'auto_deferred', mode, gate: 'auto_deferred_embeds', newTokens: inline.tokens, estimateKind: inline.estimateKind, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName, hint: SPEND_HINT }));
+ } else {
+ console.log(
+ `${previewMsg} Exceeds floor $${formatUsdLimit(floorUsd)} in a non-interactive ` +
+ `session — importing now, deferring embeds to capped backfill jobs. ` +
+ `Drain: run the jobs worker or \`gbrain embed --stale\`. Pass --yes to embed inline.\n${SPEND_HINT}`,
+ );
+ }
+ return { action: 'proceed', autoDeferEmbeds: true };
+ }
+
+ // Below floor → proceed without blocking (kills inline-cron noise).
+ if (jsonOut) {
+ console.log(JSON.stringify({ status: 'below_floor', mode, gate: 'below_floor', newTokens: inline.tokens, estimateKind: inline.estimateKind, staleChars, costUsd, floorUsd: formatUsdLimit(floorUsd), model: embeddingModelName }));
+ } else {
+ console.log(`${previewMsg} Below cost gate floor ($${formatUsdLimit(floorUsd)}), proceeding.`);
+ }
+ return { action: 'proceed', autoDeferEmbeds: false };
+}
diff --git a/src/core/sync-git.ts b/src/core/sync-git.ts
new file mode 100644
index 0000000000..175c82088d
--- /dev/null
+++ b/src/core/sync-git.ts
@@ -0,0 +1,435 @@
+/**
+ * Git plumbing for `gbrain sync`: invocation building, repo discovery,
+ * baseline-commit self-heal, and path-containment guards. Peeled out of
+ * src/commands/sync.ts (containment sprint C13-C14) as a pure move.
+ */
+import { existsSync, readFileSync, realpathSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { isAbsolute, join, relative, sep } from 'path';
+import type { BrainEngine } from './engine.ts';
+import { resolveSlugForPath } from './sync.ts';
+import { loadStorageConfig } from './storage-config.ts';
+
+/**
+ * v0.32.7 CJK wave (codex post-merge F4): resolve a slug by `pages.source_path`
+ * first, falling back to `resolveSlugForPath(path)`.
+ *
+ * Frontmatter-fallback pages (emoji-only / Thai / Arabic / exotic-script
+ * filenames where `slugifyPath` returns empty and the slug came from the
+ * frontmatter) have a slug that ISN'T derivable from the path. Delete and
+ * rename operations that only know the path would otherwise orphan these
+ * pages by trying to delete the path-derived (wrong) slug.
+ *
+ * Returns the actual stored slug when source_path matches a row, or the
+ * path-derived slug when there's no match (normal-case path-derived pages).
+ */
+export async function resolveSlugByPathOrSourcePath(
+ engine: BrainEngine,
+ path: string,
+ sourceId?: string,
+): Promise<string> {
+ // v0.41.19.0 (D8): when sourceId is set, delegate to the new batch
+ // resolveSlugsByPaths so single-call and batched paths share one SQL
+ // owner + one fallback semantic. One Map allocation per single-call;
+ // negligible cost. When sourceId is undefined (legacy unscoped callers),
+ // fall back to the original executeRaw shape — the batch method
+ // requires sourceId to prevent the multi-source-bug-class on its new
+ // surface (D5). The unscoped fallback preserves back-compat.
+ try {
+ if (sourceId) {
+ const m = await engine.resolveSlugsByPaths([path], { sourceId });
+ const slug = m.get(path);
+ if (slug) return slug;
+ } else {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_path = $1 LIMIT 1`,
+ [path],
+ );
+ if (rows.length > 0 && rows[0].slug) return rows[0].slug;
+ }
+ } catch {
+ // Fall through — best-effort. Pre-migration brains or query errors
+ // shouldn't break delete/rename for path-derived pages.
+ }
+ return resolveSlugForPath(path);
+}
+
+/**
+ * git CLI helper.
+ *
+ * `configs` flags are emitted as `-c key=val` pairs BEFORE `-C repoPath` and
+ * BEFORE the subcommand. `core.quotepath=false` is always emitted first so CJK
+ * (and other non-ASCII) paths arrive as UTF-8 in `diff --name-status` and
+ * sibling commands. Callers that need additional git config should pass via
+ * the `configs` parameter; never inline `-c` into `args`.
+ *
+ * Exported for `test/sync.test.ts` invariant assertion only.
+ */
+export function buildGitInvocation(repoPath: string, args: string[], configs: string[] = []): string[] {
+ const cfg = ['core.quotepath=false', ...configs].flatMap(c => ['-c', c]);
+ return [...cfg, '-C', repoPath, ...args];
+}
+
+export function buildAutoEmbedArgs(slugs: string[], sourceId?: string): string[] {
+ return sourceId ? ['--source', sourceId, '--slugs', ...slugs] : ['--slugs', ...slugs];
+}
+
+/**
+ * Resolve sync's effective no-embed mode from CLI args + config.
+ *
+ * The deferred-setup sentinel (`embedding_disabled: true`, written by
+ * `gbrain init --no-embedding`) is an implicit `--no-embed`: without this,
+ * the embed credential preflight demands provider credentials the user
+ * deliberately deferred at init, and every `gbrain sync` on a keyless
+ * brain exits 1. See embed-preflight.ts's skip protocol — the sentinel is
+ * meant to be honored before the credential check ever runs.
+ *
+ * Exported for `test/sync-no-embed-sentinel.test.ts`.
+ */
+export function resolveNoEmbed(
+ args: string[],
+ cfg: { embedding_disabled?: boolean } | null,
+): boolean {
+ return args.includes('--no-embed') || cfg?.embedding_disabled === true;
+}
+
+/**
+ * Shell out to git with a generous maxBuffer.
+ *
+ * Node's default maxBuffer is 1 MiB. `git diff --name-status -M` on a
+ * 60–100K file repo easily exceeds that, causing an ENOBUFS crash that
+ * kills the sync process with no error message in the log.
+ *
+ * 100 MiB is generous but still bounded — a 100K-file diff with long
+ * paths tops out around 10–20 MiB in practice.
+ *
+ * `silenceStderr`: Node's `execFileSync` writes the child's stderr straight
+ * through to the parent's real stderr by default (in addition to attaching
+ * it to the thrown error's `.stderr`) *unless* an explicit `stdio` array is
+ * given. Callers that treat a failure as an expected, self-handled outcome
+ * (rather than a crash to surface) pass `silenceStderr: true` so git's raw
+ * `fatal: ...` line never reaches the process's own stderr — only the
+ * caller's own (usually friendlier) handling of the caught error does.
+ * Default `false` preserves today's passthrough for every other call site.
+ */
+export function git(
+ repoPath: string,
+ args: string[],
+ configs: string[] = [],
+ timeoutMs = 30000,
+ { silenceStderr = false }: { silenceStderr?: boolean } = {},
+): string {
+ return execFileSync('git', buildGitInvocation(repoPath, args, configs), {
+ encoding: 'utf-8',
+ timeout: timeoutMs,
+ maxBuffer: 100 * 1024 * 1024,
+ ...(silenceStderr ? { stdio: ['ignore', 'pipe', 'pipe'] as const } : {}),
+ }).trim();
+}
+
+/**
+ * #753/#774: walk up from inputPath to the nearest git repo root via
+ * `git -C <path> rev-parse --show-toplevel`. Handles worktrees and submodules
+ * natively (git itself resolves them). Throws a user-friendly error when no
+ * git repo is found.
+ *
+ * The probe's failure is expected and routine (a non-git-yet brain dir, a
+ * scratch dir, a caller checking "is this a repo?") — `sync.ts` self-heals
+ * it (git-init) or surfaces the message below, never the raw git stderr.
+ * `silenceStderr: true` keeps git's own `fatal: not a git repository ...`
+ * off the process's real stderr so operator log-scanning for `fatal:` as a
+ * crash signature doesn't false-alarm on every routine probe miss (#2964
+ * auto-recovery made the *outcome* self-healing; this keeps the *log* quiet
+ * about the expected miss that triggered it).
+ */
+export function discoverGitRoot(inputPath: string): string {
+ try {
+ return git(inputPath, ['rev-parse', '--show-toplevel'], [], 30000, { silenceStderr: true });
+ } catch {
+ throw new Error(
+ `Not inside a git repository: ${inputPath}. GBrain sync requires a git-initialized repo (or a subdirectory of one).`,
+ );
+ }
+}
+
+/**
+ * #2964: snapshot the CURRENT on-disk state of a gbrain-owned brain dir as
+ * a baseline commit — used both right after a self-healing `git init` (no
+ * `.git` at all) and to recover a repo left with `.git` but zero commits
+ * (an interrupted prior self-heal, or a `git init` from some other source
+ * that never got a first commit). Respects `.gitignore` (written first) so
+ * future incremental syncs diff against what's actually here rather than
+ * an empty tree — an empty initial commit would make every existing file
+ * look "added" again on the next sync, even though the full-sync pass that
+ * follows already imported them from disk directly.
+ *
+ * `--no-gpg-sign` + explicit `-c user.name/user.email`: this runs from a
+ * headless nightly cron/launchd invocation, which has no reason to have
+ * git signing/identity configured, and must not block on an unavailable
+ * signing agent or pinentry prompt.
+ *
+ * db_only exclusion is recomputed directly and passed to `git add` as
+ * negative pathspecs, rather than relying solely on `manageGitignore`
+ * having written `.gitignore` successfully: that helper is deliberately
+ * best-effort (a broken gbrain.yml parse, or an unwritable .gitignore,
+ * only warns and returns — the right default for its OTHER callers, where
+ * .gitignore management is a side effect that must never kill the sync
+ * job). For a commit we are about to create ourselves, "fail open" there
+ * would mean silently committing db_only content into git history. Fail
+ * closed instead: db_only exclusion doesn't depend on the .gitignore
+ * write having succeeded. `loadStorageConfig` throwing (unreadable
+ * gbrain.yml, or a semantic overlap) propagates — better to leave this
+ * self-heal wedged with a clear error than commit unknown content.
+ */
+/**
+ * Classify a caught `git rev-parse --verify --quiet HEAD` failure for the
+ * baseline-commit guard. A genuinely UNBORN HEAD makes git exit with status
+ * EXACTLY 1 and nothing on stderr — precisely what `--verify --quiet` emits
+ * for an unresolvable HEAD (verified empirically: unborn => exit 1, empty
+ * stderr; born => exit 0). Every OTHER failure shape — a 30s timeout (killed
+ * by signal, so `status` is null), an index/ref lock (`fatal: Unable to
+ * create ...lock`, non-empty stderr), or any nonzero-but-not-1 exit — is NOT
+ * proof the repo is empty; it is the transient-probe-failure class that
+ * corrupted the live brain on 2026-08-10. Return 'unborn' ONLY for the clean
+ * signal so the caller fails CLOSED on 'ambiguous'. Pure (no I/O) so the
+ * distinction is unit-testable without fault injection.
+ */
+export function classifyHeadProbeError(err: unknown): 'unborn' | 'ambiguous' {
+ const e = (err ?? {}) as { status?: number | null; signal?: string | null; stderr?: unknown };
+ const stderr = e.stderr == null ? '' : String(e.stderr).trim();
+ return e.status === 1 && e.signal == null && stderr === '' ? 'unborn' : 'ambiguous';
+}
+
+export function createSyncBaselineCommit(repoPath: string): void {
+ // Fail-closed backstop (2026-08-10 auto-init incident). This function's
+ // ENTIRE contract is "snapshot an unborn/uninitialized repo as its FIRST
+ // commit". It must NEVER run on a repo that already has commits: doing so
+ // stacks a spurious `gbrain: initial commit (auto-init by sync)` commit ON
+ // TOP of real history and, on a case-insensitive filesystem, re-cases the
+ // whole tree (`projects` -> `Projects`) as a `git add -A` side effect.
+ //
+ // Both call sites are *supposed* to reach here only on an unborn/non-git
+ // repo, but each infers "unborn" from a FAILURE to observe git state
+ // (`discoverGitRoot` threw / `git rev-parse HEAD` threw), and those probes
+ // ALSO fail transiently — a 30s timeout on a large brain, or a concurrent
+ // `gbrain-sync` holding a git lock — against a fully-populated repo, which
+ // is exactly what corrupted the live brain on 2026-08-10. So we cannot
+ // trust "the caller said it's unborn"; verify POSITIVELY here — and, since
+ // this very probe is subject to the same transient failures, accept ONLY a
+ // CLEAN unborn signal. A born HEAD (exit 0) OR an ambiguous probe failure
+ // (timeout / lock / other) both REFUSE, so the backstop is fail-closed
+ // against every corruption path, not just the born-HEAD one.
+ // `classifyHeadProbeError` isolates that born/unborn/ambiguous distinction
+ // as a pure, unit-tested predicate.
+ //
+ // Known non-incident edge (B2, documented not fixed): an orphan branch
+ // (`git switch --orphan`) in a repo with history elsewhere probes as unborn
+ // and would still be baselined. A gbrain brain is never in that state; it is
+ // not the incident (no stacking on real history, no re-case of other
+ // branches), so it is left as a limitation rather than complicating the
+ // guard with a `rev-list --all` "commits anywhere" probe.
+ let headState: 'born' | 'unborn' | 'ambiguous';
+ try {
+ git(repoPath, ['rev-parse', '--verify', '--quiet', 'HEAD'], [], 30000, { silenceStderr: true });
+ headState = 'born';
+ } catch (err) {
+ headState = classifyHeadProbeError(err);
+ }
+ if (headState !== 'unborn') {
+ throw new Error(
+ `Refusing to create a sync baseline commit in ${repoPath}: HEAD probe is ` +
+ `'${headState}', expected a clean unborn HEAD. 'born' = the repo already ` +
+ `has commits (real history); 'ambiguous' = the HEAD check failed ` +
+ `transiently (30s timeout, or a concurrent gbrain-sync holding a git ` +
+ `lock), which is NOT proof the repo is empty. Committing either way ` +
+ `would stack a bogus auto-init commit on real history and re-case the ` +
+ `tree on a case-insensitive filesystem.`,
+ );
+ }
+ // #2964: db_only exclusion is computed directly from loadStorageConfig
+ // and passed to `git add` as pathspecs — deliberately NOT via
+ // manageGitignore/.gitignore, for two independent reasons:
+ //
+ // 1. Ordering (Codex review round 6, P1): `collectSyncableFiles` — the
+ // file enumeration `performFullSync` runs right after this function
+ // returns — honors `.gitignore` via `git ls-files --exclude-standard`.
+ // Writing db_only entries into `.gitignore` BEFORE that first import
+ // would silently exclude those pages from the database entirely.
+ // That's the exact bug class `runSync`'s existing "manage .gitignore
+ // ONLY on successful sync" ordering (this file, `manageGitignoreAtGitRoot`
+ // callers below — itself a prior Codex P1 fix) exists to prevent. Leave
+ // `.gitignore` untouched here; the existing post-sync flow writes it
+ // once this sync completes, same as it does for every other sync.
+ // 2. Fail-closed (rounds 5-6): `manageGitignore`'s "warn and return" on a
+ // broken gbrain.yml/unwritable .gitignore is the right default for its
+ // OTHER callers (a side effect that must never kill the sync job), but
+ // wrong for a commit we are creating ourselves — silently committing
+ // db_only content into git history.
+ const storageConfig = loadStorageConfig(repoPath);
+ const dbOnlyDirs = storageConfig?.db_only ?? [];
+ // Sniff-test fail-closed (round 6, P2): `loadStorageConfig` warns-and-
+ // returns an EMPTY config for syntactically-valid-but-unsupported YAML
+ // (e.g. flow-style `db_only: [dir/]` — the narrow custom parser only
+ // handles block-style lists), which would silently resolve zero
+ // exclusions from a file that clearly intended some. If gbrain.yml
+ // exists and mentions db_only (or its deprecated pre-v0.22.11 alias
+ // `supabase_only` — same keep-out-of-git semantics, still a supported
+ // backward-compat key per storage-config.ts) but nothing resolved from
+ // it, refuse rather than guess "genuinely empty" vs "syntax ignored".
+ //
+ // Known false-positive (round 8 review): a genuinely, intentionally
+ // empty `db_only: []` mentioning the word also refuses, and can't be
+ // told apart from the unsupported-syntax case — `loadStorageConfig`
+ // returns the IDENTICAL `{db_tracked:[],db_only:[]}` for both (verified
+ // directly: flow-style `[dir/]` and literal `[]` both collapse to that
+ // same shape). Distinguishing them would mean teaching this function
+ // about the parser's internal line-recognition rules, which belongs in
+ // storage-config.ts, not here. Accepted trade-off: the false-positive
+ // cost is low and self-resolving (the brain stays wedged with a clear,
+ // actionable error until the user drops the pointless empty stanza or
+ // fixes their syntax; retried on every subsequent sync); the
+ // false-negative this guards against — silently committing db_only
+ // content into permanent git history — is high-cost and hard to undo.
+ if (dbOnlyDirs.length === 0) {
+ const yamlPath = join(repoPath, 'gbrain.yml');
+ const yamlContent = existsSync(yamlPath) ? readFileSync(yamlPath, 'utf-8') : '';
+ // A YAML KEY line (`db_only:` / `supabase_only:`, ignoring leading
+ // whitespace and `#` comments), not a bare substring search — round 9,
+ // P2: a comment or unrelated prose value that happens to mention the
+ // word (e.g. `# db_only handling TBD`) must not trip this guard on an
+ // otherwise-genuinely-config-free gbrain.yml.
+ const mentionsUnresolvedKey = yamlContent.split('\n').some((line) => {
+ const trimmed = line.trim();
+ return !trimmed.startsWith('#') && /^(db_only|supabase_only)\s*:/.test(trimmed);
+ });
+ if (mentionsUnresolvedKey) {
+ throw new Error(
+ `${yamlPath} mentions db_only but no directories resolved from it — refusing to ` +
+ `auto-commit (cannot tell "genuinely empty" from "unsupported syntax silently ignored"). ` +
+ `Fix gbrain.yml's storage.db_only syntax, or git-init this directory manually.`,
+ );
+ }
+ }
+ // #2964 (round 9, P1): every db_only dir is ALWAYS pathspec-excluded,
+ // unconditionally — never pre-filtered against what an existing
+ // `.gitignore` claims to already cover. An earlier version checked
+ // `git check-ignore -q dir` first and skipped the pathspec when it
+ // already reported "ignored" (to dodge the advisory error below), but
+ // `check-ignore` on a directory can say "ignored" even when a
+ // pre-existing `.gitignore` re-includes a child via negation (e.g.
+ // `private-cache/*` + `!private-cache/index.md`) — the filter would
+ // then skip excluding it via pathspec, and `git add -A` would stage
+ // that re-included child despite the whole directory being declared
+ // db_only. Our OWN pathspec exclusion is unconditional and doesn't
+ // consult `.gitignore` at all, so it can't be defeated by ANY
+ // .gitignore content, negated or not. `:(exclude,literal)dir` (not the
+ // `:!dir` shorthand) so a db_only dir name that itself starts with a
+ // pathspec magic character like `:` is excluded literally rather than
+ // reinterpreted (round 9, P2).
+ const excludePathspecs = dbOnlyDirs.map((dir) => `:(exclude,literal)${dir}`);
+ // Clear the index before staging (round 6, P1): the unborn-HEAD
+ // recovery site can reach this function with a repo whose index
+ // already has entries staged from some OTHER prior operation (a manual
+ // `git add`, an interrupted workflow) before gbrain ever touched it.
+ // `add -A` only adds/updates — it does not drop an already-staged path
+ // that our exclusion pathspecs above now want excluded. `read-tree
+ // --empty` resets the index without touching the working tree; a
+ // no-op on a freshly-`git init`-ed repo, whose index is already empty.
+ git(repoPath, ['read-tree', '--empty']);
+ try {
+ // #2964: 10 minutes, not the shared git() helper's 30s default — this
+ // full-tree `git add -A` walks a legacy brain that may hold years of
+ // accumulated content. A 30s timeout would abort staging after `git
+ // init` already created `.git`, leaving an unborn repo that every
+ // subsequent sync would retry (and time out identically) forever;
+ // the unborn-HEAD recovery path exists for OTHER causes of that
+ // state, not to be this one's normal first outcome.
+ git(repoPath, ['add', '-A', '--', '.', ...excludePathspecs], [], 600_000);
+ } catch (err) {
+ // Now that exclusion is always applied (never pre-filtered), an
+ // explicit pathspec exclusion for a path a pre-existing `.gitignore`
+ // ALSO happens to cover trips git's advice.addIgnoredFile: nonzero
+ // exit + "paths ignored by one of your .gitignore files, use -f",
+ // even though the add otherwise fully succeeded (verified directly:
+ // `git status --short` right after this exact error shows every
+ // non-excluded path staged correctly). Recognize and swallow ONLY
+ // this exact advisory; anything else (timeout, permission denied,
+ // real corruption) rethrows.
+ const stderr = err && typeof err === 'object' && 'stderr' in err ? String((err as { stderr: unknown }).stderr) : '';
+ if (!stderr.includes('ignored by one of your .gitignore files')) throw err;
+ }
+ git(
+ repoPath,
+ // --no-verify only skips pre-commit/commit-msg — prepare-commit-msg
+ // and (worse, since it runs AFTER the commit object already exists,
+ // synchronously inside this same git invocation) post-commit are
+ // NOT covered by it. An operator's global core.hooksPath or
+ // init.templateDir can wire either, expecting project tooling,
+ // prompting interactively, or hanging — none of which a headless
+ // self-heal commit can satisfy, and a hanging post-commit hook would
+ // burn the 600s budget above without even being the slow step.
+ // `-c core.hooksPath=/dev/null` (in configs, below) makes git look
+ // for hook scripts inside a location that can't contain any,
+ // disabling the entire hooks path for this one invocation — the
+ // complete form of what --no-verify only partially covers, kept for
+ // explicitness on the two hooks it does name.
+ [
+ 'commit', '--quiet', '--allow-empty', '--no-gpg-sign', '--no-verify',
+ '-m', 'gbrain: initial commit (auto-init by sync)',
+ ],
+ ['user.name=gbrain', 'user.email=gbrain@localhost', 'core.hooksPath=/dev/null'],
+ );
+}
+
+/**
+ * True when `childReal` is `rootReal` itself or lives inside it. Both arguments
+ * must already be realpath-resolved. Containment is decided by `relative()`
+ * rather than a string prefix, so it holds on Windows too: `realpathSync`
+ * returns backslash paths there, and a literal `rootReal + '/'` prefix can
+ * never match one. A sibling (`root-evil`) is rejected because `relative`
+ * yields `../root-evil`, and a cross-drive path because it yields an absolute.
+ */
+export function isWithinRoot(childReal: string, rootReal: string): boolean {
+ if (childReal === rootReal) return true;
+ const rel = relative(rootReal, childReal);
+ return rel !== '' && rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
+}
+
+/**
+ * #774 NAV-1 TOCTOU: true only if filePath realpath-resolves inside gitRoot.
+ * Guards symlink escape at the per-file level (a committed symlink whose
+ * target lives outside the repo), not just at scope entry.
+ */
+export function isPathSafe(filePath: string, gitRoot: string): boolean {
+ try {
+ return isWithinRoot(realpathSync(filePath), realpathSync(gitRoot));
+ } catch {
+ return false;
+ }
+}
+
+export function hasOriginRemote(repoPath: string): boolean {
+ try {
+ execFileSync('git', buildGitInvocation(repoPath, ['remote', 'get-url', 'origin']), {
+ encoding: 'utf-8',
+ timeout: 30000,
+ stdio: ['ignore', 'ignore', 'ignore'],
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function isDetachedHead(repoPath: string): boolean {
+ try {
+ git(repoPath, ['symbolic-ref', '--quiet', 'HEAD']);
+ return false;
+ } catch {
+ return true;
+ }
+}
+
+export function unique<T>(items: T[]): T[] {
+ return [...new Set(items)];
+}
diff --git a/src/core/sync-lock.ts b/src/core/sync-lock.ts
new file mode 100644
index 0000000000..70a6abaa21
--- /dev/null
+++ b/src/core/sync-lock.ts
@@ -0,0 +1,313 @@
+/**
+ * Sync lock layer: the typed lock-busy error, the rich busy message,
+ * `--break-lock` handling, and the partial-result envelope. Peeled out of
+ * src/commands/sync.ts (containment sprint C13-C14) as a pure move —
+ * `performSync` itself (the lock acquisition wrapper) stays in that file.
+ */
+import type { BrainEngine } from './engine.ts';
+import type { SyncResult } from '../commands/sync.ts';
+
+/**
+ * v0.42.x (#1794, Part B): typed lock-busy error so callers can distinguish a
+ * benign "another sync holds the lock, skip cleanly" from a real failure.
+ * Subclasses Error so existing CLI handlers that print `err.message` keep the
+ * rich `formatLockBusyMessage` text verbatim. The Minion `sync` handler catches
+ * this to mark the job skipped (not failed) — single-flight backpressure: the
+ * cron/autopilot sync defers to the holder instead of erroring + retrying noisily.
+ */
+export class SyncLockBusyError extends Error {
+ readonly lockKey: string;
+ constructor(message: string, lockKey: string) {
+ super(message);
+ this.name = 'SyncLockBusyError';
+ this.lockKey = lockKey;
+ }
+}
+
+/**
+ * v0.41.6.0 D3: rich "Another sync is in progress" message that names the
+ * holder PID, hostname, age, and the right --break-lock invocation to
+ * recover. Falls back to the legacy message when inspectLock can't read
+ * the row (best-effort — the lock itself was still busy).
+ */
+export async function formatLockBusyMessage(engine: BrainEngine, lockKey: string): Promise<string> {
+ const { inspectLock } = await import('./db-lock.ts');
+ let snap;
+ try { snap = await inspectLock(engine, lockKey); }
+ catch { snap = null; }
+
+ if (!snap) {
+ return (
+ `Another sync is in progress (lock ${lockKey} held). ` +
+ `Wait for it to finish, or run 'gbrain doctor' if it has been more than 30 minutes.`
+ );
+ }
+
+ const ageHuman = formatAgeHuman(snap.age_ms);
+ const breakHint = lockKey.startsWith('gbrain-sync:')
+ ? `gbrain sync --break-lock --source ${lockKey.slice('gbrain-sync:'.length)}`
+ : `gbrain sync --break-lock`;
+ const ttlNote = snap.ttl_expired ? ' [TTL expired]' : '';
+ return (
+ `Another sync is in progress (lock ${lockKey} held by pid ${snap.holder_pid} on ${snap.holder_host}, ` +
+ `started ${ageHuman} ago${ttlNote}).\n` +
+ `If pid ${snap.holder_pid} is dead, re-run with --break-lock to clear it:\n` +
+ ` ${breakHint}\n` +
+ `Or wait for the holder to finish.`
+ );
+}
+
+/**
+ * v0.41.6.0 D3: `gbrain sync --break-lock` / `--force-break-lock` worker.
+ * Returns the process exit code (0 = lock cleared or absent; 1 = refused).
+ *
+ * Safe path (`force=false`): refuses unless the holder is on this host
+ * AND either (a) TTL has expired (the lock is structurally available
+ * already) OR (b) the holder PID is dead AND the lock is older than 60s
+ * (the age guard defeats PID-reuse coincidence — Linux PID space wraps
+ * at 32768 so a 10-day-old lock with pid=12345 may be falsely
+ * refused-to-clear because an unrelated process now owns pid 12345; 60s
+ * is the codex F7-amended minimum age that makes coincidence unlikely).
+ *
+ * Force path (`force=true`): skips liveness check, deletes the row,
+ * warns loudly that the holder may still be writing.
+ *
+ * Both paths use the same atomic `DELETE ... RETURNING id` so a race
+ * with another break-lock or with TTL-eviction can't produce confusing
+ * post-conditions.
+ */
+export async function runBreakLock(
+ engine: BrainEngine,
+ lockKey: string,
+ sourceId: string,
+ opts: { force: boolean; json: boolean; maxAgeSeconds?: number },
+): Promise<number> {
+ const { inspectLock, deleteLockRow, deleteLockRowIfStale, classifyHolderLiveness } = await import('./db-lock.ts');
+ const { hostname } = await import('os');
+ const localHost = hostname();
+ let snap;
+ try { snap = await inspectLock(engine, lockKey); }
+ catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ if (opts.json) console.log(JSON.stringify({ status: 'error', error: msg, lock: lockKey }));
+ else console.error(`Failed to inspect lock ${lockKey}: ${msg}`);
+ return 1;
+ }
+
+ if (!snap) {
+ // BUG 5 (v0.42.x): --force-break-lock used to emit the same terse "not
+ // held" line and exit 0 even when a sync was genuinely wedged — sending the
+ // operator down a dead end (the wedge was not a held lock). Keep rc=0
+ // (breaking a non-existent lock is idempotently successful; flipping the
+ // exit code would break automation that treats it as success), but under
+ // --force say plainly that nothing was broken and point at the real next
+ // step. The non-force path message is unchanged.
+ if (opts.force) {
+ const wedgeHint =
+ `No lock is held on ${lockKey} — nothing to break. If a sync still ` +
+ `appears wedged, the cause is not a held lock; inspect checkpoint/resume ` +
+ `state with \`gbrain sync --source ${sourceId}\` or \`gbrain doctor\`.`;
+ if (opts.json) {
+ console.log(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId, wedge_hint: wedgeHint }));
+ } else {
+ console.log(wedgeHint);
+ }
+ return 0;
+ }
+ if (opts.json) console.log(JSON.stringify({ status: 'absent', lock: lockKey, source_id: sourceId }));
+ else console.log(`Lock ${lockKey} is not held (nothing to break).`);
+ return 0;
+ }
+
+ // v0.41.13.0 (T4 / D-V3-4 / D-V4-mech-4) — --max-age path: route through
+ // deleteLockRowIfStale which runs a single atomic DELETE keyed on
+ // (id, holder_pid, last_refreshed_at < NOW() - maxAge). Healthy refreshing
+ // holders survive by construction (their last_refreshed_at is recent).
+ // Wedged-but-alive holders (JS interval stopped firing) get broken.
+ // No TOCTOU between inspect + delete; the WHERE clause is the gate.
+ if (opts.maxAgeSeconds !== undefined && !opts.force) {
+ // Cross-host guard preserved from the safe path: --max-age does NOT
+ // bypass cross-host refusal because process.kill(pid, 0) is invalid
+ // across hosts (PID is meaningful only on the same host). Operators
+ // who need to clear a cross-host lock use --force-break-lock.
+ if (snap.holder_host !== localHost) {
+ if (opts.json) {
+ console.log(JSON.stringify({
+ status: 'refused', reason: 'cross_host', lock: lockKey, source_id: sourceId,
+ snapshot: snap, local_host: localHost,
+ }));
+ } else {
+ console.error(`Lock ${lockKey} is held on a different host (${snap.holder_host}, this host is ${localHost}).`);
+ console.error('Cross-host --max-age is unsupported. Use --force-break-lock when certain the remote holder is dead.');
+ }
+ return 1;
+ }
+ const { deleted, lastRefreshedAt } = await deleteLockRowIfStale(
+ engine, lockKey, snap.holder_pid, opts.maxAgeSeconds,
+ );
+ if (opts.json) {
+ console.log(JSON.stringify({
+ status: deleted ? 'broken' : 'refused',
+ reason: deleted ? 'max_age_breached' : 'within_max_age',
+ lock: lockKey,
+ source_id: sourceId,
+ snapshot: snap,
+ max_age_seconds: opts.maxAgeSeconds,
+ last_refreshed_at: lastRefreshedAt ? lastRefreshedAt.toISOString() : null,
+ }));
+ } else if (deleted) {
+ const ageStr = lastRefreshedAt ? formatAgeHuman(Date.now() - lastRefreshedAt.getTime()) : 'unknown';
+ console.log(`Broke lock ${lockKey} (pid ${snap.holder_pid} on ${snap.holder_host}; last refresh was ${ageStr} ago, > --max-age=${opts.maxAgeSeconds}s).`);
+ } else {
+ // last_refreshed_at within --max-age window OR null (pre-v98 brain).
+ // Distinguish the two cases for the operator.
+ if (snap.last_refreshed_at === null) {
+ console.error(`Lock ${lockKey} has NULL last_refreshed_at (pre-v98 brain or migration window).`);
+ console.error('Run `gbrain apply-migrations --yes` to land v98, OR use --force-break-lock if you know the holder is dead.');
+ } else {
+ const ageStr = snap.ms_since_last_refresh != null ? formatAgeHuman(snap.ms_since_last_refresh) : 'unknown';
+ console.error(`Refusing to break lock ${lockKey}: last refresh was ${ageStr} ago, within --max-age=${opts.maxAgeSeconds}s window.`);
+ console.error('The holder is actively refreshing — likely a healthy long-running sync.');
+ }
+ return 1;
+ }
+ return 0;
+ }
+
+ // Force path: skip all guards, atomic DELETE, warn.
+ if (opts.force) {
+ const { deleted } = await deleteLockRow(engine, lockKey, snap.holder_pid);
+ if (opts.json) {
+ console.log(JSON.stringify({
+ status: deleted ? 'force_broken' : 'race_already_cleared',
+ lock: lockKey, source_id: sourceId, snapshot: snap,
+ }));
+ } else if (deleted) {
+ console.log(`Force-broke lock ${lockKey} (was held by pid ${snap.holder_pid} on ${snap.holder_host}, age ${formatAgeHuman(snap.age_ms)}).`);
+ console.log('WARNING: the holder may still be writing. Verify with `gbrain doctor` before re-running.');
+ } else {
+ console.log(`Lock ${lockKey} was already cleared by another process between our check and DELETE (race-safe).`);
+ }
+ return 0;
+ }
+
+ // Safe path: must be local host AND (TTL-expired OR (PID-dead AND age >= 60s)).
+ if (snap.holder_host !== localHost) {
+ if (opts.json) {
+ console.log(JSON.stringify({
+ status: 'refused',
+ reason: 'cross_host',
+ lock: lockKey, source_id: sourceId, snapshot: snap, local_host: localHost,
+ }));
+ } else {
+ console.error(`Lock ${lockKey} is held on a different host (${snap.holder_host}, this host is ${localHost}).`);
+ console.error('Cross-host PID liveness is unsound. To break anyway, use --force-break-lock');
+ console.error('(only safe when you KNOW the holder is dead — verify before forcing).');
+ }
+ return 1;
+ }
+
+ let safe = false;
+ let reason: string;
+ if (snap.ttl_expired) {
+ safe = true;
+ reason = 'ttl_expired';
+ } else {
+ // PID liveness on local host, via the shared predicate (v0.42 #1780 Gap 3).
+ // Same gate as tryAcquireDbLock's auto-takeover: same-host + provably-dead
+ // (ESRCH) + age >= 60s. EPERM is treated as ALIVE (the PID exists but isn't
+ // ours) — never break a live lock. host is already == localHost here (the
+ // cross-host branch returned above), so classify never yields 'cross_host'.
+ const liveness = classifyHolderLiveness(snap.holder_pid, snap.holder_host, snap.age_ms);
+ if (liveness === 'dead_eligible') {
+ safe = true;
+ reason = 'pid_dead_age_60s';
+ } else if (liveness === 'too_young') {
+ reason = 'pid_dead_but_lock_too_young';
+ } else {
+ // 'alive' | 'unknown' | 'cross_host' (the latter unreachable here).
+ reason = 'pid_alive';
+ }
+ }
+
+ if (!safe) {
+ if (opts.json) {
+ console.log(JSON.stringify({
+ status: 'refused', reason, lock: lockKey, source_id: sourceId, snapshot: snap,
+ }));
+ } else {
+ console.error(`Refusing to break lock ${lockKey}: holder pid ${snap.holder_pid} appears alive on ${snap.holder_host} (age ${formatAgeHuman(snap.age_ms)}).`);
+ if (reason === 'pid_dead_but_lock_too_young') {
+ console.error('(PID is dead but the lock is younger than 60s — the PID may have been reused. Wait or use --force-break-lock if you are certain.)');
+ } else {
+ console.error('If the holder is wedged, kill it first then re-run --break-lock,');
+ console.error('OR use --force-break-lock to clear regardless (the holder may still write afterwards).');
+ }
+ }
+ return 1;
+ }
+
+ const { deleted } = await deleteLockRow(engine, lockKey, snap.holder_pid);
+ if (opts.json) {
+ console.log(JSON.stringify({
+ status: deleted ? 'broken' : 'race_already_cleared',
+ reason, lock: lockKey, source_id: sourceId, snapshot: snap,
+ }));
+ } else if (deleted) {
+ console.log(`Broke lock ${lockKey} (was held by pid ${snap.holder_pid} on ${snap.holder_host}, age ${formatAgeHuman(snap.age_ms)}; reason: ${reason}).`);
+ } else {
+ console.log(`Lock ${lockKey} was already cleared by another process between our check and DELETE (race-safe).`);
+ }
+ return 0;
+}
+
+function formatAgeHuman(ms: number): string {
+ if (ms < 1000) return `${ms}ms`;
+ const s = Math.floor(ms / 1000);
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m${s % 60}s`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h}h${m % 60}m`;
+ const d = Math.floor(h / 24);
+ return `${d}d${h % 24}h`;
+}
+
+/**
+ * v0.41.13.0 — build a SyncResult { status: 'partial' } envelope.
+ *
+ * D-V3-1 invariant: this is only ever called BEFORE the bookmark write at
+ * sync.ts:writeSyncAnchor('last_commit'), so `last_commit` is NEVER advanced
+ * on partial. The next sync re-walks last_commit..HEAD and `content_hash`
+ * short-circuits already-imported files at ~10ms each. The caller's lock is
+ * released by `withRefreshingLock`'s try/finally as soon as this returns.
+ */
+export function buildPartialResult(opts: {
+ fromCommit: string | null;
+ toCommit: string;
+ filesImported: number;
+ pagesAffected: string[];
+ chunksCreated: number;
+ added: number;
+ modified: number;
+ deleted: number;
+ renamed: number;
+ reason: 'timeout' | 'pull_timeout' | 'pull_failed' | 'stall_timeout' | 'checkpoint_unavailable';
+ bankedFiles?: number;
+}): SyncResult {
+ return {
+ status: 'partial',
+ fromCommit: opts.fromCommit,
+ toCommit: opts.toCommit,
+ added: opts.added,
+ modified: opts.modified,
+ deleted: opts.deleted,
+ renamed: opts.renamed,
+ chunksCreated: opts.chunksCreated,
+ embedded: 0,
+ pagesAffected: opts.pagesAffected,
+ filesImported: opts.filesImported,
+ reason: opts.reason,
+ bankedFiles: opts.bankedFiles,
+ };
+}
diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.ts
new file mode 100644
index 0000000000..06a1103f65
--- /dev/null
+++ b/src/core/sync-reconcile.ts
@@ -0,0 +1,210 @@
+/**
+ * Full-sync reconcile planning (#2828 mass-delete valve, #2426 ever-committed
+ * gate) + sync deadline/stall resolution (#1633, #1950). Peeled out of
+ * src/commands/sync.ts (containment sprint C13-C14) as a pure move.
+ */
+import { execFileSync } from 'child_process';
+import { parseDurationSeconds } from './sync-concurrency.ts';
+
+/**
+ * #2828 full-sync reconcile safety-valve thresholds. A reconcile that would
+ * delete more than MASS_RECONCILE_RATIO of the file-backed pages a strategy
+ * manages, on a source that holds more than MASS_RECONCILE_MIN_PAGES of them, is
+ * treated as a suspected path-comparison bug rather than a real bulk deletion.
+ */
+export const MASS_RECONCILE_RATIO = 0.5;
+export const MASS_RECONCILE_MIN_PAGES = 20;
+
+/**
+ * Normalize path separators so a page whose stored `source_path` was written
+ * with a different separator than the local OS's `path.relative` produces (e.g.
+ * git-derived forward-slash paths on a Windows checkout) still compares equal.
+ * Without this, on Windows every file-backed page looks stale and the reconcile
+ * wrongly deletes the whole source (#2828).
+ */
+function normalizeReconcilePath(p: string): string {
+ return p.replace(/\\/g, '/');
+}
+
+export interface ReconcilePlan {
+ /** Slugs whose backing file is genuinely gone; safe to reconcile-delete. */
+ staleSlugs: string[];
+ /**
+ * File-backed, in-strategy pages the reconcile can act on. This is the
+ * denominator for the mass-delete valve (the exact population at risk).
+ */
+ reconcilableCount: number;
+ /**
+ * True when `staleSlugs` would sweep more than MASS_RECONCILE_RATIO of
+ * `reconcilableCount`, on a source with more than MASS_RECONCILE_MIN_PAGES of
+ * them — the mass-delete signal that trips the safety valve.
+ */
+ massDelete: boolean;
+}
+
+/**
+ * #2828: decide which file-backed pages a full-sync reconcile should delete, and
+ * whether that deletion is suspiciously large. Pure and exported so both the
+ * separator normalization and the mass-delete valve are unit-testable without a
+ * live engine or a Windows host.
+ *
+ * @param rows pages with a non-null `source_path` (deleted_at IS NULL).
+ * @param currentFiles repo-relative paths present in the working tree.
+ * @param isSyncablePath predicate excluding metafiles and the wrong strategy.
+ */
+export function planReconcileDeletes(
+ rows: ReadonlyArray<{ slug: string; source_path: string | null }>,
+ currentFiles: Iterable<string>,
+ isSyncablePath: (p: string) => boolean,
+): ReconcilePlan {
+ const current = new Set<string>();
+ for (const f of currentFiles) current.add(normalizeReconcilePath(f));
+ const reconcilable = rows.filter(
+ r => r.source_path != null && isSyncablePath(r.source_path),
+ );
+ const staleSlugs = reconcilable
+ .filter(r => !current.has(normalizeReconcilePath(r.source_path as string)))
+ .map(r => r.slug);
+ const massDelete =
+ reconcilable.length > MASS_RECONCILE_MIN_PAGES &&
+ staleSlugs.length > reconcilable.length * MASS_RECONCILE_RATIO;
+ return { staleSlugs, reconcilableCount: reconcilable.length, massDelete };
+}
+
+/**
+ * #2426: every repo-relative path that ever appeared as an ADD in git history
+ * (rename detection off, so a `git mv` destination still counts as an add).
+ * Used by the full-sync reconcile to distinguish "file was committed and later
+ * deleted" (genuine delete → reconcile) from "file was NEVER committed"
+ * (DB-only write-through → preserve). Returns null when `repoPath` isn't a git
+ * work tree or git is unavailable — callers keep the plain-directory behavior.
+ * Forward-slash-normalized to match `normalizeReconcilePath` membership tests.
+ */
+export function listEverCommittedPaths(repoPath: string): Set<string> | null {
+ let stdout: string;
+ try {
+ stdout = execFileSync(
+ 'git',
+ ['-C', repoPath, '-c', 'core.quotepath=off', 'log', '--all', '--no-renames',
+ '--diff-filter=A', '--format=', '--name-only'],
+ { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] },
+ );
+ } catch {
+ return null;
+ }
+ const set = new Set<string>();
+ for (const line of stdout.split('\n')) {
+ if (line) set.add(line.replace(/\\/g, '/'));
+ }
+ return set;
+}
+
+/**
+ * #2828 escape hatch: `GBRAIN_ALLOW_MASS_RECONCILE=1` restores the pre-valve
+ * behavior for the rare intentional bulk removal. Env-only (an incident-time
+ * override), mirroring `resolveStallAbortSeconds`' pure, env-parameterized shape.
+ */
+export function massReconcileAllowed(
+ env: Record<string, string | undefined> = process.env,
+): boolean {
+ return env.GBRAIN_ALLOW_MASS_RECONCILE === '1';
+}
+
+/**
+ * Grace window (seconds) between the watchdog's SIGTERM and SIGKILL. SIGTERM
+ * gives a responsive loop a clean shutdown; SIGKILL is the starvation backstop.
+ */
+export const HARD_DEADLINE_GRACE_SEC = 30;
+
+export interface HardDeadlineResolution {
+ deadlineMs: number;
+ graceMs: number;
+ /** Where the deadline came from (for the armed-log line + tests). */
+ reason: string;
+}
+
+/**
+ * #1950: default no-import-progress window before the in-band stall watchdog
+ * aborts the drain. Generous on purpose — it must clear one legitimately large
+ * file (cross-region, big page) without false-tripping; one file taking longer
+ * than this trips it (documented limit). Distinct from the wall-clock hard
+ * deadline (whole-run cap) and the lock heartbeat (refreshes regardless of
+ * import progress). Env-tunable; <=0 disables.
+ */
+export const DEFAULT_SYNC_STALL_ABORT_SEC = 900;
+
+export function resolveStallAbortSeconds(
+ env: Record<string, string | undefined> = process.env,
+): number {
+ const raw = env.GBRAIN_SYNC_STALL_ABORT_SECONDS;
+ if (raw === undefined || raw === '') return DEFAULT_SYNC_STALL_ABORT_SEC;
+ const n = Number(raw);
+ if (!Number.isFinite(n)) return DEFAULT_SYNC_STALL_ABORT_SEC;
+ return n; // n <= 0 disables the watchdog
+}
+
+/**
+ * Resolve the out-of-band hard-deadline for a `gbrain sync` invocation (#1633).
+ * Pure + argv/env-only so it runs BEFORE `connectEngine` (so a connect-phase hang
+ * is also bounded — `timeout-layer-vs-connectengine` learning). DB-plane config
+ * (`gbrain config set`) is unreadable pre-connect, so the operator knob is the
+ * `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env var; bare cron is covered by the non-TTY
+ * default. Returns null when no watchdog should arm (TTY interactive with no
+ * flag, or an explicit opt-out / 0).
+ *
+ * Precedence: --no-hard-deadline > --hard-deadline > --timeout(non-all) > env >
+ * non-TTY default (3600s) > none.
+ */
+export function resolveSyncHardDeadline(
+ args: string[],
+ opts: { isTty: boolean; env?: Record<string, string | undefined>; defaultNonTtySec?: number },
+): HardDeadlineResolution | null {
+ const env = opts.env ?? {};
+ const graceMs = HARD_DEADLINE_GRACE_SEC * 1000;
+ const mk = (sec: number, reason: string): HardDeadlineResolution | null =>
+ sec > 0 ? { deadlineMs: sec * 1000, graceMs, reason } : null;
+
+ if (args.includes('--no-hard-deadline')) return null;
+
+ const hardStr = args.find((a, i) => args[i - 1] === '--hard-deadline');
+ if (hardStr !== undefined) {
+ // Throws on a bad value (cli.ts surfaces it + exits 1) — same posture as --timeout.
+ const sec = parseDurationSeconds(hardStr, '--hard-deadline');
+ return mk(sec ?? 0, 'flag:--hard-deadline');
+ }
+
+ // --timeout auto-arms a hard backstop at timeout(+grace), but ONLY single-source.
+ // For --all, per-source budgets don't collapse to one wall-clock; fall through.
+ const isAll = args.includes('--all');
+ const timeoutStr = args.find((a, i) => args[i - 1] === '--timeout');
+ if (timeoutStr !== undefined && !isAll) {
+ const sec = parseDurationSeconds(timeoutStr, '--timeout');
+ if (sec && sec > 0) return mk(sec, 'flag:--timeout');
+ }
+
+ const envRaw = env.GBRAIN_SYNC_MAX_RUNTIME_SECONDS;
+ if (envRaw !== undefined && envRaw !== '') {
+ const n = Number(envRaw);
+ if (Number.isFinite(n)) return mk(n, 'env:GBRAIN_SYNC_MAX_RUNTIME_SECONDS'); // n<=0 disables
+ }
+
+ if (!opts.isTty) return mk(opts.defaultNonTtySec ?? 3600, 'default:non-tty');
+
+ return null;
+}
+
+/**
+ * Compose 1..N AbortSignals into one (CQ2). Undefined inputs are dropped; the
+ * result aborts when ANY input aborts. Returns a single signal directly (no
+ * wrapper), `undefined` when nothing is set. Used at both performSync call sites
+ * so the SIGINT graceful-cancel signal and the per-source `--timeout` signal
+ * compose without duplicating `AbortSignal.any` logic.
+ */
+export function composeAbortSignals(
+ ...signals: Array<AbortSignal | undefined>
+): AbortSignal | undefined {
+ const live = signals.filter((s): s is AbortSignal => s !== undefined);
+ if (live.length === 0) return undefined;
+ if (live.length === 1) return live[0];
+ return AbortSignal.any(live);
+}
diff --git a/src/core/sync-status-report.ts b/src/core/sync-status-report.ts
new file mode 100644
index 0000000000..37fb46503e
--- /dev/null
+++ b/src/core/sync-status-report.ts
@@ -0,0 +1,341 @@
+/**
+ * Per-source sync status report (`gbrain sources status` + the
+ * get_status_snapshot MCP op). Peeled out of src/commands/sync.ts
+ * (containment sprint C13-C14) as a pure move.
+ */
+import type { BrainEngine } from './engine.ts';
+import { loadConfig } from './config.ts';
+import { unacknowledgedSyncFailures } from './sync.ts';
+// lagFromContentMs is the remote/column comparator (buildSyncStatusReport
+// backs the get_status_snapshot MCP op — must NOT shell out to git).
+import { lagFromContentMs } from './source-health.ts';
+
+/**
+ * v0.40.3.0 — read-only per-source dashboard for `gbrain sources status`.
+ *
+ * Aggregates from existing tables (no schema changes):
+ * - sources: last_commit, last_sync_at, archived, config.syncEnabled
+ * (filtered: archived=false, local_path IS NOT NULL)
+ * - pages: per-source page count (excluding soft-deleted)
+ * - content_chunks: per-source total + count of unembedded chunks for
+ * the ACTIVE embedding column (resolved via the
+ * registry — see `src/core/search/embedding-column.ts`).
+ * Voyage / multimodal / non-default-column brains
+ * see counts against the column they actually use.
+ * - sync-failures.jsonl: unacknowledged failures (brain-global; the
+ * JSONL log isn't per-source. v0.40.4 TODO source-scopes it.)
+ *
+ * Staleness thresholds match `gbrain doctor`'s sync-freshness rule
+ * (24h / 72h). Sources that have NEVER synced (last_sync_at IS NULL)
+ * report `staleness_hours: null` so callers can disambiguate "first run
+ * pending" from "32h since last successful sync".
+ *
+ * Errors propagate. Pre-v0.40.3.0 the dashboard swallowed all DB errors
+ * and reported zero counts, which lied at exactly the moment it mattered
+ * (Q2 sub-fix from Codex review). The dashboard is read-only — a thrown
+ * error surfaces the real problem (DB down, permission denied, statement
+ * timeout) instead of misleading the operator with a "0 chunks" report.
+ */
+export interface SyncStatusReportSource {
+ source_id: string;
+ name: string;
+ local_path: string | null;
+ sync_enabled: boolean;
+ last_sync_at: string | null;
+ /** Raw wall-clock hours since the last successful sync — the honest human
+ * number. Distinct from staleness_hours, which is threshold-relative. */
+ hours_since_last_sync: number | null;
+ /** Threshold-relative lag driving staleness_class. For a source whose
+ * content is OLDER than its last sync this is the ceiling-ramped value
+ * (see lagFromContentMs), which deliberately under-reads raw wall-clock so
+ * the warn tier fires before the fail tier — display hours_since_last_sync
+ * when a human asks "how long since we synced". */
+ staleness_hours: number | null;
+ staleness_class: 'fresh' | 'stale' | 'severe' | 'unknown';
+ last_commit: string | null;
+ pages: number;
+ chunks_total: number;
+ chunks_unembedded: number;
+ embedding_coverage_pct: number;
+ // v0.41.31: embed-backfill job visibility (federated_v2 defers embedding
+ // to these jobs; without this an operator can't see queued/lagging work
+ // after `sync --all` exits 0). Best-effort — all 0 / null on brains
+ // without the minion_jobs table.
+ backfill_queued: number;
+ backfill_active: number;
+ backfill_last_completed_at: string | null;
+}
+
+export interface SyncStatusReport {
+ schema_version: 1;
+ generated_at: string;
+ sources: SyncStatusReportSource[];
+ unacknowledged_failures: number;
+ /** The embedding column counts were computed against. Useful for
+ * operators verifying their Voyage / multimodal setup is reported
+ * correctly. */
+ embedding_column: string;
+}
+
+export async function buildSyncStatusReport(
+ engine: BrainEngine,
+ sources: Array<{ id: string; name: string; local_path: string | null; config: Record<string, unknown> }>,
+): Promise<SyncStatusReport> {
+ // Resolve the active embedding column via the registry. Brains pointed
+ // at Voyage / multimodal / any non-default column get accurate counts
+ // for the column they actually use (D16 → A, Codex P2 #10).
+ const { resolveEmbeddingColumn, quoteIdentifier } = await import('./search/embedding-column.ts');
+ // loadConfig() returns null when ~/.gbrain/config.json is missing.
+ // resolveEmbeddingColumn handles missing fields via its own
+ // gateway-fallback chain, so a minimal stub satisfies the call shape.
+ const cfg = loadConfig() ?? ({ engine: engine.kind } as Parameters<typeof resolveEmbeddingColumn>[1]);
+ const resolved = resolveEmbeddingColumn(undefined, cfg);
+ const embeddingColIdent = quoteIdentifier(resolved.name);
+
+ const sourceIds = sources.map((s) => s.id);
+ type SourceRow = {
+ id: string;
+ last_commit: string | null;
+ last_sync_at: string | Date | null;
+ // v0.41.32.0: remote staleness reads this column (no git subprocess).
+ newest_content_at: string | Date | null;
+ };
+ type CountRow = {
+ source_id: string;
+ pages: string | number;
+ chunks_total: string | number;
+ chunks_unembedded: string | number;
+ };
+
+ // Pull last_commit + last_sync_at fresh (caller may have called us
+ // with stale rows). Empty source list → skip the round-trip.
+ const sourceRows = sourceIds.length === 0
+ ? []
+ : await engine.executeRaw<SourceRow>(
+ `SELECT id, last_commit, last_sync_at, newest_content_at FROM sources WHERE id = ANY($1::text[])`,
+ [sourceIds],
+ );
+ const sourceMap = new Map<string, SourceRow>();
+ for (const r of sourceRows) sourceMap.set(r.id, r);
+
+ // Per-source page + chunk + unembedded-chunk counts in a single
+ // round-trip. Canonical SQL (verified against
+ // src/commands/doctor/checks/extraction-sync.ts: content_chunks joined on page_id
+ // (NOT page_slug — Codex P0 #1), filtered for non-soft-deleted pages
+ // (NOT NULL — soft-delete shipped v0.26.5), unembedded counted
+ // against the resolved active embedding column (D16 → A).
+ //
+ // No try/catch swallow — a thrown error means DB down / permission
+ // denied / statement timeout (NOT a schema variant). Surfacing the
+ // real error is better than a misleading "0 chunks" report (Q2).
+ let countRows: CountRow[] = [];
+ if (sourceIds.length > 0) {
+ countRows = await engine.executeRaw<CountRow>(
+ `WITH s AS (
+ SELECT unnest($1::text[]) AS source_id
+ )
+ SELECT
+ s.source_id,
+ COALESCE(p.pages, 0) AS pages,
+ COALESCE(c.chunks_total, 0) AS chunks_total,
+ COALESCE(c.chunks_unembedded, 0) AS chunks_unembedded
+ FROM s
+ LEFT JOIN (
+ SELECT source_id, COUNT(*) AS pages
+ FROM pages
+ WHERE deleted_at IS NULL
+ GROUP BY source_id
+ ) p ON p.source_id = s.source_id
+ LEFT JOIN (
+ SELECT pg.source_id,
+ COUNT(*) AS chunks_total,
+ COUNT(*) FILTER (WHERE cc.${embeddingColIdent} IS NULL) AS chunks_unembedded
+ FROM content_chunks cc
+ JOIN pages pg ON pg.id = cc.page_id
+ WHERE pg.deleted_at IS NULL
+ GROUP BY pg.source_id
+ ) c ON c.source_id = s.source_id`,
+ [sourceIds],
+ );
+ }
+ const countMap = new Map<string, { pages: number; chunks_total: number; chunks_unembedded: number }>();
+ for (const r of countRows) {
+ countMap.set(r.source_id, {
+ pages: Number(r.pages) || 0,
+ chunks_total: Number(r.chunks_total) || 0,
+ chunks_unembedded: Number(r.chunks_unembedded) || 0,
+ });
+ }
+
+ // v0.41.31: per-source embed-backfill job state. Best-effort — the
+ // minion_jobs table doesn't exist on every brain (a brain that never ran
+ // a worker has the pre-minions schema), and the dashboard must not crash
+ // for that. A failure → empty map → all sources report 0/null.
+ type BackfillRow = {
+ source_id: string | null;
+ queued: string | number;
+ active: string | number;
+ last_completed_at: string | Date | null;
+ };
+ const backfillMap = new Map<string, { queued: number; active: number; last_completed_at: string | null }>();
+ if (sourceIds.length > 0) {
+ try {
+ const backfillRows = await engine.executeRaw<BackfillRow>(
+ `SELECT data->>'sourceId' AS source_id,
+ COUNT(*) FILTER (WHERE status IN ('waiting','delayed','waiting-children'))::int AS queued,
+ COUNT(*) FILTER (WHERE status = 'active')::int AS active,
+ MAX(finished_at) FILTER (WHERE status = 'completed') AS last_completed_at
+ FROM minion_jobs
+ WHERE name = 'embed-backfill' AND data->>'sourceId' = ANY($1::text[])
+ GROUP BY data->>'sourceId'`,
+ [sourceIds],
+ );
+ for (const r of backfillRows) {
+ if (!r.source_id) continue;
+ const last = r.last_completed_at;
+ backfillMap.set(r.source_id, {
+ queued: Number(r.queued) || 0,
+ active: Number(r.active) || 0,
+ last_completed_at: last == null ? null : (last instanceof Date ? last.toISOString() : last),
+ });
+ }
+ } catch {
+ // minion_jobs absent / unreadable → leave backfillMap empty.
+ }
+ }
+
+ const now = Date.now();
+ const out: SyncStatusReportSource[] = sources.map((src) => {
+ const cfgEntry = (src.config || {}) as { syncEnabled?: boolean };
+ const row = sourceMap.get(src.id) || { id: src.id, last_commit: null, last_sync_at: null, newest_content_at: null };
+ const counts = countMap.get(src.id) || { pages: 0, chunks_total: 0, chunks_unembedded: 0 };
+ const lastSyncMs = row.last_sync_at
+ ? (row.last_sync_at instanceof Date ? row.last_sync_at.getTime() : Date.parse(row.last_sync_at))
+ : null;
+ // v0.41.32.0: commit-relative staleness from the stored column — NO git
+ // subprocess (this function backs the remote get_status_snapshot MCP op,
+ // so it must honor the v0.41.27.0 trust boundary). A quiet repo whose
+ // newest commit predates its last sync reports 0; null column → wall-clock.
+ const contentMs = row.newest_content_at
+ ? (row.newest_content_at instanceof Date ? row.newest_content_at.getTime() : Date.parse(row.newest_content_at))
+ : null;
+ const lagSeconds = lagFromContentMs(
+ Number.isFinite(contentMs as number) ? (contentMs as number) : null,
+ lastSyncMs !== null && Number.isFinite(lastSyncMs) ? lastSyncMs : null,
+ now,
+ );
+ const stalenessHours = lagSeconds === null ? null : lagSeconds / 3600;
+ const hoursSinceLastSync = lastSyncMs !== null && Number.isFinite(lastSyncMs)
+ ? Math.round(((now - lastSyncMs) / 3600_000) * 10) / 10
+ : null;
+ let stalenessClass: 'fresh' | 'stale' | 'severe' | 'unknown' = 'unknown';
+ if (stalenessHours !== null) {
+ if (stalenessHours < 24) stalenessClass = 'fresh';
+ else if (stalenessHours < 72) stalenessClass = 'stale';
+ else stalenessClass = 'severe';
+ }
+ const embeddingCoveragePct = counts.chunks_total === 0
+ ? 100
+ : Math.round(((counts.chunks_total - counts.chunks_unembedded) / counts.chunks_total) * 1000) / 10;
+ const lastSyncIso = row.last_sync_at
+ ? (row.last_sync_at instanceof Date ? row.last_sync_at.toISOString() : row.last_sync_at)
+ : null;
+ return {
+ source_id: src.id,
+ name: src.name,
+ local_path: src.local_path,
+ sync_enabled: cfgEntry.syncEnabled !== false,
+ last_sync_at: lastSyncIso,
+ hours_since_last_sync: hoursSinceLastSync,
+ staleness_hours: stalenessHours === null ? null : Math.round(stalenessHours * 10) / 10,
+ staleness_class: stalenessClass,
+ last_commit: row.last_commit,
+ pages: counts.pages,
+ chunks_total: counts.chunks_total,
+ chunks_unembedded: counts.chunks_unembedded,
+ embedding_coverage_pct: embeddingCoveragePct,
+ backfill_queued: backfillMap.get(src.id)?.queued ?? 0,
+ backfill_active: backfillMap.get(src.id)?.active ?? 0,
+ backfill_last_completed_at: backfillMap.get(src.id)?.last_completed_at ?? null,
+ };
+ });
+
+ // Unacknowledged sync failures — brain-global (the JSONL log isn't
+ // per-source). v0.40.4 TODO will source-scope this. Best-effort:
+ // missing file / parse error returns 0, doesn't throw the dashboard.
+ let unackedCount = 0;
+ try {
+ unackedCount = unacknowledgedSyncFailures().length;
+ } catch {
+ unackedCount = 0;
+ }
+
+ return {
+ schema_version: 1,
+ generated_at: new Date().toISOString(),
+ sources: out,
+ unacknowledged_failures: unackedCount,
+ embedding_column: resolved.name,
+ };
+}
+
+/**
+ * v0.40.3.0 — render a `SyncStatusReport` as a human-readable table.
+ *
+ * `sink` defaults to `process.stdout` so the bare `gbrain sources status`
+ * invocation writes its table to stdout. `--json` callers don't use
+ * this — they emit `JSON.stringify(report)` to stdout directly.
+ */
+export function printSyncStatusReport(
+ report: SyncStatusReport,
+ sink: NodeJS.WriteStream = process.stdout,
+): void {
+ const write = (line: string) => sink.write(line + '\n');
+ write(`\nSync status — generated ${report.generated_at}`);
+ write(`Embedding column: ${report.embedding_column}\n`);
+ if (report.sources.length === 0) {
+ write(' (no sources registered)');
+ return;
+ }
+ const headers = ['SOURCE', 'STATE', 'STALENESS', 'PAGES', 'EMBEDDED', 'BACKFILL', 'LAST SYNC'];
+ const rows = report.sources.map((s) => {
+ const stale = s.staleness_hours === null
+ ? 'never'
+ : `${s.staleness_hours.toFixed(1)}h`;
+ const stateBits: string[] = [];
+ if (!s.sync_enabled) stateBits.push('disabled');
+ stateBits.push(s.staleness_class);
+ // BACKFILL: active beats queued beats idle for the at-a-glance cell.
+ const backfill = s.backfill_active > 0
+ ? `active(${s.backfill_active})`
+ : s.backfill_queued > 0
+ ? `queued(${s.backfill_queued})`
+ : 'idle';
+ return [
+ s.name,
+ stateBits.join(','),
+ stale,
+ String(s.pages),
+ `${s.embedding_coverage_pct}%`,
+ backfill,
+ s.last_sync_at ?? '(never)',
+ ];
+ });
+ const widths = headers.map((h, i) =>
+ Math.max(h.length, ...rows.map((r) => r[i].length)),
+ );
+ // Numeric columns (STALENESS=2, PAGES=3, EMBEDDED=4) right-pad-left so
+ // digits align cleanly. Text columns (incl. BACKFILL=5) left-pad-right
+ // per the existing `sources list` convention.
+ const NUMERIC_COLS = new Set([2, 3, 4]);
+ const fmt = (cells: string[]) =>
+ cells.map((c, i) => (NUMERIC_COLS.has(i) ? c.padStart(widths[i]) : c.padEnd(widths[i]))).join(' ');
+ write(fmt(headers));
+ write(fmt(widths.map((w) => '-'.repeat(w))));
+ for (const r of rows) write(fmt(r));
+ write(`\nUnacknowledged sync failures (brain-wide): ${report.unacknowledged_failures}`);
+ const severe = report.sources.filter((s) => s.staleness_class === 'severe').length;
+ if (severe > 0) {
+ write(`WARNING: ${severe} source(s) are SEVERELY stale (>72h). Run \`gbrain sync --all\` to refresh.`);
+ }
+}
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index e370a5ffba..4ed9120b79 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.46.8.0 -->
+<!-- gbrain-template-stamp: 0.46.9.1 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/ai/silent-drop-regression.test.ts b/test/ai/silent-drop-regression.test.ts
index 436c640c11..cf89a4f28c 100644
--- a/test/ai/silent-drop-regression.test.ts
+++ b/test/ai/silent-drop-regression.test.ts
@@ -6,7 +6,7 @@
* different provider. This test ensures all three sites now check
* gateway.isAvailable('embedding') instead of hardcoded OPENAI_API_KEY.
*
- * 1. src/core/operations.ts:237 (put_page handler)
+ * 1. src/core/ops/pages.ts (put_page handler; operations.ts is the façade)
* 2. src/core/search/hybrid.ts:81 (vector search gate)
* 3. src/core/import-file.ts:112 (chunk embedding in import pipeline)
*
@@ -15,17 +15,31 @@
*/
import { test, expect } from 'bun:test';
-import { readFileSync } from 'fs';
-import { resolve } from 'path';
+import { readFileSync, readdirSync } from 'fs';
+import { resolve, join } from 'path';
// Resolve relative to this test file so it works on any machine + in CI.
const REPO_ROOT = resolve(import.meta.dir, '../..');
-const OPS = resolve(REPO_ROOT, 'src/core/operations.ts');
+// The put_page handler lives in the ops domain modules (operations.ts is the
+// assembly façade) — scan the whole ops surface so the negative pin is
+// strictly stronger and a future move can't escape it.
+const OPS_DIR = resolve(REPO_ROOT, 'src/core/ops');
const HYBRID = resolve(REPO_ROOT, 'src/core/search/hybrid.ts');
const IMPORT_FILE = resolve(REPO_ROOT, 'src/core/import-file.ts');
-test('operations.ts put_page does not gate embedding on OPENAI_API_KEY alone', () => {
- const src = readFileSync(OPS, 'utf-8');
+function opsSurface(): string {
+ const files = [
+ resolve(REPO_ROOT, 'src/core/operations.ts'),
+ ...readdirSync(OPS_DIR)
+ .filter((f) => f.endsWith('.ts'))
+ .sort()
+ .map((f) => join(OPS_DIR, f)),
+ ];
+ return files.map((f) => readFileSync(f, 'utf-8')).join('\n');
+}
+
+test('ops surface put_page does not gate embedding on OPENAI_API_KEY alone', () => {
+ const src = opsSurface();
// The forbidden pattern from v0.13
expect(src).not.toMatch(/!\s*process\.env\.OPENAI_API_KEY/);
// The fix MUST reference isAvailable from the gateway
diff --git a/test/brain-score-breakdown.test.ts b/test/brain-score-breakdown.test.ts
index 5eb609c232..0deefbf047 100644
--- a/test/brain-score-breakdown.test.ts
+++ b/test/brain-score-breakdown.test.ts
@@ -10,6 +10,7 @@
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { doctorSource } from './helpers/doctor-source.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
let engine: PGLiteEngine;
@@ -121,7 +122,7 @@ describe('Bug 11 — orphan_pages is "no inbound links"', () => {
describe('Bug 11 — doctor renders brain_score breakdown', () => {
test('doctor source contains brain_score breakdown rendering', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toContain('brain_score');
expect(source).toContain('embed_coverage_score');
expect(source).toContain('link_density_score');
diff --git a/test/doctor-categories.test.ts b/test/doctor-categories.test.ts
index d5d248620e..d84d7d895b 100644
--- a/test/doctor-categories.test.ts
+++ b/test/doctor-categories.test.ts
@@ -15,6 +15,7 @@
import { describe, test, expect, beforeEach } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { doctorSource } from './helpers/doctor-source.ts';
import {
BRAIN_CHECK_NAMES,
SKILL_CHECK_NAMES,
@@ -24,14 +25,14 @@ import {
_resetUnknownCheckWarningsForTest,
} from '../src/core/doctor-categories.ts';
-const DOCTOR_TS_PATH = join(import.meta.dir, '..', 'src', 'commands', 'doctor.ts');
const ONBOARD_CHECKS_TS_PATH = join(import.meta.dir, '..', 'src', 'core', 'onboard', 'checks.ts');
-const CHECK_SOURCE_PATHS = [DOCTOR_TS_PATH, ONBOARD_CHECKS_TS_PATH];
function enumerateCheckNames(): Set<string> {
const names = new Set<string>();
- for (const path of CHECK_SOURCE_PATHS) {
- const source = readFileSync(path, 'utf-8');
+ // doctorSource() spans the whole doctor surface (façade + every peeled
+ // src/commands/doctor/ module) so the name scan can't go blind on a peel.
+ const checkSources = [doctorSource(), readFileSync(ONBOARD_CHECKS_TS_PATH, 'utf-8')];
+ for (const source of checkSources) {
// 1) Inline object-literal form: `{ name: 'foo', ... }`.
for (const m of source.matchAll(/name:\s*['"]([a-z][a-z0-9_]+)['"]/g)) {
names.add(m[1]);
diff --git a/test/doctor-embedding-env-override.test.ts b/test/doctor-embedding-env-override.test.ts
index 5408148afb..b6098fb2cd 100644
--- a/test/doctor-embedding-env-override.test.ts
+++ b/test/doctor-embedding-env-override.test.ts
@@ -11,8 +11,7 @@
// Hermetic: PGLite + withEnv per CLAUDE.md R1/R3/R4.
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
-import { readFileSync } from 'fs';
-import { join } from 'path';
+import { doctorSource } from './helpers/doctor-source.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { buildChecks, doctorReportRemote, type Check } from '../src/commands/doctor.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
@@ -138,10 +137,7 @@ describe('cross-surface parity (source-grep regression guard)', () => {
// Static regression assertion: the helper must be called from BOTH surfaces.
// If a future maintainer removes the call from one surface, this test fails
// pointing at the asymmetry.
- const src = readFileSync(
- join(import.meta.dir, '../src/commands/doctor.ts'),
- 'utf-8',
- );
+ const src = doctorSource();
// The helper is called as `await checkEmbeddingEnvOverride(engine)`
const matches = src.match(/await checkEmbeddingEnvOverride\(engine\)/g) ?? [];
expect(matches.length).toBeGreaterThanOrEqual(2);
diff --git a/test/doctor-frontmatter-partial.test.ts b/test/doctor-frontmatter-partial.test.ts
index 650b16cf3f..38e09bd8d2 100644
--- a/test/doctor-frontmatter-partial.test.ts
+++ b/test/doctor-frontmatter-partial.test.ts
@@ -15,13 +15,9 @@
* codex D4 catch simplification.
*/
import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'fs';
-import { join } from 'path';
+import { doctorSource } from './helpers/doctor-source.ts';
-const DOCTOR_SOURCE = readFileSync(
- join(__dirname, '..', 'src', 'commands', 'doctor.ts'),
- 'utf8',
-);
+const DOCTOR_SOURCE = doctorSource();
describe('doctor frontmatter_integrity — structural rendering (source-grep)', () => {
test('source contains GBRAIN_DOCTOR_FM_TIMEOUT_MS handling', () => {
diff --git a/test/doctor-orphan-ratio.test.ts b/test/doctor-orphan-ratio.test.ts
index cd0089fbd4..f2454ac521 100644
--- a/test/doctor-orphan-ratio.test.ts
+++ b/test/doctor-orphan-ratio.test.ts
@@ -17,6 +17,7 @@ import { runDoctor, type DoctorReport } from '../src/commands/doctor.ts';
import { setCliOptions } from '../src/core/cli-options.ts';
import { runOrphanRatioCheck } from '../src/core/doctor-remote.ts';
import { readFileSync } from 'fs';
+import { doctorSource } from './helpers/doctor-source.ts';
let engine: PGLiteEngine;
let stdoutBuffer: string[];
@@ -242,21 +243,21 @@ describe('runOrphanRatioCheck — thin-client surface (D11)', () => {
describe('cross-surface parity contract', () => {
test('source greps: orphan_ratio check name appears in BOTH local doctor and remote doctor', () => {
- const doctor = readFileSync('src/commands/doctor.ts', 'utf8');
+ const doctor = doctorSource();
const remote = readFileSync('src/core/doctor-remote.ts', 'utf8');
expect(doctor.includes("name: 'orphan_ratio'")).toBe(true);
expect(remote.includes("name: 'orphan_ratio'")).toBe(true);
});
test('source greps: both surfaces reference the same fix command', () => {
- const doctor = readFileSync('src/commands/doctor.ts', 'utf8');
+ const doctor = doctorSource();
const remote = readFileSync('src/core/doctor-remote.ts', 'utf8');
expect(doctor).toContain('gbrain extract links --by-mention');
expect(remote).toContain('gbrain extract links --by-mention');
});
test('source greps: local hint is self-fix; thin-client hint points at operator', () => {
- const doctor = readFileSync('src/commands/doctor.ts', 'utf8');
+ const doctor = doctorSource();
const remote = readFileSync('src/core/doctor-remote.ts', 'utf8');
// Local hint: just the command (user can run it).
expect(doctor).toContain('Run: gbrain extract links --by-mention');
diff --git a/test/doctor-supervisor-singleton-pidfile.test.ts b/test/doctor-supervisor-singleton-pidfile.test.ts
index b6b207e70c..8954f487bd 100644
--- a/test/doctor-supervisor-singleton-pidfile.test.ts
+++ b/test/doctor-supervisor-singleton-pidfile.test.ts
@@ -22,6 +22,7 @@ import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { withEnv } from './helpers/with-env.ts';
+import { doctorSource } from './helpers/doctor-source.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { buildChecks } from '../src/commands/doctor.ts';
@@ -127,7 +128,7 @@ describe('doctor supervisor_singleton — honors the recorded pid_file (custom -
// on the machine running the suite.
describe('doctor supervisor_singleton — pid_file fallback (source-grep)', () => {
test('falls back to DEFAULT_PID_FILE when the started event has no pid_file', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toMatch(
/typeof lastStarted\.pid_file === 'string' && lastStarted\.pid_file\.length > 0\s*\n\s*\? lastStarted\.pid_file\s*\n\s*: DEFAULT_PID_FILE/,
);
diff --git a/test/doctor-volunteer-channels.test.ts b/test/doctor-volunteer-channels.test.ts
index 335a42c76b..286f44b25b 100644
--- a/test/doctor-volunteer-channels.test.ts
+++ b/test/doctor-volunteer-channels.test.ts
@@ -16,6 +16,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'nod
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { checkVolunteerChannels } from '../src/commands/doctor.ts';
+import { doctorSource } from './helpers/doctor-source.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -167,7 +168,7 @@ describe('checkVolunteerChannels', () => {
});
test('wiring pins: the check runs on BOTH doctor paths and serve registers the delivery callback (source greps)', () => {
- const doctorSrc = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'doctor.ts'), 'utf8');
+ const doctorSrc = doctorSource();
// Local path (buildChecks) AND remote path both push the check — the docs
// point local operators at `gbrain doctor`, so remote-only is a doc lie.
const pushes = doctorSrc.match(/checks\.push\(await checkVolunteerChannels\(engine/g) ?? [];
diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.ts
index 0248251b75..f5561ea954 100644
--- a/test/doctor-wedged-queue.test.ts
+++ b/test/doctor-wedged-queue.test.ts
@@ -11,8 +11,7 @@
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
-import { readFileSync } from 'fs';
-import { join } from 'path';
+import { doctorSource } from './helpers/doctor-source.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { computeQueueHealthCheck, computeWedgedQueueCheck } from '../src/commands/doctor.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -172,10 +171,7 @@ describe('Minions-visibility wave — computeQueueHealthCheck structured details
describe('issue #1801 fix #3 — remote queue_health state→status regression', () => {
it('doctor.ts no longer queries the non-existent `state` column', () => {
- const src = readFileSync(
- join(import.meta.dir, '..', 'src', 'commands', 'doctor.ts'),
- 'utf8',
- );
+ const src = doctorSource();
// The column is `status`; the pre-fix `WHERE state = 'active'` errored every
// run and the catch silently returned "No queue activity".
expect(src).not.toContain("state = 'active'");
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index 4df47eda45..822d147919 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -7,6 +7,7 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { withEnv } from './helpers/with-env.ts';
import { logRerankFailure } from '../src/core/rerank-audit.ts';
+import { doctorSource, doctorFileSource } from './helpers/doctor-source.ts';
describe('doctor command', () => {
test('doctor module exports runDoctor', async () => {
@@ -30,8 +31,7 @@ describe('doctor command', () => {
});
test('frontmatter_integrity subcheck added in v0.22.4', async () => {
- const fs = await import('fs');
- const src = fs.readFileSync('src/commands/doctor.ts', 'utf8');
+ const src = doctorSource();
// Subcheck name and call into shared scanner are present.
expect(src).toContain("name: 'frontmatter_integrity'");
expect(src).toContain('scanBrainSources');
@@ -206,7 +206,7 @@ describe('doctor command', () => {
});
test('doctor --fast emits source-specific message when URL present', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// The source-aware message must reference the variable name so users
// know where their URL is coming from.
expect(source).toContain('Skipping DB checks (--fast mode, URL present from');
@@ -218,14 +218,14 @@ describe('doctor command', () => {
// bodies and points users at the standalone `gbrain repair-jsonb` command.
// Detection only; repair lives in src/commands/repair-jsonb.ts.
test('doctor source contains jsonb_integrity and markdown_body_completeness checks', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toContain('jsonb_integrity');
expect(source).toContain('markdown_body_completeness');
expect(source).toContain('gbrain repair-jsonb');
});
test('jsonb_integrity check covers the four JSONB sites fixed in v0.12.1', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toMatch(/table:\s*'pages'.*col:\s*'frontmatter'/);
expect(source).toMatch(/table:\s*'raw_data'.*col:\s*'data'/);
expect(source).toMatch(/table:\s*'ingest_log'.*col:\s*'pages_updated'/);
@@ -328,12 +328,13 @@ describe('doctor command', () => {
// pair exceeds the configurable threshold (facts.absorb_warn_threshold,
// default 10).
test('doctor source contains facts_extraction_health check that iterates sources', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
- expect(source).toContain('facts_extraction_health');
+ const doctorAll = doctorSource();
+ expect(doctorAll).toContain('facts_extraction_health');
// The check must group by source_id, not hardcode 'default'.
- const block = source.slice(
- source.indexOf('// 11a-bis-2. facts_extraction_health'),
- source.indexOf('// 11a-2. effective_date_health'),
+ const doctorTs = doctorFileSource('doctor.ts');
+ const block = doctorTs.slice(
+ doctorTs.indexOf('// 11a-bis-2. facts_extraction_health'),
+ doctorTs.indexOf('// 11a-2. effective_date_health'),
);
expect(block.length).toBeGreaterThan(0);
expect(block).toContain('GROUP BY source_id');
@@ -353,7 +354,7 @@ describe('doctor command', () => {
// These are structural assertions on the source string so a silent revert
// of the severity or the IN-filter removal fails loudly without a live DB.
test('RLS check scans ALL public tables (no hardcoded tablename IN list near the RLS block)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorFileSource('doctor.ts');
const rlsBlock = source.slice(
source.indexOf('// 5. RLS'),
source.indexOf('// 6. Schema version'),
@@ -367,7 +368,7 @@ describe('doctor command', () => {
});
test('RLS check raises status=fail with quoted-identifier remediation SQL', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorFileSource('doctor.ts');
const rlsBlock = source.slice(
source.indexOf('// 5. RLS'),
source.indexOf('// 6. Schema version'),
@@ -381,7 +382,7 @@ describe('doctor command', () => {
});
test('RLS check skips on PGLite (no PostgREST, not applicable)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorFileSource('doctor.ts');
const rlsBlock = source.slice(
source.indexOf('// 5. RLS'),
source.indexOf('// 6. Schema version'),
@@ -391,7 +392,7 @@ describe('doctor command', () => {
});
test('RLS check reads pg_description and recognizes the GBRAIN:RLS_EXEMPT escape hatch', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorFileSource('doctor.ts');
const rlsBlock = source.slice(
source.indexOf('// 5. RLS'),
source.indexOf('// 6. Schema version'),
@@ -407,7 +408,7 @@ describe('doctor command', () => {
// Lives AFTER `// 6. Schema version` so the existing `// 5. RLS` slice
// tests stay intact (codex correction).
test('rls_event_trigger check exists, scoped after schema_version, healthy on (O,A) only', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorFileSource('doctor.ts');
const idx7 = source.indexOf('// 7. RLS event trigger');
const idx8 = source.indexOf('// 8. Embedding health');
expect(idx7).toBeGreaterThan(0);
@@ -436,8 +437,7 @@ describe('doctor command', () => {
// with the canonical `gbrain extract all`. Pin the user-facing copy so a
// future edit can't silently re-regress to a stale verb.
test('graph_coverage hint uses canonical `gbrain extract all`, not removed verbs', async () => {
- const fs = await import('fs');
- const src = fs.readFileSync('src/commands/doctor.ts', 'utf8');
+ const src = doctorSource();
// Canonical form (post-v0.16 single-verb consolidation).
expect(src).toContain('Run: gbrain extract all');
// Stale verb names removed in v0.16 must not return.
@@ -600,23 +600,24 @@ describe('doctor command', () => {
// ─────────────────────────────────────────────────────────────────────────
describe('v0.31.8 — wedge migration force-retry hint (D19)', () => {
test('local doctor source contains wedge detection alongside the existing stuck path', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const doctorAll = doctorSource();
// The existing forward-progress override stays intact. Both branches
// must be present and live next to each other; replacing the override
// with statusForVersion() would re-open stale wedge alerts (codex OV11).
- expect(source).toContain('Forward-progress override');
- expect(source).toContain('partialCount >= 3');
+ expect(doctorAll).toContain('Forward-progress override');
+ expect(doctorAll).toContain('partialCount >= 3');
// Both branches must coexist. Wedged path builds the command list with
// --force-retry; partial path falls back to plain --yes. Order varies
// between the local + remote doctor blocks, so just assert presence.
- expect(source).toContain('WEDGED MIGRATION(s)');
- expect(source).toContain('MINIONS HALF-INSTALLED');
- expect(source).toContain('--force-retry');
- expect(source).toMatch(/MINIONS HALF-INSTALLED[\s\S]{0,400}--yes/);
+ expect(doctorAll).toContain('WEDGED MIGRATION(s)');
+ expect(doctorAll).toContain('MINIONS HALF-INSTALLED');
+ expect(doctorAll).toContain('--force-retry');
+ const doctorTs = doctorFileSource('doctor.ts');
+ expect(doctorTs).toMatch(/MINIONS HALF-INSTALLED[\s\S]{0,400}--yes/);
});
test('wedge detection is local to doctor — no statusForVersion import (D19 anti-regression)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// D19 explicitly chose to extend the existing block in place rather than
// import statusForVersion, because statusForVersion is per-version only
// and doesn't encode the cross-version forward-progress override. If a
@@ -627,7 +628,7 @@ describe('v0.31.8 — wedge migration force-retry hint (D19)', () => {
});
test('multiple wedged versions chain force-retry calls with &&', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// The local doctor block uses `.join(' && ')` so multiple wedged
// versions render as a single copy-pasteable command line. Match BOTH
// engine.ts blocks (local doctor + remote doctor) — the regex finds
@@ -636,15 +637,18 @@ describe('v0.31.8 — wedge migration force-retry hint (D19)', () => {
});
test('remote doctor (doctorReportRemote) also emits the force-retry hint (D14)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ // doctorReportRemote was peeled into its own module (containment
+ // sprint); the positional guard follows the code to its new file per
+ // the doctorFileSource contract.
+ const source = doctorFileSource('doctor/report-remote.ts');
// Check that the wedge detection is duplicated in the remote doctor
// path so thin-client operators see it. Find the doctorReportRemote
- // function span and verify the wedge-hint code lives inside it.
+ // function span and verify the wedge-hint code lives inside it
+ // (doctorReportRemote is the last declaration in its file, so
+ // slice-to-end covers exactly the function span).
const remoteStart = source.indexOf('export async function doctorReportRemote(');
expect(remoteStart).toBeGreaterThan(0);
- const remoteEnd = source.indexOf('\nexport async function runDoctor(', remoteStart);
- expect(remoteEnd).toBeGreaterThan(remoteStart);
- const remoteBlock = source.slice(remoteStart, remoteEnd);
+ const remoteBlock = source.slice(remoteStart);
expect(remoteBlock).toContain('--force-retry');
expect(remoteBlock).toContain('partialCount >= 3');
expect(remoteBlock).toMatch(/WEDGED MIGRATION\(s\) on brain host/);
@@ -1215,7 +1219,7 @@ describe('v0.41.32.0 — commit-relative staleness', () => {
// status` (jobs.ts:805) cannot drift: both go through `summarizeCrashes`.
describe('supervisor crash classifier wiring (v0.35.x)', () => {
test('doctor.ts uses summarizeCrashes — no ad-hoc worker_exited filter', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// Wired to the shared helper.
expect(source).toContain('summarizeCrashes');
// The pre-fix ad-hoc filter pattern must NOT survive. The exact buggy
@@ -1227,7 +1231,7 @@ describe('supervisor crash classifier wiring (v0.35.x)', () => {
});
test('doctor.ts warn threshold dropped from >3 to >=1', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// The pre-fix `crashes24h > 3` threshold made sense only because the
// counter was over-counting clean exits. Under accurate counts, any real
// crash is signal — threshold lands at `>=1`.
@@ -1237,7 +1241,7 @@ describe('supervisor crash classifier wiring (v0.35.x)', () => {
});
test('doctor.ts ok + warn messages include per-cause breakdown and clean_exits_24h', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// Per-cause breakdown surfaces qualitative signal (oom vs runtime vs unknown
// vs legacy) so operators can triage without grep'ing JSONL.
expect(source).toContain('runtime=');
@@ -1269,25 +1273,25 @@ describe('supervisor crash classifier wiring (v0.35.x)', () => {
// signal that prefix-expansion in resolveEntitySlug is missing a case.
describe('stub_guard_24h check (v0.34.5)', () => {
test('doctor source defines the stub_guard_24h check', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toContain("name: 'stub_guard_24h'");
});
test('WARN threshold is >10 hits/24h', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// The WARN gate must fire above 10, not at or below — that's the threshold
// the v0.36 sunset criterion is calibrated against.
expect(source).toMatch(/events\.length\s*>\s*10/);
});
test('fix hint points operators at the audit log', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toContain('stub-guard-*.jsonl');
expect(source).toContain('prefix-expansion in resolveEntitySlug');
});
test('check reads via the dual-week-aware reader (NOT supervisor-audit pattern)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// The point of the divergence from supervisor-audit.ts is this reader
// reads both current and previous ISO-week files. If the check ever
// gets re-pointed at readSupervisorEvents-style single-week, this test
@@ -1297,7 +1301,7 @@ describe('stub_guard_24h check (v0.34.5)', () => {
});
test('zero hits emits no check (keeps doctor output clean on healthy brains)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// The implementation falls through silently when events.length === 0.
// Codify this in source-grep form so a future refactor doesn't add an
// "ok: 0 hits" line that pollutes every doctor run.
@@ -1402,7 +1406,7 @@ describe('v0.40.4 — graph_signals_coverage check', () => {
});
test('check is wired into runDoctor (source-grep)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
// Local engine path.
expect(source).toMatch(/await checkGraphSignalsCoverage\(engine\)/);
// Remote/JSON path heartbeat.
@@ -1552,9 +1556,7 @@ describe('issue #972 — link_resolution_opportunity check', () => {
});
test('check is wired into runDoctor AND doctorReportRemote (source-grep)', async () => {
- const source = await Bun.file(
- new URL('../src/commands/doctor.ts', import.meta.url),
- ).text();
+ const source = doctorSource();
// Local buildChecks path.
expect(source).toMatch(/await checkLinkResolutionOpportunity\(engine, progress\)/);
// Thin-client doctorReportRemote path.
@@ -1570,7 +1572,7 @@ describe('issue #972 — link_resolution_opportunity check', () => {
describe('v0.42 (#1699) — quarantined_pages + flagged_pages checks', () => {
test('both checks are wired into buildChecks (source-grep)', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toContain("progress.heartbeat('quarantined_pages')");
expect(source).toContain("progress.heartbeat('flagged_pages')");
// quarantine HIDES (JSONB existence scan), content_flag WARNS.
diff --git a/test/embedding-dim-check-facts.test.ts b/test/embedding-dim-check-facts.test.ts
index 8c56527297..bdd60eb483 100644
--- a/test/embedding-dim-check-facts.test.ts
+++ b/test/embedding-dim-check-facts.test.ts
@@ -24,6 +24,7 @@ import {
import type { BrainEngine } from '../src/core/engine.ts';
import { readFileSync } from 'fs';
import { resolve } from 'path';
+import { doctorSource, doctorFileSource } from './helpers/doctor-source.ts';
/**
* Synthetic engine satisfying the slice of BrainEngine these helpers
@@ -205,32 +206,34 @@ describe('assertFactsEmbeddingDimMatchesConfig', () => {
});
describe('doctor checkFactsEmbeddingWidthConsistency wiring (T6)', () => {
- const DOC_PATH = resolve(import.meta.dir, '..', 'src/commands/doctor.ts');
- const DOC_SRC = readFileSync(DOC_PATH, 'utf-8');
+ // Containment greps read the whole doctor surface; the ordering assertion
+ // stays pinned to the single file that holds both call sites.
+ const DOC_ALL = doctorSource();
+ const DOC_TS = doctorFileSource('doctor.ts');
test('doctor.ts exports the new check function', () => {
- expect(DOC_SRC).toMatch(
+ expect(DOC_ALL).toMatch(
/export\s+async\s+function\s+checkFactsEmbeddingWidthConsistency/,
);
});
test('check is registered in runDoctor alongside the content_chunks check', () => {
- expect(DOC_SRC).toMatch(/checkFactsEmbeddingWidthConsistency\(engine\)/);
+ expect(DOC_ALL).toMatch(/checkFactsEmbeddingWidthConsistency\(engine\)/);
// Must appear AFTER the content_chunks check so a single
// mismatch surface ordering is stable in the JSON envelope.
- const widthIdx = DOC_SRC.indexOf('checkEmbeddingWidthConsistency(engine)');
- const factsIdx = DOC_SRC.indexOf('checkFactsEmbeddingWidthConsistency(engine)');
+ const widthIdx = DOC_TS.indexOf('checkEmbeddingWidthConsistency(engine)');
+ const factsIdx = DOC_TS.indexOf('checkFactsEmbeddingWidthConsistency(engine)');
expect(widthIdx).toBeGreaterThan(0);
expect(factsIdx).toBeGreaterThan(0);
expect(widthIdx).toBeLessThan(factsIdx);
});
test('doctor check uses readFactsEmbeddingDim from the shared helper', () => {
- expect(DOC_SRC).toMatch(/readFactsEmbeddingDim/);
+ expect(DOC_ALL).toMatch(/readFactsEmbeddingDim/);
});
test('doctor check uses buildFactsAlterRecipe (NOT a hand-rolled ALTER string)', () => {
- expect(DOC_SRC).toMatch(/buildFactsAlterRecipe/);
+ expect(DOC_ALL).toMatch(/buildFactsAlterRecipe/);
});
});
diff --git a/test/exit-classification.test.ts b/test/exit-classification.test.ts
index b71ccabf44..be6906a433 100644
--- a/test/exit-classification.test.ts
+++ b/test/exit-classification.test.ts
@@ -2,6 +2,15 @@ import { describe, it, expect } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { classifyWorkerExit } from '../src/core/minions/exit-classification.ts';
+import { doctorSource } from './helpers/doctor-source.ts';
+
+// doctor.ts is being peeled into src/commands/doctor/ modules — containment
+// greps against the doctor site must read the whole doctor surface so a peel
+// can't silently move the target out of the guard's sight.
+const readSiteSource = (path: string): string =>
+ path === 'src/commands/doctor.ts'
+ ? doctorSource()
+ : readFileSync(join(import.meta.dir, '..', path), 'utf8');
describe('classifyWorkerExit', () => {
it('code=0 → clean_exit', () => {
@@ -47,21 +56,21 @@ describe('consumer wire-up — helper used by all 3 sites (no inline filters lef
for (const site of SITES) {
it(`${site.label} uses a shared classifier helper (${site.helper})`, () => {
- const source = readFileSync(join(import.meta.dir, '..', site.path), 'utf8');
+ const source = readSiteSource(site.path);
// Helper is either imported by name (top-level) or via dynamic import.
const helperRe = new RegExp(`\\b${site.helper}\\b`);
expect(source).toMatch(helperRe);
});
it(`${site.label} calls ${site.helper} at least once`, () => {
- const source = readFileSync(join(import.meta.dir, '..', site.path), 'utf8');
+ const source = readSiteSource(site.path);
const callRe = new RegExp(`\\b${site.helper}\\s*\\(`);
expect(source).toMatch(callRe);
});
}
it('doctor.ts no longer has the inline `code !== 0 && code !== undefined` filter', () => {
- const source = readFileSync(join(import.meta.dir, '..', 'src/commands/doctor.ts'), 'utf8');
+ const source = doctorSource();
// The pre-T7 inline filter; if this regex matches, the refactor leaked back.
expect(source).not.toMatch(/code !== 0\s*&&\s*\(?\s*\w+\s+as\s+any\s*\)?\.\s*code !== undefined/);
});
diff --git a/test/fixtures/guards/check-module-size.sh/bad/scripts/module-size-limits.tsv b/test/fixtures/guards/check-module-size.sh/bad/scripts/module-size-limits.tsv
new file mode 100644
index 0000000000..8a89e70927
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/bad/scripts/module-size-limits.tsv
@@ -0,0 +1,2 @@
+src/big.ts 5 ratchet fixture: grew past ceiling
+src/migrate-like.ts 3 region-exempt fixture: logic grew outside the array
diff --git a/test/fixtures/guards/check-module-size.sh/bad/src/big.ts b/test/fixtures/guards/check-module-size.sh/bad/src/big.ts
new file mode 100644
index 0000000000..89da6af44f
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/bad/src/big.ts
@@ -0,0 +1,10 @@
+export const line1 = 1;
+export const line2 = 2;
+export const line3 = 3;
+export const line4 = 4;
+export const line5 = 5;
+export const line6 = 6;
+export const line7 = 7;
+export const line8 = 8;
+export const line9 = 9;
+export const line10 = 10;
diff --git a/test/fixtures/guards/check-module-size.sh/bad/src/migrate-like.ts b/test/fixtures/guards/check-module-size.sh/bad/src/migrate-like.ts
new file mode 100644
index 0000000000..c4128277bd
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/bad/src/migrate-like.ts
@@ -0,0 +1,9 @@
+export const MIGRATIONS: unknown[] = [
+ { version: 2, name: 'a' },
+ { version: 3, name: 'b' },
+ { version: 4, name: 'c' },
+];
+export function runnerLogicOne() { return 1; }
+export function runnerLogicTwo() { return 1; }
+export function runnerLogicThree() { return 1; }
+export function runnerLogicFour() { return 1; }
diff --git a/test/fixtures/guards/check-module-size.sh/bad/src/tiny.ts b/test/fixtures/guards/check-module-size.sh/bad/src/tiny.ts
new file mode 100644
index 0000000000..6396850612
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/bad/src/tiny.ts
@@ -0,0 +1 @@
+export const tiny = 1;
diff --git a/test/fixtures/guards/check-module-size.sh/good/scripts/module-size-limits.tsv b/test/fixtures/guards/check-module-size.sh/good/scripts/module-size-limits.tsv
new file mode 100644
index 0000000000..9d435b15e3
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/good/scripts/module-size-limits.tsv
@@ -0,0 +1,2 @@
+src/big.ts 12 ratchet fixture: within ceiling
+src/migrate-like.ts 6 region-exempt fixture: array grows freely
diff --git a/test/fixtures/guards/check-module-size.sh/good/src/big.ts b/test/fixtures/guards/check-module-size.sh/good/src/big.ts
new file mode 100644
index 0000000000..89da6af44f
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/good/src/big.ts
@@ -0,0 +1,10 @@
+export const line1 = 1;
+export const line2 = 2;
+export const line3 = 3;
+export const line4 = 4;
+export const line5 = 5;
+export const line6 = 6;
+export const line7 = 7;
+export const line8 = 8;
+export const line9 = 9;
+export const line10 = 10;
diff --git a/test/fixtures/guards/check-module-size.sh/good/src/migrate-like.ts b/test/fixtures/guards/check-module-size.sh/good/src/migrate-like.ts
new file mode 100644
index 0000000000..0369ff1151
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/good/src/migrate-like.ts
@@ -0,0 +1,11 @@
+export const MIGRATIONS: unknown[] = [
+ { version: 2, name: 'a' },
+ { version: 3, name: 'b' },
+ { version: 4, name: 'c' },
+ { version: 5, name: 'd' },
+ { version: 6, name: 'e' },
+ { version: 7, name: 'f' },
+ { version: 8, name: 'g' },
+ { version: 9, name: 'h' },
+];
+export function runnerLogic() { return 1; }
diff --git a/test/fixtures/guards/check-module-size.sh/good/src/tiny.ts b/test/fixtures/guards/check-module-size.sh/good/src/tiny.ts
new file mode 100644
index 0000000000..6396850612
--- /dev/null
+++ b/test/fixtures/guards/check-module-size.sh/good/src/tiny.ts
@@ -0,0 +1 @@
+export const tiny = 1;
diff --git a/test/helpers/doctor-source.ts b/test/helpers/doctor-source.ts
new file mode 100644
index 0000000000..7c0fb6d1d8
--- /dev/null
+++ b/test/helpers/doctor-source.ts
@@ -0,0 +1,60 @@
+/**
+ * Shared source-text loader for doctor structural guards.
+ *
+ * doctor.ts is being peeled into src/commands/doctor/ modules (containment
+ * sprint). Guards that assert a string EXISTS somewhere in the doctor
+ * implementation must read the whole doctor surface — the façade file plus
+ * every extracted module — or a peel silently moves their target out of
+ * sight and the guard rots into a permanently-green no-op.
+ *
+ * Two loaders, two guard classes:
+ * - doctorSource(): concatenation of src/commands/doctor.ts + every
+ * src/commands/doctor/**\/*.ts, deterministic order (façade first, then
+ * sorted module paths). For CONTAINMENT assertions (toContain / toMatch
+ * with no ordering semantics). File boundaries are marked so a regex
+ * cannot accidentally span two files.
+ * - doctorFileSource(rel): one specific file under the doctor surface, for
+ * POSITIONAL assertions (indexOf ordering, slice windows) — concatenation
+ * would let those match across file boundaries, which is weaker than the
+ * guard intends. Callers name the file that holds the code post-peel.
+ */
+import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
+import { join } from 'node:path';
+
+const REPO_ROOT = join(import.meta.dir, '..', '..');
+const DOCTOR_FACADE = join(REPO_ROOT, 'src', 'commands', 'doctor.ts');
+const DOCTOR_DIR = join(REPO_ROOT, 'src', 'commands', 'doctor');
+
+/** A separator no plausible TS source contains, so cross-file regex matches fail loudly. */
+const FILE_BOUNDARY = '\n /* __doctor-source-file-boundary__ */ \n';
+
+function listDoctorModules(dir: string): string[] {
+ if (!existsSync(dir)) return [];
+ const out: string[] = [];
+ for (const entry of readdirSync(dir).sort()) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) out.push(...listDoctorModules(full));
+ else if (entry.endsWith('.ts')) out.push(full);
+ }
+ return out;
+}
+
+/** Every file on the doctor surface, façade first, then sorted module paths. */
+export function doctorSourceFiles(): string[] {
+ return [DOCTOR_FACADE, ...listDoctorModules(DOCTOR_DIR)];
+}
+
+/** Concatenated doctor surface for containment assertions. */
+export function doctorSource(): string {
+ return doctorSourceFiles()
+ .map((f) => readFileSync(f, 'utf-8'))
+ .join(FILE_BOUNDARY);
+}
+
+/**
+ * One file of the doctor surface for positional assertions.
+ * @param rel path relative to src/commands/ — e.g. 'doctor.ts' or 'doctor/checks/calibration.ts'
+ */
+export function doctorFileSource(rel: string): string {
+ return readFileSync(join(REPO_ROOT, 'src', 'commands', rel), 'utf-8');
+}
diff --git a/test/resolver.test.ts b/test/resolver.test.ts
index af6dc964c3..7c0d62a83a 100644
--- a/test/resolver.test.ts
+++ b/test/resolver.test.ts
@@ -3,10 +3,10 @@ import { readFileSync, existsSync, readdirSync, statSync } from "fs";
import { join } from "path";
import { checkResolvable } from "../src/core/check-resolvable.ts";
import { PROTECTED_JOB_NAMES } from "../src/core/minions/protected-names.ts";
+import { operations } from "../src/core/operations.ts";
const SKILLS_DIR = join(import.meta.dir, "..", "skills");
const RESOLVER_PATH = join(SKILLS_DIR, "RESOLVER.md");
-const OPERATIONS_PATH = join(import.meta.dir, "..", "src", "core", "operations.ts");
describe("RESOLVER.md", () => {
test("exists", () => {
@@ -143,11 +143,7 @@ describe("RESOLVER.md trigger round-trip (D5/C)", () => {
// bugs where docs reference handler names that don't exist (e.g., the
// `name="research"` / `name="orchestrate"` bug from PR #381 pre-reframe).
describe("Skill example-name validator (D13)", () => {
- const opNames: string[] = (() => {
- if (!existsSync(OPERATIONS_PATH)) return [];
- const content = readFileSync(OPERATIONS_PATH, "utf-8");
- return Array.from(content.matchAll(/^\s+name:\s*'([a-z_]+)',/gm)).map(m => m[1]);
- })();
+ const opNames: string[] = operations.map((op) => op.name);
const knownNames = new Set<string>([...opNames, ...PROTECTED_JOB_NAMES]);
diff --git a/test/scripts/check-engine-dynamic-import.test.ts b/test/scripts/check-engine-dynamic-import.test.ts
index 60ecb664d4..36452e6e16 100644
--- a/test/scripts/check-engine-dynamic-import.test.ts
+++ b/test/scripts/check-engine-dynamic-import.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, setDefaultTimeout } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
@@ -23,6 +23,23 @@ function fixture(name: string, content: string): string {
return path;
}
+/**
+ * The guard's default scan set = the 3 engine-live façades PLUS every .ts
+ * file peeled into src/core/{pglite,postgres}-engine/ (the guard resolves its
+ * ROOT from its own script path, so the count always reflects the REAL repo
+ * regardless of cwd). Derived, not hardcoded, so adding an engine module
+ * doesn't break this test.
+ */
+function expectedDefaultScanCount(): number {
+ let count = 3;
+ for (const dir of ['src/core/pglite-engine', 'src/core/postgres-engine']) {
+ const full = join(REPO_ROOT, dir);
+ if (!existsSync(full)) continue;
+ count += readdirSync(full).filter((f) => f.endsWith('.ts')).length;
+ }
+ return count;
+}
+
function runGuard(files: string[] = [], cwd = REPO_ROOT) {
const result = spawnSync(BASH, [GUARD, ...files], {
cwd,
@@ -286,7 +303,9 @@ describe('check-engine-dynamic-import.sh', () => {
const result = runGuard([], foreign);
expect(result.code).toBe(0);
- expect(result.stdout).toContain('check-engine-dynamic-import: ok (3 file(s) scanned)');
+ expect(result.stdout).toContain(
+ `check-engine-dynamic-import: ok (${expectedDefaultScanCount()} file(s) scanned)`,
+ );
}, 30_000);
it('still catches a violation in CRLF input', () => {
@@ -299,7 +318,9 @@ describe('check-engine-dynamic-import.sh', () => {
it('passes on the reconciled repository sources', () => {
const result = runGuard();
expect(result.code).toBe(0);
- expect(result.stdout).toContain('check-engine-dynamic-import: ok (3 file(s) scanned)');
+ expect(result.stdout).toContain(
+ `check-engine-dynamic-import: ok (${expectedDefaultScanCount()} file(s) scanned)`,
+ );
}, 30_000);
});
diff --git a/test/scripts/check-module-size.test.ts b/test/scripts/check-module-size.test.ts
new file mode 100644
index 0000000000..fd8d287b45
--- /dev/null
+++ b/test/scripts/check-module-size.test.ts
@@ -0,0 +1,141 @@
+/**
+ * Failing-side proof for every check-module-size.sh rule. The guard-self-test
+ * fixtures cover rule 1 (growth) in both policies; these tests drive rules
+ * 2-4 and the unknown-policy arm through GBRAIN_GUARD_ROOT temp trees so no
+ * rule can rot into a permanently-green no-op — the exact failure class the
+ * module-size ratchet exists to kill.
+ */
+import { describe, test, expect, afterEach } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { spawnSync } from 'node:child_process';
+
+const REPO_ROOT = resolve(import.meta.dir, '..', '..');
+const GUARD = join(REPO_ROOT, 'scripts', 'check-module-size.sh');
+const tempDirs: string[] = [];
+
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function makeTree(tsvRows: string[], files: Record<string, number>): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-module-size-'));
+ tempDirs.push(root);
+ mkdirSync(join(root, 'scripts'), { recursive: true });
+ writeFileSync(join(root, 'scripts', 'module-size-limits.tsv'), tsvRows.join('\n') + '\n');
+ for (const [rel, lines] of Object.entries(files)) {
+ const full = join(root, rel);
+ mkdirSync(join(full, '..'), { recursive: true });
+ writeFileSync(full, Array.from({ length: lines }, (_, i) => `export const l${i} = ${i};`).join('\n') + '\n');
+ }
+ return root;
+}
+
+/** Like makeTree but with verbatim file content (region-exempt fixtures). */
+function makeTreeWithContent(tsvRows: string[], files: Record<string, string>): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-module-size-'));
+ tempDirs.push(root);
+ mkdirSync(join(root, 'scripts'), { recursive: true });
+ writeFileSync(join(root, 'scripts', 'module-size-limits.tsv'), tsvRows.join('\n') + '\n');
+ for (const [rel, content] of Object.entries(files)) {
+ const full = join(root, rel);
+ mkdirSync(join(full, '..'), { recursive: true });
+ writeFileSync(full, content);
+ }
+ return root;
+}
+
+function runGuard(root: string, env: Record<string, string> = {}) {
+ const res = spawnSync('bash', [GUARD], {
+ encoding: 'utf8',
+ env: { ...process.env, GBRAIN_GUARD_ROOT: root, ...env },
+ timeout: 30_000,
+ });
+ return { code: res.status ?? -1, out: `${res.stdout}\n${res.stderr}` };
+}
+
+describe('check-module-size.sh rule-by-rule failing sides', () => {
+ test('rule 2: stale ceiling after a shrink fails with the exact lower-to value', () => {
+ const root = makeTree(['src/small.ts\t500\tratchet\tfixture'], { 'src/small.ts': 10 });
+ const r = runGuard(root);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('shrank to 10');
+ expect(r.out).toContain('Lower the ceiling');
+ });
+
+ test('rule 2 slack: within the slack window passes', () => {
+ const root = makeTree(['src/small.ts\t40\tratchet\tfixture'], { 'src/small.ts': 10 });
+ const r = runGuard(root, { GBRAIN_MODULE_SIZE_SLACK: '50' });
+ expect(r.code).toBe(0);
+ });
+
+ test('rule 3: a TSV row for a deleted file fails with remove-the-row', () => {
+ const root = makeTree(['src/ghost.ts\t100\tratchet\tfixture'], {});
+ const r = runGuard(root);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('does not exist');
+ expect(r.out).toContain('remove the row');
+ });
+
+ test('rule 4: an unlisted src file over the cap fails; under the cap passes', () => {
+ const over = makeTree([], { 'src/unlisted.ts': 30 });
+ const rOver = runGuard(over, { GBRAIN_MODULE_SIZE_NEWFILE_CAP: '20' });
+ expect(rOver.code).toBe(1);
+ expect(rOver.out).toContain('over the 20 cap for files not listed');
+
+ const under = makeTree([], { 'src/unlisted.ts': 10 });
+ expect(runGuard(under, { GBRAIN_MODULE_SIZE_NEWFILE_CAP: '20' }).code).toBe(0);
+ });
+
+ test('unknown policy fails loudly instead of skipping the row', () => {
+ const root = makeTree(['src/x.ts\t100\tfreeform\tfixture'], { 'src/x.ts': 10 });
+ const r = runGuard(root);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain("unknown policy 'freeform'");
+ });
+
+ test('region-exempt: a spoof-named const (MIGRATIONS_ANYTHING) does not open the region', () => {
+ // 23 total lines; 21 sit inside a region opened by a SPOOF-named const.
+ // A loose prefix match would exempt them (measured 2 → pass); the
+ // tightened opener (`export const MIGRATIONS` + ':', ' ', or '=')
+ // measures all 23 lines → growth FAIL against the 5-line ceiling.
+ const content =
+ [
+ 'export const MIGRATIONS_ANYTHING = [',
+ ...Array.from({ length: 20 }, (_, i) => ` { version: ${i} },`),
+ '];',
+ 'export function runnerLogic() { return 1; }',
+ ].join('\n') + '\n';
+ const root = makeTreeWithContent(['src/spoof.ts\t5\tregion-exempt\tfixture'], { 'src/spoof.ts': content });
+ const r = runGuard(root);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('over its 5 ceiling');
+ });
+
+ test('region-exempt: an unclosed MIGRATIONS region fails loudly instead of exempting the file tail', () => {
+ // Region opens (the `= [` form) and never closes — EOF while in_region.
+ // Ceiling 100 is generous on purpose: only the unclosed-region check can
+ // produce this failure.
+ const content =
+ ['export const MIGRATIONS = [', ' { version: 1 },', ' { version: 2 },', ' { version: 3 },'].join('\n') + '\n';
+ const root = makeTreeWithContent(['src/unclosed.ts\t100\tregion-exempt\tfixture'], {
+ 'src/unclosed.ts': content,
+ });
+ const r = runGuard(root);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('unclosed MIGRATIONS region');
+ });
+
+ test('all violations are accumulated, not first-fail', () => {
+ const root = makeTree(
+ ['src/ghost.ts\t100\tratchet\tfixture', 'src/big.ts\t5\tratchet\tfixture'],
+ { 'src/big.ts': 30, 'src/unlisted.ts': 30 },
+ );
+ const r = runGuard(root, { GBRAIN_MODULE_SIZE_NEWFILE_CAP: '20' });
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('does not exist'); // rule 3
+ expect(r.out).toContain('over its 5 ceiling'); // rule 1
+ expect(r.out).toContain('for files not listed'); // rule 4 (src/unlisted.ts over the 20 cap)
+ });
+});
diff --git a/test/scripts/classify-tests.test.ts b/test/scripts/classify-tests.test.ts
new file mode 100644
index 0000000000..2d25554fc6
--- /dev/null
+++ b/test/scripts/classify-tests.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Unit tests for the test-intent classifier (scripts/classify-tests.ts).
+ * classifyFile is pure (path + content in, rows out) so every detector and
+ * attribution rule gets a direct fixture — no filesystem needed.
+ */
+import { describe, test, expect } from 'bun:test';
+import { classifyFile } from '../../scripts/classify-tests.ts';
+
+describe('classify-tests detectors', () => {
+ test('repo-anchored readFileSync binding attributes the referencing suite', () => {
+ const src = [
+ "import { readFileSync } from 'node:fs';",
+ "const SRC = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'doctor.ts'), 'utf-8');",
+ "describe('structural pin', () => {",
+ " test('contains marker', () => { expect(SRC).toContain('x'); });",
+ " test('other', () => { expect(SRC).toMatch(/y/); });",
+ '});',
+ "describe('behavioral', () => {",
+ " test('runs code', () => { expect(1).toBe(1); });",
+ '});',
+ ].join('\n');
+ const res = classifyFile('test/fake.test.ts', src);
+ expect(res.rows).toHaveLength(1);
+ expect(res.rows[0].suite).toBe('structural pin');
+ expect(res.rows[0].cases).toBe(2);
+ expect(res.rows[0].detector).toBe('readFileSync');
+ expect(res.unknown).toBe(false);
+ });
+
+ test('tmpdir reads are behavioral, not structural', () => {
+ const src = [
+ "const out = readFileSync(join(tmpdir, 'AGENTS.md'), 'utf-8');",
+ "describe('scaffolder output', () => {",
+ " test('emits agents md', () => { expect(out).toContain('gbrain'); });",
+ '});',
+ ].join('\n');
+ expect(classifyFile('test/fake.test.ts', src).rows).toHaveLength(0);
+ });
+
+ test('Bun.file reader on src/ is structural', () => {
+ const src = [
+ "const text = await Bun.file(new URL('../src/core/migrate.ts', import.meta.url)).text();",
+ "describe('migrate shape', () => {",
+ " test('pin', () => { expect(text).toContain('MIGRATIONS'); });",
+ '});',
+ ].join('\n');
+ const rows = classifyFile('test/fake.test.ts', src).rows;
+ expect(rows).toHaveLength(1);
+ expect(rows[0].detector).toBe('bun-file');
+ });
+
+ test('exec grep over src/ is structural; exec of product CLI is not', () => {
+ const grep = [
+ "describe('grep guard', () => {",
+ " test('scan', () => {",
+ " const out = execSync(`grep -rn 'pattern' src/ --include=*.ts`);",
+ ' });',
+ '});',
+ ].join('\n');
+ expect(classifyFile('test/fake.test.ts', grep).rows).toHaveLength(1);
+ const cli = [
+ "describe('cli run', () => {",
+ " test('runs', () => {",
+ " const out = execSync('bun run src/cli.ts --version', { cwd: tmpDir });",
+ ' });',
+ '});',
+ ].join('\n');
+ expect(classifyFile('test/fake.test.ts', cli).rows).toHaveLength(0);
+ });
+
+ test('doctor-source helper marks the suite structural', () => {
+ const src = [
+ "import { doctorSource } from './helpers/doctor-source.ts';",
+ "describe('doctor pin', () => {",
+ " test('has check', () => { expect(doctorSource()).toContain('checkX'); });",
+ '});',
+ ].join('\n');
+ const rows = classifyFile('test/fake.test.ts', src).rows;
+ expect(rows).toHaveLength(1);
+ expect(rows[0].detector).toBe('doctor-source-helper');
+ });
+
+ test('detector outside any describe attributes to file-level pseudo-suite', () => {
+ const src = [
+ "const SRC = readFileSync('src/core/operations.ts', 'utf-8');",
+ "test('top-level pin', () => { expect(SRC).toContain('Operation'); });",
+ ].join('\n');
+ const res = classifyFile('test/fake.test.ts', src);
+ expect(res.rows).toHaveLength(1);
+ expect(res.rows[0].suite).toBe('(file-level)');
+ expect(res.rows[0].cases).toBe(1);
+ });
+
+ test('binding names with regex metachars ($) are escaped, not read as anchors', () => {
+ // `$SRC` interpolated unescaped becomes /\b$SRC\b/ — `$` reads as an
+ // end-anchor and the binding can never match, so attribution silently
+ // falls through to the (file-level) pseudo-suite.
+ const src = [
+ "const $SRC = readFileSync('src/core/operations.ts', 'utf-8');",
+ "describe('uses dollar binding', () => {",
+ " test('pin', () => { expect($SRC).toContain('Operation'); });",
+ '});',
+ ].join('\n');
+ const res = classifyFile('test/fake.test.ts', src);
+ expect(res.rows).toHaveLength(1);
+ expect(res.rows[0].suite).toBe('uses dollar binding');
+ expect(res.rows[0].detector).toBe('readFileSync');
+ });
+
+ test('comment lines never trigger detectors', () => {
+ const src = [
+ "// reads src/commands/doctor.ts via readFileSync at runtime",
+ "describe('behavioral', () => {",
+ " test('x', () => { expect(1).toBe(1); });",
+ '});',
+ ].join('\n');
+ expect(classifyFile('test/fake.test.ts', src).rows).toHaveLength(0);
+ });
+});
diff --git a/test/scripts/coverage-baseline-gate.test.ts b/test/scripts/coverage-baseline-gate.test.ts
new file mode 100644
index 0000000000..ebd8d6ed67
--- /dev/null
+++ b/test/scripts/coverage-baseline-gate.test.ts
@@ -0,0 +1,297 @@
+// coverage-baseline-gate.test.ts — behavioral, fixture-locked tests for
+// scripts/coverage-baseline-gate.ts, plus unit coverage of the pure section
+// builder in scripts/update-coverage-baseline.ts.
+//
+// The git-show source is injected via the documented test seam
+// COVERAGE_BASELINE_JSON_OVERRIDE (literal JSON; sentinels ABSENT_ON_MASTER
+// and GIT_FAILURE), so tests never depend on the real origin/master.
+
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { compareCorpus } from "../../scripts/coverage-baseline-gate.ts";
+import { buildCorpusSection } from "../../scripts/update-coverage-baseline.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..");
+
+let tmp: string;
+beforeAll(() => {
+ tmp = mkdtempSync(join(tmpdir(), "coverage-baseline-gate-test-"));
+});
+afterAll(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+let fixtureSeq = 0;
+function writeSummary(
+ total: { pct: number },
+ dirs: Record<string, { pct: number }>,
+ degraded = false,
+ neverLoadedCount?: number,
+): string {
+ const p = join(tmp, `summary-${fixtureSeq++}.json`);
+ const expand = (x: { pct: number }) => ({ lines: 1000, covered: Math.round(x.pct * 10), pct: x.pct });
+ writeFileSync(
+ p,
+ JSON.stringify({
+ corpus: "prCorpus",
+ degraded,
+ total: expand(total),
+ dirs: Object.fromEntries(Object.entries(dirs).map(([k, v]) => [k, expand(v)])),
+ ...(neverLoadedCount === undefined ? {} : { neverLoaded: { count: neverLoadedCount, files: [] } }),
+ }) + "\n",
+ "utf8",
+ );
+ return p;
+}
+
+const BASELINE = {
+ provisional: false,
+ prCorpus: {
+ global: { lines: 1000, covered: 800, pct: 80 },
+ dirs: { "src/core": { lines: 500, covered: 350, pct: 70 } },
+ files: {},
+ },
+ fullCorpus: null,
+ watchlist: [],
+};
+
+interface RunResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+function runGate(opts: {
+ summary: string;
+ corpus?: string;
+ baseline?: string;
+ enforce?: string;
+ worktreePath?: string;
+}): RunResult {
+ const res = Bun.spawnSync(
+ [
+ "bun",
+ join(REPO_ROOT, "scripts", "coverage-baseline-gate.ts"),
+ "--summary",
+ opts.summary,
+ "--corpus",
+ opts.corpus ?? "prCorpus",
+ ],
+ {
+ cwd: REPO_ROOT,
+ env: {
+ ...process.env,
+ COVERAGE_BASELINE_JSON_OVERRIDE: opts.baseline ?? JSON.stringify(BASELINE),
+ COVERAGE_GATE_ENFORCE: opts.enforce ?? "0",
+ ...(opts.worktreePath ? { COVERAGE_BASELINE_WORKTREE_PATH: opts.worktreePath } : {}),
+ },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ return { code: res.exitCode, stdout: res.stdout.toString(), stderr: res.stderr.toString() };
+}
+
+describe("regression thresholds", () => {
+ it("within thresholds → PASS (report-only WOULD PASS; enforcing PASS)", () => {
+ const summary = writeSummary({ pct: 79.6 }, { "src/core": { pct: 69.1 } });
+ const reportOnly = runGate({ summary });
+ expect(reportOnly.code).toBe(0);
+ expect(reportOnly.stdout).toContain("WOULD PASS");
+
+ const enforcing = runGate({ summary, enforce: "1" });
+ expect(enforcing.code).toBe(0);
+ expect(enforcing.stdout).toContain("PASS: no coverage regression");
+ });
+
+ it("global drop of exactly 0.5pp is NOT a regression (strictly-greater rule)", () => {
+ const summary = writeSummary({ pct: 79.5 }, { "src/core": { pct: 70 } });
+ const res = runGate({ summary, enforce: "1" });
+ expect(res.code).toBe(0);
+ });
+
+ it("global regression > 0.5pp → WOULD FAIL report-only (exit 0), FAIL enforcing (exit 1)", () => {
+ const summary = writeSummary({ pct: 79.0 }, { "src/core": { pct: 70 } });
+ const reportOnly = runGate({ summary });
+ expect(reportOnly.code).toBe(0);
+ expect(reportOnly.stdout).toContain("WOULD FAIL");
+ expect(reportOnly.stdout).toContain("REGRESSION: global");
+
+ const enforcing = runGate({ summary, enforce: "1" });
+ expect(enforcing.code).toBe(1);
+ expect(enforcing.stdout).toContain("FAIL: coverage regression");
+ });
+
+ it("per-dir regression > 1.0pp fails even when global holds", () => {
+ const summary = writeSummary({ pct: 80 }, { "src/core": { pct: 68.9 } });
+ const res = runGate({ summary, enforce: "1" });
+ expect(res.code).toBe(1);
+ expect(res.stdout).toContain("REGRESSION: src/core");
+ });
+
+ it("per-dir drop of exactly 1.0pp passes", () => {
+ const summary = writeSummary({ pct: 80 }, { "src/core": { pct: 69 } });
+ const res = runGate({ summary, enforce: "1" });
+ expect(res.code).toBe(0);
+ });
+});
+
+describe("never-loaded regression (shrinking-denominator defense)", () => {
+ const BASELINE_WITH_NL = {
+ ...BASELINE,
+ prCorpus: { ...BASELINE.prCorpus, neverLoadedCount: 5 },
+ };
+
+ it("run count EXCEEDS the baseline → WOULD FAIL report-only, FAIL enforcing (exit 1)", () => {
+ // pcts hold steady — only the never-loaded count regresses (tests were
+ // deleted, shrinking the denominator).
+ const summary = writeSummary({ pct: 80 }, { "src/core": { pct: 70 } }, false, 7);
+ const reportOnly = runGate({ summary, baseline: JSON.stringify(BASELINE_WITH_NL) });
+ expect(reportOnly.code).toBe(0);
+ expect(reportOnly.stdout).toContain("WOULD FAIL");
+ expect(reportOnly.stdout).toContain("REGRESSION: neverLoaded: 5 → 7");
+
+ const enforcing = runGate({ summary, baseline: JSON.stringify(BASELINE_WITH_NL), enforce: "1" });
+ expect(enforcing.code).toBe(1);
+ expect(enforcing.stdout).toContain("FAIL: coverage regression");
+ });
+
+ it("run count EQUAL to the baseline passes", () => {
+ const summary = writeSummary({ pct: 80 }, { "src/core": { pct: 70 } }, false, 5);
+ const res = runGate({ summary, baseline: JSON.stringify(BASELINE_WITH_NL), enforce: "1" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("PASS: no coverage regression");
+ });
+
+ it("null/absent baseline neverLoadedCount skips the check entirely", () => {
+ // BASELINE has no neverLoadedCount field: even a huge run count passes.
+ const absentField = writeSummary({ pct: 80 }, { "src/core": { pct: 70 } }, false, 999);
+ const resAbsent = runGate({ summary: absentField, enforce: "1" });
+ expect(resAbsent.code).toBe(0);
+
+ // Explicit null skips too.
+ const nullBaseline = { ...BASELINE, prCorpus: { ...BASELINE.prCorpus, neverLoadedCount: null } };
+ const resNull = runGate({ summary: absentField, baseline: JSON.stringify(nullBaseline), enforce: "1" });
+ expect(resNull.code).toBe(0);
+
+ // And a summary WITHOUT neverLoaded is skipped even when the baseline
+ // carries a count (older summary shapes stay comparable).
+ const noSummaryField = writeSummary({ pct: 80 }, { "src/core": { pct: 70 } });
+ const resNoSummary = runGate({ summary: noSummaryField, baseline: JSON.stringify(BASELINE_WITH_NL), enforce: "1" });
+ expect(resNoSummary.code).toBe(0);
+ });
+});
+
+describe("report-only downgrades", () => {
+ it("provisional baseline → report-only even with a regression under enforcement", () => {
+ const summary = writeSummary({ pct: 70 }, { "src/core": { pct: 60 } });
+ const res = runGate({
+ summary,
+ enforce: "1",
+ baseline: JSON.stringify({ ...BASELINE, provisional: true }),
+ });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("REPORT-ONLY (baseline is provisional)");
+ expect(res.stdout).toContain("WOULD FAIL");
+ });
+
+ it("degraded summary → report-only even with a regression under enforcement", () => {
+ const summary = writeSummary({ pct: 70 }, { "src/core": { pct: 60 } }, true);
+ const res = runGate({ summary, enforce: "1" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("DEGRADED");
+ expect(res.stdout).toContain("WOULD FAIL");
+ });
+});
+
+describe("ungated first landings", () => {
+ it("null corpus section → ungated, exit 0", () => {
+ const summary = writeSummary({ pct: 10 }, {});
+ const res = runGate({ summary, corpus: "fullCorpus", enforce: "1" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("ungated first landing");
+ });
+
+ it("baseline absent on master → ungated, exit 0", () => {
+ const summary = writeSummary({ pct: 10 }, {});
+ const res = runGate({ summary, enforce: "1", baseline: "ABSENT_ON_MASTER" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("ungated first landing");
+ });
+});
+
+describe("infrastructure errors", () => {
+ it("unresolvable ref → exit 2", () => {
+ const summary = writeSummary({ pct: 80 }, {});
+ const res = runGate({ summary, baseline: "GIT_FAILURE" });
+ expect(res.code).toBe(2);
+ expect(res.stderr).toContain("infrastructure error");
+ });
+
+ it("deletion defense: baseline on master but working-tree copy missing → exit 2", () => {
+ const summary = writeSummary({ pct: 80 }, { "src/core": { pct: 70 } });
+ const res = runGate({ summary, worktreePath: join(tmp, "deleted-baseline.json") });
+ expect(res.code).toBe(2);
+ expect(res.stderr).toContain("working-tree copy is missing");
+ });
+
+ it("missing summary → exit 2; bad --corpus → exit 2", () => {
+ const missing = runGate({ summary: join(tmp, "nope.json") });
+ expect(missing.code).toBe(2);
+ const badCorpus = runGate({ summary: writeSummary({ pct: 80 }, {}), corpus: "weekendCorpus" });
+ expect(badCorpus.code).toBe(2);
+ });
+});
+
+describe("compareCorpus (unit)", () => {
+ it("ignores dirs absent from the summary and reports both regression kinds", () => {
+ const report = compareCorpus(
+ {
+ global: { lines: 100, covered: 80, pct: 80 },
+ dirs: {
+ "src/core": { lines: 50, covered: 35, pct: 70 },
+ "src/gone": { lines: 10, covered: 9, pct: 90 },
+ },
+ files: {},
+ },
+ { pct: 79 },
+ { "src/core": { pct: 68 } },
+ );
+ expect(report.pass).toBe(false);
+ expect(report.regressions.length).toBe(2); // global + src/core; src/gone skipped
+ });
+});
+
+describe("buildCorpusSection (unit, update-coverage-baseline.ts)", () => {
+ it("limits files to watchlist entries present in the summary", () => {
+ const section = buildCorpusSection(
+ {
+ total: { lines: 10, covered: 5, pct: 50 },
+ dirs: { src: { lines: 10, covered: 5, pct: 50 } },
+ files: {
+ "src/cli.ts": { lines: 5, covered: 1, pct: 20 },
+ "src/unwatched.ts": { lines: 5, covered: 4, pct: 80 },
+ },
+ },
+ ["src/cli.ts", "src/core/migrate.ts"],
+ );
+ expect(section.global.pct).toBe(50);
+ expect(Object.keys(section.files)).toEqual(["src/cli.ts"]);
+ expect(section.neverLoadedCount).toBe(null); // summary lacks neverLoaded
+ });
+
+ it("records the summary's neverLoaded.count so the gate can catch shrinking denominators", () => {
+ const section = buildCorpusSection(
+ {
+ total: { lines: 10, covered: 5, pct: 50 },
+ dirs: {},
+ files: {},
+ neverLoaded: { count: 42 },
+ },
+ [],
+ );
+ expect(section.neverLoadedCount).toBe(42);
+ });
+});
diff --git a/test/scripts/coverage-diff-gate.test.ts b/test/scripts/coverage-diff-gate.test.ts
new file mode 100644
index 0000000000..ecec327556
--- /dev/null
+++ b/test/scripts/coverage-diff-gate.test.ts
@@ -0,0 +1,315 @@
+// coverage-diff-gate.test.ts — behavioral, fixture-locked tests for
+// scripts/coverage-diff-gate.ts (containment-sprint coverage machinery).
+//
+// The gate's git, classify, and exemption-list inputs are injected via its
+// documented test seams (COVERAGE_GATE_DIFF_FILE / COVERAGE_GATE_CLASSIFY /
+// COVERAGE_GATE_COMMITS_FILE / COVERAGE_GATE_EXEMPTIONS_OVERRIDE) so every
+// test is hermetic: no git calls, no select-e2e subprocess.
+
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { isGateScopedPath, parseExemptions, parseUnifiedDiff } from "../../scripts/coverage-diff-gate.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..");
+
+// Simulates the exemption list AS IT EXISTS ON origin/master (the gate
+// resolves the list from master, never the working tree).
+const MASTER_EXEMPTIONS =
+ [
+ "# fixture exemption list (simulated origin/master content)",
+ "src/core/postgres-engine.ts",
+ "src/core/pglite-engine.ts",
+ "src/core/postgres-engine/",
+ "src/core/pglite-engine/",
+ "src/core/migrate.ts",
+ "src/cli.ts",
+ ].join("\n") + "\n";
+
+let tmp: string;
+let emptyCommitsFile: string;
+beforeAll(() => {
+ tmp = mkdtempSync(join(tmpdir(), "coverage-diff-gate-test-"));
+ emptyCommitsFile = join(tmp, "commits-empty.txt");
+ writeFileSync(emptyCommitsFile, "feat: something unrelated\n", "utf8");
+});
+afterAll(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+let fixtureSeq = 0;
+function writeFixture(name: string, content: string): string {
+ const p = join(tmp, `${fixtureSeq++}-${name}`);
+ writeFileSync(p, content, "utf8");
+ return p;
+}
+
+function summaryFixture(overrides: Record<string, unknown> = {}): string {
+ const summary = {
+ generatedAt: "2026-08-15T00:00:00.000Z",
+ corpus: "prCorpus",
+ lanes: { expected: [], complete: [] },
+ degraded: false,
+ total: { lines: 3, covered: 2, pct: 66.67 },
+ dirs: { src: { lines: 3, covered: 2, pct: 66.67 } },
+ files: { "src/fixture-gate-a.ts": { lines: 3, covered: 2, pct: 66.67 } },
+ functionCoverage: "informational",
+ neverLoaded: { count: 0, files: [] },
+ lineHits: { "src/fixture-gate-a.ts": { "10": 3, "11": 0, "12": 5 } },
+ ...overrides,
+ };
+ return writeFixture("summary.json", JSON.stringify(summary, null, 2) + "\n");
+}
+
+function diffHunk(file: string, start: number, count: number): string {
+ const added = Array.from({ length: count }, (_, i) => `+line ${start + i}`).join("\n");
+ return [
+ `diff --git a/${file} b/${file}`,
+ `--- a/${file}`,
+ `+++ b/${file}`,
+ `@@ -${start - 1},0 +${start},${count} @@`,
+ added,
+ "",
+ ].join("\n");
+}
+
+interface RunResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+function runGate(opts: {
+ summary: string;
+ diff: string;
+ enforce?: string;
+ classify?: string;
+ commitsFile?: string;
+ exemptions?: string;
+}): RunResult {
+ const diffFile = writeFixture("diff.patch", opts.diff);
+ const res = Bun.spawnSync(["bun", join(REPO_ROOT, "scripts", "coverage-diff-gate.ts"), "--summary", opts.summary], {
+ cwd: REPO_ROOT,
+ env: {
+ ...process.env,
+ COVERAGE_GATE_DIFF_FILE: diffFile,
+ COVERAGE_GATE_CLASSIFY: opts.classify ?? "SRC",
+ COVERAGE_GATE_COMMITS_FILE: opts.commitsFile ?? emptyCommitsFile,
+ COVERAGE_GATE_ENFORCE: opts.enforce ?? "0",
+ COVERAGE_GATE_EXEMPTIONS_OVERRIDE: opts.exemptions ?? MASTER_EXEMPTIONS,
+ },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ return { code: res.exitCode, stdout: res.stdout.toString(), stderr: res.stderr.toString() };
+}
+
+describe("parseUnifiedDiff (unit)", () => {
+ it("extracts new-side line numbers per hunk, defaults count to 1, skips deletions", () => {
+ const text = [
+ "diff --git a/src/a.ts b/src/a.ts",
+ "--- a/src/a.ts",
+ "+++ b/src/a.ts",
+ "@@ -1,2 +5,3 @@ ctx",
+ "+x",
+ "+y",
+ "+z",
+ "@@ -9,0 +12 @@",
+ "+w",
+ "@@ -20,4 +20,0 @@", // pure deletion — contributes nothing
+ "diff --git a/src/gone.ts b/src/gone.ts",
+ "--- a/src/gone.ts",
+ "+++ /dev/null",
+ "@@ -1,10 +0,0 @@",
+ ].join("\n");
+ const parsed = parseUnifiedDiff(text);
+ expect(parsed.get("src/a.ts")).toEqual([5, 6, 7, 12]);
+ expect(parsed.has("src/gone.ts")).toBe(false);
+ });
+});
+
+describe("gate scope + exemptions (unit)", () => {
+ it("scopes to src/ .ts minus test/generated/declaration files", () => {
+ expect(isGateScopedPath("src/core/foo.ts")).toBe(true);
+ expect(isGateScopedPath("src/cli.ts")).toBe(true);
+ expect(isGateScopedPath("src/core/foo.test.ts")).toBe(false);
+ expect(isGateScopedPath("src/core/foo.generated.ts")).toBe(false);
+ expect(isGateScopedPath("src/types/foo.d.ts")).toBe(false);
+ expect(isGateScopedPath("scripts/foo.ts")).toBe(false);
+ expect(isGateScopedPath("test/foo.ts")).toBe(false);
+ });
+
+ it("parses exact + directory-prefix exemption entries", () => {
+ const ex = parseExemptions("# comment\nsrc/core/migrate.ts\nsrc/core/pglite-engine/\n\n");
+ expect(ex.exact.has("src/core/migrate.ts")).toBe(true);
+ expect(ex.prefixes).toEqual(["src/core/pglite-engine/"]);
+ });
+});
+
+describe("verdicts (report-only default)", () => {
+ it("covered added lines → WOULD PASS, exit 0", () => {
+ // Lines 10 and 12 are covered (hits 3 and 5); line 11 untouched.
+ const diff = diffHunk("src/fixture-gate-a.ts", 10, 1) + diffHunk("src/fixture-gate-a.ts", 12, 1);
+ const res = runGate({ summary: summaryFixture(), diff });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("WOULD PASS");
+ expect(res.stdout).toContain("2/2 = 100.00%");
+ });
+
+ it("uncovered added lines below 80% → WOULD FAIL with uncovered line numbers, exit 0", () => {
+ const diff = diffHunk("src/fixture-gate-a.ts", 10, 3); // 10 covered, 11 uncovered, 12 covered
+ const res = runGate({ summary: summaryFixture(), diff });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("WOULD FAIL");
+ expect(res.stdout).toContain("2/3 = 66.67%");
+ expect(res.stdout).toContain("L11");
+ });
+
+ it("non-executable added lines are excluded from the denominator", () => {
+ // Lines 100-102 are absent from DA — non-executable, so 0/0 → vacuous pass.
+ const diff = diffHunk("src/fixture-gate-a.ts", 100, 3);
+ const res = runGate({ summary: summaryFixture(), diff });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("WOULD PASS");
+ });
+});
+
+describe("enforcement (COVERAGE_GATE_ENFORCE=1)", () => {
+ it("pass → exit 0", () => {
+ const diff = diffHunk("src/fixture-gate-a.ts", 10, 1);
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("PASS: changed-line coverage gate.");
+ });
+
+ it("fail → exit 1", () => {
+ const diff = diffHunk("src/fixture-gate-a.ts", 10, 3);
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1" });
+ expect(res.code).toBe(1);
+ expect(res.stdout).toContain("FAIL");
+ });
+});
+
+describe("never-loaded files", () => {
+ it("a changed file with no coverage record is ONE violation, not a physical-line count", () => {
+ const diff = diffHunk("src/fixture-gate-ghost.ts", 1, 50);
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1" });
+ expect(res.code).toBe(1);
+ expect(res.stdout).toContain("never loaded by any test in the PR corpus — add a test that imports it");
+ expect(res.stdout).toContain("Never-loaded gate-scoped files: 1");
+ // The 50 physical lines must NOT enter the covered/uncovered arithmetic.
+ expect(res.stdout).not.toContain("0/50");
+ });
+});
+
+describe("scope short-circuits", () => {
+ it("zero gate-scoped changes → explicit PASS, exit 0", () => {
+ const diff =
+ diffHunk("src/foo.test.ts", 1, 2) + diffHunk("src/bar.generated.ts", 1, 2) + diffHunk("src/types/x.d.ts", 1, 2);
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("PASS: no gate-scoped changes.");
+ });
+
+ it("classify EMPTY / DOC_ONLY → gate not applicable, exit 0 even with uncovered diff", () => {
+ const diff = diffHunk("src/fixture-gate-a.ts", 10, 3);
+ for (const classify of ["EMPTY", "DOC_ONLY"]) {
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1", classify });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain(`PASS: change classified ${classify}`);
+ }
+ });
+});
+
+describe("exemptions", () => {
+ it("exempt files are reported with their tag but never gated", () => {
+ const diff =
+ diffHunk("src/core/migrate.ts", 5, 4) +
+ diffHunk("src/cli.ts", 5, 4) +
+ diffHunk("src/core/postgres-engine/part.ts", 5, 4) +
+ diffHunk("src/fixture-gate-a.ts", 10, 1); // covered — keeps the gate scoped
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1" });
+ expect(res.code).toBe(0); // exempt uncovered lines don't count
+ expect(res.stdout).toContain("| src/core/migrate.ts | 4 | - | - | [e2e-exempt] |");
+ expect(res.stdout).toContain("| src/core/postgres-engine/part.ts | 4 | - | - | [e2e-exempt] |");
+ expect(res.stdout).toContain("| src/cli.ts | 4 | - | - | [subprocess-undercount] |");
+ });
+
+ it("only-exempt changes → no gate-scoped changes, tags still reported", () => {
+ const diff = diffHunk("src/core/migrate.ts", 5, 2);
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("PASS: no gate-scoped changes.");
+ expect(res.stdout).toContain("[e2e-exempt]");
+ });
+
+ it("a working-tree-only exemption entry does NOT exempt (list resolves from origin/master)", () => {
+ // Governance: the exemption LIST is read from origin/master, so a PR
+ // adding its own file to scripts/coverage-gate-exemptions.txt cannot
+ // self-exempt. The seam simulates master's content WITHOUT the entry
+ // (deterministic — no dependency on the real origin/master), while the
+ // REAL working-tree file temporarily carries the entry; the gate must
+ // ignore the working-tree addition (inert until merged).
+ const worktreeExemptions = join(REPO_ROOT, "scripts", "coverage-gate-exemptions.txt");
+ const original = readFileSync(worktreeExemptions, "utf8");
+ writeFileSync(worktreeExemptions, original + "src/fixture-gate-ghost.ts\n", "utf8");
+ try {
+ const diff = diffHunk("src/fixture-gate-ghost.ts", 1, 5);
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1", exemptions: MASTER_EXEMPTIONS });
+ expect(res.code).toBe(1); // never-loaded violation — NOT exempted
+ expect(res.stdout).toContain("never loaded by any test in the PR corpus");
+ expect(res.stdout).not.toContain("| src/fixture-gate-ghost.ts | 5 | - | - | [e2e-exempt] |");
+ } finally {
+ writeFileSync(worktreeExemptions, original, "utf8");
+ }
+ });
+});
+
+describe("downgrades + escape hatch", () => {
+ it("degraded summary → DEGRADED banner, report-only even when enforcing", () => {
+ const diff = diffHunk("src/fixture-gate-a.ts", 10, 3); // would fail
+ const res = runGate({ summary: summaryFixture({ degraded: true }), diff, enforce: "1" });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("DEGRADED");
+ expect(res.stdout).toContain("WOULD FAIL");
+ });
+
+ it("[coverage-exempt:] trailer → loud bypass, exit 0 even when enforcing", () => {
+ const commits = writeFixture(
+ "commits-exempt.txt",
+ "fix: emergency hotfix\n\n[coverage-exempt: incident escape hatch]\n",
+ );
+ const diff = diffHunk("src/fixture-gate-a.ts", 10, 3); // would fail
+ const res = runGate({ summary: summaryFixture(), diff, enforce: "1", commitsFile: commits });
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("BYPASSED");
+ expect(res.stdout).toContain("WARNING");
+ });
+});
+
+describe("infrastructure errors", () => {
+ it("missing summary JSON → exit 2", () => {
+ const res = Bun.spawnSync(
+ ["bun", join(REPO_ROOT, "scripts", "coverage-diff-gate.ts"), "--summary", join(tmp, "nope.json")],
+ {
+ cwd: REPO_ROOT,
+ env: { ...process.env, COVERAGE_GATE_CLASSIFY: "SRC" },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ expect(res.exitCode).toBe(2);
+ expect(res.stderr.toString()).toContain("infrastructure error");
+ });
+
+ it("missing --summary flag → exit 2", () => {
+ const res = Bun.spawnSync(["bun", join(REPO_ROOT, "scripts", "coverage-diff-gate.ts")], {
+ cwd: REPO_ROOT,
+ env: { ...process.env },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ expect(res.exitCode).toBe(2);
+ });
+});
diff --git a/test/scripts/merge-lcov.test.ts b/test/scripts/merge-lcov.test.ts
new file mode 100644
index 0000000000..9e9efe4d00
--- /dev/null
+++ b/test/scripts/merge-lcov.test.ts
@@ -0,0 +1,390 @@
+// merge-lcov.test.ts — behavioral, fixture-locked tests for
+// scripts/merge-lcov.ts (containment-sprint coverage machinery).
+//
+// Fixtures are inline synthetic lcov strings written into tmp lane dirs;
+// the script runs as a subprocess from the repo root (SF normalization and
+// the neverLoaded scan resolve against process.cwd()).
+
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+import { isMergedArtifactPath, normalizeSf, parseLcovText } from "../../scripts/merge-lcov.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..");
+
+interface RunResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+function runMerge(args: string[], env: Record<string, string> = {}): RunResult {
+ const res = Bun.spawnSync(["bun", join(REPO_ROOT, "scripts", "merge-lcov.ts"), ...args], {
+ cwd: REPO_ROOT,
+ env: { ...process.env, GENERATED_AT: "2026-08-15T00:00:00.000Z", ...env },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ return { code: res.exitCode, stdout: res.stdout.toString(), stderr: res.stderr.toString() };
+}
+
+let tmp: string;
+beforeAll(() => {
+ tmp = mkdtempSync(join(tmpdir(), "merge-lcov-test-"));
+});
+afterAll(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function laneDir(name: string, lcovText: string, manifest?: object): string {
+ const dir = join(tmp, name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "lcov.info"), lcovText, "utf8");
+ if (manifest) writeFileSync(join(dir, "lane-manifest.json"), JSON.stringify(manifest), "utf8");
+ return dir;
+}
+
+function outPaths(name: string): { lcov: string; json: string } {
+ return { lcov: join(tmp, `${name}.lcov.info`), json: join(tmp, `${name}.json`) };
+}
+
+interface SummaryShape {
+ generatedAt: string;
+ corpus: string;
+ lanes: { expected: string[]; complete: string[] };
+ degraded: boolean;
+ total: { lines: number; covered: number; pct: number };
+ dirs: Record<string, { lines: number; covered: number; pct: number }>;
+ files: Record<string, { lines: number; covered: number; pct: number }>;
+ functionCoverage: string;
+ neverLoaded: { count: number; files: string[] };
+ lineHits: Record<string, Record<string, number>>;
+}
+
+function readSummary(path: string): SummaryShape {
+ return JSON.parse(readFileSync(path, "utf8")) as SummaryShape;
+}
+
+const LANE_A = [
+ "TN:",
+ "SF:src/fixture-cov-a.ts",
+ "FN:1,alpha",
+ "FNDA:2,alpha",
+ "DA:1,1",
+ "DA:2,0",
+ "DA:3,5",
+ "LF:3",
+ "LH:2",
+ "end_of_record",
+ "",
+].join("\n");
+
+const LANE_B = [
+ "TN:",
+ "SF:src/fixture-cov-a.ts",
+ "FN:1,alpha",
+ "FNDA:3,alpha",
+ "DA:1,2",
+ "DA:2,0",
+ "DA:4,7",
+ "end_of_record",
+ "",
+].join("\n");
+
+describe("merge: DA summing across lanes", () => {
+ it("sums per-line hits, unions lines, regenerates counters", () => {
+ const a = laneDir("sum-a", LANE_A);
+ const b = laneDir("sum-b", LANE_B);
+ const out = outPaths("sum");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, a, b]);
+ expect(res.code).toBe(0);
+
+ const lcov = readFileSync(out.lcov, "utf8");
+ expect(lcov).toContain("SF:src/fixture-cov-a.ts");
+ expect(lcov).toContain("DA:1,3"); // 1 + 2
+ expect(lcov).toContain("DA:2,0"); // 0 + 0
+ expect(lcov).toContain("DA:3,5"); // lane A only
+ expect(lcov).toContain("DA:4,7"); // lane B only
+ expect(lcov).toContain("FNDA:5,alpha"); // 2 + 3 summed per function name
+ expect(lcov).toContain("FNF:1");
+ expect(lcov).toContain("FNH:1");
+ expect(lcov).toContain("LF:4");
+ expect(lcov).toContain("LH:3");
+
+ const json = readSummary(out.json);
+ expect(json.files["src/fixture-cov-a.ts"]).toEqual({ lines: 4, covered: 3, pct: 75 });
+ expect(json.lineHits["src/fixture-cov-a.ts"]).toEqual({ "1": 3, "2": 0, "3": 5, "4": 7 });
+ expect(json.degraded).toBe(false);
+ expect(json.functionCoverage).toBe("informational");
+ expect(json.generatedAt).toBe("2026-08-15T00:00:00.000Z");
+ });
+
+ it("honors COVERAGE_CORPUS and defaults to 'unknown'", () => {
+ const a = laneDir("corpus-a", LANE_A);
+ const out = outPaths("corpus");
+ runMerge(["--out-lcov", out.lcov, "--out-json", out.json, a], { COVERAGE_CORPUS: "prCorpus" });
+ expect(readSummary(out.json).corpus).toBe("prCorpus");
+
+ const out2 = outPaths("corpus2");
+ const res = Bun.spawnSync(
+ ["bun", join(REPO_ROOT, "scripts", "merge-lcov.ts"), "--out-lcov", out2.lcov, "--out-json", out2.json, a],
+ {
+ cwd: REPO_ROOT,
+ env: { ...process.env, COVERAGE_CORPUS: "", GENERATED_AT: "2026-08-15T00:00:00.000Z" },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ expect(res.exitCode).toBe(0);
+ expect(readSummary(out2.json).corpus).toBe("unknown");
+ });
+});
+
+describe("merge: SF normalization", () => {
+ it("merges absolute, repo-relative, and foreign-checkout-prefix SF paths into one record", () => {
+ const abs = [
+ `SF:${REPO_ROOT}/src/fixture-cov-n.ts`,
+ "DA:1,1",
+ "end_of_record",
+ "",
+ ].join("\n");
+ const rel = ["SF:src/fixture-cov-n.ts", "DA:1,1", "DA:2,4", "end_of_record", ""].join("\n");
+ const foreign = [
+ `SF:/ci/runner/work/${basename(REPO_ROOT)}/src/fixture-cov-n.ts`,
+ "DA:1,1",
+ "end_of_record",
+ "",
+ ].join("\n");
+ const a = laneDir("norm-a", abs);
+ const b = laneDir("norm-b", rel);
+ const c = laneDir("norm-c", foreign);
+ const out = outPaths("norm");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, a, b, c]);
+ expect(res.code).toBe(0);
+
+ const json = readSummary(out.json);
+ expect(Object.keys(json.files)).toEqual(["src/fixture-cov-n.ts"]);
+ // 1+1+1 on line 1, 4 on line 2 — all three spellings merged.
+ expect(json.lineHits["src/fixture-cov-n.ts"]).toEqual({ "1": 3, "2": 4 });
+ const lcov = readFileSync(out.lcov, "utf8");
+ expect(lcov.match(/^SF:/gm)?.length).toBe(1);
+ });
+
+ it("normalizeSf unit: strips cwd, strips any prefix ending in the repo dir name, keeps relatives", () => {
+ expect(normalizeSf(`${REPO_ROOT}/src/a.ts`, REPO_ROOT)).toBe("src/a.ts");
+ expect(normalizeSf(`/ci/work/${basename(REPO_ROOT)}/src/a.ts`, REPO_ROOT)).toBe("src/a.ts");
+ expect(normalizeSf("src/a.ts", REPO_ROOT)).toBe("src/a.ts");
+ expect(normalizeSf("./src/a.ts", REPO_ROOT)).toBe("src/a.ts");
+ expect(normalizeSf("/somewhere/else/src/a.ts", REPO_ROOT)).toBe("/somewhere/else/src/a.ts");
+ });
+});
+
+describe("merge: malformed input handling", () => {
+ it("skips a malformed lcov file whole and marks degraded, keeping the good lane", () => {
+ const good = laneDir("mal-good", LANE_A);
+ const bad = laneDir("mal-bad", "DA:1,1\n"); // DA outside any SF record
+ const out = outPaths("mal");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, good, bad]);
+ expect(res.code).toBe(0); // never aborts
+ expect(res.stderr).toContain("malformed");
+ const json = readSummary(out.json);
+ expect(json.degraded).toBe(true);
+ expect(json.files["src/fixture-cov-a.ts"]).toEqual({ lines: 3, covered: 2, pct: 66.67 });
+ });
+
+ it("treats a truncated file (SF without end_of_record) as malformed", () => {
+ const bad = laneDir("trunc-bad", "SF:src/fixture-trunc.ts\nDA:1,1\n");
+ const out = outPaths("trunc");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, bad]);
+ expect(res.code).toBe(0);
+ const json = readSummary(out.json);
+ expect(json.degraded).toBe(true);
+ expect(json.files["src/fixture-trunc.ts"]).toBeUndefined(); // whole file skipped
+ });
+
+ it("parseLcovText unit: unknown record types warn and are skipped without malforming", () => {
+ const res = parseLcovText("SF:src/x.ts\nBRDA:1,0,0,1\nDA:1,1\nend_of_record\n");
+ expect(res.malformed).toBe(false);
+ expect(res.warnings.some((w) => w.includes("BRDA"))).toBe(true);
+ expect(res.records[0]?.da).toEqual([[1, 1]]);
+ });
+
+ it("parseLcovText unit: non-numeric DA is malformed", () => {
+ const res = parseLcovText("SF:src/x.ts\nDA:one,1\nend_of_record\n");
+ expect(res.malformed).toBe(true);
+ expect(res.records).toEqual([]);
+ });
+});
+
+describe("merge: lane manifests", () => {
+ const GOOD_MANIFEST = { lane: "shard-1", sha: "deadbeef", lcovCount: 1, complete: true };
+
+ it("complete expected lanes → not degraded; lanes.complete lists them", () => {
+ const a = laneDir("man-ok", LANE_A, GOOD_MANIFEST);
+ const out = outPaths("man-ok");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, "--manifest-expect", "shard-1", a]);
+ expect(res.code).toBe(0);
+ const json = readSummary(out.json);
+ expect(json.degraded).toBe(false);
+ expect(json.lanes.expected).toEqual(["shard-1"]);
+ expect(json.lanes.complete).toEqual(["shard-1"]);
+ });
+
+ it("missing manifest for an expected lane → degraded", () => {
+ const a = laneDir("man-miss", LANE_A, GOOD_MANIFEST);
+ const out = outPaths("man-miss");
+ const res = runMerge([
+ "--out-lcov", out.lcov, "--out-json", out.json,
+ "--manifest-expect", "shard-1,serial", a,
+ ]);
+ expect(res.code).toBe(0);
+ expect(res.stderr).toContain("serial");
+ const json = readSummary(out.json);
+ expect(json.degraded).toBe(true);
+ expect(json.lanes.expected).toEqual(["shard-1", "serial"]);
+ expect(json.lanes.complete).toEqual(["shard-1"]);
+ });
+
+ it("incomplete manifest for an expected lane → degraded", () => {
+ const a = laneDir("man-inc", LANE_A, { ...GOOD_MANIFEST, complete: false });
+ const out = outPaths("man-inc");
+ runMerge(["--out-lcov", out.lcov, "--out-json", out.json, "--manifest-expect", "shard-1", a]);
+ const json = readSummary(out.json);
+ expect(json.degraded).toBe(true);
+ expect(json.lanes.complete).toEqual([]);
+ });
+
+ it("shard manifest with lcovCount != 1 → degraded (xargs-batching tripwire)", () => {
+ const a = laneDir("man-two", LANE_A, { ...GOOD_MANIFEST, lcovCount: 2 });
+ const out = outPaths("man-two");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, "--manifest-expect", "shard-1", a]);
+ expect(res.stderr).toContain("lcovCount=2");
+ expect(readSummary(out.json).degraded).toBe(true);
+ });
+
+ it("non-shard lane may carry many lcov files without tripping the tripwire", () => {
+ const a = laneDir("man-serial", LANE_A, { lane: "serial", sha: "d", lcovCount: 12, complete: true });
+ const out = outPaths("man-serial");
+ runMerge(["--out-lcov", out.lcov, "--out-json", out.json, "--manifest-expect", "serial", a]);
+ expect(readSummary(out.json).degraded).toBe(false);
+ });
+});
+
+describe("merge: JSON metrics scope + hand-computed totals", () => {
+ const LANE_C = [
+ "SF:src/fixture-tot-one.ts",
+ "DA:1,1",
+ "DA:2,0",
+ "end_of_record",
+ "SF:src/core/fixture-tot-two.ts",
+ "DA:10,3",
+ "DA:11,1",
+ "DA:12,0",
+ "end_of_record",
+ "SF:test/fixture-tot.test.ts",
+ "DA:1,1",
+ "end_of_record",
+ "SF:scripts/fixture-tot-tool.ts",
+ "DA:1,1",
+ "end_of_record",
+ "",
+ ].join("\n");
+
+ it("totals/dirs/files count src/ only; out-lcov keeps every record", () => {
+ const c = laneDir("tot-c", LANE_C);
+ const out = outPaths("tot");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, c]);
+ expect(res.code).toBe(0);
+
+ const json = readSummary(out.json);
+ // Hand-computed: src lines 2+3=5, covered 1+2=3 → 60%.
+ expect(json.total).toEqual({ lines: 5, covered: 3, pct: 60 });
+ expect(json.dirs["src"]).toEqual({ lines: 2, covered: 1, pct: 50 });
+ expect(json.dirs["src/core"]).toEqual({ lines: 3, covered: 2, pct: 66.67 });
+ expect(Object.keys(json.files).sort()).toEqual([
+ "src/core/fixture-tot-two.ts",
+ "src/fixture-tot-one.ts",
+ ]);
+ expect(json.lineHits["test/fixture-tot.test.ts"]).toBeUndefined();
+
+ // Non-src records stay in the merged lcov artifact.
+ const lcov = readFileSync(out.lcov, "utf8");
+ expect(lcov).toContain("SF:test/fixture-tot.test.ts");
+ expect(lcov).toContain("SF:scripts/fixture-tot-tool.ts");
+ });
+
+ it("neverLoaded inventories real src files absent from the data — count + sorted list, no percentage", () => {
+ const c = laneDir("never-c", LANE_C);
+ const out = outPaths("never");
+ runMerge(["--out-lcov", out.lcov, "--out-json", out.json, c]);
+ const json = readSummary(out.json);
+ // The fixture files are "loaded" (present in data); every real src file is not.
+ expect(json.neverLoaded.count).toBe(json.neverLoaded.files.length);
+ expect(json.neverLoaded.files).toContain("src/cli.ts");
+ expect(json.neverLoaded.files).not.toContain("src/fixture-tot-one.ts");
+ const sorted = [...json.neverLoaded.files].sort();
+ expect(json.neverLoaded.files).toEqual(sorted);
+ expect(json.neverLoaded.files.every((f) => !f.endsWith(".test.ts") && !f.endsWith(".d.ts"))).toBe(true);
+ });
+});
+
+describe("merge: self-merge guard (coverage-merged exclusion)", () => {
+ it("skips lcov.info under a coverage-merged path segment without degrading", () => {
+ // CI report-job re-runs download the PRIOR run's own coverage-merged
+ // artifact via the coverage-* glob; re-merging it would double every hit
+ // count. The guard drops it while keeping real lanes.
+ laneDir("selfmerge/lane-a", LANE_A);
+ laneDir(
+ "selfmerge/coverage-merged",
+ ["SF:src/fixture-prior-merged.ts", "DA:1,100", "end_of_record", ""].join("\n"),
+ );
+ const out = outPaths("selfmerge");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, join(tmp, "selfmerge")]);
+ expect(res.code).toBe(0);
+ expect(res.stderr).toContain("self-merge guard");
+ const json = readSummary(out.json);
+ expect(json.files["src/fixture-prior-merged.ts"]).toBeUndefined(); // prior artifact dropped
+ expect(json.files["src/fixture-cov-a.ts"]).toEqual({ lines: 3, covered: 2, pct: 66.67 }); // real lane kept
+ expect(json.degraded).toBe(false); // expected on re-runs, not data loss
+ });
+
+ it("skips a direct lcov.info FILE input under a coverage-merged segment", () => {
+ laneDir("selfmerge-direct/coverage-merged", LANE_A);
+ const a = laneDir("selfmerge-direct/lane-a", LANE_A);
+ const out = outPaths("selfmerge-direct");
+ const res = runMerge([
+ "--out-lcov", out.lcov, "--out-json", out.json,
+ join(tmp, "selfmerge-direct", "coverage-merged", "lcov.info"),
+ a,
+ ]);
+ expect(res.code).toBe(0);
+ expect(res.stderr).toContain("self-merge guard");
+ // Only the real lane merged: hits are lane-A's alone, not doubled.
+ expect(readSummary(out.json).lineHits["src/fixture-cov-a.ts"]).toEqual({ "1": 1, "2": 0, "3": 5 });
+ });
+
+ it("isMergedArtifactPath unit: matches a path SEGMENT, not a substring", () => {
+ expect(isMergedArtifactPath("/dl/coverage-merged/lcov.info")).toBe(true);
+ expect(isMergedArtifactPath("dl/coverage-merged/nested/lcov.info")).toBe(true);
+ expect(isMergedArtifactPath("/dl/coverage-merged-old/lcov.info")).toBe(false);
+ expect(isMergedArtifactPath("/dl/coverage-shard1/lcov.info")).toBe(false);
+ });
+});
+
+describe("merge: CLI contract", () => {
+ it("missing required args → exit 2", () => {
+ const res = runMerge(["--out-lcov", join(tmp, "x.lcov")]);
+ expect(res.code).toBe(2);
+ expect(res.stderr).toContain("usage");
+ });
+
+ it("nonexistent input path warns and marks degraded, never aborts", () => {
+ const a = laneDir("ghost-a", LANE_A);
+ const out = outPaths("ghost");
+ const res = runMerge(["--out-lcov", out.lcov, "--out-json", out.json, a, join(tmp, "does-not-exist")]);
+ expect(res.code).toBe(0);
+ expect(res.stderr).toContain("not found");
+ expect(readSummary(out.json).degraded).toBe(true);
+ });
+});
diff --git a/test/scripts/render-coverage-summary.test.ts b/test/scripts/render-coverage-summary.test.ts
new file mode 100644
index 0000000000..272e7e254d
--- /dev/null
+++ b/test/scripts/render-coverage-summary.test.ts
@@ -0,0 +1,141 @@
+// render-coverage-summary.test.ts — behavioral, fixture-locked tests for
+// scripts/render-coverage-summary.ts (containment-sprint coverage
+// machinery). The renderer consumes ONLY the JSON artifact (+ optional
+// structural TSV); these tests assert the key markdown lines appear.
+
+import { afterAll, beforeAll, describe, expect, it } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { parseStructuralTsv } from "../../scripts/render-coverage-summary.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..");
+
+let tmp: string;
+beforeAll(() => {
+ tmp = mkdtempSync(join(tmpdir(), "render-coverage-test-"));
+});
+afterAll(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+let fixtureSeq = 0;
+function writeFixture(name: string, content: string): string {
+ const p = join(tmp, `${fixtureSeq++}-${name}`);
+ writeFileSync(p, content, "utf8");
+ return p;
+}
+
+const NEVER_LOADED_FILES = Array.from({ length: 12 }, (_, i) => `src/never/loaded-${String(i).padStart(2, "0")}.ts`);
+
+function summaryFixture(overrides: Record<string, unknown> = {}): string {
+ const summary = {
+ generatedAt: "2026-08-15T00:00:00.000Z",
+ corpus: "prCorpus",
+ lanes: { expected: ["shard-1", "serial"], complete: ["shard-1"] },
+ degraded: false,
+ total: { lines: 200, covered: 124, pct: 62 },
+ dirs: {
+ src: { lines: 50, covered: 40, pct: 80 },
+ "src/core": { lines: 150, covered: 84, pct: 56 },
+ },
+ files: {
+ "src/core/operations.ts": { lines: 100, covered: 10, pct: 10 },
+ "src/other-file.ts": { lines: 100, covered: 5, pct: 5 },
+ },
+ functionCoverage: "informational",
+ neverLoaded: { count: 12, files: NEVER_LOADED_FILES },
+ ...overrides,
+ };
+ return writeFixture("summary.json", JSON.stringify(summary, null, 2) + "\n");
+}
+
+interface RunResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+function runRender(args: string[]): RunResult {
+ const res = Bun.spawnSync(["bun", join(REPO_ROOT, "scripts", "render-coverage-summary.ts"), ...args], {
+ cwd: REPO_ROOT,
+ env: { ...process.env },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ return { code: res.exitCode, stdout: res.stdout.toString(), stderr: res.stderr.toString() };
+}
+
+describe("render: key lines", () => {
+ it("prints corpus, lane completeness, totals, dir table, worst files, neverLoaded, cli.ts note", () => {
+ const res = runRender(["--summary", summaryFixture()]);
+ expect(res.code).toBe(0);
+ const out = res.stdout;
+ expect(out).toContain("## Coverage summary");
+ expect(out).toContain("- Corpus: `prCorpus`");
+ expect(out).toContain("Lanes: 1/2 complete");
+ expect(out).toContain("Total line coverage: **62%** (124/200 executable lines)");
+ expect(out).toContain("Function coverage: informational only");
+ expect(out).toContain("| src/core | 150 | 84 | 56% |");
+ expect(out).toContain("### Never-loaded src files: 12");
+ expect(out).toContain("- src/never/loaded-00.ts");
+ expect(out).toContain("+2 more");
+ expect(out).toContain("[subprocess-undercount]");
+ expect(out).not.toContain("DEGRADED");
+ });
+
+ it("prioritizes watchlist files in the worst-covered table", () => {
+ // src/core/operations.ts is on the committed watchlist
+ // (scripts/coverage-baseline.json); src/other-file.ts is worse (5%) but
+ // must sort AFTER the watchlist entry.
+ const res = runRender(["--summary", summaryFixture()]);
+ const out = res.stdout;
+ const opsIdx = out.indexOf("| src/core/operations.ts | 10% | 100 | yes |");
+ const otherIdx = out.indexOf("| src/other-file.ts | 5% | 100 | |");
+ expect(opsIdx).toBeGreaterThan(-1);
+ expect(otherIdx).toBeGreaterThan(-1);
+ expect(opsIdx).toBeLessThan(otherIdx);
+ });
+
+ it("prints the DEGRADED banner when the summary is degraded", () => {
+ const res = runRender(["--summary", summaryFixture({ degraded: true })]);
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain("**DEGRADED COVERAGE DATA**");
+ });
+});
+
+describe("render: structural test-intent line", () => {
+ const TSV = [
+ "# Structural test suites — comment header",
+ "# Columns: file\tsuite\tcases\tdetector",
+ "test/a.test.ts\tsuite one\t3\treadFileSync",
+ "test/b.test.ts\tsuite two\t2\texecSync",
+ "",
+ ].join("\n");
+
+ it("counts suites and sums cases from the TSV", () => {
+ const tsv = writeFixture("structural.tsv", TSV);
+ const res = runRender(["--summary", summaryFixture(), "--structural", tsv]);
+ expect(res.code).toBe(0);
+ expect(res.stdout).toContain(
+ "Behavioral vs structural: structural suites 2 / cases 5 (see scripts/structural-suites.tsv)",
+ );
+ });
+
+ it("parseStructuralTsv (unit) skips comments and non-numeric cases", () => {
+ expect(parseStructuralTsv(TSV)).toEqual({ suites: 2, cases: 5 });
+ expect(parseStructuralTsv("# only comments\n")).toEqual({ suites: 0, cases: 0 });
+ });
+});
+
+describe("render: CLI contract", () => {
+ it("missing summary → exit 2", () => {
+ const res = runRender(["--summary", join(tmp, "nope.json")]);
+ expect(res.code).toBe(2);
+ });
+
+ it("missing structural TSV → exit 2", () => {
+ const res = runRender(["--summary", summaryFixture(), "--structural", join(tmp, "nope.tsv")]);
+ expect(res.code).toBe(2);
+ });
+});
diff --git a/test/sync-failures.test.ts b/test/sync-failures.test.ts
index b1b762fc8b..217e400c8b 100644
--- a/test/sync-failures.test.ts
+++ b/test/sync-failures.test.ts
@@ -18,6 +18,7 @@
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync } from 'fs';
+import { doctorSource } from './helpers/doctor-source.ts';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -135,7 +136,7 @@ describe('Bug 9 — sync-failures JSONL helpers', () => {
describe('Bug 9 — doctor surfaces sync failures', () => {
test('doctor source contains sync_failures check', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
expect(source).toContain('sync_failures');
expect(source).toContain('unacknowledgedSyncFailures');
expect(source).toContain("'gbrain sync --skip-failed'");
@@ -146,7 +147,7 @@ describe('Bug 9 — doctor surfaces sync failures', () => {
// they can never drift. The remote surface must no longer hand-roll an
// `acknowledged_at` count (the old field-split that caused drift).
test('both doctor surfaces use the shared decideSyncFailureSeverity', async () => {
- const source = await Bun.file(new URL('../src/commands/doctor.ts', import.meta.url)).text();
+ const source = doctorSource();
const occurrences = source.split('decideSyncFailureSeverity').length - 1;
expect(occurrences).toBeGreaterThanOrEqual(2); // local + remote
// remote no longer counts `!entry.acknowledged_at` by hand.