Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.47.5.0 fix(bootstrap): self-repairing upgrade path for older Postgres brains + blob coverage gate (#4657) (#4699)
Garry Tand9909cddd15f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex cded3f6319..c82b488b90 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "gbrain",- "version": "0.47.4.0",- "description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",+ "version": "0.47.5.0",+ "description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan","url": "https://github.com/garrytan"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 83e67f517a..5550ec42e3 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "gbrain",- "version": "0.47.4.0",- "description": "Personal knowledge brain for your coding agent \u2014 hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",+ "version": "0.47.5.0",+ "description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.","author": {"name": "Garry Tan","url": "https://github.com/garrytan"@@ -23,7 +23,7 @@"interface": {"displayName": "GBrain","shortDescription": "Give your agent a persistent brain: search, synthesis, memory",- "longDescription": "GBrain wires a personal knowledge brain into every session: hybrid keyword+vector search, entity graph traversal, synthesis, and memory your agent writes itself \u2014 served on the starter MCP surface (the seven memory verbs plus the daily-driver brain ops). Bundles the curated brain-first skill set: setup (walks install + gbrain init), cold-start day-one brain filling, ingest, query, briefing, upgrade, and more. Requires the gbrain CLI (bun install -g github:garrytan/gbrain#latest-stable) and a brain (gbrain init); the bundled setup skill walks the rest. Unix (macOS/Linux) only.",+ "longDescription": "GBrain wires a personal knowledge brain into every session: hybrid keyword+vector search, entity graph traversal, synthesis, and memory your agent writes itself — served on the starter MCP surface (the seven memory verbs plus the daily-driver brain ops). Bundles the curated brain-first skill set: setup (walks install + gbrain init), cold-start day-one brain filling, ingest, query, briefing, upgrade, and more. Requires the gbrain CLI (bun install -g github:garrytan/gbrain#latest-stable) and a brain (gbrain init); the bundled setup skill walks the rest. Unix (macOS/Linux) only.","developerName": "Garry Tan","category": "Productivity","capabilities": [diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 4b1489cad2..be89185644 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.47.4.0 -->+<!-- gbrain-runbook-stamp: 0.47.5.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 999c38af72..1b7ad56d1f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,51 @@All notable changes to GBrain will be documented in this file.+## [0.47.5.0] - 2026-08-29++**Postgres brains created before v0.46.35.0 upgrade cleanly again — the+upgrade path self-repairs on the next connect, and a new build-time gate+keeps this whole class of upgrade wedge from shipping again.**++### Fixed++- **Self-repairing upgrade path for older Postgres brains.** A brain created+ before v0.46.35.0 could fail to complete its schema upgrade on newer+ releases; every database-touching command then stopped at connect. The+ schema bootstrap now detects and repairs the gap automatically — upgrade+ the binary, run any command, and the brain converges to the latest schema+ with no manual steps. Brains that already applied a manual workaround are+ unaffected (the repair is a no-op there). Pinned by a live-Postgres+ end-to-end test that rewinds a brain to the affected shape and proves+ convergence, including that pre-existing rows keep their original+ time-to-live instead of gaining a fresh one. (#4657)+- The bootstrap's diagnostic line no longer mislabels newer brains as+ "pre-v0.21" — it now names what it actually found (a schema+ forward-reference gap), on both engines.++### Added++- **Build-time closure of the upgrade-wedge class (4th recurrence).** The+ schema-coverage suite now parses the embedded Postgres schema for every+ index-to-column forward reference and fails any pull request that adds one+ without a matching bootstrap repair — the same guard the PGLite schema+ already had. The gap this release fixes was only catchable on a+ live-Postgres test lane before; now it fails locally at PR time.++## To take advantage of v0.47.5.0++`gbrain upgrade` is all you need. If your brain was affected, the repair runs+automatically on the next command that touches the database.++**Say to your agent:** *"upgrade gbrain and run the doctor"* — your agent runs+`gbrain upgrade` and `gbrain doctor` to confirm the brain is healthy.++1. **Verify the upgrade:**+ ```bash+ gbrain --version+ gbrain doctor+ ```+## [0.47.4.0] - 2026-08-28**Your brain's remote surface now behaves the same everywhere: reads staydiff --git a/TODOS.md b/TODOS.mdindex e04c9ae7ee..ff13e3949e 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,19 @@# TODOS+## Schema-bootstrap coverage follow-ups (filed 2026-08-29, follow-up from the #4657 P0 fix)++- [ ] **P3 — Extend the blob forward-reference gates beyond CREATE INDEX.**+ **What:** `test/schema-bootstrap-coverage.test.ts` now gates CREATE INDEX+ column references on BOTH schema blobs (PGLite A2 check + the #4657+ Postgres-blob class-closure gate), but forward references through+ constraints, views, trigger bodies, and partial-index WHERE clauses are+ not parsed. **Why:** the #4657 class (4th recurrence) proved blob-only+ forward references break zero locally-runnable tests; the remaining DDL+ forms are the same shape through a different syntax. **Where to start:**+ extend `parseIndexColumnReferences` siblings for `CHECK`/`REFERENCES`/+ `CREATE TRIGGER` bodies against `SCHEMA_SQL` + `PGLITE_SCHEMA_SQL`, reuse+ `buildIndexRefCoveragePredicate`, keep the exemption-with-rationale bar.+## Gmail open-loop engine follow-ups (filed 2026-08-25, follow-up from the gmail-open-loop-engine wave)- [ ] **P1 — gbrain.io hosted OAuth relay: server build + CASA clock.**diff --git a/VERSION b/VERSIONindex 17634b0c3b..3ad89d9f6d 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.47.4.0\ No newline at end of file+0.47.5.0diff --git a/docs/TESTING.md b/docs/TESTING.mdindex cc919b8cef..0c76b1ee87 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -495,7 +495,8 @@ Unit tests and what they cover:- `test/import-resume.test.ts` — import checkpoints.- `test/migrate.test.ts` — migration: v8/v9 helper-btree-index SQL structural assertions; 1000-row wall-clock fixtures guarding the O(n²)→O(n log n) fix; v12/v13 SQL shape; `sqlFor` + `transaction:false` runner semantics; the `max_stalled DEFAULT 1` regression guard; v24 `sqlFor.pglite: ''` no-op assertion; v117 `context_volunteer_events` (named + idempotent entry, documented columns + both source-scoped indexes after `initSchema`, insert + 90-day `purgeStaleVolunteerEvents` round-trip).- `test/bootstrap.test.ts` — bootstrap contract: no-op on fresh install, idempotent across two `initSchema()` calls, no-op on modern brain that already has every probed column, full bootstrap path on a simulated legacy brain, fresh-install regression guard, legacy `links` shape coverage.-- `test/schema-bootstrap-coverage.test.ts` — CI guard. `REQUIRED_BOOTSTRAP_COVERAGE` lists every forward reference in `PGLITE_SCHEMA_SQL`; the test fails loudly if `applyForwardReferenceBootstrap` skips one (extend both arrays when adding a column-with-index to the embedded schema blob). Also parses `src/core/migrate.ts` source text for every `ALTER TABLE ... ADD COLUMN` (top-level `sql:`, `sqlFor.{postgres,pglite}` overrides, AND handler-body `engine.runMigration(N, \`ALTER TABLE ...\`)`) and asserts each (table, column) pair is covered by the bootstrap OR by the schema blob's CREATE TABLE bodies — catching the column-only forward-reference class (e.g. `sources.archived`, `oauth_clients.source_id`) that a CREATE INDEX parser alone can't see. `parseBaseTableColumns` strips SQL line + block comments before identifying column names so commented-out lines don't hide adjacent columns.+- `test/schema-bootstrap-coverage.test.ts` — CI guard covering BOTH embedded schema blobs: neither may forward-reference state its engine's bootstrap can't create, and a reference covered on one blob is NOT automatically covered on the other (`dream_verdicts` exists only in the Postgres blob). PGLite half: `REQUIRED_BOOTSTRAP_COVERAGE` lists every forward reference in `PGLITE_SCHEMA_SQL`; the test fails loudly if `applyForwardReferenceBootstrap` skips one (extend both arrays when adding a column-with-index to the embedded schema blob). Also parses `src/core/migrate.ts` source text for every `ALTER TABLE ... ADD COLUMN` (top-level `sql:`, `sqlFor.{postgres,pglite}` overrides, AND handler-body `engine.runMigration(N, \`ALTER TABLE ...\`)`) and asserts each (table, column) pair is covered by the bootstrap OR by the schema blob's CREATE TABLE bodies — catching the column-only forward-reference class (e.g. `sources.archived`, `oauth_clients.source_id`) that a CREATE INDEX parser alone can't see. Postgres half (the class-closure gate): parses every CREATE INDEX column reference in `SCHEMA_SQL` and requires each to be in the blob's CREATE TABLE body AND not migration-added, or probed + ALTERed by `src/core/postgres-engine/forward-reference-bootstrap.ts` — a column that is both in the blob's CREATE TABLE and migration-added is still a forward reference for pre-existing brains, where `CREATE TABLE IF NOT EXISTS` no-ops and the blob's CREATE INDEX wedges `initSchema` before migrations can help. This gate is parser-driven (no registry to extend); intentional non-probes go in `POSTGRES_INDEX_REF_EXEMPTIONS` with a rationale. Honest scope: CREATE INDEX column references only — constraints, views, and trigger bodies are a filed TODOS.md follow-up. `parseBaseTableColumns` strips SQL line + block comments before identifying column names so commented-out lines don't hide adjacent columns.+- `test/dream-verdict-cache-ttl.test.ts` — `dream_verdicts` TTL contract on PGLite: put assigns the default TTL, expired rows miss on read and only they are swept, re-judging via upsert refreshes a nearly-expired row, the migration backfill derives expiry from `judged_at` idempotently, and a NULL-expiry row (the pre-backfill upgrade window) reads as a hit and survives the sweep — the locally-runnable pin for the NULL-tolerant read predicate both engines share.- `test/helpers/schema-diff.ts` + `test/helpers/schema-diff.test.ts` + `test/e2e/schema-drift.test.ts` — cross-engine schema parity gate. Helper exports pure `snapshotSchema(query)` / `diffSnapshots(pg, pglite, opts)` / `formatDiffForFailure(diff)` / `isCleanDiff(diff)` over a four-tuple per column (`data_type`, `udt_name`, `is_nullable`, `column_default`). E2E test spins up fresh PGLite + Postgres, runs `engine.initSchema()` on each, snapshots `information_schema.columns`, then diffs. 2-table allowlist (`files`, `file_migration_ledger`) — every other Postgres table must reach PGLite via `PGLITE_SCHEMA_SQL` or a migration's `sqlFor.pglite` branch. Sentinels for `oauth_clients`, `mcp_request_log`, `access_tokens`, `eval_candidates` give tighter blame messages. Skips without `DATABASE_URL`. Wired into `scripts/e2e-test-map.ts` so changes to `src/schema.sql`, `src/core/pglite-schema.ts`, or `src/core/migrate.ts` trigger it. The failure message names every drift with a paste-ready hint pointing at `src/core/pglite-schema.ts`.- `test/setup-branching.test.ts` — setup flow.- `test/slug-validation.test.ts` — slug validation.@@ -625,7 +626,7 @@ E2E tests live in `test/e2e/` and run against real Postgres+pgvector (require `D- `test/e2e/search-swamp.test.ts` — reproduces the source-swamp case. Seeds a curated `originals/talks/article-outline-fat-code` page against two `<fork>/chat/` pages stuffed with the same multi-word phrase. Asserts the article wins keyword AND vector ranking, that `detail=high` lets the chat swamp re-surface, and that `source_id` passes through the two-stage CTE intact. PGLite in-memory.- `test/e2e/search-exclude.test.ts` — `test/` + `archive/` pages hidden by default, `include_slug_prefixes` opts back in, caller-supplied `exclude_slug_prefixes` adds to defaults. Both keyword and vector search paths.- `test/e2e/engine-parity.test.ts` — Postgres ↔ PGLite top-result and result-set parity for `searchKeyword` + `searchVector` (Postgres ranks pages then picks best chunk while PGLite returns chunks directly, so the source-boost behavior needs parity coverage). Skips without `DATABASE_URL`.-- `test/e2e/postgres-bootstrap.test.ts` — exercises `PostgresEngine.initSchema()` directly against a fresh real Postgres database. Asserts the bootstrap path is no-op on fresh installs and that SCHEMA_SQL replays cleanly through the engine path (not via the standalone `db.initSchema` from `src/core/db.ts`).+- `test/e2e/postgres-bootstrap.test.ts` — exercises `PostgresEngine.initSchema()` directly against a real Postgres database: bootstrap → SCHEMA_SQL → migrations converge from a pre-v0.18 brain, and a brain already at LATEST is an idempotent no-op. Live wedge-class convergence cases rewind a brain to an old schema shape and assert full `initSchema` convergence: pre-v121 timeline, pre-v143 `dream_verdicts` (including that pre-existing rows keep their `judged_at`-derived TTL instead of gaining a fresh 30 days), and pre-v7/pre-v136 `minion_jobs` shapes. Also covers the standalone `db.initSchema` replay path from `src/core/db.ts`, which shares the same bootstrap. Skips without `DATABASE_URL`.- `test/e2e/http-transport.test.ts` — `gbrain serve --http` end-to-end against real Postgres: bearer auth round-trip, `last_used_at` SQL-level debounce, `mcp_request_log` row insertion on success and auth_failed paths, `/health` DB-down → 503 (DB-probing health check), and the dispatch round-trip with a real operation. Skips without `DATABASE_URL`.- `test/e2e/serve-http-oauth.test.ts` — real-Postgres E2E against `gbrain serve --http` with full OAuth 2.1. Spawns a subprocess server, registers a client via the CLI, mints `client_credentials` tokens, exercises the `/mcp` JSON-RPC pipeline. Real DCR `/register` HTTP-level response-shape test (asserts `typeof body.client_id_issued_at === 'number'` over the wire, RFC 7591 §3.2.1); real CLI subprocess test for `revoke-client` (registers → mints token → revokes via `execSync` → asserts token rejected at `/mcp` → asserts re-run exits 1); server fixture flips on `--enable-dcr` so `/register` is reachable. **bun execSync env-inheritance contract:** bun's `execSync` does NOT inherit env mutations done via `process.env.X = ...`, only OS-level env from before bun started. helpers.ts loads `.env.testing` and sets `DATABASE_URL` via `process.env` mutation, which is invisible to subprocesses unless `env: { ...process.env }` is passed explicitly — every subprocess call in this file passes `env: { ...process.env }`. Reference fix for the same failure mode in sibling sync/cycle/dream/claw-test E2Es. `afterAll` cleanup is guarded on `clientId` (won't throw if `beforeAll` failed before registration); cleanup errors surface to stderr without throwing so real test failures aren't masked. Also covers the trust-boundary fix: an HTTP MCP `submit_job` for `name: "shell"` MUST reject with a permission error (request handler sets `remote: true` and `submit_job`'s protected-name guard fires), and the same guard rejects subagent submission. Skips without `DATABASE_URL`.- `test/e2e/sync-parallel.test.ts` — `DATABASE_URL`-gated. 60-file Postgres sync at concurrency=4 imports all + no connection leak (probes `pg_stat_activity` before/after to confirm worker engines disconnected). 120-file serial-vs-parallel benchmark prints `SYNC_PARALLEL_BENCH N files | serial=Xms | parallel(4)=Yms | speedup=Zx`. Asserts parallel ≤ serial × 1.5 (CI-noise tolerant; not a strict speedup gate).diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 383ae87ff8..9806a63863 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -44,9 +44,9 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `--no-migrate` keeps doctor observational: the CLI connects with `probeOnly` so a clean-or-behind schema is reported as-is instead of being auto-migrated before the checks run (#4364). 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`; a version AHEAD of this client's `LATEST_VERSION` warns "upgrade this client"; and when the ledger reads current, a read-only `detectMissingColumns` diff from `src/core/schema-verify.ts` runs INSIDE the ledger-current branch — a PgBouncer-swallowed ALTER TABLE can advance `config.version` over a physically narrower table, so missing live columns downgrade the ok to a warn naming them with the `gbrain init --migrate-only` hint; diff failure is best-effort and the ledger ok stands; positional wiring pinned by `test/doctor-schema-column-diff.test.ts`), `upgrade_errors` (async `checkUpgradeErrors(engine)` over `~/.gbrain/upgrade-errors.jsonl`: the warn downgrades to an EXPLICIT status-ok line — never silence — only when the past failure is provably superseded, i.e. the running binary is at/past the failed target version AND the schema verifies current via `engine.getConfig('version')`; a missing engine or unverifiable schema keeps the warn, fail-closed, because `self-upgrade` swaps the binary before `post-upgrade` runs migrations and the binary alone can lie; pinned by `test/doctor-upgrade-errors.test.ts` + `test/doctor-upgrade-errors-stale.test.ts`), `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, connectError?): Promise<Check[]>` exported as a test seam; the optional `connectError` is the connect failure captured by the CLI's dead-DB fallback, which the null-engine path turns into a SYNTHESIZED classified `connection` fail entry (so `checks[name=="connection"]` exists in every failure shape — smoke-test branches on it). The `connection` check's failure path classifies via `src/core/pg-access-classify.ts` into a redacted message + `details: {reason, transient, fix_hint}` naming `gbrain db-repair` (deliberately NOT `remediation[]`/`makeRemediationStep` — that lane feeds `--remediate`, whose Minion jobs need the very DB that's down; applicator boundary: `--remediate` = brain-DATA quality with a live engine, `db-repair` = DB ACCESS engine-free). The URL-only `pgbouncerPrepareCheck` helper and the engine-free `db_repair_recurrence` check run BOTH before the connection check and in the dead-DB filesystem lane; `pglite_scale` (engine-fit, warn at ≥1000 pages on pglite) runs in the DB phase. `computeDoctorReport(checks, extras?)` accepts optional `{engine, db_url_source}` which land as additive `DoctorReport.engine` / `DoctorReport.db_url_source` JSON fields (schema_version stays 2). `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`. Schema health is a two-check pair: `schema_version` resolves through `schemaVersionHealth` (`src/core/schema-version-health.ts`, shared with the remote doctor report; a DB AHEAD of the client warns with an upgrade-this-client hint rather than suggesting migrations), and on ledger-current brains a read-only `schema_columns` check diffs live columns against the expected schema (`detectMissingColumns`, dynamically imported inside the ledger-current branch — positional guard in `test/doctor-schema-column-diff.test.ts`) and warns naming the missing columns with the `gbrain init --migrate-only` hint.- `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`, `stale-mentions.ts`, `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `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/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkChatFallbackChainInert` returns one warning when either the effective file/environment config or the DB plane has a non-empty `chat_fallback_chain`; it returns `null` when both are empty, so clean doctor reports add no line. The local and remote doctor registries both consume the check.-- `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. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (#4143 engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `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()` routes text-embedding writes through the column registry (#1262, both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; a registry-routed brain no longer fails every write with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `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.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. `disconnect()` runs `drainBackgroundWorkBeforeDisconnect()` before pool teardown (#4143 engine parity with PGLiteEngine — mode `'disconnect'`, so residual telemetry buffers drop symmetrically on both engines; guarded so a never-connected/already-torn-down engine skips the drain). `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()` routes text-embedding writes through the column registry (#1262, both engines in parity): a caller-resolved `opts.embeddingColumn` descriptor wins; otherwise the DB-plane `search_embedding_column` + `embedding_columns` config rows resolve via `resolveWriteColumnFromConfigRows` to the SAME active column + cast the read side searches (legacy `embedding`::vector on pre-registry brains; a registry-routed brain no longer fails every write with a dimension mismatch against the legacy column). The INSERT column list, the `$N::vector|::halfvec(N)` cast, and every `embedding` reference in the ON CONFLICT CASE branches use the resolved column; it resets both the active column AND `embedded_at` to NULL when chunk_text changes without a new embedding. Pinned by `test/e2e/upsert-chunks-registry-column.test.ts` (PGLite always; Postgres DATABASE_URL-gated). `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — a superset of PGLite's probe set: the shared 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`) plus Postgres-blob-only probes for state the PGLite blob doesn't carry (`dream_verdicts.expires_at` — see the forward-reference-bootstrap.ts entry); 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/postgres-engine/forward-reference-bootstrap.ts` — `applyPostgresForwardReferenceBootstrap(conn)`: the forward-reference bootstrap for the RAW `SCHEMA_SQL` replay path (probe + patch every column/table the embedded schema blob forward-references but older brains don't have yet — single probe round-trip, idempotent, fast no-op when nothing is missing). Peeled out of `PostgresEngine` so BOTH replay entrypoints run it before the blob: `PostgresEngine.initSchema()` AND the standalone module-singleton `db.ts:initSchema()` (which previously replayed with NO bootstrap, wedging an upgrade-boundary brain on `CREATE INDEX` over a column the replayed blob predates). Callers MUST hold the initSchema advisory lock (key 42) on `conn` so concurrent bootstraps can't race on a transaction pooler. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap` in shape — keep in sync; covered by `test/schema-bootstrap-coverage.test.ts` (PGLite side) + `test/e2e/postgres-bootstrap.test.ts` (Postgres side).+- `src/core/postgres-engine/forward-reference-bootstrap.ts` — `applyPostgresForwardReferenceBootstrap(conn)`: the forward-reference bootstrap for the RAW `SCHEMA_SQL` replay path (probe + patch every column/table the embedded schema blob forward-references but older brains don't have yet — single probe round-trip, idempotent, fast no-op when nothing is missing). Peeled out of `PostgresEngine` so BOTH replay entrypoints run it before the blob: `PostgresEngine.initSchema()` AND the standalone module-singleton `db.ts:initSchema()` (which previously replayed with NO bootstrap, wedging an upgrade-boundary brain on `CREATE INDEX` over a column the replayed blob predates). Callers MUST hold the initSchema advisory lock (key 42) on `conn` so concurrent bootstraps can't race on a transaction pooler. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap` in shape — keep in sync; covered by `test/schema-bootstrap-coverage.test.ts` (PGLite A2 static check + the Postgres-blob CREATE-INDEX class-closure gate, which parses `SCHEMA_SQL` and requires every migration-added blob-indexed column to have a probe here or an explicit exemption) + `test/e2e/postgres-bootstrap.test.ts` (Postgres side, live convergence cases). Probes are column-only (nullable `ADD COLUMN`, plus `SET DEFAULT` where hardening the upgrade window needs it — `dream_verdicts.expires_at`); the owning migration stays the source of truth for backfill/constraints/indexes: on the engine path it runs right after the bootstrap under the same advisory lock, while the standalone `db.ts:initSchema` path replays the blob WITHOUT running migrations — safe because the NULL-tolerant read predicates treat pre-backfill rows as valid until the next full engine init.- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `countCJKAwareWords(s)` (30% density threshold — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS`, `pglite-engine.ts:searchKeyword + searchKeywordChunks`.- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Lossless invariant: non-overlapping portions reassemble to the original. Also strips the facts fence via `stripFactsFence({keepVisibility:['world']})` so private fact visibility tiers never reach embeddings.- `src/core/chunkers/semantic.ts` — embedding-based topic-boundary detection: embeds sentences, computes cosine-similarity valleys, smooths with a Savitzky-Golay filter (5-window, 3rd-order polynomial) to find chunk boundaries.@@ -253,7 +253,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch (#1963); it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it) and timed out 100% of the time on PGLite. Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands).- `src/core/source-config-sql.ts` + `src/core/sources-load.ts` — canonical recovery for historical non-object `sources.config` values. The application reader unwraps nested JSON strings and merges recoverable array fragments left-to-right; the shared SQL expression mirrors that policy atomically for both engines, source config updates, archive/restore, and the paste-ready `source_config_shape` doctor repair. `localFederatedSourceIds` reads config through the same parser so stdio/CLI federation cannot silently disagree with `sources list`. `sourceConfigHasRemoteUrl` uses that parser for autopilot pull policy, including PGLite's JSON-string config shape. Invalid fragments degrade to `{}` rather than throwing. Pinned by `test/sources-load.test.ts`, `test/job-pull-policy.test.ts`, `test/list-all-sources.test.ts`, `test/local-federated-search-scope.test.ts`, `test/destructive-guard.test.ts`, and `test/doctor-source-config-shape.test.ts`.- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the pre-guard routing), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `src/commands/sync.ts:1497-1519` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the #3242 widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases).-- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (#1941, opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (#2073, idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — NULL never matched a scoped `AND source_id = …` filter so scoped `code-callers`/`code-callees` returned 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (#4152, additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes). The dedup-index self-heal (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) is NOT version-gated: `runMigrations` invokes `repairTimelineDedupIndex` on every pass (including the no-pending early-return path) because a merge-renumbered migration can leave the version counter past the index change while the index stays the old shape. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).+- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). `Migration` interface carries `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses in a transaction; ignored on PGLite). Key migrations: v14 (handler branches on `engine.kind` for CONCURRENTLY-on-Postgres with invalid-remnant pre-drop via `pg_index.indisvalid`, plain `CREATE INDEX` on PGLite); v15 (`minion_jobs.max_stalled` default 1→5 + backfill non-terminal rows); v24 `rls_backfill_missing_tables` (`sqlFor: { pglite: '' }` no-op — PGLite has no RLS engine, targets subagent tables absent from pglite-schema.ts); v30 `dream_verdicts (file_path TEXT, content_hash TEXT, worth_processing BOOL, reasons JSONB, judged_at TIMESTAMPTZ, PK(file_path, content_hash))` (RLS-enabled under BYPASSRLS; synthesize reads/writes to avoid re-judging); v35 auto-RLS event trigger `auto_rls_on_create_table` fires on `ddl_command_end` for `WHEN TAG IN ('CREATE TABLE','CREATE TABLE AS','SELECT INTO')` running `ALTER TABLE … ENABLE ROW LEVEL SECURITY` on new `public.*` tables (no FORCE) + one-time backfill on every existing `public.*` base table whose comment doesn't match `^GBRAIN:RLS_EXEMPT\s+reason=\S.{3,}` (per-table failure aborts the offending CREATE TABLE; no EXCEPTION wrap; PGLite no-op via `sqlFor.pglite: ''`; breaking change: intentionally-RLS-off public tables need the GBRAIN:RLS_EXEMPT comment before upgrade); v40 `pages_emotional_weight` (`pages.emotional_weight REAL NOT NULL DEFAULT 0.0`, column-only metadata-only); v46 `mcp_request_log_params_jsonb_normalize` (`UPDATE ... SET params = params::text::jsonb WHERE jsonb_typeof(params) = 'string'`, idempotent); v60-v65 six-migration chain wiring source-scoping into `oauth_clients` — v60 (`oauth_clients_source_id_fk`: `source_id TEXT` NULL→`'default'` backfill + FK to `sources(id) ON DELETE SET NULL`), v61 (`federated_read TEXT[] NOT NULL DEFAULT '{}'`), v62 (explicit-CASE backfill so `source_id IS NULL` → `'{}'`), v63 (fail-loud check every row's source_id is in its federated_read array), v64 (FK flipped to `ON DELETE RESTRICT`), v65 (GIN index for array-containment); v68 `eval_candidates_embedding_column` (`eval_candidates.embedding_column TEXT NULL` per-row provenance for `gbrain eval replay` to reproduce the same retrieval space; NULL-tolerant); v108 `pages_embedding_signature` (`pages.embedding_signature TEXT NULL` = `<provider:model>:<dims>` stamped via `setPageEmbeddingSignature`; GRANDFATHER — stale predicate is `embedding_signature IS NOT NULL AND embedding_signature <> $current` so NULL is NEVER stale and upgrade never re-embeds the whole corpus; no index; metadata-only); v109 `sources_newest_content_at` (`sources.newest_content_at TIMESTAMPTZ` durable newest-COMMIT HEAD committer time written by `writeSyncAnchor`, read by the REMOTE staleness path instead of shelling to git; mirror in pglite-schema.ts + schema.sql + bootstrap probe); v110 `page_aliases` (`(id, source_id, alias_norm, slug, ...)` with `UNIQUE (source_id, alias_norm, slug)` + lookup indexes on `(source_id, alias_norm)` and `(source_id, slug)`; `alias_norm` is `normalizeAlias()` output so WRITE/READ key on the same form; also in `src/core/pglite-schema.ts`); v111 `search_telemetry_rank1_columns` (`ADD COLUMN IF NOT EXISTS` on both engines: `sum_rank1_score`, `count_rank1`, three buckets `rank1_lt_solid`/`rank1_solid`/`rank1_high` on `search_telemetry` — aggregate not per-query rows so rank-1 median drift is bounded-growth; ALTERs right after v57 which created the table); v114 `links_link_source_check_kebab_regex` (#1941, opens `link_source` from the closed allowlist to a kebab-case format gate `^[a-z][a-z0-9]*(-[a-z0-9]+)*$` + `char_length<=64`; Postgres branch uses `NOT VALID` + `VALIDATE CONSTRAINT` with `transaction:false`, PGLite plain DROP+ADD; existing built-ins all satisfy the regex so VALIDATE never fails on existing data); v116 `code_edges_source_backfill_and_callee_index` (#2073, idempotent: backfills NULL `code_edges_symbol`/`code_edges_chunk` `source_id` from each edge's `from_chunk` page — NULL never matched a scoped `AND source_id = …` filter so scoped `code-callers`/`code-callees` returned 0 rows on multi-source brains — plus plain `CREATE INDEX` on `from_symbol_qualified` for both edge tables, which had no index and seq-scanned per BFS node); v129 `dream_verdicts_triage_v1_columns` (#4152, additive `ADD COLUMN IF NOT EXISTS` widening `dream_verdicts` into a scored triage record — `score`, `content_type`, `segments`, `entities`, `model`, `triage_version`; legacy rows keep `score` NULL and read as cache misses, re-judged once; no backfill, no index; same SQL on both engines since `dream_verdicts` is migration-created on PGLite too, so the columns take the COLUMN_EXEMPTIONS route in `test/schema-bootstrap-coverage.test.ts` rather than bootstrap probes); v143 `dream_verdicts_ttl` (30-day `expires_at` TTL: nullable `ADD COLUMN` + `SET DEFAULT` run BEFORE the `judged_at`-derived backfill — statement order is load-bearing so a legacy writer racing the upgrade window picks up the default instead of inserting a NULL that would fail `SET NOT NULL` on every retry; on Postgres the schema blob's `dream_verdicts_expires_idx` forward-references the column, so `forward-reference-bootstrap.ts` probes + ALTERs it before the blob replays, and both engines' `getDreamVerdict` read predicate is NULL-tolerant — `expires_at IS NULL OR expires_at > now()` — so a pre-backfill row reads as a hit instead of silently re-judging the corpus). The dedup-index self-heal (`timeline_dedup_index`, see `timeline-dedup-repair.ts`) is NOT version-gated: `runMigrations` invokes `repairTimelineDedupIndex` on every pass (including the no-pending early-return path) because a merge-renumbered migration can leave the version counter past the index change while the index stays the old shape. `retry-matcher.ts` and `timeline-dedup-repair.ts` are static dependencies because `runMigrations()` executes from live engine initialization; the engine dynamic-import guard scans this file with both engine implementations. v95: `pages_dedup_partial_index` adds `CREATE INDEX pages_dedup_idx ON pages (source_id, content_hash) WHERE deleted_at IS NULL`. Postgres uses `CREATE INDEX CONCURRENTLY` with `transaction: false` + pre-drops any invalid remnant; PGLite uses plain `CREATE INDEX`. Powers `findDuplicatePage` hot path (O(log n) instead of O(n)). v74 `mcp_spend_log` uses BTREE on `(client_id, created_at)` + `(token_name, created_at)` — `date_trunc('day', TIMESTAMPTZ)` is NOT IMMUTABLE so can't appear in index expressions; a `created_at` range scan covers the per-day rollup. v75 `embedding_multimodal_column` is column-only (no HNSW index — deferred to post-reindex per pgvector best practice).- `src/cli.ts` — no-DB fallbacks announce themselves on stderr instead of degrading silently. `dream` dispatch binds the caught engine-connect error and emits `[dream] WARNING: could not connect to DB (...)` before falling through to filesystem-only phases; the `runDream(null, ...)` no-DB fallback is preserved (pinned by `test/cli-dream-engine-warn.test.ts`, 2 subprocess cases against good + bad DATABASE_URL). `doctor` dispatch does the same: when `connectEngine` OR the DB-backed `runDoctor` run throws, it emits `[doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks`, scrubbing the error message through BOTH `url-redact.ts:redactUrlsInText` and `redact-connection-info.ts:redactConnectionInfo` first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in `test/doctor-minions-check.test.ts`: stderr note present, credentials absent, stdout stays parseable `--json`).- `skills/conventions/brain-routing.md` — agent-facing convention skill documenting the canonical 6-tier source resolution chain (flag → env → dotfile → local_path → brain_default → seed_default) with paste-ready decision tables. Linked from CLAUDE.md's "Two organizational axes" section and from `gbrain sources current`'s hint output.- `test/operations-trust-boundary.test.ts` + `scripts/check-operations-filter-bypass.sh` — operations trust-boundary contract coverage. Pure assertions over all 74 ops (every op has a scope annotation; every mutating op has a non-read scope; `localOnly: true` ops are excluded from `operations.filter(op => !op.localOnly)`; the seven historically-sensitive localOnly ops snapshot-pinned by name) plus targeted handler-invocation regressions for the historically-broken HTTP-callable classes: `submit_job` with `name='shell'` + `ctx.remote=true` MUST reject (the HTTP MCP shell-job RCE class); `search_by_image` with `image_path` + `ctx.remote=true` MUST reject (the P0 image-leak class); and the list-op read-leak class — `find_orphans`/`get_recent_salience`/`find_anomalies`/`find_experts` invoked with `ctx.remote=true` over a seeded `visibility: private` page MUST NOT return its slug/title, with a local positive control proving the assertions non-vacuous, count self-consistency assertions pinning the no-count-oracle posture (both orphan denominators shrink with hidden rows; `excluded` untouched; anomaly `count` mirrors the visible slug list), and a soft-delete re-probe pinning the includeDeleted fail-closed path. `file_upload` and `sync_brain` omitted from handler-invocation tests because they're `localOnly: true` (that path would test an impossible production scenario). The shell guard greps `src/` for any module importing the `operations` value outside the canonical filter site at `src/commands/serve-http.ts` (three import shapes: destructured, aliased, namespace), with an explicit 10-entry allow-list + a literal-string check that `serve-http.ts` still contains `operations.filter(op => !op.localOnly)`. Wired into `bun run verify`. Dynamic sibling: `test/remote-privacy-sweep.test.ts` (next entry) — same doctrine, corpus-seeded, catches leaks in ops neither curated list has heard of yet.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 5e376e3f15..40e73468bd 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.47.4.0",+ "version": "0.47.5.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 3fa4e87076..167a174353 100644--- a/package.json+++ b/package.json@@ -172,7 +172,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.47.4.0",+ "version": "0.47.5.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.jsonindex d00ccd8dc4..066cb25330 100644--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.47.4.0",+ "version": "0.47.5.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.jsonindex a2a637996d..e9b72e3d3f 100644--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-coding",- "version": "0.47.4.0",+ "version": "0.47.5.0","description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.mdindex b87c3d8234..9f2b583da1 100644--- a/plugin-variants/gbrain-coding/README.md+++ b/plugin-variants/gbrain-coding/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.47.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.47.5.0 --># gbrain-coding (generated persona variant — do not hand-edit)Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.jsonindex ea79875576..8fc9656f1f 100644--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.47.4.0",+ "version": "0.47.5.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.jsonindex fe6f20a33b..bec392bdb0 100644--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "gbrain-daily",- "version": "0.47.4.0",+ "version": "0.47.5.0","description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)","author": {"name": "Garry Tan",diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.mdindex 686d7bbf33..824074a805 100644--- a/plugin-variants/gbrain-daily/README.md+++ b/plugin-variants/gbrain-daily/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.47.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.47.5.0 --># gbrain-daily (generated persona variant — do not hand-edit)Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.diff --git a/plugin/README.md b/plugin/README.mdindex bb85cf2e80..9b5bd3b989 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -1,4 +1,4 @@-<!-- gbrain-plugin-tree-stamp: 0.47.4.0 -->+<!-- gbrain-plugin-tree-stamp: 0.47.5.0 --># gbrain plugin skill tree (generated — do not hand-edit)This tree is the curated skill set for the gbrain Codex and Claude Codediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 6e1d080f68..dc0c0001f4 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -19,8 +19,8 @@ src/core/engine.ts 2550 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2189 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893src/core/migrate.ts 687 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482)src/core/operations.ts 321 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS-src/core/pglite-engine.ts 6164 ratchet grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up-src/core/postgres-engine.ts 5652 ratchet lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069)+src/core/pglite-engine.ts 6165 ratchet grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +1: #4657 NULL-tolerant verdict-read SQL comment (bootstrap window)+src/core/postgres-engine.ts 5653 ratchet lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +1: #4657 NULL-tolerant verdict-read SQL comment (bootstrap window)src/core/search/hybrid.ts 2971 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380)src/core/types.ts 1956 ratchet grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867)src/core/minions/queue.ts 2442 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic leasediff --git a/src/core/migrate.ts b/src/core/migrate.tsindex 45b864b80c..394477c752 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -6277,13 +6277,22 @@ export const MIGRATIONS: Migration[] = [// instead of gaining a fresh 30 days. The interval literal mirrors// DREAM_VERDICT_TTL_SECONDS (engine.ts) and the schema.sql default.idempotent: true,+ // Statement order matters (#4657 adversarial review): SET DEFAULT runs+ // BEFORE the backfill so a concurrent pre-v143 writer (e.g. an old+ // autopilot daemon judging transcripts mid-upgrade) inserts rows that+ // pick up the default instead of NULL — otherwise a NULL landing between+ // the backfill UPDATE and SET NOT NULL fails the migration on every+ // retry for as long as the legacy writer keeps writing. Safe to edit:+ // the ledger records no SQL checksum, recorded brains never re-run v143,+ // and the reordered form is idempotent for everyone else.sql: `ALTER TABLE dream_verdicts ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;+ ALTER TABLE dream_verdicts+ ALTER COLUMN expires_at SET DEFAULT (now() + interval '30 days');UPDATE dream_verdictsSET expires_at = judged_at + interval '30 days'WHERE expires_at IS NULL;ALTER TABLE dream_verdicts- ALTER COLUMN expires_at SET DEFAULT (now() + interval '30 days'),ALTER COLUMN expires_at SET NOT NULL;CREATE INDEX IF NOT EXISTS dream_verdicts_expires_idxON dream_verdicts (expires_at);diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 30df1b57fc..0e6931abb7 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1334,7 +1334,7 @@ export class PGLiteEngine implements BrainEngine {&& !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey&& !needsMinionJobsPrivateQueue) return;- process.stderr.write(' Pre-v0.21 brain detected, applying forward-reference bootstrap\n');+ process.stderr.write(' Schema forward-reference gap detected, applying bootstrap\n');if (needsPagesBootstrap) {// Mirror schema-embedded.ts shape for `sources` so the subsequent@@ -5186,7 +5186,8 @@ export class PGLiteEngine implements BrainEngine {score, content_type, segments, entities, model, triage_versionFROM dream_verdictsWHERE file_path = $1 AND content_hash = $2- AND expires_at > now()`,+ -- NULL = pre-TTL row in the #4657 bootstrap window; a miss here re-judges the corpus+ AND (expires_at IS NULL OR expires_at > now())`,[filePath, contentHash]);if (result.rows.length === 0) return null;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 63e04b739c..fa83f651ec 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -4417,7 +4417,8 @@ export class PostgresEngine implements BrainEngine {score, content_type, segments, entities, model, triage_versionFROM dream_verdictsWHERE file_path = ${filePath} AND content_hash = ${contentHash}- AND expires_at > now()+ -- NULL = pre-TTL row in the #4657 bootstrap window; a miss here re-judges the corpus+ AND (expires_at IS NULL OR expires_at > now())`;if (rows.length === 0) return null;const r = rows[0];diff --git a/src/core/postgres-engine/forward-reference-bootstrap.ts b/src/core/postgres-engine/forward-reference-bootstrap.tsindex 69cb158c00..216ebec6c4 100644--- a/src/core/postgres-engine/forward-reference-bootstrap.ts+++ b/src/core/postgres-engine/forward-reference-bootstrap.ts@@ -11,9 +11,13 @@//// Bootstrap state that SCHEMA_SQL forward-references but that older brains// don't have yet. Mirror of `PGLiteEngine#applyForwardReferenceBootstrap`-// in shape and intent. Keep in sync with the PGLite version; covered by-// `test/schema-bootstrap-coverage.test.ts` (PGLite side) and-// `test/e2e/postgres-bootstrap.test.ts` (Postgres side).+// in shape and intent — keep in sync, except where a forward reference is+// blob-specific (e.g. dream_verdicts.expires_at exists only in the Postgres+// blob; the PGLite blob carries no dream_verdicts). Covered by+// `test/schema-bootstrap-coverage.test.ts` (the PGLite A2 static check AND+// the Postgres-blob CREATE-INDEX class-closure gate, which parses THIS+// file's source) and `test/e2e/postgres-bootstrap.test.ts` (live Postgres+// convergence cases).import type postgres from 'postgres';@@ -64,6 +68,8 @@ const probeRows = await conn<{sources_archived_exists: boolean;sources_archived_at_exists: boolean;sources_archive_expires_at_exists: boolean;+ dream_verdicts_exists: boolean;+ dream_verdicts_expires_at_exists: boolean;}[]>`SELECTEXISTS (SELECT 1 FROM information_schema.tables@@ -165,7 +171,11 @@ const probeRows = await conn<{EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_owner_token') AS minion_jobs_pq_token_exists,EXISTS (SELECT 1 FROM information_schema.columns- WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_lease_until') AS minion_jobs_pq_lease_exists+ WHERE table_schema = current_schema() AND table_name = 'minion_jobs' AND column_name = 'private_queue_lease_until') AS minion_jobs_pq_lease_exists,+ EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = current_schema() AND table_name = 'dream_verdicts') AS dream_verdicts_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'dream_verdicts' AND column_name = 'expires_at') AS dream_verdicts_expires_at_exists`;const probe = probeRows[0]!;@@ -296,6 +306,13 @@ const needsMinionJobsIdempotencyKey = probeCr.minion_jobs_exists === trueconst needsMinionJobsPrivateQueue = probeCr.minion_jobs_exists === true&& (!probeCr.minion_jobs_pq_owner_exists || !probeCr.minion_jobs_pq_token_exists|| !probeCr.minion_jobs_pq_lease_exists);+// v143 (dream_verdicts_ttl, #4657): blob index dream_verdicts_expires_idx+// references expires_at, but the column only lands via migration v143 — a+// Postgres brain at schema v30-v142 (dream_verdicts exists since v30)+// wedges on the blob's CREATE INDEX before any migration runs. Same class+// as v121/v7; PGLite is unaffected (its blob carries no dream_verdicts).+const needsDreamVerdictsExpiresAt = probe.dream_verdicts_exists+ && !probe.dream_verdicts_expires_at_exists;if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap&& !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId@@ -310,9 +327,10 @@ if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap&& !needsPagesLinksExtractedAt&& !needsTimelineEventPageId&& !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey- && !needsMinionJobsPrivateQueue) return;+ && !needsMinionJobsPrivateQueue+ && !needsDreamVerdictsExpiresAt) return;-process.stderr.write(' Pre-v0.21 brain detected, applying forward-reference bootstrap\n');+process.stderr.write(' Schema forward-reference gap detected, applying bootstrap\n');if (needsPagesBootstrap) {// Mirror schema-embedded.ts's `sources` shape so the subsequent@@ -591,6 +609,24 @@ if (needsMinionJobsIdempotencyKey) {ALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS idempotency_key TEXT;`);}+if (needsDreamVerdictsExpiresAt) {+ // Nullable column + DEFAULT as TWO statements, deliberately:+ // - a single `ADD COLUMN ... DEFAULT` would stamp EXISTING rows via+ // PG11 fast-defaults, destroying v143's judged_at-derived backfill+ // (pre-TTL rows must keep their original age);+ // - SET DEFAULT after ADD affects only NEW rows, so a legacy writer+ // racing the upgrade window can't insert NULLs (and getDreamVerdict's+ // read predicate is NULL-tolerant for rows older than the default).+ // Migration v143 stays the source of truth for the backfill, SET NOT+ // NULL, and the index. On the engine path it runs right after bootstrap+ // under the same advisory lock; on the standalone db.ts:initSchema path+ // migrations do NOT run — the column stays nullable there until the next+ // full engine init, which the NULL-tolerant read predicate makes safe.+ await conn.unsafe(`+ ALTER TABLE dream_verdicts ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;+ ALTER TABLE dream_verdicts ALTER COLUMN expires_at SET DEFAULT (now() + interval '30 days');+ `);+}if (needsMinionJobsPrivateQueue) {// v0.46.26: blob indexes idx_minion_jobs_private_queue_recovery /// idx_minion_jobs_private_queue_owner reference the private-queuediff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 7b53598833..10185dae22 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.47.4.0 -->+<!-- gbrain-template-stamp: 0.47.5.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/dream-verdict-cache-ttl.test.ts b/test/dream-verdict-cache-ttl.test.tsindex 9f018d47a0..644b7f65f3 100644--- a/test/dream-verdict-cache-ttl.test.ts+++ b/test/dream-verdict-cache-ttl.test.ts@@ -114,6 +114,29 @@ describe('dream_verdicts TTL', () => {expect((await engine.getDreamVerdict('/tmp/rejudged.md', 'rejudged-hash'))?.score).toBe(0.9);});+ test('a NULL-expiry row (bootstrap window, pre-v143 backfill) reads as a hit and survives the sweep (#4657)', async () => {+ // Simulate the Postgres upgrade window: the forward-reference bootstrap+ // added expires_at nullable, but v143's backfill/NOT NULL haven't run+ // yet (e.g. a pooler-swallowed migration). A NULL row is a pre-TTL row:+ // a read miss here would silently re-judge the whole corpus with paid+ // LLM calls, and a sweep delete would drop a valid verdict. v143 stamps+ // NULL rows from judged_at when it eventually succeeds.+ await engine.executeRaw(`ALTER TABLE dream_verdicts ALTER COLUMN expires_at DROP NOT NULL`);+ try {+ await engine.putDreamVerdict('/tmp/window.md', 'window-hash', verdictInput({ score: 0.7 }));+ await engine.executeRaw(+ `UPDATE dream_verdicts SET expires_at = NULL WHERE content_hash = 'window-hash'`,+ );+ expect((await engine.getDreamVerdict('/tmp/window.md', 'window-hash'))?.score).toBe(0.7);+ expect(await engine.sweepDreamVerdicts()).toBe(0);+ } finally {+ await engine.executeRaw(+ `UPDATE dream_verdicts SET expires_at = now() + interval '30 days' WHERE expires_at IS NULL`,+ );+ await engine.executeRaw(`ALTER TABLE dream_verdicts ALTER COLUMN expires_at SET NOT NULL`);+ }+ });+test('expired rows miss on read and sweep deletes only expired rows', async () => {await engine.putDreamVerdict('/tmp/expired.md', 'expired-hash', verdictInput({worth_processing: false,diff --git a/test/e2e/postgres-bootstrap.test.ts b/test/e2e/postgres-bootstrap.test.tsindex 5ae990d7ff..f9ec98201b 100644--- a/test/e2e/postgres-bootstrap.test.ts+++ b/test/e2e/postgres-bootstrap.test.ts@@ -130,6 +130,53 @@ describe.skipIf(skip)('PostgresEngine forward-reference bootstrap (E2E)', () =>expect(idx).toHaveLength(2);}, 60_000);+ test('pre-v143 dream_verdicts shape (#4657 wedge class) converges on REAL Postgres', async () => {+ // #4657: blob CREATE INDEX dream_verdicts_expires_idx references+ // expires_at, added only by migration v143 — every Postgres brain at+ // schema v30-v142 wedged on connect. Rewind schema AND version to the+ // wedged cohort's state, seed a row so v143's judged_at-derived backfill+ // is exercised, then assert full initSchema convergence.+ await engine.initSchema();+ const conn = (engine as any).sql;+ await conn.unsafe(`+ DROP INDEX IF EXISTS dream_verdicts_expires_idx;+ ALTER TABLE dream_verdicts DROP COLUMN IF EXISTS expires_at;+ DELETE FROM dream_verdicts WHERE file_path = '/tmp/i4657.jsonl';+ INSERT INTO dream_verdicts (file_path, content_hash, worth_processing, judged_at)+ VALUES ('/tmp/i4657.jsonl', 'i4657hash', true, now() - interval '10 days');+ `);+ await engine.setConfig('version', '142');++ await engine.initSchema();++ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ // Column converged: NOT NULL with the 30-day default restored by v143.+ const col = await conn`+ SELECT is_nullable, column_default FROM information_schema.columns+ WHERE table_schema = current_schema()+ AND table_name = 'dream_verdicts' AND column_name = 'expires_at'+ `;+ expect(col).toHaveLength(1);+ expect(col[0].is_nullable).toBe('NO');+ expect(String(col[0].column_default)).toContain('30 days');+ // Pre-TTL row backfilled from judged_at, not stamped with a fresh 30 days.+ const row = await conn`+ SELECT (expires_at = judged_at + interval '30 days') AS backfilled+ FROM dream_verdicts WHERE file_path = '/tmp/i4657.jsonl'+ `;+ expect(row).toHaveLength(1);+ expect(row[0].backfilled).toBe(true);+ // Index restored.+ const idx = await conn`+ SELECT indexname FROM pg_indexes+ WHERE tablename = 'dream_verdicts' AND indexname = 'dream_verdicts_expires_idx'+ `;+ expect(idx).toHaveLength(1);+ // Clean up the seeded row so it doesn't leak into other suites sharing+ // the DATABASE_URL database (its expires_at sits ~20 days in the future).+ await conn.unsafe(`DELETE FROM dream_verdicts WHERE file_path = '/tmp/i4657.jsonl'`);+ }, 60_000);+test('pre-v7 minion_jobs shape (scanner-sweep wedge class) converges on REAL Postgres', async () => {await engine.initSchema();const conn = (engine as any).sql;diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 6ad0b05164..e000fc0674 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -1,6 +1,12 @@/**- * CI guard: PGLITE_SCHEMA_SQL must not forward-reference state that- * `applyForwardReferenceBootstrap` doesn't know how to create.+ * CI guard: NEITHER embedded schema blob may forward-reference state that+ * its engine's `applyForwardReferenceBootstrap` doesn't know how to create.+ * Two halves: the PGLite checks below guard PGLITE_SCHEMA_SQL against the+ * pglite-engine bootstrap; the #4657 Postgres-blob gate (end of file)+ * guards SCHEMA_SQL against src/core/postgres-engine/+ * forward-reference-bootstrap.ts. A reference covered on one blob is NOT+ * automatically covered on the other (dream_verdicts exists only in the+ * Postgres blob).** Background: gbrain ships an "embedded latest schema" blob* (`pglite-schema.ts`) for fast bootstraps, alongside a numbered migration@@ -18,9 +24,12 @@* `REQUIRED_BOOTSTRAP_COVERAGE`.** **When you add a new schema-blob forward reference:**- * 1. Extend `applyForwardReferenceBootstrap` in pglite-engine.ts +- * postgres-engine.ts to add the new state.- * 2. Add an entry to `REQUIRED_BOOTSTRAP_COVERAGE` below.+ * 1. Extend `applyForwardReferenceBootstrap` in pglite-engine.ts and/or+ * src/core/postgres-engine/forward-reference-bootstrap.ts (whichever+ * blob(s) carry the reference) to add the new state.+ * 2. Add an entry to `REQUIRED_BOOTSTRAP_COVERAGE` below (PGLite side);+ * the Postgres-blob gate is parser-driven and needs no registry entry+ * (an intentional non-probe goes in POSTGRES_INDEX_REF_EXEMPTIONS).* 3. This test will pass.** If you add a forward reference but skip step 1, this test fails. If you@@ -38,6 +47,10 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';// snapshot-loaded engine would skip the bootstrap entirely.delete process.env.GBRAIN_PGLITE_SNAPSHOT;+// Single home for the Postgres bootstrap's source path (moved once already,+// #4477 — keep the three source-pinning tests below on one literal).+const POSTGRES_BOOTSTRAP_PATH = 'src/core/postgres-engine/forward-reference-bootstrap.ts';+// Forward-reference targets that PGLITE_SCHEMA_SQL requires.// When you add a new one, extend this list AND the bootstrap.type ForwardReference =@@ -939,13 +952,16 @@ const COLUMN_EXEMPTIONS = new Set<string>([// statement shape, doctor's extract_health falls back to a 0-column// query). Column-only, no bootstrap probe needed.'extract_rollup_7d.expected_limit_count',- // #4069 (migration v143) — verdict TTL column. Same precedent as the- // triage-v1 columns above: dream_verdicts is migration-created on PGLite- // (v30, absent from PGLITE_SCHEMA_SQL), so no schema-blob forward- // reference can exist, and dream_verdicts_expires_idx is created INSIDE- // the same v143 migration. The migration chain always runs before any- // reader, so getDreamVerdict's expiry predicate sees the column on old- // brains too.+ // #4069 (migration v143) — verdict TTL column. The PGLite half of this+ // exemption is correct: dream_verdicts is migration-created on PGLite+ // (v30, absent from PGLITE_SCHEMA_SQL), so no PGLite-blob forward+ // reference exists. But the POSTGRES blob (src/schema.sql) DOES carry+ // dream_verdicts + dream_verdicts_expires_idx, which forward-references+ // this migration-added column — that gap wedged every pre-v143 Postgres+ // upgrade (#4657, 4th recurrence of the class). The Postgres bootstrap+ // now ALTERs it (probe dream_verdicts_expires_at_exists), pinned by the+ // Postgres-blob gate test below and the e2e pre-v143 convergence case.+ // This exemption only silences the PGLite column-only check.'dream_verdicts.expires_at',]);@@ -1078,7 +1094,7 @@ test('postgres-engine.ts bootstrap carries the private-queue ALTERs and probes (// #4477 peeled the Postgres forward-reference bootstrap out of the// postgres-engine.ts façade into its module dir; the guard follows the// block to its current home.- const enginePath = resolvePath(process.cwd(), 'src/core/postgres-engine/forward-reference-bootstrap.ts');+ const enginePath = resolvePath(process.cwd(), POSTGRES_BOOTSTRAP_PATH);const engineSrc = readFileSync(enginePath, 'utf-8');const normalized = engineSrc.replace(/\s+/g, ' ');@@ -1109,6 +1125,116 @@ test('postgres-engine.ts bootstrap carries the private-queue ALTERs and probes (}});+// ─────────────────────────────────────────────────────────────────+// #4657 class closure — the POSTGRES-blob half of the A2 static check.+// The A2 test above parses PGLITE_SCHEMA_SQL only, and the Postgres e2e pin+// (test/e2e/postgres-bootstrap.test.ts) is DATABASE_URL-gated — so a+// Postgres-blob-only CREATE INDEX forward reference+// (dream_verdicts.expires_at, #4657 — 4th recurrence of the+// #2537/#2703/#4477 class) broke zero locally-runnable tests. This gate is+// the locally-runnable Postgres half: every column referenced by a+// CREATE INDEX in the embedded Postgres blob (SCHEMA_SQL, generated from+// src/schema.sql) must be covered by CREATE-TABLE-presence-and-not-+// migration-added, or by an ALTER/CREATE TABLE in the Postgres bootstrap+// (src/core/postgres-engine/forward-reference-bootstrap.ts).+//+// Honest scope: CREATE INDEX column references only, on both schema blobs+// (the PGLite half is the A2 test above). Forward references through+// constraints, views, or trigger bodies are NOT parsed here — see the+// "Schema-bootstrap coverage follow-ups" entry in TODOS.md.+// ─────────────────────────────────────────────────────────────────++const POSTGRES_INDEX_REF_EXEMPTIONS = new Set<string>([+ // (empty — every current Postgres-blob CREATE INDEX forward reference has+ // a bootstrap probe. Add `table.column` entries here ONLY with a rationale+ // proving the reference cannot wedge a pre-existing brain.)+]);++test('every CREATE INDEX column in the Postgres SCHEMA_SQL blob is covered by CREATE TABLE or the Postgres bootstrap (#4657 class closure)', async () => {+ const { readFileSync } = await import('fs');+ const { resolve: resolvePath } = await import('path');+ const { SCHEMA_SQL } = await import('../src/core/schema-embedded.generated.ts');+ const { extractAddedColumnsFromMigrations } = await import('./helpers/extract-added-columns.ts');++ const bootstrapPath = resolvePath(process.cwd(), POSTGRES_BOOTSTRAP_PATH);+ const bootstrapSrc = readFileSync(bootstrapPath, 'utf-8');++ const tableColumns = parseBaseTableColumns(SCHEMA_SQL);+ const indexRefs = parseIndexColumnReferences(SCHEMA_SQL);+ const bootstrapAdds = parseAlterAddColumns(bootstrapSrc);+ // The bootstrap's inline `CREATE TABLE IF NOT EXISTS sources (...)` counts+ // as coverage too (same treatment as the PGLite column-only check).+ const bootstrapCreateTableCols = parseBaseTableColumns(bootstrapSrc);+ const migrationAddedKeys = new Set(+ extractAddedColumnsFromMigrations().map(a => `${a.table}.${a.column}`),+ );++ const basePredicate = buildIndexRefCoveragePredicate(tableColumns, bootstrapAdds, migrationAddedKeys);+ const covered = (table: string, column: string): boolean => {+ if (POSTGRES_INDEX_REF_EXEMPTIONS.has(`${table}.${column}`)) return true;+ if (basePredicate(table, column)) return true;+ // Bootstrap's inline CREATE TABLE counts ONLY for columns no migration+ // also adds — a migration-added column proves pre-existing tables can+ // lack it, and CREATE TABLE IF NOT EXISTS no-ops on those brains (the+ // exact v121 mask, which would otherwise re-enter through this channel).+ if (migrationAddedKeys.has(`${table}.${column}`)) return false;+ const bootCols = bootstrapCreateTableCols.get(table);+ return Boolean(bootCols && bootCols.has(column));+ };++ // Direct pin of the #4657 incident: migration-added, Postgres-blob-indexed,+ // and now bootstrap-covered.+ expect(migrationAddedKeys.has('dream_verdicts.expires_at')).toBe(true);+ expect(indexRefs.some(r => r.table === 'dream_verdicts' && r.column === 'expires_at')).toBe(true);+ expect(bootstrapAdds).toContainEqual({ table: 'dream_verdicts', column: 'expires_at' });+ expect(covered('dream_verdicts', 'expires_at')).toBe(true);++ // The contract: every Postgres-blob index column reference must be covered.+ const uncovered: Array<{ table: string; column: string }> = [];+ for (const ref of indexRefs) {+ if (!covered(ref.table, ref.column)) uncovered.push(ref);+ }++ if (uncovered.length > 0) {+ const list = [...new Set(uncovered.map(u => ` ${u.table}.${u.column}`))].join('\n');+ throw new Error(+ `The Postgres schema blob (src/schema.sql) has CREATE INDEX column reference(s) ` ++ `that are not safely covered (in the CREATE TABLE body AND not migration-added, ` ++ `or added by the Postgres forward-reference bootstrap):\n${list}\n\n` ++ `A column that is BOTH in the blob's CREATE TABLE AND added by a migration is a ` ++ `forward reference for pre-existing brains — CREATE TABLE IF NOT EXISTS no-ops on ` ++ `them, so the blob's CREATE INDEX wedges initSchema before runMigrations can help ` ++ `(the #4657 / v121 wedge class).\n` ++ `Fix: add a probe + column-only ALTER in ` ++ `src/core/postgres-engine/forward-reference-bootstrap.ts (the migration stays the ` ++ `source of truth for backfill/constraints/indexes), or add an exemption with a ` ++ `rationale to POSTGRES_INDEX_REF_EXEMPTIONS.`,+ );+ }+}, 30000);++test('postgres bootstrap carries the dream_verdicts.expires_at probe + ALTER (#4657 guard symmetry)', async () => {+ // Local half of the #4657 pin (the e2e pre-v143 convergence case is the+ // DATABASE_URL-gated live half). Deleting the bootstrap block must break+ // a locally-runnable test.+ const { readFileSync } = await import('fs');+ const { resolve: resolvePath } = await import('path');+ const bootstrapPath = resolvePath(process.cwd(), POSTGRES_BOOTSTRAP_PATH);+ const normalized = readFileSync(bootstrapPath, 'utf-8').replace(/\s+/g, ' ');+ expect(normalized).toContain('dream_verdicts_expires_at_exists');+ expect(normalized).toContain('ALTER TABLE dream_verdicts ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;');+ // The DEFAULT must be a SEPARATE statement (a one-statement ADD COLUMN+ // DEFAULT would fast-default EXISTING rows and destroy v143's+ // judged_at-derived backfill).+ expect(normalized).toContain("ALTER TABLE dream_verdicts ALTER COLUMN expires_at SET DEFAULT (now() + interval '30 days');");+ // Pin the WIRING, not just the strings: the flag must gate the early+ // return AND the ALTER block. A regression that keeps both strings but+ // drops the conjunction (or gates the ALTER on the wrong flag) would+ // otherwise stay green locally and only fail on the DATABASE_URL lane.+ expect(normalized).toContain('&& !needsDreamVerdictsExpiresAt');+ expect(normalized).toContain('if (needsDreamVerdictsExpiresAt)');+});+test('planted-bug: simulated unprovided column produces a clear failure message', async () => {// Negative case — regression guard. If the contract test silently passes// on uncovered columns, the gate is fake. This test plants a fake column