Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

embedding state: active-column classifier in engine-sql/chunks.ts and readEmbeddingState (#6696 B3)

garrytanfcff365275c6
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ba331f52a7..3381df626f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 525 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3303 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts)
src/core/cycle/synthesize.ts 3228 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; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1654 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; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +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; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
-src/core/engine.ts 2787 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; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts)
+src/core/engine.ts 2792 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; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts)
src/core/import-file.ts 2027 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); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 240 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; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)
-src/core/pglite-engine.ts 3026 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts)
-src/core/postgres-engine.ts 3042 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); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured)
+src/core/pglite-engine.ts 3037 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +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); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import
+src/core/postgres-engine.ts 3053 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); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import
src/core/search/hybrid.ts 1648 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)
src/core/types.ts 2304 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/core/embedding-state.ts b/src/core/embedding-state.ts
new file mode 100644
index 0000000000..8caa41940a
--- /dev/null
+++ b/src/core/embedding-state.ts
@@ -0,0 +1,232 @@
+/**
+ * Embedding state, derived (#6696 B3): where every piece of indexed text
+ * stands against the registry-ACTIVE embedding column, read from the rows
+ * themselves (no stored status column, no migration).
+ *
+ * Unit: one `content_chunks` row, plus one unit per page that has no chunk
+ * row. Each unit is in exactly one state; the classifier SQL lives once in
+ * `src/core/engine-sql/chunks.ts` (`chunkEmbeddingState` /
+ * `chunklessPageState`, next to `staleChunkWhere`) and both engines delegate
+ * to it. Precedence for a chunk: deleted page, quarantined page, stored
+ * vector, embed job predicate, else embed_skip. For a chunkless live page:
+ * quarantined, embed_skip, healable body, else empty.
+ *
+ * - `embedded`: a chunk on a live, unquarantined page whose active column
+ * holds a vector (vectors retained on an embed_skip page count: vector
+ * search reads them).
+ * - `pending`: a chunk the embed job selects (`staleChunkWhere`: active vector
+ * NULL, page live, no `embed_skip`) on an unquarantined page.
+ * `gbrain embed --stale` drains it. On a brain keyless by choice keyword
+ * search is the configured retrieval and reads these chunks, so they are
+ * not counted as unsearchable there.
+ * - `keyword_only`: a chunk with no vector on a live `embed_skip` page, or an
+ * `embed_skip` page with no chunk rows. By design (#4306: never purged; its
+ * text feeds keyword search). The import gate sets the marker for a body
+ * over the effective `content_sanity.bytes_block`, so removing the marker
+ * alone is undone on the next import; the exits are splitting the page or
+ * an operator-approved threshold override followed by a re-import.
+ * - `quarantined`: the chunks of a live page carrying the `quarantine` marker,
+ * or the page itself when it has none (the gate writes zero chunks). Hidden
+ * from search; doctor `quarantined_pages` owns the warning.
+ * - `empty`: a live page with no chunk rows and an empty body
+ * (`compiled_truth` and `timeline` both ''): nothing to index.
+ * - `deleted_page_chunks`: chunks on a soft-deleted page. The purge lifecycle
+ * (`gbrain pages purge-deleted`, the autopilot purge phase, 72 h) removes
+ * them; past that window they are overdue.
+ * - `chunkless_healable`: a live page with body text, no markers and no chunk
+ * rows (`listChunklessPagesWithContent`'s predicate): `gbrain embed --stale`
+ * chunks it before embedding.
+ *
+ * Unstamped pending chunks (`embedding_pending_since` NULL: written by a binary
+ * older than the v221 stamp) carry no age; the summary reports their count,
+ * this writer's version and a `created_at` lower bound, and never warns on it.
+ */
+import type { BrainEngine } from './engine.ts';
+import type { Action } from './agent-output.ts';
+import { embeddingsDisabled } from './embedding-disabled.ts';
+import { SOFT_DELETE_TTL_HOURS } from './destructive-guard.ts';
+import { DEFAULT_BYTES_BLOCK } from './content-sanity.ts';
+import { loadConfig } from './config.ts';
+import { embeddingEnablement } from './readiness.ts';
+import { VERSION } from '../version.ts';
+
+export type EmbeddingState = 'embedded' | 'pending' | 'keyword_only' | 'quarantined' | 'empty' | 'deleted_page_chunks' | 'chunkless_healable';
+
+export { EMBEDDING_STATES } from './engine-sql/chunks.ts';
+
+/** The states `unsearchable` sums (pending drops out on a brain keyless by choice). */
+export const UNSEARCHABLE_STATES: readonly EmbeddingState[] = ['pending', 'quarantined', 'empty', 'chunkless_healable'];
+
+/** Hours a soft-deleted page waits before the purge lifecycle removes it (`pages purge-deleted` default). */
+export const DELETED_PAGE_PURGE_WINDOW_HOURS = SOFT_DELETE_TTL_HOURS;
+
+export const EMBEDDING_STATE_DOCS = 'docs/guides/troubleshooting.md#embedding-state';
+
+/** What the engine's classifier returns (`BrainEngine.readEmbeddingStateCounts`). */
+export interface EmbeddingStateCounts {
+ active_column: string;
+ /** `unknown` only in ops mode without a covering partial index on the active column. */
+ basis: 'exact' | 'estimated' | 'unknown';
+ /** The partial index (`WHERE <active column> IS NULL`) ops mode reads through; null when none (or full mode). */
+ covering_index: string | null;
+ counts: Partial<Record<EmbeddingState, number>>;
+ /** States this mode does not count (ops: the anti-join states no index backs). */
+ omitted: EmbeddingState[];
+ /** Embedded chunks on pages the embed job serves (no embed_skip); null in ops mode. */
+ eligible_embedded: number | null;
+ deleted_overdue: number;
+ embed_skip_pages: number;
+ embed_skip_marker_bytes: number;
+ unstamped_pending: number;
+ unstamped_created_at_min: Date | null;
+}
+
+/** One `(page, state)` row (`BrainEngine.listEmbeddingStateRows`). */
+export interface EmbeddingStateRow {
+ slug: string;
+ source_id: string;
+ state: EmbeddingState;
+ chunks: number;
+ /** Chunk text bytes, or the body bytes of a page with no chunk rows. */
+ bytes: number;
+ embed_skip_reason: string | null;
+ marker_bytes: number | null;
+ quarantine_reason: string | null;
+ deleted_at: Date | null;
+ overdue: boolean;
+}
+
+export interface EmbeddingStateSummary {
+ status: 'known' | 'unknown';
+ basis: 'exact' | 'estimated' | 'unknown';
+ reason?: string;
+ active_column: string;
+ counts: Partial<Record<EmbeddingState, number>>;
+ /** pending + quarantined + empty + chunkless_healable (never keyword_only or deleted_page_chunks); null when unknown. */
+ unsearchable: number | null;
+ [k: string]: unknown;
+}
+
+/**
+ * The brain's embedding state. `mode: 'ops'` counts only what an index backs
+ * (Postgres and PGLite alike: the covering partial index for the active
+ * column, the frontmatter GIN index, the deleted-at purge index; `embedded` is
+ * a planner estimate) and reports `status: 'unknown'` with
+ * `reason: 'no_covering_index'` rather than scan; `empty` and
+ * `chunkless_healable` are omitted there (`unsearchable_complete: false`).
+ * `mode: 'full'` counts every state exactly. `sourceIds` is the caller's
+ * resolved scope (sourceScopeOpts); absent means brain-wide.
+ */
+export async function readEmbeddingState(engine: BrainEngine, opts: { mode: 'ops' | 'full'; sourceIds?: string[] }): Promise<EmbeddingStateSummary> {
+ const raw = await engine.readEmbeddingStateCounts({ mode: opts.mode, sourceIds: opts.sourceIds, purgeWindowHours: DELETED_PAGE_PURGE_WINDOW_HOURS });
+ if (raw.basis === 'unknown') {
+ return { status: 'unknown', basis: 'unknown', reason: 'no_covering_index', active_column: raw.active_column, counts: {}, unsearchable: null, mode: opts.mode };
+ }
+ const disabled = await embeddingsDisabled(engine);
+ const parts = UNSEARCHABLE_STATES.filter(state => !(disabled && state === 'pending'));
+ const counts = raw.counts;
+ const pending = counts.pending ?? 0;
+ const threshold = await effectiveBlockThreshold(engine);
+ return {
+ status: 'known',
+ basis: raw.basis,
+ ...(disabled ? { reason: 'embeddings_disabled' } : {}),
+ active_column: raw.active_column,
+ counts,
+ unsearchable: parts.reduce((sum, state) => sum + (counts[state] ?? 0), 0),
+ unsearchable_complete: parts.every(state => counts[state] !== undefined),
+ omitted_states: raw.omitted,
+ mode: opts.mode,
+ embeddings_enabled: !disabled,
+ units: 'content_chunks rows, plus one unit per page with no chunk rows',
+ covering_index: raw.covering_index,
+ coverage: raw.eligible_embedded === null
+ ? { basis: 'estimated', ratio: ratio(counts.embedded, pending) }
+ : { basis: 'exact', embedded: raw.eligible_embedded, eligible: raw.eligible_embedded + pending, ratio: ratio(raw.eligible_embedded, pending) },
+ keyword_only: { reason: 'embed_skip', pages: raw.embed_skip_pages, marker_bytes: raw.embed_skip_marker_bytes, threshold_bytes: threshold },
+ deleted_page_chunks: { within_window: (counts.deleted_page_chunks ?? 0) - raw.deleted_overdue, past_window: raw.deleted_overdue, window_hours: DELETED_PAGE_PURGE_WINDOW_HOURS },
+ unstamped_pending: { count: raw.unstamped_pending, created_at_lower_bound: raw.unstamped_created_at_min?.toISOString() ?? null, writer_version: VERSION },
+ };
+}
+
+function ratio(embedded: number | undefined, pending: number): number | null {
+ const total = (embedded ?? 0) + pending;
+ return total === 0 ? null : Math.round(((embedded ?? 0) / total) * 10_000) / 10_000;
+}
+
+/** The effective `content_sanity.bytes_block` the import gate applies (env > file > DB > default). */
+async function effectiveBlockThreshold(engine: BrainEngine): Promise<number> {
+ try {
+ const { loadImportSanityConfig } = await import('./import-screen.ts');
+ const configured = (await loadImportSanityConfig(engine)).cs.bytes_block;
+ return typeof configured === 'number' && configured > 0 ? configured : DEFAULT_BYTES_BLOCK;
+ } catch {
+ return DEFAULT_BYTES_BLOCK;
+ }
+}
+
+/** `gbrain pages unsearchable` for one state: the read-only check every fix verifies with. */
+export function embeddingStateVerify(sourceId: string, state: EmbeddingState): { argv: string[] } {
+ return { argv: ['gbrain', 'pages', 'unsearchable', '--source', sourceId, '--state', state, '--json'] };
+}
+
+/**
+ * The exit for one state, built only from existing commands (agent operator
+ * protocol: argv, consent, actor, why, requires_exclusive, read-only verify,
+ * docs). Null for `embedded`, which needs none.
+ */
+export function embeddingStateFix(state: EmbeddingState, ctx: { sourceId: string; slug?: string; markerBytes?: number | null; embeddingsEnabled: boolean; verify?: { argv: string[] } }): Action | null {
+ const verify = ctx.verify ?? embeddingStateVerify(ctx.sourceId, state);
+ const base = { verify, docs: EMBEDDING_STATE_DOCS, requires_exclusive: false };
+ const source = ['--source', ctx.sourceId];
+ switch (state) {
+ case 'embedded':
+ return null;
+ case 'pending':
+ case 'chunkless_healable': {
+ if (!ctx.embeddingsEnabled) return keylessFix(verify);
+ const run = ['gbrain', 'embed', '--stale', '--catch-up', ...source];
+ return { ...base, argv: [...run, '--yes'], preview_argv: [...run, '--dry-run'], consent: ['paid'], actor: 'agent',
+ why: state === 'pending'
+ ? 'These chunks have no vector in the active embedding column, so vector search cannot see them. The catch-up drain embeds them; it sends their text to the embedding provider and costs money.'
+ : 'These pages have body text but no chunk rows, so neither keyword nor vector search can read their body. `embed --stale` chunks them first, then embeds the new chunks; it sends their text to the embedding provider and costs money.',
+ user_message: 'Some notes are not indexed for search yet. Indexing them sends their text to your embedding provider and costs a little money. OK to run it?' };
+ }
+ case 'keyword_only': {
+ const threshold = ctx.markerBytes && ctx.markerBytes > 0 ? String(ctx.markerBytes + 1) : null;
+ const why = 'The import gate marked this page embed_skip because its body exceeds content_sanity.bytes_block; keyword search still reads its chunks. Removing the marker alone is undone on the next import. Two exits: split the page into smaller pages, or raise the threshold (a brain-wide setting the operator approves) and re-import, which embeds it.';
+ const reimport: Action = { ...base, argv: ['gbrain', 'sync', ...source, '--full'], consent: ['paid'], actor: 'agent',
+ why: 'Re-imports the source so the gate re-assesses the page under the new threshold, drops the marker and embeds the page.' };
+ if (!threshold) return { ...base, ask_user: true, argv: ['gbrain', 'config', 'get', 'content_sanity.bytes_block'], consent: [], actor: 'user', why,
+ user_message: 'An oversized page is searchable by keyword only. Split it into smaller pages, or raise the size limit for embedding and re-import it?' };
+ return { ...base, ask_user: true, argv: ['gbrain', 'config', 'set', 'content_sanity.bytes_block', threshold], consent: [], actor: 'user', why,
+ user_message: `A page of ${ctx.markerBytes} bytes is searchable by keyword only. Split it into smaller pages, or raise the size limit for embedding to ${threshold} bytes and re-import it (embedding costs a little money)?`,
+ then: reimport };
+ }
+ case 'quarantined':
+ return { ...base, ask_user: true, argv: ctx.slug ? ['gbrain', 'quarantine', 'clear', ctx.slug, '--source-id', ctx.sourceId, '--force'] : ['gbrain', 'quarantine', 'list', '--json'],
+ preview_argv: ['gbrain', 'quarantine', 'list', '--json'], consent: ctx.slug ? ['paid'] : [], actor: 'user',
+ why: 'The content-quality gate hid this page as junk, so it has no searchable chunks. Clearing is the owner\'s judgement for a false positive; it re-imports and embeds the page.',
+ user_message: 'A page was hidden from search as junk. Review it and clear it if it is a false positive?' };
+ case 'empty':
+ return { ...base, ask_user: true, argv: ctx.slug ? ['gbrain', 'delete', ctx.slug, '--source', ctx.sourceId, '--force'] : ['gbrain', 'list', '--json'],
+ consent: ['destructive'], actor: 'user',
+ why: 'The page has no body text, so there is nothing to index. Writing content to it chunks it on the next write; delete it only if it is a stub nobody needs (soft delete, restorable).',
+ user_message: 'A page is empty, so there is nothing to search. Add content to it, or delete the empty stub?' };
+ case 'deleted_page_chunks':
+ return { ...base, argv: ['gbrain', 'pages', 'purge-deleted', '--yes'], preview_argv: ['gbrain', 'pages', 'purge-deleted', '--dry-run', '--json'],
+ consent: ['destructive'], actor: 'agent',
+ why: `These chunks belong to soft-deleted pages; search never reads them. The purge lifecycle hard-deletes pages soft-deleted more than ${DELETED_PAGE_PURGE_WINDOW_HOURS}h ago (brain-wide, irreversible), taking their chunks with them.` };
+ }
+}
+
+function keylessFix(verify: { argv: string[] }): Action {
+ try {
+ const cfg = loadConfig();
+ if (cfg) {
+ return { ...embeddingEnablement(cfg), verify, docs: EMBEDDING_STATE_DOCS };
+ }
+ } catch { /* unreadable config: the read-only fallback below */ }
+ return { argv: ['gbrain', 'doctor', '--only', 'embeddings', '--json'], consent: [], actor: 'agent', verify, docs: EMBEDDING_STATE_DOCS, requires_exclusive: false,
+ why: 'Embeddings are disabled on this brain by choice; keyword search reads these chunks. The embeddings check names the command that turns embeddings on, if the user wants them.' };
+}
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 01d96262e0..31dae85d54 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -20,6 +20,7 @@
import type { PageKey, PageSnapshot, PageSnapshotOptions } from '../page-state/types.ts';
import { assertPageRevision } from '../page-state/types.ts';
import type { BrainEngine } from '../engine.ts';
+import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from '../embedding-state.ts';
import type { Chunk, ChunkInput, ChunklessPageRow, ResolvedColumn, StaleChunkRow } from '../types.ts';
import { rowToChunk, validateSlug } from '../utils.ts';
import { sanitizeText } from '../batch-rows.ts';
@@ -42,6 +43,7 @@ import type { SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';
import { joinFragments, renderFragment, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';
import { pipelined } from '../page-state/transactions.ts';
+import { compileRowNormalizer } from './normalize.ts';
/** The engine's page-state guards, run on the same (transaction) engine. */
export interface ChunkPageGuards {
@@ -655,6 +657,184 @@ export async function listChunklessPagesWithContent(exec: ScopedRead, opts?: {
}));
}
+/** Every embedding state, in report order (re-exported by src/core/embedding-state.ts). */
+export const EMBEDDING_STATES: readonly EmbeddingState[] = ['embedded', 'pending', 'keyword_only', 'quarantined', 'empty', 'deleted_page_chunks', 'chunkless_healable'];
+
+/**
+ * #6696 B3 embedding-state classifier (contract in src/core/embedding-state.ts).
+ * A chunk's state, by precedence: soft-deleted page, quarantined page, a
+ * vector in the ACTIVE column, the embed job's own predicate
+ * (`staleChunkWhere`, so `pending` can never drift from what `embed --stale`
+ * selects), else a vector-less chunk on an embed_skip page.
+ */
+function chunkEmbeddingState(column: string): SqlFragment {
+ const colRef = trustedSql(`cc.${quoteIdentifier(column)}`);
+ return sqlFragment`CASE
+ WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks'
+ WHEN NOT ${trustedSql(QUARANTINE_FILTER_FRAGMENT)} THEN 'quarantined'
+ WHEN ${colRef} IS NOT NULL THEN 'embedded'
+ WHEN ${staleChunkWhere(column)} THEN 'pending'
+ ELSE 'keyword_only' END`;
+}
+
+/** A live page with no chunk row: gated (quarantine, embed_skip), healable (`chunklessPagesWhere`), else empty. */
+function chunklessPageState(): SqlFragment {
+ return sqlFragment`CASE
+ WHEN NOT ${trustedSql(QUARANTINE_FILTER_FRAGMENT)} THEN 'quarantined'
+ WHEN NOT ${trustedSql(EMBED_SKIP_FILTER_FRAGMENT)} THEN 'keyword_only'
+ WHEN ${chunklessPagesWhere()} THEN 'chunkless_healable'
+ ELSE 'empty' END`;
+}
+
+function embeddingStateScope(sourceIds?: string[]): SqlFragment {
+ return sourceIds ? sqlFragment` AND p.source_id = ANY(${sourceIds}::text[])` : sqlFragment``;
+}
+
+const NO_CHUNK_ROWS = sqlFragment`NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)`;
+const MARKER_BYTES = sqlFragment`CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number'
+ THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END`;
+
+const normalizeStateCount = compileRowNormalizer<{ state: EmbeddingState; n: number; eligible: number; overdue: number; unstamped: number; unstamped_min: Date | null }>(
+ { n: 'bigint', eligible: 'bigint', overdue: 'bigint', unstamped: 'bigint', unstamped_min: 'date' });
+const normalizeEmbedSkip = compileRowNormalizer<{ pages: number; marker_bytes: number; chunkless: number }>({ pages: 'bigint', marker_bytes: 'bigint', chunkless: 'bigint' });
+
+/**
+ * Counts per embedding state. `full`: two exact aggregates (every chunk, every
+ * chunkless live page). `ops`: only index-backed reads, and `basis: 'unknown'`
+ * when no valid partial index on content_chunks has the predicate
+ * `<active column> IS NULL` (never a slow scan): the vector-less chunks through
+ * that index, quarantined and embed_skip pages through the frontmatter GIN
+ * index, deleted pages through the purge index, and `embedded` as the
+ * planner's row estimate; `empty` and `chunkless_healable` need an anti-join
+ * over every live page and are omitted.
+ */
+export async function readEmbeddingStateCounts(exec: ScopedRead, column: string,
+ opts: { mode: 'ops' | 'full'; sourceIds?: string[]; purgeWindowHours: number }): Promise<EmbeddingStateCounts> {
+ const scope = embeddingStateScope(opts.sourceIds);
+ const colRef = trustedSql(`cc.${quoteIdentifier(column)}`);
+ let coveringIndex: string | null = null;
+ if (opts.mode === 'ops') {
+ const { rows } = await exec.run<{ name: string }>(sqlFragment`
+ SELECT ic.relname AS name
+ FROM pg_index i
+ JOIN pg_class ic ON ic.oid = i.indexrelid
+ JOIN pg_class t ON t.oid = i.indrelid
+ JOIN pg_namespace n ON n.oid = t.relnamespace
+ WHERE t.relname = 'content_chunks' AND n.nspname = current_schema()
+ AND i.indisvalid AND i.indpred IS NOT NULL
+ AND pg_get_expr(i.indpred, i.indrelid) = '(' || quote_ident(${column}) || ' IS NULL)'
+ ORDER BY ic.relname LIMIT 1`);
+ coveringIndex = rows[0]?.name ?? null;
+ if (!coveringIndex) {
+ return { active_column: column, basis: 'unknown', covering_index: null, counts: {}, omitted: [], eligible_embedded: null,
+ deleted_overdue: 0, embed_skip_pages: 0, embed_skip_marker_bytes: 0, unstamped_pending: 0, unstamped_created_at_min: null };
+ }
+ }
+ const counts: Partial<Record<EmbeddingState, number>> = {};
+ const add = (state: EmbeddingState, n: number) => { counts[state] = (counts[state] ?? 0) + n; };
+ const overdue = sqlFragment`(p.deleted_at < now() - make_interval(hours => ${opts.purgeWindowHours}::int))`;
+ const aggregate = (where: SqlFragment) => exec.run(sqlFragment`
+ SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible,
+ count(*) FILTER (WHERE s.overdue)::bigint AS overdue,
+ count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped,
+ min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min
+ FROM (SELECT ${chunkEmbeddingState(column)} AS state, ${trustedSql(EMBED_SKIP_FILTER_FRAGMENT)} AS eligible,
+ COALESCE(${overdue}, false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE ${where}${scope}) s
+ GROUP BY s.state`);
+ const chunkRows = (await aggregate(opts.mode === 'ops' ? sqlFragment`${colRef} IS NULL` : sqlFragment`TRUE`)).rows.map(row => normalizeStateCount(row));
+ let pendingUnstamped = 0;
+ let unstampedMin: Date | null = null;
+ let eligibleEmbedded = 0;
+ let deletedOverdue = 0;
+ for (const row of chunkRows) {
+ if (row.state === 'pending') { pendingUnstamped = row.unstamped; unstampedMin = row.unstamped_min; }
+ if (row.state === 'embedded') eligibleEmbedded = row.eligible;
+ if (opts.mode === 'ops' && (row.state === 'quarantined' || row.state === 'deleted_page_chunks')) continue;
+ if (row.state === 'deleted_page_chunks') deletedOverdue = row.overdue;
+ add(row.state, row.n);
+ }
+ const embedSkip = normalizeEmbedSkip((await exec.run(sqlFragment`
+ SELECT count(*)::bigint AS pages, COALESCE(sum(${MARKER_BYTES}), 0)::bigint AS marker_bytes,
+ count(*) FILTER (WHERE ${NO_CHUNK_ROWS})::bigint AS chunkless
+ FROM pages p
+ WHERE p.frontmatter ? 'embed_skip' AND p.deleted_at IS NULL AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}${scope}`)).rows[0] ?? {});
+ const base = { active_column: column, covering_index: coveringIndex, embed_skip_pages: embedSkip.pages ?? 0, embed_skip_marker_bytes: embedSkip.marker_bytes ?? 0,
+ unstamped_pending: pendingUnstamped, unstamped_created_at_min: unstampedMin };
+ if (opts.mode === 'full') {
+ const { rows } = await exec.run(sqlFragment`
+ SELECT s.state, count(*)::bigint AS n
+ FROM (SELECT ${chunklessPageState()} AS state FROM pages p WHERE p.deleted_at IS NULL AND ${NO_CHUNK_ROWS}${scope}) s
+ GROUP BY s.state`);
+ for (const row of rows) add(row.state as EmbeddingState, Number(row.n));
+ for (const state of EMBEDDING_STATES) counts[state] ??= 0;
+ return { ...base, basis: 'exact', counts, omitted: [], eligible_embedded: eligibleEmbedded, deleted_overdue: deletedOverdue };
+ }
+ add('keyword_only', embedSkip.chunkless ?? 0);
+ const quarantined = await exec.run(sqlFragment`
+ SELECT COALESCE(sum(GREATEST((SELECT count(*) FROM content_chunks cc WHERE cc.page_id = p.id), 1)), 0)::bigint AS n
+ FROM pages p
+ WHERE p.frontmatter ? 'quarantine' AND p.deleted_at IS NULL${scope}`);
+ counts.quarantined = Number(quarantined.rows[0]?.n ?? 0);
+ const deleted = await exec.run(sqlFragment`
+ SELECT count(*)::bigint AS n, count(*) FILTER (WHERE ${overdue})::bigint AS overdue
+ FROM pages p JOIN content_chunks cc ON cc.page_id = p.id
+ WHERE p.deleted_at IS NOT NULL${scope}`);
+ counts.deleted_page_chunks = Number(deleted.rows[0]?.n ?? 0);
+ const plan = await exec.run<{ 'QUERY PLAN': unknown }>(sqlFragment`
+ EXPLAIN (FORMAT JSON) SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE ${colRef} IS NOT NULL AND p.deleted_at IS NULL AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}${scope}`);
+ counts.embedded = plannerRows(plan.rows[0]?.['QUERY PLAN']);
+ for (const state of ['pending', 'keyword_only'] as const) counts[state] ??= 0;
+ return { ...base, basis: 'estimated', counts, omitted: ['empty', 'chunkless_healable'], eligible_embedded: null,
+ deleted_overdue: Number(deleted.rows[0]?.overdue ?? 0) };
+}
+
+/** `EXPLAIN (FORMAT JSON)`'s top-level row estimate (postgres.js parses json; PGLite may hand back text). */
+function plannerRows(plan: unknown): number {
+ const parsed = typeof plan === 'string' ? JSON.parse(plan) as unknown : plan;
+ const rows = Array.isArray(parsed) ? (parsed[0] as { Plan?: { 'Plan Rows'?: unknown } } | undefined)?.Plan?.['Plan Rows'] : undefined;
+ return typeof rows === 'number' && Number.isFinite(rows) ? Math.max(0, Math.round(rows)) : 0;
+}
+
+const normalizeStateRow = compileRowNormalizer<EmbeddingStateRow>({ chunks: 'bigint', bytes: 'bigint', marker_bytes: 'bigint', deleted_at: 'date' });
+
+/**
+ * One row per (page, state) in `states`, ordered (state, source_id, slug):
+ * a page whose chunks sit in two states (some embedded, some pending) yields
+ * two rows; a page with no chunk row yields one row with `chunks: 0` and its
+ * body bytes. Exact (full scan); the caller passes `limit` (one more than it
+ * prints, to report completeness).
+ */
+export async function listEmbeddingStateRows(exec: ScopedRead, column: string,
+ opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ const scope = embeddingStateScope(opts.sourceIds);
+ const { rows } = await exec.run(sqlFragment`
+ SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue
+ FROM (
+ SELECT p.slug, p.source_id, ${chunkEmbeddingState(column)} AS state, count(*)::bigint AS chunks,
+ COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes,
+ p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, ${MARKER_BYTES} AS marker_bytes,
+ p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at,
+ COALESCE(p.deleted_at < now() - make_interval(hours => ${opts.purgeWindowHours}::int), false) AS overdue
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE TRUE${scope}
+ GROUP BY p.id, 3
+ UNION ALL
+ SELECT p.slug, p.source_id, ${chunklessPageState()}, 0::bigint,
+ (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint,
+ p.frontmatter -> 'embed_skip' ->> 'reason', ${MARKER_BYTES},
+ p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false
+ FROM pages p
+ WHERE p.deleted_at IS NULL AND ${NO_CHUNK_ROWS}${scope}
+ ) r
+ WHERE r.state = ANY(${[...opts.states]}::text[])
+ ORDER BY r.state, r.source_id, r.slug
+ LIMIT ${opts.limit}`);
+ return rows.map(row => normalizeStateRow(row));
+}
+
export async function deleteChunks(exec: SqlExecutor, slug: string, opts?: { sourceId?: string }): Promise<void> {
const sourceId = opts?.sourceId ?? 'default';
// Source-qualify the page-id subquery; slugs are only unique per source.
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 2fb0089b3f..31752fe1db 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -4,6 +4,7 @@ import type { PageSnapshotBatch } from './page-snapshot-batch.ts';
import type { LinkReadScope } from './link-validity.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';
import type { KeywordPageWindow } from './search/keyword-statement.ts';
+import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from './embedding-state.ts';
import type { DerivedLinkBatchItem, DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';
export type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions, PageMutationPrecondition, PageWithdrawal } from './page-state/types.ts';
import type {
@@ -1358,6 +1359,10 @@ export interface BrainEngine {
afterPageId?: number;
sourceId?: string;
}): Promise<ChunklessPageRow[]>;
+ /** #6696 B3: counts per embedding state over the ACTIVE column (contract and ops/full semantics: src/core/embedding-state.ts). */
+ readEmbeddingStateCounts(opts: { mode: 'ops' | 'full'; sourceIds?: string[]; purgeWindowHours: number }): Promise<EmbeddingStateCounts>;
+ /** #6696 B3: one row per (page, state) in `states`, ordered (state, source_id, slug), at most `limit` rows. */
+ listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]>;
/**
* Delete every chunk for a page. Internal page-id lookup is sourceId-scoped
* when `opts.sourceId` is given; otherwise the bare-slug subquery returns
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index ef9ed93f07..ee7e6a4e46 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -149,6 +149,7 @@ import * as sourcesImpl from './engine-sql/sources.ts';
import * as filesImpl from './engine-sql/files.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';
import type { KeywordPageWindow } from './search/keyword-statement.ts';
+import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from './embedding-state.ts';
import * as chunksImpl from './engine-sql/chunks.ts';
import { searchKeywordCJK } from './engine-sql/cjk-search.ts';
import * as titlesImpl from './engine-sql/titles.ts';
@@ -1856,6 +1857,16 @@ export class PGLiteEngine implements BrainEngine {
return chunksImpl.listChunklessPagesWithContent(scopedRead(this.engineSql), opts);
}
+ async readEmbeddingStateCounts(opts: { mode: 'ops' | 'full'; sourceIds?: string[]; purgeWindowHours: number }): Promise<EmbeddingStateCounts> {
+ const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
+ return chunksImpl.readEmbeddingStateCounts(scopedRead(this.engineSql), column, opts);
+ }
+
+ async listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
+ return chunksImpl.listEmbeddingStateRows(scopedRead(this.engineSql), column, opts);
+ }
+
async deleteChunks(slug: string, opts?: { sourceId?: string }): Promise<void> {
return chunksImpl.deleteChunks(this.engineSql, slug, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 3f7fd515c2..a3dc44ff1b 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -136,6 +136,7 @@ import * as sourcesImpl from './engine-sql/sources.ts';
import * as filesImpl from './engine-sql/files.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';
import type { KeywordPageWindow } from './search/keyword-statement.ts';
+import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from './embedding-state.ts';
import * as chunksImpl from './engine-sql/chunks.ts';
import { hasCJK } from './cjk.ts';
import { searchKeywordCJK as searchKeywordCJKImpl } from './engine-sql/cjk-search.ts';
@@ -1606,6 +1607,16 @@ export class PostgresEngine implements BrainEngine {
return this.withScopedReadTransaction(undefined, opts?.sourceId, tx => chunksImpl.listChunklessPagesWithContent(scopedRead(this.engineSqlOn(tx)), opts));
}
+ async readEmbeddingStateCounts(opts: { mode: 'ops' | 'full'; sourceIds?: string[]; purgeWindowHours: number }): Promise<EmbeddingStateCounts> {
+ const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
+ return this.withScopedReadTransaction(opts.sourceIds, undefined, tx => chunksImpl.readEmbeddingStateCounts(scopedRead(this.engineSqlOn(tx)), column, opts));
+ }
+
+ async listEmbeddingStateRows(opts: { sourceIds?: string[]; states: readonly EmbeddingState[]; limit: number; purgeWindowHours: number }): Promise<EmbeddingStateRow[]> {
+ const column = (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name;
+ return this.withScopedReadTransaction(opts.sourceIds, undefined, tx => chunksImpl.listEmbeddingStateRows(scopedRead(this.engineSqlOn(tx)), column, opts));
+ }
+
async deleteChunks(slug: string, opts?: { sourceId?: string }): Promise<void> {
return chunksImpl.deleteChunks(this.engineSql, slug, opts);
}
diff --git a/test/embedding-state.test.ts b/test/embedding-state.test.ts
new file mode 100644
index 0000000000..486cbb5f10
--- /dev/null
+++ b/test/embedding-state.test.ts
@@ -0,0 +1,219 @@
+/**
+ * #6696 B3 embedding state, derived: the classifier puts every chunk, and every
+ * live page with no chunk row, in exactly one state against the ACTIVE embedding
+ * column, ops mode reads only index-backed counts (unknown without a covering
+ * partial index), and the summary's unsearchable / keyword_only / deleted /
+ * unstamped fields follow the contract in src/core/embedding-state.ts.
+ *
+ * Protects: the state counts doctor `embedding_state`, `get_brain_health` and
+ * `gbrain pages unsearchable` report. Regression it catches: a classifier that
+ * reads the legacy `embedding` column on a registry-routed brain, drifts from the
+ * embed job's predicate, or scans in ops mode. No existing owner: the classifier
+ * is new. PGLite in-memory; the SQL is shared by both engines.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { readEmbeddingState, embeddingStateFix, EMBEDDING_STATES } from '../src/core/embedding-state.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.unsetConfig('search_embedding_column');
+ await engine.unsetConfig('embedding_columns');
+ await engine.unsetConfig('embedding_disabled');
+});
+
+const VEC = `array_fill(0.1::real, ARRAY[1536])::vector`;
+
+async function page(slug: string, opts: { body?: string; frontmatter?: Record<string, unknown>; deletedHoursAgo?: number; source?: string } = {}): Promise<number> {
+ const source = opts.source ?? 'default';
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: opts.body ?? `${slug} body` }, { sourceId: source });
+ const [row] = await engine.executeRaw<{ id: number }>(
+ `UPDATE pages SET frontmatter = $3::jsonb, deleted_at = CASE WHEN $4::int IS NULL THEN NULL ELSE now() - make_interval(hours => $4::int) END
+ WHERE slug = $1 AND source_id = $2 RETURNING id`,
+ [slug, source, JSON.stringify(opts.frontmatter ?? {}), opts.deletedHoursAgo ?? null]);
+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [row!.id]);
+ return row!.id;
+}
+
+async function chunks(pageId: number, specs: Array<{ vector?: boolean; stamped?: boolean; column?: string }>): Promise<void> {
+ for (const [i, spec] of specs.entries()) {
+ const column = spec.column ?? 'embedding';
+ await engine.executeRaw(
+ `INSERT INTO content_chunks (page_id, chunk_index, chunk_text, ${column}, embedding_pending_since)
+ VALUES ($1, $2, $3, ${spec.vector ? (column === 'embedding' ? VEC : `array_fill(0.1::real, ARRAY[8])::vector`) : 'NULL'}, ${spec.stamped === false || spec.vector ? 'NULL' : 'now()'})`,
+ [pageId, i, `chunk ${i} of page ${pageId}`]);
+ }
+}
+
+/** One page per state; expected full counts below. */
+async function seedEveryState(): Promise<void> {
+ await chunks(await page('notes/alice-example'), [{ vector: true }, { vector: true }]);
+ await chunks(await page('notes/acme-example'), [{}, { stamped: false }]);
+ await chunks(await page('notes/fund-a-oversized', { frontmatter: { embed_skip: { reason: 'oversized', bytes: 600_000, assessed_at: '2026-01-01T00:00:00Z' } } }), [{}]);
+ await page('notes/fund-a-oversized-bare', { frontmatter: { embed_skip: { reason: 'oversized', bytes: 700_000, assessed_at: '2026-01-01T00:00:00Z' } } });
+ await page('notes/junk-hidden', { frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'captcha', assessed_at: '2026-01-01T00:00:00Z' } } });
+ await chunks(await page('notes/junk-legacy', { frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'captcha', assessed_at: '2026-01-01T00:00:00Z' } } }), [{}, {}]);
+ await page('notes/empty-stub', { body: '' });
+ await page('notes/stub-with-body');
+ await chunks(await page('notes/deleted-recent', { deletedHoursAgo: 1 }), [{ vector: true }]);
+ await chunks(await page('notes/deleted-old', { deletedHoursAgo: 100 }), [{}, { vector: true }]);
+}
+
+const EVERY_STATE = { embedded: 2, pending: 2, keyword_only: 2, quarantined: 3, empty: 1, deleted_page_chunks: 3, chunkless_healable: 1 };
+
+describe('embedding state classifier (full mode)', () => {
+ test('every state on the legacy column, exact', async () => {
+ await seedEveryState();
+ const s = await readEmbeddingState(engine, { mode: 'full' });
+ expect(s.status).toBe('known');
+ expect(s.basis).toBe('exact');
+ expect(s.active_column).toBe('embedding');
+ expect(s.counts).toEqual(EVERY_STATE);
+ expect(Object.keys(s.counts).sort()).toEqual([...EMBEDDING_STATES].sort());
+ expect(s.unsearchable).toBe(2 + 3 + 1 + 1);
+ expect(s.unsearchable_complete).toBe(true);
+ expect(s.deleted_page_chunks).toEqual({ within_window: 1, past_window: 2, window_hours: 72 });
+ expect(s.keyword_only).toMatchObject({ reason: 'embed_skip', pages: 2, marker_bytes: 1_300_000, threshold_bytes: 500_000 });
+ const unstamped = s.unstamped_pending as { count: number; created_at_lower_bound: string | null; writer_version: string };
+ expect(unstamped.count).toBe(1);
+ expect(unstamped.created_at_lower_bound).not.toBeNull();
+ expect(unstamped.writer_version).toMatch(/^\d+\.\d+/);
+ expect(s.coverage).toMatchObject({ basis: 'exact', embedded: 2, eligible: 4, ratio: 0.5 });
+ });
+
+ test('pending is the embed job predicate minus quarantined pages; chunkless_healable is the healer predicate', async () => {
+ await seedEveryState();
+ const s = await readEmbeddingState(engine, { mode: 'full' });
+ expect(s.counts.pending! + 2).toBe(await engine.countStaleChunks());
+ expect(s.counts.chunkless_healable).toBe(await engine.countChunklessPagesWithContent());
+ });
+
+ test('classifier per state with a custom active column', async () => {
+ await seedEveryState();
+ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_reg8 vector(8)');
+ await engine.setConfig('embedding_columns', JSON.stringify({ embedding_reg8: { provider: 'openai:text-embedding-3-small', dimensions: 8, type: 'vector' } }));
+ await engine.setConfig('search_embedding_column', 'embedding_reg8');
+ // The legacy vectors no longer count: alice-example's two chunks are pending under embedding_reg8.
+ let s = await readEmbeddingState(engine, { mode: 'full' });
+ expect(s.active_column).toBe('embedding_reg8');
+ expect(s.counts).toEqual({ ...EVERY_STATE, embedded: 0, pending: 4 });
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_reg8 = array_fill(0.1::real, ARRAY[8])::vector
+ WHERE page_id = (SELECT id FROM pages WHERE slug = 'notes/acme-example')`);
+ s = await readEmbeddingState(engine, { mode: 'full' });
+ expect(s.counts).toEqual({ ...EVERY_STATE, embedded: 2, pending: 2 });
+ const rows = await engine.listEmbeddingStateRows({ states: ['embedded', 'pending'], limit: 10, purgeWindowHours: 72 });
+ expect(rows.map(r => [r.slug, r.state])).toEqual([['notes/acme-example', 'embedded'], ['notes/alice-example', 'pending']]);
+ });
+
+ test('sourceIds scopes every count', async () => {
+ await seedEveryState();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('src-b','src-b') ON CONFLICT DO NOTHING");
+ await chunks(await page('notes/other-source', { source: 'src-b' }), [{}, {}, {}]);
+ expect((await readEmbeddingState(engine, { mode: 'full' })).counts.pending).toBe(5);
+ expect((await readEmbeddingState(engine, { mode: 'full', sourceIds: ['default'] })).counts).toEqual(EVERY_STATE);
+ const b = await readEmbeddingState(engine, { mode: 'full', sourceIds: ['src-b'] });
+ expect(b.counts).toEqual({ embedded: 0, pending: 3, keyword_only: 0, quarantined: 0, empty: 0, deleted_page_chunks: 0, chunkless_healable: 0 });
+ expect((await readEmbeddingState(engine, { mode: 'ops', sourceIds: ['src-b'] })).counts.pending).toBe(3);
+ });
+
+ test('a brain keyless by choice does not count pending as unsearchable', async () => {
+ await seedEveryState();
+ await engine.setConfig('embedding_disabled', 'true');
+ const s = await readEmbeddingState(engine, { mode: 'full' });
+ expect(s.reason).toBe('embeddings_disabled');
+ expect(s.counts.pending).toBe(2);
+ expect(s.unsearchable).toBe(3 + 1 + 1);
+ });
+});
+
+describe('embedding state classifier (ops mode)', () => {
+ test('index-backed counts on the legacy column: exact gated states, estimated embedded, anti-join states omitted', async () => {
+ await seedEveryState();
+ const s = await readEmbeddingState(engine, { mode: 'ops' });
+ expect(s.status).toBe('known');
+ expect(s.basis).toBe('estimated');
+ expect(s.covering_index).toBe('content_chunks_stale_idx');
+ expect(s.counts).toMatchObject({ pending: 2, keyword_only: 2, quarantined: 3, deleted_page_chunks: 3 });
+ expect(s.counts.empty).toBeUndefined();
+ expect(s.counts.chunkless_healable).toBeUndefined();
+ expect(typeof s.counts.embedded).toBe('number');
+ expect(s.omitted_states).toEqual(['empty', 'chunkless_healable']);
+ expect(s.unsearchable).toBe(2 + 3);
+ expect(s.unsearchable_complete).toBe(false);
+ expect(s.deleted_page_chunks).toMatchObject({ within_window: 1, past_window: 2 });
+ });
+
+ test('a custom active column without a covering partial index is unknown, never scanned; the index makes it known', async () => {
+ await seedEveryState();
+ await engine.executeRaw('ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_reg8 vector(8)');
+ await engine.setConfig('embedding_columns', JSON.stringify({ embedding_reg8: { provider: 'openai:text-embedding-3-small', dimensions: 8, type: 'vector' } }));
+ await engine.setConfig('search_embedding_column', 'embedding_reg8');
+ const unknown = await readEmbeddingState(engine, { mode: 'ops' });
+ expect(unknown).toMatchObject({ status: 'unknown', basis: 'unknown', reason: 'no_covering_index', active_column: 'embedding_reg8', counts: {}, unsearchable: null });
+ await engine.executeRaw('CREATE INDEX content_chunks_reg8_stale_idx ON content_chunks(page_id, chunk_index) WHERE embedding_reg8 IS NULL');
+ try {
+ const known = await readEmbeddingState(engine, { mode: 'ops' });
+ expect(known.status).toBe('known');
+ expect(known.covering_index).toBe('content_chunks_reg8_stale_idx');
+ expect(known.counts.pending).toBe(4);
+ } finally {
+ await engine.executeRaw('DROP INDEX content_chunks_reg8_stale_idx');
+ }
+ });
+});
+
+describe('embedding state rows and fixes', () => {
+ test('rows per (page, state) with reason inputs, bytes and limit', async () => {
+ await seedEveryState();
+ const rows = await engine.listEmbeddingStateRows({ states: ['keyword_only', 'quarantined', 'empty', 'chunkless_healable', 'deleted_page_chunks'], limit: 50, purgeWindowHours: 72 });
+ expect(rows.map(r => `${r.state} ${r.slug} ${r.chunks}`)).toEqual([
+ 'chunkless_healable notes/stub-with-body 0',
+ 'deleted_page_chunks notes/deleted-old 2',
+ 'deleted_page_chunks notes/deleted-recent 1',
+ 'empty notes/empty-stub 0',
+ 'keyword_only notes/fund-a-oversized 1',
+ 'keyword_only notes/fund-a-oversized-bare 0',
+ 'quarantined notes/junk-hidden 0',
+ 'quarantined notes/junk-legacy 2',
+ ]);
+ const old = rows.find(r => r.slug === 'notes/deleted-old')!;
+ expect(old.overdue).toBe(true);
+ expect(old.deleted_at).toBeInstanceOf(Date);
+ expect(rows.find(r => r.slug === 'notes/deleted-recent')!.overdue).toBe(false);
+ expect(rows.find(r => r.slug === 'notes/fund-a-oversized')).toMatchObject({ embed_skip_reason: 'oversized', marker_bytes: 600_000 });
+ expect(rows.find(r => r.slug === 'notes/junk-hidden')!.quarantine_reason).toBe('junk_pattern');
+ expect(rows.find(r => r.slug === 'notes/stub-with-body')!.bytes).toBe('notes/stub-with-body body'.length);
+ expect(await engine.listEmbeddingStateRows({ states: ['quarantined'], limit: 1, purgeWindowHours: 72 })).toHaveLength(1);
+ });
+
+ test('every state but embedded has a protocol fix with a read-only verify and the docs anchor', () => {
+ for (const state of EMBEDDING_STATES) {
+ const fix = embeddingStateFix(state, { sourceId: 'default', slug: 'notes/alice-example', markerBytes: 600_000, embeddingsEnabled: true });
+ if (state === 'embedded') { expect(fix).toBeNull(); continue; }
+ expect(fix, state).not.toBeNull();
+ expect(fix!.argv?.[0]).toBe('gbrain');
+ expect(Array.isArray(fix!.consent)).toBe(true);
+ expect(typeof fix!.why).toBe('string');
+ expect(fix!.requires_exclusive).toBe(false);
+ expect(fix!.docs).toBe('docs/guides/troubleshooting.md#embedding-state');
+ expect(fix!.verify?.argv).toEqual(['gbrain', 'pages', 'unsearchable', '--source', 'default', '--state', state, '--json']);
+ }
+ expect(embeddingStateFix('keyword_only', { sourceId: 'default', markerBytes: 600_000, embeddingsEnabled: true })).toMatchObject({
+ ask_user: true, argv: ['gbrain', 'config', 'set', 'content_sanity.bytes_block', '600001'], then: { argv: ['gbrain', 'sync', '--source', 'default', '--full'] } });
+ expect(embeddingStateFix('deleted_page_chunks', { sourceId: 'default', embeddingsEnabled: true })).toMatchObject({
+ argv: ['gbrain', 'pages', 'purge-deleted', '--yes'], preview_argv: ['gbrain', 'pages', 'purge-deleted', '--dry-run', '--json'], consent: ['destructive'] });
+ });
+});
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index 13f137d557..eaf3926a65 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -1,7 +1,7 @@
{
"golden": {
"counts": {
- "chunks": 14,
+ "chunks": 16,
"cjk-search": 2,
"code-edges": 5,
"facts": 19,
@@ -130,6 +130,7 @@
"listChunklessPagesWithContent": "chunks",
"listConfigKeys": "out-of-scope:config",
"listCorpusSample": "pages",
+ "listEmbeddingStateRows": "chunks",
"listEnrichCandidates": "salience",
"listEvalCandidates": "out-of-scope:eval-capture",
"listEvalCaptureFailures": "out-of-scope:eval-capture",
@@ -162,6 +163,7 @@
"putDreamVerdict": "out-of-scope:dream-verdicts",
"putPage": "pages",
"putRawData": "out-of-scope:raw-data",
+ "readEmbeddingStateCounts": "chunks",
"readPageSnapshot": "pages",
"readPageSnapshotsBatch": "pages",
"reconnect": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 57aaea1c12..df50da7131 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -429,6 +429,48 @@
}
]
},
+ "listEmbeddingStateRows": {
+ "default": [
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": true
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 3,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "sourceIds": [
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": true
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 5,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"listStaleChunks": {
"default": [
{
@@ -551,6 +593,104 @@
}
]
},
+ "readEmbeddingStateCounts": {
+ "full": [
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": true
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "full+sourceIds": [
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": true
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "ops": [
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": true
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"setPageEmbeddingSignature": {
"default": [
{
diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.json
index d184810596..0f3c6eb852 100644
--- a/test/fixtures/goldens/sql-text/chunks.json
+++ b/test/fixtures/goldens/sql-text/chunks.json
@@ -438,6 +438,46 @@
}
]
},
+ "listEmbeddingStateRows": {
+ "default": [
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ },
+ {
+ "lane": "pool",
+ "params": [
+ "number",
+ "array<string>",
+ "number"
+ ],
+ "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ) r WHERE r.state = ANY($2::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $3",
+ "textSha256": "9195ae4bc4427e2bc4f920dd5560a8883e153a4c0b0cffda020e04f9953eea30"
+ }
+ ],
+ "sourceIds": [
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ },
+ {
+ "lane": "pool",
+ "params": [
+ "number",
+ "array<string>",
+ "array<string>",
+ "array<string>",
+ "number"
+ ],
+ "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND p.source_id = ANY($2::text[]) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($3::text[]) ) r WHERE r.state = ANY($4::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $5",
+ "textSha256": "171949d8dd45f600cc00a808e38acf0b2716359b6e642d8a2a91a8af19d76ff9"
+ }
+ ]
+ },
"listStaleChunks": {
"default": [
{
@@ -555,6 +595,85 @@
}
]
},
+ "readEmbeddingStateCounts": {
+ "full": [
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ },
+ {
+ "lane": "pool",
+ "params": [
+ "number"
+ ],
+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE) s GROUP BY s.state",
+ "textSha256": "71c9be80016724dfa58e92a4c5b2f5f364f275babcb26ad4c25334953636db9a"
+ },
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT count(*)::bigint AS pages, COALESCE(sum(CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END), 0)::bigint AS marker_bytes, count(*) FILTER (WHERE NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id))::bigint AS chunkless FROM pages p WHERE p.frontmatter ? 'embed_skip' AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')",
+ "textSha256": "9fc4b55b9f5316227a7ad722bef9f4e18cd48958ed8ca259390ddc5c0158489d"
+ },
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT s.state, count(*)::bigint AS n FROM (SELECT CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END AS state FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)) s GROUP BY s.state",
+ "textSha256": "b2d51df28315e0a7e6a7398d11744d4ffec51b3b539698b822782de61e7cf0de"
+ }
+ ],
+ "full+sourceIds": [
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ },
+ {
+ "lane": "pool",
+ "params": [
+ "number",
+ "array<string>"
+ ],
+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND p.source_id = ANY($2::text[])) s GROUP BY s.state",
+ "textSha256": "cc791916e96432ab7a27cb9e08e851f3c288dfa67f22b9828ecb346b9773cd29"
+ },
+ {
+ "lane": "pool",
+ "params": [
+ "array<string>"
+ ],
+ "sql": "SELECT count(*)::bigint AS pages, COALESCE(sum(CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END), 0)::bigint AS marker_bytes, count(*) FILTER (WHERE NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id))::bigint AS chunkless FROM pages p WHERE p.frontmatter ? 'embed_skip' AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND p.source_id = ANY($1::text[])",
+ "textSha256": "6ed9cefe65301945aa7ee791953c2b95daa9bcd55f9b6e24be69dbabc2fdaca2"
+ },
+ {
+ "lane": "pool",
+ "params": [
+ "array<string>"
+ ],
+ "sql": "SELECT s.state, count(*)::bigint AS n FROM (SELECT CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END AS state FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($1::text[])) s GROUP BY s.state",
+ "textSha256": "0d349e62d3ec1f08e76c1c2c38ad677566a42717f1bc965c293210eb2807b452"
+ }
+ ],
+ "ops": [
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns')",
+ "textSha256": "0c97097b286eb3415cffbfa812bc301187d88bc7a5266678332b0f4c8c571371"
+ },
+ {
+ "lane": "pool",
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT ic.relname AS name FROM pg_index i JOIN pg_class ic ON ic.oid = i.indexrelid JOIN pg_class t ON t.oid = i.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace WHERE t.relname = 'content_chunks' AND n.nspname = current_schema() AND i.indisvalid AND i.indpred IS NOT NULL AND pg_get_expr(i.indpred, i.indrelid) = '(' || quote_ident($1) || ' IS NULL)' ORDER BY ic.relname LIMIT 1",
+ "textSha256": "024a6c1f7deca626d307cb1f3566cdadb7c7ea81af23f13aeb816981efdfe79f"
+ }
+ ]
+ },
"setPageEmbeddingSignature": {
"default": [
{
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index 3153994c32..44d5679354 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -112,6 +112,7 @@ export const DOMAIN_OF: Record<string, string> = {
'setPageEmbeddingSignature': 'chunks', 'invalidateStaleSignatureEmbeddings': 'chunks',
'invalidateContentDriftEmbeddings': 'chunks', 'listStaleChunks': 'chunks',
'countChunklessPagesWithContent': 'chunks', 'listChunklessPagesWithContent': 'chunks', 'deleteChunks': 'chunks',
+ 'readEmbeddingStateCounts': 'chunks', 'listEmbeddingStateRows': 'chunks',
'getEmbeddingsByChunkIds': 'chunks', 'getChunksWithEmbeddings': 'chunks',
// facts (incl. the ontology rows of the facts table)
'insertFact': 'facts', 'expireFact': 'facts', 'insertFacts': 'facts', 'deleteFactsForPage': 'facts',
@@ -565,6 +566,15 @@ export const SQL_CASES: SqlCase[] = [
['default', (e) => e.listChunklessPagesWithContent()],
['afterPageId+sourceId', (e) => e.listChunklessPagesWithContent({ afterPageId: 3, sourceId: SRC, batchSize: 5 })],
]),
+ ...variants('readEmbeddingStateCounts', [
+ ['full', (e) => e.readEmbeddingStateCounts({ mode: 'full', purgeWindowHours: 72 })],
+ ['full+sourceIds', (e) => e.readEmbeddingStateCounts({ mode: 'full', sourceIds: [SRC], purgeWindowHours: 72 })],
+ ['ops', (e) => e.readEmbeddingStateCounts({ mode: 'ops', purgeWindowHours: 72 })],
+ ]),
+ ...variants('listEmbeddingStateRows', [
+ ['default', (e) => e.listEmbeddingStateRows({ states: ['pending', 'empty'], limit: 51, purgeWindowHours: 72 })],
+ ['sourceIds', (e) => e.listEmbeddingStateRows({ sourceIds: [SRC], states: ['keyword_only'], limit: 11, purgeWindowHours: 72 })],
+ ]),
...variants('deleteChunks', [['default', (e) => e.deleteChunks(SLUG)]]),
...variants('getEmbeddingsByChunkIds', [
['default', (e) => e.getEmbeddingsByChunkIds([1, 2])],