Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(takes): automatic take embedding with a full vector lifecycle; doctor fact_take_vectors (#5885 #5188)

garrytanf7cb66c9876c
diff --git a/docs/GBRAIN_VERIFY.md b/docs/GBRAIN_VERIFY.md
index 599900097f..4622288617 100644
--- a/docs/GBRAIN_VERIFY.md
+++ b/docs/GBRAIN_VERIFY.md
@@ -221,6 +221,41 @@ If blank, set the key. Then:
gbrain embed --stale
```
+### 5a. Fact and take vectors
+
+Chunk coverage says nothing about facts and takes, which are searched by vector
+too (fact dedup and consolidation, `think`, `takes search --semantic`).
+
+**Command:**
+
+```bash
+gbrain doctor --json
+```
+
+**Expected:** the `fact_take_vectors` check is `ok`. On a keyless brain
+(embeddings disabled) it reports "not applicable" and stays `ok`.
+
+**If it warns** (code `stale_vectors`): its `details` count, per source, facts
+and takes with no vector for their current text under the brain's embedding
+model, and `details.fix` lists the exact commands. Takes are repaired by the
+ordinary stale pass:
+
+```bash
+gbrain embed --stale
+```
+
+Facts are repaired per source, after a preview (paid provider calls need
+explicit authorization):
+
+```bash
+gbrain embed --facts --stale --source <source-id> --dry-run --json
+gbrain embed --facts --stale --source <source-id> --yes --max-cost-usd 1
+```
+
+If the check says the vectors were not verified (code `vectors_not_verified`),
+run `gbrain migrate embeddings --status` to see which model and width the brain
+records.
+
---
## 6. Brain-First Lookup Protocol
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 3841081674..9da85cf967 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -11,6 +11,8 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set), origins (`mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`, and the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
+- `src/commands/doctor/checks/auto-chronicle.ts` — `auto_chronicle` (#5876), registered after `unlinked_facts`: warns (code `auto_chronicle_no_effect`, fix `gbrain chronicle-backfill --dry-run`) while `auto_chronicle=true`, because nothing reads that setting; ok otherwise.
+- `src/commands/doctor/checks/vector-coverage.ts` — `fact_take_vectors` (#5188, #5885), registered after `auto_chronicle`: per unarchived source (honoring `--source`), active facts (`eligibleFactEmbedding` + `staleFactEmbedding`) and takes (`countStaleTakes` with the DB-plane model and width) with no vector for their current text, split into missing versus other-model; warns with code `stale_vectors` and `details.fix` (`gbrain embed --stale`, or `gbrain takes embed` when `takes.auto_embed` is off; per-source `gbrain embed --facts --stale --source <id> --dry-run --json`). Keyless brains report `applicable: false`; a brain with no recorded model or width warns `vectors_not_verified`.
- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.md
index 7d0e2a93f9..0961e5533e 100644
--- a/docs/architecture/key-files/engines-1.md
+++ b/docs/architecture/key-files/engines-1.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/docker-postgres.ts` — gbrain's OWN docker Postgres container, the shared seam between the init ladder's docker rung and db-repair's `conn_refused` auto arm. `GBRAIN_PG_CONTAINER = 'gbrain-postgres'` / `GBRAIN_PG_IMAGE = 'pgvector/pgvector:pg16'` / `GBRAIN_PG_HOST_PORT = 5434` live HERE and only here (DRY — the init rung and the repair arm must never carry two string literals that can drift). Ownership contract: gbrain starts and reuses this container, NEVER stops or removes it, and never touches a container whose credentials it cannot recover via `inspectCredentials` (docker inspect → `POSTGRES_PASSWORD` env + the container's ORIGINAL port mapping — a freshly generated password can never match a surviving container; unrecoverable → refuse with a recreate-with-consent recipe). Hardening: the port binds loopback-only (`127.0.0.1:5434` — a single-machine brain store, not a network service); data lives on the named `gbrain-pgdata` volume so a container recreate never loses the brain; the password rides the child ENVIRONMENT (bare `-e POSTGRES_PASSWORD` — argv is world-readable in `ps`); `docker run` gets a 10-minute timeout (the first run synchronously pulls the image; 30s stays for cheap ps/inspect/start calls). `isGbrainDockerUrl` is the one predicate for "does this URL point at our container" (loopback + dedicated port — never error text).
-- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all three dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.
+- `src/core/embedding-migration.ts` — provider-agnostic embedding migration core; owns the schema-transition + env-gate primitives. `runSchemaTransition(engine, targetDim)`: ONE transaction rebuilds all four dim-pinned text-embedding-space columns (`content_chunks.embedding`, `query_cache.embedding`, `facts.embedding`, `takes.embedding`) preserving each column's `vector`/`halfvec` type, HNSW gated on `hnswIndexExpected` (dims > 2000 skip the index; exact scans stay correct — 2048d targets work); image/multimodal columns deliberately untouched; AFTER commit it clears `embedded_at` in yielding 50k batches (belt-and-braces hygiene — read surfaces key on the vector itself). `planEmbeddingMigration`: workload via widened stale predicates (absent-column fallback counts every chunk), cost, `signature_census` (top-5 page signatures — DB-reality corroboration of From), `synopsis_tier_pages` (context-tier downgrade consent), bundle-aware `reranker_warning`, `dim_change` via the shared `schemaRebuildNeeded` (null ⇒ rebuild, same computation apply uses). `applyEmbeddingMigration`: env≠target refusal (`detectEnvOverride`; `detectEnvPresence` drives the ==target notice) → marker v2 write (same-target re-apply preserves `started_at`; retarget records `superseded` history) → full rebuild when the chunks column is off-width, else INDEPENDENT repair of stale dim-pinned columns (`readDimPinnedWidths`) → false-target-stamp clearing (chunk-model truth) + guarded NULL-signature-inclusive invalidation (embed_skip pages' retained vectors preserved; both via `embedding-invalidation.ts`) BEFORE config writes (same-dim-swap crash safety) → DB plane → file-plane callback → cache purge. `verifyMigrationComplete`: the ONLY basis for "nothing to migrate" — column + pinned widths, wide stale census, false-stamp census blocker (embedded chunks whose `model` contradicts a page already stamped with the target signature), `missing_embeddings` residue, chunkless-pages census, embed_skip-NULL visibility (report-only detail, never a blocker), marker state, un-merged file plane (or env-canonical), env-contradiction blocker; never trusts `from_model`. `completeEmbeddingMigration`: marker delete + completion stamp in ONE transaction (no lost-receipt crash window); accepts content-free `extra` (smoke-check outcome). `readMigrationState` (corrupt-safe), `readMigrationStatus` (read-only, spend-free, everything-degrades-to-null), `verifySearchRoundTrip` (completion smoke check: query-side `embedQuery` + `searchVector`, hit identity by page_id, NEVER throws, warn-don't-block, content-free samples), `resolveRerankerExposure`/`resolveRerankerPlan`/`applyRerankerAction` (D8 companion switch: bundle-resolved exposure; auto→target-provider default reranker, never a silent third provider; config write + cache purge in one tx), `reconcilePageSignatures` (batch-boundary stamp repair). Engine-pure; every step idempotent under crash + re-run — the NULL-embedding column is the checkpoint. Pinned by `test/embedding-migration.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`, `test/e2e/migrate-embeddings-postgres.test.ts`.
- `src/core/engine-constants.ts` — single source of truth for engine batch-sizing constants. Exports `DELETE_BATCH_SIZE = 500` consumed by both engines' `deletePages` + `resolveSlugsByPaths` and by the sync delete + rename loops. Lives outside `engine.ts` (the interface module) to avoid circular-import worry — bounded per-statement work for predictable lock hold time + write amplification. Also exports `TRAVERSE_PATH_ROW_CAP = 5000`, the raw-row bound on `traversePaths`/`traversePathsDetailed` (both engines `LIMIT CAP + 1`; the extra row is the truncation probe; counted before edge dedup), and `TRAVERSE_WALK_ROW_CAP = 20000`, the bound on simple-path rows the recursive walks enumerate (`traverseGraph` and `traversePaths*`, both engines). The walk CTE is pulled through `LIMIT` so a dense hub stops enumerating, rows are deduped to `(page, depth)` before the edge join or the per-node link aggregation, and `traversePaths` stops recursing one layer early because the deepest layer only terminates edges. A capped walk sets `truncated` on `traversePathsDetailed`.
diff --git a/docs/guides/embedding-migration.md b/docs/guides/embedding-migration.md
index ae695bff25..378392e2b7 100644
--- a/docs/guides/embedding-migration.md
+++ b/docs/guides/embedding-migration.md
@@ -137,6 +137,10 @@ even if a custom base URL still serves its old model.
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.
+ Active takes on live pages are re-embedded in the same drain (their
+ vectors record the model and claim text, and `takes.embedding` is resized
+ with the other text columns on a width change); the plan, `--status`
+ (`takes pending`) and the completion check all count them.
## Recovery
diff --git a/docs/takes-vs-facts.md b/docs/takes-vs-facts.md
index bcd6fd4980..c6d3dc48b1 100644
--- a/docs/takes-vs-facts.md
+++ b/docs/takes-vs-facts.md
@@ -21,15 +21,25 @@ The epistemological layer. WHO believes WHAT, with confidence weight and time.
**Query surface:** `gbrain takes list`, `gbrain takes search`, `gbrain takes search --semantic`, `gbrain think`
-Run `gbrain takes embed` after extraction to populate the take vectors used by
-semantic search and the `think` vector stream. `gbrain takes embed --dry-run`
-shows the pending provider work without making calls.
-
-The `takes.embedding` column follows your configured embedding dimension
-(migration v142): if the configured model's width differs from the column,
-the migration resizes it and clears every existing take vector by design —
-run `gbrain takes embed` once after the migration to repopulate them. Until you
-do, `think` falls back to keyword-only takes retrieval and
+Take vectors (used by `takes search --semantic` and the `think` vector stream)
+are kept current by `gbrain embed --stale`, which the cycle's embed phase runs:
+it embeds every active take that has no vector, whose claim changed since it
+was embedded, or whose vector came from another embedding model. Each vector
+records the model and the claim text it was computed from. Takes on deleted
+pages or archived sources are skipped. `gbrain takes embed` runs the same pass
+on its own; `gbrain takes embed --dry-run` shows the pending provider work
+without making calls.
+
+To stop automatic take embedding, run `gbrain config set takes.auto_embed false`
+(or set `GBRAIN_EMBED_TAKES=0` for one process; the variable wins over the
+config key). `gbrain takes embed` keeps working when it is off.
+
+`gbrain migrate embeddings` moves take vectors with the rest of the brain: the
+plan counts stale takes, a width change resizes `takes.embedding`, the re-embed
+drain refills it, and the run does not complete while takes are still stale.
+`gbrain doctor` reports takes and facts without a current-model vector in the
+`fact_take_vectors` check ([verification runbook](GBRAIN_VERIFY.md#5a-fact-and-take-vectors)).
+Until take vectors exist, `think` falls back to keyword-only takes retrieval and
`takes search --semantic` simply reports no semantic matches.
## Facts (hot memory — `facts` table)
diff --git a/llms-full.txt b/llms-full.txt
index 53d90d6a17..72fa695b23 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -7952,6 +7952,41 @@ If blank, set the key. Then:
gbrain embed --stale
```
+### 5a. Fact and take vectors
+
+Chunk coverage says nothing about facts and takes, which are searched by vector
+too (fact dedup and consolidation, `think`, `takes search --semantic`).
+
+**Command:**
+
+```bash
+gbrain doctor --json
+```
+
+**Expected:** the `fact_take_vectors` check is `ok`. On a keyless brain
+(embeddings disabled) it reports "not applicable" and stays `ok`.
+
+**If it warns** (code `stale_vectors`): its `details` count, per source, facts
+and takes with no vector for their current text under the brain's embedding
+model, and `details.fix` lists the exact commands. Takes are repaired by the
+ordinary stale pass:
+
+```bash
+gbrain embed --stale
+```
+
+Facts are repaired per source, after a preview (paid provider calls need
+explicit authorization):
+
+```bash
+gbrain embed --facts --stale --source <source-id> --dry-run --json
+gbrain embed --facts --stale --source <source-id> --yes --max-cost-usd 1
+```
+
+If the check says the vectors were not verified (code `vectors_not_verified`),
+run `gbrain migrate embeddings --status` to see which model and width the brain
+records.
+
---
## 6. Brain-First Lookup Protocol
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 043119188a..e0c0316f9c 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -13,8 +13,8 @@ src/commands/doctor/bootstrap-checks.ts bootstrapDoctorChecks 476 seed: W5 basel
src/commands/doctor/checks/extraction-sync.ts checkSyncFreshness 333 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/doctor/report-remote.ts doctorReportRemote 416 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/dream-retriage.ts runDreamRetriage 524 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/commands/embed.ts embedAllStale 560 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +9 #5804: a null projection snapshot is a counted failure (archived sources left to reportArchived) with one end-of-run batch summary
-src/commands/embed.ts runEmbedCore 376 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/commands/embed.ts embedAllStale 564 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +9 #5804: a null projection snapshot is a counted failure (archived sources left to reportArchived) with one end-of-run batch summary; +4 wave 8 lane D1 #5527: subtract current-model chunks from the mixed-space warning
+src/commands/embed.ts runEmbedCore 381 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 wave 8 lane D1 #5885: stale-drain takes pass call and its watchdog progress counter
src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/extract-conversation-facts.ts processPage 307 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/extract-conversation-facts.ts runExtractConversationFactsCore 372 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState
@@ -43,7 +43,7 @@ src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline,
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 447 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1043 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/import-file.ts importFromContent 857 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/import-file.ts importFromContent 859 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 377 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/handlers/subagent.ts makeSubagentHandler 884 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 814 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f18e97205a..3be3026725 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -6,7 +6,7 @@
src/cli.ts 3198 ratchet +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts)
src/commands/autopilot.ts 1635 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195)
src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
-src/commands/embed.ts 2190 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; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale
+src/commands/embed.ts 2208 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; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts)
src/commands/extract-conversation-facts.ts 2146 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); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts)
src/commands/extract.ts 2623 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; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference)
src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)
@@ -17,7 +17,7 @@ src/core/cycle.ts 3189 ratchet +2 System One v1 S9: extract_facts phase tail run
src/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); 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; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge
src/core/cycle/extract-atoms.ts 1834 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; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize
src/core/engine.ts 2674 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; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option
-src/core/import-file.ts 2230 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; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)
+src/core/import-file.ts 2232 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; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts)
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
src/core/operations.ts 331 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; +2 security wave: withOutputRedaction applied at op registration
src/core/pglite-engine.ts 3225 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166)
@@ -32,11 +32,11 @@ 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 2013 ratchet +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); 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; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)
src/core/link-extraction.ts 2143 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; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note
-src/core/embedding-migration.ts 1525 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; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed
+src/core/embedding-migration.ts 1550 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; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify
src/core/github-source.ts 1530 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; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 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; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 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; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1813 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge
+src/core/config.ts 1816 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row
src/core/bootstrap/harness.ts 2674 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 626 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op
diff --git a/src/commands/doctor/checks/vector-coverage.ts b/src/commands/doctor/checks/vector-coverage.ts
new file mode 100644
index 0000000000..b8ed8374c6
--- /dev/null
+++ b/src/commands/doctor/checks/vector-coverage.ts
@@ -0,0 +1,86 @@
+/**
+ * fact_take_vectors (#5188, #5885): facts and takes are searched by vector
+ * (dedup, consolidation, think, `takes search --semantic`), but chunk coverage
+ * says nothing about them. Counts, per source, active facts and takes whose
+ * vector is missing or was computed by another model, width or text than the
+ * brain's configured embedding model, and names the recovery commands.
+ *
+ * Keyless brains (embedding_disabled) report "not applicable": nothing can
+ * embed there, and keyword search keeps working.
+ */
+import { loadConfig } from '../../../core/config.ts';
+import { AUDIT_ROW_SOURCES } from '../../../core/facts/audit-sources.ts';
+import { eligibleFactEmbedding, staleFactEmbedding } from '../../../core/facts/embedding-identity.ts';
+import { takesAutoEmbedEnabled } from '../../../core/embed-takes.ts';
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+export const VECTOR_COVERAGE_DOCS = 'docs/GBRAIN_VERIFY.md#5a-fact-and-take-vectors';
+
+interface SourceVectors { source_id: string; facts_missing: number; facts_stale: number; takes_missing: number; takes_stale: number }
+
+async function runFactTakeVectors(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ ctx.progress.heartbeat('fact_take_vectors');
+ if (loadConfig()?.embedding_disabled === true || await engine.getConfig('embedding_disabled') === 'true') {
+ checks.push({ name: 'fact_take_vectors', status: 'ok', message: 'Not applicable: embeddings are disabled on this brain (keyword search keeps working).',
+ details: { applicable: false } });
+ return checks;
+ }
+ const model = await engine.getConfig('embedding_model');
+ const dims = Number(await engine.getConfig('embedding_dimensions'));
+ if (!model || !Number.isInteger(dims) || dims <= 0) {
+ checks.push({ name: 'fact_take_vectors', status: 'warn', message: 'Fact and take vectors were not verified: the brain records no embedding model and width. Fix: gbrain migrate embeddings --status',
+ details: { code: 'vectors_not_verified', applicable: true, fix: 'gbrain migrate embeddings --status', docs: VECTOR_COVERAGE_DOCS } });
+ return checks;
+ }
+ try {
+ const sources = (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE NOT archived ORDER BY id'))
+ .filter(s => !ctx.orphanRatioSourceId || s.id === ctx.orphanRatioSourceId);
+ const factRows = await engine.executeRaw<{ source_id: string; missing: number; stale: number }>(
+ `SELECT f.source_id, count(*) FILTER (WHERE f.embedding IS NULL)::int AS missing, count(*)::int AS stale
+ FROM facts f WHERE ($1::text IS NULL OR f.source_id = $1) AND ${eligibleFactEmbedding} AND ${staleFactEmbedding}
+ GROUP BY f.source_id`,
+ [ctx.orphanRatioSourceId ?? null, [...AUDIT_ROW_SOURCES], model, dims]);
+ const bySource: SourceVectors[] = [];
+ for (const source of sources) {
+ const fact = factRows.find(r => r.source_id === source.id);
+ const takesStale = await engine.countStaleTakes({ model, dims, sourceId: source.id });
+ const takesMissing = takesStale ? await engine.countStaleTakes({ sourceId: source.id }) : 0;
+ const row = { source_id: source.id, facts_missing: Number(fact?.missing ?? 0), facts_stale: Number(fact?.stale ?? 0),
+ takes_missing: takesMissing, takes_stale: takesStale };
+ if (row.facts_stale || row.takes_stale) bySource.push(row);
+ }
+ const sum = (key: keyof Omit<SourceVectors, 'source_id'>) => bySource.reduce((n, r) => n + r[key], 0);
+ const facts = { missing: sum('facts_missing'), other_model: sum('facts_stale') - sum('facts_missing'), stale: sum('facts_stale') };
+ const takes = { missing_or_changed: sum('takes_missing'), other_model: sum('takes_stale') - sum('takes_missing'), stale: sum('takes_stale') };
+ const takesFix = await takesAutoEmbedEnabled(engine) ? 'gbrain embed --stale' : 'gbrain takes embed';
+ const factSources = bySource.filter(r => r.facts_stale).map(r => r.source_id);
+ const fix = [
+ ...(takes.stale ? [takesFix] : []),
+ ...factSources.map(id => `gbrain embed --facts --stale --source ${id} --dry-run --json`),
+ ];
+ if (facts.stale === 0 && takes.stale === 0) {
+ checks.push({ name: 'fact_take_vectors', status: 'ok', message: `Every active fact and take has a ${model} vector for its current text.`,
+ details: { applicable: true, model, dims, facts, takes, by_source: [] } });
+ return checks;
+ }
+ checks.push({
+ name: 'fact_take_vectors',
+ status: 'warn',
+ message: `${facts.stale} active fact(s) and ${takes.stale} active take(s) have no ${model} (${dims}d) vector for their current text ` +
+ `(facts: ${facts.missing} missing, ${facts.other_model} from another model or text; takes: ${takes.missing_or_changed} missing or claim changed, ${takes.other_model} from another model). ` +
+ `Vector dedup, consolidation and semantic take search skip them. Fix: ${fix.join('; ')}`,
+ details: { code: 'stale_vectors', applicable: true, model, dims, facts, takes, by_source: bySource,
+ cause: 'facts and takes without a current-model vector', fix, docs: VECTOR_COVERAGE_DOCS },
+ });
+ } catch (err) {
+ checks.push({ name: 'fact_take_vectors', status: 'warn',
+ message: `Fact and take vectors were not verified: ${err instanceof Error ? err.message : String(err)}. Fix: gbrain migrate embeddings --status`,
+ details: { code: 'vectors_not_verified', applicable: true, fix: 'gbrain migrate embeddings --status', docs: VECTOR_COVERAGE_DOCS } });
+ }
+ return checks;
+}
+
+export const factTakeVectorsEntry: DoctorEntry = { name: 'fact_take_vectors', emits: ['fact_take_vectors'], run: runFactTakeVectors };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index bea04c5a1f..81dbb26703 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -81,6 +81,7 @@ import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/qu
import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';
import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { autoChronicleEntry } from './checks/auto-chronicle.ts';
+import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
@@ -141,6 +142,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
decideHealthEntry,
unlinkedFactsEntry,
autoChronicleEntry,
+ factTakeVectorsEntry,
searchModeEntry,
];
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 8eacf09331..a032cb00d5 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1,6 +1,7 @@
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 { embedTakesForStaleDrain, type EmbedTakesResult } from '../core/embed-takes.ts';
import { parseFactEmbedArgs } from './embed-facts-delegate.ts';
import { readProjectionSnapshot, installPageProjection, installPageEmbeddings } from '../core/page-state/projections.ts';
import { PageRevisionConflictError } from '../core/page-state/types.ts';
@@ -245,6 +246,12 @@ export interface EmbedOpts {
*/
heldLocks?: DbLockHandle[];
assertOwned?: (tx?: BrainEngine) => Promise<void>;
+ /**
+ * #5885: a `stale` drain also embeds stale takes (missing, claim-drifted or
+ * other-model vectors). Unset follows `takes.auto_embed` / GBRAIN_EMBED_TAKES
+ * (default on); the embedding-model migration drain passes true.
+ */
+ takes?: boolean;
}
/**
@@ -343,6 +350,8 @@ export interface EmbedResult {
* failures>0 consumers surface it unchanged.
*/
reason?: 'stall_timeout';
+ /** #5885: the takes pass of a `stale` drain, when it ran. Its failures are also counted in `failures`. */
+ takes?: EmbedTakesResult;
}
/**
@@ -679,6 +688,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
// src/core/embed-stall.ts for the two-clock design and the operator
// notes). Armed for real drains only; dryRun never embeds so "no
// successful progress" is its normal state, and 0/negative disables.
+ let takesEmbedded = 0;
const stallSeconds = opts.dryRun ? 0 : resolveEmbedStallAbortSeconds();
const watchdog = stallSeconds > 0
? createEmbedStallWatchdog({
@@ -687,7 +697,7 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
// prelude (thousands of getChunks+upsertChunks before the first
// embed) is healthy work, not a stall — without this it would
// abort deterministically at the same point on every resume.
- readProgress: () => result.embedded + (result.healed_splits ?? 0),
+ readProgress: () => result.embedded + (result.healed_splits ?? 0) + takesEmbedded,
})
: undefined;
@@ -709,6 +719,10 @@ export async function runEmbedCore(engine: BrainEngine, opts: EmbedOpts): Promis
includeNullSignature: opts.includeNullSignature,
assertOwned: opts.assertOwned,
}, drainSignal);
+ if (opts.stale && !isAborted(drainSignal)) await embedTakesForStaleDrain(engine, {
+ dryRun: !!opts.dryRun, signal: drainSignal, sourceId: opts.sourceId, assertOwned: opts.assertOwned, quiet: opts.quiet,
+ takes: opts.takes, onProgress: (_done, _total, embedded) => { takesEmbedded = embedded; },
+ }, result);
} catch (e) {
// A heartbeat-triggered abort is a clean, resumable stop (lock_lost is
// already set + explained on stderr) — not an error to propagate.
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index 2e90eb0dd0..64ddee8026 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -113,7 +113,7 @@ 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 to embed, ${plan.chunks_to_restamp} to restamp, ${plan.facts_to_embed ?? 0} active facts; ${plan.blocked_projection_pages ?? 0} projection-blocked pages.`);
+ lines.push(` Work: ${plan.chunks_to_embed} chunks to embed, ${plan.chunks_to_restamp} to restamp, ${plan.facts_to_embed ?? 0} active facts, ${plan.takes_to_embed ?? 0} active takes; ${plan.blocked_projection_pages ?? 0} projection-blocked pages.`);
lines.push(' Paid authorization: --max-cost-usd is a durable total cap; each attempt reserves its maximum input size and settles to reported usage; unknown prices refuse.');
// DB-reality census: what pages say they were embedded with (env can lie
// about From; the census cannot).
@@ -751,6 +751,7 @@ export async function executeMigrationFlow(
catchUp: true,
singleFlight: true,
includeNullSignature: true,
+ takes: true,
quiet: opts.quiet,
heldLocks,
assertOwned,
@@ -780,18 +781,21 @@ export async function executeMigrationFlow(
includeNullSignature: true,
});
const remainingFacts = await countStaleFactEmbeddings(engine, plan.to_model, plan.to_dims);
+ const remainingTakes = await engine.countStaleTakes({ model: plan.to_model, dims: 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 remaining = remainingChunks + remainingFacts.count + remainingTakes + finalReadiness.blocked + chunkless + (sourceChanged || configChanged ? 1 : 0);
const base = {
embedded: embedResult.embedded + embeddedFacts,
facts_embedded: embeddedFacts,
facts_remaining: remainingFacts.count,
+ takes_embedded: embedResult.takes?.embedded ?? 0,
+ takes_remaining: remainingTakes,
blocked_projection_pages: finalReadiness.blocked,
signatures_reconciled: reconciled,
invalidated: applied.invalidated,
@@ -814,7 +818,7 @@ export async function executeMigrationFlow(
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 };
+ verified.details.stale_wide + (verified.details.stale_facts ?? 0) + (verified.details.stale_takes ?? 0) + (verified.details.blocked_projection_pages ?? 0)), ...base };
await assertOwned();
await completeEmbeddingMigration(engine, plan, {
verify_search: { status: verifySearch.status, samples: verifySearch.samples },
@@ -927,7 +931,7 @@ export async function runMigrateEmbeddings(
console.log(` File plane: ${filePlane ? `${filePlane.model ?? '(none)'} @ ${filePlane.dims ?? '?'}d` : '(no ~/.gbrain/config.json)'}`);
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(` Vectors: ${report.missing_embeddings ?? '?'} chunk(s) missing; ${report.chunkless_pages ?? '?'} contentful page(s) without chunks; facts pending: ${report.facts_pending ?? 'n/a'}; takes pending: ${report.takes_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)`);
@@ -1040,7 +1044,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 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}`}?`);
+ const ok = await confirm(`Re-embed ${plan.chunks_to_embed} chunks, ${plan.facts_to_embed ?? 0} facts and ${plan.takes_to_embed ?? 0} takes (${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);
diff --git a/src/core/config.ts b/src/core/config.ts
index 47359e4b31..01681496ea 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1576,6 +1576,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// consent reads this key, and enabling it is the documented path to
// `gbrain takes extract --from-pages` — same unregistered-key class.
'takes.bootstrap_enabled',
+ // #5885: `embed --stale` (cycle embed phase, migration drain) also embeds
+ // stale takes; `false` turns that off (GBRAIN_EMBED_TAKES=0 overrides).
+ 'takes.auto_embed',
// B-14: USD cap for one takes-bootstrap run's classifier calls (default 5.0;
// 0 disables). Read by src/core/extract-takes-from-pages.ts.
'takes.bootstrap_budget_usd',
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index cc911defa4..89088e0e09 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -70,6 +70,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'child_table_orphans',
'chronicle_projection_health',
'auto_chronicle',
+ 'fact_take_vectors',
'code_chunk_metadata',
'content_hash_duplicates',
'content_sanity_audit_recent',
diff --git a/src/core/embed-takes.ts b/src/core/embed-takes.ts
index afcc850ef0..ecba94a956 100644
--- a/src/core/embed-takes.ts
+++ b/src/core/embed-takes.ts
@@ -1,13 +1,19 @@
/**
* Embedding pass for typed take claims.
*
- * Takes already have vector search and a stale-row contract, but no writer.
- * Keep this pass separate from page/chunk embedding so callers can opt into
- * the extra provider work and see its counts independently.
+ * Runs from `gbrain takes embed` and, unless `takes.auto_embed` is off, from
+ * every `embed --stale` drain (which the cycle's embed phase and the
+ * embedding-model migration drain both use). A take is stale when it has no
+ * vector, its claim changed since it was embedded, or another model or width
+ * produced its vector (#5885). Each write is bound to the claim text and model
+ * it was computed from, so a claim edited mid-flight keeps its NULL vector.
*/
import type { BrainEngine, StaleTakeRow, TakeEmbeddingInput } from './engine.ts';
import { embedBatchWithBackoff } from '../commands/embed.ts';
+import { getEmbeddingDimensions, getEmbeddingModel } from './ai/gateway.ts';
+import { slog } from './console-prefix.ts';
+import { currentEmbeddingSignature } from './embedding.ts';
const DEFAULT_BATCH_SIZE = 100;
@@ -15,6 +21,8 @@ export interface EmbedTakesOpts {
batchSize?: number;
dryRun?: boolean;
signal?: AbortSignal;
+ sourceId?: string;
+ assertOwned?: (tx: BrainEngine) => Promise<void>;
embedFn?: (texts: string[], opts: { abortSignal?: AbortSignal }) => Promise<Float32Array[]>;
onProgress?: (done: number, total: number, embedded: number) => void;
}
@@ -23,21 +31,46 @@ export interface EmbedTakesResult {
total_stale: number;
embedded: number;
would_embed: number;
+ /** Vectors not written because the take's claim changed while they were computed; the next pass embeds the new claim. */
+ discarded: number;
failures: number;
failure_samples: string[];
dryRun: boolean;
}
-/** Embed active takes whose embedding column is NULL. */
+/** `takes.auto_embed` (config) with `GBRAIN_EMBED_TAKES` (env) taking precedence; default on. */
+export async function takesAutoEmbedEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {
+ const raw = process.env.GBRAIN_EMBED_TAKES ?? await engine.getConfig('takes.auto_embed');
+ return raw == null || !['0', 'false', 'off', 'no'].includes(raw.trim().toLowerCase());
+}
+
+/** Width of `takes.embedding`, or null when the column is absent. */
+export async function readTakesEmbeddingDim(engine: Pick<BrainEngine, 'executeRaw'>): Promise<number | null> {
+ const rows = await engine.executeRaw<{ formatted: string | null }>(
+ `SELECT format_type(a.atttypid, a.atttypmod) AS formatted
+ 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 = 'takes' AND a.attname = 'embedding' AND NOT a.attisdropped`,
+ );
+ const dims = Number(rows[0]?.formatted?.match(/^(?:halfvec|vector)\((\d+)\)$/)?.[1]);
+ return Number.isInteger(dims) && dims > 0 ? dims : null;
+}
+
+/** Embed active takes that have no current-model vector for their current claim. */
export async function embedStaleTakes(
engine: BrainEngine,
opts: EmbedTakesOpts = {},
): Promise<EmbedTakesResult> {
- const stale = await engine.listStaleTakes();
+ const model = getEmbeddingModel();
+ const dims = getEmbeddingDimensions();
+ const scope = { model, dims, ...(opts.sourceId ? { sourceId: opts.sourceId } : {}) };
+ const stale = await engine.countStaleTakes(scope) > 0 ? await engine.listStaleTakes(scope) : [];
const result: EmbedTakesResult = {
total_stale: stale.length,
embedded: 0,
would_embed: opts.dryRun ? stale.length : 0,
+ discarded: 0,
failures: 0,
failure_samples: [],
dryRun: !!opts.dryRun,
@@ -46,6 +79,15 @@ export async function embedStaleTakes(
opts.onProgress?.(stale.length, stale.length, 0);
return result;
}
+ const columnDims = await readTakesEmbeddingDim(engine);
+ if (columnDims !== dims) {
+ result.failures = stale.length;
+ result.failure_samples.push(
+ `takes_embedding_width_mismatch: takes.embedding is ${columnDims === null ? 'absent' : `${columnDims}d`}, the configured model is ${dims}d. ` +
+ 'Fix: gbrain migrate embeddings --status',
+ );
+ return result;
+ }
const batchSize = Math.min(500, Math.max(1, Math.floor(opts.batchSize ?? DEFAULT_BATCH_SIZE)));
const embedFn = opts.embedFn ?? ((texts: string[], embedOpts: { abortSignal?: AbortSignal }) =>
@@ -65,8 +107,14 @@ export async function embedStaleTakes(
const writes: TakeEmbeddingInput[] = batch.map((row: StaleTakeRow, index) => ({
take_id: row.take_id,
embedding: embeddings[index],
+ claim: row.claim,
+ model,
}));
- result.embedded += await engine.updateTakeEmbeddings(writes, { signal: opts.signal });
+ const written = opts.assertOwned
+ ? await engine.transaction(async tx => { await opts.assertOwned!(tx); return tx.updateTakeEmbeddings(writes, { signal: opts.signal }); })
+ : await engine.updateTakeEmbeddings(writes, { signal: opts.signal });
+ result.embedded += written;
+ result.discarded += batch.length - written;
} catch (error: unknown) {
result.failures += batch.length;
if (result.failure_samples.length < 10) {
@@ -78,3 +126,34 @@ export async function embedStaleTakes(
return result;
}
+
+/**
+ * The takes pass of an `embed --stale` drain (#5885). Runs when `opts.takes`
+ * is true, or when it is unset and takes.auto_embed allows it; records its
+ * result on the drain result and counts its failures there too.
+ */
+export async function embedTakesForStaleDrain(
+ engine: BrainEngine,
+ opts: EmbedTakesOpts & { quiet?: boolean; takes?: boolean },
+ result: { failures: number; failure_samples: string[]; takes?: EmbedTakesResult },
+): Promise<void> {
+ if (!(opts.takes ?? await takesAutoEmbedEnabled(engine))) return;
+ // No configured model to bind a vector to (embedding_identity_unverified): the chunk drain runs signature-free; takes wait.
+ if (currentEmbeddingSignature() === null) return;
+ let takes: EmbedTakesResult;
+ try {
+ takes = await embedStaleTakes(engine, opts);
+ } catch (error: unknown) {
+ takes = { total_stale: 0, embedded: 0, would_embed: 0, discarded: 0, failures: 1, dryRun: !!opts.dryRun,
+ failure_samples: [error instanceof Error ? error.message : String(error)] };
+ }
+ result.takes = takes;
+ if (takes.failures > 0) {
+ result.failures += takes.failures;
+ result.failure_samples.push(...takes.failure_samples.slice(0, Math.max(0, 10 - result.failure_samples.length)).map(sample => `takes: ${sample}`));
+ }
+ if (opts.quiet || takes.total_stale === 0) return;
+ slog(opts.dryRun
+ ? `[dry-run] Would embed ${takes.would_embed} stale take(s)`
+ : `[embed] takes: embedded ${takes.embedded} of ${takes.total_stale} stale take(s)${takes.discarded ? `, ${takes.discarded} changed mid-flight (re-embedded next run)` : ''}`);
+}
diff --git a/src/core/embedding-migration-retention.ts b/src/core/embedding-migration-retention.ts
index 908cacd330..70ebfea28d 100644
--- a/src/core/embedding-migration-retention.ts
+++ b/src/core/embedding-migration-retention.ts
@@ -49,6 +49,11 @@ export async function assertRetainedEmbeddingRebuildability(tx: BrainEngine, dim
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 takeColumns = await tx.executeRaw<{ type: string }>(`SELECT format_type(atttypid,atttypmod) AS type
+ FROM pg_attribute WHERE attrelid='takes'::regclass AND attname='embedding' AND attnum>0 AND NOT attisdropped`);
+ if (!Array.isArray(takeColumns) || takeColumns.length !== 1 || typeof takeColumns[0].type !== 'string') throw new Error('Unknown take schema');
+ const takeWidth = Number(takeColumns[0].type.match(/^(?:vector|halfvec)\((\d+)\)$/)?.[1]);
+ if (!Number.isSafeInteger(takeWidth) || takeWidth <= 0) throw new Error('Unknown take 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'
@@ -70,7 +75,7 @@ export async function assertRetainedEmbeddingRebuildability(tx: BrainEngine, dim
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]);
+ schemaRebuild || factWidth !== dimensions || clearCompanions, schemaRebuild || takeWidth !== dimensions || clearCompanions]);
if (!row || (['pages', 'facts', 'takes'] as const).some(key => !Number.isSafeInteger(row[key]) || row[key] < 0)) {
throw new Error('Unknown retained-vector census');
}
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index bd35265192..4a4863da6b 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -240,13 +240,9 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number
* The dim-pinned TEXT-embedding-space columns outside content_chunks.
* `indexSql` is a factory because each table's index carries its own partial
* WHERE clause + opclass, and the opclass must match the column TYPE
- * (vector_cosine_ops vs halfvec_cosine_ops).
- *
- * Deliberately OMITTED: `takes.embedding` — the live takes search path
- * (`searchTakes`, both engines) is trigram-based, not vector, so that column
- * has no read path this migration could break; its own stale lane
- * (`active AND embedding IS NULL`) covers regeneration if a vector consumer
- * lands later.
+ * (vector_cosine_ops vs halfvec_cosine_ops). `takes.embedding` is searched by
+ * `searchTakesVector` (think, takes search --semantic), so it moves with the
+ * model too (#5885); the re-embed drain refills it.
*/
export const TEXT_EMBEDDING_DIM_PINNED_TABLES: ReadonlyArray<{
table: string;
@@ -269,6 +265,14 @@ export const TEXT_EMBEDDING_DIM_PINNED_TABLES: ReadonlyArray<{
ON facts USING hnsw (embedding ${opclass})
WHERE embedding IS NOT NULL AND expired_at IS NULL`,
},
+ {
+ table: 'takes',
+ index: 'idx_takes_embedding_hnsw',
+ indexSql: (opclass) =>
+ `CREATE INDEX IF NOT EXISTS idx_takes_embedding_hnsw
+ ON takes USING hnsw (embedding ${opclass})
+ WHERE active AND embedding IS NOT NULL`,
+ },
];
/**
@@ -390,8 +394,18 @@ export async function readMigrationState(
}
}
+/** #5885 plan input: stale takes against the target, with claim characters for the cost estimate. */
+async function countStaleTakeEmbeddings(engine: BrainEngine, model: string, dims: number): Promise<{ count: number; chars: number }> {
+ const count = await engine.countStaleTakes({ model, dims });
+ if (count === 0) return { count, chars: 0 };
+ const rows = await engine.listStaleTakes({ model, dims });
+ return { count, chars: rows.reduce((sum, row) => sum + row.claim.length, 0) };
+}
+
export interface EmbeddingMigrationPlan {
facts_to_embed?: number;
+ /** #5885: active takes whose vector is missing or from another model, width or claim text. */
+ takes_to_embed?: number;
blocked_projection_pages?: number;
from_model: string;
from_dims: number;
@@ -618,8 +632,9 @@ export async function planEmbeddingMigration(
}
const facts = await countStaleFactEmbeddings(engine, toModel, toDims);
+ const takes = await countStaleTakeEmbeddings(engine, toModel, toDims);
const readiness = await prepareEmbeddingProjections(engine);
- totalChars += facts.chars + falseStamped.chars;
+ totalChars += facts.chars + takes.chars + falseStamped.chars;
const price = lookupEmbeddingPrice(toModel);
const estCostUsd = price.kind === 'known'
? estimateCostFromChars(totalChars, price.pricePerMTok)
@@ -676,6 +691,7 @@ export async function planEmbeddingMigration(
return {
from_model: fromModel,
facts_to_embed: facts.count,
+ takes_to_embed: takes.count,
blocked_projection_pages: readiness.blocked,
from_dims: fromDims,
column_dims: col.dims,
@@ -718,6 +734,8 @@ export interface MigrationStatusReport {
* excluding the audit checkpoint rows extract-conversation-facts writes into
* `facts` — those are never embedded and never recalled (#4875). */
facts_pending: number | null;
+ /** #5885: active takes on live pages whose vector is missing or not from the target model/width/claim. */
+ takes_pending: number | null;
synopsis_tier_pages: number | null;
/** Stale count vs the live marker's target (else null — no target known);
* `false_stamped` (#4305) = embedded chunks hidden behind pages falsely
@@ -809,6 +827,8 @@ export async function readMigrationStatus(engine: BrainEngine): Promise<Migratio
: dbModel && dbDims && Number.isFinite(Number(dbDims))
? { model: dbModel, dims: Number(dbDims) }
: null;
+ let takesPending: number | null = null;
+ try { takesPending = await engine.countStaleTakes(target ? { model: target.model, dims: target.dims } : undefined); } catch { /* report null */ }
if (target) {
try {
factsPending = (await countStaleFactEmbeddings(engine, target.model, target.dims)).count;
@@ -853,6 +873,7 @@ export async function readMigrationStatus(engine: BrainEngine): Promise<Migratio
chunkless_pages: chunkless,
signature_census: census,
facts_pending: factsPending,
+ takes_pending: takesPending,
synopsis_tier_pages: synopsisTier,
stale_vs_target: staleVsTarget,
embed_skip_null_chunks: embedSkipNull,
@@ -964,6 +985,7 @@ export interface MigrationVerify {
blockers: string[];
details: {
stale_facts?: number;
+ stale_takes?: number;
blocked_projection_pages?: number;
column_dims: number | null;
pinned_widths: Array<{ table: string; dims: number | null }>;
@@ -999,6 +1021,8 @@ export async function verifyMigrationComplete(
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`);
+ const staleTakes = await engine.countStaleTakes({ model: target.toModel, dims: target.toDims });
+ if (staleTakes) blockers.push(`${staleTakes} active take(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
@@ -1113,6 +1137,7 @@ export async function verifyMigrationComplete(
blockers,
details: {
stale_facts: facts.count,
+ stale_takes: staleTakes,
blocked_projection_pages: readiness.blocked,
column_dims: col.dims,
pinned_widths: pinned,
diff --git a/src/core/engine-sql/takes.ts b/src/core/engine-sql/takes.ts
index 541b1a2fda..ae1e833c69 100644
--- a/src/core/engine-sql/takes.ts
+++ b/src/core/engine-sql/takes.ts
@@ -10,7 +10,7 @@
import type {
BatchOpts,
TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow,
- TakeEmbeddingInput,
+ TakeEmbeddingInput, StaleTakeOpts,
TakeResolution, SynthesisEvidenceInput,
TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,
} from '../engine.ts';
@@ -73,6 +73,10 @@ async function _addTakesBatchOnce(exec: SqlExecutor, rowsIn: TakeBatchInput[]):
since_date text, until_date text, source text, superseded_by int, active boolean
)
ON CONFLICT (page_id, row_num) DO UPDATE SET
+ embedding = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedding END,
+ embedded_at = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedded_at END,
+ embedding_model = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedding_model END,
+ embedded_text_hash = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedded_text_hash END,
claim = EXCLUDED.claim,
kind = EXCLUDED.kind,
holder = EXCLUDED.holder,
@@ -395,19 +399,37 @@ export async function getTakeEmbeddings(exec: LegacyUnscopedRead, ids: number[])
return out;
}
-export async function countStaleTakes(exec: LegacyUnscopedRead): Promise<number> {
+/**
+ * #5885 take vector lifecycle: an active take on a live page in an
+ * unarchived source is stale when it has no vector, its vector was computed
+ * from other claim text, or (when the caller names the target) another model
+ * or width produced it. Legacy vectors with no recorded provenance are stale.
+ */
+function staleTakeWhere(opts?: StaleTakeOpts) {
+ return sqlFragment`t.active
+ AND p.deleted_at IS NULL
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id = p.source_id AND NOT s.archived)
+ AND (${opts?.sourceId ?? null}::text IS NULL OR p.source_id = ${opts?.sourceId ?? null}::text)
+ AND (t.embedding IS NULL
+ OR t.embedded_text_hash IS DISTINCT FROM md5(t.claim)
+ OR (${opts?.model ?? null}::text IS NOT NULL AND t.embedding_model IS DISTINCT FROM ${opts?.model ?? null}::text)
+ OR (${opts?.dims ?? null}::int IS NOT NULL AND vector_dims(t.embedding) <> ${opts?.dims ?? null}::int))`;
+}
+
+export async function countStaleTakes(exec: LegacyUnscopedRead, opts?: StaleTakeOpts): Promise<number> {
const [row] = (await exec.run(sqlFragment`
- SELECT count(*)::int AS count FROM takes WHERE active AND embedding IS NULL
+ SELECT count(*)::int AS count FROM takes t JOIN pages p ON p.id = t.page_id
+ WHERE ${staleTakeWhere(opts)}
`)).rows;
return Number((row as { count?: number } | undefined)?.count ?? 0);
}
-export async function listStaleTakes(exec: LegacyUnscopedRead): Promise<StaleTakeRow[]> {
+export async function listStaleTakes(exec: LegacyUnscopedRead, opts?: StaleTakeOpts): Promise<StaleTakeRow[]> {
const rows = (await exec.run(sqlFragment`
SELECT t.id AS take_id, p.slug AS page_slug, t.row_num, t.claim
FROM takes t
JOIN pages p ON p.id = t.page_id
- WHERE t.active AND t.embedding IS NULL
+ WHERE ${staleTakeWhere(opts)}
ORDER BY t.id
LIMIT 100000
`)).rows;
@@ -434,25 +456,31 @@ async function _updateTakeEmbeddingsOnce(
rowsIn: TakeEmbeddingInput[],
): Promise<number> {
const seen = new Set<number>();
- const rows = rowsIn.map(({ take_id, embedding }) => {
+ const rows = rowsIn.map(({ take_id, embedding, claim, model }) => {
if (!Number.isInteger(take_id) || take_id <= 0) throw new Error(`invalid take_id: ${take_id}`);
if (seen.has(take_id)) throw new Error(`duplicate take_id in embedding batch: ${take_id}`);
seen.add(take_id);
+ if (typeof claim !== 'string' || typeof model !== 'string' || model.length === 0) {
+ throw new Error(`take embedding for take_id=${take_id} must name its claim text and model`);
+ }
const values = Array.from(embedding);
if (values.length === 0 || values.some(v => !Number.isFinite(v))) {
throw new Error(`invalid embedding for take_id=${take_id}`);
}
- return { take_id, embedding: `[${values.join(',')}]` };
+ return { take_id, embedding: `[${values.join(',')}]`, claim, model };
});
+ // The claim compare discards a vector whose row was edited while it was in flight.
const result = await executeRawJsonb(
exec,
`WITH updated AS (
UPDATE takes AS t
SET embedding = v.embedding::vector,
embedded_at = now(),
+ embedding_model = v.model,
+ embedded_text_hash = md5(v.claim),
updated_at = now()
- FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(take_id bigint, embedding text)
- WHERE t.id = v.take_id AND t.active
+ FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(take_id bigint, embedding text, claim text, model text)
+ WHERE t.id = v.take_id AND t.active AND t.claim = v.claim
RETURNING t.id
)
SELECT id FROM updated`,
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 0a2378553c..0a1293ebfc 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -330,8 +330,8 @@ export interface TakeHit {
score: number; // search rank score (ts_rank for keyword, 1-cos_dist for vector)
}
-import type { StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';
-export type { StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';
+import type { StaleTakeOpts, StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';
+export type { StaleTakeOpts, StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';
/** Resolution metadata for resolveTake. */
export interface TakeResolution {
@@ -1856,11 +1856,11 @@ export interface BrainEngine {
/** Look up embeddings by take id (mirrors getEmbeddingsByChunkIds). */
getTakeEmbeddings(ids: number[]): Promise<Map<number, Float32Array>>;
- /** Pre-flight count for `gbrain embed --stale`. WHERE active AND embedding IS NULL. */
- countStaleTakes(): Promise<number>;
+ /** Stale-take count (#5885 lifecycle: missing, claim-drifted, or, with a target, other-model/width vectors). */
+ countStaleTakes(opts?: StaleTakeOpts): Promise<number>;
/** List stale takes (no embedding column in payload — same pattern as listStaleChunks). */
- listStaleTakes(): Promise<StaleTakeRow[]>;
+ listStaleTakes(opts?: StaleTakeOpts): Promise<StaleTakeRow[]>;
/**
* Update a take's mutable fields. May NOT change claim/kind/holder per the
diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.ts
index 7d496abaa8..81fddc4a7d 100644
--- a/src/core/persistence/writer-guard-schema.ts
+++ b/src/core/persistence/writer-guard-schema.ts
@@ -28,10 +28,8 @@ 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;
+ row_data := row_data - ARRAY['embedding_model','embedded_text_hash'];
+ old_data := old_data - ARRAY['embedding_model','embedded_text_hash'];
-- 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 da51ea5fcc..d60d76eb02 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -44,7 +44,7 @@ import type {
ReservedConnection,
DreamVerdict, DreamVerdictInput,
FileSpec, FileRow,
- TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow, TakeEmbeddingInput,
+ TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow, StaleTakeOpts, TakeEmbeddingInput,
TakeResolution, SynthesisEvidenceInput,
TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,
FactRow, FactInsertStatus,
@@ -2594,12 +2594,12 @@ export class PGLiteEngine implements BrainEngine {
return takesImpl.getTakeEmbeddings(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'), ids);
}
- async countStaleTakes(): Promise<number> {
- return takesImpl.countStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'));
+ async countStaleTakes(opts?: StaleTakeOpts): Promise<number> {
+ return takesImpl.countStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'), opts);
}
- async listStaleTakes(): Promise<StaleTakeRow[]> {
- return takesImpl.listStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'));
+ async listStaleTakes(opts?: StaleTakeOpts): Promise<StaleTakeRow[]> {
+ return takesImpl.listStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'), opts);
}
async updateTakeEmbeddings(rowsIn: TakeEmbeddingInput[], opts?: BatchOpts): Promise<number> { return takesImpl.updateTakeEmbeddings(() => this.engineSql, (site, signal, fn, size) => this.batchRetry(site, signal, fn, size), rowsIn, opts); }
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 43e58690e3..010d66d54b 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1202,10 +1202,8 @@ 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;
+ row_data := row_data - ARRAY['embedding_model','embedded_text_hash'];
+ old_data := old_data - ARRAY['embedding_model','embedded_text_hash'];
-- 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/postgres-engine.ts b/src/core/postgres-engine.ts
index 8abd7b1091..0b11e47cc3 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -21,7 +21,7 @@ import type {
ReservedConnection,
DreamVerdict, DreamVerdictInput,
FileSpec, FileRow,
- TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow, TakeEmbeddingInput,
+ TakeBatchInput, Take, TakesListOpts, TakeHit, StaleTakeRow, StaleTakeOpts, TakeEmbeddingInput,
TakeResolution, SynthesisEvidenceInput,
TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,
FactRow, FactInsertStatus,
@@ -2392,12 +2392,12 @@ export class PostgresEngine implements BrainEngine {
return takesImpl.getTakeEmbeddings(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'), ids);
}
- async countStaleTakes(): Promise<number> {
- return takesImpl.countStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'));
+ async countStaleTakes(opts?: StaleTakeOpts): Promise<number> {
+ return takesImpl.countStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'), opts);
}
- async listStaleTakes(): Promise<StaleTakeRow[]> {
- return takesImpl.listStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'));
+ async listStaleTakes(opts?: StaleTakeOpts): Promise<StaleTakeRow[]> {
+ return takesImpl.listStaleTakes(unscopedExecutor(this.engineSql, 'takes: unscoped on master (EO4 inventory)'), opts);
}
async updateTakeEmbeddings(rowsIn: TakeEmbeddingInput[], opts?: BatchOpts): Promise<number> { return takesImpl.updateTakeEmbeddings(() => this.engineSql, (site, signal, fn, size) => this.batchRetry(site, signal, fn, size), rowsIn, opts); }
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 67b1e1109d..944e1621eb 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1905,10 +1905,8 @@ 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;
+ row_data := row_data - ARRAY['embedding_model','embedded_text_hash'];
+ old_data := old_data - ARRAY['embedding_model','embedded_text_hash'];
-- 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/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 300159b15b..92f0bb2203 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -191,6 +191,7 @@ import { v187 } from './v187-fact-relink-attempts.ts';
import { v188 } from './v188-facts-ontology-stint-dedup.ts';
import { v189 } from './v189-pages-credential-projection-pending.ts';
import { v190 } from './v190-alias-source-cascade.ts';
+import { v191 } from './v191-take-embedding-identity.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -380,4 +381,5 @@ export const MIGRATIONS: Migration[] = [
v188,
v189,
v190,
+ v191,
];
diff --git a/src/core/schema-migrations/v191-take-embedding-identity.ts b/src/core/schema-migrations/v191-take-embedding-identity.ts
new file mode 100644
index 0000000000..5cbe16a20d
--- /dev/null
+++ b/src/core/schema-migrations/v191-take-embedding-identity.ts
@@ -0,0 +1,19 @@
+import type { Migration } from './types.ts';
+import { MANAGED_WRITER_GUARD_SQL } from '../persistence/writer-guard-schema.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// #5885: a take vector records the model and the claim text it was computed
+// from, like facts (v166), so a model swap or a claim edit makes it stale
+// instead of silently searchable. Existing vectors keep NULL provenance and
+// count as stale until re-embedded. The writer guard treats both columns as
+// physical projection on takes too (re-installed here).
+export const v191: Migration = {
+ version: 191,
+ name: 'take_embedding_identity',
+ idempotent: true,
+ sql: `ALTER TABLE takes ADD COLUMN IF NOT EXISTS embedding_model TEXT;
+ ALTER TABLE takes ADD COLUMN IF NOT EXISTS embedded_text_hash TEXT;
+ ${MANAGED_WRITER_GUARD_SQL}`,
+};
diff --git a/src/core/takes-row-types.ts b/src/core/takes-row-types.ts
index 9aefb7c0f2..cf357b3c81 100644
--- a/src/core/takes-row-types.ts
+++ b/src/core/takes-row-types.ts
@@ -12,8 +12,24 @@ export interface StaleTakeRow {
claim: string;
}
-/** Vector write for an existing take row. */
+/**
+ * Stale-take inventory scope. `model` / `dims` widen "stale" from a missing
+ * vector to one from another model or width; `sourceId` scopes to one source.
+ */
+export interface StaleTakeOpts {
+ model?: string;
+ dims?: number;
+ sourceId?: string;
+}
+
+/**
+ * Vector write for an existing take row, bound to the claim text the vector
+ * was computed from and the model that computed it (#5885): the write is
+ * discarded when the row's claim changed in the meantime.
+ */
export interface TakeEmbeddingInput {
take_id: number;
embedding: Float32Array;
+ claim: string;
+ model: string;
}
diff --git a/src/schema.sql b/src/schema.sql
index 5b0eb10313..914cf5ac87 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1901,10 +1901,8 @@ 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;
+ row_data := row_data - ARRAY['embedding_model','embedded_text_hash'];
+ old_data := old_data - ARRAY['embedding_model','embedded_text_hash'];
-- 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/test/embedding-recovery.serial.test.ts b/test/embedding-recovery.serial.test.ts
index 3c889ab13c..3487671853 100644
--- a/test/embedding-recovery.serial.test.ts
+++ b/test/embedding-recovery.serial.test.ts
@@ -1084,9 +1084,11 @@ for (const kind of backends) {
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);
+ // #5885: takes.embedding moves with the text columns, so a raw width
+ // transition refuses to drop a retained (archived) take vector.
+ await expect(runSchemaTransition(engine, dimensions * 2)).rejects.toThrow('retained_vectors_blocked');
expect(await engine.executeRaw('SELECT embedding::text FROM takes')).toEqual(before);
- expect((await readContentChunksEmbeddingDim(engine)).dims).toBe(dimensions * 2);
+ 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'");
await runSchemaTransition(engine, dimensions);
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index ef3b84e576..8c18d45f0f 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -304,7 +304,7 @@
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
"gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9f7ebd3894599fd125d255f78ada3d945b14b15a114e340a43da0414a3de4208",
+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e35a67bb4bbcb2555e88ff14c0be82245d5090062da28cf4a63eb13150089b55",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e12c37d5489202aaf708560db42e6c0c7c8886d198d412e1c5d915c3ae782559",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1ff2515e6d6626907c0a6b660e31bd13bf51fe38fc585f7380d57ed746dc3357"
@@ -2555,7 +2555,9 @@
"20 embedded_at timestamp with time zone/timestamptz NULL",
"21 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"22 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "23 resolved_quality text/text NULL"
+ "23 resolved_quality text/text NULL",
+ "24 embedding_model text/text NULL",
+ "25 embedded_text_hash text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index eaaee9f1c9..f4c510cfa8 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -304,7 +304,7 @@
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
"gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9f7ebd3894599fd125d255f78ada3d945b14b15a114e340a43da0414a3de4208",
+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e35a67bb4bbcb2555e88ff14c0be82245d5090062da28cf4a63eb13150089b55",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e099e8a1d30bd74b7632b6055d3edffe753c00c00183e3bdac34d28d23347555",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=078bd418f597924b56e631887aaddc41d98c231b3d27c6a52a9460b0ef252dd9"
@@ -2555,7 +2555,9 @@
"20 embedded_at timestamp with time zone/timestamptz NULL",
"21 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"22 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
- "23 resolved_quality text/text NULL"
+ "23 resolved_quality text/text NULL",
+ "24 embedding_model text/text NULL",
+ "25 embedded_text_hash text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index be90ea8b67..a95e12c2ac 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -304,7 +304,7 @@
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
"gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9f7ebd3894599fd125d255f78ada3d945b14b15a114e340a43da0414a3de4208",
+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e35a67bb4bbcb2555e88ff14c0be82245d5090062da28cf4a63eb13150089b55",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e12c37d5489202aaf708560db42e6c0c7c8886d198d412e1c5d915c3ae782559",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1ff2515e6d6626907c0a6b660e31bd13bf51fe38fc585f7380d57ed746dc3357"
@@ -2551,7 +2551,9 @@
"21 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"22 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
"23 resolved_quality text/text NULL",
- "24 embedding USER-DEFINED/vector NULL"
+ "24 embedding USER-DEFINED/vector NULL",
+ "25 embedding_model text/text NULL",
+ "26 embedded_text_hash text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 1df1435835..eb1829f0e2 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -239,7 +239,7 @@
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9f7ebd3894599fd125d255f78ada3d945b14b15a114e340a43da0414a3de4208",
+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e35a67bb4bbcb2555e88ff14c0be82245d5090062da28cf4a63eb13150089b55",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8e2e253471f22c3e70b2fa2e67ba9162ee3d2c764d175cb5b674db2b907d1e9d"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index 9ef54603ca..f3bfb1840c 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -239,7 +239,7 @@
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9f7ebd3894599fd125d255f78ada3d945b14b15a114e340a43da0414a3de4208",
+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e35a67bb4bbcb2555e88ff14c0be82245d5090062da28cf4a63eb13150089b55",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3d98cc6ce4387bd742c1588ddc2133d036c7c5c8c64f7d33d1909c9ae44e73a6"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index 88aa7a6f30..21c789a397 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -239,7 +239,7 @@
"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9",
"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf",
"gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",
- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9f7ebd3894599fd125d255f78ada3d945b14b15a114e340a43da0414a3de4208",
+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e35a67bb4bbcb2555e88ff14c0be82245d5090062da28cf4a63eb13150089b55",
"gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8e2e253471f22c3e70b2fa2e67ba9162ee3d2c764d175cb5b674db2b907d1e9d"
},
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 7e00dec391..7e7f314bb6 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -381,7 +381,7 @@
},
{
"category": "meta",
- "message": "Version 190 (latest: 190)",
+ "message": "Version 191 (latest: 191)",
"name": "schema_version",
"status": "ok"
},
@@ -1034,6 +1034,28 @@
"name": "auto_chronicle",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "applicable": true,
+ "by_source": [],
+ "dims": 1024,
+ "facts": {
+ "missing": 0,
+ "other_model": 0,
+ "stale": 0
+ },
+ "model": "voyage:voyage-4",
+ "takes": {
+ "missing_or_changed": 0,
+ "other_model": 0,
+ "stale": 0
+ }
+ },
+ "message": "Every active fact and take has a voyage:voyage-4 vector for its current text.",
+ "name": "fact_take_vectors",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 174336f030..9cc63b9678 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -381,7 +381,7 @@
},
{
"category": "meta",
- "message": "Version 190 (latest: 190)",
+ "message": "Version 191 (latest: 191)",
"name": "schema_version",
"status": "ok"
},
@@ -1034,6 +1034,15 @@
"name": "auto_chronicle",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "applicable": false
+ },
+ "message": "Not applicable: embeddings are disabled on this brain (keyword search keeps working).",
+ "name": "fact_take_vectors",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 39a18f2ddf..05bfa76984 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -557,6 +557,10 @@
"category": "brain",
"name": "auto_chronicle"
},
+ {
+ "category": "brain",
+ "name": "fact_take_vectors"
+ },
{
"category": "ops",
"name": "chat_fallback_chain_inert"
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 9a3abf2f13..f9fc8d1036 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 185,
+ "count": 186,
"gaps": [
17,
18,
@@ -28,7 +28,7 @@
"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 190,
+ "latest": 191,
"records": [
{
"handler": {
@@ -2222,8 +2222,8 @@
"idempotent": true,
"name": "durable_concurrent_persistence",
"sql": {
- "length": 8821,
- "sha256": "4fa061dc870cff4ddc05a739c19cf94c22e37a6720a02d1242bae2a6566e626f"
+ "length": 8771,
+ "sha256": "2dab6c2b2b8c067470b95ee6dc9e126cc7223264bfd1e2d9dcf1124548b78614"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -2287,8 +2287,8 @@
"idempotent": true,
"name": "managed_alias_and_source_checkpoint_guards",
"sql": {
- "length": 3972,
- "sha256": "ac3822581bfef61ade30ed95eadb176c872e59fa97453ffa888d16f51ad43b6d"
+ "length": 3922,
+ "sha256": "d25f72b13d5e79d9eccb7f6b80dcf7cd5a3b9f9fe1e939beb693acfa8bb16cce"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -2446,8 +2446,8 @@
"idempotent": true,
"name": "fact_embedding_identity",
"sql": {
- "length": 4117,
- "sha256": "fa6e56fe6b112aea45c474c7025c4a7b368b20f262c6952a139773491cf90361"
+ "length": 4067,
+ "sha256": "08197d572339bb3303d318d24c021d6b97e9aa5fc77e7f6910e0bc0447f367c1"
},
"sqlFor": "absent",
"transaction": "absent",
@@ -2826,6 +2826,19 @@
"sha256": "052f104e335dfd940101c094e4d3aff16229d0ef5cf8ae59334eb9341a66d95a"
},
"version": 190
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "take_embedding_identity",
+ "sql": {
+ "length": 4067,
+ "sha256": "be92a11e45a3b9cd7fcdc51c9372daa1c362c3af99d6d827476933701bab4ddf"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 191
}
],
"versions": [
@@ -3013,7 +3026,8 @@
187,
188,
189,
- 190
+ 190,
+ 191
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 9ebbb07170..0f2896ca12 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -3993,7 +3993,7 @@
"countStaleTakes": {
"default": [
{
- "paramCount": 0,
+ "paramCount": 6,
"unsafeOptions": {
"cancelFence": false,
"prepare": true,
@@ -4126,7 +4126,7 @@
"listStaleTakes": {
"default": [
{
- "paramCount": 0,
+ "paramCount": 6,
"unsafeOptions": {
"cancelFence": false,
"prepare": true,
diff --git a/test/fixtures/goldens/sql-text/takes.json b/test/fixtures/goldens/sql-text/takes.json
index 027499f3ec..8c924f536f 100644
--- a/test/fixtures/goldens/sql-text/takes.json
+++ b/test/fixtures/goldens/sql-text/takes.json
@@ -24,8 +24,8 @@
"params": [
"object"
],
- "sql": "INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active) SELECT v.page_id, v.row_num, v.claim, v.kind, v.holder, v.weight, v.since_date, v.until_date, v.source, v.superseded_by, v.active FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v( page_id int, row_num int, claim text, kind text, holder text, weight real, since_date text, until_date text, source text, superseded_by int, active boolean ) ON CONFLICT (page_id, row_num) DO UPDATE SET claim = EXCLUDED.claim, kind = EXCLUDED.kind, holder = EXCLUDED.holder, weight = EXCLUDED.weight, since_date = EXCLUDED.since_date, until_date = EXCLUDED.until_date, source = EXCLUDED.source, superseded_by = EXCLUDED.superseded_by, active = EXCLUDED.active, updated_at = now() RETURNING 1",
- "textSha256": "1232762c3affb0b239b2c6068a6848282f02b82713a2a7d4e0b44a9b2689a01b"
+ "sql": "INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active) SELECT v.page_id, v.row_num, v.claim, v.kind, v.holder, v.weight, v.since_date, v.until_date, v.source, v.superseded_by, v.active FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v( page_id int, row_num int, claim text, kind text, holder text, weight real, since_date text, until_date text, source text, superseded_by int, active boolean ) ON CONFLICT (page_id, row_num) DO UPDATE SET embedding = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedding END, embedded_at = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedded_at END, embedding_model = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedding_model END, embedded_text_hash = CASE WHEN takes.claim IS DISTINCT FROM EXCLUDED.claim THEN NULL ELSE takes.embedded_text_hash END, claim = EXCLUDED.claim, kind = EXCLUDED.kind, holder = EXCLUDED.holder, weight = EXCLUDED.weight, since_date = EXCLUDED.since_date, until_date = EXCLUDED.until_date, source = EXCLUDED.source, superseded_by = EXCLUDED.superseded_by, active = EXCLUDED.active, updated_at = now() RETURNING 1",
+ "textSha256": "4beee891a2452a98d6f4163f8a2b6fcb0a96f1750ef67a0be8751e08e8ae0f41"
}
]
},
@@ -33,9 +33,16 @@
"default": [
{
"lane": "pool",
- "params": [],
- "sql": "SELECT count(*)::int AS count FROM takes WHERE active AND embedding IS NULL",
- "textSha256": "f418172e9208f3e264814797db037b02a3a8b8fc93d51633c58966cbbfe39cea"
+ "params": [
+ "null",
+ "null",
+ "null",
+ "null",
+ "null",
+ "null"
+ ],
+ "sql": "SELECT count(*)::int AS count FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.active AND p.deleted_at IS NULL AND EXISTS (SELECT 1 FROM sources s WHERE s.id = p.source_id AND NOT s.archived) AND ($1::text IS NULL OR p.source_id = $2::text) AND (t.embedding IS NULL OR t.embedded_text_hash IS DISTINCT FROM md5(t.claim) OR ($3::text IS NOT NULL AND t.embedding_model IS DISTINCT FROM $4::text) OR ($5::int IS NOT NULL AND vector_dims(t.embedding) <> $6::int))",
+ "textSha256": "bf015146ab51fd3f029ffd8718ae12d2f025c6535640eb8c1fc0e6fd3c7b70b5"
}
]
},
@@ -177,9 +184,16 @@
"default": [
{
"lane": "pool",
- "params": [],
- "sql": "SELECT t.id AS take_id, p.slug AS page_slug, t.row_num, t.claim FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.active AND t.embedding IS NULL ORDER BY t.id LIMIT 100000",
- "textSha256": "1826fa7f471c17386dadfb4590a734fb155ead45b8818788c8025a3b07453165"
+ "params": [
+ "null",
+ "null",
+ "null",
+ "null",
+ "null",
+ "null"
+ ],
+ "sql": "SELECT t.id AS take_id, p.slug AS page_slug, t.row_num, t.claim FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.active AND p.deleted_at IS NULL AND EXISTS (SELECT 1 FROM sources s WHERE s.id = p.source_id AND NOT s.archived) AND ($1::text IS NULL OR p.source_id = $2::text) AND (t.embedding IS NULL OR t.embedded_text_hash IS DISTINCT FROM md5(t.claim) OR ($3::text IS NOT NULL AND t.embedding_model IS DISTINCT FROM $4::text) OR ($5::int IS NOT NULL AND vector_dims(t.embedding) <> $6::int)) ORDER BY t.id LIMIT 100000",
+ "textSha256": "0529abe74d08093373e239ede128c3a8d46ed33c39ec8a63ce4e637f60c23721"
}
]
},
@@ -527,8 +541,8 @@
"params": [
"object"
],
- "sql": "WITH updated AS ( UPDATE takes AS t SET embedding = v.embedding::vector, embedded_at = now(), updated_at = now() FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(take_id bigint, embedding text) WHERE t.id = v.take_id AND t.active RETURNING t.id ) SELECT id FROM updated",
- "textSha256": "4ad900c932635917a67e63727f07e451aab97d92e159dcbdae478128d7b43765"
+ "sql": "WITH updated AS ( UPDATE takes AS t SET embedding = v.embedding::vector, embedded_at = now(), embedding_model = v.model, embedded_text_hash = md5(v.claim), updated_at = now() FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(take_id bigint, embedding text, claim text, model text) WHERE t.id = v.take_id AND t.active AND t.claim = v.claim RETURNING t.id ) SELECT id FROM updated",
+ "textSha256": "d78838acb39cf84a669f00ad4f3c7ddd1b1cc01a4962a37a12b9610b3fdc28a9"
}
]
},
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index a8d7928040..25621655e4 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -655,7 +655,7 @@ export const SQL_CASES: SqlCase[] = [
...variants('getTakeEmbeddings', [['default', (e) => e.getTakeEmbeddings([1, 2])]]),
...variants('countStaleTakes', [['default', (e) => e.countStaleTakes()]]),
...variants('listStaleTakes', [['default', (e) => e.listStaleTakes()]]),
- ...variants('updateTakeEmbeddings', [['default', (e) => e.updateTakeEmbeddings([{ take_id: 1, embedding: EMB }])]]),
+ ...variants('updateTakeEmbeddings', [['default', (e) => e.updateTakeEmbeddings([{ take_id: 1, embedding: EMB, claim: 'x', model: 'openai:text-embedding-3-large' }])]]),
...variants('updateTake', [
['default', (e) => e.updateTake(1, 1, { since_date: '2026-01-01' }), [[/UPDATE takes/, [{ id: 1 }]]]],
['weight', (e) => e.updateTake(1, 1, { weight: 0.8 }), [[/UPDATE takes/, [{ id: 1 }]]]],
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index b7b9cea3dd..ab4116a74c 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -868,6 +868,11 @@ const COLUMN_EXEMPTIONS = new Set<string>([
// migration block. Fresh installs and upgrades both get the column + index
// from the migration chain, never from the bootstrap.
'takes.embedding',
+ // takes vector provenance (#5885, take_embedding_identity): same migration-only
+ // table, no schema-blob reference; fresh installs and upgrades get both
+ // columns from the migration chain.
+ 'takes.embedding_model',
+ 'takes.embedded_text_hash',
// T7 — search_telemetry rank-1 drift columns (migration v111). search_telemetry
// is created entirely by migration v57 (not in the schema blob), so the v57+v111
// chain handles fresh + upgrade; no CREATE INDEX references these columns, so
diff --git a/test/takes-engine.test.ts b/test/takes-engine.test.ts
index 7474d7faff..bafc409375 100644
--- a/test/takes-engine.test.ts
+++ b/test/takes-engine.test.ts
@@ -403,6 +403,8 @@ describe('take embedding writes', () => {
const updated = await engine.updateTakeEmbeddings([{
take_id: take!.id,
embedding: new Float32Array(dims).fill(0.25),
+ claim: take!.claim,
+ model: 'openai:text-embedding-3-large',
}]);
expect(updated).toBe(1);
diff --git a/test/takes-vector-lifecycle-5885.serial.test.ts b/test/takes-vector-lifecycle-5885.serial.test.ts
new file mode 100644
index 0000000000..68474ffd05
--- /dev/null
+++ b/test/takes-vector-lifecycle-5885.serial.test.ts
@@ -0,0 +1,195 @@
+/**
+ * #5885 + #5188: take vectors have a full lifecycle, and doctor reports
+ * facts and takes that lack a current-model vector.
+ *
+ * Protects (O-ENG-8): a `--stale` embed drain (the cycle's embed phase and the
+ * migration drain) embeds stale takes and records the model and claim text;
+ * `takes.auto_embed=false` / GBRAIN_EMBED_TAKES=0 turn that off; a claim edit
+ * clears the vector; a vector computed for a claim that changed in flight is
+ * discarded; a same-width model swap and a width change make take vectors
+ * stale and the migration plan, verify and schema transition include takes;
+ * takes on deleted pages or archived sources are not work; a managed brain
+ * accepts the embedding write without a coordinated grant; doctor's
+ * fact_take_vectors check warns with counts and fixes, and is "not
+ * applicable" on a keyless brain.
+ * Fails when: takes are embedded only by `gbrain takes embed`, vectors carry
+ * no provenance, or the migration ignores takes.
+ * Installs the process-global gateway transport seam, so this stays serial.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { embedStaleTakes } from '../src/core/embed-takes.ts';
+import { EMBED_PROBE_TEXT } from '../src/core/embed-stale.ts';
+import { planEmbeddingMigration, readDimPinnedWidths, runSchemaTransition, verifyMigrationComplete } from '../src/core/embedding-migration.ts';
+import { factTakeVectorsEntry } from '../src/commands/doctor/checks/vector-coverage.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const DIMS = 1536;
+const MODEL = 'openai:text-embedding-3-large';
+const OTHER_MODEL = 'openai:text-embedding-3-small';
+let embedded: string[] = [];
+
+const gateway = (model: string) => configureGateway({ embedding_model: model, embedding_dimensions: DIMS, env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' } });
+
+beforeAll(() => {
+ gateway(MODEL);
+ __setEmbedTransportForTests((async (input: { values: string[] }) => {
+ embedded.push(...input.values.filter(v => v !== EMBED_PROBE_TEXT));
+ return { embeddings: input.values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: input.values.length * 4 } };
+ }) as never);
+});
+afterAll(() => { __setEmbedTransportForTests(null); resetGateway(); });
+
+type Row = { row_num: number; claim: string; has_vector: boolean; embedding_model: string | null; hash_ok: boolean | null };
+async function takeRows(engine: BrainEngine, slug: string): Promise<Row[]> {
+ return engine.executeRaw<Row>(
+ `SELECT t.row_num, t.claim, t.embedding IS NOT NULL AS has_vector, t.embedding_model, t.embedded_text_hash = md5(t.claim) AS hash_ok
+ FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.slug = $1 ORDER BY t.row_num`, [slug]);
+}
+async function seedTakes(engine: BrainEngine, slug: string, claims: string[], sourceId = 'default'): Promise<number> {
+ const page = await engine.putPage(slug, { type: 'person', title: slug, compiled_truth: `# ${slug}` }, { sourceId });
+ await engine.addTakesBatch(claims.map((claim, i) => ({ page_id: page.id, row_num: i + 1, claim, kind: 'bet', holder: 'world',
+ weight: 0.5, active: true, superseded_by: null })));
+ return page.id;
+}
+const doctor = async (engine: BrainEngine) =>
+ (await factTakeVectorsEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[])[0];
+
+for (const backend of testBackends()) describe(`#5885 take vector lifecycle (${backend})`, () => {
+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(requirePostgresTestDatabase()));
+ else { engine = new PGLiteEngine(); await engine.connect({ embedding_model: MODEL, embedding_dimensions: DIMS } as never); await engine.initSchema(); }
+ await engine.setConfig('embedding_model', MODEL);
+ await engine.setConfig('embedding_dimensions', String(DIMS));
+ }, 120_000);
+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });
+ beforeEach(async () => {
+ embedded = [];
+ gateway(MODEL);
+ await engine.executeRaw('DELETE FROM takes');
+ await engine.unsetConfig('takes.auto_embed');
+ });
+
+ test('an embed --stale drain embeds stale takes with provenance; the opt-out skips them', async () => {
+ await seedTakes(engine, 'people/alice-example', ['Widget co ships in Q3', 'Acme example hires a CFO']);
+ await engine.setConfig('takes.auto_embed', 'false');
+ const off = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(off.takes).toBeUndefined();
+ await withEnv({ GBRAIN_EMBED_TAKES: '0' }, async () => {
+ await engine.unsetConfig('takes.auto_embed');
+ expect((await runEmbedCore(engine, { stale: true, quiet: true })).takes).toBeUndefined();
+ });
+ expect((await takeRows(engine, 'people/alice-example')).every(r => !r.has_vector)).toBe(true);
+
+ const preview = await runEmbedCore(engine, { stale: true, dryRun: true, quiet: true });
+ expect(preview.takes).toMatchObject({ would_embed: 2, embedded: 0 });
+ embedded = [];
+ const live = await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(live.takes).toMatchObject({ total_stale: 2, embedded: 2, failures: 0 });
+ expect(embedded.sort()).toEqual(['Acme example hires a CFO', 'Widget co ships in Q3']);
+ expect(await takeRows(engine, 'people/alice-example')).toEqual([
+ { row_num: 1, claim: 'Widget co ships in Q3', has_vector: true, embedding_model: MODEL, hash_ok: true },
+ { row_num: 2, claim: 'Acme example hires a CFO', has_vector: true, embedding_model: MODEL, hash_ok: true },
+ ]);
+ embedded = [];
+ expect((await runEmbedCore(engine, { stale: true, quiet: true })).takes).toMatchObject({ total_stale: 0 });
+ expect(embedded).toEqual([]);
+ });
+
+ test('a claim edit clears the vector; a vector for a claim edited in flight is discarded', async () => {
+ const pageId = await seedTakes(engine, 'people/bob-example', ['Widget co ships in Q3']);
+ await embedStaleTakes(engine, {});
+ expect((await takeRows(engine, 'people/bob-example'))[0].has_vector).toBe(true);
+ const edit = (claim: string) => engine.addTakesBatch([{ page_id: pageId, row_num: 1, claim, kind: 'bet', holder: 'world', weight: 0.5, active: true, superseded_by: null }]);
+ await edit('Widget co ships in Q3');
+ expect((await takeRows(engine, 'people/bob-example'))[0].has_vector).toBe(true);
+ await edit('Widget co ships in Q4');
+ expect((await takeRows(engine, 'people/bob-example'))[0]).toMatchObject({ has_vector: false, embedding_model: null });
+
+ const raced = await embedStaleTakes(engine, { embedFn: async texts => {
+ await edit('Widget co ships next year');
+ return texts.map(() => new Float32Array(DIMS).fill(0.002));
+ } });
+ expect(raced).toMatchObject({ total_stale: 1, embedded: 0, discarded: 1, failures: 0 });
+ expect((await takeRows(engine, 'people/bob-example'))[0]).toMatchObject({ claim: 'Widget co ships next year', has_vector: false });
+ });
+
+ test('takes on deleted pages and archived sources are not stale work', async () => {
+ await seedTakes(engine, 'people/live-example', ['Live claim']);
+ const gone = await seedTakes(engine, 'people/gone-example', ['Deleted page claim']);
+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [gone]);
+ await engine.executeRaw(`INSERT INTO sources (id, name, archived) VALUES ('archived-example', 'archived-example', true) ON CONFLICT (id) DO NOTHING`);
+ await seedTakes(engine, 'people/archived-example', ['Archived source claim'], 'archived-example');
+ expect((await engine.listStaleTakes({ model: MODEL, dims: DIMS })).map(t => t.claim)).toEqual(['Live claim']);
+ await engine.executeRaw('UPDATE pages SET deleted_at = NULL WHERE id = $1', [gone]);
+ });
+
+ test('a same-width model swap makes take vectors stale, and plan/verify count them', async () => {
+ await seedTakes(engine, 'people/carol-example', ['Acme example raised a seed round']);
+ await embedStaleTakes(engine, {});
+ expect(await engine.countStaleTakes({ model: MODEL, dims: DIMS })).toBe(0);
+ expect(await engine.countStaleTakes({ model: OTHER_MODEL, dims: DIMS })).toBe(1);
+ expect((await planEmbeddingMigration(engine, { to: OTHER_MODEL, dim: DIMS })).takes_to_embed).toBe(1);
+ const verify = await verifyMigrationComplete(engine, { toModel: OTHER_MODEL, toDims: DIMS }, { ignoreMarker: true });
+ expect(verify.blockers).toContain('1 active take(s) not in the target embedding space');
+ expect(verify.details.stale_takes).toBe(1);
+
+ gateway(OTHER_MODEL);
+ const result = await runEmbedCore(engine, { stale: true, takes: true, quiet: true });
+ expect(result.takes).toMatchObject({ embedded: 1 });
+ expect((await takeRows(engine, 'people/carol-example'))[0].embedding_model).toBe(OTHER_MODEL);
+ });
+
+ test('doctor fact_take_vectors warns with counts and fixes, then clears', async () => {
+ await seedTakes(engine, 'people/dana-example', ['Acme example opens an office']);
+ const warn = await doctor(engine);
+ expect(warn).toMatchObject({ name: 'fact_take_vectors', status: 'warn', details: { code: 'stale_vectors', takes: { stale: 1, missing_or_changed: 1, other_model: 0 } } });
+ expect((warn.details!.fix as string[])).toContain('gbrain embed --stale');
+ await embedStaleTakes(engine, {});
+ expect(await doctor(engine)).toMatchObject({ details: { takes: { stale: 0 } } });
+ await engine.setConfig('embedding_model', OTHER_MODEL);
+ expect(await doctor(engine)).toMatchObject({ status: 'warn', details: { takes: { stale: 1, other_model: 1 } } });
+ await engine.setConfig('embedding_model', MODEL);
+ await engine.setConfig('embedding_disabled', 'true');
+ expect(await doctor(engine)).toMatchObject({ status: 'ok', details: { applicable: false } });
+ await engine.unsetConfig('embedding_disabled');
+ });
+
+ test('a width change resizes takes.embedding with the other text-embedding columns', async () => {
+ await seedTakes(engine, 'people/erin-example', ['Widget co hires a CTO']);
+ await embedStaleTakes(engine, {});
+ await runSchemaTransition(engine, 768);
+ expect((await readDimPinnedWidths(engine)).find(p => p.table === 'takes')).toEqual({ table: 'takes', dims: 768 });
+ expect(await engine.countStaleTakes({ model: MODEL, dims: 768 })).toBe(1);
+ await runSchemaTransition(engine, DIMS);
+ });
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ test(`${backend}: a managed brain accepts take embedding writes without a coordinated grant`, async () => {
+ await managedBrain(async ({ engine }) => {
+ const takeId = await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.write_sources', $1, true)", [JSON.stringify(['default'])]);
+ const page = await tx.putPage('people/frank-example', { type: 'person', title: 'Frank', compiled_truth: '# Frank' });
+ await tx.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Widget co expands', kind: 'bet', holder: 'world', weight: 0.5, active: true, superseded_by: null }]);
+ const [take] = await tx.executeRaw<{ id: number }>('SELECT id FROM takes WHERE page_id = $1', [page.id]);
+ return Number(take.id);
+ });
+ const [col] = await engine.executeRaw<{ f: string }>(`SELECT format_type(atttypid, atttypmod) AS f FROM pg_attribute WHERE attrelid = 'takes'::regclass AND attname = 'embedding'`);
+ const width = Number(col.f.match(/\((\d+)\)/)![1]);
+ expect(await engine.updateTakeEmbeddings([{ take_id: takeId, embedding: new Float32Array(width).fill(0.003), claim: 'Widget co expands', model: MODEL }])).toBe(1);
+ const [row] = await engine.executeRaw<{ embedding_model: string }>('SELECT embedding_model FROM takes WHERE id = $1', [takeId]);
+ expect(row.embedding_model).toBe(MODEL);
+ }, { databaseUrl });
+ }, 120_000);
+}