Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.59.10.0 fix: preserve memory across maintenance operations (#5658)

Garry Tan5fffbe5b9a4d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 72857acdec..0b8db854d3 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.59.8.0",
+ "version": "0.59.10.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index bf5e220e51..ebe1ae00e9 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.59.8.0",
+ "version": "0.59.10.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.github/workflows/native-locks.yml b/.github/workflows/native-locks.yml
index 129d32b508..602d28571a 100644
--- a/.github/workflows/native-locks.yml
+++ b/.github/workflows/native-locks.yml
@@ -89,6 +89,8 @@ jobs:
bun --no-env-file test --timeout=180000 test/persistence-git-publication.test.ts || status=1
bun --no-env-file test --timeout=180000 test/persistence-sync-origin-native.serial.test.ts || status=1
bun --no-env-file test --timeout=180000 test/backup-portability-native.serial.test.ts || status=1
+ bun --no-env-file test --timeout=180000 test/export-publication-native.serial.test.ts || status=1
+ bun --no-env-file test --timeout=180000 test/native-export-publication.test.ts || status=1
exit "$status"
- name: Build the published CLI platforms and verify persistent writes
if: matrix.target == 'linux-x64-glibc' || matrix.target == 'darwin-arm64'
@@ -204,5 +206,7 @@ jobs:
bun install --frozen-lockfile --ignore-scripts
bun scripts/native/verify.ts
bun test --timeout=60000 test/native-lock.test.ts test/pglite-lock.test.ts test/local-ipc-path.test.ts
+ bun --no-env-file test --timeout=180000 test/native-export-publication.test.ts
+ bun --no-env-file test --timeout=180000 test/export-publication-native.serial.test.ts
bun scripts/native/compiled-smoke.ts
'
diff --git a/AGENTS.md b/AGENTS.md
index 79e4d5c768..0850d9b334 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -167,6 +167,11 @@ Ship via the `/ship` skill, not by hand. The full release + contributor process
(CHANGELOG voice, version-locations sync, PR conventions, community-PR-wave) lives in
[`./docs/RELEASING.md`](./docs/RELEASING.md); read it before shipping.
+**Always use PATCH without asking**, including the initial release choice;
+override `/ship`'s MINOR/MAJOR prompts. Auto-allocate past collisions, sync all
+version stamps and the PR title, then report the number. This changes numbering
+only: scope, merge, deployment, paid-work and validation approvals still apply.
+
## Privacy
Never commit real names of people, companies, or funds into public artifacts. See the
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 1afb1dfd37..068b930a9f 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.59.8.0 -->
+<!-- gbrain-runbook-stamp: 0.59.10.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index beec4015d3..819b58672b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,103 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.59.10.0] - 2026-09-28
+
+**Memory maintenance preserves what it cannot safely rebuild and tells you what remains unfinished.**
+
+Changing how your brain searches should not erase information it cannot recreate.
+GBrain now checks that saved material can be rebuilt before replacing its search
+data. Archived material stays untouched. If something blocks the work, the command
+explains what needs attention instead of reporting success with unfinished work.
+Retries also remember the spending already authorized, including requests whose
+outcome is uncertain after an interruption.
+
+Forgetting one fact no longer sends every page in its source through a rewrite.
+Only the affected pages are updated, with unrelated content, search data and local
+changes preserved. Interrupted work keeps its recorded intent and resumes within
+the same boundaries.
+
+Exports now describe one consistent point in time. They include all selected pages
+within the documented resource limits, refuse conflicting names and occupied
+output paths, and leave an explicit incomplete marker if publication fails.
+Use a fresh destination for another export. Exported Markdown is still not a full
+database backup.
+
+Gmail imports distinguish attachments present, inspected with none found, not
+inspected, and incompletely inspected. Unavailable messages and threads are
+reported separately. An optional historical repair inspects metadata without
+downloading attachments or replacing your edited message text. It does not mean
+the attachments have been read or indexed.
+
+| Operation | What changes |
+|---|---|
+| Embedding migration | Saved facts participate in repair and completion checks; blocked archived work is reported before spending. |
+| Forgetting | Publication and retry work stay limited to the affected pages. |
+| Export | Conflicts fail before output, and interruption cannot look like a complete export. |
+| Gmail repair | Source-scoped, bounded metadata inspection preserves edits and withdrawals. |
+| MCP search | Provider timeouts remain distinguishable from genuine misses; source-binding warnings do not widen access. |
+
+Older fact vectors with unknown model identity are not treated as compatible
+merely because their dimensions match. Repair is explicit, not an automatic paid
+side effect of upgrading. The reported Windows/Hermes clean-miss issue remains
+unresolved; these diagnostics are not a claimed fix for that environment.
+
+## To take advantage of v0.59.10.0
+
+Stop old writers and verify an engine-appropriate full backup before upgrading.
+Do not run mixed old and new workers during migration. Follow
+[the upgrade guide](skills/migrations/v0.59.10.0.md); Markdown export is not a backup
+substitute.
+
+If the automatic upgrade did not finish its schema work, run
+`gbrain apply-migrations --yes --no-autopilot-install` only after those precautions.
+Inspect `gbrain migrate embeddings --status` and preview a chosen target with
+`--dry-run` before approving any paid repair. New migrations require an explicit
+finite `--max-cost-usd` total. Retained-vector refusals require
+the supported recovery described in [embedding migration](docs/guides/embedding-migration.md),
+not an override or an automatic archive restore.
+
+`forget` can now refuse with `withdrawal_capacity` before changing memory when
+discovery exceeds its safety limits: 12,000 source pages, 40,000 chunks, 40,000
+facts, 64 MiB of combined text or 256 affected pages. Additional manifest,
+per-batch and scan-time limits apply. Follow
+[withdrawal recovery](docs/guides/concurrent-writes.md#withdrawal-recovery)
+for investigation; there is no unsafe override or unchanged-retry workaround.
+
+### Itemized changes
+
+- **Embedding safety:** prepare eligible projections before invalidation, retain
+ protected archived/deleted data, preserve source and lease fences, and verify
+ fresh page/fact convergence before completion. Schema v166 records fact-vector
+ model and exact-text identity; incompatible or unknown generations are withheld
+ from semantic comparison. Paid migration attempts require durable bounded
+ authorization, including retries and verification calls.
+- **Migration replay:** retain existing fact and query-cache vector types and
+ widths when rebuilding supported indexes, instead of assuming the current
+ extension's preferred type. Malformed existing columns refuse without
+ rewriting stored data.
+- **Withdrawal safety:** discover exact affected pages before mutation and
+ persist bounded targets atomically with withdrawal intent. Legacy effect
+ recovery preserves unrelated pages and genuine conflicts.
+- **Export safety:** use a coherent snapshot, bounded staging, global path
+ preflight and native no-replace publication. Existing files and unrelated
+ destination content are never silently overwritten.
+- **Attachment visibility:** retain bounded MIME inspection receipts and expose
+ `gbrain google attachments backfill --source <id>` for preview. Explicit
+ `--yes` authorizes a bounded metadata-only batch on an existing managed source.
+ Traversal completion is distinct from complete inspection.
+- **Search diagnostics:** preserve timeout classification through wrapped
+ provider errors and warn about unresolved stdio source binding without
+ changing grants or revealing private matches.
+
+### For contributors
+
+Recovery coverage runs in separate PGLite and PostgreSQL lanes without increasing
+timeouts. Fixture provenance is explicit, temporary Git repositories do not
+depend on the host identity, and the MCP transport matrix participates in
+diff-aware test selection. Release instructions now default to patch numbering
+and resolve collisions without an approval prompt.
+
## [0.59.8.0] - 2026-09-28
**Pull request CI now finishes in about 10-12 minutes instead of 20-34.**
diff --git a/CLAUDE.md b/CLAUDE.md
index 073a2d0b56..0c098224ec 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -379,9 +379,10 @@ four numeric segments are required first. Historical 3-segment versions
DRIFT_STALE_PKG / DRIFT_UNEXPECTED, and refuses to proceed on
DRIFT_UNEXPECTED. This is why the two must move together.
-**Auto-renumber when needed; never ask.** Use `/ship`'s queue-aware allocator,
-update all version stamps and the PR title, then report the number. This overrides
-its ALREADY_BUMPED rebump prompt, not scope, merge or deployment approvals.
+**Always use PATCH without asking**, including the initial release choice;
+override `/ship`'s MINOR/MAJOR prompts. Auto-allocate past collisions, sync all
+version stamps and the PR title, then report the number. This changes numbering
+only: scope, merge, deployment, paid-work and validation approvals still apply.
CI rejects mismatched `VERSION`/`package.json` or versions not newer than master.
### Version consistency and conflict recovery
diff --git a/VERSION b/VERSION
index 1792efab27..dd4b94f925 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.59.8.0
+0.59.10.0
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 07fd5a9c49..709f23c972 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -158,3 +158,4 @@ src/core/shared-skills/setup.ts 1 engine_guard Trusted preactivation empty-sourc
src/core/shared-skills/optimizer.ts 0 coordinator Shared optimization preserves the exact approved closure and original grants in private staging; only accepted body changes reach put_skill with the original revision and stable request UUID.
src/core/persistence/import-prepare.ts 1 coordinator The prepared local import updates source_path only inside canonical publication; owner, input and target hashes, source confinement and knowledge-versus-skill boundary revalidate before apply.
src/core/persistence/grandfather.ts 2 coordinator Private migration intents preserve exact page/source/incarnation/revision identity and rollback snapshots; frontmatter/hash and existing text seals change only inside canonical file publication, without new embedding or fact-backstop effects.
+src/core/persistence/connector-google-receipts.ts 1 coordinator Account and message-owned Gmail receipt metadata changes only under canonical source/page locks, identity/revision and file guards; guarded projection installation preserves withdrawal overlays without replaying bodies or extracting facts.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 5739280cd8..a90ec10677 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -3,6 +3,8 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+Doctor's embedding-dimension warning treats existing chunks as existing data even when every vector is missing. It directs the operator to a verified database backup and a brain-wide migration preview, followed only by explicitly approved total spending authorization; it never recommends forced reinitialization for that case. `test/doctor.test.ts` pins this recovery guidance.
+
- `src/commands/doctor/checks/sync-failures.ts` — reads managed durable cursor/receipt state even when its compatibility ledger is absent. An unavailable read is unknown/warn, not healthy; local findings carry diagnostics and remote findings contain only source-scoped aggregates. Legacy remediation stays separate from explicit managed retry. Tests: `test/persistence-sync-failures.serial.test.ts`, `test/doctor-report-remote.serial.test.ts`.
- `src/commands/doctor.ts` — `gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit] [--no-migrate]`: health checks. `checkPostgresCancellationDriver` (`postgres_cancellation_driver`) inspects a real reserved runtime owner through the shared cancellation helper: unsupported `discard()` is a typed local failure with a repair link, connection/deadline failure is a warning, and PGLite is exempt. The bounded reserve releases late arrivals and does not make general engine connect require cancellation, preserving broken-install diagnostics. `--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. 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 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. the IRON-RULE guard banning stale verb names, the sync_freshness boundary matrix, the D4 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 checks: `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, 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.
@@ -27,4 +29,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE).
-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND no inline `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` pool shape remains). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed.
+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-helper-migration.test.ts` (asserts the helper is wired in AND no inline `let nextIdx = 0` + `Promise.all(Array.from({length: numWorkers}, ...))` pool shape remains). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed.
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index d039433b31..b95b88f278 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -25,6 +25,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/eval.ts` — `gbrain eval` command: single-run table + A/B config comparison. Sub-subcommand dispatch on `args[0]` routes `gbrain eval export` + `gbrain eval prune` + `gbrain eval replay` into session-capture handlers; bare `gbrain eval --qrels …` fall-through preserves the legacy IR-metrics flow. `gbrain eval cross-modal` is in the dispatch (the user-facing path is the cli.ts no-DB branch — `src/commands/eval.ts:cross-modal` only fires when callers re-enter with an existing engine).
+- `src/commands/export.ts` + `src/core/export-snapshot.ts` + `src/core/export-stage.ts` + `src/core/export-publish.ts` — local Markdown export collects source/page/canonical-withdrawal/tag/raw state in one export-scoped repeatable-read read-only transaction, using 256-key ID batches and private disk-backed SQLite staging. Primary-key page reads reuse the canonical withdrawal overlay without source-wide slug scans under stale planner statistics. Each 256-key batch groups by source and retains only one capacity-checked withdrawal ledger at a time; bodies with no literal `gbrain:facts:` marker skip normalization, while malformed/orphan markers still use canonical SQL fingerprinting. No engine defaults or shared migration iterators change. Explicit source selection is validated; restore-only selects one source and checks its recorded file path through the existing native path resolver. The manifest rejects unsafe paths, same/cross-source aliases, case/Unicode and file-prefix collisions before destination output, preserving the `<slug>.md` and `.raw/<name>.json` layout. Existing planned paths refuse rather than overwrite. The portable first-party native addon anchors no-follow directories and publishes leaves with atomic no-replace operations, retaining an exclusive persistent `.gbrain-export-status` marker; success requires flushed data and a final COMPLETE line. Unsupported native capabilities fail closed without a pathname fallback. A fresh destination is the retry path; unrelated files are never pruned. Fixed capacity/time limits fail visibly, never truncate. This is a historical snapshot, not a database backup or a sandbox against another same-user process renaming directories. See [safe export](../../storage-tiering.md#safe-export). Engine-free `export --help` documents scope, no-overwrite publication and incomplete-output recovery. Pinned by both-engine export safety/independent-roundtrip/snapshot/failure-release suites, the 100001-page scale fixture with staging bytes and full export SQL statement accounting, the native publication/compiled-wrapper suite, actual CLI help tests, and the PostgreSQL export E2E wrapper.
+
- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-workers.test.ts` + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. Managed bulk calls, including segmentation-only previews, refuse before queue or provider work; they are listed separately from the supported coordinated fact operation.
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. Both return `ExtractForSlugsResult { created, processed }`; `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.generated.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 5f6987377b..137cc0c764 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -60,3 +60,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.
- `src/commands/init-mode-picker.ts` — install-time mode recommendation, downstream-input cost matrix, and mandatory operator choice. Mode summaries describe payload knobs only. Expansion follows the command (`query` on unless opted out; `search` and memory verbs off), not the chosen mode; provider charges and downstream prompt caching are disclosed separately from GBrain result caching.
+
+- `src/core/embedding-migration-cli.ts` — pure, positive migration control contract, shared by the pre-engine CLI boundary and the command parser (re-exported by `commands/migrate-embeddings.ts`). Validates original argv as well as command arguments, so consumed global timeout/progress flags cannot evade validation. Unknown controls, unsupported equals forms, duplicate flags, missing values, invalid numeric ranges and unknown pace modes refuse rather than falling back, truncating, clamping or widening work. Only implemented globals are accepted; no new fact-only or deadline behavior. The flag-registry generator includes this peeled surface; the registry's embed/import unions do not define migration legality.
+- `test/migrate-embeddings-recovery-cli.serial.test.ts` — real migration CLI subprocesses over isolated synthetic PGLite brains. Pins recovery envelopes and private-safe help/stderr, then exercises unsupported scope/work flags, consumed timeout, malformed numeric controls, supported pacing/globals/status/help, zero dispatch and unchanged DB/config snapshots on both routes. Direct parser cases use the same adversarial matrix. Help directs deferred work back through the migration with the existing total authorization, never standalone/background embedding. The static `EMBEDDING_MIGRATION_RECOVERY` is shared with the local-only admin operation; its unchanged discriminators and restrictions remain covered by `test/migrate-embeddings-op-contract.serial.test.ts`. Archived pending projections still block destructive transitions; no silent restore or source exclusion is introduced.
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index 27983676ba..437ea7cd78 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -33,6 +33,12 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/hybrid.ts` — `Promise<SearchResult[]>` return shape. `onMeta?: (m: HybridSearchMeta) => void` callback so op-layer capture records what hybridSearch actually did; callers that don't need it leave it undefined. `HybridSearchOpts.queryEmbedFn?: (text) => Float32Array | Promise<Float32Array>` is the hermetic eval seam: when set, the TEXT vector arm's query embedding comes from this function instead of the gateway's query-embed path AND the no-embedding-provider keyword-only short-circuit is bypassed, so deterministic eval canaries (`gbrain eval gate --embedder deterministic`, `scripts/run-eval-canary.ts`) run the vector arm with no provider key; never set on production paths — absent, the production path is untouched, and bare `hybridSearch` never touches the semantic query cache so the seam can't poison `query_cache`. `HybridSearchOpts.types?: PageType[]` (on `SearchOpts`) threads a multi-type filter into per-engine `searchKeyword` + `searchVector` + `searchKeywordChunks` as `AND p.type = ANY($N::text[])` (primary consumer `gbrain whoknows`, filters to `['person','company']`); AND-applies alongside the single-value `type` filter. `hybridSearch` resolves the embedding column at the boundary via `resolveColumn(loadRegistry(cfg), opts.embedding_column, cfg)` from `src/core/search/embedding-column.ts`, threads the `ResolvedColumn` descriptor (not a raw string) into per-engine `searchVector`, and uses `isCacheSafe(resolved, cfg)` for the cache-skip decision so a repointed `embedding` builtin doesn't leak across vector spaces. `cosineReScore` calls `engine.getEmbeddingsByChunkIds(ids, resolved.name)` so rerank uses vectors from the active column, not the hardcoded OpenAI `embedding`, and hydrates each result's raw query↔chunk `cosine` onto `SearchResult` (the calibrated signal evidence and `--explain` consume). `SearchOpts.onVectorPoolMeta` reports bounded candidate incompleteness after up to three pool escalations. SQL limits and offsets are independent of ef_search, filtered short pools need an exhaustion witness, and Postgres alone can use one exact fallback inside the remaining deadline. Hybrid and direct image query paths publish the scoped details and recall-affecting degraded stage; an exhausted genuine small corpus does not emit a false warning. The `query` MCP op accepts `embedding_column` for per-call A/B; `search` (keyword-only) rejects it. Two post-fusion stages + evidence stamp: `applyTitleBoost(results, query, titleBoost, floorThreshold)` multiplies a result's score by the resolved `title_boost` when `isTitlePhraseMatch` fires, stamps `title_match_boost`, inherits the floor-ratio gate so a title match can't shove a much-stronger page below it; `applyAliasHop(engine, results, query, opts)` normalizes the query, calls `engine.resolveAliases`, and on exact normalized-alias match surfaces that page at top-of-organic + epsilon with `alias_hit=true`; `stampEvidence(...)` runs LAST (after the alias hop, before slice) on every path — keyword-only, no-embed, and full hybrid — so MCP callers and `--explain` read the same `evidence` + `create_safety` contract. `title_boost` resolved from the mode bundle and threaded in. `runPostFusionStages` has a 4th stage (`graphSignalsEnabled`, `onGraphMeta`, `onScoreDistribution`). `base_score` stamped at function entry idempotently (captured ONCE before any boost stage mutates `score`). Each post-fusion stage stamps its multiplier: `applyBacklinkBoost`→`backlink_boost`, `applySalienceBoost`→`salience_boost`, `applyRecencyBoost`→`recency_boost`. `applyReranker` (earlier in the pipeline) stamps `reranker_delta` as a rank delta (positive = improved). `applyExactMatchBoost` in `src/core/search/intent-weights.ts` stamps `exact_match_boost` when fired. Per-stage attribution powers `gbrain search --explain` — every boost surface carries its own field so `formatResultsExplain` reads them all without coupling to internal stage ordering. with `src/core/search/sql-ranking.ts` + `src/core/operations.ts` + `src/core/types.ts`: agent-warning channel. `SearchResult.content_flag?: {reason, detail}` (optional field in `types.ts`) is stamped post-fusion by `stampContentFlags` (the `stampEvidence` precedent) in `hybridSearch` AND in the keyword-only `search` MCP op so both retrieval paths surface the marker. `get_page` returns a top-level `content_flag` parallel field via `getContentFlag(page.frontmatter)`. `buildVisibilityClause` (sql-ranking.ts) ANDs in `QUARANTINE_FILTER_FRAGMENT` so quarantined pages are excluded from all six search call sites (alongside soft-delete + archived-source filters). Pinned by `test/sql-ranking.test.ts` + `test/e2e/quarantine-search-exclusion.test.ts`. Cross-modal routing at the embed step: `effectiveModality` resolves per-call `opts.crossModal` (literal `'auto'` → undefined) → `suggestions.suggestedModality` → `'text'`. Image route: `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_image'})`, skipping expansion + keyword. `'both'` route: parallel text + image vector searches merged via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the configured cross-modal weights. Unified routing fires when `search.unified_multimodal` is true — bypasses dual-column branching, runs `embedQueryMultimodal` + `searchVector({embeddingColumn: 'embedding_multimodal'})`, fail-open on zero rows (non-strict falls through to dual-column). LLM modality escalation fires only when no explicit per-call opt is set AND the regex returned `'text'` AND `search.cross_modal.llm_intent` is on AND `isAmbiguousModalityQuery` fires; fail-open on every error. `compiledTruthBoost(result, applyBoost)` is exported for direct predicate tests: a synthetic chunkless title row (`chunk_id === 0` AND blank `chunk_text`) never receives the 2x compiled-truth boost (`test/search/compiled-truth-boost.test.ts`). The reranker pass-through callback is typed with `RerankPassThroughReason` imported from `rerank.ts` — one union, not a re-declaration. RRF inputs are assembled by ONE `composeFusionLists` call (next entry) over role-tagged `vectorArms` built with `pushVectorList` at every assembly site (unified, image-only, text/both, and the `allSettled` salvage path — where the `original` role additionally requires the original's `searchVector` to have succeeded); after `expandFn`, `queries[0]` is re-enforced to be the caller's query and repeats are deduped, so a variant can never take the anchor role. `HybridSearchOpts.onRerankPool` (eval-only, best-effort) fires immediately before `applyAutocut` with the exact pre-autocut `returnPool` — post alias-hop / exact-lookup / adaptive-return, unscored injected rows included, even when autocut is off — plus the deduped pre-rerank order, so an offline autocut replay is byte-faithful. Immediately after `applyReranker` — only when it actually reordered (`reranked !== deduped`) and never for image modality — `pinRelationalRows` (`relational-rerank-pin.ts`) re-pins the relational arm's rows above the reranked text rows bounded by `resolvedMode.relational_rerank_pin`, stamps `relational_pinned`, and emits `HybridSearchMeta.relational_rerank_pin`; `ensureRelationalEvidenceSlot` still runs after autocut (usually a no-op on relational queries now — it remains the page-1 guarantee for pin 0, reranker fail-open, and arm rows dropped before the pin).
+ `embedQueryBounded` preserves its own expired signal's timeout reason when
+ the gateway wraps transport cancellation, keeping `embed_timeout` stable
+ regardless of which deadline path wins. Provider failures before that deadline
+ retain their classification. The timeout budget and keyword fallback are unchanged;
+ pinned by `test/search/query-embed-deadline.test.ts` and the real transport matrix.
+
- `src/core/search/image-loader.ts` — `loadImageInput(input, opts)` accepts a local path, `data:` URI, or `http(s)://` URL. Magic-byte sniff for PNG/JPEG/WebP. Hard size cap (default 10 MB, configurable via `search.image_query.max_bytes`). URLs route through `fetchWithSSRFGuard` so DNS rebinding + redirect chains are defeated; shared guarded transport pins validated DNS answers and streams decoded bodies with a 2 MiB remote cap (10 MiB local cap). `ImageLoadError` with discriminated `code` (INVALID_FORMAT / OVERSIZED / INVALID_URL / FETCH_FAILED / TIMEOUT / SSRF_BLOCKED / NOT_FOUND).
- `src/core/search/llm-intent.ts` — opt-in LLM modality tie-break. `classifyModalityWithLLM(query, fallback)` routes through `gateway.chat()` with a fixed single-word-output system prompt; 1s timeout via AbortController. `parseModality(raw, fallback)` is the pure parser (tolerates trailing punctuation + casing). Fail-open on every error (gateway unavailable, timeout, parse failure, unrecognized output) — returns the fallback so a misbehaving LLM can never break search. Cost-bounded by `isAmbiguousModalityQuery` in `query-intent.ts` so the LLM call fires on only a small fraction of queries when on.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 9496a31429..91d1ac65f7 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -1,5 +1,7 @@
# Key files: Core Services (2/3)
+- `src/core/persistence/connector-google-receipts.ts` — the managed Google attachment-repair preparer checks account/thread/message ownership from the current canonical snapshot, changes only the owned receipt frontmatter field, and installs provider-free text projections under the existing source-before-page publication locks. Page identity/revision, current authorization, source incarnation and file recovery guards remain mandatory; body, unrelated frontmatter, tags and the withdrawal ledger are preserved. It schedules no embeddings, loop detection or fact extraction. `connector-sync.ts` admits this narrow mutation and banks its committed receipts through the existing managed connector checkpoints.
+
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
@@ -17,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).
-- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` — durable withdrawal key is `(source_id, visibility, SHA256(normalized claim))`; entity/page names are excluded so rename and index recreation do not restore it. Normalization folds case and whitespace, not meaning. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim before embedding, using the protocol error envelope. Ordinary TTL/supersession expiry creates no withdrawal. Migration backfill only trusts explicit `forgotten:` markers; old unmarked DB-only intent cannot be inferred. Markdown-only copies do not preserve DB-only withdrawals.
+- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, SHA256(normalized claim))`; entity/page names are excluded so rename and index recreation do not restore it. Normalization folds case and whitespace, not meaning. Bounded exact discovery parses canonical rows and verifies fingerprints with database normalization before mutation, refusing matching malformed evidence or row/byte/target capacity exhaustion. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim before embedding, using the protocol error envelope. Ordinary TTL/supersession expiry creates no withdrawal. Migration backfill only trusts explicit `forgotten:` markers; old unmarked DB-only intent cannot be inferred. Markdown-only copies do not preserve DB-only withdrawals.
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + forgetFactInFence(old) + superseded_by link; DB path: engine insertFact supersedeId). Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug.
@@ -45,6 +47,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. Recovery preserves compatible legacy NULL-hash vectors without stamping provenance; non-NULL hash, model, context or chunk-identity drift still invalidates them. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.
+ Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.
+
- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.
- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks.
@@ -71,7 +75,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three fixed-size source scans with durable slug cursors. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts.
- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index ccbcc9fe41..92b92814b4 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -3,6 +3,8 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+- Primary `searchVector` generation filters in both engines require the resolved model and either a current embedded-text hash or a grandfathered pre-v133 NULL hash. A budget/resume marker alone never changes a matching-model legacy vector's eligibility; known stale hashes and incompatible models remain excluded. This does not infer provenance for legacy fact vectors. `test/legacy-vector-compatibility.test.ts` and its PostgreSQL wrapper pin actual hybrid retrieval through a failed provider probe and retained migration marker without rewriting stored vectors.
+
- `src/core/connection-manager.ts` — routes ordinary and direct Postgres pools. Supabase-shaped URLs retain automatic derivation; a valid explicit `GBRAIN_DIRECT_DATABASE_URL` or constructor override also enables dual routing for generic Postgres and PgBouncer on custom ports. The kill switch and inherited parent route stay authoritative. `describeMode()` reports the same route used by `ddl()` and `bulk()`. Regression coverage: `test/connection-manager.serial.test.ts` and the real 24-case persistence runtime matrix.
- `src/core/context-engine.ts` + `src/openclaw-context-engine.ts` — the deterministic context engine OpenClaw loads on every turn (`assemble()` injects the Live Context block, zero-LLM). `createGBrainContextEngine({workspaceDir, resolveEntities?})` accepts an OPTIONAL host-injected resolver (`ENGINE_API_VERSION` 0.3.0, additive — older hosts work unchanged; the plugin entry maps `ctx.resolveEntities`/`ctx.brainQuery` onto it). Checkpoint compaction: `compact()` runs a time-bounded (8s), fail-open, lazily-imported checkpoint step BEFORE delegating — spools the since-last-boundary window (openclaw tail reader over the exported adapter mapper, 40-turn cap = the no-prior-boundary fallback) as a content-addressed corpus segment + ledger entry, then rung 2 (PGLite: one `bankOnly`+`flushCorpusFile` IPC round trip to serve) or rung 3 (Postgres: inline harvest over the reflex ladder's exported `getDirectPostgresEngine` singleton, under sweep claim fencing + capability/kill-switch gates, abort post-check) — and rides an additive `result.gbrain_checkpoint` bag on the delegate's return (`ownsCompaction` stays false). After the segment is spooled, the Memorable receipt lane runs (gate + stamp via `memorableGateAllowed`, span-filtered redacted tool calls, `recordAndRelayReceipt` with `harness: 'openclaw'` — per-compaction capture, content-hash dedup on retries, fail-open for the checkpoint; the whole block is skipped once the host's compact() deadline has fired; the rendered segment text is re-scanned with highEntropy at receipt time and the relay REFUSED fail-closed on any hit — the segment rendering feeds the ledger hash and cannot change, so the next compaction window re-evaluates; this lane NEVER compacts the receipts file — the hook lane is the ONE compactor, single-rewriter rule — but DOES trim the relay file, since an openclaw-only host has no hook lane and converging newest-keeping trims make concurrent trims safe). `assemble()` consumes `sessionId ?? sessionKey` and splices a deterministic envelope-bearing Compaction-checkpoint block at parts[1] (after Live Context) from the banked manifest via an in-process memo + hash-keyed polls (≤5; stale manifests can't satisfy a poll for the new segment; no manifest ⇒ byte-identical output). `assemble()` runs the Retrieval Reflex after the Live Context block: extracts the current turn's user text, builds prior-context text (every message EXCEPT the current turn — suppression must not see the triggering mention), passes the rolling window (`getWindowTurns`, last 12 user/assistant turns; the reflex slices to its configured `retrieval_reflex_window_turns`), and appends the pointer block. `warmReflex()` fires at construction. Current-host plugin factories may be called with zero arguments. The host workspace takes precedence; ambiguous/unbound legacy fallback warns and reads no source. The canonical slot ID is `gbrain-context-engine`; `gbrain-context` remains a registry alias, not a current-host slot alias. The exclusive context-engine contract and no-write stateless admitted-turn acknowledgement are additive. `assemble` uses an authoritative separate prompt: sqlite transcript-storage metadata fences historic turns, whereas an identical final legacy user message already represents the current turn. Reflex-only synthesis leaves messages intact; absent prompt keeps message extraction. These contracts do not prove model recall.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 899d408968..42b2fe9fc5 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -9,7 +9,7 @@
- `src/core/serve-service.ts` — the persistent-service half of `mcp expose`, everything under `gbrainPath('serve')` (`serveDir`, `adminTokenPath`, `wrapperPath`, `receiptPath`, `serveLogPath`, `serveErrPath`) so `GBRAIN_HOME` is honored. `SERVE_LAUNCHD_LABEL = 'com.gbrain.serve'`, `SERVE_SYSTEMD_UNIT = 'gbrain-serve.service'`, `detectServiceTarget(signals)` → `'macos' | 'linux-systemd' | 'none'` (a working user bus is required for systemd; cloud sandboxes and ephemeral containers fall to `none`). `renderServeWrapper` produces the 0755 launcher that sources the shell profiles and `~/.gbrain/env`, prepends the Bun dir to `PATH`, reads the admin token from its file at run time into `GBRAIN_ADMIN_BOOTSTRAP_TOKEN` (the token is never written into the wrapper, plist or unit), resolves `gbrain` the way autopilot's wrapper does (baked installer path, `type -P gbrain` fallback) and `exec`s `serve --http --port N --public-url URL [--surface] [--enable-dcr]`. `resolveServeGbrainCommand({ which, execPath, argv1, metaUrl, fileExists })` picks the baked program: a `gbrain` on PATH wins; a COMPILED binary — `import.meta.url` (or the injected `metaUrl`) under `/$bunfs/`, or an `execPath` that is not the bun runtime while `argv[1]` is absent/virtual — is `[execPath]` whatever its basename (release assets are renamed); otherwise the `[bun, <cli.ts>]` dev form only when that `cli.ts` exists on disk, else `[execPath]` rather than a path that cannot run; `renderServeLaunchdPlist` (RunAtLoad, KeepAlive, ThrottleInterval 30, logs to `serve.log` / `serve.err`, local `escapeXml`) and `renderServeSystemdUnit` (After=network-online.target, Restart=always, RestartSec=10, start-limit window; systemd specifiers escaped — `%` → `%%` in `ExecStart` and both `append:` log paths, `$` → `$$` in `ExecStart`). `ensureAdminToken` (0700 dir, 0600 file created with `wx` semantics, 64 hex chars; reuse a file matching the exported `ADMIN_TOKEN_SHAPE` = `^[A-Za-z0-9_-]{32,}$` — the same regex `serve-http.ts`'s `resolveBootstrapToken` accepts, so the file and the env var can never disagree on what a valid token is — unlink and regenerate otherwise), `installServeService` (launchd: domain-explicit `launchctl bootout gui/<uid> <plist>` — failure ignored — then `launchctl bootstrap gui/<uid> <plist>`, both through the one `launchctl(run, uid, plist, { modern, legacy })` helper whose legacy `launchctl unload` / `load` fallback is used ONLY when the modern verb exits non-zero with stderr matching `/Unknown command|unrecognized|not found/i`, never on a genuine failure or a killed call, and which reports the `verb` whose result it returns; a bootstrap that fails with stderr matching `LAUNCHCTL_SETTLE_RE` (`Input/output error`, `already in progress`, `\b5\b`, `\b37\b` — launchd still unloading the previous job) is retried up to `LAUNCHCTL_SETTLE_RETRIES` (5) times, `LAUNCHCTL_SETTLE_MS` (1s) apart through the injectable `sleep` param (default `setTimeout`; `mcp-expose.ts` passes `d.sleep`), a success after retries is a note and an exhausted retry appends "(after N settle retries)" to `error`; systemd: `daemon-reload` → `enable` → `restart` so a regenerated wrapper takes effect; `loginctl enable-linger` best effort) / `uninstallServeService` (launchd: the same `bootout gui/<uid>` with the same fallback; a bootout that exits non-zero — or is killed — with stderr NOT matching `LAUNCHCTL_NOT_LOADED_RE` (`No such process|not loaded|Could not find|not find service`) pushes `launchctl <verb> failed: <describeFailure>` into `notes`, and the exported `launchdBootoutFailed(result)` recognizes that note so `mcp-expose.ts` can say the job may still be loaded) / `serveServiceState` (`launchctl print gui/<uid>/<label>` / `systemctl --user is-active`); all three take `uid?: number` defaulting to `process.getuid?.() ?? 501`, threaded from `mcp-expose.ts`. Every supervisor subprocess carries a timeout — 60s for `launchctl bootstrap/bootout` (and the legacy `load/unload`) and `systemctl --user enable/restart/disable`, 15s for `launchctl print`, `daemon-reload`, `is-active` and `loginctl enable-linger` — and a `status: null` (killed) result counts as a failure (`error` / note) or `unknown` state; a failed call is described by `describeFailure` (its stderr, else stdout, else `exit <status>`). `readExposeReceipt` / `writeExposeReceipt` (`expose.json`, 0600, version 1, no secrets): the reader is a structural shape guard, not just `version`/`port`/`public_url` — it also requires `mode` in `tailnet|funnel`, a `service` object with a string `wrapper_path`, a `target` in `macos|linux-systemd|none`, a string `state` and string-or-null `plist_path` / `unit_path`, a `tailscale` object whose `binary` / `dns_name` are string-or-null, and string `mcp_url` / `admin_url` / `admin_token_file`; anything less is null (absent), so `--status` / `--remove` never dereference a half-written receipt. The token, receipt, wrapper, plist and unit writers refuse (clear error) when the target path is a symlink (`lstatSync`) before any supervisor call runs. Uses `shellQuote` from `src/core/mcp-registration.ts`; every filesystem/exec effect is behind injectable deps.
- `src/core/harness/verify.ts` — Randomized server-side memory verification with revision-conditional cleanup and retained mutation UUIDs, with separate transport, identity, authority, read, write/readback, delegation and cleanup verdicts. Lost mutation responses are reconciled before retry; server success never certifies native-harness activation or cross-conversation behavior.
-- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work. `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL.
+- `src/core/persistence/memory-mutations.ts` + `memory-prepare.ts` — managed `remember`, `forget`, and `forget_fact`: durable same-ID replay precedes entity/TTL/provider work; semantic append preparation preserves hidden canonical fences and revalidates dedup under page guards. Embedding preparation records the stored model/dimension generation and publication compares it under transaction row locks, preserving unchanged runtime overrides while refusing intervening migrations; fact vectors retain their actual provider model. Withdrawal admits and completes in one source-exclusive database transaction, independent of filesystem ownership, with durable mirror/projection work. `src/core/facts/single-prepare.ts` isolates provider preparation from the SQL-only semantic decision and propagates cooperative provider abort without degrading it into success. Preparation checkpoints prevent a late aborted result from reaching publication. Tests: `test/persistence-memory-mutations.test.ts` runs identical races on PGLite and PostgreSQL.
- `src/core/page-state/import-guard.ts` — imported canonical bytes publish only after source/page identity and knowledge-revision CAS, including unchanged-file and legacy hash-repair paths. Prepared same-hash imports compare full canonical metadata and additive tags, since captured timestamps are excluded from content hashes. Tests: `import-revision-concurrency.test.ts`.
- `src/core/persistence/{maintenance,root-registry,filesystem-guard,writer-guard-schema}.ts` — fail-closed legacy writer coverage: durable private refusal records and shared refusal-only root markers work before PGLite connect, resolve symlink ancestors, and retain stale roots conservatively. The selected PGLite path is registered at connect/init and source claim refresh, so managed reinit refuses even offline; unmanaged backup acquires the stable sibling native lock through rename. SQL guards include free-text aliases and canonical source sync checkpoints. `docs/architecture/canonical-writers.tsv` is the finite writer census; `canonical-writer-inventory.test.ts` rejects unreviewed additions, and `persistence-writer-fences.test.ts`/`pglite-maintenance-fence.test.ts` exercise real engines, competing processes and separate homes.
@@ -20,7 +20,7 @@
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
-- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. Fingerprints match independently in each fence, including inactive history; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
+- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.serial.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.
-- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page.
+- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page.
- `src/commands/migrations/v0_32_2.ts` — fences live legacy facts only onto an existing source-scoped page and its recorded canonical file. Missing pages/files are counted as `skipped_no_page`, never materialized as stubs. Dirty-tree checks stay inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired.
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index 91e1e9f647..325973b4f1 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -8,6 +8,11 @@ Hosted-relay server design: `docs/designs/HOSTED_OAUTH_RELAY.md` (the CLI-side
seams are frozen in this repo; the server is gbrain.io's build). Agent-facing
operation: `skills/google-loops/SKILL.md`.
+Historical Gmail repair selects explicit nested MIME metadata fields, excluding `body.data` at every depth. Depth-33 child sentinels preserve incomplete inspection beyond the depth-32 traversal bound. Its decoded HTTP response is capped at 2 MiB before JSON parsing; overflow cancels the stream and preserves the affected page/cursor. Ordinary sync's body requests remain unchanged.
+
+- `src/core/google/attachment-receipts.ts` — bounded iterative Gmail MIME inspection and inert receipt rendering. Per-message depth/part limits and a per-thread aggregate byte budget distinguish not-inspected, incomplete, inspected-none and present-not-downloaded/not-indexed states. Receipt identity includes account, message and MIME part/path; body parts, inline assets and calendar documents are distinguished. `google-clients.ts` retains these receipts and `google-render.ts` stores them in connector-owned `gmail_attachment_receipts` frontmatter alongside readable per-message summaries.
+- `src/core/google/attachment-backfill.ts` + `src/commands/google-attachments.ts` — `google attachments backfill --source` previews imported-thread scope without Google calls; explicit `--yes` runs at most 25 metadata-only repairs through an existing managed source. Account-bound keyset checkpoints use a fixed historical page-ID boundary and advance only after committed receipts. Confirmed thread 404s and missing historical message IDs retain prior metadata with explicit unavailable diagnostics, advance traversal, and count separately from inspected pages; traversal completion is not inspection completeness. Malformed or otherwise incomplete inspection stops before the affected page; conflicts preserve edits and withdrawals. This local-only path never enables persistence or services, downloads attachment content, or invokes loop/fact extraction. Incremental sync does not imply historical completeness. Tests: `google-attachment-{receipts,sync,backfill,recovery}.test.ts` cover normalization, real managed publication on both engines, private visibility, races, and SIGKILL recovery.
+
- `src/core/creds/vault.ts` — the generic credential vault: one home for every outbound credential gbrain holds (Google OAuth today; provider-agnostic by design, providers register under `src/core/creds/providers/`). Two backends behind one frozen interface: `FileVaultBackend` (`~/.gbrain/credentials.json`, 0600, atomic writes — the CLI/self-host default) and the DB-backed `EngineVaultBackend` shape hosted gbrain.io implements. Custody rules: secrets live ONLY in the vault (never the config plane; `sources.config` stores a credential-id pointer, mirroring how github sources store an env NAME); `list()` returns redacted metadata only. No CLI imports — prompts live in `src/commands/`.
- `src/core/creds/errors.ts` — the typed credential error catalog (`CredentialError`): every connect/refresh failure a user can hit maps to one code with four user-facing fields (`{code, problem, cause, fix, doc_url}`), rendered two ways — a conversational fix-first one-liner (stderr / `[SHOW USER]` blocks) and structured JSON (`--json` envelopes). Single source of truth for the troubleshooting table in `docs/guides/google-connect.md` — update both together. No CLI imports; hosted reuses it.
- `src/core/creds/providers/google.ts` — Google OAuth2 client, BYO + relay-minted; hand-rolled fetch (no googleapis dependency, `fetchImpl`-injectable). PKCE S256 with `access_type=offline&prompt=consent` so a refresh token is always minted; `client_ref` on the vault entry routes refresh (`byo` → direct against the Google token endpoint with the user's own client; `hosted-relay` → through the relay). `invalid_grant` is sub-classified into the catalog: clock skew (local clock vs Google's `Date` response header), the 7-day Testing-mode expiry (age heuristic on last_refresh_ok_at/connected_at), and plain revocation. `GOOGLE_SERVICE_SCOPES` is read-only by construction — the connector never writes to Google.
@@ -23,7 +28,7 @@ operation: `skills/google-loops/SKILL.md`.
- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. Eligible managed loop-extraction jobs refuse with `writer_coordinator_required` before chat; disabled, missing-page and suppressed cases retain their existing no-work outcomes.
- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.
- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. The result carries the google sources' last-successful-sync ages + a `stale` flag (>24h) so callers can refuse stale-but-confident output on a trust-critical surface. Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly.
-- `src/commands/google.ts` — `gbrain google connect|status|calendars|disconnect` (+ `setup` dispatch). Agent-first contract: every subcommand supports `--json` emitting `{ ok, status, next_action: { command?, user_message? }, error? }` (`calendars` adds `account` + `calendars[]` — id/summary/primary/accessRole — and carries the `sources add --calendar-id` template in `next_action.command`; it resolves a lone connected account, exits 2 when there are none or several without `--account`, and throws `not_connected` for an unknown `--account`); human copy the harness must relay verbatim is fenced in `[SHOW USER] ... [/SHOW USER]` blocks; secret intake is `--client-json <path|->` (preferred) / env `GOOGLE_CLIENT_ID`+`GOOGLE_CLIENT_SECRET` / TTY prompt, with raw argv flags accepted but documented last-resort; connect is an idempotent state machine (detects what exists, performs only the missing step — re-running is the documented fix for most errors). Engine-free except `status`'s best-effort linked-sources listing (degrades without an engine). Funnel events append to `~/.gbrain/integrations/google/heartbeat.jsonl`; account addresses are hashed to a short non-reversible tag, never raw. The vault entry's `meta.scopes` records what Google ACTUALLY granted (the token response's `scope` — the consent screen lets users uncheck scopes; the requested set is only the fallback), which is what lets downstream preflights report `scope_missing` instead of opaque per-sweep 403s.
+- `src/commands/google.ts` — `gbrain google connect|status|calendars|disconnect` (+ `setup` and `attachments` dispatch). Agent-first contract: every subcommand supports `--json` emitting `{ ok, status, next_action: { command?, user_message? }, error? }` (`calendars` adds `account` + `calendars[]` — id/summary/primary/accessRole — and carries the `sources add --calendar-id` template in `next_action.command`; it resolves a lone connected account, exits 2 when there are none or several without `--account`, and throws `not_connected` for an unknown `--account`); human copy the harness must relay verbatim is fenced in `[SHOW USER] ... [/SHOW USER]` blocks; secret intake is `--client-json <path|->` (preferred) / env `GOOGLE_CLIENT_ID`+`GOOGLE_CLIENT_SECRET` / TTY prompt, with raw argv flags accepted but documented last-resort; connect is an idempotent state machine (detects what exists, performs only the missing step — re-running is the documented fix for most errors). Credential commands are engine-free; `status` has a best-effort linked-sources listing, while `attachments backfill` requires the explicitly selected local managed brain. Funnel events append to `~/.gbrain/integrations/google/heartbeat.jsonl`; account addresses are hashed to a short non-reversible tag, never raw. The vault entry's `meta.scopes` records what Google ACTUALLY granted (the token response's `scope` — the consent screen lets users uncheck scopes; the requested set is only the fallback), which is what lets downstream preflights report `scope_missing` instead of opaque per-sweep 403s.
- `src/commands/creds.ts` — `gbrain creds list|remove|export|import`: the provider-agnostic vault surface; never prints a secret (list is always redacted). Provider-SPECIFIC connect flows live in their own commands. Export custody: a loud per-credential warning when a byo Google entry's consent screen is not known published-to-Production (its 7-day Testing expiry travels with the tokens).
- `src/commands/loops.ts` — `gbrain waiting [--top N] [--json] [--stale-ok]` + `gbrain loops list|show|done|drop|mute`: all paths dispatch through the trusted-local op layer (`handleToolCall`, remote:false) so CLI and MCP share one behavior. `waiting` REFUSES when EVERY google source has gone >24h without a successful sync and prints the exact fix (`--stale-ok` bypasses; per-source sync ages are always reported) — stale-but-confident output is worse than none. Output per counterparty: what's owed, evidence quotes, Gmail deep links, entity-card context, a paste-ready digest. Reads default to the `__all__` brain span (loops live in google sources, not `default` — a default-scoped read would say "all clean" while people wait); `--source <id>` narrows explicitly. An unqualified `mute`/`unmute` resolves the brain's google source (never `default`) through the SAME resolution — an unmute can never aim at a different source than the mute it reverses — and refuses with the exact fix when none or multiple exist. `unmute sender <email> | thread <id>` is exact and forward-only; a repeated unmute is a no-op success (`removed: false`, exit 0) so scripts can call it unconditionally.
- `src/commands/google-setup.ts` + `google-setup-tail.ts` — the one-command orchestrator behind `gbrain google setup`: connect (skipped when tokens exist) → source registration (skipped when registered) → first bounded sync under a wall-clock budget (the newest-first backfill floor means whatever lands is the NEWEST mail — exactly what `waiting` needs; the remainder resumes on every later sync, and setup says so honestly) → the first `gbrain waiting` digest in the same session as consent. Split in two so the connect half stays engine-free. Every step idempotent; re-running resumes wherever the last run stopped.
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index 5123607041..14c5fe11a6 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/mcp/server.ts` — MCP stdio server (generated from operations). Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/e2e/serve-stdio-roundtrip.test.ts`.
-- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. Exemptions mirror `resolveMcpStdioSourceScope`: unset env, `__all__`, and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` (helper cases + a real `startMcpServer` integration case with a tmp `GBRAIN_HOME`).
+- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.
- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases).
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index c471d88819..321b95d01e 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -3,6 +3,11 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+- `src/core/embedding-readiness.ts` — bounded source-aware recovery through canonical projection snapshots, queued intent, preparation and guarded installation. Global readiness remains archive-visible. Plain stale repair selects active sources for recovery and separately reports archived stranded work, so live pages can progress without pretending the whole brain completed. `countArchivedEmbeddingWork` classifies archived NULL vectors, non-NULL hash drift, signature work, contentful chunkless pages and, for migration, pending projections before authorization. Repair queues and snapshots require a live source under the existing source-before-page guard; unsupported pages remain blocked, never revision-stamped. The invalidation SQL additionally excludes unsealed projections.
+- `src/core/embedding-migration-retention.ts` — fail-closed retained-vector rebuildability check shared by migration preflight, direct apply, schema transition, pinned-column repair and invalidation/config transactions. Transaction-local SHARE locks freeze source/page/vector/withdrawal/config eligibility during the census and mutation. Sealed importer text chunks can be embedded and oversized chunks healed without regenerating their source projection; unsealed unsupported media still refuses. Width changes protect archived, skipped, deleted and unrebuildable retained page vectors; same-width checks match the shared false-stamp predicate, signature gate and current-space test. Archived pending work, including same-target content drift, metadata-only restamping, NULL vectors and chunkless pages, refuses before authorization or provider work; correct target-stamped archived vectors, including grandfathered NULL hashes, are retained controls. Companion retention checks follow actual schema/pinned-width changes and the same-target persisted migration marker; the guard returns the locked companion-clear decision consumed by the writer, ignoring a different target's completed-clear flag. Schema-only work leaves takes untouched. Existing fact eligibility and deliberate expiry/supersession/audit/withdrawal policy remain unchanged. Unknown registry, width or census fails closed. The source census includes archive state, but embed leases are not archive coordination. Synthetic two-engine regressions cover preservation refusals, real imported-image migration, same-target companion preservation, retarget/first-clear refusal and fail-closed metadata. Completion counts remain archive-visible; refusal never restores a source automatically.
+- `src/core/embedding-migration-budget.ts` — finite authorization in the existing migration marker, conservatively debited under the acquired leases before each provider attempt with the existing BudgetTracker. Resume preserves uncertain dispatched liability; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.
+- `src/core/facts/embedding-identity.ts` — active fact eligibility and stale model/text/width census shared by migration and fact repair. Legacy identity stays unknown. Both engine writers accept explicit `embedding_model` and compute the exact text hash; duplicate vector selection requires matching caller identity. `embed-facts.ts` installs under source-incarnation, row-version, withdrawal and configuration guards, retaining the outer migration invocation budget when nested.
+
- `src/core/anthropic-pricing.ts` — bare-keyed Anthropic VIEW of `model-pricing.ts` (the `anthropic:` canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because `estimateMaxCostUsd(modelId, inTokens, maxOutTokens)` carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; `BudgetMeter` tries `canonicalLookup` first and only falls back here, so it warns `BUDGET_METER_NO_PRICING` and runs unbounded only when canonical has no rates either). `estimateMaxCostUsd` routes bare/colon/slash ids through `splitProviderModelId`. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. `ANTHROPIC_PRICING` is consumed by `budget/budget-tracker.ts`, `minions/batch-projection.ts`, and `cycle/budget-meter.ts`.
- `src/core/contextual-retrieval-service.ts` — captures the complete originating projection before synopsis/embedding providers, then installs vectors with UPDATE-only CAS and stamps mode/generation in the same guarded transaction. Stored corpus generation participates in `page-state/projections.ts` indexing context even when the mode and canonical revision stay unchanged. New vectors receive the captured provider model; text, chunk identity, metadata and retrieval seal remain intact. Source contextual policy is rechecked before publication. Superseded preparation returns the existing retryable database result. Empty/disabled-mode stamps compare identity, seal, context and raw chunk inventory under the guard; unsealed nonempty chunks never reach a provider. `test/embedding-completion-atomic.serial.test.ts` covers real service/edit/rechunk/context interleavings and ordinary retrieval on both engines.
@@ -17,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embed-skip.ts` — 5-site shared predicate for the soft-block embed-skip filter. Exports `shouldSkipEmbedding(frontmatter): boolean` (JS predicate for callers holding the page in memory), `EMBED_SKIP_SQL_FRAGMENT` (parameterized SQL clause shared by Postgres + PGLite via `executeRaw`), and `buildEmbedSkipMarker(reason: string)` (writes `frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}` so the JSONB shape stays uniform). The 5 sites: `embed.ts --stale`, `embed.ts --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks`. Single source of truth so the filter cannot drift. Pinned by `test/embed-skip.test.ts` (cross-site invariant + JSONB shape).
-- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five paths against the real contextual service on PGLite and isolated Postgres.
+- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines.
- `src/core/embed-stall.ts` — progress-keyed stall watchdog for embed drains (mirror of sync's stall watchdog; bounds embed drains that hang without a pinned root cause). Two clocks, one trigger: LIVENESS ticks via `noteEmbedApiResponse()` on EVERY settled embed API attempt — success, error, or retry (hooked in `embed-retry.ts:embedBatchWithBackoff`; diagnostic only, distinguishes "fully wedged" from "live but failing" in the abort message, scoped to the armed run); the TRIGGER is no SUCCESSFUL forward progress (`readProgress()`, wired to chunks embedded) for `GBRAIN_EMBED_STALL_ABORT_SECONDS` (env-only knob; default 900 via `DEFAULT_EMBED_STALL_ABORT_SEC`, `<= 0` disables, garbage falls back to default) — a retry storm that never lands a chunk trips it BY DESIGN. A stall produces an ERROR RESULT (`reason: 'stall_timeout'`), never a `process.exit`: only the CLI wrapper (`src/commands/embed.ts:runEmbed`) maps it to a non-zero exit, and minion handlers and the cycle's embed phase (`cycle.ts:runPhaseEmbed`) convert it to a failure via `assertEmbedNotStalled`. The abort path runs an idempotent, deadline-bounded cleanup (`EMBED_STALL_CLEANUP_DEADLINE_MS`) that releases only the run's self-acquired single-flight locks and banks partial progress, so the next run resumes cleanly. The check interval is deliberately NOT unref'd — for non-single-flight callers it can be the only handle keeping a lost-promise hang loud; `stop()` clears it on every normal path. Pinned by `test/embed-stall.test.ts`.
@@ -25,7 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embedding-input-limit.ts` — per-model embedding INPUT token caps. Some hosted encoders reject any single input over a hard per-input limit far below their batch budget (a 512-token model would otherwise leave ~35% of a typical vault's chunks permanently unembeddable, re-failing every sweep). `resolveMaxChunkTokens(env?)` resolves the effective chunk-token cap for the ACTIVE embedding model so the chunkers SPLIT (never truncate) at a size the model accepts: `GBRAIN_MAX_CHUNK_TOKENS` env (escape hatch for models not in a recipe; warn-once per distinct invalid value) → recipe per-model `max_input_tokens` × `EMBED_INPUT_SAFETY` (0.6 — covers the cl100k-based `estimateEmbedTokens` overestimate vs BERT-wordpiece tokenizer mismatch) → `DEFAULT_MAX_CHUNK_TOKENS` (2000 for every other provider). `MIN_CHUNK_TOKENS` floor of 64 so a tiny declared limit can't produce confetti chunks; fail-open on any resolver error (a resolver bug must never change chunking for unaffected installs). `maxInputTokensForModel(recipe, modelId)` mirrors `model_dims`' case-fold lookup rule (exact match first, then case-insensitive scan). Consumed at `import-file.ts`'s chunk step. Pinned by `test/embedding-input-limit.test.ts`.
-- `src/core/embedding-invalidation.ts` — signature-truth guards shared by the migration + embed paths, engine-pure via `executeRaw` (identical SQL on both engines). `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})`: same semantics as the engines' `invalidateStaleSignatureEmbeddings` PLUS the `NOT (frontmatter ? 'embed_skip')` predicate every stale selector applies — never NULL what nothing will re-embed (without it a migration would destroy vectors retained on embed_skip pages permanently and silently). Chunks whose model, current text hash, and vector width already match the target are preserved across interrupted batches, and fully current pages are restamped without another embedding call. Both engines use the shared current-space predicate. ALL invalidation call sites (`applyEmbeddingMigration`, `runEmbedCore`, `embedStaleChunks`) route through it. `countFalseStampedChunks` / `clearFalseStampedSignatures`: the chunk-model truth cross-check — pages stamped WITH the target signature whose embedded chunks' `model` names another provider (bare provider-less model tails exempt, no surprise paid re-embed); count feeds plan/verify/`--status` honesty, clear runs in apply so the NULL-signature-inclusive invalidation re-embeds them. Pinned by `test/embedding-migration.test.ts` (`#4305 false target stamps + #4306 embed_skip-safe invalidation`).
+- `src/core/embedding-invalidation.ts` — signature-truth guards shared by migration and embed paths, using identical SQL on both engines. `invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})` adds the stale selectors' embed-skip and projection-seal fences to raw engine invalidation. Current model/hash/width chunks survive interrupted batches; fully current active pages can be restamped without another embedding call. Source `FOR SHARE` locks precede mutation in short transactions, serializing both signature writes, raw engine signature/content-drift invalidation, false-stamp clearing and final reconciliation against archive. Archived vectors and page signatures are never mutated. The shared `falseStampPageWhere` and `countFalseStampedChunks` remain archive-visible for retention, plan and completion diagnostics; only the clearing write is fenced. Bare provider-less model aliases retain their existing exemption. Provider dispatch and completion smoke run outside source locks and revalidate live, safe snapshots before sending text. Pinned by `test/embedding-migration.test.ts` and the shared `test/embedding-recovery.serial.test.ts` suite: PGLite runs in the serial lane, while `test/e2e/embedding-recovery-parity.test.ts` selects PostgreSQL.
- `src/core/embedding-pricing.ts` — `EMBEDDING_PRICING` map keyed `provider:model` for the post-upgrade reindex cost estimate. Sibling to `anthropic-pricing.ts`; EMBEDDINGS only — chat/completion pricing lives in `model-pricing.ts` (different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M). `voyage-4-nano` is deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0. `lookupEmbeddingPrice(modelString)` returns a tagged union (`known` with price + `unknown` with provider name); `estimateCostFromChars(charCount, pricePerMTok)` uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index 4f6523c752..35634e7aa6 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -34,4 +34,4 @@ union widening (`'person' | 'company'` → `string`), facts/eligibility.ts
pack-aware `ELIGIBLE_TYPES` wiring, and 3 doctor checks (schema_pack_coverage,
schema_pack_writability, schema_pack_mutation_audit).
-- `src/core/vector-index.ts` + `src/commands/doctor.ts:embedding_column_registry` — shared pgvector HNSW eligibility policy. `hnswIndexExpected(columnType, dims)` derives the answer from the canonical `vector`/`halfvec` dimension caps already used by migration index generation. Doctor reports an HNSW-less active embedding column as a healthy exact-scan configuration when its declared width exceeds the applicable pgvector cap, and only emits the index repair recipe when an index is actually supported. Pinned at both cap boundaries by `test/vector-index-lifecycle.test.ts`.
+- `src/core/vector-index.ts` + `src/commands/doctor.ts:embedding_column_registry` — shared pgvector HNSW eligibility policy. `hnswIndexExpected(columnType, dims)` derives the answer from the canonical `vector`/`halfvec` dimension caps already used by migration index generation. Doctor reports an HNSW-less active embedding column as a healthy exact-scan configuration when its declared width exceeds the applicable pgvector cap, and only emits the index repair recipe when an index is actually supported. Pinned at both cap boundaries by `test/vector-index-lifecycle.test.ts`. `readExistingEmbeddingShape` resolves the same relation as migration DDL and validates its actual type and width. Historical facts/query-cache replay uses that shape instead of extension/config defaults, preserving existing rows, vectors and compatible indexes; malformed existing shapes refuse before migration writes. `test/migration-vector-replay.test.ts` and its PostgreSQL wrapper pin both engines.
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.md
index 1651dea2c6..2dbfcaf6e3 100644
--- a/docs/architecture/key-files/tooling-and-tests.md
+++ b/docs/architecture/key-files/tooling-and-tests.md
@@ -3,12 +3,20 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+- `test/e2e/migration-wave-*.test.ts` + `test/helpers/migration-wave-*.ts` — isolated both-engine acceptance for phase-boundary lease loss, oversized-healing rollback, prepared embedding/withdrawal ordering, archived-source refusal, incompatible-model publication, failed partial migration and reopened retrieval, malformed provider batches, and actual SIGKILL around durable authorization reservation/dispatch. Fixtures prove their PostgreSQL database differs from the supplied test base. Providers and reranker pricing are synthetic; phase takeovers are controlled injections, not exhaustive schedules. `scripts/e2e-test-map.ts` routes affected migration, projection and engine changes to these suites.
+
+- `test/safety-wave-coverage-export-ledger.test.ts` + `test/safety-wave-coverage-invocation-inheritance.test.ts` — export ledger capacity/read-failure and source-binding contracts, plus nested invocation allowance, settlement and async-isolation checks. These pure fixtures supplement, rather than replace, real-engine snapshot and process-crash acceptance.
+
- `test/helpers/real-home-guard-preload.ts` — detection-only backstop for changes to the real-home autopilot wrapper, environment file, start script and launchd/systemd units. It compares file metadata before/after tests without reading secret-bearing contents and attributes earlier changes separately. `GBRAIN_TEST_ALLOW_REAL_HOME_WRITES=1` explicitly disarms it with a warning. Installer fixtures set both HOME before Bun startup and GBRAIN_HOME per fixture; `test/real-home-guard-preload.test.ts` verifies fake-live sentinels and the autopilot suite in disposable subprocess homes.
-- `.github/workflows/test.yml` — required full validation remains the default for pushes, pull requests and manual runs. Explicit manual `native_only` uses a distinct concurrency group to preserve in-flight full persistence soaks, runs the unchanged native matrix, and emits only a scoped native result (`full_ci: false`), never the full-suite aggregate check name. `test/scripts/native-only-workflow.test.ts` evaluates the actual event/input conditions and executes the scope/result scripts; `test/scripts/ci-gates.test.ts` retains all default required-result failures.
+- `.github/workflows/test.yml` — required full validation remains the default for pushes, pull requests and manual runs. Explicit manual `native_only` uses a distinct concurrency group to preserve in-flight full persistence soaks, runs the native matrix, and emits only a scoped native result (`full_ci: false`), never the full-suite aggregate check name. `test/scripts/native-only-workflow.test.ts` evaluates the actual event/input conditions and executes the scope/result scripts; `test/scripts/ci-gates.test.ts` retains all default required-result failures.
- `.github/workflows/native-locks.yml` — native glibc Linux, macOS and Windows jobs also run publication, Git helper, historical sync-origin and backup portability contracts in separate Bun processes, collecting fatal suite outcomes. macOS/Windows publication fixtures require an actual case-insensitive filesystem. Separate six-cell Windows diagnostic jobs opt into a directory-only hidden-window comparison and file/directory cmdlet-versus-production comparisons after real PGLite setup; neither filters or replaces native acceptance. `test/fixtures/windows-backup-cmdlet-protect.ps1` freezes the old program for A; B forwards the actual production program. The separate read-only `windows-backup-dotnet-inspect.ps1` reports actual owner/SYSTEM, protected-DACL, rights, inheritance and propagation for the independent oracle. The persistence deployment matrix separately executes the publication journal and all three sync-safety suites with PostgreSQL; E2E parity wrappers select them in the local full gate. `test/scripts/data-safety-native-workflow.test.ts` pins mandatory native/database execution without ignored failures and requires both file and directory observations; actual results, not configuration or simulated paths, establish platform coverage.
+- `test/native-export-publication.test.ts` + `test/export-publication-native.serial.test.ts` — native export primitive, wrapper and compiled-publication contracts run on all eight addon targets, including the native musl containers. macOS/Windows wrapper checks require a real case-insensitive volume. Failures remain fatal; a compiled fixture runs outside the checkout and checks successful completion, repeat refusal and incomplete output after process death.
+
+- `test/memory-safety-wave.serial.test.ts` + `test/e2e/memory-safety-wave-postgres.test.ts` — provider-free cross-feature lifecycle on isolated PGLite/PostgreSQL. A repair owner is killed after the metadata commit and a new process resumes the cursor without duplicating edits. Remember/withdraw survives projection and fact-vector migration; source-scoped export and stale reimport retain withdrawal intent. Actual HTTP MCP checks lexical privacy/misses; a fresh stdio process uses a loopback embedding provider to verify vector-positive retrieval and private/foreign/withdrawn exclusions after reconnect. Synthetic basis vectors establish routing and persistence, not retrieval quality.
+
- `scripts/build-pglite-snapshot.ts` — `bun run build:pglite-snapshot [--profile legacy|default]` bakes post-schema PGLite snapshots. Legacy (the default) matches the unit preload; default follows canonical CLI embedding defaults. Profiles have disjoint tar/version/lock paths and CI cache keys. Version sidecars retain schema-byte hash, dims and model. The builder requires PID/token lock ownership, only reclaims confirmed dead owners using its retirement protocol, times out on live/unknown locks, and publishes temporary files via atomic rename with the version last. Normal release and crash recovery retain the same nonempty owner tombstone so a delayed observer cannot move a replacement lock. `scripts/lib/test-env.sh` exposes `ensure_pglite_snapshot` (legacy primary env) and `ensure_default_pglite_snapshot` (absolute auxiliary `GBRAIN_TEST_DEFAULT_SNAPSHOT`); failure visibly falls back to cold init. `GBRAIN_NO_SNAPSHOT=1` clears both and survives preloads. BrainBench overrides only CLI children, including run-all, to the default path. The production loader's per-process memoization, schema/shape refusal and in-memory-only gate remain authoritative and unchanged. Keep `computeSnapshotSchemaHash` and every CI profile cache key aligned with imported SQL helpers, including grants, withdrawals, page state and persistence schemas. Tests: `test/scripts/build-pglite-snapshot.test.ts`, `test/snapshot-shape-guard.test.ts`, BrainBench CLI E2E and operator preload tests.
- `scripts/check-compile-autoload.sh` — CI scanner: every `bun build --compile` invocation (CLI one-liners carrying `--outfile`, or `['build', '--compile', …]` spawn arrays) in `package.json`, `CLAUDE.md`, `CONTRIBUTING.md`, `.github/`, `scripts/` and `docs/` must carry `--no-compile-autoload-bunfig`, because a compiled Bun binary otherwise auto-loads a cwd `bunfig.toml` and runs its `preload` before any gbrain code (before `cli-preflight.ts`). Prose that names the command without `--outfile` is ignored; `test/` compile helpers are out of scope (throwaway binaries run from temp dirs). Self-tested via `test/fixtures/guards/check-compile-autoload.sh/{bad,good}/`; wired as `check:compile-autoload` in verify CHECKS.
diff --git a/docs/embedding-migrations.md b/docs/embedding-migrations.md
index 4124c5e935..ce1061bc48 100644
--- a/docs/embedding-migrations.md
+++ b/docs/embedding-migrations.md
@@ -1,231 +1,225 @@
# Switching embedding models or dimensions on an existing brain
-> **Use the command, not the recipes:** `gbrain migrate embeddings --to
-> <provider:model> --dim <N>` is the supported path — it handles the schema
-> transition (all three dim-pinned columns), NULL-signature pages, the
-> reranker companion switch, the query cache, locks, and resume-after-kill,
-> and verifies the database before declaring anything done. Preview with
-> `--dry-run`; inspect state with `--status`. For the explicit-consent playbook, follow
-> `skills/migrations/v0.46.3.0.md`. The manual recipes below remain as the
-> appendix for unusual situations (they are what the dimension-mismatch
-> error messages link to).
-
-
-GBrain stores embeddings in a fixed-dimension `vector(N)` column on
-`content_chunks`. If you switch to a model with a different dimension
-(e.g. `openai:text-embedding-3-large` 1536 → `voyage:voyage-4` 1024, or
-`voyage:voyage-4-large` 2048), the on-disk column type doesn't change
-automatically.
-
-`gbrain init`, `gbrain doctor`, and `gbrain embed --stale` all detect
-this mismatch and refuse to silently proceed. This doc is the recipe
-they point at.
-
-## Same-dimension model swaps (automatic)
-
-If you switch to a different model at the **same** dimension count
-(e.g. one 1536-dim provider to another, or a re-tuned model that keeps
-its width), the column type doesn't change, so no `ALTER`/wipe recipe
-is needed. gbrain stamps an embedding-provenance
-signature (`<provider:model>:<dims>`) onto each page when its chunks are
-embedded. After you point the config at the new model, the stored
-signatures differ from the current one, and `gbrain embed --stale`
-revisits those pages. Chunks already matching the target model, current text
-hash, and vector width keep their embeddings. A fully current page can have
-its signature restamped without another provider call; interrupted batches
-do not discard completed current vectors.
+Use `gbrain migrate embeddings` for both same-width model changes and dimension
+changes, on **PGLite and PostgreSQL**. It coordinates the text-vector schema,
+configuration, invalidation, guarded projection recovery, chunk/fact repair and
+resumable authorization. Changing a config value alone does not convert vectors.
+Do not wipe/reinitialize a brain, re-import Markdown, or run hand-written vector
+column SQL as an embedding migration: those paths bypass this coordination and
+can lose database-only memory or durable intent.
+
+Select the intended brain with the global `--brain` option and retain that
+selection on every command below. Migration is **brain-wide**; `--source` does
+not narrow it. See the [migration reference](guides/embedding-migration.md) and
+[explicit-consent playbook](../skills/migrations/v0.46.3.0.md).
+
+## Preview, authorize, then verify
+
+Inspect state and preview a deliberately selected target without provider work:
```bash
-# After switching to the new same-dim model in your config:
-gbrain embed --stale # embeds stale chunks; preserves current vectors
-gbrain embed --stale --dry-run # preview the count without re-embedding
+gbrain migrate embeddings --status --json
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run --json
```
-Under federated_v2, the same drift is picked up by the per-source
-`embed-backfill` jobs that `gbrain sync --all` enqueues (capped
-`$X/source/24h`). **Grandfather:** pages whose chunks were embedded
-without a provenance stamp carry a NULL signature and are NEVER flagged
-stale by the routine sweep, so a stamp-less corpus is not re-embedded
-wholesale by surprise. `gbrain embed --stale --include-null-signature`
-re-embeds them deliberately, and `gbrain migrate embeddings` always
-includes them.
+Review actual column widths, model provenance, pending chunks and facts,
+projection blockers, estimated cost (or unavailable pricing), and the reranker
+action. The example target is not a recommendation to change a keyless brain.
+An upgrade or health warning never authorizes paid work.
+
+Before applying, verify a [full backup on an isolated restore](#backup-and-isolated-restore),
+coordinate quiescing writers with the owner, and obtain approval for the selected
+brain, target, dimensions, reranker action and a finite nonnegative **total USD
+cap**. Replace `<approved-total-usd>` with the operator's choice, not an amount
+invented by the agent:
+
+```bash
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 \
+ --max-cost-usd <approved-total-usd> --yes --json
+gbrain migrate embeddings --status --json
+```
-A **dimension** change still requires the wipe-and-reinit (PGLite) or
-column-alter (Postgres) recipe below — the on-disk `vector(N)` width
-genuinely has to change.
+`--yes` is operation consent, not a substitute for the cap. Batch size is not a
+spending bound. Admission uses conservative per-attempt ceilings, so the preview
+estimate is not a guarantee that the selected cap will finish the work. Unknown
+pricing or a missing provider input ceiling can refuse before dispatch.
+
+At the same width, the schema need not resize, but a new model is still a new
+vector space: incompatible fact/take vectors and semantic cache entries cannot
+be retained as though they belonged to the target. A width change uses the
+guarded transition for all three dim-pinned text columns, not a PGLite wipe.
+Image/multimodal embeddings remain separate.
+
+Completion requires inspecting the actual remaining work, not just the configured
+model. An incomplete or failed run may have committed projection repairs,
+configuration/schema changes, vectors or authorization debits. Inspect `--status`
+before resuming the same approved target; correct chunks/facts are retained.
+Increasing `--max-cost-usd` authorizes a larger **total**, not a reset of prior
+debits. Do not reset the marker or clear another writer's lock. `--no-embed` is
+deferred work, not completion; resume through the migration command so its
+authorization and verification remain in force.
+
+After completion, separately authorize any provider calls needed to check a
+known-positive retrieval and a genuine miss in the same brain. A green width
+check alone does not prove retrieval. See the
+[verification commands and expected hit/miss distinction](guides/embedding-migration.md#verify-a-known-result-and-a-genuine-miss)
+and [failure/recovery table](guides/embedding-migration.md#recovery).
## Repair missing fact vectors deliberately
-Fact vectors are separate from page/chunk embeddings. Extraction preserves
-already embedded facts when it cannot produce a complete valid replacement;
-it does not transplant old vectors onto different text or a new model.
-Restrictive source changes still expire removed claims and tighten visibility
-before deferred reconciliation. Existing NULL fact vectors do not heal merely
-because later extraction runs. Preview a selected source without provider work:
+Fact vectors are separate from page/chunk embeddings. The brain-wide migration
+repairs eligible active facts as part of its guarded run, including same-width
+model swaps and facts-only brains. Standalone fact repair is a separate,
+explicitly **source-scoped** operation:
```bash
-gbrain embed --stale --facts --source <source-id>
+gbrain embed --stale --facts --source source-example --dry-run --json
```
+Eligible work includes a missing vector, a different or unknown stored model,
+a missing/mismatched text hash, or the wrong vector width. It is **not NULL-only**.
+Expired, superseded, withdrawn and audit facts, facts from archived sources, and
+facts linked to deleted pages are excluded. Already-current vectors are retained;
+unknown legacy provenance is not inferred from today's configuration.
+
The preview reports the scope and count, not a repair-price estimate. Its zero
cost means no provider spend occurred during the preview. After reviewing the
-count and choosing a finite spending cap, explicitly authorize a bounded repair:
+count and obtaining an operator-selected cap, authorize the bounded repair:
```bash
-gbrain embed --stale --facts --source <source-id> --yes --max-cost-usd <cap>
+gbrain embed --stale --facts --source source-example \
+ --yes --max-cost-usd <approved-usd> --json
```
The cap must be finite and nonnegative. `--max-facts` limits attempted facts
(default 100, range 1–10,000); `--batch-size` bounds each batch (default 100,
range 1–100); `--budget-ms` limits run time (default 60,000, range 1–3,600,000).
-All three accept integers. This is not an automatic, background or full-brain fact sweep.
-Only NULL vectors on current source/incarnation, row-version and withdrawal
-state are eligible; valid vectors are not re-embedded. Each provider attempt
-rechecks the selected-brain and database off switches and spend allowance.
-Managed sources repair physical fact projections under guarded authority, not
-canonical content; an owner-held PGLite brain uses private resident delegation
-without stopping its writer. Failed/unavailable providers leave the original
-facts intact and return bounded diagnostics.
-
-## Why we don't do this automatically
-
-Switching dimensions requires:
-
-1. Dropping the HNSW vector index (pgvector won't survive an `ALTER COLUMN TYPE`).
-2. Wiping every existing embedding (the old vectors are unusable in the new space — and pgvector refuses to cast them across dimensions, so this must happen before the alter).
-3. Altering the column type (Postgres only — PGLite cannot do this).
-4. Re-embedding the entire corpus (can take hours on a 50K-page brain and costs $1-100 in API calls depending on model).
-5. Conditionally recreating the index (HNSW supports up to 2000 dimensions per pgvector; above that you must use exact scans).
-
-That's not an upgrade-time auto-run. It's a deliberate, expensive
-operation. Run it when you've decided you actually want the new model.
-
-## PGLite (default install)
-
-**PGLite cannot `ALTER COLUMN TYPE vector(N)`.** pgvector ships as
-embedded WASM, not a native extension, and the WASM build rejects the
-column-type alter with `could not access file "$libdir/vector"`. The
-SQL recipe below works against Postgres only.
-
-The path that works on PGLite is **wipe-and-reinit**. There is a
-single-command wrapper:
+All three accept integers. These limits do not authorize spend. Standalone
+repair is bounded per invocation; use brain-wide migration when durable total
+authorization across interruptions is required.
+
+Each provider attempt rechecks source identity, authority, selected-brain and
+database off switches, model identity and spend allowance. Installation rechecks
+row version and eligibility. Managed sources repair physical fact projections,
+not canonical text; an owner-held PGLite brain uses private resident delegation.
+Provider failures leave the affected original facts intact and report bounded
+diagnostics. Inspect `remaining`, `failures` and `stopped`; do not equate a bounded
+batch with a completed backfill. Repair does not run automatically on upgrade.
+
+## Backup and isolated restore
+
+A backup is a **point-in-time snapshot**, not a rollback of later events.
+An old snapshot does not contain later edits, withdrawals, grants/revocations or
+queued requests. Restoring it can make a subsequently withdrawn claim active
+again in the isolated copy. Preserve the current brain and reconcile those later
+changes before considering any restored copy for service. Reverting a binary is
+not data restoration, and Markdown export is not a full database backup.
+
+The examples below are operator templates, not commands run against your brain.
+They are grounded in a tiny synthetic drill using the current runtime: closed
+PGLite copies and supported archives, and PostgreSQL 16 `pg_dump`/`pg_restore`
+with pgvector. The drill verified canonical edits, fact withdrawals, retained
+queued intent, unchanged originals and PGLite occupied-target refusal. It did
+**not** establish old-binary/mixed-version compatibility or safe service activation.
+
+For either engine:
+
+1. Obtain approval to pause all writers: MCP/service owners, persistence
+ consumers, scheduled jobs, CLI writers, sync and file editors. Stop old-version
+ workers too. Let active transactions finish and engines close/checkpoint;
+ preserve queued work rather than draining or discarding it merely to back up.
+2. Record the selected database, configuration, binary/schema versions, extensions,
+ external files/object stores and the snapshot time. Keep comparison evidence
+ for canonical pages, facts, `fact_withdrawals`, `persistence_requests` and
+ `page_projection_jobs`. A momentary lack of sessions is not a fence against a
+ scheduler reconnecting.
+3. Keep archives, configuration and comparison evidence private. Full database
+ snapshots may contain credentials and withdrawn/history content; they are not
+ sanitized exports or evidence of physical erasure. Never publish them in a PR.
+4. Restore only into a new isolated target with compatible software. Do not point
+ an application, worker or harness at it, publish it, or reuse its old authority.
+
+### PGLite: supported archive into an absent root
+
+This format requires a file-configured local host installation with the database
+at `<root>/.gbrain/brain.pglite`. `GBRAIN_HOME` selects `<root>`, **not** its
+`.gbrain` child. Use an absolute recorded CLI launcher if your harness has one.
+Replace the example source root after verifying its configuration; keep the
+backup directory outside it. With all owners stopped:
```bash
-gbrain reinit-pglite \
- --embedding-model voyage:voyage-4 \
- --embedding-dimensions 1024
+umask 077
+source_root=/absolute/path/to/brain-root
+backup_dir=$(mktemp -d "$HOME/gbrain-backup.XXXXXX")
+GBRAIN_HOME="$source_root" gbrain backup create --brain host \
+ --output "$backup_dir/brain.gbrain-backup" --json
```
-This backs up the existing brain to `<path>.bak`, runs `gbrain init`
-with the new flags (preserving every other field in
-`~/.gbrain/config.json`), and re-syncs the brain repo. Add `--no-sync`
-to skip the resync, `--yes` to skip the TTY confirmation, `--json` for
-structured output.
+The archive contains the full database plus sanitized file configuration and
+installer-managed files, not every external asset. Review its omitted-assets
+inventory and separately protect excluded source files, credentials and object
+storage. A custom database path is not supported by this archive format; use a
+verified closed whole-directory backup plus configuration instead, and rebase
+only the copied configuration before inspecting a copy with the matching binary.
+Never copy individual live database files or rename the original out of service
+as a migration step.
-Equivalent by hand:
+Restore the archive into an absent child of a fresh private directory. Do **not**
+create `restored_root` first; occupied roots are refused:
```bash
-# 1. Back up the existing brain (in case you want to roll back).
-mv ~/.gbrain/brain.pglite ~/.gbrain/brain.pglite.bak
-
-# 2. Re-init with the new model + dimensions. `gbrain init` writes
-# the schema sized to the new dim, and preserves
-# every other field in ~/.gbrain/config.json (chat model,
-# expansion model, API keys).
-gbrain init --pglite \
- --embedding-model voyage:voyage-4 \
- --embedding-dimensions 1024
-
-# 3. Re-import your brain repo. `gbrain sync` reads the brain repo
-# from disk and re-creates the page rows.
-gbrain sync
-
-# 4. Re-embed. The embed pipeline now uses the new model and the
-# column accepts the new dim.
-gbrain embed --stale
+restore_parent=$(mktemp -d "$HOME/gbrain-restore-review.XXXXXX")
+restored_root="$restore_parent/brain"
+GBRAIN_HOME="$source_root" gbrain backup restore "$backup_dir/brain.gbrain-backup" \
+ --brain host --into "$restored_root" --mode new-brain --json
```
-If your brain repo is large enough that re-syncing from disk is
-expensive (>50K pages), see the Postgres section below — migrating to
-Postgres temporarily lets you run the SQL recipe, then migrate back to
-PGLite.
-
-`GBRAIN_HOME` users: substitute the active database path (or use
-`gbrain config get database_path` to find it).
-
-## Postgres (Supabase / self-hosted)
-
-Postgres supports the in-place column alter. Replace `<NEW_DIMS>` with
-your target dimension count.
-
-```sql
-BEGIN;
+Read `restore-receipt.json` and `.gbrain/restore-detached.json` under the restored
+root. New-brain restore revokes archived authority, disables publication and
+quarantines unfinished work without starting automation. In the synthetic drill,
+the queued request's intent and digest survived, but its state became `cancelled`
+with `restore_new_brain`; do not expect automatic replay. Compare canonical
+pages, facts and the withdrawal ledger with snapshot evidence, and account for
+this deliberate queue-state transformation. Do not use `--mode recovery` merely
+to avoid these safeguards or to claim an old service has been excluded.
--- 1. Drop the HNSW index. It can't survive the column type change.
-DROP INDEX IF EXISTS idx_chunks_embedding;
+### PostgreSQL: dump into a separate, newly created database
--- 2. Clear stale embeddings FIRST. This must happen BEFORE the column
--- alter: pgvector refuses to cast existing vectors across dimensions
--- ("expected <NEW_DIMS> dimensions, not <OLD_DIMS>"), so altering a
--- column that still holds old-width vectors aborts the transaction.
--- NULLs cast fine. (The old vectors are unusable in the new space
--- anyway — this is the wipe step from the rationale above.)
-UPDATE content_chunks SET embedding = NULL, embedded_at = NULL;
+Use compatible PostgreSQL client tools, the required pgvector/extensions and a
+separate inspection server without application access. Configure private libpq
+service entries beforehand: `gbrain-source-example` selects the exact source
+database; `gbrain-restore-admin-example` selects the isolated inspection server's
+maintenance database with permission to create a database. These are placeholders,
+not services GBrain creates. Keep credentials in protected service/password
+files, not command text. Do not reuse a production service for the restore.
--- 3. Alter the column type (all rows are NULL now, so the cast succeeds).
-ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(<NEW_DIMS>);
-
--- 4. Recreate the HNSW index ONLY IF dims <= 2000. Above that, leave it
--- indexless and rely on exact scans (gbrain searchVector handles this
--- automatically — search just gets slower, not broken).
--- For dims <= 2000 (e.g. 1024, 1280, 1536, 768):
-CREATE INDEX IF NOT EXISTS idx_chunks_embedding
- ON content_chunks USING hnsw (embedding vector_cosine_ops);
--- For dims > 2000 (e.g. 2048 Voyage 4 Large): skip step 4.
-
-COMMIT;
-```
-
-Then re-init config with the new model:
+After quiescing the source and protecting its file configuration/external assets:
```bash
-gbrain init --supabase \
- --embedding-model <provider:model> \
- --embedding-dimensions <NEW_DIMS>
-```
-
-And re-embed:
-
-```bash
-gbrain embed --stale
-```
-
-## A note on `gbrain config set`
-
-`gbrain config set embedding_model X` cannot switch models: `config set`
-writes the DB plane, and the embed gateway reads the file plane
-(`~/.gbrain/config.json`), so such a write would be a no-op for the embed
-pipeline. For that reason `gbrain config set embedding_model` and
-`gbrain config set embedding_dimensions` REFUSE and print the
-wipe-and-reinit recipe.
-
-To change schema-sizing fields, use `gbrain init` (PGLite) or the SQL
-recipe (Postgres). Both update the file plane AND the schema together.
-
-## Verify
-
-After the recipe lands, `gbrain doctor --fast` should report green and
-`gbrain doctor` should pass the `embedding_width_consistency` check:
-
-```
-✓ embedding_width_consistency dim parity: config 1280 / column vector(1280)
+umask 077
+backup_dir=$(mktemp -d "$HOME/gbrain-pg-backup.XXXXXX")
+pg_dump --dbname='service=gbrain-source-example' --format=custom \
+ --no-owner --no-acl --file="$backup_dir/brain.dump"
+
+createdb --maintenance-db='service=gbrain-restore-admin-example' \
+ --template=template0 gbrain_restore_example &&
+pg_restore --dbname='service=gbrain-restore-admin-example dbname=gbrain_restore_example' \
+ --no-owner --no-acl --exit-on-error "$backup_dir/brain.dump"
```
-If it doesn't, file an issue with the doctor output and the steps you
-ran.
-
-## Followups
-
-- Auto-fallback to alternative embedding providers when the primary
- fails quota/auth. Tracked; requires explicit `--try-fallback`
- consent because mixing provider vectors silently corrupts retrieval.
+The `&&` is intentional: if the database already exists, `createdb` fails and
+restore must not run. On any restore error, leave that partial inspection target
+offline and use a different new name for the next attempt. Do not add `--clean`,
+drop the current brain, or restore over an occupied database. PostgreSQL tools
+alone do not provide GBrain's PGLite occupied-root protection or authority
+quarantine. A raw dump retains queued work and application authority; it must
+remain inspection-only. `--no-owner --no-acl` does not sanitize stored credentials.
+
+Compare the restored canonical state, facts, withdrawal ledger and durable intent
+with snapshot evidence before any reconciliation. The synthetic PostgreSQL drill
+preserved full queued rows exactly and never launched a consumer on the copy.
+Account separately for roles/permissions, configuration and external storage,
+which this single-database dump does not restore. Have the owner reconcile every
+post-snapshot withdrawal, write and authority change from preserved current
+records before any separately approved cutover. If those records are unavailable,
+do not assume the stale copy is safe to activate.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index bc6ac323df..92c9782660 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -303,6 +303,62 @@ files. An unconfigured remote is reported as a skipped push. Embeddings wait
for an enabled, configured provider and install only if the page revision and
its text projection still match.
+### Withdrawal recovery
+
+Withdrawal discovers exact, source- and visibility-scoped fact rows, recorded
+provenance and stale chunk evidence before changing the ledger. Unrelated page
+bytes, revisions, chunks and embedding signatures remain unchanged. Managed
+withdrawals retain a versioned target manifest for the mirror, Git and embedding
+workers; each worker checkpoints one affected page at a time.
+
+Stop older mutation workers before upgrading the owner and restarting work. Older
+binaries do not understand the target manifest and must not share the brain with
+the upgraded worker. This is a quiesced upgrade, not a mixed-version rollout.
+Take an engine-appropriate database backup first, not a Markdown export. Prefer
+forward recovery: restoring an older database can discard committed withdrawal
+intent or intervening edits and can make withdrawn content active again.
+
+Discovery has fixed safety limits: 12,000 source pages, 40,000 chunks, 40,000 fact
+rows, 64 MiB of combined text and 256 affected pages in a target manifest no larger
+than 1 MiB. It reads bodies in batches of 128 and refuses when its checked scan
+budget exceeds 10 seconds; an individual matching batch also has a 16,384-row/8 MiB input limit.
+Each body also has a 16,384-marker parsing limit, enforced during a linear scan.
+These are capacity limits, not a latency guarantee or permission to spend on
+providers. `withdrawal_capacity` or `withdrawal_provenance` refuses the attempt
+before ledger, expiry, revision or chunk changes. Matching malformed fences need
+canonical repair; capacity refusals need host-operator investigation and a
+separately reviewed repair, not an unchanged retry, source deletion or a forced
+cursor reset. There is no override that trades away complete discovery.
+
+Already queued source-wide effects are converted using the same bounded exact
+discovery and retain their individual progress cursors. An over-capacity or
+unverifiable legacy effect stays pending; its previously committed withdrawal
+is not undone. A retained physical publication recovers forward before new work.
+If its recorded file bytes no longer match, preserve the file and receipt and
+resolve the conflict on the owner; do not delete recovery records.
+
+If a sync cursor was already invalidated, keep its failure visible until the
+owner has checked the canonical content. Then explicitly re-enumerate with the
+same source and processing options:
+
+```bash
+gbrain sync --source example-source --no-pull --no-embed --no-extract --retry-failed
+```
+
+Use `--no-embed` and `--no-extract` here only if they were the original sync
+options; retain the original `--no-schema-pack` choice as well. Explicit retry
+retains old terminal receipts, refuses while work is still active and creates
+fresh guarded requests. It does not ignore revision conflicts. Inspect the
+result and the original withdrawal receipt, then verify that the fact is inactive
+and the affected canonical file shows the withdrawal before reporting recovery
+complete. A queued mirror, failed embedding effect or blocked sync is not a
+completed repair. These rules apply to both PGLite and PostgreSQL; they do not
+require connecting a second process to an already-owned PGLite store.
+
+**Say to your agent:** *"Inspect the withdrawal receipt and the failed sync on
+this source. Preserve my edits and the withdrawal, and ask before explicit
+recovery if the original processing options are unknown."*
+
Before and after managed activation, eligible `put_page` and `capture` writes
record durable facts-extraction intent. `facts_backstop.queued` means that
intent committed with the page; the `facts-backstop` effect becomes
diff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.md
index c606419e35..5e5816fc85 100644
--- a/docs/guides/embedding-migration.md
+++ b/docs/guides/embedding-migration.md
@@ -16,10 +16,10 @@ command. It uses the same flags, preview, consent and verification workflow.
gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --dry-run
# After reviewing the plan, run with interactive confirmation.
-gbrain migrate embeddings --to voyage:voyage-4 --dim 1024
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --max-cost-usd 1
# Only after explicit approval: --yes is required non-interactively, else exit 2.
-gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --max-cost-usd 1 --yes
```
`--dim <N>` overrides the target width; it defaults to the provider recipe's
@@ -68,18 +68,27 @@ even if a custom base URL still serves its old model.
(pages whose chunks were embedded without a provenance stamp). Prices the re-embed
from the pricing table; unknown providers print "estimate unavailable"
instead of a fabricated number.
-2. **Consent gate.** Prints the plan; requires an interactive `y` or `--yes`.
+2. **Consent gate.** Prints the plan; requires an interactive `y` or `--yes`,
+ plus a finite `--max-cost-usd` total authorization for a new migration.
Non-TTY without `--yes` refuses with exit 2 (mirrors the `reindex-code`
gate in [spend-controls](../operations/spend-controls.md)). Unlike the pure
cost gates there, `spend.posture=tokenmax` does **not** bypass this one:
- posture waives the spend *ceiling*, and this gate also guards a
- destructive schema rebuild. Under `tokenmax` the dollar figure is marked
- informational and the confirmation is still asked. `--yes` is the single
- scripted bypass.
-3. **Live probe.** One tiny embed against the TARGET provider before any
- mutation — validates the API key, model id, and dimension support in a
- single call. A bad key fails here, with nothing changed.
-4. **Env-override gate.** When `GBRAIN_EMBEDDING_MODEL` /
+ this gate guards both destructive work and bounded provider attempts.
+ `--yes` confirms the operation; it does not waive the cap. Retries retain
+ pre-dispatch debits, including requests with uncertain outcomes. Raising
+ the total cap explicitly authorizes more work. Unknown pricing or a
+ missing conservative provider input ceiling refuses before dispatch.
+3. **Live probe.** After checking environment and embedding-enabled policy,
+ one tiny embed against the TARGET provider before any
+ vector invalidation — validates the API key, model id, and dimension
+ support in a single call. A bad key preserves vectors; its authorization
+ debit and resumable marker remain. Pending projections are then rebuilt
+ through the canonical queue/snapshot/install path in batches of at most
+ 100 pages. Unsupported or still-pending projections refuse migration-wide
+ invalidation and retain their recovery work.
+ Pending projections in archived sources also block a brain-wide schema
+ rebuild; restore the source deliberately before attempting its repair.
+4. **Env-override policy (checked before the probe).** When `GBRAIN_EMBEDDING_MODEL` /
`GBRAIN_EMBEDDING_DIMENSIONS` are set and DISAGREE with the target, the
live run refuses (config-says-new / runtime-embeds-old silently splits a brain
across two embedding spaces); `--ignore-env-override` for deliberate experiments. When they
@@ -109,6 +118,160 @@ even if a custom base URL still serves its old model.
6. **Re-embed.** The standard embed pipeline (`embed --stale --catch-up`)
with per-source single-flight locks, rate-limit backoff, stderr progress,
and optional DB-contention pacing (`--pace[=mode]`).
+ Active facts are repaired through the same guarded document-embedding
+ path as `embed --facts --stale`, including same-width model swaps and
+ facts-only brains. Expired, withdrawn, superseded and audit rows are not
+ work. Unknown legacy fact provenance is never inferred from new config.
+
+## Recovery
+
+Legacy saved facts have no recorded embedding model until they are repaired.
+Exact-text duplicate detection still works, but semantic duplicate detection
+and consolidation do not compare these unverified vectors. Preview the scoped
+work with `gbrain embed --facts --stale --source 'source-example' --dry-run --json`;
+repair requires explicit `--yes --max-cost-usd <amount>` authorization. No paid
+re-embedding is started automatically on upgrade. Existing page vectors with a
+matching model and a legacy NULL text hash remain searchable, including after a
+failed migration attempt; this does not relabel vectors from another model.
+
+Stop older GBrain mutation workers before repair; this release does not prove
+mixed-version mutation compatibility. Preserve their durable queued work.
+Select the intended brain using the ordinary global `--brain` option. This
+migration is brain-wide: both `gbrain migrate embeddings` and `gbrain retrieval-upgrade`
+reject `--source` and `--slugs`, including `--flag=value`
+forms, before planning or opening the brain. Neither flag narrows schema work.
+
+Both routes accept only their documented migration controls and the global
+`--brain`, `--quiet`, `--progress-json`, and `--progress-interval` controls.
+Flags from embed/import, such as `--facts`, `--limit`, or `--background`, are
+unsupported; so is `--timeout` (migration has no CLI deadline implementation).
+Validation checks the original arguments even when global parsing consumes a
+flag. Unsupported controls, duplicate flags, missing values, and invalid numbers
+refuse before opening the brain rather than silently widening work.
+
+Use separate values for `--to`, `--dim`, `--batch-size`, `--max-cost-usd`, and
+`--reranker`; their `--flag=value` forms are unsupported. Dimensions must be an
+integer from 1 through 100000, batch size an integer from 1 through 10000, and the
+cost cap finite and nonnegative. Values are never truncated or clamped. Pacing
+accepts bare `--pace` (balanced), `--pace=off|gentle|balanced|aggressive`, and
+`--pace-max-concurrency N` or `--pace-max-concurrency=N` with a positive safe
+integer. Empty or unknown pace modes refuse rather than falling back to off.
+Pacing's existing configuration/environment precedence is unchanged.
+
+Unsuccessful CLI JSON and local `migrate_embeddings` operation envelopes retain
+their existing status and reason fields and add a `recovery` object with the status
+command, this guide, and partial-state and authorization cautions. Human stderr
+prints the same guidance after the case-specific advice. The operation remains
+local-only and admin-scoped; its `failed` discriminator is unchanged. Reuse the same
+brain selection when inspecting status; do not blindly retry or reset the migration marker.
+
+| Failure | Action before retrying | Partial state to inspect |
+| --- | --- | --- |
+| `locked` | Check the existing holder; let it finish or deliberately stop it, then inspect status. | A previous holder may have committed progress or debits. |
+| `refused` | Resolve the named environment mismatch or deliberately choose whether to resume or retarget. | An earlier migration and its authorization may still be live. |
+| `probe_failed` (operation: `failed`) | Check provider configuration and the reported dimensions before authorizing another attempt. | An authorized probe debit may remain even when invalidation did not run. |
+| `apply_failed` (operation: `failed`) | Inspect the specific blocker first. Restore an archived source with `gbrain sources restore <id>` only after owner approval; unsealed unsupported projections need their original importer. Resolve configuration, database, or ownership errors before retrying. | Canonical repairs, schema/config changes, vectors, and debits may have committed in earlier phases. |
+| `retained_vectors_blocked` within `apply_failed` (operation: `failed`) | Inspect both the retained page-chunk/fact/take counts and the archived-page blocked-work count. Migration can lack an eligible rebuild path even when vectors are already missing. Preserve the data and obtain the owner's retention/recovery decision before retrying. | Refusal does not undo earlier committed progress or authorization debits. |
+| `retained_vector_check_failed` within `apply_failed` (operation: `failed`) | Rebuildability could not be established. Inspect the same selected brain's status and database/schema/embedding-registry access; restore reliable inspection before retrying. Do not interpret an unavailable census as zero blockers. | This phase is refused; the failed check does not establish that previous phases made no changes or spent nothing. |
+| `incomplete` | Inspect remaining work, provider health, and ownership; resume only after resolving the blocker. | Completed chunks/facts and prior debits remain; incomplete is not a rollback. |
+
+Keeping the current model, or leaving an in-flight migration paused, is valid until
+the owner chooses an eligible recovery path. Preserve deletion and `embed_skip`
+intent: do not automatically restore pages or remove skip policy to bypass a
+refusal. A width change may refuse because of retained deleted/skip vectors even
+when a same-width migration can leave those vectors untouched and complete.
+Archived blocked work can include NULL vectors, contentful chunkless pages,
+unsealed projections, or signature/legacy text-hash drift. At preflight, known
+archived blockers refuse migration before new authorization or provider calls.
+Standalone brain-wide `embed --stale` can repair active work while explicitly
+reporting archived blockers as incomplete; it does not dispatch archived text.
+Restoring an archived source still requires the owner's deliberate approval.
+Unsealed unsupported media needs its original importer; a sealed imported image
+with usable stored chunks can migrate through the existing embedder. These are
+phase-local checks, not a purge path or permission for raw SQL, a forced marker
+reset, or a new override. `--status` and `--dry-run` describe runnable work and
+estimates; they do not prove that the live retained-vector check will pass.
+
+Use `gbrain migrate embeddings --status --json` on the selected brain. Increasing
+`--max-cost-usd` is renewed authorization for a larger **total** cap, not a reset
+of prior debits. The CLI does not infer that a failure means zero writes.
+
+1. Inspect without mutations or provider calls:
+ `gbrain migrate embeddings --status --json`, then a target-specific
+ `--dry-run`. Inspect chunks, facts, projection blockers, target dimensions,
+ reranker action and whether pricing is known.
+2. Verify a full database backup on an isolated restore. For PGLite, stop all
+ processes using the brain, wait for a clean close/checkpoint, and copy the
+ entire database directory plus configuration. Open a **copy** with the
+ matching binary. For PostgreSQL, use the PostgreSQL backup tools against
+ the selected database and restore into a separate database with compatible
+ pgvector/extensions. Compare canonical pages, facts, withdrawal ledger and
+ queued intent. Markdown export is not a database backup. Follow the
+ [engine-specific backup and isolated-restore examples](../embedding-migrations.md#backup-and-isolated-restore).
+3. Authorize a bounded migration, for example:
+ `gbrain migrate embeddings --to openai:text-embedding-3-small --dim 1536 --reranker off --max-cost-usd 1 --yes --json`.
+ The dollar amount is an operator-chosen total limit, not a price quote.
+ A batch size is not a spending cap. The preview character-based cost is
+ an estimate; admission reserves conservative per-attempt token ceilings.
+4. An incomplete or failed apply exits nonzero. Read `--status` before
+ repeating the same command. Already-correct chunks/facts are not sent
+ again. A crash, timeout or provider refusal does not refund a debit.
+ If the cap is exhausted, fix the underlying provider problem and explicitly
+ raise the **total** authorization to continue. Do not reset the marker.
+ Projection recovery may have made durable progress even when migration
+ invalidation was refused. Unsealed unsupported media needs its original
+ importer; never stamp projection revisions with SQL.
+5. Verify `facts_pending`, remaining chunks and the completion receipt with
+ `--status --json`, then perform a known-positive retrieval in the same
+ brain and a genuine miss. `--no-embed` is deliberately deferred, not
+ complete. A cursor reaching EOF does not mean blocked work completed.
+
+For a synthetic brain containing one pending page and one active fact, the
+tested PostgreSQL and PGLite runs returned this subset of the JSON result:
+
+```json
+{"status":"completed","remaining":0,"facts_embedded":1,"facts_remaining":0,"blocked_projection_pages":0}
+```
+
+Repeating the same completed migration, including `--reranker off`, returned
+`{"status":"skipped_no_work"}` without new provider work. These are synthetic
+recovery checks, not a prediction of a personal brain's counts or provider cost.
+
+For a brain already missing page vectors, `gbrain embed --stale
+--include-null-signature` uses the same bounded canonical projection recovery.
+For source-scoped facts, preview `gbrain embed --facts --stale --source
+'source-example' --dry-run --json`; explicit repair requires `--yes
+--max-cost-usd 1` and supports `--max-facts` bounded work. Use the brain-wide
+migration command when durable authorization across interruptions is required.
+
+Prefer forward recovery. A binary rollback does not restore vectors or undo
+the schema. Restoring an older backup over a brain with intervening writes or
+committed withdrawals can resurrect forgotten content and is unsafe; do not
+do that without a separately reviewed reconciliation of all later intent.
+
+### Verify a known result and a genuine miss
+
+After status reports completion, keep the same brain and source selection and
+check content you already know exists. Authorize any provider calls separately;
+a search on an embedded brain can contact its configured provider. In the
+network-isolated keyless fixture used for this release, these exact commands ran
+against an existing synthetic page:
+
+```bash
+gbrain --brain host search amberbadgerfixtureproof --source default --json
+gbrain --brain host search zzzgenuinemissfixtureproof --source default --json
+```
+
+The first returned `concepts/keyless-fixture-example` with `keyword_hit: true`;
+the second returned `[]`, and both exited zero. These tokens belong only to that
+fixture. For your brain, substitute an existing non-sensitive phrase and a
+deliberately absent phrase, and check the expected source/slug rather than merely
+counting results. A clean miss must remain a miss. Those recorded keyless results
+prove content persistence and keyword retrieval, **not vector repair**: that
+fixture explicitly reported keyword-only degradation. On an approved embedded
+brain, also inspect migration completion and retrieval degradation; a keyword
+hit alone does not establish semantic recovery. Do not paste private content
+into diagnostic reports.
## What the rebuild deletes
@@ -116,8 +279,9 @@ The dimension change **deletes the stored vectors in the dim-pinned text columns
they are in the old model's space and unusable. They are not recoverable:
going back to the previous provider means paying for a second full re-embed.
`content_chunks` vectors are rebuilt by the re-embed pass. Semantic result
-caching remains disabled. Fact-vector repair is separate and explicitly
-consented; see [fact-vector repair](../embedding-migrations.md). Image and
+caching remains disabled. Eligible fact vectors are repaired in the same
+consented migration; a separate source-scoped repair is also available in
+[fact-vector repair](../embedding-migrations.md#repair-missing-fact-vectors-deliberately). Image and
multimodal columns are not part of this text-space rebuild.
## Resume after a kill
@@ -145,14 +309,20 @@ fully-embedded page. Without it a large brain would report "incomplete" and the
re-run would pay again for those pages. `--batch-size N` tunes the batch
(default 2000).
-`--no-embed` applies schema + config + invalidation and stops, so you can run
-the (potentially long) re-embed later or in the background:
+`--no-embed` applies schema + config + invalidation and stops with deliberately
+deferred work. Inspect status, then resume the migration without `--no-embed` so
+the existing total authorization and completion checks still cover the repair:
```bash
-gbrain migrate embeddings --to openai:text-embedding-3-small --yes --no-embed
-gbrain embed --stale --catch-up --include-null-signature --background
+gbrain migrate embeddings --to openai:text-embedding-3-small --yes --no-embed --max-cost-usd 1
+gbrain migrate embeddings --status --json
+gbrain migrate embeddings --to openai:text-embedding-3-small --yes --max-cost-usd 1
```
+The example cap must be approved by the operator. The resumed command retains
+earlier debits; it does not authorize another dollar. A standalone/background
+embedding invocation does not inherit this migration's durable allowance.
+
## During the migration
While the re-embed runs, semantic search returns degraded (lexical-arm-only)
diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.md
index 2fb4895a24..b9d081e14a 100644
--- a/docs/guides/google-connect.md
+++ b/docs/guides/google-connect.md
@@ -270,3 +270,105 @@ copy the harness should relay verbatim is fenced in `[SHOW USER]` blocks.
The whole setup is exactly two user interactions: (1) the GCP checklist +
client JSON hand-back, (2) one consent click. Never pass secrets via argv —
use `--client-json <path>`, stdin, or env.
+
+## Attachment receipts and historical repair
+
+Gmail attachment receipts record filenames, MIME types, byte sizes when supplied,
+account/message/part identity, and Gmail attachment IDs when available. They do
+**not** download attachments or index their contents. Calendar documents and
+inline parts are distinguished from ordinary documents; plain/HTML message-body
+parts are not attachment receipts. Receipt metadata inherits its message page's
+source and visibility. Filenames are inert data, not paths or executable links.
+
+Message rendering distinguishes four states:
+
+- **Not inspected:** a legacy message has no inspection receipt. Absence of a
+ receipt says nothing about whether an attachment exists.
+- **Inspection incomplete:** missing/malformed MIME data or a safety bound stopped
+ inspection. Any receipts already observed remain visible, but absence is unknown.
+- **Inspected; none found:** bounded inspection completed without attachments.
+- **Present; not downloaded; not indexed:** metadata exists, but attachment content
+ is not available to search. For example, `fixture.pdf — application/pdf; 17 bytes`.
+
+Each message MIME walk is iterative, capped at depth 32 and 512 visited parts.
+Attachment receipt payloads have a 64 KiB aggregate budget per fetched thread;
+over-limit metadata is incomplete rather than silently marked empty. Missing part
+IDs use deterministic MIME paths. Duplicate filenames remain separate receipts.
+Missing message IDs have deterministic fallback identities but no invented Gmail
+link. Pure-noise threads remain excluded by the existing ingestion policy.
+
+Historical repair requests a Gmail partial response containing message IDs and
+explicit MIME metadata fields; `body.data`, raw messages and snippets are never
+selected. The selection includes child-identity sentinels beyond depth 32 so a
+deeper MIME tree remains incomplete rather than appearing empty. Decoded metadata
+responses are capped at 2 MiB before JSON parsing; oversized responses fail without
+advancing repair. Ordinary sync's message-body requests are unchanged.
+
+Upgrading changes future ingestion, **not** every historical page. Ordinary
+incremental sync only revisits changed threads and its success does not establish
+historical inspection. To repair already-imported pages without replaying bodies:
+
+```sh
+gbrain google attachments backfill --brain host --source gmail-example --json
+gbrain google attachments backfill --brain host --source gmail-example --yes --limit 25 --json
+```
+
+This is a trusted **local, managed-persistence-only** command for both PGLite and
+PostgreSQL. Use an existing Google source and existing CLI writer registration on
+the selected canonical host. It never enables persistence, installs services, or
+silently registers a new repair writer. Keep old conflicting mutation workers
+quiesced without deleting their queued work. For PGLite, stop its resident owner
+cleanly first: this command does not delegate historical repair to a running owner.
+For PostgreSQL, use the configured host brain or an explicitly selected local
+PostgreSQL mount; source selection never switches the database. Unmanaged sources
+can continue ordinary ingestion, but this historical repair refuses them.
+
+The first command is read-only and makes no Google calls. Its `status: "preview"`
+names the effective brain, source, account, imported-page count and saved historical
+cursor (or `not_inspected`). Review that scope before applying `--yes`. The apply
+command processes at most 25 imported thread pages, patches only the
+`gmail_attachment_receipts` frontmatter field, and preserves current body, other
+frontmatter, tags, visibility and committed withdrawals. It never calls loop/fact
+extraction or an attachment-download/model API. Canonical text projections are
+rebuilt without provider calls; receipt filenames are not extracted as facts.
+
+A batch returning `status: "paused", complete: false` exits nonzero with its
+durable count and cursor. Repeat the **same command** to resume. The per-account
+cursor is checkpointed only after committed page receipts; interruption can repeat
+a page safely without duplicating receipt identities. `status: "complete"` means
+traversal of the fixed upper page-ID boundary captured at the first repair invocation
+is done, **not that every message was inspected or mailbox-wide coverage**.
+`inspected` counts fully inspected pages; `unavailable` counts pages with missing
+historical messages, and `unavailableMessages` counts those identities separately.
+`inspection_complete` is false when traversal is paused or any identity is unavailable.
+This scan has no date filter and does not import
+missing/deleted pages; new ingestion handles newly imported pages.
+
+A confirmed Gmail thread HTTP 404 or a missing historical message ID in an otherwise
+valid thread records `messages[].unavailable` (`thread_not_found` or
+`message_not_found`). Any prior receipt and inspection metadata stays intact; an
+identity without prior metadata has `inspection.state: not_inspected`, not `none`.
+The historical body, privacy and message IDs remain unchanged. The durable cursor
+can then continue to later pages without repeatedly blocking on upstream absence.
+Authorization/rate-limit errors, malformed responses, other HTTP errors and unknown
+ownership are not disappearance and do not authorize skipping the affected page.
+
+`incomplete` also exits nonzero and leaves the cursor before that page. A conflict
+(unknown receipt ownership, canonical edit during publication, delete/recreation,
+source/account change or lost lease) preserves existing content and stops progress.
+Inspect the retained write receipt and source before retrying. After resolving a
+terminal failed receipt, `--yes --retry-failed` explicitly authorizes its linked
+retry; never reset cursors, force overwrite, or restore an old backup to bypass a
+withdrawal. Completed partial work remains durable. Provider failure, unavailable
+owners and malformed metadata are not successful inspection.
+
+Verify with the preview command above and an authorized page read:
+
+```sh
+gbrain get emails/2026/09/example-thread --brain host --source gmail-example
+```
+
+Inspect `frontmatter.gmail_attachment_receipts.messages[].inspection` for the
+individual states and preserved attachment identities. The page's existing Gmail
+citation remains its navigation link; a missing message ID reports unavailable.
+Private pages and their receipts remain unavailable to unauthorized remote readers.
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index 9b6911f2a8..57d63a1427 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -71,6 +71,29 @@ No server, no tunnel, no token needed. Works on both PGLite and Postgres engines
`--surface starter` sits between (~27 ops: the verbs plus the daily-driver set);
omit the flag (default `full`) for every operation.
+#### Stdio source binding
+
+Do not inherit `GBRAIN_SOURCE=__all__` from a trusted CLI session into a
+stdio MCP server. It does not grant all-source access: the server keeps a
+fail-closed scope, so searches can return healthy empty results even when
+the trusted CLI finds pages. Startup stderr warns about this binding before
+the MCP handshake; it does not inspect or reveal private pages.
+
+In the MCP host's server environment, set `GBRAIN_SOURCE` to the intended
+registered source id, or remove it to use normal source resolution and its
+configured federation rules. Inspect registered ids with `gbrain sources list`
+on the brain host, then restart the MCP server and check a known world-visible
+page in the intended source. Removing the variable is not unrestricted access:
+dotfiles and other source-resolution settings still apply. No memory writes or
+index repair are needed to correct this environment binding.
+
+This differs from the per-call `source_id: "__all__"` argument, which searches
+only the caller's granted sources. MCP callers also exclude private pages by
+default; a private-only miss is not evidence of a broken index. For a concrete
+source binding that still misses a known visible page, retain the version,
+engine, schema pack, effective source/grants, and retrieval metadata for a
+sanitized reproduction rather than broadening permissions.
+
### Tailscale (recommended): `gbrain mcp expose`
```bash
diff --git a/docs/storage-tiering.md b/docs/storage-tiering.md
index ef2ec52ca2..6812fa9478 100644
--- a/docs/storage-tiering.md
+++ b/docs/storage-tiering.md
@@ -218,5 +218,77 @@ On the PGLite engine (gbrain's local-only embedded Postgres), the "DB" your db_o
- **Backward compatible**: systems without `gbrain.yml` work unchanged.
- **Progressive enhancement**: add configuration when needed.
- **Database unchanged**: all data remains in Postgres regardless of tier.
-- **Existing workflows**: all existing `sync` and `export` behavior preserved.
+- **Export safety**: exports refuse collisions and occupied planned paths; use a fresh destination for each snapshot.
- **Deprecated keys**: `git_tracked` / `supabase_only` still load with a once-per-process warning.
+
+## Safe export
+
+`gbrain export` produces a point-in-time Markdown snapshot, not a full database
+backup. It does not replace a verified PGLite/PostgreSQL backup or preserve all
+database state. The existing `<slug>.md` and `.raw/<name>.json` layout is unchanged.
+
+```sh
+gbrain export --source default --dir './exports/default-new'
+gbrain export --source=default --slug-prefix 'notes/' --dir './exports/notes-new'
+gbrain export --restore-only --source default --repo './brain' --dir './restore-new'
+```
+
+Normal export without `--source` includes every source, including archived sources;
+environment/dotfile defaults do not silently narrow it. An explicit source must be
+active and registered. Restore-only selects one source, uses its storage tiering
+configuration and checks the recorded file path before deciding a page is missing.
+An ambiguous repo requires an explicit source. Restore-only writes to `--dir`, not
+implicitly to `--repo`.
+
+Source selection, page enumeration, canonical withdrawal overlays, tags and raw
+sidecars share one repeatable-read transaction. A withdrawal committed before the
+snapshot is reflected. A later withdrawal does not rewrite an already-created
+historical export. Re-import is still subject to the current withdrawal ledger;
+do not restore an old database over committed withdrawal intent.
+
+All planned paths are staged privately before destination publication. Duplicate
+slugs across sources, same-source aliases, case/Unicode aliases, page/sidecar and
+file-prefix conflicts refuse without publishing files. Export sources separately
+into fresh directories rather than changing their slug layout. Existing empty
+destinations and unrelated files are preserved. An occupied planned file, sidecar
+or reserved `.gbrain-export-status` path refuses; export never overwrites or prunes
+unknown files and has no force option.
+
+Publication uses the first-party native addon for Linux glibc/musl, macOS and
+Windows on x64/arm64. Directory handles remain anchored, symlinks/reparse points
+are rejected, and native no-replace operations publish complete leaves. Missing
+addons or unsupported filesystem capabilities refuse rather than use an unsafe
+pathname fallback. Windows destinations must use absolute drive paths, not UNC
+or device namespaces. POSIX destinations must have no symlink ancestors; on macOS,
+use physical paths rather than the conventional `/tmp` or `/var` aliases.
+Use a directory controlled by the exporting operator; do not
+concurrently rename the destination or its parent directories. Native confinement
+is not a sandbox against another process running as the same operating-system user.
+
+The reserved status file starts with `GBRAIN EXPORT INCOMPLETE`. Its final line is
+`COMPLETE` only after data publication and flushes succeed. A nonzero exit means
+the current run did not produce a complete new export; an occupied-path refusal
+leaves an earlier completed export unchanged. A missing completion line or malformed
+status marks newly published output as incomplete: preserve it for inspection and
+retry into a **fresh** directory. Do not import a partial
+export. Interruption or I/O failure can leave complete individual files plus the
+incomplete marker; retry never deletes these or tries to guess ownership. Only a
+completed run prints `Exported N pages` (or `Restored N pages`).
+
+Enumeration uses 256-key batches, not OFFSET or a total-page cap. Private on-disk
+SQLite staging is bounded to 8 GiB, individual payloads/withdrawal ledgers to 32 MiB,
+and snapshot collection to ten minutes with a 60-second statement timeout. Reaching
+a bound is failure, not truncation or success. Use `--source`, `--type` or
+`--slug-prefix` to make smaller snapshots. These are fixed safety limits, not a
+promise about export duration or a paid-work budget. No model provider is called.
+
+The ten-minute collection limit includes time waiting for a remote database.
+Page reads are sequential, so network latency can make a large remote snapshot
+reach that limit even when its files fit the staging budget. Run the export near
+the database or select smaller scopes. Separately exported scopes each have their
+own snapshot time; together they are not one point-in-time database backup.
+
+Within each key batch, export reads one source's capacity-checked withdrawal ledger
+at a time and reuses it for that source's pages. It does not retain a whole-brain
+ledger cache. Bodies and timelines without literal fact-marker text skip SQL
+normalization; actual, malformed and orphan markers retain canonical fingerprinting.
diff --git a/llms-full.txt b/llms-full.txt
index 5ea9df8cfd..baa3111cb6 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1797,6 +1797,11 @@ Ship via the `/ship` skill, not by hand. The full release + contributor process
(CHANGELOG voice, version-locations sync, PR conventions, community-PR-wave) lives in
[`./docs/RELEASING.md`](./docs/RELEASING.md); read it before shipping.
+**Always use PATCH without asking**, including the initial release choice;
+override `/ship`'s MINOR/MAJOR prompts. Auto-allocate past collisions, sync all
+version stamps and the PR title, then report the number. This changes numbering
+only: scope, merge, deployment, paid-work and validation approvals still apply.
+
## Privacy
Never commit real names of people, companies, or funds into public artifacts. See the
@@ -2195,9 +2200,10 @@ four numeric segments are required first. Historical 3-segment versions
DRIFT_STALE_PKG / DRIFT_UNEXPECTED, and refuses to proceed on
DRIFT_UNEXPECTED. This is why the two must move together.
-**Auto-renumber when needed; never ask.** Use `/ship`'s queue-aware allocator,
-update all version stamps and the PR title, then report the number. This overrides
-its ALREADY_BUMPED rebump prompt, not scope, merge or deployment approvals.
+**Always use PATCH without asking**, including the initial release choice;
+override `/ship`'s MINOR/MAJOR prompts. Auto-allocate past collisions, sync all
+version stamps and the PR title, then report the number. This changes numbering
+only: scope, merge, deployment, paid-work and validation approvals still apply.
CI rejects mismatched `VERSION`/`package.json` or versions not newer than master.
### Version consistency and conflict recovery
@@ -6133,6 +6139,29 @@ No server, no tunnel, no token needed. Works on both PGLite and Postgres engines
`--surface starter` sits between (~27 ops: the verbs plus the daily-driver set);
omit the flag (default `full`) for every operation.
+#### Stdio source binding
+
+Do not inherit `GBRAIN_SOURCE=__all__` from a trusted CLI session into a
+stdio MCP server. It does not grant all-source access: the server keeps a
+fail-closed scope, so searches can return healthy empty results even when
+the trusted CLI finds pages. Startup stderr warns about this binding before
+the MCP handshake; it does not inspect or reveal private pages.
+
+In the MCP host's server environment, set `GBRAIN_SOURCE` to the intended
+registered source id, or remove it to use normal source resolution and its
+configured federation rules. Inspect registered ids with `gbrain sources list`
+on the brain host, then restart the MCP server and check a known world-visible
+page in the intended source. Removing the variable is not unrestricted access:
+dotfiles and other source-resolution settings still apply. No memory writes or
+index repair are needed to correct this environment binding.
+
+This differs from the per-call `source_id: "__all__"` argument, which searches
+only the caller's granted sources. MCP callers also exclude private pages by
+default; a private-only miss is not evidence of a broken index. For a concrete
+source binding that still misses a known visible page, retain the version,
+engine, schema pack, effective source/grants, and retrieval metadata for a
+sanitized reproduction rather than broadening permissions.
+
### Tailscale (recommended): `gbrain mcp expose`
```bash
diff --git a/native/locks/README.md b/native/locks/README.md
index 7a62ba7071..887a6a2050 100644
--- a/native/locks/README.md
+++ b/native/locks/README.md
@@ -58,6 +58,77 @@ exports refuse registration without borrowing another runtime's environment.
The Windows IPC helpers link the OS-provided `bcrypt` CNG library and remain
within Node-API v3 and the existing Windows platform minimum.
+## Export publication
+
+`export-publication.h` adds `beginExport(absoluteDestination)`,
+`publishExportFile(handle, relativePath, Buffer)`, `completeExport(handle)` and
+idempotent `closeExport(handle)`. `nativeExportPublisher()` loads these four
+synchronous methods asynchronously through the same literal addon imports.
+Export handles have their own registry and cleanup hook; they cannot be passed
+to lock operations, or vice versa. There is no filesystem fallback when the
+addon or an OS primitive is unavailable.
+
+The destination must be operator-controlled. Existing components are opened one
+at a time without following symlinks or Windows reparse points. Missing
+directories are created privately on POSIX and with inherited permissions on
+Windows. Windows retains ancestor handles without delete sharing and accepts
+absolute drive paths, not UNC/device namespaces. POSIX accepts absolute paths;
+macOS's conventional `/tmp` and `/var` symlink aliases must be supplied using
+their real directory paths. Relative publication paths use `/`, contain no
+empty/dot/parent components, and reject Windows device names, alternate streams,
+backslashes, control characters, and trailing dots/spaces on every platform.
+Components are limited to 255 UTF-8 bytes and walks to 256 components.
+
+Begin exclusively creates `.gbrain-export-status` and writes and flushes
+`GBRAIN EXPORT INCOMPLETE\n`. Existing markers are never removed or overwritten.
+Each file is fully written and flushed to a same-directory exclusive temporary
+file before publication. POSIX uses `linkat(..., 0)` followed by temporary-name
+removal and directory `fsync`; Windows uses `SetFileInformationByHandle` with
+`FileRenameInfo`, `ReplaceIfExists=FALSE`, a null `RootDirectory`, and the absolute
+destination path. Retained ancestor handles deny delete sharing throughout the
+rename, so destination components cannot be replaced. Existing files, hard-link
+aliases, directories and symlinks cannot be replaced. Windows files use `FILE_FLAG_WRITE_THROUGH` and
+`FlushFileBuffers`; this is not a claim of POSIX directory-fsync or whole-volume
+power-loss durability. Microsoft's contracts are documented in
+[FILE_RENAME_INFO](https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_rename_info)
+and [FlushFileBuffers](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers).
+
+A publication error permanently prevents completion on that handle. Complete
+appends and flushes `COMPLETE\n`; a failed completion attempts to truncate that
+append and flush the original incomplete marker, then refuses further use.
+As with all filesystem durability, a device that also refuses recovery writes
+cannot provide a guaranteed on-disk rollback. Close, finalization, process exit,
+and errors retain the marker and any already-published output; they never erase
+unknown or preexisting files. Successful completion does not implicitly close.
+
+Before each POSIX publication and completion, the addon reopens the retained
+destination and every ancestor component without following symlinks and compares
+their device/inode identities with the retained handles. It also verifies that
+the current marker name still identifies the retained regular file. Publication
+repeats these checks after staging, including its output-parent chain. A missing
+or replaced component or marker poisons the handle before further publication
+or completion, without modifying a replacement tree or marker. This detects
+topology changes between calls; it does not eliminate the race after the last
+identity check against a hostile equally privileged process.
+
+Staging names are `.gbrain-export-<128-bit-random-run-id>.tmp`. Ordinary failures
+remove only the staging file just created by the call. Synchronous publication
+allows at most one outstanding staging file per export; a crash can leave that
+one file (possibly partially written), plus completed output and the incomplete
+marker. Failed exports do not automatically retry or reclaim another run's
+leftovers. An operator can inspect and remove their failed destination before
+retrying. This is anchored confinement for operator-controlled directories, not
+a security claim against equally privileged hostile processes moving or editing
+the export tree or its retained ancestors.
+
+`bun test test/native-export-publication.test.ts test/native-export-faults.test.ts`
+checks real no-replace behavior, marker ownership, handle separation, component
+refusals, competing exporters, lifecycle, and permissions. The Linux/glibc-only
+fault suite compiles a test-only interposer to exercise write, flush, terminal
+flush and SIGKILL failures against the real addon; it is not linked into shipped
+binaries. Native macOS and Windows execution and the Darwin SDK ABI check are
+required separately; cross-compilation alone does not validate runtime behavior.
+
Use the pinned Zig 0.14.1 compiler. Archive URLs, SHA-256 hashes and sizes
are in `scripts/native/toolchain.json`; setup verifies them before extracting.
diff --git a/native/locks/abi-check.c b/native/locks/abi-check.c
index 2c5eb961ae..2ac8c8b645 100644
--- a/native/locks/abi-check.c
+++ b/native/locks/abi-check.c
@@ -4,9 +4,24 @@
#include <sys/stat.h>
#include <sys/file.h>
#include <errno.h>
+#include <unistd.h>
+#include <stdint.h>
_Static_assert(sizeof(struct stat) == 144, "Darwin stat ABI size");
+_Static_assert(offsetof(struct stat, st_dev) == 0, "Darwin stat device offset");
+_Static_assert(offsetof(struct stat, st_ino) == 8, "Darwin stat inode offset");
_Static_assert(offsetof(struct stat, st_mode) == 4, "Darwin stat mode offset");
_Static_assert(offsetof(struct stat, st_size) == 96, "Darwin stat size offset");
_Static_assert(O_RDWR == 2 && O_NONBLOCK == 4 && O_NOFOLLOW == 0x100 && O_CREAT == 0x200 && O_CLOEXEC == 0x1000000, "Darwin open ABI");
_Static_assert(LOCK_EX == 2 && LOCK_NB == 4 && EAGAIN == 35 && EINTR == 4 && EINVAL == 22, "Darwin lock ABI");
+_Static_assert(O_RDONLY == 0 && O_WRONLY == 1 && O_EXCL == 0x800 && O_DIRECTORY == 0x100000, "Darwin export open ABI");
+_Static_assert(SEEK_SET == 0 && ENOENT == 2 && EIO == 5 && ENOMEM == 12 && EEXIST == 17, "Darwin export error ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&openat), int (*)(int, const char *, int, ...)), "openat ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&mkdirat), int (*)(int, const char *, unsigned short)), "mkdirat ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&linkat), int (*)(int, const char *, int, const char *, int)), "linkat ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&unlinkat), int (*)(int, const char *, int)), "unlinkat ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&write), long (*)(int, const void *, size_t)), "write ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&read), long (*)(int, void *, size_t)), "read ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&fsync), int (*)(int)), "fsync ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&ftruncate), int (*)(int, int64_t)), "ftruncate ABI");
+_Static_assert(__builtin_types_compatible_p(__typeof__(&lseek), int64_t (*)(int, int64_t, int)), "lseek ABI");
int main(void) { return 0; }
diff --git a/native/locks/darwin-abi.h b/native/locks/darwin-abi.h
index 455e3dbef3..0895f5caa9 100644
--- a/native/locks/darwin-abi.h
+++ b/native/locks/darwin-abi.h
@@ -15,12 +15,30 @@ extern void *calloc(size_t, size_t);
extern void free(void *);
extern int snprintf(char *, size_t, const char *, ...);
extern void *memchr(const void *, int, size_t);
+extern void *memcpy(void *, const void *, size_t);
+extern size_t strlen(const char *);
+extern int strcmp(const char *, const char *);
+extern char *strchr(const char *, int);
extern int open(const char *, int, ...);
+extern int openat(int, const char *, int, ...);
+extern int mkdirat(int, const char *, unsigned short);
+extern int linkat(int, const char *, int, const char *, int);
+extern int unlinkat(int, const char *, int);
+extern long read(int, void *, size_t);
+extern long write(int, const void *, size_t);
+extern int fsync(int);
+extern int ftruncate(int, int64_t);
+extern int64_t lseek(int, int64_t, int);
extern int close(int);
extern int flock(int, int);
extern int *__error(void);
#define errno (*__error())
#define O_RDWR 0x0002
+#define O_RDONLY 0
+#define O_WRONLY 1
+#define O_EXCL 0x0800
+#define O_DIRECTORY 0x100000
+#define SEEK_SET 0
#define O_NONBLOCK 0x0004
#define O_NOFOLLOW 0x0100
#define O_CREAT 0x0200
@@ -29,6 +47,10 @@ extern int *__error(void);
#define LOCK_NB 4
#define EINTR 4
#define EINVAL 22
+#define ENOENT 2
+#define EIO 5
+#define ENOMEM 12
+#define EEXIST 17
#define EAGAIN 35
#define EWOULDBLOCK EAGAIN
#define S_ISREG(mode) (((mode) & 0170000) == 0100000)
@@ -50,6 +72,8 @@ struct stat {
int64_t reserved[2];
};
_Static_assert(sizeof(struct stat) == 144, "Darwin stat ABI size");
+_Static_assert(offsetof(struct stat, st_dev) == 0, "Darwin stat ABI device offset");
+_Static_assert(offsetof(struct stat, st_ino) == 8, "Darwin stat ABI inode offset");
_Static_assert(offsetof(struct stat, st_mode) == 4, "Darwin stat ABI mode offset");
#ifdef __x86_64__
extern int fstat(int, struct stat *) __asm("_fstat$INODE64");
diff --git a/native/locks/export-publication.h b/native/locks/export-publication.h
new file mode 100644
index 0000000000..aa1abd81fe
--- /dev/null
+++ b/native/locks/export-publication.h
@@ -0,0 +1,532 @@
+#ifndef GBRAIN_EXPORT_PUBLICATION_H
+#define GBRAIN_EXPORT_PUBLICATION_H
+
+#define EXPORT_MARKER ".gbrain-export-status"
+#define EXPORT_INCOMPLETE "GBRAIN EXPORT INCOMPLETE\n"
+
+typedef struct export_dir {
+ os_handle handle;
+ struct export_dir *parent;
+#ifdef _WIN32
+ wchar_t *path;
+#else
+ char name[256];
+#endif
+} export_dir;
+
+typedef struct export_state export_state;
+typedef struct export_handle {
+ export_dir *root;
+ os_handle marker;
+ bool failed;
+ bool completed;
+ char temporary[64];
+ struct export_handle *next;
+ export_state *owner;
+} export_handle;
+
+struct export_state {
+ export_handle *handles;
+ size_t references;
+ bool closing;
+};
+
+static unsigned long export_error(void) {
+#ifdef _WIN32
+ return GetLastError();
+#else
+ return (unsigned long)errno;
+#endif
+}
+
+static unsigned long export_invalid(void) {
+#ifdef _WIN32
+ return ERROR_INVALID_DATA;
+#else
+ return EINVAL;
+#endif
+}
+
+static napi_value export_fail(napi_env env, const char *action, unsigned long code) {
+ char message[160];
+ snprintf(message, sizeof(message), "Native export %s failed (OS error %lu)", action, code);
+ napi_throw_error(env, "GBRAIN_NATIVE_EXPORT_IO", message);
+ return NULL;
+}
+
+static unsigned long export_close_file(os_handle handle) {
+ if (handle == INVALID_LOCK_HANDLE) return 0;
+#ifdef _WIN32
+ return CloseHandle(handle) ? 0 : export_error();
+#else
+ return close(handle) == 0 ? 0 : export_error();
+#endif
+}
+
+static unsigned long export_close_dirs(export_dir *dir, export_dir *stop) {
+ unsigned long error = 0;
+ while (dir && dir != stop) {
+ export_dir *parent = dir->parent;
+ unsigned long current = export_close_file(dir->handle);
+ if (!error) error = current;
+#ifdef _WIN32
+ free(dir->path);
+#endif
+ free(dir);
+ dir = parent;
+ }
+ return error;
+}
+
+static unsigned long export_flush(os_handle handle) {
+#ifdef _WIN32
+ return FlushFileBuffers(handle) ? 0 : export_error();
+#else
+ int result;
+ do { result = fsync(handle); } while (result != 0 && errno == EINTR);
+ return result == 0 ? 0 : export_error();
+#endif
+}
+
+static unsigned long export_flush_dir(export_dir *dir) {
+#ifdef _WIN32
+ (void)dir;
+ return 0;
+#else
+ return export_flush(dir->handle);
+#endif
+}
+
+static unsigned long export_verify(export_handle *handle, export_dir *dir) {
+#ifdef _WIN32
+ (void)handle; (void)dir;
+ return 0;
+#else
+ for (; dir; dir = dir->parent) {
+ int current = dir->parent ? openat(dir->parent->handle, dir->name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ : open(dir->name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (current < 0) return export_error();
+ struct stat retained_info, current_info;
+ unsigned long error = 0;
+ if (fstat(dir->handle, &retained_info) != 0 || fstat(current, &current_info) != 0) error = export_error();
+ else if (retained_info.st_dev != current_info.st_dev || retained_info.st_ino != current_info.st_ino) error = export_invalid();
+ unsigned long close_error = export_close_file(current);
+ if (error || close_error) return error ? error : close_error;
+ }
+ int marker = openat(handle->root->handle, EXPORT_MARKER, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
+ if (marker < 0) return export_error();
+ struct stat retained_info, current_info;
+ unsigned long error = 0;
+ if (fstat(handle->marker, &retained_info) != 0 || fstat(marker, &current_info) != 0) error = export_error();
+ else if (!S_ISREG(current_info.st_mode) || retained_info.st_dev != current_info.st_dev ||
+ retained_info.st_ino != current_info.st_ino) error = export_invalid();
+ unsigned long close_error = export_close_file(marker);
+ return error ? error : close_error;
+#endif
+}
+
+static unsigned long export_write(os_handle handle, const void *data, size_t length) {
+ const char *cursor = data;
+ while (length) {
+ size_t amount = length > 0x40000000 ? 0x40000000 : length;
+#ifdef _WIN32
+ DWORD written = 0;
+ if (!WriteFile(handle, cursor, (DWORD)amount, &written, NULL)) return export_error();
+#else
+ long written = write(handle, cursor, amount);
+ if (written < 0) { if (errno == EINTR) continue; return export_error(); }
+#endif
+ if (!written) return export_invalid();
+ cursor += written;
+ length -= (size_t)written;
+ }
+ return export_flush(handle);
+}
+
+static bool export_component(const char *name) {
+ size_t length = strlen(name);
+ if (!length || length > 255 || name[length - 1] == '.' || name[length - 1] == ' ') return false;
+ char stem[8] = {0};
+ size_t stem_length = 0;
+ for (size_t i = 0; i < length; i++) {
+ unsigned char c = (unsigned char)name[i];
+ if (c < 32 || c == 127 || strchr("\\/:*?\"<>|", c)) return false;
+ if (c != '.' && stem_length == i && stem_length < sizeof(stem) - 1)
+ stem[stem_length++] = c >= 'a' && c <= 'z' ? (char)(c - 32) : (char)c;
+ }
+ if (!strcmp(stem, "CON") || !strcmp(stem, "PRN") || !strcmp(stem, "AUX") || !strcmp(stem, "NUL")) return false;
+ if (stem[0] == 'C' && stem[1] == 'O' && stem[2] == 'M') {
+ if ((stem_length == 4 && stem[3] >= '1' && stem[3] <= '9') ||
+ (stem_length == 5 && (unsigned char)stem[3] == 0xc2 &&
+ ((unsigned char)stem[4] == 0xb9 || (unsigned char)stem[4] == 0xb2 || (unsigned char)stem[4] == 0xb3))) return false;
+ }
+ if (stem[0] == 'L' && stem[1] == 'P' && stem[2] == 'T') {
+ if ((stem_length == 4 && stem[3] >= '1' && stem[3] <= '9') ||
+ (stem_length == 5 && (unsigned char)stem[3] == 0xc2 &&
+ ((unsigned char)stem[4] == 0xb9 || (unsigned char)stem[4] == 0xb2 || (unsigned char)stem[4] == 0xb3))) return false;
+ }
+ return true;
+}
+
+static char *export_string(napi_env env, napi_value value) {
+ size_t length = 0;
+ if (napi_get_value_string_utf8(env, value, NULL, 0, &length) != napi_ok || !length || length > 32768) return NULL;
+ char *text = malloc(length + 1);
+ if (!text) return NULL;
+ if (napi_get_value_string_utf8(env, value, text, length + 1, &length) != napi_ok || memchr(text, 0, length)) {
+ free(text); return NULL;
+ }
+ return text;
+}
+
+#ifdef _WIN32
+static wchar_t *export_wide(const char *text) {
+ int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text, -1, NULL, 0);
+ wchar_t *wide = length > 0 ? malloc((size_t)length * sizeof(wchar_t)) : NULL;
+ if (!wide) return NULL;
+ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text, -1, wide, length)) { free(wide); return NULL; }
+ return wide;
+}
+
+static wchar_t *export_child_path(export_dir *parent, const char *name) {
+ wchar_t *leaf = export_wide(name);
+ if (!leaf) return NULL;
+ size_t a = wcslen(parent->path), b = wcslen(leaf);
+ wchar_t *path = malloc((a + b + 2) * sizeof(wchar_t));
+ if (path) {
+ memcpy(path, parent->path, a * sizeof(wchar_t));
+ path[a] = L'\\';
+ memcpy(path + a + 1, leaf, (b + 1) * sizeof(wchar_t));
+ }
+ free(leaf);
+ return path;
+}
+#endif
+
+static export_dir *export_open_dir(export_dir *parent, const char *name, unsigned long *error) {
+ export_dir *dir = calloc(1, sizeof(*dir));
+ if (!dir) { *error = export_invalid(); return NULL; }
+ dir->handle = INVALID_LOCK_HANDLE;
+ dir->parent = parent;
+#ifdef _WIN32
+ dir->path = parent ? export_child_path(parent, name) : export_wide(name);
+ if (!dir->path) { *error = export_invalid(); goto failed; }
+ dir->handle = CreateFileW(dir->path, FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES,
+ FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
+ if (dir->handle == INVALID_LOCK_HANDLE && parent && GetLastError() == ERROR_FILE_NOT_FOUND) {
+ if (!CreateDirectoryW(dir->path, NULL) && GetLastError() != ERROR_ALREADY_EXISTS) { *error = export_error(); goto failed; }
+ dir->handle = CreateFileW(dir->path, FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES,
+ FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
+ }
+ if (dir->handle == INVALID_LOCK_HANDLE) { *error = export_error(); goto failed; }
+ BY_HANDLE_FILE_INFORMATION info;
+ if (!GetFileInformationByHandle(dir->handle, &info)) { *error = export_error(); goto failed; }
+ if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {
+ *error = export_invalid(); goto failed;
+ }
+#else
+ size_t name_length = strlen(name);
+ if (name_length >= sizeof(dir->name)) { *error = export_invalid(); goto failed; }
+ memcpy(dir->name, name, name_length + 1);
+ dir->handle = parent ? openat(parent->handle, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
+ : open(name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (dir->handle < 0 && parent && errno == ENOENT) {
+ if (mkdirat(parent->handle, name, 0700) != 0 && errno != EEXIST) { *error = export_error(); goto failed; }
+ if ((*error = export_flush_dir(parent))) goto failed;
+ dir->handle = openat(parent->handle, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ }
+ if (dir->handle < 0) { *error = export_error(); goto failed; }
+#endif
+ return dir;
+failed:
+ export_close_dirs(dir, parent);
+ return NULL;
+}
+
+static export_dir *export_walk(export_dir *start, char *path, char **leaf, unsigned long *error) {
+ export_dir *dir = start;
+ char *cursor = path;
+ unsigned depth = 0;
+ for (;;) {
+ char *slash = strchr(cursor, '/');
+ if (slash) *slash = 0;
+ if (++depth > 256 || !export_component(cursor)) { *error = export_invalid(); break; }
+ if (!slash && leaf) { *leaf = cursor; return dir; }
+ export_dir *next = export_open_dir(dir, cursor, error);
+ if (!next) break;
+ dir = next;
+ if (!slash) return dir;
+ cursor = slash + 1;
+ }
+ export_close_dirs(dir, start);
+ return NULL;
+}
+
+static os_handle export_create(export_dir *parent, const char *name, unsigned long *error) {
+ os_handle handle;
+#ifdef _WIN32
+ wchar_t *path = export_child_path(parent, name);
+ if (!path) { *error = export_invalid(); return INVALID_LOCK_HANDLE; }
+ handle = CreateFileW(path, GENERIC_WRITE | DELETE, FILE_SHARE_READ, NULL, CREATE_NEW,
+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH, NULL);
+ free(path);
+#else
+ handle = openat(parent->handle, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
+#endif
+ if (handle == INVALID_LOCK_HANDLE) *error = export_error();
+ return handle;
+}
+
+static unsigned long export_remove_temp(export_dir *parent, const char *name, os_handle handle) {
+#ifdef _WIN32
+ (void)parent; (void)name;
+ FILE_DISPOSITION_INFO disposition = { .DeleteFile = TRUE };
+ return SetFileInformationByHandle(handle, FileDispositionInfo, &disposition, sizeof(disposition)) ? 0 : export_error();
+#else
+ (void)handle;
+ return unlinkat(parent->handle, name, 0) == 0 ? 0 : export_error();
+#endif
+}
+
+static unsigned long export_publish(export_dir *parent, const char *temporary, const char *leaf, os_handle handle) {
+#ifdef _WIN32
+ (void)temporary;
+ wchar_t *wide = export_child_path(parent, leaf);
+ if (!wide) return export_invalid();
+ size_t bytes = wcslen(wide) * sizeof(wchar_t);
+ size_t size = sizeof(FILE_RENAME_INFO) + bytes;
+ FILE_RENAME_INFO *rename = calloc(1, size);
+ if (!rename) { free(wide); return export_invalid(); }
+ rename->ReplaceIfExists = FALSE;
+ rename->RootDirectory = NULL;
+ rename->FileNameLength = (DWORD)bytes;
+ memcpy(rename->FileName, wide, bytes);
+ unsigned long error = SetFileInformationByHandle(handle, FileRenameInfo, rename, (DWORD)size) ? 0 : export_error();
+ free(rename); free(wide);
+ return error;
+#else
+ (void)handle;
+ return linkat(parent->handle, temporary, parent->handle, leaf, 0) == 0 ? 0 : export_error();
+#endif
+}
+
+static unsigned long export_nonce(char *output) {
+ unsigned char bytes[16];
+#ifdef _WIN32
+ if (BCryptGenRandom(NULL, bytes, sizeof(bytes), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) return export_invalid();
+#else
+ int fd = open("/dev/urandom", O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd < 0) return export_error();
+ size_t offset = 0;
+ unsigned long error = 0;
+ while (offset < sizeof(bytes)) {
+ long count = read(fd, bytes + offset, sizeof(bytes) - offset);
+ if (count < 0 && errno == EINTR) continue;
+ if (count <= 0) { error = count < 0 ? export_error() : export_invalid(); break; }
+ offset += (size_t)count;
+ }
+ unsigned long close_error = export_close_file(fd);
+ if (error || close_error) return error ? error : close_error;
+#endif
+ for (size_t i = 0; i < sizeof(bytes); i++) snprintf(output + i * 2, 3, "%02x", bytes[i]);
+ return 0;
+}
+
+static unsigned long export_close(export_handle *handle) {
+ unsigned long error = export_close_file(handle->marker);
+ handle->marker = INVALID_LOCK_HANDLE;
+ unsigned long dir_error = export_close_dirs(handle->root, NULL);
+ handle->root = NULL;
+ return error ? error : dir_error;
+}
+
+static void export_release_state(export_state *state) {
+ if (--state->references == 0) free(state);
+}
+
+static void export_finalize(napi_env env, void *data, void *hint) {
+ (void)env; (void)hint;
+ export_handle *handle = data;
+ export_state *state = handle->owner;
+ export_close(handle);
+ export_handle **cursor = &state->handles;
+ while (*cursor && *cursor != handle) cursor = &(*cursor)->next;
+ if (*cursor) *cursor = handle->next;
+ free(handle);
+ export_release_state(state);
+}
+
+static void export_cleanup(void *data) {
+ export_state *state = data;
+ state->closing = true;
+ for (export_handle *handle = state->handles; handle; handle = handle->next) export_close(handle);
+ export_release_state(state);
+}
+
+static export_handle *export_get(napi_env env, napi_callback_info info, size_t count, napi_value *argv) {
+ size_t argc = count;
+ export_state *state = NULL;
+ void *pointer = NULL;
+ if (napi_get_cb_info(env, info, &argc, argv, NULL, (void **)&state) == napi_ok && argc > 0 &&
+ napi_unwrap(env, argv[0], &pointer) == napi_ok) {
+ for (export_handle *handle = state->handles; handle; handle = handle->next) if (handle == pointer) {
+ if (argc == count) return handle;
+ handle->failed = true;
+ break;
+ }
+ }
+ napi_throw_type_error(env, "GBRAIN_NATIVE_EXPORT_HANDLE", "Expected this addon's opaque export handle");
+ return NULL;
+}
+
+static napi_value export_undefined(napi_env env) {
+ napi_value result;
+ return napi_get_undefined(env, &result) == napi_ok ? result : NULL;
+}
+
+static napi_value begin_export(napi_env env, napi_callback_info info) {
+ napi_value argv[1], object;
+ size_t argc = 1;
+ export_state *state = NULL;
+ if (napi_get_cb_info(env, info, &argc, argv, NULL, (void **)&state) != napi_ok || argc != 1) return export_fail(env, "arguments", 0);
+ char *path = export_string(env, argv[0]);
+ if (!path) return export_fail(env, "destination", 0);
+ unsigned long error = 0;
+ export_dir *base = NULL, *root = NULL;
+ export_handle *handle = NULL;
+ if (state->closing) { error = export_invalid(); goto failed; }
+#ifdef _WIN32
+ size_t path_length = strlen(path);
+ if (path_length < 3 || !((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z')) ||
+ path[1] != ':' || (path[2] != '/' && path[2] != '\\')) { error = export_invalid(); goto failed; }
+ for (char *p = path + 2; *p; p++) if (*p == '\\') *p = '/';
+ char drive[] = "C:\\";
+ drive[0] = path[0];
+ base = export_open_dir(NULL, drive, &error);
+ char *relative = path + 3;
+#else
+ if (path[0] != '/') { error = export_invalid(); goto failed; }
+ base = export_open_dir(NULL, "/", &error);
+ char *relative = path + 1;
+#endif
+ if (!base) goto failed;
+ root = *relative ? export_walk(base, relative, NULL, &error) : base;
+ if (!root) goto failed;
+ handle = calloc(1, sizeof(*handle));
+ if (!handle) { error = export_invalid(); goto failed; }
+ handle->marker = INVALID_LOCK_HANDLE;
+ handle->root = root;
+ handle->owner = state;
+ char nonce[33];
+ if ((error = export_nonce(nonce))) goto failed;
+ snprintf(handle->temporary, sizeof(handle->temporary), ".gbrain-export-%s.tmp", nonce);
+ handle->marker = export_create(root, EXPORT_MARKER, &error);
+ if (handle->marker == INVALID_LOCK_HANDLE) goto failed;
+ if ((error = export_write(handle->marker, EXPORT_INCOMPLETE, sizeof(EXPORT_INCOMPLETE) - 1)) ||
+ (error = export_flush_dir(root))) goto failed;
+ if (napi_create_object(env, &object) != napi_ok || napi_wrap(env, object, handle, export_finalize, NULL, NULL) != napi_ok) {
+ error = export_invalid(); goto failed;
+ }
+ handle->next = state->handles;
+ state->handles = handle;
+ state->references++;
+ free(path);
+ return object;
+failed:
+ if (handle) { export_close(handle); free(handle); }
+ else export_close_dirs(root ? root : base, NULL);
+ free(path);
+ return export_fail(env, "begin", error);
+}
+
+static napi_value publish_export_file(napi_env env, napi_callback_info info) {
+ napi_value argv[3];
+ export_handle *handle = export_get(env, info, 3, argv);
+ if (!handle) return NULL;
+ if (!handle->root || handle->failed || handle->completed) return export_fail(env, "inactive handle", 0);
+ char *path = export_string(env, argv[1]);
+ void *data = NULL;
+ size_t length = 0;
+ bool buffer = false;
+ unsigned long error = 0;
+ export_dir *parent = NULL;
+ os_handle temporary = INVALID_LOCK_HANDLE;
+ bool published = false;
+ if ((error = export_verify(handle, handle->root))) goto failed;
+ if (!path || !strcmp(path, EXPORT_MARKER) ||
+ napi_is_buffer(env, argv[2], &buffer) != napi_ok || !buffer ||
+ napi_get_buffer_info(env, argv[2], &data, &length) != napi_ok) { error = export_invalid(); goto failed; }
+ char *leaf = NULL;
+ parent = export_walk(handle->root, path, &leaf, &error);
+ if (!parent) goto failed;
+ temporary = export_create(parent, handle->temporary, &error);
+ if (temporary == INVALID_LOCK_HANDLE) goto failed;
+ if ((error = export_write(temporary, data, length))) goto failed;
+ if ((error = export_verify(handle, parent))) goto failed;
+ if ((error = export_publish(parent, handle->temporary, leaf, temporary))) goto failed;
+ published = true;
+#ifndef _WIN32
+ if ((error = export_remove_temp(parent, handle->temporary, temporary))) goto failed;
+#endif
+ if ((error = export_flush_dir(parent))) goto failed;
+failed:
+ if (temporary != INVALID_LOCK_HANDLE) {
+ if (!published) {
+ unsigned long remove_error = export_remove_temp(parent, handle->temporary, temporary);
+ if (!error) error = remove_error;
+ }
+ unsigned long close_error = export_close_file(temporary);
+ if (!error) error = close_error;
+ }
+ unsigned long close_error = export_close_dirs(parent, handle->root);
+ if (!error) error = close_error;
+ free(path);
+ if (error) { handle->failed = true; return export_fail(env, "publish", error); }
+ return export_undefined(env);
+}
+
+static void export_uncomplete(export_handle *handle) {
+#ifdef _WIN32
+ LARGE_INTEGER offset;
+ offset.QuadPart = sizeof(EXPORT_INCOMPLETE) - 1;
+ if (SetFilePointerEx(handle->marker, offset, NULL, FILE_BEGIN)) SetEndOfFile(handle->marker);
+#else
+ ftruncate(handle->marker, sizeof(EXPORT_INCOMPLETE) - 1);
+ lseek(handle->marker, sizeof(EXPORT_INCOMPLETE) - 1, SEEK_SET);
+#endif
+ export_flush(handle->marker);
+}
+
+static napi_value complete_export(napi_env env, napi_callback_info info) {
+ napi_value argv[1];
+ export_handle *handle = export_get(env, info, 1, argv);
+ if (!handle) return NULL;
+ if (!handle->root || handle->failed || handle->completed) return export_fail(env, "inactive handle", 0);
+ unsigned long error = export_verify(handle, handle->root);
+ if (!error) error = export_flush_dir(handle->root);
+ if (error) {
+ handle->failed = true;
+ return export_fail(env, "complete", error);
+ }
+ error = export_write(handle->marker, "COMPLETE\n", 9);
+ if (error) {
+ handle->failed = true;
+ export_uncomplete(handle);
+ return export_fail(env, "complete", error);
+ }
+ handle->completed = true;
+ return export_undefined(env);
+}
+
+static napi_value close_export(napi_env env, napi_callback_info info) {
+ napi_value argv[1];
+ export_handle *handle = export_get(env, info, 1, argv);
+ if (!handle) return NULL;
+ unsigned long error = export_close(handle);
+ if (error) return export_fail(env, "close", error);
+ return export_undefined(env);
+}
+
+#endif
diff --git a/native/locks/locks.c b/native/locks/locks.c
index 6ab4c6665f..e85f13da45 100644
--- a/native/locks/locks.c
+++ b/native/locks/locks.c
@@ -296,6 +296,8 @@ static napi_value close_lock(napi_env env, napi_callback_info info) {
return result;
}
+#include "export-publication.h"
+
NAPI_MODULE_INIT() {
#ifdef _WIN32
/* Missing exports reject registration before any Node-API call. */
@@ -307,10 +309,20 @@ NAPI_MODULE_INIT() {
if (napi_add_env_cleanup_hook(env, cleanup, state) != napi_ok) {
free(state); return fail(env, "register cleanup", 0);
}
+ export_state *publisher = calloc(1, sizeof(*publisher));
+ if (!publisher) return fail(env, "allocate export registry", 0);
+ publisher->references = 1;
+ if (napi_add_env_cleanup_hook(env, export_cleanup, publisher) != napi_ok) {
+ free(publisher); return fail(env, "register export cleanup", 0);
+ }
const napi_property_descriptor properties[] = {
{"openLock", NULL, open_lock, NULL, NULL, NULL, napi_default, state},
{"tryLock", NULL, try_lock, NULL, NULL, NULL, napi_default, state},
{"close", NULL, close_lock, NULL, NULL, NULL, napi_default, state},
+ {"beginExport", NULL, begin_export, NULL, NULL, NULL, napi_default, publisher},
+ {"publishExportFile", NULL, publish_export_file, NULL, NULL, NULL, napi_default, publisher},
+ {"completeExport", NULL, complete_export, NULL, NULL, NULL, napi_default, publisher},
+ {"closeExport", NULL, close_export, NULL, NULL, NULL, napi_default, publisher},
#ifdef _WIN32
{"openIpcMutex", NULL, open_ipc_mutex, NULL, NULL, NULL, napi_default, state},
{"removeWindowsUnixSocket", NULL, remove_windows_unix_socket, NULL, NULL, NULL, napi_default, state},
diff --git a/native/locks/manifest.json b/native/locks/manifest.json
index ee5c16a589..2bee588ec1 100644
--- a/native/locks/manifest.json
+++ b/native/locks/manifest.json
@@ -2,39 +2,39 @@
"version": 1,
"napi": 3,
"zig": "0.14.1",
- "input_sha256": "4759bdd927c0c0fa29c2d5af30e42972a183f9be006d595144d73b6ca1111636",
+ "input_sha256": "93c31a185cca8bfdf8a58fbb79d81bafcc8c377b4a0625eb39571c68115dde84",
"artifacts": {
"linux-x64-glibc": {
- "sha256": "1a8b15c6be3f0ada433a5c1e6558b913641fde7f6daf72b9c37f54e4bfebb3fa",
- "bytes": 7928
+ "sha256": "8370d9d1b62cdd7ee518035ef558496096c2acc045e10c5c582692a3004d4d49",
+ "bytes": 16464
},
"linux-arm64-glibc": {
- "sha256": "2a4096d1341d965cdc1832a295b3d16cf18a543b29e694b29d3d28cc93229919",
- "bytes": 7976
+ "sha256": "ca8a2b9efedbc0568fc8c017e52ca561d68dee97c45b679405bedd4f09431784",
+ "bytes": 16544
},
"linux-x64-musl": {
- "sha256": "75c63f94f7a252379a3151811c0ec5d0178b65059b134ed29b92fa066b8c1814",
- "bytes": 7536
+ "sha256": "704c847c4f9d6713997ebdfea2f7d00ab2accb58a5f4cc57b8ca83bebd1a35c7",
+ "bytes": 15976
},
"linux-arm64-musl": {
- "sha256": "9edaaa72d55f3cfcd9c454761b23e0fbefd9cd78849bf851f0ae18c74739d475",
- "bytes": 7600
+ "sha256": "c2be13cfb32fb44b5415e541452988406e60473c051b2266add664ca85fa0979",
+ "bytes": 16120
},
"darwin-x64": {
- "sha256": "ab11b4c3e9bf3624b204267e0eb9b6a046cdf0fa1f800258a721960abce6feae",
- "bytes": 22493
+ "sha256": "3d4fff3b91a6c1d80f0efd39bcb0f8bca5df369463510cf9c8f0645aeafbfaf6",
+ "bytes": 27910
},
"darwin-arm64": {
- "sha256": "015249a269deb6670619ae73b959e1d0e3bf96b131c3acb0be86df7902b0c219",
- "bytes": 52288
+ "sha256": "1caa3889223ef912a190fea43891d402b7c75d134415bb1ba8de0a9b791e0833",
+ "bytes": 70512
},
"win32-x64": {
- "sha256": "0b494ec94896219a3b142b6f216bf12c9ee94d27fa7e7399bcdab707ca60212e",
- "bytes": 28160
+ "sha256": "04e8bea13fe224cb12d6f71fefc67390be1777eb64cd5d129daf54b2872d53ff",
+ "bytes": 35328
},
"win32-arm64": {
- "sha256": "e8315b4453dce3df775eeb76c73e8895c273390e64b16a2c255e10790fa75dd7",
- "bytes": 24576
+ "sha256": "1ec55b4859643655882a7f486af04d5d49391605d5d96343b432e9bff08b855b",
+ "bytes": 31744
}
}
}
diff --git a/native/locks/prebuilds/darwin-arm64.node b/native/locks/prebuilds/darwin-arm64.node
index 536ece324a..6267bcad85 100755
Binary files a/native/locks/prebuilds/darwin-arm64.node and b/native/locks/prebuilds/darwin-arm64.node differ
diff --git a/native/locks/prebuilds/darwin-x64.node b/native/locks/prebuilds/darwin-x64.node
index bf33811ded..fca6976d54 100755
Binary files a/native/locks/prebuilds/darwin-x64.node and b/native/locks/prebuilds/darwin-x64.node differ
diff --git a/native/locks/prebuilds/linux-arm64-glibc.node b/native/locks/prebuilds/linux-arm64-glibc.node
index df546009ca..a6a49dffe0 100755
Binary files a/native/locks/prebuilds/linux-arm64-glibc.node and b/native/locks/prebuilds/linux-arm64-glibc.node differ
diff --git a/native/locks/prebuilds/linux-arm64-musl.node b/native/locks/prebuilds/linux-arm64-musl.node
index 53747d5364..4a18b23aa9 100755
Binary files a/native/locks/prebuilds/linux-arm64-musl.node and b/native/locks/prebuilds/linux-arm64-musl.node differ
diff --git a/native/locks/prebuilds/linux-x64-glibc.node b/native/locks/prebuilds/linux-x64-glibc.node
index ccbb0a10f2..74dadd6436 100755
Binary files a/native/locks/prebuilds/linux-x64-glibc.node and b/native/locks/prebuilds/linux-x64-glibc.node differ
diff --git a/native/locks/prebuilds/linux-x64-musl.node b/native/locks/prebuilds/linux-x64-musl.node
index 82baadfeb9..159a9bb2de 100755
Binary files a/native/locks/prebuilds/linux-x64-musl.node and b/native/locks/prebuilds/linux-x64-musl.node differ
diff --git a/native/locks/prebuilds/win32-arm64.node b/native/locks/prebuilds/win32-arm64.node
index 88180e8c6a..6766c155c7 100755
Binary files a/native/locks/prebuilds/win32-arm64.node and b/native/locks/prebuilds/win32-arm64.node differ
diff --git a/native/locks/prebuilds/win32-x64.node b/native/locks/prebuilds/win32-x64.node
index 082835e383..a21a9fa6c0 100755
Binary files a/native/locks/prebuilds/win32-x64.node and b/native/locks/prebuilds/win32-x64.node differ
diff --git a/native/locks/windows-napi.h b/native/locks/windows-napi.h
index bab614764e..61c180cf10 100644
--- a/native/locks/windows-napi.h
+++ b/native/locks/windows-napi.h
@@ -14,6 +14,8 @@
X(napi_throw_type_error) \
X(napi_throw_error) \
X(napi_get_value_string_utf8) \
+ X(napi_is_buffer) \
+ X(napi_get_buffer_info) \
X(napi_create_object) \
X(napi_wrap) \
X(napi_get_boolean) \
@@ -57,6 +59,8 @@ static bool gbrain_initialize_napi(void) {
#define napi_throw_type_error gbrain_napi.napi_throw_type_error
#define napi_throw_error gbrain_napi.napi_throw_error
#define napi_get_value_string_utf8 gbrain_napi.napi_get_value_string_utf8
+#define napi_is_buffer gbrain_napi.napi_is_buffer
+#define napi_get_buffer_info gbrain_napi.napi_get_buffer_info
#define napi_create_object gbrain_napi.napi_create_object
#define napi_wrap gbrain_napi.napi_wrap
#define napi_get_boolean gbrain_napi.napi_get_boolean
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 34e406ff09..834d2c44c6 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.59.8.0",
+ "version": "0.59.10.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 25301ea141..d0b5c23938 100644
--- a/package.json
+++ b/package.json
@@ -190,7 +190,7 @@
"bun": ">=1.3.11"
},
"license": "MIT",
- "version": "0.59.8.0",
+ "version": "0.59.10.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 3fc16d49be..5241cddb34 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.59.8.0",
+ "version": "0.59.10.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 — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index d002da5446..904ec6d231 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.59.8.0",
+ "version": "0.59.10.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 — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 31241c92a7..67021813fe 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.59.8.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.59.10.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 512961c8fe..d62a794632 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.59.8.0",
+ "version": "0.59.10.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 — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 7990534760..eb0436b1c7 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.59.8.0",
+ "version": "0.59.10.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 — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 57c8da6b84..27f05f8c4a 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.59.8.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.59.10.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 56749efaf5..59bf10424b 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.59.8.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.59.10.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh
index a58bb3f39f..1294fddc72 100755
--- a/scripts/ci-local.sh
+++ b/scripts/ci-local.sh
@@ -343,10 +343,11 @@ if ! command -v git >/dev/null 2>&1 || \
! command -v python3 >/dev/null 2>&1 || \
! command -v ps >/dev/null 2>&1 || \
! command -v psql >/dev/null 2>&1 || \
+ ! command -v cc >/dev/null 2>&1 || \
! command -v jq >/dev/null 2>&1; then
echo "[runner] Installing test prerequisites (debian apt)..."
apt-get update -qq >/dev/null
- apt-get install -y -qq git ca-certificates python3 procps postgresql-client jq >/dev/null
+ apt-get install -y -qq git ca-certificates python3 procps postgresql-client jq build-essential >/dev/null
fi
# Container runs as root (uid 0) against a host-uid bind-mount; mark repo +
# any worktree gitdir as safe so `git status` etc. don't refuse.
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 758b7f0249..af3271d83b 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -14,6 +14,15 @@
// - everything else is literal
// No brace expansion, no ?, no [ ].
+const MIGRATION_WAVE_TESTS = [
+ "test/e2e/migration-wave-budget-crash.test.ts",
+ "test/e2e/migration-wave-healing-fence.test.ts",
+ "test/e2e/migration-wave-intermediate-retrieval.test.ts",
+ "test/e2e/migration-wave-phase-leases.test.ts",
+ "test/e2e/migration-wave-prepared-withdrawal.test.ts",
+ "test/e2e/migration-wave-provider-outcomes.test.ts",
+];
+
export const E2E_TEST_MAP: Record<string, string[]> = {
// SkillOpt orchestrator, outcome/resume, models plan + strict mode, spend ledger.
"src/core/skillopt/**": [
@@ -31,6 +40,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/skillopt-models-strict.serial.test.ts",
"test/e2e/skillopt-models-used.serial.test.ts",
],
+ "src/commands/export.ts": ["test/e2e/export-snapshot-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts"],
+ "src/core/export-*.ts": ["test/e2e/export-snapshot-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts"],
"src/core/company-brain/receipts.ts": ["test/e2e/company-brain-receipts.test.ts"],
"src/core/company-brain/receipt-schema.ts": ["test/e2e/company-brain-receipts.test.ts"],
"src/core/minions/errors.ts": ["test/e2e/subagent-gateway-path.test.ts", "test/e2e/delegated-http-worker.test.ts", "test/e2e/subagent-crash-replay-multi-provider.test.ts"],
@@ -39,7 +50,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/mcp/skill-resources.ts": ["test/e2e/shared-skills-transports.test.ts"],
"src/core/scope.ts": ["test/e2e/client-grants.test.ts", "test/e2e/shared-skills-transports.test.ts"],
"src/core/grants/**": ["test/e2e/client-grants.test.ts", "test/e2e/harness-access.test.ts", "test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/delegated-http-worker.test.ts"],
- "src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts"],
+ "src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/withdrawal-bounded-safety-postgres.test.ts", "test/e2e/withdrawal-crash-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts"],
"src/commands/mcp*.ts": ["test/e2e/harness-access.test.ts"],
// OpenRouter subagent-loop families: the family allowlist + recipe feed the
// key-gated live DeepSeek replay (self-skips without OPENROUTER_API_KEY).
@@ -83,7 +94,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/search-exclude.test.ts",
"test/e2e/search-swamp.test.ts",
],
- "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts"],
+ "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts", ...MIGRATION_WAVE_TESTS],
"src/core/code-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],
"src/core/markdown-chunks.ts": ["test/e2e/projection-recovery-parity.test.ts"],
// Tree-sitter chunkers feed code-indexing E2E.
@@ -143,13 +154,16 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/worker-abort-recovery.test.ts",
],
"src/commands/embed.ts": [
+ ...MIGRATION_WAVE_TESTS,
"test/e2e/multi-source-bug-class.test.ts",
// #3391: the NULL-signature stale predicates differ per engine.
"test/e2e/migrate-embeddings-postgres.test.ts",
],
// #3390: runSchemaTransition's DDL path + the stale predicates behave
// differently on real pgvector than on PGLite.
- "src/core/embedding-migration.ts": ["test/e2e/migrate-embeddings-postgres.test.ts"],
+ "src/core/embedding-migration*.ts": ["test/e2e/migrate-embeddings-postgres.test.ts", "test/e2e/embedding-recovery-parity.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts", ...MIGRATION_WAVE_TESTS],
+ "src/core/embedding-readiness.ts": ["test/e2e/embedding-recovery-parity.test.ts"],
+ "src/core/facts/embedding-identity.ts": ["test/e2e/embedding-recovery-parity.test.ts", "test/e2e/fact-embedding-backfill-parity.test.ts"],
"src/core/stored-embedding-identity.ts": ["test/e2e/unsupported-embedding-identity-postgres.test.ts"],
"src/commands/extract.ts": ["test/e2e/multi-source-bug-class.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/extract-timeline-attendance-postgres.test.ts"],
"src/commands/extract-attendance-repair.ts": ["test/e2e/attendance-repair-postgres.test.ts"],
@@ -208,6 +222,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/managed-maintenance.test.ts",
"test/e2e/managed-synthesis-postprocess.test.ts",
"test/e2e/persistence-embedding-effects.test.ts",
+ "test/e2e/withdrawal-bounded-safety-postgres.test.ts",
+ "test/e2e/withdrawal-crash-postgres.test.ts",
+ "test/e2e/memory-safety-wave-postgres.test.ts",
"test/e2e/fact-backfill-resident.test.ts",
"test/e2e/reconcile-crash.test.ts",
"test/e2e/reconcile-crash-unactivated.test.ts",
@@ -223,6 +240,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/pool-budget.ts": ["test/e2e/persistence-runtime-matrix.test.ts"],
"src/core/connection-manager.ts": ["test/e2e/persistence-runtime-matrix.test.ts", "test/e2e/pgbouncer-teardown.test.ts"],
"src/core/postgres-engine.ts": [
+ ...MIGRATION_WAVE_TESTS,
+ "test/e2e/legacy-vector-compatibility-postgres.test.ts",
"test/e2e/postgres-driver-install.test.ts",
"test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/fixture-reset-postgres.test.ts",
@@ -245,6 +264,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
],
// PGLite bootstrap path + parity guard.
"src/core/pglite-engine.ts": [
+ ...MIGRATION_WAVE_TESTS,
+ "test/e2e/legacy-vector-compatibility-postgres.test.ts",
"test/e2e/unsupported-embedding-identity-postgres.test.ts",
"test/e2e/persistence-chaos.test.ts",
"test/e2e/chunk-canonical-text-privacy.test.ts",
@@ -310,6 +331,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/schema.sql": ["test/e2e/schema-drift.test.ts"],
"src/core/pglite-schema.ts": ["test/e2e/schema-drift.test.ts"],
"src/core/migrate.ts": [
+ "test/e2e/migration-vector-replay-postgres.test.ts",
"test/e2e/schema-drift.test.ts",
"test/e2e/migrate-chain.test.ts",
"test/e2e/link-source-check-repair-postgres.test.ts",
@@ -319,8 +341,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Postgres — lock semantics PGLite can't observe. Keyed on the repair module
// and on migrate.ts (the definition it reproduces).
"src/core/link-source-check-repair.ts": ["test/e2e/link-source-check-repair-postgres.test.ts"],
+ "src/core/vector-index.ts": ["test/e2e/migration-vector-replay-postgres.test.ts"],
// MCP stdio + HTTP transports share dispatch.
- "src/mcp/**": ["test/e2e/mcp.test.ts", "test/e2e/http-transport.test.ts"],
+ "src/mcp/**": ["test/e2e/mcp.test.ts", "test/e2e/http-transport.test.ts", "test/e2e/mcp-search-transport-matrix.test.ts"],
// G6: the --surface verbs CEILING journey over a real `serve --http` boot
// (hermetic PGLite): 7-verb tools/list for full-preset + bare clients,
// fail-closed dispatch on hidden ops, the narrow-only
@@ -410,10 +433,14 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/cycle/extract-facts.ts": ["test/e2e/fact-vector-repair-parity.test.ts", "test/e2e/facts-fence-reconcile-postgres.test.ts"],
"src/core/cycle/phases/consolidate.ts": ["test/e2e/managed-maintenance.test.ts", "test/e2e/cycle.test.ts"],
"src/core/ops/facts.ts": ["test/e2e/managed-facts-backstop.test.ts"],
- "src/core/facts/backstop.ts": ["test/e2e/managed-facts-backstop.test.ts", "test/e2e/facts-worker-config.test.ts", "test/e2e/managed-facts-embedding.test.ts", "test/e2e/managed-facts-compaction.test.ts"],
+ "src/core/facts/backstop.ts": ["test/e2e/managed-facts-backstop.test.ts", "test/e2e/facts-worker-config.test.ts", "test/e2e/managed-facts-embedding.test.ts", "test/e2e/managed-facts-compaction.test.ts", "test/e2e/legacy-fact-extraction-dedup-postgres.test.ts"],
"src/core/facts/extract.ts": ["test/e2e/managed-facts-embedding.test.ts"],
"src/core/github-source.ts": ["test/e2e/managed-connector-routing.test.ts", "test/e2e/managed-connector-retry.test.ts", "test/e2e/managed-connector-fencing.test.ts", "test/e2e/managed-connector-recovery.test.ts"],
- "src/core/google/google-source.ts": ["test/e2e/managed-connector-routing.test.ts", "test/e2e/managed-connector-retry.test.ts", "test/e2e/managed-connector-fencing.test.ts", "test/e2e/managed-connector-recovery.test.ts"],
+ "src/core/google/google-source.ts": ["test/e2e/managed-connector-routing.test.ts", "test/e2e/managed-connector-retry.test.ts", "test/e2e/managed-connector-fencing.test.ts", "test/e2e/managed-connector-recovery.test.ts", "test/e2e/google-attachments-postgres.test.ts"],
+ "src/core/google/attachment-receipts.ts": ["test/e2e/google-attachments-postgres.test.ts"],
+ "src/core/google/attachment-backfill.ts": ["test/e2e/google-attachments-postgres.test.ts"],
+ "src/core/persistence/connector-google-receipts.ts": ["test/e2e/google-attachments-postgres.test.ts"],
+ "src/commands/google-attachments.ts": ["test/e2e/google-attachments-postgres.test.ts"],
"src/core/backup/**": ["test/e2e/backup-coverage-parity.test.ts"],
"src/commands/backup.ts": ["test/e2e/backup-coverage-parity.test.ts"],
"src/commands/doctor/checks/backup-coverage.ts": ["test/e2e/backup-coverage-parity.test.ts"],
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 48f7bc7995..b383aa2ec3 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -127,6 +127,7 @@ function facadeExpansion(p: string): string[] {
return out;
};
if (rel === 'src/core/operations.ts') return collect(join(ROOT, 'src/core/ops'));
+ if (rel === 'src/commands/migrate-embeddings.ts') return [join(ROOT, 'src/core/embedding-migration-cli.ts')];
if (rel === 'src/commands/mcp.ts') return [
join(ROOT, 'src/commands/mcp-admin.ts'),
join(ROOT, 'src/commands/mcp-admin-http.ts'),
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1492bf3f96..0058c9daa3 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,26 +3,26 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 4119 ratchet +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; typed readiness, configuration-blocked lifecycle and bounded release
+src/cli.ts 4124 ratchet +2 export engine-free detailed help dispatch; +48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; +4 strict pre-engine rejection of unsupported brain-wide migration narrowing flags; merged upstream: 48 fix wave: get_versions --json + honest ellipsis (#4692), boolean-flag literal true/false consume (#4602); grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help section; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: CLI combines hosted access and explicit legacy queue review; lowered to 4077: GHSA wave v0.50.5.0 moved the #3688 guardrails block into core/cli-preflight.ts (-10); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; #5252 wave: partial-retrieval notices and resident code reindex delegation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared skills: parse typed object/array operation flags before resident-owner delegation; merged reliability/shared-skills source integration Explicit-policy thin recall routing before local engine connection; actual CLI subprocess regression coverage. Reject explicit thin recall brain selection before dispatch.; +10 A2 preview-bound attendance repair dispatch and help; integrated upstream provider retirement with thin recall and gated repair dispatch; typed readiness, configuration-blocked lifecycle and bounded release
src/commands/autopilot.ts 2725 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring; +20 #4728 wrapper exec guard (baked CLI path gone -> PATH fallback / --install hint); +5 #4952 (refs #4399): syncEnabled=false skip in the freshness dispatch loop; typed readiness, configuration-blocked lifecycle and bounded release; +3 guard transaction callbacks and roll back on configuration block
src/commands/doctor.ts 4593 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift); +8 memorable_relay_health wiring (check itself is a peel: doctor/checks/integrations-memorable.ts); +9 ambient-writeback WP6: memory_writeback check registration (logic lives in doctor/checks/memory-writeback.ts); +14 default_source_local_path registration (#4739 — check body peeled to doctor/checks/default-source-path.ts); +9 atom_provenance_drift registration (#4566 — check body lives in doctor/checks/extraction-sync.ts); master: | merged v0.48.1.0 true-up; #5252 wave: scoped projection readiness registration; shared content: register the separately scoped canonical publication/recovery check; merged reliability/shared-skills source integration
-src/commands/embed.ts 2144 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring
+src/commands/embed.ts 2169 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures
src/commands/extract-conversation-facts.ts 2125 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364)
src/commands/extract.ts 2571 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain
src/commands/jobs.ts 3260 ratchet grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; queued import failures remain failures; master integration: grown v0.46.26.0 megawave (#4098 #2308) + master v0.46.26.0 worker startup recovery + stats gating; +typed provider-failure logging on the facts-absorb catch (#4308); +chat-connectors wiring (master merge); +16 v0.47 gmail-loops: loops_extract handler + gateway-refresh entry; +8 refs #4599: embed + embed-catch-up handlers fail the job on a stall_timeout result (assertEmbedNotStalled); #5105: two-line delegate validates revision and durable authority before fact backstop execution; upstream integration: preserve independently reviewed master additions with branch facade extraction; +13 v0.50.5.0 security merge (upstream delta; coordinated facade retained); merged reliability/shared-skills source integration; +1 #5584: skillopt job reflect_max_tokens (validated + clamped via skillopt/output-cap.ts); lowered #5585: skillopt handler body peeled to skillopt/job.ts (execution-time model re-resolution + strict re-check); typed readiness, configuration-blocked lifecycle and bounded release (issue #5560 merge)
src/commands/serve-http.ts 3098 ratchet registration and grant routes extracted; owner authentication and configured discovery remain in the HTTP facade; one shared bootstrap-token-shape import from serve-service; merged scoped shared-skill resources and named capability checks
-src/core/ai/gateway.ts 4439 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed
+src/core/ai/gateway.ts 4441 ratchet +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings
src/commands/sync.ts 5995 ratchet +1 #4786/#3068 pre-landing: pullFailed early return reports the sweep count (comment line); +1 #4786 x #2139 pre-landing: both embed-backfill submit gates require syncProducedEmbeddableContent (import line); re-summed after merging master v0.50.0.0 with the wave (include_hidden, sweep count, cost-gate envelope); +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; security: durable queued authority and confined filesystem dispatch; drained cancellation and lease-safe partial results; master integration: +1 wave review: sync trigger --json emits {job_id} JSON; grown v0.46.26.0 megawave: image sync, ingest-log gating, dry-run purity, checkpoint honesty (#2683 #4342 #3875) + 3 nosemgrep dataflow annotations (path-traversal audit); +#2683 residual: status-error failure recording at both import sites; +143 wave G #3974: working-tree drift surfacing + opt-in --working-tree import; grown wave-g (#4412 #4543): break-lock ambient source resolution + named failing files; grown db-availability loop: GBRAIN_DB_ACCESS marker on checkpoint-dead aborts; fix cycle: marker via shared DB_ACCESS_MARKER_PREFIX + shouldEmitDbAccessMarker; wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +master-merge true-up; +25 post-sync backup-coverage stale-only refresh (monthly backup check); wave-k: #3570 rename-sentinel operator-exit safety (cross-source-scoped resolve, tracked-file liveness index, orphaned-sentinel self-heal) + #4027 --include-hidden dot-prune waiver (threaded into the hoisted syncOpts); +6 #2683 residual: the rename lane's errored-skip branch now sets importErrored too, closing the gap left when status-error handling was added only for the throw and status='error' cases; +1: #4412 refinement — explicit --source stays resolver-free (deleted-source locks breakable); +10 v0.47 gmail-loops: google source-kind dispatch branch; +48 #4667 adoption: persisted sync.exclude config union hoisted above the performFullSync early returns; +22 #4587: all 7 delete lanes swapped to softDeletePages (72h recovery window), decompose comments + summary wording; +16 #4583: seed_default write refusal on bulk-non-default brains (assessDefaultWriteGuard call site + escape-hatch comment); composition true-up (fix-wave multi-train); +33 #4597: trackedSlugIndex.anchorOnlyPaths (slug -> anchor paths that alone proved it) + the self-referential from-path rule in slugLiveness so a fallback rename's own pre-rename duplicate converges under incremental sync; +12 #4888: runSync wraps runSyncInner in withHumanLogsToStderr under --json (stdout = JSON lines only) + help text; wave composition: #4903 stored-strategy honor + #4597 fallback-rename duplicate convergence + #4888 --json stdout purity summed; #5252 wave: post-batch planner statistics refresh; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; merged reliability/shared-skills source integration; +1 cancellation guard before company dispatch
src/core/cycle.ts 3207 ratchet grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false
src/core/cycle/synthesize.ts 3218 ratchet merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates
src/core/cycle/extract-atoms.ts 1752 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration
-src/core/engine.ts 2657 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes
-src/core/import-file.ts 2205 ratchet grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication
+src/core/engine.ts 2660 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract
+src/core/import-file.ts 2207 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication
src/core/migrate.ts 722 region-exempt append-only MIGRATIONS array grows freely; runner logic is ratcheted — grown v0.46.26.0: repair-handler hooks (#3957 pages-upsert-arbiter); wave-k v142 takes-embedding resize is in-region (renumbered from v141; master consumed v141 for #4482); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: projection migration helper; #5105: lease schema helper; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +1 import for focused topology migration module; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: static projection statistics import; DDL remains region-exempt; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion
src/core/operations.ts 329 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base
-src/core/pglite-engine.ts 6120 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation
+src/core/pglite-engine.ts 6127 ratchet +6 #4881: ontology provenance-page visibility gate (getOntology/findOntologyConflicts); grown v0.46.26.0 megawave parity twins + master v0.46.26.0 private-queue columns; +#3754 traverseGraph soft-delete filters; grown wave-g (#4524 #4527): canonical islanded orphans + timestamp-preserving migrate; wave-k: +1 semantic takes retrieval delegate (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +7 getAllConfig bulk read (#3980); +22: pre-close WAL CHECKPOINT in disconnect (#3893); +10: #4109 atomic link/timeline mutation + typed per-endpoint miss (parity); +1: getBacklinkCounts page-id keying comment (#4380); +14: dream-verdict TTL expiry predicate + sweep (#4069); +7 test-gap-wave merge true-up; +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +51: #4592 source-scoped getStats/getHealth (bound $1 scope, both-endpoint link rule); +5 file-bytes snapshot hash (coverage-immune — CI shards were silently cold-initting); +7 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); cold-initting); +11: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +2: #4681 listPages projects updated_at_iso (microsecond keyset cursor); master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: grant and authority schema bootstrap parity; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained); +7 ceiling: bounded in-memory create retry with attached-database exclusion and second-failure diagnostics; #5252 bounded candidate recovery and statistics snapshot dependency; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared-skills integration on company-ingestion base; shared skills: include explicit access DDL in snapshot invalidation; archived eligibility: source-locked drift and raw signature mutations
src/core/postgres-engine.ts 5577 ratchet +6 #4881: ontology provenance-page visibility gate (parity twin); lowered wave-g: #4477 bootstrap peel to src/core/postgres-engine/ modules (ratchet holds the win); +2 on wave-g-prs merge true-up; wave-k: +2 semantic takes retrieval (#3776), +5 NUL-sanitize shared chunk_text local (#3998), +11 getAllConfig bulk read (#3980); +13: #4109 atomic FOR KEY SHARE link/timeline mutation + typed per-endpoint miss; +2: getBacklinkCounts page-id keying comment (#4380); +12: dream-verdict TTL expiry predicate + sweep (#4069); +23: softDeletePages batch soft-delete primitive (#4587, parity twin); +61: #4592 source-scoped getStats/getHealth (scope predicate, both-endpoint link rule); +11 2026-09 fix wave (#3617 follow-up): OR-fallback rows tagged keyword_relaxed in searchKeyword + title arm (fusion demotion reads it); rule); +12: #4280 orphan/health served-memory denominators (quarantine + leaf-type metadata, parity twin); composition true-up (fix-wave multi-train); +14: traversePathsDetailed row cap (LIMIT + truncated probe, parity twin); +7: resolveSlugWithAliasDetailed (owning source_id, parity twin) | merged v0.48.1.0 true-up; corrective release: shared batched enrichment peel; concrete content and Chronicle authorization; +3: #4681 listPages projects updated_at_iso (microsecond keyset cursor, parity twin); #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop barrier and direct transaction route; upstream integration: preserve independently reviewed master additions with branch facade extraction; +1 v0.50.5.0 security merge (upstream delta; coordinated facade retained)
-src/core/search/hybrid.ts 3213 ratchet grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed
+src/core/search/hybrid.ts 3215 ratchet +2: preserve local query-deadline classification through gateway error wrapping; grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; grown db-availability loop: all-lexical-arms-dead access-error rethrow (a dead DB must never return an empty success) — refined to both-arms-FAILED (a succeeded-but-empty arm proves the DB is alive); grown v0.46.26.0 megawave: CRAG escalation seam, degradation visibility, excludePrivate knobs-fold v23 (#1663 #3873 #4352); grown #4356: semantic-cache-hit slice honors resolved mode searchLimit (double-resolution caveat); grown #4414: offset!==0 cache-skip widening + knobs-hash v24; grown #4487: chunkless rows join the cosine blend (no raw-score head start); grown wave-g (#4480 #4415): shared salience/recency resolution + pattern-aware cache keying; +2: backlink-boost counts page-id keying doc (#4380); +59 2026-09 adversarial batch 2: both-mode text-only demotion gate (textVectorArmNonEmpty) + relaxed_dropped meta + keyword_relaxed_carried degraded stamp + intent-skew caveat docs; +35 #3617 follow-up: relaxed-row fusion demotion (vectorArmNonEmpty gate + keywordFusionList/titleFusionList) with the LongMemEval 51.3%-vs-93.8% receipt comment; +24 2026-08 eval fix wave (E5b/D8): adaptive-return knobs-hash v27 fold (resolved gate + intent class threaded to the cache key), adaptive-on skipCache removal, dedupOpts cache-skip honesty, explicit-maxPerPage min() precedence under walk widening; (#4380); +20 wave #4256: compiledTruthBoost helper — synthetic chunkless title rows (chunk_id 0 + empty chunk_text) never gain the 2x compiled-truth boost (#3695); composition true-up (fix-wave multi-train) | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: read-policy propagation and semantic result-cache containment; ranker wave v0.48.4.0: role-tagged fusion arms, relational rerank pin, metadata boost gate, per-call knob seams, onRerankPool hook (+150) merged over master's read-policy plumbing (+31); +11 #4359 (#4972): thread the loaded search-mode config snapshot from hybridSearchCached into the inner hybridSearch call (INTERNAL _searchModeInput opt) so both resolve from the same one DB-plane config read instead of two independent ones — closes the cache-key/result desync window and removes the second config-table round trip on every hybridSearchCached call; #5252 wave: inclusive date bounds and public vector incompleteness; shared date-bounds peel retains exports; merged company ingestion/schema routing changes; retired provider integration removed
src/core/types.ts 2072 ratchet +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed
src/core/minions/queue.ts 2513 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release
src/commands/init.ts 1932 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init
@@ -32,7 +32,7 @@ src/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 150
src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry
src/commands/sources.ts 1993 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts
src/core/link-extraction.ts 2082 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges
-src/core/embedding-migration.ts 1435 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed
+src/core/embedding-migration.ts 1513 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation
src/core/github-source.ts 1576 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper
src/commands/hook.ts 1881 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking
src/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES
diff --git a/scripts/native/build.ts b/scripts/native/build.ts
index 38d6fa6a5f..5fc0f3ab40 100644
--- a/scripts/native/build.ts
+++ b/scripts/native/build.ts
@@ -20,6 +20,7 @@ const repo = resolve(import.meta.dir, '../..');
const nativeDir = join(repo, 'native/locks');
export const buildInputs = [
'native/locks/locks.c', 'native/locks/darwin-abi.h', 'native/locks/abi-check.c',
+ 'native/locks/export-publication.h',
'native/locks/windows-napi.h', 'native/locks/windows-ipc.h', 'native/locks/vendor/node-v22.15.0/node_api.h',
'native/locks/vendor/node-v22.15.0/node_api_types.h',
'native/locks/vendor/node-v22.15.0/js_native_api.h',
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index da4a37b4d7..41be1917a6 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -118,7 +118,7 @@ test/doctor-supervisor-singleton-pidfile.test.ts doctor supervisor_singleton —
test/doctor-volunteer-channels.test.ts checkVolunteerChannels 9 doctor-source-helper,readFileSync
test/doctor-wedged-queue.test.ts issue #1801 fix #3 — remote queue_health state→status regression 1 doctor-source-helper
test/doctor.test.ts BUG 4 — in-progress sync via live lock, not stale freshness 8 doctor-source-helper
-test/doctor.test.ts doctor command 37 doctor-source-helper
+test/doctor.test.ts doctor command 38 doctor-source-helper
test/doctor.test.ts issue #972 — link_resolution_opportunity check 8 doctor-source-helper
test/doctor.test.ts stub_guard_24h check (v0.34.5) 5 doctor-source-helper
test/doctor.test.ts supervisor crash classifier wiring (v0.35.x) 4 bun-file,doctor-source-helper
@@ -151,6 +151,7 @@ test/eval-synthesize-concepts-routing.test.ts dispatch-layer source pins (routin
test/eval-synthesize-concepts-routing.test.ts subprocess smoke — end-to-end routing 1 readFileSync
test/eval-takes-bootstrap.test.ts corpus integrity 4 readFileSync
test/exit-classification.test.ts consumer wire-up — helper used by all 3 sites (no inline filters left) 5 doctor-source-helper,readFileSync
+test/export-publication.test.ts (file-level) 6 readFileSync
test/extract-atoms-drain-errors.test.ts runExtractAtomsDrainForSource forwards typed per-item failures (#4730) 1 readFileSync
test/extract-atoms-drain.test.ts extract-atoms-drain Minion handler retries on provider_failure (issue #3218) 2 readFileSync
test/extract-atoms-drain.test.ts protected-names register comment names the real trust mechanism 1 readFileSync
diff --git a/scripts/ubicloud/setup-ci-vm.sh b/scripts/ubicloud/setup-ci-vm.sh
index 276258972b..fc04a28e26 100755
--- a/scripts/ubicloud/setup-ci-vm.sh
+++ b/scripts/ubicloud/setup-ci-vm.sh
@@ -38,7 +38,7 @@ export DEBIAN_FRONTEND=noninteractive
(
sudo apt-get update -qq >/dev/null
sudo apt-get install -y -qq --no-install-recommends \
- docker.io git ca-certificates python3 procps postgresql-client jq nodejs >/dev/null
+ docker.io git ca-certificates python3 procps postgresql-client jq nodejs build-essential >/dev/null
) &
apt_pid=$!
diff --git a/skills/migrations/v0.46.3.0.md b/skills/migrations/v0.46.3.0.md
index cbd8940e0e..b5ed287034 100644
--- a/skills/migrations/v0.46.3.0.md
+++ b/skills/migrations/v0.46.3.0.md
@@ -28,8 +28,9 @@ instructions are preserved at Git revision
**No upgrade, warning or old pending action item authorizes this work.**
Migration can delete incompatible vectors and incur a full re-embedding bill.
-Keep a verified full backup and obtain explicit approval for the selected
-brain, target model, dimensions, reranker action and cost before proceeding.
+Keep a [verified full backup](../../docs/embedding-migrations.md#backup-and-isolated-restore)
+and obtain explicit approval for the selected brain, target model, dimensions,
+reranker action and a finite total USD cap before proceeding.
## 1. Inspect the intended brain without spending
@@ -80,16 +81,22 @@ before the migration. Do not stop services without the owner's approval.
The plan warns about concurrent jobs; migration locks are not permission to
ignore another writer.
-Only after approval, replace `--dry-run` with `--yes`:
+Only after approval, replace `--dry-run` with `--yes` and supply the
+operator-selected total cap. Replace `<approved-total-usd>` with that approved
+amount; never invent a cap from the estimate or a suggested command:
```bash
-gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 --yes
+gbrain migrate embeddings --to voyage:voyage-4 --dim 1024 \
+ --max-cost-usd <approved-total-usd> --yes
```
Without `--yes`, an interactive caller must confirm; a non-TTY caller exits
-2. A spending posture does not waive the migration's destructive-change
-consent gate. The live run probes the target before mutation. A failed probe
-does not authorize a fallback provider or a different model.
+2. `--yes` and a spending posture do not waive the required finite nonnegative
+cap. Batch size is not a spending bound. Admission reserves conservative
+per-attempt ceilings, not the preview's character-based estimate; unknown pricing
+or a missing input ceiling can refuse before dispatch. The live run probes the
+target before invalidation. A failed probe does not authorize a fallback provider
+or a different model, and its prior authorization debit can remain.
`--reranker auto` is the default companion action. Review it in the plan, or
explicitly choose `--reranker off`, `--reranker keep`, or a supported model
@@ -103,27 +110,33 @@ OpenAI has no reranker on its key, so do not silently enable a third provider.
gbrain migrate embeddings --status
```
-Check target widths, remaining chunk vectors, signature census, in-flight
-state and the recorded smoke-check result. A converged config value alone is
-not proof. Semantic retrieval is degraded for content not yet re-embedded.
+Check target widths, remaining chunks and eligible facts, projection blockers,
+signature census, in-flight state and the recorded smoke-check result. A converged
+config value alone is not proof. Semantic retrieval is degraded for content not
+yet re-embedded.
After approval for any provider calls, search for a known page as a separate
behavioral check; distinguish that check from the spend-free status output.
-Fact-vector repair is separate and consented. Inspect the pending census;
-follow [fact-vector repair](../../docs/embedding-migrations.md) rather than
-claiming every fact was backfilled by the primary migration.
+Migration repairs eligible active fact vectors, including missing, stale-model,
+stale-text and wrong-width vectors. It excludes expired, withdrawn, superseded
+and audit rows; a nonzero remaining count is not completion. For a separate
+source-scoped repair, preview first and follow
+[fact-vector repair](../../docs/embedding-migrations.md#repair-missing-fact-vectors-deliberately)
+with its own explicit approval and cap.
## Recovery and boundaries
-- Re-run the same approved target after a kill or partial failure. Status
- prints the exact resume command; chunks already in that space are retained.
+- Inspect status after a kill or partial failure, then resume the same approved
+ target once its blocker is resolved. Already-correct chunks/facts are retained.
+ Prior debits survive interruptions; increasing `--max-cost-usd` authorizes a
+ larger total, not a fresh allowance. Never clear the marker to reset spending.
- A different in-flight target refuses. Use `--retarget` only after explicit
approval to abandon that target and review the new cost.
- A lost or held lock means paused, not complete. Inspect the reported lock
and jobs before retrying; do not clear another writer's lock.
- `--no-embed` stages schema/config/invalidation but does not complete a
- migration. Finish the approved re-embed with
- `gbrain embed --stale --catch-up --include-null-signature`.
+ migration. Resume through `gbrain migrate embeddings` with the same approved
+ target and authorization so its durable cap and verification remain in force.
- Custom `embedding_columns` have no automatic migration here. Changing
their model labels does not convert their vectors. Plan a separate,
explicitly approved replacement or removal with the owner.
diff --git a/skills/migrations/v0.59.10.0.md b/skills/migrations/v0.59.10.0.md
new file mode 100644
index 0000000000..76426f7be0
--- /dev/null
+++ b/skills/migrations/v0.59.10.0.md
@@ -0,0 +1,50 @@
+# Upgrade to v0.59.10.0: preserve memory during maintenance
+
+This release adds schema v166 fact-vector provenance and changes migration,
+withdrawal, export and Gmail attachment metadata handling. It does not authorize
+paid repair, archive restoration, attachment downloads or new background services.
+
+1. **Prepare a maintenance window.** Stop all old CLI, resident, sync and worker
+ processes for this brain. Take and verify an engine-appropriate full backup.
+ Markdown export does not include the full database and is not a backup
+ substitute. Mixed old/new writers are not a supported upgrade procedure.
+
+2. **Upgrade and apply the schema.** Run
+ `gbrain upgrade --no-autopilot-install`, then confirm
+ `gbrain --version` reports v0.59.10.0 or newer. If the binary upgraded but its
+ schema work did not complete, use
+ `gbrain apply-migrations --yes --no-autopilot-install` after the backup and
+ quiescence checks. The new fact identity fields do not infer an old vector's
+ model from the current configuration. Unknown legacy identity remains unknown;
+ installing the schema does not call an embedding provider.
+
+3. **Inspect before authorizing repair.** Run
+ `gbrain migrate embeddings --status`. Preview an explicitly chosen model and
+ dimension with `--dry-run`. Any live migration requires an operator-approved
+ finite `--max-cost-usd` total; `--yes` does not waive the cap. Interrupted
+ requests retain their debits. Read
+ [embedding migration](../../docs/guides/embedding-migration.md) for retained
+ vector refusals, pending projections and safe retry instructions. Never
+ automatically restore an archived source, reset a cursor or force a revision.
+
+4. **Use fresh export destinations.** Export now refuses collisions and occupied
+ planned output paths rather than overwriting files. An interrupted destination
+ remains visibly incomplete; retry into a fresh destination. Existing exports
+ remain historical snapshots and are not retroactively edited by a withdrawal.
+
+5. **Keep Gmail repair opt-in.** Ordinary sync reports attachment inspection for
+ that sweep, not historical completeness. Preview
+ `gbrain google attachments backfill --source <id>` for an existing managed
+ Gmail source. Add `--yes` only when the operator approves the bounded
+ metadata-only batch. No attachment content is downloaded or indexed, and
+ unavailable or incomplete inspection remains explicit.
+
+6. **Verify the intended outcome.** Check `gbrain --version`, the migration status,
+ and representative authorized searches after any approved repair. Genuine
+ misses and private-only matches remain clean misses. MCP timeout/source-binding
+ diagnostics do not establish a fix for the unresolved Windows/Hermes report.
+ Restart only upgraded writers after the maintenance checks succeed.
+
+If a step fails, preserve the backup and diagnostic output and follow the linked
+recovery guide. Do not run a destructive reset, restore over intervening writes,
+or expand a spending authorization to make the status turn green.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 0fd1f316dd..9dc36ff7f2 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -132,7 +132,7 @@
"migrations/v0.40.3.0.md": "5f500f8c543c2b6f41778b0bd3beedada68f7284f7933ad8b769322b433a8fe9",
"migrations/v0.40.5.md": "b9837d52a030517698dfb31c439f562cde60a1015ae488dab09be2c16ff182e5",
"migrations/v0.41.11.0.md": "5c6873ab969d14def4a450d792f070f1259d08b3aca43bc7825d0a9114b2b36b",
- "migrations/v0.46.3.0.md": "82e0ce4cf96700332235f4d4307697651fe7376af5b5c1e88331ccbdbd3abc86",
+ "migrations/v0.46.3.0.md": "add5bdace741f8f0a75a114e354aa8ea3bcadf4cb54e1823338fdc69a5ae3f5d",
"migrations/v0.46.35.0.md": "145c841d89c4b6b6f7089126354fae272df7db6ceaf9cfcec2797d3301cdab57",
"migrations/v0.48.3.0.md": "1d9a23b6078164717944c94791b18effc7af630b716e8fde2680d6b6de47ce81",
"migrations/v0.49.0.0.md": "adf719246c3d6bcc7a1e5d24badb9968fe636651183a75c18d534e16aaa33ee8",
@@ -149,6 +149,7 @@
"migrations/v0.56.2.0.md": "e88f04a5deaef82ebb8bd194aec931f26e69e87687098eb64b94666931b5e319",
"migrations/v0.58.0.0.md": "a6ee3d3125ff1be612df776c7b8d6dfcaeb57ca073255793a67dff78a23c51cc",
"migrations/v0.59.0.0.md": "7903e547e79ad3429a393d9102a610e2674388bfaa71607431b1cd857b4af939",
+ "migrations/v0.59.10.0.md": "e0268a05ab184d5518f88747313e772629b2af91db59eacbba728f2ebd9db3cd",
"migrations/v0.59.2.0.md": "b6d61af8ef48c154a26e8d427dd6f6570e99efb82b891728426046eea493247b",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
diff --git a/src/cli.ts b/src/cli.ts
index a73fd5a5de..3e428295f1 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -43,6 +43,7 @@ import type { CliOptions } from './core/cli-options.ts';
import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from './core/mcp-client.ts';
import { maybePromptForUpgrade } from './core/thin-client-upgrade-prompt.ts';
import { CLI_FLAG_REGISTRY } from './core/cli-flag-registry.generated.ts';
+import { migrationCliArgumentError } from './core/embedding-migration-cli.ts';
import { VERSION } from './version.ts';
import { assertSupportedBun } from './core/runtime-version.ts';
import { bigintToStringReplacer } from './core/utils.ts';
@@ -115,6 +116,7 @@ export const CLI_ONLY = new Set(['mcp', 'init', 'reinit-pglite', 'pglite-repair'
// excluded from the generic short-circuit so detailed per-command and
// per-subcommand usage stays reachable.
const CLI_ONLY_SELF_HELP = new Set([
+ 'export',
'mcp',
'upgrade', 'post-upgrade', 'check-update',
// cathedral-6: agent ships per-subcommand help (run/logs/register) inside
@@ -263,6 +265,7 @@ const CLI_ONLY_SELF_HELP = new Set([
* GBRAIN_HOME and requires exit 0 plus real help output.
*/
const SELF_HELP_WITHOUT_ENGINE: Record<string, () => Promise<(engine: never, args: string[]) => unknown>> = {
+ export: async () => (await import('./commands/export.ts')).runExport as never,
models: async () => (await import('./commands/models.ts')).runModels as never,
watch: async () => (await import('./commands/watch.ts')).runWatch as never,
skillopt: async () => (await import('./commands/skillopt.ts')).runSkillOptCommand as never,
@@ -603,13 +606,14 @@ async function main() {
// short-circuit so `gbrain x --help` never errors; runs before any dispatch
// or engine connect so the error is instant and side-effect-free.
{
- const unknown = validateCommandFlags(command, subArgs);
+ const migrationError = migrationCliArgumentError(command, subArgs, rawArgs);
+ const unknown = migrationError?.flag ?? validateCommandFlags(command, subArgs);
if (unknown) {
// Message contract shared with init.ts's in-handler check (which this
// pre-dispatch validator now reaches first): lowercase 'unknown flag'
// on stderr; --json callers get the structured error on stdout with
// reason 'invalid_flag' (pinned by test/init-migrate-only.test.ts).
- const message = `unknown flag ${unknown} for 'gbrain ${command}'`;
+ const message = migrationError?.message ?? `unknown flag ${unknown} for 'gbrain ${command}'`;
// Both --json spellings get the structured envelope (--json=false opts out).
if (subArgs.some(a => a === '--json' || (a.startsWith('--json=') && a !== '--json=false'))) {
process.stdout.write(JSON.stringify({ status: 'error', reason: 'invalid_flag', message }) + '\n');
@@ -1425,6 +1429,7 @@ function flagValidationExempt(command: string, subArgs: string[]): boolean {
/** Returns the first unknown flag (e.g. '--dry-run') or null when clean. */
export function validateCommandFlags(command: string, subArgs: string[]): string | null {
if (flagValidationExempt(command, subArgs)) return null;
+ if (command === 'retrieval-upgrade' || command === 'migrate' && subArgs[0] === 'embeddings') return migrationCliArgumentError(command, subArgs)?.flag ?? null;
// Lane order MUST mirror dispatch order (CLI_ONLY first): commands that are
// BOTH an op and a CLI_ONLY member (think, salience, anomalies) dispatch to
// handleCliOnly, whose handlers parse flags the op contract doesn't declare
@@ -3884,8 +3889,8 @@ IMPORT/EXPORT
See also: autopilot --install (continuous daemon).
sync --all --missing-path skip Classify sources whose local_path is absent
on this machine as skipped, not failed
- export [--dir ./out/] Export to markdown
- export --restore-only [--repo <p>] Restore missing supabase-only files
+ export [--source <id>] [--dir <p>] Coherent Markdown snapshot; fresh output, no overwrite
+ export --restore-only [--repo <p>] Restore missing db_only files; export --help for safe retry
[--type T] [--slug-prefix S] With optional filters
FILES
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index 7f11fc4fc7..9745953c0b 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -2189,9 +2189,7 @@ export async function buildChecks(
} catch { /* table may be missing or fresh; treat as empty */ }
if (totalChunks > 0) {
- const fix = embeddedCount === 0
- ? `No embeddings yet — drop the empty schema and re-init at the right dim:\n gbrain init --force --pglite --embedding-model ${configuredModel} --embedding-dimensions ${configuredDims}`
- : `Non-empty brain (${embeddedCount} embedded chunks). Migrate cleanly:\n gbrain migrate embeddings --to ${configuredModel} --dim ${configuredDims}`;
+ const fix = `Existing brain (${totalChunks} chunks, ${embeddedCount} embedded). Keep a verified database backup and preview the brain-wide migration:\n gbrain migrate embeddings --to ${configuredModel} --dim ${configuredDims} --dry-run\n After reviewing the plan, replace --dry-run with --yes --max-cost-usd <approved-total>. Missing vectors do not mean the brain is empty. See docs/guides/embedding-migration.md#recovery.`;
checks.push({
name: 'embedding_provider',
@@ -2244,7 +2242,7 @@ export async function buildChecks(
const { readContentChunksEmbeddingDim } = await import('../core/embedding-dim-check.ts');
const colDim = await readContentChunksEmbeddingDim(engine);
if (colDim.exists && colDim.dims !== null && colDim.dims !== actualDims) {
- issues.push(`DB dimension mismatch: column is vector(${colDim.dims}) but provider returns ${actualDims}-dim. See docs/embedding-migrations.md for the manual ALTER recipe.`);
+ issues.push(`DB dimension mismatch: column is vector(${colDim.dims}) but provider returns ${actualDims}-dim. See docs/embedding-migrations.md for a verified backup, migration preview and explicitly authorized repair.`);
}
} catch { /* column or table missing — fresh brain, fine */ }
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index ac5963d2fd..7dfc552468 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1,4 +1,5 @@
import { sanitizeRemoteBody } from '../core/remote-body.ts';
+import { prepareEmbeddingProjections, countArchivedEmbeddingWork } from '../core/embedding-readiness.ts';
import { embedStaleFacts, type EmbedFactsResult } from '../core/embed-facts.ts';
import { parseFactEmbedArgs } from './embed-facts-delegate.ts';
import { readProjectionSnapshot, installPageProjection, installPageEmbeddings } from '../core/page-state/projections.ts';
@@ -72,6 +73,7 @@ export type { EmbedBatchWithBackoffOpts } from '../core/embed-retry.ts';
/** #3037: cap failure samples so a corpus-wide outage doesn't bloat --json. */
const FAILURE_SAMPLE_CAP = 10;
const DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS = 30_000;
+const EMBED_UNAVAILABLE_MESSAGE = 'Page or source is unavailable or changed; no embeddings were installed. An archived source requires deliberate gbrain sources restore <id>; inspect the page and source before retrying.';
/**
* #3037: record embed failures on the run result. `chunkCount` is the number
@@ -236,6 +238,7 @@ export interface EmbedOpts {
* function refreshes them (heartbeat) but never releases them.
*/
heldLocks?: DbLockHandle[];
+ assertOwned?: (tx?: BrainEngine) => Promise<void>;
}
/**
@@ -696,6 +699,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
paceMaxConcurrency,
quiet: opts.quiet,
includeNullSignature: opts.includeNullSignature,
+ assertOwned: opts.assertOwned,
}, drainSignal);
} catch (e) {
// A heartbeat-triggered abort is a clean, resumable stop (lock_lost is
@@ -992,9 +996,12 @@ async function embedPage(
if (!initial) {
throw new Error(`Page not found: ${slug}`);
}
- const origin = await readProjectionSnapshot(engine, slug, initial.page.source_id, { allowUnsealed: true });
+ const origin = await readProjectionSnapshot(engine, slug, initial.page.source_id, { allowUnsealed: true, requireLiveSource: !dryRun });
if (!origin || origin.snapshot.revision !== initial.revision || origin.snapshot.page.id !== initial.page.id
- || origin.snapshot.sourceIncarnation !== initial.sourceIncarnation) return;
+ || origin.snapshot.sourceIncarnation !== initial.sourceIncarnation) {
+ if (!dryRun) recordFailure(result, 1, slug, EMBED_UNAVAILABLE_MESSAGE);
+ return;
+ }
const snapshot = origin.snapshot;
const page = snapshot.page;
@@ -1030,6 +1037,7 @@ async function embedPage(
await installPageProjection(engine, origin, inputs, { seal: true });
} catch (error) {
if (!(error instanceof PageRevisionConflictError)) throw error;
+ recordFailure(result, 1, slug, EMBED_UNAVAILABLE_MESSAGE);
return;
}
chunks = await engine.getChunks(slug, { sourceId: page.source_id });
@@ -1076,8 +1084,11 @@ async function embedPage(
// swallowed: the page stays NULL exactly as before, but the run now
// reports it (result.failures → non-zero exit) instead of pretending
// success. Abort (shutdown) still propagates.
- const prepared = await readProjectionSnapshot(engine, slug, page.source_id);
- if (!prepared || prepared.snapshot.revision !== snapshot!.revision || prepared.chunks.some((chunk, i) => chunk.id !== chunks[i]?.id || chunk.chunk_text !== chunks[i]?.chunk_text)) return;
+ const prepared = await readProjectionSnapshot(engine, slug, page.source_id, { requireLiveSource: true });
+ if (!prepared || prepared.snapshot.revision !== snapshot!.revision || prepared.chunks.some((chunk, i) => chunk.id !== chunks[i]?.id || chunk.chunk_text !== chunks[i]?.chunk_text)) {
+ recordFailure(result, toEmbed.length, slug, EMBED_UNAVAILABLE_MESSAGE);
+ return;
+ }
let embeddings: (Float32Array | null)[];
let failed = 0;
let firstError: unknown;
@@ -1114,7 +1125,10 @@ async function embedPage(
fullyEmbedded ? currentEmbeddingSignature() ?? undefined : undefined)) return false;
if (fullyEmbedded) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, page.source_id);
return true;
- })) return;
+ })) {
+ recordFailure(result, toEmbed.length, slug, EMBED_UNAVAILABLE_MESSAGE);
+ return;
+ }
result.embedded += toEmbed.length - failed;
if (failed > 0) {
recordFailure(result, failed, slug, firstError);
@@ -1166,6 +1180,7 @@ async function embedAll(
quiet?: boolean;
/** #3391: lift the NULL-signature grandfather clause (see EmbedOpts). */
includeNullSignature?: boolean;
+ assertOwned?: (tx?: BrainEngine) => Promise<void>;
},
signal?: AbortSignal,
) {
@@ -1237,8 +1252,11 @@ async function embedAll(
// target the correct (source_id, slug) row, not the 'default' source.
const pageSourceId = page.source_id;
const pageOpts = pageSourceId ? { sourceId: pageSourceId } : undefined;
- const prepared = await observed(pacer, () => readProjectionSnapshot(engine, page.slug, pageSourceId));
- if (!prepared) return;
+ const prepared = await observed(pacer, () => readProjectionSnapshot(engine, page.slug, pageSourceId, { requireLiveSource: !dryRun }));
+ if (!prepared) {
+ if (!dryRun) recordFailure(result, 1, page.slug, EMBED_UNAVAILABLE_MESSAGE);
+ return;
+ }
page = prepared.snapshot.page;
const chunks = prepared.chunks;
const toEmbed = chunks; // staleOnly path handled above via embedAllStale
@@ -1292,7 +1310,10 @@ async function embedAll(
if (!await installPageEmbeddings(tx, prepared, updated, failed === 0 ? signature : undefined)) return false;
if (failed === 0) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, page.slug, pageSourceId);
return true;
- }))) return;
+ }))) {
+ recordFailure(result, toEmbed.length, page.slug, EMBED_UNAVAILABLE_MESSAGE);
+ return;
+ }
result.embedded += toEmbed.length - failed;
if (failed > 0) {
recordFailure(result, failed, page.slug, firstError);
@@ -1404,6 +1425,7 @@ async function healChunklessPages(
pacer: DbPacer | undefined,
startedAt: number,
catchUp: boolean,
+ assertOwned?: (tx?: BrainEngine) => Promise<void>,
): Promise<void> {
const BATCH_SIZE = 50;
const BUDGET_MS: number | null = catchUp
@@ -1466,14 +1488,15 @@ async function healChunklessPages(
continue;
}
- const prepared = await observed(activePacer, () => readProjectionSnapshot(engine, page.slug, page.source_id, { allowUnsealed: true }));
+ const prepared = await observed(activePacer, () => readProjectionSnapshot(engine, page.slug, page.source_id, { allowUnsealed: true, requireLiveSource: true }));
if (!prepared || prepared.chunks.length > 0) continue;
const inputs = buildInputs(prepared.snapshot.page.compiled_truth, prepared.snapshot.page.timeline, prepared.maxChunkTokens);
if (inputs.length === 0) continue;
- await observed(activePacer, () =>
- installPageProjection(engine, prepared, inputs, { seal: true }),
- );
+ await observed(activePacer, () => engine.transaction(async tx => {
+ await assertOwned?.(tx);
+ await installPageProjection(tx, prepared, inputs, { seal: true });
+ }));
pagesHealed++;
try {
await activePacer.pace(signal);
@@ -1540,6 +1563,7 @@ async function embedAllStale(
quiet?: boolean;
/** #3391: lift the NULL-signature grandfather clause (see EmbedOpts). */
includeNullSignature?: boolean;
+ assertOwned?: (tx?: BrainEngine) => Promise<void>;
},
signature?: string,
externalSignal?: AbortSignal,
@@ -1550,11 +1574,45 @@ async function embedAllStale(
// ONE `GBRAIN_EMBED_TIME_BUDGET_MS` window instead of summing two
// independent 30-minute budgets.
const overallStartedAt = Date.now();
+ const BUDGET_MS: number | null = staleOpts?.catchUp
+ ? null
+ : parseInt(process.env.GBRAIN_EMBED_TIME_BUDGET_MS || `${30 * 60 * 1000}`, 10);
// D7: thread sourceId so source-scoped runs only count + visit
// that source's NULL embeddings.
const sourceOpt = sourceId ? { sourceId } : undefined;
+ if (isAborted(externalSignal)) return;
const includeNullSig = !!staleOpts?.includeNullSignature;
+ let reportedArchived = 0;
+ const reportArchived = async () => {
+ if (dryRun) return;
+ const blocked = await countArchivedEmbeddingWork(engine, { sourceId, signature, includeNullSignature: includeNullSig });
+ if (blocked <= reportedArchived) return;
+ result.failures += blocked - reportedArchived;
+ reportedArchived = blocked;
+ result.failure_samples.push(`${blocked} archived page(s) have blocked embedding work; active pages can progress, but this run is incomplete. Use gbrain sources restore <id> deliberately before retrying archived work.`);
+ };
+ await reportArchived();
+ const readinessOptions = { sourceId, existingChunksOnly: true, activeSourcesOnly: true, stale: { signature, includeNullSignature: includeNullSig }, signal: externalSignal,
+ deadline: BUDGET_MS === null ? undefined : overallStartedAt + BUDGET_MS };
+ let readiness = await prepareEmbeddingProjections(engine, readinessOptions);
+ if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return;
+ if (readiness.blocked && !dryRun) {
+ const probeOk = await probeEmbedder((texts, fnOpts) => embedBatchWithBackoff(texts, { abortSignal: fnOpts.abortSignal }), signature ?? undefined, externalSignal);
+ if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return;
+ if (!probeOk) {
+ result.failures += readiness.blocked;
+ result.failure_samples.push('Projection recovery requires a working embedding provider; existing projections were preserved.');
+ return;
+ }
+ readiness = await prepareEmbeddingProjections(engine, { ...readinessOptions, repair: true, assertOwned: staleOpts?.assertOwned });
+ if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return;
+ }
+ if (readiness.blocked && !dryRun) {
+ result.failures += readiness.blocked;
+ result.failure_samples.push('Projection recovery remains blocked; rerun embed --stale for bounded recovery or restore unsupported media with its source importer.');
+ return;
+ }
// Chunkless-page safety net: pre-flight count mirrors the countStaleChunks
// short-circuit just below — a healthy brain pays one extra SELECT
@@ -1566,7 +1624,7 @@ async function embedAllStale(
if (chunklessCount > 0) {
await healChunklessPages(
engine, sourceId, dryRun, result, staleOpts?.quiet, externalSignal, staleOpts?.pacer,
- overallStartedAt, !!staleOpts?.catchUp,
+ overallStartedAt, !!staleOpts?.catchUp, staleOpts?.assertOwned,
);
}
// Review catch: an abort during healing must stop the run HERE, before
@@ -1593,11 +1651,12 @@ async function embedAllStale(
if (!dryRun && signature) {
let signatureDrift = 0;
try {
- const wide = await engine.countStaleChunks({
- ...sourceOpt, signature, ...(includeNullSig && { includeNullSignature: true }),
- });
- const nullOnly = await engine.countStaleChunks(sourceOpt);
- signatureDrift = wide - nullOnly;
+ const sources = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived AND ($1::text IS NULL OR id=$1) ORDER BY id', [sourceId ?? null]);
+ for (const source of sources) {
+ const wide = await engine.countStaleChunks({ sourceId: source.id, signature, ...(includeNullSig && { includeNullSignature: true }) });
+ const nullOnly = await engine.countStaleChunks({ sourceId: source.id });
+ signatureDrift += wide - nullOnly;
+ }
} catch {
// Pre-count is best-effort; fall through as "no drift" (no NULLing).
}
@@ -1609,10 +1668,13 @@ async function embedAllStale(
externalSignal,
);
if (probeOk) {
- invalidated = await invalidateStaleSignatureEmbeddingsGuarded(engine, {
- signature,
- ...(sourceId && { sourceId }),
- ...(includeNullSig && { includeNullSignature: true }),
+ invalidated = await engine.transaction(async tx => {
+ await staleOpts?.assertOwned?.(tx);
+ return invalidateStaleSignatureEmbeddingsGuarded(tx, {
+ signature,
+ ...(sourceId && { sourceId }),
+ ...(includeNullSig && { includeNullSignature: true }),
+ });
});
} else {
serr(
@@ -1662,7 +1724,10 @@ async function embedAllStale(
// (pre-v133 rows) is grandfathered.
if (!dryRun) {
try {
- const drifted = await engine.invalidateContentDriftEmbeddings(sourceId ? { sourceId } : undefined);
+ const drifted = staleOpts?.assertOwned ? await engine.transaction(async tx => {
+ await staleOpts?.assertOwned?.(tx);
+ return tx.invalidateContentDriftEmbeddings(sourceId ? { sourceId } : undefined);
+ }) : await engine.invalidateContentDriftEmbeddings(sourceId ? { sourceId } : undefined);
if (drifted > 0 && !staleOpts?.quiet) {
slog(`[embed] invalidated ${drifted} chunk(s) whose text changed after embedding (content drift)`);
}
@@ -1679,6 +1744,7 @@ async function embedAllStale(
: sourceOpt,
);
if (staleCount === 0) {
+ await reportArchived();
if (!staleOpts?.quiet) {
if (dryRun) {
// dryRun never writes, so a healed-but-hypothetical chunkless page's
@@ -1741,9 +1807,6 @@ async function embedAllStale(
// to NOT arm the timer in catch-up at all: the keyset pass below terminates on
// its own (the (page_id, chunk_index) cursor advances monotonically), and
// SIGINT / worker-abort still propagate via externalSignal.
- const BUDGET_MS: number | null = staleOpts?.catchUp
- ? null
- : parseInt(process.env.GBRAIN_EMBED_TIME_BUDGET_MS || `${30 * 60 * 1000}`, 10);
const budgetController = new AbortController();
// Shares overallStartedAt with the chunkless-page healing sweep above
// (review catch) so the two phases draw from ONE combined budget window
@@ -1891,15 +1954,16 @@ async function embedAllStale(
// `--stale` reuses stored rows; without this, one pre-cap chunk
// (e.g. a long pre-cap notes page on a 512-token model) fails
// forever and exits the sweep non-zero.
- const healed = await observed(pacer, () =>
- healOversizedPageChunks(engine, slug, {
+ const healed = await observed(pacer, () => engine.transaction(async tx => {
+ await staleOpts?.assertOwned?.(tx);
+ return healOversizedPageChunks(tx, slug, {
sourceId: keySourceId,
onSplit: (n) => {
result.healed_splits = (result.healed_splits ?? 0) + n;
serr(`\n ${slug}: split ${n} oversized chunk(s) to fit embedding input limit`);
},
- }),
- );
+ });
+ }));
if (healed.changed) {
stale = healedChunksToStaleRows(healed.chunks, slug, keySourceId);
if (stale.length === 0) {
@@ -1914,7 +1978,7 @@ async function embedAllStale(
// silently stripping contextual prefixes — `embed --stale` is the
// NORMAL post-model-migration path, so raw-text embedding here
// quietly converted whole corpora to the unwrapped convention.
- const prepared = await observed(pacer, () => readProjectionSnapshot(engine, slug, keySourceId));
+ const prepared = await observed(pacer, () => readProjectionSnapshot(engine, slug, keySourceId, { requireLiveSource: true }));
if (!prepared) return;
const selected = new Map(stale.map(c => [c.chunk_index, c]));
const existing = prepared.chunks;
@@ -1943,6 +2007,7 @@ async function embedAllStale(
// Keep both stamps with vector installation so later contextual
// work cannot commit between installation and title-tier demotion.
if (!await observed(pacer, () => engine.transaction(async tx => {
+ await staleOpts?.assertOwned?.(tx);
if (!await installPageEmbeddings(tx, prepared, merged)) return false;
if (stamp && failed === 0) await stampIfPageProvenanceComplete(tx, slug, keySourceId, stamp);
if (failed === 0 && stale.length === existing.length) {
@@ -2008,6 +2073,7 @@ async function embedAllStale(
}
} finally {
if (budgetTimer) clearTimeout(budgetTimer);
+ await reportArchived();
}
if (!staleOpts?.quiet) slog(`Embedded ${result.embedded} chunks across ${totalProcessedPages} pages`);
diff --git a/src/commands/export.ts b/src/commands/export.ts
index f2efcb208a..f414829f75 100644
--- a/src/commands/export.ts
+++ b/src/commands/export.ts
@@ -1,173 +1,148 @@
-import { writeFileSync, mkdirSync, existsSync } from 'fs';
-import { join, dirname } from 'path';
+import { existsSync } from 'node:fs';
+import { join, resolve } from 'node:path';
import type { BrainEngine } from '../core/engine.ts';
-import { serializeMarkdown } from '../core/markdown.ts';
+import { resolveSourceLocalFilePath, serializeMarkdown } from '../core/markdown.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import { loadStorageConfig, isDbOnly } from '../core/storage-config.ts';
import { slugifyPath } from '../core/sync.ts';
-import { getDefaultSourcePath } from '../core/source-resolver.ts';
-import type { PageType } from '../core/types.ts';
-
-export async function runExport(engine: BrainEngine, args: string[]) {
- const dirIdx = args.indexOf('--dir');
- const outDir = dirIdx !== -1 ? args[dirIdx + 1] : './export';
-
- const repoIdx = args.indexOf('--repo');
- const explicitRepoPath = repoIdx !== -1 ? args[repoIdx + 1] : null;
-
- const typeIdx = args.indexOf('--type');
- const typeFilter = typeIdx !== -1 ? (args[typeIdx + 1] as string) : undefined;
-
- const slugPrefixIdx = args.indexOf('--slug-prefix');
- const slugPrefix = slugPrefixIdx !== -1 ? args[slugPrefixIdx + 1] : undefined;
-
- const restoreOnly = args.includes('--restore-only');
-
- // Resolution chain (D5): explicit --repo → typed sources.getDefault() →
- // hard-error for restore-only paths (never fall through to cwd).
- // For non-restore exports, repoPath stays null because regular export
- // doesn't need a brain repo to run (D26 — exports include everything).
- let repoPath: string | null = explicitRepoPath;
- if (restoreOnly && !repoPath) {
- repoPath = await getDefaultSourcePath(engine);
- if (!repoPath) {
- console.error(
- `Error: gbrain export --restore-only requires --repo <path> or a configured\n` +
- `default source with a local_path. Run \`gbrain sources list\` to inspect\n` +
- `sources, or pass --repo explicitly.`,
- );
- process.exit(1);
- }
- }
-
- // Load storage configuration if repo path is provided
- const storageConfig = repoPath ? loadStorageConfig(repoPath) : null;
+import { resolveSourceId } from '../core/source-resolver.ts';
+import { ALL_SOURCES, assertValidSourceId } from '../core/source-id.ts';
+import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_SNAPSHOT_MS, exportPathKey } from '../core/export-stage.ts';
+import { publishExport } from '../core/export-publish.ts';
+import { nativeFileTarget } from '../core/persistence/native-file-target.ts';
+import { readExportPage, readExportWithdrawals } from '../core/export-snapshot.ts';
+
+function option(args: string[], name: string): string | undefined {
+ const indices = args.flatMap((arg, i) => arg === name || arg.startsWith(name + '=') ? [i] : []);
+ if (!indices.length) return undefined;
+ if (indices.length > 1) throw new Error(`${name} must be provided only once.`);
+ const i = indices[0];
+ const value = args[i].startsWith(name + '=') ? args[i].slice(name.length + 1) : args[i + 1];
+ if (!value || value.startsWith('--') || value.includes('\0')) throw new Error(`${name} requires a value.`);
+ return value;
+}
- // D5 + Codex P0: refuse --restore-only when there's no storage config to
- // scope the restore. Without storageConfig, the selective filter (db_only
- // pages missing on disk) can't run, and falling through to the full
- // listPages export silently dumps the entire DB. Catch this before any
- // page query fires.
- if (restoreOnly && !storageConfig) {
- console.error(
- `Error: gbrain export --restore-only requires a storage tiering config\n` +
- `(gbrain.yml with a "storage:" section) at ${repoPath}/gbrain.yml.\n` +
- `Without it, there's nothing to scope the restore to.\n` +
- `Run \`gbrain storage status\` to inspect the current configuration.`,
- );
- process.exit(1);
+export async function runExport(engine: BrainEngine, args: string[]): Promise<void> {
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: gbrain export [--dir <path>] [--source <id>] [--type <type>] [--slug-prefix <prefix>]
+ gbrain export --restore-only [--source <id>] [--repo <path>] [--dir <path>] [--slug-prefix <prefix>]
+
+Export a coherent point-in-time Markdown snapshot; this is not a database backup.
+ --dir <path> Output directory (default: ./export).
+ --source <id> Select one active source; omitted includes all sources.
+ --type <type> Select one page type.
+ --slug-prefix <prefix> Select stored slugs beginning with this literal prefix.
+ --restore-only Export missing db_only files for one source.
+ --repo <path> Restore source's repository and storage config; output still goes to --dir.
+
+Colliding planned paths and occupied output paths refuse; nothing is overwritten.
+Existing empty directories and unrelated files are preserved. There is no force option.
+The reserved .gbrain-export-status starts incomplete and ends with COMPLETE only
+after successful publication. On failure, preserve partial output and retry into
+a fresh directory. See docs/storage-tiering.md#safe-export.`);
+ return;
}
-
- // Build filters. slugPrefix is engine-side (Issue #13) — no in-memory
- // post-filter, no full-table load.
- const filters: import('../core/types.ts').PageFilters = { limit: 100000 };
- if (typeFilter) filters.type = typeFilter;
- if (slugPrefix) filters.slugPrefix = slugPrefix;
-
- let pages: import('../core/types.ts').Page[];
-
- // Restore-only path: query each db_only directory with slugPrefix instead
- // of loading every page in the brain. On a 200K-page brain where 95% is
- // db_only, this is roughly the same load — but on brains where only 5K
- // out of 200K are db_only, this is a ~40x reduction.
- if (restoreOnly && repoPath && storageConfig) {
- const seen = new Set<string>();
- pages = [];
- for (const dir of storageConfig.db_only) {
- const tierFilters: import('../core/types.ts').PageFilters = {
- ...filters,
- slugPrefix: filters.slugPrefix
- ? // If user passed --slug-prefix, only include tier dirs that start with it.
- (dir.startsWith(filters.slugPrefix) ? dir : undefined)
- : dir,
- };
- if (!tierFilters.slugPrefix) continue;
- const tierPages = await engine.listPages(tierFilters);
- for (const p of tierPages) {
- if (seen.has(p.slug)) continue;
- seen.add(p.slug);
- if (!isDbOnly(p.slug, storageConfig)) continue; // belt-and-suspenders
- const filePath = join(repoPath, p.slug + '.md');
- if (existsSync(filePath)) continue;
- pages.push(p);
+ let stage: ExportStage | undefined;
+ try {
+ const outDir = option(args, '--dir') ?? './export';
+ const requested = option(args, '--source');
+ const type = option(args, '--type');
+ const prefix = option(args, '--slug-prefix');
+ const explicitRepo = option(args, '--repo');
+ const restoreOnly = args.includes('--restore-only');
+ stage = new ExportStage();
+ const staged = stage;
+ const started = Date.now();
+ const checkDeadline = () => {
+ if (Date.now() - started > EXPORT_SNAPSHOT_MS) throw new Error('Export snapshot time limit reached. Select a smaller scope with --source, --type or --slug-prefix.');
+ };
+ await engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
+ await tx.executeRaw('SET LOCAL statement_timeout = 60000');
+ let source = requested ? await resolveSourceId(tx, requested) : undefined;
+ let repo = explicitRepo;
+ if (restoreOnly) {
+ if (source === ALL_SOURCES) throw new Error('--restore-only requires one source; pass --source <id>.');
+ if (!source && repo) {
+ const matches = await tx.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE AND local_path=$1 LIMIT 2', [resolve(repo)]);
+ if (matches.length === 1) source = matches[0].id;
+ else {
+ const owners = await tx.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id LIMIT 2');
+ if (!matches.length && owners.length === 1) source = owners[0].id;
+ else throw new Error('The restore repo does not identify exactly one source. Pass --source <id> and --repo <path> for that source.');
+ }
+ }
+ source ??= await resolveSourceId(tx, undefined);
+ if (source === ALL_SOURCES) throw new Error('--restore-only requires one source; pass --source <id>.');
+ if (!repo) {
+ const [owner] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [source]);
+ repo = owner?.local_path ?? (source === 'default' ? await tx.getConfig('sync.repo_path') : undefined) ?? undefined;
+ }
+ if (!repo) throw new Error('--restore-only requires --repo <path> or a configured default source with a local_path.');
}
- }
- } else {
- pages = await engine.listPages(filters);
- }
- if (restoreOnly) {
- console.log(`Restoring ${pages.length} db_only pages to ${outDir}/`);
- } else {
- console.log(`Exporting ${pages.length} pages to ${outDir}/`);
- }
-
- // Progress on stderr so stdout stays clean for scripts parsing counts.
- const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
- progress.start('export.pages', pages.length);
-
- let exported = 0;
-
- for (const page of pages) {
- // Slugs are unique per source, not brain-wide, so both sidecar reads are
- // pinned to the page's own source. Unscoped, `getTags` falls back to
- // `source_id = 'default'` and stamps the default source's tags onto a
- // same-slug page from another source (dropping its real ones).
- const tags = await engine.getTags(page.slug, { sourceId: page.source_id });
- // #3772: the file is written at <slug>.md and import re-derives the slug
- // from that path. When the stored slug is NOT a slugifyPath fixed point
- // (legacy/hand-keyed slugs with case, apostrophes, accents…), a re-import
- // would silently re-key the page — stamp the true identity into the
- // frontmatter so import can restore it (import accepts a frontmatter slug
- // whose slugified spelling equals the path-derived one). Fixed-point
- // slugs stay unstamped: no diff noise on the common path. A stale
- // frontmatter slug that contradicts the DB identity is corrected either way.
- const fmSlug = (page.frontmatter as Record<string, unknown> | null | undefined)?.['slug'];
- const needsSlugStamp = slugifyPath(page.slug + '.md') !== page.slug;
- const frontmatter = (needsSlugStamp || fmSlug !== undefined) && fmSlug !== page.slug
- ? { ...(page.frontmatter ?? {}), slug: page.slug }
- : page.frontmatter;
- const md = serializeMarkdown(
- frontmatter,
- page.compiled_truth,
- page.timeline,
- { type: page.type, title: page.title, tags },
- );
-
- const filePath = join(outDir, page.slug + '.md');
- mkdirSync(dirname(filePath), { recursive: true });
- writeFileSync(filePath, md);
-
- // Export raw data as sidecar JSON. Unscoped, this matches the slug in
- // EVERY source and the loop below merges the rows into one sidecar keyed
- // by `rd.source`, so another source's raw data silently overwrites this
- // page's own on a key collision.
- const rawData = await engine.getRawData(page.slug, undefined, {
- sourceId: page.source_id,
- includeDeleted: true, // the page list decides which rows export; raw follows its page
- });
- if (rawData.length > 0) {
- const slugParts = page.slug.split('/');
- const rawDir = join(outDir, ...slugParts.slice(0, -1), '.raw');
- mkdirSync(rawDir, { recursive: true });
- const rawPath = join(rawDir, slugParts[slugParts.length - 1] + '.json');
-
- const rawObj: Record<string, unknown> = {};
- for (const rd of rawData) {
- rawObj[rd.source] = rd.data;
+ const storage = restoreOnly && repo ? loadStorageConfig(repo) : null;
+ if (restoreOnly && !storage) throw new Error('--restore-only requires a storage tiering config (gbrain.yml with a storage section).');
+ let cursor = '0';
+ for (;;) {
+ checkDeadline();
+ const batch = await tx.executeRaw<{ id: string; slug: string; source_id: string; source_path: string | null; source_path_bytes: number; raw_count: number; bytes: number }>(
+ `SELECT p.id::text, left(p.slug,4097) AS slug, p.source_id, left(p.source_path,4097) AS source_path, octet_length(p.source_path) AS source_path_bytes,
+ (SELECT count(*) FROM raw_data r WHERE r.page_id=p.id) AS raw_count,
+ octet_length(p.compiled_truth)::bigint + octet_length(p.timeline) + octet_length(p.frontmatter::text)
+ + octet_length(p.title) + octet_length(p.slug) + COALESCE(octet_length(p.source_path),0)
+ + COALESCE((SELECT sum(octet_length(r.data::text)+octet_length(r.source)) FROM raw_data r WHERE r.page_id=p.id),0)
+ + COALESCE((SELECT sum(octet_length(t.tag)) FROM tags t WHERE t.page_id=p.id),0) AS bytes
+ FROM pages p WHERE p.id > $1::bigint AND p.deleted_at IS NULL
+ AND ($2::text IS NULL OR p.source_id=$2) AND ($3::text IS NULL OR p.type=$3)
+ AND ($4::text IS NULL OR starts_with(p.slug,$4)) ORDER BY p.id LIMIT 256`,
+ [cursor, source === ALL_SOURCES ? null : source ?? null, type ?? null, prefix ?? null]);
+ if (!batch.length) break;
+ for (const batchSource of new Set(batch.map(key => key.source_id))) {
+ checkDeadline();
+ const withdrawals = await readExportWithdrawals(tx, batchSource);
+ for (const key of batch.filter(key => key.source_id === batchSource)) {
+ checkDeadline();
+ assertValidSourceId(key.source_id);
+ exportPathKey(key.slug + '.md');
+ if (restoreOnly && storage && repo) {
+ if (!isDbOnly(key.slug, storage)) continue;
+ if (Number(key.source_path_bytes) > 4096) throw new Error('The recorded restore path exceeds the safe path limit.');
+ const recorded = resolveSourceLocalFilePath(repo, key.source_path, key.slug);
+ if (key.source_path && !recorded) throw new Error('The recorded restore file path is unsafe. Reconcile it before exporting.');
+ if (existsSync(nativeFileTarget(repo, recorded ?? join(repo, key.slug + '.md')))) continue;
+ }
+ if (Number(key.bytes) > EXPORT_PAYLOAD_LIMIT) throw new Error('Export page payload limit exceeded. No destination output was published.');
+ const snapshot = await readExportPage(tx, key, withdrawals);
+ const page = snapshot.page;
+ const fmSlug = page.frontmatter?.slug;
+ const needsSlugStamp = slugifyPath(page.slug + '.md') !== page.slug;
+ const frontmatter = (needsSlugStamp || fmSlug !== undefined) && fmSlug !== page.slug
+ ? { ...(page.frontmatter ?? {}), slug: page.slug } : page.frontmatter;
+ staged.add(page.slug + '.md', 'file', serializeMarkdown(frontmatter, page.compiled_truth, page.timeline,
+ { type: page.type, title: page.title, tags: snapshot.tags }));
+ const raw = Number(key.raw_count) ? await tx.getRawData(page.slug, undefined, { sourceId: page.source_id, includeDeleted: true }) : [];
+ if (raw.length) {
+ const parts = page.slug.split('/');
+ const name = parts.pop()!;
+ staged.add([...parts, '.raw', name + '.json'].join('/'), 'file', JSON.stringify(Object.fromEntries(raw.map(row => [row.source, row.data])), null, 2) + '\n');
+ }
+ staged.pages++;
+ }
+ }
+ cursor = batch[batch.length - 1].id;
}
- writeFileSync(rawPath, JSON.stringify(rawObj, null, 2) + '\n');
- }
-
- exported++;
- progress.tick();
- }
-
- progress.finish();
- // Stdout summary preserved so scripts that grep for "Exported N pages" keep working.
- if (restoreOnly) {
- console.log(`Restored ${exported} pages to ${outDir}/`);
- } else {
- console.log(`Exported ${exported} pages to ${outDir}/`);
- }
+ checkDeadline();
+ });
+ console.log(`${restoreOnly ? 'Restoring' : 'Exporting'} ${stage.pages}${restoreOnly ? ' db_only' : ''} pages to ${outDir}/`);
+ const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
+ progress.start('export.pages', stage.pages);
+ await publishExport(stage, outDir, path => { if (path.endsWith('.md')) progress.tick(); });
+ progress.finish();
+ console.log(`${restoreOnly ? 'Restored' : 'Exported'} ${stage.pages} pages to ${outDir}/`);
+ } catch (error) {
+ console.error(`Error: Export failed: ${(error as Error).message}\nNo complete export was produced. If ${'.gbrain-export-status'} exists without a final COMPLETE line, the destination is incomplete. Preserve its files and retry into a fresh directory. See docs/storage-tiering.md#safe-export.`);
+ if (stage) { stage.close(); stage = undefined; }
+ process.exit(1);
+ } finally { stage?.close(); }
}
diff --git a/src/commands/google-attachments.ts b/src/commands/google-attachments.ts
new file mode 100644
index 0000000000..6a599f9fa4
--- /dev/null
+++ b/src/commands/google-attachments.ts
@@ -0,0 +1,107 @@
+import type { BrainEngine } from '../core/engine.ts';
+import { getCliOptions } from '../core/cli-options.ts';
+import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
+import { isThinClient, loadConfig, toEngineConfig } from '../core/config.ts';
+import { resolveBrainId } from '../core/brain-resolver.ts';
+import { loadMounts } from '../core/brain-registry.ts';
+import { persistenceConfigForBrain } from '../core/persistence/local-client.ts';
+import { readLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';
+import { OperationError } from '../core/ops/contract.ts';
+import { isValidSourceId } from '../core/source-id.ts';
+import { parseGoogleSourceConfig, runGoogleAttachmentBackfill } from '../core/google/google-source.ts';
+import type { FetchImpl } from '../core/google/google-clients.ts';
+import { managedSyncAuthority } from '../core/persistence/sync-authority.ts';
+import { connectorCheckpointKey } from '../core/persistence/connector-sync.ts';
+import type { GoogleSourceState } from '../core/google/types.ts';
+import { isCredentialError } from '../core/creds/errors.ts';
+
+export const GOOGLE_ATTACHMENTS_HELP = `Usage: gbrain google attachments backfill --source <id> [--brain <id>] [--yes] [--limit 1-25] [--retry-failed] [--json]
+
+Without --yes, inspect the selected source without contacting Google or changing metadata.
+With --yes, repair attachment receipts on at most 25 already-imported thread pages.
+Managed persistence and an existing trusted local CLI registration are required.
+This command never enables persistence/services, downloads attachments, or extracts facts.
+It preserves page content and resumes its account-bound historical cursor on the next run.
+Complete means traversal of this fixed set, not successful inspection of unavailable messages or the entire mailbox.
+Confirmed upstream absence preserves prior receipts, records unavailable identities, and does not block later pages.
+Paused/incomplete apply returns a nonzero exit status; repeat the same command to resume a paused batch.
+Inspect conflicts before retrying; --retry-failed explicitly approves a terminal failed receipt.
+Run on the canonical host with the selected PGLite brain idle; remote delegation is not supported.
+See docs/guides/google-connect.md#attachment-receipts-and-historical-repair`;
+
+export function parseGoogleAttachmentsArgs(args: string[]) {
+ if (args[0] !== 'backfill') throw new OperationError('invalid_params', 'Select the attachment backfill subcommand.');
+ const flags = new Map<string, string | true>();
+ for (let i = 1; i < args.length; i++) {
+ const [flag, inline] = args[i].split(/=(.*)/s);
+ if (!['--source', '--brain', '--limit', '--yes', '--json', '--retry-failed'].includes(flag) || flags.has(flag)) throw new OperationError('invalid_params', 'Unknown or duplicate attachment repair option.');
+ if (['--yes', '--json', '--retry-failed'].includes(flag)) {
+ if (inline !== undefined) throw new OperationError('invalid_params', 'Boolean attachment repair options do not accept values.');
+ flags.set(flag, true);
+ } else {
+ const value = inline ?? args[++i];
+ if (!value || value.startsWith('-') || value.includes('\0')) throw new OperationError('invalid_params', 'An attachment repair option needs a value.');
+ flags.set(flag, value);
+ }
+ }
+ const sourceId = flags.get('--source');
+ if (!isValidSourceId(sourceId)) throw new OperationError('invalid_params', 'Select one explicit valid Google source ID.');
+ const limit = flags.has('--limit') ? Number(flags.get('--limit')) : 25;
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 25) throw new OperationError('invalid_params', 'Attachment repair limit must be 1-25.');
+ const brain = flags.get('--brain') as string | undefined;
+ if (brain && !isValidSourceId(brain)) throw new OperationError('invalid_params', 'Select a valid brain ID.');
+ if (flags.has('--retry-failed') && !flags.has('--yes')) throw new OperationError('invalid_params', '--retry-failed requires --yes.');
+ return { sourceId, limit, brain, yes: flags.has('--yes'), json: flags.has('--json'), retryFailed: flags.has('--retry-failed') };
+}
+
+export async function runGoogleAttachments(args: string[], connected?: BrainEngine, fetchImpl?: FetchImpl): Promise<void> {
+ if (!args.length || args.includes('--help') || args.includes('-h')) { process.stdout.write(GOOGLE_ATTACHMENTS_HELP + '\n'); return; }
+ let owned: BrainEngine | undefined;
+ let applyAttempted = false;
+ try {
+ const parsed = parseGoogleAttachmentsArgs(args);
+ const brain = resolveBrainId(parsed.brain ?? getCliOptions().brain);
+ const config = persistenceConfigForBrain(loadConfig(), brain, brain === 'host' ? [] : loadMounts());
+ if (!connected && (!config || isThinClient(config))) throw new OperationError('permission_denied', 'Attachment repair requires the configured canonical host, not a remote token.');
+ if (!connected) {
+ const { createEngine } = await import('../core/engine-factory.ts');
+ owned = await createEngine(toEngineConfig(config!));
+ await owned.connect(toEngineConfig(config!));
+ }
+ const engine = connected ?? owned!;
+ const registration = await readLocalWriter(engine, 'cli');
+ const result = await withVerifiedLocalRegistration(engine, registration, async () => {
+ const [source] = await engine.executeRaw<{ config: Record<string, unknown>; incarnation: string; local_path: string | null; archived: boolean }>('SELECT config,incarnation,local_path,archived FROM sources WHERE id=$1', [parsed.sourceId]);
+ if (!source || source.archived || source.config.kind !== 'google') throw new OperationError('invalid_params', 'Select an active Google source.');
+ const [mode] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ if (!mode?.enabled) throw new OperationError('writer_coordinator_required', 'Attachment repair requires already-enabled managed persistence.');
+ await managedSyncAuthority(engine, parsed.sourceId, source.incarnation, source.local_path ?? '');
+ const cfg = parseGoogleSourceConfig(source.config, source.local_path ?? '');
+ if (!parsed.yes) {
+ const [count] = await engine.executeRaw<{ count: string }>(`SELECT count(*)::text AS count FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND frontmatter->>'thread_id' IS NOT NULL`, [parsed.sourceId]);
+ const [checkpoint] = await engine.executeRaw<{ completed_keys: Array<{ state: GoogleSourceState }> }>(
+ "SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1",
+ [connectorCheckpointKey(parsed.sourceId, source.incarnation, 'google', source.config)]);
+ return { status: 'preview' as const, complete: false, imported_thread_pages: Number(count.count), account: cfg.account, writes: 'none',
+ historical_inspection: checkpoint?.completed_keys[0]?.state?.gmail_attachment_backfill ?? { status: 'not_inspected' } };
+ }
+ applyAttempted = true;
+ return { ...await runGoogleAttachmentBackfill(engine, parsed.sourceId, cfg, { limit: parsed.limit, retryFailed: parsed.retryFailed }, fetchImpl), account: cfg.account };
+ });
+ const complete = result.status === 'complete';
+ const summary = { ok: !parsed.yes || complete, ...result, brain, source: parsed.sourceId, limit: parsed.limit,
+ scope: 'already-imported Gmail thread pages; not mailbox-wide', doc_url: 'docs/guides/google-connect.md#attachment-receipts-and-historical-repair',
+ next_action: { user_message: result.status === 'paused' ? 'Repeat the same authorized command to resume the saved cursor.' : result.status === 'incomplete' ? 'Receipt inspection is incomplete. The cursor did not pass the incomplete page; inspect it before retrying.' : result.status === 'complete' && result.unavailable ? `Traversal is complete, but ${result.unavailable} pages contain ${result.unavailableMessages} unavailable historical messages. Prior receipts remain; those identities were not inspected this run.` : parsed.yes ? 'Inspect gmail_attachment_receipts on the authorized message pages.' : 'Review this source/account scope, then pass --yes to apply one bounded batch.' } };
+ if (parsed.json) await writeStdoutFinal(JSON.stringify(summary, null, 2) + '\n');
+ else process.stdout.write(`[SHOW USER]\nAttachment repair: ${result.status}; brain=${brain}; source=${parsed.sourceId}; account=${result.account}.\n${summary.scope}.\n${summary.next_action.user_message}\n${summary.doc_url}\n[/SHOW USER]\n`);
+ if (parsed.yes && !complete) setCliExitVerdict(1);
+ } catch (error) {
+ const code = error instanceof OperationError || isCredentialError(error) ? error.code : 'repair_failed';
+ const failure = { ok: false, status: 'failed', writes: applyAttempted ? 'durable_partial_work_possible' : 'none', error: { code, problem: 'Attachment repair did not complete.', cause: code === 'repair_failed' ? 'unknown' : code,
+ fix: 'Inspect the selected canonical source and retained write receipt before retrying. Completed metadata and cursor checkpoints remain durable; no message body is replayed.',
+ doc_url: 'docs/guides/google-connect.md#attachment-receipts-and-historical-repair' } };
+ if (args.includes('--json')) await writeStdoutFinal(JSON.stringify(failure, null, 2) + '\n');
+ else process.stderr.write(`${failure.error.problem} ${failure.error.fix}\n${failure.error.doc_url}\n`);
+ setCliExitVerdict(code === 'invalid_params' ? 2 : 1);
+ } finally { if (owned) await finishCliTeardown({ engine: owned, drainTimeoutMs: 1000 }); }
+}
diff --git a/src/commands/google.ts b/src/commands/google.ts
index 0394890c6b..4e56f6908a 100644
--- a/src/commands/google.ts
+++ b/src/commands/google.ts
@@ -810,6 +810,9 @@ Subcommands:
--sync-budget-ms <ms> first-sync wall-clock budget
(+ all connect flags above)
status accounts, scopes, refresh probe, linked sources [--json] [--no-probe]
+ attachments backfill --source <id> [--yes] [--limit 1-25] [--retry-failed] [--json]
+ bounded metadata-only repair of imported Gmail; managed persistence required
+ See docs/guides/google-connect.md#attachment-receipts-and-historical-repair
calendars list every calendar the account can read (ids for --calendar-id)
[--account <email>] [--json]
disconnect remove an account's tokens <email> [--purge-client]
@@ -878,6 +881,10 @@ export async function runGoogle(args: string[]): Promise<void> {
}
if (sub === 'connect') return runGoogleConnect(rest);
if (sub === 'status') return runGoogleStatus(rest);
+ if (sub === 'attachments') {
+ const { runGoogleAttachments } = await import('./google-attachments.ts');
+ return runGoogleAttachments(rest);
+ }
if (sub === 'calendars') return runGoogleCalendars(rest);
if (sub === 'disconnect') return runGoogleDisconnect(rest);
if (sub === 'setup') {
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index 3d4f50d6c3..8e96f98d3b 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -29,7 +29,15 @@ import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';
import { embedBackfillLockId, EMBED_BACKFILL_LOCK_TTL_MIN } from '../core/embed-backfill-lock.ts';
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS } from '../core/vector-index.ts';
import { redactPgUrl } from '../core/url-redact.ts';
-import { parsePaceArgs, runEmbedCore, type EmbedResult } from './embed.ts';
+import { runEmbedCore, type EmbedResult, type parsePaceArgs } from './embed.ts';
+import { parseMigrateEmbeddingsFlags } from '../core/embedding-migration-cli.ts';
+export { parseMigrateEmbeddingsFlags, type MigrateEmbeddingsFlags } from '../core/embedding-migration-cli.ts';
+import { prepareEmbeddingProjections } from '../core/embedding-readiness.ts';
+import { assertRetainedEmbeddingRebuildability } from '../core/embedding-migration-retention.ts';
+import { embedStaleFacts } from '../core/embed-facts.ts';
+import { countStaleFactEmbeddings } from '../core/facts/embedding-identity.ts';
+import { authorizeMigrationBudget, assertMigrationLeases } from '../core/embedding-migration-budget.ts';
+import { withAIInvocationGuard } from '../core/ai/invocation-guard.ts';
/**
* Brain-wide migration lock (round-2 #4): serializes whole migrations so two
@@ -39,44 +47,13 @@ import { parsePaceArgs, runEmbedCore, type EmbedResult } from './embed.ts';
*/
export const GLOBAL_MIGRATION_LOCK_ID = 'gbrain-embedding-migration';
-export interface MigrateEmbeddingsFlags {
- to?: string;
- dim?: number;
- yes: boolean;
- dryRun: boolean;
- json: boolean;
- noEmbed: boolean;
- ignoreEnvOverride: boolean;
- retarget: boolean;
- /** auto (default) | off | keep | <provider:model> */
- reranker?: string;
- batchSize?: number;
- pace?: ReturnType<typeof parsePaceArgs>;
-}
-
-export function parseMigrateEmbeddingsFlags(args: string[]): MigrateEmbeddingsFlags {
- const toIdx = args.indexOf('--to');
- const dimIdx = args.indexOf('--dim');
- const dimRaw = dimIdx >= 0 ? parseInt(args[dimIdx + 1] ?? '', 10) : NaN;
- const rrIdx = args.indexOf('--reranker');
- const reranker = rrIdx >= 0 ? args[rrIdx + 1] : undefined;
- const bsIdx = args.indexOf('--batch-size');
- const bsRaw = bsIdx >= 0 ? parseInt(args[bsIdx + 1] ?? '', 10) : NaN;
- const batchSize = Number.isFinite(bsRaw) && bsRaw > 0 ? Math.min(10_000, bsRaw) : undefined;
- return {
- to: toIdx >= 0 ? args[toIdx + 1] : undefined,
- dim: Number.isFinite(dimRaw) && dimRaw > 0 ? dimRaw : undefined,
- yes: args.includes('--yes') || args.includes('--non-interactive'),
- dryRun: args.includes('--dry-run'),
- json: args.includes('--json'),
- noEmbed: args.includes('--no-embed'),
- ignoreEnvOverride: args.includes('--ignore-env-override'),
- retarget: args.includes('--retarget'),
- ...(reranker !== undefined && { reranker }),
- ...(batchSize !== undefined && { batchSize }),
- pace: parsePaceArgs(args),
- };
-}
+export const EMBEDDING_MIGRATION_RECOVERY = {
+ status_command: 'gbrain migrate embeddings --status --json',
+ docs: 'https://github.com/garrytan/gbrain/blob/master/docs/guides/embedding-migration.md#recovery',
+ partial_state: 'Previously committed progress and authorization debits may remain.',
+ action: 'Inspect the selected brain using the same --brain selection before retrying. Do not blindly retry or reset the migration marker.',
+ authorization: 'Increasing --max-cost-usd renews authorization for a larger total cap; it does not reset prior debits.',
+} as const;
function printHelp(): void {
process.stdout.write(`Usage: gbrain migrate embeddings --to <provider:model> [flags]
@@ -84,6 +61,7 @@ function printHelp(): void {
Re-embed the whole brain onto a different embedding provider/model. Handles
dimension changes (schema transition), pages without a recorded embedding
signature (#3391), the query cache, and resume-after-kill.
+This operation is brain-wide: --source and --slugs are unsupported.
Flags:
--to <provider:model> Target embedding model (e.g. openai:text-embedding-3-small).
@@ -91,12 +69,14 @@ Flags:
declared width; required when the recipe declares none.
--dry-run Plan + cost estimate only; change nothing.
--yes Skip the confirm prompt (required non-interactively).
+ --max-cost-usd <USD> Total durable authorization; retries retain debits. Raise explicitly to renew.
--json Machine-readable envelope on stdout.
--no-embed Apply schema + config + invalidation, but skip the
- re-embed pass (run \`gbrain embed --stale --include-null-signature\`
- or \`... --background\` yourself).
- --batch-size <N> Stale-chunk batch size for the re-embed (default 2000).
+ re-embed pass. Inspect --status, then rerun this migration
+ without --no-embed using the same cap; prior debits remain.
+ --batch-size <N> Stale-chunk batch size, integer 1..10000 (default 2000).
--pace[=mode] DB-contention pacing for the re-embed (off|gentle|balanced|aggressive).
+ --pace-max-concurrency <N> Positive integer pacing cap; also accepts =N.
--ignore-env-override Proceed even when GBRAIN_EMBEDDING_* env vars would
override the target at runtime (you know why).
--retarget Abandon a DIFFERENT in-flight migration target and
@@ -115,8 +95,11 @@ Flags:
command, last completion + smoke-check outcome.
--help Show this help.
-A killed run is resumable: re-run the same command. Already-migrated chunks
-are never re-embedded twice.
+A killed run may retain committed progress and debits. Inspect the selected brain
+before resuming: ${EMBEDDING_MIGRATION_RECOVERY.status_command}
+Only documented controls are accepted. --timeout and work/scope restrictions are
+unsupported. Use separate values except for the documented --pace forms and globals.
+Recovery guide: ${EMBEDDING_MIGRATION_RECOVERY.docs}
`);
}
@@ -128,6 +111,8 @@ function renderPlan(ctx: MigrationPlanContext): string {
lines.push(` Brain: ${identity.engine} (${identity.target}); scope: brain-wide (all sources)`);
lines.push(` From: ${plan.from_model} (${plan.from_dims}d${plan.column_dims !== null && plan.column_dims !== plan.from_dims ? `; column is actually ${plan.column_dims}d` : ''})`);
lines.push(` To: ${plan.to_model} (${plan.to_dims}d)`);
+ lines.push(` Work: ${plan.chunks_to_embed} chunks, ${plan.facts_to_embed ?? 0} active facts; ${plan.blocked_projection_pages ?? 0} projection-blocked pages.`);
+ lines.push(' Paid authorization: --max-cost-usd is a durable total cap, conservatively debited before each attempt; unknown prices refuse.');
// DB-reality census: what pages say they were embedded with (env can lie
// about From; the census cannot).
if (plan.signature_census.length > 0) {
@@ -154,7 +139,7 @@ function renderPlan(ctx: MigrationPlanContext): string {
lines.push(' going back to the old provider means paying for a second full re-embed.');
lines.push(' Until the re-embed finishes, semantic search is degraded to lexical-only.');
lines.push(` The query cache and fact embeddings are rebuilt at ${plan.to_dims}d too`);
- lines.push(' (cache refills on next query; facts re-embed on their next write/extract).');
+ lines.push(' (cache refills on next query; active facts are repaired by this migration).');
} else {
// Absent/unreadable column: nothing stored to lose, but the DDL still
// runs — say so instead of silently skipping the warning (dim-honesty).
@@ -293,7 +278,7 @@ export async function probeTargetProvider(
dimensions: toDims,
});
const got = vecs[0]?.length ?? 0;
- if (got !== toDims) {
+ if (vecs.length !== 1 || got !== toDims || !vecs[0].every(Number.isFinite)) {
return {
ok: false,
message: `Target provider returned ${got}-dim vectors, expected ${toDims}. Pass a valid --dim for ${toModel}.`,
@@ -303,7 +288,7 @@ export async function probeTargetProvider(
} catch (e) {
return {
ok: false,
- message: `Preflight embed against ${toModel} failed — nothing was changed:\n ${e instanceof Error ? e.message : String(e)}`,
+ message: `Preflight embed against ${toModel} failed; no migration invalidation performed. Any authorized request debit is retained for safe resume. Check provider configuration and migration status before retrying.`,
};
}
}
@@ -333,7 +318,7 @@ export async function probeTargetReranker(
} catch (e) {
return {
ok: false,
- message: `Reranker probe against ${model} failed: ${e instanceof Error ? e.message : String(e)}`,
+ message: `Reranker probe against ${model} failed. Previous configuration was retained; inspect provider configuration before retrying.`,
};
}
}
@@ -404,6 +389,7 @@ export async function persistEmbeddingFileConfig(
// ============================================================================
export interface MigrationFlowOpts {
+ maxCostUsd?: number;
to: string;
dim?: number;
ignoreEnvOverride?: boolean;
@@ -598,6 +584,27 @@ export async function executeMigrationFlow(
}
const heldLocks: DbLockHandle[] = [globalLock];
+ const controller = new AbortController();
+ let expectedSources: string | undefined;
+ let lost = false;
+ let renewing: Promise<void> | undefined;
+ const assertOwned = async (tx?: BrainEngine) => {
+ if (!tx && renewing) await renewing;
+ if (lost) throw new Error('Migration lock lease lost; durable work retained. Inspect --status before resuming.');
+ if (tx) await assertMigrationLeases(tx, heldLocks);
+ else for (const lock of heldLocks) {
+ if (!await lock.refresh({ signal: AbortSignal.timeout(30_000) })) { lost = true; controller.abort(); throw new Error('Migration lock lease lost; further mutations refused.'); }
+ }
+ if (expectedSources !== undefined) {
+ if (tx) await tx.executeRaw('LOCK TABLE sources IN SHARE MODE');
+ const sources = await (tx ?? engine).executeRaw('SELECT id,incarnation::text,archived FROM sources ORDER BY id');
+ if (JSON.stringify(sources) !== expectedSources) throw new Error('Source census changed (including archive state); migration paused before further work. Inspect --status; use gbrain sources restore <id> deliberately only if restoring an archived source is intended.');
+ }
+ };
+ const heartbeat = setInterval(() => {
+ if (renewing) return;
+ renewing = assertOwned().catch(() => { lost = true; controller.abort(); }).finally(() => { renewing = undefined; });
+ }, 15_000);
try {
// Retarget gate UNDER the global lock (no read-then-write race).
const marker = await readMigrationState(engine);
@@ -615,7 +622,7 @@ export async function executeMigrationFlow(
try {
const rows = await engine.listAllSources({ includeArchived: true });
sourceIds = rows.map((r) => r.id).sort();
- } catch { /* zero sources (empty brain) — global lock alone covers it */ }
+ } catch { return { status: 'apply_failed', reason: 'Source census unavailable; no migration or paid work performed. Restore database access and retry.' }; }
for (const sid of sourceIds) {
let lock: DbLockHandle | null = null;
try {
@@ -633,13 +640,42 @@ export async function executeMigrationFlow(
heldLocks.push(lock);
}
- // Live probe BEFORE any mutation.
+ const lockedCensus = await engine.executeRaw<{ id: string; incarnation: string; archived: boolean }>('SELECT id,incarnation::text,archived FROM sources ORDER BY id');
+ if (JSON.stringify(lockedCensus.map(s => s.id)) !== JSON.stringify(sourceIds)) {
+ return { status: 'apply_failed', reason: 'Source census changed while acquiring locks; no embedding work performed. Retry the scoped preview.' };
+ }
+ expectedSources = JSON.stringify(lockedCensus);
+ await assertOwned();
+ const envWarning = detectEnvOverride(plan.to_model, plan.to_dims);
+ if (envWarning.triggered && !opts.ignoreEnvOverride) return { status: 'refused_env', warning: envWarning };
+ const { loadConfigFileOnly } = await import('../core/config.ts');
+ const runtimeConfig = loadConfigFileOnly();
+ if (!runtimeConfig && !envFullyPinsTarget(plan.to_model, plan.to_dims)) {
+ return { status: 'apply_failed', reason: 'No ~/.gbrain/config.json found — refusing to migrate before invalidation. Initialize the selected brain or persist target model and dimensions in its environment.' };
+ }
+ const disabled = await engine.getConfig('embedding_disabled');
+ if (runtimeConfig?.embedding_disabled || disabled !== null && disabled !== 'false') {
+ return { status: 'apply_failed', reason: 'Embedding is disabled or its policy is invalid; no provider requests or migration invalidation performed. Review the selected brain embedding configuration before retrying.' };
+ }
+ await engine.transaction(async tx => { await assertOwned(tx); await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan); });
+ const debit = await authorizeMigrationBudget(engine, plan, opts.maxCostUsd, heldLocks,
+ ctx.rerankerPlan.action.kind === 'switch' ? ctx.rerankerPlan.action.to : undefined);
+ return await withAIInvocationGuard(async call => {
+ await assertOwned();
+ const permit = await debit(call);
+ return { settle: async usage => { await permit.settle(usage); await assertOwned(); } };
+ }, async () => {
const probe = await probeTargetProvider(plan.to_model, plan.to_dims);
if (!probe.ok) return { status: 'probe_failed', message: probe.message };
+ await assertOwned();
+ const readiness = await prepareEmbeddingProjections(engine, { repair: true, assertOwned });
+ if (readiness.blocked) return { status: 'apply_failed', reason: `projection_blocked: ${readiness.blocked} page(s) remain; no migration-wide embedding invalidation performed. Canonical projection recovery may have made durable progress. Inspect blockers before retrying: archived sources require deliberate gbrain sources restore <id>; unsupported media requires its source importer. See docs/guides/embedding-migration.md#recovery.` };
+
const applied = await applyEmbeddingMigration(engine, plan, {
ignoreEnvOverride: opts.ignoreEnvOverride,
persistConfig: (m, d) => persistEmbeddingFileConfig(m, d),
+ assertOwned,
});
if (applied.status === 'refused') return { status: 'refused_env', warning: applied.warning };
if (applied.status === 'failed') return { status: 'apply_failed', reason: applied.reason };
@@ -652,13 +688,13 @@ export async function executeMigrationFlow(
if (rrAction.kind === 'switch') {
const rrProbe = await probeTargetReranker(rrAction.to);
if (rrProbe.ok) {
- await applyRerankerAction(engine, rrAction);
+ await applyRerankerAction(engine, rrAction, assertOwned);
reranker = { action: 'switched', to: rrAction.to };
} else {
reranker = { action: 'switch_failed', to: rrAction.to, reason: rrProbe.message };
}
} else if (rrAction.kind === 'disable') {
- await applyRerankerAction(engine, rrAction);
+ await applyRerankerAction(engine, rrAction, assertOwned);
reranker = { action: 'disabled' };
} else if (rrAction.suggestion !== null) {
// auto found exposure but the target ships no reranker: never silently
@@ -686,19 +722,46 @@ export async function executeMigrationFlow(
includeNullSignature: true,
quiet: opts.quiet,
heldLocks,
+ assertOwned,
+ signal: controller.signal,
...(opts.batchSize !== undefined && { batchSize: opts.batchSize }),
...(opts.pace && { pace: opts.pace }),
...(opts.onProgress && { onProgress: opts.onProgress }),
});
- const reconciled = await reconcilePageSignatures(engine, plan);
- const remaining = await engine.countStaleChunks({
+ await assertOwned();
+ let embeddedFacts = 0;
+ for (const sourceId of sourceIds) {
+ const [active] = await engine.executeRaw('SELECT id FROM sources WHERE id=$1 AND NOT archived', [sourceId]);
+ if (!active) continue;
+ await assertOwned();
+ const facts = await embedStaleFacts(engine, { sourceId, yes: true, maxCostUsd: opts.maxCostUsd ?? marker.state?.budget?.max_cost_usd ?? 0, maxFacts: 10_000, signal: controller.signal, assertOwned });
+ embeddedFacts += facts.embedded;
+ if (facts.failures) break;
+ }
+ await assertOwned();
+ const reconciled = await engine.transaction(async tx => {
+ await assertOwned(tx);
+ return reconcilePageSignatures(tx, plan);
+ });
+ const remainingChunks = await engine.countStaleChunks({
signature: migrationSignature(plan.to_model, plan.to_dims),
includeNullSignature: true,
});
+ const remainingFacts = await countStaleFactEmbeddings(engine, plan.to_model, plan.to_dims);
+ const finalReadiness = await prepareEmbeddingProjections(engine);
+ const finalSources = (await engine.listAllSources({ includeArchived: true })).map(s => s.id).sort();
+ const sourceChanged = JSON.stringify(sourceIds) !== JSON.stringify(finalSources);
+ const configChanged = await engine.getConfig('embedding_model') !== plan.to_model
+ || Number(await engine.getConfig('embedding_dimensions')) !== plan.to_dims;
+ const chunkless = await engine.countChunklessPagesWithContent();
+ const remaining = remainingChunks + remainingFacts.count + finalReadiness.blocked + chunkless + (sourceChanged || configChanged ? 1 : 0);
const base = {
- embedded: embedResult.embedded,
+ embedded: embedResult.embedded + embeddedFacts,
+ facts_embedded: embeddedFacts,
+ facts_remaining: remainingFacts.count,
+ blocked_projection_pages: finalReadiness.blocked,
signatures_reconciled: reconciled,
invalidated: applied.invalidated,
cache_cleared: applied.cache_cleared,
@@ -711,10 +774,34 @@ export async function executeMigrationFlow(
// outcome is stamped into the completion marker (content-free) so
// `--status` can READ it later without re-spending on live probes.
const verifySearch = await verifySearchRoundTrip(engine, { samples: 3 });
+ await assertOwned();
+ const { loadConfigFileOnly } = await import('../core/config.ts');
+ const file = loadConfigFileOnly();
+ const verified = await verifyMigrationComplete(engine, { toModel: plan.to_model, toDims: plan.to_dims }, {
+ ignoreMarker: true,
+ filePlane: file ? { model: file.embedding_model, dims: file.embedding_dimensions } : null,
+ envMatchesTarget: envFullyPinsTarget(plan.to_model, plan.to_dims), envPresent: detectEnvPresence().present,
+ });
+ if (!verified.complete) return { status: 'incomplete', remaining: Math.max(1,
+ verified.details.stale_wide + (verified.details.stale_facts ?? 0) + (verified.details.blocked_projection_pages ?? 0)), ...base };
+ await assertOwned();
await completeEmbeddingMigration(engine, plan, {
verify_search: { status: verifySearch.status, samples: verifySearch.samples },
...(reranker.action !== 'none' && { reranker }),
...(plan.synopsis_tier_pages > 0 && { context_tier_downgraded_pages: plan.synopsis_tier_pages }),
+ }, async tx => {
+ await assertOwned(tx);
+ await tx.executeRaw('LOCK TABLE pages,content_chunks,facts,config IN SHARE MODE');
+ if (await tx.getConfig('embedding_model') !== plan.to_model
+ || Number(await tx.getConfig('embedding_dimensions')) !== plan.to_dims) {
+ throw new Error('Embedding configuration changed before completion; migration remains resumable.');
+ }
+ const final = await verifyMigrationComplete(tx, { toModel: plan.to_model, toDims: plan.to_dims }, {
+ ignoreMarker: true,
+ filePlane: file ? { model: file.embedding_model, dims: file.embedding_dimensions } : null,
+ envMatchesTarget: envFullyPinsTarget(plan.to_model, plan.to_dims), envPresent: detectEnvPresence().present,
+ });
+ if (!final.complete) throw new Error('Migration work changed before completion; progress retained. Inspect --status and resume.');
});
return { status: 'completed', remaining: 0, verify_search: verifySearch, ...base };
}
@@ -725,7 +812,12 @@ export async function executeMigrationFlow(
...(embedResult.lock_skipped && { lock_skipped: true }),
...(embedResult.lock_lost && { lock_lost: true }),
};
+ });
+ } catch (error) {
+ return { status: 'apply_failed', reason: error instanceof Error ? error.message : 'Migration stopped; inspect --status before resuming.' };
} finally {
+ clearInterval(heartbeat);
+ await renewing;
for (const h of heldLocks.reverse()) {
try { await h.release(); } catch { /* best-effort; TTL is the backstop */ }
}
@@ -746,7 +838,10 @@ export async function runMigrateEmbeddings(
): Promise<void> {
// Explicit `never` annotation so TS control-flow analysis treats every
// exit() call as terminal (required for narrowing after the guard blocks).
- const exit: (code: number) => never = opts.exit ?? ((code: number) => process.exit(code));
+ const exit: (code: number) => never = code => {
+ if (code !== 0) for (const line of Object.values(EMBEDDING_MIGRATION_RECOVERY)) serr(` Recovery: ${line}`);
+ return (opts.exit ?? ((value: number) => process.exit(value)))(code);
+ };
if (args.includes('--help') || args.includes('-h')) {
printHelp();
exit(0);
@@ -802,6 +897,7 @@ export async function runMigrateEmbeddings(
console.log(` DB plane: ${report.db_plane.model ?? '(none)'} @ ${report.db_plane.dims ?? '?'}d`);
console.log(` Column: content_chunks.embedding ${report.column_dims === null ? 'absent/unreadable' : `${report.column_dims}d`}${report.pinned_widths.map((p) => `; ${p.table} ${p.dims === null ? '?' : `${p.dims}d`}`).join('')}`);
console.log(` Vectors: ${report.missing_embeddings ?? '?'} chunk(s) missing; ${report.chunkless_pages ?? '?'} contentful page(s) without chunks; facts pending: ${report.facts_pending ?? 'n/a'}`);
+ console.log(` Projection: ${report.blocked_projection_pages ?? '?'} page(s) blocked; bounded canonical recovery runs before invalidation.`);
if (report.embed_skip_null_chunks !== null && report.embed_skip_null_chunks > 0) {
console.log(` Embed-skip: ${report.embed_skip_null_chunks} chunk(s) on embed_skip pages have NULL vectors — excluded from re-embedding by design (remove the frontmatter marker to re-embed them)`);
}
@@ -818,6 +914,7 @@ export async function runMigrateEmbeddings(
switch (report.marker.kind) {
case 'live': {
const s = report.marker.state;
+ if (s.budget) console.log(` Budget: $${s.budget.debited_usd} conservatively debited of $${s.budget.max_cost_usd} authorized; ${s.budget.requests} dispatched/reserved request(s).`);
console.log(` Migration: IN FLIGHT to ${s.to_model} (${s.to_dims}d), started ${s.started_at}${s.retargeted_at ? `, retargeted ${s.retargeted_at}` : ''}`);
if (s.superseded && s.superseded.length > 0) {
console.log(` abandoned targets: ${s.superseded.map((x) => `${x.to_model} (${x.to_dims}d, started ${x.started_at})`).join('; ')}`);
@@ -870,7 +967,7 @@ export async function runMigrateEmbeddings(
// user to resume it or explicitly abandon it.
if (ctx.inflightOther && !flags.retarget && !flags.dryRun) {
const s = ctx.inflightOther;
- if (flags.json) console.log(JSON.stringify({ status: 'refused', reason: 'retarget_required', inflight: s, plan }, null, 2));
+ if (flags.json) console.log(JSON.stringify({ status: 'refused', reason: 'retarget_required', inflight: s, plan, recovery: EMBEDDING_MIGRATION_RECOVERY }, null, 2));
printRetargetRefusal(s);
exit(1);
}
@@ -912,7 +1009,7 @@ export async function runMigrateEmbeddings(
}
const confirm = opts.confirm ?? defaultConfirm;
const priceNote = plan.price_known ? `~$${plan.est_cost_usd.toFixed(2)}` : 'an UNKNOWN amount';
- const ok = await confirm(`Re-embed ${plan.chunks_to_embed} chunks (${priceNote})?`);
+ const ok = await confirm(`Re-embed ${plan.chunks_to_embed} chunks and ${plan.facts_to_embed ?? 0} facts (${priceNote}) with total authorization ${flags.maxCostUsd === undefined ? 'retained from the existing run (required for new work)' : `$${flags.maxCostUsd}`}?`);
if (!ok) {
serr('Aborted. Nothing was changed.');
exit(1);
@@ -932,6 +1029,7 @@ export async function runMigrateEmbeddings(
retarget: flags.retarget,
...(flags.reranker !== undefined && { reranker: flags.reranker }),
noEmbed: flags.noEmbed,
+ maxCostUsd: flags.maxCostUsd,
quiet: flags.json,
...(flags.batchSize !== undefined && { batchSize: flags.batchSize }),
...(flags.pace && { pace: flags.pace }),
@@ -948,7 +1046,9 @@ export async function runMigrateEmbeddings(
// Refusals normalize to the op-envelope shape ({status:'refused', reason})
// in their own cases below; everything else gets the generic envelope.
if (flags.json && result.status !== 'refused_env' && result.status !== 'refused_retarget') {
- console.log(JSON.stringify({ ...result, plan }, null, 2));
+ console.log(JSON.stringify({ ...result, plan,
+ ...(result.status !== 'completed' && result.status !== 'applied_no_embed' && { recovery: EMBEDDING_MIGRATION_RECOVERY }),
+ }, null, 2));
}
switch (result.status) {
@@ -965,7 +1065,7 @@ export async function runMigrateEmbeddings(
}
case 'refused_retarget': {
if (flags.json) {
- console.log(JSON.stringify({ status: 'refused', reason: 'retarget_required', inflight: result.inflight, plan }, null, 2));
+ console.log(JSON.stringify({ status: 'refused', reason: 'retarget_required', inflight: result.inflight, plan, recovery: EMBEDDING_MIGRATION_RECOVERY }, null, 2));
} else {
printRetargetRefusal(result.inflight);
}
@@ -974,7 +1074,7 @@ export async function runMigrateEmbeddings(
}
case 'refused_env': {
if (flags.json) {
- console.log(JSON.stringify({ status: 'refused', reason: 'env_override', warning: result.warning, plan }, null, 2));
+ console.log(JSON.stringify({ status: 'refused', reason: 'env_override', warning: result.warning, plan, recovery: EMBEDDING_MIGRATION_RECOVERY }, null, 2));
} else {
serr(formatEnvOverrideWarning(result.warning));
}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index ac4a258c0b..e684503036 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -4364,7 +4364,9 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
};
try {
const transport: RerankTransport = _rerankTransport ?? ((u, init) => fetch(u, init));
- const resp = await invokeAI({ operation: 'gateway.rerank', kind: 'rerank', model: modelStr }, () => transport(url, {
+ const maxInputTokens = input.documents.reduce((sum, document) =>
+ sum + Buffer.byteLength(input.query, 'utf8') + Buffer.byteLength(document, 'utf8'), 0);
+ const resp = await invokeAI({ operation: 'gateway.rerank', kind: 'rerank', model: modelStr, maxInputTokens }, () => transport(url, {
method: 'POST',
headers,
body,
diff --git a/src/core/ai/invocation-guard.ts b/src/core/ai/invocation-guard.ts
index bc246b2a82..2142a74747 100644
--- a/src/core/ai/invocation-guard.ts
+++ b/src/core/ai/invocation-guard.ts
@@ -25,8 +25,16 @@ export function isAIInvocationPolicyError(error: unknown): boolean {
}
/** Isolated to this async job; concurrent local work never inherits its owner. */
-export function withAIInvocationGuard<T>(guard: AIInvocationGuard, run: () => Promise<T>): Promise<T> {
- return guards.run(guard, run);
+export function withAIInvocationGuard<T>(guard: AIInvocationGuard, run: () => Promise<T>, opts: { inherit?: boolean } = {}): Promise<T> {
+ const parent = opts.inherit ? guards.getStore() : undefined;
+ if (!parent) return guards.run(guard, run);
+ return guards.run(async call => {
+ const outer = await parent(call);
+ let inner: AIInvocationPermit;
+ try { inner = await guard(call); }
+ catch (error) { await outer.settle(null); throw error; }
+ return { settle: async usage => { await outer.settle(usage); await inner.settle(usage); } };
+ }, run);
}
export function withAIInvocationPreflight<T>(preflight: (call: AIInvocation) => Promise<void>, run: () => Promise<T>): Promise<T> {
const parent = guards.getStore();
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index ae6a9fd878..a51fd7bd31 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -61,7 +61,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],
- 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via'],
+ 'google': ['--access', '--account', '--allow-create-db', '--allow-docker', '--brain', '--calendar-id', '--chat-model', '--client-id', '--client-json', '--client-secret', '--code', '--consent-state', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--history-days', '--http', '--issuer-url', '--json', '--key', '--kind', '--limit', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-browser', '--no-embedding', '--no-git', '--no-probe', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--paste', '--path', '--pglite', '--port', '--prefer-postgres', '--provenance', '--purge-client', '--reauth', '--retry-failed', '--schema-pack', '--scopes', '--services', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--sync-budget-ms', '--timeout-ms', '--to', '--token-command', '--url', '--version', '--via', '--yes'],
'graph-query': ['--brain', '--depth', '--direction', '--help', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--exclude-standard', '--get', '--harness', '--help', '--jq', '--json', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--session', '--show-current', '--show-toplevel', '--source'],
'import': ['--allow-empty', '--allow-noncanonical-root', '--background', '--brain', '--cached', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--fresh', '--help', '--include-gitignored', '--json', '--log-noop', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-verify', '--others', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--workers'],
@@ -72,9 +72,9 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],
'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
- 'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
+ 'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
@@ -99,7 +99,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-verify', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
- 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],
+ 'retrieval-upgrade': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 2b215e12c1..5cd40778b8 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -71,7 +71,7 @@ import {
emptyPhantomPassResult,
type PhantomPassResult,
} from './phantom-redirect.ts';
-import { embed, isAvailable } from '../ai/gateway.ts';
+import { embed, getEmbeddingDimensions, getEmbeddingModel, isAvailable } from '../ai/gateway.ts';
import { isAborted } from '../abort-check.ts';
import { parseMarkdown } from '../markdown.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
@@ -791,15 +791,18 @@ export async function runExtractFacts(
if (isAvailable('embedding')) {
try {
const texts = toInsert.map(e => e.fact);
+ const embeddingModel = getEmbeddingModel();
+ const dimensions = getEmbeddingDimensions();
// #1972: forward the abort signal so a cancelled cycle's in-flight
// batch embed (a network call) is itself abortable, not just the loop.
- const embeddings = await embed(texts, { abortSignal: opts.signal });
+ const embeddings = await embed(texts, { abortSignal: opts.signal, embeddingModel, dimensions, inputType: 'document' });
if (embeddings.length !== toInsert.length || embeddings.some(vector =>
- !vector?.length || !vector.every(Number.isFinite))) {
+ vector?.length !== dimensions || !vector.every(Number.isFinite))) {
throw new Error('embedding provider returned an incomplete or invalid fact batch');
}
for (let i = 0; i < toInsert.length; i++) {
toInsert[i].embedding = embeddings[i];
+ toInsert[i].embedding_model = embeddingModel;
}
} catch (err) {
// Embedding failure is non-fatal — facts still get inserted, just
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index 9dd7192724..c2bbbd5a91 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -25,6 +25,7 @@
import type { BrainEngine, FactRow } from '../../engine.ts';
import type { PhaseResult } from '../../cycle.ts';
import { cosineSimilarity } from '../../facts/classify.ts';
+import { createHash } from 'node:crypto';
import { isAborted } from '../../abort-check.ts';
import { maintenancePreflight, submitMaintenanceConsolidation } from '../../persistence/prepared-maintenance.ts';
import { managedPersistenceEnabled } from '../../persistence/ownership.ts';
@@ -329,14 +330,16 @@ function clusterFacts(facts: FactRow[], threshold: number): FactRow[][] {
const sorted = [...facts].sort((a, b) => b.valid_from.getTime() - a.valid_from.getTime());
const clusters: FactRow[][] = [];
for (const f of sorted) {
- if (!f.embedding) {
+ if (!f.embedding || !f.embedding_model || f.embedded_text_hash !== createHash('md5').update(f.fact).digest('hex')) {
clusters.push([f]);
continue;
}
let placed = false;
for (const c of clusters) {
const head = c[0];
- if (!head.embedding) continue;
+ if (!head.embedding || f.embedding_model !== head.embedding_model
+ || head.embedded_text_hash !== createHash('md5').update(head.fact).digest('hex')
+ || f.embedding.length !== head.embedding.length) continue;
if (cosineSimilarity(f.embedding, head.embedding) >= threshold) {
c.push(f);
placed = true;
diff --git a/src/core/embed-facts.ts b/src/core/embed-facts.ts
index 2039a5684b..4313031e51 100644
--- a/src/core/embed-facts.ts
+++ b/src/core/embed-facts.ts
@@ -15,9 +15,11 @@ import { validateEmbedFactsOptions, type EmbedFactsOptions } from './embed-facts
import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';
import { resolveMaxChunkTokens } from './embedding-input-limit.ts';
import { estimateTokens } from './chunkers/token-estimate.ts';
+import { eligibleFactEmbedding, staleFactEmbedding } from './facts/embedding-identity.ts';
export interface EmbedFactsOpts extends EmbedFactsOptions {
signal?: AbortSignal;
+ assertOwned?: (tx: BrainEngine) => Promise<void>;
}
export interface EmbedFactsResult {
@@ -41,16 +43,11 @@ interface PendingFact {
version: string;
}
-const eligible = `f.source_id = $1 AND f.embedding IS NULL AND f.expired_at IS NULL
- AND f.superseded_by IS NULL AND NOT (f.source = ANY($2::text[]))
- AND NOT EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id
- AND w.visibility=f.visibility AND w.fact_hash=gbrain_fact_fingerprint(f.fact))
- AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=f.source_id
- AND p.slug=f.source_markdown_slug AND p.deleted_at IS NOT NULL)`;
+const eligible = `f.source_id = $1 AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}`;
export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts, selectedConfig: GBrainConfig | null = null): Promise<EmbedFactsResult> {
- const { signal: externalSignal, ...wireOptions } = opts;
- opts = { ...validateEmbedFactsOptions(wireOptions), signal: externalSignal };
+ const { signal: externalSignal, assertOwned, ...wireOptions } = opts;
+ opts = { ...validateEmbedFactsOptions(wireOptions), signal: externalSignal, assertOwned };
const maxFacts = opts.maxFacts ?? 100;
const batchSize = opts.batchSize ?? 100;
const budgetMs = opts.budgetMs ?? 60_000;
@@ -74,7 +71,9 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
if (row?.unrestricted_slugs !== true) throw new OperationError('permission_denied', 'Fact backfill requires a current source-wide CLI grant');
};
await authorize(engine);
- const params = [opts.sourceId, [...AUDIT_ROW_SOURCES]];
+ const model = getEmbeddingModel();
+ const dims = getEmbeddingDimensions();
+ const params = [opts.sourceId, [...AUDIT_ROW_SOURCES], model, dims];
const census = async () => {
const [row] = await engine.executeRaw<{ count: string; last_id: string }>(
`SELECT count(*)::text AS count, COALESCE(max(f.id),0)::text AS last_id FROM facts f WHERE ${eligible}`, params);
@@ -97,8 +96,6 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
assertEmbeddingEnabled({ embedding_disabled: disabled === 'true' });
};
await assertEnabled(engine);
- const model = getEmbeddingModel();
- const dims = getEmbeddingDimensions();
const shape = await readFactsEmbeddingDim(engine);
if (!shape.exists || shape.dims !== dims || !shape.columnType) {
throw new Error('Facts embedding dimensions differ from the configured model; inspect migrate embeddings --status first');
@@ -121,8 +118,8 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
if (signal.aborted) { result.stopped = 'aborted'; result.failures++; break; }
const batch = await engine.executeRaw<PendingFact>(
`SELECT f.id::text, f.fact, f.xmin::text AS version FROM facts f
- WHERE ${eligible} AND f.id > $3::bigint AND f.id <= $4::bigint
- ORDER BY f.id LIMIT $5`, [...params, afterId, initial.lastId, Math.min(batchSize, maxFacts - result.attempted)]);
+ WHERE ${eligible} AND f.id > $5::bigint AND f.id <= $6::bigint
+ ORDER BY f.id LIMIT $7`, [...params, afterId, initial.lastId, Math.min(batchSize, maxFacts - result.attempted)]);
if (!batch.length) break;
result.attempted += batch.length;
try {
@@ -148,14 +145,15 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
tracker.record({ modelId: call.model, kind: 'embed', inputTokens: usage?.inputTokens ?? inputCeiling, outputTokens: 0 });
} };
}, () => embed(batch.map(row => row.fact), {
- abortSignal: signal, embeddingModel: model, dimensions: dims,
- }));
+ abortSignal: signal, embeddingModel: model, dimensions: dims, inputType: 'document',
+ }), { inherit: true });
signal.throwIfAborted();
if (vectors.length !== batch.length || vectors.some(vector =>
vector.length !== dims || !vector.every(Number.isFinite))) {
throw new Error('Embedding provider returned an incomplete or invalid fact batch');
}
const installed = await engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
const current = await tx.executeRaw('SELECT id FROM sources WHERE id=$1 AND incarnation=$2::uuid AND archived=false FOR SHARE',
[opts.sourceId, source.incarnation]);
if (!current.length) throw new Error('Source identity changed during fact backfill; rerun the scoped preview');
@@ -169,8 +167,9 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
for (let i = 0; i < batch.length; i++) {
signal.throwIfAborted();
const rows = await tx.executeRaw(
- `UPDATE facts f SET embedding=$5::${shape.columnType}, embedded_at=now()
- WHERE ${eligible} AND f.id=$3::bigint AND f.xmin::text=$4 RETURNING f.id::text`,
+ `UPDATE facts f SET embedding=$7::${shape.columnType}, embedded_at=now(),
+ embedding_model=$3,embedded_text_hash=md5(f.fact)
+ WHERE ${eligible} AND f.id=$5::bigint AND f.xmin::text=$6 RETURNING f.id::text`,
[...params, batch[i].id, batch[i].version, `[${Array.from(vectors[i]).join(',')}]`]);
count += rows.length;
}
diff --git a/src/core/embed-oversize-heal.ts b/src/core/embed-oversize-heal.ts
index ea34a16444..d69bc2e8f3 100644
--- a/src/core/embed-oversize-heal.ts
+++ b/src/core/embed-oversize-heal.ts
@@ -179,7 +179,7 @@ export async function healOversizedPageChunks(
): Promise<{ changed: boolean; splitCount: number; chunks: Chunk[] }> {
const sourceId = opts.sourceId ?? 'default';
const getOpts = { sourceId };
- const prepared = await readProjectionSnapshot(engine, slug, sourceId, { maxChunkTokens: opts.maxTokens });
+ const prepared = await readProjectionSnapshot(engine, slug, sourceId, { maxChunkTokens: opts.maxTokens, requireLiveSource: true });
if (!prepared) return { changed: false, splitCount: 0, chunks: [] };
const existing = prepared.chunks;
const healed = healOversizedChunks(existing, prepared.maxChunkTokens);
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index da6734752a..3f29dd412e 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -1,4 +1,6 @@
import { readProjectionSnapshot, installPageEmbeddings } from './page-state/projections.ts';
+import { prepareEmbeddingProjections, countArchivedEmbeddingWork } from './embedding-readiness.ts';
+import { readContentChunksEmbeddingDim } from './embedding-dim-check.ts';
/**
* Stale-chunk embedding loop, extracted from `src/commands/embed.ts:embedAllStale`
* for reuse by the v0.40 `embed-backfill` Minion handler (D15.2 — codex
@@ -78,6 +80,8 @@ export interface EmbedStaleOpts {
cursor?: StaleCursor;
/** AbortSignal honored at three sites: batch claim, retry sleep, HTTP body. */
signal?: AbortSignal;
+ deadline?: number;
+ assertOwned?: (tx?: BrainEngine) => Promise<void>;
/**
* Fired once per batch with the cursor after that batch finishes. Caller
* uses this for crash-resumable progress (Minion `job.updateProgress`).
@@ -113,6 +117,10 @@ export interface EmbedStaleOpts {
}
export interface EmbedStaleResult {
+ blocked?: number;
+ remaining?: number;
+ failures?: number;
+ complete?: boolean;
/** Chunks newly embedded in this call. */
embedded: number;
/** Total chunks pulled across all batches (including ones that errored). */
@@ -184,7 +192,8 @@ export async function stampIfPageProvenanceComplete(
`SELECT count(*) > 0
AND bool_and(${currentSpaceChunkPredicate(colId, 1, 4)}) AS complete
FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
- WHERE p.slug = $2 AND p.source_id = $3 AND p.text_projection_revision=p.knowledge_revision`,
+ WHERE p.slug = $2 AND p.source_id = $3 AND p.text_projection_revision=p.knowledge_revision
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)`,
[model, slug, sourceId, dims],
);
if (rows[0]?.complete !== true) return false;
@@ -215,7 +224,7 @@ export async function probeEmbedder(
try {
const vecs = await embedFn([EMBED_PROBE_TEXT], { abortSignal: signal });
const vec = vecs?.[0];
- if (!vec || vec.length === 0) return false;
+ if (vecs.length !== 1 || !vec || vec.length === 0 || !vec.every(Number.isFinite)) return false;
const dims = signature ? Number(signature.split(':').pop()) : NaN;
if (Number.isFinite(dims) && dims > 0 && vec.length !== dims) return false;
return true;
@@ -284,7 +293,7 @@ export async function embedStalePages(
// SUP-3874: split legacy oversized rows before embedding so a single
// pre-cap chunk cannot permanently fail the page.
await healOversizedPageChunks(engine, slug, { sourceId });
- const prepared = await readProjectionSnapshot(engine, slug, sourceId);
+ const prepared = await readProjectionSnapshot(engine, slug, sourceId, { requireLiveSource: true });
if (!prepared) continue;
const existing = prepared.chunks;
const staleIdx = new Set(
@@ -360,7 +369,35 @@ export async function embedStaleForSource(
aborted: false,
};
const signature = opts.embeddingSignature;
+ const stopped = () => !!signal?.aborted || Date.now() >= (opts.deadline ?? Infinity);
+ if (stopped()) return { ...result, aborted: true };
+ await opts.assertOwned?.();
+ if (stopped()) return { ...result, aborted: true };
+ const archivedWork = await countArchivedEmbeddingWork(engine, { sourceId, signature });
+ if (archivedWork) return { ...result, blocked: archivedWork, failures: archivedWork, complete: false, done: true,
+ remaining: await engine.countStaleChunks({ sourceId, ...(signature && { signature }) }) };
+ const readinessOptions = { sourceId, existingChunksOnly: true, activeSourcesOnly: true, stale: { signature }, signal,
+ deadline: opts.deadline, assertOwned: opts.assertOwned };
+ let readiness = await prepareEmbeddingProjections(engine, readinessOptions);
+ if (stopped()) return { ...result, aborted: true };
+ if (readiness.blocked) {
+ await opts.assertOwned?.();
+ if (stopped()) return { ...result, aborted: true };
+ const probeOk = await probeEmbedder(embedFn, signature, signal);
+ if (stopped()) return { ...result, aborted: true };
+ await opts.assertOwned?.();
+ if (!probeOk) {
+ return { ...result, blocked: readiness.blocked, complete: false, done: true,
+ remaining: await engine.countStaleChunks({ sourceId }), invalidationSkipped: 'embedder_probe_failed' };
+ }
+ readiness = await prepareEmbeddingProjections(engine, { ...readinessOptions, repair: true });
+ if (stopped()) return { ...result, aborted: true };
+ }
+ if (readiness.blocked) return { ...result, blocked: readiness.blocked, complete: false, done: true,
+ remaining: await engine.countStaleChunks({ sourceId, ...(signature && { signature }) }) };
const stamp = await resolveProvenanceStamp(engine, signature); // column resolved once per drain, not per page
+ if (stopped()) return { ...result, aborted: true };
+ await opts.assertOwned?.();
// v0.41.31: invalidate embeddings stamped under a prior model signature so
// the NULL cursor below re-embeds them. GRANDFATHER: NULL signature
@@ -376,10 +413,22 @@ export async function embedStaleForSource(
const wide = await engine.countStaleChunks({ sourceId, signature });
const nullOnly = await engine.countStaleChunks({ sourceId });
if (wide - nullOnly > 0) {
- if (await probeEmbedder(embedFn, signature, signal)) {
+ await opts.assertOwned?.();
+ if (stopped()) return { ...result, aborted: true };
+ const probeOk = await probeEmbedder(embedFn, signature, signal);
+ if (stopped()) return { ...result, aborted: true };
+ await opts.assertOwned?.();
+ if (probeOk) {
// #4306: guarded wrapper — never NULL embed_skip pages the stale
// selectors below can't re-embed.
- result.invalidated += await invalidateStaleSignatureEmbeddingsGuarded(engine, { signature, sourceId });
+ result.invalidated += opts.assertOwned ? await engine.transaction(async tx => {
+ await opts.assertOwned!(tx);
+ if (stopped()) throw new AbortError();
+ const invalidated = await invalidateStaleSignatureEmbeddingsGuarded(tx, { signature, sourceId });
+ await opts.assertOwned!(tx);
+ if (stopped()) throw new AbortError();
+ return invalidated;
+ }) : await invalidateStaleSignatureEmbeddingsGuarded(engine, { signature, sourceId });
} else {
result.invalidationSkipped = 'embedder_probe_failed';
process.stderr.write(
@@ -389,6 +438,8 @@ export async function embedStaleForSource(
}
}
} catch {
+ if (stopped()) return { ...result, aborted: true };
+ await opts.assertOwned?.();
// Non-fatal: fall through to the NULL-only stale loop.
}
}
@@ -400,13 +451,23 @@ export async function embedStaleForSource(
// drift) and those vectors point at stale text either way. NULL hash
// (pre-v133 rows) is grandfathered.
try {
- result.invalidated += await engine.invalidateContentDriftEmbeddings({ sourceId });
+ if (stopped()) return { ...result, aborted: true };
+ result.invalidated += opts.assertOwned ? await engine.transaction(async tx => {
+ await opts.assertOwned!(tx);
+ if (stopped()) throw new AbortError();
+ const invalidated = await tx.invalidateContentDriftEmbeddings({ sourceId });
+ await opts.assertOwned!(tx);
+ if (stopped()) throw new AbortError();
+ return invalidated;
+ }) : await engine.invalidateContentDriftEmbeddings({ sourceId });
} catch {
+ if (stopped()) return { ...result, aborted: true };
+ await opts.assertOwned?.();
// Non-fatal: fall through to the NULL-only stale loop.
}
for (;;) {
- if (signal?.aborted) {
+ if (stopped()) {
result.aborted = true;
return result;
}
@@ -420,6 +481,13 @@ export async function embedStaleForSource(
}),
);
if (batch.length === 0) {
+ const blocked = await countArchivedEmbeddingWork(engine, { sourceId, signature });
+ if (blocked) { result.blocked = blocked; result.failures = (result.failures ?? 0) + blocked; }
+ const remaining = await engine.countStaleChunks({ sourceId, ...(signature && { signature }) });
+ if (remaining || result.chunksProcessed || result.blocked) {
+ result.remaining = remaining;
+ result.complete = remaining === 0 && !result.blocked;
+ }
result.done = true;
return result;
}
@@ -450,10 +518,17 @@ export async function embedStaleForSource(
const keySourceId = stale[0]?.source_id ?? sourceId;
const slug = stale[0].slug;
try {
+ await opts.assertOwned?.();
+ if (stopped()) return;
// SUP-3874: split legacy oversized chunk_text before embedding.
- const healed = await observed(pacer, () =>
- healOversizedPageChunks(engine, slug, { sourceId: keySourceId }),
- );
+ const healed = await observed(pacer, () => engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
+ if (stopped()) throw new AbortError();
+ const healed = await healOversizedPageChunks(tx, slug, { sourceId: keySourceId });
+ await opts.assertOwned?.(tx);
+ if (stopped()) throw new AbortError();
+ return healed;
+ }));
if (healed.changed) {
stale = healedChunksToStaleRows(healed.chunks, slug, keySourceId);
if (stale.length === 0) {
@@ -466,7 +541,7 @@ export async function embedStaleForSource(
// re-embed reproduces the page's wrapping convention instead of
// silently stripping contextual prefixes (mirrors
// src/commands/embed.ts:embedAllStale).
- const prepared = await observed(pacer, () => readProjectionSnapshot(engine, slug, keySourceId));
+ const prepared = await observed(pacer, () => readProjectionSnapshot(engine, slug, keySourceId, { requireLiveSource: true }));
if (!prepared) return;
const selected = new Map(stale.map(c => [c.chunk_index, c]));
const existing = prepared.chunks;
@@ -474,7 +549,15 @@ export async function embedStaleForSource(
.map(c => ({ ...selected.get(c.chunk_index)!, ...c }));
if (!stale.length) return;
const pageRow = prepared.snapshot.page;
+ await opts.assertOwned?.();
+ if (stopped()) return;
const embeddings = await embedFn(wrapChunkTextsForStoredMode(pageRow, stale), { abortSignal: signal });
+ if (stopped()) return;
+ const dimensions = signature ? splitEmbeddingSignature(signature).dims
+ : prepared.embeddingColumn.name === 'embedding' ? (await readContentChunksEmbeddingDim(engine)).dims : prepared.embeddingColumn.dimensions;
+ if (embeddings.length !== stale.length || embeddings.some(v => !v || v.length !== dimensions || !v.every(Number.isFinite))) {
+ throw new Error('Embedding provider returned an incomplete or invalid batch');
+ }
const staleIdxToEmbedding = new Map<number, Float32Array>();
for (let j = 0; j < stale.length; j++) {
@@ -490,16 +573,22 @@ export async function embedStaleForSource(
// The keyset's last batch stamps complete DB provenance (#4825),
// with context demotion in the same transaction as its vector writes.
if (!await observed(pacer, () => engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
+ if (stopped()) throw new AbortError();
if (!await installPageEmbeddings(tx, prepared, merged)) return false;
if (stamp) await stampIfPageProvenanceComplete(tx, slug, keySourceId, stamp);
if (stale.length === existing.length) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, keySourceId);
+ await opts.assertOwned?.(tx);
+ if (stopped()) throw new AbortError();
return true;
}))) return;
result.embedded += stale.length;
result.pagesProcessed += 1;
} catch (e: unknown) {
+ result.failures = (result.failures ?? 0) + stale.length;
// Aborted mid-fetch is expected; treat as graceful exit.
- if (signal?.aborted) return;
+ if (stopped()) return;
+ await opts.assertOwned?.();
// Otherwise log and skip — the chunk stays NULL and next call retries.
process.stderr.write(
`\n [embed-stale] error on ${keySourceId}/${slug}: ${
@@ -510,7 +599,7 @@ export async function embedStaleForSource(
}
async function worker(): Promise<void> {
- while (nextIdx < keys.length && !signal?.aborted) {
+ while (nextIdx < keys.length && !stopped()) {
const idx = nextIdx++;
await embedOneKey(keys[idx]);
// Cooperative DB-contention pace between keys (no-op when unpaced).
@@ -527,6 +616,7 @@ export async function embedStaleForSource(
const numWorkers = Math.min(concurrency, keys.length);
await Promise.all(Array.from({ length: numWorkers }, () => worker()));
+ if (stopped()) return { ...result, aborted: true };
if (opts.onProgress) {
opts.onProgress({
@@ -538,6 +628,10 @@ export async function embedStaleForSource(
// Short batch = end of stale set; advance and exit.
if (batch.length < batchSize) {
+ const blocked = await countArchivedEmbeddingWork(engine, { sourceId, signature });
+ if (blocked) { result.blocked = blocked; result.failures = (result.failures ?? 0) + blocked; }
+ result.remaining = await engine.countStaleChunks({ sourceId, ...(signature && { signature }) });
+ result.complete = result.remaining === 0 && !result.blocked;
result.done = true;
return result;
}
diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.ts
index cd91b59863..bf7bdf4485 100644
--- a/src/core/embedding-invalidation.ts
+++ b/src/core/embedding-invalidation.ts
@@ -49,6 +49,11 @@ export function currentSpaceChunkPredicate(colId: string, modelParam: number, di
AND vector_dims(cc.${colId}) = $${dimsParam}::int, false)`;
}
+export async function lockEmbeddingSources(tx: Pick<BrainEngine, 'executeRaw'>, sourceId?: string): Promise<string[]> {
+ const rows = await tx.executeRaw<{ id: string }>('SELECT id FROM sources WHERE ($1::text IS NULL OR id=$1) AND NOT archived ORDER BY id FOR SHARE', [sourceId ?? null]);
+ return rows.map(row => row.id);
+}
+
/**
* `<provider:model>:<dims>` — the one-line shape of
* embedding-migration.ts:migrationSignature, duplicated here so this module
@@ -80,16 +85,16 @@ async function activeColId(engine: Pick<BrainEngine, 'executeRaw'>): Promise<str
* match the selectors (#4306). $1 = target signature, $2 = target model.
* `colId` = registry-active embedding column identifier (S2).
*/
-function falseStampPageWhere(colId: string): string {
+export function falseStampPageWhere(colId: string, signatureParam = 1, modelParam = 2): string {
return `
- p.embedding_signature = $1
+ p.embedding_signature = $${signatureParam}
AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND EXISTS (
SELECT 1 FROM content_chunks c
WHERE c.page_id = p.id AND c.${colId} IS NOT NULL
- AND c.model IS NOT NULL AND c.model <> $2
- AND c.model <> substr($2, strpos($2, ':') + 1)
+ AND c.model IS NOT NULL AND c.model <> $${modelParam}
+ AND c.model <> substr($${modelParam}, strpos($${modelParam}, ':') + 1)
)`;
}
@@ -130,63 +135,71 @@ export async function countFalseStampedChunks(
* Returns the number of pages cleared.
*/
export async function clearFalseStampedSignatures(
- engine: Pick<BrainEngine, 'executeRaw'>,
+ engine: BrainEngine,
toModel: string,
toDims: number,
): Promise<number> {
- const colId = await activeColId(engine);
- const rows = await engine.executeRaw<{ id: number }>(
- `UPDATE pages p SET embedding_signature = NULL
- WHERE ${falseStampPageWhere(colId)}
- RETURNING p.id`,
- [targetSignature(toModel, toDims), toModel],
- );
- return (rows as unknown[]).length;
+ return engine.transaction(async tx => {
+ const sources = await lockEmbeddingSources(tx);
+ const colId = await activeColId(tx);
+ const rows = await tx.executeRaw<{ id: number }>(
+ `UPDATE pages p SET embedding_signature = NULL
+ WHERE ${falseStampPageWhere(colId)}
+ AND p.source_id=ANY($3::text[])
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ RETURNING p.id`,
+ [targetSignature(toModel, toDims), toModel, sources],
+ );
+ return (rows as unknown[]).length;
+ });
}
export async function invalidateStaleSignatureEmbeddingsGuarded(
- engine: Pick<BrainEngine, 'executeRaw'>,
+ engine: BrainEngine,
opts: { signature: string; sourceId?: string; includeNullSignature?: boolean },
): Promise<number> {
- const colId = await activeColId(engine);
- const { model, dims } = splitEmbeddingSignature(opts.signature);
- const params: unknown[] = [opts.signature, model, dims];
- const currentChunk = currentSpaceChunkPredicate(colId, 2, 3);
- let srcClause = '';
- if (opts.sourceId !== undefined) {
- params.push(opts.sourceId);
- srcClause = ` AND p.source_id = $${params.length}`;
- }
- // Mirrors the engine method's clauses (NULL-signature grandfather lifted by
- // includeNullSignature, #3391); the embed_skip predicate matches
- // buildStaleChunkWhere exactly.
- const sigClause = opts.includeNullSignature
- ? `(p.embedding_signature IS NULL OR p.embedding_signature <> $1)`
- : `p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1`;
- const rows = await engine.executeRaw<{ page_id: number }>(
- `UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL
- FROM pages p
- WHERE cc.page_id = p.id
- AND cc.${colId} IS NOT NULL
- AND NOT ${currentChunk}
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
- AND ${sigClause}${srcClause}
- RETURNING cc.page_id`,
- params,
- );
- await engine.executeRaw(
- `UPDATE pages p SET embedding_signature = $1
- WHERE ${sigClause}${srcClause}
- AND p.deleted_at IS NULL
- AND p.text_projection_revision = p.knowledge_revision
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
- AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
- AND NOT EXISTS (
- SELECT 1 FROM content_chunks cc
- WHERE cc.page_id = p.id AND NOT ${currentChunk}
- )`,
- params,
- );
- return (rows as unknown[]).length;
+ return engine.transaction(async tx => {
+ const sources = await lockEmbeddingSources(tx, opts.sourceId);
+ const colId = await activeColId(tx);
+ const { model, dims } = splitEmbeddingSignature(opts.signature);
+ const params: unknown[] = [opts.signature, model, dims, sources];
+ const currentChunk = currentSpaceChunkPredicate(colId, 2, 3);
+ const srcClause = ' AND p.source_id=ANY($4::text[])';
+ // Mirrors the engine method's clauses (NULL-signature grandfather lifted by
+ // includeNullSignature, #3391); the embed_skip predicate matches
+ // buildStaleChunkWhere exactly.
+ const sigClause = opts.includeNullSignature
+ ? `(p.embedding_signature IS NULL OR p.embedding_signature <> $1)`
+ : `p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1`;
+ const rows = await tx.executeRaw<{ page_id: number }>(
+ `UPDATE content_chunks cc
+ SET ${colId} = NULL, embedded_at = NULL
+ FROM pages p
+ WHERE cc.page_id = p.id
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND cc.${colId} IS NOT NULL
+ AND NOT ${currentChunk}
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND p.deleted_at IS NULL
+ AND p.text_projection_revision = p.knowledge_revision
+ AND ${sigClause}${srcClause}
+ RETURNING cc.page_id`,
+ params,
+ );
+ await tx.executeRaw(
+ `UPDATE pages p SET embedding_signature = $1
+ WHERE ${sigClause}${srcClause}
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND p.deleted_at IS NULL
+ AND p.text_projection_revision = p.knowledge_revision
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
+ AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
+ AND NOT EXISTS (
+ SELECT 1 FROM content_chunks cc
+ WHERE cc.page_id = p.id AND NOT ${currentChunk}
+ )`,
+ params,
+ );
+ return (rows as unknown[]).length;
+ });
}
diff --git a/src/core/embedding-migration-budget.ts b/src/core/embedding-migration-budget.ts
new file mode 100644
index 0000000000..2f002dda01
--- /dev/null
+++ b/src/core/embedding-migration-budget.ts
@@ -0,0 +1,73 @@
+import type { BrainEngine } from './engine.ts';
+import { BudgetTracker, loadPricingOverrides } from './budget/budget-tracker.ts';
+import type { AIInvocation, AIInvocationPermit } from './ai/invocation-guard.ts';
+import { MIGRATION_STATE_KEY, readMigrationState, type EmbeddingMigrationPlan, type MigrationState } from './embedding-migration.ts';
+import type { DbLockHandle } from './db-lock.ts';
+
+export async function assertMigrationLeases(engine: BrainEngine, locks: DbLockHandle[]) {
+ if (!locks.length) return;
+ const owned = await engine.executeRaw<{ id: string; token: string }>(`SELECT id,acquisition_token::text AS token
+ FROM gbrain_cycle_locks WHERE id=ANY($1::text[]) AND ttl_expires_at>now() ORDER BY id FOR SHARE`, [locks.map(lock => lock.id)]);
+ if (owned.length !== locks.length || locks.some(lock => !owned.some(row => row.id === lock.id && row.token === lock.acquisitionToken))) {
+ throw new Error('Migration lease lost; authorization debit and provider dispatch refused');
+ }
+}
+
+export async function authorizeMigrationBudget(engine: BrainEngine, plan: EmbeddingMigrationPlan, maxCostUsd?: number, locks: DbLockHandle[] = [], rerankerModel?: string) {
+ const prior = await readMigrationState(engine);
+ if (prior.corrupt) {
+ let legacy = false;
+ try {
+ const raw = JSON.parse(prior.raw ?? 'null');
+ legacy = raw !== null && typeof raw === 'object' && !Array.isArray(raw)
+ && !Object.hasOwn(raw, 'budget') && !Object.hasOwn(raw, 'authorization_version');
+ } catch {}
+ if (!legacy || maxCostUsd === undefined) throw new Error('Migration state is corrupt; no paid request or invalidation was authorized. Inspect migrate embeddings --status.');
+ }
+ const same = prior.state?.to_model === plan.to_model && prior.state.to_dims === plan.to_dims;
+ const state: MigrationState = same ? prior.state! : {
+ version: 2, to_model: plan.to_model, to_dims: plan.to_dims, from_model: plan.from_model,
+ from_dims: plan.from_dims, started_at: new Date().toISOString(),
+ };
+ const old = state.budget;
+ if (state.authorization_version && !old) throw new Error('Migration authorization is missing; automatic renewal refused');
+ if (old && (!Number.isFinite(old.max_cost_usd) || old.max_cost_usd < 0 || !Number.isFinite(old.debited_usd)
+ || old.debited_usd < 0 || !Number.isSafeInteger(old.requests) || old.requests < 0)) {
+ throw new Error('Migration authorization is corrupt; no request dispatched');
+ }
+ if (maxCostUsd !== undefined && (!Number.isFinite(maxCostUsd) || maxCostUsd < 0)) throw new Error('--max-cost-usd must be finite and nonnegative');
+ if (!old && maxCostUsd === undefined) throw new Error('Paid work requires explicit --max-cost-usd. Preview with --dry-run; resume retains spent authorization.');
+ state.budget = { max_cost_usd: maxCostUsd ?? old!.max_cost_usd, debited_usd: old?.debited_usd ?? 0, requests: old?.requests ?? 0 };
+ state.authorization_version = 1;
+ if (!same && prior.state) {
+ state.retargeted_at = state.started_at;
+ state.superseded = [...prior.state.superseded ?? [], { to_model: prior.state.to_model, to_dims: prior.state.to_dims, started_at: prior.state.started_at }];
+ }
+ await engine.transaction(async tx => {
+ await assertMigrationLeases(tx, locks);
+ await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));
+ });
+ const pricingOverrides = await loadPricingOverrides(engine);
+ return async (call: AIInvocation): Promise<AIInvocationPermit> => {
+ if (call.kind !== 'embedding' && call.kind !== 'rerank') throw new Error('Migration permits embedding and reranker probes only');
+ if (call.model !== (call.kind === 'embedding' ? plan.to_model : rerankerModel)) throw new Error('Provider model differs from the authorized migration plan; no request dispatched');
+ if (!Number.isSafeInteger(call.maxInputTokens) || call.maxInputTokens! <= 0) throw new Error('Provider request has no conservative input ceiling; no request dispatched');
+ await engine.transaction(async tx => {
+ await assertMigrationLeases(tx, locks);
+ await tx.executeRaw('SELECT key FROM config WHERE key=$1 FOR UPDATE', [MIGRATION_STATE_KEY]);
+ const current = (await readMigrationState(tx)).state;
+ if (!current?.budget || current.to_model !== plan.to_model || current.to_dims !== plan.to_dims) throw new Error('Migration authorization changed; no request dispatched');
+ if (![current.budget.max_cost_usd, current.budget.debited_usd].every(n => Number.isFinite(n) && n >= 0)
+ || !Number.isSafeInteger(current.budget.requests) || current.budget.requests < 0) throw new Error('Migration authorization is corrupt; no request dispatched');
+ const tracker = new BudgetTracker({ label: 'embedding-migration', maxCostUsd: Math.max(0, current.budget.max_cost_usd-current.budget.debited_usd), pricingOverrides });
+ const estimate = { modelId: call.model, kind: call.kind === 'embedding' ? 'embed' as const : 'rerank' as const,
+ estimatedInputTokens: call.maxInputTokens!, maxOutputTokens: 0 };
+ tracker.reserve(estimate);
+ tracker.record({ modelId: call.model, kind: estimate.kind, inputTokens: call.maxInputTokens!, outputTokens: 0 });
+ current.budget.debited_usd += tracker.totalSpent;
+ current.budget.requests++;
+ await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(current));
+ });
+ return { settle: async () => {} };
+ };
+}
diff --git a/src/core/embedding-migration-cli.ts b/src/core/embedding-migration-cli.ts
new file mode 100644
index 0000000000..95c6247924
--- /dev/null
+++ b/src/core/embedding-migration-cli.ts
@@ -0,0 +1,109 @@
+import type { PaceKeyOverrides } from './pace-mode.ts';
+
+export interface MigrateEmbeddingsFlags {
+ maxCostUsd?: number;
+ to?: string;
+ dim?: number;
+ yes: boolean;
+ dryRun: boolean;
+ json: boolean;
+ noEmbed: boolean;
+ ignoreEnvOverride: boolean;
+ retarget: boolean;
+ reranker?: string;
+ batchSize?: number;
+ pace?: { perCallMode?: string; perCall?: PaceKeyOverrides };
+}
+
+const CONTROLS: Record<string, string> = {
+ '--to': 'text', '--dim': 'dimension', '--reranker': 'text',
+ '--batch-size': 'batch', '--max-cost-usd': 'cost',
+ '--yes': 'boolean', '--non-interactive': 'boolean', '--dry-run': 'boolean',
+ '--json': 'boolean', '--no-embed': 'boolean', '--ignore-env-override': 'boolean',
+ '--retarget': 'boolean', '--status': 'boolean', '--help': 'boolean', '-h': 'boolean',
+ '--pace': 'pace', '--pace-max-concurrency': 'concurrency',
+};
+const GLOBAL_CONTROLS: Record<string, string> = {
+ '--quiet': 'boolean', '--progress-json': 'boolean',
+ '--progress-interval': 'interval', '--brain': 'brain',
+};
+
+class MigrationArgumentError extends Error {
+ constructor(readonly flag: string, message: string) { super(message); }
+}
+
+export function parseMigrateEmbeddingsFlags(
+ args: string[], options: { globals?: boolean; route?: string } = {},
+): MigrateEmbeddingsFlags {
+ const values = new Map<string, string>();
+ const route = options.route === 'migrate' ? ['migrate', 'embeddings'] : options.route ? [options.route] : [];
+ for (let i = 0; i < args.length; i++) {
+ const token = args[i];
+ if (route.length && token === route[0]) { route.shift(); continue; }
+ if (!token.startsWith('-')) throw new MigrationArgumentError('<argument>', 'Unexpected positional argument; migration accepts only documented controls.');
+ const equals = token.indexOf('=');
+ const flag = equals < 0 ? token : token.slice(0, equals);
+ const kind = Object.hasOwn(CONTROLS, flag) ? CONTROLS[flag]
+ : options.globals && Object.hasOwn(GLOBAL_CONTROLS, flag) ? GLOBAL_CONTROLS[flag] : undefined;
+ if (!kind) throw new MigrationArgumentError(flag, `unknown flag ${flag}; embedding migration is brain-wide and only documented controls are supported. Use --brain to select the brain.`);
+ if (values.has(flag)) throw new MigrationArgumentError(flag, `Duplicate ${flag}; specify each migration control once.`);
+ if (equals >= 0 && !['pace', 'concurrency', 'interval', 'brain'].includes(kind)) {
+ throw new MigrationArgumentError(flag, `${flag}=value is unsupported; use the documented ${flag} syntax.`);
+ }
+ if (kind === 'pace' && equals < 0 && args[i + 1] && !args[i + 1].startsWith('-') && args[i + 1] !== route[0]) {
+ throw new MigrationArgumentError(flag, '--pace accepts a bare flag or --pace=mode, not a separate mode value.');
+ }
+ let value = kind === 'boolean' ? 'true' : kind === 'pace' && equals < 0 ? 'balanced'
+ : equals >= 0 ? token.slice(equals + 1) : args[++i];
+ if (value === undefined || !value.trim() || value.startsWith('-')) {
+ throw new MigrationArgumentError(flag, `${flag} requires a valid value; no default will be substituted.`);
+ }
+ if (['dimension', 'batch', 'concurrency', 'interval'].includes(kind)) {
+ const max = kind === 'dimension' ? 100_000 : kind === 'batch' ? 10_000 : Number.MAX_SAFE_INTEGER;
+ const min = kind === 'interval' ? 0 : 1;
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < min || Number(value) > max) {
+ throw new MigrationArgumentError(flag, `${flag} requires an integer from ${min} through ${max}; values are never truncated or clamped.`);
+ }
+ }
+ if (kind === 'cost' && (!/^(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value) || !Number.isFinite(Number(value)))) {
+ throw new MigrationArgumentError(flag, `${flag} requires a finite nonnegative dollar amount.`);
+ }
+ if (kind === 'pace') {
+ value = value.trim().toLowerCase();
+ if (!['off', 'gentle', 'balanced', 'aggressive'].includes(value)) throw new MigrationArgumentError(flag, `${flag} requires off, gentle, balanced, or aggressive.`);
+ }
+ if (kind === 'brain' && !/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/.test(value)) {
+ throw new MigrationArgumentError(flag, `${flag} requires a valid brain id.`);
+ }
+ values.set(flag, value);
+ }
+ if (route.length) throw new MigrationArgumentError(route[0], 'Incomplete migration command.');
+ const paceMode = values.get('--pace');
+ const concurrency = values.get('--pace-max-concurrency');
+ return {
+ ...(values.has('--max-cost-usd') && { maxCostUsd: Number(values.get('--max-cost-usd')) }),
+ to: values.get('--to'), dim: values.has('--dim') ? Number(values.get('--dim')) : undefined,
+ yes: values.has('--yes') || values.has('--non-interactive'), dryRun: values.has('--dry-run'),
+ json: values.has('--json'), noEmbed: values.has('--no-embed'),
+ ignoreEnvOverride: values.has('--ignore-env-override'), retarget: values.has('--retarget'),
+ ...(values.has('--reranker') && { reranker: values.get('--reranker') }),
+ ...(values.has('--batch-size') && { batchSize: Number(values.get('--batch-size')) }),
+ pace: paceMode !== undefined || concurrency !== undefined ? {
+ ...(paceMode !== undefined && { perCallMode: paceMode }),
+ ...(concurrency !== undefined && { perCall: { maxConcurrency: Number(concurrency) } }),
+ } : undefined,
+ };
+}
+
+export function migrationCliArgumentError(command: string, args: string[], rawArgs?: string[]): MigrationArgumentError | null {
+ if (command !== 'retrieval-upgrade' && !(command === 'migrate' && args[0] === 'embeddings')) return null;
+ try {
+ parseMigrateEmbeddingsFlags(rawArgs ?? (command === 'migrate' ? args.slice(1) : args), {
+ globals: true, ...(rawArgs && { route: command }),
+ });
+ return null;
+ } catch (error) {
+ if (error instanceof MigrationArgumentError) return error;
+ throw error;
+ }
+}
diff --git a/src/core/embedding-migration-retention.ts b/src/core/embedding-migration-retention.ts
new file mode 100644
index 0000000000..908cacd330
--- /dev/null
+++ b/src/core/embedding-migration-retention.ts
@@ -0,0 +1,87 @@
+import type { BrainEngine } from './engine.ts';
+import { currentSpaceChunkPredicate, falseStampPageWhere } from './embedding-invalidation.ts';
+import { readMigrationState, type EmbeddingMigrationPlan, type MigrationState } from './embedding-migration.ts';
+import { eligibleFactEmbedding, retainedFactEmbedding } from './facts/embedding-identity.ts';
+import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';
+import { quoteIdentifier, resolveWriteColumnFromConfigRows } from './search/embedding-column.ts';
+import { countArchivedEmbeddingWork } from './embedding-readiness.ts';
+
+export async function assertRetainedEmbeddingRebuildability(tx: BrainEngine, dimensions: number, model?: string, plan?: Pick<EmbeddingMigrationPlan, 'from_model' | 'from_dims'>): Promise<boolean> {
+ let counts: { pages: number; facts: number; takes: number };
+ let clearCompanions = false;
+ let archivedWork = 0;
+ try {
+ await tx.executeRaw('LOCK TABLE sources, pages, content_chunks, facts, fact_withdrawals, takes, config IN SHARE MODE');
+ const registry = await tx.executeRaw<{ key: string; value: string }>("SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns')");
+ if (!Array.isArray(registry) || registry.some(row => typeof row.key !== 'string' || typeof row.value !== 'string')) throw new Error('Unknown embedding registry');
+ const embeddingColumnsJson = registry.find(row => row.key === 'embedding_columns')?.value;
+ if (embeddingColumnsJson) {
+ const parsed = JSON.parse(embeddingColumnsJson);
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('Invalid embedding registry');
+ }
+ const active = resolveWriteColumnFromConfigRows({
+ searchEmbeddingColumn: registry.find(row => row.key === 'search_embedding_column')?.value, embeddingColumnsJson,
+ }).name;
+ const columns = await tx.executeRaw<{ name: string; type: string }>(`SELECT attname AS name,format_type(atttypid,atttypmod) AS type
+ FROM pg_attribute WHERE attrelid='content_chunks'::regclass AND attnum>0 AND NOT attisdropped`);
+ if (!Array.isArray(columns) || !columns.some(c => c.name === 'page_id') || columns.some(c => typeof c.name !== 'string' || typeof c.type !== 'string')) throw new Error('Unknown chunk schema');
+ const primary = columns.find(c => c.name === 'embedding');
+ const width = primary ? Number(primary.type.match(/^(?:vector|halfvec)\((\d+)\)$/)?.[1]) : null;
+ if (primary && (!Number.isSafeInteger(width) || width! <= 0)) throw new Error('Unknown stored dimensions');
+ const activeExists = columns.some(c => c.name === active);
+ if (!activeExists && active !== 'embedding') throw new Error('Missing configured embedding column');
+ const column = quoteIdentifier(active);
+ const legacyVector = primary ? 'cc.embedding' : 'NULL::vector';
+ const activeVector = activeExists ? `cc.${column}` : 'NULL::vector';
+ const current = activeExists ? currentSpaceChunkPredicate(column, 4, 5)
+ : 'COALESCE(cc.model=$4::text AND vector_dims(NULL::vector)=$5::int,false)';
+ if (model !== undefined) {
+ const prior = await readMigrationState(tx);
+ const storedModel = await tx.getConfig('embedding_model');
+ const state: Pick<MigrationState, 'from_model' | 'from_dims' | 'companion_vectors_invalidated'> =
+ prior.state?.to_model === model && prior.state.to_dims === dimensions ? prior.state
+ : { from_model: plan?.from_model ?? storedModel ?? 'unrecorded', from_dims: plan?.from_dims ?? width ?? 0 };
+ clearCompanions = !state.companion_vectors_invalidated
+ && (state.from_model !== model || state.from_dims !== dimensions || storedModel !== model);
+ }
+ const factColumns = await tx.executeRaw<{ type: string }>(`SELECT format_type(atttypid,atttypmod) AS type
+ FROM pg_attribute WHERE attrelid='facts'::regclass AND attname='embedding' AND attnum>0 AND NOT attisdropped`);
+ if (!Array.isArray(factColumns) || factColumns.length !== 1 || typeof factColumns[0].type !== 'string') throw new Error('Unknown fact schema');
+ const factWidth = Number(factColumns[0].type.match(/^(?:vector|halfvec)\((\d+)\)$/)?.[1]);
+ if (!Number.isSafeInteger(factWidth) || factWidth <= 0) throw new Error('Unknown fact dimensions');
+ const schemaRebuild = model === undefined || width !== dimensions;
+ const unavailablePage = `(s.archived IS DISTINCT FROM false OR p.deleted_at IS NOT NULL
+ OR COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip'
+ OR (p.text_projection_revision IS DISTINCT FROM p.knowledge_revision
+ AND (p.page_kind IS NULL OR NOT (p.page_kind=ANY($1::text[])))))`;
+ const [row] = await tx.executeRaw<{ pages: number; facts: number; takes: number }>(`SELECT
+ (SELECT count(*)::int FROM content_chunks cc LEFT JOIN pages p ON p.id=cc.page_id
+ LEFT JOIN sources s ON s.id=p.source_id
+ WHERE ${unavailablePage} AND (${legacyVector} IS NOT NULL OR ${activeVector} IS NOT NULL)
+ AND ($3::boolean OR (p.deleted_at IS NULL
+ AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')
+ AND p.text_projection_revision=p.knowledge_revision
+ AND (p.embedding_signature IS DISTINCT FROM $6 OR (${activeExists ? falseStampPageWhere(column, 6, 4) : 'false'}))
+ AND ${activeVector} IS NOT NULL AND NOT ${current}))) AS pages,
+ (SELECT count(*)::int FROM facts f WHERE $7::boolean AND f.embedding IS NOT NULL
+ AND (${retainedFactEmbedding}) IS DISTINCT FROM false
+ AND (${eligibleFactEmbedding}) IS DISTINCT FROM true) AS facts,
+ (SELECT count(*)::int FROM takes t LEFT JOIN pages p ON p.id=t.page_id
+ LEFT JOIN sources s ON s.id=p.source_id
+ WHERE $8::boolean AND t.embedding IS NOT NULL AND t.active AND t.superseded_by IS NULL AND ${unavailablePage}) AS takes`,
+ [['markdown', 'code'], [...AUDIT_ROW_SOURCES], schemaRebuild, model ?? '', dimensions, `${model ?? ''}:${dimensions}`,
+ schemaRebuild || factWidth !== dimensions || clearCompanions, clearCompanions]);
+ if (!row || (['pages', 'facts', 'takes'] as const).some(key => !Number.isSafeInteger(row[key]) || row[key] < 0)) {
+ throw new Error('Unknown retained-vector census');
+ }
+ counts = row;
+ if (model !== undefined) archivedWork = await countArchivedEmbeddingWork(tx,
+ { signature: `${model}:${dimensions}`, includeNullSignature: true, includeUnsealed: true }, activeExists ? active : null);
+ } catch {
+ throw new Error('retained_vector_check_failed: Cannot determine whether retained vectors can be rebuilt; migration mutations refused. Inspect the selected brain and database/schema access before retrying.');
+ }
+ if (counts.pages + counts.facts + counts.takes + archivedWork > 0) {
+ throw new Error(`retained_vectors_blocked: ${counts.pages} page chunk(s), ${counts.facts} fact(s), ${counts.takes} take(s) cannot be rebuilt by this migration; ${archivedWork} archived page(s) have blocked embedding work. No invalidation is permitted. Inspect the blockers: archived sources require deliberate gbrain sources restore <id>; embed_skip, importer-only media, and deleted pages require an explicit retention/recovery decision. No source or page is restored automatically. See docs/guides/embedding-migration.md#recovery.`);
+ }
+ return clearCompanions;
+}
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 5c528bb57a..98d8c349e1 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -8,12 +8,18 @@ import {
invalidateStaleSignatureEmbeddingsGuarded,
countFalseStampedChunks,
clearFalseStampedSignatures,
+ lockEmbeddingSources,
+ splitEmbeddingSignature,
+ currentSpaceChunkPredicate,
} from './embedding-invalidation.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
import { hnswIndexExpected } from './vector-index.ts';
import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';
import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';
+import { countStaleFactEmbeddings } from './facts/embedding-identity.ts';
+import { prepareEmbeddingProjections } from './embedding-readiness.ts';
+import { assertRetainedEmbeddingRebuildability } from './embedding-migration-retention.ts';
export interface EnvOverrideWarning {
triggered: boolean;
@@ -96,7 +102,7 @@ export function formatEnvOverrideWarning(w: EnvOverrideWarning): string {
* IF NOT EXISTS on CREATE INDEX makes the operation safe to re-run during
* `--resume`.
*/
-export async function runSchemaTransition(engine: BrainEngine, targetDim: number): Promise<void> {
+export async function runSchemaTransition(engine: BrainEngine, targetDim: number, assertOwned?: (tx: BrainEngine) => Promise<void>): Promise<void> {
// Sink-side guard: targetDim is interpolated into DDL below. Every current
// caller validates upstream, but a future programmatic caller passing an
// unvalidated value must fail HERE, not become SQL in an admin DDL path
@@ -105,6 +111,8 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number
throw new Error(`runSchemaTransition: targetDim must be a positive integer, got ${String(targetDim)}`);
}
await engine.transaction(async (tx) => {
+ await assertOwned?.(tx);
+ await assertRetainedEmbeddingRebuildability(tx, targetDim);
// #4252: capture every index the DROP COLUMN below will cascade-drop.
// pg_depend holds the exact column→index dependency edges the cascade
// follows, so this also catches indexes that reference the column only
@@ -316,6 +324,8 @@ export const MIGRATION_STATE_KEY = 'embedding_migration.state';
export const MIGRATION_COMPLETED_KEY = 'embedding_migration.completed';
export interface MigrationState {
+ authorization_version?: 1;
+ budget?: { max_cost_usd: number; debited_usd: number; requests: number };
/** Marker schema version. Absent = v1 (pre-hardening). */
version?: 2;
companion_vectors_invalidated?: boolean;
@@ -355,7 +365,7 @@ export async function readMigrationState(
try {
raw = await engine.getConfig(MIGRATION_STATE_KEY);
} catch {
- return { state: null, corrupt: false, raw: null };
+ return { state: null, corrupt: true, raw: null };
}
if (!raw) return { state: null, corrupt: false, raw: null };
try {
@@ -379,6 +389,8 @@ export async function readMigrationState(
}
export interface EmbeddingMigrationPlan {
+ facts_to_embed?: number;
+ blocked_projection_pages?: number;
from_model: string;
from_dims: number;
/** Actual `content_chunks.embedding` vector(N) width (null = column absent). */
@@ -595,6 +607,9 @@ export async function planEmbeddingMigration(
totalChars = Number(rows[0]?.chars ?? 0);
}
+ const facts = await countStaleFactEmbeddings(engine, toModel, toDims);
+ const readiness = await prepareEmbeddingProjections(engine);
+ totalChars += facts.chars + falseStamped.chars;
const price = lookupEmbeddingPrice(toModel);
const estCostUsd = price.kind === 'known'
? estimateCostFromChars(totalChars, price.pricePerMTok)
@@ -650,6 +665,8 @@ export async function planEmbeddingMigration(
return {
from_model: fromModel,
+ facts_to_embed: facts.count,
+ blocked_projection_pages: readiness.blocked,
from_dims: fromDims,
column_dims: col.dims,
to_model: toModel,
@@ -657,7 +674,7 @@ export async function planEmbeddingMigration(
// ONE computation shared with apply's trigger (absent column ⇒ build).
dim_change: schemaRebuildNeeded(col.dims, toDims),
chunks_to_embed: wide + falseStamped.chunks,
- total_chars: totalChars + falseStamped.chars,
+ total_chars: totalChars,
null_signature_chunks: wide - narrow,
false_stamped_chunks: falseStamped.chunks,
est_cost_usd: estCostUsd,
@@ -684,8 +701,9 @@ export interface MigrationStatusReport {
pinned_widths: Array<{ table: string; dims: number | null }>;
missing_embeddings: number | null;
chunkless_pages: number | null;
+ blocked_projection_pages?: number | null;
signature_census: Array<{ signature: string | null; pages: number }>;
- /** facts rows whose text-space vector is NULL (regenerate on next extract/write),
+ /** Eligible facts whose vector is missing or has stale model/text provenance,
* excluding the audit checkpoint rows extract-conversation-facts writes into
* `facts` — those are never embedded and never recalled (#4875). */
facts_pending: number | null;
@@ -782,6 +800,7 @@ export async function readMigrationStatus(engine: BrainEngine): Promise<Migratio
: null;
if (target) {
try {
+ factsPending = (await countStaleFactEmbeddings(engine, target.model, target.dims)).count;
const stale = await engine.countStaleChunks({
signature: migrationSignature(target.model, target.dims),
includeNullSignature: true,
@@ -810,8 +829,11 @@ export async function readMigrationStatus(engine: BrainEngine): Promise<Migratio
embedSkipNull = Number(rows[0]?.n ?? 0);
} catch { /* report null */ }
+ let blockedProjectionPages: number | null = null;
+ try { blockedProjectionPages = (await prepareEmbeddingProjections(engine)).blocked; } catch {}
return {
marker: markerReport,
+ blocked_projection_pages: blockedProjectionPages,
completed,
db_plane: { model: dbModel, dims: dbDims },
column_dims: columnDims,
@@ -847,19 +869,27 @@ export async function verifySearchRoundTrip(
): Promise<VerifySearchOutcome> {
try {
const { currentEmbeddingSignature, embedQuery } = await import('./embedding.ts');
- if (currentEmbeddingSignature() === null) {
+ const { getEmbeddingModel } = await import('./ai/gateway.ts');
+ const signature = currentEmbeddingSignature();
+ if (signature === null) {
return { status: 'skipped', samples: [], reason_code: 'gateway_unconfigured' };
}
const n = Math.max(1, Math.min(10, opts.samples ?? 3));
- const rows = await engine.executeRaw<{ page_id: number; source_id: string; chunk_text: string }>(
- `SELECT cc.page_id, p.source_id, cc.chunk_text
+ const queryModel = getEmbeddingModel();
+ const { dims } = splitEmbeddingSignature(signature);
+ const eligible = `NOT s.archived AND p.deleted_at IS NULL
+ AND p.text_projection_revision=p.knowledge_revision AND p.embedding_signature=$2
+ AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')
+ AND (cc.modality IS NULL OR cc.modality='text') AND ${currentSpaceChunkPredicate('embedding', 3, 4)}`;
+ const rows = await engine.executeRaw<{ id: number; slug: string; page_id: number; source_id: string }>(
+ `SELECT cc.id, p.slug, cc.page_id, p.source_id
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.embedding IS NOT NULL AND p.deleted_at IS NULL
- AND (cc.modality IS NULL OR cc.modality = 'text')
+ JOIN sources s ON s.id=p.source_id
+ WHERE ${eligible}
ORDER BY cc.id DESC
LIMIT $1`,
- [n],
+ [n, signature, queryModel, dims],
);
if (rows.length === 0) {
return { status: 'skipped', samples: [], reason_code: 'no_embedded_chunks' };
@@ -867,11 +897,19 @@ export async function verifySearchRoundTrip(
const samples: VerifySearchOutcome['samples'] = [];
for (const row of rows) {
try {
- const query = row.chunk_text.slice(0, 160);
+ const current = await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug }]);
+ return tx.executeRaw<{ chunk_text: string }>(`SELECT cc.chunk_text FROM content_chunks cc
+ JOIN pages p ON p.id=cc.page_id JOIN sources s ON s.id=p.source_id
+ WHERE cc.id=$1 AND ${eligible}`, [row.id, signature, queryModel, dims]);
+ });
+ if (!current.length) continue;
+ const query = current[0].chunk_text.slice(0, 160);
const vec = await embedQuery(query);
const results = await engine.searchVector(vec, {
limit: 10,
sourceId: row.source_id,
+ embeddingColumn: { name: 'embedding', type: 'vector', dimensions: vec.length, embeddingModel: queryModel },
} as never);
const hit = Array.isArray(results)
&& results.some((r) => Number((r as { page_id?: unknown }).page_id) === Number(row.page_id));
@@ -890,6 +928,7 @@ export async function verifySearchRoundTrip(
samples.push({ page_id: Number(row.page_id), status: 'error', reason_code: code });
}
}
+ if (!samples.length) return { status: 'skipped', samples: [], reason_code: 'no_embedded_chunks' };
const misses = samples.filter((s) => s.status !== 'hit');
return misses.length === 0
? { status: 'pass', samples }
@@ -898,7 +937,7 @@ export async function verifySearchRoundTrip(
return {
status: 'warn',
samples: [],
- reason_code: e instanceof Error ? e.message.slice(0, 80) : 'unknown',
+ reason_code: 'verification_unavailable',
};
}
}
@@ -913,6 +952,8 @@ export interface MigrationVerify {
complete: boolean;
blockers: string[];
details: {
+ stale_facts?: number;
+ blocked_projection_pages?: number;
column_dims: number | null;
pinned_widths: Array<{ table: string; dims: number | null }>;
stale_wide: number;
@@ -940,9 +981,14 @@ export async function verifyMigrationComplete(
envMatchesTarget?: boolean;
/** True when GBRAIN_EMBEDDING_* env is set at all. */
envPresent?: boolean;
+ ignoreMarker?: boolean;
} = {},
): Promise<MigrationVerify> {
const blockers: string[] = [];
+ const facts = await countStaleFactEmbeddings(engine, target.toModel, target.toDims);
+ const readiness = await prepareEmbeddingProjections(engine);
+ if (facts.count) blockers.push(`${facts.count} active fact(s) not in the target embedding space`);
+ if (readiness.blocked) blockers.push(`${readiness.blocked} page projection(s) blocked; rerun migration for bounded canonical recovery`);
// env≠target: the runtime would embed at a DIFFERENT model than the target
// no matter what the DB says — a converged-looking brain is one process
@@ -1036,7 +1082,7 @@ export async function verifyMigrationComplete(
} else if (marker.state) {
const same = marker.state.to_model === target.toModel && marker.state.to_dims === target.toDims;
markerState = same ? 'same_target' : 'different_target';
- if (same) {
+ if (same && !opts.ignoreMarker) {
blockers.push(`a migration to this target started ${marker.state.started_at} is still in flight — resuming it`);
}
// different_target is the caller's --retarget decision, not a convergence
@@ -1055,6 +1101,8 @@ export async function verifyMigrationComplete(
complete: blockers.length === 0,
blockers,
details: {
+ stale_facts: facts.count,
+ blocked_projection_pages: readiness.blocked,
column_dims: col.dims,
pinned_widths: pinned,
stale_wide: staleWide,
@@ -1081,8 +1129,8 @@ export async function applyEmbeddingMigration(
opts: {
ignoreEnvOverride?: boolean;
/** Persist target model+dims to the file plane + reconfigure the gateway. */
- persistConfig?: (toModel: string, toDims: number) => void | Promise<void>;
- /** Stamped into the marker so the printed resume command is complete. */
+ persistConfig?: (toModel: string, toDims: number, tx: BrainEngine) => void | Promise<void>;
+ assertOwned?: (tx?: BrainEngine) => Promise<void>;
} = {},
): Promise<MigrationApplyResult> {
const envWarning = detectEnvOverride(plan.to_model, plan.to_dims);
@@ -1091,6 +1139,11 @@ export async function applyEmbeddingMigration(
}
try {
+ await opts.assertOwned?.();
+ await engine.transaction(async tx => { await opts.assertOwned?.(tx); await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan); });
+ const readiness = await prepareEmbeddingProjections(engine, { repair: true, assertOwned: opts.assertOwned });
+ if (readiness.blocked) return { status: 'failed', reason: `projection_blocked: ${readiness.blocked} page(s) remain; no embedding invalidation performed. Canonical projection recovery may have made durable progress. Inspect blockers before retrying: archived sources require deliberate gbrain sources restore <id>; unsupported media requires its source importer. See docs/guides/embedding-migration.md#recovery.` };
+ await opts.assertOwned?.();
// 1. State marker FIRST — a crash after any later step is resumable.
// Same-target re-apply PRESERVES the original started_at (set-if-
// absent) so status/doctor report the migration's true age; a
@@ -1116,6 +1169,8 @@ export async function applyEmbeddingMigration(
state.from_dims = prior.state.from_dims;
state.started_at = prior.state.started_at;
state.companion_vectors_invalidated = prior.state.companion_vectors_invalidated;
+ state.budget = prior.state.budget;
+ state.authorization_version = prior.state.authorization_version;
if (prior.state.retargeted_at) state.retargeted_at = prior.state.retargeted_at;
if (prior.state.superseded) state.superseded = prior.state.superseded;
} else if (prior.state) {
@@ -1126,7 +1181,11 @@ export async function applyEmbeddingMigration(
{ to_model: prior.state.to_model, to_dims: prior.state.to_dims, started_at: prior.state.started_at },
];
}
- await engine.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));
+ await engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
+ await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
+ await tx.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));
+ });
// 2. Schema work — probe again (the plan may be stale after a resume) and
// repair each dim-pinned column INDEPENDENTLY (round-2 #9): a brain
@@ -1135,14 +1194,18 @@ export async function applyEmbeddingMigration(
let schemaTransitioned = false;
const pinnedRepaired: string[] = [];
const col = await readContentChunksEmbeddingDim(engine);
+ await opts.assertOwned?.();
if (schemaRebuildNeeded(col.dims, plan.to_dims)) {
- await runSchemaTransition(engine, plan.to_dims);
+ await runSchemaTransition(engine, plan.to_dims, opts.assertOwned);
schemaTransitioned = true;
} else {
const pinned = await readDimPinnedWidths(engine);
const stalePinned = pinned.filter((p) => schemaRebuildNeeded(p.dims, plan.to_dims));
if (stalePinned.length > 0) {
await engine.transaction(async (tx) => {
+ await opts.assertOwned?.(tx);
+ await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
+ const stalePinned = (await readDimPinnedWidths(tx)).filter(p => schemaRebuildNeeded(p.dims, plan.to_dims));
for (const t of TEXT_EMBEDDING_DIM_PINNED_TABLES) {
if (stalePinned.some((p) => p.table === t.table)) {
await transitionDimPinnedColumn(tx, t.table, t.index, t.indexSql, plan.to_dims);
@@ -1163,18 +1226,22 @@ export async function applyEmbeddingMigration(
// vectors are invisible to every stale selector, so NULLing them
// would be permanent loss.
//
- await clearFalseStampedSignatures(engine, plan.to_model, plan.to_dims);
- const invalidated = await invalidateStaleSignatureEmbeddingsGuarded(engine, {
- signature: migrationSignature(plan.to_model, plan.to_dims),
- includeNullSignature: true,
+ const invalidated = await engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
+ await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
+ await clearFalseStampedSignatures(tx, plan.to_model, plan.to_dims);
+ return invalidateStaleSignatureEmbeddingsGuarded(tx, {
+ signature: migrationSignature(plan.to_model, plan.to_dims),
+ includeNullSignature: true,
+ });
});
let cacheCleared = 0;
await engine.transaction(async (tx) => {
+ await opts.assertOwned?.(tx);
+ const clearCompanions = await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
const stores = await readPrimaryEmbeddingStores(tx);
- if (!state.companion_vectors_invalidated
- && (state.from_model !== plan.to_model || state.from_dims !== plan.to_dims
- || await tx.getConfig('embedding_model') !== plan.to_model)) {
+ if (clearCompanions) {
for (const table of stores) {
if (table === 'content_chunks' || table === 'query_cache') continue;
await tx.executeRaw(`UPDATE ${table} SET embedding = NULL${table === 'takes' ? ', embedded_at = NULL' : ''} WHERE embedding IS NOT NULL`);
@@ -1193,7 +1260,11 @@ export async function applyEmbeddingMigration(
});
// 5. File plane + gateway (the embed pipeline reads file/env, not DB).
- await opts.persistConfig?.(plan.to_model, plan.to_dims);
+ if (opts.persistConfig) await engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
+ await assertRetainedEmbeddingRebuildability(tx, plan.to_dims, plan.to_model, plan);
+ await opts.persistConfig!(plan.to_model, plan.to_dims, tx);
+ });
return {
status: 'applied',
@@ -1266,7 +1337,8 @@ export async function resolveRerankerPlan(
const mode = flag ?? 'auto';
if (mode === 'keep') return { exposed, action: { kind: 'none', suggestion: null } };
- if (mode === 'off') return { exposed, action: { kind: 'disable' } };
+ if (mode === 'off') return { exposed, action: await engine.getConfig('search.reranker.enabled') === 'false'
+ ? { kind: 'none', suggestion: null } : { kind: 'disable' } };
if (mode !== 'auto') {
// Explicit provider:model — validate BEFORE anything destructive runs.
if (!mode.includes(':')) {
@@ -1310,9 +1382,11 @@ export async function resolveRerankerPlan(
export async function applyRerankerAction(
engine: BrainEngine,
action: RerankerAction,
+ assertOwned?: (tx: BrainEngine) => Promise<void>,
): Promise<void> {
if (action.kind === 'none') return;
await engine.transaction(async (tx) => {
+ await assertOwned?.(tx);
const upsert = async (key: string, value: string) => {
await tx.executeRaw(
`INSERT INTO config (key, value) VALUES ($1, $2)
@@ -1368,30 +1442,35 @@ export async function reconcilePageSignatures(
engine: BrainEngine,
plan: EmbeddingMigrationPlan,
): Promise<number> {
- const sig = migrationSignature(plan.to_model, plan.to_dims);
- const rows = await engine.executeRaw<{ slug: string }>(
- `UPDATE pages p
- SET embedding_signature = $1
- WHERE p.deleted_at IS NULL
- AND (p.embedding_signature IS DISTINCT FROM $1)
- AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id)
- AND NOT EXISTS (
- SELECT 1 FROM content_chunks c
- WHERE c.page_id = p.id AND c.embedding IS NULL
- )
- AND NOT EXISTS (
- -- Model-truth conjunct: chunks carry the gateway-resolved
- -- provider:model at write time. A page whose vectors were written by
- -- a concurrent OUT-OF-LOCK embed worker still running the OLD model
- -- must NOT be relabeled as target-space — the final census relies on
- -- the old signature/model evidence this stamp would erase.
- SELECT 1 FROM content_chunks c
- WHERE c.page_id = p.id AND c.model IS DISTINCT FROM $2
- )
- RETURNING p.slug`,
- [sig, plan.to_model],
- );
- return (rows as unknown[]).length;
+ return engine.transaction(async tx => {
+ const sources = await lockEmbeddingSources(tx);
+ const sig = migrationSignature(plan.to_model, plan.to_dims);
+ const rows = await tx.executeRaw<{ slug: string }>(
+ `UPDATE pages p
+ SET embedding_signature = $1
+ WHERE p.deleted_at IS NULL
+ AND p.source_id=ANY($3::text[])
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND (p.embedding_signature IS DISTINCT FROM $1)
+ AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id = p.id)
+ AND NOT EXISTS (
+ SELECT 1 FROM content_chunks c
+ WHERE c.page_id = p.id AND c.embedding IS NULL
+ )
+ AND NOT EXISTS (
+ -- Model-truth conjunct: chunks carry the gateway-resolved
+ -- provider:model at write time. A page whose vectors were written by
+ -- a concurrent OUT-OF-LOCK embed worker still running the OLD model
+ -- must NOT be relabeled as target-space — the final census relies on
+ -- the old signature/model evidence this stamp would erase.
+ SELECT 1 FROM content_chunks c
+ WHERE c.page_id = p.id AND c.model IS DISTINCT FROM $2
+ )
+ RETURNING p.slug`,
+ [sig, plan.to_model, sources],
+ );
+ return (rows as unknown[]).length;
+ });
}
/**
@@ -1411,8 +1490,11 @@ export async function completeEmbeddingMigration(
engine: BrainEngine,
plan: EmbeddingMigrationPlan,
extra: Record<string, unknown> = {},
+ assertOwned?: (tx: BrainEngine) => Promise<void>,
): Promise<void> {
+ const state = (await readMigrationState(engine)).state;
const completed = JSON.stringify({
+ budget: state?.budget,
to_model: plan.to_model,
to_dims: plan.to_dims,
from_model: plan.from_model,
@@ -1420,6 +1502,7 @@ export async function completeEmbeddingMigration(
...extra,
});
await engine.transaction(async (tx) => {
+ await assertOwned?.(tx);
await tx.executeRaw(`DELETE FROM config WHERE key = $1`, [MIGRATION_STATE_KEY]);
await tx.executeRaw(
`INSERT INTO config (key, value) VALUES ($1, $2)
diff --git a/src/core/embedding-readiness.ts b/src/core/embedding-readiness.ts
new file mode 100644
index 0000000000..9be54c522e
--- /dev/null
+++ b/src/core/embedding-readiness.ts
@@ -0,0 +1,92 @@
+import type { BrainEngine } from './engine.ts';
+import { readProjectionSnapshot, queuePageProjection, preparePageProjection, installPageProjection } from './page-state/projections.ts';
+import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from './search/embedding-column.ts';
+import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';
+
+export async function countArchivedEmbeddingWork(engine: BrainEngine, opts: { sourceId?: string; signature?: string; includeNullSignature?: boolean; includeUnsealed?: boolean } = {}, activeColumn?: string | null): Promise<number> {
+ const column = activeColumn === undefined ? (await resolveActiveEmbeddingColumnFromEngine(engine)).name : activeColumn;
+ const vector = column === null ? 'NULL::vector' : `c.${quoteIdentifier(column)}`;
+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages p
+ JOIN sources s ON s.id=p.source_id WHERE s.archived AND p.deleted_at IS NULL
+ AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')
+ AND ($1::text IS NULL OR p.source_id=$1)
+ AND (($4::boolean AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision)
+ OR EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND (${vector} IS NULL
+ OR c.embedded_text_hash <> md5(c.chunk_text)
+ OR ($2::text IS NOT NULL AND (p.embedding_signature <> $2 OR ($3::boolean AND p.embedding_signature IS NULL)))))
+ OR ((p.compiled_truth <> '' OR p.timeline <> '') AND ${QUARANTINE_FILTER_FRAGMENT}
+ AND NOT EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)))`,
+ [opts.sourceId ?? null, opts.signature ?? null, opts.includeNullSignature ?? false, opts.includeUnsealed ?? false]);
+ if (!Number.isSafeInteger(row?.n) || row.n < 0) throw new Error('Cannot determine archived embedding work.');
+ return row.n;
+}
+
+export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { sourceId?: string; limit?: number; repair?: boolean; existingChunksOnly?: boolean; activeSourcesOnly?: boolean; stale?: { signature?: string; includeNullSignature?: boolean }; signal?: AbortSignal; deadline?: number; assertOwned?: (tx?: BrainEngine) => Promise<void> } = {}) {
+ const limit = Math.max(1, Math.min(opts.limit ?? 100, 100));
+ const params: unknown[] = [opts.sourceId ?? null, opts.existingChunksOnly ?? false];
+ let eligible = '';
+ if (opts.stale) {
+ const column = quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine)).name);
+ params.push(opts.stale.signature ?? null, opts.stale.includeNullSignature ?? false);
+ eligible = `AND EXISTS(SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND (
+ c.${column} IS NULL OR c.embedded_text_hash <> md5(c.chunk_text)
+ OR ($3::text IS NOT NULL AND (p.embedding_signature <> $3 OR ($4::boolean AND p.embedding_signature IS NULL)))))`;
+ }
+ const where = `p.deleted_at IS NULL
+ AND NOT (COALESCE(p.frontmatter,'{}'::jsonb) ? 'embed_skip')
+ AND p.text_projection_revision IS DISTINCT FROM p.knowledge_revision
+ AND ($1::text IS NULL OR p.source_id=$1)
+ ${opts.activeSourcesOnly ? 'AND NOT s.archived' : ''}
+ AND (NOT $2::boolean OR EXISTS(SELECT 1 FROM content_chunks c WHERE c.page_id=p.id)) ${eligible}`;
+ const countBlocked = async () => {
+ const [remaining] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages p
+ JOIN sources s ON s.id=p.source_id WHERE ${where}`, params);
+ if (!Number.isSafeInteger(remaining?.n) || remaining.n < 0) throw new Error('Cannot determine pending embedding projections.');
+ return remaining.n;
+ };
+ let rebuilt = 0;
+ let blocked = await countBlocked();
+ while (opts.repair && blocked > 0 && !opts.signal?.aborted && Date.now() < (opts.deadline ?? Infinity)) {
+ const previousBlocked = blocked;
+ const rows = await engine.executeRaw<{ slug: string; source_id: string }>(`SELECT p.slug,p.source_id FROM pages p
+ JOIN sources s ON s.id=p.source_id WHERE ${where} AND NOT s.archived ORDER BY p.id LIMIT $${params.length + 1}`, [...params, limit]);
+ for (const row of rows) {
+ if (opts.signal?.aborted || Date.now() >= (opts.deadline ?? Infinity)) break;
+ await opts.assertOwned?.();
+ try {
+ if (await readProjectionSnapshot(engine, row.slug, row.source_id)) continue;
+ const queued = await engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
+ await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug }]);
+ if (!await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, requireLiveSource: true })) return false;
+ opts.signal?.throwIfAborted();
+ await queuePageProjection(tx, row.source_id, row.slug, 'embedding_recovery');
+ opts.signal?.throwIfAborted();
+ return true;
+ });
+ if (!queued) continue;
+ const prepared = await readProjectionSnapshot(engine, row.slug, row.source_id, { allowUnsealed: true, requireLiveSource: true });
+ if (!prepared) continue;
+ const projection = await preparePageProjection(prepared);
+ await opts.assertOwned?.();
+ await engine.transaction(async tx => {
+ await opts.assertOwned?.(tx);
+ opts.signal?.throwIfAborted();
+ if (Date.now() >= (opts.deadline ?? Infinity)) throw new Error('Projection recovery deadline exceeded.');
+ await installPageProjection(tx, prepared, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });
+ await opts.assertOwned?.(tx);
+ opts.signal?.throwIfAborted();
+ if (Date.now() >= (opts.deadline ?? Infinity)) throw new Error('Projection recovery deadline exceeded.');
+ });
+ rebuilt++;
+ } catch {
+ if (opts.signal?.aborted) break;
+ await opts.assertOwned?.();
+ }
+ }
+ await opts.assertOwned?.();
+ blocked = await countBlocked();
+ if (blocked >= previousBlocked) break;
+ }
+ return { rebuilt, blocked };
+}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index b9b3031354..17e4b6f9c9 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -505,6 +505,8 @@ export type FactInsertStatus = 'inserted' | 'duplicate' | 'superseded';
/** A fact row read from the facts table. */
export interface FactRow {
+ embedding_model?: string | null;
+ embedded_text_hash?: string | null;
id: number;
source_id: string;
entity_slug: string | null;
@@ -535,6 +537,7 @@ export interface FactRow {
/** Input for insertFact. source_id supplied via the ctx arg. */
export interface NewFact {
+ embedding_model?: string | null;
fact: string;
kind?: FactKind; // default 'fact'
entity_slug?: string | null;
@@ -2215,7 +2218,7 @@ export interface BrainEngine {
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
): Promise<FactRow[]>;
/**
diff --git a/src/core/export-publish.ts b/src/core/export-publish.ts
new file mode 100644
index 0000000000..e6c06d8fad
--- /dev/null
+++ b/src/core/export-publish.ts
@@ -0,0 +1,51 @@
+import { lstatSync, opendirSync } from 'node:fs';
+import { join, parse, relative, resolve, sep } from 'node:path';
+import { nativeExportPublisher } from './persistence/native-lock.ts';
+import { exportPathKey, type ExportStage } from './export-stage.ts';
+
+function hasDirectory(path: string): boolean {
+ const root = parse(path).root;
+ let current = root;
+ for (const part of relative(root, path).split(sep).filter(Boolean)) {
+ current = join(current, part);
+ try {
+ const info = lstatSync(current);
+ if (info.isSymbolicLink() || !info.isDirectory()) throw new Error('Export destination has an unsafe directory. Use an operator-controlled destination without symlinks or reparse points.');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
+ throw error;
+ }
+ }
+ return true;
+}
+
+export async function publishExport(stage: ExportStage, destination: string, tick: (path: string) => void | Promise<void> = () => {}): Promise<void> {
+ const publisher = await nativeExportPublisher();
+ const root = resolve(destination);
+ for (const row of stage.db.query<{ path: string }, []>("SELECT '' AS path UNION ALL SELECT path FROM paths WHERE kind='directory'").iterate()) {
+ const directory = join(root, ...row.path.split('/'));
+ if (!hasDirectory(directory)) continue;
+ const entries = opendirSync(directory);
+ try {
+ for (let entry = entries.readSync(); entry; entry = entries.readSync()) {
+ const path = row.path ? row.path + '/' + entry.name : entry.name;
+ let key: string;
+ try { key = exportPathKey(path); } catch { continue; }
+ const planned = stage.db.query<{ path: string; kind: string }, [string]>('SELECT path, kind FROM paths WHERE key=?').get(key);
+ if (!planned) continue;
+ const info = lstatSync(join(directory, entry.name));
+ if (planned.path !== path || planned.kind !== 'directory' || !info.isDirectory() || info.isSymbolicLink()) {
+ throw new Error('Export destination has an occupied, aliased or unsafe planned path. Nothing was published. Use a fresh destination.');
+ }
+ }
+ } finally { entries.closeSync(); }
+ }
+ const handle = publisher.beginExport(root);
+ try {
+ for (const row of stage.db.query<{ path: string; payload: string }, []>("SELECT path, payload FROM paths WHERE kind='file' ORDER BY path").iterate()) {
+ publisher.publishExportFile(handle, row.path, Buffer.from(row.payload));
+ await tick(row.path);
+ }
+ publisher.completeExport(handle);
+ } finally { publisher.closeExport(handle); }
+}
diff --git a/src/core/export-snapshot.ts b/src/core/export-snapshot.ts
new file mode 100644
index 0000000000..9a018f1e01
--- /dev/null
+++ b/src/core/export-snapshot.ts
@@ -0,0 +1,29 @@
+import type { BrainEngine } from './engine.ts';
+import { overlayCanonicalBodies } from './page-state/snapshot.ts';
+import type { PageWithdrawal } from './page-state/types.ts';
+import { rowToPage } from './utils.ts';
+import { EXPORT_PAYLOAD_LIMIT } from './export-stage.ts';
+
+export async function readExportWithdrawals(tx: BrainEngine, sourceId: string): Promise<PageWithdrawal[]> {
+ const [size] = await tx.executeRaw<{ bytes: number }>(`SELECT COALESCE(sum(octet_length(
+ jsonb_build_object('visibility',visibility,'fact_hash',fact_hash,'withdrawn_at',withdrawn_at)::text)+1),0)+2 AS bytes
+ FROM fact_withdrawals WHERE source_id=$1`, [sourceId]);
+ if (Number(size.bytes) > EXPORT_PAYLOAD_LIMIT) throw new Error('Export withdrawal ledger capacity exceeded. No destination output was published.');
+ return tx.executeRaw<PageWithdrawal>(`SELECT visibility,fact_hash,withdrawn_at
+ FROM fact_withdrawals WHERE source_id=$1 ORDER BY visibility,fact_hash`, [sourceId]);
+}
+
+export async function readExportPage(tx: BrainEngine, key: { id: string; source_id: string; slug: string }, withdrawals: PageWithdrawal[]) {
+ const [row] = await tx.executeRaw<Record<string, unknown>>(`WITH export_page AS MATERIALIZED (
+ SELECT * FROM pages WHERE id=$1::bigint
+ ) SELECT p.*,
+ COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS export_tags
+ FROM export_page p WHERE p.source_id=$2 AND p.slug=$3 AND p.deleted_at IS NULL`,
+ [key.id, key.source_id, key.slug]);
+ if (!row) throw new Error('Export snapshot unexpectedly lost a selected page.');
+ const page = rowToPage(row);
+ if (page.compiled_truth.includes('gbrain:facts:') || page.timeline.includes('gbrain:facts:')) {
+ Object.assign(page, await overlayCanonicalBodies(tx.executeRaw.bind(tx), page.compiled_truth, page.timeline, withdrawals));
+ }
+ return { page, tags: row.export_tags as string[] };
+}
diff --git a/src/core/export-stage.ts b/src/core/export-stage.ts
new file mode 100644
index 0000000000..fea65ae304
--- /dev/null
+++ b/src/core/export-stage.ts
@@ -0,0 +1,57 @@
+import { Database } from 'bun:sqlite';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+export const EXPORT_MARKER = '.gbrain-export-status';
+export const EXPORT_PAYLOAD_LIMIT = 32 * 1024 * 1024;
+export const EXPORT_STAGE_LIMIT = 8 * 1024 * 1024 * 1024;
+export const EXPORT_SNAPSHOT_MS = 10 * 60 * 1000;
+
+export function exportPathKey(path: string): string {
+ const parts = path.split('/');
+ if (Buffer.byteLength(path) > 4096 || parts.length > 256 || parts.some(part => !part || part === '.' || part === '..'
+ || /[\\\x00-\x1f\x7f:<>"|?*]/.test(part) || /[\uD800-\uDFFF]/u.test(part) || /[. ]$/.test(part)
+ || /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part) || Buffer.byteLength(part) > 240)) {
+ throw new Error('Unsafe export path. Correct the stored slug before exporting.');
+ }
+ return path.normalize('NFC').toUpperCase().toLowerCase().normalize('NFC');
+}
+
+export class ExportStage {
+ readonly directory = mkdtempSync(join(tmpdir(), 'gbrain-export-'));
+ readonly db = new Database(join(this.directory, 'manifest.sqlite'));
+ bytes = 0;
+ pages = 0;
+
+ constructor() {
+ this.db.exec('PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-4096; PRAGMA max_page_count=2097152; CREATE TABLE paths (key TEXT PRIMARY KEY, path TEXT NOT NULL, kind TEXT NOT NULL, payload BLOB)');
+ this.add(EXPORT_MARKER, 'marker');
+ }
+
+ add(path: string, kind: 'file' | 'directory' | 'marker', payload?: string): void {
+ exportPathKey(path);
+ const parts = path.split('/');
+ const size = payload === undefined ? 0 : Buffer.byteLength(payload);
+ if (size > EXPORT_PAYLOAD_LIMIT || this.bytes + size > EXPORT_STAGE_LIMIT) {
+ throw new Error('Export staging capacity exceeded; nothing was published. Use --source, --type or --slug-prefix to select a smaller snapshot.');
+ }
+ for (let i = 1; i <= parts.length; i++) {
+ const current = parts.slice(0, i).join('/');
+ const currentKind = i === parts.length ? kind : 'directory';
+ const key = exportPathKey(current);
+ const prior = this.db.query<{ path: string; kind: string }, [string]>('SELECT path, kind FROM paths WHERE key=?').get(key);
+ if (prior) {
+ if (prior.kind === 'directory' && currentKind === 'directory' && prior.path === current) continue;
+ throw new Error('Export path collision (including case, Unicode, page/sidecar or file-prefix aliases). Nothing was published. Export one source at a time with --source <id> into separate fresh directories.');
+ }
+ this.db.query('INSERT INTO paths VALUES (?, ?, ?, ?)').run(key, current, currentKind, i === parts.length ? payload ?? null : null);
+ }
+ this.bytes += size;
+ }
+
+ close(): void {
+ this.db.close();
+ rmSync(this.directory, { recursive: true, force: true });
+ }
+}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index c6a5eccaa1..952a3b773b 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -46,6 +46,7 @@ import type { WriteReceipt } from '../persistence/types.ts';
import type { GBrainConfig } from '../config.ts';
import { isAvailable } from '../ai/gateway.ts';
import { withAIInvocationPreflight } from '../ai/invocation-guard.ts';
+import { decideSingleFact } from './single-prepare.ts';
/**
* Notability-filter vocabulary shared by the durable facts-absorb payload
@@ -671,13 +672,14 @@ async function runPipelineBodyInner(
// Dedup against DB candidates (correct per Codex Q7: fence rows
// have no embeddings; FS lock + sync invariant means DB == fence
// at write time). Threshold 0.95 unchanged.
- let matchedExistingId: number | null = null;
- if (resolvedSlug && f.embedding) {
+ const exact = resolvedSlug ? await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility }, null) : null;
+ let matchedExistingId: number | null = exact?.candidate?.id ?? null;
+ if (matchedExistingId === null && resolvedSlug && f.embedding) {
const candidates = await ctx.engine.findCandidateDuplicates(
ctx.sourceId,
resolvedSlug,
f.fact,
- { embedding: f.embedding, k: DEDUP_CANDIDATE_LIMIT },
+ { embedding: f.embedding, embeddingModel: f.embedding_model, k: DEDUP_CANDIDATE_LIMIT },
);
let topId: number | null = null;
let topScore = -1;
@@ -763,6 +765,7 @@ async function runPipelineBodyInner(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
+ embedding_model: f.embedding_model ?? null,
// #4206: caller event-time fallback + provenance context. #4819: a
// DB-only row has no fence to name the page it came from, so the page
// path's slug fills context when the caller passed no sourceSlug.
@@ -802,6 +805,7 @@ async function runPipelineBodyInner(
// (historical imports); then import time.
validFrom: f.valid_from ?? ctx.validFrom ?? new Date(),
embedding: f.embedding ?? null,
+ embedding_model: f.embedding_model ?? null,
sessionId: f.source_session ?? null,
}));
@@ -850,6 +854,7 @@ async function runPipelineBodyInner(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
+ embedding_model: f.embedding_model ?? null,
// #4206: caller event-time fallback + provenance context.
valid_from: f.valid_from ?? ctx.validFrom,
context: ctx.sourceSlug ?? input.pageSlug ?? null,
@@ -882,6 +887,7 @@ async function runPipelineBodyInner(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
+ embedding_model: f.embedding_model ?? null,
// #4206: caller event-time fallback + provenance context.
valid_from: f.valid_from ?? ctx.validFrom,
context: ctx.sourceSlug ?? input.pageSlug ?? null,
diff --git a/src/core/facts/embedding-identity.ts b/src/core/facts/embedding-identity.ts
new file mode 100644
index 0000000000..612456cc51
--- /dev/null
+++ b/src/core/facts/embedding-identity.ts
@@ -0,0 +1,24 @@
+import type { BrainEngine } from '../engine.ts';
+import { AUDIT_ROW_SOURCES } from './audit-sources.ts';
+
+export const retainedFactEmbedding = `f.expired_at IS NULL AND f.superseded_by IS NULL
+ AND (f.valid_until IS NULL OR f.valid_until>now())
+ AND NOT (f.source = ANY($2::text[]))
+ AND NOT EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id
+ AND w.visibility=f.visibility AND w.fact_hash=gbrain_fact_fingerprint(f.fact))`;
+
+export const eligibleFactEmbedding = `${retainedFactEmbedding}
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=f.source_id AND NOT s.archived)
+ AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=f.source_id
+ AND p.slug=f.source_markdown_slug AND p.deleted_at IS NOT NULL)`;
+
+export const staleFactEmbedding = `(f.embedding IS NULL OR f.embedding_model IS DISTINCT FROM $3
+ OR f.embedded_text_hash IS DISTINCT FROM md5(f.fact) OR vector_dims(f.embedding)<>$4::int)`;
+
+export async function countStaleFactEmbeddings(engine: Pick<BrainEngine, 'executeRaw'>, model: string, dimensions: number, sourceId?: string) {
+ const [row] = await engine.executeRaw<{ count: number; chars: string }>(`SELECT count(*)::int AS count,
+ COALESCE(sum(length(f.fact)),0)::text AS chars FROM facts f
+ WHERE ($1::text IS NULL OR f.source_id=$1) AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}`,
+ [sourceId ?? null, [...AUDIT_ROW_SOURCES], model, dimensions]);
+ return { count: Number(row.count), chars: Number(row.chars) };
+}
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 772ef3a4b1..6afdaa2e7b 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -21,7 +21,7 @@
* gateway-down errors are absorbed into NULL-embedding rows.
*/
-import { chat, embedOne, isAvailable } from '../ai/gateway.ts';
+import { chat, embedOne, isAvailable, getEmbeddingModel } from '../ai/gateway.ts';
import { classifyGlobalLlmError } from '../ai/errors.ts';
import { stripReasoningBlocks } from '../llm-json.ts';
import type { ChatResult } from '../ai/gateway.ts';
@@ -648,9 +648,11 @@ export async function extractFactsFromTurnWithOutcome(
: 'medium';
let embedding: Float32Array | null = null;
+ let embeddingModel: string | null = null;
try {
if (input.embedding !== null) {
- embedding = await embedOne(factText, { abortSignal: input.abortSignal,
+ embeddingModel = input.embedding?.model ?? getEmbeddingModel();
+ embedding = await embedOne(factText, { abortSignal: input.abortSignal, inputType: 'document', embeddingModel,
...(input.embedding ? { embeddingModel: input.embedding.model, dimensions: input.embedding.dimensions } : {}) });
}
} catch (err) {
@@ -689,6 +691,7 @@ export async function extractFactsFromTurnWithOutcome(
confidence,
notability,
embedding,
+ embedding_model: embedding ? embeddingModel : null,
claim_metric: claimMetric,
claim_value: claimValue,
claim_unit: claimUnit,
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index a964dbf5b3..d28423fb38 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -75,6 +75,7 @@ export interface FenceTarget {
/** Input fact prepared by runPipelineWithBody (post-dedup). */
export interface FenceInputFact {
+ embedding_model?: string | null;
fact: string;
kind: NewFact['kind'];
notability: NewFact['notability'];
@@ -512,6 +513,7 @@ export async function writeFactsToFence(
const enriched = toInsert.map((row, i) => ({
...row,
embedding: facts[i].embedding,
+ embedding_model: facts[i].embedding_model,
source_session: facts[i].sessionId,
}));
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 0fd55b18bf..ce39cf4b37 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -1,6 +1,6 @@
import type { BrainEngine, FactRow } from '../engine.ts';
import { verbError } from '../ops/contract.ts';
-import { isAvailable, embedOne } from '../ai/gateway.ts';
+import { isAvailable, embedOne, getEmbeddingModel } from '../ai/gateway.ts';
import { cosineSimilarity } from './classify.ts';
import { isFactWithdrawn } from './withdrawal.ts';
@@ -10,12 +10,15 @@ export interface SingleFactIntent {
fact: string; kind: FactRow['kind']; visibility: FactRow['visibility']; entity_slug: string | null;
}
/** Provider work belongs to preparation, never to a page/source transaction. */
-export async function prepareFactEmbedding(fact: string, signal?: AbortSignal): Promise<{ embedding: Float32Array | null; degraded: boolean }> {
+export async function prepareFactEmbedding(fact: string, signal?: AbortSignal): Promise<{ embedding: Float32Array | null; embedding_model: string | null; degraded: boolean }> {
signal?.throwIfAborted();
if (isAvailable('embedding')) {
- try { return { embedding: await embedOne(fact, { abortSignal: signal }), degraded: false }; } catch { signal?.throwIfAborted(); }
+ try {
+ const model = getEmbeddingModel();
+ return { embedding: await embedOne(fact, { abortSignal: signal, embeddingModel: model, inputType: 'document' }), embedding_model: model, degraded: false };
+ } catch { signal?.throwIfAborted(); }
}
- return { embedding: null, degraded: true };
+ return { embedding: null, embedding_model: null, degraded: true };
}
export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: string, input: SingleFactIntent): Promise<void> {
if (await isFactWithdrawn(engine, sourceId, input.visibility, input.fact)) {
@@ -24,14 +27,14 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: stri
}
}
/** SQL-only, so publication can verify the semantic decision under its guard. */
-export async function decideSingleFact(engine: BrainEngine, sourceId: string, input: SingleFactIntent, embedding: Float32Array | null): Promise<FactDecision> {
+export async function decideSingleFact(engine: BrainEngine, sourceId: string, input: SingleFactIntent, embedding: Float32Array | null, embeddingModel?: string | null): Promise<FactDecision> {
const [exact] = await engine.executeRaw<FactCandidate>(`SELECT * FROM facts WHERE source_id=$1
AND entity_slug IS NOT DISTINCT FROM $2 AND visibility=$3 AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until>now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($4)
ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact]);
if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };
if (embedding && input.entity_slug) {
- const candidates = await engine.findCandidateDuplicates(sourceId, input.entity_slug, input.fact, { embedding, k: 5 });
+ const candidates = await engine.findCandidateDuplicates(sourceId, input.entity_slug, input.fact, { embedding, embeddingModel, k: 5 });
const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null }>(
'SELECT id,source_markdown_slug,row_num FROM facts WHERE source_id=$1 AND id=ANY($2::int[])',
[sourceId, candidates.map(c => c.id)]);
diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.ts
new file mode 100644
index 0000000000..8b6d5977cd
--- /dev/null
+++ b/src/core/facts/withdrawal-discovery.ts
@@ -0,0 +1,91 @@
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { getCode } from '../retry-matcher.ts';
+import { parseRowCells, isSeparatorRow, stripStrikethrough } from '../fence-shared.ts';
+import { withdrawalFenceBlocks, ambiguousWithdrawalFenceSegments } from './withdrawal-overlay.ts';
+
+export const WITHDRAWAL_LIMITS = { pages: 12_000, chunks: 40_000, facts: 40_000, bytes: 64 * 1024 * 1024, targets: 256, targetBytes: 1024 * 1024, scanMs: 10_000, batch: 128 } as const;
+export interface WithdrawalTarget { slug: string; page_id: number; revision: string }
+export interface WithdrawalClaim { visibility: string; fact_hash: string }
+
+function refuse(code = 'withdrawal_capacity'): never {
+ throw new OperationError(code, 'Withdrawal discovery could not prove a bounded complete target set. This attempt committed no withdrawal or page changes; earlier durable intent remains retained.',
+ 'Do not retry unchanged or split/delete the source. Keep mutation workers quiesced and inspect the source with the host operator; repair malformed fact fences before retrying. See docs/guides/concurrent-writes.md#withdrawal-recovery.');
+}
+
+export function ambiguousFenceClaims(body: string): Array<{ claim: string; visibility: string | null }> {
+ const claims: Array<{ claim: string; visibility: string | null }> = [];
+ for (const segment of ambiguousWithdrawalFenceSegments(body)) for (const line of segment.split('\n')) {
+ const cells = parseRowCells(line);
+ if (!cells || isSeparatorRow(cells) || cells[1]?.trim().toLowerCase() === 'claim') continue;
+ const { text, struck } = stripStrikethrough((cells[1] ?? '').trim());
+ if (!struck && text) claims.push({ claim: text, visibility: ['private', 'world'].includes(cells[4]?.toLowerCase()) ? cells[4].toLowerCase() : null });
+ }
+ return claims;
+}
+
+export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: string, claims: readonly WithdrawalClaim[]): Promise<WithdrawalTarget[]> {
+ if (!claims.length) return [];
+ if (claims.length > WITHDRAWAL_LIMITS.targets) refuse();
+ const deadline = performance.now() + WITHDRAWAL_LIMITS.scanMs;
+ const pageSizes = await engine.executeRaw<{ id: number; bytes: number }>(`SELECT id,octet_length(compiled_truth)+octet_length(timeline) AS bytes
+ FROM pages WHERE source_id=$1 ORDER BY id LIMIT $2`, [sourceId, WITHDRAWAL_LIMITS.pages + 1]);
+ const chunkSizes = await engine.executeRaw<{ id: number; bytes: number }>(`SELECT c.id,octet_length(c.chunk_text) AS bytes FROM content_chunks c
+ JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 ORDER BY c.id LIMIT $2`, [sourceId, WITHDRAWAL_LIMITS.chunks + 1]);
+ const factSizes = await engine.executeRaw<{ id: number; bytes: number }>(`SELECT id,octet_length(fact) AS bytes FROM facts
+ WHERE source_id=$1 ORDER BY id LIMIT $2`, [sourceId, WITHDRAWAL_LIMITS.facts + 1]);
+ if (pageSizes.length > WITHDRAWAL_LIMITS.pages || chunkSizes.length > WITHDRAWAL_LIMITS.chunks || factSizes.length > WITHDRAWAL_LIMITS.facts ||
+ [...pageSizes, ...chunkSizes, ...factSizes].reduce((sum, row) => sum + Number(row.bytes), 0) > WITHDRAWAL_LIMITS.bytes) refuse();
+ const affected = new Set<number>();
+ const provenance = await engine.executeRaw<{ id: number }>(`SELECT DISTINCT p.id FROM facts f
+ JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)
+ JOIN jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text)
+ ON w.visibility=f.visibility AND w.fact_hash=gbrain_fact_fingerprint(f.fact) WHERE f.source_id=$1`, [sourceId, JSON.stringify(claims)]);
+ for (const row of provenance) affected.add(row.id);
+ if (affected.size > WITHDRAWAL_LIMITS.targets) refuse();
+ const match = async (incoming: Array<{ id: number; claim: string; visibility: string | null; ambiguous: boolean }>) => {
+ if (!incoming.length) return;
+ if (incoming.length > 16_384 || Buffer.byteLength(JSON.stringify(incoming)) > 8 * 1024 * 1024) refuse();
+ const matches = await engine.executeRaw<{ id: number; ambiguous: boolean }>(`SELECT DISTINCT i.id,i.ambiguous
+ FROM jsonb_to_recordset($1::text::jsonb) i(id integer,claim text,visibility text,ambiguous boolean)
+ JOIN jsonb_to_recordset($2::text::jsonb) w(visibility text,fact_hash text)
+ ON (i.visibility IS NULL OR i.visibility=w.visibility) AND gbrain_fact_fingerprint(i.claim)=w.fact_hash`, [JSON.stringify(incoming), JSON.stringify(claims)]);
+ if (matches.some(row => row.ambiguous)) refuse('withdrawal_provenance');
+ for (const row of matches) affected.add(row.id);
+ if (affected.size > WITHDRAWAL_LIMITS.targets) refuse();
+ };
+ for (let offset = 0; offset < pageSizes.length; offset += WITHDRAWAL_LIMITS.batch) {
+ if (performance.now() > deadline) refuse();
+ const pages = await engine.executeRaw<{ id: number; compiled_truth: string; timeline: string }>(
+ 'SELECT id,compiled_truth,timeline FROM pages WHERE source_id=$1 AND id=ANY($2::int[])', [sourceId, pageSizes.slice(offset, offset + WITHDRAWAL_LIMITS.batch).map(row => row.id)]);
+ const incoming = pages.flatMap(page => [page.compiled_truth, page.timeline].flatMap(body => [
+ ...withdrawalFenceBlocks(body).filter(block => !block.parsed.warnings.length).flatMap(block => block.parsed.facts.map(f => ({ id: page.id, claim: f.claim, visibility: f.visibility, ambiguous: false }))),
+ ...ambiguousFenceClaims(body).map(f => ({ id: page.id, ...f, ambiguous: true })),
+ ]));
+ await match(incoming);
+ }
+ for (let offset = 0; offset < chunkSizes.length; offset += WITHDRAWAL_LIMITS.batch) {
+ if (performance.now() > deadline) refuse();
+ const chunks = await engine.executeRaw<{ page_id: number; chunk_text: string }>(
+ 'SELECT page_id,chunk_text FROM content_chunks WHERE id=ANY($1::int[])', [chunkSizes.slice(offset, offset + WITHDRAWAL_LIMITS.batch).map(row => row.id)]);
+ await match(chunks.flatMap(chunk => {
+ const rows = [{ id: chunk.page_id, claim: chunk.chunk_text, visibility: null as string | null, ambiguous: false }];
+ for (const line of chunk.chunk_text.split('\n')) {
+ const cells = parseRowCells(line.slice(Math.max(0, line.indexOf('|'))));
+ if (!cells || isSeparatorRow(cells) || !cells[1]) continue;
+ const { text, struck } = stripStrikethrough(cells[1]);
+ if (!struck) rows.push({ id: chunk.page_id, claim: text, visibility: ['private', 'world'].includes(cells[4]) ? cells[4] : null, ambiguous: false });
+ }
+ return rows;
+ }));
+ }
+ if (affected.size > WITHDRAWAL_LIMITS.targets) refuse();
+ const targets = await engine.executeRaw<WithdrawalTarget>('SELECT slug,id AS page_id,knowledge_revision AS revision FROM pages WHERE source_id=$1 AND id=ANY($2::int[])', [sourceId, [...affected]]);
+ if (performance.now() > deadline || Buffer.byteLength(JSON.stringify(targets)) > WITHDRAWAL_LIMITS.targetBytes) refuse();
+ return targets.sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
+}
+
+export function withdrawalDiscoveryFailure(error: unknown): never {
+ if (getCode(error) === '57014') refuse();
+ throw error;
+}
diff --git a/src/core/facts/withdrawal-overlay.ts b/src/core/facts/withdrawal-overlay.ts
index 5fe16e2a19..de9a59e353 100644
--- a/src/core/facts/withdrawal-overlay.ts
+++ b/src/core/facts/withdrawal-overlay.ts
@@ -1,4 +1,9 @@
-import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, type ParsedFact } from '../facts-fence.ts';
+import { createHash } from 'node:crypto';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fence.ts';
+import type { PageWithdrawal } from '../page-state/types.ts';
+import { OperationError } from '../ops/contract.ts';
+
+export const WITHDRAWAL_MARKER_LIMIT = 16_384;
/** Preserve historical expiry and context while emitting the parser's explicit withdrawal marker. */
export function withdrawnFact(fact: ParsedFact, date: string, reason = 'memory withdrawn'): ParsedFact {
@@ -12,16 +17,117 @@ export function withdrawnFact(fact: ParsedFact, date: string, reason = 'memory w
/** Enumerate every complete legacy fence; leave ambiguous tails untouched for diagnostics. */
export function withdrawalFenceBlocks(body: string): Array<{ start: number; end: number; parsed: ReturnType<typeof parseFactsFence> }> {
const blocks: Array<{ start: number; end: number; parsed: ReturnType<typeof parseFactsFence> }> = [];
- let cursor = 0;
- while (cursor < body.length) {
- const start = body.indexOf(FACTS_FENCE_BEGIN, cursor);
- if (start < 0) break;
- const endMarker = body.indexOf(FACTS_FENCE_END, start + FACTS_FENCE_BEGIN.length);
- const nested = body.indexOf(FACTS_FENCE_BEGIN, start + FACTS_FENCE_BEGIN.length);
- if (endMarker < 0 || (nested >= 0 && nested < endMarker)) break;
- const end = endMarker + FACTS_FENCE_END.length;
- blocks.push({ start, end, parsed: parseFactsFence(body.slice(start, end)) });
- cursor = end;
+ const markers = literalFenceMarkers(body);
+ let open: { start: number } | undefined;
+ for (const marker of markers) {
+ if (marker.kind === 'begin') {
+ if (marker.inlineCode) continue;
+ open = { start: marker.start };
+ continue;
+ }
+ if (!open) continue;
+ blocks.push({ start: open.start, end: marker.end, parsed: parseFactsFence(body.slice(open.start, marker.end)) });
+ open = undefined;
+ }
+ const inline: typeof blocks = [];
+ let blockIndex = 0;
+ for (const candidate of inlineCodeFenceBlocks(body, markers)) {
+ while (blockIndex < blocks.length && blocks[blockIndex].end <= candidate.start) blockIndex++;
+ if (!blocks[blockIndex] || candidate.end <= blocks[blockIndex].start) inline.push(candidate);
+ }
+ return [...blocks, ...inline].sort((a, b) => a.start - b.start);
+}
+
+interface FenceMarker { start: number; end: number; kind: 'begin' | 'end'; inlineCode: boolean }
+
+function literalFenceMarkers(body: string): FenceMarker[] {
+ const markers: FenceMarker[] = [];
+ const tokens = new RegExp([FACTS_FENCE_BEGIN, FACTS_FENCE_END, '`'].join('|'), 'g');
+ let offset = 0;
+ for (const line of body.split('\n')) {
+ let ticks = 0;
+ const lastTick = line.lastIndexOf('`');
+ for (const token of line.matchAll(tokens)) {
+ if (token[0] === '`') { ticks++; continue; }
+ if (markers.length >= WITHDRAWAL_MARKER_LIMIT) throw new OperationError('withdrawal_capacity',
+ 'The fact-fence marker limit was exceeded; incomplete withdrawal discovery is refused.',
+ 'Inspect and repair excessive malformed fact fences on the host before retrying. See docs/guides/concurrent-writes.md#withdrawal-recovery.');
+ const start = offset + token.index;
+ markers.push({ start, end: start + token[0].length, kind: token[0] === FACTS_FENCE_BEGIN ? 'begin' : 'end',
+ inlineCode: ticks % 2 === 1 && lastTick >= token.index + token[0].length });
+ }
+ offset += line.length + 1;
+ }
+ return markers;
+}
+
+function inlineCodeFenceBlocks(body: string, markers: FenceMarker[]): Array<{ start: number; end: number; parsed: ReturnType<typeof parseFactsFence> }> {
+ const blocks: Array<{ start: number; end: number; parsed: ReturnType<typeof parseFactsFence> }> = [];
+ for (let i = 0; i < markers.length; i++) {
+ const begin = markers[i], end = markers[i + 1];
+ if (begin.kind !== 'begin' || end?.kind !== 'end' || !(begin.inlineCode || end.inlineCode)) continue;
+ const parsed = parseFactsFence(body.slice(begin.start, end.end));
+ if (parsed.facts.length || parsed.warnings.length) blocks.push({ start: begin.start, end: end.end, parsed });
}
return blocks;
}
+
+/** Return only malformed live fence segments. */
+export function ambiguousWithdrawalFenceSegments(body: string): string[] {
+ const markers = literalFenceMarkers(body), segments: string[] = [], inlineBlocks = inlineCodeFenceBlocks(body, markers);
+ const inlineEnds = new Set(inlineBlocks.map(block => block.end));
+ let boundary = 0;
+ let open: { start: number } | undefined;
+ for (const marker of markers) {
+ if (marker.kind === 'begin') {
+ if (marker.inlineCode) continue;
+ if (open) segments.push(body.slice(open.start, marker.start));
+ open = { start: marker.start };
+ continue;
+ }
+ if (!open) {
+ if (inlineEnds.has(marker.end)) { boundary = marker.end; continue; }
+ if (marker.inlineCode) continue;
+ segments.push(body.slice(boundary, marker.end));
+ boundary = marker.end;
+ continue;
+ }
+ const segment = body.slice(open.start, marker.end);
+ if (parseFactsFence(segment).warnings.length) segments.push(segment);
+ boundary = marker.end;
+ open = undefined;
+ }
+ if (open) segments.push(body.slice(open.start));
+ for (const block of inlineBlocks) {
+ if (block.parsed.warnings.length) segments.push(body.slice(block.start, block.end));
+ }
+ return segments;
+}
+
+/** A shortlisted claim inside an unparseable live fence is conservatively page-affecting. */
+export function hasAmbiguousWithdrawalFence(body: string): boolean {
+ return ambiguousWithdrawalFenceSegments(body).length > 0;
+}
+
+/** Apply hashes from DB-normalized companion text to the original Markdown. */
+export function overlayWithdrawalBody(body: string, normalizedBody: string, withdrawals: PageWithdrawal[]): string {
+ if (!withdrawals.length || !body.includes('gbrain:facts:begin')) return body;
+ const ledger = new Map(withdrawals.map(w => [`${w.visibility}:${w.fact_hash}`, w.withdrawn_at]));
+ const blocks = withdrawalFenceBlocks(body), normalized = withdrawalFenceBlocks(normalizedBody);
+ for (let i = blocks.length - 1; i >= 0; i--) {
+ const block = blocks[i], norm = normalized[i];
+ if (!norm || block.parsed.warnings.length || norm.parsed.warnings.length) continue;
+ const claims = new Map(norm.parsed.facts.map(f => [f.rowNum, f.claim]));
+ let changed = false;
+ const facts = block.parsed.facts.map(f => {
+ const claim = claims.get(f.rowNum);
+ if (claim === undefined) return f;
+ const at = ledger.get(`${f.visibility}:${createHash('sha256').update(claim).digest('hex')}`);
+ if (!at) return f;
+ changed = true;
+ return withdrawnFact(f, new Date(at).toISOString().slice(0, 10));
+ });
+ if (changed) body = body.slice(0, block.start) + renderFactsTable(facts) + body.slice(block.end);
+ }
+ return body;
+}
diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.ts
index f23fec466f..305ae3904d 100644
--- a/src/core/facts/withdrawal.ts
+++ b/src/core/facts/withdrawal.ts
@@ -1,6 +1,8 @@
import type { BrainEngine } from '../engine.ts';
import { renderFactsTable, type ParsedFact } from '../facts-fence.ts';
+import { OperationError } from '../ops/contract.ts';
import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';
+import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';
export interface WithdrawalCommit {
withdrawn: boolean;
@@ -16,14 +18,15 @@ export async function recordFactWithdrawal(
// A managed caller takes this EXCLUSIVE source lock before authority,
// counters and request rows. Repeating an already-held lock is safe.
await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
- const visible = await tx.executeRaw<{ visibility: string; fact: string }>(
- `SELECT visibility,fact FROM facts WHERE id=$1 AND source_id=$2
+ const visible = await tx.executeRaw<{ visibility: 'private' | 'world'; fact: string; fact_hash: string }>(
+ `SELECT visibility,fact,gbrain_fact_fingerprint(fact) AS fact_hash FROM facts WHERE id=$1 AND source_id=$2
AND ($3::boolean=false OR visibility='world')`, [id, sourceId, worldOnly]);
if (!visible.length) return { withdrawn: false, pages: [] };
- // Derived provenance can be incomplete or already rebuilt. Conservatively
- // invalidate this source's pages rather than miss an unindexed duplicate.
- const pageKeys = await tx.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 ORDER BY slug', [sourceId]);
- await tx.lockPageKeys(pageKeys.map(page => ({ sourceId, slug: page.slug })));
+ const target = visible[0];
+ const existing = await tx.executeRaw(`SELECT 1 FROM fact_withdrawals
+ WHERE source_id=$1 AND visibility=$2 AND fact_hash=$3 LIMIT 1`, [sourceId, target.visibility, target.fact_hash]);
+ const affected = existing.length ? [] : await discoverWithdrawalTargets(tx, sourceId, [target]).catch(withdrawalDiscoveryFailure);
+ await tx.lockPageKeys(affected.map(({ slug }) => ({ sourceId, slug })));
const rows = await tx.executeRaw<{ visibility: string; fact: string }>(
`SELECT visibility,fact FROM facts WHERE id=$1 AND source_id=$2
AND ($3::boolean=false OR visibility='world') FOR UPDATE`, [id, sourceId, worldOnly]);
@@ -37,21 +40,31 @@ export async function recordFactWithdrawal(
if (!inserted.length) return { withdrawn: false, pages: [] };
// Logical revision and projection invalidation commit with the withdrawal.
// The revision trigger queues durable rebuild work even for unmanaged calls.
- const pages = await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
+ const pages = affected.length ? await tx.executeRaw<{ id: number; slug: string; knowledge_revision: string }>(
`UPDATE pages SET knowledge_revision=gen_random_uuid(),text_projection_revision=NULL,embedding_signature=NULL
- WHERE source_id=$1 RETURNING id,slug,knowledge_revision`, [sourceId]);
- await tx.executeRaw('DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE source_id=$1)', [sourceId]);
+ WHERE source_id=$1 AND slug=ANY($2::text[]) RETURNING id,slug,knowledge_revision`, [sourceId, affected.map(page => page.slug)]) : [];
+ if (pages.length) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=ANY($1::integer[])', [pages.map(page => page.id)]);
if (opts.requestId) {
await tx.executeRaw(`INSERT INTO persistence_effects(request_id,kind,data,source_id,source_incarnation,worktree_id)
- SELECT $1::uuid,k.kind,jsonb_build_object('source_id',s.id,'source_scan',true),s.id,s.incarnation,b.worktree_id
+ SELECT $1::uuid,k.kind,$3::text::jsonb,s.id,s.incarnation,b.worktree_id
FROM sources s LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
CROSS JOIN (VALUES ('withdrawal-mirror'),('git'),('embedding')) AS k(kind)
- WHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [opts.requestId, sourceId]);
+ WHERE s.id=$2 ON CONFLICT(request_id,kind) DO NOTHING`, [opts.requestId, sourceId, JSON.stringify({ version: 2, targets: pages.map(page => ({ slug: page.slug, page_id: page.id, revision: page.knowledge_revision })).sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0) })]);
}
return { withdrawn: true, pages: pages.map(page => ({ sourceId, slug: page.slug, revision: page.knowledge_revision })) };
});
}
+async function ambiguousFenceMatchesWithdrawal(engine: BrainEngine, sourceId: string, bodies: readonly string[]): Promise<boolean> {
+ const claims = bodies.flatMap(ambiguousFenceClaims);
+ if (!claims.length) return false;
+ const rows = await engine.executeRaw(`SELECT 1 FROM jsonb_to_recordset($2::text::jsonb) incoming(claim text,visibility text)
+ JOIN fact_withdrawals w ON w.source_id=$1 AND w.fact_hash=gbrain_fact_fingerprint(incoming.claim)
+ AND (incoming.visibility IS NULL OR w.visibility=incoming.visibility) LIMIT 1`,
+ [sourceId, JSON.stringify(claims)]);
+ return rows.length > 0;
+}
+
async function withdrawalDates(engine: BrainEngine, sourceId: string, facts: readonly ParsedFact[]): Promise<Map<number,string>> {
if (!facts.length) return new Map();
const rows = await engine.executeRaw<{ row_num: number; withdrawn_at: string }>(
@@ -82,6 +95,21 @@ export async function preserveWithdrawnFenceRows(engine: BrainEngine, sourceId:
return body;
}
+/** Refuse provider-free preparation that raced a newly committed withdrawal. */
+export async function assertPreparedFactWithdrawals(engine: BrainEngine, sourceId: string, body: string, timeline: string): Promise<void> {
+ const changed = await preserveWithdrawnFenceRows(engine, sourceId, body) !== body ||
+ await preserveWithdrawnFenceRows(engine, sourceId, timeline) !== timeline;
+ const blocked = await ambiguousFenceMatchesWithdrawal(engine, sourceId, [body, timeline]);
+ if (changed) {
+ throw new OperationError('revision_conflict', 'A fact withdrawal changed during import preparation. Retry the import.',
+ 'Read the current page revision, then submit the updated import with a new request_id.');
+ }
+ if (blocked) {
+ throw new OperationError('invalid_params', 'A malformed fact fence contains a withdrawn claim.',
+ 'Repair the matching fence row, then retry the import.');
+ }
+}
+
/** Explicit remember is not an implicit restore operation. */
export async function isFactWithdrawn(engine: BrainEngine, sourceId: string, visibility: string, claim: string): Promise<boolean> {
const rows = await engine.executeRaw(`SELECT 1 FROM fact_withdrawals
diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts
index 550de753ab..08aab7f113 100644
--- a/src/core/facts/write-single.ts
+++ b/src/core/facts/write-single.ts
@@ -82,7 +82,7 @@ export async function writeSingleFact(
const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
const { cosineSimilarity } = await import('./classify.ts');
const { writeFactsToFence, lookupSourceLocalPath } = await import('./fence-write.ts');
- const { isAvailable, embedOne } = await import('../ai/gateway.ts');
+ const { isAvailable, embedOne, getEmbeddingModel } = await import('../ai/gateway.ts');
const factText = input.fact.trim();
const kind = input.kind ?? 'fact';
@@ -112,10 +112,12 @@ export async function writeSingleFact(
// Embedding (NOT an LLM call): powers dedup + downstream recall. Fail-soft —
// a missing/failing provider degrades dedup, never the write.
let embedding: Float32Array | null = null;
+ let embeddingModel: string | null = null;
let degradedDedup = false;
if (isAvailable('embedding')) {
try {
- embedding = await embedOne(factText);
+ embeddingModel = getEmbeddingModel();
+ embedding = await embedOne(factText, { embeddingModel, inputType: 'document' });
} catch {
degradedDedup = true;
}
@@ -128,6 +130,7 @@ export async function writeSingleFact(
if (resolvedSlug && embedding) {
const candidates = await engine.findCandidateDuplicates(sourceId, resolvedSlug, factText, {
embedding,
+ embeddingModel,
k: DEDUP_CANDIDATE_LIMIT,
});
let top: (typeof candidates)[number] | null = null;
@@ -166,6 +169,7 @@ export async function writeSingleFact(
confidence: input.confidence ?? 1.0,
valid_until: validUntil,
embedding,
+ embedding_model: embedding ? embeddingModel : null,
};
// Fence-first write (markdown durability — same policy as the pipeline):
@@ -191,6 +195,7 @@ export async function writeSingleFact(
validFrom: new Date(),
validUntil,
embedding,
+ embedding_model: embedding ? embeddingModel : null,
sessionId: input.sessionId ?? null,
},
],
diff --git a/src/core/google/attachment-backfill.ts b/src/core/google/attachment-backfill.ts
new file mode 100644
index 0000000000..dd80707208
--- /dev/null
+++ b/src/core/google/attachment-backfill.ts
@@ -0,0 +1,107 @@
+import type { BrainEngine } from '../engine.ts';
+import { withConnectorSync, type ManagedConnectorSync } from '../persistence/connector-sync.ts';
+import { OperationError } from '../ops/contract.ts';
+import { GmailClient, GoogleCursorExpiredError, type FetchImpl } from './google-clients.ts';
+import type { GmailThreadAttachmentReceipts, GoogleSourceConfig, GoogleSourceState } from './types.ts';
+import { threadAttachmentReceipts } from './attachment-receipts.ts';
+import { CommandAccessProvider, EnvAccessProvider, type GoogleAccessProvider } from './access.ts';
+import { credentialId, openVault, type CredentialVault } from '../creds/vault.ts';
+import { GOOGLE_PROVIDER, GoogleTokenProvider } from '../creds/providers/google.ts';
+import { CredentialError } from '../creds/errors.ts';
+
+export const GMAIL_ATTACHMENT_BACKFILL_LIMIT = 25;
+
+export async function runGoogleAttachmentBackfill(engine: BrainEngine, sourceId: string, cfg: GoogleSourceConfig,
+ opts: { limit?: number; signal?: AbortSignal; retryFailed?: boolean } = {}, fetchImpl: FetchImpl = fetch, vaultOverride?: CredentialVault) {
+ return withConnectorSync(engine, sourceId, 'google', cfg, {
+ sourceId, noEmbed: true, noExtract: true, noSchemaPack: true, signal: opts.signal, retryFailed: opts.retryFailed,
+ }, async (managed, options) => {
+ if (!managed) throw new OperationError('writer_coordinator_required', 'Historical attachment repair requires managed persistence. No metadata was changed.');
+ if (!cfg.account || !cfg.services.includes('gmail')) throw new OperationError('invalid_params', 'Select a Gmail source for attachment repair.');
+ let tokens: GoogleAccessProvider;
+ if (cfg.access === 'command') tokens = new CommandAccessProvider(cfg.tokenCommand ?? '');
+ else if (cfg.access === 'env') tokens = new EnvAccessProvider(cfg.tokenEnv ?? '');
+ else {
+ const vault = vaultOverride ?? openVault();
+ const id = credentialId(GOOGLE_PROVIDER, cfg.account);
+ const entry = await vault.get(id);
+ if (!entry) throw new CredentialError('not_connected');
+ if (entry.meta.scopes?.length && !entry.meta.scopes.includes('https://www.googleapis.com/auth/gmail.readonly')) throw new CredentialError('scope_missing');
+ tokens = new GoogleTokenProvider(vault, id, fetchImpl);
+ }
+ const gmail = new GmailClient(tokens, fetchImpl);
+ const profile = await gmail.getProfile({ signal: options.signal });
+ if (profile.emailAddress?.toLowerCase() !== cfg.account) {
+ throw new OperationError('source_changed', 'The Gmail credential belongs to a different account. No metadata was changed.');
+ }
+ const state = managed.state<GoogleSourceState>({ gmail_history_id: null, gmail_backfill_floor_ms: null,
+ gmail_backfill_done: false, gmail_newest_ms: null, calendar_sync_token: null, contacts_sync_token: null, last_full_at: null });
+ return backfillGmailAttachments(engine, managed, gmail, state, cfg.account, opts.limit, options.signal);
+ });
+}
+
+export async function backfillGmailAttachments(engine: BrainEngine, managed: ManagedConnectorSync, gmail: GmailClient,
+ state: GoogleSourceState, account: string, limit = GMAIL_ATTACHMENT_BACKFILL_LIMIT, signal?: AbortSignal) {
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > GMAIL_ATTACHMENT_BACKFILL_LIMIT) {
+ throw new OperationError('invalid_params', `Attachment backfill limit must be 1-${GMAIL_ATTACHMENT_BACKFILL_LIMIT}.`);
+ }
+ let cursor = state.gmail_attachment_backfill;
+ if (cursor && (cursor.version !== 1 || cursor.account !== account || !Number.isSafeInteger(cursor.afterPageId) ||
+ !Number.isSafeInteger(cursor.throughPageId) || !Number.isSafeInteger(cursor.inspected) || cursor.inspected < 0 || typeof cursor.complete !== 'boolean' ||
+ !Number.isSafeInteger(cursor.unavailable ?? 0) || (cursor.unavailable ?? 0) < 0 ||
+ !Number.isSafeInteger(cursor.unavailableMessages ?? 0) || (cursor.unavailableMessages ?? 0) < 0 ||
+ cursor.afterPageId < 0 || cursor.throughPageId < cursor.afterPageId)) {
+ throw new OperationError('revision_conflict', 'Attachment backfill checkpoint does not match this account. No metadata was changed.');
+ }
+ if (!cursor) {
+ const [row] = await engine.executeRaw<{ id: number | null }>(
+ `SELECT MAX(id) AS id FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND frontmatter->>'thread_id' IS NOT NULL`, [managed.sourceId]);
+ cursor = { version: 1, account, afterPageId: 0, throughPageId: Number(row?.id ?? 0), inspected: 0, complete: false };
+ state.gmail_attachment_backfill = cursor;
+ await managed.saveState(state);
+ }
+ if (cursor.complete) return { status: 'complete' as const, processed: 0, inspected: cursor.inspected,
+ unavailable: cursor.unavailable ?? 0, unavailableMessages: cursor.unavailableMessages ?? 0,
+ inspection_complete: !cursor.unavailable, complete: true };
+ const rows = await engine.executeRaw<{ id: number; slug: string; thread_id: string; account: string }>(
+ `SELECT id,slug,frontmatter->>'thread_id' AS thread_id,frontmatter->>'account' AS account FROM pages
+ WHERE source_id=$1 AND id>$2 AND id<=$3 AND deleted_at IS NULL AND frontmatter->>'thread_id' IS NOT NULL ORDER BY id LIMIT $4`,
+ [managed.sourceId, cursor.afterPageId, cursor.throughPageId, limit]);
+ let processed = 0;
+ for (const row of rows) {
+ signal?.throwIfAborted();
+ if (row.account !== account || typeof row.thread_id !== 'string' || !/^[A-Za-z0-9]{1,128}$/.test(row.thread_id)) {
+ throw new OperationError('revision_conflict', 'Historical Gmail page ownership is unknown. Content and the current cursor were preserved.');
+ }
+ let fetched: GmailThreadAttachmentReceipts;
+ try {
+ const thread = await gmail.getThread(row.thread_id, account, { signal, metadataOnly: true });
+ if (thread.threadId !== row.thread_id || !thread.messages.length) {
+ throw new OperationError('revision_conflict', 'Gmail metadata does not match the historical page. Content and the current cursor were preserved.');
+ }
+ fetched = threadAttachmentReceipts(thread);
+ } catch (error) {
+ if (!(error instanceof GoogleCursorExpiredError) || error.status !== 404) throw error;
+ fetched = { version: 1, account, threadId: row.thread_id, unavailable: 'thread_not_found', messages: [] };
+ }
+ const receipts = await managed.patchGoogleReceipts(row.slug, fetched, Number(row.id));
+ if (receipts.messages.some(m => !m.unavailable && (m.inspection.state === 'incomplete' || m.inspection.state === 'not_inspected'))) {
+ return { status: 'incomplete' as const, processed, inspected: cursor.inspected,
+ unavailable: cursor.unavailable ?? 0, unavailableMessages: cursor.unavailableMessages ?? 0, inspection_complete: false, complete: false };
+ }
+ const unavailable = receipts.messages.filter(m => m.unavailable).length;
+ processed++;
+ cursor = { ...cursor, afterPageId: Number(row.id), inspected: cursor.inspected + (unavailable ? 0 : 1),
+ unavailable: (cursor.unavailable ?? 0) + (unavailable ? 1 : 0), unavailableMessages: (cursor.unavailableMessages ?? 0) + unavailable };
+ state.gmail_attachment_backfill = cursor;
+ await managed.saveState(state);
+ }
+ if (rows.length < limit || cursor.afterPageId === cursor.throughPageId) {
+ cursor = { ...cursor, complete: true };
+ state.gmail_attachment_backfill = cursor;
+ await managed.saveState(state);
+ }
+ return { status: cursor.complete ? 'complete' as const : 'paused' as const, processed, inspected: cursor.inspected,
+ unavailable: cursor.unavailable ?? 0, unavailableMessages: cursor.unavailableMessages ?? 0,
+ inspection_complete: cursor.complete && !cursor.unavailable, complete: cursor.complete };
+}
diff --git a/src/core/google/attachment-receipts.ts b/src/core/google/attachment-receipts.ts
new file mode 100644
index 0000000000..f12fd4fcdd
--- /dev/null
+++ b/src/core/google/attachment-receipts.ts
@@ -0,0 +1,119 @@
+import { createHash } from 'node:crypto';
+import type { GmailAttachmentInspection, GmailAttachmentReceipt, GmailThreadData } from './types.ts';
+
+export interface GmailMimePart {
+ partId?: string;
+ mimeType?: string;
+ filename?: string;
+ headers?: Array<{ name: string; value: string }>;
+ body?: { data?: string; size?: number; attachmentId?: string };
+ parts?: GmailMimePart[];
+}
+
+export const GMAIL_MIME_LIMITS = { depth: 32, parts: 512, receiptBytes: 65_536 } as const;
+
+export function walkGmailMime(root: GmailMimePart | undefined): {
+ parts: Array<{ part: GmailMimePart; path: string }>;
+ reason?: GmailAttachmentInspection['reason'];
+} {
+ const parts: Array<{ part: GmailMimePart; path: string }> = [];
+ if (!root) return { parts, reason: 'missing_payload' };
+ const stack = [{ nodes: [root], index: 0, path: '', depth: 0 }];
+ let reason: GmailAttachmentInspection['reason'];
+ let visited = 0;
+ while (stack.length) {
+ const frame = stack[stack.length - 1];
+ if (frame.index >= frame.nodes.length) { stack.pop(); continue; }
+ if (visited++ >= GMAIL_MIME_LIMITS.parts) { reason = 'part_limit'; break; }
+ const index = frame.index++;
+ const part = frame.nodes[index];
+ if (!part || typeof part !== 'object' || Array.isArray(part)) { reason ??= 'malformed_part'; continue; }
+ const path = frame.path ? `${frame.path}.${index}` : String(index);
+ parts.push({ part, path });
+ if (part.parts !== undefined && !Array.isArray(part.parts)) { reason ??= 'malformed_part'; continue; }
+ if (part.parts?.length) {
+ if (frame.depth >= GMAIL_MIME_LIMITS.depth) reason ??= 'depth_limit';
+ else stack.push({ nodes: part.parts, index: 0, path, depth: frame.depth + 1 });
+ }
+ }
+ return { parts, ...(reason ? { reason } : {}) };
+}
+
+export function gmailPartHeader(part: GmailMimePart | undefined, name: string): string {
+ if (!Array.isArray(part?.headers)) return '';
+ const header = part.headers.slice(0, GMAIL_MIME_LIMITS.parts).find(h => typeof h?.name === 'string' && h.name.toLowerCase() === name.toLowerCase());
+ return typeof header?.value === 'string' ? header.value.slice(0, GMAIL_MIME_LIMITS.receiptBytes) : '';
+}
+
+export function inspectGmailAttachments(root: GmailMimePart | undefined, account: string, messageId: string, receiptBudget: number = GMAIL_MIME_LIMITS.receiptBytes): GmailAttachmentInspection {
+ if (receiptBudget <= 0) return { state: 'incomplete', reason: 'receipt_bytes_limit', attachments: [] };
+ const walk = walkGmailMime(root);
+ let reason = walk.reason;
+ const attachments: GmailAttachmentReceipt[] = [];
+ let bytes = 0;
+ for (const { part, path } of walk.parts) {
+ if (!part.mimeType && !part.filename && !part.body && !part.parts?.length) reason ??= 'malformed_part';
+ if (part.body !== undefined && (!part.body || typeof part.body !== 'object' || Array.isArray(part.body))) reason ??= 'malformed_part';
+ if (part.body?.size !== undefined && (typeof part.body.size !== 'number' || !Number.isSafeInteger(part.body.size) || part.body.size < 0)) reason ??= 'malformed_part';
+ if (part.headers !== undefined && (!Array.isArray(part.headers) || part.headers.slice(0, GMAIL_MIME_LIMITS.parts).some(h => !h || typeof h.name !== 'string' || typeof h.value !== 'string'))) reason ??= 'malformed_part';
+ if (Array.isArray(part.headers) && part.headers.length > GMAIL_MIME_LIMITS.parts) reason ??= 'part_limit';
+ if ([part.filename, part.mimeType, part.partId, part.body?.attachmentId].some(v => v !== undefined && typeof v !== 'string')) {
+ reason ??= 'malformed_part';
+ continue;
+ }
+ const filename = part.filename ?? '';
+ const mimeType = part.mimeType ?? 'application/octet-stream';
+ const partId = part.partId || `path:${path}`;
+ const fields = [filename, mimeType, partId, part.body?.attachmentId ?? '', account, messageId];
+ if (fields.some(v => v.length > GMAIL_MIME_LIMITS.receiptBytes)) {
+ reason = 'receipt_bytes_limit'; break;
+ }
+ if (fields.some(v => v.includes('\0') || Buffer.from(v).toString('utf8') !== v)) {
+ reason ??= 'malformed_part'; continue;
+ }
+ const mime = mimeType.split(';')[0].trim().toLowerCase();
+ const disposition = gmailPartHeader(part, 'Content-Disposition').split(';')[0].trim().toLowerCase();
+ if (mime.startsWith('multipart/') && !part.parts?.length) reason ??= 'malformed_part';
+ if ((!part.mimeType || !mime) && !filename && !part.body?.attachmentId && !part.parts?.length &&
+ disposition !== 'attachment' && disposition !== 'inline' && !gmailPartHeader(part, 'Content-ID')) {
+ reason ??= 'malformed_part';
+ continue;
+ }
+ const calendar = mime === 'text/calendar' || mime === 'application/ics';
+ const body = mime === 'text/plain' || mime === 'text/html' || mime.startsWith('multipart/');
+ if (!filename && disposition !== 'attachment' && !calendar && body) continue;
+ if (!filename && !part.body?.attachmentId && !calendar && mime !== 'message/rfc822' && disposition !== 'attachment' && (!part.body || mime.startsWith('multipart/'))) continue;
+ const receipt: GmailAttachmentReceipt = {
+ id: createHash('sha256').update(JSON.stringify([account.toLowerCase(), messageId, partId, path])).digest('hex'),
+ account, messageId, partId, filename, mimeType,
+ size: typeof part.body?.size === 'number' && Number.isSafeInteger(part.body.size) && part.body.size >= 0 ? part.body.size : null,
+ attachmentId: part.body?.attachmentId || null,
+ kind: calendar ? 'calendar' : disposition === 'inline' || gmailPartHeader(part, 'Content-ID') ? 'inline' : 'document',
+ fetched: false, indexed: false,
+ };
+ bytes += Buffer.byteLength(JSON.stringify(receipt));
+ if (bytes > Math.min(receiptBudget, GMAIL_MIME_LIMITS.receiptBytes)) { reason = 'receipt_bytes_limit'; break; }
+ attachments.push(receipt);
+ }
+ return { state: reason ? 'incomplete' : attachments.length ? 'present' : 'none', attachments, ...(reason ? { reason } : {}) };
+}
+
+function escaped(value: string): string {
+ return value.replace(/[&<>"'`\[\]\\*_{}|\r\n\u0000-\u001f\u007f]/g, c => `&#${c.charCodeAt(0)};`);
+}
+
+export function renderAttachmentInspection(inspection?: GmailAttachmentInspection): string {
+ const state = inspection?.state ?? 'not_inspected';
+ const heading = state === 'not_inspected' ? 'Attachments: not inspected.'
+ : state === 'incomplete' ? 'Attachments: inspection incomplete; absence is not established.'
+ : state === 'none' ? 'Attachments: inspected; none found.'
+ : 'Attachments: present; not downloaded; not indexed.';
+ return [heading, ...(inspection?.attachments ?? []).map(a =>
+ `- ${escaped(a.filename || '(unnamed)')} — ${escaped(a.mimeType)}; ${a.size === null ? 'size unavailable' : `${a.size} bytes`}; ${a.kind}; not downloaded; not indexed. Receipt: ${a.id}.`
+ )].join('\n');
+}
+
+export function threadAttachmentReceipts(thread: GmailThreadData) {
+ return { version: 1 as const, account: thread.account, threadId: thread.threadId,
+ messages: thread.messages.map(m => ({ messageId: m.id, inspection: m.attachmentInspection ?? { state: 'not_inspected' as const, attachments: [] } })) };
+}
diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.ts
index 2dfff4113f..34c75e3d63 100644
--- a/src/core/google/google-clients.ts
+++ b/src/core/google/google-clients.ts
@@ -22,6 +22,7 @@ import { CredentialError } from '../creds/errors.ts';
import type { GoogleAccessProvider } from './access.ts';
import { apiEnableLink } from '../creds/providers/google.ts';
import { parseRetryAfterMs } from '../github-source.ts';
+import { readBoundedHttpBody } from '../guarded-http.ts';
import {
bareAddress,
DEFAULT_CALENDAR_ID,
@@ -32,6 +33,7 @@ import {
type GmailThreadData,
} from './types.ts';
import { htmlToText, trimQuotedReply } from './google-render.ts';
+import { GMAIL_MIME_LIMITS, gmailPartHeader, inspectGmailAttachments, walkGmailMime, type GmailMimePart } from './attachment-receipts.ts';
export type FetchImpl = (url: string, init?: RequestInit) => Promise<Response>;
@@ -93,7 +95,7 @@ export class GoogleApiClient {
async fetchJSON<T>(
url: string,
apiHint: ApiHint,
- opts: { signal?: AbortSignal; retries?: number; rateLimitRetries?: number } = {},
+ opts: { signal?: AbortSignal; retries?: number; rateLimitRetries?: number; maxResponseBytes?: number } = {},
): Promise<T> {
const retries = opts.retries ?? DEFAULT_RETRIES;
// Rate-limit-class failures get their OWN (larger) retry budget — see
@@ -108,14 +110,18 @@ export class GoogleApiClient {
headers: { authorization: `Bearer ${token}` },
...(opts.signal ? { signal: opts.signal } : {}),
});
- if (res.ok) return (await res.json()) as T;
+ const readJSON = () => opts.maxResponseBytes
+ ? readBoundedHttpBody(new Response(res.body), opts.maxResponseBytes, opts.signal ?? new AbortController().signal)
+ .then(bytes => JSON.parse(bytes.toString('utf8')))
+ : res.json();
+ if (res.ok) return (await readJSON()) as T;
if (res.status === 401 && attempt < retries) {
this.log('[google] HTTP 401; refreshing access token');
await this.tokens.forceRefresh();
continue;
}
- const body = (await res.json().catch(() => ({}))) as GoogleErrorBody;
+ const body = (await readJSON().catch(() => ({}))) as GoogleErrorBody;
if (res.status === 403) {
const reason = body.error?.errors?.[0]?.reason ?? '';
const msg = body.error?.message ?? '';
@@ -194,21 +200,7 @@ export class GoogleCursorExpiredError extends Error {
// ── Gmail ────────────────────────────────────────────────────────────────────
-interface RawGmailHeader {
- name: string;
- value: string;
-}
-
-interface RawGmailPart {
- /** BARE media type ('text/calendar') — Gmail strips the Content-Type
- * parameters from this field; they live on `headers[]` (format=full). */
- mimeType?: string;
- filename?: string;
- /** Per-part MIME headers (Content-Type with its params, Content-Disposition, …). */
- headers?: RawGmailHeader[];
- body?: { data?: string; size?: number };
- parts?: RawGmailPart[];
-}
+type RawGmailPart = GmailMimePart;
interface RawGmailMessage {
id: string;
@@ -225,8 +217,7 @@ interface RawGmailThread {
}
function partHeader(part: RawGmailPart | undefined, name: string): string {
- const h = part?.headers?.find((x) => x.name.toLowerCase() === name.toLowerCase());
- return h?.value ?? '';
+ return gmailPartHeader(part, name);
}
function header(msg: RawGmailMessage, name: string): string {
@@ -247,21 +238,24 @@ function decodeB64Url(data: string): string {
/** MIME walk: prefer text/plain, fall back to text/html (caller strips). */
export function extractBody(part: RawGmailPart | undefined): { text: string; isHtml: boolean } {
if (!part) return { text: '', isHtml: false };
- const stack: RawGmailPart[] = [part];
let html: string | null = null;
- while (stack.length > 0) {
- const p = stack.shift()!;
+ const attachmentPaths: string[] = [];
+ for (const { part: p, path } of walkGmailMime(part).parts) {
+ if (attachmentPaths.some(parent => path.startsWith(`${parent}.`))) continue;
+ if (p.filename || p.mimeType === 'message/rfc822' || /^attachment\b/i.test(partHeader(p, 'Content-Disposition'))) {
+ attachmentPaths.push(path);
+ continue;
+ }
if (p.mimeType === 'text/plain' && p.body?.data) {
return { text: decodeB64Url(p.body.data), isHtml: false };
}
if (p.mimeType === 'text/html' && p.body?.data && html === null) {
html = decodeB64Url(p.body.data);
}
- if (p.parts) stack.push(...p.parts);
}
if (html !== null) return { text: html, isHtml: true };
// Single-part messages sometimes carry data at the top level with no mimeType match.
- if (part.body?.data) return { text: decodeB64Url(part.body.data), isHtml: false };
+ if (!part.mimeType && !part.filename && part.body?.data) return { text: decodeB64Url(part.body.data), isHtml: false };
return { text: '', isHtml: false };
}
@@ -282,10 +276,8 @@ export function extractBody(part: RawGmailPart | undefined): { text: string; isH
*/
export function extractCalendarMethod(part: RawGmailPart | undefined): string | null {
if (!part) return null;
- const stack: RawGmailPart[] = [part];
- while (stack.length > 0) {
- const p = stack.shift()!;
- const mime = (p.mimeType ?? '').toLowerCase();
+ for (const { part: p } of walkGmailMime(part).parts) {
+ const mime = typeof p.mimeType === 'string' ? p.mimeType.toLowerCase() : '';
if (mime.startsWith('text/calendar') || mime === 'application/ics') {
// Gmail's MessagePart.mimeType is the BARE media type; the `method=`
// parameter lives in the part's own Content-Type header (format=full
@@ -303,7 +295,6 @@ export function extractCalendarMethod(part: RawGmailPart | undefined): string |
// mail, and short-circuiting '' here used to suppress the whole message
// from loop detection. Keep scanning — a real text/calendar part
// elsewhere in the tree still wins.
- if (p.parts) stack.push(...p.parts);
}
return null;
}
@@ -367,17 +358,33 @@ export class GmailClient extends GoogleApiClient {
async getThread(
threadId: string,
account: string,
- opts: { signal?: AbortSignal; bodyCapChars?: number } = {},
+ opts: { signal?: AbortSignal; bodyCapChars?: number; metadataOnly?: boolean } = {},
): Promise<GmailThreadData> {
+ let fields = '';
+ if (opts.metadataOnly) {
+ let payload = 'partId,mimeType';
+ for (let depth = GMAIL_MIME_LIMITS.depth; depth >= 0; depth--) {
+ payload = `partId,mimeType,filename,headers(name,value),body(attachmentId,size),parts(${payload})`;
+ }
+ fields = `&fields=${encodeURIComponent(`id,messages(id,internalDate,labelIds,payload(${payload}))`)}`;
+ }
const raw = await this.fetchJSON<RawGmailThread>(
- `${GMAIL_BASE}/users/me/threads/${encodeURIComponent(threadId)}?format=full`,
+ `${GMAIL_BASE}/users/me/threads/${encodeURIComponent(threadId)}?format=full${fields}`,
'gmail',
- opts,
+ opts.metadataOnly ? { ...opts, maxResponseBytes: 2 * 1024 * 1024 } : opts,
);
const cap = opts.bodyCapChars ?? 8_000;
- const messages: GmailMessageMeta[] = (raw.messages ?? []).map((m) => {
+ if (opts.metadataOnly && (typeof raw.id !== 'string' || !raw.id || !Array.isArray(raw.messages) || !raw.messages.length ||
+ raw.messages.some(m => !m || typeof m.id !== 'string' || !/^[A-Za-z0-9]{1,128}$/.test(m.id)) ||
+ new Set(raw.messages.map(m => m.id)).size !== raw.messages.length)) {
+ throw new Error('Gmail returned malformed thread identities; historical metadata was preserved.');
+ }
+ const normalizedThreadId = typeof raw.id === 'string' && raw.id ? raw.id : threadId;
+ let receiptBudget: number = GMAIL_MIME_LIMITS.receiptBytes;
+ const messages: GmailMessageMeta[] = (raw.messages ?? []).map((m, index) => {
+ const messageId = typeof m.id === 'string' && m.id ? m.id : `missing:${threadId}:${index}`;
const fromRaw = header(m, 'From');
- const { text: rawText, isHtml } = extractBody(m.payload);
+ const { text: rawText, isHtml } = opts.metadataOnly ? { text: '', isHtml: false } : extractBody(m.payload);
// Pre-truncate before conversion: only the first `cap` output chars
// survive, so a multi-hundred-KB marketing email must not pay ~15
// full-body regex passes in htmlToText inside the per-thread hot loop.
@@ -386,9 +393,11 @@ export class GmailClient extends GoogleApiClient {
bodyText = trimQuotedReply(bodyText);
if (bodyText.length > cap) bodyText = bodyText.slice(0, cap) + '\n[truncated]';
const internalDateMs = Number(m.internalDate ?? 0);
+ const attachmentInspection = inspectGmailAttachments(m.payload, account, messageId, receiptBudget);
+ receiptBudget -= Buffer.byteLength(JSON.stringify(attachmentInspection));
return {
- id: m.id,
- threadId: raw.id,
+ id: messageId,
+ threadId: normalizedThreadId,
from: fromRaw,
fromAddress: bareAddress(fromRaw),
to: splitAddressList(header(m, 'To')),
@@ -400,10 +409,11 @@ export class GmailClient extends GoogleApiClient {
listUnsubscribe: header(m, 'List-Unsubscribe') !== '',
calendarMethod: extractCalendarMethod(m.payload),
bodyText,
+ attachmentInspection,
};
});
messages.sort((a, b) => a.internalDateMs - b.internalDateMs);
- return { threadId: raw.id, account, messages };
+ return { threadId: normalizedThreadId, account, messages };
}
}
diff --git a/src/core/google/google-render.ts b/src/core/google/google-render.ts
index b8423cf246..9745925657 100644
--- a/src/core/google/google-render.ts
+++ b/src/core/google/google-render.ts
@@ -11,6 +11,7 @@
*/
import { createHash } from 'node:crypto';
+import { renderAttachmentInspection, threadAttachmentReceipts } from './attachment-receipts.ts';
import { emailCitation } from '../output/scaffold.ts';
import type { CalendarEventData, ContactData, GmailThreadData } from './types.ts';
@@ -255,6 +256,7 @@ export function renderThreadPage(thread: GmailThreadData): RenderedPage | null {
`date: ${yamlStr(last.dateIso)}`,
`first_message_date: ${yamlStr(first.dateIso)}`,
`message_count: ${thread.messages.length}`,
+ `gmail_attachment_receipts: ${JSON.stringify(threadAttachmentReceipts(thread))}`,
`participants: ${yamlList([...participants].sort())}`,
`senders: ${yamlList([...senders].sort())}`,
`labels: ${yamlList([...new Set(thread.messages.flatMap((m) => m.labelIds))].sort())}`,
@@ -264,12 +266,12 @@ export function renderThreadPage(thread: GmailThreadData): RenderedPage | null {
const body: string[] = ['', `# ${subject}`, ''];
for (const m of thread.messages) {
- const cite = emailCitation({
+ const cite = /^[A-Za-z0-9]{10,60}$/.test(m.id) ? emailCitation({
account: thread.account,
messageId: m.id,
subject: m.subject || subject,
dateISO: m.dateIso.slice(0, 10),
- });
+ }) : 'Gmail message link unavailable.';
const sent = m.labelIds.includes('SENT');
body.push(
`## ${sent ? '→ ' : ''}${m.from || m.fromAddress} · ${m.dateIso.slice(0, 16).replace('T', ' ')}`,
@@ -278,7 +280,7 @@ export function renderThreadPage(thread: GmailThreadData): RenderedPage | null {
'',
);
if (m.to.length > 0) body.push(`To: ${m.to.join(', ')}${m.cc.length > 0 ? ` · Cc: ${m.cc.join(', ')}` : ''}`, '');
- body.push(m.bodyText || '_empty message_', '');
+ body.push(m.bodyText || '_empty message_', '', renderAttachmentInspection(m.attachmentInspection), '');
}
return { relPath: threadRelPath(thread), markdown: fm.join('\n') + body.join('\n') + '\n' };
diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.ts
index 3b46a49c85..bd7b0062b4 100644
--- a/src/core/google/google-source.ts
+++ b/src/core/google/google-source.ts
@@ -63,6 +63,7 @@ import {
import { LOOPS_EXTRACT_WINDOW_DAYS, loopExtractionEligibility } from './loops-extract.ts';
export type { GoogleSourceConfig } from './types.ts';
+export { runGoogleAttachmentBackfill } from './attachment-backfill.ts';
// ── Config ───────────────────────────────────────────────────────────────────
@@ -182,6 +183,7 @@ interface GoogleSyncSummary {
embedded: number;
pagesAffected: string[];
threadsSeen: number;
+ attachmentInspection: Record<string, number>;
/**
* Why each in-window thread was or was not sent to the extractor, keyed by
* the machine reason from loopExtractionEligibility. Counts only — no
@@ -511,6 +513,10 @@ async function processThread(
// produces an empty verdict anyway, so nothing opens and nothing closes.
if (!rendered) return thread;
const slug = await importRendered(deps, rendered.relPath, rendered.markdown, activePack, summary, countedSlugs);
+ for (const message of thread.messages) {
+ const state = message.attachmentInspection?.state ?? 'not_inspected';
+ summary.attachmentInspection[state] = (summary.attachmentInspection[state] ?? 0) + 1;
+ }
await applyLoopDetection(deps, thread, slug);
// LLM extraction candidates: trickle + the bounded recent window only —
// the deep historical backfill is never extracted (spend honesty, F9).
@@ -1062,6 +1068,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
embedded: 0,
pagesAffected: [],
threadsSeen: 0,
+ attachmentInspection: {},
extractEligibility: {},
failedFiles: 0,
};
@@ -1202,6 +1209,9 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
}
const changed = summary.added + summary.modified + summary.deleted > 0;
+ if (activeServices.includes('gmail')) {
+ log(`[google] attachment inspection (this sweep only): ${Object.entries(summary.attachmentInspection).map(([state, count]) => `${state}=${count}`).join(' ') || 'no messages inspected'}; historical completeness is not established by incremental sync.`);
+ }
return {
status:
summary.status === 'partial'
diff --git a/src/core/google/types.ts b/src/core/google/types.ts
index 0fdc0e2af6..08ae5cb6fb 100644
--- a/src/core/google/types.ts
+++ b/src/core/google/types.ts
@@ -70,6 +70,16 @@ export interface GoogleSourceState {
calendar_id?: string | null;
contacts_sync_token: string | null;
last_full_at: string | null;
+ gmail_attachment_backfill?: {
+ version: 1;
+ account: string;
+ afterPageId: number;
+ throughPageId: number;
+ inspected: number;
+ unavailable?: number;
+ unavailableMessages?: number;
+ complete: boolean;
+ };
}
/**
@@ -113,6 +123,39 @@ export interface GmailMessageMeta {
calendarMethod?: string | null;
/** Extracted, HTML-stripped, quote-trimmed, capped body text. */
bodyText: string;
+ attachmentInspection?: GmailAttachmentInspection;
+}
+
+export interface GmailAttachmentReceipt {
+ id: string;
+ account: string;
+ messageId: string;
+ partId: string;
+ filename: string;
+ mimeType: string;
+ size: number | null;
+ attachmentId: string | null;
+ kind: 'document' | 'inline' | 'calendar';
+ fetched: false;
+ indexed: false;
+}
+
+export interface GmailAttachmentInspection {
+ state: 'not_inspected' | 'incomplete' | 'none' | 'present';
+ attachments: GmailAttachmentReceipt[];
+ reason?: 'missing_payload' | 'malformed_part' | 'depth_limit' | 'part_limit' | 'receipt_bytes_limit';
+}
+
+export interface GmailThreadAttachmentReceipts {
+ version: 1;
+ account: string;
+ threadId: string;
+ unavailable?: 'thread_not_found';
+ messages: Array<{
+ messageId: string;
+ inspection: GmailAttachmentInspection;
+ unavailable?: 'thread_not_found' | 'message_not_found';
+ }>;
}
export interface GmailThreadData {
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 0700cdf9ae..1361c60b54 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -592,7 +592,7 @@ export async function importFromContent(
parsed.compiled_truth = mergeHiddenFactRowsIntoBody(slug, parsed.compiled_truth, existing.compiled_truth);
parsed.timeline = mergeHiddenFactRowsIntoBody(slug, parsed.timeline, existing.timeline);
}
- const { preserveWithdrawnFenceRows } = await import('./facts/withdrawal.ts');
+ const { assertPreparedFactWithdrawals, preserveWithdrawnFenceRows } = await import('./facts/withdrawal.ts');
parsed.compiled_truth = await preserveWithdrawnFenceRows(engine, sourceId ?? 'default', parsed.compiled_truth);
parsed.timeline = await preserveWithdrawnFenceRows(engine, sourceId ?? 'default', parsed.timeline);
@@ -666,7 +666,7 @@ export async function importFromContent(
if (opts.prepare) {
const result: ImportResult = { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
return opts.prepare({ slug, parsedPage, observedRevision: (existing as typeof existing & { knowledge_revision?: string }).knowledge_revision ?? null,
- noop: true, result, apply: async () => {} });
+ noop: true, result, validate: async () => {}, apply: async () => {} });
}
await persistUnchanged();
return { slug, status: 'skipped', chunks: 0, parsedPage, ...(typeWarning ? { type_warning: typeWarning } : {}) };
@@ -738,7 +738,7 @@ export async function importFromContent(
if (opts.prepare) {
const result: ImportResult = { slug: dup.slug, status: 'skipped', chunks: 0, parsedPage };
return opts.prepare({ slug: dup.slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
- noop: true, result, apply: async () => {} });
+ noop: true, result, validate: async () => {}, apply: async () => {} });
}
// True duplicate (same external ID). Skip + log to stderr.
process.stderr.write(
@@ -870,6 +870,7 @@ export async function importFromContent(
let persistedProjection: ProjectionSnapshot | null = null;
const applyPrepared = async (tx: BrainEngine) => {
await assertImportBase(tx, slug, txOpts.sourceId, existing);
+ await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '');
if (existing) await tx.createVersion(slug, txOpts);
// v0.29.1 — compute effective_date from frontmatter precedence chain.
@@ -1030,6 +1031,7 @@ export async function importFromContent(
slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,
noop: false, result: { slug, status: 'imported', chunks: chunks.length, parsedPage,
...(pageQuarantined ? { quarantined: true } : {}), ...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}) },
+ validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || ''),
apply: applyPrepared,
});
await engine.transaction(applyPrepared).catch(async (err: unknown) => {
@@ -1408,7 +1410,7 @@ export async function importCodeFile(
if (!opts.force && existing?.content_hash === hash && !existing.deleted_at && existing.text_projection_revision === existing.knowledge_revision) {
if (opts.prepare) {
const result: ImportResult = { slug, status: 'skipped', chunks: 0 };
- return opts.prepare({ slug, parsedPage, observedRevision: existing.knowledge_revision ?? null, noop: true, result, apply: async () => {} });
+ return opts.prepare({ slug, parsedPage, observedRevision: existing.knowledge_revision ?? null, noop: true, result, validate: async () => {}, apply: async () => {} });
}
await engine.transaction(tx => assertImportBase(tx, slug, sourceId ?? 'default', existing));
return { slug, status: 'skipped', chunks: 0 };
@@ -1420,7 +1422,7 @@ export async function importCodeFile(
const result: ImportResult = { slug, status: 'imported', chunks: projection.chunks.length };
const apply = (tx: BrainEngine) => installPageProjection(tx, snapshot, projection.chunks,
{ seal: true, preserveEmbeddings: true, code: projection.code });
- if (opts.prepare) return opts.prepare({ slug, parsedPage, observedRevision: snapshot.snapshot.revision, noop: false, result, apply });
+ if (opts.prepare) return opts.prepare({ slug, parsedPage, observedRevision: snapshot.snapshot.revision, noop: false, result, validate: async () => {}, apply });
await engine.transaction(apply);
return result;
}
@@ -1528,7 +1530,7 @@ export async function importCodeFile(
};
if (opts.prepare) {
const result: ImportResult = { slug, status: 'imported', chunks: chunks.length };
- return opts.prepare({ slug, parsedPage, observedRevision: existing?.knowledge_revision ?? null, noop: false, result, apply });
+ return opts.prepare({ slug, parsedPage, observedRevision: existing?.knowledge_revision ?? null, noop: false, result, validate: async () => {}, apply });
}
await engine.transaction(apply);
@@ -2063,7 +2065,7 @@ export async function importImageFile(
[sourceOpts.sourceId, imageSlug]);
if (sealed.length && !existing.deleted_at && existing.text_projection_revision === existing.knowledge_revision) {
if (opts.prepare) return opts.prepare({ slug: imageSlug, observedRevision: existing.knowledge_revision ?? null, noop: true,
- result: { slug: imageSlug, status: 'skipped', chunks: 0 }, apply: async () => {} });
+ result: { slug: imageSlug, status: 'skipped', chunks: 0 }, validate: async () => {}, apply: async () => {} });
await engine.transaction(tx => assertImportBase(tx, imageSlug, sourceOpts.sourceId, existing));
return { slug: imageSlug, status: 'skipped', chunks: 0 };
}
@@ -2190,7 +2192,7 @@ export async function importImageFile(
};
if (opts.prepare) return opts.prepare({ slug: imageSlug, observedRevision: existing?.knowledge_revision ?? null, noop: false,
- result: { slug: imageSlug, status: 'imported', chunks: 1 }, apply: tx => applyImportTransaction(tx, spec) });
+ result: { slug: imageSlug, status: 'imported', chunks: 1 }, validate: async () => {}, apply: tx => applyImportTransaction(tx, spec) });
await withImportTransaction(engine, spec);
return { slug: imageSlug, status: 'imported', chunks: 1 };
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 0b8c3fe2c8..5bea9c6d5b 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -9,7 +9,7 @@ import { PAGE_STATE_SCHEMA_SQL, PAGE_VERSION_DELETION_SCHEMA_SQL } from './page-
import type { BrainEngine } from './engine.ts';
import { slugifyPath } from './sync.ts';
import { getFtsLanguage } from './fts-language.ts';
-import { hnswMaxDimsForType } from './vector-index.ts';
+import { hnswMaxDimsForType, readExistingEmbeddingShape } from './vector-index.ts';
// runMigrations executes while an initialized engine is live. Keep its helper
// modules in the static graph rather than importing them from async handlers.
import {
@@ -2374,14 +2374,15 @@ export const MIGRATIONS: Migration[] = [
useHalfvec = true;
}
- const columnType = useHalfvec ? 'halfvec' : 'vector';
+ const existingShape = await readExistingEmbeddingShape(engine, 'facts');
+ const columnType = existingShape?.type ?? (useHalfvec ? 'halfvec' : 'vector');
const vecType = columnType.toUpperCase();
// HNSW operator class must match the column type:
// VECTOR(n) → vector_cosine_ops
// HALFVEC(n) → halfvec_cosine_ops
- const opclass = useHalfvec ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
+ const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
const hnswMaxDims = hnswMaxDimsForType(columnType);
- const factsEmbeddingIndexSql = embeddingDim <= hnswMaxDims
+ const factsEmbeddingIndexSql = (existingShape?.dimensions ?? embeddingDim) <= hnswMaxDims
? `CREATE INDEX IF NOT EXISTS idx_facts_embedding_hnsw
ON facts USING hnsw (embedding ${opclass})
WHERE embedding IS NOT NULL AND expired_at IS NULL;`
@@ -2974,11 +2975,12 @@ export const MIGRATIONS: Migration[] = [
useHalfvec = true;
}
- const columnType = useHalfvec ? 'halfvec' : 'vector';
+ const existingShape = await readExistingEmbeddingShape(engine, 'query_cache');
+ const columnType = existingShape?.type ?? (useHalfvec ? 'halfvec' : 'vector');
const vecType = columnType.toUpperCase();
- const opclass = useHalfvec ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
+ const opclass = columnType === 'halfvec' ? 'halfvec_cosine_ops' : 'vector_cosine_ops';
const hnswMaxDims = hnswMaxDimsForType(columnType);
- const queryCacheEmbeddingIndexSql = embeddingDim <= hnswMaxDims
+ const queryCacheEmbeddingIndexSql = (existingShape?.dimensions ?? embeddingDim) <= hnswMaxDims
? `CREATE INDEX IF NOT EXISTS idx_query_cache_embedding_hnsw
ON query_cache USING hnsw (embedding ${opclass})
WHERE embedding IS NOT NULL;`
@@ -6660,6 +6662,12 @@ CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON minion_jobs
: PERSISTENCE_DATABASE_PENDING_INDEX_SQL);
},
},
+ {
+ version: 166, name: 'fact_embedding_identity', idempotent: true,
+ sql: `ALTER TABLE facts ADD COLUMN IF NOT EXISTS embedding_model TEXT;
+ ALTER TABLE facts ADD COLUMN IF NOT EXISTS embedded_text_hash TEXT;
+ ${MANAGED_WRITER_GUARD_SQL}`,
+ },
];
export const LATEST_VERSION = MIGRATIONS.length > 0
diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.ts
index 73bac4baec..44254d623d 100644
--- a/src/core/minions/handlers/embed-backfill.ts
+++ b/src/core/minions/handlers/embed-backfill.ts
@@ -34,7 +34,7 @@
* - try/finally ALWAYS releases the per-source lock. Aborted runs leave
* the next call free to claim.
*/
-import { tryAcquireDbLock } from '../../db-lock.ts';
+import { tryAcquireDbLock, LockStolenError } from '../../db-lock.ts';
import {
BudgetTracker,
BudgetExhausted,
@@ -281,6 +281,18 @@ export function makeEmbedBackfillHandler(
runStale(engine, sourceId, {
batchSize,
signal: drainAbort.signal,
+ deadline: job.deadlineAtMs ?? undefined,
+ assertOwned: async tx => {
+ const owned = tx
+ ? (await tx.executeRaw(`SELECT id FROM gbrain_cycle_locks
+ WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at>now() FOR SHARE`, [lock.id, lock.acquisitionToken])).length === 1
+ : await lock.refresh({ signal: drainAbort.signal });
+ if (!owned) {
+ const error = new LockStolenError(lock.id);
+ drainAbort.abort(error);
+ throw error;
+ }
+ },
pacer,
...(concurrency !== undefined && { concurrency }),
// v0.41.31: re-embed pages whose model signature drifted + stamp
@@ -330,6 +342,9 @@ export function makeEmbedBackfillHandler(
// failed — pre-fix this shape reported `status: "success"` twelve runs
// in a row while an entire corpus sat stripped. NULLed chunks stay NULL
// for the next (fixed-config) run to pick up.
+ if ((result.remaining ?? 0) > 0 || (result.blocked ?? 0) > 0) {
+ throw new Error(`embed-backfill: incomplete; ${result.remaining ?? 0} chunks remain and ${result.blocked ?? 0} projections are blocked. Durable progress is retained; inspect provider and projection readiness before retrying.`);
+ }
if (result.embedded === 0 && (result.invalidated > 0 || result.chunksProcessed > 0)) {
throw new Error(
`embed-backfill: embedded 0 of ${result.chunksProcessed} processed chunk(s) ` +
diff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.ts
index 642cacca32..f6f127949f 100644
--- a/src/core/ops/embedding-migration.ts
+++ b/src/core/ops/embedding-migration.ts
@@ -22,6 +22,7 @@ const migrate_embeddings: Operation = {
dim: { type: 'number', description: "Target dimensions. Defaults to the provider recipe's declared width; required when the recipe declares none." },
dry_run: { type: 'boolean', description: 'Plan + cost estimate only; change nothing.' },
yes: { type: 'boolean', description: 'Confirm the re-embed spend + destructive schema change. Required for a live run.' },
+ max_cost_usd: { type: 'number', description: 'Finite total paid authorization. Required for new work; resume preserves all conservative pre-dispatch debits. Increase explicitly to renew.' },
retarget: { type: 'boolean', description: 'Abandon a DIFFERENT in-flight migration target and start this one (the abandoned target is recorded in the marker history).' },
reranker: { type: 'string', description: 'Reranker companion action: auto (default), off, keep, or an explicit provider:model (e.g. voyage:rerank-2.5). Reranker config lives on the DB plane.' },
},
@@ -39,7 +40,7 @@ const migrate_embeddings: Operation = {
// ONE shared orchestrator with the CLI (round-2 #11): locks, retarget
// gate, DB-verified skip, heartbeat, and completion bookkeeping are
// identical on both surfaces by construction.
- const { planMigrationFlow, executeMigrationFlow } = await import('../../commands/migrate-embeddings.ts');
+ const { planMigrationFlow, executeMigrationFlow, EMBEDDING_MIGRATION_RECOVERY: recovery } = await import('../../commands/migrate-embeddings.ts');
const to = p.to as string;
const dim = p.dim as number | undefined;
const planCtx = await planMigrationFlow(ctx.engine, {
@@ -51,7 +52,7 @@ const migrate_embeddings: Operation = {
// Different-target in-flight marker: the retarget decision precedes any
// skip (mirrors the CLI ordering exactly — shared-orchestrator parity).
if (planCtx.inflightOther && p.retarget !== true && p.dry_run !== true && !ctx.dryRun) {
- return { status: 'refused', reason: 'retarget_required', inflight: planCtx.inflightOther, plan };
+ return { status: 'refused', reason: 'retarget_required', inflight: planCtx.inflightOther, plan, recovery };
}
if (planCtx.verify.complete && !planCtx.inflightOther && planCtx.rerankerPlan.action.kind === 'none') {
return { status: 'skipped_no_work', plan, verified: planCtx.verify };
@@ -65,6 +66,7 @@ const migrate_embeddings: Operation = {
}
const result = await executeMigrationFlow(ctx.engine, planCtx, {
to,
+ maxCostUsd: p.max_cost_usd as number | undefined,
...(dim !== undefined && { dim }),
...(p.retarget === true && { retarget: true }),
...(typeof p.reranker === 'string' && { reranker: p.reranker }),
@@ -74,15 +76,15 @@ const migrate_embeddings: Operation = {
// failures carry a `reason`, refusals carry `status:'refused'` + a reason
// discriminator (the env refusal keeps its pre-orchestrator spelling so
// existing consumers keying on reason:'env_override' still match).
- if (result.status === 'probe_failed') return { status: 'failed', reason: result.message, plan };
- if (result.status === 'apply_failed') return { status: 'failed', reason: result.reason, plan };
+ if (result.status === 'probe_failed') return { status: 'failed', reason: result.message, plan, recovery };
+ if (result.status === 'apply_failed') return { status: 'failed', reason: result.reason, plan, recovery };
// A held lock keeps its discriminator (holder: migration vs embed_backfill)
// — remote callers need it to pick the right remediation, same as the CLI.
if (result.status === 'locked') {
- return { status: 'locked', holder: result.holder, detail: result.detail, plan };
+ return { status: 'locked', holder: result.holder, detail: result.detail, plan, recovery };
}
if (result.status === 'refused_env') {
- return { status: 'refused', reason: 'env_override', warning: result.warning, plan };
+ return { status: 'refused', reason: 'env_override', warning: result.warning, plan, recovery };
}
if (result.status === 'refused_retarget') {
return {
@@ -90,9 +92,10 @@ const migrate_embeddings: Operation = {
reason: 'retarget_required',
inflight: result.inflight,
plan,
+ recovery,
};
}
- return { ...result, plan };
+ return { ...result, plan, ...(result.status === 'incomplete' && { recovery }) };
},
cliHints: { name: 'migrate-embeddings', hidden: true },
};
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 1d02f34dfe..b633d8c88b 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -66,10 +66,10 @@ async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxC
/** A short guarded read binds the exact chunk set and title/body revision. */
export async function readProjectionSnapshot(engine: BrainEngine, slug: string, sourceId: string,
- opts: { allowUnsealed?: boolean; maxChunkTokens?: number } = {}): Promise<ProjectionSnapshot | null> {
+ opts: { allowUnsealed?: boolean; maxChunkTokens?: number; requireLiveSource?: boolean } = {}): Promise<ProjectionSnapshot | null> {
return engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId, slug }]);
- const snapshot = await tx.readPageSnapshot(slug, { sourceId });
+ const snapshot = await tx.readPageSnapshot(slug, { sourceId, ...(opts.requireLiveSource && { requireLiveSource: true }) });
if (!snapshot || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;
const context = await indexingContext(tx, snapshot, opts.maxChunkTokens);
return { snapshot, chunks: await tx.getChunks(slug, { sourceId, includeUnsealed: true }), indexingContext: context.key,
@@ -138,8 +138,10 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Proje
return engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId, slug }]);
const current = await tx.readPageSnapshot(slug, { sourceId });
- if (!current || current.revision !== snapshot.revision || current.sourceIncarnation !== snapshot.sourceIncarnation || current.page.id !== snapshot.page.id
+ if (!current || current.page.deleted_at || current.revision !== snapshot.revision || current.sourceIncarnation !== snapshot.sourceIncarnation || current.page.id !== snapshot.page.id
|| current.page.text_projection_revision !== current.revision) return false;
+ const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);
+ if (!source || source.archived) return false;
const context = await indexingContext(tx, current, prepared.maxChunkTokensOverride);
if (context.key !== prepared.indexingContext) return false;
const stored = await tx.getChunks(slug, { sourceId, includeUnsealed: true });
diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.ts
index 35d592c0bd..1650adae24 100644
--- a/src/core/page-state/snapshot.ts
+++ b/src/core/page-state/snapshot.ts
@@ -1,35 +1,10 @@
-import { createHash } from 'node:crypto';
-import { renderFactsTable } from '../facts-fence.ts';
-import { withdrawnFact, withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';
+import { overlayWithdrawalBody } from '../facts/withdrawal-overlay.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
import type { ReadQuery } from '../search/read-enrichment.ts';
import { rowToPage } from '../utils.ts';
import type { PageSnapshot, PageSnapshotOptions, PageWithdrawal } from './types.ts';
import { PageSnapshotAmbiguousError } from './types.ts';
-/** The DB normalizes companion lines, preserving its lower()/POSIX-space semantics. */
-function overlayWithdrawals(body: string, normalizedBody: string, withdrawals: PageWithdrawal[]): string {
- if (!withdrawals.length || !body.includes('gbrain:facts:begin')) return body;
- const ledger = new Map(withdrawals.map(w => [`${w.visibility}:${w.fact_hash}`, w.withdrawn_at]));
- const blocks = withdrawalFenceBlocks(body), normalized = withdrawalFenceBlocks(normalizedBody);
- for (let i = blocks.length - 1; i >= 0; i--) {
- const block = blocks[i], norm = normalized[i];
- if (!norm || block.parsed.warnings.length || norm.parsed.warnings.length) continue;
- const claims = new Map(norm.parsed.facts.map(f => [f.rowNum, f.claim]));
- let changed = false;
- const facts = block.parsed.facts.map(f => {
- const claim = claims.get(f.rowNum);
- if (claim === undefined) return f;
- const at = ledger.get(`${f.visibility}:${createHash('sha256').update(claim).digest('hex')}`);
- if (!at) return f;
- changed = true;
- return withdrawnFact(f, new Date(at).toISOString().slice(0, 10));
- });
- if (changed) body = body.slice(0, block.start) + renderFactsTable(facts) + body.slice(block.end);
- }
- return body;
-}
-
/** Normalize filesystem bytes with the exact ledger fingerprint rules before comparing them. */
export async function overlayCanonicalBodies(query: ReadQuery, body: string, timeline: string, withdrawals: PageWithdrawal[]): Promise<{ compiled_truth: string; timeline: string }> {
if (!withdrawals.length) return { compiled_truth: body, timeline };
@@ -38,8 +13,8 @@ export async function overlayCanonicalBodies(query: ReadQuery, body: string, tim
FROM unnest(string_to_array($1::text,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS body,
(SELECT string_agg(regexp_replace(lower(line),'[[:space:]]+',' ','g'),chr(10) ORDER BY ord)
FROM unnest(string_to_array($2::text,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS timeline`, [body, timeline]);
- return { compiled_truth: overlayWithdrawals(body, normalized.body ?? '', withdrawals),
- timeline: overlayWithdrawals(timeline, normalized.timeline ?? '', withdrawals) };
+ return { compiled_truth: overlayWithdrawalBody(body, normalized.body ?? '', withdrawals),
+ timeline: overlayWithdrawalBody(timeline, normalized.timeline ?? '', withdrawals) };
}
/** One MVCC statement binds content, tags, identity and withdrawals to one revision. */
@@ -80,8 +55,8 @@ export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: Pa
if (opts?.requireUnambiguous && Number(row.snapshot_matches) > 1) throw new PageSnapshotAmbiguousError();
const page = rowToPage(row);
const withdrawals = row.snapshot_withdrawals as PageWithdrawal[];
- page.compiled_truth = overlayWithdrawals(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);
- page.timeline = overlayWithdrawals(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);
+ page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);
+ page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);
return { page, tags: row.snapshot_tags as string[], revision: String(row.knowledge_revision),
sourceIncarnation: String(row.source_incarnation), withdrawals };
}
diff --git a/src/core/persistence/connector-google-receipts.ts b/src/core/persistence/connector-google-receipts.ts
new file mode 100644
index 0000000000..87ad068d1c
--- /dev/null
+++ b/src/core/persistence/connector-google-receipts.ts
@@ -0,0 +1,94 @@
+import type { BrainEngine } from '../engine.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import type { WriteRequest } from './model.ts';
+import type { PreparedMutation } from './coordinator.ts';
+import { OperationError } from '../ops/contract.ts';
+import { digest } from './digest.ts';
+import { contentHash } from '../utils.ts';
+import { serializePageToMarkdown } from '../markdown.ts';
+import { prepareFileTarget } from './page-prepare.ts';
+import { installPageProjection, preparePageProjection, readProjectionSnapshot } from '../page-state/projections.ts';
+import type { GmailThreadAttachmentReceipts } from '../google/types.ts';
+
+export type GoogleReceipts = GmailThreadAttachmentReceipts;
+
+export function ownedGoogleReceipts(snapshot: PageSnapshot | null, config: Record<string, unknown>, receipts: GoogleReceipts): GoogleReceipts {
+ const page = snapshot?.page;
+ const fm = page?.frontmatter;
+ if (!page || page.deleted_at || page.type !== 'email' || !page.source_path?.startsWith('emails/') ||
+ config.kind !== 'google' || typeof config.g_account !== 'string' || config.g_account.trim().toLowerCase() !== receipts.account || fm?.account !== receipts.account ||
+ fm.thread_id !== receipts.threadId || !Array.isArray(fm.message_ids) || !fm.message_ids.length ||
+ !fm.message_ids.every(id => typeof id === 'string' && /^[A-Za-z0-9]{1,128}$/.test(id)) || fm.message_ids.length > 512 ||
+ new Set(fm.message_ids).size !== fm.message_ids.length || receipts.version !== 1 || !Array.isArray(receipts.messages) ||
+ (receipts.unavailable !== undefined && receipts.unavailable !== 'thread_not_found') ||
+ (!receipts.messages.length && !receipts.unavailable) || receipts.messages.length > 512 || Buffer.byteLength(JSON.stringify(receipts)) > 131_072) {
+ throw new OperationError('revision_conflict', 'Historical Gmail receipt ownership is unknown or metadata exceeds the repair bound. Content was preserved.');
+ }
+ const prior = fm.gmail_attachment_receipts as GoogleReceipts | undefined;
+ if (prior !== undefined && (prior?.version !== 1 || prior.account !== receipts.account || prior.threadId !== receipts.threadId || !Array.isArray(prior.messages) ||
+ prior.messages.length > 512 || Buffer.byteLength(JSON.stringify(prior)) > 131_072)) {
+ throw new OperationError('revision_conflict', 'The attachment metadata field is not connector-owned. Content was preserved.');
+ }
+ const messageIds = fm.message_ids as string[];
+ for (const entries of [receipts.messages, prior?.messages ?? []]) {
+ if (new Set(entries.map(m => m?.messageId)).size !== entries.length || entries.some(m =>
+ !m || typeof m.messageId !== 'string' || !m.messageId ||
+ (m.unavailable !== undefined && !['thread_not_found', 'message_not_found'].includes(m.unavailable)) ||
+ !['not_inspected', 'incomplete', 'none', 'present'].includes(m.inspection?.state) || !Array.isArray(m.inspection.attachments) ||
+ m.inspection.attachments.some(a => !a || a.account !== receipts.account || a.messageId !== m.messageId || a.fetched !== false || a.indexed !== false))) {
+ throw new OperationError('revision_conflict', 'Gmail receipt identity or ownership is unknown. Content was preserved.');
+ }
+ }
+ if (prior?.messages.some(m => !messageIds.includes(m.messageId))) {
+ throw new OperationError('revision_conflict', 'Existing Gmail receipts do not match the historical message identities. Content was preserved.');
+ }
+ if (!receipts.unavailable && messageIds.some(id => !receipts.messages.some(m => m.messageId === id)) &&
+ receipts.messages.some(m => m.inspection.state === 'incomplete' || m.inspection.state === 'not_inspected')) {
+ throw new OperationError('revision_conflict', 'Incomplete Gmail metadata cannot establish disappearance. Content was preserved.');
+ }
+ const selected = messageIds.map(messageId => {
+ const incoming = receipts.messages.find(m => m.messageId === messageId);
+ if (incoming && !receipts.unavailable && !incoming.unavailable) return incoming;
+ const previous = prior?.messages.find(m => m.messageId === messageId) ?? incoming;
+ return { ...previous, messageId, inspection: previous?.inspection ?? { state: 'not_inspected' as const, attachments: [] },
+ unavailable: receipts.unavailable ?? incoming?.unavailable ?? 'message_not_found' as const };
+ });
+ const merged = { ...prior, ...receipts, messages: selected };
+ if (!receipts.unavailable) delete merged.unavailable;
+ if (Buffer.byteLength(JSON.stringify(merged)) > 131_072) {
+ throw new OperationError('revision_conflict', 'Preserved Gmail receipts exceed the repair bound. Content was preserved.');
+ }
+ return merged;
+}
+
+export async function prepareGoogleReceiptPatch(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot | null,
+ config: Record<string, unknown>, supplied: GoogleReceipts): Promise<PreparedMutation> {
+ const receipts = ownedGoogleReceipts(snapshot, config, supplied);
+ const current = snapshot!;
+ const frontmatter = { ...current.page.frontmatter, gmail_attachment_receipts: receipts };
+ const page = { ...current.page, frontmatter };
+ const noop = digest(current.page.frontmatter.gmail_attachment_receipts ?? null) === digest(receipts);
+ const file = await prepareFileTarget(engine, row, current, serializePageToMarkdown(page, current.tags));
+ const projection = noop ? null : await readProjectionSnapshot(engine, row.slug, row.source_id, { allowUnsealed: true });
+ if (!noop && (!projection || projection.snapshot.revision !== current.revision)) throw new OperationError('revision_conflict', 'The Gmail page changed during receipt preparation.');
+ const chunks = projection ? await preparePageProjection(projection) : null;
+ return { observedRevision: current.revision, sourceExclusive: true, deferEmbedding: true, noop, file,
+ apply: async tx => {
+ if (!noop) {
+ const liveProjection = await readProjectionSnapshot(tx, row.slug, row.source_id, { allowUnsealed: true });
+ if (!liveProjection || liveProjection.indexingContext !== projection!.indexingContext ||
+ digest(liveProjection.chunks) !== digest(projection!.chunks)) {
+ throw new OperationError('revision_conflict', 'The Gmail projection changed during receipt preparation.');
+ }
+ await tx.createVersion(row.slug, { sourceId: row.source_id });
+ const changed = await tx.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(frontmatter,'{gmail_attachment_receipts}',$3::text::jsonb),content_hash=$4,updated_at=now()
+ WHERE source_id=$1 AND slug=$2 AND id=$5 AND knowledge_revision=$6::uuid AND deleted_at IS NULL RETURNING id`,
+ [row.source_id, row.slug, JSON.stringify(receipts), contentHash({ ...page, tags: current.tags }), current.page.id, current.revision]);
+ if (changed.length !== 1) throw new OperationError('revision_conflict', 'The Gmail page changed before metadata publication.');
+ const next = await readProjectionSnapshot(tx, row.slug, row.source_id, { allowUnsealed: true });
+ if (!next || !chunks) throw new OperationError('revision_conflict', 'The Gmail receipt projection is unavailable.');
+ await installPageProjection(tx, next, chunks.chunks, { seal: true, preserveEmbeddings: true, code: chunks.code });
+ }
+ return { status: noop ? 'skipped' : 'updated', slug: row.slug, source_id: row.source_id, noop, attachment_metadata_only: true };
+ } };
+}
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index ff8231f647..ee3b5848f9 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -27,6 +27,7 @@ import { prepareFileTarget } from './page-prepare.ts';
import { assertPhysicalRoot } from './physical-root.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';
+import { ownedGoogleReceipts, prepareGoogleReceiptPatch, type GoogleReceipts } from './connector-google-receipts.ts';
type ConnectorKind = 'google' | 'github';
interface ConnectorLease { handle: DbLockHandle; signal: AbortSignal; }
@@ -41,7 +42,7 @@ interface ConnectorRetry {
attempt: number;
}
interface ConnectorIntent extends Record<string, unknown> {
- kind: 'managed_connector_import' | 'managed_connector_delete' | 'managed_connector_checkpoint';
+ kind: 'managed_connector_import' | 'managed_connector_delete' | 'managed_connector_checkpoint' | 'managed_connector_google_receipts';
connector: ConnectorKind;
configHash: string;
sourceRoot: string | null;
@@ -49,6 +50,8 @@ interface ConnectorIntent extends Record<string, unknown> {
expected_revision: string | null;
sourcePath: string | null;
content?: string;
+ googleReceipts?: GoogleReceipts;
+ googlePageId?: number;
noEmbed: boolean;
noSchemaPack: boolean;
checkpointKey: string;
@@ -90,6 +93,10 @@ function stableId(value: unknown): string {
return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-5${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}`;
}
+export function connectorCheckpointKey(sourceId: string, incarnation: string, connector: ConnectorKind, config: Record<string, unknown>): string {
+ return digest({ sourceId, incarnation, connector, config });
+}
+
async function connectorFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>,
snapshot: PageSnapshot | null, content: string | null, sourcePath: string | null, root: string | null): Promise<PreparedMutation['file']> {
if (!row.worktree_id || snapshot || !sourcePath || !root) return prepareFileTarget(engine, row, snapshot, content);
@@ -158,7 +165,7 @@ export class ManagedConnectorSync {
private source: ConnectorSource, private authority: SyncAuthority, private binding: WorktreeBinding | null,
private canonicalRoot: string | null, private noEmbed: boolean, private noSchemaPack: boolean, private retryFailed = false,
private lease?: ConnectorLease) {
- this.checkpointKey = digest({ sourceId, incarnation: source.incarnation, connector, config: source.config });
+ this.checkpointKey = connectorCheckpointKey(sourceId, source.incarnation, connector, source.config);
}
async assertLease(engine: BrainEngine): Promise<void> {
if (!this.lease) return;
@@ -285,6 +292,11 @@ export class ManagedConnectorSync {
const row = await this.submit('managed_connector_delete', slug, sourcePath, {});
return row.outcome?.noop !== true;
}
+ async patchGoogleReceipts(slug: string, receipts: GoogleReceipts, pageId: number): Promise<GoogleReceipts> {
+ if (this.connector !== 'google') throw new OperationError('invalid_params', 'Attachment repair requires a Google source.');
+ const row = await this.submit('managed_connector_google_receipts', slug, null, { googleReceipts: receipts, googlePageId: pageId, noEmbed: true });
+ return (row.intent as ConnectorIntent).googleReceipts!;
+ }
async saveState(state: unknown, fresh = false, newestContentAt?: string): Promise<void> {
const next = [{ generation: Number((this.checkpoint[0] as { generation?: number } | undefined)?.generation ?? 0) + 1, state: structuredClone(state) }];
await this.submit('managed_connector_checkpoint', '__managed_connector_checkpoint__', null,
@@ -295,6 +307,11 @@ export class ManagedConnectorSync {
private async submit(kind: ConnectorIntent['kind'], slug: string, sourcePath: string | null, extra: Partial<ConnectorIntent>): Promise<WriteRequest> {
await this.recover(slug);
const snapshot = await this.engine.readPageSnapshot(slug, { sourceId: this.sourceId, includeDeleted: true });
+ if (kind === 'managed_connector_google_receipts') {
+ if (!snapshot || snapshot.page.id !== extra.googlePageId) throw new OperationError('page_identity_changed', 'The historical Gmail page was deleted or recreated.');
+ extra.googleReceipts = ownedGoogleReceipts(snapshot, this.source.config, extra.googleReceipts!);
+ sourcePath = snapshot!.page.source_path!;
+ }
const file = kind === 'managed_connector_checkpoint' ? undefined : await connectorFileTarget(this.engine,
{ source_id: this.sourceId, worktree_id: this.binding?.worktree_id ?? null, slug }, snapshot, extra.content ?? null, sourcePath, this.canonicalRoot);
if (file && sourcePath && resolve(file.path) !== resolve(this.canonicalRoot!, sourcePath)) {
@@ -380,7 +397,7 @@ export class ManagedConnectorSync {
export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
const p = row.intent as ConnectorIntent | null;
- if (!p || !['managed_connector_import', 'managed_connector_delete', 'managed_connector_checkpoint'].includes(p.kind) ||
+ if (!p || !['managed_connector_import', 'managed_connector_delete', 'managed_connector_checkpoint', 'managed_connector_google_receipts'].includes(p.kind) ||
p.syncAuthority.writer.remote || p.syncAuthority.remoteJob) throw new OperationError('permission_denied', 'Unsupported connector authority.');
if (!row.worktree_id && (row.authority.databaseOnlyReason !== 'connector_database' || p.syncAuthority.writer.databaseOnlyReason !== 'connector_database') ||
row.worktree_id && (row.authority.databaseOnlyReason !== undefined || p.syncAuthority.writer.databaseOnlyReason !== undefined)) {
@@ -431,6 +448,12 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
}
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };
} };
+ if (p.kind === 'managed_connector_google_receipts') {
+ if (p.connector !== 'google' || !p.googleReceipts) throw new OperationError('invalid_params', 'Invalid Google attachment receipt mutation.');
+ const [source] = await engine.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [row.source_id]);
+ const prepared = await prepareGoogleReceiptPatch(engine, row, snapshot, source.config, p.googleReceipts);
+ return { ...prepared, validate };
+ }
if (!p.sourcePath || typeof p.content !== 'string' || slugifyPath(p.sourcePath) !== row.slug ||
p.sourcePath.split('/').some(part => !part || part === '.' || part === '..') || p.sourcePath.includes('\\')) {
throw new OperationError('invalid_params', 'The connector import path is invalid.');
@@ -452,7 +475,9 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
const page: Page = { ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(row.created_at), updated_at: new Date(row.created_at) }), ...ready.parsedPage };
const file = await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);
if (file && (file.path !== p.filePath || file.expectedBeforeHash !== p.fileBeforeHash)) throw new OperationError('source_changed', 'The connector canonical file changed during preparation.');
- return { observedRevision: ready.observedRevision, sourceExclusive: true, validate, file, noop: ready.noop, deferEmbedding: p.noEmbed, apply: async tx => {
+ return { observedRevision: ready.observedRevision, sourceExclusive: true,
+ validate: async tx => { await validate(tx); await ready.validate(tx); },
+ file, noop: ready.noop, deferEmbedding: p.noEmbed, apply: async tx => {
await ready.apply(tx);
if (!ready.noop) { await project(tx); await sealPageTextProjection(tx, row.slug, row.source_id); }
return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index d1bd998a07..2ba2220359 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -1,4 +1,5 @@
import type { WriteRequest } from './model.ts';
+import type { WithdrawalTarget } from '../facts/withdrawal-discovery.ts';
export type EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-backstop';
export interface EffectRecovery {
@@ -25,7 +26,7 @@ export interface PersistenceEffect {
source_id: string;
source_incarnation: string;
worktree_id: string | null;
- data: { slug?: string; page_id?: number; relative_path?: string; expected_hash?: string | null; after_slug?: string; source_id?: string; source_scan?: boolean; visibility?: 'private' | 'world'; embedding_attempt_base?: number; embedding_retry_base?: number };
+ data: { version?: 2; targets?: WithdrawalTarget[]; slug?: string; page_id?: number; relative_path?: string; expected_hash?: string | null; after_slug?: string; source_id?: string; source_scan?: boolean; visibility?: 'private' | 'world'; embedding_attempt_base?: number; embedding_retry_base?: number };
state: 'queued' | 'running' | 'committed' | 'failed';
execution_token: string | null;
claim_expires_at: string | Date | null;
diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.ts
index 857334d845..f41472b5fe 100644
--- a/src/core/persistence/effect-retry.ts
+++ b/src/core/persistence/effect-retry.ts
@@ -10,6 +10,7 @@ import { guardEffectSource } from './effect-recovery.ts';
import { assertEmbeddingEffectEnabled, readEmbeddingEffectProjection, selectedEffectPage } from './effects.ts';
import type { PersistenceEffect } from './effect-model.ts';
import type { WriteRequest } from './model.ts';
+import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';
async function mountedEmbeddingSignature(engine: BrainEngine): Promise<string> {
const rows = await engine.executeRaw<{ key: string; value: string }>(`SELECT key,value FROM config
@@ -56,20 +57,26 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: string
return engine.transaction(async tx => {
const [selected] = await tx.executeRaw<PersistenceEffect>("SELECT * FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [request.id]);
if (!selected) throw new OperationError('invalid_params', 'The embedding obligation is unavailable.');
+ if (selected.data.source_scan && selected.data.version === undefined) {
+ if (selected.worktree_id) await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [selected.worktree_id]);
+ await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
+ }
await guardEffectSource(tx, selected, hostId);
await authorizeStoredRequest(tx, request, true);
const authority = await submissionAuthority({ engine: tx, remote: false, sourceId } as OperationContext,
request.operation, sourceId, request.source_incarnation, request.slug);
await authorizeWrite(tx, authority, request.operation, request.slug, true);
if (request.state !== 'committed') throw new OperationError('write_pending', 'Only committed canonical requests have retryable embedding obligations.');
- const [effect] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [selected.id]);
- if (!effect || effect.source_id !== sourceId || effect.source_incarnation !== request.source_incarnation || effect.recovery) {
+ const [stored] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [selected.id]);
+ if (!stored || stored.source_id !== sourceId || stored.source_incarnation !== request.source_incarnation || stored.recovery) {
throw new OperationError('source_changed', 'The effect source or recovery state changed.');
}
+ const effect = await upgradeWithdrawalEffect(tx, stored, hostId, false);
const snapshot = await selectedEffectPage(tx, effect);
- const scanComplete = effect.data.source_scan === true && !snapshot;
- if (!scanComplete && (!snapshot || snapshot.page.deleted_at || !effect.data.source_scan &&
- (snapshot.revision !== effect.revision || snapshot.page.id !== effect.data.page_id))) {
+ const scanning = targetedWithdrawalEffect(effect) || effect.data.source_scan === true;
+ const scanComplete = scanning && !snapshot;
+ if (!scanComplete && (!snapshot || !scanning &&
+ (snapshot.page.deleted_at || snapshot.revision !== effect.revision || snapshot.page.id !== effect.data.page_id))) {
throw new OperationError('revision_conflict', 'The original embedding obligation is superseded; inspect the current page instead.');
}
if (snapshot) {
@@ -87,8 +94,8 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: string
if (effect.execution_token !== null) throw new OperationError('write_claim_lost', 'A failed effect still has an execution claim; inspect it before retrying.');
const signature = policy === 'mounted_database' && !scanComplete ? await mountedEmbeddingSignature(tx) : configuredSignature;
if (!signature && !scanComplete) return { ...receipt, state: 'failed', action: 'blocked', reason: 'embedding_unconfigured', next_action: 'Configure embeddings, then inspect this request again.' };
- const pending = scanComplete ? [] : (await readEmbeddingEffectProjection(tx, effect, snapshot!, hostId, signature!)).pending;
- const complete = scanComplete || pending.length === 0 && !effect.data.source_scan;
+ const pending = scanComplete || snapshot?.page.deleted_at ? [] : (await readEmbeddingEffectProjection(tx, effect, snapshot!, hostId, signature!)).pending;
+ const complete = scanComplete || pending.length === 0 && !scanning;
if (!complete) {
await tx.executeRaw("SELECT key FROM config WHERE key='embedding_disabled' FOR SHARE");
try { await assertEmbeddingEffectEnabled(tx, config); }
@@ -103,11 +110,11 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: string
if (dryRun) return { ...receipt, state: 'failed', action: complete ? 'would_reconcile' : 'would_retry',
pending_chunks: pending.length, next_action: 'Run the same command without --dry-run to approve this bounded action.' };
const [updated] = await tx.executeRaw<{ state: string }>(`UPDATE persistence_effects SET state=$4,
- data=CASE WHEN $4='queued' THEN data||jsonb_build_object('embedding_attempt_base',attempts,'embedding_retry_base',attempts) ELSE data END,
+ data=CASE WHEN $4='queued' THEN $5::text::jsonb||jsonb_build_object('embedding_attempt_base',attempts,'embedding_retry_base',attempts) ELSE $5::text::jsonb END,
error_code=NULL,claim_expires_at=NULL,next_attempt_at=now(),updated_at=now(),
outcome=CASE WHEN $4='committed' THEN '{"embedding":"reconciled"}'::jsonb ELSE NULL END
WHERE id=$1 AND state='failed' AND execution_token IS NULL AND recovery IS NULL AND attempts=$2 AND source_incarnation=$3::uuid RETURNING state`,
- [effect.id, effect.attempts, effect.source_incarnation, complete ? 'committed' : 'queued']);
+ [effect.id, effect.attempts, effect.source_incarnation, complete ? 'committed' : 'queued', JSON.stringify(effect.data)]);
if (!updated) throw new OperationError('write_claim_lost', 'The embedding obligation changed during retry approval.');
return { ...receipt, state: updated.state, action: complete ? 'reconciled' : 'retry_queued', pending_chunks: pending.length,
next_action: complete ? 'The existing vectors satisfy this obligation; no provider work was scheduled.' : 'The resident owner may spend up to five attempts only when its selected file configuration and the database policy permit embedding, under existing provider and job budgets. Repeating this command does not renew that allowance.' };
diff --git a/src/core/persistence/effect-targets.ts b/src/core/persistence/effect-targets.ts
new file mode 100644
index 0000000000..b17ab29764
--- /dev/null
+++ b/src/core/persistence/effect-targets.ts
@@ -0,0 +1,48 @@
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { discoverWithdrawalTargets, withdrawalDiscoveryFailure, WITHDRAWAL_LIMITS, type WithdrawalClaim } from '../facts/withdrawal-discovery.ts';
+import type { PersistenceEffect } from './effect-model.ts';
+import { guardEffectSource } from './effect-recovery.ts';
+
+export function targetedWithdrawalEffect(effect: PersistenceEffect): boolean {
+ if (effect.data.version === undefined) return false;
+ const targets = effect.data.targets;
+ if (effect.data.version !== 2 || !Array.isArray(targets) || targets.length > WITHDRAWAL_LIMITS.targets || Buffer.byteLength(JSON.stringify(targets)) > WITHDRAWAL_LIMITS.targetBytes ||
+ targets.some((target, index) => !target || typeof target.slug !== 'string' || !target.slug || !Number.isSafeInteger(target.page_id) || target.page_id <= 0 ||
+ typeof target.revision !== 'string' || !/^[0-9a-f-]{36}$/i.test(target.revision) || index > 0 && targets[index - 1].slug >= target.slug)) {
+ throw new OperationError('withdrawal_provenance', 'The withdrawal target manifest is invalid. Durable intent remains pending.',
+ 'Keep older mutation workers stopped and inspect the retained receipt on the host. Do not reset its cursor. See docs/guides/concurrent-writes.md#withdrawal-recovery.');
+ }
+ return true;
+}
+
+export async function upgradeWithdrawalEffect(engine: BrainEngine, effect: PersistenceEffect, hostId: string, persist = true): Promise<PersistenceEffect> {
+ if (targetedWithdrawalEffect(effect) || !effect.data.source_scan && effect.kind !== 'withdrawal-mirror') return effect;
+ if (effect.kind !== 'withdrawal-mirror') {
+ const withdrawal = await engine.executeRaw(`SELECT r.id FROM persistence_requests r WHERE r.id=$1::uuid
+ AND (r.operation IN ('forget','forget_fact') OR EXISTS (SELECT 1 FROM persistence_effects m WHERE m.request_id=r.id AND m.kind='withdrawal-mirror'))`, [effect.request_id]);
+ if (!withdrawal.length) return effect;
+ }
+ return engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ if (effect.worktree_id) await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [effect.worktree_id]);
+ await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [effect.source_id]);
+ await guardEffectSource(tx, effect, hostId);
+ const claims = await tx.executeRaw<WithdrawalClaim>('SELECT visibility,fact_hash FROM fact_withdrawals WHERE source_id=$1 ORDER BY visibility,fact_hash LIMIT $2',
+ [effect.source_id, WITHDRAWAL_LIMITS.targets + 1]);
+ if (!claims.length) throw new OperationError('withdrawal_provenance', 'Legacy withdrawal intent has no verifiable ledger. Its queued work remains retained.');
+ const discovered = await discoverWithdrawalTargets(tx, effect.source_id, claims).catch(withdrawalDiscoveryFailure);
+ const remaining = await tx.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id=$1 AND id=ANY($2::int[])
+ AND ($3::text IS NULL OR slug>$3)`, [effect.source_id, discovered.map(target => target.page_id), effect.data.after_slug ?? null]);
+ const ids = new Set(remaining.map(row => row.id));
+ const targets = discovered.filter(target => ids.has(target.page_id));
+ const { source_scan, after_slug, ...retained } = effect.data;
+ const data = { ...retained, version: 2 as const, targets, legacy_after_slug: after_slug ?? null };
+ if (!persist) return { ...effect, data };
+ const [current] = await tx.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET data=(data-'source_scan'-'after_slug')||$3::text::jsonb,updated_at=now()
+ WHERE id=$1 AND execution_token IS NOT DISTINCT FROM $2::uuid AND recovery IS NULL RETURNING *`,
+ [effect.id, effect.execution_token, JSON.stringify(data)]);
+ if (!current) throw new OperationError('write_claim_lost', 'The legacy withdrawal effect changed during discovery.');
+ return current;
+ });
+}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index be7f94f81d..8505c7ad53 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -1,4 +1,5 @@
import { randomUUID } from 'node:crypto';
+import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';
import { existsSync, statSync } from 'node:fs';
import { join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
@@ -41,6 +42,16 @@ export interface EffectWorkerOptions {
}
export async function selectedEffectPage(engine: BrainEngine, effect: PersistenceEffect): Promise<PageSnapshot | null> {
+ if (targetedWithdrawalEffect(effect)) {
+ for (const target of effect.data.targets!) {
+ if (effect.data.after_slug !== undefined && target.slug <= effect.data.after_slug) continue;
+ const snapshot = await engine.readPageSnapshot(target.slug, { sourceId: effect.source_id, includeDeleted: true });
+ if (snapshot?.page.id !== target.page_id || snapshot.sourceIncarnation !== effect.source_incarnation) continue;
+ if (effect.kind === 'embedding' && (snapshot.page.deleted_at || snapshot.revision !== target.revision)) continue;
+ return snapshot;
+ }
+ return null;
+ }
let slug = effect.data.slug;
if (effect.data.source_scan || effect.kind === 'withdrawal-mirror') {
const [row] = await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND ($2::text IS NULL OR slug>$2) ORDER BY slug LIMIT 1',
@@ -52,7 +63,7 @@ export async function selectedEffectPage(engine: BrainEngine, effect: Persistenc
}
async function finishPage(engine: BrainEngine, effect: PersistenceEffect, snapshot: PageSnapshot | null, outcome: Record<string, unknown> = {}): Promise<void> {
- if (snapshot && (effect.data.source_scan || effect.kind === 'withdrawal-mirror')) await advanceEffectCursor(engine, effect, snapshot.page.slug);
+ if (snapshot && (targetedWithdrawalEffect(effect) || effect.data.source_scan || effect.kind === 'withdrawal-mirror')) await advanceEffectCursor(engine, effect, snapshot.page.slug);
else await completeEffect(engine, effect, outcome);
}
@@ -94,7 +105,7 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }
const snapshot = await selectedEffectPage(engine, effect);
let path: string;
- if (effect.data.source_scan) {
+ if (targetedWithdrawalEffect(effect) || effect.data.source_scan) {
if (!snapshot) { await completeEffect(engine, effect); return; }
const file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,
snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });
@@ -138,7 +149,7 @@ export async function readEmbeddingEffectProjection(engine: BrainEngine, effect:
async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: PersistenceEffect, opts: EffectWorkerOptions): Promise<void> {
const snapshot = await selectedEffectPage(engine, effect);
if (!snapshot || snapshot.page.deleted_at) { await finishPage(engine, effect, snapshot); return; }
- if (!effect.data.source_scan && (snapshot.revision !== effect.revision || snapshot.page.id !== effect.data.page_id)) {
+ if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan && (snapshot.revision !== effect.revision || snapshot.page.id !== effect.data.page_id)) {
await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return;
}
const signature = opts.embedding?.signature ?? currentEmbeddingSignature();
@@ -194,7 +205,7 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
return installed;
});
if (!installed) {
- if (effect.data.source_scan) throw new OperationError('revision_conflict', 'The page changed while embedding.');
+ if (targetedWithdrawalEffect(effect) || effect.data.source_scan) throw new OperationError('revision_conflict', 'The page changed while embedding.');
await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return;
}
return;
@@ -272,8 +283,9 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
finally { await lock.release(); }
}
while (attempted++ < limit && !opts.signal?.aborted) {
- const effect = await claimPersistenceEffect(engine, opts.hostId);
- if (!effect) return;
+ const claimed = await claimPersistenceEffect(engine, opts.hostId);
+ if (!claimed) return;
+ let effect = claimed;
let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;
try {
const binding = effect.worktree_id ? await getWorktreeBinding(engine, effect.source_id, opts.hostId) : null;
@@ -289,6 +301,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
if (blocked.length) throw new OperationError('recovery_required', 'Canonical publication recovery must finish first.');
}
});
+ effect = await upgradeWithdrawalEffect(engine, effect, opts.hostId);
if (effect.kind === 'withdrawal-mirror') await mirrorPage(engine, effect, binding, opts);
else if (effect.kind === 'git') await gitPage(engine, effect, binding, opts);
else if (effect.kind === 'facts-backstop') await dispatchFactsBackstopEffect(engine, effect, opts.hostId);
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index 02ee410dfd..a6692796d7 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -73,7 +73,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
if (snapshot?.page.deleted_at || (snapshot?.page.id ?? null) !== row.page_id || (snapshot?.revision ?? null) !== (p.expected_revision ?? null)) {
throw new OperationError('revision_conflict', 'The fact entity changed after extraction admission.');
}
- const facts = (p.facts ?? []).map(thawFact);
+ const facts = (p.facts ?? []).map(fact => ({ ...thawFact(fact), embedding_model: fact.embedding ? p.embedding?.model ?? null : null }));
if (!facts.length || facts.some(fact => fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !snapshot)) {
throw new OperationError('invalid_params', 'The prepared facts do not match their entity.');
}
@@ -90,7 +90,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const earlier = seen.get(key);
if (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }
seen.set(key, entries.length);
- const decision = await decideSingleFact(engine, row.source_id, fact, fact.embedding ?? null);
+ const decision = await decideSingleFact(engine, row.source_id, fact, fact.embedding ?? null, fact.embedding_model);
if (decision.candidate) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }
const rowNum = fact.entity_slug !== null ? nextRow++ : undefined;
if (rowNum !== undefined) body = upsertFactRow(body, { rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,
@@ -122,7 +122,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
for (const entry of entries) {
await assertFactNotWithdrawn(tx, row.source_id, entry.fact);
if (entry.duplicateOf !== undefined) continue;
- const current = await decideSingleFact(tx, row.source_id, entry.fact, entry.fact.embedding ?? null);
+ const current = await decideSingleFact(tx, row.source_id, entry.fact, entry.fact.embedding ?? null, entry.fact.embedding_model);
if ((current.candidate?.id ?? null) !== entry.duplicateId) throw new OperationError('revision_conflict', 'The fact deduplication state changed before publication.');
}
}, apply: async tx => {
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index 4a2ebb9849..cd2fe98204 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -137,7 +137,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
} as Page, tags));
const project = code || image ? undefined : prepareCanonicalProjections(ready.parsedPage!, row.slug, row.source_id);
return { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),
- deferEmbedding: image || p.noEmbed, validate: checkPaths,
+ deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },
file: { root, path, content: rendered, expectedBeforeHash: p.targetHash },
apply: async tx => {
await ready.apply(tx);
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 90ae93e578..23f76f286e 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -37,12 +37,15 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const observedRevision = snapshot?.revision ?? null;
await assertFactNotWithdrawn(engine, row.source_id, input);
signal?.throwIfAborted();
- const { embedding, degraded } = await prepareFactEmbedding(input.fact, signal);
+ const embeddingConfigSql = "SELECT key,value FROM config WHERE key IN ('embedding_model','embedding_dimensions') ORDER BY key";
+ const observedEmbeddingConfig = JSON.stringify(await engine.executeRaw(embeddingConfigSql));
+ const { embedding, embedding_model, degraded } = await prepareFactEmbedding(input.fact, signal);
signal?.throwIfAborted();
- const decision = await decideSingleFact(engine, row.source_id, input, embedding);
+ const decision = await decideSingleFact(engine, row.source_id, input, embedding, embedding_model);
const validate = async (tx: BrainEngine) => {
await assertFactNotWithdrawn(tx, row.source_id, input);
- const current = await decideSingleFact(tx, row.source_id, input, embedding);
+ if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict();
+ const current = await decideSingleFact(tx, row.source_id, input, embedding, embedding_model);
if (candidateState(current) !== candidateState(decision)) conflict();
};
if (decision.status === 'duplicate') {
@@ -52,7 +55,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const validUntil = p.valid_until ? new Date(String(p.valid_until)) : null;
const validFrom = new Date(String(p.valid_from));
const fact: NewFact = { ...input, source: String(p.provenance).trim(), valid_from: validFrom, valid_until: validUntil,
- confidence: 1, embedding };
+ confidence: 1, embedding, embedding_model };
let page: PreparedMutation | undefined;
let rowNum: number | undefined;
if (p.fence === true && snapshot) {
diff --git a/src/core/persistence/native-lock.ts b/src/core/persistence/native-lock.ts
index cfe24b7394..0748843616 100644
--- a/src/core/persistence/native-lock.ts
+++ b/src/core/persistence/native-lock.ts
@@ -4,7 +4,14 @@ import { dirname, isAbsolute } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { family, GLIBC, MUSL } from 'detect-libc';
-interface NativeBinding {
+export interface NativeExportPublisher {
+ beginExport(absoluteDestination: string): object;
+ publishExportFile(handle: object, relativePath: string, data: Buffer): void;
+ completeExport(handle: object): void;
+ closeExport(handle: object): void;
+}
+
+interface NativeBinding extends NativeExportPublisher {
target: string;
openLock(path: string): object;
tryLock(handle: object): boolean;
@@ -87,6 +94,15 @@ export async function nativeLockCapability(): Promise<{ target: string; napi: 3
return { target: binding.target, napi: 3 };
}
+export async function nativeExportPublisher(): Promise<NativeExportPublisher> {
+ const binding = await (bindingPromise ??= loadBinding());
+ if (typeof binding.beginExport !== 'function' || typeof binding.publishExportFile !== 'function' ||
+ typeof binding.completeExport !== 'function' || typeof binding.closeExport !== 'function') {
+ throw new NativeLockUnavailableError('Installed native addon lacks safe export publication support');
+ }
+ return binding;
+}
+
function budget(value: number | undefined, fallback: number, minimum: number): number {
const result = value ?? fallback;
if (!Number.isFinite(result) || result < minimum || result > 2 ** 31 - 1) throw new RangeError(`Native lock duration must be between ${minimum} and ${2 ** 31 - 1} milliseconds`);
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 83937b6a45..8fad9c0924 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -219,7 +219,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;
const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered);
const sourcePath = file ? scannerSourcePath(file.root, file.path) : undefined;
- return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, apply: async tx => {
+ return { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, validate: ready.validate, apply: async tx => {
let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;
if (!noop) {
await ready.apply(tx);
diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.ts
index a1b6f1008a..1f915f58bb 100644
--- a/src/core/persistence/prepared-import.ts
+++ b/src/core/persistence/prepared-import.ts
@@ -8,5 +8,6 @@ export interface PreparedContentImport {
observedRevision: string | null;
noop: boolean;
result: ImportResult;
+ validate(tx: BrainEngine): Promise<void>;
apply(tx: BrainEngine): Promise<void>;
}
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 2525734d27..2f4aa46909 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -80,6 +80,7 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
await authorizeStoredRequest(tx, row, true);
assertReconcilePins(artifact.preconditions, (await readReconcileState(tx, row.source_id, row.slug, artifact.preconditions.assessment_at)).pins);
verifyReconcileBackup(reference, artifact);
+ await ready.validate(tx);
},
apply: async tx => {
await ready.apply(tx);
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index fe9f3a5ebc..2170348ab9 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -149,7 +149,9 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (!prepared || prepared.slug !== row.slug) throw new OperationError('invalid_params', result.error ?? 'The code file identity could not be prepared.');
const ready = prepared;
if (ready.observedRevision !== (snapshot?.revision ?? null)) throw new OperationError('revision_conflict', 'The code page changed during preparation.');
- return { observedRevision: ready.observedRevision, validate, noop: ready.noop, deferEmbedding: true, apply: async tx => {
+ return { observedRevision: ready.observedRevision,
+ validate: async tx => { await validate(tx); await ready.validate(tx); },
+ noop: ready.noop, deferEmbedding: true, apply: async tx => {
await ready.apply(tx);
return { status: ready.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,
chunks: result.chunks, noop: ready.noop, imported_file: true };
@@ -199,7 +201,9 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (overlay && p.companyApproval) throw new OperationError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.');
if (overlay && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw new OperationError('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.');
const project = prepareCanonicalProjections(ready.parsedPage, row.slug, row.source_id);
- return { observedRevision: snapshot?.revision ?? null, validate, deferEmbedding: p.processingOptions?.noEmbed,
+ return { observedRevision: snapshot?.revision ?? null,
+ validate: async tx => { await validate(tx); await ready.validate(tx); },
+ deferEmbedding: p.processingOptions?.noEmbed,
...(overlay ? { file: { root, path: join(root, p.path), content: serializePageToMarkdown(renderedPage, tags), expectedBeforeHash: p.rawHash } } : {}),
apply: async tx => {
await ready.apply(tx);
diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.ts
index 1bd91083db..7d496abaa8 100644
--- a/src/core/persistence/writer-guard-schema.ts
+++ b/src/core/persistence/writer-guard-schema.ts
@@ -28,6 +28,10 @@ BEGIN
END IF;
IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
ELSIF TG_TABLE_NAME IN ('facts','takes') AND TG_OP='UPDATE' THEN
+ IF TG_TABLE_NAME='facts' THEN
+ row_data := row_data - ARRAY['embedding_model','embedded_text_hash'];
+ old_data := old_data - ARRAY['embedding_model','embedded_text_hash'];
+ END IF;
-- Embedding completion and retrieval telemetry are physical projections.
IF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])
= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NEW; END IF;
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index e901f4247c..a22ccc384e 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -83,7 +83,7 @@ import { acquireLock, releaseLock, type LockHandle } from './pglite-lock.ts';
// connect() catch. No cycle: pglite-repair.ts imports nothing from this file.
import { attemptWalRepairAndRetry, closeRepairEpisodeIfOpen, type WalRepairReceipt } from './pglite-repair.ts';
import { getFtsLanguage } from './fts-language.ts';
-import { splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
+import { splitEmbeddingSignature, currentSpaceChunkPredicate, lockEmbeddingSources } from './embedding-invalidation.ts';
import type {
Page, PageInput, PageFilters, PageType,
Chunk, ChunkInput, StaleChunkRow, StalePageRow, ChunklessPageRow,
@@ -1196,7 +1196,13 @@ export class PGLiteEngine implements BrainEngine {
EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='submission_authority') AS minion_jobs_submission_authority_exists,
EXISTS (SELECT 1 FROM information_schema.columns
- WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='claim_generation') AS minion_jobs_claim_generation_exists
+ WHERE table_schema='public' AND table_name='minion_jobs' AND column_name='claim_generation') AS minion_jobs_claim_generation_exists,
+ EXISTS (SELECT 1 FROM information_schema.tables
+ WHERE table_schema='public' AND table_name='facts') AS facts_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema='public' AND table_name='facts' AND column_name='embedding_model') AS facts_embedding_model_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema='public' AND table_name='facts' AND column_name='embedded_text_hash') AS facts_embedded_text_hash_exists
`);
const probe = rows[0] as {
pages_exists: boolean;
@@ -1252,6 +1258,9 @@ export class PGLiteEngine implements BrainEngine {
minion_jobs_pq_lease_exists: boolean;
minion_jobs_submission_authority_exists: boolean;
minion_jobs_claim_generation_exists: boolean;
+ facts_exists: boolean;
+ facts_embedding_model_exists: boolean;
+ facts_embedded_text_hash_exists: boolean;
};
const needsPagesBootstrap = probe.pages_exists && !probe.source_id_exists;
@@ -1353,6 +1362,8 @@ export class PGLiteEngine implements BrainEngine {
// partial upgrades too; historical authority remains NULL until reviewed.
const needsMinionJobsAuthority = probe.minion_jobs_exists
&& (!probe.minion_jobs_submission_authority_exists || !probe.minion_jobs_claim_generation_exists);
+ const needsFactEmbeddingIdentity = probe.facts_exists
+ && (!probe.facts_embedding_model_exists || !probe.facts_embedded_text_hash_exists);
// Fresh installs (no tables yet) and modern brains both no-op.
if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap
@@ -1368,10 +1379,17 @@ export class PGLiteEngine implements BrainEngine {
&& !needsPagesLinksExtractedAt
&& !needsTimelineEventPageId
&& !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey
- && !needsMinionJobsPrivateQueue && !needsMinionJobsAuthority) return;
+ && !needsMinionJobsPrivateQueue && !needsMinionJobsAuthority && !needsFactEmbeddingIdentity) return;
process.stderr.write(' Schema forward-reference gap detected, applying bootstrap\n');
+ if (needsFactEmbeddingIdentity) {
+ await this.db.exec(`
+ ALTER TABLE facts ADD COLUMN IF NOT EXISTS embedding_model TEXT;
+ ALTER TABLE facts ADD COLUMN IF NOT EXISTS embedded_text_hash TEXT;
+ `);
+ }
+
if (needsPagesBootstrap) {
// Mirror schema-embedded.ts shape for `sources` so the subsequent
// PGLITE_SCHEMA_SQL CREATE TABLE IF NOT EXISTS is a true no-op.
@@ -2900,6 +2918,11 @@ export class PGLiteEngine implements BrainEngine {
extraFilter += ` AND p.source_id = $${params.length}`;
}
+ if (resolvedColEarly.name === 'embedding') {
+ params.push(resolvedColEarly.embeddingModel || null);
+ extraFilter += ` AND ((cc.model=$${params.length} AND (cc.embedded_text_hash=md5(cc.chunk_text) OR cc.embedded_text_hash IS NULL))
+ OR ($${params.length}::text IS NULL AND NOT EXISTS(SELECT 1 FROM config WHERE key='embedding_migration.state')))`;
+ }
const innerLimitIdx = params.length;
params.push(innerLimit, limit, offset);
const innerLimitParam = `$${innerLimitIdx + 1}`;
@@ -3350,7 +3373,7 @@ export class PGLiteEngine implements BrainEngine {
*/
private buildStaleChunkWhere(staleColRef: string, opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean }): { where: string; params: unknown[] } {
const params: unknown[] = [];
- const conds: string[] = [];
+ const conds: string[] = ['p.deleted_at IS NULL'];
if (opts?.signature !== undefined) {
params.push(opts.signature);
conds.push(
@@ -3432,18 +3455,23 @@ export class PGLiteEngine implements BrainEngine {
? `(p.embedding_signature IS NULL OR p.embedding_signature <> $1)`
: `p.embedding_signature IS NOT NULL
AND p.embedding_signature <> $1`;
- const { rows } = await this.db.query(
- `UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL
- FROM pages p
- WHERE cc.page_id = p.id
- AND cc.${colId} IS NOT NULL
- AND NOT ${currentSpaceChunkPredicate(colId, 2, 3)}
- AND ${sigClause}${srcClause}
- RETURNING cc.page_id`,
- params,
- );
- return (rows as unknown[]).length;
+ return this.transaction(async tx => {
+ params.push(await lockEmbeddingSources(tx, opts.sourceId));
+ const rows = await tx.executeRaw(
+ `UPDATE content_chunks cc
+ SET ${colId} = NULL, embedded_at = NULL
+ FROM pages p
+ WHERE cc.page_id = p.id
+ AND p.source_id=ANY($${params.length}::text[])
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND cc.${colId} IS NOT NULL
+ AND NOT ${currentSpaceChunkPredicate(colId, 2, 3)}
+ AND ${sigClause}${srcClause}
+ RETURNING cc.page_id`,
+ params,
+ );
+ return (rows as unknown[]).length;
+ });
}
async invalidateContentDriftEmbeddings(opts?: { sourceId?: string }): Promise<number> {
@@ -3463,19 +3491,25 @@ export class PGLiteEngine implements BrainEngine {
params.push(opts.sourceId);
srcClause = ` AND p.source_id = $${params.length}`;
}
- const { rows } = await this.db.query(
- `UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL, embedded_text_hash = NULL
- FROM pages p
- WHERE cc.page_id = p.id
- AND cc.${colId} IS NOT NULL
- AND cc.embedded_text_hash IS NOT NULL
- AND cc.embedded_text_hash <> md5(cc.chunk_text)
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')${srcClause}
- RETURNING cc.page_id`,
- params,
- );
- return (rows as unknown[]).length;
+ return this.transaction(async tx => {
+ params.push(await lockEmbeddingSources(tx, opts?.sourceId));
+ const rows = await tx.executeRaw(
+ `UPDATE content_chunks cc
+ SET ${colId} = NULL, embedded_at = NULL, embedded_text_hash = NULL
+ FROM pages p
+ WHERE cc.page_id = p.id
+ AND p.source_id=ANY($${params.length}::text[])
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND p.deleted_at IS NULL
+ AND cc.${colId} IS NOT NULL
+ AND cc.embedded_text_hash IS NOT NULL
+ AND cc.embedded_text_hash <> md5(cc.chunk_text)
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')${srcClause}
+ RETURNING cc.page_id`,
+ params,
+ );
+ return (rows as unknown[]).length;
+ });
}
async listStaleChunks(opts?: {
@@ -3507,7 +3541,7 @@ export class PGLiteEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${staleColId} IS NULL
+ WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
LIMIT $1`,
@@ -3518,7 +3552,7 @@ export class PGLiteEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${staleColId} IS NULL
+ WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (
p.updated_at < $1::timestamptz
@@ -3537,7 +3571,7 @@ export class PGLiteEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${staleColId} IS NULL
+ WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND p.source_id = $1
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
@@ -3549,7 +3583,7 @@ export class PGLiteEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${staleColId} IS NULL
+ WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND p.source_id = $1
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (
@@ -3574,7 +3608,7 @@ export class PGLiteEngine implements BrainEngine {
cc.model, cc.token_count, p.source_id, cc.page_id
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${staleColId} IS NULL
+ WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (cc.page_id, cc.chunk_index) > ($1, $2)
ORDER BY cc.page_id, cc.chunk_index
@@ -3588,7 +3622,7 @@ export class PGLiteEngine implements BrainEngine {
cc.model, cc.token_count, p.source_id, cc.page_id
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${staleColId} IS NULL
+ WHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL
AND p.source_id = $1
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (cc.page_id, cc.chunk_index) > ($2, $3)
@@ -5205,7 +5239,7 @@ export class PGLiteEngine implements BrainEngine {
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
): Promise<FactRow[]> {
return factsImpl.findCandidateDuplicates(this.factsDeps, source_id, entitySlug, factText, opts);
}
@@ -5566,7 +5600,7 @@ export class PGLiteEngine implements BrainEngine {
-- count can reach zero and the embed.stale remediation can converge.
(SELECT count(*) FROM content_chunks cc
JOIN scoped_pages p ON p.id = cc.page_id
- WHERE cc.${colId} IS NULL
+ WHERE cc.${colId} IS NULL AND p.deleted_at IS NULL
AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
) as missing_embeddings,
(SELECT count(*) FROM links l
diff --git a/src/core/pglite-engine/facts.ts b/src/core/pglite-engine/facts.ts
index 62a26af5c0..ac9e268ca5 100644
--- a/src/core/pglite-engine/facts.ts
+++ b/src/core/pglite-engine/facts.ts
@@ -53,25 +53,25 @@ export async function insertFact(
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
+ claim_metric, claim_value, claim_unit, claim_period, embedding_model, embedded_text_hash
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
NULL, NULL,
- $13, $14, $15, $16
+ $13, $14, $15, $16, NULL, NULL
) RETURNING id`
: `INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
+ claim_metric, claim_value, claim_unit, claim_period, embedding_model, embedded_text_hash
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
$13::vector, $14,
- $15, $16, $17, $18
+ $15, $16, $17, $18, $19, CASE WHEN $19::text IS NOT NULL THEN md5($3) END
) RETURNING id`,
embedStr === null
? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, claimMetric, claimValue, claimUnit, claimPeriod]
- : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod],
+ : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod, input.embedding_model ?? null],
);
const newId = ins.rows[0].id;
await tx.query(
@@ -90,25 +90,25 @@ export async function insertFact(
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
+ claim_metric, claim_value, claim_unit, claim_period, embedding_model, embedded_text_hash
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
NULL, NULL,
- $13, $14, $15, $16
+ $13, $14, $15, $16, NULL, NULL
) RETURNING id`
: `INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
embedding, embedded_at,
- claim_metric, claim_value, claim_unit, claim_period
+ claim_metric, claim_value, claim_unit, claim_period, embedding_model, embedded_text_hash
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,
$13::vector, $14,
- $15, $16, $17, $18
+ $15, $16, $17, $18, $19, CASE WHEN $19::text IS NOT NULL THEN md5($3) END
) RETURNING id`,
embedStr === null
? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, claimMetric, claimValue, claimUnit, claimPeriod]
- : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod],
+ : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, input.source, sourceSession, confidence, embedStr, embeddedAt, claimMetric, claimValue, claimUnit, claimPeriod, input.embedding_model ?? null],
);
return { id: ins.rows[0].id, status: 'inserted' };
}
@@ -213,13 +213,13 @@ export async function insertFacts(
embedding, embedded_at,
row_num, source_markdown_slug,
claim_metric, claim_value, claim_unit, claim_period,
- event_type
+ event_type, embedding_model, embedded_text_hash
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,
NULL, $14,
$15, $16,
$17, $18, $19, $20,
- $21
+ $21, NULL, NULL
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
@@ -231,13 +231,13 @@ export async function insertFacts(
embedding, embedded_at,
row_num, source_markdown_slug,
claim_metric, claim_value, claim_unit, claim_period,
- event_type
+ event_type, embedding_model, embedded_text_hash
) VALUES (
$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,
$14::vector, $15,
$16, $17,
$18, $19, $20, $21,
- $22
+ $22, $23, CASE WHEN $23::text IS NOT NULL THEN md5($3) END
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
@@ -245,7 +245,7 @@ export async function insertFacts(
RETURNING id`,
embedStr === null
? [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, expiredAt, input.source, sourceSession, confidence, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType]
- : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, expiredAt, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType],
+ : [ctx.source_id, entitySlug, input.fact, kind, visibility, notability, context, validFrom, validUntil, expiredAt, input.source, sourceSession, confidence, embedStr, embeddedAt, input.row_num, input.source_markdown_slug, claimMetric, claimValue, claimUnit, claimPeriod, eventType, input.embedding_model ?? null],
);
if (ins.rows[0]) out.push(ins.rows[0].id);
rowIds.push(ins.rows[0] ? Number(ins.rows[0].id) : null);
@@ -440,12 +440,13 @@ export async function findCandidateDuplicates(
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
): Promise<FactRow[]> {
const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
// Validity-lapsed rows are not dedup candidates: a re-stated fact after
// its valid_until lapses re-inserts fresh (WP5 read-time TTL honesty).
if (opts?.embedding) {
+ if (!opts.embeddingModel) return [];
// Embedding-cosine ordered candidates within the entity bucket.
const vec = toPgVectorLiteral(opts.embedding);
const result = await deps.db.query<FactRowSqlShape>(
@@ -455,9 +456,12 @@ export async function findCandidateDuplicates(
AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until > now())
AND embedding IS NOT NULL
+ AND embedding_model=$5 AND embedded_text_hash=md5(fact)
+ AND vector_dims(embedding)=$6
+ AND source != ALL($7::text[])
ORDER BY embedding <=> $3::vector
LIMIT $4`,
- [source_id, entitySlug, vec, k],
+ [source_id, entitySlug, vec, k, opts.embeddingModel, opts.embedding.length, [...AUDIT_ROW_SOURCES]],
);
return result.rows.map(rowToFact);
}
@@ -532,7 +536,8 @@ export async function findTrajectory(deps: PgliteFactsDeps, opts: import('../eng
claim_metric, claim_value, claim_unit, claim_period,
event_type,
fact, source_session, source_markdown_slug,
- embedding
+ CASE WHEN embedding_model=(SELECT value FROM config WHERE key='embedding_model')
+ AND embedded_text_hash=md5(fact) THEN embedding END AS embedding
FROM facts
WHERE ${where.join(' AND ')}
ORDER BY valid_from ASC, id ASC
@@ -712,6 +717,8 @@ interface FactRowSqlShape {
source_session: string | null;
confidence: number;
embedding: string | number[] | Float32Array | null;
+ embedding_model?: string | null;
+ embedded_text_hash?: string | null;
embedded_at: Date | string | null;
created_at: Date | string;
}
@@ -756,6 +763,8 @@ function rowToFact(row: FactRowSqlShape): FactRow {
source_session: row.source_session,
confidence: Number(row.confidence),
embedding,
+ embedding_model: row.embedding_model ?? null,
+ embedded_text_hash: row.embedded_text_hash ?? null,
embedded_at: toDate(row.embedded_at),
created_at: toDate(row.created_at)!,
};
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index c06158dd1f..7c6fec995f 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -71,7 +71,7 @@ import {
EmbeddingColumnNotRegisteredError,
} from './search/embedding-column.ts';
import { getFtsLanguage, applyFtsLanguagePolicy } from './fts-language.ts';
-import { splitEmbeddingSignature, currentSpaceChunkPredicate } from './embedding-invalidation.ts';
+import { splitEmbeddingSignature, currentSpaceChunkPredicate, lockEmbeddingSources } from './embedding-invalidation.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion, chunkWriteInvalidation, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './search/safe-chunks.ts';
import type {
Page, PageInput, PageFilters, PageType,
@@ -2028,6 +2028,12 @@ export class PostgresEngine implements BrainEngine {
params.push(opts.sourceId);
sourceClause = `AND p.source_id = $${params.length}`;
}
+ let generationClause = '';
+ if (resolvedCol.name === 'embedding') {
+ params.push(resolvedCol.embeddingModel || null);
+ generationClause = `AND ((cc.model=$${params.length} AND (cc.embedded_text_hash=md5(cc.chunk_text) OR cc.embedded_text_hash IS NULL))
+ OR ($${params.length}::text IS NULL AND NOT EXISTS(SELECT 1 FROM config WHERE key='embedding_migration.state')))`;
+ }
params.push(innerLimit);
const innerLimitIdx = params.length - 1; // mutated by the escalation loop
const innerLimitParam = `$${params.length}`;
@@ -2069,6 +2075,7 @@ export class PostgresEngine implements BrainEngine {
${afterDateClause}
${beforeDateClause}
${sourceClause}
+ ${generationClause}
${hardExcludeClause}
${visibilityClause}`;
const rawQuery = (exact: boolean) => `
@@ -2548,7 +2555,7 @@ export class PostgresEngine implements BrainEngine {
*/
private buildStaleChunkWhere(staleColRef: string, opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean }): { where: string; params: unknown[] } {
const params: unknown[] = [];
- const conds: string[] = [];
+ const conds: string[] = ['p.deleted_at IS NULL'];
if (opts?.signature !== undefined) {
params.push(opts.signature);
conds.push(
@@ -2632,18 +2639,23 @@ export class PostgresEngine implements BrainEngine {
? `(p.embedding_signature IS NULL OR p.embedding_signature <> $1)`
: `p.embedding_signature IS NOT NULL
AND p.embedding_signature <> $1`;
- const rows = await this.sql.unsafe(
- `UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL
- FROM pages p
- WHERE cc.page_id = p.id
- AND cc.${colId} IS NOT NULL
- AND NOT ${currentSpaceChunkPredicate(colId, 2, 3)}
- AND ${sigClause}${srcClause}
- RETURNING cc.page_id`,
- params as Parameters<typeof this.sql.unsafe>[1],
- );
- return (rows as unknown[]).length;
+ return this.transaction(async tx => {
+ params.push(await lockEmbeddingSources(tx, opts.sourceId));
+ const rows = await tx.executeRaw(
+ `UPDATE content_chunks cc
+ SET ${colId} = NULL, embedded_at = NULL
+ FROM pages p
+ WHERE cc.page_id = p.id
+ AND p.source_id=ANY($${params.length}::text[])
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND cc.${colId} IS NOT NULL
+ AND NOT ${currentSpaceChunkPredicate(colId, 2, 3)}
+ AND ${sigClause}${srcClause}
+ RETURNING cc.page_id`,
+ params,
+ );
+ return (rows as unknown[]).length;
+ });
}
async invalidateContentDriftEmbeddings(opts?: { sourceId?: string }): Promise<number> {
@@ -2663,20 +2675,25 @@ export class PostgresEngine implements BrainEngine {
params.push(opts.sourceId);
srcClause = ` AND p.source_id = $${params.length}`;
}
- const sql = this.sql;
- const rows = await sql.unsafe(
- `UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL, embedded_text_hash = NULL
- FROM pages p
- WHERE cc.page_id = p.id
- AND cc.${colId} IS NOT NULL
- AND cc.embedded_text_hash IS NOT NULL
- AND cc.embedded_text_hash <> md5(cc.chunk_text)
- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')${srcClause}
- RETURNING cc.page_id`,
- params as Parameters<typeof sql.unsafe>[1],
- );
- return (rows as unknown[]).length;
+ return this.transaction(async tx => {
+ params.push(await lockEmbeddingSources(tx, opts?.sourceId));
+ const rows = await tx.executeRaw(
+ `UPDATE content_chunks cc
+ SET ${colId} = NULL, embedded_at = NULL, embedded_text_hash = NULL
+ FROM pages p
+ WHERE cc.page_id = p.id
+ AND p.source_id=ANY($${params.length}::text[])
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
+ AND p.deleted_at IS NULL
+ AND cc.${colId} IS NOT NULL
+ AND cc.embedded_text_hash IS NOT NULL
+ AND cc.embedded_text_hash <> md5(cc.chunk_text)
+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')${srcClause}
+ RETURNING cc.page_id`,
+ params,
+ );
+ return (rows as unknown[]).length;
+ });
}
async listStaleChunks(opts?: {
@@ -2712,7 +2729,7 @@ export class PostgresEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${tx.unsafe(staleColId)} IS NULL
+ WHERE cc.${tx.unsafe(staleColId)} IS NULL AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
LIMIT ${limit}
@@ -2722,7 +2739,7 @@ export class PostgresEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${tx.unsafe(staleColId)} IS NULL
+ WHERE cc.${tx.unsafe(staleColId)} IS NULL AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (
p.updated_at < ${afterUpdated}::timestamptz
@@ -2740,7 +2757,7 @@ export class PostgresEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${tx.unsafe(staleColId)} IS NULL
+ WHERE cc.${tx.unsafe(staleColId)} IS NULL AND p.deleted_at IS NULL
AND p.source_id = ${opts.sourceId}
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC
@@ -2751,7 +2768,7 @@ export class PostgresEngine implements BrainEngine {
p.updated_at
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${tx.unsafe(staleColId)} IS NULL
+ WHERE cc.${tx.unsafe(staleColId)} IS NULL AND p.deleted_at IS NULL
AND p.source_id = ${opts.sourceId}
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (
@@ -2771,7 +2788,7 @@ export class PostgresEngine implements BrainEngine {
cc.model, cc.token_count, p.source_id, cc.page_id
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${tx.unsafe(staleColId)} IS NULL
+ WHERE cc.${tx.unsafe(staleColId)} IS NULL AND p.deleted_at IS NULL
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})
ORDER BY cc.page_id, cc.chunk_index
@@ -2784,7 +2801,7 @@ export class PostgresEngine implements BrainEngine {
cc.model, cc.token_count, p.source_id, cc.page_id
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
- WHERE cc.${tx.unsafe(staleColId)} IS NULL
+ WHERE cc.${tx.unsafe(staleColId)} IS NULL AND p.deleted_at IS NULL
AND p.source_id = ${opts.sourceId}
AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')
AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})
@@ -4441,7 +4458,7 @@ export class PostgresEngine implements BrainEngine {
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
): Promise<FactRow[]> {
return factsImpl.findCandidateDuplicates(this.factsDeps, source_id, entitySlug, factText, opts);
}
@@ -4815,7 +4832,7 @@ export class PostgresEngine implements BrainEngine {
-- cannot move it and 'doctor --remediate' re-plans it every pass.
(SELECT count(*) FROM content_chunks cc
JOIN scoped_pages p ON p.id = cc.page_id
- WHERE cc.${sql.unsafe(colId)} IS NULL
+ WHERE cc.${sql.unsafe(colId)} IS NULL AND p.deleted_at IS NULL
AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
) as missing_embeddings,
(SELECT count(*) FROM links l
diff --git a/src/core/postgres-engine/facts.ts b/src/core/postgres-engine/facts.ts
index b440f46a09..6abab591b5 100644
--- a/src/core/postgres-engine/facts.ts
+++ b/src/core/postgres-engine/facts.ts
@@ -76,12 +76,12 @@ export async function insertFact(
INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
+ embedding, embedded_at, embedding_model, embedded_text_hash,
claim_metric, claim_value, claim_unit, claim_period
) VALUES (
${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
- ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
+ ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt}, ${embedding ? input.embedding_model ?? null : null}, ${embedding && input.embedding_model ? tx`md5(${input.fact})` : null},
${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
) RETURNING id
`;
@@ -103,12 +103,12 @@ export async function insertFact(
INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
- embedding, embedded_at,
+ embedding, embedded_at, embedding_model, embedded_text_hash,
claim_metric, claim_value, claim_unit, claim_period
) VALUES (
${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
- ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
+ ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt}, ${embedding ? input.embedding_model ?? null : null}, ${embedding && input.embedding_model ? tx`md5(${input.fact})` : null},
${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
) RETURNING id
`;
@@ -216,14 +216,14 @@ export async function insertFacts(
INSERT INTO facts (
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, expired_at, source, source_session, confidence,
- embedding, embedded_at,
+ embedding, embedded_at, embedding_model, embedded_text_hash,
row_num, source_markdown_slug,
claim_metric, claim_value, claim_unit, claim_period,
event_type
) VALUES (
${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
${validFrom}, ${validUntil}, ${expiredAt}, ${input.source}, ${sourceSession}, ${confidence},
- ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt},
+ ${embedLit === null ? null : tx.unsafe(`'${embedLit}'${castSuffix}`)}, ${embeddedAt}, ${embedding ? input.embedding_model ?? null : null}, ${embedding && input.embedding_model ? tx`md5(${input.fact})` : null},
${input.row_num}, ${input.source_markdown_slug},
${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
${eventType}
@@ -462,13 +462,14 @@ export async function findCandidateDuplicates(
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
): Promise<FactRow[]> {
const sql = deps.sql;
const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
// Validity-lapsed rows are not dedup candidates: a re-stated fact after
// its valid_until lapses re-inserts fresh (WP5 read-time TTL honesty).
if (opts?.embedding) {
+ if (!opts.embeddingModel) return [];
const lit = toPgVectorLiteral(opts.embedding);
const rows = await sql<FactRowSqlShape[]>`
SELECT * FROM facts
@@ -477,6 +478,9 @@ export async function findCandidateDuplicates(
AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until > now())
AND embedding IS NOT NULL
+ AND embedding_model=${opts.embeddingModel} AND embedded_text_hash=md5(fact)
+ AND vector_dims(embedding)=${opts.embedding.length}
+ AND source != ALL(${AUDIT_ROW_SOURCES}::text[])
ORDER BY embedding <=> ${sql.unsafe(`'${lit}'::vector`)}
LIMIT ${k}
`;
@@ -535,7 +539,8 @@ export async function findTrajectory(deps: PgFactsDeps, opts: import('../engine.
claim_metric, claim_value, claim_unit, claim_period,
event_type,
fact, source_session, source_markdown_slug,
- embedding::text AS embedding
+ CASE WHEN embedding_model=(SELECT value FROM config WHERE key='embedding_model')
+ AND embedded_text_hash=md5(fact) THEN embedding::text END AS embedding
FROM facts
WHERE ${useArray ? sql`source_id = ANY(${sourceIds}::text[])` : sql`source_id = ${sourceId}`}
AND entity_slug = ${opts.entitySlug}
@@ -632,6 +637,8 @@ interface FactRowSqlShape {
source_session: string | null;
confidence: number | string;
embedding: string | number[] | Float32Array | null;
+ embedding_model?: string | null;
+ embedded_text_hash?: string | null;
embedded_at: Date | null;
created_at: Date;
}
@@ -671,6 +678,8 @@ function rowToFactPg(row: FactRowSqlShape): FactRow {
source_session: row.source_session,
confidence: typeof row.confidence === 'string' ? parseFloat(row.confidence) : row.confidence,
embedding,
+ embedding_model: row.embedding_model ?? null,
+ embedded_text_hash: row.embedded_text_hash ?? null,
embedded_at: row.embedded_at,
created_at: row.created_at,
};
diff --git a/src/core/postgres-engine/forward-reference-bootstrap.ts b/src/core/postgres-engine/forward-reference-bootstrap.ts
index 0478be8617..097a179bfa 100644
--- a/src/core/postgres-engine/forward-reference-bootstrap.ts
+++ b/src/core/postgres-engine/forward-reference-bootstrap.ts
@@ -72,6 +72,9 @@ const probeRows = await conn<{
sources_archive_expires_at_exists: boolean;
dream_verdicts_exists: boolean;
dream_verdicts_expires_at_exists: boolean;
+ facts_exists: boolean;
+ facts_embedding_model_exists: boolean;
+ facts_embedded_text_hash_exists: boolean;
}[]>`
SELECT
EXISTS (SELECT 1 FROM information_schema.tables
@@ -184,7 +187,13 @@ const probeRows = await conn<{
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
+ WHERE table_schema = current_schema() AND table_name = 'dream_verdicts' AND column_name = 'expires_at') AS dream_verdicts_expires_at_exists,
+ EXISTS (SELECT 1 FROM information_schema.tables
+ WHERE table_schema = current_schema() AND table_name = 'facts') AS facts_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = 'facts' AND column_name = 'embedding_model') AS facts_embedding_model_exists,
+ EXISTS (SELECT 1 FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = 'facts' AND column_name = 'embedded_text_hash') AS facts_embedded_text_hash_exists
`;
const probe = probeRows[0]!;
@@ -329,6 +338,8 @@ const needsMinionJobsAuthority = probeCr.minion_jobs_exists === true
// as v121/v7; PGLite is unaffected (its blob carries no dream_verdicts).
const needsDreamVerdictsExpiresAt = probe.dream_verdicts_exists
&& !probe.dream_verdicts_expires_at_exists;
+const needsFactEmbeddingIdentity = probe.facts_exists
+ && (!probe.facts_embedding_model_exists || !probe.facts_embedded_text_hash_exists);
if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap
&& !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId
@@ -344,10 +355,17 @@ if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap
&& !needsTimelineEventPageId
&& !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey
&& !needsMinionJobsPrivateQueue && !needsMinionJobsAuthority
- && !needsDreamVerdictsExpiresAt) return;
+ && !needsDreamVerdictsExpiresAt && !needsFactEmbeddingIdentity) return;
process.stderr.write(' Schema forward-reference gap detected, applying bootstrap\n');
+if (needsFactEmbeddingIdentity) {
+ await conn.unsafe(`
+ ALTER TABLE facts ADD COLUMN IF NOT EXISTS embedding_model TEXT;
+ ALTER TABLE facts ADD COLUMN IF NOT EXISTS embedded_text_hash TEXT;
+ `);
+}
+
if (needsPagesBootstrap) {
// Mirror schema-embedded.ts's `sources` shape so the subsequent
// SCHEMA_SQL CREATE TABLE IF NOT EXISTS is a true no-op.
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 4ccbe35f7a..854f022272 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1872,6 +1872,10 @@ BEGIN
END IF;
IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
ELSIF TG_TABLE_NAME IN ('facts','takes') AND TG_OP='UPDATE' THEN
+ IF TG_TABLE_NAME='facts' THEN
+ row_data := row_data - ARRAY['embedding_model','embedded_text_hash'];
+ old_data := old_data - ARRAY['embedding_model','embedded_text_hash'];
+ END IF;
-- Embedding completion and retrieval telemetry are physical projections.
IF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])
= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NEW; END IF;
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 1a55f7146f..6eb83d83d1 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -1137,7 +1137,9 @@ export async function embedQueryBounded(
// deadline was mostly consumed by prior work (codex). Still bounded overall.
const remaining = Math.max(MIN_QUERY_EMBED_BUDGET_MS, dl.deadlineAt - Date.now());
const signal = AbortSignal.timeout(remaining);
- const p = embedQuery(text, { ...(embedOpts ?? {}), abortSignal: signal });
+ const p = embedQuery(text, { ...(embedOpts ?? {}), abortSignal: signal }).catch(error => {
+ throw signal.aborted ? signal.reason : error;
+ });
p.catch(() => { /* swallow the loser's late rejection */ });
let timer: ReturnType<typeof setTimeout> | undefined;
const deadline = new Promise<never>((_, reject) => {
diff --git a/src/core/vector-index.ts b/src/core/vector-index.ts
index f604296c19..cf9cfbb9ec 100644
--- a/src/core/vector-index.ts
+++ b/src/core/vector-index.ts
@@ -34,6 +34,24 @@ export function hnswMaxDimsForType(columnType: 'vector' | 'halfvec'): number {
return columnType === 'halfvec' ? PGVECTOR_HNSW_HALFVEC_MAX_DIMS : PGVECTOR_HNSW_VECTOR_MAX_DIMS;
}
+export async function readExistingEmbeddingShape(
+ engine: BrainEngine, table: 'facts' | 'query_cache',
+): Promise<{ type: 'vector' | 'halfvec'; dimensions: number } | null> {
+ const [column] = await engine.executeRaw<{ type: string | null; dimensions: number | null }>(
+ `SELECT t.typname AS type,a.atttypmod AS dimensions
+ FROM pg_class c
+ LEFT JOIN pg_attribute a ON a.attrelid=c.oid AND a.attname='embedding'
+ AND a.attnum>0 AND NOT a.attisdropped
+ LEFT JOIN pg_type t ON t.oid=a.atttypid
+ WHERE c.oid=to_regclass($1)`, [table]);
+ if (!column) return null;
+ if ((column.type !== 'vector' && column.type !== 'halfvec')
+ || typeof column.dimensions !== 'number' || !Number.isSafeInteger(column.dimensions) || column.dimensions <= 0) {
+ throw new Error(`Cannot replay ${table} migration: existing embedding column must be vector(n) or halfvec(n) with a positive dimension`);
+ }
+ return { type: column.type, dimensions: column.dimensions };
+}
+
/** Whether pgvector can build an HNSW index for this exact column shape. */
export function hnswIndexExpected(columnType: 'vector' | 'halfvec', dims: number): boolean {
return dims <= hnswMaxDimsForType(columnType);
diff --git a/src/mcp/source-preflight.ts b/src/mcp/source-preflight.ts
index f5a12b0a28..b38413b5a9 100644
--- a/src/mcp/source-preflight.ts
+++ b/src/mcp/source-preflight.ts
@@ -17,8 +17,8 @@ import { isEngineDegraded } from '../core/degraded-marker.ts';
* source-resolver.ts, whose `archived = false` predicate this mirrors).
*
* Scope: only the stdio server calls this. HTTP tokens carry their own
- * source grant. `__all__` and malformed values keep their existing handling
- * (malformed already falls back to the seed tier in the resolver).
+ * source grant. `__all__` warns without changing its fail-closed scope;
+ * malformed values still fall back to the seed tier in the resolver.
* A transient engine error does NOT block startup — this guards config, not
* connectivity — and a degraded engine is never touched, so a boot under
* the degraded proxy does not spend its reconnect attempt here.
@@ -28,7 +28,17 @@ export async function assertStdioSourceBindable(
env: string | undefined = process.env.GBRAIN_SOURCE,
): Promise<void> {
if (!env) return;
- if (env === ALL_SOURCES || !isValidSourceId(env)) return;
+ if (env === ALL_SOURCES) {
+ process.stderr.write(
+ '[gbrain] GBRAIN_SOURCE=__all__ does not grant all-source access to stdio MCP; ' +
+ 'this binding remains fail-closed and reads return no results. In the MCP server environment, ' +
+ 'set GBRAIN_SOURCE to a registered source id, or remove it to use normal source resolution ' +
+ '(not unrestricted access), then restart the server. ' +
+ 'See docs/mcp/DEPLOY.md#stdio-source-binding.\n',
+ );
+ return;
+ }
+ if (!isValidSourceId(env)) return;
if (isEngineDegraded(engine)) return;
let rows: Array<{ id: string }>;
try {
diff --git a/src/schema.sql b/src/schema.sql
index 80b9f36f3c..91c65d0281 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1868,6 +1868,10 @@ BEGIN
END IF;
IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
ELSIF TG_TABLE_NAME IN ('facts','takes') AND TG_OP='UPDATE' THEN
+ IF TG_TABLE_NAME='facts' THEN
+ row_data := row_data - ARRAY['embedding_model','embedded_text_hash'];
+ old_data := old_data - ARRAY['embedding_model','embedded_text_hash'];
+ END IF;
-- Embedding completion and retrieval telemetry are physical projections.
IF (row_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at'])
= (old_data - ARRAY['embedding','embedded_at','last_retrieved_at','retrieval_count','updated_at']) THEN RETURN NEW; END IF;
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index d8e1d9b119..8a1c315f67 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.59.8.0 -->
+<!-- gbrain-template-stamp: 0.59.10.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/bootstrap.test.ts b/test/bootstrap.test.ts
index d0f7d69c8d..401ed56be7 100644
--- a/test/bootstrap.test.ts
+++ b/test/bootstrap.test.ts
@@ -22,6 +22,7 @@
import { describe, test, expect } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { readFactsEmbeddingDim } from '../src/core/embedding-dim-check.ts';
// Tier 3 opt-out: this file tests the cold init / bootstrap path explicitly.
// If GBRAIN_PGLITE_SNAPSHOT is set (ci:local sets it for unit shards), every
@@ -31,6 +32,44 @@ import { LATEST_VERSION } from '../src/core/migrate.ts';
delete process.env.GBRAIN_PGLITE_SNAPSHOT;
describe('PGLiteEngine#applyForwardReferenceBootstrap', () => {
+ test('fact embedding identity bootstrap repairs old and partial schemas without inventing provenance', async () => {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ try {
+ await engine.initSchema();
+ const { dims } = await readFactsEmbeddingDim(engine);
+ const fact = await engine.insertFact({ fact: 'Synthetic bootstrap claim', source: 'synthetic', embedding: new Float32Array(dims!).fill(0.1) }, { source_id: 'default' });
+ const original = await engine.executeRaw('SELECT id,fact,embedding::text,embedded_at FROM facts WHERE id=$1', [fact.id]);
+ expect(original[0].embedding).not.toBeNull();
+ for (const missing of [['embedding_model', 'embedded_text_hash'], ['embedding_model'], ['embedded_text_hash']]) {
+ await engine.executeRaw("UPDATE facts SET embedding_model='synthetic:original',embedded_text_hash='synthetic-preserved-hash' WHERE id=$1", [fact.id]);
+ for (const column of missing) await engine.executeRaw(`ALTER TABLE facts DROP COLUMN ${column}`);
+ await engine.setConfig('version', '165');
+ await (engine as any).applyForwardReferenceBootstrap();
+ await (engine as any).applyForwardReferenceBootstrap();
+ expect(await engine.getConfig('version')).toBe('165');
+ expect(await engine.executeRaw(`SELECT column_name,data_type,is_nullable,column_default FROM information_schema.columns
+ WHERE table_schema='public' AND table_name='facts' AND column_name IN ('embedding_model','embedded_text_hash') ORDER BY column_name`)).toEqual([
+ { column_name: 'embedded_text_hash', data_type: 'text', is_nullable: 'YES', column_default: null },
+ { column_name: 'embedding_model', data_type: 'text', is_nullable: 'YES', column_default: null },
+ ]);
+ const identity = [{
+ embedding_model: missing.includes('embedding_model') ? null : 'synthetic:original',
+ embedded_text_hash: missing.includes('embedded_text_hash') ? null : 'synthetic-preserved-hash',
+ }];
+ expect(await engine.executeRaw('SELECT embedding_model,embedded_text_hash FROM facts WHERE id=$1', [fact.id])).toEqual(identity);
+ for (const column of missing) await engine.executeRaw(`ALTER TABLE facts DROP COLUMN ${column}`);
+ await engine.initSchema();
+ await engine.initSchema();
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+ expect(await engine.executeRaw('SELECT embedding_model,embedded_text_hash FROM facts WHERE id=$1', [fact.id])).toEqual(identity);
+ expect(await engine.executeRaw('SELECT id,fact,embedding::text,embedded_at FROM facts WHERE id=$1', [fact.id])).toEqual(original);
+ }
+ } finally {
+ await engine.disconnect();
+ }
+ }, 60_000);
+
test('queue bootstrap preserves legacy jobs without authorizing them and repairs either missing column', async () => {
const engine = new PGLiteEngine();
await engine.connect({});
diff --git a/test/consolidate-valid-until.test.ts b/test/consolidate-valid-until.test.ts
index fcf4ec01d2..06744beb5e 100644
--- a/test/consolidate-valid-until.test.ts
+++ b/test/consolidate-valid-until.test.ts
@@ -81,8 +81,8 @@ async function insertFact(args: {
confidence?: number;
}): Promise<number> {
const r = await engine.executeRaw<{ id: number }>(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, confidence, embedding, embedded_at)
- VALUES ('default', $1, $2, 'fact', 'test', $3::timestamptz, $4, $5::vector, $3::timestamptz)
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, confidence, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', $1, $2, 'fact', 'test', $3::timestamptz, $4, $5::vector, $3::timestamptz, 'openai:text-embedding-3-large', md5($2))
RETURNING id`,
[args.entity_slug, args.text, args.valid_from.toISOString(), args.confidence ?? 0.9, unitVec()],
);
diff --git a/test/cycle-consolidate.test.ts b/test/cycle-consolidate.test.ts
index b04682c652..e254304ea2 100644
--- a/test/cycle-consolidate.test.ts
+++ b/test/cycle-consolidate.test.ts
@@ -70,8 +70,8 @@ describe('runPhaseConsolidate', () => {
await seedPage('cons-skip-count');
for (let i = 0; i < 2; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at)
- VALUES ('default', 'cons-skip-count', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'cons-skip-count', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`fact ${i}`, oldDate(), unitVec()],
);
}
@@ -84,8 +84,8 @@ describe('runPhaseConsolidate', () => {
await seedPage('cons-skip-age');
for (let i = 0; i < 4; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at)
- VALUES ('default', 'cons-skip-age', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'cons-skip-age', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`fact ${i}`, recentDate(), unitVec()],
);
}
@@ -99,8 +99,8 @@ describe('runPhaseConsolidate', () => {
expect(pageId).toBeGreaterThan(0);
for (let i = 0; i < 4; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, confidence, embedding, embedded_at)
- VALUES ('default', 'people/alice-example', $1, 'fact', 'test', $2::timestamptz, 0.9, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, confidence, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'people/alice-example', $1, 'fact', 'test', $2::timestamptz, 0.9, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`alice fact ${i}`, oldDate(), unitVec()],
);
}
@@ -133,8 +133,8 @@ describe('runPhaseConsolidate', () => {
await seedPage('cons-dryrun');
for (let i = 0; i < 3; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at)
- VALUES ('default', 'cons-dryrun', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'cons-dryrun', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`dryrun fact ${i}`, oldDate(), unitVec()],
);
}
@@ -156,8 +156,8 @@ describe('runPhaseConsolidate', () => {
// Don't seed a page — entity_slug 'no-page' won't resolve.
for (let i = 0; i < 4; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at)
- VALUES ('default', 'no-page', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'no-page', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`orphan fact ${i}`, oldDate(), unitVec()],
);
}
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index 6202aaf5b3..6f556b59c3 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -15,6 +15,20 @@ import { doctorSource, doctorFileSource } from './helpers/doctor-source.ts';
afterEach(() => resetGateway());
describe('doctor command', () => {
+ test('dimension recovery previews existing brains without recommending reinitialization', () => {
+ const source = doctorFileSource('doctor.ts');
+ const start = source.indexOf('if (totalChunks > 0)');
+ const end = source.indexOf('surfacedUnconfiguredDrift = true;', start);
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ const hint = source.slice(start, end);
+ expect(hint).toContain('--dry-run');
+ expect(hint).toContain('--yes --max-cost-usd <approved-total>');
+ expect(hint).toContain('docs/guides/embedding-migration.md#recovery');
+ expect(hint).not.toContain('init --force');
+ expect(source).not.toContain('manual ALTER recipe');
+ });
+
test('doctor module exports runDoctor', async () => {
const { runDoctor } = await import('../src/commands/doctor.ts');
expect(typeof runDoctor).toBe('function');
diff --git a/test/e2e/cycle-consolidate-postgres.test.ts b/test/e2e/cycle-consolidate-postgres.test.ts
index 1dcaeef389..99f2ccc74c 100644
--- a/test/e2e/cycle-consolidate-postgres.test.ts
+++ b/test/e2e/cycle-consolidate-postgres.test.ts
@@ -11,6 +11,7 @@
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { createHash } from 'node:crypto';
import { setupLegacyEmbeddingDB, teardownDB, hasDatabase, getEngine } from './helpers.ts';
import { runPhaseConsolidate } from '../../src/core/cycle/phases/consolidate.ts';
@@ -41,8 +42,8 @@ d('cycle consolidate phase (Postgres)', () => {
for (let i = 0; i < 4; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, confidence, valid_from, embedding, embedded_at)
- VALUES ('default', 'people/post-cons-alice', $1, 'fact', 'test', 0.9, $2::timestamptz, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, confidence, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'people/post-cons-alice', $1, 'fact', 'test', 0.9, $2::timestamptz, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`postgres consolidate fact ${i}`, oldDate(), unitVec()],
);
}
@@ -64,14 +65,17 @@ d('cycle consolidate phase (Postgres)', () => {
// All 4 facts marked consolidated, NEVER deleted.
const facts = await engine.executeRaw<{
id: number; consolidated_at: Date | null; consolidated_into: number | null;
+ fact: string; embedding_model: string; embedded_text_hash: string;
}>(
- `SELECT id, consolidated_at, consolidated_into FROM facts
+ `SELECT id, consolidated_at, consolidated_into, fact, embedding_model, embedded_text_hash FROM facts
WHERE entity_slug = 'people/post-cons-alice' ORDER BY id`,
);
expect(facts.length).toBe(4);
for (const f of facts) {
expect(f.consolidated_at).not.toBeNull();
expect(f.consolidated_into).not.toBeNull();
+ expect(f.embedding_model).toBe('openai:text-embedding-3-large');
+ expect(f.embedded_text_hash).toBe(createHash('md5').update(f.fact).digest('hex'));
}
});
@@ -83,8 +87,8 @@ d('cycle consolidate phase (Postgres)', () => {
const recent = new Date(Date.now() - 60 * 1000).toISOString();
for (let i = 0; i < 4; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at)
- VALUES ('default', 'cons-recent', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'cons-recent', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`recent fact ${i}`, recent, unitVec()],
);
}
@@ -104,8 +108,8 @@ d('cycle consolidate phase (Postgres)', () => {
);
for (let i = 0; i < 3; i++) {
await engine.executeRaw(
- `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at)
- VALUES ('default', 'cons-dryrun-pg', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz)`,
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash)
+ VALUES ('default', 'cons-dryrun-pg', $1, 'fact', 'test', $2::timestamptz, $3::vector, $2::timestamptz, 'openai:text-embedding-3-large', md5($1))`,
[`dryrun fact ${i}`, oldDate(), unitVec()],
);
}
diff --git a/test/e2e/embedding-recovery-parity.test.ts b/test/e2e/embedding-recovery-parity.test.ts
new file mode 100644
index 0000000000..1ee42a6b85
--- /dev/null
+++ b/test/e2e/embedding-recovery-parity.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../embedding-recovery.serial.test.ts'));
diff --git a/test/e2e/engine-parity.test.ts b/test/e2e/engine-parity.test.ts
index deb87d0f51..440a0a8d12 100644
--- a/test/e2e/engine-parity.test.ts
+++ b/test/e2e/engine-parity.test.ts
@@ -14,6 +14,7 @@
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { createHash } from 'node:crypto';
import { installFixtureChunks } from '../helpers/page-projection.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
@@ -2405,14 +2406,21 @@ describeBoth('Engine parity — facts TTL read-time validity (WP5)', () => {
);
// Embedding-branch pair (separate entity keeps the recency-branch counts clean).
const emb = basisEmbedding(101);
+ const embeddingModel = 'test:ttl-validity';
await eng.insertFact(
- { fact: 'ttl embed lapsed', kind: 'fact', entity_slug: EMB_ENTITY, source: 'test', valid_until: past, embedding: emb },
+ { fact: 'ttl embed lapsed', kind: 'fact', entity_slug: EMB_ENTITY, source: 'test', valid_until: past, embedding: emb, embedding_model: embeddingModel },
{ source_id: SRC },
);
await eng.insertFact(
- { fact: 'ttl embed live', kind: 'fact', entity_slug: EMB_ENTITY, source: 'test', embedding: emb },
+ { fact: 'ttl embed live', kind: 'fact', entity_slug: EMB_ENTITY, source: 'test', embedding: emb, embedding_model: embeddingModel },
{ source_id: SRC },
);
+ const stored = await eng.listFactsByEntity(SRC, EMB_ENTITY, { activeOnly: false });
+ expect(stored).toHaveLength(2);
+ for (const row of stored) {
+ expect(row.embedding_model).toBe(embeddingModel);
+ expect(row.embedded_text_hash).toBe(createHash('md5').update(row.fact).digest('hex'));
+ }
// Ontology-writer-style supersession: valid_until close + superseded_by,
// expired_at stays NULL (--asof time-travel intact).
const oldRow = await eng.insertFact(
@@ -2435,7 +2443,7 @@ describeBoth('Engine parity — facts TTL read-time validity (WP5)', () => {
bySince: texts(await eng.listFactsSince(SRC, since, { entitySlug: ENTITY })),
bySession: texts(await eng.listFactsBySession(SRC, SESSION)),
dupRecency: texts(await eng.findCandidateDuplicates(SRC, ENTITY, 'ttl lapsed fact')),
- dupEmbedding: texts(await eng.findCandidateDuplicates(SRC, EMB_ENTITY, 'ttl embed lapsed', { embedding: emb })),
+ dupEmbedding: texts(await eng.findCandidateDuplicates(SRC, EMB_ENTITY, 'ttl embed lapsed', { embedding: emb, embeddingModel })),
history: texts(await eng.listFactsByEntity(SRC, ENTITY, { activeOnly: false })),
supersessions: texts(await eng.listSupersessions(SRC)),
health: {
diff --git a/test/e2e/export-snapshot-postgres.test.ts b/test/e2e/export-snapshot-postgres.test.ts
new file mode 100644
index 0000000000..e733d91232
--- /dev/null
+++ b/test/e2e/export-snapshot-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../export-snapshot.test.ts'), () => import('../export-safety.test.ts'));
diff --git a/test/e2e/fact-backfill-resident.test.ts b/test/e2e/fact-backfill-resident.test.ts
index ee40584f8a..6600e97f13 100644
--- a/test/e2e/fact-backfill-resident.test.ts
+++ b/test/e2e/fact-backfill-resident.test.ts
@@ -1,4 +1,5 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
import { once } from 'node:events';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -98,14 +99,34 @@ describe('resident managed fact-vector repair', () => {
}));
test('authenticated preview and bounded execution work without canonical mutations', () => inHome(async () => {
- const canonical = async () => Array.from(await engine.executeRaw("SELECT to_jsonb(f)-ARRAY['embedding','embedded_at'] AS row FROM facts f ORDER BY id"));
+ const canonical = async () => Array.from(await engine.executeRaw("SELECT to_jsonb(f)-ARRAY['embedding','embedded_at','embedding_model','embedded_text_hash'] AS row FROM facts f ORDER BY id"));
const before = await canonical();
+ const metadata = () => engine.executeRaw<{
+ source_id: string; fact: string; embedding_model: string | null;
+ embedded_text_hash: string | null; embedded_at: Date | null; has_embedding: boolean;
+ }>('SELECT source_id, fact, embedding_model, embedded_text_hash, embedded_at, embedding IS NOT NULL AS has_embedding FROM facts ORDER BY id');
+ for (const row of await metadata()) {
+ expect(row).toMatchObject({ embedding_model: null, embedded_text_hash: null, embedded_at: null, has_embedding: false });
+ }
expect(await request({ sourceId })).toMatchObject({ dryRun: true, would_embed: 2, embedded: 0 });
expect(calls).toBe(0);
expect(await request({ sourceId, yes: true, maxCostUsd: 1, maxFacts: 1 })).toMatchObject({ embedded: 1, remaining: 1, failures: 0 });
expect(await request({ sourceId, yes: true, maxCostUsd: 1 })).toMatchObject({ embedded: 1, remaining: 0, failures: 0 });
expect(await request({ sourceId, yes: true, maxCostUsd: 1 })).toMatchObject({ embedded: 0, remaining: 0, failures: 0 });
expect(await canonical()).toEqual(before);
+ const repaired = await metadata();
+ expect(repaired.filter(row => row.source_id === sourceId)).toHaveLength(2);
+ expect(repaired.filter(row => row.source_id === foreignSource)).toHaveLength(1);
+ for (const row of repaired) {
+ if (row.source_id === sourceId) {
+ expect(row.embedding_model).toBe('openai:text-embedding-3-small');
+ expect(row.embedded_text_hash).toBe(createHash('md5').update(row.fact).digest('hex'));
+ expect(row.embedded_at).not.toBeNull();
+ expect(row.has_embedding).toBe(true);
+ } else {
+ expect(row).toMatchObject({ embedding_model: null, embedded_text_hash: null, embedded_at: null, has_embedding: false });
+ }
+ }
expect(await countEmbedded()).toBe(2);
expect(calls).toBe(2);
await expect(engine.executeRaw("UPDATE facts SET visibility='world' WHERE source_id=$1", [sourceId])).rejects.toThrow('writer_coordinator_required');
diff --git a/test/e2e/fact-embedding-backfill-parity.test.ts b/test/e2e/fact-embedding-backfill-parity.test.ts
index 1b80ac0fa9..c8b6411ec8 100644
--- a/test/e2e/fact-embedding-backfill-parity.test.ts
+++ b/test/e2e/fact-embedding-backfill-parity.test.ts
@@ -80,7 +80,7 @@ for (const kind of ['pglite', 'postgres'] as const) {
await seed('pending');
await seed('private pending', { visibility: 'private' });
await seed('expired', { expired_at: new Date('2020-01-01') });
- await seed('already embedded', { embedding: new Float32Array(1536).fill(0.5) });
+ await seed('already embedded', { embedding: new Float32Array(1536).fill(0.5), embedding_model: 'openai:text-embedding-3-small' });
await seed('audit', { source: AUDIT_ROW_SOURCES[0] });
await seed('neighbor pending', {}, neighbor);
const before = await state();
@@ -222,7 +222,7 @@ for (const kind of ['pglite', 'postgres'] as const) {
test('managed repair updates only physical vectors and preserves canonical rows and guards', async () => {
await seed('private pending', { visibility: 'private' });
await seed('neighbor pending', {}, neighbor);
- const canonical = async () => Array.from(await engine.executeRaw(`SELECT to_jsonb(f)-ARRAY['embedding','embedded_at'] AS row
+ const canonical = async () => Array.from(await engine.executeRaw(`SELECT to_jsonb(f)-ARRAY['embedding','embedded_at','embedding_model','embedded_text_hash'] AS row
FROM facts f WHERE source_id=ANY($1::text[]) ORDER BY id`, [[sourceId, neighbor]]));
const before = await canonical();
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
diff --git a/test/e2e/google-attachments-postgres.test.ts b/test/e2e/google-attachments-postgres.test.ts
new file mode 100644
index 0000000000..64741345dd
--- /dev/null
+++ b/test/e2e/google-attachments-postgres.test.ts
@@ -0,0 +1,8 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(
+ () => import('../google-attachment-sync.test.ts'),
+ () => import('../google-attachment-backfill.test.ts'),
+ () => import('../google-attachment-recovery.test.ts'),
+ () => import('../google-attachments-command.serial.test.ts'),
+);
diff --git a/test/e2e/legacy-fact-extraction-dedup-postgres.test.ts b/test/e2e/legacy-fact-extraction-dedup-postgres.test.ts
new file mode 100644
index 0000000000..629ac5a4d7
--- /dev/null
+++ b/test/e2e/legacy-fact-extraction-dedup-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../legacy-fact-extraction-dedup.test.ts'));
diff --git a/test/e2e/legacy-vector-compatibility-postgres.test.ts b/test/e2e/legacy-vector-compatibility-postgres.test.ts
new file mode 100644
index 0000000000..1ed1e1beed
--- /dev/null
+++ b/test/e2e/legacy-vector-compatibility-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../legacy-vector-compatibility.test.ts'));
diff --git a/test/e2e/mcp-search-transport-matrix.test.ts b/test/e2e/mcp-search-transport-matrix.test.ts
new file mode 100644
index 0000000000..acf479b4eb
--- /dev/null
+++ b/test/e2e/mcp-search-transport-matrix.test.ts
@@ -0,0 +1,406 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash, randomBytes } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { createConnection, createServer, type Socket } from 'node:net';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { keylessBrainEnv } from '../helpers/provider-env.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { createManagedFixtureSource, withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';
+import { cliDiagnostic, fixtureDiagnostic, toolDiagnostic } from '../helpers/fixture-diagnostics.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const VISIBLE = 'quartzvisible';
+const PRIVATE = 'cobaltprivate';
+const FOREIGN = 'amberforeign';
+const BOUND = 'matrix-bound';
+const FEDERATED = 'matrix-federated';
+const PRIVATE_SOURCE = 'matrix-private';
+const backends = process.env.DATABASE_URL ? ['postgres', 'pglite'] as const : ['pglite'] as const;
+
+async function unusedPort(): Promise<number> {
+ const server = createServer();
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ const port = (server.address() as { port: number }).port;
+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
+ return port;
+}
+
+async function stop(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) return;
+ await new Promise<void>(resolve => {
+ const deadline = setTimeout(() => child.kill('SIGKILL'), 5_000);
+ child.once('exit', () => { clearTimeout(deadline); resolve(); });
+ child.kill('SIGTERM');
+ });
+}
+
+async function search(client: Client, query: string, source_id?: string) {
+ const result = await client.callTool({ name: 'search', arguments: { query, ...(source_id ? { source_id } : {}) } });
+ expect(result.isError, toolDiagnostic('search', result)).not.toBe(true);
+ const content = result.content as Array<{ type: string; text: string }>;
+ const rows = JSON.parse(content[0]!.text) as Array<{ slug: string; source_id: string; cosine?: number }>;
+ const meta = result._meta?.retrieval as { returned_count: number; vector_enabled?: boolean; degraded?: Array<{ stage: string; reason?: string }>; projection_readiness: { status: string } };
+ expect(meta).toBeDefined();
+ expect(JSON.stringify(result)).not.toContain(PRIVATE);
+ return { result, rows, meta, content };
+}
+
+for (const backend of backends) describe(`search transport safety matrix (${backend})`, () => {
+ let home: string;
+ let env: Record<string, string>;
+ let engine: BrainEngine;
+ let config: GBrainConfig;
+ let cleanupPostgres: (() => Promise<void>) | undefined;
+ let provider: ReturnType<typeof Bun.serve>;
+ let providerState: 'healthy' | 'timeout' | 'failure' = 'healthy';
+ let embeddingCalls = 0;
+ const token = `gbrain_${randomBytes(32).toString('hex')}`;
+
+ async function cli(args: string[]) {
+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', ...args], {
+ cwd: process.cwd(), env, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([
+ new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited,
+ ]);
+ expect(exitCode, cliDiagnostic(args[0]!, { stdout, stderr, exitCode }, [token])).toBe(0);
+ return stdout;
+ }
+
+ async function withStdio(binding: string | undefined, run: (client: Client, stderr: () => string) => Promise<void>) {
+ const childEnv = { ...env };
+ if (binding === undefined) delete childEnv.GBRAIN_SOURCE;
+ else childEnv.GBRAIN_SOURCE = binding;
+ const transport = new StdioClientTransport({
+ command: 'bun', args: ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--surface', 'starter'],
+ cwd: process.cwd(), env: childEnv, stderr: 'pipe',
+ });
+ let stderr = '';
+ transport.stderr?.on('data', data => { stderr += String(data); });
+ const client = new Client({ name: 'search-matrix', version: '1' });
+ try {
+ await client.connect(transport);
+ await run(client, () => stderr);
+ } catch (error) {
+ console.error(fixtureDiagnostic('stdio fixture', stderr, [token]));
+ throw error;
+ } finally {
+ await client.close();
+ await transport.close();
+ }
+ }
+
+ async function withHttp(run: (client: Client) => Promise<void>) {
+ const port = await unusedPort();
+ const base = `http://127.0.0.1:${port}`;
+ const child = spawn('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--surface', 'starter',
+ '--bind', '127.0.0.1', '--port', String(port), '--public-url', base, '--suppress-bootstrap-token'],
+ { cwd: process.cwd(), env, stdio: ['ignore', 'ignore', 'pipe'] });
+ let stderr = '';
+ child.stderr?.on('data', data => { stderr = (stderr + String(data)).slice(-6000); });
+ const client = new Client({ name: 'search-matrix-http', version: '1' });
+ try {
+ let ready = false;
+ for (let i = 0; i < 120; i++) {
+ try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(500) })).ok; } catch {}
+ if (ready || child.exitCode !== null) break;
+ await Bun.sleep(250);
+ }
+ expect(ready, fixtureDiagnostic('HTTP startup', stderr, [token])).toBe(true);
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${base}/mcp`), {
+ requestInit: { headers: { Authorization: `Bearer ${token}` } },
+ }));
+ await run(client);
+ } catch (error) {
+ console.error(fixtureDiagnostic('HTTP fixture', stderr, [token]));
+ throw error;
+ } finally {
+ await client.close();
+ await stop(child);
+ }
+ }
+
+ async function mutate(run: () => Promise<void>) {
+ await engine.connect(config);
+ try { await run(); } finally { await engine.disconnect(); }
+ }
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-search-matrix-'));
+ provider = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request) {
+ if (request.method === 'GET') return Response.json({ data: [{ id: 'text-embedding-3-small' }] });
+ embeddingCalls++;
+ const body = await request.json() as { input: string | string[] };
+ const state = providerState;
+ if (state === 'timeout') await Bun.sleep(9_000);
+ if (state === 'failure') return Response.json({ error: { message: 'synthetic refusal' } }, { status: 400 });
+ const input = Array.isArray(body.input) ? body.input : [body.input];
+ return Response.json({ object: 'list', model: 'text-embedding-3-small', data: input.map((text, index) => {
+ const embedding = Array(1536).fill(0);
+ embedding[text.includes(VISIBLE) ? 0 : text.includes(PRIVATE) ? 1 : text.includes(FOREIGN) ? 2 : 3] = 1;
+ return { object: 'embedding', index, embedding };
+ }), usage: { prompt_tokens: 1, total_tokens: 1 } });
+ } });
+ env = keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_ENGINE: undefined,
+ GBRAIN_SOURCE: BOUND, GBRAIN_SCHEMA_PACK: 'gbrain-base-v2', GBRAIN_SWEEP: '0',
+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_RETRY_CONNECT: '1',
+ OPENAI_API_KEY: 'synthetic-fixture', OPENAI_BASE_URL: `http://127.0.0.1:${provider.port}/v1`,
+ });
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env });
+ if (backend === 'postgres') {
+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = isolated.engine;
+ cleanupPostgres = isolated.close;
+ config = { engine: 'postgres', database_url: isolated.databaseUrl };
+ } else {
+ config = { engine: 'pglite', database_path: join(home, 'db') };
+ engine = new PGLiteEngine();
+ await engine.connect(config);
+ await engine.initSchema();
+ }
+ config = { ...config, embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 };
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify(config));
+ await createManagedFixtureSource(engine, BOUND, { federated: false });
+ await createManagedFixtureSource(engine, FEDERATED, { federated: true });
+ await createManagedFixtureSource(engine, PRIVATE_SOURCE, { federated: false });
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const [slug, word, source, visibility] of [
+ ['notes/visible', VISIBLE, BOUND, 'world'], ['notes/private', PRIVATE, BOUND, 'private'],
+ ['notes/foreign', FOREIGN, FEDERATED, 'world'], ['notes/private', PRIVATE, PRIVATE_SOURCE, 'private'],
+ ]) {
+ await importFromContent(engine, slug!, `---\ntitle: ${word}\ntype: note\nvisibility: ${visibility}\n---\n\n${word} synthetic transport fixture.`, {
+ sourceId: source!, noEmbed: false,
+ prepare: async prepared => {
+ await withManagedFixtureWrite(engine, [source!], tx => prepared.apply(tx));
+ return prepared.result;
+ },
+ });
+ }
+ });
+ await engine.executeRaw(`INSERT INTO access_tokens (name, token_hash, permissions, scopes) VALUES ($1, $2, $3::text::jsonb, $4::text[])`,
+ ['matrix-read', createHash('sha256').update(token).digest('hex'), JSON.stringify({ source_id: BOUND, takes_holders: ['world'] }), ['read']]);
+ const rows = await engine.executeRaw<{ ready: boolean; chunker_version: number }>(
+ 'SELECT knowledge_revision = text_projection_revision AS ready, chunker_version FROM pages');
+ expect(rows).toHaveLength(4);
+ expect(rows.every(row => row.ready && row.chunker_version >= 4)).toBe(true);
+ await engine.disconnect();
+ }, 120_000);
+
+ afterAll(async () => {
+ await engine?.disconnect();
+ await cleanupPostgres?.();
+ provider?.stop(true);
+ resetGateway();
+ if (home) rmSync(home, { recursive: true, force: true });
+ });
+
+ test('CLI and both authorized transports retrieve the same visible indexed hit without exposing private pages', async () => {
+ const rows = JSON.parse(await cli(['search', VISIBLE, '--json']));
+ expect(rows.some((row: { slug: string }) => row.slug === 'notes/visible')).toBe(true);
+ expect(await cli(['search', PRIVATE, '--json'])).toContain(PRIVATE);
+ const verify = async (client: Client) => {
+ const before = embeddingCalls;
+ const hit = await search(client, VISIBLE);
+ expect(hit.rows.map(row => row.slug)).toContain('notes/visible');
+ expect(hit.rows.every(row => row.source_id === BOUND)).toBe(true);
+ expect(hit.rows.find(row => row.slug === 'notes/visible')?.cosine).toBe(1);
+ expect(hit.meta.vector_enabled).toBe(true);
+ expect(hit.meta.projection_readiness.status).toBe('ready');
+ expect(embeddingCalls).toBeGreaterThan(before);
+ await search(client, PRIVATE);
+ expect((await search(client, VISIBLE, BOUND)).rows.map(row => row.slug)).toContain('notes/visible');
+ expect((await search(client, VISIBLE, '__all__')).rows.every(row => row.source_id === BOUND)).toBe(true);
+ const denied = await client.callTool({ name: 'search', arguments: { query: FOREIGN, source_id: FEDERATED } });
+ expect(denied.isError).toBe(true);
+ expect(JSON.stringify(denied)).toContain('permission_denied');
+ expect(JSON.stringify(denied)).not.toContain(FOREIGN);
+ };
+ await withStdio(BOUND, verify);
+ await withHttp(verify);
+ }, 90_000);
+
+ test('unbound stdio reads federated sources, while a private-only bound source remains a clean miss', async () => {
+ await withStdio(undefined, async client => {
+ const hit = await search(client, FOREIGN);
+ expect(hit.rows.map(row => row.source_id)).toContain(FEDERATED);
+ expect(hit.rows.map(row => row.source_id)).not.toContain(BOUND);
+ });
+ await withStdio(PRIVATE_SOURCE, async client => {
+ const miss = await search(client, PRIVATE);
+ expect(miss.rows).toEqual([]);
+ expect(miss.meta.degraded).toEqual([]);
+ expect(miss.content[1]!.text).toContain('clean miss');
+ });
+ }, 60_000);
+
+ test('an inherited __all__ binding warns once without widening its fail-closed scope', async () => {
+ await withStdio('__all__', async (client, stderr) => {
+ expect((await search(client, VISIBLE)).rows).toEqual([]);
+ expect((await search(client, FOREIGN, '__all__')).rows).toEqual([]);
+ const denied = await client.callTool({ name: 'search', arguments: { query: VISIBLE, source_id: BOUND } });
+ expect(denied.isError).toBe(true);
+ expect(stderr().match(/GBRAIN_SOURCE=__all__ does not grant all-source access to stdio MCP/g)).toHaveLength(1);
+ expect(stderr()).toContain('set GBRAIN_SOURCE to a registered source id');
+ expect(stderr()).not.toContain(PRIVATE);
+ });
+ }, 30_000);
+
+ test('provider timeout and refusal are distinguished and vectors recover in the same stdio and HTTP process', async () => {
+ const verify = async (client: Client) => {
+ try {
+ providerState = 'timeout';
+ const degraded = await search(client, `${VISIBLE} timeout`);
+ expect(degraded.meta.vector_enabled).toBe(false);
+ expect(degraded.meta.degraded).toContainEqual({ stage: 'embed_timeout', reason: 'timeout' });
+ providerState = 'healthy';
+ const recovered = await search(client, `${VISIBLE} recovered`);
+ expect(recovered.meta.vector_enabled).toBe(true);
+ expect(recovered.meta.degraded?.some(item => item.stage === 'embed_timeout')).toBe(false);
+ expect(recovered.rows.map(row => row.slug)).toContain('notes/visible');
+ providerState = 'failure';
+ const unavailable = await search(client, `${VISIBLE} unavailable`);
+ expect(unavailable.meta.vector_enabled).toBe(false);
+ expect(unavailable.meta.degraded).toContainEqual({ stage: 'embed_unavailable', reason: 'provider_error' });
+ providerState = 'healthy';
+ const retry = await search(client, `${VISIBLE} retry`);
+ expect(retry.meta.vector_enabled).toBe(true);
+ expect(retry.rows.map(row => row.slug)).toContain('notes/visible');
+ } finally { providerState = 'healthy'; }
+ };
+ await withStdio(BOUND, verify);
+ await withHttp(verify);
+ }, 60_000);
+
+ if (backend === 'postgres') test('stdio reconnects in place after a DB outage; HTTP fails startup loudly and recovers after restart', async () => {
+ const port = await unusedPort();
+ const actual = new URL(config.database_url!);
+ const unavailable = new URL(actual);
+ unavailable.hostname = '127.0.0.1';
+ unavailable.port = String(port);
+ const sockets = new Set<Socket>();
+ const proxy = createServer(socket => {
+ const upstream = createConnection({ host: actual.hostname, port: Number(actual.port || 5432) });
+ for (const connection of [socket, upstream]) {
+ sockets.add(connection);
+ connection.on('close', () => sockets.delete(connection));
+ connection.on('error', () => { socket.destroy(); upstream.destroy(); });
+ }
+ socket.pipe(upstream).pipe(socket);
+ });
+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify({ ...config, database_url: unavailable.toString() }));
+ try {
+ await withStdio(BOUND, async (client, stderr) => {
+ const failed = await client.callTool({ name: 'search', arguments: { query: VISIBLE } });
+ expect(failed.isError).toBe(true);
+ expect(JSON.stringify(failed)).toContain('database_error');
+ expect(JSON.stringify(failed)).toContain('GBRAIN_DB_ACCESS conn_refused');
+ expect(stderr()).toContain('DEGRADED: database unreachable at startup');
+ await new Promise<void>(resolve => proxy.listen(port, '127.0.0.1', resolve));
+ let recovered = false;
+ for (let i = 0; i < 12; i++) {
+ await Bun.sleep(1_000);
+ const response = await client.callTool({ name: 'search', arguments: { query: VISIBLE } });
+ if (response.isError) continue;
+ recovered = true;
+ break;
+ }
+ expect(recovered).toBe(true);
+ const result = await search(client, VISIBLE);
+ expect(result.meta.vector_enabled).toBe(true);
+ expect(result.meta.degraded?.some(item => item.stage === 'embed_timeout')).toBe(false);
+ expect(result.rows.map(row => row.slug)).toContain('notes/visible');
+ expect(result.rows.every(row => row.source_id === BOUND)).toBe(true);
+ expect(stderr()).toContain('RECOVERED: database reachable');
+ });
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>(resolve => proxy.close(() => resolve()));
+ const httpPort = await unusedPort();
+ const failedHttp = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--bind', '127.0.0.1',
+ '--port', String(httpPort), '--public-url', `http://127.0.0.1:${httpPort}`, '--suppress-bootstrap-token'],
+ { cwd: process.cwd(), env, stdout: 'pipe', stderr: 'pipe' });
+ const deadline = setTimeout(() => failedHttp.kill(), 15_000);
+ try {
+ const [exitCode, stderr] = await Promise.all([failedHttp.exited, new Response(failedHttp.stderr).text()]);
+ expect(exitCode, fixtureDiagnostic('HTTP unavailable startup', stderr, [token])).toBe(1);
+ expect(stderr).toContain('GBRAIN_DB_ACCESS conn_refused');
+ } finally {
+ clearTimeout(deadline);
+ failedHttp.kill();
+ }
+ await new Promise<void>(resolve => proxy.listen(port, '127.0.0.1', resolve));
+ await withHttp(async client => {
+ const result = await search(client, VISIBLE);
+ expect(result.meta.vector_enabled).toBe(true);
+ expect(result.rows.map(row => row.slug)).toContain('notes/visible');
+ expect(result.rows.every(row => row.source_id === BOUND)).toBe(true);
+ });
+ } finally {
+ writeFileSync(join(home, '.gbrain/config.json'), JSON.stringify(config));
+ for (const socket of sockets) socket.destroy();
+ if (proxy.listening) await new Promise<void>(resolve => proxy.close(() => resolve()));
+ }
+ }, 60_000);
+
+ test('keyword-only genuine and private misses remain clean on both transports', async () => {
+ await mutate(async () => { await engine.setConfig('search.mcp_keyword_only', 'true'); });
+ try {
+ const verify = async (client: Client) => {
+ for (const query of ['absentunfindable', PRIVATE]) {
+ const miss = await search(client, query);
+ expect(miss.rows).toEqual([]);
+ expect(miss.meta.degraded ?? []).toEqual([]);
+ expect(miss.content[1]!.text).toContain('clean miss');
+ }
+ };
+ await withStdio(BOUND, verify);
+ await withHttp(verify);
+ } finally {
+ await mutate(async () => { await engine.setConfig('search.mcp_keyword_only', 'false'); });
+ }
+ }, 60_000);
+
+ test('existing readiness metadata distinguishes visible pending projections and safe-index work without private leakage', async () => {
+ await mutate(async () => {
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ await withManagedFixtureWrite(engine, [BOUND, PRIVATE_SOURCE], async tx => {
+ await tx.executeRaw('UPDATE pages SET text_projection_revision = NULL WHERE source_id = ANY($1::text[])', [[BOUND, PRIVATE_SOURCE]]);
+ });
+ });
+ const verify = async (client: Client) => {
+ const pending = await search(client, VISIBLE);
+ expect(pending.rows).toEqual([]);
+ expect(pending.meta.degraded).toContainEqual({ stage: 'projection_pending' });
+ expect(pending.meta.projection_readiness.status).toBe('projection_pending');
+ };
+ await withStdio(BOUND, verify);
+ await withHttp(verify);
+ await withStdio(PRIVATE_SOURCE, async client => {
+ const miss = await search(client, PRIVATE);
+ expect(miss.rows).toEqual([]);
+ expect(miss.meta.degraded ?? []).toEqual([]);
+ expect(miss.meta.projection_readiness.status).toBe('ready');
+ });
+ await mutate(async () => {
+ await withManagedFixtureWrite(engine, [FEDERATED], async tx => {
+ await tx.executeRaw('UPDATE pages SET chunker_version = 3 WHERE source_id = $1', [FEDERATED]);
+ });
+ });
+ await withStdio(FEDERATED, async client => {
+ const withheld = await search(client, FOREIGN);
+ expect(withheld.rows).toEqual([]);
+ expect(withheld.meta.degraded).toContainEqual({ stage: 'safe_index_pending' });
+ });
+ }, 60_000);
+});
diff --git a/test/e2e/memory-safety-wave-postgres.test.ts b/test/e2e/memory-safety-wave-postgres.test.ts
new file mode 100644
index 0000000000..1ad7e971e7
--- /dev/null
+++ b/test/e2e/memory-safety-wave-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../memory-safety-wave.serial.test.ts'));
diff --git a/test/e2e/migration-vector-replay-postgres.test.ts b/test/e2e/migration-vector-replay-postgres.test.ts
new file mode 100644
index 0000000000..3f471b6027
--- /dev/null
+++ b/test/e2e/migration-vector-replay-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../migration-vector-replay.test.ts'));
diff --git a/test/e2e/migration-wave-budget-crash.test.ts b/test/e2e/migration-wave-budget-crash.test.ts
new file mode 100644
index 0000000000..107b29163f
--- /dev/null
+++ b/test/e2e/migration-wave-budget-crash.test.ts
@@ -0,0 +1,47 @@
+import { expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { migrationWaveFixture } from '../helpers/migration-wave-fixture.ts';
+
+for (const kind of ['pglite', 'postgres'] as const) {
+ for (const requestKind of ['embedding', 'rerank']) {
+ for (const boundary of ['before-reservation', 'after-debit', 'after-dispatch']) {
+ test.skipIf(kind === 'postgres' && !process.env.DATABASE_URL)(`${kind} ${requestKind}: SIGKILL ${boundary} retains authorization across reopen`, async () => {
+ const root = mkdtempSync(join(tmpdir(), 'migration-wave-crash-'));
+ const fixture = await migrationWaveFixture(kind);
+ await fixture.engine.disconnect();
+ const launch = (mode: string) => Bun.spawn([process.execPath, '--no-env-file', join(import.meta.dir, '../helpers/migration-wave-budget-process.ts'), mode, kind, fixture.database, root, boundary, requestKind], {
+ env: { ...process.env, HOME: join(root, 'home'), GBRAIN_HOME: join(root, 'home'), DATABASE_URL: '', GBRAIN_DATABASE_URL: '', OPENAI_API_KEY: '', ANTHROPIC_API_KEY: '' }, stdout: 'pipe', stderr: 'pipe',
+ });
+ try {
+ const child = launch('crash');
+ const errors = new Response(child.stderr).text();
+ const reader = child.stdout.getReader();
+ const timer = setTimeout(() => child.kill('SIGKILL'), 30_000);
+ let output = '';
+ try {
+ for (;;) {
+ const next = await reader.read();
+ if (next.done) break;
+ output += new TextDecoder().decode(next.value);
+ if (output.includes('MIGRATION_WAVE_CRASH_BOUNDARY')) break;
+ }
+ child.kill('SIGKILL');
+ expect(await child.exited, await errors).toBe(137);
+ expect(child.signalCode).toBe('SIGKILL');
+ expect(output).toContain('MIGRATION_WAVE_CRASH_BOUNDARY');
+ } finally { clearTimeout(timer); child.kill(); await child.exited; }
+ const recovery = launch('recover');
+ const killRecovery = setTimeout(() => recovery.kill('SIGKILL'), 30_000);
+ try {
+ const [stdout, stderr, code] = await Promise.all([new Response(recovery.stdout).text(), new Response(recovery.stderr).text(), recovery.exited]);
+ expect(code, stderr).toBe(0);
+ expect(stdout).toContain('MIGRATION_WAVE_BUDGET_RECOVERED');
+ console.log(stdout.trim());
+ } finally { clearTimeout(killRecovery); recovery.kill(); await recovery.exited; }
+ } finally { await fixture.close(); rmSync(root, { recursive: true, force: true }); }
+ }, 120_000);
+ }
+ }
+}
diff --git a/test/e2e/migration-wave-healing-fence.test.ts b/test/e2e/migration-wave-healing-fence.test.ts
new file mode 100644
index 0000000000..70852c131b
--- /dev/null
+++ b/test/e2e/migration-wave-healing-fence.test.ts
@@ -0,0 +1,61 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { embedStaleForSource } from '../../src/core/embed-stale.ts';
+import { tryAcquireDbLock } from '../../src/core/db-lock.ts';
+import { assertMigrationLeases } from '../../src/core/embedding-migration-budget.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { migrationWaveFixture, observeMigrationEngine } from '../helpers/migration-wave-fixture.ts';
+
+for (const kind of ['pglite', 'postgres'] as const) {
+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;
+ suite(`migration wave oversized healing fence (${kind})`, () => {
+ let fixture: Awaited<ReturnType<typeof migrationWaveFixture>>;
+ let engine: BrainEngine;
+ beforeAll(async () => { fixture = await migrationWaveFixture(kind); engine = fixture.engine; }, 60_000);
+ afterAll(async () => { resetGateway(); await fixture?.close(); });
+ for (const boundary of ['lease', 'abort', 'deadline'] as const) {
+ test(`${boundary} during prepared healing leaves exact projection unchanged and dispatches nothing`, async () => {
+ await withEnv({ GBRAIN_MAX_CHUNK_TOKENS: '128' }, async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });
+ const slug = `synthetic-healing-${boundary}`;
+ const body = 'Synthetic oversized canonical recovery paragraph with several distinct words. '.repeat(150);
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: body }]);
+ const snapshot = () => engine.executeRaw(`SELECT row_to_json(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(c) ORDER BY c.id) FROM content_chunks c WHERE c.page_id=p.id) AS chunks
+ FROM pages p WHERE slug=$1`, [slug]);
+ const before = await snapshot();
+ const lock = (await tryAcquireDbLock(engine, `migration-wave-healing-${boundary}`, 1))!;
+ const controller = new AbortController();
+ let armed = false, injected = false, calls = 0;
+ const opts = {
+ signal: controller.signal,
+ deadline: Date.now() + 60_000,
+ assertOwned: (tx?: BrainEngine) => assertMigrationLeases(tx ?? engine, [lock]),
+ embedFn: async (texts: string[]) => { calls++; return texts.map(() => new Float32Array(1536).fill(0.1)); },
+ };
+ const observed = observeMigrationEngine(engine, async (tx, method) => {
+ if (method === 'listStaleChunks') armed = true;
+ if (!armed || injected || method !== 'getChunks') return;
+ injected = true;
+ if (boundary === 'lease') await tx.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id=$1', [lock.id]);
+ if (boundary === 'abort') controller.abort();
+ if (boundary === 'deadline') opts.deadline = Date.now() - 1;
+ });
+ try {
+ try { await embedStaleForSource(observed, 'default', opts); }
+ catch (error) { expect(String(error)).toMatch(/lease lost|abort/i); }
+ expect(injected).toBe(true);
+ expect(calls).toBe(0);
+ expect(await snapshot()).toEqual(before);
+ } finally {
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [lock.id]);
+ await engine.deletePage(slug);
+ }
+ });
+ });
+ }
+ });
+}
diff --git a/test/e2e/migration-wave-intermediate-retrieval.test.ts b/test/e2e/migration-wave-intermediate-retrieval.test.ts
new file mode 100644
index 0000000000..0c7c61ff80
--- /dev/null
+++ b/test/e2e/migration-wave-intermediate-retrieval.test.ts
@@ -0,0 +1,83 @@
+import { expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { runSchemaTransition, readMigrationState } from '../../src/core/embedding-migration.ts';
+import { executeMigrationFlow, planMigrationFlow } from '../../src/commands/migrate-embeddings.ts';
+import { migrationWaveFixture } from '../helpers/migration-wave-fixture.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const model = 'openai:text-embedding-3-small';
+const oldModel = 'openai:text-embedding-3-large';
+const vector = new Float32Array(8).fill(0.25);
+for (const kind of ['pglite', 'postgres'] as const) {
+ test.skipIf(kind === 'postgres' && !process.env.DATABASE_URL)(`${kind}: partial failed migration, reopened readers and resumed completion never mix vector generations`, async () => {
+ const fixture = await migrationWaveFixture(kind);
+ const engine = fixture.engine;
+ const home = mkdtempSync(join(tmpdir(), 'migration-wave-retrieval-home-')); mkdirSync(join(home, '.gbrain'));
+ try {
+ await runSchemaTransition(engine, 8);
+ await engine.setConfig('embedding_model', oldModel); await engine.setConfig('embedding_dimensions', '8');
+ configureGateway({ embedding_model: oldModel, embedding_dimensions: 8, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: kind, embedding_model: oldModel, embedding_dimensions: 8, openai_api_key: 'synthetic-only' }));
+ for (const slug of ['synthetic-good-page', 'synthetic-failed-page']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `${slug} canonical retained text` });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `${slug} canonical retained text`, model: oldModel, embedding: vector }]);
+ await engine.setPageEmbeddingSignature(slug, { sourceId: 'default', signature: `${oldModel}:8` });
+ }
+ await engine.insertFact({ fact: 'synthetic-good-fact retained claim', entity_slug: 'synthetic-entity', source: 'synthetic', visibility: 'world', embedding: vector, embedding_model: oldModel }, { source_id: 'default' });
+ const pages = async (identity: string) => (await engine.searchVector(vector, { sourceId: 'default', embeddingColumn: { name: 'embedding', type: 'vector', dimensions: 8, embeddingModel: identity } })).map(r => r.slug).sort();
+ const duplicates = async (identity?: string) => (await engine.findCandidateDuplicates('default', 'synthetic-entity', 'unrelated cosine query', { embedding: vector, embeddingModel: identity })).map(r => r.fact).sort();
+ expect(await pages(oldModel)).toHaveLength(2);
+ expect(await pages(model)).toEqual([]);
+ let added = false, failed = false;
+ __setEmbedTransportForTests(async ({ values }) => {
+ if (!added && values.some(v => v.includes('synthetic-good-fact'))) {
+ added = true;
+ await engine.insertFact({ fact: 'synthetic-late-fact retained claim', entity_slug: 'synthetic-entity', source: 'synthetic', visibility: 'world' }, { source_id: 'default' });
+ }
+ const embeddings = values.map(v => {
+ if (v.includes('synthetic-failed-page')) { failed = true; return [0.25]; }
+ return Array.from(vector);
+ });
+ return { values, warnings: [], embeddings, usage: { tokens: values.length * 8 } };
+ });
+ const flow = () => withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined }, async () => {
+ const opts = { to: model, dim: 8, reranker: 'off', maxCostUsd: 1, quiet: true };
+ return executeMigrationFlow(engine, await planMigrationFlow(engine, opts), opts);
+ });
+ const first = await flow();
+ expect(first.status).toBe('incomplete'); expect(added).toBe(true); expect(failed).toBe(true);
+ const checkpoint = async () => {
+ expect(await pages(model)).toEqual(['synthetic-good-page']);
+ expect(await pages(oldModel)).toEqual([]);
+ expect(await duplicates(model)).toEqual(['synthetic-good-fact retained claim']);
+ expect(await duplicates(oldModel)).toEqual([]);
+ expect(await duplicates()).toEqual([]);
+ expect((await engine.listFactsByEntity('default', 'synthetic-entity', { visibility: ['world'] })).map(f => f.fact).sort()).toEqual(['synthetic-good-fact retained claim', 'synthetic-late-fact retained claim']);
+ expect((await readMigrationState(engine)).state).not.toBeNull();
+ expect(await engine.getConfig('embedding_migration.completed')).toBeNull();
+ };
+ await checkpoint();
+ const goodState = () => engine.executeRaw(`SELECT 'page' AS kind,c.embedding::text,c.embedded_at::text,c.embedded_text_hash FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.slug='synthetic-good-page'
+ UNION ALL SELECT 'fact',embedding::text,embedded_at::text,embedded_text_hash FROM facts WHERE fact='synthetic-good-fact retained claim' ORDER BY kind`);
+ const before = await goodState();
+ const budget = (await readMigrationState(engine)).state!.budget!;
+ await engine.disconnect();
+ await engine.connect(kind === 'pglite' ? { database_path: fixture.database } : { database_url: fixture.database });
+ resetGateway(); configureGateway({ embedding_model: model, embedding_dimensions: 8, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ await checkpoint();
+ expect((await readMigrationState(engine)).state!.budget).toEqual(budget);
+ __setEmbedTransportForTests(async ({ values }) => ({ values, warnings: [], embeddings: values.map(() => Array.from(vector)), usage: { tokens: values.length * 8 } }));
+ expect((await flow()).status).toBe('completed');
+ expect(await goodState()).toEqual(before);
+ expect(await pages(model)).toEqual(['synthetic-failed-page', 'synthetic-good-page']);
+ expect(await pages(oldModel)).toEqual([]);
+ expect(await duplicates(model)).toEqual(['synthetic-good-fact retained claim', 'synthetic-late-fact retained claim']);
+ expect(await duplicates(oldModel)).toEqual([]);
+ expect((await readMigrationState(engine)).state).toBeNull();
+ } finally { __setEmbedTransportForTests(null); resetGateway(); await fixture.close(); rmSync(home, { recursive: true, force: true }); }
+ }, 120_000);
+}
diff --git a/test/e2e/migration-wave-phase-leases.test.ts b/test/e2e/migration-wave-phase-leases.test.ts
new file mode 100644
index 0000000000..a35431f53e
--- /dev/null
+++ b/test/e2e/migration-wave-phase-leases.test.ts
@@ -0,0 +1,79 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { runSchemaTransition } from '../../src/core/embedding-migration.ts';
+import { executeMigrationFlow, planMigrationFlow } from '../../src/commands/migrate-embeddings.ts';
+import { migrationWaveFixture, observeMigrationEngine } from '../helpers/migration-wave-fixture.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const model = 'openai:text-embedding-3-small';
+const boundaries = {
+ schema: 'DROP INDEX IF EXISTS idx_chunks_embedding',
+ projection: 'await installPageProjection',
+ reconcile: 'return reconcilePageSignatures',
+ completion: 'MIGRATION_COMPLETED_KEY',
+};
+for (const kind of ['pglite', 'postgres'] as const) {
+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;
+ suite(`migration wave whole-flow source lease phases (${kind})`, () => {
+ let fixture: Awaited<ReturnType<typeof migrationWaveFixture>>;
+ let engine: BrainEngine;
+ let home: string;
+ beforeAll(async () => {
+ fixture = await migrationWaveFixture(kind); engine = fixture.engine;
+ home = mkdtempSync(join(tmpdir(), 'migration-wave-lease-home-')); mkdirSync(join(home, '.gbrain'));
+ }, 60_000);
+ beforeEach(async () => {
+ await engine.executeRaw('TRUNCATE pages,facts,fact_withdrawals,page_projection_jobs,gbrain_cycle_locks CASCADE');
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'embedding_migration.%'");
+ await runSchemaTransition(engine, 8);
+ await engine.setConfig('embedding_model', model); await engine.setConfig('embedding_dimensions', '8');
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: kind, embedding_model: model, embedding_dimensions: 8, openai_api_key: 'synthetic-only' }));
+ });
+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await fixture?.close(); rmSync(home, { recursive: true, force: true }); });
+ for (const [phase, marker] of Object.entries(boundaries)) {
+ test(`source lease takeover immediately before ${phase} transaction prevents every subsequent durable mutation`, async () => {
+ const dim = phase === 'schema' ? 16 : 8;
+ configureGateway({ embedding_model: model, embedding_dimensions: dim, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ await engine.putPage('synthetic-phase', { type: 'note', title: 'Synthetic phase', compiled_truth: 'Synthetic current canonical body' });
+ const chunk = { chunk_index: 0, chunk_source: 'compiled_truth' as const, chunk_text: 'Synthetic current canonical body' };
+ if (phase === 'projection') await engine.upsertChunks('synthetic-phase', [chunk]);
+ else await installFixtureChunks(engine, 'synthetic-phase', [chunk]);
+ await engine.insertFact({ fact: 'Synthetic phase fact', source: 'synthetic' }, { source_id: 'default' });
+ let injected = false, calls = 0, callsAtLoss = -1;
+ let atLoss: Record<string, unknown> = {};
+ const snapshot = async () => {
+ const state: Record<string, unknown> = {};
+ for (const table of ['pages', 'content_chunks', 'facts', 'page_projection_jobs', 'config']) {
+ state[table] = await engine.executeRaw(`SELECT to_jsonb(t) AS value FROM ${table} t ORDER BY to_jsonb(t)::text`);
+ }
+ state.columns = await engine.executeRaw("SELECT attrelid::regclass::text AS table_name,attname,atttypmod FROM pg_attribute WHERE attrelid IN ('content_chunks'::regclass,'facts'::regclass) AND attname='embedding' ORDER BY attrelid");
+ return state;
+ };
+ __setEmbedTransportForTests(async ({ values }) => { calls++; return { values, warnings: [], embeddings: values.map(() => Array(dim).fill(0.25)), usage: { tokens: values.length * 8 } }; });
+ const observed = observeMigrationEngine(engine, async () => {}, async (_tx, method, args) => {
+ if (injected || method !== 'transaction' || !String(args[0]).includes(marker)) return;
+ injected = true;
+ const changed = await engine.executeRaw("UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id='gbrain-embed-backfill:default' RETURNING id");
+ expect(changed).toHaveLength(1);
+ callsAtLoss = calls;
+ atLoss = await snapshot();
+ });
+ const result = await withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined }, async () => {
+ const opts = { to: model, dim, reranker: 'off', maxCostUsd: 1, quiet: true };
+ return executeMigrationFlow(observed, await planMigrationFlow(observed, opts), opts);
+ });
+ expect(injected).toBe(true);
+ expect(result.status).toBe('apply_failed');
+ expect(JSON.stringify(result)).toMatch(/lease lost/);
+ expect(calls).toBe(callsAtLoss);
+ expect(await snapshot()).toEqual(atLoss);
+ expect(await engine.getConfig('embedding_migration.completed')).toBeNull();
+ });
+ }
+ });
+}
diff --git a/test/e2e/migration-wave-prepared-withdrawal.test.ts b/test/e2e/migration-wave-prepared-withdrawal.test.ts
new file mode 100644
index 0000000000..cf0446afcf
--- /dev/null
+++ b/test/e2e/migration-wave-prepared-withdrawal.test.ts
@@ -0,0 +1,71 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { runSchemaTransition } from '../../src/core/embedding-migration.ts';
+import { readProjectionSnapshot, installPageEmbeddings, rebuildPendingPageProjections } from '../../src/core/page-state/projections.ts';
+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';
+import { renderFactsTable } from '../../src/core/facts-fence.ts';
+import { migrationWaveFixture } from '../helpers/migration-wave-fixture.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+
+const model = 'openai:text-embedding-3-small';
+const vector = new Float32Array(8).fill(0.25);
+for (const kind of ['pglite', 'postgres'] as const) {
+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;
+ suite(`migration wave prepared publication (${kind})`, () => {
+ let fixture: Awaited<ReturnType<typeof migrationWaveFixture>>;
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ fixture = await migrationWaveFixture(kind); engine = fixture.engine;
+ await runSchemaTransition(engine, 8);
+ await engine.setConfig('embedding_model', model);
+ await engine.setConfig('embedding_dimensions', '8');
+ configureGateway({ embedding_model: model, embedding_dimensions: 8, env: {} });
+ }, 60_000);
+ afterAll(async () => { resetGateway(); await fixture?.close(); });
+ for (const order of ['withdraw-first', 'install-first']) {
+ test(`${order}: delayed real vector installation never resurrects a withdrawn claim`, async () => {
+ const sourceId = `synthetic-${order}`;
+ const slug = 'synthetic-claim';
+ const claim = `withdrawalsentinel ${order} synthetic claim`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic race', compiled_truth: 'Safe retained prose', timeline: renderFactsTable([
+ { rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true },
+ ]) }, { sourceId });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'timeline', chunk_text: claim }], { sourceId });
+ const fact = await engine.insertFact({ fact: claim, source: 'synthetic', visibility: 'world' }, { source_id: sourceId });
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ const install = () => installPageEmbeddings(engine, prepared, prepared.chunks.map(chunk => ({ chunk_index: chunk.chunk_index, chunk_source: chunk.chunk_source, chunk_text: chunk.chunk_text, embedding: vector })), `${model}:8`);
+ if (order === 'install-first') {
+ expect(await install()).toBe(true);
+ expect(await engine.searchVector(vector, { sourceId })).toHaveLength(1);
+ }
+ expect((await recordFactWithdrawal(engine, fact.id, sourceId, true)).withdrawn).toBe(true);
+ expect(await install()).toBe(false);
+ expect(await engine.searchVector(vector, { sourceId })).toEqual([]);
+ expect(await engine.searchKeyword('withdrawalsentinel', { sourceId })).toEqual([]);
+ expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBeGreaterThan(0);
+ expect((await engine.getChunks(slug, { sourceId })).map(c => c.chunk_text).join('\n')).not.toContain(claim);
+ expect(await install()).toBe(false);
+ expect(await engine.searchKeyword('withdrawalsentinel', { sourceId })).toEqual([]);
+ });
+ }
+ for (const change of ['source', 'model', 'soft-deleted-page'] as const) {
+ test(`${change} change rejects a prepared vector without changing the replacement state`, async () => {
+ const sourceId = `synthetic-prepared-${change}`;
+ const slug = 'synthetic-prepared';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Synthetic stable content' }, { sourceId });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic stable content' }], { sourceId });
+ const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;
+ if (change === 'source') await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ else if (change === 'model') await engine.setConfig('embedding_model', 'openai:text-embedding-3-large');
+ else expect(await engine.softDeletePage(slug, { sourceId })).not.toBeNull();
+ const before = await engine.executeRaw('SELECT to_jsonb(c) AS chunk FROM content_chunks c WHERE page_id=$1 ORDER BY id', [prepared.snapshot.page.id]);
+ expect(await installPageEmbeddings(engine, prepared, prepared.chunks.map(chunk => ({ chunk_index: chunk.chunk_index, chunk_source: chunk.chunk_source, chunk_text: chunk.chunk_text, embedding: vector })))).toBe(false);
+ expect(await engine.executeRaw('SELECT to_jsonb(c) AS chunk FROM content_chunks c WHERE page_id=$1 ORDER BY id', [prepared.snapshot.page.id])).toEqual(before);
+ await engine.setConfig('embedding_model', model);
+ });
+ }
+ });
+}
diff --git a/test/e2e/migration-wave-provider-outcomes.test.ts b/test/e2e/migration-wave-provider-outcomes.test.ts
new file mode 100644
index 0000000000..e7e418f3ab
--- /dev/null
+++ b/test/e2e/migration-wave-provider-outcomes.test.ts
@@ -0,0 +1,83 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { runSchemaTransition, readMigrationState } from '../../src/core/embedding-migration.ts';
+import { executeMigrationFlow, planMigrationFlow } from '../../src/commands/migrate-embeddings.ts';
+import { migrationWaveFixture } from '../helpers/migration-wave-fixture.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const model = 'openai:text-embedding-3-small';
+const dimensions = 8;
+const valid = () => Array(dimensions).fill(0.25) as number[];
+
+for (const kind of ['pglite', 'postgres'] as const) {
+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;
+ suite(`migration wave malformed provider outcomes (${kind})`, () => {
+ let fixture: Awaited<ReturnType<typeof migrationWaveFixture>>;
+ let engine: BrainEngine;
+ let home: string;
+ beforeAll(async () => {
+ fixture = await migrationWaveFixture(kind); engine = fixture.engine;
+ await runSchemaTransition(engine, dimensions);
+ home = mkdtempSync(join(tmpdir(), 'migration-wave-provider-home-'));
+ mkdirSync(join(home, '.gbrain'));
+ }, 60_000);
+ beforeEach(async () => {
+ await engine.executeRaw('TRUNCATE pages,facts,fact_withdrawals,page_projection_jobs CASCADE');
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'embedding_migration.%'");
+ await engine.setConfig('embedding_model', model);
+ await engine.setConfig('embedding_dimensions', String(dimensions));
+ resetGateway();
+ configureGateway({ embedding_model: model, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: kind, embedding_model: model, embedding_dimensions: dimensions, openai_api_key: 'synthetic-only' }));
+ });
+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await fixture?.close(); rmSync(home, { recursive: true, force: true }); });
+ async function flow() {
+ return withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined }, async () => {
+ const opts = { to: model, dim: dimensions, reranker: 'off', maxCostUsd: 1, quiet: true };
+ return executeMigrationFlow(engine, await planMigrationFlow(engine, opts), opts);
+ });
+ }
+ for (const path of ['page', 'fact'] as const) {
+ for (const malformed of ['empty', 'count', 'width', 'nonfinite', 'partial'] as const) {
+ test(`${path} ${malformed} batch installs nothing, remains incomplete, and retries successfully`, async () => {
+ const sentinel = `synthetic-${path}-${malformed}`;
+ if (path === 'page') {
+ await engine.putPage(sentinel, { type: 'note', title: sentinel, compiled_truth: `${sentinel} first. ${sentinel} second.` });
+ await installFixtureChunks(engine, sentinel, [0, 1].map(i => ({ chunk_index: i, chunk_source: 'compiled_truth' as const, chunk_text: `${sentinel} ${i}` })));
+ } else {
+ for (const i of [0, 1]) await engine.insertFact({ fact: `${sentinel} ${i}`, entity_slug: sentinel, source: 'synthetic', visibility: 'world' }, { source_id: 'default' });
+ }
+ let faults = 0;
+ __setEmbedTransportForTests(async ({ values }) => {
+ let embeddings = values.map(valid);
+ if (values.some(value => value.includes(sentinel))) {
+ faults++;
+ if (malformed === 'empty') embeddings = [];
+ if (malformed === 'count') embeddings.push(valid());
+ if (malformed === 'width') embeddings = values.map(() => [0.25]);
+ if (malformed === 'nonfinite') embeddings = values.map(() => Array(dimensions).fill(NaN));
+ if (malformed === 'partial') embeddings[embeddings.length - 1] = [0.25];
+ }
+ return { values, warnings: [], embeddings, usage: { tokens: values.length * 8 } };
+ });
+ const failed = await flow();
+ expect(faults).toBeGreaterThan(0);
+ expect(failed.status).toBe('incomplete');
+ expect(await engine.getConfig('embedding_migration.completed')).toBeNull();
+ expect((await readMigrationState(engine)).state).not.toBeNull();
+ const table = path === 'page' ? 'content_chunks' : 'facts';
+ expect(await engine.executeRaw(`SELECT id FROM ${table} WHERE embedding IS NOT NULL`)).toEqual([]);
+ __setEmbedTransportForTests(async ({ values }) => ({ values, warnings: [], embeddings: values.map(valid), usage: { tokens: values.length * 8 } }));
+ expect((await flow()).status).toBe('completed');
+ expect(await engine.executeRaw(`SELECT id FROM ${table} WHERE embedding IS NOT NULL`)).toHaveLength(2);
+ expect((await readMigrationState(engine)).state).toBeNull();
+ });
+ }
+ }
+ });
+}
diff --git a/test/e2e/persistence-http-liveness.test.ts b/test/e2e/persistence-http-liveness.test.ts
index cb56116a14..c7d5130b99 100644
--- a/test/e2e/persistence-http-liveness.test.ts
+++ b/test/e2e/persistence-http-liveness.test.ts
@@ -149,7 +149,12 @@ describe.skipIf(!url)('authenticated PostgreSQL HTTP accepted-write liveness', (
expect(aged.diagnostic.next_action).toBe('inspect_owner');
expect(aged.retry_after_ms).toBe(30000);
expect((await call(client, 'put_page', put)).body.suggestion).toContain('inspect');
- await stop('SIGKILL');
+ await pg.engine.transaction(async tx => {
+ await waitFor(async () => (await tx.executeRaw(`SELECT id FROM persistence_requests
+ WHERE request_id=$1::uuid AND state='queued' FOR SHARE SKIP LOCKED`, [put.request_id])).length === 1,
+ { label: 'accepted queued receipt before owner restart' });
+ await stop('SIGKILL');
+ });
} finally { await lock!.release(); }
await start();
await connect(tokens[0]); await connect(tokens[1]);
diff --git a/test/e2e/postgres-bootstrap.test.ts b/test/e2e/postgres-bootstrap.test.ts
index 5c1d14be5b..54868ff601 100644
--- a/test/e2e/postgres-bootstrap.test.ts
+++ b/test/e2e/postgres-bootstrap.test.ts
@@ -25,6 +25,7 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { LATEST_VERSION } from '../../src/core/migrate.ts';
+import { readFactsEmbeddingDim } from '../../src/core/embedding-dim-check.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
import { applyPostgresForwardReferenceBootstrap } from '../../src/core/postgres-engine/forward-reference-bootstrap.ts';
@@ -45,6 +46,45 @@ describe.skipIf(skip)('PostgresEngine forward-reference bootstrap (E2E)', () =>
await close?.();
});
+ test('fact embedding identity bootstrap repairs old and partial schemas without inventing provenance', async () => {
+ await engine.initSchema();
+ const { dims } = await readFactsEmbeddingDim(engine);
+ const fact = await engine.insertFact({ fact: 'Synthetic bootstrap claim', source: 'synthetic', embedding: new Float32Array(dims!).fill(0.1) }, { source_id: 'default' });
+ const original = await engine.executeRaw('SELECT id,fact,embedding::text,embedded_at FROM facts WHERE id=$1', [fact.id]);
+ expect(original[0].embedding).not.toBeNull();
+ for (const missing of [['embedding_model', 'embedded_text_hash'], ['embedding_model'], ['embedded_text_hash']]) {
+ const conn = await (engine as any).sql.reserve();
+ try {
+ await conn.unsafe('SELECT pg_advisory_lock(42)');
+ await conn.unsafe("UPDATE facts SET embedding_model='synthetic:original',embedded_text_hash='synthetic-preserved-hash' WHERE id=$1", [fact.id]);
+ for (const column of missing) await conn.unsafe(`ALTER TABLE facts DROP COLUMN ${column}`);
+ await conn.unsafe("UPDATE config SET value='165' WHERE key='version'");
+ await applyPostgresForwardReferenceBootstrap(conn);
+ await applyPostgresForwardReferenceBootstrap(conn);
+ expect((await conn.unsafe("SELECT value FROM config WHERE key='version'"))[0].value).toBe('165');
+ expect(await conn.unsafe(`SELECT column_name,data_type,is_nullable,column_default FROM information_schema.columns
+ WHERE table_schema=current_schema() AND table_name='facts' AND column_name IN ('embedding_model','embedded_text_hash') ORDER BY column_name`)).toEqual([
+ { column_name: 'embedded_text_hash', data_type: 'text', is_nullable: 'YES', column_default: null },
+ { column_name: 'embedding_model', data_type: 'text', is_nullable: 'YES', column_default: null },
+ ]);
+ } finally {
+ await conn.unsafe('SELECT pg_advisory_unlock(42)');
+ conn.release();
+ }
+ const identity = [{
+ embedding_model: missing.includes('embedding_model') ? null : 'synthetic:original',
+ embedded_text_hash: missing.includes('embedded_text_hash') ? null : 'synthetic-preserved-hash',
+ }];
+ expect(await engine.executeRaw('SELECT embedding_model,embedded_text_hash FROM facts WHERE id=$1', [fact.id])).toEqual(identity);
+ for (const column of missing) await engine.executeRaw(`ALTER TABLE facts DROP COLUMN ${column}`);
+ await engine.initSchema();
+ await engine.initSchema();
+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));
+ expect(await engine.executeRaw('SELECT embedding_model,embedded_text_hash FROM facts WHERE id=$1', [fact.id])).toEqual(identity);
+ expect(await engine.executeRaw('SELECT id,fact,embedding::text,embedded_at FROM facts WHERE id=$1', [fact.id])).toEqual(original);
+ }
+ }, 60_000);
+
test('grant bootstrap repairs a partial installation without changing existing client policy', async () => {
await engine.initSchema();
const conn = await (engine as any).sql.reserve();
diff --git a/test/e2e/upsert-chunks-registry-column.test.ts b/test/e2e/upsert-chunks-registry-column.test.ts
index 666392ccc8..3801f29bc3 100644
--- a/test/e2e/upsert-chunks-registry-column.test.ts
+++ b/test/e2e/upsert-chunks-registry-column.test.ts
@@ -65,17 +65,18 @@ function registryWriteScenario(name: string, getEngine: () => BrainEngine) {
for (const guarded of [false, true]) {
for (const includeNullSignature of [false, true]) {
await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: '# resumed' });
- await engine.upsertChunks(slug, [0, 1].map((i) => ({
- chunk_index: i, chunk_text: `resumed chunk ${i}`, chunk_source: 'compiled_truth',
+ const fixture = [0, 1].map((i) => ({
+ chunk_index: i, chunk_text: `resumed chunk ${i}`, chunk_source: 'compiled_truth' as const,
embedding: VEC8, model: i === 0 ? 'voyage:voyage-3-large' : 'foreign:model',
- })));
+ }));
+ if (guarded) await installFixtureChunks(engine, slug, fixture);
+ else await engine.upsertChunks(slug, fixture);
if (!includeNullSignature) await engine.setPageEmbeddingSignature(slug, { signature: 'old:model:8' });
const opts = { signature, includeNullSignature };
const invalidated = guarded
? await invalidateStaleSignatureEmbeddingsGuarded(engine, opts)
: await engine.invalidateStaleSignatureEmbeddings(opts);
expect(invalidated).toBe(1);
- // Inspect the raw write-side state before a retrieval projection is sealed.
const chunks = await engine.getChunks(slug, { includeUnsealed: true });
expect(chunks.map((chunk) => chunk.embedding_is_null)).toEqual([false, true]);
await engine.deletePage(slug);
@@ -86,6 +87,35 @@ function registryWriteScenario(name: string, getEngine: () => BrainEngine) {
await engine.setConfig('search_embedding_column', 'embedding_test8');
}
});
+ test(`${name}: guarded invalidation preserves unsealed ${column} registry chunks`, async () => {
+ const engine = getEngine();
+ const slug = `docs/registry-unsealed-${column}`;
+ await engine.setConfig('embedding_columns', REGISTRY_JSON);
+ await engine.setConfig('search_embedding_column', column);
+ try {
+ for (const includeNullSignature of [false, true]) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: '# unsealed' });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_text: 'Synthetic unsealed registry chunk',
+ chunk_source: 'compiled_truth', embedding: VEC8, model: 'foreign:model' }]);
+ if (!includeNullSignature) await engine.setPageEmbeddingSignature(slug, { signature: 'old:model:8' });
+ const snapshot = () => engine.executeRaw<{ page: Record<string, unknown>; chunk: Record<string, unknown> }>(`SELECT
+ to_jsonb(p) AS page,to_jsonb(cc) AS chunk FROM pages p JOIN content_chunks cc ON cc.page_id=p.id
+ WHERE p.slug=$1 AND p.source_id='default' ORDER BY cc.chunk_index`, [slug]);
+ const before = await snapshot();
+ expect(before).toHaveLength(1);
+ expect(before[0].page.text_projection_revision).toBeNull();
+ expect(before[0].chunk[column]).not.toBeNull();
+ expect(await invalidateStaleSignatureEmbeddingsGuarded(engine, {
+ signature: 'voyage:voyage-3-large:8', includeNullSignature,
+ })).toBe(0);
+ expect(await snapshot()).toEqual(before);
+ await engine.deletePage(slug);
+ }
+ } finally {
+ await engine.deletePage(slug);
+ await engine.setConfig('search_embedding_column', 'embedding_test8');
+ }
+ });
}
test(`${name}: registry-routed write lands in the active column, not legacy embedding`, async () => {
@@ -315,6 +345,8 @@ function registryStaleScenario(name: string, getEngine: () => BrainEngine) {
test(`${name}: signature invalidation NULLs the registry column (guarded + engine method)`, async () => {
const engine = getEngine();
+ await installFixtureChunks(engine, SLUG, [{ chunk_index: 0, chunk_text: 'stale probe v2',
+ chunk_source: 'compiled_truth', embedding: VEC8_B, model: 'voyage:voyage-3-large' }]);
// Guarded helper (the migration/embed entry point).
await engine.setPageEmbeddingSignature(SLUG, { signature: 'sig-old' });
const n = await invalidateStaleSignatureEmbeddingsGuarded(engine, { signature: 'sig-new' });
diff --git a/test/e2e/withdrawal-bounded-safety-postgres.test.ts b/test/e2e/withdrawal-bounded-safety-postgres.test.ts
new file mode 100644
index 0000000000..4d8d9cd350
--- /dev/null
+++ b/test/e2e/withdrawal-bounded-safety-postgres.test.ts
@@ -0,0 +1,2 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+await registerPostgresTests(() => import('../withdrawal-bounded-safety.test.ts'));
diff --git a/test/e2e/withdrawal-crash-postgres.test.ts b/test/e2e/withdrawal-crash-postgres.test.ts
new file mode 100644
index 0000000000..51dda26b77
--- /dev/null
+++ b/test/e2e/withdrawal-crash-postgres.test.ts
@@ -0,0 +1,2 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+await registerPostgresTests(() => import('../withdrawal-crash.slow.test.ts'));
diff --git a/test/embedding-identity-companions.serial.test.ts b/test/embedding-identity-companions.serial.test.ts
index e129ffef05..41bef701ed 100644
--- a/test/embedding-identity-companions.serial.test.ts
+++ b/test/embedding-identity-companions.serial.test.ts
@@ -147,7 +147,7 @@ async function withBrain(kind: Kind, fn: (fixture: {
async function seedStore(engine: BrainEngine, table: Store) {
if (table === 'facts') {
await engine.executeRaw(
- "INSERT INTO facts(source_id, entity_slug, fact, source, embedding) VALUES ('default', 'people/example', 'A synthetic durable fact.', 'manual', $1::vector)", [VECTOR_TEXT],
+ "INSERT INTO facts(source_id, entity_slug, fact, source, embedding, embedding_model, embedded_text_hash) VALUES ('default', 'people/example', 'A synthetic durable fact.', 'manual', $1::vector, $2, md5('A synthetic durable fact.'))", [VECTOR_TEXT, OLD],
);
} else if (table === 'query_cache') {
await engine.executeRaw(
@@ -204,7 +204,7 @@ for (const kind of ['pglite', 'postgres'] as const) {
const facts = await seedStore(engine, 'facts');
const takes = await seedStore(engine, 'takes');
await seedStore(engine, 'query_cache');
- expect((await engine.findCandidateDuplicates('default', 'people/example', 'Another fact', { embedding: VECTOR })).map(row => String(row.id))).toEqual([String(facts[0].id)]);
+ expect((await engine.findCandidateDuplicates('default', 'people/example', 'Another fact', { embedding: VECTOR, embeddingModel: OLD })).map(row => String(row.id))).toEqual([String(facts[0].id)]);
await seedRaw(engine);
await engine.executeRaw('UPDATE content_chunks SET embedding_image = $1::vector, embedding_multimodal = $1::vector', [VECTOR_TEXT]);
const independent = await engine.executeRaw('SELECT embedding_image::text AS image, embedding_multimodal::text AS multimodal FROM content_chunks');
@@ -212,14 +212,14 @@ for (const kind of ['pglite', 'postgres'] as const) {
const plan = await planEmbeddingMigration(engine, { to: TARGET, dim: DIMS });
expect(plan.from_model).toBe(OLD);
const result = await applyEmbeddingMigration(engine, plan, {
- persistConfig: async () => {
- expect(await engine.getConfig('embedding_model')).toBe(TARGET);
- expect(await snapshotStore(engine, 'facts')).toEqual(facts.map(row => ({ ...row, embedding: null })));
- expect(await snapshotStore(engine, 'takes'))
+ persistConfig: async (_model, _dimensions, tx) => {
+ expect(await tx.getConfig('embedding_model')).toBe(TARGET);
+ expect(await snapshotStore(tx, 'facts')).toEqual(facts.map(row => ({ ...row, embedding: null })));
+ expect(await snapshotStore(tx, 'takes'))
.toEqual(takes.map(row => ({ ...row, embedding: null, row: { ...row.row, embedded_at: null } })));
- expect(await engine.executeRaw('SELECT id FROM query_cache')).toHaveLength(0);
- expect((await readMigrationStatus(engine)).facts_pending).toBe(1);
- expect(await engine.findCandidateDuplicates('default', 'people/example', 'Another fact', { embedding: VECTOR })).toHaveLength(0);
+ expect(await tx.executeRaw('SELECT id FROM query_cache')).toHaveLength(0);
+ expect((await readMigrationStatus(tx)).facts_pending).toBe(1);
+ expect(await tx.findCandidateDuplicates('default', 'people/example', 'Another fact', { embedding: VECTOR })).toHaveLength(0);
throw new Error('fixture publication interruption');
},
});
@@ -228,7 +228,7 @@ for (const kind of ['pglite', 'postgres'] as const) {
expect(await engine.executeRaw('SELECT embedding_image::text AS image, embedding_multimodal::text AS multimodal FROM content_chunks')).toEqual(independent);
await reopen();
const regenerated = JSON.stringify(new Array(DIMS).fill(0.25));
- await engine.executeRaw('UPDATE facts SET embedding = $1::vector', [regenerated]);
+ await engine.executeRaw('UPDATE facts SET embedding = $1::vector, embedding_model=$2, embedded_text_hash=md5(fact)', [regenerated, TARGET]);
await engine.executeRaw('UPDATE takes SET embedding = $1::vector, embedded_at = now()', [regenerated]);
const regeneratedFacts = await snapshotStore(engine, 'facts');
const regeneratedTakes = await snapshotStore(engine, 'takes');
diff --git a/test/embedding-migration.test.ts b/test/embedding-migration.test.ts
index ada8a4f275..465aad28a5 100644
--- a/test/embedding-migration.test.ts
+++ b/test/embedding-migration.test.ts
@@ -22,6 +22,7 @@
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
import type { ChunkInput } from '../src/core/types.ts';
@@ -71,7 +72,7 @@ async function seedEmbedded(slug: string, text: string, signature: string | null
const chunks: ChunkInput[] = [
{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', token_count: 4, embedding: undefined },
];
- await engine.upsertChunks(slug, chunks);
+ await installFixtureChunks(engine, slug, chunks);
await engine.executeRaw(
`UPDATE content_chunks
SET embedding = ('[' || array_to_string(array_fill(0.0::real, ARRAY[$1::int]), ',') || ']')::vector
@@ -424,7 +425,7 @@ describe('#4305 false target stamps + #4306 embed_skip-safe invalidation', () =>
type: 'note', title: slug, compiled_truth: `# ${slug}`,
...(opts.frontmatter ? { frontmatter: opts.frontmatter } : {}),
});
- await engine.upsertChunks(slug, [
+ await installFixtureChunks(engine, slug, [
{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', token_count: 4, model: opts.model },
]);
if (opts.embedded !== false) {
diff --git a/test/embedding-readiness.test.ts b/test/embedding-readiness.test.ts
new file mode 100644
index 0000000000..176e479fc6
--- /dev/null
+++ b/test/embedding-readiness.test.ts
@@ -0,0 +1,46 @@
+import { expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { prepareEmbeddingProjections } from '../src/core/embedding-readiness.ts';
+import { mockEmbedProjectionEngine } from './helpers/embed-projection-mock.ts';
+
+test('projection fixture count models its sealed snapshots', async () => {
+ const engine = mockEmbedProjectionEngine();
+ const snapshot = await engine.readPageSnapshot('synthetic-fixture');
+ expect(snapshot?.page.text_projection_revision).toBe(snapshot?.page.knowledge_revision);
+ expect(await prepareEmbeddingProjections(engine)).toEqual({ rebuilt: 0, blocked: 0 });
+});
+
+test.each([undefined, null, NaN, -1, 'unknown'])('projection readiness rejects an unknown or invalid count: %s', async n => {
+ const engine = { executeRaw: async (sql: string) => sql.startsWith('SELECT count(') ? [{ n }] : [] } as unknown as BrainEngine;
+ await expect(prepareEmbeddingProjections(engine)).rejects.toThrow('Cannot determine pending embedding projections');
+});
+
+test('projection readiness rejects missing count rows', async () => {
+ const engine = { executeRaw: async () => [] } as unknown as BrainEngine;
+ await expect(prepareEmbeddingProjections(engine)).rejects.toThrow('Cannot determine pending embedding projections');
+});
+
+test('projection readiness propagates count failures', async () => {
+ const engine = { executeRaw: async (sql: string) => {
+ if (sql.startsWith('SELECT count(')) throw new Error('synthetic count failure');
+ return [];
+ } } as unknown as BrainEngine;
+ await expect(prepareEmbeddingProjections(engine)).rejects.toThrow('synthetic count failure');
+});
+
+test('projection recovery stops after a batch makes no progress', async () => {
+ let batches = 0;
+ const engine = mockEmbedProjectionEngine({
+ readPageSnapshot: async () => null,
+ executeRaw: async (sql: string) => {
+ if (sql.startsWith('SELECT count(')) return [{ n: 1 }];
+ if (sql.startsWith('SELECT p.slug,p.source_id')) {
+ batches++;
+ return [{ slug: 'synthetic-unavailable', source_id: 'default' }];
+ }
+ return [];
+ },
+ });
+ expect(await prepareEmbeddingProjections(engine, { repair: true })).toEqual({ rebuilt: 0, blocked: 1 });
+ expect(batches).toBe(1);
+});
diff --git a/test/embedding-recovery.serial.test.ts b/test/embedding-recovery.serial.test.ts
new file mode 100644
index 0000000000..3c889ab13c
--- /dev/null
+++ b/test/embedding-recovery.serial.test.ts
@@ -0,0 +1,1485 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { setupDB, teardownDB } from './e2e/helpers.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { configureGateway, getEmbeddingModel, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { applyEmbeddingMigration, planEmbeddingMigration, runSchemaTransition, verifyMigrationComplete, readMigrationState, reconcilePageSignatures, verifySearchRoundTrip } from '../src/core/embedding-migration.ts';
+import { readContentChunksEmbeddingDim } from '../src/core/embedding-dim-check.ts';
+import { readProjectionSnapshot } from '../src/core/page-state/projections.ts';
+import { embedStaleForSource } from '../src/core/embed-stale.ts';
+import { embedStaleFacts } from '../src/core/embed-facts.ts';
+import { countStaleFactEmbeddings } from '../src/core/facts/embedding-identity.ts';
+import { authorizeMigrationBudget, assertMigrationLeases } from '../src/core/embedding-migration-budget.ts';
+import { tryAcquireDbLock } from '../src/core/db-lock.ts';
+import { invokeAI, withAIInvocationGuard } from '../src/core/ai/invocation-guard.ts';
+import { planMigrationFlow, executeMigrationFlow, persistEmbeddingFileConfig } from '../src/commands/migrate-embeddings.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { prepareEmbeddingProjections } from '../src/core/embedding-readiness.ts';
+import { makeEmbedBackfillHandler } from '../src/core/minions/handlers/embed-backfill.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { loadConfigFileOnly } from '../src/core/config.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { AUDIT_ROW_SOURCES } from '../src/core/facts/audit-sources.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { softDeleteSource } from '../src/core/destructive-guard.ts';
+import { assertRetainedEmbeddingRebuildability } from '../src/core/embedding-migration-retention.ts';
+import { importImageFile } from '../src/core/import-file.ts';
+import { clearFalseStampedSignatures, countFalseStampedChunks, invalidateStaleSignatureEmbeddingsGuarded } from '../src/core/embedding-invalidation.ts';
+
+const model = 'openai:text-embedding-3-small';
+const dimensions = 8;
+const backends = testBackends();
+for (const kind of backends) {
+ describe(`embedding recovery safety (${kind})`, () => {
+ let engine: BrainEngine;
+ let originalDimensions: number;
+ let originalIdentity: Array<{ key: string; value: string }>;
+ async function flow(maxCostUsd = 1, to = model, targetDimensions = dimensions, retarget = false) {
+ const home = mkdtempSync(join(tmpdir(), 'migration-recovery-'));
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: kind, embedding_model: model, embedding_dimensions: dimensions, openai_api_key: 'synthetic-only' }));
+ try {
+ return await withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined }, async () => {
+ const options = { to, dim: targetDimensions, reranker: 'off', maxCostUsd, quiet: true, retarget };
+ return executeMigrationFlow(engine, await planMigrationFlow(engine, options), options);
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }
+ beforeAll(async () => {
+ if (kind === 'postgres') engine = await setupDB();
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ originalDimensions = (await readContentChunksEmbeddingDim(engine)).dims!;
+ originalIdentity = await engine.executeRaw("SELECT key,value FROM config WHERE key IN ('embedding_model','embedding_dimensions')");
+ await runSchemaTransition(engine, dimensions);
+ }, 60_000);
+ beforeEach(async () => {
+ if (kind === 'pglite') await resetPgliteState(engine as PGLiteEngine);
+ else {
+ await engine.executeRaw('TRUNCATE facts, pages, fact_withdrawals, page_projection_jobs CASCADE');
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'embedding_migration.%'");
+ }
+ await engine.setConfig('embedding_model', model);
+ await engine.setConfig('embedding_dimensions', String(dimensions));
+ resetGateway();
+ configureGateway({ embedding_model: model, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => ({
+ embeddings: values.map(() => Array.from({ length: dimensions }, (_, i) => (i+1)/10)), usage: { tokens: values.length * 8 },
+ }) as never);
+ });
+ afterAll(async () => {
+ __setEmbedTransportForTests(null); resetGateway();
+ await runSchemaTransition(engine, originalDimensions);
+ await engine.executeRaw("DELETE FROM config WHERE key IN ('embedding_model','embedding_dimensions')");
+ for (const row of originalIdentity) await engine.setConfig(row.key, row.value);
+ if (kind === 'postgres') await teardownDB(); else await engine.disconnect();
+ });
+ async function seedArchivedEligibility(scenario: string) {
+ const sourceId = 'synthetic-cycle6-archive';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT(id) DO UPDATE SET archived=false', [sourceId]);
+ for (const source of ['default', sourceId]) {
+ const text = source === sourceId ? 'Synthetic archived eligibility payload.' : 'Synthetic active eligibility payload.';
+ await engine.putPage('eligibility', { type: 'note', title: 'Synthetic eligibility', compiled_truth: text }, { sourceId: source });
+ await installFixtureChunks(engine, 'eligibility', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text,
+ ...(source === sourceId && !['null', 'unsealed', 'chunkless'].includes(scenario)
+ && { embedding: new Float32Array(dimensions).fill(0.1) }) }], { sourceId: source });
+ }
+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);
+ await engine.executeRaw(`UPDATE content_chunks cc SET model=$1,embedded_at='2025-01-01'::timestamptz,
+ embedded_text_hash=md5(cc.chunk_text) FROM pages p WHERE p.id=cc.page_id AND p.source_id=$2`, [model, sourceId]);
+ if (scenario === 'drift') await engine.executeRaw(`UPDATE content_chunks cc SET embedded_text_hash=md5('Synthetic obsolete content')
+ FROM pages p WHERE p.id=cc.page_id AND p.source_id=$1`, [sourceId]);
+ if (scenario === 'null-hash') await engine.executeRaw(`UPDATE content_chunks cc SET embedded_text_hash=NULL
+ FROM pages p WHERE p.id=cc.page_id AND p.source_id=$1`, [sourceId]);
+ if (scenario === 'signature') await engine.executeRaw("UPDATE pages SET embedding_signature='old:model:8' WHERE source_id=$1", [sourceId]);
+ if (scenario === 'false-stamp') await engine.executeRaw(`UPDATE content_chunks cc SET model='old:model'
+ FROM pages p WHERE p.id=cc.page_id AND p.source_id=$1`, [sourceId]);
+ if (scenario === 'unsealed') await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1', [sourceId]);
+ if (scenario === 'chunkless') await engine.executeRaw('DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE source_id=$1)', [sourceId]);
+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ const snapshot = () => engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE p.source_id=$1 ORDER BY p.id`, [sourceId]);
+ return { sourceId, snapshot };
+ }
+ describe('archived eligibility boundary', () => {
+ afterEach(async () => {
+ await engine.executeRaw('TRUNCATE pages CASCADE');
+ await engine.executeRaw("UPDATE sources SET archived=false WHERE id='default'");
+ });
+ for (const scenario of ['drift', 'null', 'unsealed', 'chunkless', 'signature', 'false-stamp']) {
+ test(`archived eligibility: migration refuses ${scenario} before authorization on repeated same-target attempts`, async () => {
+ const { snapshot } = await seedArchivedEligibility(scenario);
+ const before = await snapshot();
+ const pages = await engine.executeRaw('SELECT to_jsonb(p) AS page FROM pages p ORDER BY id');
+ const chunks = await engine.executeRaw('SELECT to_jsonb(cc) AS chunk FROM content_chunks cc ORDER BY id');
+ const config = await engine.executeRaw('SELECT key,value FROM config ORDER BY key');
+ let calls = 0;
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('Archived work must refuse before transport'); });
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const result = await flow();
+ expect(result.status).toBe('apply_failed');
+ expect(JSON.stringify(result)).toContain('retained_vectors_blocked');
+ expect(JSON.stringify(result)).toContain('gbrain sources restore');
+ expect(calls).toBe(0);
+ expect(await snapshot()).toEqual(before);
+ expect(await engine.executeRaw('SELECT to_jsonb(p) AS page FROM pages p ORDER BY id')).toEqual(pages);
+ expect(await engine.executeRaw('SELECT to_jsonb(cc) AS chunk FROM content_chunks cc ORDER BY id')).toEqual(chunks);
+ expect(await engine.executeRaw('SELECT key,value FROM config ORDER BY key')).toEqual(config);
+ }
+ });
+ }
+ for (const scenario of ['unsealed', 'null', 'drift', 'signature', 'chunkless']) {
+ test(`archived eligibility: plain stale repairs active work and honestly skips archived ${scenario}`, async () => {
+ const { sourceId, snapshot } = await seedArchivedEligibility(scenario);
+ const before = await snapshot();
+ const inputs: string[] = [];
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ inputs.push(...values);
+ return { values, warnings: [], embeddings: values.map(() => Array.from({ length: dimensions }, () => 0.1)), usage: { tokens: 8 } };
+ });
+ const result = await runEmbedCore(engine, { stale: true, quiet: true, catchUp: true });
+ expect(result.embedded).toBe(1);
+ expect(result.failures).toBeGreaterThan(0);
+ expect(result.failure_samples.join(' ')).toContain('archived');
+ expect(inputs).toHaveLength(1);
+ expect(inputs[0]).toContain('Synthetic active eligibility payload.');
+ expect(await snapshot()).toEqual(before);
+ const drainedInputs: string[] = [];
+ const drained = await embedStaleForSource(engine, sourceId, { embeddingSignature: `${model}:${dimensions}`,
+ embedFn: async texts => { drainedInputs.push(...texts); return texts.map(() => new Float32Array(dimensions).fill(0.1)); } });
+ expect(drained.complete).toBe(false);
+ expect(drained.blocked).toBeGreaterThan(0);
+ expect(drainedInputs).toEqual([]);
+ expect(await snapshot()).toEqual(before);
+ });
+ }
+ test('archived eligibility: existing same-target authorization and uncertain debits survive repeated refusal', async () => {
+ const { snapshot } = await seedArchivedEligibility('null');
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions });
+ const debit = await authorizeMigrationBudget(engine, plan, 1);
+ await debit({ kind: 'embedding', operation: 'synthetic-prior-attempt', model, maxInputTokens: 100 });
+ const before = await snapshot();
+ const config = await engine.executeRaw('SELECT key,value FROM config ORDER BY key');
+ const budget = (await readMigrationState(engine)).state!.budget!;
+ expect(budget.requests).toBe(1);
+ expect(budget.debited_usd).toBeGreaterThan(0);
+ let calls = 0;
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('Refusal must precede transport'); });
+ for (let attempt = 0; attempt < 2; attempt++) {
+ expect((await flow()).status).toBe('apply_failed');
+ expect(calls).toBe(0);
+ expect((await readMigrationState(engine)).state!.budget).toEqual(budget);
+ expect(await engine.executeRaw('SELECT key,value FROM config ORDER BY key')).toEqual(config);
+ expect(await snapshot()).toEqual(before);
+ }
+ });
+ for (const scenario of ['current', 'null-hash']) {
+ test(`archived eligibility: ${scenario} retained control permits live migration without archived smoke input`, async () => {
+ const { snapshot } = await seedArchivedEligibility(scenario);
+ const before = await snapshot();
+ const inputs: string[] = [];
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ inputs.push(...values);
+ return { values, warnings: [], embeddings: values.map(() => Array.from({ length: dimensions }, (_, i) => (i + 1) / 10)), usage: { tokens: 8 } };
+ });
+ expect((await flow()).status).toBe('completed');
+ expect(inputs.some(text => text.includes('Synthetic archived eligibility payload.'))).toBe(false);
+ expect(inputs.some(text => text.includes('Synthetic active eligibility payload.'))).toBe(true);
+ expect(await snapshot()).toEqual(before);
+ });
+ }
+ for (const operation of ['drift', 'raw-signature', 'guarded-signature', 'guarded-restamp', 'false-stamp', 'reconcile'] as const) {
+ for (const scoped of [false, true]) {
+ test(`archived eligibility: ${operation} preserves raw archived rows with ${scoped ? 'active source scope' : 'brain scope'}`, async () => {
+ const { snapshot } = await seedArchivedEligibility('current');
+ await engine.executeRaw(`UPDATE content_chunks SET embedding=$1::vector, model=$2,
+ embedded_at='2025-01-01'::timestamptz,embedded_text_hash=md5(chunk_text)`, ['[0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]', model]);
+ if (operation === 'drift') await engine.executeRaw("UPDATE content_chunks SET embedded_text_hash=md5('Synthetic obsolete content')");
+ if (['raw-signature', 'guarded-signature', 'false-stamp'].includes(operation)) await engine.executeRaw("UPDATE content_chunks SET model='old:model'");
+ if (operation !== 'drift' && operation !== 'false-stamp') await engine.executeRaw("UPDATE pages SET embedding_signature='old:model:8'");
+ const before = await snapshot();
+ const options = { signature: `${model}:${dimensions}`, ...(scoped && { sourceId: 'default' }) };
+ if (operation === 'drift') expect(await engine.invalidateContentDriftEmbeddings(options)).toBe(1);
+ if (operation === 'raw-signature') expect(await engine.invalidateStaleSignatureEmbeddings(options)).toBe(1);
+ if (operation === 'guarded-signature') expect(await invalidateStaleSignatureEmbeddingsGuarded(engine, options)).toBe(1);
+ if (operation === 'guarded-restamp') expect(await invalidateStaleSignatureEmbeddingsGuarded(engine, options)).toBe(0);
+ if (operation === 'false-stamp') {
+ expect((await countFalseStampedChunks(engine, model, dimensions)).pages).toBe(2);
+ expect(await clearFalseStampedSignatures(engine, model, dimensions)).toBe(1);
+ expect((await countFalseStampedChunks(engine, model, dimensions)).pages).toBe(1);
+ }
+ if (operation === 'reconcile') {
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions });
+ expect(await reconcilePageSignatures(engine, plan)).toBe(1);
+ }
+ expect(await snapshot()).toEqual(before);
+ const [active] = await engine.executeRaw<{ signature: string | null; embedded: boolean }>(`SELECT
+ p.embedding_signature AS signature,cc.embedding IS NOT NULL AS embedded FROM pages p
+ JOIN content_chunks cc ON cc.page_id=p.id WHERE p.source_id='default'`);
+ if (['drift', 'raw-signature', 'guarded-signature'].includes(operation)) expect(active.embedded).toBe(false);
+ if (['guarded-restamp', 'reconcile'].includes(operation)) expect(active.signature).toBe(options.signature);
+ if (operation === 'false-stamp') expect(active.signature).toBeNull();
+ });
+ }
+ }
+ test('archived eligibility: smoke verification never sends archived-only current content', async () => {
+ const { snapshot } = await seedArchivedEligibility('current');
+ const before = await snapshot();
+ let calls = 0;
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('No runnable smoke candidate'); });
+ expect((await verifySearchRoundTrip(engine)).status).toBe('skipped');
+ expect(calls).toBe(0);
+ expect(await snapshot()).toEqual(before);
+ });
+ test('archived eligibility: smoke rechecks a candidate archived after selection without dispatching it', async () => {
+ await seedArchivedEligibility('current');
+ await engine.executeRaw(`UPDATE content_chunks cc SET embedding=$1::vector,model=$2,
+ embedded_text_hash=md5(cc.chunk_text),embedded_at=now() FROM pages p WHERE p.id=cc.page_id AND p.source_id='default'`,
+ ['[0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]', model]);
+ const before = await engine.executeRaw('SELECT to_jsonb(p) AS page FROM pages p ORDER BY id');
+ const chunks = await engine.executeRaw('SELECT to_jsonb(cc) AS chunk FROM content_chunks cc ORDER BY id');
+ let selected = false, calls = 0;
+ const original = engine.executeRaw;
+ engine.executeRaw = async function(this: BrainEngine, sql, params) {
+ const rows = await original.call(this, sql, params);
+ if (!selected && sql.includes('ORDER BY cc.id DESC')) {
+ selected = true;
+ await original.call(this, "UPDATE sources SET archived=true WHERE id='default'");
+ }
+ return rows;
+ } as BrainEngine['executeRaw'];
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('Stale smoke candidate must not dispatch'); });
+ try {
+ expect((await verifySearchRoundTrip(engine)).status).toBe('skipped');
+ expect(selected).toBe(true);
+ expect(calls).toBe(0);
+ expect(await engine.executeRaw('SELECT to_jsonb(p) AS page FROM pages p ORDER BY id')).toEqual(before);
+ expect(await engine.executeRaw('SELECT to_jsonb(cc) AS chunk FROM content_chunks cc ORDER BY id')).toEqual(chunks);
+ } finally { engine.executeRaw = original; }
+ });
+ test('archived eligibility: active unsealed recovery progresses without repairing archived unsupported media', async () => {
+ const { sourceId, snapshot } = await seedArchivedEligibility('unsealed');
+ await engine.executeRaw("UPDATE pages SET page_kind='image' WHERE source_id=$1", [sourceId]);
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='default'");
+ const before = await snapshot();
+ const inputs: string[] = [];
+ __setEmbedTransportForTests(async ({ values }) => {
+ inputs.push(...values);
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ expect((await prepareEmbeddingProjections(engine)).blocked).toBe(2);
+ const result = await runEmbedCore(engine, { stale: true, quiet: true, catchUp: true });
+ expect(result.embedded).toBe(1);
+ expect(result.failures).toBe(1);
+ expect(inputs).toHaveLength(2);
+ expect(inputs.some(text => text.includes('Synthetic archived eligibility payload.'))).toBe(false);
+ expect((await prepareEmbeddingProjections(engine)).blocked).toBe(1);
+ expect(await snapshot()).toEqual(before);
+ });
+ for (const guarded of [false, true]) {
+ for (const includeNullSignature of [false, true]) {
+ test(`archived eligibility: ${guarded ? 'guarded' : 'raw'} NULL-signature invalidation with includeNull=${includeNullSignature}`, async () => {
+ const { snapshot } = await seedArchivedEligibility('current');
+ await engine.executeRaw('UPDATE pages SET embedding_signature=NULL');
+ await engine.executeRaw(`UPDATE content_chunks SET embedding=$1::vector,model='old:model'`, ['[0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]']);
+ const before = await snapshot();
+ const opts = { signature: `${model}:${dimensions}`, includeNullSignature };
+ expect(await (guarded ? invalidateStaleSignatureEmbeddingsGuarded(engine, opts) : engine.invalidateStaleSignatureEmbeddings(opts))).toBe(includeNullSignature ? 1 : 0);
+ expect(await snapshot()).toEqual(before);
+ expect(await engine.countStaleChunks({ signature: opts.signature, includeNullSignature: true })).toBe(2);
+ });
+ }
+ }
+ for (const path of ['plain', 'source', 'smoke'] as const) {
+ test(`archived eligibility: ${path} provider runs without a source lock and archive wins final installation`, async () => {
+ await seedArchivedEligibility('current');
+ if (path === 'smoke') await engine.executeRaw(`UPDATE content_chunks cc SET embedding=$1::vector,model=$2,
+ embedded_text_hash=md5(cc.chunk_text),embedded_at=now() FROM pages p WHERE p.id=cc.page_id AND p.source_id='default'`,
+ ['[0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]', model]);
+ const before = await engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE source_id='default'`);
+ let calls = 0;
+ const archive = async (values: string[]) => {
+ calls++;
+ expect(values.some(text => text.includes('Synthetic archived eligibility payload.'))).toBe(false);
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL statement_timeout='1s'");
+ await tx.executeRaw("UPDATE sources SET archived=true WHERE id='default'");
+ });
+ };
+ __setEmbedTransportForTests(async ({ values }) => {
+ await archive(values);
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ if (path === 'plain') {
+ const result = await runEmbedCore(engine, { stale: true, quiet: true, catchUp: true });
+ expect(result.embedded).toBe(0);
+ expect(result.failures).toBe(1);
+ expect(result.failure_samples.join(' ')).toContain('archived');
+ } else if (path === 'source') {
+ const result = await embedStaleForSource(engine, 'default', { embeddingSignature: `${model}:${dimensions}`,
+ embedFn: async texts => { await archive(texts); return texts.map(() => new Float32Array(dimensions).fill(0.1)); } });
+ expect(result.embedded).toBe(0);
+ expect(result.complete).toBe(false);
+ expect(result.blocked).toBe(1);
+ } else await verifySearchRoundTrip(engine);
+ expect(calls).toBe(1);
+ expect(await engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE source_id='default'`)).toEqual(before);
+ });
+ }
+ for (const archiveFirst of [true, false]) {
+ test.skipIf(kind !== 'postgres')(`archived eligibility: PostgreSQL serializes ${archiveFirst ? 'archive before invalidation' : 'invalidation before archive'}`, async () => {
+ const { sourceId, snapshot } = await seedArchivedEligibility('drift');
+ await engine.executeRaw('UPDATE sources SET archived=false WHERE id=$1', [sourceId]);
+ const before = await snapshot();
+ const other = new PostgresEngine();
+ await other.connect({ database_url: process.env.DATABASE_URL! });
+ const original = engine.executeRaw;
+ const started = Promise.withResolvers<number>();
+ let mutation: Promise<number> | undefined;
+ let archive: Promise<void> | undefined;
+ let blocked = false;
+ const observeWait = async (tx: BrainEngine, pid: number) => {
+ for (let attempt = 0; attempt < 100; attempt++) {
+ const [row] = await original.call(tx, 'SELECT EXISTS(SELECT 1 FROM pg_locks WHERE pid=$1 AND NOT granted) AS blocked', [pid]) as Array<{ blocked: boolean }>;
+ if (row.blocked) return true;
+ await Bun.sleep(10);
+ }
+ return false;
+ };
+ engine.executeRaw = async function(this: BrainEngine, sql, params) {
+ if (!sql.startsWith('SELECT id FROM sources WHERE ($1::text')) return original.call(this, sql, params);
+ if (archiveFirst) {
+ const [backend] = await original.call(this, 'SELECT pg_backend_pid() AS pid') as Array<{ pid: number }>;
+ started.resolve(backend.pid);
+ return original.call(this, sql, params);
+ }
+ const rows = await original.call(this, sql, params);
+ archive = other.transaction(async tx => {
+ const [backend] = await tx.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ started.resolve(backend.pid);
+ await tx.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ });
+ blocked = await observeWait(this, await started.promise);
+ return rows;
+ } as BrainEngine['executeRaw'];
+ try {
+ if (archiveFirst) {
+ await other.transaction(async tx => {
+ await tx.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ mutation = engine.invalidateContentDriftEmbeddings({ sourceId });
+ const pid = await Promise.race([started.promise, mutation.then(() => null)]);
+ expect(pid).not.toBeNull();
+ if (pid !== null) blocked = await observeWait(tx, pid);
+ });
+ } else mutation = engine.invalidateContentDriftEmbeddings({ sourceId });
+ expect(await mutation).toBe(archiveFirst ? 0 : 1);
+ await archive;
+ expect(blocked).toBe(true);
+ if (archiveFirst) expect(await snapshot()).toEqual(before);
+ else expect((await engine.executeRaw<{ present: boolean }>(`SELECT cc.embedding IS NOT NULL AS present
+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.source_id=$1`, [sourceId]))[0].present).toBe(false);
+ expect((await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]))[0].archived).toBe(true);
+ } finally {
+ await mutation?.catch(() => {});
+ await archive?.catch(() => {});
+ engine.executeRaw = original;
+ await other.disconnect();
+ }
+ }, 20_000);
+ }
+ });
+ describe('explicit archived admission', () => {
+ afterEach(async () => {
+ await engine.executeRaw('TRUNCATE pages CASCADE');
+ await engine.executeRaw("UPDATE sources SET archived=false WHERE id='default'");
+ });
+ async function seedExplicit(scenario: string) {
+ const sourceId = 'synthetic-explicit-archive';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT(id) DO UPDATE SET archived=false', [sourceId]);
+ for (const source of ['default', sourceId]) {
+ const slug = source === sourceId ? 'archived-target' : 'eligibility';
+ const text = source === sourceId ? 'Synthetic archived eligibility payload.' : 'Synthetic active eligibility payload.';
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic eligibility', compiled_truth: text }, { sourceId: source });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text,
+ ...(source === sourceId && scenario === 'current' && { embedding: new Float32Array(dimensions).fill(0.1) }) }], { sourceId: source });
+ }
+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);
+ if (scenario === 'unsealed') await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1', [sourceId]);
+ if (scenario === 'chunkless') await engine.executeRaw('DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE source_id=$1)', [sourceId]);
+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [sourceId]);
+ const snapshot = () => engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE p.source_id=$1 ORDER BY p.id`, [sourceId]);
+ return { sourceId, snapshot };
+ }
+ for (const route of ['slug', 'slugs', 'all'] as const) {
+ for (const scenario of ['null', 'current', 'unsealed', 'chunkless']) {
+ for (const scoped of [false, true]) {
+ test(`${route} refuses ${scenario} archived work ${scoped ? 'within its source' : 'without hiding active work'}`, async () => {
+ const { sourceId, snapshot } = await seedExplicit(scenario);
+ const before = await snapshot();
+ const inputs: string[] = [];
+ __setEmbedTransportForTests(async ({ values }) => {
+ inputs.push(...values);
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ const target = route === 'all' ? { all: true } : route === 'slugs'
+ ? { slugs: scoped ? ['archived-target'] : ['archived-target', 'eligibility'] } : { slug: 'archived-target' };
+ const result = await runEmbedCore(engine, { ...target, ...(scoped && { sourceId }), quiet: true });
+ expect(result.failures).toBe(1);
+ expect(result.failure_samples.join(' ')).toContain('archived');
+ expect(result.failure_samples.join(' ')).toContain('gbrain sources restore');
+ expect(result.failure_samples.join(' ')).not.toContain('Synthetic archived eligibility payload.');
+ const live = !scoped && route !== 'slug';
+ expect(result.embedded).toBe(live ? 1 : 0);
+ expect(inputs).toHaveLength(live ? 1 : 0);
+ if (live) expect(inputs[0]).toContain('Synthetic active eligibility payload.');
+ expect(await snapshot()).toEqual(before);
+ expect((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM content_chunks cc
+ JOIN pages p ON p.id=cc.page_id WHERE p.source_id='default' AND cc.embedding IS NOT NULL`))[0].n).toBe(live ? 1 : 0);
+ });
+ }
+ test(`${route} preserves dry-run counts and archived ${scenario} bytes`, async () => {
+ const { sourceId, snapshot } = await seedExplicit(scenario);
+ const before = await snapshot();
+ let calls = 0;
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('Dry run must not dispatch'); });
+ const target = route === 'all' ? { all: true } : route === 'slugs' ? { slugs: ['archived-target'] } : { slug: 'archived-target' };
+ const result = await runEmbedCore(engine, { ...target, sourceId, dryRun: true, quiet: true });
+ expect(result.failures).toBe(0);
+ expect(result.embedded).toBe(0);
+ expect(result.would_embed).toBe(route === 'all' ? (['null', 'current'].includes(scenario) ? 1 : 0) : scenario === 'current' ? 0 : 1);
+ expect(calls).toBe(0);
+ expect(await snapshot()).toEqual(before);
+ });
+ }
+ test(`${route} preserves active source-scoped admission with an identically named archive`, async () => {
+ const { snapshot } = await seedArchivedEligibility('null');
+ const before = await snapshot();
+ const inputs: string[] = [];
+ __setEmbedTransportForTests(async ({ values }) => {
+ inputs.push(...values);
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ const target = route === 'all' ? { all: true } : route === 'slugs' ? { slugs: ['eligibility'] } : { slug: 'eligibility' };
+ const result = await runEmbedCore(engine, { ...target, sourceId: 'default', quiet: true });
+ expect(result.embedded).toBe(1);
+ expect(result.failures).toBe(0);
+ expect(inputs).toHaveLength(1);
+ expect(inputs[0]).toContain('Synthetic active eligibility payload.');
+ expect(await snapshot()).toEqual(before);
+ });
+ test(`${route} reports an archive racing installation without holding provider locks`, async () => {
+ await seedArchivedEligibility('null');
+ const before = await engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE p.source_id='default'`);
+ let calls = 0;
+ __setEmbedTransportForTests(async ({ values }) => {
+ calls++;
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL statement_timeout='1s'");
+ await tx.executeRaw("UPDATE sources SET archived=true WHERE id='default'");
+ });
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ const target = route === 'all' ? { all: true } : route === 'slugs' ? { slugs: ['eligibility'] } : { slug: 'eligibility' };
+ const result = await runEmbedCore(engine, { ...target, sourceId: 'default', quiet: true });
+ expect(calls).toBe(1);
+ expect(result.embedded).toBe(0);
+ expect(result.failures).toBe(1);
+ expect(result.failure_samples.join(' ')).toContain('archived');
+ expect(await engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE p.source_id='default'`)).toEqual(before);
+ });
+ }
+ for (const route of ['slug', 'slugs'] as const) {
+ for (const chunkless of [false, true]) {
+ test(`${route} reports archive after ${chunkless ? 'chunkless' : 'sealed'} preparation before dispatch`, async () => {
+ await seedArchivedEligibility('null');
+ if (chunkless) await engine.executeRaw("DELETE FROM content_chunks WHERE page_id IN (SELECT id FROM pages WHERE source_id='default')");
+ const before = await engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE p.source_id='default'`);
+ const original = engine.transaction;
+ let archived = false, calls = 0;
+ engine.transaction = async function<T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ const result = await original.call(this, run) as T;
+ if (!archived && (result as { snapshot?: { page: { source_id: string } } })?.snapshot?.page.source_id === 'default') {
+ archived = true;
+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id='default'");
+ }
+ return result;
+ };
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('Prepared archived work must not dispatch'); });
+ try {
+ const target = route === 'slugs' ? { slugs: ['eligibility'] } : { slug: 'eligibility' };
+ const result = await runEmbedCore(engine, { ...target, sourceId: 'default', quiet: true });
+ expect(archived).toBe(true);
+ expect(calls).toBe(0);
+ expect(result.embedded).toBe(0);
+ expect(result.failures).toBe(1);
+ expect(result.failure_samples.join(' ')).toContain('archived');
+ expect(await engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE p.source_id='default'`)).toEqual(before);
+ } finally { engine.transaction = original; }
+ });
+ }
+ }
+ });
+ async function seedLegacyContentDrift() {
+ const otherSource = 'synthetic-legacy-drift';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [otherSource]);
+ for (const sourceId of ['default', otherSource]) {
+ for (const slug of ['deleted-drift', 'live-drift', 'current-hash', 'null-hash', 'skipped-drift']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Synthetic ${slug}`,
+ ...(slug === 'skipped-drift' && { frontmatter: { embed_skip: true } }) }, { sourceId });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Synthetic ${slug}`,
+ embedding: new Float32Array(dimensions).fill(0.1) }], { sourceId });
+ }
+ await engine.softDeletePages(['deleted-drift'], { sourceId });
+ }
+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);
+ await engine.executeRaw(`UPDATE content_chunks cc SET model=$1,embedded_at='2025-01-01'::timestamptz,
+ embedded_text_hash=CASE p.slug WHEN 'null-hash' THEN NULL WHEN 'current-hash' THEN md5(cc.chunk_text)
+ ELSE md5('Synthetic prior legacy content') END FROM pages p WHERE p.id=cc.page_id`, [model]);
+ return () => engine.executeRaw<{ source_id: string; slug: string; chunk: Record<string, unknown> }>(`SELECT
+ p.source_id,p.slug,to_jsonb(cc) AS chunk FROM content_chunks cc JOIN pages p ON p.id=cc.page_id ORDER BY p.source_id,p.slug`);
+ }
+ for (const sourceId of [undefined, 'default']) {
+ test(`deleted legacy drift: ${sourceId ? 'scoped' : 'unscoped'} invalidation preserves retained bytes and grandfathered controls`, async () => {
+ try {
+ const snapshot = await seedLegacyContentDrift();
+ const before = await snapshot();
+ expect(await engine.invalidateContentDriftEmbeddings({ sourceId: 'missing-source' })).toBe(0);
+ expect(await snapshot()).toEqual(before);
+ const invalidated = await engine.invalidateContentDriftEmbeddings({ sourceId });
+ const after = await snapshot();
+ const protectedRow = (row: typeof before[number]) => row.slug !== 'live-drift' || sourceId !== undefined && row.source_id !== sourceId;
+ expect(after.filter(protectedRow)).toEqual(before.filter(protectedRow));
+ expect(invalidated).toBe(sourceId === undefined ? 2 : 1);
+ for (const row of after.filter(row => !protectedRow(row))) {
+ expect(row.chunk.embedding).toBeNull();
+ expect(row.chunk.embedded_text_hash).toBeNull();
+ expect(row.chunk.embedded_at).toBeNull();
+ }
+ expect(await engine.invalidateContentDriftEmbeddings({ sourceId })).toBe(0);
+ } finally { await engine.executeRaw('TRUNCATE pages CASCADE'); }
+ });
+ }
+ test('deleted legacy drift: same-width migration completes and preserves deleted vector hash and timestamp', async () => {
+ try {
+ const snapshot = await seedLegacyContentDrift();
+ const before = (await snapshot()).filter(row => row.slug === 'deleted-drift');
+ const result = await flow(1, 'openai:text-embedding-3-large');
+ expect(result.status).toBe('completed');
+ expect((await snapshot()).filter(row => row.slug === 'deleted-drift')).toEqual(before);
+ expect(await engine.countStaleChunks({ signature: `openai:text-embedding-3-large:${dimensions}`, includeNullSignature: true })).toBe(0);
+ const live = await engine.executeRaw<{ correct: boolean }>(`SELECT cc.embedding IS NOT NULL
+ AND cc.embedded_text_hash=md5(cc.chunk_text) AND cc.model=$1 AS correct
+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.slug='live-drift'`, ['openai:text-embedding-3-large']);
+ expect(live).toEqual([{ correct: true }, { correct: true }]);
+ } finally { await engine.executeRaw('TRUNCATE pages CASCADE'); }
+ });
+ for (const retained of [true, false]) {
+ const label = retained ? 'retained vector' : 'NULL vector';
+ const otherSource = 'synthetic-deleted-parity';
+ const liveTexts = ['Synthetic live-a 0', 'Synthetic live-a 1', 'Synthetic live-b 0'];
+ async function seedDeletedRows() {
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING", [otherSource]);
+ for (const sourceId of ['default', otherSource]) {
+ for (const slug of ['live-a', 'deleted-target', 'live-b']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Synthetic ${slug}` }, { sourceId });
+ const texts = slug === 'live-a' ? liveTexts.slice(0, 2) : slug === 'live-b' ? liveTexts.slice(2) : ['Synthetic deleted target'];
+ await installFixtureChunks(engine, slug, texts.map((chunk_text, chunk_index) => ({
+ chunk_index, chunk_source: 'compiled_truth', chunk_text,
+ ...(slug === 'deleted-target' && retained && { embedding: new Float32Array(dimensions).fill(0.1) }),
+ })), { sourceId });
+ }
+ await engine.softDeletePages(['deleted-target'], { sourceId });
+ }
+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);
+ await engine.executeRaw("UPDATE pages SET updated_at=CASE slug WHEN 'live-a' THEN '2025-03-01'::timestamptz WHEN 'deleted-target' THEN '2025-02-01'::timestamptz ELSE '2025-01-01'::timestamptz END");
+ await engine.executeRaw('UPDATE content_chunks SET model=$1,embedded_text_hash=md5(chunk_text),embedded_at=now()', [model]);
+ return () => engine.executeRaw("SELECT to_jsonb(p) AS page,to_jsonb(cc) AS chunk FROM pages p JOIN content_chunks cc ON cc.page_id=p.id WHERE p.slug='deleted-target' ORDER BY p.source_id,cc.chunk_index");
+ }
+ test(`deleted completion ${label}: stale count and cost exclude only deleted rows`, async () => {
+ const snapshot = await seedDeletedRows();
+ const before = await snapshot();
+ for (const sourceId of [undefined, 'default', otherSource, 'missing-source']) {
+ const multiplier = sourceId === undefined ? 2 : sourceId === 'missing-source' ? 0 : 1;
+ for (const signature of [undefined, `${model}:${dimensions}`, `openai:text-embedding-3-large:${dimensions}`]) {
+ for (const includeNullSignature of [false, true]) {
+ const opts = { sourceId, signature, includeNullSignature };
+ expect(await engine.countStaleChunks(opts)).toBe(liveTexts.length * multiplier);
+ expect(await engine.sumStaleChunkChars(opts)).toBe(liveTexts.reduce((sum, text) => sum + text.length, 0) * multiplier);
+ }
+ }
+ }
+ expect(await snapshot()).toEqual(before);
+ });
+ test(`deleted completion ${label}: stale listing preserves all cursor branches and scopes`, async () => {
+ const snapshot = await seedDeletedRows();
+ const before = await snapshot();
+ for (const sourceId of [undefined, 'default', otherSource, 'missing-source']) {
+ for (const orderBy of ['page_id', 'updated_desc'] as const) {
+ const expected = await engine.executeRaw<{ page_id: number; chunk_index: number }>(`SELECT p.id AS page_id,cc.chunk_index
+ FROM pages p JOIN content_chunks cc ON cc.page_id=p.id WHERE p.slug IN ('live-a','live-b')
+ AND ($1::text IS NULL OR p.source_id=$1)
+ ORDER BY ${orderBy === 'updated_desc' ? 'p.updated_at DESC NULLS LAST,' : ''} p.id,cc.chunk_index`, [sourceId ?? null]);
+ const seen: Array<{ page_id: number; chunk_index: number }> = [];
+ let cursor: { afterPageId?: number; afterChunkIndex?: number; afterUpdatedAt?: string } = {};
+ for (let batch = 0; batch < 10; batch++) {
+ const rows = await engine.listStaleChunks({ sourceId, orderBy, batchSize: 1, ...cursor });
+ if (!rows.length) break;
+ const row = rows[0] as typeof rows[number] & { updated_at?: string | Date };
+ expect(row.slug).not.toBe('deleted-target');
+ seen.push({ page_id: row.page_id, chunk_index: row.chunk_index });
+ cursor = { afterPageId: row.page_id, afterChunkIndex: row.chunk_index,
+ ...(row.updated_at && { afterUpdatedAt: new Date(row.updated_at).toISOString() }) };
+ }
+ expect(seen).toEqual(expected);
+ }
+ }
+ expect(await snapshot()).toEqual(before);
+ });
+ test(`deleted completion ${label}: missing embedding health respects live and source scopes`, async () => {
+ const snapshot = await seedDeletedRows();
+ const before = await snapshot();
+ const scopes: Array<[{ sourceId?: string; sourceIds?: string[] }, number]> = [
+ [{}, 6], [{ sourceId: 'default' }, 3], [{ sourceId: otherSource }, 3],
+ [{ sourceIds: ['default', otherSource] }, 6], [{ sourceId: 'missing-source' }, 0], [{ sourceIds: [] }, 0],
+ ];
+ for (const [scope, expected] of scopes) {
+ expect((await engine.getHealth(scope)).missing_embeddings).toBe(expected);
+ }
+ expect(await snapshot()).toEqual(before);
+ });
+ test(`deleted completion ${label}: same-width migration completes without changing deleted bytes`, async () => {
+ const snapshot = await seedDeletedRows();
+ const before = await snapshot();
+ const result = await flow(1, 'openai:text-embedding-3-large');
+ expect(await snapshot()).toEqual(before);
+ expect(result.status).toBe('completed');
+ expect(await engine.countStaleChunks({ signature: `openai:text-embedding-3-large:${dimensions}`, includeNullSignature: true })).toBe(0);
+ expect(await engine.listStaleChunks()).toEqual([]);
+ expect((await engine.getHealth()).missing_embeddings).toBe(0);
+ expect(await engine.getConfig('embedding_model')).toBe('openai:text-embedding-3-large');
+ });
+ }
+ for (const widthChange of [false, true]) {
+ test(`retention mutation parity: imported sealed image migrates ${widthChange ? 'width' : 'model'} after stale embedding`, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'synthetic-image-retention-'));
+ const image = join(dir, 'pixel.png');
+ writeFileSync(image, Buffer.from('89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c6360000002000154a24f5d0000000049454e44ae426082', 'hex'));
+ try {
+ await importImageFile(engine, image, 'media/pixel.png', { noEmbed: true });
+ await runEmbedCore(engine, { stale: true, includeNullSignature: true, quiet: true });
+ const [before] = await engine.executeRaw<{ sealed: boolean; embedded: boolean }>(`SELECT
+ p.text_projection_revision=p.knowledge_revision AS sealed,cc.embedding IS NOT NULL AS embedded
+ FROM pages p JOIN content_chunks cc ON cc.page_id=p.id WHERE p.page_kind='image'`);
+ expect(before).toEqual({ sealed: true, embedded: true });
+ const targetDimensions = widthChange ? dimensions * 2 : dimensions;
+ const targetModel = widthChange ? model : 'openai:text-embedding-3-large';
+ __setEmbedTransportForTests(async ({ values }) => ({ values, warnings: [],
+ embeddings: values.map(() => Array(targetDimensions).fill(0.2)), usage: { tokens: 8 } }));
+ const result = await flow(1, targetModel, targetDimensions);
+ expect(result.status).toBe('completed');
+ const [after] = await engine.executeRaw<{ width: number; model: string; sealed: boolean }>(`SELECT
+ vector_dims(cc.embedding) AS width,cc.model,p.text_projection_revision=p.knowledge_revision AS sealed
+ FROM pages p JOIN content_chunks cc ON cc.page_id=p.id WHERE p.page_kind='image'`);
+ expect(after).toEqual({ width: targetDimensions, model: targetModel, sealed: true });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ await engine.executeRaw('TRUNCATE pages CASCADE');
+ await runSchemaTransition(engine, dimensions);
+ }
+ });
+ }
+ for (const scenario of ['same-target', 'resume-cleared', 'resume-first-clear', 'resume-first-width-clear', 'retarget-cleared-marker', 'pinned-fact-width'] as const) {
+ test(`retention mutation parity: archived companions ${scenario}`, async () => {
+ const archivedSource = 'synthetic-retained-companions';
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [archivedSource]);
+ await engine.putPage('retained-companion', { type: 'note', title: 'Synthetic retained companion', compiled_truth: '' }, { sourceId: archivedSource });
+ await installFixtureChunks(engine, 'retained-companion', [], { sourceId: archivedSource });
+ await engine.insertFact({ fact: 'Synthetic retained companion fact', source: 'synthetic', embedding_model: model,
+ embedding: new Float32Array(dimensions).fill(0.2) }, { source_id: archivedSource });
+ await engine.executeRaw(`INSERT INTO takes(page_id,row_num,claim,kind,holder,embedding)
+ SELECT id,0,'Synthetic retained take','take','self',
+ ('[' || array_to_string(array_fill(0.1::real, ARRAY[(SELECT atttypmod FROM pg_attribute WHERE attrelid='takes'::regclass AND attname='embedding')]), ',') || ']')::vector
+ FROM pages WHERE source_id=$1`, [archivedSource]);
+ await softDeleteSource(engine, archivedSource);
+ await engine.putPage('live-companion-work', { type: 'note', title: 'Synthetic live work', compiled_truth: 'Synthetic live page work' });
+ await installFixtureChunks(engine, 'live-companion-work', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic live page work' }]);
+ if (scenario !== 'same-target') await engine.setConfig('embedding_migration.state', JSON.stringify({
+ to_model: model, to_dims: dimensions, from_model: scenario === 'resume-first-width-clear' ? model : 'openai:text-embedding-3-large',
+ from_dims: scenario === 'resume-first-width-clear' ? dimensions * 2 : dimensions,
+ started_at: new Date().toISOString(), companion_vectors_invalidated: !scenario.startsWith('resume-first-'),
+ }));
+ if (scenario === 'pinned-fact-width') {
+ await engine.executeRaw('DROP INDEX IF EXISTS idx_facts_embedding_hnsw');
+ await engine.executeRaw(`ALTER TABLE facts ALTER COLUMN embedding TYPE vector(${dimensions * 2}) USING
+ ('[' || array_to_string(array_fill(0.2::real, ARRAY[${dimensions * 2}]), ',') || ']')::vector`);
+ }
+ const snapshot = () => Promise.all(['facts', 'takes'].map(table => engine.executeRaw(`SELECT to_jsonb(t) AS row FROM ${table} t ORDER BY to_jsonb(t)::text`)));
+ const before = await snapshot();
+ try {
+ const blocked = ['resume-first-clear', 'resume-first-width-clear', 'retarget-cleared-marker', 'pinned-fact-width'].includes(scenario);
+ const result = await flow(1, scenario === 'retarget-cleared-marker' ? 'openai:text-embedding-3-large' : model, dimensions, scenario === 'retarget-cleared-marker');
+ expect(await snapshot()).toEqual(before);
+ expect(result.status).toBe(blocked ? 'apply_failed' : 'completed');
+ if (blocked && result.status === 'apply_failed') expect(result.reason).toContain('retained_vectors_blocked');
+ if (!blocked) expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);
+ } finally {
+ await engine.executeRaw('UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id=$1', [archivedSource]);
+ await engine.executeRaw('TRUNCATE facts,pages CASCADE');
+ await runSchemaTransition(engine, dimensions);
+ }
+ });
+ }
+ test('retention mutation parity: target-stamped archived legacy alias is not invalidated', async () => {
+ await engine.putPage('legacy-archived', { type: 'note', title: 'Synthetic legacy alias', compiled_truth: 'Synthetic legacy alias' });
+ await installFixtureChunks(engine, 'legacy-archived', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic legacy alias', embedding: new Float32Array(dimensions).fill(0.1) }]);
+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);
+ await engine.executeRaw('UPDATE content_chunks SET model=$1,embedded_text_hash=md5(chunk_text)', [model.split(':')[1]]);
+ await softDeleteSource(engine, 'default');
+ const snapshot = () => engine.executeRaw('SELECT to_jsonb(cc) AS row FROM content_chunks cc');
+ const before = await snapshot();
+ try {
+ const result = await applyEmbeddingMigration(engine, await planEmbeddingMigration(engine, { to: model, dim: dimensions }));
+ expect(await snapshot()).toEqual(before);
+ expect(result.status).toBe('applied');
+ } finally { await engine.executeRaw("UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id='default'"); }
+ });
+ test('legacy unsealed and already-zero pages recover through canonical projection before embedding', async () => {
+ await engine.putPage('synthetic-recovery', { type: 'note', title: 'Synthetic recovery', compiled_truth: 'Canonical synthetic recovery content.' });
+ await engine.upsertChunks('synthetic-recovery', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Obsolete projection content', token_count: 4 }]);
+ expect(await readProjectionSnapshot(engine, 'synthetic-recovery', 'default')).toBeNull();
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions });
+ expect(plan.blocked_projection_pages).toBe(1);
+ expect((await applyEmbeddingMigration(engine, plan)).status).toBe('applied');
+ const ready = await readProjectionSnapshot(engine, 'synthetic-recovery', 'default');
+ expect(ready).not.toBeNull();
+ expect(ready!.chunks.map(c => c.chunk_text).join(' ')).toContain('Canonical synthetic recovery content.');
+ expect(ready!.chunks.map(c => c.chunk_text).join(' ')).not.toContain('Obsolete');
+ const result = await embedStaleForSource(engine, 'default', { embeddingSignature: `${model}:${dimensions}` });
+ expect(result.embedded).toBeGreaterThan(0);
+ expect(result.done).toBe(true);
+ expect(result.remaining).toBe(0);
+ });
+ test('same-width migration counts and repairs facts with unknown generation, but skips TTL and audit rows', async () => {
+ const fact = await engine.insertFact({ fact: 'Synthetic active claim', source: 'synthetic', embedding: new Float32Array(dimensions).fill(0.1) }, { source_id: 'default' });
+ await engine.insertFact({ fact: 'Synthetic expired claim', source: 'synthetic', valid_until: new Date(0) }, { source_id: 'default' });
+ await engine.insertFact({ fact: 'Synthetic audit row', source: AUDIT_ROW_SOURCES[0] }, { source_id: 'default' });
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions });
+ expect(plan.facts_to_embed).toBe(1);
+ expect((await verifyMigrationComplete(engine, { toModel: model, toDims: dimensions }, { envMatchesTarget: true })).complete).toBe(false);
+ const result = await embedStaleFacts(engine, { sourceId: 'default', yes: true, maxCostUsd: 1 });
+ expect(result).toMatchObject({ embedded: 1, remaining: 0, stopped: 'complete' });
+ const [row] = await engine.executeRaw<{ embedding_model: string; current: boolean }>('SELECT embedding_model, embedded_text_hash=md5(fact) AS current FROM facts WHERE id=$1', [fact.id]);
+ expect(row).toEqual({ embedding_model: model, current: true });
+ expect((await countStaleFactEmbeddings(engine, model, dimensions)).count).toBe(0);
+ });
+ test('fact changes during provider work cannot install a late vector', async () => {
+ const fact = await engine.insertFact({ fact: 'Synthetic concurrent claim', source: 'synthetic' }, { source_id: 'default' });
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ await engine.expireFact(fact.id);
+ return { values, warnings: [], embeddings: values.map(() => new Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ const result = await embedStaleFacts(engine, { sourceId: 'default', yes: true, maxCostUsd: 1 });
+ expect(result.embedded).toBe(0);
+ expect(result.stopped).toBe('failed');
+ expect((await engine.executeRaw<{ absent: boolean }>('SELECT embedding IS NULL AS absent FROM facts WHERE id=$1', [fact.id]))[0].absent).toBe(true);
+ });
+ test('nonfinite vectors never install and provider failure remains incomplete', async () => {
+ await engine.insertFact({ fact: 'Synthetic invalid-vector claim', source: 'synthetic' }, { source_id: 'default' });
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => ({ values, warnings: [], embeddings: values.map(() => new Array(dimensions).fill(NaN)), usage: { tokens: 8 } }));
+ const result = await embedStaleFacts(engine, { sourceId: 'default', yes: true, maxCostUsd: 1 });
+ expect(result).toMatchObject({ embedded: 0, remaining: 1, stopped: 'failed' });
+ });
+ test('duplicate cosine lookup withholds unknown and incompatible same-width generations', async () => {
+ for (const embedding_model of [undefined, 'other:model', model]) {
+ await engine.insertFact({ fact: `Synthetic ${embedding_model ?? 'unknown'} generation`, entity_slug: 'synthetic-entity', source: 'synthetic', embedding: new Float32Array(dimensions).fill(0.1), embedding_model }, { source_id: 'default' });
+ }
+ const found = await engine.findCandidateDuplicates('default', 'synthetic-entity', 'Synthetic query', { embedding: new Float32Array(dimensions).fill(0.1), embeddingModel: model });
+ expect(found).toHaveLength(1);
+ expect(found[0].embedding_model).toBe(model);
+ expect(await engine.findCandidateDuplicates('default', 'synthetic-entity', 'Synthetic query', { embedding: new Float32Array(dimensions).fill(0.1) })).toEqual([]);
+ });
+ test('authorization debits before dispatch and an interrupted request cannot reset on resume', async () => {
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions });
+ const debit = await authorizeMigrationBudget(engine, plan, 0.001);
+ await debit({ kind: 'embedding', operation: 'synthetic', model, maxInputTokens: 40_000 });
+ const before = (await readMigrationState(engine)).state!.budget!;
+ expect(before.requests).toBe(1);
+ expect(before.debited_usd).toBeGreaterThan(0);
+ const resume = await authorizeMigrationBudget(engine, plan, 0.001);
+ await expect(resume({ kind: 'embedding', operation: 'synthetic', model, maxInputTokens: 40_000 })).rejects.toThrow();
+ expect((await readMigrationState(engine)).state!.budget).toEqual(before);
+ });
+ test('facts-only brain completes through the full orchestrator and records authorization', async () => {
+ await engine.insertFact({ fact: 'Synthetic facts-only claim', source: 'synthetic' }, { source_id: 'default' });
+ const result = await flow();
+ expect(result.status).toBe('completed');
+ expect((await countStaleFactEmbeddings(engine, model, dimensions)).count).toBe(0);
+ const receipt = JSON.parse((await engine.getConfig('embedding_migration.completed'))!);
+ expect(receipt.budget.requests).toBeGreaterThan(0);
+ expect(receipt.budget.debited_usd).toBeGreaterThan(0);
+ });
+ test('provider preflight outage preserves blocked page vectors and durable uncertain debit', async () => {
+ await engine.putPage('synthetic-provider-outage', { type: 'note', title: 'Synthetic outage', compiled_truth: 'Synthetic content' });
+ await engine.upsertChunks('synthetic-provider-outage', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic old projection', token_count: 4, embedding: new Float32Array(dimensions).fill(0.1) }]);
+ const before = await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks ORDER BY id');
+ __setEmbedTransportForTests(async () => { throw new Error('Synthetic provider unavailable'); });
+ expect((await flow()).status).toBe('probe_failed');
+ expect(await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks ORDER BY id')).toEqual(before);
+ expect((await readMigrationState(engine)).state!.budget!.requests).toBe(1);
+ });
+ test('losing migration ownership during provider work refuses schema or fact installation', async () => {
+ await engine.insertFact({ fact: 'Synthetic lease-loss claim', source: 'synthetic' }, { source_id: 'default' });
+ __setEmbedTransportForTests(async ({ values }) => {
+ await engine.executeRaw("UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id='gbrain-embedding-migration'");
+ return { values, warnings: [], embeddings: values.map(() => new Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ expect((await flow()).status).toBe('probe_failed');
+ expect((await countStaleFactEmbeddings(engine, model, dimensions)).count).toBe(1);
+ await engine.executeRaw("DELETE FROM gbrain_cycle_locks WHERE id='gbrain-embedding-migration'");
+ });
+ test('source-enumeration failure never becomes an empty-brain migration', async () => {
+ const original = engine.listAllSources.bind(engine);
+ let calls = 0;
+ __setEmbedTransportForTests(async () => { calls++; throw new Error('No provider calls permitted'); });
+ engine.listAllSources = async () => { throw new Error('Synthetic census outage'); };
+ try { expect((await flow()).status).toBe('apply_failed'); }
+ finally { engine.listAllSources = original; }
+ expect(calls).toBe(0);
+ expect((await readMigrationState(engine)).state).toBeNull();
+ });
+ test('source creation during preflight stops the flow before destructive work', async () => {
+ __setEmbedTransportForTests(async ({ values }) => {
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('synthetic-new-source','Synthetic source')");
+ return { values, warnings: [], embeddings: values.map(() => new Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ try {
+ expect((await flow()).status).toBe('probe_failed');
+ expect(await engine.getConfig('embedding_migration.completed')).toBeNull();
+ } finally { await engine.executeRaw("DELETE FROM sources WHERE id='synthetic-new-source'"); }
+ });
+ test('lease loss during the fact phase cannot install or mark complete', async () => {
+ await engine.insertFact({ fact: 'Synthetic fact-phase claim', source: 'synthetic' }, { source_id: 'default' });
+ let calls = 0;
+ __setEmbedTransportForTests(async ({ values }) => {
+ if (++calls === 2) await engine.executeRaw("UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id='gbrain-embedding-migration'");
+ return { values, warnings: [], embeddings: values.map(() => new Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ try {
+ expect((await flow()).status).toBe('apply_failed');
+ expect(calls).toBe(2);
+ expect((await countStaleFactEmbeddings(engine, model, dimensions)).count).toBe(1);
+ expect(await engine.getConfig('embedding_migration.completed')).toBeNull();
+ } finally { await engine.executeRaw("DELETE FROM gbrain_cycle_locks WHERE id='gbrain-embedding-migration'"); }
+ });
+ test('uncertain attempts remain charged while unknown pricing refuses dispatch', async () => {
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions });
+ const debit = await authorizeMigrationBudget(engine, plan, 1, [], 'synthetic:unpriced');
+ let calls = 0;
+ for (const failure of ['Synthetic timeout', 'Synthetic 429']) {
+ await expect(withAIInvocationGuard(debit, () => invokeAI({ kind: 'embedding', operation: 'synthetic', model, maxInputTokens: 100 }, async () => {
+ calls++;
+ throw new Error(failure);
+ }, () => null))).rejects.toThrow(failure);
+ }
+ const before = (await readMigrationState(engine)).state!.budget!;
+ expect(before.requests).toBe(2);
+ expect(before.debited_usd).toBeGreaterThan(0);
+ await expect(withAIInvocationGuard(debit, () => invokeAI({ kind: 'rerank', operation: 'synthetic', model: 'synthetic:unpriced', maxInputTokens: 100 }, async () => { calls++; }, () => null))).rejects.toThrow();
+ expect(calls).toBe(2);
+ expect((await readMigrationState(engine)).state!.budget).toEqual(before);
+ });
+ test('actual page vector search withholds incompatible and unknown same-width generations', async () => {
+ for (const [slug, generation] of [['synthetic-current', model], ['synthetic-old', 'other:model'], ['synthetic-unknown', '']] as const) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: slug });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: slug, token_count: 4, embedding: new Float32Array(dimensions).fill(0.1) }]);
+ await engine.executeRaw('UPDATE content_chunks SET model=$1,embedded_text_hash=md5(chunk_text) WHERE page_id=(SELECT id FROM pages WHERE source_id=$2 AND slug=$3)', [generation, 'default', slug]);
+ }
+ const query = () => engine.searchVector(new Float32Array(dimensions).fill(0.1), {
+ sourceId: 'default', embeddingColumn: { name: 'embedding', type: 'vector', dimensions, embeddingModel: model },
+ });
+ expect((await query()).map(row => row.slug)).toEqual(['synthetic-current']);
+ await engine.setConfig('embedding_migration.state', JSON.stringify({ to_model: model, to_dims: dimensions }));
+ expect((await query()).map(row => row.slug)).toEqual(['synthetic-current']);
+ });
+ test('unsupported projection refuses invalidation while preserving existing vectors', async () => {
+ await engine.putPage('synthetic-media', { type: 'note', title: 'Synthetic media', compiled_truth: 'Synthetic retained content' });
+ await engine.upsertChunks('synthetic-media', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic retained projection', token_count: 4, embedding: new Float32Array(dimensions).fill(0.1) }]);
+ await engine.executeRaw("UPDATE pages SET page_kind='image' WHERE source_id='default' AND slug='synthetic-media'");
+ const before = await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks ORDER BY id');
+ const result = await applyEmbeddingMigration(engine, await planEmbeddingMigration(engine, { to: model, dim: dimensions }));
+ expect(result.status).toBe('failed');
+ expect(await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks ORDER BY id')).toEqual(before);
+ });
+ test('a text migration does not suppress the independent image vector column', async () => {
+ await engine.putPage('synthetic-image-vector', { type: 'note', title: 'Synthetic image vector', compiled_truth: 'Synthetic image-vector holder' });
+ await installFixtureChunks(engine, 'synthetic-image-vector', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic image-vector holder', token_count: 4 }]);
+ const [column] = await engine.executeRaw<{ dimensions: number }>("SELECT atttypmod AS dimensions FROM pg_attribute WHERE attrelid='content_chunks'::regclass AND attname='embedding_image'");
+ const vector = new Float32Array(column.dimensions).fill(0.1);
+ await engine.executeRaw("UPDATE content_chunks SET embedding_image=$1::vector,modality='image'", [`[${Array.from(vector).join(',')}]`]);
+ await engine.setConfig('embedding_migration.state', JSON.stringify({ to_model: model, to_dims: dimensions }));
+ const found = await engine.searchVector(vector, { sourceId: 'default', embeddingColumn: { name: 'embedding_image', type: 'vector', dimensions: column.dimensions, embeddingModel: 'synthetic:image-model' } });
+ expect(found.map(row => row.slug)).toEqual(['synthetic-image-vector']);
+ });
+ test('archived unsealed projections refuse a destructive transition without losing vectors', async () => {
+ await engine.putPage('synthetic-archived', { type: 'note', title: 'Synthetic archived', compiled_truth: 'Synthetic archived content' });
+ await engine.upsertChunks('synthetic-archived', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic archived projection', embedding: new Float32Array(dimensions).fill(0.1) }]);
+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id='default'");
+ const before = await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks');
+ try {
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions * 2 });
+ expect((await applyEmbeddingMigration(engine, plan)).status).toBe('failed');
+ expect(await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks')).toEqual(before);
+ } finally { await engine.executeRaw("UPDATE sources SET archived=false WHERE id='default'"); }
+ });
+ for (const scenario of ['archived-page-same-width', 'archived-page-width', 'archived-fact-same-width', 'archived-fact-width', 'skip-page-width', 'media-page-width', 'deleted-page-width']) {
+ test(`retained vector refusal: ${scenario}`, async () => {
+ const archived = scenario.startsWith('archived');
+ const factOnly = scenario.includes('fact');
+ const targetDim = scenario.endsWith('same-width') ? dimensions : dimensions * 2;
+ if (factOnly) {
+ await engine.insertFact({ fact: 'Synthetic retained archived claim', source: 'synthetic', embedding: new Float32Array(dimensions).fill(0.2) }, { source_id: 'default' });
+ } else {
+ await engine.putPage('synthetic-retained', { type: 'note', title: 'Synthetic retained', compiled_truth: 'Synthetic retained content',
+ ...(scenario.startsWith('skip') && { frontmatter: { embed_skip: true } }) });
+ if (scenario.startsWith('media')) await engine.executeRaw("UPDATE pages SET page_kind='image'");
+ await installFixtureChunks(engine, 'synthetic-retained', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic retained content', embedding: new Float32Array(dimensions).fill(0.1) }]);
+ await engine.executeRaw('UPDATE pages SET embedding_signature=$1', [`${model}:${dimensions}`]);
+ await engine.executeRaw('UPDATE content_chunks SET model=$1,embedded_text_hash=md5(chunk_text)', [model]);
+ expect((await engine.executeRaw('SELECT id FROM pages WHERE text_projection_revision=knowledge_revision')).length).toBe(1);
+ if (scenario.startsWith('media')) await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL');
+ if (scenario.startsWith('deleted')) await engine.executeRaw('UPDATE pages SET deleted_at=now()');
+ }
+ if (archived) await engine.executeRaw("UPDATE sources SET archived=true WHERE id='default'");
+ const snapshot = async () => Promise.all(['pages', 'content_chunks', 'facts', 'config'].map(table =>
+ engine.executeRaw(`SELECT to_jsonb(t) AS row FROM ${table} t ORDER BY to_jsonb(t)::text`)));
+ try {
+ expect((await prepareEmbeddingProjections(engine)).blocked).toBe(scenario.startsWith('media') ? 1 : 0);
+ if (factOnly) expect((await countStaleFactEmbeddings(engine, 'openai:text-embedding-3-large', targetDim)).count).toBe(0);
+ const before = await snapshot();
+ let fileWrites = 0;
+ const result = await applyEmbeddingMigration(engine,
+ await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-large', dim: targetDim }),
+ { persistConfig: () => { fileWrites++; } });
+ expect(await snapshot()).toEqual(before);
+ expect(fileWrites).toBe(0);
+ expect(result.status).toBe('failed');
+ if (result.status === 'failed') expect(result.reason).toContain('retained_vectors_blocked');
+ expect((await readContentChunksEmbeddingDim(engine)).dims).toBe(dimensions);
+ } finally {
+ await engine.executeRaw("UPDATE sources SET archived=false WHERE id='default'");
+ await engine.executeRaw('TRUNCATE facts, pages CASCADE');
+ await runSchemaTransition(engine, dimensions);
+ }
+ });
+ }
+ for (const phase of ['after-plan', 'before-ddl', 'before-companions']) {
+ test(`retained vector refusal after normal archive ${phase}`, async () => {
+ const factOnly = phase === 'before-companions';
+ if (factOnly) await engine.insertFact({ fact: 'Synthetic late archive fact', source: 'synthetic', embedding: new Float32Array(dimensions).fill(0.2) }, { source_id: 'default' });
+ else {
+ await engine.putPage('late-archive', { type: 'note', title: 'Synthetic late archive', compiled_truth: 'Synthetic late archive' });
+ await installFixtureChunks(engine, 'late-archive', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic late archive', embedding: new Float32Array(dimensions).fill(0.1) }]);
+ }
+ const plan = await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-large', dim: factOnly ? dimensions : dimensions * 2 });
+ const vectors = async () => Promise.all([
+ engine.executeRaw('SELECT embedding::text,model,embedded_text_hash FROM content_chunks ORDER BY id'),
+ engine.executeRaw('SELECT embedding::text,embedding_model,embedded_text_hash FROM facts ORDER BY id'),
+ engine.executeRaw("SELECT key,value FROM config WHERE key IN ('embedding_model','embedding_dimensions') ORDER BY key"),
+ ]);
+ const before = await vectors();
+ const identity = await engine.executeRaw("SELECT incarnation::text FROM sources WHERE id='default'");
+ let archived = false, fileWrites = 0;
+ const archive = async () => { expect(await softDeleteSource(engine, 'default')).not.toBeNull(); archived = true; };
+ const raced = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw' && phase === 'before-ddl') return async (sql: string, params?: unknown[]) => {
+ if (!archived && sql.includes('format_type') && await target.getConfig('embedding_migration.state')) await archive();
+ return target.executeRaw(sql, params);
+ };
+ if (key === 'transaction' && phase === 'before-companions') return async (fn: (tx: BrainEngine) => Promise<unknown>) => {
+ let invalidation = false;
+ const observe = (tx: BrainEngine): BrainEngine => new Proxy(tx, { get(inner, field) {
+ if (field === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (sql.includes('UPDATE content_chunks cc')) invalidation = true;
+ return inner.executeRaw(sql, params);
+ };
+ if (field === 'transaction') return (nested: (tx: BrainEngine) => Promise<unknown>) =>
+ inner.transaction(tx => nested(observe(tx)));
+ const value = Reflect.get(inner, field); return typeof value === 'function' ? value.bind(inner) : value;
+ } });
+ const result = await target.transaction(tx => fn(observe(tx)));
+ if (invalidation && !archived) await archive();
+ return result;
+ };
+ const value = Reflect.get(target, key); return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ try {
+ if (phase === 'after-plan') await archive();
+ const result = await applyEmbeddingMigration(raced, plan, { persistConfig: () => { fileWrites++; } });
+ expect(archived).toBe(true);
+ expect(await vectors()).toEqual(before);
+ expect(await engine.executeRaw("SELECT incarnation::text FROM sources WHERE id='default'")).toEqual(identity);
+ expect(result).toMatchObject({ status: 'failed' });
+ if (result.status === 'failed') expect(result.reason).toContain('retained_vectors_blocked');
+ expect(fileWrites).toBe(0);
+ expect((await readContentChunksEmbeddingDim(engine)).dims).toBe(dimensions);
+ } finally { await engine.executeRaw("UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id='default'"); }
+ });
+ }
+ for (const phase of ['before-provider', 'during-provider']) {
+ test(`retained vector flow refusal ${phase} preserves vectors and configuration`, async () => {
+ await engine.insertFact({ fact: 'Synthetic guarded flow fact', source: 'synthetic', embedding: new Float32Array(dimensions).fill(0.2) }, { source_id: 'default' });
+ const before = await engine.executeRaw('SELECT to_jsonb(f) AS row FROM facts f');
+ const beforeConfig = await engine.executeRaw('SELECT key,value FROM config ORDER BY key');
+ if (phase === 'before-provider') await softDeleteSource(engine, 'default');
+ let calls = 0;
+ __setEmbedTransportForTests(async ({ values }) => {
+ calls++;
+ if (phase === 'during-provider') await softDeleteSource(engine, 'default');
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ try {
+ const result = await flow(1, 'openai:text-embedding-3-large');
+ expect(result.status).toBe(phase === 'before-provider' ? 'apply_failed' : 'probe_failed');
+ expect(calls).toBe(phase === 'before-provider' ? 0 : 1);
+ expect(await engine.executeRaw('SELECT to_jsonb(f) AS row FROM facts f')).toEqual(before);
+ expect(await engine.getConfig('embedding_model')).toBe(model);
+ expect(await engine.getConfig('embedding_dimensions')).toBe(String(dimensions));
+ if (phase === 'before-provider') expect(await engine.executeRaw('SELECT key,value FROM config ORDER BY key')).toEqual(beforeConfig);
+ else expect((await readMigrationState(engine)).state?.budget?.requests).toBe(1);
+ } finally { await engine.executeRaw("UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id='default'"); }
+ });
+ }
+ test('retained vector guard preserves archived takes and refuses destructive companion changes', async () => {
+ await engine.putPage('retained-take', { type: 'note', title: 'Synthetic retained take', compiled_truth: '' });
+ await engine.executeRaw(`INSERT INTO takes(page_id,row_num,claim,kind,holder,embedding)
+ SELECT id,0,'Synthetic retained take','take','self',
+ ('[' || array_to_string(array_fill(0.1::real, ARRAY[(SELECT atttypmod FROM pg_attribute WHERE attrelid='takes'::regclass AND attname='embedding')]), ',') || ']')::vector
+ FROM pages WHERE slug='retained-take' AND source_id='default'`);
+ await softDeleteSource(engine, 'default');
+ const before = await engine.executeRaw('SELECT embedding::text FROM takes');
+ try {
+ const result = await applyEmbeddingMigration(engine, await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-large', dim: dimensions * 2 }));
+ expect(result).toMatchObject({ status: 'failed' });
+ if (result.status === 'failed') expect(result.reason).toContain('retained_vectors_blocked');
+ expect(await engine.executeRaw('SELECT embedding::text FROM takes')).toEqual(before);
+ expect((await readContentChunksEmbeddingDim(engine)).dims).toBe(dimensions);
+ await runSchemaTransition(engine, dimensions * 2);
+ expect(await engine.executeRaw('SELECT embedding::text FROM takes')).toEqual(before);
+ expect((await readContentChunksEmbeddingDim(engine)).dims).toBe(dimensions * 2);
+ } finally {
+ await engine.executeRaw("UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id='default'");
+ await runSchemaTransition(engine, dimensions);
+ }
+ });
+ test('retained vector guard distinguishes intentionally retired fact vectors', async () => {
+ for (const [fact, source, valid_until] of [['Synthetic expired', 'synthetic', new Date(0)], ['Synthetic audit', AUDIT_ROW_SOURCES[0], undefined], ['Synthetic withdrawn', 'synthetic', undefined]] as const) {
+ await engine.insertFact({ fact, source, valid_until, embedding: new Float32Array(dimensions).fill(0.2) }, { source_id: 'default' });
+ }
+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) SELECT source_id,visibility,gbrain_fact_fingerprint(fact) FROM facts WHERE fact='Synthetic withdrawn'");
+ await softDeleteSource(engine, 'default');
+ try {
+ const result = await applyEmbeddingMigration(engine, await planEmbeddingMigration(engine, { to: 'openai:text-embedding-3-large', dim: dimensions * 2 }));
+ expect(result.status).toBe('applied');
+ expect((await engine.executeRaw('SELECT id FROM facts WHERE embedding IS NOT NULL')).length).toBe(0);
+ expect((await countStaleFactEmbeddings(engine, 'openai:text-embedding-3-large', dimensions * 2)).count).toBe(0);
+ } finally {
+ await engine.executeRaw("UPDATE sources SET archived=false,archived_at=NULL,archive_expires_at=NULL WHERE id='default'");
+ await engine.executeRaw('TRUNCATE facts, fact_withdrawals, pages CASCADE');
+ await runSchemaTransition(engine, dimensions);
+ }
+ });
+ test('retained vector guard fails closed on unreadable registry or unknown counts', async () => {
+ for (const failure of ['registry', 'catalog', 'dimension', 'census', 'missing-key', 'negative', 'nonnumeric']) {
+ const before = await engine.executeRaw('SELECT key,value FROM config ORDER BY key');
+ await expect(engine.transaction(tx => assertRetainedEmbeddingRebuildability(new Proxy(tx, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ if (failure === 'registry' && sql.includes("SELECT key,value FROM config WHERE key IN")) throw new Error('Synthetic registry failure');
+ if (failure === 'catalog' && sql.includes("FROM pg_attribute WHERE attrelid='content_chunks'")) return [];
+ if (failure === 'dimension' && sql.includes("FROM pg_attribute WHERE attrelid='content_chunks'")) return [{ name: 'page_id', type: 'integer' }, { name: 'embedding', type: 'text' }];
+ if (failure === 'census' && sql.includes('AS pages')) return [];
+ if (failure === 'missing-key' && sql.includes('AS pages')) return [{ pages: 0, facts: 0, wrong: 0 }];
+ if (failure === 'negative' && sql.includes('AS pages')) return [{ pages: -1, facts: 0, takes: 0 }];
+ if (failure === 'nonnumeric' && sql.includes('AS pages')) return [{ pages: '0', facts: 0, takes: 0 }];
+ return target.executeRaw(sql, params);
+ };
+ const value = Reflect.get(target, key); return typeof value === 'function' ? value.bind(target) : value;
+ } }), dimensions, model))).rejects.toThrow('retained_vector_check_failed');
+ expect(await engine.executeRaw('SELECT key,value FROM config ORDER BY key')).toEqual(before);
+ }
+ });
+ test('cursor EOF does not masquerade as completed work after a provider failure', async () => {
+ await engine.putPage('synthetic-failed', { type: 'note', title: 'Synthetic failed', compiled_truth: 'Synthetic pending content' });
+ await installFixtureChunks(engine, 'synthetic-failed', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic pending content', token_count: 4 }]);
+ const result = await embedStaleForSource(engine, 'default', { embedFn: async () => { throw new Error('Synthetic provider failure'); } });
+ expect(result).toMatchObject({ done: true, complete: false, embedded: 0, failures: 1, remaining: 1 });
+ });
+ test('a lowered authorization never silently reuses the previous higher cap', async () => {
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: dimensions });
+ const debit = await authorizeMigrationBudget(engine, plan, 1);
+ await debit({ kind: 'embedding', operation: 'synthetic', model, maxInputTokens: 100 });
+ const before = (await readMigrationState(engine)).state!.budget!.debited_usd;
+ const paused = await authorizeMigrationBudget(engine, plan, 0);
+ await expect(paused({ kind: 'embedding', operation: 'synthetic', model, maxInputTokens: 100 })).rejects.toThrow();
+ expect((await readMigrationState(engine)).state!.budget).toMatchObject({ max_cost_usd: 0, debited_usd: before, requests: 1 });
+ });
+ test('fresh cycle facts retain their captured vector identity and enter dedup without repair', async () => {
+ const slug = 'people/synthetic-cycle-identity';
+ await engine.putPage(slug, { type: 'person', title: 'Synthetic cycle identity', compiled_truth: renderFactsTable([{
+ rowNum: 1, claim: 'Synthetic cycle-produced claim', kind: 'fact', confidence: 1,
+ visibility: 'world', notability: 'medium', source: 'synthetic', active: true,
+ }]) });
+ let calls = 0;
+ const vector = new Float32Array(dimensions).fill(0.1);
+ __setEmbedTransportForTests(async ({ values, model: provider, providerOptions }) => {
+ calls++;
+ expect(typeof provider === 'string' ? provider : provider.modelId).toBe('text-embedding-3-small');
+ expect(providerOptions?.openai?.dimensions).toBe(dimensions);
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dimensions * 2, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ return { values, warnings: [], embeddings: values.map(() => Array.from(vector)), usage: { tokens: 8 } };
+ });
+ const result = await runExtractFacts(engine, { slugs: [slug], sourceId: 'default' });
+ expect(result.factsInserted).toBe(1);
+ expect(result.warnings).toEqual([]);
+ expect(calls).toBe(1);
+ const [fact] = await engine.executeRaw<{ present: boolean; embedding_model: string; current: boolean; dimensions: number }>(
+ 'SELECT embedding IS NOT NULL AS present,embedding_model,embedded_text_hash=md5(fact) AS current,vector_dims(embedding) AS dimensions FROM facts WHERE source_id=$1 AND entity_slug=$2', ['default', slug]);
+ expect(fact).toEqual({ present: true, embedding_model: model, current: true, dimensions });
+ expect((await countStaleFactEmbeddings(engine, model, dimensions)).count).toBe(0);
+ expect(await engine.findCandidateDuplicates('default', slug, 'Synthetic query', { embedding: vector, embeddingModel: model })).toHaveLength(1);
+ });
+ test('stale projection recovery preserves grandfathered vectors until explicitly widened', async () => {
+ const slug = 'synthetic-grandfathered-projection';
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic grandfathered projection', compiled_truth: 'Synthetic current canonical body' });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic legacy projected body', embedding: new Float32Array(dimensions).fill(0.1) }]);
+ const before = await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks');
+ let calls = 0;
+ __setEmbedTransportForTests(async ({ values }) => {
+ calls++;
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ expect((await runEmbedCore(engine, { stale: true, quiet: true })).embedded).toBe(0);
+ expect(calls).toBe(0);
+ expect(await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks')).toEqual(before);
+ expect(await readProjectionSnapshot(engine, slug, 'default')).toBeNull();
+ expect((await runEmbedCore(engine, { stale: true, quiet: true, includeNullSignature: true })).embedded).toBeGreaterThan(0);
+ expect(calls).toBeGreaterThan(0);
+ expect(await readProjectionSnapshot(engine, slug, 'default')).not.toBeNull();
+ });
+ test.each(['before preflight', 'during probe'] as const)('stale projection recovery stops when aborted %s', async phase => {
+ const slug = 'synthetic-aborted-projection';
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic aborted projection', compiled_truth: 'Synthetic current canonical body' });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic pending projected body' }]);
+ const before = await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks');
+ const jobs = await engine.executeRaw('SELECT * FROM page_projection_jobs');
+ const controller = new AbortController();
+ let calls = 0;
+ if (phase === 'before preflight') controller.abort();
+ __setEmbedTransportForTests(async ({ values }) => {
+ calls++;
+ controller.abort();
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ const result = await runEmbedCore(engine, { stale: true, quiet: true, signal: controller.signal });
+ expect(result.embedded).toBe(0);
+ expect(result.failures).toBe(0);
+ expect(calls).toBe(phase === 'before preflight' ? 0 : 1);
+ expect(await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks')).toEqual(before);
+ expect(await engine.executeRaw('SELECT * FROM page_projection_jobs')).toEqual(jobs);
+ expect(await readProjectionSnapshot(engine, slug, 'default')).toBeNull();
+ });
+ test.each(['stale', 'migration', 'standalone'] as const)('one %s invocation repairs and embeds more than one bounded projection batch', async mode => {
+ for (let i = 0; i < 103; i++) {
+ const slug = `synthetic-multi-batch-${i}`;
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic recovery batch', compiled_truth: `Synthetic canonical batch body ${i}` });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Synthetic obsolete projected body ${i}` }]);
+ }
+ if (mode === 'stale') {
+ const result = await runEmbedCore(engine, { stale: true, quiet: true, catchUp: true });
+ expect(result.embedded).toBe(103);
+ expect(result.failures).toBe(0);
+ } else if (mode === 'migration') {
+ expect((await flow()).status).toBe('completed');
+ } else {
+ const result = await embedStaleForSource(engine, 'default', { embeddingSignature: `${model}:${dimensions}` });
+ expect(result.embedded).toBe(103);
+ expect(result.complete).toBe(true);
+ }
+ expect(await prepareEmbeddingProjections(engine)).toEqual({ rebuilt: 0, blocked: 0 });
+ expect(await engine.countStaleChunks()).toBe(0);
+ }, 60_000);
+ test.each([false, true])('standalone recovery refuses grandfathered paid work with signature=%s', async withSignature => {
+ const slug = 'synthetic-standalone-grandfather';
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic legacy page', compiled_truth: 'Synthetic current body' });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic prior body', embedding: new Float32Array(dimensions).fill(0.1) }]);
+ const before = await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks');
+ let calls = 0;
+ const result = await embedStaleForSource(engine, 'default', {
+ embeddingSignature: withSignature ? `${model}:${dimensions}` : undefined,
+ embedFn: async texts => { calls++; return texts.map(() => new Float32Array(dimensions).fill(0.1)); },
+ });
+ expect(result.embedded).toBe(0);
+ expect(calls).toBe(0);
+ expect(await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks')).toEqual(before);
+ expect(await readProjectionSnapshot(engine, slug, 'default')).toBeNull();
+ });
+ test.each(['before preflight', 'during probe', 'expired deadline'] as const)('standalone recovery honors cancellation %s', async phase => {
+ const slug = 'synthetic-standalone-abort';
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic pending page', compiled_truth: 'Synthetic current body' });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic prior body' }]);
+ const before = await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks');
+ const jobs = await engine.executeRaw('SELECT * FROM page_projection_jobs');
+ const controller = new AbortController();
+ if (phase === 'before preflight') controller.abort();
+ const executeRaw = engine.executeRaw;
+ let queries = 0;
+ let calls = 0;
+ engine.executeRaw = async function (...args: Parameters<BrainEngine['executeRaw']>) {
+ queries++;
+ return executeRaw.apply(this, args) as never;
+ };
+ try {
+ const result = await embedStaleForSource(engine, 'default', {
+ embeddingSignature: `${model}:${dimensions}`, signal: controller.signal,
+ deadline: phase === 'expired deadline' ? Date.now() - 1 : undefined,
+ embedFn: async texts => { calls++; controller.abort(); return texts.map(() => new Float32Array(dimensions).fill(0.1)); },
+ });
+ expect(result.aborted).toBe(true);
+ expect(result.embedded).toBe(0);
+ expect(calls).toBe(phase === 'during probe' ? 1 : 0);
+ if (phase !== 'during probe') expect(queries).toBe(0);
+ } finally { engine.executeRaw = executeRaw; }
+ expect(await engine.executeRaw('SELECT embedding::text,chunk_text FROM content_chunks')).toEqual(before);
+ expect(await engine.executeRaw('SELECT * FROM page_projection_jobs')).toEqual(jobs);
+ expect(await readProjectionSnapshot(engine, slug, 'default')).toBeNull();
+ });
+ test('standalone recovery refuses installation after its source lease is lost during the probe', async () => {
+ const slug = 'synthetic-standalone-lease';
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic lease page', compiled_truth: 'Synthetic current body' });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic prior body' }]);
+ const lock = (await tryAcquireDbLock(engine, 'synthetic-standalone-lease', 1))!;
+ let calls = 0;
+ try {
+ await expect(embedStaleForSource(engine, 'default', {
+ embeddingSignature: `${model}:${dimensions}`,
+ assertOwned: tx => assertMigrationLeases(tx ?? engine, [lock]),
+ embedFn: async texts => {
+ calls++;
+ await engine.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id=$1', [lock.id]);
+ return texts.map(() => new Float32Array(dimensions).fill(0.1));
+ },
+ })).rejects.toThrow('lease lost');
+ expect(calls).toBe(1);
+ expect(await readProjectionSnapshot(engine, slug, 'default')).toBeNull();
+ expect((await engine.getChunks(slug, { includeUnsealed: true }))[0].chunk_text).toBe('Synthetic prior body');
+ } finally { await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [lock.id]); }
+ });
+ test('background handler repairs and embeds pending pages under its actual source lease', async () => {
+ for (let i = 0; i < 3; i++) {
+ const slug = `synthetic-background-recovery-${i}`;
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic background page', compiled_truth: `Synthetic current body ${i}` });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Synthetic prior body ${i}` }]);
+ }
+ const controller = new AbortController();
+ const result = await makeEmbedBackfillHandler(engine)({
+ id: 1, name: 'embed-backfill', data: { sourceId: 'default' }, attempts_made: 0,
+ signal: controller.signal, shutdownSignal: controller.signal, deadlineAtMs: Date.now() + 60_000,
+ isActive: async () => true, updateProgress: async () => {}, updateTokens: async () => {},
+ log: async () => {}, readInbox: async () => [],
+ });
+ expect(result.status).toBe('success');
+ expect(result.embedded).toBe(3);
+ expect(await engine.countStaleChunks()).toBe(0);
+ expect(await prepareEmbeddingProjections(engine)).toEqual({ rebuilt: 0, blocked: 0 });
+ expect(await engine.executeRaw("SELECT id FROM gbrain_cycle_locks WHERE id='gbrain-embed-backfill:default'")).toHaveLength(0);
+ });
+ test('an expired stale budget prevents probing or repairing pending projections', async () => {
+ const slug = 'synthetic-expired-projection';
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic deadline', compiled_truth: 'Synthetic current canonical body' });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic obsolete projected body' }]);
+ let calls = 0;
+ __setEmbedTransportForTests(async ({ values }) => {
+ calls++;
+ return { values, warnings: [], embeddings: values.map(() => Array(dimensions).fill(0.1)), usage: { tokens: 8 } };
+ });
+ const result = await withEnv({ GBRAIN_EMBED_TIME_BUDGET_MS: '0' }, () => runEmbedCore(engine, { stale: true, quiet: true }));
+ expect(result.embedded).toBe(0);
+ expect(calls).toBe(0);
+ expect(await prepareEmbeddingProjections(engine, { repair: true, deadline: Date.now() - 1 })).toEqual({ rebuilt: 0, blocked: 1 });
+ expect(await readProjectionSnapshot(engine, slug, 'default')).toBeNull();
+ expect((await engine.getChunks(slug, { includeUnsealed: true }))[0].chunk_text).toBe('Synthetic obsolete projected body');
+ });
+ test('multi-batch projection recovery stops on cancellation and resumes the remaining work', async () => {
+ for (let i = 0; i < 103; i++) {
+ const slug = `synthetic-cancel-batch-${i}`;
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic cancellable batch', compiled_truth: `Synthetic canonical batch body ${i}` });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Synthetic obsolete projected body ${i}` }]);
+ }
+ const controller = new AbortController();
+ let installed = 0;
+ const interrupted = await prepareEmbeddingProjections(engine, { repair: true, signal: controller.signal, assertOwned: async tx => {
+ if (!tx) return;
+ const [row] = await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE text_projection_revision=knowledge_revision');
+ installed = Math.max(installed, row.n);
+ if (row.n >= 101) controller.abort();
+ } });
+ expect(controller.signal.aborted).toBe(true);
+ expect(installed).toBe(101);
+ expect(interrupted).toEqual({ rebuilt: 100, blocked: 3 });
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE chunk_text LIKE $1', ['Synthetic obsolete%']))[0].n).toBe(3);
+ const resumed = await runEmbedCore(engine, { stale: true, quiet: true, catchUp: true });
+ expect(resumed.embedded).toBe(103);
+ expect(resumed.failures).toBe(0);
+ expect(await prepareEmbeddingProjections(engine)).toEqual({ rebuilt: 0, blocked: 0 });
+ }, 60_000);
+ test.skipIf(kind !== 'postgres')('file publication holds the lease against a second PostgreSQL owner through the real publisher', async () => {
+ const other = new PostgresEngine();
+ await other.connect({ database_url: process.env.DATABASE_URL! });
+ const home = mkdtempSync(join(tmpdir(), 'migration-publication-'));
+ mkdirSync(join(home, '.gbrain'));
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: kind, embedding_model: model, embedding_dimensions: dimensions }));
+ const leaseId = 'synthetic-migration-publication';
+ const lease = (await tryAcquireDbLock(engine, leaseId, 1))!;
+ let takeover: Promise<void> | undefined;
+ try {
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined }, async () => {
+ let publicationTx: BrainEngine | undefined;
+ let blockedAtPublication = false;
+ const winnerModel = 'openai:text-embedding-3-large';
+ const result = await applyEmbeddingMigration(engine, await planEmbeddingMigration(engine, { to: model, dim: dimensions }), {
+ assertOwned: async tx => {
+ publicationTx = tx;
+ await assertMigrationLeases(tx ?? engine, [lease]);
+ },
+ persistConfig: async (toModel, toDims) => {
+ const started = Promise.withResolvers<number>();
+ let takeoverFinished = false;
+ takeover = other.transaction(async tx => {
+ const [backend] = await tx.executeRaw<{ pid: number }>('SELECT pg_backend_pid() AS pid');
+ started.resolve(backend.pid);
+ await tx.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id=$1', [leaseId]);
+ await tx.setConfig('embedding_model', winnerModel);
+ await tx.setConfig('embedding_dimensions', String(dimensions));
+ await persistEmbeddingFileConfig(winnerModel, dimensions);
+ }).finally(() => { takeoverFinished = true; });
+ const pid = await started.promise;
+ for (let attempt = 0; attempt < 100; attempt++) {
+ const [waiting] = await (publicationTx ?? engine).executeRaw<{ blocked: boolean }>(
+ 'SELECT EXISTS(SELECT 1 FROM pg_locks WHERE pid=$1 AND NOT granted) AS blocked', [pid]);
+ blockedAtPublication = waiting.blocked;
+ if (blockedAtPublication || takeoverFinished) break;
+ await Bun.sleep(10);
+ }
+ await persistEmbeddingFileConfig(toModel, toDims);
+ },
+ });
+ await takeover;
+ expect(result.status).toBe('applied');
+ expect(loadConfigFileOnly()?.embedding_model).toBe(winnerModel);
+ expect(getEmbeddingModel()).toBe(winnerModel);
+ expect(await engine.getConfig('embedding_model')).toBe(winnerModel);
+ expect(blockedAtPublication).toBe(true);
+ });
+ } finally {
+ await takeover;
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [leaseId]);
+ await other.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+ });
+}
+
+if (backends.includes('pglite')) {
+test('explicit archived admission: actual CLI refuses all three routes without leaking content or dispatching archives', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'explicit-archive-cli-'));
+ const data = join(home, '.gbrain');
+ mkdirSync(data);
+ const database = join(data, 'brain.pglite');
+ const calls = join(home, 'calls.jsonl');
+ const preload = join(home, 'provider.ts');
+ const privateBody = 'SYNTHETIC_ARCHIVED_CLI_BODY_NEVER_PRINT';
+ const credential = 'synthetic-only-never-print';
+ writeFileSync(join(data, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: database,
+ embedding_model: model, embedding_dimensions: dimensions, openai_api_key: credential }));
+ writeFileSync(preload, `import { appendFileSync } from 'node:fs';
+ import { __setEmbedTransportForTests } from ${JSON.stringify(join(import.meta.dir, '../src/core/ai/gateway.ts'))};
+ globalThis.fetch = async () => { throw new Error('Synthetic fixture forbids network'); };
+ __setEmbedTransportForTests(async ({values}) => {
+ appendFileSync(${JSON.stringify(calls)}, JSON.stringify(values)+'\\n');
+ return { values, warnings: [], embeddings: values.map(() => Array(8).fill(0.1)), usage: { tokens: 8 } };
+ });`);
+ const engine = new PGLiteEngine();
+ const snapshot = () => engine.executeRaw(`SELECT to_jsonb(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(cc) ORDER BY cc.id) FROM content_chunks cc WHERE cc.page_id=p.id) AS chunks
+ FROM pages p WHERE source_id='synthetic-archive'`);
+ const env = { PATH: process.env.PATH, HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1' };
+ const run = async (args: string[]) => {
+ const child = Bun.spawn([process.execPath, '--no-env-file', '--preload', preload,
+ join(import.meta.dir, '../src/cli.ts'), 'embed', ...args], { cwd: home, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, code };
+ };
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ resetGateway();
+ configureGateway({ embedding_model: model, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: credential } });
+ await engine.connect({ database_path: database, embedding_dimensions: dimensions } as never);
+ await engine.initSchema();
+ await runSchemaTransition(engine, dimensions);
+ await engine.setConfig('embedding_model', model);
+ await engine.setConfig('embedding_dimensions', String(dimensions));
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('synthetic-archive','Synthetic archive')");
+ for (const [sourceId, slug, text] of [['synthetic-archive', 'archived-target', privateBody], ['default', 'active-target', 'Synthetic active CLI control.']]) {
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic CLI control', compiled_truth: text }, { sourceId });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: text }], { sourceId });
+ }
+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id='synthetic-archive'");
+ const before = await snapshot();
+ await engine.disconnect();
+ for (const args of [['archived-target'], ['--slugs', 'archived-target'], ['--all']]) {
+ writeFileSync(calls, '');
+ const dryRun = await run([...args, '--dry-run']);
+ expect(dryRun.code).toBe(0);
+ expect(readFileSync(calls, 'utf8')).toBe('');
+ const result = await run(args);
+ expect({ code: result.code, diagnostic: result.code === 1 ? '' : result.stderr }).toEqual({ code: 1, diagnostic: '' });
+ expect(result.stderr).toContain('gbrain sources restore');
+ expect(result.stdout + result.stderr).not.toContain(privateBody);
+ expect(result.stdout + result.stderr).not.toContain(credential);
+ const inputs: string[][] = readFileSync(calls, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
+ expect(inputs.flat().some(text => text.includes(privateBody))).toBe(false);
+ expect(inputs.length).toBe(args[0] === '--all' ? 1 : 0);
+ await engine.connect({ database_path: database });
+ expect(await snapshot()).toEqual(before);
+ await engine.disconnect();
+ }
+ expect((await run(['active-target'])).code).toBe(0);
+ });
+ } finally {
+ await engine.disconnect();
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+ }
+}, 120_000);
+}
diff --git a/test/embedding-signature-stale.test.ts b/test/embedding-signature-stale.test.ts
index a8945b8780..bdf230b20c 100644
--- a/test/embedding-signature-stale.test.ts
+++ b/test/embedding-signature-stale.test.ts
@@ -20,6 +20,7 @@ import type { ChunkInput } from '../src/core/types.ts';
import { invalidateStaleSignatureEmbeddingsGuarded } from '../src/core/embedding-invalidation.ts';
import { sealPageTextProjection } from '../src/core/page-state/projections.ts';
import { stampIfPageProvenanceComplete } from '../src/core/embed-stale.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
let engine: PGLiteEngine;
let colDim: number;
@@ -47,12 +48,14 @@ beforeEach(async () => {
* Seed a page with one EMBEDDED chunk (non-null vector) and a given
* embedding_signature (null → grandfathered legacy state).
*/
-async function seedEmbedded(slug: string, text: string, signature: string | null, sourceId?: string): Promise<void> {
+async function seedEmbedded(slug: string, text: string, signature: string | null, opts: { sourceId?: string; currentProjection?: boolean } = {}): Promise<void> {
+ const { sourceId } = opts;
await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` }, sourceId ? { sourceId } : undefined);
const chunks: ChunkInput[] = [
{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth', token_count: 4, embedding: undefined },
];
- await engine.upsertChunks(slug, chunks, sourceId ? { sourceId } : undefined);
+ if (opts.currentProjection) await installFixtureChunks(engine, slug, chunks, { sourceId });
+ else await engine.upsertChunks(slug, chunks, sourceId ? { sourceId } : undefined);
// Flip the chunk to a non-null vector sized to the actual column dim.
await engine.executeRaw(
`UPDATE content_chunks
@@ -73,7 +76,7 @@ describe('embedding_signature stale semantics', () => {
const signature = `${model}:${colDim}`;
const slug = 'mixed-provenance';
await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: '# mixed' });
- await engine.upsertChunks(slug, Array.from({ length: 5 }, (_, i) => ({
+ await installFixtureChunks(engine, slug, Array.from({ length: 5 }, (_, i) => ({
chunk_index: i, chunk_text: `chunk ${i}`, chunk_source: 'compiled_truth',
embedding: new Float32Array(colDim).fill(0.1), model,
})));
@@ -96,7 +99,7 @@ describe('embedding_signature stale semantics', () => {
}
test('matching model and text cannot preserve vectors of the wrong width (#5051)', async () => {
- await seedEmbedded('wrong-width', 'text', 'old:model:1');
+ await seedEmbedded('wrong-width', 'text', 'old:model:1', { currentProjection: true });
await engine.executeRaw(`UPDATE content_chunks SET model = 'target:model', embedded_text_hash = md5(chunk_text)`);
expect(await invalidateStaleSignatureEmbeddingsGuarded(engine, {
signature: `target:model:${colDim + 1}`,
@@ -129,7 +132,7 @@ describe('embedding_signature stale semantics', () => {
});
test('unparseable signatures never claim provenance or preserve unknown widths (#5051)', async () => {
- await seedEmbedded('unknown-width', 'text', 'old:model:1');
+ await seedEmbedded('unknown-width', 'text', 'old:model:1', { currentProjection: true });
await engine.executeRaw(`UPDATE content_chunks SET model = 'target:model', embedded_text_hash = md5(chunk_text)`);
expect(await invalidateStaleSignatureEmbeddingsGuarded(engine, { signature: 'target:model' })).toBe(1);
});
@@ -174,7 +177,7 @@ describe('embedding_signature stale semantics', () => {
`INSERT INTO sources (id, name, config) VALUES ('other', 'other', '{}'::jsonb) ON CONFLICT (id) DO NOTHING`,
);
await seedEmbedded('a', 'abcde', 'openai:old:1536'); // default
- await seedEmbedded('b', 'fghij', 'openai:old:1536', 'other'); // other
+ await seedEmbedded('b', 'fghij', 'openai:old:1536', { sourceId: 'other' }); // other
const n = await engine.invalidateStaleSignatureEmbeddings({ signature: 'voyage:new:1024', sourceId: 'default' });
expect(n).toBe(1);
expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(1);
diff --git a/test/embedding-truth-predicates.serial.test.ts b/test/embedding-truth-predicates.serial.test.ts
index 27a506d70b..138676a219 100644
--- a/test/embedding-truth-predicates.serial.test.ts
+++ b/test/embedding-truth-predicates.serial.test.ts
@@ -164,12 +164,12 @@ describe('truth predicates survive a schema rebuild', () => {
}, 30000);
test('embed_skip is excluded from both sides; all-skip brain reads vacuous 100%', async () => {
+ // Darken the vectors again so the old predicate would have read 0%.
+ await runSchemaTransition(engine, DIMS);
// Mark every page embed_skip: eligible set becomes empty.
await engine.executeRaw(
`UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"embed_skip": true}'::jsonb`,
);
- // Darken the vectors again so the old predicate would have read 0%.
- await runSchemaTransition(engine, DIMS);
const health = await engine.getHealth();
expect(health.embed_coverage).toBe(1); // vacuous: zero eligible chunks
diff --git a/test/export-help.test.ts b/test/export-help.test.ts
new file mode 100644
index 0000000000..6d0646adbd
--- /dev/null
+++ b/test/export-help.test.ts
@@ -0,0 +1,24 @@
+import { expect, test } from 'bun:test';
+import { mkdtempSync, readdirSync, realpathSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+test.each(['--help', '-h'])('actual export %s explains safe scope and recovery without a configured brain', help => {
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'export-help-')));
+ const env: Record<string, string> = { HOME: home, GBRAIN_HOME: home };
+ for (const key of ['PATH', 'SystemRoot', 'WINDIR', 'PATHEXT', 'TEMP', 'TMP']) {
+ if (process.env[key]) env[key] = process.env[key]!;
+ }
+ try {
+ const child = Bun.spawnSync([process.execPath, '--no-env-file', resolve('src/cli.ts'), 'export', help], {
+ cwd: home, env, stdout: 'pipe', stderr: 'pipe',
+ });
+ expect(child.exitCode).toBe(0);
+ expect(child.stderr.toString()).toBe('');
+ const output = child.stdout.toString();
+ for (const text of ['--dir', '--source', '--type', '--slug-prefix', '--restore-only', '--repo',
+ 'all sources', 'occupied', 'Colliding', 'nothing is overwritten', '.gbrain-export-status', 'COMPLETE',
+ 'fresh directory', 'not a database backup', 'docs/storage-tiering.md#safe-export']) expect(output).toContain(text);
+ expect(readdirSync(home)).not.toContain('export');
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}, 30000);
diff --git a/test/export-import-slug-roundtrip.test.ts b/test/export-import-slug-roundtrip.test.ts
index a63df1018c..aadaac16b3 100644
--- a/test/export-import-slug-roundtrip.test.ts
+++ b/test/export-import-slug-roundtrip.test.ts
@@ -16,7 +16,7 @@
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
-import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { mkdtempSync, realpathSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -42,7 +42,7 @@ beforeAll(async () => {
target = new PGLiteEngine();
await target.connect({});
await target.initSchema();
- outDir = mkdtempSync(join(tmpdir(), 'gbrain-roundtrip-'));
+ outDir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-roundtrip-')));
expect(slugifyPath(LEGACY_SLUG + '.md')).not.toBe(LEGACY_SLUG);
expect(slugifyPath(CLEAN_SLUG + '.md')).toBe(CLEAN_SLUG);
diff --git a/test/export-publication-native.serial.test.ts b/test/export-publication-native.serial.test.ts
new file mode 100644
index 0000000000..74fcb67caf
--- /dev/null
+++ b/test/export-publication-native.serial.test.ts
@@ -0,0 +1,58 @@
+import { expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { ExportStage, EXPORT_MARKER } from '../src/core/export-stage.ts';
+import { publishExport } from '../src/core/export-publish.ts';
+import { removeCompiledSmokeDirectory } from '../scripts/native/compiled-smoke-cleanup.ts';
+
+await import('./export-publication.test.ts');
+
+test('native filesystem case aliases refuse before publication and preserve occupied bytes', async () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'export-native-case-')));
+ const stage = new ExportStage();
+ try {
+ writeFileSync(join(root, 'Case-Probe.md'), 'operator bytes');
+ const caseInsensitive = existsSync(join(root, 'case-probe.md'));
+ if (process.env.GBRAIN_TEST_REQUIRE_CASE_INSENSITIVE === '1') expect(caseInsensitive).toBe(true);
+ console.log(`Native export fixture: platform=${process.platform} caseInsensitive=${caseInsensitive}`);
+ stage.add('case-probe.md', 'file', 'must not replace');
+ await expect(publishExport(stage, root)).rejects.toThrow();
+ expect(readFileSync(join(root, 'Case-Probe.md'), 'utf8')).toBe('operator bytes');
+ expect(readdirSync(root)).toEqual(['Case-Probe.md']);
+ } finally { stage.close(); rmSync(root, { recursive: true, force: true }); }
+});
+
+test('compiled publisher outside the checkout completes, refuses repeats and survives process death honestly', async () => {
+ const base = realpathSync(mkdtempSync(join(tmpdir(), 'export-native-compiled-')));
+ const binary = join(base, process.platform === 'win32' ? 'publisher.exe' : 'publisher');
+ const out = join(base, 'out'), partial = join(base, 'partial');
+ const env: Record<string, string> = { GBRAIN_HOME: join(base, 'home') };
+ for (const key of ['PATH', 'SystemRoot', 'WINDIR', 'PATHEXT', 'TEMP', 'TMP']) {
+ if (process.env[key]) env[key] = process.env[key]!;
+ }
+ mkdirSync(env.GBRAIN_HOME);
+ try {
+ const built = Bun.spawnSync([process.execPath, '--no-env-file', 'build', '--compile', '--no-compile-autoload-bunfig',
+ '--outfile', binary, resolve('test/fixtures/export-native-publish.ts')], { cwd: process.cwd(), env, stdout: 'pipe', stderr: 'pipe' });
+ expect({ status: built.exitCode, stderr: built.stderr.toString() }).toEqual({ status: 0, stderr: expect.any(String) });
+ const completed = Bun.spawnSync([binary, out], { cwd: base, env, stdout: 'pipe', stderr: 'pipe' });
+ expect({ status: completed.exitCode, stderr: completed.stderr.toString() }).toEqual({ status: 0, stderr: '' });
+ expect(completed.stdout.toString()).toContain('EXPORT_FIXTURE_COMPLETE');
+ expect(readFileSync(join(out, EXPORT_MARKER), 'utf8')).toBe('GBRAIN EXPORT INCOMPLETE\nCOMPLETE\n');
+ const bytes = readFileSync(join(out, 'first.md'), 'utf8');
+ const repeated = Bun.spawnSync([binary, out], { cwd: base, env, stdout: 'pipe', stderr: 'pipe' });
+ expect(repeated.exitCode).not.toBe(0);
+ expect(repeated.stdout.toString()).not.toContain('EXPORT_FIXTURE_COMPLETE');
+ expect(readFileSync(join(out, 'first.md'), 'utf8')).toBe(bytes);
+ const killed = Bun.spawnSync([binary, partial, 'kill'], { cwd: base, env, stdout: 'pipe', stderr: 'pipe' });
+ expect(killed.exitCode).not.toBe(0);
+ expect(killed.stdout.toString()).toContain('EXPORT_FIXTURE_KILLING');
+ expect(killed.stderr.toString()).toBe('');
+ if (process.platform !== 'win32') expect(killed.signalCode).toBe('SIGKILL');
+ expect(killed.stdout.toString()).not.toContain('EXPORT_FIXTURE_COMPLETE');
+ expect(readFileSync(join(partial, 'first.md'), 'utf8')).toBe('Synthetic first page\n');
+ expect(existsSync(join(partial, 'nested/second.md'))).toBe(false);
+ expect(readFileSync(join(partial, EXPORT_MARKER), 'utf8')).not.toContain('\nCOMPLETE\n');
+ } finally { await removeCompiledSmokeDirectory(base); }
+}, 180000);
diff --git a/test/export-publication.test.ts b/test/export-publication.test.ts
new file mode 100644
index 0000000000..2ab74a8b79
--- /dev/null
+++ b/test/export-publication.test.ts
@@ -0,0 +1,74 @@
+import { expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { ExportStage, EXPORT_MARKER } from '../src/core/export-stage.ts';
+import { publishExport } from '../src/core/export-publish.ts';
+
+async function fixture(run: (stage: ExportStage, root: string, outside: string) => Promise<void>) {
+ const stage = new ExportStage();
+ const base = realpathSync(mkdtempSync(join(tmpdir(), 'export-publish-')));
+ const root = join(base, 'out'), outside = join(base, 'outside');
+ mkdirSync(root); mkdirSync(outside);
+ try { await run(stage, root, outside); }
+ finally { chmodSync(root, 0o700); stage.close(); rmSync(base, { recursive: true, force: true }); }
+}
+test('atomic leaves never replace a newly occupied later target', () => fixture(async (stage, root) => {
+ stage.add('a.md', 'file', 'first'); stage.add('b.md', 'file', 'second');
+ await expect(publishExport(stage, root, () => writeFileSync(join(root, 'b.md'), 'competitor'))).rejects.toThrow();
+ expect(readFileSync(join(root, 'b.md'), 'utf8')).toBe('competitor');
+ expect(readFileSync(join(root, EXPORT_MARKER), 'utf8')).not.toContain('\nCOMPLETE\n');
+}));
+test('exclusive marker fences competing exporters', () => fixture(async (stage, root) => {
+ stage.add('a.md', 'file', 'first');
+ const competitor = new ExportStage(); competitor.add('b.md', 'file', 'second');
+ try {
+ await publishExport(stage, root, async () => { await expect(publishExport(competitor, root)).rejects.toThrow(); });
+ expect(existsSync(join(root, 'b.md'))).toBe(false);
+ } finally { competitor.close(); }
+}));
+test('ancestor symlink replacement cannot redirect a later file outside', () => fixture(async (stage, root, outside) => {
+ stage.add('a.md', 'file', 'first'); stage.add('nested/b.md', 'file', 'second');
+ await expect(publishExport(stage, root, () => symlinkSync(outside, join(root, 'nested'), process.platform === 'win32' ? 'junction' : 'dir'))).rejects.toThrow();
+ expect(existsSync(join(outside, 'b.md'))).toBe(false);
+}));
+test('root replacement cannot receive files or a completion receipt', () => fixture(async (stage, root, outside) => {
+ stage.add('a.md', 'file', 'first'); stage.add('b.md', 'file', 'second');
+ await expect(publishExport(stage, root, (path) => {
+ if (path === 'a.md') { renameSync(root, root + '-old'); mkdirSync(root); }
+ })).rejects.toThrow();
+ expect(existsSync(join(root, 'b.md'))).toBe(false);
+ expect(readFileSync(join(existsSync(root + '-old') ? root + '-old' : root, EXPORT_MARKER), 'utf8')).not.toContain('\nCOMPLETE\n');
+ expect(existsSync(join(outside, 'b.md'))).toBe(false);
+}));
+test('marker replacement refuses completion without modifying the replacement', () => fixture(async (stage, root) => {
+ stage.add('a.md', 'file', 'first');
+ await expect(publishExport(stage, root, () => {
+ renameSync(join(root, EXPORT_MARKER), join(root, 'original-marker'));
+ writeFileSync(join(root, EXPORT_MARKER), 'unknown');
+ })).rejects.toThrow();
+ if (existsSync(join(root, 'original-marker'))) {
+ expect(readFileSync(join(root, EXPORT_MARKER), 'utf8')).toBe('unknown');
+ expect(readFileSync(join(root, 'original-marker'), 'utf8')).not.toContain('\nCOMPLETE\n');
+ } else expect(readFileSync(join(root, EXPORT_MARKER), 'utf8')).not.toContain('\nCOMPLETE\n');
+}));
+test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('permission failure after publication leaves a durable incomplete marker', () => fixture(async (stage, root) => {
+ stage.add('a.md', 'file', 'first'); stage.add('b.md', 'file', 'second');
+ await expect(publishExport(stage, root, () => chmodSync(root, 0o500))).rejects.toThrow();
+ expect(readFileSync(join(root, 'a.md'), 'utf8')).toBe('first');
+ expect(readFileSync(join(root, EXPORT_MARKER), 'utf8')).not.toContain('\nCOMPLETE\n');
+}));
+test('SIGKILL after a leaf leaves an incomplete marker and nonzero process result', () => fixture(async (_stage, root) => {
+ const program = `import {ExportStage} from './src/core/export-stage.ts';
+ import {publishExport} from './src/core/export-publish.ts';
+ const stage = new ExportStage(); stage.add('a.md','file','first'); stage.add('b.md','file','second');
+ await publishExport(stage, ${JSON.stringify(root)}, () => { console.log('KILLING'); process.kill(process.pid, 'SIGKILL'); });`;
+ const child = Bun.spawnSync([process.execPath, '-e', program], { cwd: process.cwd(), env: { PATH: process.env.PATH }, stdout: 'pipe', stderr: 'pipe' });
+ expect(child.exitCode).not.toBe(0);
+ expect(child.stdout.toString()).toContain('KILLING');
+ expect(child.stderr.toString()).toBe('');
+ if (process.platform !== 'win32') expect(child.signalCode).toBe('SIGKILL');
+ expect(readFileSync(join(root, 'a.md'), 'utf8')).toBe('first');
+ expect(existsSync(join(root, 'b.md'))).toBe(false);
+ expect(readFileSync(join(root, EXPORT_MARKER), 'utf8')).not.toContain('\nCOMPLETE\n');
+}));
diff --git a/test/export-raw-include-deleted.test.ts b/test/export-raw-include-deleted.test.ts
index 511bcebcd8..ecb606b79b 100644
--- a/test/export-raw-include-deleted.test.ts
+++ b/test/export-raw-include-deleted.test.ts
@@ -6,7 +6,7 @@
* the engine read is observed through an instance-level wrapper.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { existsSync, mkdtempSync, realpathSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -27,7 +27,7 @@ afterAll(async () => {
});
beforeEach(() => {
- tmp = mkdtempSync(join(tmpdir(), 'gbrain-export-raw-'));
+ tmp = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-export-raw-')));
originalLog = console.log;
console.log = () => {};
});
@@ -48,11 +48,11 @@ describe('export — raw_data sidecar read', () => {
const seen: unknown[] = [];
const real = engine.getRawData;
- (engine as unknown as { getRawData: unknown }).getRawData = async (
+ (engine as unknown as { getRawData: unknown }).getRawData = async function (this: PGLiteEngine,
slug: string, source: string | undefined, opts: unknown,
- ) => {
+ ) {
seen.push({ slug, source, opts });
- return real.call(engine, slug, source, opts as never);
+ return real.call(this, slug, source, opts as never);
};
try {
await runExport(engine, ['--dir', join(tmp, 'out')]);
diff --git a/test/export-safety.test.ts b/test/export-safety.test.ts
new file mode 100644
index 0000000000..66a4142deb
--- /dev/null
+++ b/test/export-safety.test.ts
@@ -0,0 +1,238 @@
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runExport } from '../src/commands/export.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { importFromFile } from '../src/core/import-file.ts';
+import { slugifyPath } from '../src/core/sync.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { ExportStage, EXPORT_SNAPSHOT_MS } from '../src/core/export-stage.ts';
+
+for (const backend of testBackends()) describe(`export safety: ${backend}`, () => {
+ let engine: BrainEngine;
+ let target: BrainEngine;
+ let closeTarget: () => Promise<void>;
+ let dir: string;
+ let exit: typeof process.exit;
+ let log: typeof console.log;
+ let err: typeof console.error;
+ let messages: string[];
+ beforeAll(async () => {
+ engine = backend === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+ if (engine instanceof PostgresEngine) await engine.connect({ database_url: requirePostgresTestDatabase(), poolSize: 1 });
+ else await engine.connect({});
+ await engine.initSchema();
+ if (backend === 'postgres') {
+ const isolated = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ target = isolated.engine; closeTarget = isolated.close;
+ } else {
+ target = new PGLiteEngine();
+ await target.connect({}); await target.initSchema();
+ closeTarget = () => target.disconnect();
+ }
+ }, 60000);
+ afterAll(async () => { await closeTarget?.(); await engine.disconnect(); });
+ beforeEach(async () => {
+ dir = realpathSync(mkdtempSync(join(tmpdir(), 'export-safety-')));
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("INSERT INTO sources (id,name) VALUES ('other','Other') ON CONFLICT DO NOTHING");
+ exit = process.exit; log = console.log; err = console.error; messages = [];
+ process.exit = ((code: number) => { throw new Error(`EXIT:${code}`); }) as never;
+ console.log = console.error = (...args) => { messages.push(args.join(' ')); };
+ });
+ afterEach(() => { process.exit = exit; console.log = log; console.error = err; rmSync(dir, { recursive: true, force: true }); });
+ async function page(slug: string, sourceId = 'default') {
+ await engine.putPage(slug, { type: 'note', title: sourceId, compiled_truth: `body-${sourceId}`, timeline: '' }, { sourceId });
+ await engine.addTag(slug, `tag-${sourceId}`, { sourceId });
+ await engine.putRawData(slug, 'feed', { owner: sourceId }, { sourceId });
+ }
+ test('same-slug source collision refuses without any destination writes', async () => {
+ await page('notes/shared'); await page('notes/shared', 'other');
+ await expect(runExport(engine, ['--dir', dir])).rejects.toThrow('EXIT:1');
+ expect(readdirSync(dir)).toEqual([]);
+ expect(messages.join('\n')).not.toContain('Exported ');
+ });
+ test('explicit source preserves body, tags and raw identity', async () => {
+ await page('notes/shared'); await page('notes/shared', 'other');
+ await runExport(engine, ['--dir', dir, '--source=other']);
+ const md = readFileSync(join(dir, 'notes/shared.md'), 'utf8');
+ expect(md).toContain('body-other'); expect(md).toContain('tag-other'); expect(md).not.toContain('tag-default');
+ expect(JSON.parse(readFileSync(join(dir, 'notes/.raw/shared.json'), 'utf8'))).toEqual({ feed: { owner: 'other' } });
+ });
+ test('occupied planned leaf and repeated export preserve all existing bytes', async () => {
+ await page('sample'); writeFileSync(join(dir, 'sample.md'), 'operator bytes');
+ await expect(runExport(engine, ['--dir', dir])).rejects.toThrow('EXIT:1');
+ expect(readFileSync(join(dir, 'sample.md'), 'utf8')).toBe('operator bytes');
+ expect(readdirSync(dir)).toEqual(['sample.md']);
+ });
+ test('same-source Unicode and case aliases refuse before publication', async () => {
+ await page('first'); await page('second');
+ await engine.executeRaw('UPDATE pages SET slug=$1 WHERE slug=$2', ['Notes/Café', 'first']);
+ await engine.executeRaw('UPDATE pages SET slug=$1 WHERE slug=$2', ['notes/Cafe\u0301', 'second']);
+ await expect(runExport(engine, ['--dir', dir])).rejects.toThrow('EXIT:1');
+ expect(readdirSync(dir)).toEqual([]);
+ });
+ test('page/sidecar file-prefix collision refuses before publication', async () => {
+ await page('one'); await page('one.md/two');
+ await expect(runExport(engine, ['--dir', dir])).rejects.toThrow('EXIT:1');
+ expect(readdirSync(dir)).toEqual([]);
+ });
+ test('unrelated files survive and only complete publication gets success', async () => {
+ await page('sample'); writeFileSync(join(dir, 'keep'), 'untouched');
+ await runExport(engine, ['--dir', dir]);
+ expect(readFileSync(join(dir, 'keep'), 'utf8')).toBe('untouched');
+ expect(readFileSync(join(dir, '.gbrain-export-status'), 'utf8')).toBe('GBRAIN EXPORT INCOMPLETE\nCOMPLETE\n');
+ expect(messages.join('\n')).toContain('Exported 1 pages');
+ await expect(runExport(engine, ['--dir', dir])).rejects.toThrow('EXIT:1');
+ expect(existsSync(join(dir, 'sample.md'))).toBe(true);
+ });
+ test('missing, invalid, unknown and archived source inputs refuse without output', async () => {
+ await page('sample');
+ await engine.executeRaw("UPDATE sources SET archived=true WHERE id='other'");
+ try {
+ for (const args of [['--source'], ['--source='], ['--source', '../bad'], ['--source', 'unknown'], ['--source', 'other'],
+ ['--source', 'a'.repeat(33)], ['--source', 'café'], ['--source', 'cafe\u0301'], ['--source', 'a\0b'],
+ ['--source', 'default', '--source=other']]) {
+ await expect(runExport(engine, ['--dir', dir, ...args])).rejects.toThrow('EXIT:1');
+ expect(readdirSync(dir)).toEqual([]);
+ }
+ } finally { await engine.executeRaw("UPDATE sources SET archived=false WHERE id='other'"); }
+ });
+ test('restore checks the recorded path and limits output to the repo source and narrower prefix', async () => {
+ await page('media/first'); await page('media/second'); await page('media/second', 'other'); await page('notes/third');
+ const repo = join(dir, 'repo'), out = join(dir, 'out');
+ mkdirSync(repo); mkdirSync(join(repo, 'Media'));
+ writeFileSync(join(repo, 'gbrain.yml'), 'storage:\n db_tracked: []\n db_only:\n - media/\n');
+ writeFileSync(join(repo, 'Media/First Note.md'), 'original human bytes');
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [repo]);
+ await engine.executeRaw("UPDATE pages SET source_path='Media/First Note.md' WHERE source_id='default' AND slug='media/first'");
+ await runExport(engine, ['--dir', out, '--repo', repo, '--restore-only', '--slug-prefix', 'media/']);
+ expect(existsSync(join(out, 'media/first.md'))).toBe(false);
+ expect(readFileSync(join(out, 'media/second.md'), 'utf8')).toContain('body-default');
+ expect(existsSync(join(out, 'notes/third.md'))).toBe(false);
+ expect(readFileSync(join(repo, 'Media/First Note.md'), 'utf8')).toBe('original human bytes');
+ });
+ test('unscoped export ignores inherited source while explicit and maximum-length sources route exactly', async () => {
+ const longest = 'a'.repeat(32);
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES ($1,$2) ON CONFLICT (id) DO UPDATE SET archived=false', [longest, 'Export longest source']);
+ await page('default-page'); await page('other-page', 'other'); await page('long-page', longest);
+ await withEnv({ GBRAIN_SOURCE: 'other' }, async () => {
+ await runExport(engine, ['--dir', join(dir, 'all')]);
+ for (const slug of ['default-page', 'other-page', 'long-page']) expect(existsSync(join(dir, 'all', slug + '.md'))).toBe(true);
+ await runExport(engine, ['--dir', join(dir, 'default'), '--source', 'default']);
+ expect(existsSync(join(dir, 'default/default-page.md'))).toBe(true);
+ expect(existsSync(join(dir, 'default/other-page.md'))).toBe(false);
+ await runExport(engine, ['--dir', join(dir, 'long'), '--source', longest]);
+ expect(readFileSync(join(dir, 'long/long-page.md'), 'utf8')).toContain(`body-${longest}`);
+ });
+ });
+ test('source-separated legacy-slug exports re-import independently without cross-source tags or rekeying', async () => {
+ const slug = "notes/caf\u00e9-o'example";
+ await page(slug); await page(slug, 'other');
+ for (const source of ['default', 'other']) await runExport(engine, ['--dir', join(dir, source), '--source', source]);
+ await target.executeRaw("INSERT INTO sources(id,name) VALUES ('other','Other')");
+ for (const source of ['default', 'other']) {
+ const imported = await importFromFile(target, join(dir, source, slug + '.md'), slug + '.md', { sourceId: source, noEmbed: true });
+ expect(imported.error).toBeUndefined();
+ expect(imported.slug).toBe(slug);
+ const snapshot = await target.readPageSnapshot(slug, { sourceId: source });
+ expect(snapshot!.page.compiled_truth).toContain(`body-${source}`);
+ expect(snapshot!.tags).toEqual([`tag-${source}`]);
+ expect(await target.getPage(slugifyPath(slug + '.md'), { sourceId: source })).toBeNull();
+ expect(JSON.parse(readFileSync(join(dir, source, 'notes/.raw', "caf\u00e9-o'example.json"), 'utf8'))).toEqual({ feed: { owner: source } });
+ }
+ expect(await target.executeRaw('SELECT count(*)::int AS count FROM pages')).toEqual([{ count: 2 }]);
+ }, 60000);
+ test.each(['page-read', 'deadline', 'transaction-end'])('snapshot %s failure releases its transaction and staging without publishing', async fault => {
+ await page('failure-page');
+ const query = engine.executeRaw, transaction = engine.transaction, now = Date.now, close = ExportStage.prototype.close;
+ const [before] = await engine.executeRaw("SELECT current_setting('statement_timeout') AS timeout, current_setting('transaction_isolation') AS isolation");
+ let staging: string | undefined, active = false, captured: Record<string, unknown> | undefined;
+ ExportStage.prototype.close = function () { staging = this.directory; return close.call(this); };
+ engine.executeRaw = async function (sql, params, options) {
+ if (sql.includes('AS export_tags')) {
+ captured = (await query.call(this, "SELECT current_setting('transaction_read_only') AS read_only, current_setting('transaction_isolation') AS isolation, current_setting('statement_timeout') AS timeout"))[0] as Record<string, unknown>;
+ if (fault === 'page-read') throw new Error('Injected export page read failure');
+ if (fault === 'deadline') {
+ const expired = now() + EXPORT_SNAPSHOT_MS + 1;
+ Date.now = () => expired;
+ }
+ }
+ return query.call(this, sql, params, options) as never;
+ };
+ engine.transaction = async function (fn) {
+ try {
+ return await transaction.call(this, async tx => {
+ active = true;
+ const value = await fn(tx);
+ if (fault === 'transaction-end') await query.call(tx, 'SELECT 1/0');
+ return value;
+ }) as never;
+ } finally { active = false; }
+ };
+ try {
+ await expect(runExport(engine, ['--dir', dir])).rejects.toThrow('EXIT:1');
+ expect(captured).toEqual({ read_only: 'on', isolation: 'repeatable read', timeout: '1min' });
+ expect(active).toBe(false);
+ expect(readdirSync(dir)).toEqual([]);
+ expect(staging).toBeDefined();
+ expect(existsSync(staging!)).toBe(false);
+ expect(messages.join('\n')).not.toContain('Exported ');
+ if (fault === 'deadline') expect(messages.join('\n')).toContain('snapshot time limit');
+ } finally { engine.executeRaw = query; engine.transaction = transaction; Date.now = now; ExportStage.prototype.close = close; }
+ expect(await engine.executeRaw("SELECT current_setting('statement_timeout') AS timeout, current_setting('transaction_isolation') AS isolation")).toEqual([before]);
+ await engine.transaction(async tx => { await tx.executeRaw("UPDATE pages SET title='Connection reused' WHERE slug='failure-page'"); });
+ if (engine instanceof PostgresEngine) expect(engine.getPoolDiagnostics()!.tracked).toEqual({ tx: 0, raw: 0, direct: 0, reserved: 0 });
+ await runExport(engine, ['--dir', dir]);
+ expect(readFileSync(join(dir, 'failure-page.md'), 'utf8')).toContain('Connection reused');
+ }, 60000);
+ test.skipIf(backend !== 'postgres')('real PostgreSQL statement timeout rolls back and releases its sole pool connection', async () => {
+ await page('timeout-page');
+ expect((engine as PostgresEngine).getPoolDiagnostics()!.poolMax).toBe(1);
+ const query = engine.executeRaw;
+ let code: unknown;
+ engine.executeRaw = async function (sql, params, options) {
+ const rows = await query.call(this, sql, params, options);
+ if (sql === 'SET LOCAL statement_timeout = 60000') {
+ await query.call(this, 'SET LOCAL statement_timeout = 10');
+ try { await query.call(this, 'SELECT pg_sleep(0.1)'); }
+ catch (error) { code = (error as { code: string }).code; throw error; }
+ }
+ return rows as never;
+ };
+ try {
+ await expect(runExport(engine, ['--dir', dir])).rejects.toThrow('EXIT:1');
+ expect(code).toBe('57014');
+ expect(readdirSync(dir)).toEqual([]);
+ } finally { engine.executeRaw = query; }
+ expect((engine as PostgresEngine).getPoolDiagnostics()!.tracked).toEqual({ tx: 0, raw: 0, direct: 0, reserved: 0 });
+ expect(await engine.executeRaw('SELECT 42 AS value')).toEqual([{ value: 42 }]);
+ await runExport(engine, ['--dir', dir]);
+ expect(existsSync(join(dir, 'timeout-page.md'))).toBe(true);
+ }, 60000);
+ test('snapshot transaction ends before destination publication begins', async () => {
+ await page('lifetime-page');
+ const transaction = engine.transaction;
+ let active = false, transactions = 0, publicationChecked = false;
+ engine.transaction = async function (fn) {
+ transactions++; active = true;
+ try { return await transaction.call(this, fn) as never; }
+ finally { active = false; }
+ };
+ const capture = console.log;
+ console.log = (...args) => {
+ if (String(args[0]).startsWith('Exporting ')) { expect(active).toBe(false); publicationChecked = true; }
+ capture(...args);
+ };
+ try {
+ await runExport(engine, ['--dir', dir]);
+ expect(transactions).toBe(1);
+ expect(publicationChecked).toBe(true);
+ } finally { engine.transaction = transaction; console.log = capture; }
+ });
+});
diff --git a/test/export-scale.slow.test.ts b/test/export-scale.slow.test.ts
new file mode 100644
index 0000000000..491ddcb868
--- /dev/null
+++ b/test/export-scale.slow.test.ts
@@ -0,0 +1,85 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, realpathSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runExport } from '../src/commands/export.ts';
+import { parseFactsFence, renderFactsTable } from '../src/core/facts-fence.ts';
+import { ExportStage } from '../src/core/export-stage.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+for (const backend of testBackends()) describe(`export scale: ${backend}`, () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ engine = backend === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+ await engine.connect(backend === 'postgres' ? { database_url: requirePostgresTestDatabase() } : {});
+ await engine.initSchema();
+ }, 60000);
+ afterAll(async () => { await engine.disconnect(); });
+ test('exports all 100001 pages with bounded keyset enumeration', async () => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'export-scale-')));
+ const started = performance.now();
+ let batches = 0, largestBatch = 0, ledgerReads = 0, normalizations = 0;
+ let executeRawQueries = 0, rawQueries = 0, transactions = 0, stagingPayloadBytes = 0, stagingManifestBytes = 0;
+ const real = engine.executeRaw, raw = engine.getRawData, transaction = engine.transaction, close = ExportStage.prototype.close;
+ try {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM fact_withdrawals WHERE source_id='default'");
+ const fenced = renderFactsTable([{ rowNum: 1, claim: 'Synthetic withdrawn claim', kind: 'fact', confidence: 1,
+ visibility: 'world', notability: 'medium', active: true, context: '' }]);
+ await engine.executeRaw('ALTER TABLE pages DISABLE TRIGGER bump_page_generation_trg');
+ try {
+ await engine.executeRaw(`INSERT INTO pages (source_id,slug,type,title,compiled_truth,timeline,frontmatter,generation)
+ SELECT 'default', 'scale/p' || lpad(n::text,6,'0'), 'note', 'Synthetic ' || n,
+ 'Body ' || n || CASE WHEN n%100=0 THEN chr(10)||$1 ELSE '' END, '', '{}'::jsonb, n
+ FROM generate_series(1,100001) n`, [fenced]);
+ } finally { await engine.executeRaw('ALTER TABLE pages ENABLE TRIGGER bump_page_generation_trg'); }
+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,fact_hash)
+ SELECT 'default','world',gbrain_fact_fingerprint(CASE WHEN n=1 THEN 'Synthetic withdrawn claim'
+ ELSE 'Unrelated synthetic claim '||n END) FROM generate_series(1,1000) n`);
+ await engine.executeRaw("INSERT INTO tags(page_id,tag) SELECT id,'scale-tag' FROM pages WHERE right(slug,2)='00'");
+ await engine.executeRaw("INSERT INTO raw_data(page_id,source,data) SELECT id,'feed',jsonb_build_object('slug',slug) FROM pages WHERE right(slug,2)='00'");
+ const seededMs = performance.now() - started;
+ console.log(JSON.stringify({ backend, seeded: 100001, seededMs: Math.round(seededMs) }));
+ engine.executeRaw = async function (query: string, params?: unknown[], options?: never) {
+ executeRawQueries++;
+ const rows = await real.call(this, query, params, options);
+ if (query.includes('ORDER BY p.id LIMIT 256')) { batches++; largestBatch = Math.max(largestBatch, rows.length); }
+ if (query.includes('SELECT visibility,fact_hash,withdrawn_at')) ledgerReads++;
+ if (query.includes('AS lines(line,ord)')) normalizations++;
+ return rows as never;
+ };
+ engine.getRawData = async function (...args) { rawQueries++; return raw.apply(this, args); };
+ engine.transaction = async function (fn) { transactions++; return transaction.call(this, fn) as never; };
+ ExportStage.prototype.close = function () {
+ stagingPayloadBytes = this.bytes;
+ stagingManifestBytes = statSync(join(this.directory, 'manifest.sqlite')).size;
+ return close.call(this);
+ };
+ await runExport(engine, ['--dir', dir]);
+ expect(readdirSync(join(dir, 'scale')).filter(name => name.endsWith('.md')).length).toBe(100001);
+ expect(readdirSync(join(dir, 'scale/.raw')).length).toBe(1000);
+ expect(readFileSync(join(dir, 'scale/p100001.md'), 'utf8')).toContain('Body 100001');
+ expect(readFileSync(join(dir, 'scale/p100000.md'), 'utf8')).toContain('scale-tag');
+ expect(parseFactsFence(readFileSync(join(dir, 'scale/p100000.md'), 'utf8')).facts[0].active).toBe(false);
+ expect(parseFactsFence(readFileSync(join(dir, 'scale/p000100.md'), 'utf8')).facts[0].active).toBe(false);
+ expect(JSON.parse(readFileSync(join(dir, 'scale/.raw/p100000.json'), 'utf8'))).toEqual({ feed: { slug: 'scale/p100000' } });
+ expect(batches).toBe(392); expect(largestBatch).toBe(256);
+ expect(ledgerReads).toBe(391); expect(normalizations).toBe(1000);
+ expect(transactions).toBe(1); expect(rawQueries).toBe(1000);
+ expect(executeRawQueries).toBe(100001 + 392 + 391 * 2 + 1000 + 2);
+ expect(stagingPayloadBytes).toBeGreaterThan(100001);
+ expect(stagingManifestBytes).toBeGreaterThan(stagingPayloadBytes);
+ console.log(JSON.stringify({ backend, selected: 100001, processed: 100001, rawSidecars: 1000, taggedPages: 1000,
+ withdrawals: 1000, fencedPages: 1000, ledgerReads, normalizations, blocked: 0, failed: 0, retries: 0,
+ stagingPayloadBytes, stagingManifestBytes, executeRawQueries, rawQueries, transactions,
+ totalSqlStatements: executeRawQueries + rawQueries + transactions * 2,
+ batches, largestBatch, durationMs: Math.round(performance.now() - started), exportMs: Math.round(performance.now() - started - seededMs), peakRssKb: process.resourceUsage().maxRSS }));
+ } finally {
+ engine.executeRaw = real; engine.getRawData = raw; engine.transaction = transaction; ExportStage.prototype.close = close;
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 900000);
+});
diff --git a/test/export-snapshot.test.ts b/test/export-snapshot.test.ts
new file mode 100644
index 0000000000..1257293865
--- /dev/null
+++ b/test/export-snapshot.test.ts
@@ -0,0 +1,200 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, realpathSync, readFileSync, readdirSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runExport } from '../src/commands/export.ts';
+import { parseFactsFence, renderFactsTable } from '../src/core/facts-fence.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { readExportPage, readExportWithdrawals } from '../src/core/export-snapshot.ts';
+import { overlayCanonicalBodies } from '../src/core/page-state/snapshot.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+for (const backend of testBackends()) describe(`coherent export: ${backend}`, () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ engine = backend === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+ await engine.connect(backend === 'postgres' ? { database_url: requirePostgresTestDatabase() } : {});
+ await engine.initSchema();
+ }, 60000);
+ afterAll(async () => { await engine.disconnect(); });
+ test('batch-local withdrawal ledgers stay source-isolated and are not read per page', async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('ledger-other','Ledger synthetic') ON CONFLICT (id) DO UPDATE SET archived=false");
+ await engine.executeRaw("DELETE FROM fact_withdrawals WHERE source_id IN ('default','ledger-other')");
+ const body = renderFactsTable([{ rowNum: 1, claim: 'Shared synthetic claim', kind: 'fact', confidence: 1,
+ visibility: 'world', notability: 'medium', active: true, context: '' }]);
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter)
+ SELECT CASE WHEN n%2=1 THEN 'default' ELSE 'ledger-other' END,'ledger/p'||n,'note','Synthetic',
+ CASE WHEN n<=4 THEN $1 ELSE 'No fact markers' END,'','{}'::jsonb FROM generate_series(1,513) n`, [body]);
+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES ('default','world',gbrain_fact_fingerprint($1))", ['Shared synthetic claim']);
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'export-ledger-')));
+ const real = engine.executeRaw;
+ const reads: string[] = [];
+ let normalizations = 0;
+ engine.executeRaw = async function (query, params, options) {
+ if (query.includes('SELECT visibility,fact_hash,withdrawn_at')) reads.push(String(params?.[0]));
+ if (query.includes('AS lines(line,ord)')) normalizations++;
+ return real.call(this, query, params, options) as never;
+ };
+ try {
+ await runExport(engine, ['--dir', dir]);
+ expect(reads.filter(source => source === 'default')).toHaveLength(3);
+ expect(reads.filter(source => source === 'ledger-other')).toHaveLength(2);
+ expect(normalizations).toBe(2);
+ expect(parseFactsFence(readFileSync(join(dir, 'ledger/p1.md'), 'utf8')).facts[0].active).toBe(false);
+ expect(parseFactsFence(readFileSync(join(dir, 'ledger/p2.md'), 'utf8')).facts[0].active).toBe(true);
+ expect(parseFactsFence(readFileSync(join(dir, 'ledger/p3.md'), 'utf8')).facts[0].active).toBe(false);
+ expect(parseFactsFence(readFileSync(join(dir, 'ledger/p4.md'), 'utf8')).facts[0].active).toBe(true);
+ } finally { engine.executeRaw = real; rmSync(dir, { recursive: true, force: true }); }
+ }, 60000);
+ test('export-local marker shortcut preserves canonical malformed and orphan fence handling', async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM fact_withdrawals WHERE source_id='default'");
+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES ('default','world',gbrain_fact_fingerprint($1))", ['MiXeD\t synthetic claim']);
+ const body = renderFactsTable([{ rowNum: 1, claim: 'MIXED synthetic claim', kind: 'fact', confidence: 1,
+ visibility: 'world', notability: 'medium', active: true, context: '' }]);
+ const variants = ['Plain text without a marker', body, '<!--- gbrain:facts:end -->',
+ 'gbrain:facts:begin malformed', body + '\n<!--- gbrain:facts:begin -->',
+ '<!--- gbrain:facts:begin -->\n' + body, '<!--- gbrain:facts:begin -->\nbroken\n<!--- gbrain:facts:end -->'];
+ await engine.transaction(async tx => {
+ const withdrawals = await readExportWithdrawals(tx, 'default');
+ for (let n = 0; n < variants.length; n++) {
+ const compiled = variants[n], timeline = variants[variants.length - 1 - n];
+ const [key] = await tx.executeRaw<{ id: string; source_id: string; slug: string }>(`INSERT INTO pages
+ (source_id,slug,type,title,compiled_truth,timeline,frontmatter) VALUES ('default',$1,'note','Synthetic',$2,$3,'{}')
+ RETURNING id::text,source_id,slug`, ['adversarial/p' + n, compiled, timeline]);
+ const canonical = await overlayCanonicalBodies(tx.executeRaw.bind(tx), compiled, timeline, withdrawals);
+ let normalized = 0;
+ const real = tx.executeRaw;
+ tx.executeRaw = async function (query, params, options) {
+ if (query.includes('AS lines(line,ord)')) normalized++;
+ return real.call(this, query, params, options) as never;
+ };
+ try {
+ const snapshot = await readExportPage(tx, key, withdrawals);
+ expect(snapshot.page.compiled_truth).toBe(canonical.compiled_truth);
+ expect(snapshot.page.timeline).toBe(canonical.timeline);
+ expect(normalized).toBe(1);
+ } finally { tx.executeRaw = real; }
+ }
+ });
+ }, 60000);
+ test('source/page/tag/raw changes after snapshot do not tear the export', async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("INSERT INTO sources (id,name) VALUES ('snapshot-source','Snapshot') ON CONFLICT (id) DO UPDATE SET archived=false");
+ await engine.putPage('sample', { type: 'note', title: 'Before', compiled_truth: 'before-body', timeline: '' }, { sourceId: 'snapshot-source' });
+ await engine.addTag('sample', 'before-tag', { sourceId: 'snapshot-source' });
+ await engine.putRawData('sample', 'feed', { state: 'before' }, { sourceId: 'snapshot-source' });
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'export-snapshot-')));
+ const real = engine.executeRaw;
+ let writer: Promise<void> | undefined;
+ engine.executeRaw = async function (query, params, options) {
+ const result = await real.call(this, query, params, options);
+ if (!query.includes('AS export_tags')) return result as never;
+ writer = engine.transaction(async tx => {
+ await tx.executeRaw("UPDATE pages SET compiled_truth='after-body' WHERE source_id='snapshot-source'");
+ await tx.executeRaw("UPDATE tags SET tag='after-tag' WHERE page_id IN (SELECT id FROM pages WHERE source_id='snapshot-source')");
+ await tx.executeRaw("UPDATE raw_data SET data=$1::text::jsonb WHERE page_id IN (SELECT id FROM pages WHERE source_id='snapshot-source')", ['{"state":"after"}']);
+ await tx.executeRaw("UPDATE sources SET archived=true WHERE id='snapshot-source'");
+ });
+ if (backend === 'postgres') await writer;
+ return result as never;
+ };
+ try {
+ await runExport(engine, ['--dir', dir, '--source', 'snapshot-source']);
+ await writer;
+ const md = readFileSync(join(dir, 'sample.md'), 'utf8');
+ expect(md).toContain('before-body'); expect(md).toContain('before-tag'); expect(md).not.toContain('after-');
+ expect(JSON.parse(readFileSync(join(dir, '.raw/sample.json'), 'utf8'))).toEqual({ feed: { state: 'before' } });
+ } finally { engine.executeRaw = real; await writer; rmSync(dir, { recursive: true, force: true }); }
+ }, 60000);
+ test('pre-snapshot withdrawal is reflected and later withdrawal preserves historical snapshot', async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM fact_withdrawals WHERE source_id='default'");
+ const body = renderFactsTable([
+ { rowNum: 1, claim: 'Earlier synthetic claim', kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true, context: '' },
+ { rowNum: 2, claim: 'Later synthetic claim', kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true, context: '' },
+ ]);
+ await engine.putPage('claims', { type: 'note', title: 'Claims', compiled_truth: body, timeline: '' }, { sourceId: 'default' });
+ await engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES ('default','world',gbrain_fact_fingerprint($1))", ['Earlier synthetic claim']);
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'export-withdrawal-')));
+ const real = engine.executeRaw;
+ let writer: Promise<unknown> | undefined;
+ engine.executeRaw = async function (query, params, options) {
+ const result = await real.call(this, query, params, options);
+ if (!query.includes('AS export_tags')) return result as never;
+ writer = engine.executeRaw("INSERT INTO fact_withdrawals(source_id,visibility,fact_hash) VALUES ('default','world',gbrain_fact_fingerprint($1))", ['Later synthetic claim']);
+ if (backend === 'postgres') await writer;
+ return result as never;
+ };
+ try {
+ await runExport(engine, ['--dir', dir, '--source', 'default']);
+ await writer;
+ const exported = parseFactsFence(readFileSync(join(dir, 'claims.md'), 'utf8')).facts;
+ expect(exported.map(fact => fact.active)).toEqual([false, true]);
+ engine.executeRaw = real;
+ const imported = await importFromContent(engine, 'claims', readFileSync(join(dir, 'claims.md'), 'utf8'), { sourceId: 'default', noEmbed: true });
+ expect(imported.error).toBeUndefined();
+ const current = await engine.readPageSnapshot('claims', { sourceId: 'default' });
+ expect(parseFactsFence(current!.page.compiled_truth).facts.map(fact => fact.active)).toEqual([false, false]);
+ } finally { engine.executeRaw = real; await writer; rmSync(dir, { recursive: true, force: true }); }
+ }, 60000);
+ test('deleting and recreating a source after S cannot replace its raw sidecar', async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES ('incarnation-source','Synthetic') ON CONFLICT DO NOTHING");
+ await engine.putPage('same', { type: 'note', title: 'Original', compiled_truth: 'original', timeline: '' }, { sourceId: 'incarnation-source' });
+ await engine.putRawData('same', 'feed', { incarnation: 'old' }, { sourceId: 'incarnation-source' });
+ const real = engine.executeRaw;
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'export-incarnation-')));
+ let writer: Promise<void> | undefined;
+ engine.executeRaw = async function (query, params, options) {
+ const result = await real.call(this, query, params, options);
+ if (!query.includes('AS export_tags')) return result as never;
+ writer = engine.transaction(async tx => {
+ await tx.executeRaw("DELETE FROM sources WHERE id='incarnation-source'");
+ await tx.executeRaw("INSERT INTO sources(id,name) VALUES ('incarnation-source','Replacement')");
+ await tx.executeRaw("INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter) VALUES ('incarnation-source','same','note','Replacement','new','', '{}'::jsonb)");
+ await tx.executeRaw("INSERT INTO raw_data(page_id,source,data) SELECT id,'feed',$1::text::jsonb FROM pages WHERE source_id='incarnation-source'", ['{"incarnation":"new"}']);
+ });
+ if (backend === 'postgres') await writer;
+ return result as never;
+ };
+ try {
+ await runExport(engine, ['--dir', dir, '--source', 'incarnation-source']); await writer;
+ expect(JSON.parse(readFileSync(join(dir, '.raw/same.json'), 'utf8'))).toEqual({ feed: { incarnation: 'old' } });
+ } finally { engine.executeRaw = real; await writer; rmSync(dir, { recursive: true, force: true }); }
+ }, 60000);
+ test('keyset batches preserve S while an unseen page is removed and a new page appears', async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter)
+ SELECT 'default','batch/p'||n,'note','Synthetic','Original','','{}'::jsonb FROM generate_series(1,513) n`);
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'export-keyset-')));
+ const real = engine.executeRaw;
+ let writer: Promise<void> | undefined;
+ let batches = 0;
+ engine.executeRaw = async function (query, params, options) {
+ const rows = await real.call(this, query, params, options);
+ if (query.includes('ORDER BY p.id LIMIT 256')) {
+ batches++;
+ if (!writer) {
+ writer = engine.transaction(async tx => {
+ await tx.executeRaw("DELETE FROM pages WHERE source_id='default' AND slug='batch/p400'");
+ await tx.executeRaw("INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter) VALUES ('default','batch/new','note','New','New','','{}'::jsonb)");
+ });
+ if (backend === 'postgres') await writer;
+ }
+ }
+ return rows as never;
+ };
+ try {
+ await runExport(engine, ['--dir', dir, '--source', 'default']); await writer;
+ expect(batches).toBe(4);
+ expect(readdirSync(join(dir, 'batch')).length).toBe(513);
+ expect(existsSync(join(dir, 'batch/p400.md'))).toBe(true);
+ expect(existsSync(join(dir, 'batch/new.md'))).toBe(false);
+ } finally { engine.executeRaw = real; await writer; rmSync(dir, { recursive: true, force: true }); }
+ }, 60000);
+});
diff --git a/test/export-stage.test.ts b/test/export-stage.test.ts
new file mode 100644
index 0000000000..77d64ce166
--- /dev/null
+++ b/test/export-stage.test.ts
@@ -0,0 +1,39 @@
+import { expect, test } from 'bun:test';
+import { ExportStage, EXPORT_PAYLOAD_LIMIT, EXPORT_STAGE_LIMIT, exportPathKey } from '../src/core/export-stage.ts';
+
+test('manifest rejects unsafe paths and conservatively folds Unicode aliases', () => {
+ for (const path of ['../escape.md', '/absolute.md', 'a//b.md', 'a/../b.md', 'a\\b.md', 'nul.md', 'a\0b.md', 'a/./b.md', '\ud800.md', 'a'.repeat(241) + '.md']) {
+ expect(() => exportPathKey(path)).toThrow();
+ }
+ expect(exportPathKey('Notes/Café.md')).toBe(exportPathKey('notes/Cafe\u0301.md'));
+ expect(exportPathKey('notes/straße.md')).toBe(exportPathKey('notes/STRASSE.md'));
+ expect(exportPathKey('notes/🚀.md')).toBe('notes/🚀.md');
+});
+test('native path depth and superscript device names refuse during staging', () => {
+ const stage = new ExportStage();
+ try {
+ for (const path of ['COM¹.md', 'lpt².json', 'COM³.txt', [...Array(256).fill('a'), 'leaf.md'].join('/')]) {
+ expect(() => stage.add(path, 'file', 'payload')).toThrow('Unsafe');
+ }
+ expect(stage.db.query("SELECT count(*) AS n FROM paths WHERE kind='file'").get()).toEqual({ n: 0 });
+ } finally { stage.close(); }
+});
+test('staging bounds fail without truncating a payload or silently dropping a file', () => {
+ const stage = new ExportStage();
+ try {
+ expect(() => stage.add('large.md', 'file', 'x'.repeat(EXPORT_PAYLOAD_LIMIT + 1))).toThrow('capacity');
+ expect(stage.db.query("SELECT count(*) AS n FROM paths WHERE kind='file'").get()).toEqual({ n: 0 });
+ stage.bytes = EXPORT_STAGE_LIMIT;
+ expect(() => stage.add('small.md', 'file', 'x')).toThrow('capacity');
+ } finally { stage.close(); }
+});
+test('deep paths use a bounded iterative manifest walk and reserved markers cannot become directories', () => {
+ const stage = new ExportStage();
+ try {
+ stage.add([...Array(100).fill('a'), 'leaf.md'].join('/'), 'file', 'payload');
+ expect(stage.db.query("SELECT count(*) AS n FROM paths WHERE kind='file'").get()).toEqual({ n: 1 });
+ expect(() => stage.add('.gbrain-export-status/leaf.md', 'file', 'payload')).toThrow('collision');
+ stage.add('notes/.raw/item.json', 'file', '{}');
+ expect(() => stage.add('notes/.raw/item.json/leaf.md', 'file', 'payload')).toThrow('collision');
+ } finally { stage.close(); }
+});
diff --git a/test/facts-engine.test.ts b/test/facts-engine.test.ts
index 460b68efeb..dde8c3b6ad 100644
--- a/test/facts-engine.test.ts
+++ b/test/facts-engine.test.ts
@@ -310,16 +310,16 @@ describe('findCandidateDuplicates', () => {
// result set can't flip the test.
const slug = `embed-test-${Math.random().toString(36).slice(2, 10)}`;
await engine.insertFact(
- { fact: 'A', kind: 'fact', entity_slug: slug, source: 'test', embedding: vec(1, 0, 0) },
+ { fact: 'A', kind: 'fact', entity_slug: slug, source: 'test', embedding: vec(1, 0, 0), embedding_model: 'synthetic:model' },
{ source_id: 'default' },
);
await engine.insertFact(
- { fact: 'B', kind: 'fact', entity_slug: slug, source: 'test', embedding: vec(0, 1, 0) },
+ { fact: 'B', kind: 'fact', entity_slug: slug, source: 'test', embedding: vec(0, 1, 0), embedding_model: 'synthetic:model' },
{ source_id: 'default' },
);
const result = await engine.findCandidateDuplicates(
'default', slug, 'q',
- { embedding: vec(1, 0, 0) },
+ { embedding: vec(1, 0, 0), embeddingModel: 'synthetic:model' },
);
const aIdx = result.findIndex(r => r.fact === 'A');
const bIdx = result.findIndex(r => r.fact === 'B');
diff --git a/test/facts/ttl-validity.test.ts b/test/facts/ttl-validity.test.ts
index 071929ea18..e29c4d3dde 100644
--- a/test/facts/ttl-validity.test.ts
+++ b/test/facts/ttl-validity.test.ts
@@ -11,6 +11,7 @@
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { createHash } from 'node:crypto';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
let engine: PGLiteEngine;
@@ -121,23 +122,30 @@ describe('WP5 read-time TTL validity — active reads', () => {
expect(column.dims).toBeGreaterThan(0);
const emb = new Float32Array(column.dims);
emb[0] = 1.0;
+ const embeddingModel = 'test:ttl-validity';
const embEntity = 'people/ttl-embed-example';
const lapsedEmb = await engine.insertFact(
{
fact: 'embed lapsed fact', kind: 'fact', entity_slug: embEntity,
- source: 'test', valid_until: past(), embedding: emb,
+ source: 'test', valid_until: past(), embedding: emb, embedding_model: embeddingModel,
},
{ source_id: SOURCE },
);
const liveEmb = await engine.insertFact(
{
fact: 'embed live fact', kind: 'fact', entity_slug: embEntity,
- source: 'test', embedding: emb,
+ source: 'test', embedding: emb, embedding_model: embeddingModel,
},
{ source_id: SOURCE },
);
+ const stored = await engine.listFactsByEntity(SOURCE, embEntity, { activeOnly: false });
+ expect(stored).toHaveLength(2);
+ for (const row of stored) {
+ expect(row.embedding_model).toBe(embeddingModel);
+ expect(row.embedded_text_hash).toBe(createHash('md5').update(row.fact).digest('hex'));
+ }
const candidates = await engine.findCandidateDuplicates(
- SOURCE, embEntity, 'embed lapsed fact', { embedding: emb },
+ SOURCE, embEntity, 'embed lapsed fact', { embedding: emb, embeddingModel },
);
const ids = candidates.map(r => r.id);
expect(ids).not.toContain(lapsedEmb.id);
diff --git a/test/fixtures/export-native-publish.ts b/test/fixtures/export-native-publish.ts
new file mode 100644
index 0000000000..9d3a20593a
--- /dev/null
+++ b/test/fixtures/export-native-publish.ts
@@ -0,0 +1,17 @@
+import { ExportStage } from '../../src/core/export-stage.ts';
+import { publishExport } from '../../src/core/export-publish.ts';
+
+const destination = process.argv[2];
+if (!destination) throw new Error('A synthetic destination is required');
+const stage = new ExportStage();
+try {
+ stage.add('first.md', 'file', 'Synthetic first page\n');
+ stage.add('nested/second.md', 'file', 'Synthetic second page\n');
+ await publishExport(stage, destination, () => {
+ if (process.argv[3] === 'kill') {
+ console.log('EXPORT_FIXTURE_KILLING');
+ process.kill(process.pid, 'SIGKILL');
+ }
+ });
+ console.log('EXPORT_FIXTURE_COMPLETE');
+} finally { stage.close(); }
diff --git a/test/fixtures/native-export-faults.c b/test/fixtures/native-export-faults.c
new file mode 100644
index 0000000000..117ed5dd71
--- /dev/null
+++ b/test/fixtures/native-export-faults.c
@@ -0,0 +1,57 @@
+#define _GNU_SOURCE
+#include <dlfcn.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static int staged_write;
+
+static int export_file(int fd, const char *suffix) {
+ char link[64], path[4096];
+ snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
+ ssize_t size = readlink(link, path, sizeof(path) - 1);
+ if (size < 0) return 0;
+ path[size] = 0;
+ size_t suffix_length = strlen(suffix);
+ return (size_t)size >= suffix_length && strcmp(path + size - suffix_length, suffix) == 0;
+}
+
+ssize_t write(int fd, const void *data, size_t size) {
+ ssize_t (*real_write)(int, const void *, size_t) = dlsym(RTLD_NEXT, "write");
+ const char *mode = getenv("GBRAIN_EXPORT_TEST_FAULT");
+ if (mode && export_file(fd, ".tmp")) {
+ staged_write = 1;
+ if (!strcmp(mode, "write")) { errno = ENOSPC; return -1; }
+ if (!strcmp(mode, "short-write")) {
+ static int interrupted;
+ if (!interrupted++) { errno = EINTR; return -1; }
+ return real_write(fd, data, size > 7 ? 7 : size);
+ }
+ if (!strcmp(mode, "crash")) {
+ real_write(fd, data, size > 16 ? 16 : size);
+ kill(getpid(), SIGKILL);
+ }
+ }
+ return real_write(fd, data, size);
+}
+
+int fsync(int fd) {
+ int (*real_fsync)(int) = dlsym(RTLD_NEXT, "fsync");
+ const char *mode = getenv("GBRAIN_EXPORT_TEST_FAULT");
+ if (mode && !strcmp(mode, "flush") && export_file(fd, ".tmp")) { errno = EIO; return -1; }
+ struct stat info;
+ if (mode && !strcmp(mode, "directory-flush") && staged_write && fstat(fd, &info) == 0 && S_ISDIR(info.st_mode)) {
+ errno = EIO;
+ return -1;
+ }
+ static unsigned marker_flushes = 0;
+ if (mode && !strcmp(mode, "complete-flush") && export_file(fd, ".gbrain-export-status") && ++marker_flushes == 2) {
+ errno = EIO;
+ return -1;
+ }
+ return real_fsync(fd);
+}
diff --git a/test/fixtures/native-export-process.ts b/test/fixtures/native-export-process.ts
new file mode 100644
index 0000000000..2837e3ccfc
--- /dev/null
+++ b/test/fixtures/native-export-process.ts
@@ -0,0 +1,13 @@
+import { nativeExportPublisher } from '../../src/core/persistence/native-lock.ts';
+
+const publisher = await nativeExportPublisher();
+try {
+ const handle = publisher.beginExport(process.argv[2]!);
+ if (process.argv[3] === 'publish') {
+ publisher.publishExportFile(handle, 'data', Buffer.alloc(4096, 42));
+ publisher.completeExport(handle);
+ publisher.closeExport(handle);
+ }
+} catch {
+ process.exit(2);
+}
diff --git a/test/fixtures/shared-skills-oauth-process.ts b/test/fixtures/shared-skills-oauth-process.ts
index d7ce0d7fc6..3040b7e975 100644
--- a/test/fixtures/shared-skills-oauth-process.ts
+++ b/test/fixtures/shared-skills-oauth-process.ts
@@ -160,8 +160,10 @@ export async function sharedSkillsOAuthProcessCase(databaseUrl: string, editorPr
const asset = await blobResource(stdio, sharedSkillResourceUri(reread.qualified_id, reread.revision, ASSET_PATH));
expect(Buffer.from(asset, 'base64').toString()).toBe('OAuth durable new asset');
expect((await stdio.listTools()).tools.map(t => t.name)).not.toContain('put_skill');
- await expect(call(stdio, 'get_skill', { schema_version: 2, name: 'alpha', source_id: 'hidden' })).rejects.toThrow();
- await expect(stdio.readResource({ uri: forbiddenUri })).rejects.toThrow();
+ const refusal = await call(stdio, 'get_skill', { schema_version: 2, name: 'alpha', source_id: 'hidden' }).then(() => null, error => error);
+ expect(refusal).toMatchObject({ code: 'skill_not_found' });
+ const refusalResource = await stdio.readResource({ uri: forbiddenUri }).then(() => null, error => error);
+ expect(refusalResource).toMatchObject({ code: -32603, data: { error: 'skill_not_found' } });
} catch (error) {
throw new Error(fixtureDiagnostic('New stdio process', `${String(error)}\n${stdioError}`, secrets));
} finally { await stdio.close(); }
diff --git a/test/git-fixture-maintenance.test.ts b/test/git-fixture-maintenance.test.ts
new file mode 100644
index 0000000000..b2ebc19f27
--- /dev/null
+++ b/test/git-fixture-maintenance.test.ts
@@ -0,0 +1,44 @@
+import { expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+
+test('Git fixtures suppress automatic maintenance from their first commit onward', () => {
+ const root = mkdtempSync(join(tmpdir(), 'git-fixture-maintenance-'));
+ const repo = join(root, 'repo');
+ const trace = join(root, 'trace.jsonl');
+ const globalConfig = join(root, 'global.gitconfig');
+ mkdirSync(repo);
+ writeFileSync(globalConfig, '');
+ const env: Record<string, string> = {
+ GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: globalConfig,
+ GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'commit.gpgsign', GIT_CONFIG_VALUE_0: 'false',
+ GIT_TRACE2_EVENT: trace,
+ };
+ for (const key of ['PATH', 'SystemRoot', 'SYSTEMROOT', 'WINDIR', 'PATHEXT', 'TEMP', 'TMP']) {
+ if (process.env[key]) env[key] = process.env[key]!;
+ }
+ try {
+ const script = `
+ import { makeGitFixture } from ${JSON.stringify(resolve(import.meta.dir, 'helpers/git-fixture.ts'))};
+ const fixture = await makeGitFixture(${JSON.stringify(repo)});
+ await Bun.write(${JSON.stringify(join(repo, 'fixture.txt'))}, 'synthetic fixture');
+ fixture.commitAll('Commit synthetic fixture');
+ fixture.reset();
+ `;
+ const result = Bun.spawnSync([process.execPath, '--no-env-file', '-e', script], {
+ env, stdout: 'pipe', stderr: 'pipe',
+ });
+ expect({ exitCode: result.exitCode, stderr: result.stderr.toString() }).toEqual({ exitCode: 0, stderr: '' });
+ const events = readFileSync(trace, 'utf8').trim().split('\n').map(line => JSON.parse(line));
+ const children = events.filter(event => event.event === 'child_start');
+ expect(children.filter(event => event.argv?.some((arg: string) => arg === 'maintenance' || arg === 'gc'))).toEqual([]);
+ for (const [key, value] of [['maintenance.auto', 'false'], ['gc.auto', '0']] as const) {
+ expect(execFileSync('git', ['-C', repo, 'config', '--local', '--get', key], { env, encoding: 'utf8' }).trim()).toBe(value);
+ }
+ expect(execFileSync('git', ['-C', repo, 'rev-list', '--count', 'HEAD'], { env, encoding: 'utf8' }).trim()).toBe('2');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+}, 30000);
diff --git a/test/google-attachment-backfill.test.ts b/test/google-attachment-backfill.test.ts
new file mode 100644
index 0000000000..b8611d2663
--- /dev/null
+++ b/test/google-attachment-backfill.test.ts
@@ -0,0 +1,333 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { prepareConnectorMutation, withConnectorSync } from '../src/core/persistence/connector-sync.ts';
+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';
+import { persistenceFileHash, publishMutation } from '../src/core/persistence/coordinator.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
+import { parseGoogleSourceConfig, runGoogleAttachmentBackfill } from '../src/core/google/google-source.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { sanitizeRemoteBody } from '../src/core/remote-body.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { syncLockId } from '../src/core/db-lock.ts';
+import { createConnectorFixture, options, json, sourceCheckpoint } from './helpers/connector-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const { engines, env, source, boundSource, setup, teardown } = createConnectorFixture();
+beforeAll(setup, 120_000);
+afterAll(teardown);
+const config = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+const claim = 'syntheticwithdrawalsentinel prefers amber fixtures';
+const ctx = (engine: BrainEngine, sourceId: string) => ({ engine, sourceId, config: { engine: engine.kind }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } });
+const slug = (n: number) => `emails/2026/09/thread-${n}`;
+const msg = (n: number) => `message${String(n).padStart(10, '0')}`;
+const content = (n: number) => `---\ntype: email\ntitle: Synthetic historical thread\nthread_id: thread${n}\naccount: [email protected]\nmessage_ids: [${msg(n)}]\nvisibility: private\ncustom: preserved\n---\n# Edited synthetic message\n\nKeep this exact user-edited prose.\n${renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true }])}\n`;
+const fetcher = async (url: string) => {
+ if (url.includes('/profile')) return json({ emailAddress: config.g_account, historyId: '100' });
+ const n = Number(url.match(/threads\/thread(\d+)/)?.[1]);
+ if (!n) throw new Error('Unexpected metadata-only fixture endpoint');
+ return json({ id: `thread${n}`, messages: [{ id: msg(n), payload: { mimeType: 'multipart/mixed', parts: [
+ { mimeType: 'text/plain', body: { data: Buffer.from('STALE PROVIDER BODY MUST NEVER BE REPLAYED').toString('base64') } },
+ { partId: '1', filename: 'fixture.pdf', mimeType: 'application/pdf', body: { attachmentId: 'opaque', size: 17 } },
+ ] } }] });
+};
+
+async function seed(engine: BrainEngine, bound = false, count = 1) {
+ const f = await (bound ? boundSource : source)(engine, config);
+ const cfg = parseGoogleSourceConfig(config, f.dir);
+ await withConnectorSync(engine, f.id, 'google', cfg, options, async managed => {
+ for (let n = 1; n <= count; n++) await managed!.importMarkdown(`${slug(n)}.md`, content(n));
+ });
+ return { ...f, cfg };
+}
+
+test('historical repair preserves current body, facts, frontmatter and private receipt visibility across bounded resume', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const bound of [false, true]) {
+ const f = await seed(engine, bound, 2);
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const facts = await engine.executeRaw('SELECT * FROM facts WHERE source_id=$1 ORDER BY id', [f.id]);
+ const first = await runGoogleAttachmentBackfill(engine, f.id, f.cfg, { limit: 1 }, fetcher);
+ expect(first).toMatchObject({ status: 'paused', processed: 1, inspected: 1, complete: false });
+ const after = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.timeline).toBe(before.page.timeline);
+ const { gmail_attachment_receipts: receipts, ...rest } = after.page.frontmatter;
+ expect(rest).toEqual(before.page.frontmatter);
+ expect(receipts).toMatchObject({ version: 1, account: config.g_account, messages: [{ messageId: msg(1), inspection: { state: 'present' } }] });
+ expect(after.tags).toEqual(before.tags);
+ expect(await engine.executeRaw('SELECT * FROM facts WHERE source_id=$1 ORDER BY id', [f.id])).toEqual(facts);
+ expect(await engine.getPage(slug(1), { sourceId: f.id, excludePrivate: true })).toBeNull();
+ await expect(operationsByName.get_page.handler({ ...ctx(engine, f.id), remote: true }, { slug: slug(1) })).rejects.toMatchObject({ code: 'page_not_found' });
+ expect(await operationsByName.get_page.handler(ctx(engine, f.id), { slug: slug(1) })).toMatchObject({ frontmatter: { gmail_attachment_receipts: receipts } });
+ if (bound) {
+ const file = readFileSync(join(f.dir, `${slug(1)}.md`), 'utf8');
+ expect(file).toContain('fixture.pdf');
+ expect(file).toContain('Keep this exact user-edited prose.');
+ expect(file).not.toContain('STALE PROVIDER BODY');
+ }
+ await disposePersistenceConsumer(engine);
+ expect(await runGoogleAttachmentBackfill(engine, f.id, f.cfg, { limit: 1 }, fetcher)).toMatchObject({ status: 'complete', processed: 1, inspected: 2 });
+ const revision = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.revision;
+ expect(await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).toMatchObject({ status: 'complete', processed: 0 });
+ expect((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.revision).toBe(revision);
+ expect(await engine.executeRaw("SELECT e.id FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.source_id=$1 AND r.intent->>'kind'='managed_connector_google_receipts' AND e.kind<>'git'", [f.id])).toHaveLength(0);
+ }
+}), 120_000);
+
+test('repair uses current edits and withdrawals rather than the fetched historical body, in both completion orders', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const order of ['before', 'after'] as const) {
+ const f = await seed(engine, true);
+ const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 ORDER BY id LIMIT 1', [f.id]);
+ const modify = async () => {
+ const current = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ await submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), expected_revision: current.revision,
+ content: serializePageToMarkdown({ ...current.page, compiled_truth: current.page.compiled_truth + '\nAdditional local edit.\n' }, current.tags) } });
+ await submitForgetMutation(ctx(engine, f.id), 'forget_fact', { id: Number(fact.id) });
+ await disposePersistenceConsumer(engine);
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 100 });
+ };
+ if (order === 'before') await modify();
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const ledger = await engine.executeRaw('SELECT * FROM fact_withdrawals WHERE source_id=$1', [f.id]);
+ expect((await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).status).toBe('complete');
+ expect((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(await engine.executeRaw('SELECT * FROM fact_withdrawals WHERE source_id=$1', [f.id])).toEqual(ledger);
+ if (order === 'after') await modify();
+ const final = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(sanitizeRemoteBody(final.page.compiled_truth)).not.toContain(claim);
+ expect(final.page.compiled_truth).toContain('Additional local edit.');
+ expect((await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).processed).toBe(0);
+ expect(sanitizeRemoteBody((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.page.compiled_truth)).not.toContain(claim);
+ }
+}), 120_000);
+
+test('failure, cancellation, unknown ownership and lease loss never skip an uncommitted historical page', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const failure of ['fetch', 'cancel', 'ownership', 'lease'] as const) {
+ const f = await seed(engine, true);
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const abort = new AbortController();
+ if (failure === 'ownership') await submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), expected_revision: before.revision,
+ content: serializePageToMarkdown({ ...before.page, frontmatter: { ...before.page.frontmatter, gmail_attachment_receipts: 'user-owned text' } }, before.tags) } });
+ const run = () => runGoogleAttachmentBackfill(engine, f.id, f.cfg, { signal: abort.signal }, async url => {
+ if (url.includes('/threads/')) {
+ if (failure === 'fetch') throw new Error('synthetic interruption');
+ if (failure === 'cancel') abort.abort();
+ if (failure === 'lease') await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [syncLockId(f.id)]);
+ }
+ return fetcher(url);
+ });
+ await expect(run()).rejects.toBeDefined();
+ const checkpoint = JSON.stringify(await sourceCheckpoint(engine, f.id));
+ expect(checkpoint).toContain('"afterPageId":0');
+ expect((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.page.compiled_truth).toBe(before.page.compiled_truth);
+ if (failure !== 'ownership') expect((await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).status).toBe('complete');
+ }
+}), 120_000);
+
+test('an edit during Gmail fetch is preserved, while delete/recreate cannot retarget historical metadata', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const change of ['edit', 'delete-recreate'] as const) {
+ const f = await seed(engine, true);
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const entered = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const repair = runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async url => {
+ if (url.includes('/threads/')) { entered.resolve(); await release.promise; }
+ return fetcher(url);
+ });
+ repair.catch(() => {});
+ await entered.promise;
+ try {
+ if (change === 'delete-recreate') {
+ await submitPageMutation(ctx(engine, f.id), { operation: 'delete_page', params: { slug: slug(1), purge: true, expected_revision: before.revision } });
+ await submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), content: content(1) } });
+ } else {
+ await submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), expected_revision: before.revision,
+ content: serializePageToMarkdown({ ...before.page, compiled_truth: before.page.compiled_truth + '\nConcurrent editor text.\n' }, before.tags) } });
+ }
+ } finally { release.resolve(); }
+ if (change === 'edit') {
+ expect((await repair).status).toBe('complete');
+ const current = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(current.page.compiled_truth).toContain('Concurrent editor text.');
+ await expect(submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), expected_revision: before.revision, content: content(1) } })).rejects.toMatchObject({ code: 'revision_conflict' });
+ expect((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.page.frontmatter.gmail_attachment_receipts).toEqual(current.page.frontmatter.gmail_attachment_receipts);
+ } else {
+ await expect(repair).rejects.toMatchObject({ code: 'page_identity_changed' });
+ expect((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.page.frontmatter.gmail_attachment_receipts).toBeUndefined();
+ expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).toContain('"afterPageId":0');
+ }
+ }
+}), 120_000);
+
+test('withdrawal wins after receipt preparation but before real canonical publication', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await seed(engine, true);
+ await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher);
+ await disposePersistenceConsumer(engine);
+ const [template] = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' LIMIT 1", [f.id]);
+ const snapshot = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const [checkpoint] = await engine.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [template.intent!.checkpointKey]);
+ const intent = structuredClone(template.intent!);
+ intent.expected_revision = snapshot.revision;
+ intent.checkpointBefore = checkpoint.completed_keys;
+ intent.fileBeforeHash = persistenceFileHash(join(f.dir, `${slug(1)}.md`));
+ (intent.googleReceipts as any).messages[0].inspection.attachments[0].filename = 'updated-fixture.pdf';
+ const admitted = await admitWrite(engine, { principal: { kind: template.principal_kind, id: template.principal_id }, requestId: randomUUID(),
+ operation: 'submit_job', sourceId: f.id, sourceIncarnation: snapshot.sourceIncarnation, slug: slug(1), pageId: snapshot.page.id,
+ callerIntent: intent, intent, authority: template.authority, worktreeId: template.worktree_id!, topologyGeneration: template.topology_generation! });
+ const claimed = (await claimNextWrite(engine, localHostId()))!;
+ expect(claimed.id).toBe(admitted.id);
+ const prepared = await prepareConnectorMutation(engine, claimed);
+ const [fact] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 ORDER BY id LIMIT 1', [f.id]);
+ await submitForgetMutation(ctx(engine, f.id), 'forget_fact', { id: Number(fact.id) });
+ const result = await publishMutation(engine, claimed, prepared);
+ expect(result.state).toBe('conflict');
+ const current = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(sanitizeRemoteBody(current.page.compiled_truth)).not.toContain(claim);
+ expect(JSON.stringify(current.page.frontmatter.gmail_attachment_receipts)).not.toContain('updated-fixture.pdf');
+ expect(await engine.executeRaw('SELECT fact_hash FROM fact_withdrawals WHERE source_id=$1', [f.id])).toHaveLength(1);
+ }
+}), 120_000);
+
+test('incomplete inspection is durable but cannot advance progress, and a foreign account cannot start repair', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await seed(engine);
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ await expect(runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async () => json({ emailAddress: '[email protected]', historyId: '100' }))).rejects.toMatchObject({ code: 'source_changed' });
+ expect(await sourceCheckpoint(engine, f.id)).toHaveLength(0);
+ const incomplete = await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async url => url.includes('/profile') ? fetcher(url)
+ : json({ id: 'thread1', messages: [{ id: msg(1) }] }));
+ expect(incomplete).toMatchObject({ status: 'incomplete', complete: false, processed: 0, inspected: 0 });
+ const after = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.frontmatter.gmail_attachment_receipts).toMatchObject({ messages: [{ inspection: { state: 'incomplete', reason: 'missing_payload' } }] });
+ expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).toContain('"afterPageId":0');
+ expect((await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).status).toBe('complete');
+ }
+}), 120_000);
+
+test('malformed MIME leaves the historical cursor resumable instead of declaring completion', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const payload of [{ mimeType: 'multipart/mixed' }, { mimeType: 'multipart/mixed', parts: [] }, { body: {} }, { mimeType: '', body: {} }]) {
+ const f = await seed(engine);
+ const result = await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async url => url.includes('/profile') ? fetcher(url)
+ : json({ id: 'thread1', messages: [{ id: msg(1), payload }] }));
+ expect(result).toMatchObject({ status: 'incomplete', complete: false, processed: 0, inspected: 0 });
+ expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).toContain('"afterPageId":0');
+ const current = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(current.page.frontmatter.gmail_attachment_receipts).toMatchObject({ messages: [{ inspection: { state: 'incomplete', reason: 'malformed_part', attachments: [] } }] });
+ expect((await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).status).toBe('complete');
+ }
+}), 120_000);
+
+test('confirmed upstream thread absence preserves history and prior receipts while later pages repair', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const bound of [false, true]) {
+ const f = await seed(engine, bound, 2);
+ const original = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const prior = { version: 1, account: config.g_account, threadId: 'thread1', messages: [{ messageId: msg(1), inspection: {
+ state: 'present', attachments: [{ id: 'retained-id', account: config.g_account, messageId: msg(1), partId: 'old', filename: 'retained.pdf',
+ mimeType: 'application/pdf', size: 9, attachmentId: 'retained-opaque', kind: 'document', fetched: false, indexed: false }],
+ } }] };
+ await withConnectorSync(engine, f.id, 'google', f.cfg, options, async managed => {
+ await managed!.importMarkdown(`${slug(1)}.md`, serializePageToMarkdown({ ...original.page,
+ frontmatter: { ...original.page.frontmatter, gmail_attachment_receipts: prior } }, original.tags));
+ });
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const result = await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async url => url.includes('/threads/thread1?') ? json({}, 404) : fetcher(url));
+ expect(result).toMatchObject({ status: 'complete', processed: 2, inspected: 1, unavailable: 1, unavailableMessages: 1, inspection_complete: false });
+ const after = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.frontmatter).toEqual({ ...before.page.frontmatter, gmail_attachment_receipts: { ...prior, unavailable: 'thread_not_found',
+ messages: [{ ...prior.messages[0], unavailable: 'thread_not_found' }] } });
+ expect(await engine.getPage(slug(1), { sourceId: f.id, excludePrivate: true })).toBeNull();
+ expect((await engine.readPageSnapshot(slug(2), { sourceId: f.id }))!.page.frontmatter.gmail_attachment_receipts).toMatchObject({ messages: [{ inspection: { state: 'present' } }] });
+ await disposePersistenceConsumer(engine);
+ expect(await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).toMatchObject({ processed: 0, inspected: 1, unavailable: 1, unavailableMessages: 1 });
+ }
+}), 120_000);
+
+test('disappeared historical message identities retain known receipts or explicit not-inspected diagnostics', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await seed(engine, true, 2);
+ const original = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ const prior = { version: 1, account: config.g_account, threadId: 'thread1', messages: [{ messageId: msg(3), inspection: { state: 'none', attachments: [] } }] };
+ await submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), expected_revision: original.revision,
+ content: serializePageToMarkdown({ ...original.page, frontmatter: { ...original.page.frontmatter, message_ids: [msg(1), msg(3), msg(4)], gmail_attachment_receipts: prior } }, original.tags) } });
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).toMatchObject({ status: 'complete', processed: 2, inspected: 1, unavailable: 1, unavailableMessages: 2, inspection_complete: false });
+ const after = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ const { gmail_attachment_receipts: receipts, ...rest } = after.page.frontmatter;
+ expect(rest).toEqual(Object.fromEntries(Object.entries(before.page.frontmatter).filter(([key]) => key !== 'gmail_attachment_receipts')));
+ expect(receipts).toMatchObject({ messages: [
+ { messageId: msg(1), inspection: { state: 'present' } },
+ { ...prior.messages[0], unavailable: 'message_not_found' },
+ { messageId: msg(4), inspection: { state: 'not_inspected', attachments: [] }, unavailable: 'message_not_found' },
+ ] });
+ }
+}), 120_000);
+
+test('authorization errors and malformed thread identities never become upstream absence', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const failure of ['forbidden', 'rate-limit', 'gone', 'missing-id', 'duplicate-id', 'empty', 'ownership', 'incomplete-other-message']) {
+ const f = await seed(engine, true, 2);
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ if (failure === 'ownership') await submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), expected_revision: before.revision,
+ content: serializePageToMarkdown({ ...before.page, frontmatter: { ...before.page.frontmatter, gmail_attachment_receipts: 'not-owned' } }, before.tags) } });
+ await expect(runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async url => {
+ if (!url.includes('/threads/thread1?')) return fetcher(url);
+ if (failure === 'forbidden') return json({}, 403);
+ if (failure === 'rate-limit') return json({}, 429, { 'retry-after': '0' });
+ if (failure === 'gone') return json({}, 410);
+ if (failure === 'ownership') return json({}, 404);
+ if (failure === 'incomplete-other-message') return json({ id: 'thread1', messages: [{ id: msg(2) }] });
+ return json({ id: 'thread1', messages: failure === 'empty' ? [] : failure === 'missing-id' ? [{ payload: { mimeType: 'text/plain' } }]
+ : [{ id: msg(1) }, { id: msg(1) }] });
+ })).rejects.toBeDefined();
+ expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).toContain('"afterPageId":0');
+ expect((await engine.readPageSnapshot(slug(2), { sourceId: f.id }))!.page.frontmatter.gmail_attachment_receipts).toBeUndefined();
+ expect((await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!.page.compiled_truth).toBe(before.page.compiled_truth);
+ }
+}), 120_000);
+
+test('malformed historical message identities do not become confirmed unavailable receipts', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const messageId of [' ', 'bad/id', 'a'.repeat(129)]) {
+ const f = await seed(engine, true);
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ await submitPageMutation(ctx(engine, f.id), { operation: 'put_page', params: { slug: slug(1), expected_revision: before.revision,
+ content: serializePageToMarkdown({ ...before.page, frontmatter: { ...before.page.frontmatter, message_ids: [messageId] } }, before.tags) } });
+ const edited = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ await expect(runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async url => url.includes('/threads/') ? json({}, 404) : fetcher(url)))
+ .rejects.toMatchObject({ code: 'revision_conflict' });
+ expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).toContain('"afterPageId":0');
+ expect(await engine.readPageSnapshot(slug(1), { sourceId: f.id })).toEqual(edited);
+ }
+}), 120_000);
+
+test('historical metadata response overflow cannot advance a managed cursor or change historical content', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await seed(engine, false, 2);
+ const before = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ await expect(runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, async url => {
+ if (url.includes('/profile')) return fetcher(url);
+ const request = new URL(url);
+ expect(request.pathname).toBe('/gmail/v1/users/me/threads/thread1');
+ const fields = request.searchParams.get('fields');
+ expect(fields).toContain('body(attachmentId,size)');
+ expect(fields).not.toMatch(/\b(data|raw|snippet)\b|\*/);
+ return json({ id: 'thread1', messages: [{ id: msg(1), payload: { mimeType: 'application/pdf', filename: 'x'.repeat(2 * 1024 * 1024) } }] });
+ })).rejects.toMatchObject({ code: 'BODY_TOO_LARGE' });
+ expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).toContain('"afterPageId":0');
+ const after = (await engine.readPageSnapshot(slug(1), { sourceId: f.id }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.frontmatter).toEqual(before.page.frontmatter);
+ expect((await engine.readPageSnapshot(slug(2), { sourceId: f.id }))!.page.frontmatter.gmail_attachment_receipts).toBeUndefined();
+ expect(await runGoogleAttachmentBackfill(engine, f.id, f.cfg, {}, fetcher)).toMatchObject({ status: 'complete', inspected: 2 });
+ }
+}), 120_000);
diff --git a/test/google-attachment-receipts.test.ts b/test/google-attachment-receipts.test.ts
new file mode 100644
index 0000000000..2824fe7366
--- /dev/null
+++ b/test/google-attachment-receipts.test.ts
@@ -0,0 +1,231 @@
+import { describe, expect, test } from 'bun:test';
+import { GmailClient } from '../src/core/google/google-clients.ts';
+import { renderThreadPage } from '../src/core/google/google-render.ts';
+import { GMAIL_MIME_LIMITS, inspectGmailAttachments, renderAttachmentInspection, type GmailMimePart } from '../src/core/google/attachment-receipts.ts';
+
+const tokens = { getAccessToken: async () => 'synthetic', forceRefresh: async () => 'synthetic' };
+
+type SelectedFields = { [key: string]: SelectedFields | null };
+
+function projectedMetadata(url: string, payload: GmailMimePart) {
+ const request = new URL(url);
+ expect(request.pathname).toBe('/gmail/v1/users/me/threads/abcdef');
+ expect(request.searchParams.get('format')).toBe('full');
+ const fields = request.searchParams.get('fields')!;
+ expect(fields).toBeTruthy();
+ let offset = 0;
+ const parse = (): SelectedFields => {
+ const selected: SelectedFields = {};
+ while (offset < fields.length && fields[offset] !== ')') {
+ const name = /^[A-Za-z]+/.exec(fields.slice(offset))?.[0];
+ if (!name) throw new Error('Unexpected partial-response selector');
+ offset += name.length;
+ selected[name] = null;
+ if (fields[offset] === '(') {
+ offset++;
+ selected[name] = parse();
+ expect(fields[offset++]).toBe(')');
+ }
+ if (fields[offset] !== ',') break;
+ offset++;
+ }
+ return selected;
+ };
+ const selected = parse();
+ expect(offset).toBe(fields.length);
+ expect(Object.keys(selected).sort()).toEqual(['id', 'messages']);
+ expect(Object.keys(selected.messages!).sort()).toEqual(['id', 'internalDate', 'labelIds', 'payload']);
+ let part = selected.messages!.payload!;
+ for (let depth = 0; depth <= GMAIL_MIME_LIMITS.depth; depth++) {
+ expect(Object.keys(part).sort()).toEqual(['body', 'filename', 'headers', 'mimeType', 'partId', 'parts']);
+ expect(part.body).toEqual({ attachmentId: null, size: null });
+ expect(part.headers).toEqual({ name: null, value: null });
+ part = part.parts!;
+ }
+ expect(part).toEqual({ partId: null, mimeType: null });
+ const project = (value: any, selector: SelectedFields): any => Array.isArray(value)
+ ? value.map(item => project(item, selector))
+ : Object.fromEntries(Object.entries(selector).filter(([key]) => value[key] !== undefined)
+ .map(([key, children]) => [key, children ? project(value[key], children) : value[key]]));
+ const wire = JSON.stringify(project({ id: 'abcdef', messages: [{ id: '123abcdef4567890', internalDate: '1700000000000', payload }] }, selected));
+ expect(wire).not.toContain('INLINE_BODY_SENTINEL');
+ expect(wire).not.toContain('"data":');
+ return new Response(wire, { headers: { 'content-type': 'application/json' } });
+}
+
+async function thread(payload: unknown, account = '[email protected]') {
+ const urls: string[] = [];
+ const client = new GmailClient(tokens, async (url) => {
+ urls.push(url);
+ return Response.json({ id: 'abcdef', messages: [{ id: '123abcdef4567890', internalDate: '1700000000000', payload }] });
+ });
+ const result = await client.getThread('abcdef', account);
+ expect(urls).toEqual(['https://gmail.googleapis.com/gmail/v1/users/me/threads/abcdef?format=full']);
+ return result;
+}
+
+describe('Gmail attachment receipts', () => {
+ test('historical MIME requests project metadata at every depth without transferring inline body data', async () => {
+ let calls = 0;
+ const client = new GmailClient(tokens, async url => {
+ calls++;
+ return projectedMetadata(url, { partId: '', mimeType: 'multipart/mixed', body: { data: 'INLINE_BODY_SENTINEL' }, parts: [
+ { partId: '0', mimeType: 'text/plain', body: { data: 'INLINE_BODY_SENTINEL', size: 20 } },
+ { partId: '1', mimeType: 'multipart/mixed', parts: [
+ { partId: '1.0', filename: 'nested.pdf', mimeType: 'application/pdf', body: { data: 'INLINE_BODY_SENTINEL', attachmentId: 'opaque', size: 42 } },
+ ] },
+ ] });
+ });
+ const result = await client.getThread('abcdef', '[email protected]', { metadataOnly: true });
+ expect(calls).toBe(1);
+ expect(result.messages[0].bodyText).toBe('');
+ expect(result.messages[0].attachmentInspection).toMatchObject({ state: 'present', attachments: [
+ { partId: '1.0', filename: 'nested.pdf', attachmentId: 'opaque', size: 42, fetched: false, indexed: false },
+ ] });
+ });
+
+ test('projected depth sentinel distinguishes overflow from a complete MIME leaf', async () => {
+ for (const depth of [GMAIL_MIME_LIMITS.depth, GMAIL_MIME_LIMITS.depth + 1, GMAIL_MIME_LIMITS.depth + 4]) {
+ let payload: GmailMimePart = { partId: 'leaf', mimeType: 'text/plain', body: { data: 'INLINE_BODY_SENTINEL' } };
+ for (let n = 0; n < depth; n++) payload = { partId: `node${n}`, mimeType: 'multipart/mixed', parts: [payload] };
+ const client = new GmailClient(tokens, async url => projectedMetadata(url, payload));
+ const result = await client.getThread('abcdef', '[email protected]', { metadataOnly: true });
+ expect(result.messages[0].attachmentInspection).toMatchObject(depth > GMAIL_MIME_LIMITS.depth
+ ? { state: 'incomplete', reason: 'depth_limit', attachments: [] }
+ : { state: 'none', attachments: [] });
+ }
+ });
+
+ test('projected wide MIME metadata still reports incomplete inspection', async () => {
+ const client = new GmailClient(tokens, async url => projectedMetadata(url, { partId: '', mimeType: 'multipart/mixed',
+ parts: Array.from({ length: GMAIL_MIME_LIMITS.parts + 1 }, (_, n) => ({ partId: String(n), mimeType: 'text/plain', body: { data: 'INLINE_BODY_SENTINEL' } })),
+ }));
+ const result = await client.getThread('abcdef', '[email protected]', { metadataOnly: true });
+ expect(result.messages[0].attachmentInspection).toMatchObject({ state: 'incomplete', reason: 'part_limit' });
+ });
+
+ test('historical metadata response limits cancel oversized decoded streams before JSON parsing', async () => {
+ let cancelled = false;
+ let reads = 0;
+ const client = new GmailClient(tokens, async url => {
+ expect(new URL(url).searchParams.has('fields')).toBe(true);
+ return new Response(new ReadableStream({
+ pull(controller) { reads++; controller.enqueue(new Uint8Array(256 * 1024)); },
+ cancel() { cancelled = true; },
+ }), { headers: { 'content-encoding': 'gzip', 'content-length': '1' } });
+ });
+ await expect(client.getThread('abcdef', '[email protected]', { metadataOnly: true })).rejects.toMatchObject({ code: 'BODY_TOO_LARGE' });
+ expect(cancelled).toBe(true);
+ expect(reads).toBeLessThan(13);
+ });
+
+ test('normalizer and renderer retain attachment metadata without downloading bytes', async () => {
+ const result = await thread({ mimeType: 'multipart/mixed', headers: [{ name: 'From', value: '[email protected]' }], parts: [
+ { mimeType: 'text/plain', body: { data: 'SGVsbG8=' } },
+ { partId: '1', mimeType: 'application/pdf', filename: 'report.pdf', body: { attachmentId: 'opaque-id', size: 42 } },
+ ] });
+ expect(result.messages[0].attachmentInspection).toMatchObject({ state: 'present', attachments: [
+ { filename: 'report.pdf', mimeType: 'application/pdf', size: 42, attachmentId: 'opaque-id', partId: '1', fetched: false, indexed: false },
+ ] });
+ expect(result.messages[0].bodyText).toBe('Hello');
+ const rendered = renderThreadPage(result)!.markdown;
+ expect(rendered).toContain('report.pdf');
+ expect(rendered).toContain('not downloaded; not indexed');
+ });
+
+ test('four inspection states stay distinct and missing payload never means no attachments', async () => {
+ expect(renderAttachmentInspection()).toBe('Attachments: not inspected.');
+ expect(inspectGmailAttachments(undefined, '[email protected]', 'message').state).toBe('incomplete');
+ expect(inspectGmailAttachments({}, '[email protected]', 'message')).toEqual({ state: 'incomplete', reason: 'malformed_part', attachments: [] });
+ const result = await thread({ mimeType: 'text/plain', body: { data: 'SGVsbG8=' } });
+ expect(result.messages[0].attachmentInspection).toEqual({ state: 'none', attachments: [] });
+ expect(renderAttachmentInspection(result.messages[0].attachmentInspection)).toContain('inspected; none found');
+ });
+
+ test('nested duplicate names retain account/message/part identities and classify inline and calendar parts', () => {
+ const payload = { mimeType: 'multipart/mixed', parts: [
+ { mimeType: 'multipart/alternative', parts: [{ mimeType: 'text/plain', body: { data: 'SGk=' } }, { mimeType: 'text/html', body: { data: 'SGk=' } }] },
+ { filename: 'same.pdf', mimeType: 'application/pdf', body: { size: 10 } },
+ { filename: 'same.pdf', mimeType: 'application/pdf', body: { size: 11 } },
+ { filename: '', mimeType: 'image/png', headers: [{ name: 'Content-ID', value: '<image>' }], body: { attachmentId: 'inline', size: 9 } },
+ { mimeType: 'text/calendar', body: { size: 20 } },
+ ] };
+ const a = inspectGmailAttachments(payload, '[email protected]', 'one');
+ expect(a.state).toBe('present');
+ expect(a.attachments.map(p => p.kind)).toEqual(['document', 'document', 'inline', 'calendar']);
+ expect(new Set(a.attachments.map(p => p.id)).size).toBe(4);
+ expect(a).toEqual(inspectGmailAttachments(payload, '[email protected]', 'one'));
+ expect(a.attachments[0].id).not.toBe(inspectGmailAttachments(payload, '[email protected]', 'one').attachments[0].id);
+ expect(a.attachments[0].id).not.toBe(inspectGmailAttachments(payload, '[email protected]', 'two').attachments[0].id);
+ expect(a.attachments[0].attachmentId).toBeNull();
+ });
+
+ test('unclassifiable empty leaves and childless multipart containers remain incomplete', async () => {
+ for (const payload of [{ mimeType: 'multipart/mixed' }, { mimeType: 'multipart/mixed', parts: [] }, { body: {} }, { mimeType: '', body: {} }]) {
+ const result = await thread(payload);
+ expect(result.messages[0].attachmentInspection).toEqual({ state: 'incomplete', reason: 'malformed_part', attachments: [] });
+ }
+ expect(inspectGmailAttachments({ mimeType: 'text/plain', body: {} }, '[email protected]', 'message')).toEqual({ state: 'none', attachments: [] });
+ expect(inspectGmailAttachments({ mimeType: 'text/html', body: { size: 0 } }, '[email protected]', 'message')).toEqual({ state: 'none', attachments: [] });
+ expect(inspectGmailAttachments({ filename: 'empty.pdf', mimeType: 'application/pdf', body: { size: 0 } }, '[email protected]', 'message')).toMatchObject({ state: 'present', attachments: [{ filename: 'empty.pdf', size: 0 }] });
+ });
+
+ test('deep, wide, malformed and oversized metadata has a bounded incomplete receipt', () => {
+ let deep: GmailMimePart = { filename: 'hidden.pdf', mimeType: 'application/pdf' };
+ for (let n = 0; n < 1000; n++) deep = { mimeType: 'multipart/mixed', parts: [deep] };
+ expect(inspectGmailAttachments(deep, '[email protected]', 'one')).toMatchObject({ state: 'incomplete', reason: 'depth_limit' });
+ const wide = { mimeType: 'multipart/mixed', parts: Array.from({ length: 10_000 }, () => ({ mimeType: 'text/plain' })) };
+ expect(inspectGmailAttachments(wide, '[email protected]', 'one')).toMatchObject({ state: 'incomplete', reason: 'part_limit' });
+ const malformed = { parts: [null, { filename: 1 }] } as unknown as GmailMimePart;
+ expect(inspectGmailAttachments(malformed, '[email protected]', 'one').state).toBe('incomplete');
+ for (const filename of ['null\0byte.pdf', 'unpaired\ud800.pdf']) {
+ expect(inspectGmailAttachments({ filename, mimeType: 'application/pdf' }, '[email protected]', 'one')).toMatchObject({ state: 'incomplete', reason: 'malformed_part', attachments: [] });
+ }
+ const large = { filename: 'x'.repeat(GMAIL_MIME_LIMITS.receiptBytes + 1) };
+ expect(inspectGmailAttachments(large, '[email protected]', 'one')).toMatchObject({ state: 'incomplete', reason: 'receipt_bytes_limit', attachments: [] });
+ const aggregate = { parts: Array.from({ length: 100 }, () => ({ filename: 'é'.repeat(1000), mimeType: 'application/pdf' })) };
+ const result = inspectGmailAttachments(aggregate, '[email protected]', 'one');
+ expect(result.state).toBe('incomplete');
+ expect(Buffer.byteLength(JSON.stringify(result.attachments))).toBeLessThan(GMAIL_MIME_LIMITS.receiptBytes);
+ });
+
+ test('untrusted filenames render as inert data and document text is not selected as the message body', async () => {
+ const result = await thread({ parts: [
+ { filename: '[x](javascript:alert(1))\n<script>bad</script>`', mimeType: 'text/plain', body: { data: 'U2VjcmV0IGRvY3VtZW50' } },
+ { mimeType: 'text/plain', body: { data: 'SGVsbG8=' } },
+ ] });
+ expect(result.messages[0].bodyText).toBe('Hello');
+ const text = renderAttachmentInspection(result.messages[0].attachmentInspection);
+ expect(text).not.toContain('<script>');
+ expect(text).not.toContain('[x](');
+ expect(text).not.toContain('\n<script>');
+ expect(text).toContain('&#91;x&#93;');
+ });
+
+ test('missing message identity gets deterministic receipts but no fabricated Gmail citation', async () => {
+ const client = new GmailClient(tokens, async () => Response.json({ id: 'abcdef', messages: [{ payload: { filename: 'file.pdf', mimeType: 'application/pdf' } }] }));
+ const first = await client.getThread('abcdef', '[email protected]');
+ expect(first).toEqual(await client.getThread('abcdef', '[email protected]'));
+ expect(first.messages[0].attachmentInspection?.attachments[0].messageId).toBe('missing:abcdef:0');
+ expect(renderThreadPage(first)!.markdown).toContain('Gmail message link unavailable.');
+ });
+
+ test('aggregate receipt bytes are bounded across messages in one thread', async () => {
+ const client = new GmailClient(tokens, async () => Response.json({ id: 'abcdef', messages: Array.from({ length: 100 }, (_, n) => ({
+ id: `message${String(n).padStart(10, '0')}`, payload: { filename: 'é'.repeat(2000), mimeType: 'application/pdf', body: { attachmentId: 'opaque', size: 42 } },
+ })) }));
+ const result = await client.getThread('abcdef', '[email protected]', { metadataOnly: true });
+ expect(result.messages.some(m => m.attachmentInspection?.state === 'incomplete')).toBe(true);
+ expect(Buffer.byteLength(JSON.stringify(result.messages.flatMap(m => m.attachmentInspection?.attachments ?? [])))).toBeLessThan(GMAIL_MIME_LIMITS.receiptBytes);
+ expect(result.messages.every(m => m.bodyText === '')).toBe(true);
+ });
+
+ test('forwarded message document bodies are never selected as the main body', async () => {
+ const result = await thread({ mimeType: 'multipart/mixed', parts: [
+ { mimeType: 'message/rfc822', parts: [{ mimeType: 'text/plain', body: { data: 'U2VjcmV0IGRvY3VtZW50' } }] },
+ { mimeType: 'text/plain', body: { data: 'SGVsbG8=' } },
+ ] });
+ expect(result.messages[0].bodyText).toBe('Hello');
+ expect(result.messages[0].attachmentInspection?.attachments).toMatchObject([{ mimeType: 'message/rfc822', kind: 'document' }]);
+ });
+});
diff --git a/test/google-attachment-recovery.test.ts b/test/google-attachment-recovery.test.ts
new file mode 100644
index 0000000000..d5d8cdecb1
--- /dev/null
+++ b/test/google-attachment-recovery.test.ts
@@ -0,0 +1,97 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { join } from 'node:path';
+import { readFileSync } from 'node:fs';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withConnectorSync } from '../src/core/persistence/connector-sync.ts';
+import { parseGoogleSourceConfig } from '../src/core/google/google-source.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { syncLockId } from '../src/core/db-lock.ts';
+import { createConnectorFixture, options } from './helpers/connector-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const { home, engines, env, boundSource, setup, teardown } = createConnectorFixture();
+beforeAll(setup, 120_000);
+afterAll(teardown);
+const config = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+const slug = 'emails/2026/09/thread-1';
+const content = '---\ntype: email\ntitle: Synthetic recovery\nthread_id: thread1\naccount: [email protected]\nmessage_ids: [message0000000001]\nvisibility: private\ncustom: retained\n---\nExact preserved historical body.\n';
+
+async function child(engine: BrainEngine, f: { id: string; dir: string }, crash?: string, unavailable = false) {
+ let database: Record<string, unknown> = { engine: 'pglite', database_path: join(home, 'database') };
+ if (engine.kind === 'postgres') {
+ const [row] = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const url = new URL(process.env.DATABASE_URL!);
+ url.pathname = `/${row.name}`;
+ database = { engine: 'postgres', database_url: url.toString(), poolSize: 4 };
+ }
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ let pid: number | undefined;
+ try {
+ const proc = Bun.spawn([process.execPath, 'run', join(import.meta.dir, 'helpers/google-attachment-restart.ts')], {
+ env: { ...process.env, ...env, GBRAIN_TEST_GMAIL_RESTART: JSON.stringify({ database, sourceId: f.id, root: f.dir, sourceConfig: config, crash, unavailable }) }, stdout: 'pipe', stderr: 'pipe',
+ });
+ pid = proc.pid;
+ const timer = setTimeout(() => proc.kill('SIGKILL'), 30_000);
+ try {
+ const [stdout, stderr, exit] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exit };
+ } finally { clearTimeout(timer); if (proc.exitCode === null) proc.kill('SIGKILL'); await proc.exited; }
+ } finally {
+ await engine.connect(database);
+ if (crash && pid) await engine.executeRaw(`UPDATE gbrain_cycle_locks SET acquired_at=now()-interval '2 minutes',last_refreshed_at=now()-interval '1 hour',ttl_expires_at=now()-interval '1 hour' WHERE id=$1 AND holder_pid=$2`, [syncLockId(f.id), pid]);
+ }
+}
+
+for (const crash of ['after_metadata_commit', 'after_checkpoint_commit']) {
+ test(`unavailable receipt diagnostics and counts survive actual SIGKILL ${crash}`, async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await boundSource(engine, config);
+ await withConnectorSync(engine, f.id, 'google', parseGoogleSourceConfig(config, f.dir), options, async managed => {
+ await managed!.importMarkdown(`${slug}.md`, content);
+ });
+ const before = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;
+ const killed = await child(engine, f, crash, true);
+ expect(killed.stdout, killed.stderr).toContain(`GMAIL_CRASH ${crash}`);
+ expect(killed.exit).not.toBe(0);
+ const restarted = await child(engine, f, undefined, true);
+ expect(restarted.exit, restarted.stderr).toBe(0);
+ const result = JSON.parse(restarted.stdout.split('GMAIL_RESULT ')[1].trim());
+ expect(result).toMatchObject({ status: 'complete', inspected: 0, unavailable: 1, unavailableMessages: 1, inspection_complete: false });
+ const after = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.frontmatter.visibility).toBe('private');
+ expect(after.page.frontmatter.message_ids).toEqual(before.page.frontmatter.message_ids);
+ expect(after.page.frontmatter.gmail_attachment_receipts).toMatchObject({ unavailable: 'thread_not_found',
+ messages: [{ unavailable: 'thread_not_found', inspection: { state: 'not_inspected', attachments: [] } }] });
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL', [f.id])).toHaveLength(0);
+ }
+ }), 120_000);
+}
+
+for (const crash of ['before_publication', 'after_publication', 'after_metadata_commit', 'after_checkpoint_commit']) {
+ test(`historical receipt journal survives actual SIGKILL ${crash}`, async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await boundSource(engine, config);
+ await withConnectorSync(engine, f.id, 'google', parseGoogleSourceConfig(config, f.dir), options, async managed => {
+ await managed!.importMarkdown(`${slug}.md`, content);
+ });
+ const before = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;
+ const killed = await child(engine, f, crash);
+ expect(killed.stdout, killed.stderr).toContain(`GMAIL_CRASH ${crash}`);
+ expect(killed.exit).not.toBe(0);
+ const restarted = await child(engine, f);
+ expect(restarted.exit, restarted.stderr).toBe(0);
+ expect(restarted.stdout).toContain('"status":"complete"');
+ const after = (await engine.readPageSnapshot(slug, { sourceId: f.id }))!;
+ expect(after.page.compiled_truth).toBe(before.page.compiled_truth);
+ expect(after.page.frontmatter.custom).toBe('retained');
+ expect(after.page.frontmatter.visibility).toBe('private');
+ expect(after.page.frontmatter.gmail_attachment_receipts).toMatchObject({ messages: [{ inspection: { state: 'present', attachments: [{ filename: 'fixture.pdf' }] } }] });
+ expect(readFileSync(join(f.dir, `${slug}.md`), 'utf8')).toContain('Exact preserved historical body.');
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL', [f.id])).toHaveLength(0);
+ const [count] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' AND state='committed' AND NOT COALESCE((outcome->>'noop')::boolean,false)", [f.id]);
+ expect(Number(count.count)).toBe(1);
+ }
+ }), 120_000);
+}
diff --git a/test/google-attachment-sync.test.ts b/test/google-attachment-sync.test.ts
new file mode 100644
index 0000000000..c145c426af
--- /dev/null
+++ b/test/google-attachment-sync.test.ts
@@ -0,0 +1,44 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { createConnectorFixture, json, options, sourceCheckpoint } from './helpers/connector-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const { engines, env, source, setup, teardown } = createConnectorFixture();
+beforeAll(setup, 120_000);
+afterAll(teardown);
+const config = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+const messageTime = Date.now() - 1000;
+
+function gmailFetch(url: string): Promise<Response> {
+ if (url.includes('/settings/sendAs')) return Promise.resolve(json({ sendAs: [] }));
+ if (url.includes('/profile')) return Promise.resolve(json({ historyId: '100', emailAddress: config.g_account }));
+ if (url.includes('/history?')) return Promise.resolve(json({ historyId: '101', history: [] }));
+ if (url.includes('/messages?')) {
+ const before = Number(new URL(url).searchParams.get('q')?.match(/before:(\d+)/)?.[1]);
+ return Promise.resolve(json({ messages: before * 1000 > messageTime + 1000 ? [{ id: '123abcdef4567890', threadId: 'abc123' }] : [] }));
+ }
+ if (url.includes('/threads/abc123?')) return Promise.resolve(json({ id: 'abc123', messages: [{ id: '123abcdef4567890', internalDate: String(messageTime), payload: {
+ mimeType: 'multipart/mixed', headers: [{ name: 'From', value: '[email protected]' }, { name: 'Subject', value: 'Synthetic report' }], parts: [
+ { mimeType: 'text/plain', body: { data: Buffer.from('Synthetic body.').toString('base64') } },
+ { partId: '1', mimeType: 'application/pdf', filename: 'synthetic-report.pdf', body: { attachmentId: 'opaque', size: 84 } },
+ ],
+ } }] }));
+ throw new Error('Unexpected synthetic Gmail route');
+}
+
+test('normal managed Gmail sync persists attachment receipts without marking historical inspection complete', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await source(engine, config);
+ const cfg = parseGoogleSourceConfig(config, f.dir);
+ const result = await runGoogleSync(engine, f.id, cfg, options, gmailFetch);
+ expect(result.added).toBe(1);
+ const [page] = await engine.executeRaw<{ frontmatter: Record<string, any>; compiled_truth: string }>('SELECT frontmatter,compiled_truth FROM pages WHERE source_id=$1', [f.id]);
+ expect(page.frontmatter.gmail_attachment_receipts.messages[0].inspection).toMatchObject({ state: 'present', attachments: [{ filename: 'synthetic-report.pdf', fetched: false, indexed: false }] });
+ expect(page.compiled_truth).toContain('not downloaded; not indexed');
+ expect(JSON.stringify(await sourceCheckpoint(engine, f.id))).not.toContain('gmail_attachment_backfill');
+ await disposePersistenceConsumer(engine);
+ expect((await runGoogleSync(engine, f.id, cfg, options, gmailFetch)).added).toBe(0);
+ expect(await engine.executeRaw('SELECT id FROM pages WHERE source_id=$1', [f.id])).toHaveLength(1);
+ }
+}), 120_000);
diff --git a/test/google-attachments-command.serial.test.ts b/test/google-attachments-command.serial.test.ts
new file mode 100644
index 0000000000..0f74e88d2e
--- /dev/null
+++ b/test/google-attachments-command.serial.test.ts
@@ -0,0 +1,81 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { parseGoogleAttachmentsArgs } from '../src/commands/google-attachments.ts';
+import { parseGoogleSourceConfig } from '../src/core/google/google-source.ts';
+import { withConnectorSync } from '../src/core/persistence/connector-sync.ts';
+import { createConnectorFixture, options } from './helpers/connector-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { join } from 'node:path';
+
+const { home, engines, env, source, setup, teardown } = createConnectorFixture();
+beforeAll(setup, 120_000);
+afterAll(teardown);
+const config = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+
+test('historical command accepts only explicit bounded source-scoped controls', () => {
+ expect(parseGoogleAttachmentsArgs(['backfill', '--source=gmail-example', '--limit', '2', '--yes', '--json'])).toMatchObject({ sourceId: 'gmail-example', limit: 2, yes: true, json: true });
+ for (const args of [[], ['backfill'], ['backfill', '--source', '../escape'], ['backfill', '--source', '__all__'],
+ ['backfill', '--source', '界'], ['backfill', '--source', 'a'.repeat(33)], ['backfill', '--source', 'ok', '--limit', '26'],
+ ['backfill', '--source', 'ok', '--limit', '0'], ['backfill', '--source', 'ok', '--source', 'other'],
+ ['backfill', '--source', 'ok', '--retry-failed'], ['backfill', '--source', 'ok', '--download']]) {
+ expect(() => parseGoogleAttachmentsArgs(args)).toThrow();
+ }
+});
+
+test('command JSON preview and apply expose truthful scope and progress without logging filenames', async () => withEnv(env, async () => {
+ for (const engine of engines) for (const unavailable of [false, true]) {
+ const f = await source(engine, config);
+ await withConnectorSync(engine, f.id, 'google', parseGoogleSourceConfig(config, f.dir), options, async managed => {
+ for (let n = 1; n <= 2; n++) await managed!.importMarkdown(`emails/2026/09/thread-${n}.md`, `---\ntype: email\ntitle: Synthetic command\naccount: [email protected]\nthread_id: thread${n}\nmessage_ids: [message000000000${n}]\n---\nRetained body.\n`);
+ });
+ let database: Record<string, unknown> = { engine: 'pglite', database_path: join(home, 'database') };
+ if (engine.kind === 'postgres') {
+ const [row] = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const url = new URL(process.env.DATABASE_URL!);
+ url.pathname = `/${row.name}`;
+ database = { engine: 'postgres', database_url: url.toString(), poolSize: 4 };
+ }
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ const run = async (extra: string[]) => {
+ const proc = Bun.spawn([process.execPath, 'run', join(import.meta.dir, 'helpers/google-attachments-command.ts')], {
+ env: { ...process.env, ...env, GBRAIN_TEST_GMAIL_COMMAND: JSON.stringify({ database, unavailable, args: ['backfill', '--source', f.id, '--json', ...extra] }) }, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, exit] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ expect(stdout + stderr).not.toContain('sensitive-name-not-for-logs');
+ return { value: JSON.parse(stdout), stderr, exit };
+ };
+ try {
+ const preview = await run([]);
+ expect(preview.stderr).toContain('FIXTURE_CALLS:0');
+ expect(preview.exit).toBe(0);
+ expect(preview.value).toMatchObject({ ok: true, status: 'preview', writes: 'none', imported_thread_pages: 2, historical_inspection: { status: 'not_inspected' } });
+ const first = await run(['--yes', '--limit', '1']);
+ expect(first.value).toMatchObject({ ok: false, status: 'paused', processed: 1, complete: false, brain: 'host', source: f.id });
+ expect(first.value).toMatchObject({ inspected: unavailable ? 0 : 1, unavailable: unavailable ? 1 : 0, inspection_complete: false });
+ expect(first.exit).toBe(1);
+ const second = await run(['--yes', '--limit', '1']);
+ expect(second.value).toMatchObject({ ok: true, status: 'complete', processed: 1, inspected: unavailable ? 1 : 2,
+ unavailable: unavailable ? 1 : 0, unavailableMessages: unavailable ? 1 : 0, inspection_complete: !unavailable });
+ if (unavailable) expect(second.value.next_action.user_message).toContain('not inspected this run');
+ expect(second.exit).toBe(0);
+ expect((await run([])).value).toMatchObject({ status: 'preview', historical_inspection: { complete: true, inspected: unavailable ? 1 : 2 } });
+ } finally { await engine.connect(database); }
+ }
+}), 120_000);
+
+test('real CLI help and invalid-input errors document the managed-only repair path', async () => {
+ const run = async (args: string[]) => {
+ const child = Bun.spawn([process.execPath, 'run', 'src/cli.ts', 'google', 'attachments', ...args], { env: { ...process.env, ...env }, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, exit };
+ };
+ const help = await run(['--help']);
+ expect(help.exit).toBe(0);
+ expect(help.stdout).toContain('Managed persistence');
+ expect(help.stdout).toContain('--limit 1-25');
+ const invalid = await run(['backfill', '--source', '../escape', '--yes', '--json']);
+ expect(invalid.exit).toBe(2);
+ expect(JSON.parse(invalid.stdout)).toMatchObject({ ok: false, status: 'failed', error: { code: 'invalid_params' } });
+ expect(invalid.stdout).not.toContain('../escape');
+}, 120_000);
diff --git a/test/handlers-embed-backfill.test.ts b/test/handlers-embed-backfill.test.ts
index 7efa947602..72bc8dc1ab 100644
--- a/test/handlers-embed-backfill.test.ts
+++ b/test/handlers-embed-backfill.test.ts
@@ -90,6 +90,28 @@ describe('embed-backfill handler — happy path', () => {
});
describe('embed-backfill handler — D2 lock contract', () => {
+ test('threads the job deadline and a transaction-fenced source lease into the drain', async () => {
+ const job = fakeJob({ sourceId: 'default' });
+ const deadline = Date.now() + 60_000;
+ job.deadlineAtMs = deadline;
+ let checked = false;
+ const handler = makeEmbedBackfillHandler(engine, {
+ runStale: async (_engine, _source, opts) => {
+ expect(opts?.deadline).toBe(deadline);
+ expect(opts?.assertOwned).toBeDefined();
+ await opts!.assertOwned!();
+ await engine.transaction(tx => opts!.assertOwned!(tx));
+ await engine.executeRaw("UPDATE gbrain_cycle_locks SET acquisition_token=gen_random_uuid() WHERE id='gbrain-embed-backfill:default'");
+ await expect(engine.transaction(tx => opts!.assertOwned!(tx))).rejects.toThrow('stolen');
+ expect(opts!.signal!.aborted).toBe(true);
+ checked = true;
+ return { embedded: 0, chunksProcessed: 0, pagesProcessed: 0, invalidated: 0, lastCursor: null, done: false, aborted: true };
+ },
+ });
+ expect((await handler(job)).status).toBe('aborted');
+ expect(checked).toBe(true);
+ });
+
test('IRON-RULE: second call returns already_in_progress when lock is held', async () => {
// Hold the per-source lock externally
const lock = await tryAcquireDbLock(engine, 'gbrain-embed-backfill:default', 60);
diff --git a/test/health-soft-delete.test.ts b/test/health-soft-delete.test.ts
index 424e2d87f9..13d0d13c0e 100644
--- a/test/health-soft-delete.test.ts
+++ b/test/health-soft-delete.test.ts
@@ -157,8 +157,7 @@ describe('#1305 — getHealth excludes soft-deleted pages', () => {
await engine.softDeletePage('wiki/gone');
const h = await engine.getHealth();
- // Soft-deleted pages' chunks still occupy storage until purge; the
- // missing_embeddings count keeps seeing them, same as getStats.
- expect(h.missing_embeddings).toBe(2);
+ expect((await engine.getStats()).chunk_count).toBe(2);
+ expect(h.missing_embeddings).toBe(1);
});
});
diff --git a/test/helpers/embed-projection-mock.ts b/test/helpers/embed-projection-mock.ts
index fc01d9fff7..59e2f838b0 100644
--- a/test/helpers/embed-projection-mock.ts
+++ b/test/helpers/embed-projection-mock.ts
@@ -9,7 +9,8 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
const pages = new Map<string, number>();
const pageKinds = new Map<number, string>();
overrides = {
- executeRaw: async () => [],
+ executeRaw: async (sql: string) => sql.startsWith('SELECT count(*)::int AS n FROM pages p')
+ && sql.includes('p.text_projection_revision IS DISTINCT FROM p.knowledge_revision') ? [{ n: 0 }] : [],
getConfigKeys: async () => [],
transaction: async (run: (tx: BrainEngine) => Promise<unknown>) => run(engine),
readPageSnapshot: async (slug: string, opts?: { sourceId?: string }) => {
@@ -27,6 +28,7 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
const executeRaw = overrides.executeRaw;
overrides.executeRaw = async (sql: string, params?: unknown[]) => sql.startsWith('SELECT page_kind FROM pages WHERE id=')
? [{ page_kind: pageKinds.get(Number(params?.[0])) ?? 'markdown' }]
+ : sql === 'SELECT archived FROM sources WHERE id=$1' ? [{ archived: false }]
: executeRaw(sql, params);
const calls: { method: string; args: any[] }[] = [];
const track = (method: string) => (...args: any[]) => {
diff --git a/test/helpers/git-fixture.ts b/test/helpers/git-fixture.ts
index 2852e537c5..be80c6921e 100644
--- a/test/helpers/git-fixture.ts
+++ b/test/helpers/git-fixture.ts
@@ -34,6 +34,8 @@ function git(dir: string, args: string[]): string {
export async function makeGitFixture(dir: string): Promise<GitFixture> {
git(dir, ['init', '-q']);
+ git(dir, ['config', 'maintenance.auto', 'false']);
+ git(dir, ['config', 'gc.auto', '0']);
git(dir, ['config', 'user.email', '[email protected]']);
git(dir, ['config', 'user.name', 't']);
// Empty initial commit so rev-parse HEAD and reset --hard work immediately.
diff --git a/test/helpers/google-attachment-restart.ts b/test/helpers/google-attachment-restart.ts
new file mode 100644
index 0000000000..a87dc2c613
--- /dev/null
+++ b/test/helpers/google-attachment-restart.ts
@@ -0,0 +1,52 @@
+import { writeSync } from 'node:fs';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { parseGoogleSourceConfig, runGoogleAttachmentBackfill } from '../../src/core/google/google-source.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+
+const input = JSON.parse(process.env.GBRAIN_TEST_GMAIL_RESTART!);
+if (input.database.database_url) assertSafeE2eDatabaseUrl(input.database.database_url);
+const engine: BrainEngine = input.database.engine === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+await engine.connect(input.database);
+const kill = () => { writeSync(1, `GMAIL_CRASH ${input.crash}\n`); process.kill(process.pid, 'SIGKILL'); };
+if (input.crash) {
+ const transaction = engine.transaction;
+ engine.transaction = async function <T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ const result = await transaction.call(this, async tx => {
+ const executeRaw = tx.executeRaw;
+ if (input.crash === 'before_publication') tx.executeRaw = async function (sql, params) {
+ if (sql.includes('publication_started=true')) {
+ const [row] = await executeRaw.call(tx, 'SELECT intent FROM persistence_requests WHERE id=$1::uuid', [params![0]]);
+ if ((row as Partial<WriteRequest>)?.intent?.kind === 'managed_connector_google_receipts') kill();
+ }
+ return executeRaw.call(tx, sql, params);
+ } as BrainEngine['executeRaw'];
+ const value = await run(tx);
+ const row = value as Partial<WriteRequest> | undefined;
+ if (input.crash === 'after_publication' && row?.state === 'committed' && row.intent?.kind === 'managed_connector_google_receipts') kill();
+ return value;
+ });
+ const row = result as Partial<WriteRequest> | undefined;
+ if (row?.state === 'committed' && (input.crash === 'after_metadata_commit' && row.intent?.kind === 'managed_connector_google_receipts' ||
+ input.crash === 'after_checkpoint_commit' && row.intent?.kind === 'managed_connector_checkpoint' &&
+ ((row.intent.checkpointAfter as any)?.[0]?.state?.gmail_attachment_backfill?.afterPageId ?? 0) > 0)) kill();
+ return result as T;
+ };
+}
+try {
+ const result = await runGoogleAttachmentBackfill(engine, input.sourceId, parseGoogleSourceConfig(input.sourceConfig, input.root), {}, async url => {
+ if (url.includes('/profile')) return Response.json({ emailAddress: '[email protected]', historyId: '100' });
+ if (!url.includes('/threads/thread1?')) throw new Error('Unexpected synthetic metadata endpoint');
+ if (input.unavailable) return Response.json({}, { status: 404 });
+ return Response.json({ id: 'thread1', messages: [{ id: 'message0000000001', payload: {
+ mimeType: 'application/pdf', filename: 'fixture.pdf', partId: '1', body: { attachmentId: 'opaque', size: 17 },
+ } }] });
+ });
+ process.stdout.write(`GMAIL_RESULT ${JSON.stringify(result)}\n`);
+} finally {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+}
diff --git a/test/helpers/google-attachments-command.ts b/test/helpers/google-attachments-command.ts
new file mode 100644
index 0000000000..337ea648a2
--- /dev/null
+++ b/test/helpers/google-attachments-command.ts
@@ -0,0 +1,27 @@
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { runGoogleAttachments } from '../../src/commands/google-attachments.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { currentExitCode } from '../../src/core/cli-force-exit.ts';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+
+const input = JSON.parse(process.env.GBRAIN_TEST_GMAIL_COMMAND!);
+if (input.database.database_url) assertSafeE2eDatabaseUrl(input.database.database_url);
+const engine = input.database.engine === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+await engine.connect(input.database);
+let calls = 0;
+try {
+ await runGoogleAttachments(input.args, engine, async url => {
+ calls++;
+ if (url.includes('/profile')) return Response.json({ emailAddress: '[email protected]', historyId: '100' });
+ const n = Number(url.match(/threads\/thread(\d+)/)?.[1]);
+ if (!n) throw new Error('Unexpected synthetic route');
+ if (input.unavailable && n === 1) return Response.json({}, { status: 404 });
+ return Response.json({ id: `thread${n}`, messages: [{ id: `message000000000${n}`, payload: { mimeType: 'application/pdf', filename: 'sensitive-name-not-for-logs.pdf', body: { size: 2 } } }] });
+ });
+} finally {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ process.stderr.write(`FIXTURE_CALLS:${calls}\n`);
+}
+process.exit(currentExitCode());
diff --git a/test/helpers/memory-safety-wave-repair.ts b/test/helpers/memory-safety-wave-repair.ts
new file mode 100644
index 0000000000..834b1885b6
--- /dev/null
+++ b/test/helpers/memory-safety-wave-repair.ts
@@ -0,0 +1,54 @@
+import { writeSync } from 'node:fs';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { parseGoogleSourceConfig, runGoogleAttachmentBackfill } from '../../src/core/google/google-source.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+
+const input = JSON.parse(process.env.GBRAIN_TEST_MEMORY_WAVE_REPAIR!);
+if (input.database.database_url) assertSafeE2eDatabaseUrl(input.database.database_url);
+let outboundCalls = 0;
+globalThis.fetch = Object.assign(async () => {
+ outboundCalls++;
+ throw new Error('Historical lifecycle repair must not make outbound requests');
+}, { preconnect() {
+ outboundCalls++;
+ throw new Error('Historical lifecycle repair must not preconnect outbound requests');
+} });
+const engine: BrainEngine = input.database.engine === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+await engine.connect(input.database);
+if (input.crash) {
+ const transaction = engine.transaction;
+ engine.transaction = async function <T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ const result = await transaction.call(this, run);
+ const row = result as Partial<WriteRequest> | undefined;
+ if (row?.state === 'committed' && row.intent?.kind === 'managed_connector_google_receipts') {
+ if (outboundCalls) throw new Error('Historical lifecycle repair attempted outbound requests');
+ writeSync(1, 'MEMORY_WAVE_CRASH after_metadata_commit\n');
+ process.kill(process.pid, 'SIGKILL');
+ }
+ return result as T;
+ };
+}
+try {
+ const result = await runGoogleAttachmentBackfill(engine, input.sourceId, parseGoogleSourceConfig(input.sourceConfig, input.root), {}, async url => {
+ if (url === 'https://gmail.googleapis.com/gmail/v1/users/me/profile') {
+ return Response.json({ emailAddress: input.sourceConfig.g_account, historyId: '100' });
+ }
+ const request = new URL(url);
+ const fields = request.searchParams.get('fields');
+ if (`${request.origin}${request.pathname}` !== `https://gmail.googleapis.com/gmail/v1/users/me/threads/${input.thread.id}` ||
+ request.searchParams.size !== 2 || request.searchParams.get('format') !== 'full' ||
+ !fields?.includes('body(attachmentId,size)') || /\b(data|raw|snippet)\b|\*/.test(fields)) {
+ throw new Error('Unexpected synthetic lifecycle Gmail endpoint');
+ }
+ return Response.json(input.thread);
+ });
+ if (outboundCalls) throw new Error('Historical lifecycle repair attempted outbound requests');
+ process.stdout.write(`MEMORY_WAVE_RESUMED ${JSON.stringify(result)}\n`);
+} finally {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+}
diff --git a/test/helpers/migration-wave-budget-process.ts b/test/helpers/migration-wave-budget-process.ts
new file mode 100644
index 0000000000..34d6ccc614
--- /dev/null
+++ b/test/helpers/migration-wave-budget-process.ts
@@ -0,0 +1,58 @@
+import { appendFileSync, existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { planEmbeddingMigration, readMigrationState } from '../../src/core/embedding-migration.ts';
+import { authorizeMigrationBudget } from '../../src/core/embedding-migration-budget.ts';
+import { invokeAI, withAIInvocationGuard } from '../../src/core/ai/invocation-guard.ts';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+
+const [mode, kind, database, root, boundary, requestKind] = process.argv.slice(2);
+if (process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY) throw new Error('Provider keys must be stripped');
+if (kind === 'postgres') assertSafeE2eDatabaseUrl(database);
+const engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+await engine.connect(kind === 'postgres' ? { database_url: database } : { database_path: database });
+const model = 'openai:text-embedding-3-small';
+const reranker = 'synthetic:priced-reranker';
+const invocation = { kind: requestKind as 'embedding' | 'rerank', operation: 'synthetic-migration-crash',
+ model: requestKind === 'rerank' ? reranker : model, maxInputTokens: 40_000 };
+const dispatches = join(root, 'dispatches');
+const pause = async () => { console.log('MIGRATION_WAVE_CRASH_BOUNDARY'); await new Promise(() => {}); };
+try {
+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: 0.02, [reranker]: 0.02 }));
+ const plan = await planEmbeddingMigration(engine, { to: model, dim: 1536 });
+ const before = (await readMigrationState(engine)).state?.budget;
+ const debit = await authorizeMigrationBudget(engine, plan, mode === 'crash' ? 0.001 : undefined, [], reranker);
+ const dispatch = async () => {
+ appendFileSync(dispatches, 'synthetic-dispatch\n');
+ if (mode === 'crash' && boundary === 'after-dispatch') await pause();
+ return { tokens: 40_000 };
+ };
+ if (mode === 'crash') {
+ await withAIInvocationGuard(async call => {
+ if (boundary === 'before-reservation') await pause();
+ const permit = await debit(call);
+ if (boundary === 'after-debit') await pause();
+ return permit;
+ }, () => invokeAI(invocation, dispatch, value => ({ inputTokens: value.tokens, outputTokens: 0 })));
+ throw new Error('Crash boundary was not reached');
+ }
+ const resumed = (await readMigrationState(engine)).state!.budget!;
+ if (JSON.stringify(before) !== JSON.stringify(resumed)) throw new Error('Resume reset durable authorization');
+ const expectedRequests = boundary === 'before-reservation' ? 0 : 1;
+ if (resumed.requests !== expectedRequests || (expectedRequests ? resumed.debited_usd <= 0 : resumed.debited_usd !== 0)) {
+ throw new Error('Unexpected durable crash debit');
+ }
+ let rejected = false;
+ await withAIInvocationGuard(debit, async () => {
+ if (!expectedRequests) await invokeAI(invocation, dispatch, value => ({ inputTokens: value.tokens, outputTokens: 0 }));
+ try { await invokeAI(invocation, dispatch, value => ({ inputTokens: value.tokens, outputTokens: 0 })); }
+ catch { rejected = true; }
+ });
+ const final = (await readMigrationState(engine)).state!.budget!;
+ const count = existsSync(dispatches) ? readFileSync(dispatches, 'utf8').trim().split('\n').length : 0;
+ if (!rejected || final.requests !== 1 || final.debited_usd > final.max_cost_usd || count !== (boundary === 'after-debit' ? 0 : 1)) {
+ throw new Error('Restart exceeded authorized dispatches');
+ }
+ console.log(JSON.stringify({ result: 'MIGRATION_WAVE_BUDGET_RECOVERED', boundary, requestKind, budget: final, dispatches: count }));
+} finally { await engine.disconnect(); }
diff --git a/test/helpers/migration-wave-fixture.ts b/test/helpers/migration-wave-fixture.ts
new file mode 100644
index 0000000000..836108c51a
--- /dev/null
+++ b/test/helpers/migration-wave-fixture.ts
@@ -0,0 +1,49 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { isolatedPersistencePostgres } from './persistence-postgres.ts';
+
+export async function migrationWaveFixture(kind: 'pglite' | 'postgres') {
+ if (kind === 'postgres') {
+ const base = process.env.DATABASE_URL!;
+ const fixture = await isolatedPersistencePostgres(base);
+ const [row] = await fixture.engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ if (row.name === new URL(base).pathname.slice(1) || !row.name.startsWith('gbrain_test_persistence_')) {
+ await fixture.close();
+ throw new Error('Migration acceptance database isolation failed');
+ }
+ console.log(`MIGRATION_WAVE_ISOLATED_DATABASE ${row.name}`);
+ return { ...fixture, database: fixture.databaseUrl };
+ }
+ const root = mkdtempSync(join(tmpdir(), 'migration-wave-'));
+ const database = join(root, 'brain');
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: database });
+ await engine.initSchema();
+ return { engine, database, close: async () => { await engine.disconnect(); rmSync(root, { recursive: true, force: true }); } };
+}
+
+export function observeMigrationEngine(
+ engine: BrainEngine,
+ after: (engine: BrainEngine, method: string, args: unknown[], result: unknown) => Promise<void>,
+ before?: (engine: BrainEngine, method: string, args: unknown[]) => Promise<void>,
+): BrainEngine {
+ return new Proxy(engine, {
+ get(target, property) {
+ const value = Reflect.get(target, property);
+ if (property === 'transaction') return async (run: (tx: BrainEngine) => Promise<unknown>) => {
+ await before?.(target, 'transaction', [run]);
+ return target.transaction(tx => run(observeMigrationEngine(tx, after, before)));
+ };
+ if (typeof value !== 'function') return value;
+ return async (...args: unknown[]) => {
+ await before?.(target, String(property), args);
+ const result = await value.apply(target, args);
+ await after(target, String(property), args, result);
+ return result;
+ };
+ },
+ });
+}
diff --git a/test/helpers/withdrawal-effect-process.ts b/test/helpers/withdrawal-effect-process.ts
new file mode 100644
index 0000000000..fe1c1525c6
--- /dev/null
+++ b/test/helpers/withdrawal-effect-process.ts
@@ -0,0 +1,70 @@
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { registerLocalWriter, localHostId } from '../../src/core/persistence/identity.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { submissionAuthority } from '../../src/core/persistence/authority.ts';
+import { admitWrite, completeWrite } from '../../src/core/persistence/journal.ts';
+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';
+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';
+import { renderFactsTable, parseFactsFence } from '../../src/core/facts-fence.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { assertSafeE2eDatabaseUrl } from './db-guard.ts';
+
+const [mode, backend, root, database, boundary] = process.argv.slice(2);
+if (backend === 'postgres') assertSafeE2eDatabaseUrl(database);
+const engine = backend === 'pglite' ? new PGLiteEngine() : new PostgresEngine();
+await engine.connect(backend === 'pglite' ? { database_path: database } : { database_url: database });
+const hostId = localHostId(), sourceId = 'synthetic-withdrawal-crash';
+try {
+ if (mode === 'seed') {
+ await engine.initSchema(); await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const binding = await claimWorktree(engine, sourceId, root, hostId);
+ for (const slug of ['affected', 'untouched']) {
+ const body = slug === 'affected' ? renderFactsTable([{ rowNum: 1, claim: 'synthetic crash claim', kind: 'fact', confidence: 1,
+ visibility: 'world', notability: 'medium', active: true }]) : 'Exact untouched bytes';
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body }, { sourceId });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: body }], { sourceId });
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ }
+ const fact = await engine.insertFact({ fact: 'synthetic crash claim', source: 'synthetic', visibility: 'world' }, { source_id: sourceId });
+ const context: OperationContext = { engine, remote: false, sourceId, config: { engine: engine.kind }, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } };
+ const authority = await submissionAuthority(context, 'forget', sourceId, binding.source_incarnation, 'affected');
+ const request = await admitWrite(engine, { authority, principal: authority.principal, operation: 'forget', sourceId,
+ sourceIncarnation: binding.source_incarnation, slug: 'affected', pageId: null, requestId: randomUUID(),
+ intent: { id: fact.id }, callerIntent: { id: fact.id }, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });
+ const untouched = await engine.executeRaw(`SELECT row_to_json(p) AS page,(SELECT jsonb_agg(to_jsonb(c) ORDER BY c.id)
+ FROM content_chunks c WHERE c.page_id=p.id) AS chunks FROM pages p WHERE source_id=$1 AND slug='untouched'`, [sourceId]);
+ await engine.transaction(async tx => {
+ await recordFactWithdrawal(tx, fact.id, sourceId, false, { requestId: request.id });
+ await completeWrite(tx, request, 'committed', { status: 'forgotten' });
+ });
+ const revision = (await engine.readPageSnapshot('affected', { sourceId }))!.revision;
+ writeFileSync(join(root, 'state.json'), JSON.stringify({ untouched, revision, requestId: request.id, bytes: readFileSync(join(root, 'untouched.md'), 'base64') }));
+ } else if (mode === 'crash') {
+ await runPersistenceEffects(engine, { engine: backend as 'pglite' | 'postgres', embedding_disabled: true }, { hostId, limit: 1,
+ boundary: async name => {
+ if (name === boundary) { console.log('AT_MIRROR_BOUNDARY'); await new Promise(() => {}); }
+ } });
+ throw new Error('Did not reach the requested mirror boundary');
+ } else {
+ const state = JSON.parse(readFileSync(join(root, 'state.json'), 'utf8'));
+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid', [state.requestId]);
+ await runPersistenceEffects(engine, { engine: backend as 'pglite' | 'postgres', embedding_disabled: true }, { hostId, limit: 3 });
+ const untouched = await engine.executeRaw(`SELECT row_to_json(p) AS page,(SELECT jsonb_agg(to_jsonb(c) ORDER BY c.id)
+ FROM content_chunks c WHERE c.page_id=p.id) AS chunks FROM pages p WHERE source_id=$1 AND slug='untouched'`, [sourceId]);
+ const snapshot = (await engine.readPageSnapshot('affected', { sourceId }))!;
+ const recovery = await engine.executeRaw('SELECT id FROM persistence_effects WHERE request_id=$1::uuid AND recovery IS NOT NULL', [state.requestId]);
+ if (JSON.stringify(untouched) !== JSON.stringify(state.untouched) || readFileSync(join(root, 'untouched.md'), 'base64') !== state.bytes ||
+ snapshot.revision !== state.revision || !parseFactsFence(readFileSync(join(root, 'affected.md'), 'utf8')).facts[0].forgotten || recovery.length) {
+ throw new Error('Native crash recovery violated canonical invariants');
+ }
+ console.log('RECOVERED_EXACTLY');
+ }
+} finally { await engine.disconnect(); }
diff --git a/test/keyword-relaxed-fusion.serial.test.ts b/test/keyword-relaxed-fusion.serial.test.ts
index 01eb8d26c0..5d5456f1a2 100644
--- a/test/keyword-relaxed-fusion.serial.test.ts
+++ b/test/keyword-relaxed-fusion.serial.test.ts
@@ -82,8 +82,8 @@ beforeAll(async () => {
{ chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },
]);
await engine.executeRaw(
- `UPDATE content_chunks SET embedding = $1::vector WHERE page_id = (SELECT id FROM pages WHERE slug = $2)`,
- [vec, slug],
+ `UPDATE content_chunks SET embedding = $1::vector, model = $3, embedded_text_hash = md5(chunk_text) WHERE page_id = (SELECT id FROM pages WHERE slug = $2)`,
+ [vec, slug, 'openai:text-embedding-3-large'],
);
}
});
diff --git a/test/legacy-fact-extraction-dedup.test.ts b/test/legacy-fact-extraction-dedup.test.ts
new file mode 100644
index 0000000000..ec6ee234ac
--- /dev/null
+++ b/test/legacy-fact-extraction-dedup.test.ts
@@ -0,0 +1,53 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { runSchemaTransition } from '../src/core/embedding-migration.ts';
+import { runFactsPipeline } from '../src/core/facts/backstop.ts';
+import { createConnectorFixture } from './helpers/connector-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const fixture = createConnectorFixture();
+beforeAll(fixture.setup, 120_000);
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await fixture.teardown();
+});
+
+test('legacy extraction deduplicates exact old facts without inferring their vector identity or crossing visibility', async () => withEnv({
+ ...fixture.env, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined,
+ GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined,
+}, async () => {
+ for (const engine of fixture.engines) {
+ const model = 'openai:text-embedding-3-small';
+ await runSchemaTransition(engine, 8);
+ await engine.setConfig('embedding_model', model);
+ await engine.setConfig('embedding_dimensions', '8');
+ resetGateway();
+ configureGateway({ embedding_model: model, embedding_dimensions: 8, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ __setEmbedTransportForTests(async ({ values }) => ({ values, warnings: [], embeddings: values.map(() => Array(8).fill(0.1)), usage: { tokens: 8 } }));
+ const fact = 'Synthetic profile prefers reproducible local fixtures.';
+ const entity = 'people/synthetic-profile';
+ let extractedEntity: string | null = entity;
+ __setChatTransportForTests(async () => ({ text: JSON.stringify({ facts: [{ fact, entity: extractedEntity, kind: 'fact', notability: 'high', confidence: 1 }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'synthetic:fixture', providerId: 'synthetic' }));
+ await engine.putPage(entity, { type: 'person', title: 'Synthetic profile', compiled_truth: 'Synthetic entity.' });
+ const old = await engine.insertFact({ entity_slug: entity, fact, source: 'synthetic', visibility: 'private', embedding: new Float32Array(8).fill(0.1) }, { source_id: 'default' });
+ const before = await engine.executeRaw('SELECT embedding::text,embedding_model,embedded_text_hash FROM facts WHERE id=$1', [old.id]);
+ expect(before[0]).toMatchObject({ embedding_model: null, embedded_text_hash: null });
+ const result = await runFactsPipeline('Synthetic extraction input for a known profile.', { engine, sourceId: 'default', sessionId: null, source: 'mcp:extract_facts', visibility: 'private' });
+ expect(result).toMatchObject({ inserted: 0, duplicate: 1, fact_ids: [old.id] });
+ expect(await engine.executeRaw('SELECT embedding::text,embedding_model,embedded_text_hash FROM facts WHERE id=$1', [old.id])).toEqual(before);
+ const visible = await runFactsPipeline('Synthetic extraction input for a known profile.', { engine, sourceId: 'default', sessionId: null, source: 'mcp:extract_facts', visibility: 'world' });
+ expect(visible).toMatchObject({ inserted: 1, duplicate: 0 });
+ expect(visible.fact_ids).not.toContain(old.id);
+ extractedEntity = null;
+ for (const sourceSlug of ['notes/first', 'notes/second']) {
+ const unparented = await runFactsPipeline('Synthetic unparented extraction input.', { engine, sourceId: 'default', sessionId: null,
+ source: 'mcp:extract_facts', sourceSlug, visibility: 'private' });
+ expect(unparented).toMatchObject({ inserted: 1, duplicate: 0 });
+ }
+ expect(await engine.executeRaw('SELECT context FROM facts WHERE entity_slug IS NULL ORDER BY id')).toEqual([{ context: 'notes/first' }, { context: 'notes/second' }]);
+ }
+}), 120_000);
diff --git a/test/legacy-vector-compatibility.test.ts b/test/legacy-vector-compatibility.test.ts
new file mode 100644
index 0000000000..db34bf6772
--- /dev/null
+++ b/test/legacy-vector-compatibility.test.ts
@@ -0,0 +1,66 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { runSchemaTransition } from '../src/core/embedding-migration.ts';
+import { executeMigrationFlow, planMigrationFlow } from '../src/commands/migrate-embeddings.ts';
+import { hybridSearch } from '../src/core/search/hybrid.ts';
+import { createConnectorFixture } from './helpers/connector-fixture.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const fixture = createConnectorFixture();
+const model = 'openai:text-embedding-3-small';
+const dimensions = 8;
+beforeAll(fixture.setup, 120_000);
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await fixture.teardown();
+});
+
+test('legacy same-model NULL hashes stay searchable through failed migrations without trusting wrong generations or stale hashes', async () => withEnv({
+ ...fixture.env, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined,
+ GBRAIN_EMBEDDING_MODEL: model, GBRAIN_EMBEDDING_DIMENSIONS: String(dimensions),
+}, async () => {
+ for (const engine of fixture.engines) {
+ await runSchemaTransition(engine, dimensions);
+ await engine.setConfig('embedding_model', model);
+ await engine.setConfig('embedding_dimensions', String(dimensions));
+ resetGateway();
+ configureGateway({ embedding_model: model, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ const vector = new Float32Array(dimensions).fill(0.1);
+ let providerDown = false;
+ __setEmbedTransportForTests(async ({ values }) => {
+ if (providerDown) throw new Error('Synthetic provider unavailable');
+ return { values, warnings: [], embeddings: values.map(() => Array.from(vector)), usage: { tokens: 8 } };
+ });
+ for (const slug of ['current', 'legacy', 'wrong-model', 'unknown-model', 'stale-text']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Synthetic body for ${slug}.` });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: `Synthetic body for ${slug}.`, embedding: vector, model }]);
+ }
+ await engine.executeRaw("UPDATE content_chunks SET embedded_text_hash=NULL WHERE page_id=(SELECT id FROM pages WHERE slug='legacy')");
+ await engine.executeRaw("UPDATE content_chunks SET model='other:synthetic' WHERE page_id=(SELECT id FROM pages WHERE slug='wrong-model')");
+ await engine.executeRaw("UPDATE content_chunks SET model='' WHERE page_id=(SELECT id FROM pages WHERE slug='unknown-model')");
+ await engine.executeRaw("UPDATE content_chunks SET embedded_text_hash=md5('obsolete synthetic text') WHERE page_id=(SELECT id FROM pages WHERE slug='stale-text')");
+ const before = await engine.executeRaw('SELECT id,embedding::text,model,embedded_text_hash FROM content_chunks ORDER BY id');
+ expect(await engine.searchKeyword('nonlexicalsaffronquery', { limit: 10 })).toEqual([]);
+ expect((await engine.searchVector(vector, { embeddingColumn: { name: 'embedding', type: 'vector', dimensions, embeddingModel: model }, limit: 10 })).map(row => row.slug).sort())
+ .toEqual(['current', 'legacy']);
+ const query = async () => {
+ const rows = await hybridSearch(engine, 'nonlexicalsaffronquery', { expansion: false, limit: 10 });
+ return rows.map(row => row.slug).sort();
+ };
+ expect(await query()).toEqual(['current', 'legacy']);
+ providerDown = true;
+ const options = { to: model, dim: dimensions, reranker: 'off', maxCostUsd: 1, quiet: true };
+ const attempted = await executeMigrationFlow(engine, await planMigrationFlow(engine, options), options);
+ expect(attempted.status).toBe('probe_failed');
+ expect(await engine.getConfig('embedding_migration.state')).toBeTruthy();
+ providerDown = false;
+ expect(await query()).toEqual(['current', 'legacy']);
+ await engine.setConfig('embedding_migration.state', JSON.stringify({ to_model: model, to_dims: dimensions }));
+ expect(await query()).toEqual(['current', 'legacy']);
+ await engine.executeRaw("DELETE FROM config WHERE key='embedding_migration.state'");
+ expect(await query()).toEqual(['current', 'legacy']);
+ expect(await engine.executeRaw('SELECT id,embedding::text,model,embedded_text_hash FROM content_chunks ORDER BY id')).toEqual(before);
+ }
+}), 120_000);
diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.ts
index eeecab4062..82ac01943c 100644
--- a/test/managed-maintenance.test.ts
+++ b/test/managed-maintenance.test.ts
@@ -83,8 +83,8 @@ async function seed(engine: BrainEngine, sourceId: string, slug = 'people/exampl
async function seedFacts(engine: BrainEngine, sourceId: string, slug: string, visibility = 'world') {
const vector = `[${[1, ...Array(1535).fill(0)].join(',')}]`;
for (let i = 0; i < 3; i++) {
- await engine.executeRaw(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility,confidence,valid_from,embedding)
- VALUES($1,$2,$3,'fact','test',$4,$5,$6::timestamptz,$7::vector)`,
+ await engine.executeRaw(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility,confidence,valid_from,embedding,embedding_model,embedded_text_hash)
+ VALUES($1,$2,$3,'fact','test',$4,$5,$6::timestamptz,$7::vector,'openai:text-embedding-3-large',md5($3))`,
[sourceId, slug, `Example claim ${i}`, visibility, 0.9 - i / 10, `2026-01-0${i + 1}T00:00:00Z`, vector]);
}
}
diff --git a/test/mcp-stdio-source-preflight.test.ts b/test/mcp-stdio-source-preflight.test.ts
index 1fc11a3372..2b7d727557 100644
--- a/test/mcp-stdio-source-preflight.test.ts
+++ b/test/mcp-stdio-source-preflight.test.ts
@@ -1,4 +1,4 @@
-import { describe, test, expect, afterEach } from 'bun:test';
+import { describe, test, expect, afterEach, spyOn } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
@@ -54,6 +54,30 @@ describe('stdio MCP source preflight', () => {
await expect(assertStdioSourceBindable(makeEngine(['default']), 'Not A Valid Id!')).resolves.toBeUndefined();
});
+ test('__all__ warns without querying the database, including during degraded startup', async () => {
+ let queries = 0;
+ const engine = {
+ kind: 'postgres',
+ [DEGRADED_STATE]: () => true,
+ executeRaw: async () => { queries++; throw new Error('must not inspect source contents'); },
+ } as unknown as BrainEngine;
+ let stderr = '';
+ const write = spyOn(process.stderr, 'write').mockImplementation(chunk => {
+ stderr += String(chunk);
+ return true;
+ });
+ try {
+ await assertStdioSourceBindable(engine, '__all__');
+ expect(queries).toBe(0);
+ expect(stderr).toContain('GBRAIN_SOURCE=__all__ does not grant all-source access to stdio MCP');
+ expect(stderr).toContain('fail-closed');
+ expect(stderr).toContain('then restart the server');
+ expect(stderr).toContain('docs/mcp/DEPLOY.md#stdio-source-binding');
+ } finally {
+ write.mockRestore();
+ }
+ });
+
test('engine failure does not block startup (guards config, not connectivity)', async () => {
await expect(assertStdioSourceBindable(makeEngine([], { throwing: true }), 'workspace')).resolves.toBeUndefined();
});
diff --git a/test/memory-safety-wave.serial.test.ts b/test/memory-safety-wave.serial.test.ts
new file mode 100644
index 0000000000..c55440644d
--- /dev/null
+++ b/test/memory-safety-wave.serial.test.ts
@@ -0,0 +1,267 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { submitRememberMutation, submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { syncLockId } from '../src/core/db-lock.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { sanitizeRemoteBody } from '../src/core/remote-body.ts';
+import { runSchemaTransition } from '../src/core/embedding-migration.ts';
+import { planMigrationFlow, executeMigrationFlow } from '../src/commands/migrate-embeddings.ts';
+import { countStaleFactEmbeddings } from '../src/core/facts/embedding-identity.ts';
+import { runExport } from '../src/commands/export.ts';
+import { startHttpTransport } from '../src/mcp/http-transport.ts';
+import { createConnectorFixture, json, options, sourceCheckpoint } from './helpers/connector-fixture.ts';
+import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { withManagedFixtureWrite } from './helpers/managed-e2e-fixture-write.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const fixture = createConnectorFixture();
+beforeAll(fixture.setup, 120_000);
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await fixture.teardown();
+});
+const originalModel = 'openai:text-embedding-3-small';
+const targetModel = 'openai:text-embedding-3-large';
+const dimensions = 8;
+const retired = 'retiredvioletclaim prefers synthetic fixtures';
+const privateText = 'privatecobaltsentinel';
+const visibleText = 'visiblequartzsentinel';
+const foreignText = 'foreignambersentinel';
+const vectorQuery = 'vectoronlysaffronlookup';
+const config = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+const messageTime = Date.now() - 1000;
+
+function embedding(text: string): number[] {
+ const vector = Array(dimensions).fill(0);
+ vector[text.includes(visibleText) || text.includes(vectorQuery) ? 0 : text.includes(privateText) ? 1 : text.includes(foreignText) ? 2 : text.includes(retired) ? 3 : 4] = 1;
+ return vector;
+}
+
+async function gmailFetch(url: string) {
+ if (url.includes('/settings/sendAs')) return json({ sendAs: [] });
+ if (url.includes('/profile')) return json({ historyId: '100', emailAddress: config.g_account });
+ if (url.includes('/history?')) return json({ historyId: '101', history: [] });
+ if (url.includes('/messages?')) {
+ const before = Number(new URL(url).searchParams.get('q')?.match(/before:(\d+)/)?.[1]);
+ return json({ messages: before * 1000 > messageTime + 1000 ? [{ id: '123abcdef4567890', threadId: 'abc123' }] : [] });
+ }
+ if (url.includes('/threads/abc123?')) return json({ id: 'abc123', messages: [{ id: '123abcdef4567890', internalDate: String(messageTime), payload: {
+ mimeType: 'multipart/mixed', headers: [{ name: 'From', value: '[email protected]' }, { name: 'Subject', value: 'Synthetic lifecycle report' }], parts: [
+ { mimeType: 'text/plain', body: { data: Buffer.from(`Synthetic message ${privateText}`).toString('base64') } },
+ { partId: '1', mimeType: 'application/pdf', filename: 'synthetic-report.pdf', body: { attachmentId: 'opaque', size: 84 } },
+ ],
+ } }] });
+ throw new Error('Unexpected synthetic Gmail endpoint');
+}
+
+function context(engine: BrainEngine, sourceId: string): OperationContext {
+ return { engine, sourceId, config: { engine: engine.kind }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+}
+
+test('sync, remember, withdraw, metadata repair, migration, export and HTTP MCP retain source and privacy boundaries', async () => withEnv({
+ ...fixture.env, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined,
+ GBRAIN_EMBEDDING_MODEL: undefined, GBRAIN_EMBEDDING_DIMENSIONS: undefined,
+}, async () => {
+ for (const engine of fixture.engines) {
+ let database: GBrainConfig = { engine: 'pglite', database_path: join(fixture.home, 'database') };
+ if (engine.kind === 'postgres') {
+ const [row] = await engine.executeRaw<{ name: string }>('SELECT current_database() AS name');
+ const url = new URL(process.env.DATABASE_URL!);
+ url.pathname = row.name;
+ database = { engine: 'postgres', database_url: url.toString() };
+ }
+ await runSchemaTransition(engine, dimensions);
+ await engine.setConfig('embedding_model', originalModel);
+ await engine.setConfig('embedding_dimensions', String(dimensions));
+ resetGateway();
+ configureGateway({ embedding_model: originalModel, embedding_dimensions: dimensions, env: { OPENAI_API_KEY: 'synthetic-only' } });
+ __setEmbedTransportForTests(async ({ values }) => ({ embeddings: values.map(embedding), usage: { tokens: values.length * 8 } }) as never);
+ mkdirSync(join(fixture.home, '.gbrain'), { recursive: true });
+ writeFileSync(join(fixture.home, '.gbrain', 'config.json'), JSON.stringify({ ...database,
+ embedding_model: originalModel, embedding_dimensions: dimensions, openai_api_key: 'synthetic-only' }));
+
+ const source = await fixture.boundSource(engine, config);
+ const other = await fixture.boundSource(engine, { kind: 'filesystem' });
+ const ctx = context(engine, source.id);
+ const cfg = parseGoogleSourceConfig(config, source.dir);
+ expect((await runGoogleSync(engine, source.id, cfg, options, gmailFetch)).added).toBe(1);
+ const [email] = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND frontmatter->>'thread_id'='abc123'", [source.id]);
+ const imported = (await engine.readPageSnapshot(email.slug, { sourceId: source.id }))!;
+ const { gmail_attachment_receipts: oldReceipts, ...frontmatter } = imported.page.frontmatter;
+ expect(oldReceipts).toBeDefined();
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: email.slug, expected_revision: imported.revision,
+ content: serializePageToMarkdown({ ...imported.page, frontmatter: { ...frontmatter, visibility: 'private', custom: 'preserved' },
+ compiled_truth: imported.page.compiled_truth + '\nUser-edited historical prose.\n' }, imported.tags) } });
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'people/synthetic-profile',
+ content: `---\ntype: person\ntitle: Synthetic profile\nvisibility: world\n---\n# Synthetic profile\n\n${visibleText}\n` } });
+ await submitPageMutation(context(engine, other.id), { operation: 'put_page', params: { slug: 'notes/foreign',
+ content: `---\ntype: note\ntitle: Synthetic foreign source\nvisibility: world\n---\n${foreignText}\n` } });
+ const beforeWithdrawal = (await engine.readPageSnapshot(email.slug, { sourceId: source.id }))!;
+ const forgotten = await submitRememberMutation(ctx, { fact: retired, entity: 'people/synthetic-profile', provenance: 'synthetic lifecycle', visibility: 'world' });
+ const beforeForget = (await engine.readPageSnapshot('people/synthetic-profile', { sourceId: source.id }))!;
+ const staleImport = serializePageToMarkdown(beforeForget.page, beforeForget.tags);
+ await submitRememberMutation(ctx, { fact: 'Active synthetic subjectless memory', provenance: 'synthetic lifecycle', visibility: 'private' });
+ await submitForgetMutation(ctx, 'forget', { id: forgotten.id });
+ await disposePersistenceConsumer(engine);
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 100 });
+ expect((await engine.readPageSnapshot(email.slug, { sourceId: source.id }))!.revision).toBe(beforeWithdrawal.revision);
+ const thread = await (await gmailFetch('https://gmail.googleapis.com/gmail/v1/users/me/threads/abc123?format=full')).json();
+ const repairChild = async (crash: boolean) => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ let pid: number | undefined;
+ try {
+ const child = Bun.spawn([process.execPath, '--no-env-file', 'run', join(import.meta.dir, 'helpers/memory-safety-wave-repair.ts')], {
+ env: keylessBrainEnv(process.env, fixture.home, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ GBRAIN_TEST_MEMORY_WAVE_REPAIR: JSON.stringify({ database, sourceId: source.id, root: source.dir, sourceConfig: config, thread, crash }) }),
+ stdout: 'pipe', stderr: 'pipe',
+ });
+ pid = child.pid;
+ const timer = setTimeout(() => child.kill('SIGKILL'), 30_000);
+ try {
+ const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, exit };
+ } finally { clearTimeout(timer); if (child.exitCode === null) child.kill('SIGKILL'); await child.exited; }
+ } finally {
+ await engine.connect(database);
+ if (crash && pid) await engine.executeRaw(`UPDATE gbrain_cycle_locks SET acquired_at=now()-interval '2 minutes',last_refreshed_at=now()-interval '1 hour',ttl_expires_at=now()-interval '1 hour' WHERE id=$1 AND holder_pid=$2`, [syncLockId(source.id), pid]);
+ }
+ };
+ const killed = await repairChild(true);
+ expect(killed.stdout, killed.stderr).toContain('MEMORY_WAVE_CRASH after_metadata_commit');
+ expect(killed.exit).not.toBe(0);
+ expect(JSON.stringify(await sourceCheckpoint(engine, source.id))).toContain('"afterPageId":0');
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' AND state='committed'", [source.id])).toHaveLength(1);
+ const resumed = await repairChild(false);
+ expect(resumed.exit, resumed.stderr).toBe(0);
+ expect(resumed.stdout).toContain('"status":"complete"');
+ expect(JSON.stringify(await sourceCheckpoint(engine, source.id))).toContain('"complete":true');
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL', [source.id])).toHaveLength(0);
+ expect(await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_connector_google_receipts' AND state='committed' AND NOT COALESCE((outcome->>'noop')::boolean,false)", [source.id])).toHaveLength(1);
+ const repaired = (await engine.readPageSnapshot(email.slug, { sourceId: source.id }))!;
+ expect(repaired.page.compiled_truth).toBe(beforeWithdrawal.page.compiled_truth);
+ expect(repaired.page.frontmatter).toMatchObject({ visibility: 'private', custom: 'preserved', gmail_attachment_receipts: { messages: [{ inspection: { state: 'present' } }] } });
+ await disposePersistenceConsumer(engine);
+ await withManagedFixtureWrite(engine, [source.id], async tx => {
+ await tx.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1 AND slug='people/synthetic-profile'", [source.id]);
+ await tx.executeRaw('UPDATE facts SET embedding_model=NULL,embedded_text_hash=NULL WHERE source_id=$1 AND expired_at IS NULL', [source.id]);
+ });
+ const migration = { to: targetModel, dim: dimensions, reranker: 'off', maxCostUsd: 1, quiet: true };
+ const migrated = await executeMigrationFlow(engine, await planMigrationFlow(engine, migration), migration);
+ expect(migrated.status).toBe('completed');
+ expect((await countStaleFactEmbeddings(engine, targetModel, dimensions)).count).toBe(0);
+ expect(await engine.executeRaw('SELECT embedding_model,embedding IS NOT NULL AS vector_present,embedded_text_hash=md5(fact) AS current FROM facts WHERE source_id=$1 AND expired_at IS NULL', [source.id]))
+ .toEqual([{ embedding_model: targetModel, vector_present: true, current: true }]);
+ expect(await engine.executeRaw('SELECT fact_hash FROM fact_withdrawals WHERE source_id=$1', [source.id])).toHaveLength(1);
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [source.id, retired])).toHaveLength(0);
+ const current = (await engine.readPageSnapshot('people/synthetic-profile', { sourceId: source.id }))!;
+ expect(sanitizeRemoteBody(current.page.compiled_truth)).not.toContain(retired);
+
+ const output = join(fixture.home, `export-${engine.kind}`);
+ await runExport(engine, ['--source', source.id, '--dir', output]);
+ expect(existsSync(join(output, 'notes/foreign.md'))).toBe(false);
+ expect(readFileSync(join(output, '.gbrain-export-status'), 'utf8')).toBe('GBRAIN EXPORT INCOMPLETE\nCOMPLETE\n');
+ const exported = readFileSync(join(output, 'people/synthetic-profile.md'), 'utf8');
+ expect(exported).toContain(visibleText);
+ expect(sanitizeRemoteBody(exported)).not.toContain(retired);
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: current.page.slug, expected_revision: current.revision, content: exported } });
+ const reimported = (await engine.readPageSnapshot(current.page.slug, { sourceId: source.id }))!;
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: current.page.slug, expected_revision: reimported.revision, content: staleImport } });
+ expect(sanitizeRemoteBody((await engine.readPageSnapshot(current.page.slug, { sourceId: source.id }))!.page.compiled_truth)).not.toContain(retired);
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL', [source.id, retired])).toHaveLength(0);
+
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+ const token = `gbrain_${randomUUID()}`;
+ await engine.executeRaw('INSERT INTO access_tokens(name,token_hash,permissions,scopes) VALUES($1,$2,$3::text::jsonb,$4::text[])',
+ ['synthetic-wave', createHash('sha256').update(token).digest('hex'), JSON.stringify({ source_id: source.id, takes_holders: ['world'] }), ['read']]);
+ const server = await startHttpTransport({ port: 0, engine });
+ try {
+ for (const query of [visibleText, privateText, foreignText, retired, 'genuinemisssentinel']) {
+ const response = await fetch(`http://127.0.0.1:${server.port}/mcp`, { method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'search', arguments: { query, expand: false } } }) });
+ expect(response.status).toBe(200);
+ const body = await response.json() as { result: { isError?: boolean; content: Array<{ text: string }> } };
+ expect(body.result.isError).not.toBe(true);
+ const rows = JSON.parse(body.result.content[0].text) as Array<{ source_id: string }>;
+ if (query === visibleText) {
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.every(row => row.source_id === source.id)).toBe(true);
+ } else expect(rows).toEqual([]);
+ expect(JSON.stringify(body.result)).not.toContain(privateText);
+ expect(JSON.stringify(body.result)).not.toContain(foreignText);
+ expect(JSON.stringify(body.result)).not.toContain(retired);
+ }
+ } finally { server.stop(true); }
+ expect((await engine.readPageSnapshot(email.slug, { sourceId: source.id }))!.page.compiled_truth).toBe(beforeWithdrawal.page.compiled_truth);
+
+ await engine.setConfig('search.mcp_keyword_only', 'false');
+ await registerLocalWriter(engine, 'stdio', { sourceIds: [source.id], operations: null, scopes: ['read'], slugPrefixes: null });
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ let embeddingCalls = 0;
+ const provider = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request) {
+ if (request.method !== 'POST' || new URL(request.url).pathname !== '/v1/embeddings') return new Response('Unexpected fixture endpoint', { status: 400 });
+ const body = await request.json() as { input: string | string[]; model: string };
+ if (body.model !== 'text-embedding-3-large') return new Response('Unexpected fixture model', { status: 400 });
+ embeddingCalls++;
+ const values = Array.isArray(body.input) ? body.input : [body.input];
+ return Response.json({ object: 'list', model: body.model,
+ data: values.map((text, index) => ({ object: 'embedding', index, embedding: embedding(text) })), usage: { prompt_tokens: values.length, total_tokens: values.length } });
+ } });
+ const transport = new StdioClientTransport({ command: process.execPath,
+ args: ['--no-env-file', 'run', join(import.meta.dir, '../src/cli.ts'), 'serve', '--surface', 'starter'],
+ cwd: fixture.home, stderr: 'pipe', env: keylessBrainEnv(process.env, fixture.home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_ENGINE: undefined, GBRAIN_BRAIN_ID: 'host',
+ GBRAIN_SOURCE: source.id, GBRAIN_SCHEMA_PACK: 'gbrain-base-v2', GBRAIN_SWEEP: '0', GBRAIN_SKIP_STARTUP_HOOKS: '1',
+ OPENAI_API_KEY: 'synthetic-only', OPENAI_BASE_URL: `http://127.0.0.1:${provider.port}/v1`,
+ }),
+ });
+ let stderr = '';
+ transport.stderr?.on('data', data => { stderr += String(data); });
+ const client = new Client({ name: 'memory-safety-wave', version: '1' });
+ try {
+ await client.connect(transport);
+ for (const query of [vectorQuery, privateText, foreignText, retired]) {
+ const callsBefore = embeddingCalls;
+ const result = await client.callTool({ name: 'search', arguments: { query, expand: false } });
+ expect(result.isError, stderr).not.toBe(true);
+ const rows = JSON.parse((result.content as Array<{ text: string }>)[0].text) as Array<{ slug: string; source_id: string; cosine?: number }>;
+ const meta = result._meta?.retrieval as { vector_enabled?: boolean; degraded?: unknown[]; projection_readiness: { status: string } };
+ expect(meta.vector_enabled).toBe(true);
+ expect(meta.degraded ?? []).toEqual([]);
+ expect(meta.projection_readiness.status).toBe('ready');
+ expect(embeddingCalls).toBeGreaterThan(callsBefore);
+ expect(rows.every(row => row.source_id === source.id && row.slug !== email.slug)).toBe(true);
+ for (const hidden of [privateText, foreignText, retired]) expect(JSON.stringify(result)).not.toContain(hidden);
+ if (query === vectorQuery) {
+ const positive = rows.find(row => row.slug === 'people/synthetic-profile');
+ expect(positive).toBeDefined();
+ expect(positive!.cosine).toBeGreaterThan(0.99);
+ }
+ }
+ const foreignRequest = await client.callTool({ name: 'search', arguments: { query: foreignText, source_id: other.id, expand: false } });
+ expect(foreignRequest.isError).toBe(true);
+ expect(JSON.stringify(foreignRequest)).not.toContain(foreignText);
+ } finally {
+ await client.close();
+ await transport.close();
+ await provider.stop(true);
+ await engine.connect(database);
+ }
+ }
+}), 180_000);
diff --git a/test/migrate-embeddings-boundary.serial.test.ts b/test/migrate-embeddings-boundary.serial.test.ts
index a3f66f0094..49d3f25f55 100644
--- a/test/migrate-embeddings-boundary.serial.test.ts
+++ b/test/migrate-embeddings-boundary.serial.test.ts
@@ -132,7 +132,7 @@ describe('migration across a stale-batch boundary', () => {
embeddedTexts = [];
const code = await runMigrate([
- '--to', 'openai:text-embedding-3-small', '--yes', '--batch-size', '3',
+ '--to', 'openai:text-embedding-3-small', '--yes', '--max-cost-usd', '1', '--batch-size', '3',
]);
// Pre-fix this was 1 ("Migration incomplete") even though all 6 chunks
// were correctly embedded — the boundary page was never stamped.
@@ -159,7 +159,7 @@ describe('migration across a stale-batch boundary', () => {
test('second run does ZERO work — the "never re-embedded twice" contract holds across a boundary', async () => {
embeddedTexts = [];
const code = await runMigrate([
- '--to', 'openai:text-embedding-3-small', '--yes', '--batch-size', '3',
+ '--to', 'openai:text-embedding-3-small', '--yes', '--max-cost-usd', '1', '--batch-size', '3',
]);
expect(code).toBe(0);
// Pre-fix the unstamped boundary page was re-invalidated and PAID FOR again.
diff --git a/test/migrate-embeddings-flow.serial.test.ts b/test/migrate-embeddings-flow.serial.test.ts
index ce5f071c56..bd31390ba7 100644
--- a/test/migrate-embeddings-flow.serial.test.ts
+++ b/test/migrate-embeddings-flow.serial.test.ts
@@ -195,7 +195,7 @@ describe('migrate embeddings — full flow on PGLite', () => {
failTexts = ['page-4', 'page-5']; // simulate dying mid-run on two pages
embeddedTexts = [];
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--yes']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--yes', '--max-cost-usd', '1']);
expect(code).toBe(1); // incomplete
// Schema + config swapped BEFORE the re-embed, so the partial run is
@@ -223,7 +223,7 @@ describe('migrate embeddings — full flow on PGLite', () => {
failTexts = [];
embeddedTexts = [];
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--yes']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--yes', '--max-cost-usd', '1']);
expect(code).toBe(0);
// Only the two previously-failed pages were embedded this pass, plus the
@@ -275,7 +275,7 @@ describe('migrate embeddings — full flow on PGLite', () => {
test('re-run on an already-migrated brain is a clean no-op', async () => {
embeddedTexts = [];
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--yes']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--yes', '--max-cost-usd', '1']);
expect(code).toBe(0);
// Nothing re-embedded (probe excluded from embeddedTexts by design).
expect(embeddedTexts.length).toBe(0);
diff --git a/test/migrate-embeddings-hardening.serial.test.ts b/test/migrate-embeddings-hardening.serial.test.ts
index 58871ac001..ff720481d1 100644
--- a/test/migrate-embeddings-hardening.serial.test.ts
+++ b/test/migrate-embeddings-hardening.serial.test.ts
@@ -204,7 +204,7 @@ describe('poisonable skip is dead', () => {
await engine.setConfig('embedding_dimensions', String(TO_DIMS));
embeddedTexts = [];
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1']);
expect(code).toBe(0); // completed — by DOING the work, not by skipping it
// 2 drain re-embeds + 2 completion smoke-check query embeds (the smoke
// check is part of the completed path). Vectors restored either way:
@@ -216,7 +216,7 @@ describe('poisonable skip is dead', () => {
// And now that the brain is GENUINELY converged, the verified skip fires.
embeddedTexts = [];
- const again = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ const again = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1']);
expect(again).toBe(0);
expect(embeddedTexts.length).toBe(0); // no work, no spend
}, 60000);
@@ -232,7 +232,7 @@ describe('poisonable skip is dead', () => {
// env != target: the #1421 refusal, unchanged.
process.env.GBRAIN_EMBEDDING_MODEL = 'voyage:voyage-4';
process.env.GBRAIN_EMBEDDING_DIMENSIONS = String(FROM_DIMS);
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1']);
expect(code).toBe(1); // refused_env
} finally {
delete process.env.GBRAIN_EMBEDDING_MODEL;
@@ -251,13 +251,13 @@ describe('poisonable skip is dead', () => {
started_at: '2026-08-01T00:00:00.000Z',
} satisfies MigrationState));
try {
- const refused = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ const refused = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1']);
expect(refused).toBe(1);
// Marker untouched by the refusal.
const marker = await readMigrationState(engine);
expect(marker.state?.to_model).toBe('voyage:voyage-4');
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--retarget']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--retarget']);
expect(code).toBe(0);
// Completed: marker cleared; the abandoned target is in the completion
// path's history via the superseded chain (marker was rewritten then
@@ -436,7 +436,7 @@ describe('reranker companion (D8)', () => {
`INSERT INTO query_cache (id, query_text, source_id) VALUES ('qc-rr', 'stale rank order', 'default')
ON CONFLICT (id) DO NOTHING`,
);
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--reranker', 'off']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--reranker', 'off']);
expect(code).toBe(0);
expect(await engine.getConfig('search.reranker.enabled')).toBe('false');
// Rank order changed ⇒ cache purged in the same transaction.
@@ -472,7 +472,7 @@ describe('reranker companion (D8)', () => {
return origFetch(url as never, init);
}) as typeof fetch;
try {
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--reranker', 'voyage:rerank-2.5']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--reranker', 'voyage:rerank-2.5']);
expect(code).toBe(0);
expect(await engine.getConfig('search.reranker.model')).toBe('voyage:rerank-2.5');
expect(await engine.getConfig('search.reranker.enabled')).toBe('true');
@@ -493,7 +493,7 @@ describe('reranker companion (D8)', () => {
return origFetch(url as never);
}) as typeof fetch;
try {
- const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--reranker', 'voyage:rerank-2.5-lite']);
+ const code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--reranker', 'voyage:rerank-2.5-lite']);
expect(code).toBe(0); // embeddings converged; reranker failure is reported, not fatal
// Old config kept — NOT flipped to the unreachable model.
expect(await engine.getConfig('search.reranker.model')).toBe('voyage:rerank-2.5');
@@ -630,7 +630,7 @@ describe('locked branches refuse before any mutation', () => {
const cap1 = captureStdout();
let code1: number;
try {
- code1 = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ code1 = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--json']);
} finally {
cap1.restore();
}
@@ -654,7 +654,7 @@ describe('locked branches refuse before any mutation', () => {
const cap2 = captureStdout();
let code2: number;
try {
- code2 = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ code2 = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--json']);
} finally {
cap2.restore();
}
@@ -746,7 +746,7 @@ describe('config-plane hygiene (env leak + env-canonical gates)', () => {
const cap = captureStdout();
let code: number;
try {
- code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ code = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--json']);
} finally {
cap.restore();
}
@@ -832,7 +832,7 @@ describe('marker integrity across surfaces', () => {
expect(wrongShape.state).toBeNull();
// A fresh migration rewrites the marker clean (v2) instead of crashing.
- const applied = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--no-embed']);
+ const applied = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--no-embed']);
expect(applied).toBe(0);
const clean = await readMigrationState(engine);
expect(clean.corrupt).toBe(false);
@@ -840,7 +840,7 @@ describe('marker integrity across surfaces', () => {
expect(clean.state?.to_model).toBe('openai:text-embedding-3-small');
// Complete the run: marker cleared, brain left converged for later suites.
- const completed = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ const completed = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1']);
expect(completed).toBe(0);
const after = await readMigrationState(engine);
expect(after.state).toBeNull();
@@ -850,10 +850,10 @@ describe('marker integrity across surfaces', () => {
test('retarget history: superseded chain + retargeted_at + resume-command flag rendering', async () => {
// Target A at the SAME width (no schema churn), applied but not drained —
// leaves a live marker for A.
- const a = await runMigrate(['--to', 'openai:text-embedding-3-large', '--dim', String(TO_DIMS), '--yes', '--no-embed']);
+ const a = await runMigrate(['--to', 'openai:text-embedding-3-large', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--no-embed']);
expect(a).toBe(0);
// Retarget to B: the marker must record A in the superseded history.
- const b = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--no-embed', '--retarget']);
+ const b = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--no-embed', '--retarget']);
expect(b).toBe(0);
const marker = await readMigrationState(engine);
expect(marker.corrupt).toBe(false);
@@ -868,7 +868,7 @@ describe('marker integrity across surfaces', () => {
// Converge again: resume B for real (drains the invalidated chunks).
embeddedTexts = [];
- const done = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ const done = await runMigrate(['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1']);
expect(done).toBe(0);
expect((await readMigrationState(engine)).state).toBeNull();
}, 60000);
@@ -877,6 +877,7 @@ describe('marker integrity across surfaces', () => {
describe('smoke-check miss + heartbeat resilience', () => {
test('verifySearchRoundTrip reports warn/self_retrieval_miss with content-free samples', async () => {
const canary = 'sealed-privacy-canary-text';
+ const targetModel = 'openai:text-embedding-3-small';
try {
// 11 decoy pages whose stored vectors EQUAL the fake transport's query
// vector, then the victim LAST (highest chunk id ⇒ it is the sampled
@@ -888,25 +889,29 @@ describe('smoke-check miss + heartbeat resilience', () => {
await installFixtureChunks(engine, slug, [
{ chunk_index: 0, chunk_text: `decoy chunk ${i}`, chunk_source: 'compiled_truth', token_count: 4 },
]);
+ await engine.setPageEmbeddingSignature(slug, { signature: `${targetModel}:${TO_DIMS}` });
}
await engine.putPage('srm-victim', { type: 'note', title: 'srm-victim', compiled_truth: '# victim\n\nbody' });
await installFixtureChunks(engine, 'srm-victim', [
{ chunk_index: 0, chunk_text: canary, chunk_source: 'compiled_truth', token_count: 4 },
]);
+ await engine.setPageEmbeddingSignature('srm-victim', { signature: `${targetModel}:${TO_DIMS}` });
// The fake transport's vector for ANY input (installTransport pattern).
const q = new Array(TO_DIMS).fill(0).map((_, i) => Math.sin(i) * 0.01 + 0.001);
const far = new Array(TO_DIMS).fill(0);
far[0] = 1; // near-orthogonal to q (q[0] = 0.001)
await engine.executeRaw(
- `UPDATE content_chunks SET embedding = $1::vector
+ `UPDATE content_chunks SET embedding = $1::vector, model = $2,
+ embedded_at = now(), embedded_text_hash = md5(chunk_text)
WHERE page_id IN (SELECT id FROM pages WHERE slug LIKE 'srm-decoy-%')`,
- ['[' + q.join(',') + ']'],
+ ['[' + q.join(',') + ']', targetModel],
);
await engine.executeRaw(
- `UPDATE content_chunks SET embedding = $1::vector
+ `UPDATE content_chunks SET embedding = $1::vector, model = $2,
+ embedded_at = now(), embedded_text_hash = md5(chunk_text)
WHERE page_id IN (SELECT id FROM pages WHERE slug = 'srm-victim')`,
- ['[' + far.join(',') + ']'],
+ ['[' + far.join(',') + ']', targetModel],
);
const outcome = await verifySearchRoundTrip(engine, { samples: 1 });
@@ -1008,7 +1013,7 @@ describe('empty-brain migration (plan pin 15)', () => {
const cap1 = captureStdout();
let code1: number;
try {
- code1 = await runMigrateOn(e2, ['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes']);
+ code1 = await runMigrateOn(e2, ['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1']);
} finally {
cap1.restore();
}
@@ -1037,7 +1042,7 @@ describe('empty-brain migration (plan pin 15)', () => {
const cap2 = captureStdout();
let code2: number;
try {
- code2 = await runMigrateOn(e2, ['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--json']);
+ code2 = await runMigrateOn(e2, ['--to', 'openai:text-embedding-3-small', '--dim', String(TO_DIMS), '--yes', '--max-cost-usd', '1', '--json']);
} finally {
cap2.restore();
}
diff --git a/test/migrate-embeddings-op-contract.serial.test.ts b/test/migrate-embeddings-op-contract.serial.test.ts
index ac06951050..7efe223755 100644
--- a/test/migrate-embeddings-op-contract.serial.test.ts
+++ b/test/migrate-embeddings-op-contract.serial.test.ts
@@ -46,7 +46,7 @@ import {
} from '../src/core/ai/gateway.ts';
import { runEmbedCore } from '../src/commands/embed.ts';
import { operationsByName, type OperationContext } from '../src/core/operations.ts';
-import { GLOBAL_MIGRATION_LOCK_ID } from '../src/commands/migrate-embeddings.ts';
+import { GLOBAL_MIGRATION_LOCK_ID, EMBEDDING_MIGRATION_RECOVERY } from '../src/commands/migrate-embeddings.ts';
import {
MIGRATION_STATE_KEY,
readMigrationState,
@@ -100,6 +100,7 @@ function expectJsonRoundTrip(res: unknown): void {
}
interface OpEnvelope {
+ recovery?: typeof EMBEDDING_MIGRATION_RECOVERY;
status: string;
reason?: string;
holder?: string;
@@ -174,11 +175,14 @@ describe('migrate_embeddings op envelope contract', () => {
test('admin scope + localOnly + remote belt-and-braces guard', async () => {
expect(op.scope).toBe('admin');
expect(op.localOnly).toBe(true);
+ expect(op.params.source).toBeUndefined();
+ expect(op.params.slugs).toBeUndefined();
// Belt-and-braces on top of localOnly: anything not strictly
// remote:false throws before the orchestrator is even imported.
await expect(
op.handler(ctx({ remote: true }), { to: TO_MODEL, dim: TO_DIMS }),
).rejects.toThrow(/local-only/);
+ await expect(op.handler(ctx({ remote: undefined }), { to: TO_MODEL, dim: TO_DIMS })).rejects.toThrow(/local-only/);
}, 30000);
test('refused_env: env pointing at a different model flattens to refused/env_override with warning + plan', async () => {
@@ -188,6 +192,7 @@ describe('migrate_embeddings op envelope contract', () => {
try {
const res = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
expect(res.status).toBe('refused');
+ expect(res.recovery).toBe(EMBEDDING_MIGRATION_RECOVERY);
expect(res.reason).toBe('env_override');
expect(res.warning?.triggered).toBe(true);
const varNames = (res.warning?.vars ?? []).map((v) => v.name);
@@ -221,6 +226,7 @@ describe('migrate_embeddings op envelope contract', () => {
// the CLI ordering — retarget decision precedes any skip/execute).
const refused = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
expect(refused.status).toBe('refused');
+ expect(refused.recovery).toBe(EMBEDDING_MIGRATION_RECOVERY);
expect(refused.reason).toBe('retarget_required');
expect(refused.inflight?.to_model).toBe('voyage:voyage-4');
expect(refused.inflight?.to_dims).toBe(1024);
@@ -235,6 +241,7 @@ describe('migrate_embeddings op envelope contract', () => {
// (`p.dry_run !== true` in the guard) and renders the plan instead.
const dry = await runOp({ to: TO_MODEL, dim: TO_DIMS, dry_run: true });
expect(dry.status).toBe('planned');
+ expect(dry.recovery).toBeUndefined();
expect(dry.plan?.to_model).toBe(TO_MODEL);
expectJsonRoundTrip(dry);
} finally {
@@ -253,6 +260,7 @@ describe('migrate_embeddings op envelope contract', () => {
try {
const res = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
expect(res.status).toBe('locked');
+ expect(res.recovery).toBe(EMBEDDING_MIGRATION_RECOVERY);
expect(res.holder).toBe('migration');
expect(res.detail).toContain('migration lock');
expect(res.plan?.to_model).toBe(TO_MODEL);
@@ -262,11 +270,45 @@ describe('migrate_embeddings op envelope contract', () => {
}
}, 30000);
+ test('provider and apply failures keep failed discriminators and share static recovery guidance', async () => {
+ __setEmbedTransportForTests(async () => { throw new Error('synthetic-private-provider-detail'); });
+ try {
+ const probe = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true, max_cost_usd: 1, reranker: 'off' });
+ expect(probe.status).toBe('failed');
+ expect(probe.reason).toContain('Preflight embed');
+ expect(probe.recovery).toBe(EMBEDDING_MIGRATION_RECOVERY);
+ expect(probe.recovery?.docs).toBe('https://github.com/garrytan/gbrain/blob/master/docs/guides/embedding-migration.md#recovery');
+ expect(JSON.stringify(probe)).not.toContain('synthetic-private-provider-detail');
+ await engine.setConfig('embedding_disabled', 'true');
+ const applied = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true, max_cost_usd: 1, reranker: 'off' });
+ expect(applied.status).toBe('failed');
+ expect(applied.reason).toContain('Embedding is disabled');
+ expect(applied.recovery).toBe(EMBEDDING_MIGRATION_RECOVERY);
+ } finally { await engine.unsetConfig('embedding_disabled'); installTransport(); }
+ }, 30_000);
+
+ test('incomplete local operation retains its discriminator and recovery guidance', async () => {
+ currentDims = TO_DIMS;
+ __setEmbedTransportForTests(async ({ values }) => ({
+ embeddings: values.map(text => Array(TO_DIMS).fill(text.includes('probe') ? 0.1 : NaN)), usage: { tokens: 8 },
+ }) as never);
+ try {
+ const result = await op.handler(ctx({ sourceId: 'default' }), {
+ to: TO_MODEL, dim: TO_DIMS, yes: true, max_cost_usd: 1, reranker: 'off',
+ }) as OpEnvelope;
+ expect(result.status).toBe('incomplete');
+ expect(result.remaining).toBeGreaterThan(0);
+ expect(result.recovery).toBe(EMBEDDING_MIGRATION_RECOVERY);
+ expectJsonRoundTrip(result);
+ } finally { installTransport(); }
+ }, 30_000);
+
test('live run completes; second call returns skipped_no_work with the verify payload and zero embed spend', async () => {
currentDims = TO_DIMS;
embeddedTexts = [];
- const completed = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
+ const completed = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true, max_cost_usd: 1, reranker: 'off' });
expect(completed.status).toBe('completed');
+ expect(completed.recovery).toBeUndefined();
expect(completed.remaining).toBe(0);
expect(Number(completed.embedded)).toBeGreaterThan(0);
expect(completed.verify_search?.status).toBeDefined();
@@ -280,8 +322,9 @@ describe('migrate_embeddings op envelope contract', () => {
// Converged brain: the DB-verified skip fires on the second call — no
// work, no spend, verify payload attached.
embeddedTexts = [];
- const skipped = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true });
+ const skipped = await runOp({ to: TO_MODEL, dim: TO_DIMS, yes: true, reranker: 'off' });
expect(skipped.status).toBe('skipped_no_work');
+ expect(skipped.recovery).toBeUndefined();
expect(skipped.verified?.complete).toBe(true);
expect(skipped.plan?.to_model).toBe(TO_MODEL);
expectJsonRoundTrip(skipped);
diff --git a/test/migrate-embeddings-recovery-cli.serial.test.ts b/test/migrate-embeddings-recovery-cli.serial.test.ts
new file mode 100644
index 0000000000..98963ab098
--- /dev/null
+++ b/test/migrate-embeddings-recovery-cli.serial.test.ts
@@ -0,0 +1,235 @@
+import { expect, test } from 'bun:test';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { tryAcquireDbLock } from '../src/core/db-lock.ts';
+import { GLOBAL_MIGRATION_LOCK_ID, MIGRATION_STATE_KEY, runMigrateEmbeddings, parseMigrateEmbeddingsFlags } from '../src/commands/migrate-embeddings.ts';
+import { runSchemaTransition } from '../src/core/embedding-migration.ts';
+import { migrationCliArgumentError } from '../src/core/embedding-migration-cli.ts';
+import { parseGlobalFlags } from '../src/core/cli-options.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const MODEL = 'openai:text-embedding-3-small';
+const DOCS = 'https://github.com/garrytan/gbrain/blob/master/docs/guides/embedding-migration.md#recovery';
+const SECRET = 'synthetic-credential-never-print';
+const PRIVATE_BODY = 'SYNTHETIC_PRIVATE_BODY_NEVER_PRINT';
+const cliPath = join(import.meta.dir, '../src/cli.ts');
+const gatewayPath = join(import.meta.dir, '../src/core/ai/gateway.ts');
+const invalidControls = [
+ ['--source', 'default'], ['--source=default'], ['--slugs', 'notes/scope-a'], ['--slugs=notes/scope-a'],
+ ['--facts'], ['--facts=true'], ['--timeout', '30s'], ['--timeout=30s'],
+ ['--limit', '1'], ['--background'], ['--type', 'note'], ['--include-null-signature'], ['--all'],
+ ['--to'], ['--to=example:model'], ['--reranker'], ['--reranker=off'], ['--yes=false'], ['--json=false'],
+ ['--dim'], ['--dim=8'], ...['0', '-1', '1.5', '8oops', 'NaN', 'Infinity', '100001', '9007199254740993'].map(v => ['--dim', v]),
+ ['--batch-size'], ['--batch-size=2'], ...['0', '-1', '1.5', '2oops', 'NaN', 'Infinity', '10001'].map(v => ['--batch-size', v]),
+ ['--max-cost-usd'], ['--max-cost-usd=1'], ...['-1', 'NaN', 'Infinity', '1oops'].map(v => ['--max-cost-usd', v]),
+ ['--pace='], ['--pace=typo'], ['--pace', 'gentle'], ['--pace-max-concurrency'], ['--pace-max-concurrency=2oops'],
+ ...['0', '-1', '1.5', '2oops', 'Infinity'].map(v => ['--pace-max-concurrency', v]),
+ ['--progress-interval=0.5'], ['--progress-interval', '-1'], ['--quiet=true'],
+ ['--dim', '8', '--dim', '16'], ['--', '--facts'],
+];
+
+test.each(invalidControls.map(args => [args.join(' '), args] as const))('direct migration parser rejects %s', (_label, args) => {
+ expect(() => parseMigrateEmbeddingsFlags([...args])).toThrow();
+});
+
+test('the shared migration contract preserves supported pacing, globals and exact numeric values', () => {
+ expect(parseMigrateEmbeddingsFlags(['--to', MODEL, '--dim', '8', '--batch-size', '1', '--max-cost-usd', '0.25',
+ '--non-interactive', '--pace=gentle', '--pace-max-concurrency=2'])).toMatchObject({
+ to: MODEL, dim: 8, batchSize: 1, maxCostUsd: 0.25, yes: true,
+ pace: { perCallMode: 'gentle', perCall: { maxConcurrency: 2 } },
+ });
+ expect(parseMigrateEmbeddingsFlags(['--pace', '--pace-max-concurrency', '3']).pace).toEqual({ perCallMode: 'balanced', perCall: { maxConcurrency: 3 } });
+ expect(parseMigrateEmbeddingsFlags(['--pace=off']).pace).toEqual({ perCallMode: 'off' });
+ expect(parseMigrateEmbeddingsFlags(['--dim', '100000', '--batch-size', '10000', '--max-cost-usd', '0'])).toMatchObject({ dim: 100000, batchSize: 10000, maxCostUsd: 0 });
+ for (const route of [['migrate', 'embeddings'], ['retrieval-upgrade']]) {
+ const raw = ['--brain=host', '--quiet', ...route, '--progress-json', '--progress-interval=0', '--status', '--json'];
+ const parsed = parseGlobalFlags(raw);
+ expect(migrationCliArgumentError(parsed.rest[0], parsed.rest.slice(1), raw)).toBeNull();
+ for (const timeout of [['--timeout', '30s'], ['--timeout=30s']]) {
+ const rawTimeout = [...timeout, ...route, '--status'];
+ const stripped = parseGlobalFlags(rawTimeout);
+ expect(stripped.cliOpts.timeoutMs).toBe(30000);
+ expect(stripped.rest).not.toContain(timeout[0]);
+ expect(migrationCliArgumentError(stripped.rest[0], stripped.rest.slice(1), rawTimeout)?.flag).toBe('--timeout');
+ }
+ }
+});
+
+test.each(['apply_failed', 'probe_failed', 'incomplete', 'locked', 'refused', 'retarget_refused'] as const)('real migration CLI supplies private-safe recovery guidance for %s', async status => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-recovery-cli-'));
+ const data = join(home, '.gbrain');
+ const calls = join(home, 'synthetic-calls.txt');
+ const preload = join(home, 'synthetic-provider.ts');
+ mkdirSync(data);
+ writeFileSync(join(data, 'config.json'), JSON.stringify({
+ engine: 'pglite', database_path: join(data, 'brain.pglite'),
+ embedding_model: MODEL, embedding_dimensions: 8, openai_api_key: SECRET,
+ embedding_disabled: status === 'apply_failed',
+ }));
+ writeFileSync(preload, `
+ import { appendFileSync } from 'node:fs';
+ import { __setEmbedTransportForTests } from ${JSON.stringify(gatewayPath)};
+ globalThis.fetch = async () => { throw new Error('Synthetic fixture blocks external network'); };
+ __setEmbedTransportForTests(async ({values}) => {
+ appendFileSync(${JSON.stringify(calls)}, 'call\\n');
+ if (${JSON.stringify(status)} === 'probe_failed') throw new Error(${JSON.stringify(`${SECRET} ${PRIVATE_BODY}`)});
+ return { embeddings: values.map(value => Array(8).fill(
+ ${JSON.stringify(status)} === 'incomplete' && value !== 'gbrain embedding migration probe' ? NaN : 0.1
+ )), usage: { tokens: 8 } };
+ });
+ `);
+ const env: NodeJS.ProcessEnv = { ...process.env, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1' };
+ for (const key of Object.keys(env)) {
+ if (/(?:API_KEY|TOKEN|SECRET|DATABASE_URL)$/.test(key) || key.startsWith('GBRAIN_') && !['GBRAIN_HOME', 'GBRAIN_SKIP_STARTUP_HOOKS'].includes(key)) delete env[key];
+ }
+ if (status === 'refused') env.GBRAIN_EMBEDDING_MODEL = 'openai:text-embedding-3-large';
+ const run = async (args: string[]) => {
+ const child = Bun.spawn([process.execPath, '--preload', preload, cliPath, 'migrate', 'embeddings', ...args], {
+ cwd: home, env, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, code };
+ };
+ const engine = new PGLiteEngine();
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await engine.connect({ database_path: join(data, 'brain.pglite'), embedding_dimensions: 8 } as never);
+ await engine.initSchema();
+ await engine.setConfig('embedding_model', MODEL);
+ await engine.setConfig('embedding_dimensions', '8');
+ await engine.putPage('notes/recovery-fixture', { type: 'note', title: 'Synthetic recovery', compiled_truth: PRIVATE_BODY });
+ await engine.upsertChunks('notes/recovery-fixture', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: PRIVATE_BODY }]);
+ if (status === 'locked') expect(await tryAcquireDbLock(engine, GLOBAL_MIGRATION_LOCK_ID, 5)).not.toBeNull();
+ if (status === 'retarget_refused') await engine.setConfig(MIGRATION_STATE_KEY, JSON.stringify({
+ version: 2, to_model: 'openai:text-embedding-3-large', to_dims: 8,
+ from_model: MODEL, from_dims: 8, started_at: '2026-09-01T00:00:00.000Z',
+ }));
+ await engine.disconnect();
+ });
+ const args = ['--to', MODEL, '--dim', '8', '--yes', '--max-cost-usd', '1', '--reranker', 'off'];
+ const preview = await run([...args, '--dry-run', '--json']);
+ expect(preview.code).toBe(0);
+ expect(JSON.parse(preview.stdout).status).toBe('planned');
+ expect(JSON.parse(preview.stdout).recovery).toBeUndefined();
+ expect(preview.stderr).not.toContain('Recovery:');
+ const json = await run([...args, '--json']);
+ expect({ code: json.code, stderr: json.code !== 1 ? json.stderr : '' }).toEqual({ code: 1, stderr: '' });
+ const envelope = JSON.parse(json.stdout);
+ expect(envelope.status).toBe(status === 'retarget_refused' ? 'refused' : status);
+ expect(envelope.plan).toBeDefined();
+ expect(envelope.recovery).toEqual({
+ status_command: 'gbrain migrate embeddings --status --json', docs: DOCS,
+ partial_state: 'Previously committed progress and authorization debits may remain.',
+ action: 'Inspect the selected brain using the same --brain selection before retrying. Do not blindly retry or reset the migration marker.',
+ authorization: 'Increasing --max-cost-usd renews authorization for a larger total cap; it does not reset prior debits.',
+ });
+ if (status === 'refused') expect(envelope.reason).toBe('env_override');
+ if (status === 'retarget_refused') expect(envelope.reason).toBe('retarget_required');
+ if (status === 'apply_failed') expect(envelope.reason).toContain('Embedding is disabled');
+ if (status === 'probe_failed') expect(envelope.message).toContain('Preflight embed');
+ if (status === 'incomplete') expect(envelope.remaining).toBeGreaterThan(0);
+ const human = await run(args);
+ expect(human.code).toBe(1);
+ for (const output of [json, human]) {
+ for (const value of Object.values(envelope.recovery)) expect(output.stderr).toContain(String(value));
+ expect(output.stdout + output.stderr).not.toContain(SECRET);
+ expect(output.stdout + output.stderr).not.toContain(PRIVATE_BODY);
+ }
+ if (['apply_failed', 'locked', 'refused', 'retarget_refused'].includes(status)) expect(existsSync(calls)).toBe(false);
+ else expect(readFileSync(calls, 'utf8')).toContain('call');
+ const help = await run(['--help']);
+ expect(help.code).toBe(0);
+ expect(help.stdout).toContain(DOCS);
+ expect(help.stdout).toContain('gbrain migrate embeddings --status --json');
+ expect(help.stderr).not.toContain('Recovery:');
+ } finally {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ }
+}, 120_000);
+
+test('both actual migration CLI routes reject unsupported or malformed controls before connection, planning, or dispatch', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-migration-scope-'));
+ const data = join(home, '.gbrain');
+ const calls = join(home, 'dispatch.txt');
+ const preload = join(home, 'provider.ts');
+ const database = { database_path: join(data, 'brain.pglite'), embedding_dimensions: 8 };
+ const engine = new PGLiteEngine();
+ mkdirSync(data);
+ const config = JSON.stringify({ engine: 'pglite', ...database, embedding_model: MODEL, openai_api_key: SECRET });
+ writeFileSync(join(data, 'config.json'), config);
+ writeFileSync(preload, `
+ import { appendFileSync } from 'node:fs';
+ import { __setEmbedTransportForTests } from ${JSON.stringify(gatewayPath)};
+ globalThis.fetch = async () => { throw new Error('Synthetic fixture blocks external network'); };
+ __setEmbedTransportForTests(async () => { appendFileSync(${JSON.stringify(calls)}, 'dispatch'); throw new Error('Synthetic provider tripwire'); });
+ `);
+ const env: NodeJS.ProcessEnv = { ...process.env, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1' };
+ for (const key of Object.keys(env)) {
+ if (/(?:API_KEY|TOKEN|SECRET|DATABASE_URL)$/.test(key) || key.startsWith('GBRAIN_') && !['GBRAIN_HOME', 'GBRAIN_SKIP_STARTUP_HOOKS'].includes(key)) delete env[key];
+ }
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await engine.connect(database as never);
+ await engine.initSchema();
+ await runSchemaTransition(engine, 8);
+ await engine.setConfig('embedding_model', MODEL);
+ await engine.setConfig('embedding_dimensions', '8');
+ for (const slug of ['notes/scope-a', 'notes/scope-b']) {
+ await engine.putPage(slug, { type: 'note', title: 'Synthetic scope fixture', compiled_truth: PRIVATE_BODY });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: PRIVATE_BODY, embedding: new Float32Array(8).fill(0.1) }]);
+ }
+ const snapshot = async () => Promise.all(['pages', 'content_chunks', 'facts', 'config', 'gbrain_cycle_locks'].map(table =>
+ engine.executeRaw(`SELECT to_jsonb(t) AS row FROM ${table} t ORDER BY to_jsonb(t)::text`)));
+ const before = await snapshot();
+ await engine.disconnect();
+ for (const route of [['migrate', 'embeddings'], ['retrieval-upgrade']]) {
+ for (const narrowing of invalidControls) {
+ const flag = narrowing[0].split('=')[0];
+ const controls = [['--to', 'openai:text-embedding-3-large'], ['--dim', '8'], ['--yes'], ['--max-cost-usd', '1']]
+ .filter(([name]) => name !== flag).flat();
+ const child = Bun.spawn([process.execPath, '--preload', preload, cliPath, ...route,
+ ...controls, '--json', ...narrowing], {
+ cwd: home, env, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ expect(code).toBe(1);
+ expect(JSON.parse(stdout)).toMatchObject({ status: 'error', reason: 'invalid_flag' });
+ if (['--source', '--slugs'].includes(flag)) expect(stderr).toContain(`unknown flag ${flag}`);
+ else expect(stderr).toContain(flag);
+ expect(stderr).not.toContain('PGLite');
+ expect(existsSync(calls)).toBe(false);
+ expect(readFileSync(join(data, 'config.json'), 'utf8')).toBe(config);
+ await engine.connect(database as never);
+ expect(await snapshot()).toEqual(before);
+ await engine.disconnect();
+ }
+ for (const supported of [
+ ['--dry-run', '--pace=gentle', '--pace-max-concurrency=2', '--quiet', '--progress-json', '--progress-interval=0', '--brain=host'],
+ ['--dry-run', '--pace', '--pace-max-concurrency', '3', '--quiet'], ['--status'], ['--help'],
+ ]) {
+ const child = Bun.spawn([process.execPath, '--preload', preload, cliPath, ...route,
+ '--to', MODEL, '--dim', '8', '--yes', '--max-cost-usd', '1', '--json', ...supported], { cwd: home, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ expect({ code, stderr: code !== 0 ? stderr : '' }).toEqual({ code: 0, stderr: '' });
+ if (supported.includes('--help')) {
+ expect(stdout).toContain('without --no-embed using the same cap; prior debits remain');
+ expect(stdout).not.toContain('gbrain embed --stale');
+ expect(stdout).toContain(DOCS);
+ } else expect(JSON.parse(stdout).status).toBe(supported.includes('--status') ? 'status' : 'planned');
+ expect(existsSync(calls)).toBe(false);
+ expect(readFileSync(join(data, 'config.json'), 'utf8')).toBe(config);
+ await engine.connect(database as never);
+ expect(await snapshot()).toEqual(before);
+ await engine.disconnect();
+ }
+ }
+ const inaccessible = new Proxy(engine, { get() { throw new Error('Planning touched the engine'); } });
+ for (const flag of ['--source', '--source=default', '--slugs', '--slugs=notes/scope-a']) {
+ await expect(runMigrateEmbeddings(inaccessible, ['--to', MODEL, '--yes', flag])).rejects.toThrow('brain-wide');
+ }
+ });
+ } finally { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); }
+}, 180_000);
diff --git a/test/migration-vector-replay.test.ts b/test/migration-vector-replay.test.ts
new file mode 100644
index 0000000000..ea413cd7b4
--- /dev/null
+++ b/test/migration-vector-replay.test.ts
@@ -0,0 +1,78 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { MIGRATIONS } from '../src/core/migrate.ts';
+import { createConnectorFixture } from './helpers/connector-fixture.ts';
+
+const fixture = createConnectorFixture();
+beforeAll(fixture.setup, 120_000);
+afterAll(fixture.teardown);
+
+for (const { table, version, index } of [
+ { table: 'facts', version: 45, index: 'idx_facts_embedding_hnsw' },
+ { table: 'query_cache', version: 55, index: 'idx_query_cache_embedding_hnsw' },
+]) {
+ for (const { type, dimensions, indexed } of [
+ { type: 'vector', dimensions: 8, indexed: true },
+ { type: 'halfvec', dimensions: 8, indexed: true },
+ { type: 'vector', dimensions: 2048, indexed: false },
+ { type: 'halfvec', dimensions: 4096, indexed: false },
+ ]) {
+ test(`migration ${version} replay preserves existing ${type}(${dimensions}) rows and physical index policy`, async () => {
+ for (const engine of fixture.engines) {
+ await engine.executeRaw(`DELETE FROM ${table}`);
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${index}`);
+ await engine.executeRaw(`ALTER TABLE ${table} ALTER COLUMN embedding TYPE ${type}(${dimensions}) USING NULL`);
+ await engine.setConfig('embedding_dimensions', '16');
+ const vector = `[${Array(dimensions).fill('0.125').join(',')}]`;
+ if (table === 'facts') {
+ await engine.executeRaw(`INSERT INTO facts(source_id,fact,source,embedding)
+ VALUES('default','Synthetic retained fact','synthetic-replay',$1::${type})`, [vector]);
+ } else {
+ await engine.executeRaw(`INSERT INTO query_cache(id,query_text,source_id,embedding,results)
+ VALUES('synthetic-cache','Synthetic retained query','default',$1::${type},'[]'::jsonb)`, [vector]);
+ }
+ const snapshot = () => engine.executeRaw(`SELECT to_jsonb(t) AS row FROM ${table} t ORDER BY id`);
+ const before = await snapshot();
+ expect(before).toHaveLength(1);
+ const migration = MIGRATIONS.find(entry => entry.version === version)!;
+ await migration.handler!(engine);
+ const indexState = () => engine.executeRaw<{ oid: string; definition: string }>(
+ `SELECT c.oid::text AS oid,pg_get_indexdef(c.oid) AS definition
+ FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
+ WHERE n.nspname='public' AND c.relname=$1`, [index]);
+ const firstIndex = await indexState();
+ expect(firstIndex).toHaveLength(indexed ? 1 : 0);
+ if (indexed) expect(firstIndex[0].definition).toContain(`${type}_cosine_ops`);
+ await migration.handler!(engine);
+ expect(await indexState()).toEqual(firstIndex);
+ expect(await snapshot()).toEqual(before);
+ expect(await engine.getConfig('embedding_dimensions')).toBe('16');
+ const shape = await engine.executeRaw<{ shape: string }>(
+ `SELECT format_type(a.atttypid,a.atttypmod) AS shape
+ FROM pg_attribute a JOIN pg_class c ON c.oid=a.attrelid
+ JOIN pg_namespace n ON n.oid=c.relnamespace
+ WHERE n.nspname='public' AND c.relname=$1 AND a.attname='embedding'
+ AND a.attnum>0 AND NOT a.attisdropped`, [table]);
+ expect(shape).toEqual([{ shape: `${type}(${dimensions})` }]);
+ }
+ }, 60_000);
+ }
+ for (const shape of ['missing', 'text', 'vector']) {
+ test(`migration ${version} refuses an existing ${shape} embedding shape without changing retained rows`, async () => {
+ for (const engine of fixture.engines) {
+ await engine.executeRaw(`DROP INDEX IF EXISTS ${index}`);
+ await engine.executeRaw(`ALTER TABLE ${table} DROP COLUMN embedding`);
+ if (shape !== 'missing') await engine.executeRaw(`ALTER TABLE ${table} ADD COLUMN embedding ${shape}`);
+ const snapshot = () => engine.executeRaw(`SELECT to_jsonb(t) AS row FROM ${table} t ORDER BY id`);
+ const before = await snapshot();
+ const ledger = await engine.getConfig('version');
+ await expect(MIGRATIONS.find(entry => entry.version === version)!.handler!(engine))
+ .rejects.toThrow(`Cannot replay ${table} migration`);
+ expect(await snapshot()).toEqual(before);
+ expect(await engine.getConfig('version')).toBe(ledger);
+ expect(await engine.getConfig('embedding_dimensions')).toBe('16');
+ await engine.executeRaw(`ALTER TABLE ${table} DROP COLUMN IF EXISTS embedding`);
+ await engine.executeRaw(`ALTER TABLE ${table} ADD COLUMN embedding vector(8)`);
+ }
+ }, 60_000);
+ }
+}
diff --git a/test/native-export-faults.test.ts b/test/native-export-faults.test.ts
new file mode 100644
index 0000000000..213770c109
--- /dev/null
+++ b/test/native-export-faults.test.ts
@@ -0,0 +1,52 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { family, GLIBC } from 'detect-libc';
+
+const supported = process.platform === 'linux' && await family() === GLIBC;
+const roots: string[] = [];
+let interposer: string;
+function temporary(): string {
+ const path = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-export-fault-')));
+ roots.push(path);
+ return path;
+}
+
+describe.skipIf(!supported)('native export OS fault injection (Linux glibc)', () => {
+ beforeAll(() => {
+ interposer = join(temporary(), 'faults.so');
+ const compile = Bun.spawnSync(['cc', '-shared', '-fPIC', resolve(import.meta.dir, 'fixtures/native-export-faults.c'), '-ldl', '-o', interposer]);
+ expect(compile.exitCode).toBe(0);
+ });
+ afterAll(() => {
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+ });
+ test.each(['write', 'flush', 'directory-flush', 'complete-flush', 'crash'])('retains honest incomplete evidence after %s failure', async fault => {
+ const root = temporary();
+ const child = Bun.spawn([process.execPath, '--no-env-file', resolve(import.meta.dir, 'fixtures/native-export-process.ts'), root, 'publish'], {
+ stdout: 'pipe', stderr: 'pipe',
+ env: { PATH: process.env.PATH, LD_PRELOAD: interposer, GBRAIN_EXPORT_TEST_FAULT: fault },
+ });
+ expect(await child.exited).not.toBe(0);
+ expect(readFileSync(join(root, '.gbrain-export-status'), 'utf8')).toBe('GBRAIN EXPORT INCOMPLETE\n');
+ const names = readdirSync(root);
+ const staged = names.filter(name => /^\.gbrain-export-[0-9a-f]{32}\.tmp$/.test(name));
+ if (fault === 'crash') {
+ expect(staged).toHaveLength(1);
+ expect(readFileSync(join(root, staged[0]!))).toEqual(Buffer.alloc(16, 42));
+ } else expect(staged).toEqual([]);
+ expect(names.includes('data')).toBe(fault === 'complete-flush' || fault === 'directory-flush');
+ });
+
+ test('retries interrupted and short OS writes until every byte is flushed', async () => {
+ const root = temporary();
+ const child = Bun.spawn([process.execPath, '--no-env-file', resolve(import.meta.dir, 'fixtures/native-export-process.ts'), root, 'publish'], {
+ stdout: 'pipe', stderr: 'pipe',
+ env: { PATH: process.env.PATH, LD_PRELOAD: interposer, GBRAIN_EXPORT_TEST_FAULT: 'short-write' },
+ });
+ expect(await child.exited).toBe(0);
+ expect(readFileSync(join(root, 'data'))).toEqual(Buffer.alloc(4096, 42));
+ expect(readFileSync(join(root, '.gbrain-export-status'), 'utf8')).toBe('GBRAIN EXPORT INCOMPLETE\nCOMPLETE\n');
+ });
+});
diff --git a/test/native-export-publication.test.ts b/test/native-export-publication.test.ts
new file mode 100644
index 0000000000..5c70050744
--- /dev/null
+++ b/test/native-export-publication.test.ts
@@ -0,0 +1,219 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { nativeExportPublisher, type NativeExportPublisher } from '../src/core/persistence/native-lock.ts';
+
+const roots: string[] = [];
+const handles: Array<{ publisher: NativeExportPublisher; handle: object }> = [];
+const incomplete = 'GBRAIN EXPORT INCOMPLETE\n';
+const marker = '.gbrain-export-status';
+function temporary(): string {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-export-native-')));
+ roots.push(root);
+ return root;
+}
+async function begin(root: string) {
+ const publisher = await nativeExportPublisher();
+ const handle = publisher.beginExport(root);
+ handles.push({ publisher, handle });
+ return { publisher, handle };
+}
+afterEach(() => {
+ for (const { publisher, handle } of handles.splice(0)) publisher.closeExport(handle);
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
+describe('native export publication', () => {
+ test('creates nested destinations, publishes exact binary bytes, completes and closes twice', async () => {
+ const root = join(temporary(), 'new', 'export ünicode');
+ const { publisher, handle } = await begin(root);
+ expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);
+ const bytes = Buffer.from([0, 1, 255, 10, 0, 13]);
+ publisher.publishExportFile(handle, 'nested/ü.txt', bytes);
+ publisher.publishExportFile(handle, 'empty', Buffer.alloc(0));
+ expect(readFileSync(join(root, 'nested/ü.txt'))).toEqual(bytes);
+ expect(readdirSync(join(root, 'nested'))).toEqual(['ü.txt']);
+ publisher.completeExport(handle);
+ expect(readFileSync(join(root, marker), 'utf8')).toBe(`${incomplete}COMPLETE\n`);
+ expect(() => publisher.publishExportFile(handle, 'later', bytes)).toThrow();
+ publisher.closeExport(handle);
+ publisher.closeExport(handle);
+ expect(() => publisher.completeExport(handle)).toThrow();
+ });
+
+ test('reserves the marker exclusively and retains evidence after close', async () => {
+ const root = temporary();
+ const { publisher, handle } = await begin(root);
+ expect(() => publisher.beginExport(root)).toThrow();
+ publisher.closeExport(handle);
+ expect(() => publisher.beginExport(root)).toThrow();
+ expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);
+ });
+
+ test('never modifies a preexisting marker or a non-directory destination prefix', async () => {
+ const root = temporary();
+ const publisher = await nativeExportPublisher();
+ writeFileSync(join(root, marker), 'operator-owned bytes');
+ expect(() => publisher.beginExport(root)).toThrow();
+ expect(readFileSync(join(root, marker), 'utf8')).toBe('operator-owned bytes');
+ writeFileSync(join(root, 'file'), 'keep');
+ expect(() => publisher.beginExport(join(root, 'file', 'child'))).toThrow();
+ expect(readFileSync(join(root, 'file'), 'utf8')).toBe('keep');
+ });
+
+ test.skipIf(process.platform === 'win32').each(['destination', 'ancestor', 'marker'])('refuses once-only %s replacement before publication', async kind => {
+ const base = temporary();
+ const root = join(base, 'parent', 'export');
+ const { publisher, handle } = await begin(root);
+ publisher.publishExportFile(handle, 'first', Buffer.from('first bytes'));
+ let retainedRoot = root;
+ let retainedMarker = join(root, marker);
+ if (kind === 'marker') {
+ retainedMarker = join(root, 'old-marker');
+ renameSync(join(root, marker), retainedMarker);
+ writeFileSync(join(root, marker), 'replacement marker');
+ } else {
+ const replaced = kind === 'ancestor' ? join(base, 'parent') : root;
+ renameSync(replaced, `${replaced}-old`);
+ mkdirSync(root, { recursive: true });
+ retainedRoot = kind === 'ancestor' ? join(base, 'parent-old', 'export') : `${root}-old`;
+ retainedMarker = join(retainedRoot, marker);
+ }
+ expect(() => publisher.publishExportFile(handle, 'second', Buffer.from('second bytes'))).toThrow();
+ expect(() => publisher.completeExport(handle)).toThrow();
+ expect(readFileSync(retainedMarker, 'utf8')).toBe(incomplete);
+ expect(existsSync(join(retainedRoot, 'second'))).toBe(false);
+ expect(existsSync(join(root, 'second'))).toBe(false);
+ if (kind === 'marker') expect(readFileSync(join(root, marker), 'utf8')).toBe('replacement marker');
+ else expect(readdirSync(root)).toEqual([]);
+ });
+
+ test.skipIf(process.platform === 'win32').each(['destination', 'ancestor', 'marker'])('refuses once-only %s replacement immediately before completion', async kind => {
+ const base = temporary();
+ const root = join(base, 'parent', 'export');
+ const { publisher, handle } = await begin(root);
+ publisher.publishExportFile(handle, 'first', Buffer.from('first bytes'));
+ let retainedMarker: string;
+ if (kind === 'marker') {
+ retainedMarker = join(root, 'old-marker');
+ renameSync(join(root, marker), retainedMarker);
+ writeFileSync(join(root, marker), 'replacement marker');
+ } else {
+ const replaced = kind === 'ancestor' ? join(base, 'parent') : root;
+ renameSync(replaced, `${replaced}-old`);
+ mkdirSync(root, { recursive: true });
+ retainedMarker = join(kind === 'ancestor' ? join(base, 'parent-old', 'export') : `${root}-old`, marker);
+ }
+ expect(() => publisher.completeExport(handle)).toThrow();
+ expect(readFileSync(retainedMarker, 'utf8')).toBe(incomplete);
+ if (kind === 'marker') expect(readFileSync(join(root, marker), 'utf8')).toBe('replacement marker');
+ else expect(readdirSync(root)).toEqual([]);
+ expect(() => publisher.publishExportFile(handle, 'second', Buffer.from('no'))).toThrow();
+ });
+
+ test.each(['file', 'directory', 'hardlink'])('never replaces an existing %s', async kind => {
+ const root = temporary();
+ const leaf = join(root, 'occupied');
+ if (kind === 'directory') mkdirSync(leaf);
+ else {
+ writeFileSync(join(root, 'original'), 'original bytes');
+ if (kind === 'hardlink') linkSync(join(root, 'original'), leaf);
+ else writeFileSync(leaf, 'original bytes');
+ }
+ const { publisher, handle } = await begin(root);
+ expect(() => publisher.publishExportFile(handle, 'occupied', Buffer.from('replacement'))).toThrow();
+ expect(() => publisher.completeExport(handle)).toThrow();
+ if (kind !== 'directory') expect(readFileSync(leaf, 'utf8')).toBe('original bytes');
+ else expect(readdirSync(leaf)).toEqual([]);
+ expect(readdirSync(root).filter(name => name.endsWith('.tmp'))).toEqual([]);
+ expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);
+ });
+
+ test.each(['../escape', '/absolute', 'a//b', 'a/./b', 'a/../b', 'a/', 'a\\b', 'a:b', 'trailing.', 'trailing ', 'NUL', 'COM1.txt', 'LPT²', 'bad\0name', '.gbrain-export-status'])('rejects invalid path %j and poisons completion', async path => {
+ const root = temporary();
+ const { publisher, handle } = await begin(root);
+ expect(() => publisher.publishExportFile(handle, path, Buffer.from('no'))).toThrow();
+ expect(() => publisher.completeExport(handle)).toThrow();
+ expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);
+ });
+
+ test('rejects a nonbuffer without permitting completion', async () => {
+ const { publisher, handle } = await begin(temporary());
+ expect(() => publisher.publishExportFile(handle, 'file', 'text' as unknown as Buffer)).toThrow();
+ expect(() => publisher.completeExport(handle)).toThrow();
+ });
+
+ test('incomplete publication arguments poison an identifiable handle', async () => {
+ const { publisher, handle } = await begin(temporary());
+ expect(() => Reflect.apply(publisher.publishExportFile, publisher, [handle, 'file'])).toThrow();
+ expect(() => publisher.completeExport(handle)).toThrow();
+ });
+
+ test('refuses filesystem case aliases when the filesystem aliases them', async () => {
+ const root = temporary();
+ writeFileSync(join(root, 'Taken'), 'existing');
+ if (!existsSync(join(root, 'taken'))) return;
+ const { publisher, handle } = await begin(root);
+ expect(() => publisher.publishExportFile(handle, 'taken', Buffer.from('replacement'))).toThrow();
+ expect(readFileSync(join(root, 'Taken'), 'utf8')).toBe('existing');
+ expect(() => publisher.completeExport(handle)).toThrow();
+ });
+
+ test('rejects foreign objects and keeps export handles separate from lock handles', async () => {
+ const { publisher, handle } = await begin(temporary());
+ const addon = publisher as NativeExportPublisher & { openLock(path: string): object; close(handle: object): void };
+ const lock = addon.openLock(join(temporary(), 'writer.lock'));
+ try {
+ expect(() => publisher.closeExport({})).toThrow();
+ expect(() => publisher.closeExport(lock)).toThrow();
+ expect(() => addon.close(handle)).toThrow();
+ publisher.completeExport(handle);
+ } finally { addon.close(lock); }
+ });
+
+ test.each(['destination', 'parent', 'leaf', 'marker'])('refuses a symlink/reparse %s without touching its target', async kind => {
+ const root = temporary();
+ const outside = temporary();
+ writeFileSync(join(outside, 'sentinel'), 'unchanged');
+ const publisher = await nativeExportPublisher();
+ if (kind === 'destination') {
+ symlinkSync(outside, join(root, 'alias'), process.platform === 'win32' ? 'junction' : 'dir');
+ expect(() => publisher.beginExport(join(root, 'alias', 'child'))).toThrow();
+ } else if (kind === 'marker') {
+ symlinkSync(outside, join(root, marker), process.platform === 'win32' ? 'junction' : 'dir');
+ expect(() => publisher.beginExport(root)).toThrow();
+ } else {
+ const { handle } = await begin(root);
+ symlinkSync(outside, join(root, 'alias'), process.platform === 'win32' ? 'junction' : 'dir');
+ expect(() => publisher.publishExportFile(handle, kind === 'parent' ? 'alias/sentinel' : 'alias', Buffer.from('no'))).toThrow();
+ expect(() => publisher.completeExport(handle)).toThrow();
+ }
+ expect(readdirSync(outside)).toEqual(['sentinel']);
+ expect(readFileSync(join(outside, 'sentinel'), 'utf8')).toBe('unchanged');
+ });
+
+ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('retains incomplete evidence on a real permission failure', async () => {
+ const root = temporary();
+ const { publisher, handle } = await begin(root);
+ mkdirSync(join(root, 'readonly'));
+ chmodSync(join(root, 'readonly'), 0o500);
+ try {
+ expect(() => publisher.publishExportFile(handle, 'readonly/file', Buffer.from('no'))).toThrow();
+ expect(() => publisher.completeExport(handle)).toThrow();
+ expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);
+ } finally { chmodSync(join(root, 'readonly'), 0o700); }
+ });
+
+ test('competing processes have exactly one marker owner and process exit retains evidence', async () => {
+ const root = temporary();
+ const fixture = resolve(import.meta.dir, 'fixtures/native-export-process.ts');
+ const children = Array.from({ length: 4 }, () => Bun.spawn([process.execPath, '--no-env-file', fixture, root], {
+ stdout: 'pipe', stderr: 'pipe', env: { PATH: process.env.PATH, SYSTEMROOT: process.env.SYSTEMROOT, TEMP: process.env.TEMP, TMP: process.env.TMP },
+ }));
+ const exits = await Promise.all(children.map(child => child.exited));
+ expect(exits.filter(code => code === 0)).toHaveLength(1);
+ expect(exits.filter(code => code === 2)).toHaveLength(3);
+ expect(readFileSync(join(root, marker), 'utf8')).toBe(incomplete);
+ });
+});
diff --git a/test/persistence-diagnostics.test.ts b/test/persistence-diagnostics.test.ts
index 240864fc1a..c80a041a9c 100644
--- a/test/persistence-diagnostics.test.ts
+++ b/test/persistence-diagnostics.test.ts
@@ -96,11 +96,11 @@ test('fresh and upgraded engines agree on the database-only pending index', asyn
} finally { abort.abort(); release.resolve(); await holding; await interrupted; }
}
await engine.setConfig('version', '164');
- expect(await runMigrations(engine)).toEqual({ applied: 1, current: 165 });
+ expect(await runMigrations(engine)).toEqual({ applied: 2, current: 166 });
const [upgraded] = await engine.executeRaw<{ indexdef: string }>(
"SELECT indexdef FROM pg_indexes WHERE indexname='persistence_requests_database_pending'");
expect(upgraded.indexdef).toBe(fresh.indexdef);
- expect(await engine.getConfig('version')).toBe('165');
+ expect(await engine.getConfig('version')).toBe('166');
}
}, 15000);
diff --git a/test/persistence-memory-mutations.test.ts b/test/persistence-memory-mutations.test.ts
index c3ea5aa9bc..46a44dff6e 100644
--- a/test/persistence-memory-mutations.test.ts
+++ b/test/persistence-memory-mutations.test.ts
@@ -230,6 +230,41 @@ describe('journaled memory publication, both engines', () => {
}
});
+ test('a prepared remember cannot publish across a stored embedding generation change', async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536,
+ env: { OPENAI_API_KEY: 'synthetic-only' } });
+ __setEmbedTransportForTests((async (opts: { values: string[] }) => ({ embeddings: opts.values.map(() => [1, ...new Array(1535).fill(0)]) })) as never);
+ try {
+ for (const engine of engines) {
+ await disposePersistenceConsumer(engine);
+ const slug = 'people/generation-fence-example';
+ const snapshot = await setupPage(engine, slug);
+ const prior = await engine.getConfig('embedding_model');
+ const authority = await submissionAuthority(context(engine), 'remember', sourceId, snapshot.sourceIncarnation, slug);
+ const p = { fact: 'Synthetic generation-fenced memory', provenance: 'test', entity_slug: slug, visibility: 'world', fence: true,
+ valid_from: new Date().toISOString(), valid_until: null };
+ const admitted = await admitWrite(engine, { principal: authority.principal, operation: 'remember', sourceId, sourceIncarnation: snapshot.sourceIncarnation,
+ slug, pageId: snapshot.page.id, callerIntent: p, intent: p, authority, requestId: randomUUID() });
+ const row = (await claimNextWrite(engine, randomUUID()))!;
+ expect(row.id).toBe(admitted.id);
+ const prepared = await prepareMemoryMutation(engine, row, context(engine).config);
+ try {
+ await engine.setConfig('embedding_model', prior === 'openai:text-embedding-3-large' ? 'openai:text-embedding-3-small' : 'openai:text-embedding-3-large');
+ expect((await publishMutation(engine, row, prepared)).state).not.toBe('committed');
+ expect((await engine.readPageSnapshot(slug, { sourceId }))!.revision).toBe(snapshot.revision);
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, p.fact])).toHaveLength(0);
+ } finally {
+ if (prior === null) await engine.executeRaw("DELETE FROM config WHERE key='embedding_model'");
+ else await engine.setConfig('embedding_model', prior);
+ await engine.executeRaw("UPDATE persistence_requests SET state='cancelled',error_code='cancelled' WHERE id=$1", [row.id]);
+ }
+ }
+ } finally {
+ __setEmbedTransportForTests(null);
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });
+ }
+ });
+
test('forget commits offline, withdraws before sealing reads and replays after fact removal', async () => {
for (const engine of engines) {
const slug = 'people/withdraw-example';
diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.ts
index 0ed5355c86..b6814c3a25 100644
--- a/test/persistence-sync-failures.serial.test.ts
+++ b/test/persistence-sync-failures.serial.test.ts
@@ -26,6 +26,8 @@ import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-f
import { prepareRemoteJob, withSubmissionAuthority } from '../src/core/minions/submission-authority.ts';
import type { OperationContext } from '../src/core/ops/contract.ts';
import { testBackends } from './helpers/test-backends.ts';
+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
+import { renderFactsTable, parseFactsFence } from '../src/core/facts-fence.ts';
const backends = testBackends();
const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-failures-'));
@@ -51,6 +53,33 @@ beforeAll(async () => {
}
if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
}, 120_000);
+
+test('withdrawal-conflicted sync resumes only through explicit guarded rediscovery and cannot restore the fact', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const body = renderFactsTable([{ rowNum: 1, claim: 'synthetic sync withdrawal', visibility: 'world', kind: 'fact', confidence: 1,
+ notability: 'medium', active: true }]);
+ const f = await fixture(engine, { 'a.md': 'First stable observation.\n', 'z.md': body });
+ const options = { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true };
+ expect((await performManagedSync(engine, options)).status).toBe('first_sync');
+ const fact = await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () =>
+ tx.insertFact({ fact: 'synthetic sync withdrawal', source: 'synthetic', visibility: 'world' }, { source_id: f.id })));
+ writeFileSync(join(f.root, 'a.md'), 'First updated observation.\n');
+ writeFileSync(join(f.root, 'z.md'), `Preserve this new prose.\n${body}`); commit(f.root);
+ expect((await performManagedSync(engine, options, { maxPages: 1, maxMs: 1000 })).status).toBe('partial');
+ await disposePersistenceConsumer(engine);
+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => recordFactWithdrawal(tx, fact.id, f.id)));
+ await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'revision_conflict' });
+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([expect.objectContaining({ phase: 'freeze', path: 'z.md', code: 'revision_conflict' })]);
+ await expect(performManagedSync(engine, options)).rejects.toMatchObject({ code: 'revision_conflict' });
+ const repaired = await performManagedSync(engine, { ...options, retryFailed: true });
+ expect(repaired.status).toBe('synced');
+ const current = (await engine.readPageSnapshot('z', { sourceId: f.id }))!;
+ expect(current.page.compiled_truth).toContain('Preserve this new prose.');
+ expect(parseFactsFence(current.page.compiled_truth).facts[0].forgotten).toBe(true);
+ expect(parseFactsFence(readFileSync(join(f.root, 'z.md'), 'utf8')).facts[0].forgotten).toBe(true);
+ expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(0);
+ }
+}), 120_000);
afterAll(async () => {
for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
await closePostgres?.(); rmSync(home, { recursive: true, force: true });
diff --git a/test/safety-wave-coverage-export-ledger.test.ts b/test/safety-wave-coverage-export-ledger.test.ts
new file mode 100644
index 0000000000..12ed59f175
--- /dev/null
+++ b/test/safety-wave-coverage-export-ledger.test.ts
@@ -0,0 +1,41 @@
+import { expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { readExportWithdrawals } from '../src/core/export-snapshot.ts';
+import { EXPORT_PAYLOAD_LIMIT } from '../src/core/export-stage.ts';
+
+test('export refuses an over-limit withdrawal ledger before fetching its payload', async () => {
+ const calls: Array<{ sql: string; params: unknown[] }> = [];
+ const engine = { executeRaw: async (sql: string, params: unknown[]) => {
+ calls.push({ sql, params });
+ return [{ bytes: EXPORT_PAYLOAD_LIMIT + 1 }];
+ } } as unknown as BrainEngine;
+ await expect(readExportWithdrawals(engine, 'synthetic-source')).rejects.toThrow('withdrawal ledger capacity');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].sql).toContain('sum(octet_length(');
+ expect(calls[0].params).toEqual(['synthetic-source']);
+});
+
+test('export accepts the exact ledger limit and keeps both reads source scoped', async () => {
+ const params: unknown[][] = [];
+ const ledger = [{ visibility: 'world' as const, fact_hash: 'synthetic-fingerprint', withdrawn_at: '2026-01-01T00:00:00Z' }];
+ const engine = { executeRaw: async (_sql: string, bound: unknown[]) => {
+ params.push(bound);
+ return params.length === 1 ? [{ bytes: String(EXPORT_PAYLOAD_LIMIT) }] : ledger;
+ } } as unknown as BrainEngine;
+ expect(await readExportWithdrawals(engine, 'synthetic-source')).toEqual(ledger);
+ expect(params).toEqual([['synthetic-source'], ['synthetic-source']]);
+});
+
+test('export ledger size-read failure never proceeds to the unbounded payload read', async () => {
+ let calls = 0;
+ const engine = { executeRaw: async () => { calls++; throw new Error('synthetic read failure'); } } as unknown as BrainEngine;
+ await expect(readExportWithdrawals(engine, 'synthetic-source')).rejects.toThrow('synthetic read failure');
+ expect(calls).toBe(1);
+});
+
+test('an empty withdrawal ledger remains an explicit empty snapshot', async () => {
+ let calls = 0;
+ const engine = { executeRaw: async () => ++calls === 1 ? [{ bytes: 2 }] : [] } as unknown as BrainEngine;
+ expect(await readExportWithdrawals(engine, 'synthetic-source')).toEqual([]);
+ expect(calls).toBe(2);
+});
diff --git a/test/safety-wave-coverage-invocation-inheritance.test.ts b/test/safety-wave-coverage-invocation-inheritance.test.ts
new file mode 100644
index 0000000000..17254cba89
--- /dev/null
+++ b/test/safety-wave-coverage-invocation-inheritance.test.ts
@@ -0,0 +1,76 @@
+import { expect, test } from 'bun:test';
+import { invokeAI, isAIInvocationPolicyError, withAIInvocationGuard, type AIInvocationGuard, type AIInvocationUsage } from '../src/core/ai/invocation-guard.ts';
+
+const call = { operation: 'synthetic.audit', kind: 'embedding' as const, model: 'synthetic:model', maxInputTokens: 8 };
+const usage = { inputTokens: 4, outputTokens: 0 };
+
+function recordingGuard(name: string, events: Array<[string, AIInvocationUsage | null]>): AIInvocationGuard {
+ return async () => {
+ events.push([`${name}:admit`, null]);
+ return { settle: async measured => { events.push([`${name}:settle`, measured]); } };
+ };
+}
+
+test('inherited fact authorization admits and settles both budgets for one provider attempt', async () => {
+ const events: Array<[string, AIInvocationUsage | null]> = [];
+ let dispatched = 0;
+ const result = await withAIInvocationGuard(recordingGuard('migration', events), () =>
+ withAIInvocationGuard(recordingGuard('facts', events), () =>
+ invokeAI(call, async () => { dispatched++; return 'synthetic-result'; }, () => usage), { inherit: true }));
+ expect(result).toBe('synthetic-result');
+ expect(dispatched).toBe(1);
+ expect(events).toEqual([['migration:admit', null], ['facts:admit', null], ['migration:settle', usage], ['facts:settle', usage]]);
+});
+
+test('inner authorization refusal retains the outer debit without dispatching', async () => {
+ const events: Array<[string, AIInvocationUsage | null]> = [];
+ const refused = new Error('synthetic inner cap exhausted');
+ let dispatched = false;
+ await expect(withAIInvocationGuard(recordingGuard('migration', events), () =>
+ withAIInvocationGuard(async () => { throw refused; }, () =>
+ invokeAI(call, async () => { dispatched = true; }, () => usage), { inherit: true }))).rejects.toBe(refused);
+ expect(dispatched).toBe(false);
+ expect(isAIInvocationPolicyError(refused)).toBe(true);
+ expect(events).toEqual([['migration:admit', null], ['migration:settle', null]]);
+});
+
+test('outer authorization refusal prevents inner admission and provider dispatch', async () => {
+ const events: Array<[string, AIInvocationUsage | null]> = [];
+ const refused = new Error('synthetic migration cap exhausted');
+ let dispatched = false;
+ await expect(withAIInvocationGuard(async () => { throw refused; }, () =>
+ withAIInvocationGuard(recordingGuard('facts', events), () =>
+ invokeAI(call, async () => { dispatched = true; }, () => usage), { inherit: true }))).rejects.toBe(refused);
+ expect(dispatched).toBe(false);
+ expect(events).toEqual([]);
+ expect(isAIInvocationPolicyError(refused)).toBe(true);
+});
+
+test('uncertain provider failure settles both inherited permits without fabricated usage', async () => {
+ const events: Array<[string, AIInvocationUsage | null]> = [];
+ const timeout = new Error('synthetic transport timeout');
+ await expect(withAIInvocationGuard(recordingGuard('migration', events), () =>
+ withAIInvocationGuard(recordingGuard('facts', events), () =>
+ invokeAI(call, async () => { throw timeout; }, () => usage), { inherit: true }))).rejects.toBe(timeout);
+ expect(events).toEqual([['migration:admit', null], ['facts:admit', null], ['migration:settle', null], ['facts:settle', null]]);
+ expect(isAIInvocationPolicyError(timeout)).toBe(false);
+});
+
+test('non-inheriting nested guards preserve the preexisting replacement contract', async () => {
+ const events: Array<[string, AIInvocationUsage | null]> = [];
+ await withAIInvocationGuard(recordingGuard('outer', events), () =>
+ withAIInvocationGuard(recordingGuard('inner', events), () => invokeAI(call, async () => 'result', () => usage)));
+ expect(events).toEqual([['inner:admit', null], ['inner:settle', usage]]);
+});
+
+test('inherit without a parent stays isolated from concurrent provider work', async () => {
+ const events: Array<[string, AIInvocationUsage | null]> = [];
+ await Promise.all([
+ withAIInvocationGuard(recordingGuard('owned', events), async () => {
+ await Promise.resolve();
+ return invokeAI(call, async () => 'owned-result', () => usage);
+ }, { inherit: true }),
+ invokeAI(call, async () => 'unowned-result', () => usage),
+ ]);
+ expect(events).toEqual([['owned:admit', null], ['owned:settle', usage]]);
+});
diff --git a/test/scripts/ci-local-rendering.test.ts b/test/scripts/ci-local-rendering.test.ts
index 472c2e9d87..e322eff907 100644
--- a/test/scripts/ci-local-rendering.test.ts
+++ b/test/scripts/ci-local-rendering.test.ts
@@ -24,7 +24,7 @@ describe('ci-local command rendering', () => {
const cases = [
{ phaseExit: 0, missingTool: '' },
{ phaseExit: 7, missingTool: '' },
- ...['git', 'python3', 'ps', 'psql', 'jq'].map(missingTool => ({ phaseExit: 0, missingTool })),
+ ...['git', 'python3', 'ps', 'psql', 'cc', 'jq'].map(missingTool => ({ phaseExit: 0, missingTool })),
];
for (const { phaseExit, missingTool } of cases) {
test(`preserves stderr and exit ${phaseExit}; missing prerequisite ${missingTool || 'none'}`, () => {
@@ -36,7 +36,7 @@ describe('ci-local command rendering', () => {
mkdirSync(bin);
// Execute the actual runner template, with installation/configuration
// commands stubbed so this regression needs neither Docker nor root.
- for (const name of ['bun', 'git', 'python3', 'ps', 'psql', 'jq']) {
+ for (const name of ['bun', 'git', 'python3', 'ps', 'psql', 'cc', 'jq']) {
writeFileSync(join(bin, name), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
}
writeFileSync(join(bin, 'apt-get'), '#!/bin/sh\nprintf "%s\\n" "$*" >> "$INSTALL_LOG"\n', { mode: 0o755 });
@@ -71,7 +71,7 @@ describe('ci-local command rendering', () => {
expect(result.stdout.includes('phase completed')).toBe(phaseExit === 0);
expect(existsSync(join(home, '__RUN_PHASES__1'))).toBe(false);
if (missingTool) {
- expect(readFileSync(installLog, 'utf8')).toBe('update -qq\ninstall -y -qq git ca-certificates python3 procps postgresql-client jq\n');
+ expect(readFileSync(installLog, 'utf8')).toBe('update -qq\ninstall -y -qq git ca-certificates python3 procps postgresql-client jq build-essential\n');
} else {
expect(existsSync(installLog)).toBe(false);
}
diff --git a/test/scripts/data-safety-native-workflow.test.ts b/test/scripts/data-safety-native-workflow.test.ts
index 8774e13d31..6b00aaf917 100644
--- a/test/scripts/data-safety-native-workflow.test.ts
+++ b/test/scripts/data-safety-native-workflow.test.ts
@@ -27,6 +27,8 @@ const suites = [
'test/persistence-git-publication.test.ts',
'test/persistence-sync-origin-native.serial.test.ts',
'test/backup-portability-native.serial.test.ts',
+ 'test/export-publication-native.serial.test.ts',
+ 'test/native-export-publication.test.ts',
];
describe('data-safety native CI coverage', () => {
diff --git a/test/search/query-embed-deadline.test.ts b/test/search/query-embed-deadline.test.ts
index dd8093f7ef..17525e5728 100644
--- a/test/search/query-embed-deadline.test.ts
+++ b/test/search/query-embed-deadline.test.ts
@@ -12,7 +12,7 @@
* insufficient against a wedged provider), and that a shared/elapsed deadline
* makes a second embed fail FAST (worst case ~one timeout, not two).
*/
-import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { describe, test, expect, beforeEach, afterEach, spyOn } from 'bun:test';
import {
configureGateway,
resetGateway,
@@ -99,4 +99,28 @@ describe('embedQueryBounded — query-embed deadline', () => {
expect(out).toBeInstanceOf(Float32Array);
expect(out.length).toBe(1024);
});
+
+ test('retains the local timeout reason when the gateway wraps transport cancellation', async () => {
+ const controller = new AbortController();
+ const reason = new DOMException('synthetic query deadline', 'TimeoutError');
+ const timeout = spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal);
+ __setEmbedTransportForTests(async () => {
+ controller.abort(reason);
+ throw reason;
+ });
+ try {
+ await expect(embedQueryBounded('fixture', undefined, {
+ signal: controller.signal, deadlineAt: Date.now() + 6_000,
+ })).rejects.toBe(reason);
+ } finally {
+ timeout.mockRestore();
+ }
+ });
+
+ test('does not relabel a provider failure before the local deadline', async () => {
+ __setEmbedTransportForTests(async () => { throw new Error('synthetic provider failure'); });
+ await expect(embedQueryBounded('fixture', undefined, makeQueryEmbedDeadline())).rejects.toMatchObject({
+ name: 'AITransientError', message: expect.stringContaining('synthetic provider failure'),
+ });
+ });
});
diff --git a/test/storage-export.test.ts b/test/storage-export.test.ts
index 064e177aef..51ce4d0ef5 100644
--- a/test/storage-export.test.ts
+++ b/test/storage-export.test.ts
@@ -14,7 +14,7 @@
*/
import { describe, test, expect, beforeEach, afterEach, beforeAll, afterAll } from 'bun:test';
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { mkdtempSync, realpathSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -42,7 +42,7 @@ afterAll(async () => {
});
beforeEach(async () => {
- tmp = mkdtempSync(join(tmpdir(), 'gbrain-export-test-'));
+ tmp = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-export-test-')));
outDir = join(tmp, 'out');
exitCode = null;
stderr = [];
@@ -169,30 +169,20 @@ describe('export sidecar reads are scoped to the page owning source', () => {
await engine.putRawData(SLUG, `feed-${sourceId}`, { owner: sourceId }, { sourceId });
}
- // One slug means one output path, so the two pages overwrite each other
- // and only the last one written survives on disk. Pin the export order
- // (listPages defaults to updated_desc) so `other` is the survivor and the
- // assertions below read a NON-default page — the only page whose sidecars
- // an unscoped, `'default'`-defaulting read would get wrong.
- await engine.executeRaw(
- `UPDATE pages SET updated_at = updated_at + interval '1 hour' WHERE source_id = 'default'`,
- );
});
test("a non-default page exports its own tags, not the default source's", async () => {
- await tryRunExport(['--dir', outDir]);
+ await tryRunExport(['--dir', outDir, '--source', 'other']);
expect(exitCode).toBeNull();
const md = readFileSync(join(outDir, SLUG + '.md'), 'utf-8');
- // Guards the ordering assumption itself: if `default` ever wins the race
- // the tag assertions stop discriminating, so fail loudly here instead.
expect(md).toContain('other title');
expect(md).toContain('tag-other');
expect(md).not.toContain('tag-default');
});
test('raw-data sidecars carry only the owning source rows', async () => {
- await tryRunExport(['--dir', outDir]);
+ await tryRunExport(['--dir', outDir, '--source', 'other']);
expect(exitCode).toBeNull();
// Unscoped, getRawData applies no source predicate at all: both sources'
diff --git a/test/withdrawal-bounded-safety.test.ts b/test/withdrawal-bounded-safety.test.ts
new file mode 100644
index 0000000000..39f1528178
--- /dev/null
+++ b/test/withdrawal-bounded-safety.test.ts
@@ -0,0 +1,370 @@
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
+import { withdrawalFenceBlocks } from '../src/core/facts/withdrawal-overlay.ts';
+import { renderFactsTable, parseFactsFence, FACTS_FENCE_BEGIN } from '../src/core/facts-fence.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, completeWrite } from '../src/core/persistence/journal.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { retryEmbeddingEffect } from '../src/core/persistence/effect-retry.ts';
+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import type { PreparedContentImport } from '../src/core/persistence/prepared-import.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { makeGitFixture } from './helpers/git-fixture.ts';
+
+const fence = (claim: string, visibility: 'private' | 'world' = 'world') => renderFactsTable([
+ { rowNum: 1, claim, visibility, kind: 'fact', confidence: 1, notability: 'medium', active: true },
+]);
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();
+
+test('linear marker scanning preserves inline documentation and complete legacy fences', () => {
+ const complete = fence('real claim');
+ const blocks = withdrawalFenceBlocks(`Use \`${FACTS_FENCE_BEGIN}\` here.\n${complete}\n${complete}`);
+ expect(blocks).toHaveLength(2);
+ expect(blocks.map(block => block.parsed.facts[0].claim)).toEqual(['real claim', 'real claim']);
+ expect(withdrawalFenceBlocks(`\`${complete}\``)[0].parsed.facts[0].claim).toBe('real claim');
+});
+
+for (const backend of testBackends()) describe(`bounded withdrawal ${backend}`, () => {
+ let engine: BrainEngine, close: () => Promise<void>;
+ const roots: string[] = [];
+ const hostId = localHostId();
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const fixture = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = fixture.engine; close = fixture.close;
+ } else {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect();
+ }
+ await registerLocalWriter(engine, 'cli');
+ await engine.setConfig('embedding_disabled', 'true');
+ }, 120_000);
+ afterAll(async () => { await close(); for (const root of roots) rmSync(root, { recursive: true, force: true }); });
+
+ async function fixture() {
+ const sourceId = `withdrawal-${randomUUID()}`, root = mkdtempSync(join(tmpdir(), 'gbrain-withdrawal-bounded-'));
+ roots.push(root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const binding = await claimWorktree(engine, sourceId, root, hostId);
+ for (const [slug, body] of [['affected', fence('uses A | B')], ['unrelated', fence('a different claim')], ['private', fence('uses A | B', 'private')]]) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body }, { sourceId });
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_text: body, chunk_source: 'compiled_truth' }], { sourceId });
+ await engine.setPageEmbeddingSignature(slug, { sourceId, signature: 'synthetic:retained:1536' });
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ }
+ await rebuildPendingPageProjections(engine, 100);
+ const repository = await makeGitFixture(root);
+ repository.commitAll('Synthetic baseline');
+ mkdirSync(join(root, '.git', 'hooks'), { recursive: true });
+ writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '# gbrain brain-durability post-commit hook (v0.42.44+)\n');
+ const fact = await engine.insertFact({ fact: ' USES A | B ', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });
+ const snapshot = (await engine.readPageSnapshot('affected', { sourceId }))!;
+ const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext, 'forget', sourceId, binding.source_incarnation, 'affected');
+ const request = await admitWrite(engine, { principal: authority.principal, authority, operation: 'forget', sourceId,
+ sourceIncarnation: binding.source_incarnation, slug: 'affected', pageId: snapshot.page.id, requestId: randomUUID(),
+ callerIntent: { id: fact.id }, intent: { id: fact.id }, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });
+ const withdraw = () => engine.transaction(async tx => {
+ const result = await recordFactWithdrawal(tx, fact.id, sourceId, false, { requestId: request.id });
+ await completeWrite(tx, request, 'committed', { status: 'forgotten' });
+ return result;
+ });
+ return { sourceId, root, fact, request, withdraw };
+ }
+ const state = (sourceId: string) => engine.executeRaw(`SELECT row_to_json(p) AS page,
+ (SELECT jsonb_agg(to_jsonb(c) ORDER BY c.id) FROM content_chunks c WHERE c.page_id=p.id) AS chunks
+ FROM pages p WHERE source_id=$1 AND slug IN ('unrelated','private') ORDER BY slug`, [sourceId]);
+ async function drain(requestId: string) {
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE request_id<>$1::uuid", [requestId]);
+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid', [requestId]);
+ await runPersistenceEffects(engine, { engine: backend, embedding_disabled: true }, { hostId, limit: 20 });
+ }
+
+ test('exact bytes, chunks, revisions, signatures and unrelated Git staging survive targeted effects', async () => {
+ const f = await fixture(), before = await state(f.sourceId);
+ const original = readFileSync(join(f.root, 'unrelated.md'));
+ writeFileSync(join(f.root, 'local-edit.txt'), 'Unrelated staged edit'); git(f.root, 'add', 'local-edit.txt');
+ const result = await f.withdraw();
+ expect(result.pages.map(p => p.slug)).toEqual(['affected']);
+ expect(await state(f.sourceId)).toEqual(before);
+ const effects = await engine.executeRaw<{ data: { version: number; targets: Array<{ slug: string }>; source_scan?: boolean } }>('SELECT data FROM persistence_effects WHERE request_id=$1::uuid', [f.request.id]);
+ expect(effects).toHaveLength(3);
+ for (const effect of effects) {
+ expect(effect.data.version).toBe(2); expect(effect.data.targets.map(t => t.slug)).toEqual(['affected']); expect(effect.data.source_scan).toBeUndefined();
+ }
+ await rebuildPendingPageProjections(engine, 100);
+ await drain(f.request.id);
+ expect(await state(f.sourceId)).toEqual(before);
+ expect(readFileSync(join(f.root, 'unrelated.md'))).toEqual(original);
+ expect(parseFactsFence(readFileSync(join(f.root, 'affected.md'), 'utf8')).facts[0].forgotten).toBe(true);
+ expect(git(f.root, 'show', '--pretty=format:', '--name-only', 'HEAD')).toBe('affected.md');
+ expect(git(f.root, 'diff', '--cached', '--name-only')).toBe('local-edit.txt');
+ const head = git(f.root, 'rev-parse', 'HEAD');
+ expect(await recordFactWithdrawal(engine, f.fact.id, f.sourceId)).toEqual({ withdrawn: false, pages: [] });
+ await drain(f.request.id); expect(git(f.root, 'rev-parse', 'HEAD')).toBe(head);
+ });
+
+ test('discovery time exhaustion refuses before any withdrawal mutation', async () => {
+ const f = await fixture(), before = await state(f.sourceId);
+ let now = 0;
+ const clock = spyOn(performance, 'now').mockImplementation(() => now += 11_000);
+ try { await expect(f.withdraw()).rejects.toMatchObject({ code: 'withdrawal_capacity' }); }
+ finally { clock.mockRestore(); }
+ expect(await state(f.sourceId)).toEqual(before);
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toEqual([]);
+ expect(await engine.executeRaw('SELECT expired_at FROM facts WHERE id=$1', [f.fact.id])).toEqual([{ expired_at: null }]);
+ expect(await engine.executeRaw('SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid', [f.request.id])).toEqual([]);
+ });
+
+ test('oversized persisted target manifests retain intent without file publication', async () => {
+ const f = await fixture(), original = readFileSync(join(f.root, 'affected.md'));
+ await f.withdraw();
+ await engine.executeRaw(`UPDATE persistence_effects SET data=jsonb_set(data,'{targets,0,slug}',to_jsonb($2::text))
+ WHERE request_id=$1::uuid`, [f.request.id, 'x'.repeat(1024 * 1024)]);
+ await drain(f.request.id);
+ expect(readFileSync(join(f.root, 'affected.md'))).toEqual(original);
+ expect(await engine.executeRaw("SELECT state,error_code FROM persistence_effects WHERE request_id=$1::uuid AND kind='withdrawal-mirror'", [f.request.id]))
+ .toEqual([{ state: 'queued', error_code: 'withdrawal_provenance' }]);
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toHaveLength(1);
+ });
+
+ test('legacy source scan continues safely and mirror crash recovers without touching unrelated pages', async () => {
+ const f = await fixture();
+ await engine.putPage('z-affected', { type: 'note', title: 'Later affected page', compiled_truth: fence('uses A | B') }, { sourceId: f.sourceId });
+ const later = (await engine.readPageSnapshot('z-affected', { sourceId: f.sourceId }))!;
+ writeFileSync(join(f.root, 'z-affected.md'), serializePageToMarkdown(later.page, later.tags));
+ git(f.root, 'add', 'z-affected.md'); git(f.root, 'commit', '-qm', 'Synthetic second target');
+ await f.withdraw();
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE request_id<>$1::uuid", [f.request.id]);
+ await runPersistenceEffects(engine, { engine: backend, embedding_disabled: true }, { hostId, limit: 1 });
+ const firstPublished = readFileSync(join(f.root, 'affected.md'));
+ await engine.executeRaw(`UPDATE persistence_effects SET data='{"source_scan":true}'::jsonb WHERE request_id=$1::uuid`, [f.request.id]);
+ await engine.executeRaw(`UPDATE persistence_effects SET data='{"after_slug":"affected"}'::jsonb WHERE request_id=$1::uuid AND kind='withdrawal-mirror'`, [f.request.id]);
+ const before = await state(f.sourceId), original = readFileSync(join(f.root, 'unrelated.md'));
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE request_id<>$1::uuid", [f.request.id]);
+ let crashed = false;
+ await runPersistenceEffects(engine, { engine: backend, embedding_disabled: true }, { hostId, limit: 1, boundary: async name => {
+ if (name === 'after_mirror_file') { crashed = true; throw new Error('synthetic interruption'); }
+ } });
+ expect(crashed).toBe(true);
+ expect((await engine.executeRaw<{ slug: string }>("SELECT recovery->>'slug' AS slug FROM persistence_effects WHERE request_id=$1::uuid AND kind='withdrawal-mirror'", [f.request.id]))[0].slug).toBe('z-affected');
+ await rebuildPendingPageProjections(engine, 100); await drain(f.request.id); await drain(f.request.id);
+ expect(await state(f.sourceId)).toEqual(before); expect(readFileSync(join(f.root, 'unrelated.md'))).toEqual(original);
+ expect(parseFactsFence(readFileSync(join(f.root, 'affected.md'), 'utf8')).facts[0].forgotten).toBe(true);
+ expect(readFileSync(join(f.root, 'affected.md'))).toEqual(firstPublished);
+ expect(parseFactsFence(readFileSync(join(f.root, 'z-affected.md'), 'utf8')).facts[0].forgotten).toBe(true);
+ expect(await engine.executeRaw('SELECT id FROM persistence_effects WHERE request_id=$1::uuid AND recovery IS NOT NULL', [f.request.id])).toEqual([]);
+ expect(git(f.root, 'show', '--pretty=format:', '--name-only', 'HEAD')).toBe('z-affected.md');
+ });
+
+ test('malformed matching rows refuse before ledger, expiry, revision or chunk mutation', async () => {
+ const f = await fixture();
+ await engine.putPage('malformed', { type: 'note', title: 'Malformed', compiled_truth: fence('uses A | B').replace('| fact |', '| invalid |') }, { sourceId: f.sourceId });
+ const before = await engine.executeRaw('SELECT row_to_json(p) AS page FROM pages p WHERE source_id=$1 ORDER BY slug', [f.sourceId]);
+ await expect(f.withdraw()).rejects.toMatchObject({ code: 'withdrawal_provenance' });
+ expect(await engine.executeRaw('SELECT row_to_json(p) AS page FROM pages p WHERE source_id=$1 ORDER BY slug', [f.sourceId])).toEqual(before);
+ expect(await engine.executeRaw('SELECT fact_hash FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toEqual([]);
+ expect((await engine.executeRaw<{ expired_at: unknown }>('SELECT expired_at FROM facts WHERE id=$1', [f.fact.id]))[0].expired_at).toBeNull();
+ await engine.transaction(tx => completeWrite(tx, f.request, 'cancelled', {}));
+ });
+
+ test('both prepared writer orderings retain committed withdrawal intent including a new page', async () => {
+ for (const first of ['writer', 'withdrawal']) {
+ const sourceId = `ordering-${randomUUID()}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const fact = await engine.insertFact({ fact: 'ordering sentinel', visibility: 'world', source: 'synthetic' }, { source_id: sourceId });
+ let ready: PreparedContentImport | undefined;
+ await importFromContent(engine, 'new-page', `---\ntitle: Ordering\ntype: note\n---\n${fence('ordering sentinel')}`, {
+ sourceId, noEmbed: true, prepare: async prepared => { ready = prepared; return prepared.result; },
+ });
+ expect(ready).toBeDefined();
+ if (first === 'writer') {
+ await engine.transaction(tx => ready!.apply(tx));
+ expect((await recordFactWithdrawal(engine, fact.id, sourceId)).pages.map(p => p.slug)).toEqual(['new-page']);
+ expect(parseFactsFence((await engine.readPageSnapshot('new-page', { sourceId }))!.page.compiled_truth).facts[0].forgotten).toBe(true);
+ } else {
+ expect((await recordFactWithdrawal(engine, fact.id, sourceId)).pages).toEqual([]);
+ await expect(engine.transaction(tx => ready!.apply(tx))).rejects.toMatchObject({ code: 'revision_conflict' });
+ await expect(engine.transaction(tx => ready!.validate(tx))).rejects.toMatchObject({ code: 'revision_conflict' });
+ expect(await engine.getPage('new-page', { sourceId })).toBeNull();
+ }
+ }
+ });
+
+ test('an over-capacity target set refuses atomically instead of partially withdrawing', async () => {
+ const sourceId = `capacity-${randomUUID()}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter)
+ SELECT $1,'page-'||n,'note','Synthetic capacity',$2,'','{}'::jsonb FROM generate_series(1,257) n`, [sourceId, fence('capacity sentinel')]);
+ const fact = await engine.insertFact({ fact: 'capacity sentinel', source: 'synthetic', visibility: 'world' }, { source_id: sourceId });
+ const before = await engine.executeRaw('SELECT slug,knowledge_revision FROM pages WHERE source_id=$1 ORDER BY slug', [sourceId]);
+ await expect(recordFactWithdrawal(engine, fact.id, sourceId)).rejects.toMatchObject({ code: 'withdrawal_capacity' });
+ expect(await engine.executeRaw('SELECT slug,knowledge_revision FROM pages WHERE source_id=$1 ORDER BY slug', [sourceId])).toEqual(before);
+ expect(await engine.executeRaw('SELECT fact_hash FROM fact_withdrawals WHERE source_id=$1', [sourceId])).toEqual([]);
+ expect((await engine.executeRaw<{ expired_at: unknown }>('SELECT expired_at FROM facts WHERE id=$1', [fact.id]))[0].expired_at).toBeNull();
+ });
+
+ test('DB-only duplicates expire once without invalidating unrelated content', async () => {
+ const f = await fixture(), before = await state(f.sourceId);
+ const first = await engine.insertFact({ fact: 'subjectless distinct claim', source: 'synthetic', visibility: 'world' }, { source_id: f.sourceId });
+ const duplicate = await engine.insertFact({ fact: ' SUBJECTLESS DISTINCT CLAIM ', source: 'synthetic', visibility: 'world' }, { source_id: f.sourceId });
+ expect(await recordFactWithdrawal(engine, first.id, f.sourceId)).toEqual({ withdrawn: true, pages: [] });
+ expect(await recordFactWithdrawal(engine, duplicate.id, f.sourceId)).toEqual({ withdrawn: false, pages: [] });
+ expect(await state(f.sourceId)).toEqual(before);
+ expect(await engine.executeRaw('SELECT id FROM facts WHERE id=ANY($1::int[]) AND expired_at IS NULL', [[first.id, duplicate.id]])).toEqual([]);
+ await engine.transaction(tx => completeWrite(tx, f.request, 'cancelled', {}));
+ });
+
+ test('stale-chunk-only evidence invalidates its page and removes a demonstrated retrieval leak', async () => {
+ const f = await fixture(), claim = 'stalechunksentinel';
+ await engine.putPage('stale-only', { type: 'note', title: 'Current observation', compiled_truth: 'The current canonical body is safe.' }, { sourceId: f.sourceId });
+ await rebuildPendingPageProjections(engine, 100);
+ const fact = await engine.insertFact({ fact: claim, source: 'synthetic', visibility: 'world' }, { source_id: f.sourceId });
+ await engine.executeRaw(`UPDATE content_chunks SET chunk_text=$2,search_vector=to_tsvector('english',$2)
+ WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug='stale-only')`, [f.sourceId, claim]);
+ expect(await engine.executeRaw('SELECT entity_slug,source_markdown_slug FROM facts WHERE id=$1', [fact.id]))
+ .toEqual([{ entity_slug: null, source_markdown_slug: null }]);
+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND position($2 IN compiled_truth||timeline)>0', [f.sourceId, claim])).toEqual([]);
+ expect((await engine.searchKeyword(claim, { sourceId: f.sourceId })).map(page => page.slug)).toEqual(['stale-only']);
+ const before = await state(f.sourceId), targetBefore = (await engine.readPageSnapshot('stale-only', { sourceId: f.sourceId }))!;
+ const result = await recordFactWithdrawal(engine, fact.id, f.sourceId);
+ expect(result.pages.map(page => page.slug)).toEqual(['stale-only']);
+ expect((await engine.readPageSnapshot('stale-only', { sourceId: f.sourceId }))!.revision).not.toBe(targetBefore.revision);
+ expect(await engine.executeRaw('SELECT id FROM content_chunks WHERE page_id=$1', [targetBefore.page.id])).toEqual([]);
+ expect(await engine.searchKeyword(claim, { sourceId: f.sourceId })).toEqual([]);
+ expect(await state(f.sourceId)).toEqual(before);
+ await rebuildPendingPageProjections(engine, 100);
+ expect(await engine.searchKeyword(claim, { sourceId: f.sourceId })).toEqual([]);
+ expect((await engine.readPageSnapshot('stale-only', { sourceId: f.sourceId }))!.page.compiled_truth).toBe(targetBefore.page.compiled_truth);
+ expect(await state(f.sourceId)).toEqual(before);
+ await engine.transaction(tx => completeWrite(tx, f.request, 'cancelled', {}));
+ });
+
+ for (const provenance of ['source_markdown_slug', 'entity_slug'] as const) test(`${provenance}-only evidence invalidates its exact page while unrelated state remains unchanged`, async () => {
+ const f = await fixture(), claim = `provenance sentinel ${provenance}`;
+ await engine.putPage('provenance-only', { type: 'note', title: 'Current evidence', compiled_truth: 'A safe canonical observation without the historical claim.' }, { sourceId: f.sourceId });
+ await rebuildPendingPageProjections(engine, 100);
+ await engine.setPageEmbeddingSignature('provenance-only', { sourceId: f.sourceId, signature: 'synthetic:retained:1536' });
+ const fact = await engine.insertFact({ fact: claim, source: 'synthetic', visibility: 'world',
+ entity_slug: provenance === 'entity_slug' ? 'provenance-only' : 'unrelated' }, { source_id: f.sourceId });
+ if (provenance === 'source_markdown_slug') await engine.executeRaw('UPDATE facts SET source_markdown_slug=$2 WHERE id=$1', [fact.id, 'provenance-only']);
+ expect(await engine.executeRaw('SELECT entity_slug,source_markdown_slug FROM facts WHERE id=$1', [fact.id])).toEqual([
+ provenance === 'entity_slug' ? { entity_slug: 'provenance-only', source_markdown_slug: null }
+ : { entity_slug: 'unrelated', source_markdown_slug: 'provenance-only' },
+ ]);
+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND position($2 IN compiled_truth||timeline)>0', [f.sourceId, claim])).toEqual([]);
+ expect(await engine.executeRaw(`SELECT c.id FROM content_chunks c JOIN pages p ON p.id=c.page_id
+ WHERE p.source_id=$1 AND position($2 IN c.chunk_text)>0`, [f.sourceId, claim])).toEqual([]);
+ const before = await state(f.sourceId), targetBefore = (await engine.readPageSnapshot('provenance-only', { sourceId: f.sourceId }))!;
+ const filesBefore = ['unrelated', 'private'].map(slug => readFileSync(join(f.root, `${slug}.md`)));
+ expect((await recordFactWithdrawal(engine, fact.id, f.sourceId)).pages.map(page => page.slug)).toEqual(['provenance-only']);
+ const targetAfter = (await engine.readPageSnapshot('provenance-only', { sourceId: f.sourceId }))!;
+ expect(targetAfter.revision).not.toBe(targetBefore.revision);
+ expect(targetAfter.page.compiled_truth).toBe(targetBefore.page.compiled_truth);
+ expect(await engine.executeRaw('SELECT text_projection_revision,embedding_signature FROM pages WHERE id=$1', [targetBefore.page.id]))
+ .toEqual([{ text_projection_revision: null, embedding_signature: null }]);
+ expect(await engine.executeRaw('SELECT id FROM content_chunks WHERE page_id=$1', [targetBefore.page.id])).toEqual([]);
+ expect(await state(f.sourceId)).toEqual(before);
+ expect(['unrelated', 'private'].map(slug => readFileSync(join(f.root, `${slug}.md`)))).toEqual(filesBefore);
+ await engine.transaction(tx => completeWrite(tx, f.request, 'cancelled', {}));
+ });
+
+ test('a 12001-page source refuses atomically before withdrawal or durable effects', async () => {
+ const f = await fixture();
+ try {
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,timeline,frontmatter)
+ SELECT $1,'capacity-page-'||n,'note','Capacity control','Unrelated control text','','{}'::jsonb FROM generate_series(1,11998) n`, [f.sourceId]);
+ const pages = () => engine.executeRaw(`SELECT count(*)::int AS count,md5(string_agg(row_to_json(p)::text,'' ORDER BY id)) AS fingerprint
+ FROM pages p WHERE source_id=$1`, [f.sourceId]);
+ const facts = () => engine.executeRaw('SELECT row_to_json(f) AS fact FROM facts f WHERE source_id=$1 ORDER BY id', [f.sourceId]);
+ const chunks = () => engine.executeRaw(`SELECT row_to_json(c) AS chunk FROM content_chunks c JOIN pages p ON p.id=c.page_id
+ WHERE p.source_id=$1 ORDER BY c.id`, [f.sourceId]);
+ const beforePages = await pages(), beforeFacts = await facts(), beforeChunks = await chunks();
+ expect(beforePages[0].count).toBe(12001);
+ const beforeRequest = await engine.executeRaw('SELECT row_to_json(r) AS request FROM persistence_requests r WHERE id=$1::uuid', [f.request.id]);
+ await expect(f.withdraw()).rejects.toMatchObject({ code: 'withdrawal_capacity' });
+ expect(await pages()).toEqual(beforePages); expect(await facts()).toEqual(beforeFacts); expect(await chunks()).toEqual(beforeChunks);
+ expect(await engine.executeRaw('SELECT row_to_json(r) AS request FROM persistence_requests r WHERE id=$1::uuid', [f.request.id])).toEqual(beforeRequest);
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toEqual([]);
+ expect(await engine.executeRaw('SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid', [f.request.id])).toEqual([]);
+ } finally { await engine.executeRaw('DELETE FROM sources WHERE id=$1', [f.sourceId]); }
+ }, 120_000);
+
+ test('orphan closing fences block withdrawal and prepared publication of matching claims', async () => {
+ const f = await fixture(), malformed = fence('uses A | B').replace(FACTS_FENCE_BEGIN, '');
+ await engine.putPage('orphan', { type: 'note', title: 'Orphan', compiled_truth: malformed }, { sourceId: f.sourceId });
+ const before = await engine.executeRaw('SELECT row_to_json(p) AS page FROM pages p WHERE source_id=$1 ORDER BY slug', [f.sourceId]);
+ await expect(f.withdraw()).rejects.toMatchObject({ code: 'withdrawal_provenance' });
+ expect(await engine.executeRaw('SELECT row_to_json(p) AS page FROM pages p WHERE source_id=$1 ORDER BY slug', [f.sourceId])).toEqual(before);
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toEqual([]);
+ await engine.executeRaw(`INSERT INTO fact_withdrawals(source_id,visibility,fact_hash)
+ SELECT source_id,visibility,gbrain_fact_fingerprint(fact) FROM facts WHERE id=$1`, [f.fact.id]);
+ let ready: PreparedContentImport | undefined;
+ await importFromContent(engine, 'new-orphan', malformed, { sourceId: f.sourceId, noEmbed: true, prepare: async value => { ready = value; return value.result; } });
+ expect(ready).toBeDefined();
+ await expect(engine.transaction(tx => ready!.validate(tx))).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(engine.transaction(tx => ready!.apply(tx))).rejects.toMatchObject({ code: 'invalid_params' });
+ expect(await engine.getPage('new-orphan', { sourceId: f.sourceId })).toBeNull();
+ });
+
+ test('dense malformed markers refuse during parsing before ledger mutation', async () => {
+ const f = await fixture();
+ await engine.putPage('dense', { type: 'note', title: 'Dense', compiled_truth: FACTS_FENCE_BEGIN.repeat(16_385) }, { sourceId: f.sourceId });
+ await expect(f.withdraw()).rejects.toMatchObject({ code: 'withdrawal_capacity' });
+ expect(await engine.executeRaw('SELECT 1 FROM fact_withdrawals WHERE source_id=$1', [f.sourceId])).toEqual([]);
+ expect(await engine.executeRaw('SELECT expired_at FROM facts WHERE id=$1', [f.fact.id])).toEqual([{ expired_at: null }]);
+ });
+
+ test('targeted embedding retry skips superseded revisions and reconciles exhausted targets without writes in preview', async () => {
+ const f = await fixture();
+ await engine.putPage('z-affected', { type: 'note', title: 'Later affected', compiled_truth: fence('uses A | B') }, { sourceId: f.sourceId });
+ await f.withdraw(); await rebuildPendingPageProjections(engine, 100);
+ await engine.executeRaw(`UPDATE persistence_effects SET state='failed',attempts=5,error_code='embedding_attempts_exhausted'
+ WHERE request_id=$1::uuid AND kind='embedding'`, [f.request.id]);
+ await engine.putPage('affected', { type: 'note', title: 'Changed', compiled_truth: 'A newer observation.' }, { sourceId: f.sourceId });
+ const before = await engine.executeRaw("SELECT data,state,attempts FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id]);
+ const config = { engine: backend, embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536 };
+ await engine.setConfig('embedding_disabled', 'false');
+ try {
+ expect(await retryEmbeddingEffect(engine, f.sourceId, f.request.request_id, true, config)).toMatchObject({ action: 'would_retry' });
+ expect(await engine.executeRaw("SELECT data,state,attempts FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id])).toEqual(before);
+ await engine.putPage('z-affected', { type: 'note', title: 'Also changed', compiled_truth: 'Another newer observation.' }, { sourceId: f.sourceId });
+ await engine.setConfig('embedding_disabled', 'true');
+ expect(await retryEmbeddingEffect(engine, f.sourceId, f.request.request_id, true, config)).toMatchObject({ action: 'would_reconcile', pending_chunks: 0 });
+ expect(await engine.executeRaw("SELECT data,state,attempts FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id])).toEqual(before);
+ expect(await retryEmbeddingEffect(engine, f.sourceId, f.request.request_id, false, config)).toMatchObject({ action: 'reconciled', attempts: 5 });
+ expect(await engine.executeRaw("SELECT data,attempts FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id]))
+ .toEqual(before.map(({ data, attempts }) => ({ data, attempts })));
+ } finally { await engine.setConfig('embedding_disabled', 'true'); }
+ });
+
+ test('failed legacy embedding preview narrows targets without writes or unrelated projection blockers', async () => {
+ const f = await fixture(); await f.withdraw();
+ await rebuildPendingPageProjections(engine, 100);
+ await engine.executeRaw(`UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1 AND slug='private'`, [f.sourceId]);
+ await engine.executeRaw(`UPDATE persistence_effects SET data='{"source_scan":true}'::jsonb,state='failed',attempts=5,error_code='embedding_attempts_exhausted'
+ WHERE request_id=$1::uuid AND kind='embedding'`, [f.request.id]);
+ const before = await engine.executeRaw("SELECT data,state,attempts FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id]);
+ await engine.setConfig('embedding_disabled', 'false');
+ try {
+ const config = { engine: backend, embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536 };
+ expect(await retryEmbeddingEffect(engine, f.sourceId, f.request.request_id, true, config)).toMatchObject({ action: 'would_retry' });
+ expect(await engine.executeRaw("SELECT data,state,attempts FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id])).toEqual(before);
+ expect(await retryEmbeddingEffect(engine, f.sourceId, f.request.request_id, false, config)).toMatchObject({ action: 'retry_queued' });
+ const [retried] = await engine.executeRaw<{ data: { version: number; targets: Array<{ slug: string }> }; attempts: number }>("SELECT data,attempts FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [f.request.id]);
+ expect(retried.data.version).toBe(2); expect(retried.data.targets.map(t => t.slug)).toEqual(['affected']); expect(retried.attempts).toBe(5);
+ } finally { await engine.setConfig('embedding_disabled', 'true'); }
+ });
+});
diff --git a/test/withdrawal-crash.slow.test.ts b/test/withdrawal-crash.slow.test.ts
new file mode 100644
index 0000000000..7097955787
--- /dev/null
+++ b/test/withdrawal-crash.slow.test.ts
@@ -0,0 +1,41 @@
+import { expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+for (const backend of testBackends()) for (const boundary of ['after_mirror_file', 'before_mirror_commit']) {
+ test(`${backend}: SIGKILL at ${boundary} recovers forward with exact unrelated state`, async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-withdrawal-crash-'));
+ const files = join(root, 'files'); mkdirSync(files);
+ const pg = backend === 'postgres' ? await isolatedPersistencePostgres(process.env.DATABASE_URL!) : null;
+ const database = pg?.databaseUrl ?? join(root, 'pglite');
+ if (pg) await pg.engine.disconnect();
+ const launch = (mode: string) => Bun.spawn([process.execPath, join(import.meta.dir, 'helpers/withdrawal-effect-process.ts'), mode, backend, files, database, boundary], {
+ env: { ...process.env, GBRAIN_HOME: join(root, 'home'), OPENAI_API_KEY: '', ANTHROPIC_API_KEY: '' }, stdout: 'pipe', stderr: 'pipe',
+ });
+ try {
+ const seed = launch('seed'); const seeded = await new Response(seed.stderr).text();
+ expect(await seed.exited, seeded).toBe(0);
+ const child = launch('crash'), reader = child.stdout.getReader();
+ const errors = new Response(child.stderr).text();
+ let output = '';
+ const timer = setTimeout(() => child.kill('SIGKILL'), 30_000);
+ try {
+ for (;;) {
+ const next = await reader.read();
+ if (next.done) break;
+ output += new TextDecoder().decode(next.value);
+ if (output.includes('AT_MIRROR_BOUNDARY')) break;
+ }
+ child.kill('SIGKILL');
+ expect(await child.exited).toBe(137); expect(child.signalCode).toBe('SIGKILL');
+ expect(output, await errors).toContain('AT_MIRROR_BOUNDARY');
+ } finally { clearTimeout(timer); child.kill(); }
+ const recovery = launch('recover');
+ const recovered = await new Response(recovery.stdout).text(), stderr = await new Response(recovery.stderr).text();
+ expect(await recovery.exited, stderr).toBe(0); expect(recovered).toContain('RECOVERED_EXACTLY');
+ } finally { await pg?.close(); rmSync(root, { recursive: true, force: true }); }
+ }, 120_000);
+}
diff --git a/test/withdrawal-publication-file.test.ts b/test/withdrawal-publication-file.test.ts
new file mode 100644
index 0000000000..a8582f670d
--- /dev/null
+++ b/test/withdrawal-publication-file.test.ts
@@ -0,0 +1,97 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { recordFactWithdrawal } from '../src/core/facts/withdrawal.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { activatePersistence } from '../src/core/persistence/activation.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+interface Fixture { engine: BrainEngine; sourceId: string; path: string; original: string; pageId: number;
+ binding: Awaited<ReturnType<typeof claimWorktree>>; }
+const slug = 'notes/withdrawal-file-race';
+const engines: BrainEngine[] = [];
+const fixtures: Fixture[] = [];
+const roots: string[] = [];
+let hostId: string;
+let closePostgres: (() => Promise<void>) | undefined;
+beforeAll(async () => {
+ hostId = localHostId();
+ const lite = new PGLiteEngine();
+ await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+ for (const engine of engines) {
+ const sourceId = `withdrawal-file-race-${engine.kind}`;
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-withdrawal-file-')); roots.push(root);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const binding = await claimWorktree(engine, sourceId, root, hostId);
+ const page = await engine.putPage(slug, { type: 'note', title: 'Withdrawal file race', compiled_truth: 'Original body.' }, { sourceId });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE source_id=$2 AND slug=$3', [`${slug}.md`, sourceId, slug]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ const path = join(root, `${slug}.md`), original = serializePageToMarkdown(snapshot.page, snapshot.tags);
+ mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, original);
+ fixtures.push({ engine, sourceId, path, original, pageId: page.id, binding });
+ await registerLocalWriter(engine, 'cli');
+ expect((await activatePersistence(engine, { confirmQuiesced: true })).enabled).toBe(true);
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) await engine.disconnect();
+ await closePostgres?.();
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+}, 60_000);
+
+test('a prepared repo-file write racing a withdrawal leaves the canonical file and page unchanged', async () => {
+ for (const { engine, sourceId, path, original, pageId, binding } of fixtures) {
+ const before = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect(readFileSync(path, 'utf8')).toBe(original);
+
+ const claim = 'withdrawn between file preparation and publication';
+ const fence = renderFactsTable([{ rowNum: 1, claim, kind: 'fact', confidence: 1, visibility: 'world',
+ notability: 'medium', active: true, context: 'test evidence' }]);
+ const content = `---\ntitle: Withdrawal file race\ntype: note\n---\nFacts: ${fence}\n`;
+ const context: OperationContext = { engine, sourceId, remote: false, dryRun: false,
+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } };
+ const authority = await submissionAuthority(context, 'put_page', sourceId, binding.source_incarnation, slug);
+ await admitWrite(engine, { principal: authority.principal, operation: 'put_page', sourceId,
+ sourceIncarnation: binding.source_incarnation, slug, pageId, requestId: randomUUID(),
+ callerIntent: { slug, content, expected_revision: before.revision },
+ intent: { slug, content, expected_revision: before.revision }, authority,
+ worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });
+ const claimed = (await claimNextWrite(engine, hostId))!;
+ const prepared = await preparePageMutation(engine, claimed, { engine: engine.kind });
+ expect(prepared.file?.path).toBe(path);
+ expect(prepared.file?.content).toContain(claim);
+
+ const fact = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>
+ tx.insertFact({ fact: claim, source: 'remember', visibility: 'world' }, { source_id: sourceId })));
+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => recordFactWithdrawal(tx, fact.id, sourceId, true)));
+
+ const boundaries: string[] = [];
+ const rejected = await publishMutation(engine, claimed, prepared, hostId, {
+ boundary: async name => { boundaries.push(name); }, fileBoundary: name => { boundaries.push(name); } });
+
+ expect(rejected).toMatchObject({ state: 'conflict', error_code: 'revision_conflict' });
+ expect(boundaries).not.toContain('before_publication');
+ expect(boundaries).not.toContain('before_file');
+ expect(readFileSync(path, 'utf8')).toBe(original);
+ const after = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ expect(after.revision).toBe(before.revision);
+ expect(after.page.compiled_truth).toBe('Original body.');
+ }
+}, 120_000);